<commit_before>define(['app/geometry', 'leaflet', 'data/pubs'],
function (geo, leaflet, pubsData) {

    /**
     * Set up the Leaflet map and target area.
     *
     * @param {GeoCoord} origin - The map origin.
     * @param {number} circleRadius - The circle radius in metres for target area.
     * @returns {Object} The Leaflet map instance.
     */
    function createMap(origin, circleRadius)
    {
        // The map itself
        var map = leaflet.map('map').setView(origin, 13);

        // Open Street Map attribution
        var osmAttr = '© OpenStreetMap contributors, CC-BY-SA';
        leaflet.tileLayer('http://{s}.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png', {
            attribution: osmAttr
        }).addTo(map);

        // Add the target area circle
        var layer = new leaflet.LayerGroup().addTo(map);
        var circle = new leaflet.circle(
            origin,
            circleRadius,
            {
                color: '#c80',
                opacity: 1,
                fill: false
            });
        layer.addLayer(circle);

        // Add a spot right in the middle
        layer.addLayer(new leaflet.circle(
            origin,
            1.0,
            {
                color: '#f00',
                opacity: 1,
                fillColor: '#f00',
                fillOpacity: 1
            }));

        return map;
    }

    function addFlag(layer, location, title, icon, bubbleContent)
    {
        var marker = leaflet.marker(location, { "title": title, "icon": icon });
        marker.addTo(layer);
        marker.bindPopup(bubbleContent);
    }

    function createLink(url, text)
    {
        return "" + text + "";
    }

    function bubbleHtml(pub)
    {
        var text = "" + pub.name + "";
        if ("link" in pub && pub.link != "")
            text = createLink(pub.link, text);
        if ("comment" in pub && pub.comment)
            text += "
" + pub.comment + "";
        if ("price" in pub && pub.price > 0)
            text += "
Price: £" + pub.price.toFixed(2);
        if ("previous" in pub) {
            var previous = [];
            for (var i = pub.previous.length-1; i >= 0; --i) {
                previous.push(createLink(pub.previous[i].link, pub.previous[i].name));
            }
            text += "
Previously known as " + previous.join(', ') + ".";
        }
        if ("tags" in pub && pub.tags.length > 0) {
            text += "
Tags: " + pub.tags.join(', ');
        }
        return text;
    }

    function setStatusMessage(html)
    {
        document.getElementById('message').innerHTML = html;
    }

    function displayStats(stats)
    {
        setStatusMessage(
            stats.name + ":
"
            + "Low (green): " + stats.format(stats.low) + "
"
            + "Median (blue): " + stats.format(stats.median) + "
"
            + "High (red): " + stats.format(stats.high)
        );
    }

    function createIcons()
    {
        // Setup icons
        var Icon = leaflet.Icon.extend({
            options: {
                iconSize: [25, 39],
                iconAnchor:   [12, 36],
                popupAnchor: [0, -30]
            }
        });
        var icons = ["gold", "blue", "red", "green"];
        return icons.reduce(function(obj, icon) {
            obj[icon] = new Icon({
                iconUrl: "img/marker-"+icon+".png",
                iconRetinaUrl: "img/marker-"+icon+"-2x.png" });
            return obj;
        }, {});
    }

    function addPubsAsLayer(pubs, layerName, icon, layersControl)
    {
        var layer = new leaflet.LayerGroup();
        pubs.forEach(function(pub) {
            addFlag(layer, [pub.lat, pub.lon], pub.name, icon, bubbleHtml(pub));
        });
        layersControl.addOverlay(layer, layerName + ": " + pubs.length);
        return layer;
    }

    function round(value)
    {
        return Math.floor(value + 0.5);
    }

    function colourDualLinear(value, low, high, median)
    {
        var red, green, blue, normalised;
        if (value < low) {
            return "#555555";
        } else if (value < median) {
            normalised = (value - low) / (median-low);
            green = round(255 * (1 - normalised));
            blue = round(255 * normalised);
            red = 0;
        } else {
            normalised = (value - median) / (high-median);
            red = round(255 * normalised);
            blue = round(255 * (1 - normalised));
            green = 0;
        }
        return '#' + ('000000' + ((red << 16) + (green<<8) + blue).toString(16)).slice(-6);
    }

    function priceStats(pubs)
    {
        var low = Number.MAX_VALUE;
        var high = Number.MIN_VALUE;
        var prices = [];
        pubs.forEach(function(pub)
        {
            if ("price" in pub && pub.price > 0) {
                low = Math.min(low, pub.price);
                high = Math.max(high, pub.price);
                prices.push(pub.price);
            }
        });
        prices.sort();
        return {
            name: 'Prices',
            low: low,
            high: high,
            median: prices[Math.floor(prices.length/2)],
            format:function(value) { return "£" + value.toFixed(2); }
        }
    }

    function addVoronoiCellsAsLayer(sites, map, layersControl, stats)
    {
        var layer = new leaflet.LayerGroup().addTo(map);
        sites.forEach(function(site) {
            leaflet.polygon(
                site.polygon.map(function(coord) { return new leaflet.LatLng(coord.lat, coord.lon); }),
                {
                    fillColor: colourDualLinear(site.colour, stats.low, stats.high, stats.median),
                    stroke: false,
                    fillOpacity: 0.5
                }
            ).addTo(layer);
        });
        layersControl.addOverlay(layer, stats.name);
    }

    function hasTag(pub, tags)
    {
        return "tags" in pub && pub.tags.some(function(pubTag) {
            return tags.some(function(tag) {
                return tag == pubTag;
            });
        });
    }

    function initialiseMap()
    {
        setStatusMessage("Calculating...");

        var origin = new geo.GeoCoord(55.94816654144937, -3.1994622945785522);
        var circleRadiusMetres = 1609;

        var map = createMap(origin, circleRadiusMetres);
        var layersControl = leaflet.control.layers(null, null, { position:"bottomright", collapsed: false }).addTo(map);

        var icons = createIcons();

        var todoPubs = [];
        var bloggedPubs = [];
        var excludedPubs = [];

        pubsData.forEach(function(pub) {
            if (pub.link) {
                bloggedPubs.push(pub);
            } else if (hasTag(pub, ['Disqualified','Closed','Student union','Club','Restaurant'])) {
                excludedPubs.push(pub);
            } else {
                todoPubs.push(pub);
            }
        });

        addPubsAsLayer(todoPubs, "Todo (yellow)", icons.gold, layersControl).addTo(map);
        addPubsAsLayer(bloggedPubs, "Visited (green)", icons.green, layersControl).addTo(map);
        addPubsAsLayer(excludedPubs, "Excluded (red)", icons.red, layersControl);

        var stats = priceStats(pubsData);
        displayStats(stats);

        var sites = geo.earthSurfaceVoronoi(bloggedPubs, origin, circleRadiusMetres);
        addVoronoiCellsAsLayer(
            sites.map(function(site) {
                return {
                    polygon: site.polygon,
                    colour: site.loc.price
                };
            }),
            map,
            layersControl,
            stats
        );
    }

    initialiseMap();
});
<commit_msg>Untangle some Leaflet stuff<commit_after>define(['app/geometry', 'leaflet', 'data/pubs'],
function (geo, leaflet, pubsData) {

    /**
     * Set up the Leaflet map and target area.
     *
     * @param {GeoCoord} origin - The map origin.
     * @param {number} circleRadius - The circle radius in metres for target area.
     * @returns {Object} The Leaflet map instance.
     */
    function createMap(origin, circleRadius)
    {
        // The map itself
        var map = leaflet.map('map').setView(origin, 13);

        // Open Street Map attribution
        var osmAttr = '© OpenStreetMap contributors, CC-BY-SA';
        leaflet.tileLayer('http://{s}.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png', {
            attribution: osmAttr
        }).addTo(map);

        var targetAreaLayer = leaflet.layerGroup().addTo(map);

        // Add the target area circle
        targetAreaLayer.addLayer(leaflet.circle(
            origin,
            circleRadius,
            {
                color: '#c80',
                opacity: 1,
                fill: false
            }
        ));

        // Add a spot right in the middle
        targetAreaLayer.addLayer(leaflet.circle(
            origin,
            1.0,
            {
                color: '#f00',
                opacity: 1,
                fillColor: '#f00',
                fillOpacity: 1
            }));

        return map;
    }

    function addFlag(layer, location, title, icon, bubbleContent)
    {
        var marker = leaflet.marker(location, { "title": title, "icon": icon });
        marker.addTo(layer);
        marker.bindPopup(bubbleContent);
    }

    function createLink(url, text)
    {
        return "" + text + "";
    }

    function bubbleHtml(pub)
    {
        var text = "" + pub.name + "";
        if ("link" in pub && pub.link != "")
            text = createLink(pub.link, text);
        if ("comment" in pub && pub.comment)
            text += "
" + pub.comment + "";
        if ("price" in pub && pub.price > 0)
            text += "
Price: £" + pub.price.toFixed(2);
        if ("previous" in pub) {
            var previous = [];
            for (var i = pub.previous.length-1; i >= 0; --i) {
                previous.push(createLink(pub.previous[i].link, pub.previous[i].name));
            }
            text += "
Previously known as " + previous.join(', ') + ".";
        }
        if ("tags" in pub && pub.tags.length > 0) {
            text += "
Tags: " + pub.tags.join(', ');
        }
        return text;
    }

    function setStatusMessage(html)
    {
        document.getElementById('message').innerHTML = html;
    }

    function displayStats(stats)
    {
        setStatusMessage(
            stats.name + ":
"
            + "Low (green): " + stats.format(stats.low) + "
"
            + "Median (blue): " + stats.format(stats.median) + "
"
            + "High (red): " + stats.format(stats.high)
        );
    }

    function createIcon(name)
    {
        return leaflet.icon({
            iconUrl: "img/marker-"+name+".png",
            iconRetinaUrl: "img/marker-"+name+"-2x.png",
            iconSize: [25, 39],
            iconAnchor: [12, 36],
            popupAnchor: [0, -30]
        });
    }

    function addPubsAsLayer(pubs, layerName, iconName, layersControl)
    {
        var layer = leaflet.layerGroup();
        var icon = createIcon(iconName);
        pubs.forEach(function(pub) {
            addFlag(layer, leaflet.latLng([pub.lat, pub.lon]), pub.name, icon, bubbleHtml(pub));
        });
        layersControl.addOverlay(layer, layerName + ": " + pubs.length);
        return layer;
    }

    function round(value)
    {
        return Math.floor(value + 0.5);
    }

    function colourDualLinear(value, low, high, median)
    {
        var red, green, blue, normalised;
        if (value < low) {
            return "#555555";
        } else if (value < median) {
            normalised = (value - low) / (median-low);
            green = round(255 * (1 - normalised));
            blue = round(255 * normalised);
            red = 0;
        } else {
            normalised = (value - median) / (high-median);
            red = round(255 * normalised);
            blue = round(255 * (1 - normalised));
            green = 0;
        }
        return '#' + ('000000' + ((red << 16) + (green<<8) + blue).toString(16)).slice(-6);
    }

    function priceStats(pubs)
    {
        var low = Number.MAX_VALUE;
        var high = Number.MIN_VALUE;
        var prices = [];
        pubs.forEach(function(pub)
        {
            if ("price" in pub && pub.price > 0) {
                low = Math.min(low, pub.price);
                high = Math.max(high, pub.price);
                prices.push(pub.price);
            }
        });
        prices.sort();
        return {
            name: 'Prices',
            low: low,
            high: high,
            median: prices[Math.floor(prices.length/2)],
            format:function(value) { return "£" + value.toFixed(2); }
        }
    }

    function addVoronoiCellsAsLayer(sites, map, layersControl, stats)
    {
        var layer = leaflet.layerGroup().addTo(map);
        sites.forEach(function(site) {
            leaflet.polygon(
                site.polygon.map(function(coord) { return leaflet.latLng([coord.lat, coord.lon]); }),
                {
                    fillColor: colourDualLinear(site.colour, stats.low, stats.high, stats.median),
                    stroke: false,
                    fillOpacity: 0.5
                }
            ).addTo(layer);
        });
        layersControl.addOverlay(layer, stats.name);
    }

    function hasTag(pub, tags)
    {
        return "tags" in pub && pub.tags.some(function(pubTag) {
            return tags.some(function(tag) {
                return tag == pubTag;
            });
        });
    }

    function initialiseMap()
    {
        setStatusMessage("Calculating...");

        var origin = new geo.GeoCoord(55.94816654144937, -3.1994622945785522);
        var circleRadiusMetres = 1609;

        var map = createMap(origin, circleRadiusMetres);
        var layersControl = leaflet.control.layers(null, null, { position:"bottomright", collapsed: false }).addTo(map);

        var todoPubs = [];
        var bloggedPubs = [];
        var excludedPubs = [];

        pubsData.forEach(function(pub) {
            if (pub.link) {
                bloggedPubs.push(pub);
            } else if (hasTag(pub, ['Disqualified','Closed','Student union','Club','Restaurant'])) {
                excludedPubs.push(pub);
            } else {
                todoPubs.push(pub);
            }
        });

        addPubsAsLayer(todoPubs, "Todo (yellow)", "gold", layersControl).addTo(map);
        addPubsAsLayer(bloggedPubs, "Visited (green)", "green", layersControl).addTo(map);
        addPubsAsLayer(excludedPubs, "Excluded (red)", "red", layersControl);

        var stats = priceStats(pubsData);
        displayStats(stats);

        var sites = geo.earthSurfaceVoronoi(bloggedPubs, origin, circleRadiusMetres);
        addVoronoiCellsAsLayer(
            sites.map(function(site) {
                return {
                    polygon: site.polygon,
                    colour: site.loc.price
                };
            }),
            map,
            layersControl,
            stats
        );
    }

    initialiseMap();
});
<|endoftext|>


