<commit_before>/*
    Copyright 2014 UW Information Technology, University of Washington

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

    Changes:

    =================================================================

*/

window.spacescout_reviews = {
    review_char_limit: 300,
    pagination: 5
};

function setupRatingsAndReviews(data) {

    $('.space-ratings-and-reviews').html(Handlebars.compile($('#space_reviews').html())());

    if (data && data.length) {
        showRatingEditorButton();
    }

    $('.space-ratings-and-reviews h4 .write-a-review').on('click', function (e) {
        showRatingEditor();
    });

    $('.space-review-compose textarea').bind('input', function (e) {
        var l = $(this).val().length,
            remaining = window.spacescout_reviews.review_char_limit - l,
            span = $('#space-review-remaining');

        if (remaining > 0) {
            span.html(remaining);
            span.removeClass('required');
        } else {
            span.html(0);
            span.addClass('required');
        }

        if (l > 0 && $('.space-review-compose .space-review-stars i.fa-star').length) {
            enableSubmitButton();
        } else {
            disableSubmitButton();
        }
    });

    $('button#space-review-cancel').click(function (e) {
        $('.space-review-compose').hide(400);
        if ($('.space-reviews-none').length) {
            $('.space-reviews-none').show();
        } else {
            showRatingEditorButton();
        }

        tidyUpRatesComposer();
    });

    $('button#space-review-submit').click(function (e) {
        var id = $(e.target).closest('div[id^=detail_container_]').attr('id').match(/_(\d+)$/)[1],
            node = $('.space-review-compose'),
            review = {
                rating: $('.space-review-rating i.fa-star', node).length,
                review: $('textarea', node).val().trim()
            };

        // validate
        if (review.rating < 1 || review.rating > 5 || review.review.length <= 0) {
            return;
        }

        // defer until authenticated
        if (window.spacescout_authenticated_user.length == 0) {
            $.cookie('space_review', JSON.stringify({ id: id, review: review }));
            window.location.href = '/login?next=' + window.location.pathname;
        }

        postRatingAndReview(id, review);
    });

    $('.space-review-submitted a').click(function (e) {
        $('.space-review-submitted').hide(400);

        if ($('.space-reviews-none').length) {
            $('.space-reviews-none').show();
        } else {
            showRatingEditorButton();
        }
    });

    $(document).on('click', '.space-review-stars i', function (e) {
        var target = $(e.target),
            stars = target.prevAll('i'),
            rating = stars.length + 1,
            ratings = ['', gettext('terrible'), gettext('poor'),
                       gettext('average'), gettext('good'), gettext('excellent')];

        stars.switchClass('fa-star-o', 'fa-star');
        target.switchClass('fa-star-o', 'fa-star');
        target.nextAll('i').switchClass('fa-star', 'fa-star-o');
        $('.space-review-stars span:last-child').html(ratings[rating]);
        if ($('.space-review-compose textarea').val().length) {
            enableSubmitButton();
        }
    });

    $('.space-review-compose a').on('click', function () {
        if ($(this).next().is(':visible')) {
            hideReviewGuidelines();
        } else {
            showReviewGuidelines();
        }
    });

    $(document).on('loadSpaceReviews', function (e, id) {
        var review = $.cookie('space_review');

        if (review && window.spacescout_authenticated_user.length > 0) {
            var json_review = review ? JSON.parse(review) : null;

            if (json_review) {
                postRatingAndReview(json_review.id, json_review.review);
                $('.space-reviews-none').hide();
            }

            $.removeCookie('space_review');
        }

        $('#show_reviews').css('cursor', 'pointer');
        $('#show_reviews').click(function () {
            $('.space-detail-body').animate({ scrollTop: $('.space-ratings-and-reviews').offset().top
                                              + $('.space-detail-body').scrollTop()
                                              - $('.space-detail-body').offset().top }, '500');
        });
    });
}

function loadRatingsAndReviews(id, review_container, rating_container) {
    $.ajax({
        url: '/web_api/v1/space/' + id + '/reviews',
        success: function (data) {
            var template = Handlebars.compile($('#space_reviews_review').html()),
                rating_sum = 0,
                total_reviews = (data && data.length) ? data.length : 0,
                html_count = Handlebars.compile($('#space_reviews_count').html())({ count : total_reviews }),
                node;

            review_container.html('');

            $('span#review_count', rating_container).html(html_count);

            if (total_reviews > 0) {

                data.sort(function (a, b) {
                    return new Date(b.date_submitted) - new Date(a.date_submitted);
                });

                $.each(data, function(i) {
                    var review = this,
                        rating = this.rating,
                        date = new Date(this.date_submitted);

                    node = $(template({
                        reviewer: this.reviewer,
                        review: (this.review && this.review.length) ? this.review : 'No review provided',
                        date: date ? monthname_from_month(date.getMonth()) + ' ' + date.getDate() + ', ' + date.getFullYear() : ''
                    }));

                    rating_sum += parseInt(this.rating);

                    $('.space-review-header i', node).each(function(i) {
                        if (i < rating) {
                            $(this).switchClass('fa-star-o', 'fa-star');
                        }
                    });

                    if (i >= window.spacescout_reviews.pagination) {
                        node.hide();
                    }

                    review_container.append(node);
                });

                if (data.length > window.spacescout_reviews.pagination) {
                    node = Handlebars.compile($('#more_space_reviews').html())();
                    review_container.append(node);

                    $('.more-space-reviews a').on('click', function (e) {
                        $('.space-reviews-review:hidden').each(function (i) {
                            if (i < window.spacescout_reviews.pagination) {
                                $(this).slideDown(400);
                            }
                        });

                        if ($('.space-reviews-review:hidden').length <= 0) {
                            $(this).parent().hide();
                        }
                    });
                }

                if (rating_sum) {
                    var avg = rating_sum / data.length,
                        dec = Math.floor(avg),
                        frac = avg % 1;

                    $('i', rating_container).each(function(i) {
                        if (i < dec) {
                            $(this).switchClass('fa-star-o', 'fa-star');
                        } else if (i == dec && frac > 0) {
                            if (frac > 0.5) {
                                $(this).switchClass('fa-star-o', 'fa-star');
                            } else {
                                $(this).switchClass('fa-star-o', 'fa-star-half-o');
                            }
                        }
                    });
                }

                showRatingEditorButton();
            } else if ($('.space-review-compose').length) {
                hideRatingEditorButton();
                review_container.html(Handlebars.compile($('#no_space_reviews').html())());
                $('.write-a-review', review_container).on('click', function (e) {
                    showRatingEditor();
                });
            } else {
                review_container.remove();
            }

            $.event.trigger('loadSpaceReviews', [ id ]);
        },
        error: function (xhr, textStatus, errorThrown) {
            console.log('Unable to load reviews: ' + xhr.responseText);
        }
    });
}

function postRatingAndReview(id, review) {
    $.ajax({
        url: '/web_api/v1/space/' + id + '/reviews',
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(review),
        type: "POST",
        success: function (data) {
            tidyUpRatesComposer();
            $('.space-review-compose').hide(400);
            $('.space-review-submitted').show(400);
        },
        error: function (xhr, textStatus, errorThrown) {
            console.log('Unable to post reviews: ' + xhr.responseText);
        }
    });
}

function showRatingEditor () {
    disableSubmitButton();
    hideRatingEditorButton();
    $('#space-review-remaining').html(window.spacescout_reviews.review_char_limit);
    $('.space-reviews-none').hide(400);
    $('.space-review-compose').show(400, function(){
        var w_node = $('.space-detail-body'),
            w_top = w_node.scrollTop(),
            w_height = w_node.height(),
            t_node = $(this),
            t_top = t_node.offset().top - w_node.offset().top,
            t_height = t_node.height(),
            diff = Math.ceil((t_top + t_height) - (w_top + w_height)),
            padding = 20;

        if (diff > 0) {
            w_node.animate( {scrollTop: (diff + w_top + padding)}, '500');
        }
    });
}

function tidyUpRatesComposer () {
    var node = $('.space-review-compose');

    disableSubmitButton();
    hideReviewGuidelines();
    $('textarea', node).val('');
    $('.space-review-stars span + span', node).html('');
    $('#space-review-remaining').html(window.spacescout_reviews.review_char_limit);
    $('#space-review-remaining').removeClass('required');
    $('.space-review-rating div + div span', node).removeClass('required');
    $('.space-review-rating i', node).switchClass('fa-star', 'fa-star-o');
}

function showRatingEditorButton () {
    $('.space-ratings-and-reviews h4 button.write-a-review').show();
}

function hideRatingEditorButton () {
    $('.space-ratings-and-reviews h4 button.write-a-review').hide();
}

function enableSubmitButton () {
    $('button#space-review-submit').removeAttr('disabled');
}

function disableSubmitButton () {
    $('button#space-review-submit').attr('disabled', 'disabled');
}

function showReviewGuidelines () {
    var ul = $('.space-review-compose ul');

    ul.show();
    ul.prev().find('i').switchClass('fa-angle-double-down', 'fa-angle-double-up');
}

function hideReviewGuidelines () {
    var ul = $('.space-review-compose ul');

    ul.hide();
    ul.prev().find('i').switchClass('fa-angle-double-up', 'fa-angle-double-down');
};
<commit_msg>enforces text in review<commit_after>/*
    Copyright 2014 UW Information Technology, University of Washington

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

    Changes:

    =================================================================

*/

window.spacescout_reviews = {
    review_char_limit: 300,
    pagination: 5
};

