<commit_before>/*select language to use*/
var onOSMlang='it-IT';

var successString,manualPosition,loadingText,modalText;

i18n.init({ fallbackLng: onOSMlang, postAsync: 'false' }, function() {
    $("body").i18n();
    successString=i18n.t('messages.success', { escapeInterpolation: false });
    manualPosition=i18n.t('messages.manualPosition', { escapeInterpolation: false });
    loadingText=i18n.t('messages.loadingText');
    modalText={};
    modalText.text=i18n.t('messages.modalTitle');
    modalText.button=i18n.t('messages.modalButton');

	onOSMlang=i18n.lng();
	$.getJSON('./locales/'+onOSMlang+'/categories.json').success(function(data){
		category_data = data;
	});

	$.getJSON('./locales/'+onOSMlang+'/payment.json').success(function(data){
		payment_data = data;
	});

	$.getJSON('./locales/'+onOSMlang+'/wheelchair.json').success(function(data){
		wheel_data = data;
	});

	loadWheelchair(onOSMlang);
  });

/* HERE BE DRAGONS */
var findme_map = L.map('findme-map')
    .setView([41.69, 12.71], 5),
    osmUrl = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
    osm = L.tileLayer(osmUrl, {minZoom: 2, maxZoom: 18, attribution: "Data © OpenStreetMap contributors"}).addTo(findme_map),
    esri = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', { attribution: 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'});

var baseMaps = {
    "Mapnik": osm,
    "Esri WorldImagery": esri
};
L.control.layers(baseMaps).addTo(findme_map);

var category_data = [];
var payment_data = [];
var wheel_data = [];

var findme_marker = L.marker([41.69, 12.71], {draggable:true}).addTo(findme_map);
findme_marker.setOpacity(0);

 L.control.locate({
  follow: true
}).addTo(findme_map);

if (location.hash) location.hash = '';

$("#category").select2({
    query: function (query) {
        var data = {results: []}, i;
        for (i = 0; i < category_data.length; i++) {
            if (query.term.length === 0 || category_data[i].toLowerCase().indexOf(query.term.toLowerCase()) >= 0) {
                data.results.push({id: category_data[i], text: category_data[i]});
            }
        }
        query.callback(data);
    }
});

$("#payment").select2({
    multiple:true,
    query:function(query) {
        var data={results:[]},i;
        for (i = 0; i < payment_data.length; i++) {
            if (query.term.length === 0 || payment_data[i].toLowerCase().indexOf(query.term.toLowerCase()) >= 0) {
                data.results.push({id: payment_data[i], text: payment_data[i]});
            }
        }
        query.callback(data);
    }
});

$("#wheel").select2({
    query: function (query) {
        var data = {results: []}, i;
        data.results=wheel_data;
        query.callback(data);
    }
});

/* search action */
$("#find").submit(function(e) {
    e.preventDefault();
    $("#couldnt-find").hide();
    var address_to_find = $("#address").val();
    if (address_to_find.length === 0) return;

    /* NOMINATIM PARAM */
    var qwarg_nominatim = {
        format: 'json',
        q: address_to_find
    };
    var url_nominatim = "https://nominatim.openstreetmap.org/search?" + $.param(qwarg_nominatim);

    $("#findme h4").text(loadingText);
    $("#findme").addClass("loading");

        $.ajax({
          'url': url_nominatim,
          'success': nominatim_callback,
          'dataType': 'jsonp',
          'jsonp': 'json_callback'
        });

});

function nominatim_callback(data){
    if (data.length > 0) {
            var chosen_place = data[0];

            var bounds = new L.LatLngBounds(
                [+chosen_place.boundingbox[0], +chosen_place.boundingbox[2]],
                [+chosen_place.boundingbox[1], +chosen_place.boundingbox[3]]);

            findme_map.fitBounds(bounds);
            findme_marker.setOpacity(1);
            findme_marker.setLatLng([chosen_place.lat, chosen_place.lon]);
            $('#instructions').html(successString);
            $('.step-2 a').attr('href', '#details');
            $('#addressalt').val(chosen_place.display_name);
    }    else {
            $("#couldnt-find").show();
        }
    $("#findme").removeClass("loading");
}

function solr_callback(data){
    if (data.response.docs.length > 0) {
        var docs=data.response.docs;
        var coords=docs[0].coordinate.split(',');
            findme_marker.setOpacity(1);
            findme_marker.setLatLng([coords[0], coords[1]]);
            findme_map.setView([coords[0], coords[1]],16);
            $('#instructions').html(successString);
            $('.step-2 a').attr('href', '#details');
    }   else {
            $("#couldnt-find").show();
        }
    $("#findme").removeClass("loading");
}

/* map action */
findme_map.on('click', function(e){
findme_marker.setOpacity(1);
findme_marker.setLatLng(e.latlng);
$('#instructions').html(manualPosition);
$('.step-2 a').attr('href', '#details');
});

$(window).on('hashchange', function() {
    if (location.hash == '#details') {
        $('#collect-data-step').removeClass('hide');
        $('#address-step').addClass('hide');
        $('#confirm-step').addClass('hide');
        $('.steps').addClass('on-2');
        $('.steps').removeClass('on-3');
    } else if (location.hash == '#done') {
        $('#confirm-step').removeClass('hide');
        $('#collect-data-step').addClass('hide');
        $('#address-step').addClass('hide');
        $('.steps').addClass('on-3');
    } else {
        $('#address-step').removeClass('hide');
        $('#collect-data-step').addClass('hide');
        $('#confirm-step').addClass('hide');
        $('.steps').removeClass('on-2');
        $('.steps').removeClass('on-3');
    }
    findme_map.invalidateSize();
});

$("#collect-data-done").click(function() {
    location.hash = '#done';

    var note_body = "E' stata inviata una nota tramite su.openstreetmap.it:\n";
        if ($("#name").val()) note_body += i18n.t('step2.name')+": " + $("#name").val() + "\n";
        if ($("#phone").val()) note_body += i18n.t('step2.phone')+": " + $("#phone").val() + "\n";
        if ($("#website").val()) note_body += i18n.t('step2.website')+": " + $("#website").val() + "\n";
        if ($("#social").val()) note_body += i18n.t('step2.social')+": " + $("#social").val() + "\n";
        if ($("#opening_hours").val()) note_body += i18n.t('step2.opening')+": " + $("#opening_hours").val() + "\n";
        if ($("#wheel").val()) note_body += i18n.t('step2.wheel')+": " + $("#wheel").val() + "\n";
        if ($("#category").val()) note_body += i18n.t('step2.catlabel')+": " + $("#category").val() + "\n";
        if ($("#categoryalt").val()) note_body += i18n.t('step2.cataltdesc')+": " + $("#categoryalt").val() + "\n";
        if ($("#addressalt").val()) note_body += i18n.t('step2.addressaltdesc')+": " + $("#addressalt").val() + "\n";
        if ($("#payment").val()) note_body += i18n.t('step2.payment')+": " + $("#payment").val() + "\n";
        if ($("#delivery").val()) note_body += i18n.t('step2.delivery')+": " + $("#delivery").val() + "\n";
        if ($("input:checked[name=delivery_covid]").val() === 'Y') note_body += "delivery:covid19=yes\n";
    var latlon = findme_marker.getLatLng();
    var qwarg = {
            lat: latlon.lat,
            lon: latlon.lng,
            text: note_body
        };

    $.post('https://api.openstreetmap.org/api/0.6/notes.json', qwarg, function( data ) {
        console.log( data );
        var noteId=data['properties']['id'];
        var link='https://www.openstreetmap.org/?note='+noteId+'#map=19/'+latlon.lat+'/'+latlon.lng+'&layers=N';
          $("#linkcoords").append(''+link+'');
    });
});

function clearFields(){
    $("#name").empty();
    $("#phone").empty();
    $("#website").empty();
    $("#social").empty();
    $("#opening_hours").empty();
    $("#category").select2("val", "");
    $("#categoryalt").empty();
    $("#address").empty();
    $("#payment").select2("val", "");
    $("#wheel").select2("val", "");
    $("#linkcoords").empty();
    $("#delivery").empty();
}

/*
 * WHEELCHAIR
 * Extended of example from http://craigsworks.com/projects/qtip/demos/effects/modal
 */
function loadWheelchair(lang)
{
   $.get('./locales/'+lang+'/wheelchair.html', function(data) {

      $('a[rel="modal"]:first').qtip(
      {
         content: {
            title: modalText,
            text: data
         },
         position: {
            target: $(document.body), // Position it via the document body...
            corner: 'center' // ...at the center of the viewport
         },
         show: {
            when: 'click', // Show it on click
            solo: true // And hide all other tooltips
         },
         hide: false,
         style: {
            width: { max: 650 },
            padding: '14px',
            border: {
               width: 9,
               radius: 9,
               color: '#666666'
            },
            name: 'light'
         },
         api: {
            beforeShow: function()
            {
               // Fade in the modal "blanket" using the defined show speed
               $('#qtip-blanket').fadeIn(this.options.show.effect.length);
            },
            beforeHide: function()
            {
               // Fade out the modal "blanket" using the defined hide speed
               $('#qtip-blanket').fadeOut(this.options.hide.effect.length);
            }
         }
      });

   });

   // Create the modal backdrop on document load so all modal tooltips can use it
   $('
')
      .css({
         position: 'absolute',
         top: $(document).scrollTop(), // Use document scrollTop so it's on-screen even if the window is scrolled
         left: 0,
         height: $(document).height(), // Span the full document height...
         width: '100%', // ...and full width

         opacity: 0.7, // Make it slightly transparent
         backgroundColor: 'black',
         zIndex: 5000  // Make sure the zIndex is below 6000 to keep it below tooltips!
      })
      .appendTo(document.body) // Append to the document body
      .hide(); // Hide it initially

};
<commit_msg>reimposto i campi input<commit_after>/*select language to use*/
var onOSMlang='it-IT';

var successString,manualPosition,loadingText,modalText;

i18n.init({ fallbackLng: onOSMlang, postAsync: 'false' }, function() {
    $("body").i18n();
    successString=i18n.t('messages.success', { escapeInterpolation: false });
    manualPosition=i18n.t('messages.manualPosition', { escapeInterpolation: false });
    loadingText=i18n.t('messages.loadingText');
    modalText={};
    modalText.text=i18n.t('messages.modalTitle');
    modalText.button=i18n.t('messages.modalButton');

	onOSMlang=i18n.lng();
	$.getJSON('./locales/'+onOSMlang+'/categories.json').success(function(data){
		category_data = data;
	});

	$.getJSON('./locales/'+onOSMlang+'/payment.json').success(function(data){
		payment_data = data;
	});

	$.getJSON('./locales/'+onOSMlang+'/wheelchair.json').success(function(data){
		wheel_data = data;
	});

	loadWheelchair(onOSMlang);
  });

/* HERE BE DRAGONS */
var findme_map = L.map('findme-map')
    .setView([41.69, 12.71], 5),
    osmUrl = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
    osm = L.tileLayer(osmUrl, {minZoom: 2, maxZoom: 18, attribution: "Data © OpenStreetMap contributors"}).addTo(findme_map),
    esri = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', { attribution: 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'});

var baseMaps = {
    "Mapnik": osm,
    "Esri WorldImagery": esri
};
L.control.layers(baseMaps).addTo(findme_map);

var category_data = [];
var payment_data = [];
var wheel_data = [];

var findme_marker = L.marker([41.69, 12.71], {draggable:true}).addTo(findme_map);
findme_marker.setOpacity(0);

 L.control.locate({
  follow: true
}).addTo(findme_map);

if (location.hash) location.hash = '';

