<commit_before>;(function($, window) {
    'use strict';

    /**
     * Parses the given {@link url} parameter and extracts all query parameters. If the parameter is numeric
     * it will automatically based to a {@link Number} instead of a {@link String}.
     * @private
     * @param {String} url - Usually {@link window.location.href}
     * @returns {{}} Object with all extracted parameters
     */
    var parseQueryString = function(url) {
        var qparams = {},
            parts = (url || '').split('?'),
            qparts, qpart,
            i = 0;

        if (parts.length <= 1) {
            return qparams;
        }

        qparts = parts[1].split('&');
        for (i in qparts) {
            var key, value;

            qpart = qparts[i].split('=');
            key = decodeURIComponent(qpart[0]);
            value = decodeURIComponent(qpart[1] || '');
            qparams[key] = ($.isNumeric(value) ? parseFloat(value, 10) : value);
        }

        return qparams;
    };

    $.plugin('swInfiniteScrolling', {

        defaults: {

            /** @bool enabled - enable or disable infinite scrolling plugin */
            'enabled': true,

            /** @string event - default "scroll" will be used for triggering this plugin */
            'eventName': 'scroll',

            /** @int categoryId - category id is used for generating ajax request */
            'categoryId': 0,

            /** @string pagingSelector - listing paging selector **/
            'pagingSelector': '.listing--paging',

            /** @string productBoxSelector - selector for single product boxes **/
            'productBoxSelector': '.product--box',

            /** @string defaultPerPageSelector - default per page selector which will be removed **/
            'defaultPerPageSelector': '.action--per-page',

            /** @string defaultChangeLayoutSelector - default change layout select which will be get a new margin **/
            'defaultChangeLayoutSelector': '.action--change-layout',

            /** @int threshold - after this threshold reached, auto fetching is disabled and the "load more" button is shown. */
            'threshold': 3,

            /** @string loadMoreCls - this class will be used for fetching further data by button. */
            'loadMoreCls': 'js--load-more',

            /** @string loadPreviousCls - this class  will be used for fetching previous data by button. */
            'loadPreviousCls': 'js--load-previous',

            /** @string Class will be used for load more or previous button */
            'loadBtnCls': 'btn is--primary is--icon-right',

            /** @string loadMoreSnippet - this snippet will be printed inside the load more button */
            'loadMoreSnippet': 'Weitere Artikel laden',

            /** @string loadPreviousSnippet - this snippet will be printed inside the load previous button */
            'loadPreviousSnippet': 'Vorherige Artikel laden',

            /** @string listingContainerSelector - will be used for prepending and appending load previous and load more button */
            'listingContainerSelector': '.listing--container',

            /** @string pagingBottomSelector - this class will be used for removing the bottom paging bar if infinite scrolling is enabled */
            'pagingBottomSelector': '.listing--bottom-paging',

            /** @string listingActionsWrapper - this class will be cloned and used as a actions wrapper for the load more and previous button */
            'listingActionsWrapper': 'infinite--actions',

            /** @string ajaxUrl - this string will be used as url for the ajax-call to load the articles */
            ajaxUrl: window.controller.ajax_listing || null,

            /** @string delegateConSelector - selector for delegate container, used for reload buttons */
            delegateConSelector: '.listing--wrapper'
        },

        /**
         * Default plugin initialisation function.
         * Handle all logic and events for infinite scrolling
         *
         * @public
         * @method init
         */
        init: function() {
            var me = this;

            me.$delegateContainer = $(me.opts.delegateConSelector);

            // Overwrite plugin configuration with user configuration
            me.applyDataAttributes();

            // Check if plugin is enabled
            if (!me.opts.enabled || !me.$el.is(':visible') || me.opts.ajaxUrl === null) {
                return;
            }

            // Remove paging top bar
            $(me.opts.pagingSelector).remove();

            // remove bottom paging bar
            $(me.opts.pagingBottomSelector).remove();

            // Check max pages by data attribute
            me.maxPages = me.$el.attr('data-pages');
            if (me.maxPages <= 1) {
                return;
            }

            // isLoading state for preventing double fetch same content
            me.isLoading = false;

            // isFinished state for disabling plugin if all pages rendered
            me.isFinished = false;

            // resetting fetch Count to prevent auto fetching after threshold reached
            me.fetchCount = 0;

            // previousPageIndex for loading in other direction
            me.previousPageIndex = 0;

            // Prepare top and bottom actions containers
            me.$buttonWrapperTop = $('<div>', {
                'class': me.opts.listingActionsWrapper
            });

            me.$buttonWrapperBottom = $('<div>', {
                'class': me.opts.listingActionsWrapper
            });

            // append load more button
            $(me.opts.listingContainerSelector).after(me.$buttonWrapperBottom);
            $(me.opts.listingContainerSelector).before(me.$buttonWrapperTop);

            // base url for push state and ajax fetch url
            me.baseUrl = window.location.href.split('?')[0];

            // Ajax configuration
            me.ajax = {
                'url': me.opts.ajaxUrl,
                'params': parseQueryString(window.location.href)
            };

            me.params = parseQueryString(window.location.href);
            me.upperParams = $.extend({}, me.params);
            me.historyParams = $.extend({}, me.params);

            me.urlBasicMode = false;

            // if no seo url is provided, use the url basic push mode
            if (!me.params.p) {
                me.basicModeSegments = window.location.pathname.split('/');
                me.basicModePageKey = $.inArray('sPage', me.basicModeSegments);
                me.basicModePageValue = me.basicModeSegments[me.basicModePageKey + 1];

                if (me.basicModePageValue) {
                    me.urlBasicMode = true;
                    me.params.p = me.basicModePageValue;
                    me.upperParams.p = me.basicModePageValue;
                }
            }

            // set page index to one if not assigned
            if (!me.params.p) {
                me.params.p = 1;
            }

            // set start page
            me.startPage = me.params.p;

            // holds the current listing url with all params
            me.currentPushState = '';

            // Check if there is/are previous pages
            if (me.params.p && me.params.p > 1) {
                me.showLoadPrevious();
            }

            // on scrolling event for auto fetching new pages and push state
            me._on(window, me.opts.eventName, $.proxy(me.onScrolling, me));

            // on load more button event for manually fetching further pages
            me.$delegateContainer.on(me.getEventName('click'), '.' + me.opts.loadMoreCls, $.proxy(me.onLoadMore, me));

            // on load previous button event for manually fetching previous pages
            me.$delegateContainer.on(me.getEventName('click'), '.' + me.opts.loadPreviousCls, $.proxy(me.onLoadPrevious, me));

            $.publish('plugin/swInfiniteScrolling/onRegisterEvents', [ me ]);
        },

        update: function () {
            var me = this;

            // disable infinite scrolling, because listing container is not visible
            me.opts.enabled = me.$el.is(':visible');

            $.publish('plugin/swInfiniteScrolling/onUpdate', [ me ]);
        },

        /**
         * onScrolling method
         */
        onScrolling: function() {
            var me = this;

            // stop fetch new page if is loading atm
            if (me.isLoading || !me.opts.enabled) {
                return;
            }

            // Viewport height
            var $window = $(window),
                docTop = $window.scrollTop() + $window.height(),

                // Get last element in list to get the reference point for fetching new data
                fetchPoint = me.$el.find(me.opts.productBoxSelector).last(),
                fetchPointOffset = fetchPoint.offset().top,
                bufferSize = fetchPoint.height(),
                triggerPoint = fetchPointOffset - bufferSize;

            if (docTop > triggerPoint && (me.params.p < me.maxPages)) {
                me.fetchNewPage();
            }

            // collect all pages
            var $products = $('*[data-page-index]'),
                visibleProducts = $.grep($products, function(item) {
                    return $(item).offset().top <= docTop;
                });

            // First visible Product
            var $firstProduct = $(visibleProducts).last(),
                tmpPageIndex = $firstProduct.attr('data-page-index');

            // Collection variables and build push state url
            var tmpParams = me.historyParams;

            // remove category id from history url
            delete tmpParams.c;

            // setting actual page index
            if (!tmpParams.p || !tmpPageIndex) {
                tmpParams.p = me.startPage;
            }

            if (tmpPageIndex) {
                tmpParams.p = tmpPageIndex;
            }

            var tmpPushState = me.baseUrl + '?' + $.param(tmpParams);

            if (me.urlBasicMode) {
                // use start page parameter if no one exists
                if (!tmpPageIndex) {
                    tmpPageIndex = me.basicModePageValue;
                }

                // redesign push url,
                var segments = me.basicModeSegments;
                segments[me.basicModePageKey + 1] = tmpPageIndex;

                tmpPushState = segments.join('/');
            }

            if (me.currentPushState != tmpPushState) {
                me.currentPushState = tmpPushState;
                if (!history || !history.pushState) {
                    return;
                }

                history.pushState('data', '', me.currentPushState);
            }

            $.publish('plugin/swInfiniteScrolling/onScrolling', [ me ]);
        },

        /**
         * fetchNewPage method
         */
        fetchNewPage: function() {
            var me = this;

            // Quit here if all pages rendered
            if (me.isFinished || me.params.p >= me.maxPages) {
                return;
            }

            // stop if process is running
            if (me.isLoading) {
                return;
            }

            // Stop automatic fetch if page threshold reached
            if (me.fetchCount >= me.opts.threshold) {
                var button = me.generateButton('next');

                // append load more button
                me.$buttonWrapperBottom.html(button);

                // set finished flag
                me.isFinished = true;

                return;
            }

            me.isLoading = true;

            me.openLoadingIndicator();

            // increase page index for further page loading
            me.params.p++;

            // increase fetch count for preventing auto fetching
            me.fetchCount++;

            // use categoryId by settings if not defined by filters
            if (!me.params.c && me.opts.categoryId) {
                me.params.c = me.opts.categoryId;
            }

            $.publish('plugin/swInfiniteScrolling/onBeforeFetchNewPage', [ me ]);

            $.publish(
                'action/fetchListing',
                [me.params, false, true, $.proxy(me.appendListing, me)]
            );

            $.publish('plugin/swInfiniteScrolling/onFetchNewPage', [ me ]);
        },

        generateButton: function(buttonType) {
            var me = this,
                type = buttonType || 'next',
                cls = (type == 'previous') ? me.opts.loadPreviousCls : me.opts.loadMoreCls,
                snippet = (type == 'previous') ? me.opts.loadPreviousSnippet : me.opts.loadMoreSnippet,
                $button = $('<a>', {
                    'class': me.opts.loadBtnCls + ' ' + cls,
                    'html': snippet + ' <i class="icon--cw is--large"></i>'
                });

            $.publish('plugin/swInfiniteScrolling/onLoadMore', [ me, $button, buttonType ]);

            return $button;
        },

        /**
         * onLoadMore method
         *
         * @param event
         */
        onLoadMore: function(event) {
            event.preventDefault();

            var me = this;

            // Remove load more button
            $('.' + me.opts.loadMoreCls).remove();

            // Set finished to false to re-enable the fetch method
            me.isFinished = false;

            // Increase threshold for auto fetch next page if there is a next page
            if (me.maxPages >= me.opts.threshold) {
                me.opts.threshold++;
            }

            // fetching new page
            me.fetchNewPage();

            $.publish('plugin/swInfiniteScrolling/onLoadMore', [ me, event ]);
        },

        /**
         * showLoadPrevious method
         *
         * Shows the load previous button
         */
        showLoadPrevious: function() {
            var me = this,
                button = me.generateButton('previous');

            // append load previous button
            me.$buttonWrapperTop.html(button);

            $.publish('plugin/swInfiniteScrolling/onShowLoadPrevious', [ me, button ]);
        },

        /**
         * onLoadPrevious method
         *
         * @param event
         *
         * will be triggered by load previous button
         */
        onLoadPrevious: function(event) {
            event.preventDefault();

            var me = this, callback;

            // Remove load previous button
            $('.' + me.opts.loadPreviousCls).remove();

            // fetching new page
            me.openLoadingIndicator('top');

            // build ajax url
            var tmpParams = me.upperParams;

            // use categoryId by settings if not defined by filters
            if (!tmpParams.c && me.opts.categoryId) {
                tmpParams.c = me.opts.categoryId;
            }

            tmpParams.p = tmpParams.p - 1;

            $.publish('plugin/swInfiniteScrolling/onBeforeFetchPreviousPage', [ me ]);

            me.previousLoadPage = tmpParams.p;

            callback = function(response) {
                me.prependListing(response);

                // Set load previous button if we aren't already on page one
                if (tmpParams.p > 1) {
                    me.showLoadPrevious();
                }
            };

            $.publish(
                'action/fetchListing',
                [tmpParams, false, true, callback]
            );

            $.publish('plugin/swInfiniteScrolling/onLoadPrevious', [ me, event ]);
        },

        /**
         * @param {object} response
         */
        appendListing: function(response) {
            var me = this, template;

            template = response.listing.trim();

            $.publish('plugin/swInfiniteScrolling/onFetchNewPageLoaded', [ me, template ]);

            // Cancel is no data provided
            if (!template) {
                me.isFinished = true;
                me.closeLoadingIndicator();
                return;
            }

            // append fetched data into listing
            me.$el.append(template);

            // trigger picturefill for regenerating thumbnail sizes
            picturefill();

            me.closeLoadingIndicator();

            // enable loading for further pages
            me.isLoading = false;

            // check if last page reached
            if (me.params.p >= me.maxPages) {
                me.isFinished = true;
            }

            $.publish('plugin/swInfiniteScrolling/onFetchNewPageFinished', [ me, template ]);
        },

        /**
         * @param {object} response
         */
        prependListing: function(response) {
            var me = this;

            // append fetched data into listing
            me.$el.prepend(response.listing.trim());

            picturefill();

            me.closeLoadingIndicator();

            // enable loading for further pages
            me.isLoading = false;

            $.publish('plugin/swInfiniteScrolling/onLoadPreviousFinished', [ me, event, response.listing ]);
        },

        /**
         * openLoadingIndicator method
         *
         * opens the loading indicator relative
         */
        openLoadingIndicator: function(type) {
            var me = this,
                $indicator = $('.js--loading-indicator.indicator--relative');

            if ($indicator.length) {
                return;
            }

            $indicator = $('<div>', {
                'class': 'js--loading-indicator indicator--relative',
                'html': $('<i>', {
                    'class': 'icon--default'
                })
            });

            if (!type) {
                me.$el.parent().after($indicator);
            } else {
                me.$el.parent().before($indicator);
            }

            $.publish('plugin/swInfiniteScrolling/onOpenLoadingIndicator', [ me, $indicator ]);
        },

        /**
         * closeLoadingIndicator method
         *
         * close the relative loading indicator
         */
        closeLoadingIndicator: function() {
            var me = this,
                $indicator = $('.js--loading-indicator.indicator--relative');

            if (!$indicator.length) {
                return;
            }

            $indicator.remove();

            $.publish('plugin/swInfiniteScrolling/onCloseLoadingIndicator', [ me ]);
        },

        /**
         * Destroys the plugin
         *
         * @public
         * @method destroy
         */
        destroy: function() {
            var me = this;

            if (me.$buttonWrapperTop) {
                me.$buttonWrapperTop.remove();
            }

            if (me.$buttonWrapperBottom) {
                me.$buttonWrapperBottom.remove();
            }

            // on load more button event for manually fetching further pages
            me.$delegateContainer.off(me.getEventName('click'), '.' + me.opts.loadMoreCls);

            // on load previous button event for manually fetching previous pages
            me.$delegateContainer.off(me.getEventName('click'), '.' + me.opts.loadPreviousCls);

            me._destroy();
        }
    });
})(jQuery, window);
<commit_msg>SW-18951 - Fixed infinite scrolling for sending empty params<commit_after>;(function($, window) {
    'use strict';

    /**
     * Parses the given {@link url} parameter and extracts all query parameters. If the parameter is numeric
     * it will automatically based to a {@link Number} instead of a {@link String}.
     * @private
     * @param {String} url - Usually {@link window.location.href}
     * @returns {{}} Object with all extracted parameters
     */
    var parseQueryString = function(url) {
        var qparams = {},
            parts = (url || '').split('?'),
            qparts, qpart,
            i = 0;

        if (parts.length <= 1) {
            return qparams;
        }

        qparts = parts[1].split('&');
        for (i in qparts) {
            var key, value;

            qpart = qparts[i].split('=');
            key = decodeURIComponent(qpart[0]);
            value = decodeURIComponent(qpart[1] || '');
            qparams[key] = ($.isNumeric(value) ? parseFloat(value, 10) : value);
        }

        return qparams;
    };

    $.plugin('swInfiniteScrolling', {

        defaults: {

            /** @bool enabled - enable or disable infinite scrolling plugin */
            'enabled': true,

            /** @string event - default "scroll" will be used for triggering this plugin */
            'eventName': 'scroll',

            /** @int categoryId - category id is used for generating ajax request */
            'categoryId': 0,

            /** @string pagingSelector - listing paging selector **/
            'pagingSelector': '.listing--paging',

            /** @string productBoxSelector - selector for single product boxes **/
            'productBoxSelector': '.product--box',

            /** @string defaultPerPageSelector - default per page selector which will be removed **/
            'defaultPerPageSelector': '.action--per-page',

            /** @string defaultChangeLayoutSelector - default change layout select which will be get a new margin **/
            'defaultChangeLayoutSelector': '.action--change-layout',

            /** @int threshold - after this threshold reached, auto fetching is disabled and the "load more" button is shown. */
            'threshold': 3,

            /** @string loadMoreCls - this class will be used for fetching further data by button. */
            'loadMoreCls': 'js--load-more',

            /** @string loadPreviousCls - this class  will be used for fetching previous data by button. */
            'loadPreviousCls': 'js--load-previous',

            /** @string Class will be used for load more or previous button */
            'loadBtnCls': 'btn is--primary is--icon-right',

            /** @string loadMoreSnippet - this snippet will be printed inside the load more button */
            'loadMoreSnippet': 'Weitere Artikel laden',

            /** @string loadPreviousSnippet - this snippet will be printed inside the load previous button */
            'loadPreviousSnippet': 'Vorherige Artikel laden',

            /** @string listingContainerSelector - will be used for prepending and appending load previous and load more button */
            'listingContainerSelector': '.listing--container',

            /** @string pagingBottomSelector - this class will be used for removing the bottom paging bar if infinite scrolling is enabled */
            'pagingBottomSelector': '.listing--bottom-paging',

            /** @string listingActionsWrapper - this class will be cloned and used as a actions wrapper for the load more and previous button */
            'listingActionsWrapper': 'infinite--actions',

            /** @string ajaxUrl - this string will be used as url for the ajax-call to load the articles */
            ajaxUrl: window.controller.ajax_listing || null,

            /** @string delegateConSelector - selector for delegate container, used for reload buttons */
            delegateConSelector: '.listing--wrapper'
        },

        /**
         * Default plugin initialisation function.
         * Handle all logic and events for infinite scrolling
         *
         * @public
         * @method init
         */
        init: function() {
            var me = this;

            me.$delegateContainer = $(me.opts.delegateConSelector);

            // Overwrite plugin configuration with user configuration
            me.applyDataAttributes();

            // Check if plugin is enabled
            if (!me.opts.enabled || !me.$el.is(':visible') || me.opts.ajaxUrl === null) {
                return;
            }

            // Remove paging top bar
            $(me.opts.pagingSelector).remove();

            // remove bottom paging bar
            $(me.opts.pagingBottomSelector).remove();

            // Check max pages by data attribute
            me.maxPages = me.$el.attr('data-pages');
            if (me.maxPages <= 1) {
                return;
            }

            // isLoading state for preventing double fetch same content
            me.isLoading = false;

            // isFinished state for disabling plugin if all pages rendered
            me.isFinished = false;

            // resetting fetch Count to prevent auto fetching after threshold reached
            me.fetchCount = 0;

            // previousPageIndex for loading in other direction
            me.previousPageIndex = 0;

            // Prepare top and bottom actions containers
            me.$buttonWrapperTop = $('<div>', {
                'class': me.opts.listingActionsWrapper
            });

            me.$buttonWrapperBottom = $('<div>', {
                'class': me.opts.listingActionsWrapper
            });

            // append load more button
            $(me.opts.listingContainerSelector).after(me.$buttonWrapperBottom);
            $(me.opts.listingContainerSelector).before(me.$buttonWrapperTop);

            // base url for push state and ajax fetch url
            me.baseUrl = window.location.href.split('?')[0];

            // Ajax configuration
            me.ajax = {
                'url': me.opts.ajaxUrl,
                'params': parseQueryString(window.location.href)
            };

            me.params = parseQueryString(window.location.href);
            me.upperParams = $.extend({}, me.params);
            me.historyParams = $.extend({}, me.params);

            me.urlBasicMode = false;

            // if no seo url is provided, use the url basic push mode
            if (!me.params.p) {
                me.basicModeSegments = window.location.pathname.split('/');
                me.basicModePageKey = $.inArray('sPage', me.basicModeSegments);
                me.basicModePageValue = me.basicModeSegments[me.basicModePageKey + 1];

                if (me.basicModePageValue) {
                    me.urlBasicMode = true;
                    me.params.p = me.basicModePageValue;
                    me.upperParams.p = me.basicModePageValue;
                }
            }

            // set page index to one if not assigned
            if (!me.params.p) {
                me.params.p = 1;
            }

            // set start page
            me.startPage = me.params.p;

            // holds the current listing url with all params
            me.currentPushState = '';

            // Check if there is/are previous pages
            if (me.params.p && me.params.p > 1) {
                me.showLoadPrevious();
            }

            // on scrolling event for auto fetching new pages and push state
            me._on(window, me.opts.eventName, $.proxy(me.onScrolling, me));

            // on load more button event for manually fetching further pages
            me.$delegateContainer.on(me.getEventName('click'), '.' + me.opts.loadMoreCls, $.proxy(me.onLoadMore, me));

            // on load previous button event for manually fetching previous pages
            me.$delegateContainer.on(me.getEventName('click'), '.' + me.opts.loadPreviousCls, $.proxy(me.onLoadPrevious, me));

            $.publish('plugin/swInfiniteScrolling/onRegisterEvents', [ me ]);
        },

        update: function () {
            var me = this;

            // disable infinite scrolling, because listing container is not visible
            me.opts.enabled = me.$el.is(':visible');

            $.publish('plugin/swInfiniteScrolling/onUpdate', [ me ]);
        },

        /**
         * onScrolling method
         */
        onScrolling: function() {
            var me = this;

            // stop fetch new page if is loading atm
            if (me.isLoading || !me.opts.enabled) {
                return;
            }

            // Viewport height
            var $window = $(window),
                docTop = $window.scrollTop() + $window.height(),

                // Get last element in list to get the reference point for fetching new data
                fetchPoint = me.$el.find(me.opts.productBoxSelector).last(),
                fetchPointOffset = fetchPoint.offset().top,
                bufferSize = fetchPoint.height(),
                triggerPoint = fetchPointOffset - bufferSize;

            if (docTop > triggerPoint && (me.params.p < me.maxPages)) {
                me.fetchNewPage();
            }

            // collect all pages
            var $products = $('*[data-page-index]'),
                visibleProducts = $.grep($products, function(item) {
                    return $(item).offset().top <= docTop;
                });

            // First visible Product
            var $firstProduct = $(visibleProducts).last(),
                tmpPageIndex = $firstProduct.attr('data-page-index');

            // Collection variables and build push state url
            var tmpParams = me.historyParams;

            // remove category id from history url
            delete tmpParams.c;

            // setting actual page index
            if (!tmpParams.p || !tmpPageIndex) {
                tmpParams.p = me.startPage;
            }

            if (tmpPageIndex) {
                tmpParams.p = tmpPageIndex;
            }

            var tmpPushState = me.baseUrl + '?' + $.param(tmpParams);

            if (me.urlBasicMode) {
                // use start page parameter if no one exists
                if (!tmpPageIndex) {
                    tmpPageIndex = me.basicModePageValue;
                }

                // redesign push url,
                var segments = me.basicModeSegments;
                segments[me.basicModePageKey + 1] = tmpPageIndex;

                tmpPushState = segments.join('/');
            }

            if (me.currentPushState != tmpPushState) {
                me.currentPushState = tmpPushState;
                if (!history || !history.pushState) {
                    return;
                }

                history.pushState('data', '', me.currentPushState);
            }

            $.publish('plugin/swInfiniteScrolling/onScrolling', [ me ]);
        },

        /**
         * fetchNewPage method
         */
        fetchNewPage: function() {
            var me = this;

            // Quit here if all pages rendered
            if (me.isFinished || me.params.p >= me.maxPages) {
                return;
            }

            // stop if process is running
            if (me.isLoading) {
                return;
            }

            // Stop automatic fetch if page threshold reached
            if (me.fetchCount >= me.opts.threshold) {
                var button = me.generateButton('next');

                // append load more button
                me.$buttonWrapperBottom.html(button);

                // set finished flag
                me.isFinished = true;

                return;
            }

            me.isLoading = true;

            me.openLoadingIndicator();

            // increase page index for further page loading
            me.params.p++;

            // increase fetch count for preventing auto fetching
            me.fetchCount++;

            // use categoryId by settings if not defined by filters
            if (!me.params.c && me.opts.categoryId) {
                me.params.c = me.opts.categoryId;
            }

            $.publish('plugin/swInfiniteScrolling/onBeforeFetchNewPage', [ me ]);

            $.publish(
                'action/fetchListing',
                [me.params, false, true, $.proxy(me.appendListing, me)]
            );

            $.publish('plugin/swInfiniteScrolling/onFetchNewPage', [ me ]);
        },

        generateButton: function(buttonType) {
            var me = this,
                type = buttonType || 'next',
                cls = (type == 'previous') ? me.opts.loadPreviousCls : me.opts.loadMoreCls,
                snippet = (type == 'previous') ? me.opts.loadPreviousSnippet : me.opts.loadMoreSnippet,
                $button = $('<a>', {
                    'class': me.opts.loadBtnCls + ' ' + cls,
                    'html': snippet + ' <i class="icon--cw is--large"></i>'
                });

            $.publish('plugin/swInfiniteScrolling/onLoadMore', [ me, $button, buttonType ]);

            return $button;
        },

        /**
         * onLoadMore method
         *
         * @param event
         */
        onLoadMore: function(event) {
            event.preventDefault();

            var me = this;

            // Remove load more button
            $('.' + me.opts.loadMoreCls).remove();

            // Set finished to false to re-enable the fetch method
            me.isFinished = false;

            // Increase threshold for auto fetch next page if there is a next page
            if (me.maxPages >= me.opts.threshold) {
                me.opts.threshold++;
            }

            // fetching new page
            me.fetchNewPage();

            $.publish('plugin/swInfiniteScrolling/onLoadMore', [ me, event ]);
        },

        /**
         * showLoadPrevious method
         *
         * Shows the load previous button
         */
        showLoadPrevious: function() {
            var me = this,
                button = me.generateButton('previous');

            // append load previous button
            me.$buttonWrapperTop.html(button);

            $.publish('plugin/swInfiniteScrolling/onShowLoadPrevious', [ me, button ]);
        },

        /**
         * onLoadPrevious method
         *
         * @param event
         *
         * will be triggered by load previous button
         */
        onLoadPrevious: function(event) {
            event.preventDefault();

            var me = this, callback;

            // Remove load previous button
            $('.' + me.opts.loadPreviousCls).remove();

            // fetching new page
            me.openLoadingIndicator('top');

            // build ajax url
            var tmpParams = me.upperParams;

            // use categoryId by settings if not defined by filters
            if (!tmpParams.c && me.opts.categoryId) {
                tmpParams.c = me.opts.categoryId;
            }

            tmpParams.p = tmpParams.p - 1;

            $.publish('plugin/swInfiniteScrolling/onBeforeFetchPreviousPage', [ me ]);

            me.previousLoadPage = tmpParams.p;

            callback = function(response) {
                me.prependListing(response);

                // Set load previous button if we aren't already on page one
                if (tmpParams.p > 1) {
                    me.showLoadPrevious();
                }
            };

            $.publish(
                'action/fetchListing',
                [tmpParams, false, true, callback]
            );

            $.publish('plugin/swInfiniteScrolling/onLoadPrevious', [ me, event ]);
        },

        /**
         * @param {object} response
         */
        appendListing: function(response) {
            var me = this, template;

            template = response.listing.trim();

            $.publish('plugin/swInfiniteScrolling/onFetchNewPageLoaded', [ me, template ]);

            // Cancel is no data provided
            if (!template) {
                me.isFinished = true;
                me.closeLoadingIndicator();
                return;
            }

            // append fetched data into listing
            me.$el.append(template);

            // trigger picturefill for regenerating thumbnail sizes
            picturefill();

            me.closeLoadingIndicator();

            // enable loading for further pages
            me.isLoading = false;

            // check if last page reached
            if (me.params.p >= me.maxPages) {
                me.isFinished = true;
            }

            $.publish('plugin/swInfiniteScrolling/onFetchNewPageFinished', [ me, template ]);
        },

        /**
         * @param {object} response
         */
        prependListing: function(response) {
            var me = this;

            // append fetched data into listing
            me.$el.prepend(response.listing.trim());

            picturefill();

            me.closeLoadingIndicator();

            // enable loading for further pages
            me.isLoading = false;

            $.publish('plugin/swInfiniteScrolling/onLoadPreviousFinished', [ me, response.listing ]);
        },

        /**
         * openLoadingIndicator method
         *
         * opens the loading indicator relative
         */
        openLoadingIndicator: function(type) {
            var me = this,
                $indicator = $('.js--loading-indicator.indicator--relative');

            if ($indicator.length) {
                return;
            }

            $indicator = $('<div>', {
                'class': 'js--loading-indicator indicator--relative',
                'html': $('<i>', {
                    'class': 'icon--default'
                })
            });

            if (!type) {
                me.$el.parent().after($indicator);
            } else {
                me.$el.parent().before($indicator);
            }

            $.publish('plugin/swInfiniteScrolling/onOpenLoadingIndicator', [ me, $indicator ]);
        },

        /**
         * closeLoadingIndicator method
         *
         * close the relative loading indicator
         */
        closeLoadingIndicator: function() {
            var me = this,
                $indicator = $('.js--loading-indicator.indicator--relative');

            if (!$indicator.length) {
                return;
            }

            $indicator.remove();

            $.publish('plugin/swInfiniteScrolling/onCloseLoadingIndicator', [ me ]);
        },

        /**
         * Destroys the plugin
         *
         * @public
         * @method destroy
         */
        destroy: function() {
            var me = this;

            if (me.$buttonWrapperTop) {
                me.$buttonWrapperTop.remove();
            }

            if (me.$buttonWrapperBottom) {
                me.$buttonWrapperBottom.remove();
            }

            // on load more button event for manually fetching further pages
            me.$delegateContainer.off(me.getEventName('click'), '.' + me.opts.loadMoreCls);

            // on load previous button event for manually fetching previous pages
            me.$delegateContainer.off(me.getEventName('click'), '.' + me.opts.loadPreviousCls);

            me._destroy();
        }
    });
})(jQuery, window);
<|endoftext|>