function setupRatingsAndReviews(data) {

    $('.space-ratings-and-reviews').html(Handlebars.compile($('#space_reviews').html())());

    if (data && data.length) {
        showRatingEditorButton();
    }

    $('.space-ratings-and-reviews h4 .write-a-review').on('click', function (e) {
        showRatingEditor();
    });

    $('.space-review-compose textarea').bind('input', function (e) {
        var text = $(this).val(),
            remaining = window.spacescout_reviews.review_char_limit - text.length,
            span = $('#space-review-remaining');

        if (remaining > 0) {
            span.html(remaining);
            span.removeClass('required');
        } else {
            span.html(0);
            span.addClass('required');
        }

        if (text.trim().length > 0
            && $('.space-review-compose .space-review-stars i.fa-star').length) {
            enableSubmitButton();
        } else {
            disableSubmitButton();
        }
    });

    $('button#space-review-cancel').click(function (e) {
        $('.space-review-compose').hide(400);
        if ($('.space-reviews-none').length) {
            $('.space-reviews-none').show();
        } else {
            showRatingEditorButton();
        }

        tidyUpRatesComposer();
    });

    $('button#space-review-submit').click(function (e) {
        var id = $(e.target).closest('div[id^=detail_container_]').attr('id').match(/_(\d+)$/)[1],
            node = $('.space-review-compose'),
            review = {
                rating: $('.space-review-rating i.fa-star', node).length,
                review: $('textarea', node).val().trim()
            };

        // validate
        if (review.rating < 1 || review.rating > 5 || review.review.length <= 0) {
            return;
        }

        // defer until authenticated
        if (window.spacescout_authenticated_user.length == 0) {
            $.cookie('space_review', JSON.stringify({ id: id, review: review }));
            window.location.href = '/login?next=' + window.location.pathname;
        }

        postRatingAndReview(id, review);
    });

    $('.space-review-submitted a').click(function (e) {
        $('.space-review-submitted').hide(400);

        if ($('.space-reviews-none').length) {
            $('.space-reviews-none').show();
        } else {
            showRatingEditorButton();
        }
    });

    $(document).on('click', '.space-review-stars i', function (e) {
        var target = $(e.target),
            stars = target.prevAll('i'),
            rating = stars.length + 1,
            ratings = ['', gettext('terrible'), gettext('poor'),
                       gettext('average'), gettext('good'), gettext('excellent')];

        stars.switchClass('fa-star-o', 'fa-star');
        target.switchClass('fa-star-o', 'fa-star');
        target.nextAll('i').switchClass('fa-star', 'fa-star-o');
        $('.space-review-stars span:last-child').html(ratings[rating]);
        if ($('.space-review-compose textarea').val().length) {
            enableSubmitButton();
        }
    });

    $('.space-review-compose a').on('click', function () {
        if ($(this).next().is(':visible')) {
            hideReviewGuidelines();
        } else {
            showReviewGuidelines();
        }
    });

    $(document).on('loadSpaceReviews', function (e, id) {
        var review = $.cookie('space_review');

        if (review && window.spacescout_authenticated_user.length > 0) {
            var json_review = review ? JSON.parse(review) : null;

            if (json_review) {
                postRatingAndReview(json_review.id, json_review.review);
                $('.space-reviews-none').hide();
            }

            $.removeCookie('space_review');
        }

        $('#show_reviews').css('cursor', 'pointer');
        $('#show_reviews').click(function () {
            $('.space-detail-body').animate({ scrollTop: $('.space-ratings-and-reviews').offset().top
                                              + $('.space-detail-body').scrollTop()
                                              - $('.space-detail-body').offset().top }, '500');
        });
    });
}

function loadRatingsAndReviews(id, review_container, rating_container) {
    $.ajax({
        url: '/web_api/v1/space/' + id + '/reviews',
        success: function (data) {
            var template = Handlebars.compile($('#space_reviews_review').html()),
                rating_sum = 0,
                total_reviews = (data && data.length) ? data.length : 0,
                html_count = Handlebars.compile($('#space_reviews_count').html())({ count : total_reviews }),
                node;

            review_container.html('');

            $('span#review_count', rating_container).html(html_count);

            if (total_reviews > 0) {

                data.sort(function (a, b) {
                    return new Date(b.date_submitted) - new Date(a.date_submitted);
                });

                $.each(data, function(i) {
                    var review = this,
                        rating = this.rating,
                        date = new Date(this.date_submitted);

                    node = $(template({
                        reviewer: this.reviewer,
                        review: (this.review && this.review.length) ? this.review : 'No review provided',
                        date: date ? monthname_from_month(date.getMonth()) + ' ' + date.getDate() + ', ' + date.getFullYear() : ''
                    }));

                    rating_sum += parseInt(this.rating);

                    $('.space-review-header i', node).each(function(i) {
                        if (i < rating) {
                            $(this).switchClass('fa-star-o', 'fa-star');
                        }
                    });

                    if (i >= window.spacescout_reviews.pagination) {
                        node.hide();
                    }

                    review_container.append(node);
                });

                if (data.length > window.spacescout_reviews.pagination) {
                    node = Handlebars.compile($('#more_space_reviews').html())();
                    review_container.append(node);

                    $('.more-space-reviews a').on('click', function (e) {
                        $('.space-reviews-review:hidden').each(function (i) {
                            if (i < window.spacescout_reviews.pagination) {
                                $(this).slideDown(400);
                            }
                        });

                        if ($('.space-reviews-review:hidden').length <= 0) {
                            $(this).parent().hide();
                        }
                    });
                }

                if (rating_sum) {
                    var avg = rating_sum / data.length,
                        dec = Math.floor(avg),
                        frac = avg % 1;

                    $('i', rating_container).each(function(i) {
                        if (i < dec) {
                            $(this).switchClass('fa-star-o', 'fa-star');
                        } else if (i == dec && frac > 0) {
                            if (frac > 0.5) {
                                $(this).switchClass('fa-star-o', 'fa-star');
                            } else {
                                $(this).switchClass('fa-star-o', 'fa-star-half-o');
                            }
                        }
                    });
                }

                showRatingEditorButton();
            } else if ($('.space-review-compose').length) {
                hideRatingEditorButton();
                review_container.html(Handlebars.compile($('#no_space_reviews').html())());
                $('.write-a-review', review_container).on('click', function (e) {
                    showRatingEditor();
                });
            } else {
                review_container.remove();
            }

            $.event.trigger('loadSpaceReviews', [ id ]);
        },
        error: function (xhr, textStatus, errorThrown) {
            console.log('Unable to load reviews: ' + xhr.responseText);
        }
    });
}

function postRatingAndReview(id, review) {
    $.ajax({
        url: '/web_api/v1/space/' + id + '/reviews',
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(review),
        type: "POST",
        success: function (data) {
            tidyUpRatesComposer();
            $('.space-review-compose').hide(400);
            $('.space-review-submitted').show(400);
        },
        error: function (xhr, textStatus, errorThrown) {
            console.log('Unable to post reviews: ' + xhr.responseText);
        }
    });
}

function showRatingEditor () {
    disableSubmitButton();
    hideRatingEditorButton();
    $('#space-review-remaining').html(window.spacescout_reviews.review_char_limit);
    $('.space-reviews-none').hide(400);
    $('.space-review-compose').show(400, function(){
        var w_node = $('.space-detail-body'),
            w_top = w_node.scrollTop(),
            w_height = w_node.height(),
            t_node = $(this),
            t_top = t_node.offset().top - w_node.offset().top,
            t_height = t_node.height(),
            diff = Math.ceil((t_top + t_height) - (w_top + w_height)),
            padding = 20;

        if (diff > 0) {
            w_node.animate( {scrollTop: (diff + w_top + padding)}, '500');
        }
    });
}

function tidyUpRatesComposer () {
    var node = $('.space-review-compose');

    disableSubmitButton();
    hideReviewGuidelines();
    $('textarea', node).val('');
    $('.space-review-stars span + span', node).html('');
    $('#space-review-remaining').html(window.spacescout_reviews.review_char_limit);
    $('#space-review-remaining').removeClass('required');
    $('.space-review-rating div + div span', node).removeClass('required');
    $('.space-review-rating i', node).switchClass('fa-star', 'fa-star-o');
}

function showRatingEditorButton () {
    $('.space-ratings-and-reviews h4 button.write-a-review').show();
}

function hideRatingEditorButton () {
    $('.space-ratings-and-reviews h4 button.write-a-review').hide();
}

function enableSubmitButton () {
    $('button#space-review-submit').removeAttr('disabled');
}

function disableSubmitButton () {
    $('button#space-review-submit').attr('disabled', 'disabled');
}

function showReviewGuidelines () {
    var ul = $('.space-review-compose ul');

    ul.show();
    ul.prev().find('i').switchClass('fa-angle-double-down', 'fa-angle-double-up');
}

function hideReviewGuidelines () {
    var ul = $('.space-review-compose ul');

    ul.hide();
    ul.prev().find('i').switchClass('fa-angle-double-up', 'fa-angle-double-down');
};
<|endoftext|>