$("#category").select2({
    query: function (query) {
        var data = {results: []}, i;
        for (i = 0; i < category_data.length; i++) {
            if (query.term.length === 0 || category_data[i].toLowerCase().indexOf(query.term.toLowerCase()) >= 0) {
                data.results.push({id: category_data[i], text: category_data[i]});
            }
        }
        query.callback(data);
    }
});

$("#payment").select2({
    multiple:true,
    query:function(query) {
        var data={results:[]},i;
        for (i = 0; i < payment_data.length; i++) {
            if (query.term.length === 0 || payment_data[i].toLowerCase().indexOf(query.term.toLowerCase()) >= 0) {
                data.results.push({id: payment_data[i], text: payment_data[i]});
            }
        }
        query.callback(data);
    }
});

$("#wheel").select2({
    query: function (query) {
        var data = {results: []}, i;
        data.results=wheel_data;
        query.callback(data);
    }
});

/* search action */
$("#find").submit(function(e) {
    e.preventDefault();
    $("#couldnt-find").hide();
    var address_to_find = $("#address").val();
    if (address_to_find.length === 0) return;

    /* NOMINATIM PARAM */
    var qwarg_nominatim = {
        format: 'json',
        q: address_to_find
    };
    var url_nominatim = "https://nominatim.openstreetmap.org/search?" + $.param(qwarg_nominatim);

    $("#findme h4").text(loadingText);
    $("#findme").addClass("loading");

        $.ajax({
          'url': url_nominatim,
          'success': nominatim_callback,
          'dataType': 'jsonp',
          'jsonp': 'json_callback'
        });

});

function nominatim_callback(data){
    if (data.length > 0) {
            var chosen_place = data[0];

            var bounds = new L.LatLngBounds(
                [+chosen_place.boundingbox[0], +chosen_place.boundingbox[2]],
                [+chosen_place.boundingbox[1], +chosen_place.boundingbox[3]]);

            findme_map.fitBounds(bounds);
            findme_marker.setOpacity(1);
            findme_marker.setLatLng([chosen_place.lat, chosen_place.lon]);
            $('#instructions').html(successString);
            $('.step-2 a').attr('href', '#details');
            $('#addressalt').val(chosen_place.display_name);
    }    else {
            $("#couldnt-find").show();
        }
    $("#findme").removeClass("loading");
}

function solr_callback(data){
    if (data.response.docs.length > 0) {
        var docs=data.response.docs;
        var coords=docs[0].coordinate.split(',');
            findme_marker.setOpacity(1);
            findme_marker.setLatLng([coords[0], coords[1]]);
            findme_map.setView([coords[0], coords[1]],16);
            $('#instructions').html(successString);
            $('.step-2 a').attr('href', '#details');
    }   else {
            $("#couldnt-find").show();
        }
    $("#findme").removeClass("loading");
}

/* map action */
findme_map.on('click', function(e){
findme_marker.setOpacity(1);
findme_marker.setLatLng(e.latlng);
$('#instructions').html(manualPosition);
$('.step-2 a').attr('href', '#details');
});

$(window).on('hashchange', function() {
    if (location.hash == '#details') {
        $('#collect-data-step').removeClass('hide');
        $('#address-step').addClass('hide');
        $('#confirm-step').addClass('hide');
        $('.steps').addClass('on-2');
        $('.steps').removeClass('on-3');
    } else if (location.hash == '#done') {
        $('#confirm-step').removeClass('hide');
        $('#collect-data-step').addClass('hide');
        $('#address-step').addClass('hide');
        $('.steps').addClass('on-3');
    } else {
        $('#address-step').removeClass('hide');
        $('#collect-data-step').addClass('hide');
        $('#confirm-step').addClass('hide');
        $('.steps').removeClass('on-2');
        $('.steps').removeClass('on-3');
    }
    findme_map.invalidateSize();
});

$("#collect-data-done").click(function() {
    location.hash = '#done';

    var note_body = "E' stata inviata una nota tramite su.openstreetmap.it:\n";
        if ($("#name").val()) note_body += i18n.t('step2.name')+": " + $("#name").val() + "\n";
        if ($("#phone").val()) note_body += i18n.t('step2.phone')+": " + $("#phone").val() + "\n";
        if ($("#website").val()) note_body += i18n.t('step2.website')+": " + $("#website").val() + "\n";
        if ($("#social").val()) note_body += i18n.t('step2.social')+": " + $("#social").val() + "\n";
        if ($("#opening_hours").val()) note_body += i18n.t('step2.opening')+": " + $("#opening_hours").val() + "\n";
        if ($("#wheel").val()) note_body += i18n.t('step2.wheel')+": " + $("#wheel").val() + "\n";
        if ($("#category").val()) note_body += i18n.t('step2.catlabel')+": " + $("#category").val() + "\n";
        if ($("#categoryalt").val()) note_body += i18n.t('step2.cataltdesc')+": " + $("#categoryalt").val() + "\n";
        if ($("#addressalt").val()) note_body += i18n.t('step2.addressaltdesc')+": " + $("#addressalt").val() + "\n";
        if ($("#payment").val()) note_body += i18n.t('step2.payment')+": " + $("#payment").val() + "\n";
        if ($("#delivery").val()) note_body += i18n.t('step2.delivery')+": " + $("#delivery").val() + "\n";
        if ($("input:checked[name=delivery_covid]").val() === 'Y') note_body += "delivery:covid19=yes\n";
    var latlon = findme_marker.getLatLng();
    var qwarg = {
            lat: latlon.lat,
            lon: latlon.lng,
            text: note_body
        };

    $.post('https://api.openstreetmap.org/api/0.6/notes.json', qwarg, function( data ) {
        console.log( data );
        var noteId=data['properties']['id'];
        var link='https://www.openstreetmap.org/?note='+noteId+'#map=19/'+latlon.lat+'/'+latlon.lng+'&layers=N';
          $("#linkcoords").append(''+link+'');
    });
});

function clearFields(){
    $("#name").val("");
    $("#phone").val("");
    $("#website").val("");
    $("#social").val("");
    $("#opening_hours").val("");
    $("#category").select2("val", "");
    $("#categoryalt").val("");
    $("#address").val("");
    $("#addressalt").val("");
    $("#payment").select2("val", "");
    $("#wheel").select2("val", "");
    $("#linkcoords").val("");
    $("#delivery").val("");
}

/*
 * WHEELCHAIR
 * Extended of example from http://craigsworks.com/projects/qtip/demos/effects/modal
 */
function loadWheelchair(lang)
{
   $.get('./locales/'+lang+'/wheelchair.html', function(data) {

      $('a[rel="modal"]:first').qtip(
      {
         content: {
            title: modalText,
            text: data
         },
         position: {
            target: $(document.body), // Position it via the document body...
            corner: 'center' // ...at the center of the viewport
         },
         show: {
            when: 'click', // Show it on click
            solo: true // And hide all other tooltips
         },
         hide: false,
         style: {
            width: { max: 650 },
            padding: '14px',
            border: {
               width: 9,
               radius: 9,
               color: '#666666'
            },
            name: 'light'
         },
         api: {
            beforeShow: function()
            {
               // Fade in the modal "blanket" using the defined show speed
               $('#qtip-blanket').fadeIn(this.options.show.effect.length);
            },
            beforeHide: function()
            {
               // Fade out the modal "blanket" using the defined hide speed
               $('#qtip-blanket').fadeOut(this.options.hide.effect.length);
            }
         }
      });

   });

   // Create the modal backdrop on document load so all modal tooltips can use it
   $('
')
      .css({
         position: 'absolute',
         top: $(document).scrollTop(), // Use document scrollTop so it's on-screen even if the window is scrolled
         left: 0,
         height: $(document).height(), // Span the full document height...
         width: '100%', // ...and full width

         opacity: 0.7, // Make it slightly transparent
         backgroundColor: 'black',
         zIndex: 5000  // Make sure the zIndex is below 6000 to keep it below tooltips!
      })
      .appendTo(document.body) // Append to the document body
      .hide(); // Hide it initially

};
<|endoftext|>


<commit_before>/*global define*/
define([
        './DeveloperError',
        './defaultValue',
        './defined'
    ], function(
        DeveloperError,
        defaultValue,
        defined) {
    'use strict';

    /**
     * Fill an array or a portion of an array with a given value.
     * @private
     *
     * @param {Array} array The array to fill.
     * @param {*} value The value to fill the array with.
     * @param {Number} start The index to start filling at.
     * @param {Number} end The index to end stop at.
     *
     * @returns {Array} The resulting array.
     */
    function arrayFill(array, value, start, end) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(array) || typeof array !== 'object') {
            throw new DeveloperError('Array is required.');
        }
        if (!defined(value)) {
            throw new DeveloperError('Value is required.');
        }
        if (defined(start) && (typeof start !== 'number')) {
            throw new DeveloperError('Start must be a valid index.');
        }
        if (defined(end) && (typeof end !== 'number')) {
            throw new DeveloperError('End must be a valid index.');
        }
        //>>includeEnd('debug');

        if (typeof array.fill !== 'undefined') {
            return array.fill(value, start, end);
        }

        var length = array.length >>> 0;

        var relativeStart = defaultValue(start, 0);

        // If negative, find wrap around position
        var k = (relativeStart < 0) ? Math.max(length + relativeStart, 0) : Math.min(relativeStart, length);

        var relativeEnd = defaultValue(end, length);

        // If negative, find wrap around position
        var final = (relativeEnd < 0) ? Math.max(length + relativeEnd, 0) : Math.min(relativeEnd, length);

        // Fill array accordingly
        while (k < final) {
            array[k] = value;
            k++;
        }
        return array;
    }

    return arrayFill;
});
<commit_msg>Address comments. Small style fixes, remove redundant error checking<commit_after>/*global define*/
define([
        './DeveloperError',
        './defaultValue',
        './defined'
    ], function(
        DeveloperError,
        defaultValue,
        defined) {
    'use strict';

    /**
     * Fill an array or a portion of an array with a given value.
     *
     * @param {Array} array The array to fill.
     * @param {Object} value The value to fill the array with.
     * @param {Number} start The index to start filling at.
     * @param {Number} end The index to end stop at.
     *
     * @returns {Array} The resulting array.
     * @private
     */
    function arrayFill(array, value, start, end) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(array) || typeof array !== 'object') {
            throw new DeveloperError('array is required.');
        }
        if (!defined(value)) {
            throw new DeveloperError('value is required.');
        }
        if (typeof start !== 'number') {
            throw new DeveloperError('start must be a valid index.');
        }
        if (typeof end !== 'number') {
            throw new DeveloperError('end must be a valid index.');
        }
        //>>includeEnd('debug');

        if (typeof array.fill === 'function') {
            return array.fill(value, start, end);
        }

        var length = array.length >>> 0;

        var relativeStart = defaultValue(start, 0);

        // If negative, find wrap around position
        var k = (relativeStart < 0) ? Math.max(length + relativeStart, 0) : Math.min(relativeStart, length);

        var relativeEnd = defaultValue(end, length);

        // If negative, find wrap around position
        var final = (relativeEnd < 0) ? Math.max(length + relativeEnd, 0) : Math.min(relativeEnd, length);

        // Fill array accordingly
        while (k < final) {
            array[k] = value;
            k++;
        }
        return array;
    }

    return arrayFill;
});
<|endoftext|>


<commit_before>var colors = ['#F44336','#673AB7','#009688','#FFEB3B','#FF9800','#9E9E9E'];
var scale_maxDate =new Date(2015, 5, 25);