<commit_before>'use strict';

var app = app || {};

let requestURL = 'https://pokeapi.co/api/v2/pokemon/' // Base URL of the pokemon we are requesting
let requestedPokemon;
let returnData;
let pokemonName;
let pokemonSprite;
let pokemonType = [];
let pokemonWeight;
let pokemonHeight;
let pokemonStats = []; // speed, spDef, spAtk, def, atk, hp -- in that order
let pokemonDescription;

(function(module) {

  const pokemon = {};

  $(document).ready(function() {
      $('.toggle-nav').click(function(e) {
          $(this).toggleClass('active');
          $('.menu ul').toggleClass('active');

          e.preventDefault();
      });
  });

  pokemon.getPokemonName = function() {
    $('#search').on('click', function(e) {
      e.preventDefault();
      requestURL = 'https://pokeapi.co/api/v2/pokemon/'
      pokemonStats = []; // emptying the stats array for subsequent searches
      pokemonType = []; // emptying the types array for subsequent searches
      requestedPokemon = $('#poke-search').val().toLowerCase();
      requestURL += requestedPokemon;
      pokemon.getPokemonInfo(requestURL);
    });
  };

  pokemon.getPokemonInfo = function(requestURL) {
    $.ajax({
      url: requestURL,
      method: 'GET',
      success: function(data) {
        returnData = data;
        pokemon.loadPokemonInfo(returnData);
      }
    });
  };

  pokemon.loadPokemonInfo = function(returnData) {
    pokemonName = returnData.name;
    pokemonSprite = returnData.sprites.front_default;
    for (let i = 0; i < returnData.types.length; i++) {
      pokemonType.push(returnData.types[i].type.name);
    }
    pokemonHeight = returnData.height;
    pokemonWeight = returnData.weight;
    for (let j = 0; j < returnData.stats.length; j++) {
      pokemonStats.push(returnData.stats[j].base_stat);
    }
    $.ajax({
      url: "https://pokeapi.co/api/v2/pokemon-species/" + requestedPokemon,
      method: 'GET',
      success: function(data) {
        pokemonDescription = data.flavor_text_entries[1].flavor_text;
        pokemon.makePokedex();
      }
    });
  };

  pokemon.makePokedex = function() {
    let info = {
      pokeName: pokemonName,
      pokeSprite: pokemonSprite,
      pokeDescription: pokemonDescription,
      pokeHp: pokemonStats[5],
      pokeAtk: pokemonStats[4],
      pokeDef: pokemonStats[3],
      pokeSpecialAtk: pokemonStats[2],
      pokeSpecialDef: pokemonStats[1],
      pokeSpeed: pokemonStats[0],
      pokeTypes: pokemonType,
      height: pokemonHeight / 10,
      weight: pokemonWeight / 10
    };

    $(document).ready(function(){
      var ctx = document.getElementById('pokeChart').getContext('2d');
      var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
          labels: ['Hp', 'Atk', 'Def', 'Sp Atk', 'Sp Def', 'Spd'],
          datasets: [
            {
              data: [pokemonStats[5], pokemonStats[4], pokemonStats[3], pokemonStats[2], pokemonStats[1], pokemonStats[0]],
              backgroundColor: [
                '#1a8cff',
                '#3399ff',
                '#4da6ff',
                '#66b3ff',
                '#80bfff',
                '#99ccff'
              ]
            }
          ]
        }
      })
    });

    var template = Handlebars.compile($('#pokedexTemplate').html())(info);
    $('#pokedex').prepend(template);
    $('main').hide();
    $('#pokedex').fadeIn();

  };

  Chart.defaults.global.legend.display = false;
  Chart.defaults.global.tooltips.enabled = false;

  module.pokemon = pokemon;

})(app);
<commit_msg>nothing<commit_after>'use strict';

var app = app || {};

let requestURL = 'https://pokeapi.co/api/v2/pokemon/' // Base URL of the pokemon we are requesting
let requestedPokemon;
let returnData;
let pokemonName;
let pokemonSprite;
let pokemonType = [];
let pokemonWeight;
let pokemonHeight;
let pokemonStats = []; // speed, spDef, spAtk, def, atk, hp -- in that order
let pokemonDescription;

(function(module) {

  const pokemon = {};

  $(document).ready(function() {
      $('.toggle-nav').click(function(e) {
          $(this).toggleClass('active');
          $('.menu ul').toggleClass('active');

          e.preventDefault();
      });
  });

  pokemon.getPokemonName = function() {
    $('#search').on('click', function(e) {
      e.preventDefault();
      requestURL = 'https://pokeapi.co/api/v2/pokemon/'
      pokemonStats = []; // emptying the stats array for subsequent searches
      pokemonType = []; // emptying the types array for subsequent searches
      requestedPokemon = $('#poke-search').val().toLowerCase();
      requestURL += requestedPokemon;
      pokemon.getPokemonInfo(requestURL);
    });
  };

  pokemon.getPokemonInfo = function(requestURL) {
    $.ajax({
      url: requestURL,
      method: 'GET',
      success: function(data) {
        returnData = data;
        pokemon.loadPokemonInfo(returnData);
      }
    });
  };

  pokemon.loadPokemonInfo = function(returnData) {
    pokemonName = returnData.name;
    pokemonSprite = returnData.sprites.front_default;
    for (let i = 0; i < returnData.types.length; i++) {
      pokemonType.push(returnData.types[i].type.name);
    }
    pokemonHeight = returnData.height;
    pokemonWeight = returnData.weight;
    for (let j = 0; j < returnData.stats.length; j++) {
      pokemonStats.push(returnData.stats[j].base_stat);
    }
    $.ajax({
      url: "https://pokeapi.co/api/v2/pokemon-species/" + requestedPokemon,
      method: 'GET',
      success: function(data) {
        pokemonDescription = data.flavor_text_entries[1].flavor_text;
        pokemon.makePokedex();
      }
    });
  };

  pokemon.makePokedex = function() {
    let info = {
      pokeName: pokemonName,
      pokeSprite: pokemonSprite,
      pokeDescription: pokemonDescription,
      pokeHp: pokemonStats[5],
      pokeAtk: pokemonStats[4],
      pokeDef: pokemonStats[3],
      pokeSpecialAtk: pokemonStats[2],
      pokeSpecialDef: pokemonStats[1],
      pokeSpeed: pokemonStats[0],
      pokeTypes: pokemonType,
      height: pokemonHeight / 10,
      weight: pokemonWeight / 10
    };

    $(document).ready(function(){
      var ctx = document.getElementById('pokeChart').getContext('2d');
      var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
          labels: ['Hp', 'Atk', 'Def', 'Sp Atk', 'Sp Def', 'Spd'],
          datasets: [
            {
              data: [pokemonStats[5], pokemonStats[4], pokemonStats[3], pokemonStats[2], pokemonStats[1], pokemonStats[0]],
              backgroundColor: [
                '#1a8cff',
                '#3399ff',
                '#4da6ff',
                '#66b3ff',
                '#80bfff',
                '#99ccff'
              ]
            }
          ]
        }
      })
    });

    var template = Handlebars.compile($('#pokedexTemplate').html())(info);
    $('#pokedex').prepend(template);
    $('main').hide();
    $('#pokedex').fadeIn();

  };

  Chart.defaults.global.legend.display = false;
  Chart.defaults.global.tooltips.enabled = false;

  module.pokemon = pokemon;

})(app);
<|endoftext|>