<commit_before>// geolocation

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition( getStreetCityZip );

    } else {
        alert("Geolocation is not supported by this browser.");
    }
    return ;
};
function getStreetCityZip(position) {

    reverseurl = '//nominatim.openstreetmap.org/reverse?format=json&lat=' + position.coords.latitude + '&lon=' + position.coords.longitude ;

    accuracy = Math.round( position.coords.accuracy ) ;

    $('#id_geoLat').val( position.coords.latitude  );
    $('#id_geoLon').val( position.coords.longitude );

    $.getJSON( reverseurl , function( data ) {

        $("#id_locationname").val( data.display_name.split(',')[0] );
        $("#id_street").val( data.address.road );
        $("#id_streetnr").val(  );
        $("#id_zip").val( data.address.postcode );
        $("#id_city").val( data.address.city );
        $("#id_city").val( data.address.village );
        $("#id_country").val( data.address.country );
    });
};
function setmap() {

    var map = L.map('mapid').setView([ 0, 0 ], 2);

    L.tileLayer('//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors'
    }).addTo(map);

    var markers = [];
    var pointDist2TargetList = [];
    var pointLogList = [];
    var boundaries = [ ];
    var recipientIcon = L.icon({
        iconUrl: '//img.klml.de/devel/ptap/ptap_ziel__30.png',
        iconAnchor:   [15, 50],
        iconSize:     [30, 50],
    });
    var holderIcon = L.icon({
        iconUrl: '//img.klml.de/devel/ptap/ptap_start__30.png',
        iconAnchor:   [15, 50],
        iconSize:     [30, 50],
    });
    var logIcon = L.icon({
        iconUrl: '//img.klml.de/devel/ptap/ptap_start__10.png',
        iconAnchor:   [7, 25],
        iconSize:     [15, 25],
    });
    var hubbingIcon = L.icon({
        iconUrl: '//img.klml.de/devel/ptap/ptap_hubbing_trns__30.png',
        iconAnchor:   [15, 15],
        iconSize:     [30, 30],
    });

    $('.transport').each( function () {
        var pointDescription = $(this).html() ;

        var holderCoordinates       = $(this).find('.holder').find('.coords').text().split(',') ;
        var recipientCoordinates    = $(this).find('.recipient').find('.coords').text().split(',') ;

        var holderPoint     = new L.LatLng( holderCoordinates[0].trim() , holderCoordinates[1].trim() );
        var recipientPoint  = new L.LatLng( recipientCoordinates[0].trim(), recipientCoordinates[1].trim() );

        var holderMarker        = new L.marker( holderPoint, {icon: holderIcon }  ).addTo(map).bindPopup( pointDescription );
        var recipientMarker     = new L.marker( recipientPoint, {icon: holderIcon }  ).addTo(map).bindPopup( pointDescription );

        boundaries.push( holderMarker ) ;
        boundaries.push( recipientMarker ) ;

        var pointDist2Target = new L.Polyline( [holderPoint , recipientPoint ] , {
            color: '#77AE9A',
            weight: 3,
            opacity: 1,
            smoothFactor: 1
         }).addTo(map);

        // arrow on target
        var arrowHead = L.polylineDecorator(pointDist2Target, {
            patterns: [
                {offset: '100%', repeat: 0, symbol: L.Symbol.arrowHead({pixelSize: 25, polygon: false, headAngle: 40, pathOptions: {stroke: true }})}
            ]
        }).addTo(map);

        // draw logline
        $(this).find('#log').find('.coords').each( function () {
            var logCoordinates = $(this).text().split(',') ;
            var point = new L.LatLng( logCoordinates[0] , logCoordinates[1] );
            pointLogList.push( point )
        });

        var logline = new L.Polyline( pointLogList , {
            color: '#CF763A',
            weight: 3,
            opacity: 1,
            smoothFactor: 1
        });

        logline.addTo(map);

    });

    $.each(userLocationsusers, function(index, value) {
        marker = [ value['lat'] , value['lon'] ] ;

        newmarker = new L.marker( marker, { icon: hubbingIcon } ).addTo(map).bindPopup( index );
    });

    var boundariesgroup = L.featureGroup( boundaries ); // only on transports
    map.fitBounds( boundariesgroup.getBounds() , { padding: [20, 20] });

    if ( typeof geosearch != "undefined" ) {
          //~ TODO geosearch.wide faktor
        L.circle([ geosearch.lat , geosearch.lon ], {radius: geosearch.wide * 70000 , fillOpacity: 0.05 , color : "green" } ).addTo(map);
    };

};

function setqrcode() {
    urlwithoutsearch = window.location.origin + window.location.pathname ;

    var qrcode = new QRCode(document.getElementById("qrcodeurl"), {
        text: urlwithoutsearch ,
        width: 128,
        height: 128,
        colorDark : "#000000",
        colorLight : "#ffffff",
        correctLevel : QRCode.CorrectLevel.H
    });
};

function getlocal() {
    navigator.geolocation.getCurrentPosition(function(position) {
        link = '/?lat=' + position.coords.latitude + '&lon=' + position.coords.longitude + '&wide=1&zoomout=1' ;
        $('.getlocal').attr( 'href' , link );
    });
};

jQuery(document).ready(function() {

    $('#log').hide();
    $('.log h3').click( function() {
        $('#log').toggle();
    });

    if( typeof user != "undefined" ) {
        $('form.transport_None #id_holdername').val( user.user_name );
    };

    $( "input.users" ).autocomplete({
        source: '/carriers/?format=json',
        minLength: 0
    });

    $( "#setuserstate button" ).hide();
    $( "#setuserstate select" ).change(function() {
        this.form.submit();
    });

    $('#getStreetZipCity').click( function ( event ) {
        getLocation();
    });

    if (  $('.singletransport').length ) {
        setqrcode();
    };
    getlocal();
    setmap();

});
<commit_msg>recipient removed: marker and popup, no using arrow<commit_after>// geolocation

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition( getStreetCityZip );

    } else {
        alert("Geolocation is not supported by this browser.");
    }
    return ;
};
function getStreetCityZip(position) {

    reverseurl = '//nominatim.openstreetmap.org/reverse?format=json&lat=' + position.coords.latitude + '&lon=' + position.coords.longitude ;

    accuracy = Math.round( position.coords.accuracy ) ;

    $('#id_geoLat').val( position.coords.latitude  );
    $('#id_geoLon').val( position.coords.longitude );

    $.getJSON( reverseurl , function( data ) {

        $("#id_locationname").val( data.display_name.split(',')[0] );
        $("#id_street").val( data.address.road );
        $("#id_streetnr").val(  );
        $("#id_zip").val( data.address.postcode );
        $("#id_city").val( data.address.city );
        $("#id_city").val( data.address.village );
        $("#id_country").val( data.address.country );
    });
};
function setmap() {

    var map = L.map('mapid').setView([ 0, 0 ], 2);

    L.tileLayer('//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors'
    }).addTo(map);

    var markers = [];
    var pointDist2TargetList = [];
    var pointLogList = [];
    var boundaries = [ ];
    var recipientIcon = L.icon({
        iconUrl: '//img.klml.de/devel/ptap/ptap_ziel__30.png',
        iconAnchor:   [15, 50],
        iconSize:     [30, 50],
    });
    var holderIcon = L.icon({
        iconUrl: '//img.klml.de/devel/ptap/ptap_start__30.png',
        iconAnchor:   [15, 50],
        iconSize:     [30, 50],
    });
    var logIcon = L.icon({
        iconUrl: '//img.klml.de/devel/ptap/ptap_start__10.png',
        iconAnchor:   [7, 25],
        iconSize:     [15, 25],
    });
    var hubbingIcon = L.icon({
        iconUrl: '//img.klml.de/devel/ptap/ptap_hubbing_trns__30.png',
        iconAnchor:   [15, 15],
        iconSize:     [30, 30],
    });

    $('.transport').each( function () {
        var pointDescription = $(this).html() ;

        var holderCoordinates       = $(this).find('.holder').find('.coords').text().split(',') ;
        var recipientCoordinates    = $(this).find('.recipient').find('.coords').text().split(',') ;

        var holderPoint     = new L.LatLng( holderCoordinates[0].trim() , holderCoordinates[1].trim() );
        var recipientPoint  = new L.LatLng( recipientCoordinates[0].trim(), recipientCoordinates[1].trim() );

        var holderMarker        = new L.marker( holderPoint, {icon: holderIcon }  ).addTo(map).bindPopup( pointDescription );
        var recipientMarker     = new L.marker( recipientPoint ) ;

        boundaries.push( holderMarker ) ;
        boundaries.push( recipientMarker ) ;

        var pointDist2Target = new L.Polyline( [holderPoint , recipientPoint ] , {
            color: '#77AE9A',
            weight: 3,
            opacity: 1,
            smoothFactor: 1
         }).addTo(map);

        // arrow on target
        var arrowHead = L.polylineDecorator(pointDist2Target, {
            patterns: [
                {offset: '100%', repeat: 0, symbol: L.Symbol.arrowHead({pixelSize: 25, polygon: false, headAngle: 40, pathOptions: {stroke: true }})}
            ]
        }).addTo(map);

        // draw logline
        $(this).find('#log').find('.coords').each( function () {
            var logCoordinates = $(this).text().split(',') ;
            var point = new L.LatLng( logCoordinates[0] , logCoordinates[1] );
            pointLogList.push( point )
        });

        var logline = new L.Polyline( pointLogList , {
            color: '#CF763A',
            weight: 3,
            opacity: 1,
            smoothFactor: 1
        });

        logline.addTo(map);

    });

    $.each(userLocationsusers, function(index, value) {
        marker = [ value['lat'] , value['lon'] ] ;

        newmarker = new L.marker( marker, { icon: hubbingIcon } ).addTo(map).bindPopup( index );
    });

    var boundariesgroup = L.featureGroup( boundaries ); // only on transports
    map.fitBounds( boundariesgroup.getBounds() , { padding: [20, 20] });

    if ( typeof geosearch != "undefined" ) {
          //~ TODO geosearch.wide faktor
        L.circle([ geosearch.lat , geosearch.lon ], {radius: geosearch.wide * 70000 , fillOpacity: 0.05 , color : "green" } ).addTo(map);
    };

};