<commit_before>var Settings = {
    TileSize: 32,

    DebugCollision: false,
    DebugSkipBootLogo: true,

    MatchmakingUri: 'http://localhost:2013'
};<commit_msg>[Net] Use remote matchmaking service (burningtomato.com:2013)<commit_after>var Settings = {
    TileSize: 32,

    DebugCollision: false,
    DebugSkipBootLogo: true,

    MatchmakingUri: 'http://burningtomato.com:2013'
};<|endoftext|>


<commit_before>define(function() {
    return codebox.settings.schema("editor",
        {
            "title": "Code Editor",
            "type": "object",
            "properties": {
                "keyboard": {
                    "description": "Keyboard",
                    "type": "string",
                    "enum": [
                        "vim", "emacs", "textinput"
                    ],
                    "default": "textinput"
                },
                "fontsize": {
                    "description": "Font Size",
                    "type": "integer",
                    "default": 13
                },
                "showprintmargin": {
                    "description": "Show Print Margin",
                    "type": "boolean",
                    "default": false
                },
                "showinvisibles": {
                    "description": "Show Invisibles",
                    "type": "boolean",
                    "default": false
                },
                "highlightactiveline": {
                    "description": "Highlight Active Line",
                    "type": "boolean",
                    "default": false
                },
                "enablesoftwrap": {
                    "description": "Enable Soft Wrap",
                    "type": "boolean",
                    "default": true
                },
                "enablesofttabs": {
                    "description": "Use Soft Tabs",
                    "type": "boolean",
                    "default": true
                },
                "printmargincolumn": {
                    "description": "Print Margin Column",
                    "type": "number",
                    "minimum":  0,
                    "maximum": 1000,
                    "multipleOf": 1,
                    "default": false
                },
                "wraplimitrange": {
                    "description": "Wrap Limit Range",
                    "type": "number",
                    "minimum":  0,
                    "maximum": 1000,
                    "multipleOf": 1,
                    "default": 80
                },
                "tabsize": {
                    "description": "Tab Size",
                    "type": "number",
                    "minimum":  0,
                    "maximum": 1000,
                    "multipleOf": 1,
                    "default": 4
                }
            }
        }
    );
});<commit_msg>Fix default value for print margin settings<commit_after>define(function() {
    return codebox.settings.schema("editor",
        {
            "title": "Code Editor",
            "type": "object",
            "properties": {
                "keyboard": {
                    "description": "Keyboard",
                    "type": "string",
                    "enum": [
                        "vim", "emacs", "textinput"
                    ],
                    "default": "textinput"
                },
                "fontsize": {
                    "description": "Font Size",
                    "type": "integer",
                    "default": 13
                },
                "showprintmargin": {
                    "description": "Show Print Margin",
                    "type": "boolean",
                    "default": false
                },
                "showinvisibles": {
                    "description": "Show Invisibles",
                    "type": "boolean",
                    "default": false
                },
                "highlightactiveline": {
                    "description": "Highlight Active Line",
                    "type": "boolean",
                    "default": false
                },
                "enablesoftwrap": {
                    "description": "Enable Soft Wrap",
                    "type": "boolean",
                    "default": true
                },
                "enablesofttabs": {
                    "description": "Use Soft Tabs",
                    "type": "boolean",
                    "default": true
                },
                "printmargincolumn": {
                    "description": "Print Margin Column",
                    "type": "number",
                    "minimum":  0,
                    "maximum": 1000,
                    "multipleOf": 1,
                    "default": 60
                },
                "wraplimitrange": {
                    "description": "Wrap Limit Range",
                    "type": "number",
                    "minimum":  0,
                    "maximum": 1000,
                    "multipleOf": 1,
                    "default": 80
                },
                "tabsize": {
                    "description": "Tab Size",
                    "type": "number",
                    "minimum":  0,
                    "maximum": 1000,
                    "multipleOf": 1,
                    "default": 4
                }
            }
        }
    );
});<|endoftext|>