var timecount_chart = dc.lineChart("#time_count");
var timestats1_chart = dc.compositeChart("#time_stats");
var timestats2_chart = dc.compositeChart("#time_stats2");
var org_chart = dc.rowChart("#rc_org");
var under5_chart = dc.pieChart("#age");

    var dateFormat = d3.time.format("%Y-%m-%d");
    data.forEach(function (e) {
        e.date = dateFormat.parse(e.date);
    });

var cf = crossfilter(data);

var dateDimension = cf.dimension(function(d){ return d.date; });
var orgDimension = cf.dimension(function(d){ return d.rc; });
var under5Dimension = cf.dimension(function(d){ return d.Under_5; });

var dateGroup = dateDimension.group().reduceSum(function(d) {return d.deaths+d.trauma+d.ari+d.awd+d.bloody_dia+d.pou;});
var deathsGroup = dateDimension.group().reduceSum(function(d) {return d.deaths;});
var traumaGroup = dateDimension.group().reduceSum(function(d) {return d.trauma;});
var ariGroup = dateDimension.group().reduceSum(function(d) {return d.ari;});
var awdGroup = dateDimension.group().reduceSum(function(d) {return d.awd;});
var bloodydiaGroup = dateDimension.group().reduceSum(function(d) {return d.bloody_dia;});
var pouGroup = dateDimension.group().reduceSum(function(d) {return d.pou;});
var orgGroup = orgDimension.group().reduceSum(function(d) {return d.deaths+d.trauma+d.ari+d.awd+d.bloody_dia+d.pou;});
var under5Group = under5Dimension.group().reduceSum(function(d) {return d.deaths+d.trauma+d.ari+d.awd+d.bloody_dia+d.pou;});

var patientsAll = cf.groupAll().reduceSum(function(d){ return d.deaths+d.trauma+d.ari+d.awd+d.bloody_dia+d.pou; });
var deathsAll = cf.groupAll().reduceSum(function(d){ return d.deaths; });
var traumaAll = cf.groupAll().reduceSum(function(d){ return d.trauma; });
var ariAll = cf.groupAll().reduceSum(function(d){ return d.ari; });
var awdAll = cf.groupAll().reduceSum(function(d){ return d.awd; });
var pouAll = cf.groupAll().reduceSum(function(d){ return d.pou; });
var bloodydiaAll = cf.groupAll().reduceSum(function(d){ return d.bloody_dia; });

var xScaleRange = d3.time.scale().domain([new Date(2015, 4, 1), scale_maxDate]);

timecount_chart
        .width($('#time_count').width())
        .height(150)
        .dimension(dateDimension)
        .group(dateGroup)
        .x(xScaleRange)
        .xAxisLabel("Date")
        .yAxisLabel("Cases")
        .xAxis().ticks(8);

timestats1_chart
        .width($('#time_stats').width())
        .height(200)
        .dimension(dateDimension)
        .x(d3.time.scale().domain([new Date(2015, 4, 1), scale_maxDate]))
        .rangeChart(timecount_chart)
        .elasticY(true)
        .compose([
            dc.lineChart(timestats1_chart).group(deathsGroup,'Deaths').colors(colors[0]),
            dc.lineChart(timestats1_chart).group(traumaGroup,'Trauma').colors(colors[1]),
        ])
        .brushOn(false)
        .xAxisLabel("Date")
        .yAxisLabel("Cases")
        .legend(dc.legend().x($('#time_count').width()-150).y(0).gap(5))
        .xAxis().ticks(8);

timestats2_chart
        .width($('#time_stats').width())
        .height(200)
        .dimension(dateDimension)
        .x(d3.time.scale().domain([new Date(2015, 4, 1), scale_maxDate]))
        .elasticY(true)
        .compose([
            dc.lineChart(timestats2_chart).group(ariGroup, 'ARI').colors(colors[2]),
            dc.lineChart(timestats2_chart).group(awdGroup, 'AWD').colors(colors[3]),
            dc.lineChart(timestats2_chart).group(bloodydiaGroup, 'Bloody Diarrhea').colors(colors[4]),
            dc.lineChart(timestats2_chart).group(pouGroup, 'PUO').colors(colors[5])
        ])
        .brushOn(false)
        .xAxisLabel("Date")
        .yAxisLabel("Cases")
        .legend(dc.legend().x($('#time_count').width()-150).y(0).gap(5))
        .xAxis().ticks(8);

org_chart.width($('#rc_org').width()).height(300)
        .dimension(orgDimension)
        .group(orgGroup)
        .xAxis().ticks(8);

under5_chart.width($('#age').width()).height(200)
        .dimension(under5Dimension)
        .group(under5Group);

dc.dataCount('#deathstotal')
	.dimension(cf)
	.group(deathsAll);

dc.dataCount('#traumatotal')
	.dimension(cf)
	.group(traumaAll);

dc.dataCount('#aritotal')
	.dimension(cf)
	.group(ariAll);

dc.dataCount('#awdtotal')
	.dimension(cf)
	.group(awdAll);

dc.dataCount('#bloodydiatotal')
	.dimension(cf)
	.group(bloodydiaAll);

dc.dataCount('#poutotal')
	.dimension(cf)
	.group(pouAll);

    function rangesEqual(range1, range2) {
        if (!range1 && !range2) {
            return true;
        }
        else if (!range1 || !range2) {
            return false;
        }
        else if (range1.length === 0 && range2.length === 0) {
            return true;
        }
        else if (range1[0].valueOf() === range2[0].valueOf() &&
            range1[1].valueOf() === range2[1].valueOf()) {
            return true;
        }
        return false;
    }
    // monkey-patch the first chart with a new function
    // technically we don't even need to do this, we could just change the 'filtered'
    // event externally, but this is a bit nicer and could be added to dc.js core someday
    timecount_chart.focusCharts = function (chartlist) {
        if (!arguments.length) {
            return this._focusCharts;
        }
        this._focusCharts = chartlist; // only needed to support the getter above
        this.on('filtered', function (range_chart) {
            if (!range_chart.filter()) {
                dc.events.trigger(function () {
                    chartlist.forEach(function(focus_chart) {
                        focus_chart.x().domain(focus_chart.xOriginalDomain());
                    });
                });
            } else chartlist.forEach(function(focus_chart) {
                if (!rangesEqual(range_chart.filter(), focus_chart.filter())) {
                    dc.events.trigger(function () {
                        focus_chart.focus(range_chart.filter());
                    });
                }
            });
        });
        return this;
    };
    timecount_chart.focusCharts([timestats1_chart,timestats2_chart]);

dc.renderAll();
<commit_msg>Changed y-axis tick marks<commit_after>var colors = ['#F44336','#673AB7','#009688','#FFEB3B','#FF9800','#9E9E9E'];
var scale_maxDate =new Date(2015, 5, 25);

var timecount_chart = dc.lineChart("#time_count");
var timestats1_chart = dc.compositeChart("#time_stats");
var timestats2_chart = dc.compositeChart("#time_stats2");
var org_chart = dc.rowChart("#rc_org");
var under5_chart = dc.pieChart("#age");

    var dateFormat = d3.time.format("%Y-%m-%d");
    data.forEach(function (e) {
        e.date = dateFormat.parse(e.date);
    });

var cf = crossfilter(data);

var dateDimension = cf.dimension(function(d){ return d.date; });
var orgDimension = cf.dimension(function(d){ return d.rc; });
var under5Dimension = cf.dimension(function(d){ return d.Under_5; });

var dateGroup = dateDimension.group().reduceSum(function(d) {return d.deaths+d.trauma+d.ari+d.awd+d.bloody_dia+d.pou;});
var deathsGroup = dateDimension.group().reduceSum(function(d) {return d.deaths;});
var traumaGroup = dateDimension.group().reduceSum(function(d) {return d.trauma;});
var ariGroup = dateDimension.group().reduceSum(function(d) {return d.ari;});
var awdGroup = dateDimension.group().reduceSum(function(d) {return d.awd;});
var bloodydiaGroup = dateDimension.group().reduceSum(function(d) {return d.bloody_dia;});
var pouGroup = dateDimension.group().reduceSum(function(d) {return d.pou;});
var orgGroup = orgDimension.group().reduceSum(function(d) {return d.deaths+d.trauma+d.ari+d.awd+d.bloody_dia+d.pou;});
var under5Group = under5Dimension.group().reduceSum(function(d) {return d.deaths+d.trauma+d.ari+d.awd+d.bloody_dia+d.pou;});

var patientsAll = cf.groupAll().reduceSum(function(d){ return d.deaths+d.trauma+d.ari+d.awd+d.bloody_dia+d.pou; });
var deathsAll = cf.groupAll().reduceSum(function(d){ return d.deaths; });
var traumaAll = cf.groupAll().reduceSum(function(d){ return d.trauma; });
var ariAll = cf.groupAll().reduceSum(function(d){ return d.ari; });
var awdAll = cf.groupAll().reduceSum(function(d){ return d.awd; });
var pouAll = cf.groupAll().reduceSum(function(d){ return d.pou; });
var bloodydiaAll = cf.groupAll().reduceSum(function(d){ return d.bloody_dia; });

var xScaleRange = d3.time.scale().domain([new Date(2015, 4, 1), scale_maxDate]);

timecount_chart
        .width($('#time_count').width())
        .height(150)
        .dimension(dateDimension)
        .group(dateGroup)
        .x(xScaleRange)
        .xAxisLabel("Date")
        .yAxisLabel("Cases")
        .xAxis().ticks(8);
timecount_chart.yAxis().ticks(8);

timestats1_chart
        .width($('#time_stats').width())
        .height(200)
        .dimension(dateDimension)
        .x(d3.time.scale().domain([new Date(2015, 4, 1), scale_maxDate]))
        .rangeChart(timecount_chart)
        .elasticY(true)
        .compose([
            dc.lineChart(timestats1_chart).group(deathsGroup,'Deaths').colors(colors[0]),
            dc.lineChart(timestats1_chart).group(traumaGroup,'Trauma').colors(colors[1]),
        ])
        .brushOn(false)
        .xAxisLabel("Date")
        .yAxisLabel("Cases")
        .legend(dc.legend().x($('#time_count').width()-150).y(0).gap(5))
        .xAxis().ticks(8);
timestats1_chart.yAxis().ticks(6);

timestats2_chart
        .width($('#time_stats').width())
        .height(200)
        .dimension(dateDimension)
        .x(d3.time.scale().domain([new Date(2015, 4, 1), scale_maxDate]))
        .elasticY(true)
        .compose([
            dc.lineChart(timestats2_chart).group(ariGroup, 'ARI').colors(colors[2]),
            dc.lineChart(timestats2_chart).group(awdGroup, 'AWD').colors(colors[3]),
            dc.lineChart(timestats2_chart).group(bloodydiaGroup, 'Bloody Diarrhea').colors(colors[4]),
            dc.lineChart(timestats2_chart).group(pouGroup, 'PUO').colors(colors[5])
        ])
        .brushOn(false)
        .xAxisLabel("Date")
        .yAxisLabel("Cases")
        .legend(dc.legend().x($('#time_count').width()-150).y(0).gap(5))
        .xAxis().ticks(8);

org_chart.width($('#rc_org').width()).height(300)
        .dimension(orgDimension)
        .group(orgGroup)
        .xAxis().ticks(8);

under5_chart.width($('#age').width()).height(200)
        .dimension(under5Dimension)
        .group(under5Group);

dc.dataCount('#deathstotal')
	.dimension(cf)
	.group(deathsAll);

dc.dataCount('#traumatotal')
	.dimension(cf)
	.group(traumaAll);

dc.dataCount('#aritotal')
	.dimension(cf)
	.group(ariAll);

dc.dataCount('#awdtotal')
	.dimension(cf)
	.group(awdAll);