function setqrcode() {
    urlwithoutsearch = window.location.origin + window.location.pathname ;

    var qrcode = new QRCode(document.getElementById("qrcodeurl"), {
        text: urlwithoutsearch ,
        width: 128,
        height: 128,
        colorDark : "#000000",
        colorLight : "#ffffff",
        correctLevel : QRCode.CorrectLevel.H
    });
};

function getlocal() {
    navigator.geolocation.getCurrentPosition(function(position) {
        link = '/?lat=' + position.coords.latitude + '&lon=' + position.coords.longitude + '&wide=1&zoomout=1' ;
        $('.getlocal').attr( 'href' , link );
    });
};

jQuery(document).ready(function() {

    $('#log').hide();
    $('.log h3').click( function() {
        $('#log').toggle();
    });

    if( typeof user != "undefined" ) {
        $('form.transport_None #id_holdername').val( user.user_name );
    };

    $( "input.users" ).autocomplete({
        source: '/carriers/?format=json',
        minLength: 0
    });

    $( "#setuserstate button" ).hide();
    $( "#setuserstate select" ).change(function() {
        this.form.submit();
    });

    $('#getStreetZipCity').click( function ( event ) {
        getLocation();
    });

    if (  $('.singletransport').length ) {
        setqrcode();
    };
    getlocal();
    setmap();

});
<|endoftext|>


<commit_before>buster.testCase("parseHTML test suite", {

    "test parse text": function() {
        var html = 'some text';
        var frag = abeja.parseHTML(html);
        assert.same(html, frag.firstChild.nodeValue);
    },

    "test parse paragraph": function() {
        var innerHTML = 'a paragraph';
        var html = '
'+innerHTML+'
';
        var frag = abeja.parseHTML(html);
        assert.same('P',  frag.firstChild.tagName);
        assert.same('a paragraph', frag.firstChild.innerHTML);
    },

});
<commit_msg>stray comma<commit_after>buster.testCase("parseHTML test suite", {

    "test parse text": function() {
        var html = 'some text';
        var frag = abeja.parseHTML(html);
        assert.same(html, frag.firstChild.nodeValue);
    },

    "test parse paragraph": function() {
        var innerHTML = 'a paragraph';
        var html = '
'+innerHTML+'
';
        var frag = abeja.parseHTML(html);
        assert.same('P',  frag.firstChild.tagName);
        assert.same('a paragraph', frag.firstChild.innerHTML);
    }

});
<|endoftext|>


<commit_before>Ext.application({

        launch: function(){
            Ext.create('Ext.data.Store', {
                    storeId: 'tutorials',
                    fields:[ 'S.No','Title', 'Link'],
                    data: [
                        { no:'1', name: 'What is Ext.JS?', link: ''}
                    ]
            });

                Ext.create('Ext.grid.Panel', {
                    title: 'Extjs Tutorials',
                    store: Ext.data.StoreManager.lookup('tutorials'),
                    columns: [
                        { text: 'S.No', dataIndex: 'no' },
                        { text: 'Name', dataIndex: 'name' },
                        { text: 'Link', dataIndex: 'link' },
                    ],
                    height: 200,
                    width: 400,
                    renderTo: Ext.getBody()
                });

        }
});

<commit_msg>Update app.js<commit_after>Ext.application({

        launch: function(){
            Ext.create('Ext.data.Store', {
                    storeId: 'tutorials',
                    fields:[ 'S.No','Title', 'Link'],
                    data: [
                        { no:'1', name: 'What is Ext.JS?', link: ''}
                    ]
            });

                Ext.create('Ext.grid.Panel', {
                    title: 'Extjs Tutorials',
                    store: Ext.data.StoreManager.lookup('tutorials'),
                    columns: [
                        { text: 'S.No', dataIndex: 'no' },
                        { text: 'Name', dataIndex: 'name' },
                        { text: 'Link', dataIndex: 'link' },
                    ],
                    height: 200,
                    width: 400,
                    renderTo: Ext.getBody()
                });
            alert();
        }
});

<|endoftext|>


<commit_before>var express = require('express');
var pg = require('pg');
var db_info = require('./db_info.js')
var app = express();
var pool = new pg.Pool(db_info.config);

app.get('/', function (req, res) {
  res.send('Hello World!');
});

//Checkout / Check in items
//------------------------------------------------------------------------------
app.get('/transaction/:id/:person/:qty', function(req, res){
  //first query the database
  //then return the results to the user

  pool.connect(function(err, client, done) {
    if(err) {
      return console.error('error fetching client from pool', err);
    }
    client.query('INSERT INTO transactions(item_id, person, qty_changed) VALUES ($1, $2, $3)', [req.params.id, req.params.person, req.params.qty], function(err, result) {
      //call `done()` to release the client back to the pool
      done();

      if(err) {
        res.send(err);
        return console.error('error running query', err);
      } else {
        res.send('Transaction Completed Successfully');
      }
      console.log(req.params.id);
      console.log(req.params.qty);
      console.log(req.params.person);

      //output: 1
    });
  });
});

app.get('/view', function(req, res){
  //first query the database
  //then return the results to the user

      pool.connect(function(err, client, done) {
        if(err) {
            return console.error('error fetching client from pool', err);
        }
        client.query('SELECT item_name AS name, description, quantity FROM items', [], function(err, result) {
            //call `done()` to release the client back to the pool
            done();

            if(err) {
                return console.error('error running query', err);
            }

            //output: 1
            res.send(result.rows);
        });
    });
});

app.listen(3000, function () {
  console.log('Listening on port 3000');
});
<commit_msg>Add checkin and checkout API functions<commit_after>var express = require('express');
var pg = require('pg');
var db_info = require('./db_info.js')
var app = express();
var pool = new pg.Pool(db_info.config);

app.get('/', function (req, res) {
  res.send('Hello World!');
});

//Checkout items api route
//------------------------------------------------------------------------------
app.get('/checkout/:id/:person/:qty', function(req, res) {

    transaction(req.params.id, req.params.person, -req.params.qty, function(err, tranRes) {
        if (err) {
            res.status(500);
            res.send('Database Error');
        } else {
            res.status(200);
            res.send(tranRes);
        }
    });
});

//Checkin items api route
//------------------------------------------------------------------------------
app.get('/checkin/:id/:person/:qty', function(req, res) {

    transaction(req.params.id, req.params.person, req.params.qty, function(err, tranRes) {
        if (err) {
            res.status(500);
            res.send('Database Error');
        } else {
            res.status(200);
            res.send(tranRes);
        }
    });
});

var transaction = function(id, person, qty, retFunc) {

    pool.connect(function(err, client, done) {
        if(err) {
            return console.error('error fetching client from pool', err);
        }

         client.query('INSERT INTO transactions(item_id, person, qty_changed) VALUES ($1, $2, $3)', [id, person, qty], function(err, result) {
             //call `done()` to release the client back to the pool
             done();

             if(err) {
                 console.error('error running query', err);
                 retFunc(err, null);
             } else {
                 retFunc(null, 'Transaction Completed Successfully');
             }
        });
    });
}

app.get('/view', function(req, res){
  //first query the database
  //then return the results to the user

      pool.connect(function(err, client, done) {
        if(err) {
            return console.error('error fetching client from pool', err);
        }
        client.query('SELECT item_name AS name, description, quantity FROM items', [], function(err, result) {
            //call `done()` to release the client back to the pool
            done();

            if(err) {
                return console.error('error running query', err);
            }

            //output: 1
            res.send(result.rows);
        });
    });
});

app.listen(3000, function () {
  console.log('Listening on port 3000');
});
<|endoftext|>


<commit_before>const _ = require('lodash')
const semver = require('semver')
const Log = require('gk-log')

const dbs = require('../lib/dbs')
const updatedAt = require('../lib/updated-at')
const statsd = require('../lib/statsd')
const getConfig = require('../lib/get-config')
const {
  seperateNormalAndMonorepos,
  getJobsPerGroup,
  filterAndSortPackages,
  getSatisfyingVersions,
  getOldVersionResolved
} = require('../utils/utils')
const {
  isPartOfMonorepo,
  hasAllMonorepoUdates,
  getMonorepoGroup,
  updateMonorepoReleaseInfo,
  deleteMonorepoReleaseInfo,
  getMonorepoGroupNameForPackage
} = require('../lib/monorepo')