<commit_before>var shlog = require(global.gBaseDir + "/src/shlog.js");
var mailer = require(global.gBaseDir + "/src/shmail.js");

var shmailer = exports;

shmailer.sendEmail = function (emailInfo, cb) {
  var locals = {
    email: emailInfo.email,
    subject: "Shelly Game Challenge",
    name: "pitty the fool",
    resetUrl: "http;//localhost:3000/password_rest/000000000001|afdaevdae353"
  };
  mailer.send("challenge", emailInfo, function (err, responseStatus, html, text) {
    if (err) {
      var errorInfo = {code: err.name, message: err.message, emailInfo: emailInfo};
      shlog.error(errorInfo);
      return cb(1, errorInfo);
    }
    return cb(0, {error: err, status: responseStatus});
  });
};

function sendLoop() {
  global.db.spop("jobs:email", function (err, data) {
    shlog.info("mailer check:", err, data);
    if (err === null && data === null) {
      // no emails, wait and loop
      setTimeout(sendLoop, 5000);
      return;
    }

    var emailInfo = JSON.parse(data);
    shlog.info("sending:", emailInfo.email);
    shmailer.sendEmail(emailInfo, function (err, data) {
      shlog.info("sent:", err, data);
    });
    sendLoop();
  });
}

shmailer.queueEmail = function (emailInfo, cb) {
  global.db.sadd("jobs:email", JSON.stringify(emailInfo), cb);
};