dc.dataCount('#bloodydiatotal')
	.dimension(cf)
	.group(bloodydiaAll);

dc.dataCount('#poutotal')
	.dimension(cf)
	.group(pouAll);

    function rangesEqual(range1, range2) {
        if (!range1 && !range2) {
            return true;
        }
        else if (!range1 || !range2) {
            return false;
        }
        else if (range1.length === 0 && range2.length === 0) {
            return true;
        }
        else if (range1[0].valueOf() === range2[0].valueOf() &&
            range1[1].valueOf() === range2[1].valueOf()) {
            return true;
        }
        return false;
    }
    // monkey-patch the first chart with a new function
    // technically we don't even need to do this, we could just change the 'filtered'
    // event externally, but this is a bit nicer and could be added to dc.js core someday
    timecount_chart.focusCharts = function (chartlist) {
        if (!arguments.length) {
            return this._focusCharts;
        }
        this._focusCharts = chartlist; // only needed to support the getter above
        this.on('filtered', function (range_chart) {
            if (!range_chart.filter()) {
                dc.events.trigger(function () {
                    chartlist.forEach(function(focus_chart) {
                        focus_chart.x().domain(focus_chart.xOriginalDomain());
                    });
                });
            } else chartlist.forEach(function(focus_chart) {
                if (!rangesEqual(range_chart.filter(), focus_chart.filter())) {
                    dc.events.trigger(function () {
                        focus_chart.focus(range_chart.filter());
                    });
                }
            });
        });
        return this;
    };
    timecount_chart.focusCharts([timestats1_chart,timestats2_chart]);

dc.renderAll();
<|endoftext|>


<commit_before>import { Component, PropTypes } from 'react';
import createHelper from 'recompose/createHelper';
import createEagerFactory from 'recompose/createEagerFactory';

const initStore = initializer => (BaseComponent) => {
  const factory = createEagerFactory(BaseComponent);

  const StoreInitializer = class extends Component {
    constructor(props, context) {
      super(props, context);
      this.store = context.store;
    }
    componentWillMount() {
      const store = this.store;
      this.isInitialized(initializer(store.dispatch, store.getState(), this.props));
    }

    componentWillReceiveProps(nextProps) {
      const store = this.store;
      this.isInitialized(initializer(store.dispatch, store.getState(), nextProps, this.props));
    }

    isInitialized(initRet) {
      this.shouldUpdate = initRet !== false;
      if (initRet instanceof Promise) {
        this.shouldUpdate = false;
        initRet.then(() => {
          this.shouldUpdate = true;
          this.forceUpdate();
        });
      }
    }
    shouldComponentUpdate() {
      return this.shouldUpdate;
    }

    render() {
      return factory(this.props);
    }
  };
  StoreInitializer.contextTypes = {
    store: PropTypes.shape({
      subscribe: PropTypes.func.isRequired,
      dispatch: PropTypes.func.isRequired,
      getState: PropTypes.func.isRequired,
    }),
  };
  return StoreInitializer;
};

export default createHelper(initStore, 'initStore');
<commit_msg>prevents calling forUpdate on unmounted components<commit_after>import { Component, PropTypes } from 'react';
import createHelper from 'recompose/createHelper';
import createEagerFactory from 'recompose/createEagerFactory';

const initStore = initializer => (BaseComponent) => {
  const factory = createEagerFactory(BaseComponent);

  const StoreInitializer = class extends Component {
    constructor(props, context) {
      super(props, context);
      this.store = context.store;
    }
    componentWillMount() {
      const store = this.store;
      this.isInitialized(initializer(store.dispatch, store.getState(), this.props));
    }
    componentDidMount() {
      this.mounted = true;
    }
    componentWillUnmount() {
      this.mounted = false;
    }

    componentWillReceiveProps(nextProps) {
      const store = this.store;
      this.isInitialized(initializer(store.dispatch, store.getState(), nextProps, this.props));
    }

    isInitialized(initRet) {
      this.shouldUpdate = initRet !== false;
      if (initRet instanceof Promise) {
        this.shouldUpdate = false;
        initRet.then(() => {
          this.shouldUpdate = true;
          if (this.mounted) this.forceUpdate();
        });
      }
    }
    shouldComponentUpdate() {
      return this.shouldUpdate;
    }

    render() {
      return factory(this.props);
    }
  };
  StoreInitializer.contextTypes = {
    store: PropTypes.shape({
      subscribe: PropTypes.func.isRequired,
      dispatch: PropTypes.func.isRequired,
      getState: PropTypes.func.isRequired,
    }),
  };
  return StoreInitializer;
};

export default createHelper(initStore, 'initStore');
<|endoftext|>


<commit_before>'use strict';

// Required args: array, todo
// Optional args: reverse
function sort_custom(args){
    args['array'].sort(args['todo']);
    args['reverse'] = args['reverse'] || false;

    if(args['reverse']){
        args['array'].reverse();
    }
}

// Required args: array
// Optional args: reverse
function sort_numbers(args){
    sort_custom({
      'array': args['array'],
      'reverse': args['reverse'] || false,
      'todo': function(a, b){
          return a - b;
      },
    });
}

// Required args: array
function sort_random(args){
    sort_custom({
      'array': args['array'],
      'todo': function(a, b){
          return Math.random() - 0.5;
      },
    });
}

// Required args: array, property
// Optional args: reverse
function sort_property(args){
    sort_custom({
      'array': args['array'],
      'reverse': args['reverse'] || false,
      'todo': function(a, b){
          if(a[args['property']] > b[args['property']]){
              return 1;

          }else if(a[args['property']] < b[args['property']]){
              return -1;
          }

          return 0;
      },
    });
}

// Required args, array
// Optional args: reverse
function sort_strings(args){
    sort_custom({
      'array': args['array'],
      'reverse': args['reverse'] || false,
      'todo': function(a, b){
          return a.localeCompare(b);
      },
    });
}
<commit_msg>added common core.js usage to common sort.js<commit_after>'use strict';

// Required args: array, todo
// Optional args: reverse
function sort_custom(args){
    args = core_args({
      'args': args,
      'defaults': {
        'reverse': false,
      },
    });

    args['array'].sort(args['todo']);
    if(args['reverse']){
        args['array'].reverse();
    }
}

// Required args: array
// Optional args: reverse
function sort_numbers(args){
    args = core_args({
      'args': args,
      'defaults': {
        'reverse': false,
      },
    });

    sort_custom({
      'array': args['array'],
      'reverse': args['reverse'],
      'todo': function(a, b){
          return a - b;
      },
    });
}

// Required args: array
function sort_random(args){
    sort_custom({
      'array': args['array'],
      'todo': function(a, b){
          return Math.random() - 0.5;
      },
    });
}

// Required args: array, property
// Optional args: reverse
function sort_property(args){
    args = core_args({
      'args': args,
      'defaults': {
        'reverse': false,
      },
    });

    sort_custom({
      'array': args['array'],
      'reverse': args['reverse'],
      'todo': function(a, b){
          if(a[args['property']] > b[args['property']]){
              return 1;

          }else if(a[args['property']] < b[args['property']]){
              return -1;
          }

          return 0;
      },
    });
}

// Required args, array
// Optional args: reverse
function sort_strings(args){
    args = core_args({
      'args': args,
      'defaults': {
        'reverse': false,
      },
    });

    sort_custom({
      'array': args['array'],
      'reverse': args['reverse'],
      'todo': function(a, b){
          return a.localeCompare(b);
      },
    });
}
<|endoftext|>


<commit_before>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const cp = require('child_process');
const path = require('path');
const fs = require('fs');
const yarn = process.platform === 'win32' ? 'yarn.cmd' : 'yarn';

/**
 * @param {string} location
 * @param {*} [opts]
 */
function yarnInstall(location, opts) {
	opts = opts || { env: process.env };
	opts.cwd = location;
	opts.stdio = 'inherit';

	const raw = process.env['npm_config_argv'] || '{}';
	const argv = JSON.parse(raw);
	const original = argv.original || [];
	const args = original.filter(arg => arg === '--ignore-optional' || arg === '--frozen-lockfile');

	console.log(`Installing dependencies in ${location}...`);
	console.log(`$ yarn ${args.join(' ')}`);
	const result = cp.spawnSync(yarn, args, opts);

	if (result.error || result.status !== 0) {
		process.exit(1);
	}
}

yarnInstall('extensions'); // node modules shared by all extensions

if (!(process.platform === 'win32' && process.env['npm_config_arch'] === 'arm64')) {
	yarnInstall('remote'); // node modules used by vscode server
	yarnInstall('remote/web'); // node modules used by vscode web
}

const allExtensionFolders = fs.readdirSync('extensions');
const extensions = allExtensionFolders.filter(e => {
	try {
		let packageJSON = JSON.parse(fs.readFileSync(path.join('extensions', e, 'package.json')).toString());
		return packageJSON && (packageJSON.dependencies || packageJSON.devDependencies);
	} catch (e) {
		return false;
	}
});

extensions.forEach(extension => yarnInstall(`extensions/${extension}`));

function yarnInstallBuildDependencies() {
	// make sure we install the deps of build/lib/watch for the system installed
	// node, since that is the driver of gulp
	const watchPath = path.join(path.dirname(__dirname), 'lib', 'watch');
	const yarnrcPath = path.join(watchPath, '.yarnrc');

	const disturl = 'https://nodejs.org/download/release';
	const target = process.versions.node;
	const runtime = 'node';

	const yarnrc = `disturl "${disturl}"
target "${target}"
runtime "${runtime}"`;

	fs.writeFileSync(yarnrcPath, yarnrc, 'utf8');
	yarnInstall(watchPath);
}

yarnInstall(`build`); // node modules required for build
yarnInstall('test/automation'); // node modules required for smoketest
yarnInstall('test/smoke'); // node modules required for smoketest
yarnInstall('test/integration/browser'); // node modules required for integration
yarnInstallBuildDependencies(); // node modules for watching, specific to host node version, not electron
<commit_msg>force rebase when pulling<commit_after>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

const cp = require('child_process');
const path = require('path');
const fs = require('fs');
const yarn = process.platform === 'win32' ? 'yarn.cmd' : 'yarn';

/**
 * @param {string} location
 * @param {*} [opts]
 */
function yarnInstall(location, opts) {
	opts = opts || { env: process.env };
	opts.cwd = location;
	opts.stdio = 'inherit';

	const raw = process.env['npm_config_argv'] || '{}';
	const argv = JSON.parse(raw);
	const original = argv.original || [];
	const args = original.filter(arg => arg === '--ignore-optional' || arg === '--frozen-lockfile');

	console.log(`Installing dependencies in ${location}...`);
	console.log(`$ yarn ${args.join(' ')}`);
	const result = cp.spawnSync(yarn, args, opts);

	if (result.error || result.status !== 0) {
		process.exit(1);
	}
}

yarnInstall('extensions'); // node modules shared by all extensions

if (!(process.platform === 'win32' && process.env['npm_config_arch'] === 'arm64')) {
	yarnInstall('remote'); // node modules used by vscode server
	yarnInstall('remote/web'); // node modules used by vscode web
}

const allExtensionFolders = fs.readdirSync('extensions');
const extensions = allExtensionFolders.filter(e => {
	try {
		let packageJSON = JSON.parse(fs.readFileSync(path.join('extensions', e, 'package.json')).toString());
		return packageJSON && (packageJSON.dependencies || packageJSON.devDependencies);
	} catch (e) {
		return false;
	}
});

extensions.forEach(extension => yarnInstall(`extensions/${extension}`));