module.exports = async function (
  { dependency, distTags, versions, installation, force }
) {
  const { installations, repositories, npm } = await dbs()
  const logs = dbs.getLogsDb()
  const log = Log({logsDb: logs, accountId: null, repoSlug: null, context: 'registry-change'})
  log.info(`started registry-change for dependency ${dependency}`, {dependency, versions})

  const isFromHook = _.isString(installation)
  let npmDoc = {
    _id: dependency,
    distTags,
    versions
  }

  // use prefix for packageFilesForUpdatedDependency sent via webhook
  if (isFromHook) npmDoc._id = `${installation}:${npmDoc._id}`

  try {
    var npmDbDoc = await npm.get(npmDoc._id)
  } catch (err) {
    if (err.status !== 404) throw err
    log.warn(`Warning: failed to load npmDoc for ${dependency} (Is probably new).`)
    npmDbDoc = {}
  }

  const oldDistTags = npmDbDoc.distTags || {}
  let distTag

  if (force) {
    distTag = 'latest'
  } else {
    // which distTag has changed
    distTag = _.findKey(distTags, (version, tag) => {
      const oldVersion = oldDistTags[tag]
      if (!oldVersion) {
        log.info(`exited: nothing to update, is first release of ${dependency}`)
        return true
      }
      return semver.lt(oldVersion, version)
    })
  }

  if (!distTag) {
    log.info(`exited: ${dependency} has no distTag`)
    return
  }
  await npm.put(updatedAt(Object.assign(npmDbDoc, npmDoc)))

  // currently we only handle latest versions
  // so we can heavily optimise by exiting here
  // we want to handle different distTags in the future
  if (distTag !== 'latest') {
    log.info(`exited: ${dependency} distTag is ${distTag} (not latest)`)
    return
  }

  const version = distTags[distTag]
  let dependencies = [ dependency ]

  // check if dependency update is part of a monorepo release
  if (await isPartOfMonorepo(dependency)) {
    // We only want to open a PR if either:
    // 1. We have all of the modules that belong to the release (have the same version number)
    // 2. The release is forced by the monorepo-supervisor. This means the release is still incomplete
    //    after n minutes, but we want to open the PR anyway
    if (!await hasAllMonorepoUdates(dependency, version) && !force) {
      log.info('exited: is not last in list of monorepo packages')
      // create/update npm/monorepo:dependency-version
      await updateMonorepoReleaseInfo(dependency, distTags, distTag, versions)
      return // do nothing, one of the next registry-change jobs is going to handle the rest
    }
    // do the update now
    await deleteMonorepoReleaseInfo(dependency, version)

    // set up keys so we can query for all packages with a dependency on any of the packages
    // in our monorepo group
    dependencies = await getMonorepoGroup(await getMonorepoGroupNameForPackage(dependency)) || dependencies
  }

  /*
  Update: 'by_dependency' handles multiple package.json files, but not in the same result.

  You get one result per matching dependency per depencyType per file in `packageFilesForUpdatedDependency`. The `value`
  object for each result (used below, in `filteredSortedPackages` for example), looks like:

  "value": {
    "fullName": "aveferrum/angular-material-demo",
    "accountId": "462667",
    "filename": "frontend/package.json", // <- yay, works
    "type": "dependencies",
    "oldVersion": "^4.2.4"
  }

  Then in a separate result, you’d get

  "value": {
    "fullName": "aveferrum/angular-material-demo",
    "accountId": "462667",
    "filename": "backend/package.json",
    "type": "dependencies",
    "oldVersion": "^4.2.4"
  }
  */
  // packageFilesForUpdatedDependency are a list of all repoDocs that have that dependency (should rename that)
  const packageFilesForUpdatedDependency = (await repositories.query('by_dependency', {
    keys: dependencies
  })).rows

  if (!packageFilesForUpdatedDependency.length) {
    log.info(`exited: no repoDocs found that depend on ${dependency}`)
    return
  }
  log.info(`found ${packageFilesForUpdatedDependency.length} repoDocs that use ${dependency}`)

  if (packageFilesForUpdatedDependency.length > 100) statsd.event('popular_package')
  // check if package has a greenkeeper.json / more then 1 package json or package.json is in subdirectory
  // continue with the rest but send all otheres to a 'new' version branch job

  let jobs = []
  const seperatedResults = seperateNormalAndMonorepos(packageFilesForUpdatedDependency)

  const withOnlyRootPackageJSON = _.flatten(seperatedResults[1])
  const withMultiplePackageJSON = seperatedResults[0]

  const accounts = _.keyBy(
    _.map(
      (await installations.allDocs({
        keys: _.compact(_.map(_.flattenDeep(seperatedResults), 'value.accountId')),
        include_docs: true
      })).rows,
      'doc'
    ),
    '_id'
  )

  // ******** Monorepos begin
  // get config
  const keysToFindMonorepoDocs = _.compact(_.map(withMultiplePackageJSON, (group) => group[0].value.fullName))

  if (keysToFindMonorepoDocs.length) {
    const monorepoDocs = (await repositories.query('by_full_name', {
      keys: keysToFindMonorepoDocs,
      include_docs: true
    })).rows

    _.forEach(withMultiplePackageJSON, monorepo => {
      const account = accounts[monorepo[0].value.accountId]
      if (isFromHook && String(account.installation) !== installation) return {}

      const plan = account.plan
      const repoDoc = monorepoDocs.find(doc => doc.key === monorepo[0].value.fullName)
      if (!repoDoc) return
      const config = getConfig(repoDoc.doc)
      jobs = jobs.concat(getJobsPerGroup({
        config,
        monorepo,
        distTags,
        distTag,
        dependency,
        versions,
        account,
        repositoryId: repoDoc.id,
        plan,
        isFromHook,
        log}))
    })
  }
  // ******** Monorepos end

  // Prioritize `dependencies` over all other dependency types
  // https://github.com/greenkeeperio/greenkeeper/issues/409

  const filteredSortedPackages = filterAndSortPackages(withOnlyRootPackageJSON)

  jobs = [...jobs, ...(_.sortedUniqBy(filteredSortedPackages, pkg => pkg.value.fullName)
    .map(pkg => {
      const account = accounts[pkg.value.accountId]
      const plan = account.plan

      const satisfyingVersions = getSatisfyingVersions(versions, pkg)
      const oldVersionResolved = getOldVersionResolved(satisfyingVersions, distTags, distTag)

      if (isFromHook && String(account.installation) !== installation) return {}
      if (semver.prerelease(version) && !semver.prerelease(pkg.value.oldVersion)) {
        log.info(`exited: ${dependency} ${version} is a prerelease on latest and user does not use prereleases`)
        return
      }

      return {
        data: Object.assign(
          {
            name: 'create-version-branch',
            dependency,
            version,
            versions,
            oldVersionResolved,
            repositoryId: pkg.id,
            installation: account.installation,
            plan,
            isFromHook
          },
          pkg.value
        ),
        plan
      }
    }))
  ]
  log.success(`${jobs.length} registry-change jobs for dependency ${dependency} created`)
  return jobs
}
<commit_msg>chore(registry-change): fewer logs<commit_after>const _ = require('lodash')
const semver = require('semver')
const Log = require('gk-log')

const dbs = require('../lib/dbs')
const updatedAt = require('../lib/updated-at')
const statsd = require('../lib/statsd')
const getConfig = require('../lib/get-config')
const {
  seperateNormalAndMonorepos,
  getJobsPerGroup,
  filterAndSortPackages,
  getSatisfyingVersions,
  getOldVersionResolved
} = require('../utils/utils')
const {
  isPartOfMonorepo,
  hasAllMonorepoUdates,
  getMonorepoGroup,
  updateMonorepoReleaseInfo,
  deleteMonorepoReleaseInfo,
  getMonorepoGroupNameForPackage
} = require('../lib/monorepo')