shmailer.queueList = function (cb) {
  global.db.smembers("jobs:email", cb);
};

shmailer.start = function () {
  process.on("uncaughtException", function (error) {
    shlog.error("uncaughtException", error.stack);
    // restart the loop
    sendLoop();
  });

  shlog.info("starting mailer");
  sendLoop();
};<commit_msg>change mailer check log to debug;<commit_after>var shlog = require(global.gBaseDir + "/src/shlog.js");
var mailer = require(global.gBaseDir + "/src/shmail.js");

var shmailer = exports;

shmailer.sendEmail = function (emailInfo, cb) {
  var locals = {
    email: emailInfo.email,
    subject: "Shelly Game Challenge",
    name: "pitty the fool",
    resetUrl: "http;//localhost:3000/password_rest/000000000001|afdaevdae353"
  };
  mailer.send("challenge", emailInfo, function (err, responseStatus, html, text) {
    if (err) {
      var errorInfo = {code: err.name, message: err.message, emailInfo: emailInfo};
      shlog.error(errorInfo);
      return cb(1, errorInfo);
    }
    return cb(0, {error: err, status: responseStatus});
  });
};

function sendLoop() {
  global.db.spop("jobs:email", function (err, data) {
    shlog.debug("mailer check:", err, data);
    if (err === null && data === null) {
      // no emails, wait and loop
      setTimeout(sendLoop, 5000);
      return;
    }

    var emailInfo = JSON.parse(data);
    shlog.info("sending:", emailInfo.email);
    shmailer.sendEmail(emailInfo, function (err, data) {
      shlog.info("sent:", err, data);
    });
    sendLoop();
  });
}