function yarnInstallBuildDependencies() {
	// make sure we install the deps of build/lib/watch for the system installed
	// node, since that is the driver of gulp
	const watchPath = path.join(path.dirname(__dirname), 'lib', 'watch');
	const yarnrcPath = path.join(watchPath, '.yarnrc');

	const disturl = 'https://nodejs.org/download/release';
	const target = process.versions.node;
	const runtime = 'node';

	const yarnrc = `disturl "${disturl}"
target "${target}"
runtime "${runtime}"`;

	fs.writeFileSync(yarnrcPath, yarnrc, 'utf8');
	yarnInstall(watchPath);
}

yarnInstall(`build`); // node modules required for build
yarnInstall('test/automation'); // node modules required for smoketest
yarnInstall('test/smoke'); // node modules required for smoketest
yarnInstall('test/integration/browser'); // node modules required for integration
yarnInstallBuildDependencies(); // node modules for watching, specific to host node version, not electron

cp.execSync('git config pull.rebase true');
<|endoftext|>


<commit_before>module.exports = function pureComponentFallback({ types: t, template }) {
  const buildPureOrNormalSuperclass = () => t.LogicalExpression('||',
    t.memberExpression(t.identifier('React'), t.identifier('PureComponent')),
    t.memberExpression(t.identifier('React'), t.identifier('Component')));

  const buildShouldComponentUpdate = () => {
    const method = t.classMethod(
      'method',
      t.identifier('shouldComponentUpdate'),
      [t.identifier('nextProps'), t.identifier('nextState')],
      t.blockStatement([template('return shallowCompare(this, nextProps, nextState);')()])
    );
    return method;
  };

  function superclassIsPureComponent(path) {
    const superclass = path.get('superClass');
    // check for PureComponent
    if (t.isIdentifier(superclass)) {
      return superclass.node.name === 'PureComponent';
    }

    if (t.isMemberExpression(superclass)) {
      // Check for React.PureComponent
      return superclass.get('object').node.name === 'React'
        && superclass.get('property').node.name === 'PureComponent';
    }

    return false;
  }

  return {
    visitor: {
      Program: {
        exit({ node }, { file }) {
          if (file.get('addShallowCompareImport')) {
            const shallowCompareImportDeclaration = t.importDeclaration([
              t.importDefaultSpecifier(t.identifier('shallowCompare')),
            ], t.stringLiteral('react-addons-shallow-compare'));
            node.body.unshift(shallowCompareImportDeclaration);
          }
        },
      },

      ClassDeclaration(path, { file }) {
        if (superclassIsPureComponent(path)) {
          const superclassPath = path.get('superClass');

          // Replace the superclass
          superclassPath.replaceWith(buildPureOrNormalSuperclass());

          // Only add an SCU if one doesn't already exist
          const existingSCU = path.get('body').get('body').find((
            p => p.isClassMethod() && p.get('key').node.name === 'shouldComponentUpdate'
          ));

          if (!existingSCU) {
            file.set('addShallowCompareImport', true);
            path.get('body').unshiftContainer('body', buildShouldComponentUpdate());
          }
        }
      },
    },
  };
};
<commit_msg>Conditionally apply the shouldComponentUpdate method if React.PureComponent does not exist<commit_after>module.exports = function pureComponentFallback({ types: t, template }) {
  const buildPureOrNormalSuperclass = () => t.LogicalExpression('||',
    t.memberExpression(t.identifier('React'), t.identifier('PureComponent')),
    t.memberExpression(t.identifier('React'), t.identifier('Component')));

  const buildShouldComponentUpdate = () => {
    const method = t.classMethod(
      'method',
      t.logicalExpression(
        '&&',
        t.unaryExpression('!', t.memberExpression(t.identifier('React'), t.identifier('PureComponent'))),
        t.stringLiteral('shouldComponentUpdate')
      ),
      [t.identifier('nextProps'), t.identifier('nextState')],
      t.blockStatement([template('return shallowCompare(this, nextProps, nextState);')()]),
      true
    );
    return method;
  };

  function superclassIsPureComponent(path) {
    const superclass = path.get('superClass');
    // check for PureComponent
    if (t.isIdentifier(superclass)) {
      return superclass.node.name === 'PureComponent';
    }

    if (t.isMemberExpression(superclass)) {
      // Check for React.PureComponent
      return superclass.get('object').node.name === 'React'
        && superclass.get('property').node.name === 'PureComponent';
    }

    return false;
  }

  return {
    visitor: {
      Program: {
        exit({ node }, { file }) {
          if (file.get('addShallowCompareImport')) {
            const shallowCompareImportDeclaration = t.importDeclaration([
              t.importDefaultSpecifier(t.identifier('shallowCompare')),
            ], t.stringLiteral('react-addons-shallow-compare'));
            node.body.unshift(shallowCompareImportDeclaration);
          }
        },
      },

      ClassDeclaration(path, { file }) {
        if (superclassIsPureComponent(path)) {
          const superclassPath = path.get('superClass');

          // Replace the superclass
          superclassPath.replaceWith(buildPureOrNormalSuperclass());

          // Only add an SCU if one doesn't already exist
          const existingSCU = path.get('body').get('body').find((
            p => p.isClassMethod() && p.get('key').node.name === 'shouldComponentUpdate'
          ));

          if (!existingSCU) {
            file.set('addShallowCompareImport', true);
            path.get('body').unshiftContainer('body', buildShouldComponentUpdate());
          }
        }
      },
    },
  };
};
<|endoftext|>


<commit_before>console.log('This would be the main JS file.');
<commit_msg>Update main.js<commit_after>console.log('This is the main JS file.');
<|endoftext|>


<commit_before>console.log("Main JS file loaded");

/*
Token Object Structure
{
  value: the literal char for the token.
  type: the type of token it is. Example: Type, Char, Boolean.
  line: the line it was found on.
  pos: the position on the above line it was found at.
}
*/

//Globals
OUTPUT = null;
INPUT = null;
INPUT_LINES = null;
TOKENS = [];

RE_TYPE = /^(int|string|boolean)/g;
RE_KEYWORD = /^(if|while|print)/g;
RE_BOOLEAN = /^(true|false)/g;

function init(){
  $('#inputTextArea').linedtextarea();
  resetPage();
}

function resetPage(){
  OUTPUT = $('#outputTextArea');
  INPUT = $('#inputTextArea');
  INPUT_LINES = INPUT.val().split("\n");
  TOKENS = [];
  OUTPUT.empty();  // Clear the output text area.
}

function test(){
  resetPage();
  lexer();
  parser();
}

function parser(){
  bracesCheck();
}

function lexer(){
  checkInvalids();
  generateTokens();
}