module.exports = async function (
  { dependency, distTags, versions, installation, force }
) {
  const { installations, repositories, npm } = await dbs()
  const logs = dbs.getLogsDb()
  const log = Log({logsDb: logs, accountId: null, repoSlug: null, context: 'registry-change'})
  // log.info(`started registry-change for dependency ${dependency}`, {dependency, versions})

  const isFromHook = _.isString(installation)
  let npmDoc = {
    _id: dependency,
    distTags,
    versions
  }

  // use prefix for packageFilesForUpdatedDependency sent via webhook
  if (isFromHook) npmDoc._id = `${installation}:${npmDoc._id}`

  try {
    var npmDbDoc = await npm.get(npmDoc._id)
  } catch (err) {
    if (err.status !== 404) throw err
    // log.warn(`Warning: failed to load npmDoc for ${dependency} (Is probably new).`)
    npmDbDoc = {}
  }

  const oldDistTags = npmDbDoc.distTags || {}
  let distTag

  if (force) {
    distTag = 'latest'
  } else {
    // which distTag has changed
    distTag = _.findKey(distTags, (version, tag) => {
      const oldVersion = oldDistTags[tag]
      if (!oldVersion) {
        // log.info(`exited: nothing to update, is first release of ${dependency}`)
        return true
      }
      return semver.lt(oldVersion, version)
    })
  }

  if (!distTag) {
    // log.info(`exited: ${dependency} has no distTag`)
    return
  }
  await npm.put(updatedAt(Object.assign(npmDbDoc, npmDoc)))

  // currently we only handle latest versions
  // so we can heavily optimise by exiting here
  // we want to handle different distTags in the future
  if (distTag !== 'latest') {
    // log.info(`exited: ${dependency} distTag is ${distTag} (not latest)`)
    return
  }

  const version = distTags[distTag]
  let dependencies = [ dependency ]

  // check if dependency update is part of a monorepo release
  if (await isPartOfMonorepo(dependency)) {
    // We only want to open a PR if either:
    // 1. We have all of the modules that belong to the release (have the same version number)
    // 2. The release is forced by the monorepo-supervisor. This means the release is still incomplete
    //    after n minutes, but we want to open the PR anyway
    if (!await hasAllMonorepoUdates(dependency, version) && !force) {
      log.info('exited: is not last in list of monorepo packages')
      // create/update npm/monorepo:dependency-version
      await updateMonorepoReleaseInfo(dependency, distTags, distTag, versions)
      return // do nothing, one of the next registry-change jobs is going to handle the rest
    }
    // do the update now
    await deleteMonorepoReleaseInfo(dependency, version)

    // set up keys so we can query for all packages with a dependency on any of the packages
    // in our monorepo group
    dependencies = await getMonorepoGroup(await getMonorepoGroupNameForPackage(dependency)) || dependencies
  }

  /*
  Update: 'by_dependency' handles multiple package.json files, but not in the same result.

  You get one result per matching dependency per depencyType per file in `packageFilesForUpdatedDependency`. The `value`
  object for each result (used below, in `filteredSortedPackages` for example), looks like:

  "value": {
    "fullName": "aveferrum/angular-material-demo",
    "accountId": "462667",
    "filename": "frontend/package.json", // <- yay, works
    "type": "dependencies",
    "oldVersion": "^4.2.4"
  }

  Then in a separate result, you’d get

  "value": {
    "fullName": "aveferrum/angular-material-demo",
    "accountId": "462667",
    "filename": "backend/package.json",
    "type": "dependencies",
    "oldVersion": "^4.2.4"
  }
  */
  // packageFilesForUpdatedDependency are a list of all repoDocs that have that dependency (should rename that)
  const packageFilesForUpdatedDependency = (await repositories.query('by_dependency', {
    keys: dependencies
  })).rows

  if (!packageFilesForUpdatedDependency.length) {
    // log.info(`exited: no repoDocs found that depend on ${dependency}`)
    return
  }
  log.info(`found ${packageFilesForUpdatedDependency.length} repoDocs that use ${dependency}`)

  if (packageFilesForUpdatedDependency.length > 100) statsd.event('popular_package')
  // check if package has a greenkeeper.json / more then 1 package json or package.json is in subdirectory
  // continue with the rest but send all otheres to a 'new' version branch job

  let jobs = []
  const seperatedResults = seperateNormalAndMonorepos(packageFilesForUpdatedDependency)

  const withOnlyRootPackageJSON = _.flatten(seperatedResults[1])
  const withMultiplePackageJSON = seperatedResults[0]

  const accounts = _.keyBy(
    _.map(
      (await installations.allDocs({
        keys: _.compact(_.map(_.flattenDeep(seperatedResults), 'value.accountId')),
        include_docs: true
      })).rows,
      'doc'
    ),
    '_id'
  )

  // ******** Monorepos begin
  // get config
  const keysToFindMonorepoDocs = _.compact(_.map(withMultiplePackageJSON, (group) => group[0].value.fullName))

  if (keysToFindMonorepoDocs.length) {
    const monorepoDocs = (await repositories.query('by_full_name', {
      keys: keysToFindMonorepoDocs,
      include_docs: true
    })).rows

    _.forEach(withMultiplePackageJSON, monorepo => {
      const account = accounts[monorepo[0].value.accountId]
      if (isFromHook && String(account.installation) !== installation) return {}

      const plan = account.plan
      const repoDoc = monorepoDocs.find(doc => doc.key === monorepo[0].value.fullName)
      if (!repoDoc) return
      const config = getConfig(repoDoc.doc)
      jobs = jobs.concat(getJobsPerGroup({
        config,
        monorepo,
        distTags,
        distTag,
        dependency,
        versions,
        account,
        repositoryId: repoDoc.id,
        plan,
        isFromHook,
        log}))
    })
  }
  // ******** Monorepos end

  // Prioritize `dependencies` over all other dependency types
  // https://github.com/greenkeeperio/greenkeeper/issues/409

  const filteredSortedPackages = filterAndSortPackages(withOnlyRootPackageJSON)

  jobs = [...jobs, ...(_.sortedUniqBy(filteredSortedPackages, pkg => pkg.value.fullName)
    .map(pkg => {
      const account = accounts[pkg.value.accountId]
      const plan = account.plan

      const satisfyingVersions = getSatisfyingVersions(versions, pkg)
      const oldVersionResolved = getOldVersionResolved(satisfyingVersions, distTags, distTag)

      if (isFromHook && String(account.installation) !== installation) return {}
      if (semver.prerelease(version) && !semver.prerelease(pkg.value.oldVersion)) {
        log.info(`exited: ${dependency} ${version} is a prerelease on latest and user does not use prereleases`)
        return
      }

      return {
        data: Object.assign(
          {
            name: 'create-version-branch',
            dependency,
            version,
            versions,
            oldVersionResolved,
            repositoryId: pkg.id,
            installation: account.installation,
            plan,
            isFromHook
          },
          pkg.value
        ),
        plan
      }
    }))
  ]
  log.success(`${jobs.length} registry-change jobs for dependency ${dependency} created`)
  return jobs
}
<|endoftext|>


<commit_before>(function($){

  $.fn.extend({
    datetimeparse: function(options) {

      var defaults = {
        //Option for assuming future set to true or false...
        hours: 0,
        minutes: 0,
        seconds: 0,
        milliseconds: 0
      }

      var options =  $.extend(defaults, options);
      var parsedDate;
      this.each(function() {
        var inputText = $.trim($(this).val()); //no harm...
        console.log("Got input: "+inputText);

        var inputArray = inputText.split(' ');
        //inputArray[0] can be... DATE, TIME, DOTW, "next"
        while (inputArray.length > 0){
          var parsed = parseInput(inputArray.shift, inputArray);
          if (parsed != null) {
            parsedDate = parsed;
          }
        }
      });
      if (parsedDate == undefined) {
        return "Something went wrong!";
      }
      return parsedDate;

      //Helper functions

      function parseInput(input,inputArray,date) {
        //Where the magic happens...
        if (date == undefined) {date = new Date();}
        if (isDate(input)) {
          date = new Date(inputArray[0]);
          date = defaultTime(parsedDate);
        }
        else if (isTime(input) && isPeriod(inputArray[0])) {
          date.setHours(getInputHour(input,inputArray[0]));
          date.setMinutes(getInputMinute(input));
        }
        return date;
      }
      function getInputMinute(time) {
        timeArray = time.split(':');
        if (timeArray.length < 2) {return 0;}
        return timeArray.pop();
      }
      function getInputHour(time,period) {
        if (period.indexOf('a') != -1) {
          //am... so make sure hours < 11 (11 == 12 PM in setHours)
          timeArray = time.split(':');
          var hour = timeArray.shift();
          if (hour > 11) {
            return hour - 12;
          }
          return hour;
        }
      }
      function defaultTime(oldDate) {
        oldDate = typeof(oldDate) != 'undefined' ? oldDate : new Date();
        oldDate.setHours(options.hours);
        oldDate.setMinutes(options.minutes);
        oldDate.setSeconds(options.seconds);
        oldDate.setMilliseconds(options.milliseconds);
        return oldDate;
      }
      function on(time, date) {
        //on is called when something like this is found: 7 PM on Friday
        return;
      }
      function at(date, time) {
        //at is called when something like this is found: Friday at 7 PM
        return;
      }
      function isDate(date) {
        //second or third character needs to be a slash.
        date = $.trim(date);
        if (date.substr(-1) == '/') {return false;} //If last char is a slash it is not complete yet...
        if (date.length <= 5) {
          //No year specified, so only one slash...
          return ( date.charAt(1) == '/' || date.charAt(2) == '/' );
        }
        else {
          //If we're here... Date must include year, so check for two slashes.
          //Year is either two or four chars...
          var year = date.split('/').pop();
          if (year.length != 2 && year.length != 4) {return false;}

          var firstSlash = (date.charAt(1) == '/' || date.charAt(2) == '/');
          var secondSlash = (date.charAt(3) == '/' || date.charAt(4) == '/' || date.charAt(5) == '/');
          return (firstSlash && secondSlash);
        }
      }
      function isPeriod(period) {
        var retval = false;
        switch(period) {
          case "a": case "am":
            retval = true;
            break;
          case "p": case "pm":
            retval = true;
            break;
        }
        return retval;
      }
      function isTime(time) {
        //TIME = [H, H:MM, HH:MM]
        timeComponents = time.split(':');
        if (time.length < 2 && timeComponents.length == 1) {return true;}
        timeArray = time.split(':');
        if (timeArray.length == 2) {return true;}
        return false;

      }
      function dayOfTheWeek(dotw) {
        switch(dotw.toLowerCase()) {
          case "mon": case "monday":
            var day = 0;
            break;
          case "tue": case "tues": case "tuesday":
            var day = 1;
            break;
          case "wed": case "wednesday":
            var day = 2;
            break;
          case "thur": case "thurs": case "thursday":
            var day = 3;
            break;
          case "fri": case "friday":
            var day = 4;
            break;
          case "sat": case "saturday":
            var day = 5;
            break;
          case "sun": case "sunday":
            var day = 6;
            break;
        }
        if (day != undefined)
        {
          return day;
        }
        return false;
      }
      function dateInFuture(date) {
        var now = new Date();
        if (date > now) {return true;}
        return false;
      }
    }

  });

})(jQuery);<commit_msg>Will be too difficult to allow past days of the week and such...<commit_after>(function($){

  $.fn.extend({
    datetimeparse: function(options) {

      var defaults = {
        hours: 0,
        minutes: 0,
        seconds: 0,
        milliseconds: 0
      }

      var options =  $.extend(defaults, options);
      var parsedDate;
      this.each(function() {
        var inputText = $.trim($(this).val()); //no harm...
        console.log("Got input: "+inputText);

        var inputArray = inputText.split(' ');
        //inputArray[0] can be... DATE, TIME, DOTW, "next"
        while (inputArray.length > 0){
          var parsed = parseInput(inputArray.shift, inputArray);
          if (parsed != null) {
            parsedDate = parsed;
          }
        }
      });
      if (parsedDate == undefined) {
        return "Something went wrong!";
      }
      return parsedDate;

      //Helper functions

      function parseInput(input,inputArray,date) {
        //Where the magic happens...
        if (date == undefined) {date = new Date();}
        if (isDate(input)) {
          date = new Date(inputArray[0]);
          date = defaultTime(parsedDate);
        }
        else if (isTime(input) && isPeriod(inputArray[0])) {
          date.setHours(getInputHour(input,inputArray[0]));
          date.setMinutes(getInputMinute(input));
        }
        return date;
      }
      function getInputMinute(time) {
        timeArray = time.split(':');
        if (timeArray.length < 2) {return 0;}
        return timeArray.pop();
      }
      function getInputHour(time,period) {
        if (period.indexOf('a') != -1) {
          //am... so make sure hours < 11 (11 == 12 PM in setHours)
          timeArray = time.split(':');
          var hour = timeArray.shift();
          if (hour > 11) {
            return hour - 12;
          }
          return hour;
        }
      }
      function defaultTime(oldDate) {
        oldDate = typeof(oldDate) != 'undefined' ? oldDate : new Date();
        oldDate.setHours(options.hours);
        oldDate.setMinutes(options.minutes);
        oldDate.setSeconds(options.seconds);
        oldDate.setMilliseconds(options.milliseconds);
        return oldDate;
      }
      function on(time, date) {
        //on is called when something like this is found: 7 PM on Friday
        return;
      }
      function at(date, time) {
        //at is called when something like this is found: Friday at 7 PM
        return;
      }
      function isDate(date) {
        //second or third character needs to be a slash.
        date = $.trim(date);
        if (date.substr(-1) == '/') {return false;} //If last char is a slash it is not complete yet...
        if (date.length <= 5) {
          //No year specified, so only one slash...
          return ( date.charAt(1) == '/' || date.charAt(2) == '/' );
        }
        else {
          //If we're here... Date must include year, so check for two slashes.
          //Year is either two or four chars...
          var year = date.split('/').pop();
          if (year.length != 2 && year.length != 4) {return false;}

          var firstSlash = (date.charAt(1) == '/' || date.charAt(2) == '/');
          var secondSlash = (date.charAt(3) == '/' || date.charAt(4) == '/' || date.charAt(5) == '/');
          return (firstSlash && secondSlash);
        }
      }
      function isPeriod(period) {
        var retval = false;
        switch(period) {
          case "a": case "am":
            retval = true;
            break;
          case "p": case "pm":
            retval = true;
            break;
        }
        return retval;
      }
      function isTime(time) {
        //TIME = [H, H:MM, HH:MM]
        timeComponents = time.split(':');
        if (time.length < 2 && timeComponents.length == 1) {return true;}
        timeArray = time.split(':');
        if (timeArray.length == 2) {return true;}
        return false;

      }
      function dayOfTheWeek(dotw) {
        switch(dotw.toLowerCase()) {
          case "mon": case "monday":
            var day = 0;
            break;
          case "tue": case "tues": case "tuesday":
            var day = 1;
            break;
          case "wed": case "wednesday":
            var day = 2;
            break;
          case "thur": case "thurs": case "thursday":
            var day = 3;
            break;
          case "fri": case "friday":
            var day = 4;
            break;
          case "sat": case "saturday":
            var day = 5;
            break;
          case "sun": case "sunday":
            var day = 6;
            break;
        }
        if (day != undefined)
        {
          return day;
        }
        return false;
      }
      function dateInFuture(date) {
        var now = new Date();
        if (date > now) {return true;}
        return false;
      }
    }

  });

})(jQuery);<|endoftext|>