shmailer.queueEmail = function (emailInfo, cb) {
  global.db.sadd("jobs:email", JSON.stringify(emailInfo), cb);
};

shmailer.queueList = function (cb) {
  global.db.smembers("jobs:email", cb);
};

shmailer.start = function () {
  process.on("uncaughtException", function (error) {
    shlog.error("uncaughtException", error.stack);
    // restart the loop
    sendLoop();
  });

  shlog.info("starting mailer");
  sendLoop();
};<|endoftext|>


<commit_before>;(function(exports) {
  var Asteroid = function(game, settings) {
    this.game = game;
    this.center = settings.center;
    this.boundingBox = this.game.c.collider.CIRCLE;

    if (settings.radius === undefined) {
      this.size = { x: 60, y: 60 };
    } else {
      this.size = { x: settings.radius * 2, y: settings.radius * 2 };
    }

    if (settings.vel !== undefined) {
      this.vel = settings.vel;
    } else {
      this.vel = {
        x: 0.02 + Math.random() * 0.1 * this.game.maths.plusMinus(),
        y: 0.02 + Math.random() * 0.1 * this.game.maths.plusMinus()
      };
    }
  };

  Asteroid.prototype = {
    destroyed: false,

    update: function(tick) {
      if (this.game.state !== this.game.STATE.PLAYING) return;
      var mx = this.vel.x * tick;
      var my = this.vel.y * tick;
      this.center.x += mx;
      this.center.y += my;

      this.wrap();
    },

    wrap: function() {
      if (this.game.maths.distance(this.center,
                                   this.game.c.renderer.getViewCenter()) >
          (this.game.c.renderer.getViewSize().x / 2 + this.size.x) + 100) {
        if (this.center.x < 0) {
          this.center.x = this.game.c.renderer.getViewSize().x;
        } else if (this.center.x > this.game.c.renderer.getViewSize().x) {
          this.center.x = -this.size.x;
        } else if (this.center.y < 0) {
          this.center.y = this.game.c.renderer.getViewSize().y + 1;
        } else if (this.center.y > this.game.c.renderer.getViewSize().y) {
          this.center.y = 0;
        }
      }
    },

    draw: function(ctx) {
      if (this.game.state !== this.game.STATE.PLAYING) return;

      this.game.startClip(ctx);

      var color = "#fff";
      if (this.getCollidingAsteroids().length === 0) {
        color = "#666";
      }
      this.game.circle(this.center, this.size.x / 2, color);

      this.game.endClip(ctx);
    },

    collision: function(other) {
      if (other instanceof Bullet) {
        var collidingAsteroids = this.getCollidingAsteroids();
        if (collidingAsteroids.length === 0) {
          this.spawnTwin(other);
        } else if (collidingAsteroids.length > 0) {
          for (var i = 0, len = collidingAsteroids.length; i < len; i++) {
            this.game.c.entities.destroy(collidingAsteroids[i]);
          }

          this.game.c.entities.destroy(this);
        }
      } else if (other instanceof Player) {
        this.spawnTwin(other);
      }
    },

    spawnTwin: function(other) {
      this.game.c.entities.create(Asteroid, {
        center: { x:this.center.x, y:this.center.y },
        radius: this.size.x / 2,
        vel: {
          x: this.vel.x + other.vel.x / 15 + Math.random() * 0.1,
          y: this.vel.y + other.vel.y / 15 + Math.random() * 0.1,
        }
      });
    },

    getCollidingAsteroids: function() {
      var self = this;
      return this.game.c.entities.all()
        .filter(function(e) { return e instanceof Asteroid; })
        .filter(function(e) { return self.game.c.collider.isColliding(self, e); });
    }
  };

  exports.Asteroid = Asteroid;
})(this);
<commit_msg>Fix left right space to destroy ALL asteroids in group<commit_after>;(function(exports) {
  var Asteroid = function(game, settings) {
    this.game = game;
    this.center = settings.center;
    this.boundingBox = this.game.c.collider.CIRCLE;

    if (settings.radius === undefined) {
      this.size = { x: 60, y: 60 };
    } else {
      this.size = { x: settings.radius * 2, y: settings.radius * 2 };
    }

    if (settings.vel !== undefined) {
      this.vel = settings.vel;
    } else {
      this.vel = {
        x: 0.02 + Math.random() * 0.1 * this.game.maths.plusMinus(),
        y: 0.02 + Math.random() * 0.1 * this.game.maths.plusMinus()
      };
    }
  };

  Asteroid.prototype = {
    destroyed: false,

    update: function(tick) {
      if (this.game.state !== this.game.STATE.PLAYING) return;
      var mx = this.vel.x * tick;
      var my = this.vel.y * tick;
      this.center.x += mx;
      this.center.y += my;

      this.wrap();
    },

    wrap: function() {
      if (this.game.maths.distance(this.center,
                                   this.game.c.renderer.getViewCenter()) >
          (this.game.c.renderer.getViewSize().x / 2 + this.size.x) + 100) {
        if (this.center.x < 0) {
          this.center.x = this.game.c.renderer.getViewSize().x;
        } else if (this.center.x > this.game.c.renderer.getViewSize().x) {
          this.center.x = -this.size.x;
        } else if (this.center.y < 0) {
          this.center.y = this.game.c.renderer.getViewSize().y + 1;
        } else if (this.center.y > this.game.c.renderer.getViewSize().y) {
          this.center.y = 0;
        }
      }
    },

    draw: function(ctx) {
      if (this.game.state !== this.game.STATE.PLAYING) return;

      this.game.startClip(ctx);

      var color = "#fff";
      if (this.getCollidingAsteroidGroup().length === 0) {
        color = "#666";
      }
      this.game.circle(this.center, this.size.x / 2, color);

      this.game.endClip(ctx);
    },

    collision: function(other) {
      if (other instanceof Bullet) {
        var collidingAsteroids = this.getCollidingAsteroidGroup();
        if (collidingAsteroids.length === 0) {
          this.spawnTwin(other);
        } else if (collidingAsteroids.length > 0) {
          for (var i = 0, len = collidingAsteroids.length; i < len; i++) {
            this.game.c.entities.destroy(collidingAsteroids[i]);
          }

          this.game.c.entities.destroy(this);
        }
      } else if (other instanceof Player) {
        this.spawnTwin(other);
      }
    },

    spawnTwin: function(other) {
      this.game.c.entities.create(Asteroid, {
        center: { x:this.center.x, y:this.center.y },
        radius: this.size.x / 2,
        vel: {
          x: this.vel.x + other.vel.x / 15 + Math.random() * 0.1,
          y: this.vel.y + other.vel.y / 15 + Math.random() * 0.1,
        }
      });
    },

    getCollidingAsteroidGroup: function() {
      var asteroids = this.game.c.entities.all()
          .filter(function(e) { return e instanceof Asteroid; });
      return getCollidingGroup(this, asteroids);
    }
  };

  function getCollidingGroup(entity, allEntities, group) {
    if (group === undefined) { return getCollidingGroup(entity, allEntities, []); }

    var next = allEntities
        .filter(function(e) { return Coquette.Collider.prototype.isColliding(entity, e); });
    for (var i = 0; i < next.length; i++) {
      if (group.indexOf(next[i]) === -1) {
        group.push(next[i]);
        getCollidingGroup(next[i], allEntities, group);
      }
    }

    return group;
  };

  exports.Asteroid = Asteroid;
})(this);
<|endoftext|>


<commit_before>var locastyle = locastyle || {};

locastyle.charCounter = (function() {
  'use strict';

  function updateCounter(index, count) {
    $('.ls-number-counter-'+index).text(count);
  }

  function countText() {
    $('[data-ls-module="charCounter"]').each(function(index, field) {
      $('.ls-number-counter-' + index).parent().remove();

      var limit = $(field).attr('maxlength');
      var html = '
' + limit +
        ' caracteres restantes
';
      var prefixGroup = $(field).closest('.ls-prefix-group');

      $(field).data().maxlength = limit;

      if (prefixGroup.length) {
        prefixGroup.after(html);
      } else {
        $(field).after(html);
      }

      $(field).keyup(function() {
        var count = $(this).val().length;
        var limit = $(this).data().maxlength;

        if(count > limit) {
          $(this).val($(this).val().substring(0, limit));
          updateCounter(index, 0);
        } else {
          updateCounter(index, limit - count);
        }
      });

      $(field).trigger('keyup');
    });
  }

  function init() {
    countText();
  }

  return {
    init: init
  };

}());
<commit_msg>Remove complete parent.<commit_after>var locastyle = locastyle || {};