function bracesCheck(){
  var index = 0;
  var stack = new Array();
  var re_braces = /[\{\(]/g;

  for (index = 0; index < TOKENS.length; index++){
    current_token = TOKENS[index].value;
    if(current_token.match(re_braces) != null) stack.push(current_token);
    else if(current_token == "}") {
      if(stack.length < 1) raiseFatalError("Unmatched } on Line: " + TOKENS[index - 1].line + ", Position: " + TOKENS[index - 1].pos);
      if(stack.pop() != "{") raiseFatalError("Unexpected } found on Line: " + TOKENS[index].line + ", Position: " + TOKENS[index].pos);
    }
    else if(current_token == ")") {
      if(stack.length < 1) raiseFatalError("Unmatched ) on Line: " + TOKENS[index - 1].line + ", Position: " + TOKENS[index - 1].pos);
      if(stack.pop() != "(") raiseFatalError("Unexpected ) found on Line: " + TOKENS[index].line + ", Position: " + TOKENS[index].pos);
    }
  }
  if(stack.length > 0) raiseFatalError("Unmatched " + stack.pop() + " on Line: " + TOKENS[index - 1].line + ", Position: " + TOKENS[index - 1].pos);
}

function generateTokens(){
  var line = 0;
  var pos = 0;
  var current_token;
  var EOF_found = false;
  var string_mode = false;

  var re_blocks = /[\{\}\(\)]/g;
  var re_digits = /[0-9]/g;
  var re_chars = /[a-z]/g;
  var re_string = /[ a-z]/g;

  while(line < INPUT_LINES.length){
    while(pos < INPUT_LINES[line].length){
      current_token = INPUT_LINES[line].charAt(pos);

      if(string_mode == false){
        if (current_token.match(/\s/g)); // Strip whitespace when not in string mode.
        else if(current_token.match(re_blocks) != null) generateToken(current_token, "Block", line, pos);
        else if(current_token.match(re_digits) != null) generateToken(current_token, "Digit", line, pos);
        else if(current_token == "+") generateToken(current_token, "IntOp", line, pos);

        else if(current_token == "\"") {
          generateToken(current_token, "Quote", line, pos);
          string_mode = true;
        }

        else if (current_token == "=") {
          if(INPUT_LINES[line].charAt(pos + 1) == "=") {
            generateToken("==", "BoolOp", line, pos);
            pos++;
          }
          else generateToken(current_token, "Assignment", line, pos);
        }

        else if (current_token == "!") {
          if(INPUT_LINES[line].charAt(pos + 1) == "=") {
            generateToken("!=", "BoolOp", line, pos);
            pos++;
          }
          else raiseFatalError("Invalid symbol at line: " + line); // This should never be reached due to checkInvalids.
        }

        else if(current_token.match(re_chars) != null) pos = pos + keywordCheck(current_token, line, pos);

        else if(current_token == "$") {generateToken(current_token, "EOF", line, pos); EOF_found = true;}

        // If you reaches here, something has gone horribly wrong.
        else raiseFatalError("Invalid symbol: " + current_token + " at line " + line);
      }
      else{ //String Mode
        if(current_token.match(re_string) != null) generateToken(current_token, "Char", line, pos);
        else if(current_token == "\"") { // Ending Quote
          generateToken(current_token, "Quote", line, pos);
          string_mode = false;
        }
        else if(current_token.match(re_string) == null) raiseFatalError("Invalid string on line " + line + ". Only characters and space allowed.");
      }
      pos++;
    }
    pos = 0;
    line++;
  }

  if(EOF_found == false) {
    raiseWarning("Reached EOF but $ not found. Added and continuing to parse.");
    generateToken(current_token, "EOF", line, pos);
  }
  console.log(printTokens());
  writeOutput("Lexer completed without errors.");
}

function keywordCheck(letter, line, pos){
  // keywordCheck returns how far to move the position pointer.
  var temp = INPUT_LINES[line].substr(pos);
  if(temp.match(RE_TYPE) != null){
    if(letter == "b"){
      generateToken("boolean", "Type", line, pos);
      return 6;
    }
    else if(letter == "i"){
      generateToken("int", "Type", line, pos);
      return 2;
    }
    else if(letter == "s"){
      generateToken("string", "Type", line, pos);
      return 5;
    }
  }
  else if (temp.match(RE_BOOLEAN) != null){
    if(letter == "f"){
      generateToken("false", "BoolVal", line, pos);
      return 4;
    }
    else if(letter == "t"){
      generateToken("true", "BoolVal", line, pos);
      return 3;
    }
  }
  else if (temp.match(RE_KEYWORD) != null){
    if(letter == "i"){
      generateToken("if", "Keyword", line, pos);
      return 1;
    }
    else if(letter == "p"){
      generateToken("print", "Keyword", line, pos);
      return 4;
    }
    else if(letter == "w"){
      generateToken("while", "Keyword", line, pos);
      return 4;
    }
  }
  generateToken(letter, "Char", line, pos);
  return 0;
}

function generateToken(val, given_type, given_line, given_pos){
  TOKENS.push({value:val, type:given_type, line:given_line + 1, pos:given_pos + 1});
}

function printTokens(printTypes){
  printTypes = printTypes || false; // Hacky way of optional parameter
  var output = [];
  var index;
  for(index = 0; index < TOKENS.length; index++){
    if(printTypes) output.push("" + TOKENS[index].value + ", " + TOKENS[index].type);
    else output.push(TOKENS[index].value);
  }
  return output;
}

function checkInvalids(){
  var re_invalid = /.*([=]{3,}|(!={2,})|\+{2,}|!(?!=)|[^a-z0-9\+\{\}\(\)"!=$ ]).*/g;
  var line = 0;
  var invalid_check;

  while(line < INPUT_LINES.length){
    invalid_check = re_invalid.exec(INPUT_LINES[line]);
    if(invalid_check != null) {
      console.log(invalid_check);
      raiseFatalError("Invalid symbol: " + invalid_check[1] + " found at line: " + (line + 1)
                      + " position: " + (re_invalid.lastIndex - invalid_check[1].length));
    }
    line++;
  }
}

function writeOutput(message){
  OUTPUT.append(message + "\n");
}

function raiseWarning(message){
  message = "Warning: " + message;
  writeOutput(message);
}

function raiseFatalError(message){
  message = "Fatal Error: " + message;
  writeOutput(message);
  throw new Error(message);
}<commit_msg>fixed auto append EOF to appended the actual EOF char<commit_after>console.log("Main JS file loaded");

/*
Token Object Structure
{
  value: the literal char for the token.
  type: the type of token it is. Example: Type, Char, Boolean.
  line: the line it was found on.
  pos: the position on the above line it was found at.
}
*/

//Globals
OUTPUT = null;
INPUT = null;
INPUT_LINES = null;
TOKENS = [];

RE_TYPE = /^(int|string|boolean)/g;
RE_KEYWORD = /^(if|while|print)/g;
RE_BOOLEAN = /^(true|false)/g;

function init(){
  $('#inputTextArea').linedtextarea();
  resetPage();
}

function resetPage(){
  OUTPUT = $('#outputTextArea');
  INPUT = $('#inputTextArea');
  INPUT_LINES = INPUT.val().split("\n");
  TOKENS = [];
  OUTPUT.empty();  // Clear the output text area.
}

function test(){
  resetPage();
  lexer();
  parser();
}

function parser(){
  bracesCheck();
}

function lexer(){
  checkInvalids();
  generateTokens();
}

function bracesCheck(){
  var index = 0;
  var stack = new Array();
  var re_braces = /[\{\(]/g;

  for (index = 0; index < TOKENS.length; index++){
    current_token = TOKENS[index].value;
    if(current_token.match(re_braces) != null) stack.push(current_token);
    else if(current_token == "}") {
      if(stack.length < 1) raiseFatalError("Unmatched } on Line: " + TOKENS[index - 1].line + ", Position: " + TOKENS[index - 1].pos);
      if(stack.pop() != "{") raiseFatalError("Unexpected } found on Line: " + TOKENS[index].line + ", Position: " + TOKENS[index].pos);
    }
    else if(current_token == ")") {
      if(stack.length < 1) raiseFatalError("Unmatched ) on Line: " + TOKENS[index - 1].line + ", Position: " + TOKENS[index - 1].pos);
      if(stack.pop() != "(") raiseFatalError("Unexpected ) found on Line: " + TOKENS[index].line + ", Position: " + TOKENS[index].pos);
    }
  }
  if(stack.length > 0) raiseFatalError("Unmatched " + stack.pop() + " on Line: " + TOKENS[index - 1].line + ", Position: " + TOKENS[index - 1].pos);
}

function generateTokens(){
  var line = 0;
  var pos = 0;
  var current_token;
  var EOF_found = false;
  var string_mode = false;

  var re_blocks = /[\{\}\(\)]/g;
  var re_digits = /[0-9]/g;
  var re_chars = /[a-z]/g;
  var re_string = /[ a-z]/g;

  while(line < INPUT_LINES.length){
    while(pos < INPUT_LINES[line].length){
      current_token = INPUT_LINES[line].charAt(pos);

      if(string_mode == false){
        if (current_token.match(/\s/g)); // Strip whitespace when not in string mode.
        else if(current_token.match(re_blocks) != null) generateToken(current_token, "Block", line, pos);
        else if(current_token.match(re_digits) != null) generateToken(current_token, "Digit", line, pos);
        else if(current_token == "+") generateToken(current_token, "IntOp", line, pos);

        else if(current_token == "\"") {
          generateToken(current_token, "Quote", line, pos);
          string_mode = true;
        }

        else if (current_token == "=") {
          if(INPUT_LINES[line].charAt(pos + 1) == "=") {
            generateToken("==", "BoolOp", line, pos);
            pos++;
          }
          else generateToken(current_token, "Assignment", line, pos);
        }

        else if (current_token == "!") {
          if(INPUT_LINES[line].charAt(pos + 1) == "=") {
            generateToken("!=", "BoolOp", line, pos);
            pos++;
          }
          else raiseFatalError("Invalid symbol at line: " + line); // This should never be reached due to checkInvalids.
        }

        else if(current_token.match(re_chars) != null) pos = pos + keywordCheck(current_token, line, pos);

        else if(current_token == "$") {generateToken(current_token, "EOF", line, pos); EOF_found = true;}

        // If you reaches here, something has gone horribly wrong.
        else raiseFatalError("Invalid symbol: " + current_token + " at line " + line);
      }
      else{ //String Mode
        if(current_token.match(re_string) != null) generateToken(current_token, "Char", line, pos);
        else if(current_token == "\"") { // Ending Quote
          generateToken(current_token, "Quote", line, pos);
          string_mode = false;
        }
        else if(current_token.match(re_string) == null) raiseFatalError("Invalid string on line " + line + ". Only characters and space allowed.");
      }
      pos++;
    }
    pos = 0;
    line++;
  }

  if(EOF_found == false) {
    raiseWarning("Reached EOF but $ not found. Added and continuing to parse.");
    generateToken("$", "EOF", line, pos);
  }
  console.log(printTokens());
  writeOutput("Lexer completed without errors.");
}

function keywordCheck(letter, line, pos){
  // keywordCheck returns how far to move the position pointer.
  var temp = INPUT_LINES[line].substr(pos);
  if(temp.match(RE_TYPE) != null){
    if(letter == "b"){
      generateToken("boolean", "Type", line, pos);
      return 6;
    }
    else if(letter == "i"){
      generateToken("int", "Type", line, pos);
      return 2;
    }
    else if(letter == "s"){
      generateToken("string", "Type", line, pos);
      return 5;
    }
  }
  else if (temp.match(RE_BOOLEAN) != null){
    if(letter == "f"){
      generateToken("false", "BoolVal", line, pos);
      return 4;
    }
    else if(letter == "t"){
      generateToken("true", "BoolVal", line, pos);
      return 3;
    }
  }
  else if (temp.match(RE_KEYWORD) != null){
    if(letter == "i"){
      generateToken("if", "Keyword", line, pos);
      return 1;
    }
    else if(letter == "p"){
      generateToken("print", "Keyword", line, pos);
      return 4;
    }
    else if(letter == "w"){
      generateToken("while", "Keyword", line, pos);
      return 4;
    }
  }
  generateToken(letter, "Char", line, pos);
  return 0;
}

function generateToken(val, given_type, given_line, given_pos){
  TOKENS.push({value:val, type:given_type, line:given_line + 1, pos:given_pos + 1});
}

function printTokens(printTypes){
  printTypes = printTypes || false; // Hacky way of optional parameter
  var output = [];
  var index;
  for(index = 0; index < TOKENS.length; index++){
    if(printTypes) output.push("" + TOKENS[index].value + ", " + TOKENS[index].type);
    else output.push(TOKENS[index].value);
  }
  return output;
}

function checkInvalids(){
  var re_invalid = /.*([=]{3,}|(!={2,})|\+{2,}|!(?!=)|[^a-z0-9\+\{\}\(\)"!=$ ]).*/g;
  var line = 0;
  var invalid_check;

  while(line < INPUT_LINES.length){
    invalid_check = re_invalid.exec(INPUT_LINES[line]);
    if(invalid_check != null) {
      console.log(invalid_check);
      raiseFatalError("Invalid symbol: " + invalid_check[1] + " found at line: " + (line + 1)
                      + " position: " + (re_invalid.lastIndex - invalid_check[1].length));
    }
    line++;
  }
}

function writeOutput(message){
  OUTPUT.append(message + "\n");
}

function raiseWarning(message){
  message = "Warning: " + message;
  writeOutput(message);
}

function raiseFatalError(message){
  message = "Fatal Error: " + message;
  writeOutput(message);
  throw new Error(message);
}<|endoftext|>


<commit_before>'use strict';

'use strict';

var http = require('http'),
    https = require('https');

function faviconApp(req, res) {
    if (req.url === '/favicon.ico') {
        res.writeHead(204);
        res.end();
        return;
    }
    console.log('GET', req.url, req.headers.origin || '',
        req.connection.remoteAddress || '', req.headers['x-forwarded-for'] || '');
    var domain = req.url.substr(1);
    if (domain.indexOf('.') < 0 || domain.indexOf('/') >= 0) {
        res.writeHead(404, {'Content-Type': 'text/plain'});
        return res.end('Usage: GET /domain.com');
    }
    loadResource('http://' + domain + '/favicon.ico', res);
}

function loadResource(url, res, redirectNum) {
    var proto = url.lastIndexOf('https', 0) === 0 ? https : http;
    var serverReq = proto.get(url, function(srvRes) {
        if (srvRes.statusCode > 300 && srvRes.statusCode < 400 && srvRes.headers.location) {
            if (redirectNum > 3) {
                res.writeHead(404, {'Content-Type': 'text/plain'});
                return res.end('Too many redirects');
            }
            return loadResource(srvRes.headers.location, res, (redirectNum || 0) + 1);
        } else if (srvRes.statusCode === 200) {
            res.writeHead(200, {'Content-Type': 'image/x-icon', 'Access-Control-Allow-Origin': '*'});
            srvRes.pipe(res, {end: true});
        } else {
            res.writeHead(404, {'Content-Type': 'text/plain'});
            return res.end('Status ' + srvRes.statusCode);
        }
    });
    serverReq.on('error', function(e) {
        res.writeHead(404, {'Content-Type': 'text/plain'});
        return res.end(e.message);
    });
    serverReq.end();
}

module.exports = faviconApp;
<commit_msg>index<commit_after>'use strict';

'use strict';

var http = require('http'),
    https = require('https');

function faviconApp(req, res) {
    if (req.url === '/favicon.ico') {
        res.writeHead(204);
        res.end();
        return;
    }
    if (req.url === '/') {
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end('This is a service for loading website favicon with CORS\n\n' +
            'Usage: GET /domain.com\n' +
            'Questions, source code: https://github.com/antelle/favicon-proxy');
        return;
    }
    console.log('GET', req.url, req.headers.origin || '',
        req.connection.remoteAddress || '', req.headers['x-forwarded-for'] || '');
    var domain = req.url.substr(1);
    if (domain.indexOf('.') < 0 || domain.indexOf('/') >= 0) {
        res.writeHead(404, {'Content-Type': 'text/plain'});
        return res.end('Usage: GET /domain.com');
    }
    loadResource('http://' + domain + '/favicon.ico', res);
}

function loadResource(url, res, redirectNum) {
    var proto = url.lastIndexOf('https', 0) === 0 ? https : http;
    var serverReq = proto.get(url, function(srvRes) {
        if (srvRes.statusCode > 300 && srvRes.statusCode < 400 && srvRes.headers.location) {
            if (redirectNum > 3) {
                res.writeHead(404, {'Content-Type': 'text/plain'});
                return res.end('Too many redirects');
            }
            return loadResource(srvRes.headers.location, res, (redirectNum || 0) + 1);
        } else if (srvRes.statusCode === 200) {
            res.writeHead(200, {'Content-Type': 'image/x-icon', 'Access-Control-Allow-Origin': '*'});
            srvRes.pipe(res, {end: true});
        } else {
            res.writeHead(404, {'Content-Type': 'text/plain'});
            return res.end('Status ' + srvRes.statusCode);
        }
    });
    serverReq.on('error', function(e) {
        res.writeHead(404, {'Content-Type': 'text/plain'});
        return res.end(e.message);
    });
    serverReq.end();
}

module.exports = faviconApp;
<|endoftext|>


<commit_before>var defaultOptions = {
  publicDrawer: 'mdlUiAppDrawerPublic',
  drawer: 'mdlUiAppDrawer',

  menuItems: [
    //{label: 'About', action: '/about'}
  ],

  search: false,
  searchSessionName: 'search'

};

// TODO: change usage to resolveOption(...)
var options = _.clone(defaultOptions);

/**
 * Resolve option from:
 *
 * 1. data context
 * 2. default MdlUi options
 *
 * @param context
 * @param name
 * @returns {*}
 */
function resolveOption(context, name) {
  // 1. resolve search from data context
  var option = context && context[name];
  if (_.isFunction(option)) {
    option = option.call();
  }

  // 2. resolve search from MdlUi options
  if (option === undefined) {
    option = MdlUi.options[name];
    if (_.isFunction(option)) {
      option = option.call();
    }
  }

  // 3. resolve from defaultOptions
  if(option===undefined) {
    option = defaultOptions[name];
    if (_.isFunction(option)) {
      option = option.call();
    }
  }

  return option;
}

Template.mdlUiAppLayout.helpers({
  title() {
    return resolveOption(this, 'title');
  },

  menuItems() {
    return resolveOption(this, 'menuItems');
  },

  search() {
    return resolveOption(this, 'search');
  },

  drawerTemplate() {
    var name = 'publicDrawer';
    if (Meteor.user()) {
      name = 'drawer';
    }

    return resolveOption(this, name);
  },

  searchValue() {
    return Session.get(options.searchSessionName);
  }
});

Template.mdlUiAppLayout.events({
  'click .mdl-menu__item'() {
    Router.go(this.action);
  },

  'keydown .search .mdl-textfield__input': _.throttle(function (e) {
    Session.set(options.searchSessionName, $(e.target).val());
  }, 300)

});
<commit_msg>Support menu.action as function<commit_after>var defaultOptions = {
  publicDrawer: 'mdlUiAppDrawerPublic',
  drawer: 'mdlUiAppDrawer',

  menuItems: [
    //{label: 'About', action: '/about'}
  ],

  search: false,
  searchSessionName: 'search'

};

// TODO: change usage to resolveOption(...)
var options = _.clone(defaultOptions);

/**
 * Resolve option from:
 *
 * 1. data context
 * 2. default MdlUi options
 *
 * @param context
 * @param name
 * @returns {*}
 */
function resolveOption(context, name) {
  // 1. resolve search from data context
  var option = context && context[name];
  if (_.isFunction(option)) {
    option = option.call();
  }

  // 2. resolve search from MdlUi options
  if (option === undefined) {
    option = MdlUi.options[name];
    if (_.isFunction(option)) {
      option = option.call();
    }
  }

  // 3. resolve from defaultOptions
  if(option===undefined) {
    option = defaultOptions[name];
    if (_.isFunction(option)) {
      option = option.call();
    }
  }

  return option;
}

Template.mdlUiAppLayout.helpers({
  title() {
    return resolveOption(this, 'title');
  },

  menuItems() {
    return resolveOption(this, 'menuItems');
  },

  search() {
    return resolveOption(this, 'search');
  },

  drawerTemplate() {
    var name = 'publicDrawer';
    if (Meteor.user()) {
      name = 'drawer';
    }

    return resolveOption(this, name);
  },

  searchValue() {
    return Session.get(options.searchSessionName);
  }
});

Template.mdlUiAppLayout.events({
  'click .mdl-menu__item'() {
    if(_.isFunction(this.action)) {
      this.action();
    } else {
      Router.go(this.action);
    }
  },

  'keydown .search .mdl-textfield__input': _.throttle(function (e) {
    Session.set(options.searchSessionName, $(e.target).val());
  }, 300)

});
<|endoftext|>


<commit_before>function readFile(path) {
    var request = new XMLHttpRequest();
    request.open("GET", path, false);
    request.send(null);
    return request.responseText;
}

d = new Date();
$(document).ready(function () {
    $('#container').highcharts({
        chart: {
            renderTo: "graph"
        },
        title: {
            text: 'Team score progression',
            x: -20
        },
        xAxis: {
            type: "datetime",
            dateTimeLabelFormats: { // don't display the dummy year
                month: '%e. %b',
                year: '%b'
            }
        },
        yAxis: {
            title: {
                text: 'Points'
            },
            plotLines: [{
                value: 0,
                width: 1,
                color: '#808080'
            }],
            floor: 0
        },
        tooltip: {
            valueSuffix: 'points'
        },
        legend: {
            enabled: false
        },
        plotOptions: {
            spline: {
                marker: {
                    enabled: true
                }
            }
        },
        //minTickInterval: 86400000,
        //min: 1434312000000,
        series: [{
            pointStart: 1434312000000,
            pointInterval: 86400000,
            name: 'foo',
            data: [
                [1434312000000, 0 ],
                [1434322800000, 10],
                [1434320320603, 25],
                [1434320329545, 55],
                [1434320329545, 95],
                [d.getTime(), 200]

            ]
        }]
    });
})

<commit_msg>Read scores and times from file now<commit_after>// Creds to the helpful guys over at stackoverflow
function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
    results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

function readFile(path) {
    var request = new XMLHttpRequest();
    request.open("GET", path, false);
    request.send(null);
    return request.responseText;
}

function getTeamInfo(data, team) {
    data = data.split("\n");
    for (i = 0; i < data.length; i++) {
        temp = data[i].split("||&&||");
        if (temp[0] === team) {
            return temp;
        }
    }
}

function getTeamData(team) {
    data = [];
    scores = readFile("accounts/scores.txt");
    scores = getTeamInfo(scores, team);
    scores = scores.slice(1);
    for (i = 0; i < scores.length; i+=2) {
        data.push([scores[i], scores[i+1]]);
    }
    return data;
}
var team = getParameterByName("tid");
d = new Date();
$(document).ready(function () {
    $('#container').highcharts({
        chart: {
            renderTo: "graph"
        },
        title: {
            text: 'Team score progression',
            x: -20
        },
        xAxis: {
            type: "datetime",
            dateTimeLabelFormats: { // don't display the dummy year
                month: '%e. %b',
                year: '%b'
            },
            max: Date.UTC(2015, 6, 22)
        },
        yAxis: {
            title: {
                text: 'Points'
            },
            plotLines: [{
                value: 0,
                width: 1,
                color: '#808080'
            }],
            floor: 0
        },
        tooltip: {
            valueSuffix: 'points'
        },
        legend: {
            enabled: false
        },
        plotOptions: {
            spline: {
                marker: {
                    enabled: true
                }
            }
        },
        series: [{
            pointStart: 1434312000000,
            pointInterval: 86400000,
            name: 'foo',
            data: getTeamData(team)
        }]
    });
})
<|endoftext|>


<commit_before>/**
 * String.sprintf
 *
 * A sprintf function in mootools.
 *
 * Copyright (c) MArc J. Schmidt, <http://marcschmidt.name/>
 *
 */

(function(){

    function sprintf(){

        var args   = arguments,
            text   = this,         //buffer of origin text
            arg,                   //current argument item
            found,                 //position of current % char
            cursorPosition = 0,    //position of current position of origin text
            result = '',           //buffer of parsed text
            code   = '',           //buffer for char(s) behind %
            opt    = '',           //buffer for optional code parameter
            number = 0,            //buffer for the number value
            autoPosition = 0;      //position of current item position in args

        while ((found = text.indexOf('%', cursorPosition)) !== -1){

            result += text.substring(cursorPosition, found);

            code = text.substr(found+1).match(/(?:([0-9]+)\$|)('.+\-?|\-?[0-9\.]*|)([%bcdeEufgGosxX])/);
            // ->
            //  1 = argument numbering
            //  2 = optional parameter
            //  3 = code
            //
            console.log(code);

            if (!code){
                cursorPosition++;
                continue;
            }

            cursorPosition = found+1+code[0].length;

            //if argument numbering/swapping
            if (code[1]){
                arg = args[parseInt(code[1])-1];
            } else if (code[3] !== '%'){
                //default code, so we move position + 1
                arg = args[autoPosition++];
            }

            //d, f, u
            if (code[3] == 'd' || code[3] == 'f' || code[3] == 'u'){
                number = Number.from(arg) || 0;
                if (code[2] && (opt = parseInt(code[2])-String.from(number.toFixed(0)).length) > 0)
                    result += '0'.repeat(opt);
            }

            if (code[3] == 's'){
                var char = '';
                if (code[2]){

                    if (code[2].substr(0,1) == '\''){
                        char = code[2].substr(1,1);
                        opt = 2;
                    } else {
                        opt = code[2].search(/[\-1-9]/);
                        char = code[2].substr(0, opt) || ' ';
                    }
                    console.log(code[2]);
                    console.log(char);

                    opt = code[2].substr(opt, code[2].length);

                    //truncate
                    if (parseFloat(opt)%1)
                        arg = String.from(arg).substr(0, parseInt(opt.substr(opt.indexOf('.')+1)));

                    opt = parseFloat(opt);

                    if (opt < 0 && (opt*-1) - arg.length > 0)
                        result += char.repeat( parseInt((opt*-1) - arg.length) );
                }

                result += String.from(arg);

                if (opt > 0 && opt - arg.length > 0)
                    result += char.repeat( parseInt(opt - arg.length) );

                continue;
            }

            switch(code[3]){
                case '%':
                    result += '%'; break;
                case 'b':
                    result += (Number.from(arg) || 0).toString(2); break;
                case 'c':
                    result += String.fromCharCode(Number.from(arg) || 0); break;
                case 'd':
                    result += number.toFixed(0); break;
                case 'e':
                    result += (Number.from(arg) || 0).toExponential(); break;
                case 'E':
                    result += (Number.from(arg) || 0).toExponential().toUpperCase(); break;
                case 'u':
                    result += number >>> 0; break;
                case 'f':
                    result += number.toFixed((code[2]?code[2].substr(code[2].indexOf('.')+1):6)); break;
                case 'o':
                    result += (Number.from(arg) || 0).toString(8); break;
                case 'x':
                    result += (Number.from(arg) || 0).toString(16); break;
                case 'X':
                    result += (Number.from(arg) || 0).toString(16).toUpperCase(); break;
            }

        }

        result += text.substr(cursorPosition);

        return result;
    }

    String.implement({
        'sprintf': sprintf
    });

})();<commit_msg>Update file header<commit_after>/*
---
description: String.sprintf

license: MIT-style

authors:
- MArc J. Schmidt

requires:
- Core
- More 'String.Extra'

provides: [String.sprintf]
*/

/**
 * String.sprintf
 *
 * A sprintf function in mootools.
 *
 * Copyright (c) MArc J. Schmidt, <http://marcschmidt.name/>
 *
 */
(function(){

    function sprintf(){

        var args   = arguments,
            text   = this,         //buffer of origin text
            arg,                   //current argument item
            found,                 //position of current % char
            cursorPosition = 0,    //position of current position of origin text
            result = '',           //buffer of parsed text
            code   = '',           //buffer for char(s) behind %
            opt    = '',           //buffer for optional code parameter
            number = 0,            //buffer for the number value
            autoPosition = 0;      //position of current item position in args

        while ((found = text.indexOf('%', cursorPosition)) !== -1){

            result += text.substring(cursorPosition, found);

            code = text.substr(found+1).match(/(?:([0-9]+)\$|)('.+\-?|\-?[0-9\.]*|)([%bcdeEufgGosxX])/);
            // ->
            //  1 = argument numbering
            //  2 = optional parameter
            //  3 = code
            //
            console.log(code);

            if (!code){
                cursorPosition++;
                continue;
            }

            cursorPosition = found+1+code[0].length;

            //if argument numbering/swapping
            if (code[1]){
                arg = args[parseInt(code[1])-1];
            } else if (code[3] !== '%'){
                //default code, so we move position + 1
                arg = args[autoPosition++];
            }

            //d, f, u
            if (code[3] == 'd' || code[3] == 'f' || code[3] == 'u'){
                number = Number.from(arg) || 0;
                if (code[2] && (opt = parseInt(code[2])-String.from(number.toFixed(0)).length) > 0)
                    result += '0'.repeat(opt);
            }

            if (code[3] == 's'){
                var char = '';
                if (code[2]){

                    if (code[2].substr(0,1) == '\''){
                        char = code[2].substr(1,1);
                        opt = 2;
                    } else {
                        opt = code[2].search(/[\-1-9]/);
                        char = code[2].substr(0, opt) || ' ';
                    }
                    console.log(code[2]);
                    console.log(char);

                    opt = code[2].substr(opt, code[2].length);

                    //truncate
                    if (parseFloat(opt)%1)
                        arg = String.from(arg).substr(0, parseInt(opt.substr(opt.indexOf('.')+1)));

                    opt = parseFloat(opt);

                    if (opt < 0 && (opt*-1) - arg.length > 0)
                        result += char.repeat( parseInt((opt*-1) - arg.length) );
                }

                result += String.from(arg);

                if (opt > 0 && opt - arg.length > 0)
                    result += char.repeat( parseInt(opt - arg.length) );

                continue;
            }

            switch(code[3]){
                case '%':
                    result += '%'; break;
                case 'b':
                    result += (Number.from(arg) || 0).toString(2); break;
                case 'c':
                    result += String.fromCharCode(Number.from(arg) || 0); break;
                case 'd':
                    result += number.toFixed(0); break;
                case 'e':
                    result += (Number.from(arg) || 0).toExponential(); break;
                case 'E':
                    result += (Number.from(arg) || 0).toExponential().toUpperCase(); break;
                case 'u':
                    result += number >>> 0; break;
                case 'f':
                    result += number.toFixed((code[2]?code[2].substr(code[2].indexOf('.')+1):6)); break;
                case 'o':
                    result += (Number.from(arg) || 0).toString(8); break;
                case 'x':
                    result += (Number.from(arg) || 0).toString(16); break;
                case 'X':
                    result += (Number.from(arg) || 0).toString(16).toUpperCase(); break;
            }

        }

        result += text.substr(cursorPosition);

        return result;
    }

    String.implement({
        'sprintf': sprintf
    });

})();<|endoftext|>


<commit_before>//Session Vars
sessionStorage.setItem('selected', sessionStorage.getItem('selected') || 'today');

//When everything is ready
$(document).ready(function() {
	ui.initLoad();
	ui.reload();
});

var ui = {
	initLoad: function() {
		//Buttons
		$('#smartlists').html('
Focus

');
		ui.lists.draw('today');
		ui.lists.draw('next');
		ui.lists.draw('all');

		$$.document.append(ui.buttons.taskAddBTN, $('#tasks .panel'));

		//Splitter
		$('#content').splitter({sizeLeft: true});
		var height = $(window).height(),
			width = $(window).width()

		$(window).resize(function() {
			//Causes lag without it?
			if (height != $(window).height() || width != $(window).width()) {
				//Redefines
				height = $(window).height(),
				width = $(window).width()

				$('#content').trigger('resize');
			}
		});
	},
	reload: function() {
		//Populates Template
		$('#lists').html('
Lists

');
		$$.document.append(ui.buttons.listAddBTN, $('#lists h2'));
		for (var i=0; i<core.storage.lists.order.length; i++) {
			ui.lists.draw(core.storage.lists.order[i]);
		}
		//Simulates Click on selected list
		$('#L' + sessionStorage.getItem('selected')).click();
	},
	tasks: {
		//Returns a task model
		draw: function(taskId) {
			var obj = $$(ui.templates.taskTemplate, {id: taskId, content: core.storage.tasks[taskId].content});
			return obj;
		}
	},
	lists: {
		//Draws a list to the DOM
		draw: function(listId) {
			if (typeof(listId) == 'string') {
				var obj = $$(ui.templates.listTemplate, {id: listId, name: listId});
				$$.document.append(obj, $('#smartlists ul'));
			} else {
				var obj = $$(ui.templates.listTemplate, {id: listId, name: core.storage.lists.items[listId].name});
				$$.document.append(obj, $('#lists ul'));
			}

			$(obj.view.$()).attr('id', 'L' + obj.model.get('id'))
		}
	},
	templates: {
		taskTemplate: $$({}, '

', {
			'click &': function() {
				$('#tasks .selected').removeClass('selected');
				$(this.view.$()).addClass('selected');
			},
			'dblclick &': function() {
				//Cache the selector
				var view = $(this.view.$());

				//Checks if it's expanded & if it isn't expand it.
				if (!view.hasClass('expanded')) {
					view.addClass('expanded').height(view.height() + view.removeClass('selected').html('New Task

Something
Something Else
Bleh
').children('.hidden').show(0).height());
				} else {
					//Collapses
					view.removeClass('expanded').css('height', '');
					setTimeout(function() {
						view.children('.hidden').remove()
					}, 150);
				}
			}
		}),
		listTemplate: $$({}, '

', {
			'click &': function() {
				//Selected List
				sessionStorage.setItem('selected', this.model.get('id'));
				$('#sidebar .selected').removeClass('selected');
				$(this.view.$()).addClass('selected');

				//Gets list id & populates
				$('#tasks .content').html('
' + this.model.get('name') + '

')
				var tasks = core.list(this.model.get('id')).populate();

				//Loops and adds each task to a tmp view
				var tmpView = $$({});
				for (var i=0; i<tasks.length; i++) {
					tmpView.append(ui.tasks.draw(tasks[i]));
				}
				$$.document.append(tmpView, $('#tasks ul'));
			}
		})
	},
	buttons: {
		//Buttons
		listAddBTN: $$({name: 'Add List'}, '<button data-bind="name"/>', {
			'click &': function() {
				//Adds a list with the core
				var listId = core.list().add('New List');
				ui.lists.draw(listId);

				//Selects List
				$('#L' + listId).click();
			}
		}),
		taskAddBTN: $$({name: 'Add Task'}, '<button data-bind="name"/>', {
			'click &': function() {
				if (sessionStorage.getItem('selected') != 'all') {
					//Adds a task with the core
					var taskId = core.task().add('New Task', sessionStorage.getItem('selected'));
					$$.document.append(ui.tasks.draw(taskId), $('#tasks ul'));
				}
			}
		})
	}
}
<commit_msg>Speed Improvements<commit_after>/* Nitro Core
 *
 * Copyright (C) 2012 Caffeinated Code <http://caffeinatedco.de>
 * Copyright (C) 2012 Jono Cooper
 * Copyright (C) 2012 George Czabania
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 * Neither the name of Caffeinated Code nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

//Session Vars
sessionStorage.setItem('selected', sessionStorage.getItem('selected') || 'today');

//When everything is ready
$(document).ready(function() {
	//Cache Selectors
	ui.initLoad();
	ui.reload();
});

var ui = {
	initLoad: function() {
		//Buttons
		$('#smartlists').html('
Focus

');
		ui.lists.draw('today');
		ui.lists.draw('next');
		ui.lists.draw('all');

		$$.document.append(ui.buttons.taskAddBTN, $('#tasks .panel'));

		//Splitter
		$('#content').splitter({sizeLeft: true});
		var height = $(window).height(),
			width = $(window).width()

		$(window).resize(function() {
			//Causes lag without it?
			if (height != $(window).height() || width != $(window).width()) {
				//Redefines
				height = $(window).height(),
				width = $(window).width()

				$('#content').trigger('resize');
			}
		});
	},
	reload: function() {
		//Populates Template
		$('#lists').html('
Lists

');
		$$.document.append(ui.buttons.listAddBTN, $('#lists h2'));
		for (var i=0; i<core.storage.lists.order.length; i++) {
			ui.lists.draw(core.storage.lists.order[i]);
		}
		//Simulates Click on selected list
		$('#L' + sessionStorage.getItem('selected')).click();
	},
	lists: {
		//Draws a list to the DOM
		draw: function(listId) {
			if (typeof(listId) == 'string') {
				var obj = $$(ui.templates.listTemplate, {id: listId, name: listId});
				$$.document.append(obj, $('#smartlists ul'));
			} else {
				var obj = $$(ui.templates.listTemplate, {id: listId, name: core.storage.lists.items[listId].name});
				$$.document.append(obj, $('#lists ul'));
			}

			$(obj.view.$()).attr('id', 'L' + obj.model.get('id'))
		}
	},
	templates: {
		taskTemplate: $$(new Object, '

', {
			'click &': function() {
				$('#tasks .selected').removeClass('selected');
				$(this.view.$()).addClass('selected');
			},
			'dblclick &': function() {
				//Cache the selector
				var view = $(this.view.$());

				//Checks if it's expanded & if it isn't expand it.
				if (!view.hasClass('expanded')) {
					view.addClass('expanded').height(view.height() + view.removeClass('selected').html('New Task

Something
Something Else
Bleh
').children('.hidden').show(0).height());
				} else {
					//Collapses
					view.removeClass('expanded').css('height', '');
					setTimeout(function() {
						view.children('.hidden').remove()
					}, 150);
				}
			}
		}),
		listTemplate: $$(new Object, '

', {
			'click &': function() {
				//Selected List
				sessionStorage.setItem('selected', this.model.get('id'));
				$('#sidebar .selected').removeClass('selected');
				$(this.view.$()).addClass('selected');

				//Gets list id & populates
				$('#tasks .content').html('
' + this.model.get('name') + '

')
				var tasks = core.list(this.model.get('id')).populate();

				//Loops and adds each task to a tmp view
				var tmpView = $$(new Object);
				for (var i=0; i<tasks.length; i++) {
					tmpView.append($$(ui.templates.taskTemplate, {id: tasks[i], content: core.storage.tasks[tasks[i]].content}));
				}
				$$.document.append(tmpView, $('#tasks ul'));
			}
		})
	},
	buttons: {
		//Buttons
		listAddBTN: $$({name: 'Add List'}, '<button data-bind="name"/>', {
			'click &': function() {
				//Adds a list with the core
				var listId = core.list().add('New List');
				ui.lists.draw(listId);

				//Selects List
				$('#L' + listId).click();
			}
		}),
		taskAddBTN: $$({name: 'Add Task'}, '<button data-bind="name"/>', {
			'click &': function() {
				if (sessionStorage.getItem('selected') != 'all') {
					//Adds a task with the core
					var taskId = core.task().add('New Task', sessionStorage.getItem('selected'));
					$$.document.append($$(ui.templates.taskTemplate, {id: taskId, content: core.storage.tasks[taskId].content}), $('#tasks ul'));
				}
			}
		})
	}
}
<|endoftext|>