<commit_before>/**
 * jQuery scroll-events
 * https://github.com/gomo/scroll-events
 *
 * Copyright (c) 2015 Masamoto Miyata
 * Licensed under the MIT.
 */

;(function($){
    "use strict";

    $.fn.extend({
        observeScrollEvents: function(options){
            //オプションデフォルト値
            options = $.extend({
                stopObserveInterval: 100,  //ストップイベント監視用タイマーのインターバル（ms）
                warpAllowance: 10,         //縦方向のスタートイベントの遊び
                weftAllowance: 10          //横方向のスタートイベントの遊び
            }, options);

            //監視用変数初期化
            this.each(function(){
                $(this).data('scrollEvents', {});
            });

            this.scroll(function(e){
                var elem = $(this);
                var data = elem.data('scrollEvents');
                clearTimeout(data.timer);

                //縦方向のスタート位置を記憶
                if(data.topPos === undefined){
                    data.topPos = elem.scrollTop();
                }

                //横方向のスタート位置を記憶
                if(data.leftPos === undefined){
                    data.leftPos = elem.scrollLeft();
                }

                //縦方向のスタートイベント発火
                if(Math.abs(data.topPos - elem.scrollTop()) > options.warpAllowance && !data.warpStarted){
                    data.warpStarted = true;
                    elem.trigger('warp-scroll-start', {top: elem.scrollTop(), left: elem.scrollLeft()});
                }

                //横方向のスタートイベント発火
                if(Math.abs(data.leftPos - elem.scrollLeft()) > options.weftAllowance && !data.weftStarted){
                    data.weftStarted = true;
                    elem.trigger('weft-scroll-start', {top: elem.scrollTop(), left: elem.scrollLeft()});
                }

                //ストップイベント監視タイマー
                data.timer = setTimeout(function() {
                    if(data.warpStarted || data.weftStarted){
                        elem.trigger('scroll-stop', {top: elem.scrollTop(), left: elem.scrollLeft()});
                    }

                    //監視用変数クリア
                    elem.data('scrollEvents', {});
                }, options.stopObserveInterval)
            });
        }
    });
})(jQuery);<commit_msg>デフォルト値を調整。<commit_after>/**
 * jQuery scroll-events
 * https://github.com/gomo/scroll-events
 *
 * Copyright (c) 2015 Masamoto Miyata
 * Licensed under the MIT.
 */

;(function($){
    "use strict";

    $.fn.extend({
        observeScrollEvents: function(options){
            //オプションデフォルト値
            options = $.extend({
                stopObserveInterval: 60,   //ストップイベント監視用タイマーのインターバル（ms）
                warpAllowance: 10,         //縦方向のスタートイベントの遊び
                weftAllowance: 10          //横方向のスタートイベントの遊び
            }, options);

            //監視用変数初期化
            this.each(function(){
                $(this).data('scrollEvents', {});
            });

            this.scroll(function(e){
                var elem = $(this);
                var data = elem.data('scrollEvents');
                clearTimeout(data.timer);

                //縦方向のスタート位置を記憶
                if(data.topPos === undefined){
                    data.topPos = elem.scrollTop();
                }

                //横方向のスタート位置を記憶
                if(data.leftPos === undefined){
                    data.leftPos = elem.scrollLeft();
                }

                //縦方向のスタートイベント発火
                if(Math.abs(data.topPos - elem.scrollTop()) > options.warpAllowance && !data.warpStarted){
                    data.warpStarted = true;
                    elem.trigger('warp-scroll-start', {top: elem.scrollTop(), left: elem.scrollLeft()});
                }

                //横方向のスタートイベント発火
                if(Math.abs(data.leftPos - elem.scrollLeft()) > options.weftAllowance && !data.weftStarted){
                    data.weftStarted = true;
                    elem.trigger('weft-scroll-start', {top: elem.scrollTop(), left: elem.scrollLeft()});
                }

                //ストップイベント監視タイマー
                data.timer = setTimeout(function() {
                    if(data.warpStarted || data.weftStarted){
                        elem.trigger('scroll-stop', {top: elem.scrollTop(), left: elem.scrollLeft()});
                    }

                    //監視用変数クリア
                    elem.data('scrollEvents', {});
                }, options.stopObserveInterval)
            });
        }
    });
})(jQuery);<|endoftext|>


<commit_before>/*
 * waitForImages 1.1.1
 * -----------------
 * Provides a callback when all images have loaded in your given selector.
 * http://www.alexanderdickson.com/
 *
 *
 * Copyright (c) 2011 Alex Dickson
 * Licensed under the MIT licenses.
 * See website for more info.
 *
 */

;(function($) {
    $.fn.waitForImages = function(finishedCallback, eachCallback) {

        eachCallback = eachCallback || function() {};

        if ( ! $.isFunction(finishedCallback) ||  ! $.isFunction(eachCallback)) {
            throw {
                name: 'invalid_callback',
                message: 'An invalid callback was supplied.'
            };
        };

        var objs = $(this),
            allImgs = objs.find('img'),
            allImgsLength = allImgs.length,
            allImgsLoaded = 0;

        if (allImgsLength == 0) {
            finishedCallback.call(this);
        };

        return objs.each(function() {
            var obj = $(this),
                imgs = obj.find('img');

            if (imgs.length == 0) {
                return true;
            };

            imgs.each(function() {
                var image = this;
                image.onload = function() {
                    allImgsLoaded++;
                    eachCallback.call(image, allImgsLoaded, allImgsLength);
                    if (allImgsLoaded == allImgsLength) {
                        finishedCallback.call(obj[0]);
                        return false;
                    };
                };
            });
        });
    };
})(jQuery);<commit_msg>IE compatibility<commit_after>/*
 * waitForImages 1.1.2
 * -----------------
 * Provides a callback when all images have loaded in your given selector.
 * http://www.alexanderdickson.com/
 *
 *
 * Copyright (c) 2011 Alex Dickson
 * Licensed under the MIT licenses.
 * See website for more info.
 *
 */

;(function($) {
    $.fn.waitForImages = function(finishedCallback, eachCallback) {

        eachCallback = eachCallback || function() {};

        if ( ! $.isFunction(finishedCallback) ||  ! $.isFunction(eachCallback)) {
            throw {
                name: 'invalid_callback',
                message: 'An invalid callback was supplied.'
            };
        };

        var objs = $(this),
            allImgs = objs.find('img'),
            allImgsLength = allImgs.length,
            allImgsLoaded = 0;

        if (allImgsLength == 0) {
            finishedCallback.call(this);
        };

        return objs.each(function() {
            var obj = $(this),
                imgs = obj.find('img');

            if (imgs.length == 0) {
                return true;
            };

            imgs.each(function() {
                var image = new Image,
                    imgElement = this;

                image.onload = function() {
                    allImgsLoaded++;
                    eachCallback.call(imgElement, allImgsLoaded, allImgsLength);
                    if (allImgsLoaded == allImgsLength) {
                        finishedCallback.call(obj[0]);
                        return false;
                    };
                };

                image.src = this.src;
            });
        });
    };
})(jQuery);<|endoftext|>