locastyle.charCounter = (function() {
  'use strict';

  function updateCounter(index, count) {
    $('.ls-number-counter-'+index).text(count);
  }

  function countText() {
    $('[data-ls-module="charCounter"]').each(function(index, field) {
      $('.ls-number-counter-' + index).parents('.ls-help-inline').remove();

      var limit = $(field).attr('maxlength');
      var html = '
' + limit +
        ' caracteres restantes
';
      var prefixGroup = $(field).closest('.ls-prefix-group');

      $(field).data().maxlength = limit;

      if (prefixGroup.length) {
        prefixGroup.after(html);
      } else {
        $(field).after(html);
      }

      $(field).keyup(function() {
        var count = $(this).val().length;
        var limit = $(this).data().maxlength;

        if(count > limit) {
          $(this).val($(this).val().substring(0, limit));
          updateCounter(index, 0);
        } else {
          updateCounter(index, limit - count);
        }
      });

      $(field).trigger('keyup');
    });
  }

  function init() {
    countText();
  }

  return {
    init: init
  };

}());
<|endoftext|>


<commit_before>define([
    "env.config",
    "env.utils"
], function(config, utils) {

    var TranslateToPing = function() {

        this.translate = function(sample){
            switch(sample.type){
                case "traceroute":
                    return this._fromTracerouteToPing(sample);
                    break;

                case "dns":
                    return this._fromDnsToPing(sample);
                    break;

                case "sslcert":
                    return this._fromSslToPing(sample);
                    break;

                case "http":
                    return this._fromHttpToPing(sample);
                    break;

                case "ping":
                    return sample;
                    break;

                default:
                    env.main.error("Not supported streamed sample type", "error");
            }
        };

        this._fromTracerouteToPing = function(sample){
            var pingSample, result, finalHop, finalHopAttempts, item;

            result = sample.result;
            finalHop = {"hop": 0, "result": []};
            finalHopAttempts = [];

            for (var currentHop in result) {
                if (result[currentHop]["hop"] > finalHop["hop"]) {
                    finalHop = result[currentHop];
                }
            }

            for (var n=0,length=finalHop["result"].length; n<length; n++){
                item = finalHop["result"][n];
                if (!item["x"] && item["rtt"]){
                    finalHopAttempts.push(item["rtt"]);
                }
            }
            finalHopAttempts.sort();

            pingSample = {
                "type": "traceroute",
                "prb_id": sample["prb_id"],
                "msm_id": sample["msm_id"],
                "timestamp": sample["timestamp"],
                "src_addr": sample["src_addr"],
                "dst_addr": sample["dst_addr"],
                "sent": finalHop["result"].length,
                "rcvd": finalHopAttempts.length,
                "min": null,
                "avg": null,
                "max": null
            };

            if (pingSample["rcvd"] > 2) {
                pingSample["max"] = finalHopAttempts[finalHopAttempts.length - 1];
                pingSample["avg"] = utils.median(finalHopAttempts);
                pingSample["min"] = finalHopAttempts[0];
            } else if (pingSample["rcvd"] == 2) {
                pingSample["max"] = finalHopAttempts[finalHopAttempts.length - 1];
                pingSample["min"] = finalHopAttempts[0];
            } else {
                pingSample["min"] = finalHopAttempts[0];
            }

            return pingSample;
        };

        this._fromSslToPing = function(sample){
            var pingSample;

            pingSample = {
                "type": "sslcert",
                "msm_id":    sample["msm_id"],
                "prb_id":    sample["prb_id"],
                "rcvd":      ((sample["rt"] != undefined) ? 1 : 0),
                "sent":      1,
                "timestamp": sample["timestamp"],
                "src_addr": sample["src_addr"],
                "dst_addr": sample["dst_addr"],
                "min": null,
                "avg": null,
                "max": null
            };

            if (pingSample["rcvd"] > 0) {
                pingSample["min"] = (sample["rt"]!= undefined) ? sample["rt"] : null;
            }

            return pingSample;
        };

        this._fromDnsToPing = function(sample){
            var pingSample;

            pingSample = {
                "type": "dns",
                "prb_id": sample["prb_id"],
                "msm_id": sample["msm_id"],
                "src_addr": sample["src_addr"],
                "dst_addr": sample["dst_addr"],
                "rcvd": ((sample["error"] != undefined) ? 0 : 1),
                "sent": 1,
                "timestamp": sample["timestamp"],
                "min": null,
                "avg": null,
                "max": null
            };

            if (pingSample["rcvd"] > 0) {
                pingSample["min"] = (sample["result"]["rt"] != undefined) ? sample["result"]["rt"] : null;
            }

            return pingSample;
        };

        this._fromHttpToPing = function(sample){
            var pingSample, latencies, errors, item;

            latencies = [];
            errors = [];
            pingSample = {
                "type": "http",
                "prb_id": sample["prb_id"],
                "msm_id": sample["msm_id"],
                "src_addr": sample["src_addr"],
                "dst_addr": sample["dst_addr"],
                "rcvd": ((sample["result"] != undefined) ? sample["result"].length : 0),
                "sent": ((sample["result"] != undefined) ? Math.max(1, sample["result"].length) : 0),
                "timestamp": sample["timestamp"],
                "min": null,
                "avg": null,
                "max": null
            };

            for (var n=0,length=sample["result"].length; n<length; n++){
                item = sample["result"][n];

                if (item["rt"] != null && item["err"] == null){
                    latencies.push(item["rt"]);
                }

                if (item["err"] != null){
                    errors.push(item["err"]);
                }
            }

            latencies.sort();

            if (pingSample["rcvd"] > 2) {
                pingSample["max"] = latencies[latencies.length - 1];
                pingSample["avg"] = utils.median(latencies);
                pingSample["min"] = latencies[0];
            } else if (pingSample["rcvd"] == 2) {
                pingSample["max"] = latencies[latencies.length - 1];
                pingSample["min"] = latencies[0];
            } else {
                pingSample["min"] = latencies[0];
            }

            if (errors.length > 0){
                pingSample["errors"] = errors;
            }

            return pingSample;
        }
    };

    return new TranslateToPing();
});<commit_msg>fixed Cannot read property 'rt' of undefined for null ping results<commit_after>define([
    "env.config",
    "env.utils"
], function(config, utils) {

    var TranslateToPing = function() {

        this.translate = function(sample){
            switch(sample.type){
                case "traceroute":
                    return this._fromTracerouteToPing(sample);
                    break;

                case "dns":
                    return this._fromDnsToPing(sample);
                    break;

                case "sslcert":
                    return this._fromSslToPing(sample);
                    break;

                case "http":
                    return this._fromHttpToPing(sample);
                    break;

                case "ping":
                    return sample;
                    break;

                default:
                    env.main.error("Not supported streamed sample type", "error");
            }
        };

        this._fromTracerouteToPing = function(sample){
            var pingSample, result, finalHop, finalHopAttempts, item;

            result = sample.result;
            finalHop = {"hop": 0, "result": []};
            finalHopAttempts = [];

            for (var currentHop in result) {
                if (result[currentHop]["hop"] > finalHop["hop"]) {
                    finalHop = result[currentHop];
                }
            }

            for (var n=0,length=finalHop["result"].length; n<length; n++){
                item = finalHop["result"][n];
                if (!item["x"] && item["rtt"]){
                    finalHopAttempts.push(item["rtt"]);
                }
            }
            finalHopAttempts.sort();

            pingSample = {
                "type": "traceroute",
                "prb_id": sample["prb_id"],
                "msm_id": sample["msm_id"],
                "timestamp": sample["timestamp"],
                "src_addr": sample["src_addr"],
                "dst_addr": sample["dst_addr"],
                "sent": finalHop["result"].length,
                "rcvd": finalHopAttempts.length,
                "min": null,
                "avg": null,
                "max": null
            };

            if (pingSample["rcvd"] > 2) {
                pingSample["max"] = finalHopAttempts[finalHopAttempts.length - 1];
                pingSample["avg"] = utils.median(finalHopAttempts);
                pingSample["min"] = finalHopAttempts[0];
            } else if (pingSample["rcvd"] == 2) {
                pingSample["max"] = finalHopAttempts[finalHopAttempts.length - 1];
                pingSample["min"] = finalHopAttempts[0];
            } else {
                pingSample["min"] = finalHopAttempts[0];
            }

            return pingSample;
        };

        this._fromSslToPing = function(sample){
            var pingSample;

            pingSample = {
                "type": "sslcert",
                "msm_id":    sample["msm_id"],
                "prb_id":    sample["prb_id"],
                "rcvd":      ((sample["rt"] != undefined) ? 1 : 0),
                "sent":      1,
                "timestamp": sample["timestamp"],
                "src_addr": sample["src_addr"],
                "dst_addr": sample["dst_addr"],
                "min": null,
                "avg": null,
                "max": null
            };

            if (pingSample["rcvd"] > 0) {
                pingSample["min"] = (sample["rt"]!= undefined) ? sample["rt"] : null;
            }

            return pingSample;
        };

        this._fromDnsToPing = function(sample){
            var pingSample;

            pingSample = {
                "type": "dns",
                "prb_id": sample["prb_id"],
                "msm_id": sample["msm_id"],
                "src_addr": sample["src_addr"],
                "dst_addr": sample["dst_addr"],
                "rcvd": ((sample["error"] != undefined) ? 0 : 1),
                "sent": 1,
                "timestamp": sample["timestamp"],
                "min": null,
                "avg": null,
                "max": null
            };

            if (pingSample["rcvd"] > 0) {
                pingSample["min"] = (sample["result"] && sample["result"]["rt"] != undefined) ? sample["result"]["rt"] : null;
            }

            return pingSample;
        };

        this._fromHttpToPing = function(sample){
            var pingSample, latencies, errors, item;

            latencies = [];
            errors = [];
            pingSample = {
                "type": "http",
                "prb_id": sample["prb_id"],
                "msm_id": sample["msm_id"],
                "src_addr": sample["src_addr"],
                "dst_addr": sample["dst_addr"],
                "rcvd": ((sample["result"] != undefined) ? sample["result"].length : 0),
                "sent": ((sample["result"] != undefined) ? Math.max(1, sample["result"].length) : 0),
                "timestamp": sample["timestamp"],
                "min": null,
                "avg": null,
                "max": null
            };

            for (var n=0,length=sample["result"].length; n<length; n++){
                item = sample["result"][n];

                if (item["rt"] != null && item["err"] == null){
                    latencies.push(item["rt"]);
                }

                if (item["err"] != null){
                    errors.push(item["err"]);
                }
            }

            latencies.sort();

            if (pingSample["rcvd"] > 2) {
                pingSample["max"] = latencies[latencies.length - 1];
                pingSample["avg"] = utils.median(latencies);
                pingSample["min"] = latencies[0];
            } else if (pingSample["rcvd"] == 2) {
                pingSample["max"] = latencies[latencies.length - 1];
                pingSample["min"] = latencies[0];
            } else {
                pingSample["min"] = latencies[0];
            }

            if (errors.length > 0){
                pingSample["errors"] = errors;
            }

            return pingSample;
        }
    };

    return new TranslateToPing();
});<|endoftext|>