<commit_before>var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
    name: 'Default',
    version:'0.4',
    prepareImgLinks: function (callback) {
        var res = [];
        const reVideos = /\/[^:]+\.(?:3gpp|m4v|mkv|mp4|ogv|webm)(?:[\?#].*)?(?:\/)?$/i
        const reImages = /\/[^:]+\.(?:bmp|gifv?|ico|jpe?g|png|svg|webp|xbm)(?:[\?#].*)?(?:\/)?$/i
        $('a[href]').filter(function () {
            if (typeof(this.href) != 'string')
			    return false;
            if (this.href.substr(0, 10).toLowerCase() == 'data:image')
                return false;
            if (this.href.match(reImages))
                return true;
            if (this.href.match(reVideos))
                return true;
            return false;
        }).each(function () {
            var _this = $(this), data = _this.data();
            if (!data.hoverZoomSrc) {
                var src = this.href;
                if (!options.zoomVideos || ((src.indexOf('imgur.com') == -1 || src.indexOf('slimgur.com') != -1) && src.indexOf('gfycat.com') == -1 && src.indexOf('pornbot.net') == -1)) {
                    data.hoverZoomSrc = [src];
                    res.push(_this);
                }
            }
        });
        if (res.length) {
            callback($(res), this.name);
        }
    }
});
<commit_msg>Support for playlists (M3U8)<commit_after>var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
    name: 'Default',
    version:'0.5',
    prepareImgLinks: function (callback) {
        var res = [];
        const reVideos = /\/[^:]+\.(?:3gpp|m4v|mkv|mp4|ogv|webm)(?:[\?#].*)?(?:\/)?$/i
        const reImages = /\/[^:]+\.(?:bmp|gifv?|ico|jpe?g|png|svg|webp|xbm)(?:[\?#].*)?(?:\/)?$/i
        const rePlaylists = /\/[^:]+\.(?:m3u8)(?:[\?#].*)?(?:\/)?$/i
        $('a[href]').filter(function () {
            if (typeof(this.href) != 'string')
			    return false;
            if (this.href.substr(0, 10).toLowerCase() == 'data:image')
                return false;
            if (this.href.match(reImages))
                return true;
            if (this.href.match(reVideos))
                return true;
            if (this.href.match(rePlaylists))
                return true;
            return false;
        }).each(function () {
            var _this = $(this), data = _this.data();
            if (!data.hoverZoomSrc) {
                var src = this.href;
                if (!options.zoomVideos || ((src.indexOf('imgur.com') == -1 || src.indexOf('slimgur.com') != -1) && src.indexOf('gfycat.com') == -1 && src.indexOf('pornbot.net') == -1)) {
                    data.hoverZoomSrc = [src];
                    res.push(_this);
                }
            }
        });
        if (res.length) {
            callback($(res), this.name);
        }
    }
});
<|endoftext|>


<commit_before>jQuery(document).ready(function () {

	var rKey, rWatchId, rInterval, x, oRundgang;

	if (localStorage.getItem("fe_user")) {
		// Set key for Rundgang
		rKey = 'r_' + localStorage.getItem("fe_user");
	}

	x = document.getElementById("geolocation");
	var rCount = 0;
	var nr = 0;
	var rStarted = false;

	// Rundgang Object
  oRundgang = {};

	/**************************************************************
		SET START-VARIABLES
	***************************************************************/
	if (!localStorage.getItem(rKey)) {
		// Wachdienst Array
		oRundgang.Wachdienst = [];

	} else {

		oRundgang = JSON.parse(localStorage.getItem(rKey));

		// Get last Rundgang (Index)
		rCount = oRundgang.Wachdienst.length -1;

		if(oRundgang.Wachdienst[rCount].ende == 0){
			// der letzte Rundgang ist noch offen

				// Get Last Checkpoint
				nr = oRundgang.Wachdienst[rCount].checkString.length - 1;

				d = new Date(oRundgang.Wachdienst[rCount].checkString[nr].datetime);
				m = d.getMonth() + 1;
				span_date = 'Zeit: ' + d.getHours() + ':' + d.getMinutes() + ' Datum: ' + d.getDate() + '.' + m + '.' + d.getFullYear() + '';
				span_text = 'Rundgang wird fortgesetzt';
				jQuery('.statusBox p:gt(0)').fadeOut(500, function () {
					jQuery('
' + span_text + '
' + span_date + '
').hide().prependTo(".statusBox").delay(350).slideToggle("slow");
					jQuery(this).remove();
				});

				rInterval = setInterval(function() {
							getCurGeoData()
					}, 5000);

				nr++;
				rStarted = true;
		} else {
				rCount++;
		}
	}

	/**************************************************************
		PRESS BUTTON -> START/STOP GEO_DATENERFASSUNG
	***************************************************************/

	jQuery("a#start").on('click', function () {

		//x.innerHTML = '
Geo-Daten werden abgerufen...
';

		jQuery(".expand").animate({
				left: '100%'
		}, 2000, 'linear', function () {
				jQuery(".expand").removeAttr('style');
		});

		jQuery('#rundgangButtons').attr('src', 'img/buttonsAct.png').delay(1500).queue(function (next) {
				jQuery(this).attr('src', 'img/buttonsRun.png');
				next();
		});
		d = new Date();
		m = d.getMonth() + 1;
		span_date = 'Zeit: ' + d.getHours() + ':' + d.getMinutes() + ' Datum: ' + d.getDate() + '.' + m + '.' + d.getFullYear() + '';

		/*var options = {
			enableHighAccuracy: true,
			timeout: 10000
		};
		rWatchId = navigator.geolocation.getCurrentPosition(onGeoDataSuccess, onGeoDataError, options);*/

		if (rStarted == false) {
			// Aktiviere die permanente Geo-Datenerfassung
			rInterval = setInterval(function() {
						getCurGeoData()
				}, 5000);

			span_text = 'Rundgang wurde gestartet';
			jQuery('.statusBox p:gt(0)').fadeOut(500, function () {
				jQuery('
' + span_text + '
' + span_date + '
').hide().prependTo(".statusBox").delay(350).slideToggle("slow");
				jQuery(this).remove();
			});

			rStarted = true;

		} else {
			// Deaktiviere die permanente Geo-Datenerfassung
			clearInterval(rInterval);

			stopGeoData();

			span_text = 'Rundgang wurde beendet';
			jQuery('.statusBox p:gt(0)').fadeOut(500, function () {
				jQuery('
' + span_text + '
' + span_date + '
').hide().prependTo(".statusBox").delay(350).slideToggle("slow");
				jQuery(this).remove();
			});

			rStarted = false;
		}

	});

	function getCurGeoData() {
		// holt die aktuellen Geokoordinaten

		var options = {
			enableHighAccuracy: true,
			timeout: 10000
		};
		rWatchId = navigator.geolocation.getCurrentPosition(onGeoDataSuccess, onGeoDataError, options);
	}

	/**************************************************************
		OBJEKT MIT GEO-DATEN ZUSAMMENSTELLEN
	***************************************************************/

	function onGeoDataSuccess(position) {

		x.innerHTML = '
Geo-Daten erfasst!
';

		//geoStrg = '{ "datetime" : ' + new Date().getTime() + ', "status" : "ok", "lat" : ' + position.coords.latitude + ', "lng" : ' + position.coords.longitude + ', "acc" : ' + position.coords.accuracy + ' }, ';
		var geoData = {};
		geoData.datetime = new Date().getTime();
		geoData.status = "ok";
		geoData.lat = position.coords.latitude;
		geoData.lng = position.coords.longitude;
		geoData.acc = position.coords.accuracy;

		saveCheckPoint(geoData);
	}

	function onGeoDataError(error) {

		x.innerHTML = '
Geo-Daten konnten nicht erfasst werden!
';

		//geoStrg = '{ "datetime" : ' + new Date().getTime() + ', "status" : "' + error.code + '" }, ';
		var geoData = {};
		geoData.datetime = new Date().getTime();
		geoData.status = error.code;

		saveCheckPoint(geoData);
	}

	/**************************************************************
		AKTUELLE GEO-DATEN SPEICHERN
	***************************************************************/

	function saveCheckPoint(geoDataElement) {

			var Rundgang;

			if (nr == 0) {

					/* Create new Rundgang */
					Rundgang = {};
					Rundgang.id = rCount;
					Rundgang.checkString = [];
					Rundgang.checkString.push(geoDataElement);
					Rundgang.start = new Date().getTime();
					Rundgang.ende = 0;

					oRundgang.Wachdienst.push(Rundgang);

					localStorage.setItem(rKey, JSON.stringify(oRundgang));

					nr++;

					newRundgang(rCount);

			} else {

					/* Load Rundgang from localStorage */
					oRundgang = JSON.parse(localStorage.getItem(rKey));

					/* Update Rundgang */
					oRundgang.Wachdienst[rCount].checkString.push(geoDataElement);

					localStorage.setItem(rKey, JSON.stringify(oRundgang));

					nr++;

					updateRundgang(rCount, false);
			}

	}

	/**************************************************************
		RUNDGANG STOPPEN
	***************************************************************/

	function stopGeoData() {

		/* Load Rundgang from localStorage */
		oRundgang = JSON.parse(localStorage.getItem(rKey));

		/* Update Rundgang Ende*/
		oRundgang.Wachdienst[rCount].ende = new Date().getTime();

		localStorage.setItem(rKey, JSON.stringify(oRundgang));

		nr = 0;
		rCount++;

		updateRundgang(rCount-1, true);

	}

	/**************************************************************
		NEUEN RUNDGANG SPEICHERN
	***************************************************************/

	function newRundgang(rCount) {

			var hmac, d, m, data, startDatetime, url, oRundgang, rKey, checkString, checkpointMan, i;

			checkpointMan = '';
			rKey = 'r_' + localStorage.getItem("fe_user");

			oRundgang = {};
			oRundgang = JSON.parse(localStorage.getItem(rKey));
			checkString = oRundgang.Wachdienst[rCount].checkString;

			for (i = 0; i < checkString.length; i++) {
					checkpointMan = checkpointMan +  JSON.stringify(checkString[i]);
			}

			hmac = 'a:3:{s:11:"newRundgang";a:5:{s:6:"feUser";i:1;s:13:"startDatetime";i:1;s:11:"endDatetime";i:1;s:13:"checkpointMan";i:1;s:14:"checkpointAuto";i:1;}s:6:"action";i:1;s:10:"controller";i:1;}f59be899124b071365d07b0bd18b87b4a16c3a91';

			// 17:21:00 5-8-2013
			d = new Date();
			m = d.getMonth() + 1;
			startDatetime = d.getHours() + ':' + d.getMinutes() + ':' +  d.getSeconds() + ' ' + d.getDate() + '-' + m + '-' + d.getFullYear();

			url = "http://ma.ids-services.at/index.php";

			data = {
					'id': 227,
					'no_cache': 1,
					'type': 99,
					'tx_mungoswachdienst_request[action]': "create",
					'tx_mungoswachdienst_request[controller]': "Rundgang",
					'tx_mungoswachdienst_request[__referrer][extensionName]': "MungosWachdienst",
					'tx_mungoswachdienst_request[__referrer][controllerName]': "Rundgang",
					'tx_mungoswachdienst_request[__referrer][actionName]': "new",
					'tx_mungoswachdienst_request[newRundgang][feUser]': localStorage.getItem("fe_user"),
					'tx_mungoswachdienst_request[newRundgang][startDatetime]': startDatetime,
					'tx_mungoswachdienst_request[newRundgang][checkpointMan]': checkpointMan,
					'tx_mungoswachdienst_request[newRundgang][checkpointAuto]': '',
					'tx_mungoswachdienst_request[__hmac]': hmac
			};

			$.jsonp({
					url: url,
					data: data,
					callbackParameter: 'jsonp_callback',
					success: function (json, textStatus, xOptions) {

							if (json.uid) {
									/* Update Rundgang */
									oRundgang.Wachdienst[rCount].uid = json.uid;

									localStorage.setItem(rKey, JSON.stringify(oRundgang));
							}

					},
					error: function (xOptions, textStatus) {
						consoleLog('debug', "ERROR: Neuen Rundgang speichern");
						consoleLog('debug', "Request failed: " + xOptions + " " + textStatus);
						consoleLog('debug', xOptions);
					}
			});

	}

	/**************************************************************
		EXISTIERENDEN RUNDGANG SPEICHERN
	***************************************************************/

	function updateRundgang(rCount, isLast) {

			var hmac, d, m, data, startDatetime, url, oRundgang, rKey, checkpointMan, separator, endDatetime, checkString;

			checkpointMan = '';
			rKey = 'r_' + localStorage.getItem("fe_user");

			oRundgang = {};
			oRundgang = JSON.parse(localStorage.getItem(rKey));
			checkString = oRundgang.Wachdienst[rCount].checkString;

			separator = '';

			for (var i=0; i < checkString.length; i++) {

					if(i>0){ separator = ', '; }
					checkpointMan = checkpointMan + separator +  JSON.stringify(checkString[i]);
			}

			hmac = 'a:3:{s:8:"rundgang";a:6:{s:6:"feUser";i:1;s:13:"startDatetime";i:1;s:11:"endDatetime";i:1;s:13:"checkpointMan";i:1;s:14:"checkpointAuto";i:1;s:10:"__identity";i:1;}s:6:"action";i:1;s:10:"controller";i:1;}6313957ab723c65dd945a4cfb7063e14c57534fa';

			d = new Date();
			m = d.getMonth() + 1;
			endDatetime = 0;

			if (isLast) {
					endDatetime = d.getHours() + ':' + d.getMinutes() + ':' +  d.getSeconds() + ' ' + d.getDate() + '-' + m + '-' + d.getFullYear();
			}

			url = "http://ma.ids-services.at/index.php";

			data = {
					'id': 227,
					'no_cache': 1,
					'type': 99,
					'tx_mungoswachdienst_request[action]': "update",
					'tx_mungoswachdienst_request[controller]': "Rundgang",
					'tx_mungoswachdienst_request[rundgang][__identity]': oRundgang.Wachdienst[rCount].uid,
					'tx_mungoswachdienst_request[__referrer][extensionName]': "MungosWachdienst",
					'tx_mungoswachdienst_request[__referrer][controllerName]': "Rundgang",
					'tx_mungoswachdienst_request[__referrer][actionName]': "edit",
					'tx_mungoswachdienst_request[rundgang][feUser]': localStorage.getItem("fe_user"),
					'tx_mungoswachdienst_request[rundgang][checkpointMan]': checkpointMan,
					'tx_mungoswachdienst_request[rundgang][checkpointAuto]': '',
					'tx_mungoswachdienst_request[rundgang][endDatetime]': endDatetime,
					'tx_mungoswachdienst_request[__hmac]': hmac
			};

			$.jsonp({
					url: url,
					data: data,
					callbackParameter: 'jsonp_callback',
					success: function(json, textStatus, xOptions) {

						if(json.uid){
							/* Update Rundgang */
							oRundgang.Wachdienst[rCount].uid = json.uid;

							localStorage.setItem(rKey,JSON.stringify(oRundgang));
						}

					},
					error: function(xOptions, textStatus){
						consoleLog('debug', "ERROR: Rundgang aktualisieren");
						consoleLog('debug', "Request failed: " + xOptions + " " + textStatus);
						consoleLog('debug', xOptions);
					}
			});
	}

});<commit_msg>Rundgang.js v1.4.1 - Änderung in StopGeoData<commit_after>jQuery(document).ready(function () {

	var rKey, rWatchId, rInterval, x, oRundgang;

	if (localStorage.getItem("fe_user")) {
		// Set key for Rundgang
		rKey = 'r_' + localStorage.getItem("fe_user");
	}

	x = document.getElementById("geolocation");
	var rCount = 0;
	var nr = 0;
	var rStarted = false;

	// Rundgang Object
  oRundgang = {};

	/**************************************************************
		SET START-VARIABLES
	***************************************************************/
	if (!localStorage.getItem(rKey)) {
		// Wachdienst Array
		oRundgang.Wachdienst = [];

	} else {

		oRundgang = JSON.parse(localStorage.getItem(rKey));

		// Get last Rundgang (Index)
		rCount = oRundgang.Wachdienst.length -1;

		if(oRundgang.Wachdienst[rCount].ende == 0){
			// der letzte Rundgang ist noch offen

				// Get Last Checkpoint
				nr = oRundgang.Wachdienst[rCount].checkString.length - 1;

				d = new Date(oRundgang.Wachdienst[rCount].checkString[nr].datetime);
				m = d.getMonth() + 1;
				span_date = 'Zeit: ' + d.getHours() + ':' + d.getMinutes() + ' Datum: ' + d.getDate() + '.' + m + '.' + d.getFullYear() + '';
				span_text = 'Rundgang wird fortgesetzt';
				jQuery('.statusBox p:gt(0)').fadeOut(500, function () {
					jQuery('
' + span_text + '
' + span_date + '
').hide().prependTo(".statusBox").delay(350).slideToggle("slow");
					jQuery(this).remove();
				});

				rInterval = setInterval(function() {
							getCurGeoData()
					}, 5000);

				nr++;
				rStarted = true;
		} else {
				rCount++;
		}
	}

	/**************************************************************
		PRESS BUTTON -> START/STOP GEO_DATENERFASSUNG
	***************************************************************/

	jQuery("a#start").on('click', function () {

		//x.innerHTML = '
Geo-Daten werden abgerufen...
';

		jQuery(".expand").animate({
				left: '100%'
		}, 2000, 'linear', function () {
				jQuery(".expand").removeAttr('style');
		});

		jQuery('#rundgangButtons').attr('src', 'img/buttonsAct.png').delay(1500).queue(function (next) {
				jQuery(this).attr('src', 'img/buttonsRun.png');
				next();
		});
		d = new Date();
		m = d.getMonth() + 1;
		span_date = 'Zeit: ' + d.getHours() + ':' + d.getMinutes() + ' Datum: ' + d.getDate() + '.' + m + '.' + d.getFullYear() + '';

		/*var options = {
			enableHighAccuracy: true,
			timeout: 10000
		};
		rWatchId = navigator.geolocation.getCurrentPosition(onGeoDataSuccess, onGeoDataError, options);*/

		if (rStarted == false) {
			// Aktiviere die permanente Geo-Datenerfassung
			rInterval = setInterval(function() {
						getCurGeoData()
				}, 5000);

			span_text = 'Rundgang wurde gestartet';
			jQuery('.statusBox p:gt(0)').fadeOut(500, function () {
				jQuery('
' + span_text + '
' + span_date + '
').hide().prependTo(".statusBox").delay(350).slideToggle("slow");
				jQuery(this).remove();
			});

			rStarted = true;

		} else {
			// Deaktiviere die permanente Geo-Datenerfassung
			clearInterval(rInterval);

			stopGeoData();

			span_text = 'Rundgang wurde beendet';
			jQuery('.statusBox p:gt(0)').fadeOut(500, function () {
				jQuery('
' + span_text + '
' + span_date + '
').hide().prependTo(".statusBox").delay(350).slideToggle("slow");
				jQuery(this).remove();
			});

			rStarted = false;
		}

	});

	function getCurGeoData() {
		// holt die aktuellen Geokoordinaten

		var options = {
			enableHighAccuracy: true,
			timeout: 10000
		};
		rWatchId = navigator.geolocation.getCurrentPosition(onGeoDataSuccess, onGeoDataError, options);
	}

	/**************************************************************
		OBJEKT MIT GEO-DATEN ZUSAMMENSTELLEN
	***************************************************************/

	function onGeoDataSuccess(position) {

		x.innerHTML = '
Geo-Daten erfasst!
';

		//geoStrg = '{ "datetime" : ' + new Date().getTime() + ', "status" : "ok", "lat" : ' + position.coords.latitude + ', "lng" : ' + position.coords.longitude + ', "acc" : ' + position.coords.accuracy + ' }, ';
		var geoData = {};
		geoData.datetime = new Date().getTime();
		geoData.status = "ok";
		geoData.lat = position.coords.latitude;
		geoData.lng = position.coords.longitude;
		geoData.acc = position.coords.accuracy;

		saveCheckPoint(geoData);
	}

	function onGeoDataError(error) {

		x.innerHTML = '
Geo-Daten konnten nicht erfasst werden!
';

		//geoStrg = '{ "datetime" : ' + new Date().getTime() + ', "status" : "' + error.code + '" }, ';
		var geoData = {};
		geoData.datetime = new Date().getTime();
		geoData.status = error.code;

		saveCheckPoint(geoData);
	}

	/**************************************************************
		AKTUELLE GEO-DATEN SPEICHERN
	***************************************************************/

	function saveCheckPoint(geoDataElement) {

			var Rundgang;

			if (nr == 0) {

					/* Create new Rundgang */
					Rundgang = {};
					Rundgang.id = rCount;
					Rundgang.checkString = [];
					Rundgang.checkString.push(geoDataElement);
					Rundgang.start = new Date().getTime();
					Rundgang.ende = 0;

					oRundgang.Wachdienst.push(Rundgang);

					localStorage.setItem(rKey, JSON.stringify(oRundgang));

					nr++;

					newRundgang(rCount);

			} else {

					/* Load Rundgang from localStorage */
					oRundgang = JSON.parse(localStorage.getItem(rKey));

					/* Update Rundgang */
					oRundgang.Wachdienst[rCount].checkString.push(geoDataElement);

					localStorage.setItem(rKey, JSON.stringify(oRundgang));

					nr++;

					updateRundgang(rCount, false);
			}

	}

	/**************************************************************
		RUNDGANG STOPPEN
	***************************************************************/

	function stopGeoData() {

		/* Load Rundgang from localStorage */
		oRundgang = JSON.parse(localStorage.getItem(rKey));

		if (oRundgang.Wachdienst[rCount]) {
			/* Update Rundgang Ende*/
			oRundgang.Wachdienst[rCount].ende = new Date().getTime();

			localStorage.setItem(rKey, JSON.stringify(oRundgang));

			nr = 0;
			rCount++;

			updateRundgang(rCount-1, true);
		}
	}

	/**************************************************************
		NEUEN RUNDGANG SPEICHERN
	***************************************************************/

	function newRundgang(rCount) {

			var hmac, d, m, data, startDatetime, url, oRundgang, rKey, checkString, checkpointMan, i;

			checkpointMan = '';
			rKey = 'r_' + localStorage.getItem("fe_user");

			oRundgang = {};
			oRundgang = JSON.parse(localStorage.getItem(rKey));
			checkpointMan = JSON.stringify(oRundgang.Wachdienst[rCount].checkString);
			/*checkString = oRundgang.Wachdienst[rCount].checkString;

			for (i = 0; i < checkString.length; i++) {
					checkpointMan = checkpointMan +  JSON.stringify(checkString[i]);
			}*/

			hmac = 'a:3:{s:11:"newRundgang";a:5:{s:6:"feUser";i:1;s:13:"startDatetime";i:1;s:11:"endDatetime";i:1;s:13:"checkpointMan";i:1;s:14:"checkpointAuto";i:1;}s:6:"action";i:1;s:10:"controller";i:1;}f59be899124b071365d07b0bd18b87b4a16c3a91';

			// 17:21:00 5-8-2013
			d = new Date();
			m = d.getMonth() + 1;
			startDatetime = d.getHours() + ':' + d.getMinutes() + ':' +  d.getSeconds() + ' ' + d.getDate() + '-' + m + '-' + d.getFullYear();

			url = "http://ma.ids-services.at/index.php";

			data = {
					'id': 227,
					'no_cache': 1,
					'type': 99,
					'tx_mungoswachdienst_request[action]': "create",
					'tx_mungoswachdienst_request[controller]': "Rundgang",
					'tx_mungoswachdienst_request[__referrer][extensionName]': "MungosWachdienst",
					'tx_mungoswachdienst_request[__referrer][controllerName]': "Rundgang",
					'tx_mungoswachdienst_request[__referrer][actionName]': "new",
					'tx_mungoswachdienst_request[newRundgang][feUser]': localStorage.getItem("fe_user"),
					'tx_mungoswachdienst_request[newRundgang][startDatetime]': startDatetime,
					'tx_mungoswachdienst_request[newRundgang][checkpointMan]': checkpointMan,
					'tx_mungoswachdienst_request[newRundgang][checkpointAuto]': '',
					'tx_mungoswachdienst_request[__hmac]': hmac
			};

			$.jsonp({
					url: url,
					data: data,
					callbackParameter: 'jsonp_callback',
					success: function (json, textStatus, xOptions) {

							if (json.uid) {
									/* Update Rundgang */
									oRundgang.Wachdienst[rCount].uid = json.uid;

									localStorage.setItem(rKey, JSON.stringify(oRundgang));
							}

					},
					error: function (xOptions, textStatus) {
						consoleLog('debug', "ERROR: Neuen Rundgang speichern");
						consoleLog('debug', "Request failed: " + xOptions + " " + textStatus);
						consoleLog('debug', xOptions);
					}
			});

	}

	/**************************************************************
		EXISTIERENDEN RUNDGANG SPEICHERN
	***************************************************************/

	function updateRundgang(rCount, isLast) {

			var hmac, d, m, data, startDatetime, url, oRundgang, rKey, checkpointMan, separator, endDatetime, checkString;

			checkpointMan = '';
			rKey = 'r_' + localStorage.getItem("fe_user");

			oRundgang = {};
			oRundgang = JSON.parse(localStorage.getItem(rKey));

			checkpointMan = JSON.stringify(oRundgang.Wachdienst[rCount].checkString);

			/*checkString = oRundgang.Wachdienst[rCount].checkString;

			separator = '';

			for (var i=0; i < checkString.length; i++) {

					if(i>0){ separator = ', '; }
					checkpointMan = checkpointMan + separator +  JSON.stringify(checkString[i]);
			}*/

			hmac = 'a:3:{s:8:"rundgang";a:6:{s:6:"feUser";i:1;s:13:"startDatetime";i:1;s:11:"endDatetime";i:1;s:13:"checkpointMan";i:1;s:14:"checkpointAuto";i:1;s:10:"__identity";i:1;}s:6:"action";i:1;s:10:"controller";i:1;}6313957ab723c65dd945a4cfb7063e14c57534fa';

			d = new Date();
			m = d.getMonth() + 1;
			endDatetime = 0;

			if (isLast) {
					endDatetime = d.getHours() + ':' + d.getMinutes() + ':' +  d.getSeconds() + ' ' + d.getDate() + '-' + m + '-' + d.getFullYear();
			}

			url = "http://ma.ids-services.at/index.php";

			data = {
					'id': 227,
					'no_cache': 1,
					'type': 99,
					'tx_mungoswachdienst_request[action]': "update",
					'tx_mungoswachdienst_request[controller]': "Rundgang",
					'tx_mungoswachdienst_request[rundgang][__identity]': oRundgang.Wachdienst[rCount].uid,
					'tx_mungoswachdienst_request[__referrer][extensionName]': "MungosWachdienst",
					'tx_mungoswachdienst_request[__referrer][controllerName]': "Rundgang",
					'tx_mungoswachdienst_request[__referrer][actionName]': "edit",
					'tx_mungoswachdienst_request[rundgang][feUser]': localStorage.getItem("fe_user"),
					'tx_mungoswachdienst_request[rundgang][checkpointMan]': checkpointMan,
					'tx_mungoswachdienst_request[rundgang][checkpointAuto]': '',
					'tx_mungoswachdienst_request[rundgang][endDatetime]': endDatetime,
					'tx_mungoswachdienst_request[__hmac]': hmac
			};

			$.jsonp({
					url: url,
					data: data,
					callbackParameter: 'jsonp_callback',
					success: function(json, textStatus, xOptions) {

						if(json.uid){
							/* Update Rundgang */
							oRundgang.Wachdienst[rCount].uid = json.uid;

							localStorage.setItem(rKey,JSON.stringify(oRundgang));
						}

					},
					error: function(xOptions, textStatus){
						consoleLog('debug', "ERROR: Rundgang aktualisieren");
						consoleLog('debug', "Request failed: " + xOptions + " " + textStatus);
						consoleLog('debug', xOptions);
					}
			});
	}

});<|endoftext|>


<commit_before>/*
 * grunticon
 * https://github.com/filamentgroup/grunticon
 *
 * Copyright (c) 2012 Scott Jehl, Filament Group, Inc
 * Licensed under the MIT license.
 */

/*global __dirname:true*/
/*global require:true*/

module.exports = function( grunt , undefined ) {

	"use strict";

	var path = require( 'path' );
	var os = require( 'os' );

	var fs = require( 'fs-extra' );
	var uglify = require( 'uglify-js' );
	var RSVP = require( 'rsvp' );

	var DirectoryColorfy = require( 'directory-colorfy' );
	var DirectoryEncoder = require( 'directory-encoder' );
	var svgToPng = require( 'svg-to-png' );

	var helper = require( path.join( '..', 'lib', 'grunticon-helper' ) );

	grunt.registerMultiTask( 'grunticon', 'A mystical CSS icon solution.', function() {
		var done = this.async();

		// get the config
		var config = this.options({
			datasvgcss: "icons.data.svg.css",
			datapngcss: "icons.data.png.css",
			urlpngcss: "icons.fallback.css",
			files: {
				loader: path.join( __dirname, 'grunticon', 'static', 'grunticon.loader.js'),
				banner: path.join( __dirname, 'grunticon', 'static', 'grunticon.loader.banner.js')
			},
			previewhtml: "preview.html",
			loadersnippet: "grunticon.loader.js",
			cssbasepath: path.sep,
			customselectors: {},
			cssprefix: ".icon-",
			defaultWidth: "400px",
			defaultHeight: "300px",
			colors: {},
			dynamicColorOnly: false,
			pngfolder: "png",
			pngpath: "",
			template: "",
			tmpPath: os.tmpDir(),
			tmpDir: "grunticon-tmp",
			previewTemplate: path.join( __dirname, "..", "example", "preview.hbs" )
		});

		// just a quick starting message
		grunt.log.writeln( "Look, it's a grunticon!" );

		var files = this.files.filter( function( file ){
			return file.src[0].match( /png|svg/ );
		});
		if( files.length === 0 ){
			grunt.log.writeln( "Grunticon has no files to read!" );
			done();
			return;
		}

		files = files.map( function( file ){
			return file.src[0];
		});

		config.src = this.files[0].orig.cwd;
		config.dest = this.files[0].orig.dest;

		if( !config.dest || config.dest && config.dest === "" ){
			grunt.fatal("The destination must be a directory");
		}

		// folder name (within the output folder) for generated png files
		var pngfolder = path.join.apply( null, config.pngfolder.split( path.sep ) );

		// create the output directory
		fs.mkdirpSync( config.dest );

		// minify the source of the grunticon loader and write that to the output
		grunt.log.writeln( "grunticon now minifying the stylesheet loader source." );
		var banner = fs.readFileSync( config.files.banner );
		config.min = banner + "\n" + uglify.minify( config.files.loader ).code;
		fs.writeFileSync( path.join( config.dest, config.loadersnippet ), config.min );
		grunt.log.writeln( "grunticon loader file created." );

		var svgToPngOpts = {
			pngfolder: pngfolder,
			defaultWidth: config.defaultWidth,
			defaultHeight: config.defaultHeight
		};

		var o = {
			pngfolder: pngfolder,
			pngpath: config.pngpath,
			customselectors: config.customselectors,
			template: path.resolve( config.template ),
			previewTemplate: path.resolve( config.previewTemplate ),
			noencodepng: false,
			prefix: config.cssprefix
		};

		var o2 = JSON.parse(JSON.stringify(o)); /* clone object */
		o2.noencodepng = true;

		grunt.log.writeln("Coloring SVG files");
		// create the tmp directory
		var tmp = path.join( config.tmpPath, config.tmpDir );
		if( fs.existsSync( tmp ) ){
			fs.removeSync( tmp );
		}
		fs.mkdirpSync( tmp );
		var colorFiles;
		try{
			var dc = new DirectoryColorfy( config.src, tmp, {
				colors: config.colors,
				dynamicColorOnly: config.dynamicColorOnly
			});
			colorFiles = dc.convert();
		} catch( e ){
			grunt.fatal(e);
			done( false );
		}

		//copy non color config files into temp directory
		var transferFiles = this.files.filter( function( f ){
			return !f.src[0].match( /\.colors/ );
		});

		transferFiles.forEach( function( f ){
			var filenameArr = f.src[0].split( "/" ),
				filename = filenameArr[filenameArr.length - 1];
			fs.copySync( f.src[0], path.join( tmp, filename ) );
		});

		grunt.log.writeln("Converting SVG to PNG");
		svgToPng.convert( tmp, config.dest, svgToPngOpts )
		.then( function( result , err ){
			if( err ){
				grunt.fatal( err );
			}

			var svgde = new DirectoryEncoder(tmp, path.join( config.dest, config.datasvgcss ), o ),
				pngde = new DirectoryEncoder( path.join( config.dest, pngfolder ) , path.join( config.dest, config.datapngcss ), o ),
				pngdefall = new DirectoryEncoder( path.join( config.dest, pngfolder ) , path.join( config.dest, config.urlpngcss ), o2 );

			grunt.log.writeln("Writing CSS");
			try {
				svgde.encode();
				pngde.encode();
				pngdefall.encode();
			} catch( e ){
				grunt.fatal( e );
				done( false );
			}

			grunt.log.writeln( "Grunticon now creating Preview File" );
			try {
				helper.createPreview( tmp, config );
			} catch(er) {
				grunt.fatal(er);
			}

			grunt.log.writeln( "Delete Temp Files" );
			fs.removeSync( tmp );
			done();
		});

	});
};
<commit_msg>Tell grunticon to leave appropriately<commit_after>/*
 * grunticon
 * https://github.com/filamentgroup/grunticon
 *
 * Copyright (c) 2012 Scott Jehl, Filament Group, Inc
 * Licensed under the MIT license.
 */

/*global __dirname:true*/
/*global require:true*/

module.exports = function( grunt , undefined ) {

	"use strict";

	var path = require( 'path' );
	var os = require( 'os' );

	var fs = require( 'fs-extra' );
	var uglify = require( 'uglify-js' );
	var RSVP = require( 'rsvp' );

	var DirectoryColorfy = require( 'directory-colorfy' );
	var DirectoryEncoder = require( 'directory-encoder' );
	var svgToPng = require( 'svg-to-png' );

	var helper = require( path.join( '..', 'lib', 'grunticon-helper' ) );

	grunt.registerMultiTask( 'grunticon', 'A mystical CSS icon solution.', function() {
		var done = this.async();

		// get the config
		var config = this.options({
			datasvgcss: "icons.data.svg.css",
			datapngcss: "icons.data.png.css",
			urlpngcss: "icons.fallback.css",
			files: {
				loader: path.join( __dirname, 'grunticon', 'static', 'grunticon.loader.js'),
				banner: path.join( __dirname, 'grunticon', 'static', 'grunticon.loader.banner.js')
			},
			previewhtml: "preview.html",
			loadersnippet: "grunticon.loader.js",
			cssbasepath: path.sep,
			customselectors: {},
			cssprefix: ".icon-",
			defaultWidth: "400px",
			defaultHeight: "300px",
			colors: {},
			dynamicColorOnly: false,
			pngfolder: "png",
			pngpath: "",
			template: "",
			tmpPath: os.tmpDir(),
			tmpDir: "grunticon-tmp",
			previewTemplate: path.join( __dirname, "..", "example", "preview.hbs" )
		});

		// just a quick starting message
		grunt.log.writeln( "Look, it's a grunticon!" );

		var files = this.files.filter( function( file ){
			return file.src[0].match( /png|svg/ );
		});
		if( files.length === 0 ){
			grunt.log.writeln( "Grunticon has no files to read!" );
			done();
			return;
		}

		files = files.map( function( file ){
			return file.src[0];
		});

		config.src = this.files[0].orig.cwd;
		config.dest = this.files[0].orig.dest;

		if( !config.dest || config.dest && config.dest === "" ){
			grunt.fatal("The destination must be a directory");
			done( false );
		}

		// folder name (within the output folder) for generated png files
		var pngfolder = path.join.apply( null, config.pngfolder.split( path.sep ) );

		// create the output directory
		fs.mkdirpSync( config.dest );

		// minify the source of the grunticon loader and write that to the output
		grunt.log.writeln( "grunticon now minifying the stylesheet loader source." );
		var banner = fs.readFileSync( config.files.banner );
		config.min = banner + "\n" + uglify.minify( config.files.loader ).code;
		fs.writeFileSync( path.join( config.dest, config.loadersnippet ), config.min );
		grunt.log.writeln( "grunticon loader file created." );

		var svgToPngOpts = {
			pngfolder: pngfolder,
			defaultWidth: config.defaultWidth,
			defaultHeight: config.defaultHeight
		};

		var o = {
			pngfolder: pngfolder,
			pngpath: config.pngpath,
			customselectors: config.customselectors,
			template: path.resolve( config.template ),
			previewTemplate: path.resolve( config.previewTemplate ),
			noencodepng: false,
			prefix: config.cssprefix
		};

		var o2 = JSON.parse(JSON.stringify(o)); /* clone object */
		o2.noencodepng = true;

		grunt.log.writeln("Coloring SVG files");
		// create the tmp directory
		var tmp = path.join( config.tmpPath, config.tmpDir );
		if( fs.existsSync( tmp ) ){
			fs.removeSync( tmp );
		}
		fs.mkdirpSync( tmp );
		var colorFiles;
		try{
			var dc = new DirectoryColorfy( config.src, tmp, {
				colors: config.colors,
				dynamicColorOnly: config.dynamicColorOnly
			});
			colorFiles = dc.convert();
		} catch( e ){
			grunt.fatal(e);
			done( false );
		}

		//copy non color config files into temp directory
		var transferFiles = this.files.filter( function( f ){
			return !f.src[0].match( /\.colors/ );
		});

		transferFiles.forEach( function( f ){
			var filenameArr = f.src[0].split( "/" ),
				filename = filenameArr[filenameArr.length - 1];
			fs.copySync( f.src[0], path.join( tmp, filename ) );
		});

		grunt.log.writeln("Converting SVG to PNG");
		svgToPng.convert( tmp, config.dest, svgToPngOpts )
		.then( function( result , err ){
			if( err ){
				grunt.fatal( err );
				done( false );
			}

			var svgde = new DirectoryEncoder(tmp, path.join( config.dest, config.datasvgcss ), o ),
				pngde = new DirectoryEncoder( path.join( config.dest, pngfolder ) , path.join( config.dest, config.datapngcss ), o ),
				pngdefall = new DirectoryEncoder( path.join( config.dest, pngfolder ) , path.join( config.dest, config.urlpngcss ), o2 );

			grunt.log.writeln("Writing CSS");
			try {
				svgde.encode();
				pngde.encode();
				pngdefall.encode();
			} catch( e ){
				grunt.fatal( e );
				done( false );
			}

			grunt.log.writeln( "Grunticon now creating Preview File" );
			try {
				helper.createPreview( tmp, config );
			} catch(er) {
				grunt.fatal(er);
				done( false );
			}

			grunt.log.writeln( "Delete Temp Files" );
			fs.removeSync( tmp );
			done();
		});

	});
};
<|endoftext|>


<commit_before>/* eslint-disable no-console */

const path = require('path');
const checker = require('license-checker');
const fs = require('fs');

const timerMessage = 'package.json dependencies written to frontend_licenses.json';
const timerMessageDev = 'dummy package.json dependencies written to frontend_licenses.json';

if (process.env.NODE_ENV === 'production') {
  console.time(timerMessage);
  checker.init({
    start: '.',
    json: path.resolve('../frontend_licenses.json')
  }, (err, json) => {
    if (err) {
      throw err;
    } else {
      const newJson = {};
      Object.keys(json).forEach((key) => {
        const value = json[key];
        delete value.licenseFile;
        newJson[key] = value;
      });

    //   console.log(newJson);
      fs.writeFile(path.resolve('./src/main/resources/static/license/frontend_licenses.json'), JSON.stringify(newJson), (err2) => {
        if (err2) {
          throw err2;
        }
      });
      console.timeEnd(timerMessage);
      return newJson;
    }
  });
} else {
  console.time(timerMessageDev);
  const dummyPackage = { 'dummypackage@0.0.1': {
    licenses: 'MIT',
    repository: 'http://github.com/dummypackage'
  } };

  fs.writeFile(path.resolve('./src/main/resources/static/license/frontend_licenses.json'), JSON.stringify(dummyPackage), (err2) => {
    if (err2) {
      throw err2;
    }
  });

  console.timeEnd(timerMessageDev);
}
<commit_msg>fix travis not creating directory<commit_after>/* eslint-disable no-console */

const path = require('path');
const checker = require('license-checker');
const fs = require('fs');

const timerMessage = 'package.json dependencies written to frontend_licenses.json';
const timerMessageDev = 'dummy package.json dependencies written to frontend_licenses.json';

if (process.env.NODE_ENV === 'production') {
  console.time(timerMessage);
  checker.init({
    start: '.',
    json: path.resolve('../frontend_licenses.json')
  }, (err, json) => {
    if (err) {
      throw err;
    } else {
      const newJson = {};
      Object.keys(json).forEach((key) => {
        const value = json[key];
        delete value.licenseFile;
        newJson[key] = value;
      });

      //   console.log(newJson);
      fs.mkdirSync(path.resolve('./src/main/resources/static/license/'));
      fs.writeFile(path.resolve('./src/main/resources/static/license/frontend_licenses.json'), JSON.stringify(newJson), (err2) => {
        if (err2) {
          throw err2;
        }
      });
      console.timeEnd(timerMessage);
      return newJson;
    }
  });
} else {
  console.time(timerMessageDev);
  const dummyPackage = { 'dummypackage@0.0.1': {
    licenses: 'MIT',
    repository: 'http://github.com/dummypackage'
  } };

  fs.writeFile(path.resolve('./src/main/resources/static/license/frontend_licenses.json'), JSON.stringify(dummyPackage), (err2) => {
    if (err2) {
      throw err2;
    }
  });

  console.timeEnd(timerMessageDev);
}
<|endoftext|>


<commit_before>define([
	'jquery',
	'underscore',
	'backbone',
	'config',
	'utils',
	'text!templates/data-detail.html',
	'views/panel-view-base'
], function($, _, Backbone, config, utils, templateHtml, PanelViewBase) {
    "use strict";

	var DataDetailView = PanelViewBase.extend({

		className: 'panel data-detail',

	    events: {
	    },

	    initialize: function(options)
	    {
	    	DataDetailView.__super__.initialize.call(this, options);
		    this.template = _.template(templateHtml);

	    	this.defaultLayout = [
	    		{fields: ['properties.icon'], label: false, formatter: 'icon', class: 'icon muted'},
	    		{fields: ['%(label)s', '%(datetime)s'], label: false, class: "box title"},
	    		{fields: ['%(numeric)s'], label: '%(numeric)s', class: 'large'},
	    		{fields: ['properties.description'], label: false, class: 'box text-body muted'},
	    		{fields: ['properties.$other'], label: '%(field)s', class: 'text-body muted'},

	    		{fields: ['count'], label: __('no. of %(itemTitlePlural)s'), class: 'muted'},
	    		{fields: ['%(numeric)s.max'], label: 'peak', class: 'muted'},
	    		{fields: ['%(numeric)s.min'], label: 'minimum', class: 'muted'},
	    		{fields: ['%(numeric)s.avg'], label: 'average', class: 'muted'}
	    	];
	    },

	    setModel: function(model)
	    {
	    	if (this.model) {
	    		this.stopListening(this.model);
	    		if (this.model.collection && this.model.collection.mapLayer)
	    			this.stopListening(this.model.collection.mapLayer);
	    	}
	    	this.model = model;
	    	this.populateFromModel();
	    	this.listenTo(model.collection.mapLayer,
	    		'change', this.populateFromModel);
	    	this.listenTo(model.collection.mapLayer,
	    		'toggle:valFormatter', this.populateFromModel);
	    },

	    populateFromModel: function()
		{
			var model = this.model,
				rows = this.compileDetailDataForModel(model),
				body = this.$('.panel-body');

			var makeRow = function(o) {
				var span = o.class ? '' : '';
				if (o.label != undefined && o.value != undefined) {
					return '
' + span + o.label + '	' + span + o.value + '
';
				} else if (o.label != undefined) {
					return '
' + span + o.label + '
';
				} else if (o.value != undefined) {
					return '
' + span + o.value + '
';
				}
				return '';
			};

			var table = $('.detail-data', body),
				tableRows = [];
			for (var i = 0; i < rows.length; i++) {
				tableRows.push(makeRow(rows[i]));
			}

			table.html(tableRows.join('\n'));
			if (this.model.collection && this.model.collection.mapLayer) {
				this.$('.model-title').text(this.model.collection.mapLayer.getDisplay('title'));
			}
		},

	    compileDetailDataForModel: function(model)
	    {
	    	if (!model.collection) return [];
	    	var mapLayer = model.collection.mapLayer,
				layerOptions = mapLayer.getLayerOptions(),
				layout = mapLayer.getDisplay('detailLayout') || this.defaultLayout,
				valFormatter = mapLayer.getValFormatter(),
				displayedFields = {};

			var isDate = function(value) {
				return value instanceof Date;
			};

			var isEmpty = function(value) {
				return !isDate(value)
					&& ((typeof value == 'object' && _.isEmpty(value))
					|| (!value && value != 0) || value === '');
			};

			var getValue = function(value, formatter) {
				if (isDate(value) || typeof value != 'object') return formatter ? formatter.format(value) : value;
				if (value.value != undefined) return getValue(value.value, formatter);
				if (value.avg != undefined) return getValue(value.avg, formatter);
				if (Array.isArray(value)) {
					return value.join(', ');
				}
				var minMax = formatter.minMaxFormat || __('%(min)s to %(max)s');
				return __(minMax).format({
						min: getValue(value.min, formatter),
						max: getValue(value.max, formatter)
					});
			};

			var formatters = {
				date: {
					format: function(value) {
						var value = value instanceof Date ? value : new Date(value);
						return value.format(layerOptions.datetimeFormat || locale.formats.DATE_SHORT);
					}
				},
				numeric: valFormatter,
				icon: {
					format: function(value) {
						return '';
					}
				}
			};

			formatters.icon.minMaxFormat = __('%(min)s %(max)s');
			formatters.date.minMaxFormat = formatters.numeric.minMaxFormat = __('%(min)s–%(max)s');

			var fieldSubst = !layerOptions.attrMap ? {} : {
				'numeric': layerOptions.attrMap.numeric,
				'datetime': layerOptions.attrMap.datetime,
				'label': layerOptions.attrMap.label
			};

			var fields = mapLayer.getFeatureCollectionAttr('fields');

			var labelSubst = {
				'numeric': !isEmpty(valFormatter.unit) ? valFormatter.unit :
					(fieldSubst.numeric && fields ? fields.reduce(function(a, b) {
						if (b.name == fieldSubst.numeric) return b.label;
						return a;
					}) : __('Value')),
				'unit': valFormatter.unit,
				'itemTitlePlural': mapLayer.getDisplay('itemTitlePlural') || __('samples'),
			};

			var rows = [];

			_.each(layout, function(row) {
				var content = [];
				var addToContent = function(content, fieldName, field, row) {
					var value = model.get(fieldName),
						formatter = row.formatter ? formatters[row.formatter] : false;
					displayedFields[fieldName] = true;
					if (!isEmpty(value)) {
						switch (field.split('.')[0]) {
							case '%(datetime)s':
								formatter = formatters.date;
								break;
							case '%(numeric)s':
								formatter = formatters.numeric;
								break;
						};
						content.push(getValue(value, formatter));
					}
					return content;
				};

				var addRow = function(content, row)
				{
					if (content.length) {
						var out = content.join(row.join || '
');
						if (row.label) {
							rows.push({label: row.label.format(labelSubst), value: out, class: row.class});
						} else {
							rows.push({value: out, class: row.class});
						}
					}
				}

				_.each(row.fields, function(field) {
					var fieldName = field.format(fieldSubst);
					if (fieldName == 'properties.$other') {
						_.each(model.get('properties'), function(value, key) {
							if (!displayedFields['properties.' + key]) {
								var r = {
									label: row.label ? row.label.format(_.extend(fieldSubst, {field: key})) : false,
									class: row.class,
									formatter: row.formatter
								}
								addRow(addToContent([], 'properties.' + key, field, r), r);
							}
						});
					} else {
						addToContent(content, fieldName, field, row);
					}
				});
				addRow(content, row);

			});

			return rows;
	    }

	});

	return DataDetailView;
});
<commit_msg>Enabled number formatting for counts<commit_after>define([
	'jquery',
	'underscore',
	'backbone',
	'config',
	'utils',
	'text!templates/data-detail.html',
	'views/panel-view-base'
], function($, _, Backbone, config, utils, templateHtml, PanelViewBase) {
    "use strict";

	var DataDetailView = PanelViewBase.extend({

		className: 'panel data-detail',

	    events: {
	    },

	    initialize: function(options)
	    {
	    	DataDetailView.__super__.initialize.call(this, options);
		    this.template = _.template(templateHtml);

	    	this.defaultLayout = [
	    		{fields: ['properties.icon'], label: false, formatter: 'icon', class: 'icon muted'},
	    		{fields: ['%(label)s', '%(datetime)s'], label: false, class: "box title"},
	    		{fields: ['%(numeric)s'], label: '%(numeric)s', class: 'large'},
	    		{fields: ['properties.description'], label: false, class: 'box text-body muted'},
	    		{fields: ['properties.$other'], label: '%(field)s', class: 'text-body muted'},

	    		{fields: ['count'], label: __('no. of %(itemTitlePlural)s'), formatter: 'numeric', class: 'muted'},
	    		{fields: ['%(numeric)s.max'], label: 'peak', class: 'muted'},
	    		{fields: ['%(numeric)s.min'], label: 'minimum', class: 'muted'},
	    		{fields: ['%(numeric)s.avg'], label: 'average', class: 'muted'}
	    	];
	    },

	    setModel: function(model)
	    {
	    	if (this.model) {
	    		this.stopListening(this.model);
	    		if (this.model.collection && this.model.collection.mapLayer)
	    			this.stopListening(this.model.collection.mapLayer);
	    	}
	    	this.model = model;
	    	this.populateFromModel();
	    	this.listenTo(model.collection.mapLayer,
	    		'change', this.populateFromModel);
	    	this.listenTo(model.collection.mapLayer,
	    		'toggle:valFormatter', this.populateFromModel);
	    },

	    populateFromModel: function()
		{
			var model = this.model,
				rows = this.compileDetailDataForModel(model),
				body = this.$('.panel-body');

			var makeRow = function(o) {
				var span = o.class ? '' : '';
				if (o.label != undefined && o.value != undefined) {
					return '
' + span + o.label + '	' + span + o.value + '
';
				} else if (o.label != undefined) {
					return '
' + span + o.label + '
';
				} else if (o.value != undefined) {
					return '
' + span + o.value + '
';
				}
				return '';
			};

			var table = $('.detail-data', body),
				tableRows = [];
			for (var i = 0; i < rows.length; i++) {
				tableRows.push(makeRow(rows[i]));
			}

			table.html(tableRows.join('\n'));
			if (this.model.collection && this.model.collection.mapLayer) {
				this.$('.model-title').text(this.model.collection.mapLayer.getDisplay('title'));
			}
		},

	    compileDetailDataForModel: function(model)
	    {
	    	if (!model.collection) return [];
	    	var mapLayer = model.collection.mapLayer,
				layerOptions = mapLayer.getLayerOptions(),
				layout = mapLayer.getDisplay('detailLayout') || this.defaultLayout,
				valFormatter = mapLayer.getValFormatter(),
				displayedFields = {};

			var isDate = function(value) {
				return value instanceof Date;
			};

			var isEmpty = function(value) {
				return !isDate(value)
					&& ((typeof value == 'object' && _.isEmpty(value))
					|| (!value && value != 0) || value === '');
			};

			var getValue = function(value, formatter) {
				if (isDate(value) || typeof value != 'object') return formatter ? formatter.format(value) : value;
				if (value.value != undefined) return getValue(value.value, formatter);
				if (value.avg != undefined) return getValue(value.avg, formatter);
				if (Array.isArray(value)) {
					return value.join(', ');
				}
				var minMax = formatter.minMaxFormat || __('%(min)s to %(max)s');
				return __(minMax).format({
						min: getValue(value.min, formatter),
						max: getValue(value.max, formatter)
					});
			};

			var formatters = {
				date: {
					format: function(value) {
						var value = value instanceof Date ? value : new Date(value);
						return value.format(layerOptions.datetimeFormat || locale.formats.DATE_SHORT);
					}
				},
				numeric: valFormatter,
				icon: {
					format: function(value) {
						return '';
					}
				}
			};

			formatters.icon.minMaxFormat = __('%(min)s %(max)s');
			formatters.date.minMaxFormat = formatters.numeric.minMaxFormat = __('%(min)s–%(max)s');

			var fieldSubst = !layerOptions.attrMap ? {} : {
				'numeric': layerOptions.attrMap.numeric,
				'datetime': layerOptions.attrMap.datetime,
				'label': layerOptions.attrMap.label
			};

			var fields = mapLayer.getFeatureCollectionAttr('fields');

			var labelSubst = {
				'numeric': !isEmpty(valFormatter.unit) ? valFormatter.unit :
					(fieldSubst.numeric && fields ? fields.reduce(function(a, b) {
						if (b.name == fieldSubst.numeric) return b.label;
						return a;
					}) : __('Value')),
				'unit': valFormatter.unit,
				'itemTitlePlural': mapLayer.getDisplay('itemTitlePlural') || __('samples'),
			};

			var rows = [];

			_.each(layout, function(row) {
				var content = [];
				var addToContent = function(content, fieldName, field, row) {
					var value = model.get(fieldName),
						formatter = row.formatter ? formatters[row.formatter] : false;
					displayedFields[fieldName] = true;
					if (!formatter && !isEmpty(value)) {
						switch (field.split('.')[0]) {
							case '%(datetime)s':
								formatter = formatters.date;
								break;
							case '%(numeric)s':
								formatter = formatters.numeric;
								break;
						};
						content.push(getValue(value, formatter));
					}
					return content;
				};

				var addRow = function(content, row)
				{
					if (content.length) {
						var out = content.join(row.join || '
');
						if (row.label) {
							rows.push({label: row.label.format(labelSubst), value: out, class: row.class});
						} else {
							rows.push({value: out, class: row.class});
						}
					}
				}

				_.each(row.fields, function(field) {
					var fieldName = field.format(fieldSubst);
					if (fieldName == 'properties.$other') {
						_.each(model.get('properties'), function(value, key) {
							if (!displayedFields['properties.' + key]) {
								var r = {
									label: row.label ? row.label.format(_.extend(fieldSubst, {field: key})) : false,
									class: row.class,
									formatter: row.formatter
								}
								addRow(addToContent([], 'properties.' + key, field, r), r);
							}
						});
					} else {
						addToContent(content, fieldName, field, row);
					}
				});
				addRow(content, row);

			});

			return rows;
	    }

	});

	return DataDetailView;
});
<|endoftext|>


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

// This script looks at the HTML files in the offline folder
// and isolates the markdown section in each page.

var page = require('webpage').create();
var fs = require('fs');

page.onConsoleMessage = function (msg) { console.log(msg); };

// code executed inside page
function fixPage() {

  function trim(s) {
    return s.replace(/^\s+|\s+$/g, '');
  }

  // set title to first header text
  // (replace any redundant mentions of ClojureScript)
  var header = document.querySelector('h1') || document.querySelector('h2');
  document.title = trim(header.innerText.replace('ClojureScript',''));

  // replace everything with .file box (markdown view)
  var file = document.querySelector('.file');
  file.style.marginTop = "0";
  document.body.innerHTML = file.outerHTML;

  // remove the file header
  document.querySelector('.file-header').innerHTML = "";

  // set width to tame formatting
  document.body.style.width = "900px";

  // make anchor links work
  var links = document.querySelectorAll('a');
  var i, link;
  for (i=0, len=links.length; i<len; i++) {
    link = links[i];
    if (link.id) {
      link.id = link.id.replace("user-content-", "");
    }
  };
}

function handlePage(file) {
  console.log("\n\nCLEANING", file);
  page.open(file, function () {
      page.evaluate(fixPage);
      fs.write(file, page.content, 'w');
      nextPage();
  });
}

function getHtmlFiles(path) {
  return fs.list(path)
           .filter(function(x) { return /\.html/.test(x); })
           .map(function (x) { return path + x; });
}

var rootPath = "offline/github.com/cljsinfo/api-refs/blob/catalog/";
var refsPath = rootPath + "refs/";
var pages = getHtmlFiles(rootPath)
             .concat(getHtmlFiles(refsPath));

function nextPage() {
  var file = pages.shift();
  if (!file) { phantom.exit() }
  handlePage(file);
}

nextPage();
<commit_msg>use native trim in clean script<commit_after>#!/usr/bin/env phantomjs

// This script looks at the HTML files in the offline folder
// and isolates the markdown section in each page.

var page = require('webpage').create();
var fs = require('fs');

page.onConsoleMessage = function (msg) { console.log(msg); };

// code executed inside page
function fixPage() {

  // set title to first header text
  // (replace any redundant mentions of ClojureScript)
  var header = document.querySelector('h1') || document.querySelector('h2');
  document.title = header.innerText.replace('ClojureScript','').trim();

  // replace everything with .file box (markdown view)
  var file = document.querySelector('.file');
  file.style.marginTop = "0";
  document.body.innerHTML = file.outerHTML;

  // remove the file header
  document.querySelector('.file-header').innerHTML = "";

  // set width to tame formatting
  document.body.style.width = "900px";

  // make anchor links work
  var links = document.querySelectorAll('a');
  var i, link;
  for (i=0, len=links.length; i<len; i++) {
    link = links[i];
    if (link.id) {
      link.id = link.id.replace("user-content-", "");
    }
  };
}

function handlePage(file) {
  console.log("\n\nCLEANING", file);
  page.open(file, function () {
      page.evaluate(fixPage);
      fs.write(file, page.content, 'w');
      nextPage();
  });
}

function getHtmlFiles(path) {
  return fs.list(path)
           .filter(function(x) { return /\.html/.test(x); })
           .map(function (x) { return path + x; });
}

var rootPath = "offline/github.com/cljsinfo/api-refs/blob/catalog/";
var refsPath = rootPath + "refs/";
var pages = getHtmlFiles(rootPath)
             .concat(getHtmlFiles(refsPath));

function nextPage() {
  var file = pages.shift();
  if (!file) { phantom.exit() }
  handlePage(file);
}

nextPage();
<|endoftext|>


<commit_before>/*
 * grunticon
 * https://github.com/filamentgroup/grunticon
 *
 * Copyright (c) 2012 Scott Jehl, Filament Group, Inc
 * Licensed under the MIT license.
 */

/*global __dirname:true*/
/*global require:true*/

module.exports = function( grunt , undefined ) {

	"use strict";

	var path = require( 'path' );
	var os = require( 'os' );

	var fs = require( 'fs-extra' );
	var uglify = require( 'uglify-js' );
	var RSVP = require( 'rsvp' );

	var DirectoryColorfy = require( 'directory-colorfy' );
	var DirectoryEncoder = require( 'directory-encoder' );
	var svgToPng = require( 'svg-to-png' );

	var helper = require( path.join( '..', 'lib', 'grunticon-helper' ) );

	grunt.registerMultiTask( 'grunticon', 'A mystical CSS icon solution.', function() {
		var done = this.async();

		// get the config
		var config = this.options({
			datasvgcss: "icons.data.svg.css",
			datapngcss: "icons.data.png.css",
			urlpngcss: "icons.fallback.css",
			files: {
				loader: path.join( __dirname, 'grunticon', 'static', 'grunticon.loader.js'),
				banner: path.join( __dirname, 'grunticon', 'static', 'grunticon.loader.banner.js')
			},
			previewhtml: "preview.html",
			loadersnippet: "grunticon.loader.js",
			cssbasepath: path.sep,
			customselectors: {},
			cssprefix: ".icon-",
			defaultWidth: "400px",
			defaultHeight: "300px",
			colors: {},
			pngfolder: "png",
			pngpath: "",
			template: "",
			previewTemplate: path.join( __dirname, "..", "example", "preview.hbs" )
		});

		var tmpFolderName = "grunticon-tmp";

		// just a quick starting message
		grunt.log.writeln( "Look, it's a grunticon!" );

		var files = this.files.filter( function( file ){
			return file.src[0].match( /png|svg/ );
		});
		if( files.length === 0 ){
			grunt.log.writeln( "Grunticon has no files to read!" );
			done();
		}

		files = files.map( function( file ){
			return file.src[0];
		});

		config.src = this.files[0].orig.cwd;
		config.dest = this.files[0].orig.dest;

		// folder name (within the output folder) for generated png files
		var pngfolder = path.join.apply( null, config.pngfolder.split( path.sep ) );

		// create the output directory
		grunt.file.mkdir( config.dest );

		// minify the source of the grunticon loader and write that to the output
		grunt.log.writeln( "grunticon now minifying the stylesheet loader source." );
		var banner = grunt.file.read( config.files.banner );
		var min = banner + "\n" + uglify.minify( config.files.loader ).code;
		grunt.file.write( path.join( config.dest, config.loadersnippet ), min );
		grunt.log.writeln( "grunticon loader file created." );

		var svgToPngOpts = {
			pngfolder: pngfolder,
			defaultWidth: config.defaultWidth,
			defaultHeight: config.defaultHeight
		};

		var o = {
			pngfolder: pngfolder,
			customselectors: config.customselectors,
			template: path.resolve( config.template ),
			previewTemplate: path.resolve( config.previewTemplate ),
			noencodepng: false,
			prefix: config.cssprefix
		};

		var o2 = {
			pngfolder: pngfolder,
			pngpath: config.pngpath,
			customselectors: config.customselectors,
			template: path.resolve( config.template ),
			previewTemplate: path.resolve( config.previewTemplate ),
			noencodepng: true,
			prefix: config.cssprefix
		};

		grunt.log.writeln("Coloring SVG files");
		var colorFiles;
		var tmp = path.join( os.tmpDir(), tmpFolderName );
		grunt.file.mkdir( tmp );
		try{
			var dc = new DirectoryColorfy( config.src, tmp, {
				colors: config.colors
			});
			colorFiles = dc.convert();
		} catch( e ){
			grunt.fatal(e);
			done( false );
		}

		//copy non color config files into temp directory
		var transferFiles = this.files.filter( function( f ){
			return !f.src[0].match( /\.colors/ );
		});

		transferFiles.forEach( function( f ){
			var filenameArr = f.src[0].split( "/" ),
				filename = filenameArr[filenameArr.length - 1];
			grunt.file.copy( f.src[0], path.join( tmp, filename ) );
		});

		grunt.log.writeln("Converting SVG to PNG");
		svgToPng.convert( tmp, config.dest, svgToPngOpts )
		.then( function( result , err ){
			if( err ){
				grunt.fatal( err );
			}

			var svgde = new DirectoryEncoder(tmp, path.join( config.dest, config.datasvgcss ), o ),
				pngde = new DirectoryEncoder( path.join( config.dest, pngfolder ) , path.join( config.dest, config.datapngcss ), o ),
				pngdefall = new DirectoryEncoder( path.join( config.dest, pngfolder ) , path.join( config.dest, config.urlpngcss ), o2 );

			grunt.log.writeln("Writing CSS");
			try {
				svgde.encode();
				pngde.encode();
				pngdefall.encode();
			} catch( e ){
				grunt.fatal( e );
				done( false );
			}

			grunt.log.writeln( "Grunticon now creating Preview File" );
			try {
				helper.createPreview(tmp, config.dest, config.defaultWidth, config.defaultHeight, min, config.previewhtml, config.cssprefix, config.previewTemplate);
			} catch(er) {
				grunt.fatal(er);
			}

			grunt.log.writeln( "Delete Temp Files" );
			fs.removeSync( tmp );
			done();
		});

	});
};
<commit_msg>Early return when Grunticon has no files to read<commit_after>/*
 * grunticon
 * https://github.com/filamentgroup/grunticon
 *
 * Copyright (c) 2012 Scott Jehl, Filament Group, Inc
 * Licensed under the MIT license.
 */

/*global __dirname:true*/
/*global require:true*/

module.exports = function( grunt , undefined ) {

	"use strict";

	var path = require( 'path' );
	var os = require( 'os' );

	var fs = require( 'fs-extra' );
	var uglify = require( 'uglify-js' );
	var RSVP = require( 'rsvp' );

	var DirectoryColorfy = require( 'directory-colorfy' );
	var DirectoryEncoder = require( 'directory-encoder' );
	var svgToPng = require( 'svg-to-png' );

	var helper = require( path.join( '..', 'lib', 'grunticon-helper' ) );

	grunt.registerMultiTask( 'grunticon', 'A mystical CSS icon solution.', function() {
		var done = this.async();

		// get the config
		var config = this.options({
			datasvgcss: "icons.data.svg.css",
			datapngcss: "icons.data.png.css",
			urlpngcss: "icons.fallback.css",
			files: {
				loader: path.join( __dirname, 'grunticon', 'static', 'grunticon.loader.js'),
				banner: path.join( __dirname, 'grunticon', 'static', 'grunticon.loader.banner.js')
			},
			previewhtml: "preview.html",
			loadersnippet: "grunticon.loader.js",
			cssbasepath: path.sep,
			customselectors: {},
			cssprefix: ".icon-",
			defaultWidth: "400px",
			defaultHeight: "300px",
			colors: {},
			pngfolder: "png",
			pngpath: "",
			template: "",
			previewTemplate: path.join( __dirname, "..", "example", "preview.hbs" )
		});

		var tmpFolderName = "grunticon-tmp";

		// just a quick starting message
		grunt.log.writeln( "Look, it's a grunticon!" );

		var files = this.files.filter( function( file ){
			return file.src[0].match( /png|svg/ );
		});
		if( files.length === 0 ){
			grunt.log.writeln( "Grunticon has no files to read!" );
			done();
			return;
		}

		files = files.map( function( file ){
			return file.src[0];
		});

		config.src = this.files[0].orig.cwd;
		config.dest = this.files[0].orig.dest;

		// folder name (within the output folder) for generated png files
		var pngfolder = path.join.apply( null, config.pngfolder.split( path.sep ) );

		// create the output directory
		grunt.file.mkdir( config.dest );

		// minify the source of the grunticon loader and write that to the output
		grunt.log.writeln( "grunticon now minifying the stylesheet loader source." );
		var banner = grunt.file.read( config.files.banner );
		var min = banner + "\n" + uglify.minify( config.files.loader ).code;
		grunt.file.write( path.join( config.dest, config.loadersnippet ), min );
		grunt.log.writeln( "grunticon loader file created." );

		var svgToPngOpts = {
			pngfolder: pngfolder,
			defaultWidth: config.defaultWidth,
			defaultHeight: config.defaultHeight
		};

		var o = {
			pngfolder: pngfolder,
			customselectors: config.customselectors,
			template: path.resolve( config.template ),
			previewTemplate: path.resolve( config.previewTemplate ),
			noencodepng: false,
			prefix: config.cssprefix
		};

		var o2 = {
			pngfolder: pngfolder,
			pngpath: config.pngpath,
			customselectors: config.customselectors,
			template: path.resolve( config.template ),
			previewTemplate: path.resolve( config.previewTemplate ),
			noencodepng: true,
			prefix: config.cssprefix
		};

		grunt.log.writeln("Coloring SVG files");
		var colorFiles;
		var tmp = path.join( os.tmpDir(), tmpFolderName );
		grunt.file.mkdir( tmp );
		try{
			var dc = new DirectoryColorfy( config.src, tmp, {
				colors: config.colors
			});
			colorFiles = dc.convert();
		} catch( e ){
			grunt.fatal(e);
			done( false );
		}

		//copy non color config files into temp directory
		var transferFiles = this.files.filter( function( f ){
			return !f.src[0].match( /\.colors/ );
		});

		transferFiles.forEach( function( f ){
			var filenameArr = f.src[0].split( "/" ),
				filename = filenameArr[filenameArr.length - 1];
			grunt.file.copy( f.src[0], path.join( tmp, filename ) );
		});

		grunt.log.writeln("Converting SVG to PNG");
		svgToPng.convert( tmp, config.dest, svgToPngOpts )
		.then( function( result , err ){
			if( err ){
				grunt.fatal( err );
			}

			var svgde = new DirectoryEncoder(tmp, path.join( config.dest, config.datasvgcss ), o ),
				pngde = new DirectoryEncoder( path.join( config.dest, pngfolder ) , path.join( config.dest, config.datapngcss ), o ),
				pngdefall = new DirectoryEncoder( path.join( config.dest, pngfolder ) , path.join( config.dest, config.urlpngcss ), o2 );

			grunt.log.writeln("Writing CSS");
			try {
				svgde.encode();
				pngde.encode();
				pngdefall.encode();
			} catch( e ){
				grunt.fatal( e );
				done( false );
			}

			grunt.log.writeln( "Grunticon now creating Preview File" );
			try {
				helper.createPreview(tmp, config.dest, config.defaultWidth, config.defaultHeight, min, config.previewhtml, config.cssprefix, config.previewTemplate);
			} catch(er) {
				grunt.fatal(er);
			}

			grunt.log.writeln( "Delete Temp Files" );
			fs.removeSync( tmp );
			done();
		});

	});
};
<|endoftext|>


<commit_before>angular.module('starter.services', ['ngResource'])

.factory('Vehicle', function ($resource) {
    return $resource('http://bustracker.pvta.com/infopoint/rest/vehicles/get/:vehicleId');
})

.factory('Route', function ($resource) {
    return $resource('http://bustracker.pvta.com/infopoint/rest/routedetails/get/:routeId');
})

.factory('Stop', function ($resource) {
    return $resource('http://bustracker.pvta.com/infopoint/rest/stops/get/:stopId');
})

.factory('Stops', function($resource){
    return $resource('http://bustracker.pvta.com/infopoint/rest/stops/getallstops');
})

.factory('RouteVehicles', function($resource){
    return $resource('http://bustracker.pvta.com/infopoint/rest/vehicles/getallvehiclesforroute?routeId=:routeId')
})

.factory('StopDeparture', function ($resource) {
    return $resource('http://bustracker.pvta.com/infopoint/rest/stopdepartures/get/:stopId');
})

.factory('StopList', function(){
  var stopsList = {};
  var pushToList = function(stop){
    var id = stop.StopId
    stopsList[id] = stop;
  };
  var pushEntireList = function(list){
    for(var i = 0; i < list.length; i++){
      var id = list[i].StopId;
      stopsList[id] = list[i];
    }
    return stopsList;
  };

  var getStopFromList = function(id){
    return stopsList[id];
  };

  var getEntireList = function(){
    return stopsList;
  }

  var isEmpty = function(){
    if(Object.keys(stopsList).length === 0) return true;
    else return false
  };

  return {
    pushEntireList: pushEntireList,
    getStopFromList: getStopFromList,
    getEntireList: getEntireList,
    pushToList: pushToList,
    isEmpty: isEmpty,
  };

})

.service('LatLong', function(){
  var latlong = [];
  return {
    push: function(lat, long){
      var p = {lat, long};
      latlong.push(p);
      console.log("LatLong push called" + JSON.stringify(latlong));
    },
    pop: function(){
      var x = latlong.pop();
      console.log("LatLong PULL called" + JSON.stringify(x));
      return x;
    }
  };
});

<commit_msg>Some error checking in StopList<commit_after>angular.module('starter.services', ['ngResource'])

.factory('Vehicle', function ($resource) {
    return $resource('http://bustracker.pvta.com/infopoint/rest/vehicles/get/:vehicleId');
})

.factory('Route', function ($resource) {
    return $resource('http://bustracker.pvta.com/infopoint/rest/routedetails/get/:routeId');
})

.factory('Stop', function ($resource) {
    return $resource('http://bustracker.pvta.com/infopoint/rest/stops/get/:stopId');
})

.factory('Stops', function($resource){
    return $resource('http://bustracker.pvta.com/infopoint/rest/stops/getallstops');
})

.factory('RouteVehicles', function($resource){
    return $resource('http://bustracker.pvta.com/infopoint/rest/vehicles/getallvehiclesforroute?routeId=:routeId')
})

.factory('StopDeparture', function ($resource) {
    return $resource('http://bustracker.pvta.com/infopoint/rest/stopdepartures/get/:stopId');
})

.factory('StopList', function(){
  var stopsList = {};
  var pushToList = function(stop){
    var id = stop.StopId
    stopsList[id] = stop;
  };
  var pushEntireList = function(list){
    for(var i = 0; i < list.length; i++){
      var id = list[i].StopId;
      stopsList[id] = list[i];
    }
    return stopsList;
  };

  var getStopFromList = function(id){
    if(stopsList[id] !== undefined) return stopsList[id];
    else return 0;
  };

  var getEntireList = function(){
    if(stopsList !== undefined) return stopsList;
    else return 0;
  }

  var isEmpty = function(){
    if(Object.keys(stopsList).length === 0) return true;
    else return false
  };

  return {
    pushEntireList: pushEntireList,
    getStopFromList: getStopFromList,
    getEntireList: getEntireList,
    pushToList: pushToList,
    isEmpty: isEmpty,
  };

})

.service('LatLong', function(){
  var latlong = [];
  return {
    push: function(lat, long){
      var p = {lat, long};
      latlong.push(p);
      console.log("LatLong push called" + JSON.stringify(latlong));
    },
    pop: function(){
      var x = latlong.pop();
      console.log("LatLong PULL called" + JSON.stringify(x));
      return x;
    }
  };
});

<|endoftext|>