<commit_before>var async = require( "async" );
var Habitat = require( "habitat" );

Habitat.load();

var config = new Habitat();

var Mongo = require( "../lib/mongoose" )();
var Make = require( "../lib/models/make" )( Mongo.mongoInstance() );

  var q = async.queue( function( doc, done ) {
    doc.index( done );
  }, 2);
  q.drain = function() {
    console.log( "Done indexing %d records from Mongo", indexedRecords );
    Mongo.mongoInstance().connection.close();
  };

  var indexedRecords = 0;
  var stream = Make.find({}).stream();
  stream.on( "data", function( doc ) {
    q.push( doc, function( err ) {
      if ( err ) {
        throw err;
      }

      indexedRecords++;
      if ( indexedRecords % 100 === 0 ) {
        console.log( "Indexed %d records", indexedRecords );
      }
    });
  });
  stream.on( "error", function ( err ) {
    throw err;
  });
  stream.on( "end", function() {
    console.log( "Done streaming records from Mongo" );
  });
<commit_msg>No bug - Allow filtering on synchronization<commit_after>var async = require( "async" );
var Habitat = require( "habitat" );

Habitat.load();

var config = new Habitat();

var Mongo = require( "../lib/mongoose" )();
var Make = require( "../lib/models/make" )( Mongo.mongoInstance() );

var criteria = process.argv[2] ? JSON.parse(process.argv[2]) : {};

  var q = async.queue( function( doc, done ) {
    doc.index( done );
  }, 2);
  q.drain = function() {
    console.log( "Done indexing %d records from Mongo", indexedRecords );
    Mongo.mongoInstance().connection.close();
  };

  var indexedRecords = 0;
  var stream = Make.find(criteria).stream();
  stream.on( "data", function( doc ) {
    q.push( doc, function( err ) {
      if ( err ) {
        throw err;
      }

      indexedRecords++;
      if ( indexedRecords % 100 === 0 ) {
        console.log( "Indexed %d records", indexedRecords );
      }
    });
  });
  stream.on( "error", function ( err ) {
    throw err;
  });
  stream.on( "end", function() {
    console.log( "Done streaming records from Mongo" );
  });
<|endoftext|>


<commit_before>// Usage: mongo nko4_development scripts/team-limits.js
var limits = {
  '2013-09-17T00:00:00Z': 10,
  '2013-09-18T00:00:00Z': 100,
  '2013-09-18T12:00:00Z': 200
};

for(dateString in limits) {
  var limit = limits[dateString];
  var date = new Date(Date.parse(dateString));
  print("Setting team limit to " + limit + " at " + date);

  db.teamlimits.update({ effectiveAt: date }, { $set: { limit: limit }}, true);
}
<commit_msg>update team limits script<commit_after>// Usage: mongo nko4_development scripts/team-limits.js
var limits = {
  '2013-09-17T00:00:00Z': 10,
  '2013-09-18T00:00:00Z': 100,
  '2013-09-18T12:00:00Z': 200,
  '2013-10-11T00:00:00Z': 250,
  '2013-10-11T12:00:00Z': 300
};

for(dateString in limits) {
  var limit = limits[dateString];
  var date = new Date(Date.parse(dateString));
  print("Setting team limit to " + limit + " at " + date);

  db.teamlimits.update({ effectiveAt: date }, { $set: { limit: limit }}, true);
}
<|endoftext|>


<commit_before>// ==UserScript==
// @name         NUreageren.nl
// @namespace    https://nureageren.nl/
// @version      2.00
// @updateURL    https://github.com/reinierkors/NUreageren/raw/master/NUreageren.nl.user.js
// @description  Deze plugin zorgt ervoor dat jij weer kunt reageren op nu.nl.
// @author       NUreageren.nl
// @match        *://www.nu.nl/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    var path = window.location.pathname;
    var site = window.location.hostname;
    var sites = ["www.nu.nl"];

    if(!include(sites, site) || path == '/') {
        return;
    }

    switch(site) {
        case 'www.nu.nl':
            nu_nl();
            break;
        default:
            console.log("Deze site word nog niet ondersteund.");
            break;
    }

    function nu_nl() {
        var buttons = document.getElementsByClassName('social-buttons');
        if(buttons.length) {
            var newButton = document.createElement('li');
            newButton.innerHTML = '-' +
                '
' +
                '
' +
                'Reageer

';

            for (var i = 0; i < buttons.length; i++) {
                buttons[i].insertBefore(newButton, buttons[i].firstChild);
            }

            setCount("nureageren_count");
        }
    }

    function setCount(elem) {
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            setText(elem, xmlHttp.responseText);
        }};
        xmlHttp.open("GET", "https://nureageren.nl/api/count/" + path.split('/')[2], true);
        xmlHttp.send(null);
    }

    function include(arr, obj) {
        return (arr.indexOf(obj) != -1);
    }

    function setText(id, newCount) {
        var count = document.getElementsByClassName(id);
        for (var i = 0; i < count.length; i++) {
            count[i].innerHTML = newCount;
        }
    }
})();
<commit_msg>Security fixes, removed innerHTML to prevent document reparsing.<commit_after>// ==UserScript==
// @name         NUreageren.nl
// @namespace    https://nureageren.nl/
// @version      2.1
// @updateURL    https://github.com/reinierkors/NUreageren/raw/master/NUreageren.nl.user.js
// @description  Deze plugin zorgt ervoor dat jij weer kunt reageren op nu.nl.
// @author       NUreageren.nl
// @match        *://www.nu.nl/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    jsonToDOM.namespaces = {
        html: "http://www.w3.org/1999/xhtml",
        xul: "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
    };
    jsonToDOM.defaultNamespace = jsonToDOM.namespaces.html;
    function jsonToDOM(jsonTemplate, doc, nodes) {
        function namespace(name) {
            var reElemNameParts = /^(?:(.*):)?(.*)$/.exec(name);
            return { namespace: jsonToDOM.namespaces[reElemNameParts[1]], shortName: reElemNameParts[2] };
        }

        // Note that 'elemNameOrArray' is: either the full element name (eg. [html:]div) or an array of elements in JSON notation
        function tag(elemNameOrArray, elemAttr) {
            // Array of elements?  Parse each one...
            if (Array.isArray(elemNameOrArray)) {
                var frag = doc.createDocumentFragment();
                Array.forEach(arguments, function(thisElem) {
                    frag.appendChild(tag.apply(null, thisElem));
                });
                return frag;
            }

            // Single element? Parse element namespace prefix (if none exists, default to defaultNamespace), and create element
            var elemNs = namespace(elemNameOrArray);
            var elem = doc.createElementNS(elemNs.namespace || jsonToDOM.defaultNamespace, elemNs.shortName);

            // Set element's attributes and/or callback functions (eg. onclick)
            for (var key in elemAttr) {
                var val = elemAttr[key];
                if (nodes && key == "key") {
                    nodes[val] = elem;
                    continue;
                }

                var attrNs = namespace(key);
                if (typeof val == "function") {
                    // Special case for function attributes; don't just add them as 'on...' attributes, but as events, using addEventListener
                    elem.addEventListener(key.replace(/^on/, ""), val, false);
                }
                else {
                    // Note that the default namespace for XML attributes is, and should be, blank (ie. they're not in any namespace)
                    elem.setAttributeNS(attrNs.namespace || "", attrNs.shortName, val);
                }
            }

            // Create and append this element's children
            var childElems = Array.slice(arguments, 2);
            childElems.forEach(function(childElem) {
                if (childElem != null) {
                    elem.appendChild(
                        childElem instanceof doc.defaultView.Node ? childElem :
                            Array.isArray(childElem) ? tag.apply(null, childElem) :
                                doc.createTextNode(childElem));
                }
            });

            return elem;
        }

        return tag.apply(null, jsonTemplate);
    }

    var path = window.location.pathname;
    var site = window.location.hostname;
    var sites = ["www.nu.nl"];

    if(!include(sites, site) || path == '/') {
        return;
    }

    switch(site) {
        case 'www.nu.nl':
            nu_nl();
            break;
        default:
            console.log("Deze site word nog niet ondersteund.");
            break;
    }

    function nu_nl() {
        var buttons = document.getElementsByClassName('social-buttons');
        if(buttons.length) {
            var newButton = document.createElement('li');
            var json =
            ['html:a', {href:'https://nureageren.nl' + path, rel:'nofollow', class:'tracksocial', target:'_blank'},
                ['html:span', {class:'nureageren_count counter'}, '-'],
                ['html:div', {class:'social-button', style:'background-color: #eaf0fa; border: none;'},
                    ['html:div', {class:'button-content'},
                        ['html:i', {class:'fc fc-nujij'}],
                        ['html:span', {class:'socialtext'}, 'Reageer'],
                    ]
                ]
            ];
            newButton.appendChild(jsonToDOM(json, document, {}));

            for (var i = 0; i < buttons.length; i++) {
                buttons[i].insertBefore(newButton, buttons[i].firstChild);
            }

            setCount("nureageren_count");
        }
    }

    function setCount(elem) {
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            setText(elem, parseInt(xmlHttp.responseText));
        }};
        xmlHttp.open("GET", "https://nureageren.nl/api/count/" + path.split('/')[2], true);
        xmlHttp.send(null);
    }

    function include(arr, obj) {
        return (arr.indexOf(obj) != -1);
    }

    function setText(id, newCount) {
        var count = document.getElementsByClassName(id);
        for (var i = 0; i < count.length; i++) {
            count[i].firstChild.nodeValue = newCount;
        }
    }
})();
<|endoftext|>