<commit_before>import MainSearch from './components/pages/mainSearch.js'
import RequestCode from './components/pages/requestCode.js'
import RequestedCodes from './components/pages/requestedCodes.js'
import SearchUsedCodes from './components/pages/searchUsedCodes.js'

import React from 'react'
import Router from 'react-router'

import Mui from 'material-ui'

import Keybindings from 'react-side-effect-mousetrap'

let { LeftNav, FlatButton } = Mui
let ThemeManager = new Mui.Styles.ThemeManager()

let { Route, RouteHandler,
      DefaultRoute, NotFoundRoute, Redirect } = Router

let menuItems = []

let NotFound = React.createClass({
  render () {
    return (

No Route Found

    )
  }
})

let App = React.createClass({

  mixins: [Router.State],

  contextTypes: {
      router: React.PropTypes.func
  },

// **
// Needed for Material-ui
  childContextTypes: {
    muiTheme: React.PropTypes.object
  },

  getChildContext () {
    return {
      muiTheme: ThemeManager.getCurrentTheme()
    }
  },
// **

  getInitialState () {
    return {
      location: '',
      isDocked: false
    }
  },

  toMainSearch () {
    let { router } = this.context
    router.transitionTo('mainSearch')
  },

  toSearchUsedCodes () {
    let { router } = this.context
    router.transitionTo('searchUsedCodes')
  },

  toRequestedCodes () {
    let { router } = this.context
    router.transitionTo('requestedCodes')
  },

  feedback () {
    window.open('https://trello.com/b/9DTy6SXm/dispense', '_blank')
  },

  keyMap () {
    return {
      'esc': () => {this.toggleNav()}
    }
  },

  toggleNav () {
    this.refs.leftNav.toggle()
    this.setState({
      isDocked: !this.state.isDocked
    })

    // fix material-ui
    // https://github.com/callemall/material-ui/issues/897
    document.body.style.overflow = 'auto'
  },

  render: function () {

    let buttonStyle = {
        height: '50',
        opacity: '0.9'
    }

    return (
      <Keybindings keyMap={{
          'esc': (e) => {
            e.preventDefault()
            this.toggleNav()
          },
          'tab': (e) => {e.preventDefault()},
          'shift+tab': (e) => {e.preventDefault()}
      }}>

            <FlatButton label='Feedback'
              style={buttonStyle}
              onClick={this.feedback}
              secondary={true} />
            <FlatButton label='Main Search'
              style={buttonStyle}
              onClick={this.toMainSearch}
              secondary={true} />
            <FlatButton label='Search Used Codes'
              style={buttonStyle}
              onClick={this.toSearchUsedCodes}
              secondary={true} />
            <FlatButton label='Requested Codes'
              style={buttonStyle}
              onClick={this.toRequestedCodes}
              secondary={true} />

            <RouteHandler toggleNav={this.toggleNav}/>

          <LeftNav ref='leftNav' docked={this.state.isDocked} menuItems={menuItems}/>

      </Keybindings>
    )
  }
})

module.exports = (
          <Route name='app' path='/dispenseApp/' handler={App}>
            <Redirect from='/dispenseApp' to='/dispenseApp/'/>
            <Route name='mainSearch' handler={MainSearch}/>
            <Route name='requestCode' path='requestCode/:productId' handler={RequestCode}/>
            <Route name='searchUsedCodes' path='searchUsedCodes' handler={SearchUsedCodes}/>
            <Route name='requestedCodes' path='requestedCodes' handler={RequestedCodes}/>
            <DefaultRoute handler={MainSearch}/>
            <NotFoundRoute handler={NotFound}/>
          </Route>
        )
<commit_msg>update approutes with changelog<commit_after>import MainSearch from './components/pages/mainSearch.js'
import RequestCode from './components/pages/requestCode.js'
import RequestedCodes from './components/pages/requestedCodes.js'
import SearchUsedCodes from './components/pages/searchUsedCodes.js'
import Changelog from './components/pages/changelog.js'

import React from 'react'
import Router from 'react-router'

import Mui from 'material-ui'
let { MenuItem } = Mui

import Keybindings from 'react-side-effect-mousetrap'

let { LeftNav, FlatButton } = Mui
let ThemeManager = new Mui.Styles.ThemeManager()

let { Route, RouteHandler,
      DefaultRoute, NotFoundRoute, Redirect } = Router

let menuItems = [
  {
     type: MenuItem.Types.LINK,
     payload: 'changelog',
     text: 'Changelog'
  }
]

let NotFound = React.createClass({
  render () {
    return (

No Route Found

    )
  }
})

let App = React.createClass({

  mixins: [Router.State],

  contextTypes: {
      router: React.PropTypes.func
  },

// **
// Needed for Material-ui
  childContextTypes: {
    muiTheme: React.PropTypes.object
  },

  getChildContext () {
    return {
      muiTheme: ThemeManager.getCurrentTheme()
    }
  },
// **

  getInitialState () {
    return {
      location: '',
      isDocked: false
    }
  },

  toMainSearch () {
    let { router } = this.context
    router.transitionTo('mainSearch')
  },

  toSearchUsedCodes () {
    let { router } = this.context
    router.transitionTo('searchUsedCodes')
  },

  toRequestedCodes () {
    let { router } = this.context
    router.transitionTo('requestedCodes')
  },

  feedback () {
    window.open('https://trello.com/b/9DTy6SXm/dispense', '_blank')
  },

  keyMap () {
    return {
      'esc': () => {this.toggleNav()}
    }
  },

  toggleNav () {
    this.refs.leftNav.toggle()
    this.setState({
      isDocked: !this.state.isDocked
    })

    // fix material-ui
    // https://github.com/callemall/material-ui/issues/897
    document.body.style.overflow = 'auto'
  },

  render: function () {

    let buttonStyle = {
        height: '50',
        opacity: '0.9'
    }

    return (
      <Keybindings keyMap={{
          'esc': (e) => {
            e.preventDefault()
            this.toggleNav()
          },
          'tab': (e) => {e.preventDefault()},
          'shift+tab': (e) => {e.preventDefault()}
      }}>

            <FlatButton label='Feedback'
              style={buttonStyle}
              onClick={this.feedback}
              secondary={true} />
            <FlatButton label='Main Search'
              style={buttonStyle}
              onClick={this.toMainSearch}
              secondary={true} />
            <FlatButton label='Search Used Codes'
              style={buttonStyle}
              onClick={this.toSearchUsedCodes}
              secondary={true} />
            <FlatButton label='Requested Codes'
              style={buttonStyle}
              onClick={this.toRequestedCodes}
              secondary={true} />

            <RouteHandler toggleNav={this.toggleNav}/>

          <LeftNav ref='leftNav' docked={this.state.isDocked} menuItems={menuItems}/>

      </Keybindings>
    )
  }
})

module.exports = (
          <Route name='app' path='/dispenseApp/' handler={App}>
            <Redirect from='/dispenseApp' to='/dispenseApp/'/>
            <Route name='mainSearch' handler={MainSearch}/>
            <Route name='requestCode' path='requestCode/:productId' handler={RequestCode}/>
            <Route name='searchUsedCodes' path='searchUsedCodes' handler={SearchUsedCodes}/>
            <Route name='requestedCodes' path='requestedCodes' handler={RequestedCodes}/>
            <Route name='changelog' path='changelog' handler={Changelog}/>
            <DefaultRoute handler={MainSearch}/>
            <NotFoundRoute handler={NotFound}/>
          </Route>
        )
<|endoftext|>


<commit_before>jQuery(document).ready(function ($) {
    if (pagenow !== 'mod-posts') {
        return;
    }

    /**
     * Posttype Meta keys
     */
    getPostMeta({
        'action': 'get_sortable_meta_keys_v2',
        'posttype': $('#modularity-latest-post-type select').val(),
        'post': modularity_current_post_id
    });

    $('#modularity-latest-post-type select').on('change', function () {
        getPostMeta({
            'action': 'get_sortable_meta_keys_v2',
            'posttype': $(this).val(),
            'post': modularity_current_post_id
        });
    });

    function getPostMeta(data) {
        if ($('#modularity-sorted-by select optgroup[label="Post fields"]').length === 0) {
            $('#modularity-sorted-by select').prepend('<optgroup label="Post fields">').append('</optgroup>');
        }

        $('#modularity-latest-meta-key label, #modularity-sorted-by label').prepend('')

        $.post(ajaxurl, data, function (response) {
            $('#modularity-sorted-by select option[value^="_metakey_"], #modularity-sorted-by select optgroup[label="Post meta"]').remove();
            $('#modularity-latest-meta-key select').empty();

            if (response.meta_keys.length > 2) {
                $('#modularity-sorted-by select').append('<optgroup label="Post meta">');

                $.each(response.meta_keys, function (index, item) {
                    var sort_selected = (response.sort_curr != null && item.meta_key == response.sort_curr.replace('_metakey_', '')) ? 'selected' : '';
                    var filter_selected = (response.filter_curr != null && item.meta_key == response.filter_curr.replace('_metakey_', '')) ? 'selected' : '';

                    $('#modularity-sorted-by select').append('<option value="_metakey_' + item.meta_key +'" ' + sort_selected + '>' + item.meta_key +'</option>');
                    $('#modularity-latest-meta-key select').append('<option value="' + item.meta_key + '" ' + filter_selected + '>' + item.meta_key + '</option>');
                });

                $('#modularity-sorted-by select').append('</optgroup>');
            }

            $('#modularity-latest-meta-key .spinner, #modularity-sorted-by .spinner').remove();
        }, 'json');
    }

    /**
     * Taxonomy type update
     */
    getTaxonomyTypes({
        'action': 'get_taxonomy_types_v2',
        'posttype': $('#modularity-latest-post-type select').val(),
        'post': modularity_current_post_id
    });

    $('#modularity-latest-post-type select').on('change', function () {
        getTaxonomyTypes({
            'action': 'get_taxonomy_types_v2',
            'posttype': $(this).val(),
            'post': modularity_current_post_id
        });
    });

    function getTaxonomyTypes(data) {
        $('#modularity-latest-taxonomy select').empty();
        $('#modularity-latest-taxonomy .acf-label label').prepend('');

        $.post(ajaxurl, data, function (response) {
            if (response.types.length === 0) {
                $('#modularity-latest-taxonomy .acf-label label .spinner').remove();
                return;
            }

            $.each(response.types, function (index, item) {
                var is_selected = (item.name == response.curr) ? 'selected' : '';
                $('#modularity-latest-taxonomy select').append('<option value="' + item.name+ '" ' + is_selected + '>' + item.label + '</option>');
            });

            $('#modularity-latest-taxonomy .acf-label label .spinner').remove();

            getTaxonomyValues({
                'action': 'get_taxonomy_values_v2',
                'tax': $('#modularity-latest-taxonomy select').val(),
                'post': modularity_current_post_id
            });
        }, 'json');
    }

    /**
     * Taxonomy values update
     */
    $('#modularity-latest-taxonomy select').on('change', function () {
        getTaxonomyValues({
            'action': 'get_taxonomy_values_v2',
            'tax': $(this).val(),
            'post': modularity_current_post_id
        });
    });

    function getTaxonomyValues(data) {
        $('#modularity-latest-taxonomy-value select').empty();
        $('#modularity-latest-taxonomy-value .acf-label label').prepend('');

        $.post(ajaxurl, data, function (response) {
            $.each(response.tax, function (index, item) {
                var is_selected = (item.slug == response.curr) ? 'selected' : '';
                $('#modularity-latest-taxonomy-value select').append('<option value="' + item.slug + '" ' + is_selected + '>' + item.name + '</option>');
            });

            $('#modularity-latest-taxonomy-value .acf-label label .spinner').remove();
        }, 'json');
    }

});
<commit_msg>Fixed Gutenberg problems with taxonomy selector<commit_after>jQuery(document).ready(function() {
    if (pagenow === 'mod-posts') {
        postsTaxonomy(modularity_current_post_id);
    }
});

jQuery(document).on('click', '.acf-block-preview', function(){
    let blockLoaded = false;
    let blockLoadedInterval = setInterval(function() {
        if (document.getElementById('modularity-latest-taxonomy-value')) {
            const block = wp.data.select('core/block-editor').getSelectedBlock();
            //console.log(block.attributes.data);
            postsTaxonomy(modularity_current_post_id, block.attributes.data);
            blockLoaded = true;
        }
        if (blockLoaded) {
            clearInterval(blockLoadedInterval);
        }
    }, 500);
});

function postsTaxonomy(modularity_current_post_id, data = null) {
    var $ = (jQuery);
    var taxType = (data == null)? null : data.posts_taxonomy_type;
    var taxValue = (data == null)? null : data.posts_taxonomy_value;
    /**
     * Posttype Meta keys
     */

    getPostMeta({
        'action': 'get_sortable_meta_keys_v2',
        'posttype': $('#modularity-latest-post-type select').val(),
        'post': modularity_current_post_id
    });

    $('#modularity-latest-post-type select').on('change', function () {
        getPostMeta({
            'action': 'get_sortable_meta_keys_v2',
            'posttype': $(this).val(),
            'post': modularity_current_post_id
        });
    });

    /**
     * Taxonomy type update
     */
    getTaxonomyTypes({
        'action': 'get_taxonomy_types_v2',
        'posttype': $('#modularity-latest-post-type select').val(),
        'post': modularity_current_post_id,
        'selected': taxType
    });

    $('#modularity-latest-post-type select').on('change', function () {
        getTaxonomyTypes({
            'action': 'get_taxonomy_types_v2',
            'posttype': $(this).val(),
            'post': modularity_current_post_id
        });
    });

    /**
     * Taxonomy values update
     */

     getTaxonomyValues({
        'action': 'get_taxonomy_values_v2',
        'tax': taxType,
        'post': modularity_current_post_id,
        'selected': taxValue
    });

    $('#modularity-latest-taxonomy select').on('change', function () {
        getTaxonomyValues({
            'action': 'get_taxonomy_values_v2',
            'tax': $(this).val(),
            'post': modularity_current_post_id
        });
    });

}

function getPostMeta(data) {
    if ($('#modularity-sorted-by select optgroup[label="Post fields"]').length === 0) {
        $('#modularity-sorted-by select').prepend('<optgroup label="Post fields">').append('</optgroup>');
    }

    $('#modularity-latest-meta-key label, #modularity-sorted-by label').prepend('')

    $.post(ajaxurl, data, function (response) {
        $('#modularity-sorted-by select option[value^="_metakey_"], #modularity-sorted-by select optgroup[label="Post meta"]').remove();
        $('#modularity-latest-meta-key select').empty();

        if (response.meta_keys.length > 2) {
            $('#modularity-sorted-by select').append('<optgroup label="Post meta">');

            $.each(response.meta_keys, function (index, item) {
                var sort_selected = (response.sort_curr != null && item.meta_key == response.sort_curr.replace('_metakey_', '')) ? 'selected' : '';
                var filter_selected = (response.filter_curr != null && item.meta_key == response.filter_curr.replace('_metakey_', '')) ? 'selected' : '';

                $('#modularity-sorted-by select').append('<option value="_metakey_' + item.meta_key +'" ' + sort_selected + '>' + item.meta_key +'</option>');
                $('#modularity-latest-meta-key select').append('<option value="' + item.meta_key + '" ' + filter_selected + '>' + item.meta_key + '</option>');
            });

            $('#modularity-sorted-by select').append('</optgroup>');
        }

        $('#modularity-latest-meta-key .spinner, #modularity-sorted-by .spinner').remove();
    }, 'json');
}

function getTaxonomyTypes(data) {
    $('#modularity-latest-taxonomy select').empty();
    $('#modularity-latest-taxonomy .acf-label label').prepend('');

    $.post(ajaxurl, data, function (response) {
        if (response.types.length === 0) {
            $('#modularity-latest-taxonomy .acf-label label .spinner').remove();
            return;
        }
        $.each(response.types, function (index, item) {
            var is_selected = (item.name == response.curr || item.name == data.selected) ? 'selected' : '';
            $('#modularity-latest-taxonomy select').append('<option value="' + item.name+ '" ' + is_selected + '>' + item.label + '</option>');
        });

        $('#modularity-latest-taxonomy .acf-label label .spinner').remove();

        getTaxonomyValues({
            'action': 'get_taxonomy_values_v2',
            'tax': $('#modularity-latest-taxonomy select').val(),
            'post': modularity_current_post_id
        });
    }, 'json');
}

function getTaxonomyValues(data) {
    $('#modularity-latest-taxonomy-value select').empty();
    $('#modularity-latest-taxonomy-value .acf-label label').prepend('');

    $.post(ajaxurl, data, function (response) {
        $.each(response.tax, function (index, item) {
            if ($("#modularity-latest-taxonomy-value select option[value='"+item.slug+"']").length == 0) {
                var is_selected = (item.slug == response.curr || item.slug == data.selected) ? 'selected' : '';
                $('#modularity-latest-taxonomy-value select').append('<option value="' + item.slug + '" ' + is_selected + '>' + item.name + '</option>');
            }
        });

        $('#modularity-latest-taxonomy-value .acf-label label .spinner').remove();
    }, 'json');
}<|endoftext|>


<commit_before>describe("chorus.models.HdfsDirectoryEntry", function() {
    it("has the right entityType", function() {
        expect(this.model.entityType).toBe("hdfs");
    });
});<commit_msg>Fix bad spec<commit_after>describe("chorus.models.HdfsDirectoryEntry", function() {
    it("has the right entityType", function() {
        this.model = fixtures.hdfsDirectoryEntryFile();
        expect(this.model.entityType).toBe("hdfs");
    });
});<|endoftext|>