<commit_before>angular.module('codeview', ['ui.router', 'firebase', 'ui.ace'])

.config(function($stateProvider, $locationProvider, $urlRouterProvider) {

  $stateProvider.state('home', {
    url: '/',
    templateUrl: 'templates/home.html',
    controller: 'HomeCtrl'
  }).state('find', {
    url: '/find/:type',
    templateUrl: 'templates/find.html',
    controller: 'FindCtrl'
  }).state('code', {
    url: '/code/:type',
    templateUrl: 'templates/code.html',
    controller: 'CodeCtrl'
  });

  $urlRouterProvider.otherwise('/');
})

.controller('HomeCtrl', function($scope) {
  $scope.test = 'asdf';
  // Closes the sidebar menu
  $("#menu-close").click(function(hi) {
    hi.preventDefault();
    $("#sidebar-wrapper").toggleClass("active");
  });

  // Opens the sidebar menu
  $("#menu-toggle").click(function(hi) {
    hi.preventDefault();
    $("#sidebar-wrapper").toggleClass("active");
  });

  // Scrolls to the selected menu item on the page
  $(function() {
    $('a[href*=#]:not([href=#])').click(function() {
      if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) {

        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
        if (target.length) {
          $('html,body').animate({
            scrollTop: target.offset().top
          }, 1000);
          return false;
        }
      }
    });
  });

  $("#validatedForm").submit(function(event) {

    var error = 0;

    clearerror("#erroremail");
    clearerror("#errorpassword");

    event.preventDefault();

    if (error != 1) {

      $("#submitButton").animate({
        "width": "240px"
      }, 800);
      $("#submitButton").val("Submitted successfully");

    }

    function isValidEmailAddress(emailAddress) {
      var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
      return pattern.test(emailAddress);
    };

    function isValidPassword(password) {
      var pattern = new RegExp(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{4,8}$/);
      return pattern.test(password);
    };

    function styleerror(errortype) {
      $(errortype).css("backgroundColor", "#CC6666");
      $(errortype).css("width", "240px");
      $(errortype).css("height", "20px");
      $(errortype).css("marginBottom", "10px");
      $(errortype).css("padding", "0px 5px 5px 15px");
    }

    function clearerror(errortype) {
      $(errortype).html("");
      $(errortype).css("backgroundColor", "none");
      $(errortype).css("width", "0");
      $(errortype).css("height", "0");
      $(errortype).css("marginBottom", "0");
      $(errortype).css("padding", "0");
    }

  });
})

.controller('FindCtrl', function($scope, $stateParams) {
  var type = $scope.type = $stateParams.type;
})

.controller('CodeCtrl', function($scope, $stateParams, Room, $http) {
  var coder = $scope.coder = mycoder = (($stateParams.type || 'code') === 'code');

  var aces = [];

  $scope.aceOpts = {
    theme: 'monokai',
    useWrapMode: true,
    rendererOptions: {
      fontSize: 13
    },
    onLoad: function(ace) {
      ace.$blockScrolling = Infinity;
      aces.push(ace);
    }
  };

  $scope.aceCons = {
    theme: 'ambiance',
    useWrapMode: true,
    rendererOptions: {
      fontSize: 13
    },
    onLoad: function(ace) {
      ace.$blockScrolling = Infinity;
    }
  };

  $scope.updateLang = function() {
    try {
      var mode = $scope.data.lang.id.split('/')[0];
      for (var i = 0; i < aces.length; i++) {
        var ace = aces[i];
        ace.getSession().setMode('ace/mode/' + mode.toLowerCase());
      }
    } catch (e) {
      console.log(e);
    }
  };

  $scope.mycode = '// Enter your code here.';
  $scope.theircode = '// Enter your code here.';

  $scope.data = {};
  var room = Room('test');
  room.$loaded().then(function() {
    $scope.data = room;
    $scope.mycode = coder ? room.code : room.code2;
    $scope.theircode = coder ? room.code2 : room.code;
    $scope.updateLang();
  });
  room.$bindTo($scope, 'data');

  if (coder) {
    // Edit code only
    $scope.$watch('mycode', function() {
      if ($scope.code) {
        $scope.data.code = $scope.mycode;
      }
    });
    $scope.$watch('data', function() {
      $scope.theircode = $scope.data.code2;
    });
  } else {
    // Edit code 2 only
    $scope.$watch('mycode', function() {
      if ($scope.code2) {
        $scope.data.code2 = $scope.mycode;
      }
    });
    $scope.$watch('data', function() {
      $scope.theircode = $scope.data.code;
    });
  }

  execute = function(code, person) {
    if (person)
      $scope.myoutput = 'Running program...';
    else
      $scope.theiroutput = 'Running program';
    $http.post('/execute', {
      code: code,
      lang: $scope.data.lang.id
    }).
    success(function(data, status, headers, config) {
      var output = "";
      if (data.error)
        output = data.error;
      else output = data.output + "\n" + data.status;
      console.log(data);
      if (person)
        $scope.myoutput = output;
      else
        $scope.theiroutput = output;
    }).
    error(function(data, status, headers, config) {
      alert("Failed to execute code");
    });
  }

  $scope.execute1 = function() {
    execute($scope.mycode, true);
  }

  $scope.execute2 = function() {
    execute($scope.theircode, false);
  }
  $scope.startmoxtra = function() {
    window.open("/moxtra/", "Voice Call", "width=600, height=500");
  }

  $scope.langs = [];
  $http.get('/langs').then(function(data) {
    $scope.langs = data.data;
  });
})

.factory('Room', function($firebase) {
  return function(room) {
    var ref = new Firebase("https://codeview1.firebaseio.com/rooms/").child(room);
    return $firebase(ref).$asObject();
  }
});
<commit_msg>Fix it<commit_after>angular.module('codeview', ['ui.router', 'firebase', 'ui.ace'])

.config(function($stateProvider, $locationProvider, $urlRouterProvider) {

  $stateProvider.state('home', {
    url: '/',
    templateUrl: 'templates/home.html',
    controller: 'HomeCtrl'
  }).state('find', {
    url: '/find/:type',
    templateUrl: 'templates/find.html',
    controller: 'FindCtrl'
  }).state('code', {
    url: '/code/:type',
    templateUrl: 'templates/code.html',
    controller: 'CodeCtrl'
  });

  $urlRouterProvider.otherwise('/');
})

.controller('HomeCtrl', function($scope) {
  $scope.test = 'asdf';
  // Closes the sidebar menu
  $("#menu-close").click(function(hi) {
    hi.preventDefault();
    $("#sidebar-wrapper").toggleClass("active");
  });

  // Opens the sidebar menu
  $("#menu-toggle").click(function(hi) {
    hi.preventDefault();
    $("#sidebar-wrapper").toggleClass("active");
  });

  // Scrolls to the selected menu item on the page
  $(function() {
    $('a[href*=#]:not([href=#])').click(function() {
      if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) {

        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
        if (target.length) {
          $('html,body').animate({
            scrollTop: target.offset().top
          }, 1000);
          return false;
        }
      }
    });
  });

  $("#validatedForm").submit(function(event) {

    var error = 0;

    clearerror("#erroremail");
    clearerror("#errorpassword");

    event.preventDefault();

    if (error != 1) {

      $("#submitButton").animate({
        "width": "240px"
      }, 800);
      $("#submitButton").val("Submitted successfully");

    }

    function isValidEmailAddress(emailAddress) {
      var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
      return pattern.test(emailAddress);
    };

    function isValidPassword(password) {
      var pattern = new RegExp(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{4,8}$/);
      return pattern.test(password);
    };

    function styleerror(errortype) {
      $(errortype).css("backgroundColor", "#CC6666");
      $(errortype).css("width", "240px");
      $(errortype).css("height", "20px");
      $(errortype).css("marginBottom", "10px");
      $(errortype).css("padding", "0px 5px 5px 15px");
    }

    function clearerror(errortype) {
      $(errortype).html("");
      $(errortype).css("backgroundColor", "none");
      $(errortype).css("width", "0");
      $(errortype).css("height", "0");
      $(errortype).css("marginBottom", "0");
      $(errortype).css("padding", "0");
    }

  });
})

.controller('FindCtrl', function($scope, $stateParams) {
  var type = $scope.type = $stateParams.type;
})

.controller('CodeCtrl', function($scope, $stateParams, Room, $http) {
  var coder = $scope.coder = mycoder = (($stateParams.type || 'code') === 'code');

  var aces = [];

  $scope.aceOpts = {
    theme: 'monokai',
    useWrapMode: true,
    rendererOptions: {
      fontSize: 13
    },
    onLoad: function(ace) {
      ace.$blockScrolling = Infinity;
      aces.push(ace);
    }
  };

  $scope.aceCons = {
    theme: 'ambiance',
    useWrapMode: true,
    rendererOptions: {
      fontSize: 13
    },
    onLoad: function(ace) {
      ace.$blockScrolling = Infinity;
    }
  };

  $scope.updateLang = function() {
    try {
      var mode = $scope.data.lang.id.split('/')[0];
      for (var i = 0; i < aces.length; i++) {
        var ace = aces[i];
        ace.getSession().setMode('ace/mode/' + mode.toLowerCase());
      }
    } catch (e) {
      console.log(e);
    }
  };

  $scope.mycode = '// Enter your code here.';
  $scope.theircode = '// Enter your code here.';

  $scope.data = {};
  var room = Room('test');
  room.$loaded().then(function() {
    $scope.data = room;
    $scope.mycode = coder ? room.code : room.code2;
    $scope.theircode = coder ? room.code2 : room.code;
    $scope.updateLang();
  });
  room.$bindTo($scope, 'data');

  if (coder) {
    // Edit code only
    $scope.$watch('mycode', function() {
      if ($scope.mycode) {
        $scope.data.code = $scope.mycode;
      }
    });
    $scope.$watch('data', function() {
      $scope.theircode = $scope.data.code2;
    });
  } else {
    // Edit code 2 only
    $scope.$watch('mycode', function() {
      if ($scope.mycode) {
        $scope.data.code2 = $scope.mycode;
      }
    });
    $scope.$watch('data', function() {
      $scope.theircode = $scope.data.code;
    });
  }

  execute = function(code, person) {
    if (person)
      $scope.myoutput = 'Running program...';
    else
      $scope.theiroutput = 'Running program';
    $http.post('/execute', {
      code: code,
      lang: $scope.data.lang.id
    }).
    success(function(data, status, headers, config) {
      var output = "";
      if (data.error)
        output = data.error;
      else output = data.output + "\n" + data.status;
      console.log(data);
      if (person)
        $scope.myoutput = output;
      else
        $scope.theiroutput = output;
    }).
    error(function(data, status, headers, config) {
      alert("Failed to execute code");
    });
  }

  $scope.execute1 = function() {
    execute($scope.mycode, true);
  }

  $scope.execute2 = function() {
    execute($scope.theircode, false);
  }
  $scope.startmoxtra = function() {
    window.open("/moxtra/", "Voice Call", "width=600, height=500");
  }

  $scope.langs = [];
  $http.get('/langs').then(function(data) {
    $scope.langs = data.data;
  });
})

.factory('Room', function($firebase) {
  return function(room) {
    var ref = new Firebase("https://codeview1.firebaseio.com/rooms/").child(room);
    return $firebase(ref).$asObject();
  }
});
<|endoftext|>


<commit_before>
function something()
	{
		var x = window.localStorage.getItem('abc');
		//x = parseInt(x);
		x = x *1 + 1;
		window.localStorage.setItem('abc', x)

		alert(x);
	}

function add_to_cart(id)
	{
		alert('Hello you added pizza with id '+ id);
	}<commit_msg>Update add_to_card function<commit_after>
function something()
	{
		var x = window.localStorage.getItem('abc');
		//x = parseInt(x);
		x = x *1 + 1;
		window.localStorage.setItem('abc', x)

		alert(x);
	}

function add_to_cart(id)
	{
		var key = 'product_'+id;
		var x = window.localStorage.getItem(key);
		x = x * 1 + 1;
		window.localStorage.setItem(key, x);
	}<|endoftext|>


<commit_before>/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
 * license.  See http://svn.openlayers.org/trunk/openlayers/license.txt for the
 * full text of the license. */

/**
 * @requires OpenLayers/Control.js
 */

/**
 * Class: OpenLayers.Control.MousePosition
 *
 * Inherits from:
 *  - <OpenLayers.Control>
 */
OpenLayers.Control.MousePosition = OpenLayers.Class(OpenLayers.Control, {

    /**
     * Property: element
     * {DOMElement}
     */
    element: null,

    /**
     * APIProperty: prefix
     * {String}
     */
    prefix: '',

    /**
     * APIProperty: separator
     * {String}
     */
    separator: ', ',

    /**
     * APIProperty: suffix
     * {String}
     */
    suffix: '',

    /**
     * APIProperty: numDigits
     * {Integer}
     */
    numDigits: 5,

    /**
     * APIProperty: granularity
     * {Integer}
     */
    granularity: 10,

    /**
     * Property: lastXy
     * {<OpenLayers.LonLat>}
     */
    lastXy: null,

    /**
     * APIProperty: displayProjection
     * {<OpenLayers.Projection>} A projection that the
     * mousecontrol will display.
     */
    displayProjection: null,

    /**
     * Constructor: OpenLayers.Control.MousePosition
     *
     * Parameters:
     * options - {DOMElement} Options for control.
     */
    initialize: function(options) {
        OpenLayers.Control.prototype.initialize.apply(this, arguments);
    },

    /**
     * Method: destroy
     */
     destroy: function() {
         if (this.map) {
             this.map.events.unregister('mousemove', this, this.redraw);
         }
         OpenLayers.Control.prototype.destroy.apply(this, arguments);
     },

    /**
     * Method: draw
     * {DOMElement}
     */
    draw: function() {
        OpenLayers.Control.prototype.draw.apply(this, arguments);

        if (!this.element) {
            this.div.left = "";
            this.div.top = "";
            this.element = this.div;
        }

        this.redraw();
        return this.div;
    },

    /**
     * Method: redraw
     */
    redraw: function(evt) {

        var lonLat;

        if (evt == null) {
            lonLat = new OpenLayers.LonLat(0, 0);
        } else {
            if (this.lastXy == null ||
                Math.abs(evt.xy.x - this.lastXy.x) > this.granularity ||
                Math.abs(evt.xy.y - this.lastXy.y) > this.granularity)
            {
                this.lastXy = evt.xy;
                return;
            }

            lonLat = this.map.getLonLatFromPixel(evt.xy);
            if (!lonLat) {
                // map has not yet been properly initialized
                return;
            }
            if (this.displayProjection) {
                lonLat.transform(this.map.getProjectionObject(),
                                 this.displayProjection );
            }
            this.lastXy = evt.xy;

        }

        var newHtml = this.formatOutput(lonLat);

        if (newHtml != this.element.innerHTML) {
            this.element.innerHTML = newHtml;
        }
    },

    /**
     * Method: formatOutput
     * Override to provide custom display output
     *
     * Parameters:
     * lonLat - {<OpenLayers.LonLat>} Location to display
     */
    formatOutput: function(lonLat) {
        var digits = parseInt(this.numDigits);
        var newHtml =
            this.prefix +
            lonLat.lon.toFixed(digits) +
            this.separator +
            lonLat.lat.toFixed(digits) +
            this.suffix;
        return newHtml;
     },

    /**
     * Method: setMap
     */
    setMap: function() {
        OpenLayers.Control.prototype.setMap.apply(this, arguments);
        this.map.events.register( 'mousemove', this, this.redraw);
    },

    CLASS_NAME: "OpenLayers.Control.MousePosition"
});
<commit_msg>minor doc error & enhancement in Control.MousePostion, p=aabt, r=me (closes #1872)<commit_after>/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
 * license.  See http://svn.openlayers.org/trunk/openlayers/license.txt for the
 * full text of the license. */

/**
 * @requires OpenLayers/Control.js
 */

/**
 * Class: OpenLayers.Control.MousePosition
 *
 * Inherits from:
 *  - <OpenLayers.Control>
 */
OpenLayers.Control.MousePosition = OpenLayers.Class(OpenLayers.Control, {

    /**
     * Property: element
     * {DOMElement}
     */
    element: null,

    /**
     * APIProperty: prefix
     * {String}
     */
    prefix: '',

    /**
     * APIProperty: separator
     * {String}
     */
    separator: ', ',

    /**
     * APIProperty: suffix
     * {String}
     */
    suffix: '',

    /**
     * APIProperty: numDigits
     * {Integer}
     */
    numDigits: 5,

    /**
     * APIProperty: granularity
     * {Integer}
     */
    granularity: 10,

    /**
     * Property: lastXy
     * {<OpenLayers.LonLat>}
     */
    lastXy: null,

    /**
     * APIProperty: displayProjection
     * {<OpenLayers.Projection>} The projection in which the
     * mouse position is displayed
     */
    displayProjection: null,

    /**
     * Constructor: OpenLayers.Control.MousePosition
     *
     * Parameters:
     * options - {Object} Options for control.
     */
    initialize: function(options) {
        OpenLayers.Control.prototype.initialize.apply(this, arguments);
    },

    /**
     * Method: destroy
     */
     destroy: function() {
         if (this.map) {
             this.map.events.unregister('mousemove', this, this.redraw);
         }
         OpenLayers.Control.prototype.destroy.apply(this, arguments);
     },

    /**
     * Method: draw
     * {DOMElement}
     */
    draw: function() {
        OpenLayers.Control.prototype.draw.apply(this, arguments);

        if (!this.element) {
            this.div.left = "";
            this.div.top = "";
            this.element = this.div;
        }

        this.redraw();
        return this.div;
    },

    /**
     * Method: redraw
     */
    redraw: function(evt) {

        var lonLat;

        if (evt == null) {
            lonLat = new OpenLayers.LonLat(0, 0);
        } else {
            if (this.lastXy == null ||
                Math.abs(evt.xy.x - this.lastXy.x) > this.granularity ||
                Math.abs(evt.xy.y - this.lastXy.y) > this.granularity)
            {
                this.lastXy = evt.xy;
                return;
            }

            lonLat = this.map.getLonLatFromPixel(evt.xy);
            if (!lonLat) {
                // map has not yet been properly initialized
                return;
            }
            if (this.displayProjection) {
                lonLat.transform(this.map.getProjectionObject(),
                                 this.displayProjection );
            }
            this.lastXy = evt.xy;

        }

        var newHtml = this.formatOutput(lonLat);

        if (newHtml != this.element.innerHTML) {
            this.element.innerHTML = newHtml;
        }
    },

    /**
     * Method: formatOutput
     * Override to provide custom display output
     *
     * Parameters:
     * lonLat - {<OpenLayers.LonLat>} Location to display
     */
    formatOutput: function(lonLat) {
        var digits = parseInt(this.numDigits);
        var newHtml =
            this.prefix +
            lonLat.lon.toFixed(digits) +
            this.separator +
            lonLat.lat.toFixed(digits) +
            this.suffix;
        return newHtml;
     },

    /**
     * Method: setMap
     */
    setMap: function() {
        OpenLayers.Control.prototype.setMap.apply(this, arguments);
        this.map.events.register( 'mousemove', this, this.redraw);
    },

    CLASS_NAME: "OpenLayers.Control.MousePosition"
});
<|endoftext|>


<commit_before>$(document).ready(function() {
  var options = {
      chart: {
        renderTo: 'chart',
        type: 'spline',
      },
      plotOptions: {
        spline: {
          marker: {
            enabled: true
          }
        }
      },
      title: {
        text: 'Recent Water Values'
      },
      xAxis: {
        type: 'datetime',
        title: {
          text: 'Date'
        }
      },
      yAxis: {
        labels: {
          formatter: function() {
            return this.value == 1 ? 'Wet' : 'Dry';
          }
        },
        min: 0,
        max: 1,
        tickInterval: 1,
        title: {
          text: null
        }
      },
      legend: {
        enabled: false
      },
      series: [{}]
  };

  Highcharts.setOptions({
    global: {
      useUTC: false
    }
  });

  // Don't cache the json :)
  $.ajaxSetup({
    cache:false
  });

  $.getJSON('data.json', function(data) {
    var series = [];

    // Store some stats while parsing through
    var lastStatus;
    var lastWet;
    var lastDry;
    $.each(data, function(key, value) {
      series.push([Date.parse(key), value]);
      lastStatus = value;

      if (value == 1) {
        lastWet = key;
      }

      if (value == 0) {
        lastDry = key;
      }
    });

    $('#current').text(lastStatus ? 'Wet' : 'Dry');
    $('#lastWet').text(lastWet);
    $('#lastDry').text(lastDry);

    options.series[0].data = series;
    options.series[0].color = '#449944';
    options.series[0].name = 'Water Value';
    var chart = new Highcharts.Chart(options);
  });

});
<commit_msg>Better handling of dates / missing data<commit_after>$(document).ready(function() {
  var options = {
      chart: {
        renderTo: 'chart',
        type: 'spline',
      },
      legend: {
        enabled: false
      },
      plotOptions: {
        spline: {
          marker: {
            enabled: true
          }
        }
      },
      series: [{}],
      title: {
        text: 'Recent Water Values'
      },
      tooltip: {
        xDateFormat: '%A, %B %d, %I:%M%p'
      },
      xAxis: {
        dateTimeLabelFormats: {
        	millisecond: '%I:%M:%S.%L',
        	second: '%I:%M:%S',
        	minute: '%I:%M%p',
        	hour: '%I:%M%p',
        	day: '%e. %b',
        	week: '%e. %b',
        	month: '%b \'%y',
        	year: '%Y'
        },
        type: 'datetime',
        title: {
          text: 'Date'
        }
      },
      yAxis: {
        labels: {
          formatter: function() {
            return this.value == 1 ? 'Wet' : 'Dry';
          }
        },
        min: 0,
        max: 1,
        tickInterval: 1,
        title: {
          text: null
        }
      }
  };

  Highcharts.setOptions({
    global: {
      useUTC: false
    }
  });

  // Don't cache the json :)
  $.ajaxSetup({
    cache:false
  });

  $.getJSON('data.json', function(data) {
    var series = [];

    // Store some stats while parsing through
    var lastStatus;
    var lastWet;
    var lastDry;
    $.each(data, function(key, value) {
      series.push([Date.parse(key), value]);
      lastStatus = value;

      if (value == 1) {
        lastWet = key;
      }

      if (value == 0) {
        lastDry = key;
      }
    });

    $('#current').text(lastStatus ? 'Wet' : 'Dry');
    if (lastWet != null && lastWet != undefined) {
      $('#lastWet').text(new Date(lastWet).toLocaleString());
    } else {
      $('#lastWet').text('Not enough data');
    }

    if (lastDry != null && lastDry != undefined) {
      $('#lastDry').text(new Date(lastDry).toLocaleString());
    } else {
      $('#lastDry').text('Not enough data');
    }

    options.series[0].data = series;
    options.series[0].color = '#449944';
    options.series[0].name = 'Water Value';
    var chart = new Highcharts.Chart(options);
  });

});
<|endoftext|>


<commit_before>// create our angular app and inject ngAnimate and ui-router
// =============================================================================
angular.module('locationTrackingApp', ['ngAnimate', 'ngRoute'])

/* VALUES */

.value("map", {})
    .value("watchID", null)
    .value("remotedb", 'https://USERNAME:PASSWORD@USERNAME.cloudant.com/locationtracker')
    .value("num", 0)
    .value("successMessage", {})
    .value("errorMessage", "error")
    .value("trackingMapInitialized", false)
    .value("resultMapInitialized", false)

/* ROUTES */

.config(['$routeProvider', function($routeProvider) {

    $routeProvider.
    when('/location/welcome', {
        templateUrl: 'location-welcome.html'
    }).
    when('/location/tracking', {
        templateUrl: 'location-tracking.html',
        controller: 'locationTrackingController'
    }).
    when('/location/savedata', {
        templateUrl: 'location-savedata.html',
        controller: 'locationTrackingSaveDataController'
    }).
    when('/location/success', {
        templateUrl: 'location-success.html',
        controller: 'locationTrackingSuccessController'
    }).
    when('/location/error', {
        templateUrl: 'location-error.html',
        controller: 'locationTrackingErrorController'
    }).
    when('/map/map', {
        templateUrl: 'map.html',
        controller: 'mapResultController'
    }).
    otherwise({
        redirectTo: '/location/welcome'
    })

}])

/* location-tracking.html Controller */

.controller('locationTrackingController', function($scope, map, watchID, pouchLocal, num, trackingMapInitialized) {

    var osmUrl = 'https://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png';
    var osmAttrib = 'Map data © OpenStreetMap contributors, ' +
        'CC-BY-SA, ' +
        'Imagery © Mapbox';
    var osm = new L.TileLayer(osmUrl, {
        attribution: osmAttrib,
        id: 'examples.map-i875mjb7'
    });
    if (!trackingMapInitialized) {
        var map = new L.Map('map', {
            layers: [osm],
            zoom: 18,
            zoomControl: true
        });
        trackingMapInitialized = true;
    }
    var last_lon = 0;
    var last_lat = 0;
    var session_id = guid();
    var db = pouchLocal;

    // add location control to global name space for testing only
    // on a production site, omit the "lc = "!
    lc = L.control.locate({
        follow: true,
        strings: {
            title: "Show me where I am, yo!"
        }
    }).addTo(map);
    /* */

    map.on('startfollowing', function() {
        map.on('dragstart', lc._stopFollowing, lc);
    }).on('stopfollowing', function() {
        map.off('dragstart', lc._stopFollowing, lc);
    });

    if (navigator.geolocation) {
        console.log("Geolocation is available");
    } else {
        alert("Geolocation IS NOT available!");
        document.getElementById('starter').disabled = true;
    }

    function onLocationFound(e) {
        console.log("onLocationFound");
        var radius = e.accuracy / 2;
        L.marker(e.latlng).addTo(map);
        lc.start();
    }

    function onLocationError(e) {
        console.log("onLocationError");
        alert("Rut ro... " + e.message);
    }

    function doWatch(position) {
        var lon = Number(Math.round(position.coords.longitude + 'e' + 4) + 'e-' + 4);
        var lat = Number(Math.round(position.coords.latitude + 'e' + 4) + 'e-' + 4);
        if ((lon == last_lon) && (lat == last_lat)) return null;

        last_lon = lon;
        last_lat = lat;
        var coord = {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [lon, lat]
            },
            "properties": {
                "session_id": session_id,
                "timestamp": position.timestamp
            }
        };

        db.post(coord, function callback(err, response) {
            if (err) {
                alert('POST ERROR: ' + err);
            }

            db.get(response.id, function callback(err, doc) {
                if (err) {
                    console.log('ERROR: ' + err);
                }

                console.log('GOT: ' + JSON.stringify(doc));
                $('.longitude-coordinate').text(doc.geometry.coordinates[0]);
                $('.latitude-coordinate').text(doc.geometry.coordinates[1]);
            });
        });
    }

    function watchError(err) {
        $('.longitude-coordinate, .latitude-coordinate').text("permission denied...");
        alert('Error' + err.code + ' msg: ' + err.message);
    }

    /**
     * Generates a GUID string.
     * @returns {String} The generated GUID.
     * @example af8a8416-6e18-a307-bd9c-f2c947bbb3aa
     * @author Slavik Meltser (slavik@meltser.info).
     * @link http://slavik.meltser.info/?p=142
     */
    function guid() {
        function _p8(s) {
            var p = (Math.random().toString(16) + "000000000").substr(2, 8);
            return s ? "-" + p.substr(0, 4) + "-" + p.substr(4, 4) : p;
        }
        return _p8() + _p8(true) + _p8(true) + _p8();
    }

    $('.longitude-coordinate, .latitude-coordinate').text("updating...");
    watchID = navigator.geolocation.watchPosition(doWatch, watchError);
    map.on('locationfound', onLocationFound);
    map.on('locationerror', onLocationError);
    map.locate({
        setView: true,
        maxZoom: 20
    });
})

.controller('locationTrackingSaveDataController', function($scope, map, watchID, pouchLocal, remotedb, successMessage, errorMessage) {

    navigator.geolocation.clearWatch(watchID);

    db = pouchLocal;

    setInterval(function() {
        $(".dot-anim")
            .velocity("transition.slideUpBigIn", {
                drag: true
            })
            .delay(750)
            .velocity({
                opacity: 0
            }, 750)
    }, 2000);

    db.replicate.to(remotedb).on('complete', function(info) {

        console.log("replicate complete");

        setTimeout(function() {
            successMessage.docs_written = info.docs_written;
            successMessage.start_time = info.start_time;
            window.location = "#/location/success";
        }, 2000)

    }).on('error', function(err) {
        console.log('error replicating: ' + err);

        errorMessage = 'error replicating: ' + err;
        window.location = "#/location/success";
    });
})

.controller('locationTrackingSuccessController', function($scope, successMessage) {

    console.log("locationTrackingSuccessController");
    console.log(successMessage);

    $scope.docs_written = successMessage.docs_written;
    $scope.start_time = successMessage.start_time;
})

.controller('locationTrackingErrorController', function($scope, errorMessage) {

    console.log("locationTrackingErrorController");
    console.log(errorMessage);

    $scope.error_message = errorMessage;
})

.controller('mapResultController', function($scope, pouchResult, resultMapInitialized) {

        console.log("mapResultController");

        console.log(pouchResult);

        var db = pouchResult;
        db.changes({
            include_docs: true,
            live: true
        }).on('change', updateMovingLayer);

        if (!resultMapInitialized) {
            var mapResult = new L.Map('mapResult');
            resultMapInitialized = true;
        }

        L.tileLayer('https://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png', {
            maxZoom: 20,
            attribution: 'Map data © ' +
                'OpenStreetMap contributors, ' +
                'CC-BY-SA',
            detectRetina: true,
            id: 'examples.map-20v6611k'
        }).addTo(mapResult);

        var movementLayer = L.geoJson(null, {
            pointToLayer: function(feature, latlng) {
                markeroptions = {
                    icon: L.icon({
                        iconUrl: 'js/images/marker-icon.png',
                        iconRetinaUrl: 'js/images/marker-icon-2x.png',
                        iconSize: [25, 41],
                        iconAnchor: [10, 10],
                        shadowURL: 'js/images/marker-icon-shadow.png',
                        shadowRetinaURL: 'js/images/marker-icon-shadow-2x.png',
                        shadowSize: [41, 41],
                        shadowAnchor: [10, 10]
                    })
                }
                return L.marker(latlng, markeroptions);
            }
        }).addTo(mapResult);

        function updateMovingLayer(change) {
            if (!change.doc._deleted && change.doc.type == 'Feature') {
                movementLayer.addData(change.doc);
                mapResult.fitBounds(movementLayer.getBounds());
            }
        }
    })
    .factory('pouchLocal', [function() {
        var db = new PouchDB('localdb');
        return db;
    }])
    .factory('pouchResult', ["remotedb", function(remotedb) {
        var db = new PouchDB(remotedb);
        return db;
    }])

/* Directive used on controller items to allow for multiple trans in/out */

.directive('locationdirective', ['$animate', '$timeout',
    function($animate, $timeout) {
        console.log("directive");
        return {
            restrict: 'A',
            link: function(scope, element, attrs) {
                console.log("directive 2");
                console.log(scope, element, attrs);
                $timeout(function() {

                    console.log('directive triggering inner animation');
                    $animate.addClass(element, 'anim-page-transition-js', function() {
                        console.log('animation complete!');
                    });

                }, 10);

            }
        }
    }
])

.animation('.anim-page-transition-js',
    function() {
        return {
            enter: function(element, done) {
                console.log('route enter animation triggered');

                var _element = $(element);
                $.each([".trans-step1", ".trans-step2", ".trans-step3", ".trans-step4"], function(index, value) {
                    _element.find(value)
                        .velocity({
                            opacity: 0,
                            translateY: "+200px"
                        }, {
                            duration: 0
                        })
                        .velocity({
                            opacity: 1,
                            translateY: "0"
                        }, {
                            easing: "easeInOutQuad", //[0.670, 0.010, 0.090, 0.970],
                            duration: 1000 + (index * 200),
                            delay: 1000 + (index * 100),
                            queue: false,
                            complete: function(elements) {
                                console.log('enter complete', value);
                            }
                        });
                });

                _element
                    .velocity({
                        opacity: 0,
                        translateY: "100%"
                    }, {
                        duration: 0
                    })
                    .velocity({
                        opacity: 1,
                        translateY: "0%"
                    }, {
                        easing: "easeInOutQuad", //[0.670, 0.010, 0.090, 0.970],
                        duration: 500,
                        delay: 1000,
                        queue: false,
                        complete: function(elements) {
                            console.log('enter complete');
                            done();
                        }
                    });

                _element.find(".trans-button")
                    .velocity({
                        opacity: 0,
                        translateY: "+100%"
                    }, {
                        duration: 0
                    })
                    .velocity({
                        opacity: 1,
                        translateY: "0%"
                    }, {
                        easing: "easeInOutQuad", //[0.670, 0.010, 0.090, 0.970],
                        delay: 1500,
                        queue: false,
                        complete: function(elements) {
                            console.log('enter trans-button complete');
                            done();
                        }
                    });

            },
            leave: function(element, done) {
                console.log('route leave animation triggered');
                var _element = $(element);

                _element.find(".trans-button")
                    .velocity({
                        opacity: 1,
                        translateY: "0%"
                    }, {
                        duration: 0
                    })
                    .velocity({
                        opacity: 0,
                        translateY: "+100%"
                    }, {
                        easing: "easeInOutQuad", //[0.670, 0.010, 0.090, 0.970],
                        duration: 1500,
                        delay: 0,
                        complete: function(elements) {
                            console.log('leave trans-button complete');
                            done();
                        }
                    });

                $.each([".trans-step1", ".trans-step2", ".trans-step3", ".trans-step4"], function(index, value) {
                    _element.find(value)
                        .velocity({
                            opacity: 1,
                            translateY: "0"
                        }, {
                            duration: 0
                        })
                        .velocity({
                            opacity: 0,
                            translateY: "-200px"
                        }, {
                            easing: "easeInOutQuad", //[0.670, 0.010, 0.090, 0.970],
                            duration: 1000 + (index * 200),
                            delay: (index * 100),
                            queue: false,
                            complete: function(elements) {
                                console.log('leave complete', value);
                            }
                        });
                });

                _element
                    .velocity({
                        opacity: 1,
                        translateY: "0%"
                    }, {
                        duration: 0
                    })
                    .velocity({
                        opacity: 0,
                        translateY: "-100%"
                    }, {
                        easing: "easeInOutQuad", //[0.670, 0.010, 0.090, 0.970],
                        duration: 1000,
                        delay: 1000,
                        queue: false,
                        // begin: function(elements) {}
                        complete: function(elements) {
                            console.log('leave complete');
                            $(element).remove();
                            done();
                        }
                    });
            }
        }
    }
);
<commit_msg>Prepend origin of current window location to database path<commit_after>// create our angular app and inject ngAnimate and ui-router
// =============================================================================
angular.module('locationTrackingApp', ['ngAnimate', 'ngRoute'])

/* VALUES */

.value("map", {})
    .value("watchID", null)
    .value("remotedb", window.location.origin + '/api/location-tracker')
    .value("num", 0)
    .value("successMessage", {})
    .value("errorMessage", "error")
    .value("trackingMapInitialized", false)
    .value("resultMapInitialized", false)

/* ROUTES */

.config(['$routeProvider', function($routeProvider) {

    $routeProvider.
    when('/location/welcome', {
        templateUrl: 'location-welcome.html'
    }).
    when('/location/tracking', {
        templateUrl: 'location-tracking.html',
        controller: 'locationTrackingController'
    }).
    when('/location/savedata', {
        templateUrl: 'location-savedata.html',
        controller: 'locationTrackingSaveDataController'
    }).
    when('/location/success', {
        templateUrl: 'location-success.html',
        controller: 'locationTrackingSuccessController'
    }).
    when('/location/error', {
        templateUrl: 'location-error.html',
        controller: 'locationTrackingErrorController'
    }).
    when('/map/map', {
        templateUrl: 'map.html',
        controller: 'mapResultController'
    }).
    otherwise({
        redirectTo: '/location/welcome'
    })

}])

/* location-tracking.html Controller */

.controller('locationTrackingController', function($scope, map, watchID, pouchLocal, num, trackingMapInitialized) {

    var osmUrl = 'https://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png';
    var osmAttrib = 'Map data © OpenStreetMap contributors, ' +
        'CC-BY-SA, ' +
        'Imagery © Mapbox';
    var osm = new L.TileLayer(osmUrl, {
        attribution: osmAttrib,
        id: 'examples.map-i875mjb7'
    });
    if (!trackingMapInitialized) {
        var map = new L.Map('map', {
            layers: [osm],
            zoom: 18,
            zoomControl: true
        });
        trackingMapInitialized = true;
    }
    var last_lon = 0;
    var last_lat = 0;
    var session_id = guid();
    var db = pouchLocal;

    // add location control to global name space for testing only
    // on a production site, omit the "lc = "!
    lc = L.control.locate({
        follow: true,
        strings: {
            title: "Show me where I am, yo!"
        }
    }).addTo(map);
    /* */

    map.on('startfollowing', function() {
        map.on('dragstart', lc._stopFollowing, lc);
    }).on('stopfollowing', function() {
        map.off('dragstart', lc._stopFollowing, lc);
    });

    if (navigator.geolocation) {
        console.log("Geolocation is available");
    } else {
        alert("Geolocation IS NOT available!");
        document.getElementById('starter').disabled = true;
    }

    function onLocationFound(e) {
        console.log("onLocationFound");
        var radius = e.accuracy / 2;
        L.marker(e.latlng).addTo(map);
        lc.start();
    }

    function onLocationError(e) {
        console.log("onLocationError");
        alert("Rut ro... " + e.message);
    }

    function doWatch(position) {
        var lon = Number(Math.round(position.coords.longitude + 'e' + 4) + 'e-' + 4);
        var lat = Number(Math.round(position.coords.latitude + 'e' + 4) + 'e-' + 4);
        if ((lon == last_lon) && (lat == last_lat)) return null;

        last_lon = lon;
        last_lat = lat;
        var coord = {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [lon, lat]
            },
            "properties": {
                "session_id": session_id,
                "timestamp": position.timestamp
            }
        };

        db.post(coord, function callback(err, response) {
            if (err) {
                alert('POST ERROR: ' + err);
            }

            db.get(response.id, function callback(err, doc) {
                if (err) {
                    console.log('ERROR: ' + err);
                }

                console.log('GOT: ' + JSON.stringify(doc));
                $('.longitude-coordinate').text(doc.geometry.coordinates[0]);
                $('.latitude-coordinate').text(doc.geometry.coordinates[1]);
            });
        });
    }

    function watchError(err) {
        $('.longitude-coordinate, .latitude-coordinate').text("permission denied...");
        alert('Error' + err.code + ' msg: ' + err.message);
    }

    /**
     * Generates a GUID string.
     * @returns {String} The generated GUID.
     * @example af8a8416-6e18-a307-bd9c-f2c947bbb3aa
     * @author Slavik Meltser (slavik@meltser.info).
     * @link http://slavik.meltser.info/?p=142
     */
    function guid() {
        function _p8(s) {
            var p = (Math.random().toString(16) + "000000000").substr(2, 8);
            return s ? "-" + p.substr(0, 4) + "-" + p.substr(4, 4) : p;
        }
        return _p8() + _p8(true) + _p8(true) + _p8();
    }

    $('.longitude-coordinate, .latitude-coordinate').text("updating...");
    watchID = navigator.geolocation.watchPosition(doWatch, watchError);
    map.on('locationfound', onLocationFound);
    map.on('locationerror', onLocationError);
    map.locate({
        setView: true,
        maxZoom: 20
    });
})

.controller('locationTrackingSaveDataController', function($scope, map, watchID, pouchLocal, remotedb, successMessage, errorMessage) {

    navigator.geolocation.clearWatch(watchID);

    db = pouchLocal;

    setInterval(function() {
        $(".dot-anim")
            .velocity("transition.slideUpBigIn", {
                drag: true
            })
            .delay(750)
            .velocity({
                opacity: 0
            }, 750)
    }, 2000);

    db.replicate.to(remotedb).on('complete', function(info) {

        console.log("replicate complete");

        setTimeout(function() {
            successMessage.docs_written = info.docs_written;
            successMessage.start_time = info.start_time;
            window.location = "#/location/success";
        }, 2000)

    }).on('error', function(err) {
        console.log('error replicating: ' + err);

        errorMessage = 'error replicating: ' + err;
        window.location = "#/location/success";
    });
})

.controller('locationTrackingSuccessController', function($scope, successMessage) {

    console.log("locationTrackingSuccessController");
    console.log(successMessage);

    $scope.docs_written = successMessage.docs_written;
    $scope.start_time = successMessage.start_time;
})

.controller('locationTrackingErrorController', function($scope, errorMessage) {

    console.log("locationTrackingErrorController");
    console.log(errorMessage);

    $scope.error_message = errorMessage;
})

.controller('mapResultController', function($scope, pouchResult, resultMapInitialized) {

        console.log("mapResultController");

        console.log(pouchResult);

        var db = pouchResult;
        db.changes({
            include_docs: true,
            live: true
        }).on('change', updateMovingLayer);

        if (!resultMapInitialized) {
            var mapResult = new L.Map('mapResult');
            resultMapInitialized = true;
        }

        L.tileLayer('https://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png', {
            maxZoom: 20,
            attribution: 'Map data © ' +
                'OpenStreetMap contributors, ' +
                'CC-BY-SA',
            detectRetina: true,
            id: 'examples.map-20v6611k'
        }).addTo(mapResult);

        var movementLayer = L.geoJson(null, {
            pointToLayer: function(feature, latlng) {
                markeroptions = {
                    icon: L.icon({
                        iconUrl: 'js/images/marker-icon.png',
                        iconRetinaUrl: 'js/images/marker-icon-2x.png',
                        iconSize: [25, 41],
                        iconAnchor: [10, 10],
                        shadowURL: 'js/images/marker-icon-shadow.png',
                        shadowRetinaURL: 'js/images/marker-icon-shadow-2x.png',
                        shadowSize: [41, 41],
                        shadowAnchor: [10, 10]
                    })
                }
                return L.marker(latlng, markeroptions);
            }
        }).addTo(mapResult);

        function updateMovingLayer(change) {
            if (!change.doc._deleted && change.doc.type == 'Feature') {
                movementLayer.addData(change.doc);
                mapResult.fitBounds(movementLayer.getBounds());
            }
        }
    })
    .factory('pouchLocal', [function() {
        var db = new PouchDB('localdb');
        return db;
    }])
    .factory('pouchResult', ["remotedb", function(remotedb) {
        var db = new PouchDB(remotedb);
        return db;
    }])

/* Directive used on controller items to allow for multiple trans in/out */

.directive('locationdirective', ['$animate', '$timeout',
    function($animate, $timeout) {
        console.log("directive");
        return {
            restrict: 'A',
            link: function(scope, element, attrs) {
                console.log("directive 2");
                console.log(scope, element, attrs);
                $timeout(function() {

                    console.log('directive triggering inner animation');
                    $animate.addClass(element, 'anim-page-transition-js', function() {
                        console.log('animation complete!');
                    });

                }, 10);

            }
        }
    }
])

.animation('.anim-page-transition-js',
    function() {
        return {
            enter: function(element, done) {
                console.log('route enter animation triggered');

                var _element = $(element);
                $.each([".trans-step1", ".trans-step2", ".trans-step3", ".trans-step4"], function(index, value) {
                    _element.find(value)
                        .velocity({
                            opacity: 0,
                            translateY: "+200px"
                        }, {
                            duration: 0
                        })
                        .velocity({
                            opacity: 1,
                            translateY: "0"
                        }, {
                            easing: "easeInOutQuad", //[0.670, 0.010, 0.090, 0.970],
                            duration: 1000 + (index * 200),
                            delay: 1000 + (index * 100),
                            queue: false,
                            complete: function(elements) {
                                console.log('enter complete', value);
                            }
                        });
                });

                _element
                    .velocity({
                        opacity: 0,
                        translateY: "100%"
                    }, {
                        duration: 0
                    })
                    .velocity({
                        opacity: 1,
                        translateY: "0%"
                    }, {
                        easing: "easeInOutQuad", //[0.670, 0.010, 0.090, 0.970],
                        duration: 500,
                        delay: 1000,
                        queue: false,
                        complete: function(elements) {
                            console.log('enter complete');
                            done();
                        }
                    });

                _element.find(".trans-button")
                    .velocity({
                        opacity: 0,
                        translateY: "+100%"
                    }, {
                        duration: 0
                    })
                    .velocity({
                        opacity: 1,
                        translateY: "0%"
                    }, {
                        easing: "easeInOutQuad", //[0.670, 0.010, 0.090, 0.970],
                        delay: 1500,
                        queue: false,
                        complete: function(elements) {
                            console.log('enter trans-button complete');
                            done();
                        }
                    });

            },
            leave: function(element, done) {
                console.log('route leave animation triggered');
                var _element = $(element);

                _element.find(".trans-button")
                    .velocity({
                        opacity: 1,
                        translateY: "0%"
                    }, {
                        duration: 0
                    })
                    .velocity({
                        opacity: 0,
                        translateY: "+100%"
                    }, {
                        easing: "easeInOutQuad", //[0.670, 0.010, 0.090, 0.970],
                        duration: 1500,
                        delay: 0,
                        complete: function(elements) {
                            console.log('leave trans-button complete');
                            done();
                        }
                    });

                $.each([".trans-step1", ".trans-step2", ".trans-step3", ".trans-step4"], function(index, value) {
                    _element.find(value)
                        .velocity({
                            opacity: 1,
                            translateY: "0"
                        }, {
                            duration: 0
                        })
                        .velocity({
                            opacity: 0,
                            translateY: "-200px"
                        }, {
                            easing: "easeInOutQuad", //[0.670, 0.010, 0.090, 0.970],
                            duration: 1000 + (index * 200),
                            delay: (index * 100),
                            queue: false,
                            complete: function(elements) {
                                console.log('leave complete', value);
                            }
                        });
                });

                _element
                    .velocity({
                        opacity: 1,
                        translateY: "0%"
                    }, {
                        duration: 0
                    })
                    .velocity({
                        opacity: 0,
                        translateY: "-100%"
                    }, {
                        easing: "easeInOutQuad", //[0.670, 0.010, 0.090, 0.970],
                        duration: 1000,
                        delay: 1000,
                        queue: false,
                        // begin: function(elements) {}
                        complete: function(elements) {
                            console.log('leave complete');
                            $(element).remove();
                            done();
                        }
                    });
            }
        }
    }
);
<|endoftext|>


<commit_before>function PhotoViewModel(data) {
  var self = this;

  self.stdAspectRatios = [[4, 3], [3, 2], [16, 9], [5, 3], [5, 4], [1, 1]];

  self.data = data;

  self.prevPhotoData = ko.observable();

  self.prevPhoto = ko.computed(function () {
    if (self.prevPhotoData()) {
      return new PhotoThumbViewModel(self.prevPhotoData());
    }
  });

  if (self.data.prev_photo_id) {
    $.getJSON('/photo', { id: self.data.prev_photo_id }, self.prevPhotoData);
  }

  self.nextPhotoData = ko.observable();

  self.nextPhoto = ko.computed(function () {
    if (self.nextPhotoData()) {
      return new PhotoThumbViewModel(self.nextPhotoData());
    }
  });

  if (self.data.next_photo_id) {
    $.getJSON('/photo', { id: self.data.next_photo_id }, self.nextPhotoData);
  }

  self.setData = ko.observable();

  self.set = ko.computed(function () {
    if (self.setData()) {
      return new SetThumbViewModel(self.setData());
    }
  });

  if (self.data.set_id) {
    $.getJSON('/set', { id: self.data.set_id }, self.setData);
  }

  self.aspectRatioText = function () {
    var aspectRatio = self.data.aspect_ratio;
    var exactMatch = _.find(self.stdAspectRatios, function (ar) {
      if (self.data.orientation === 'portrait') {
        ar[1] = [ar[0], ar[0] = ar[1]][0]; // swap hack
      }

      return ar[0] == aspectRatio[0] && ar[1] == aspectRatio[1];
    });

    if (exactMatch) { return aspectRatio.join(':'); }

    var closestMatch = _.sortBy(self.stdAspectRatios, function (ar) {
      return Math.abs((ar[0] / ar[1]) - (aspectRatio[0] / aspectRatio[1]));
    })[0];

    return '~' + closestMatch.join(':');
  };

  self.fileSize =  function () {
    return self.formatSize(self.data.size);
  };

  self.focalLength = function () {
    var fl = self.data.exif.FocalLength;
    var fl35 = self.data.exif.FocalLengthIn35mmFormat;

    if (!fl) { return; }

    fl = fl.replace('.0', '');

    if (!fl35) { return fl; }

    fl35 = fl35.replace('.0', '');

    if (fl === fl35) { return fl; }

    return fl + ' (' + fl35 + ')';
  };

  self.formatSize = function (bytes) {
    var n = bytes;

    if (n < 1024) { return _.pluralize(n, 'byte'); }

    n /= 1024; // kB

    if (n < 1024) { return self.round(n, 2) + ' kB'; }

    n /= 1024; // MB

    return self.round(n, 2) + ' MB';
  };

  self.round = function (n, scale) {
    if (_.isUndefined(scale)) { scale = 0; }
    return Math.round(n * Math.pow(10, scale)) / Math.pow(10, scale);
  }

  self.takenAtText = function () {
    return moment(self.data.taken_at).fromNow();
  };

  self.takenAtTitle = function () {
    return moment(self.data.taken_at).format('ddd, D MMM YYYY HH:mm:ss z');
  };
}

function PhotoThumbViewModel(data) {
  var self = this;

  self.data = data;
}

function SetThumbViewModel(data) {
  var self = this;

  self.data = data;

  self.photosCountTitle = function () {
    return _.pluralize(self.data.photos_count, 'photo');
  };

  self.shortName = function () {
    return _.trunc(self.data.name, 25);
  };
}

function ThymeViewModel() {
  var self = this;

  self.photoData = ko.observable();

  self.photo = ko.pureComputed({
    read: function () {
      if (self.photoData()) {
        return new PhotoViewModel(self.photoData());
      }
    },
    write: function (value) {
      self.photoData(value.data);
      location.hash = value.data.set_id + '/' + value.data.id;
    },
    owner: this
  });

  self.photosData = ko.observable();

  self.photos = ko.computed(function () {
    if (self.photosData()) {
      return _.map(self.photosData(), function (photoData) {
        return new PhotoThumbViewModel(photoData);
      });
    }
  });

  self.setsData = ko.observable();

  self.sets = ko.computed(function () {
    if (self.setsData()) {
      return _.map(self.setsData(), function (setData) {
        return new SetThumbViewModel(setData);
      });
    }
  });

  self.setData = ko.observable();

  self.set = function (value) {
    self.setData(value.data);
    location.hash = value.data.id;
  };

  self.pageTitle = ko.computed(function () {
    var parts = ['thyme'];

    if (self.setData()) {
      parts.push(self.setData().name);
    }
    else if (self.photo() && self.photo().setData()) {
      parts.push(self.photo().setData().name);
    }

    if (self.photo()) {
      parts.push(self.photo().data.filename);
    }

    return parts.join(' - ');
  });

  Sammy(function () {
    this.get('#:setId/:photoId', function () {
      self.photosData(null); // from photos

      if (!self.photoData()) { // direct (not from photos)
        $.getJSON('/photo', { id: this.params.photoId }, self.photoData);
      }
    });

    this.get('#:setId', function () {
      self.setsData(null); // from sets
      self.photoData(null); // from photo

      if (!self.setData()) { // direct (not from sets or photo)
        $.getJSON('/set', { id: this.params.setId }, self.setData);
      }

      $.getJSON('/photos', { set_id: this.params.setId }, self.photosData);
    });

    this.get('', function () {
      self.photosData(null); // back from set
      self.setData(null); // back from set
      $.getJSON('/sets', self.setsData);
    });
  }).run();
};

// lodash extensions
_.mixin({
  pluralize: function (n, singular, plural) {
    if (_.isUndefined(plural)) { plural = singular + 's'; }
    return n + ' ' + (n === 1 ? singular : plural);
  }
});

ko.bindingHandlers.photoMap = {
  init: function (element, valueAccessor) {
    var latlng = valueAccessor(); // [lat, lng]

    if (!_.isNumber(latlng[0]) || !_.isNumber(latlng[1])) { return; }

    $(element).show(); // show container before creating map

    $.getJSON('/config', function (configData) {
      var url = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'; // OpenStreetMap
      var options = {};
      var map = L.map(element).setView(latlng, 15);

      if (configData.mapbox_map_id && configData.mapbox_token) {
        url = 'http://{s}.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={token}';
        options = {
          id: configData.mapbox_map_id,
          token: configData.mapbox_token
        };
      }

      L.tileLayer(url, options).addTo(map);
      L.marker(latlng).addTo(map);
    });
  }
};

$(document).keydown(function (e) {
  switch (e.which) {
    case 37: // left
      if ($('#prev-photo').length > 0) {
        $('#prev-photo').click();
      }
      break;

    case 39: // right
      if ($('#next-photo').length > 0) {
        $('#next-photo').click();
      }
      break;

    default: return; // exit handler for other keys
  }

  e.preventDefault();
});

ko.applyBindings(new ThymeViewModel(), $('#thyme')[0]);
<commit_msg>Remove unnecessary prev/next photo link existence check<commit_after>function PhotoViewModel(data) {
  var self = this;

  self.stdAspectRatios = [[4, 3], [3, 2], [16, 9], [5, 3], [5, 4], [1, 1]];

  self.data = data;

  self.prevPhotoData = ko.observable();

  self.prevPhoto = ko.computed(function () {
    if (self.prevPhotoData()) {
      return new PhotoThumbViewModel(self.prevPhotoData());
    }
  });

  if (self.data.prev_photo_id) {
    $.getJSON('/photo', { id: self.data.prev_photo_id }, self.prevPhotoData);
  }

  self.nextPhotoData = ko.observable();

  self.nextPhoto = ko.computed(function () {
    if (self.nextPhotoData()) {
      return new PhotoThumbViewModel(self.nextPhotoData());
    }
  });

  if (self.data.next_photo_id) {
    $.getJSON('/photo', { id: self.data.next_photo_id }, self.nextPhotoData);
  }

  self.setData = ko.observable();

  self.set = ko.computed(function () {
    if (self.setData()) {
      return new SetThumbViewModel(self.setData());
    }
  });

  if (self.data.set_id) {
    $.getJSON('/set', { id: self.data.set_id }, self.setData);
  }

  self.aspectRatioText = function () {
    var aspectRatio = self.data.aspect_ratio;
    var exactMatch = _.find(self.stdAspectRatios, function (ar) {
      if (self.data.orientation === 'portrait') {
        ar[1] = [ar[0], ar[0] = ar[1]][0]; // swap hack
      }

      return ar[0] == aspectRatio[0] && ar[1] == aspectRatio[1];
    });

    if (exactMatch) { return aspectRatio.join(':'); }

    var closestMatch = _.sortBy(self.stdAspectRatios, function (ar) {
      return Math.abs((ar[0] / ar[1]) - (aspectRatio[0] / aspectRatio[1]));
    })[0];

    return '~' + closestMatch.join(':');
  };

  self.fileSize =  function () {
    return self.formatSize(self.data.size);
  };

  self.focalLength = function () {
    var fl = self.data.exif.FocalLength;
    var fl35 = self.data.exif.FocalLengthIn35mmFormat;

    if (!fl) { return; }

    fl = fl.replace('.0', '');

    if (!fl35) { return fl; }

    fl35 = fl35.replace('.0', '');

    if (fl === fl35) { return fl; }

    return fl + ' (' + fl35 + ')';
  };

  self.formatSize = function (bytes) {
    var n = bytes;

    if (n < 1024) { return _.pluralize(n, 'byte'); }

    n /= 1024; // kB

    if (n < 1024) { return self.round(n, 2) + ' kB'; }

    n /= 1024; // MB

    return self.round(n, 2) + ' MB';
  };

  self.round = function (n, scale) {
    if (_.isUndefined(scale)) { scale = 0; }
    return Math.round(n * Math.pow(10, scale)) / Math.pow(10, scale);
  }

  self.takenAtText = function () {
    return moment(self.data.taken_at).fromNow();
  };

  self.takenAtTitle = function () {
    return moment(self.data.taken_at).format('ddd, D MMM YYYY HH:mm:ss z');
  };
}

function PhotoThumbViewModel(data) {
  var self = this;

  self.data = data;
}

function SetThumbViewModel(data) {
  var self = this;

  self.data = data;

  self.photosCountTitle = function () {
    return _.pluralize(self.data.photos_count, 'photo');
  };

  self.shortName = function () {
    return _.trunc(self.data.name, 25);
  };
}

function ThymeViewModel() {
  var self = this;

  self.photoData = ko.observable();

  self.photo = ko.pureComputed({
    read: function () {
      if (self.photoData()) {
        return new PhotoViewModel(self.photoData());
      }
    },
    write: function (value) {
      self.photoData(value.data);
      location.hash = value.data.set_id + '/' + value.data.id;
    },
    owner: this
  });

  self.photosData = ko.observable();

  self.photos = ko.computed(function () {
    if (self.photosData()) {
      return _.map(self.photosData(), function (photoData) {
        return new PhotoThumbViewModel(photoData);
      });
    }
  });

  self.setsData = ko.observable();

  self.sets = ko.computed(function () {
    if (self.setsData()) {
      return _.map(self.setsData(), function (setData) {
        return new SetThumbViewModel(setData);
      });
    }
  });

  self.setData = ko.observable();

  self.set = function (value) {
    self.setData(value.data);
    location.hash = value.data.id;
  };

  self.pageTitle = ko.computed(function () {
    var parts = ['thyme'];

    if (self.setData()) {
      parts.push(self.setData().name);
    }
    else if (self.photo() && self.photo().setData()) {
      parts.push(self.photo().setData().name);
    }

    if (self.photo()) {
      parts.push(self.photo().data.filename);
    }

    return parts.join(' - ');
  });

  Sammy(function () {
    this.get('#:setId/:photoId', function () {
      self.photosData(null); // from photos

      if (!self.photoData()) { // direct (not from photos)
        $.getJSON('/photo', { id: this.params.photoId }, self.photoData);
      }
    });

    this.get('#:setId', function () {
      self.setsData(null); // from sets
      self.photoData(null); // from photo

      if (!self.setData()) { // direct (not from sets or photo)
        $.getJSON('/set', { id: this.params.setId }, self.setData);
      }

      $.getJSON('/photos', { set_id: this.params.setId }, self.photosData);
    });

    this.get('', function () {
      self.photosData(null); // back from set
      self.setData(null); // back from set
      $.getJSON('/sets', self.setsData);
    });
  }).run();
};

// lodash extensions
_.mixin({
  pluralize: function (n, singular, plural) {
    if (_.isUndefined(plural)) { plural = singular + 's'; }
    return n + ' ' + (n === 1 ? singular : plural);
  }
});

ko.bindingHandlers.photoMap = {
  init: function (element, valueAccessor) {
    var latlng = valueAccessor(); // [lat, lng]

    if (!_.isNumber(latlng[0]) || !_.isNumber(latlng[1])) { return; }

    $(element).show(); // show container before creating map

    $.getJSON('/config', function (configData) {
      var url = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'; // OpenStreetMap
      var options = {};
      var map = L.map(element).setView(latlng, 15);

      if (configData.mapbox_map_id && configData.mapbox_token) {
        url = 'http://{s}.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={token}';
        options = {
          id: configData.mapbox_map_id,
          token: configData.mapbox_token
        };
      }

      L.tileLayer(url, options).addTo(map);
      L.marker(latlng).addTo(map);
    });
  }
};

$(document).keydown(function (e) {
  switch (e.which) {
    case 37: // left
      $('#prev-photo').click();
      break;

    case 39: // right
      $('#next-photo').click();
      break;

    default: return; // exit handler for other keys
  }

  e.preventDefault();
});

ko.applyBindings(new ThymeViewModel(), $('#thyme')[0]);
<|endoftext|>


<commit_before>$(document).ready(function() {
    var localVideo = $('#local-video').get(0);
    var localAudio = $('#local-audio').get(0);
    var remoteVideo = $('#remote-video').get(0);
    var remoteAudio = $('#remote-audio').get(0);
    var peerConnection = new mozRTCPeerConnection();
    var source = new EventSource("/signalling");
    var me;

    peerConnection.onaddstream = function(obj) {
        console.log(obj);
        var type = obj.type;
        if (type == "video") {
            remoteVideo.mozSrcObject = obj.stream;
            remoteVideo.play();
        } else if (type == "audio") {
            remoteAudio.mozSrcObject = obj.stream;
            remoteAudio.play();
        } else {
            console.log("sender onaddstream of unknown type, obj = " + obj.toSource());
        }
    };

    source.addEventListener("uid", function(event) {
        event = JSON.parse(event.data);
        me    = event.uid;
        console.log('UID: ' + me);

    });

    source.addEventListener("newfriend", function(event) {
        event = JSON.parse(event.data);

        // Get local video
        navigator.mozGetUserMedia({video: true}, function(stream) {
            localVideo.mozSrcObject = stream;
            localVideo.play();
            peerConnection.addStream(stream);

            // Get local audio
            navigator.mozGetUserMedia({audio: true},function(stream) {
                localAudio.mozSrcObject = stream;
                localAudio.play();
                peerConnection.addStream(stream);

                // Create offer
                peerConnection.createOffer(function(offer) {
                    peerConnection.setLocalDescription(offer, function() {
                        // Send offer
                        $.ajax({
                            type: 'POST',
                            url:  '/signalling',
                            data: {
                                type: 'offer',
                                from: me,
                                offer: offer
                            }
                        });
                    });
                });

            }, function() {});
        }, function() {});
    });

    source.addEventListener("offer", function(event) {
        event = JSON.parse(event.data);

        if (event.from == me)
            return;

        peerConnection.setRemoteDescription(event.offer, function() {

            // Get local video
            navigator.mozGetUserMedia({video: true, fake: true}, function(stream) {
                localVideo.mozSrcObject = stream;
                localVideo.play();
                peerConnection.addStream(stream);

                // Get local audio
                navigator.mozGetUserMedia({audio: true, fake: true},function(stream) {
                    localAudio.mozSrcObject = stream;
                    localAudio.play();
                    peerConnection.addStream(stream);

                    // Create offer
                    peerConnection.createAnswer(function(answer) {
                        peerConnection.setLocalDescription(answer, function() {
                            // Send offer
                            $.ajax({
                                type: 'POST',
                                url:  '/signalling',
                                data: {
                                    type: 'answer',
                                    from: me,
                                    answer: answer
                                }
                            });
                        });
                    }, function() {});
                }, function() {});
            }, function() {});
        });
    });

    source.addEventListener('answer', function(event) {
        event = JSON.parse(event.data);
        console.log(event.answer);

        peerConnection.setRemoteDescription(event.answer, function() {
            console.log('done');
        });
    });

});

<commit_msg>App: remove the fake streams<commit_after>$(document).ready(function() {
    var localVideo = $('#local-video').get(0);
    var localAudio = $('#local-audio').get(0);
    var remoteVideo = $('#remote-video').get(0);
    var remoteAudio = $('#remote-audio').get(0);
    var peerConnection = new mozRTCPeerConnection();
    var source = new EventSource("/signalling");
    var me;

    peerConnection.onaddstream = function(obj) {
        console.log(obj);
        var type = obj.type;
        if (type == "video") {
            remoteVideo.mozSrcObject = obj.stream;
            remoteVideo.play();
        } else if (type == "audio") {
            remoteAudio.mozSrcObject = obj.stream;
            remoteAudio.play();
        } else {
            console.log("sender onaddstream of unknown type, obj = " + obj.toSource());
        }
    };

    source.addEventListener("uid", function(event) {
        event = JSON.parse(event.data);
        me    = event.uid;
        console.log('UID: ' + me);

    });

    source.addEventListener("newfriend", function(event) {
        event = JSON.parse(event.data);

        // Get local video
        navigator.mozGetUserMedia({video: true}, function(stream) {
            localVideo.mozSrcObject = stream;
            localVideo.play();
            peerConnection.addStream(stream);

            // Get local audio
            navigator.mozGetUserMedia({audio: true},function(stream) {
                localAudio.mozSrcObject = stream;
                localAudio.play();
                peerConnection.addStream(stream);

                // Create offer
                peerConnection.createOffer(function(offer) {
                    peerConnection.setLocalDescription(offer, function() {
                        // Send offer
                        $.ajax({
                            type: 'POST',
                            url:  '/signalling',
                            data: {
                                type: 'offer',
                                from: me,
                                offer: offer
                            }
                        });
                    });
                });

            }, function() {});
        }, function() {});
    });

    source.addEventListener("offer", function(event) {
        event = JSON.parse(event.data);

        if (event.from == me)
            return;

        peerConnection.setRemoteDescription(event.offer, function() {

            // Get local video
            navigator.mozGetUserMedia({video: true}, function(stream) {
                localVideo.mozSrcObject = stream;
                localVideo.play();
                peerConnection.addStream(stream);

                // Get local audio
                navigator.mozGetUserMedia({audio: true},function(stream) {
                    localAudio.mozSrcObject = stream;
                    localAudio.play();
                    peerConnection.addStream(stream);

                    // Create offer
                    peerConnection.createAnswer(function(answer) {
                        peerConnection.setLocalDescription(answer, function() {
                            // Send offer
                            $.ajax({
                                type: 'POST',
                                url:  '/signalling',
                                data: {
                                    type: 'answer',
                                    from: me,
                                    answer: answer
                                }
                            });
                        });
                    }, function() {});
                }, function() {});
            }, function() {});
        });
    });

    source.addEventListener('answer', function(event) {
        event = JSON.parse(event.data);
        console.log(event.answer);

        peerConnection.setRemoteDescription(event.answer, function() {
            console.log('done');
        });
    });

});

<|endoftext|>


<commit_before>angular.module("foodApp", ['ngRoute', 'uiGmapgoogle-maps'])

.config(function ($routeProvider, uiGmapGoogleMapApiProvider) {

  uiGmapGoogleMapApiProvider.configure({
        //    key: 'your api key',
        v: '3.20', //defaults to latest 3.X anyhow
        libraries: 'weather,geometry,visualization'
    });
  $routeProvider
    .when('/', {
      templateUrl: 'index.html',
      controller: 'mapController'
    })

})

<commit_msg>update module<commit_after>angular.module("foodApp", ['ngRoute', 'uiGmapgoogle-maps', 'foodApp.map'])

.config(function ($routeProvider, uiGmapGoogleMapApiProvider) {

  uiGmapGoogleMapApiProvider.configure({
        //    key: 'your api key',
        v: '3.20', //defaults to latest 3.X anyhow
        libraries: 'weather,geometry,visualization'
    });
  $routeProvider
    .when('/', {
      templateUrl: 'index.html',
      controller: 'mapController'
    })

})

<|endoftext|>


<commit_before>var _badestellen,_freibaeder,_fkk,_hallenbaeder;

function init() {
    $.get('data/badestellen.kml', function(kml) {
        _badestellen = kml;
        $.get("data/freibaeder.kml", function(kml) {
            _freibaeder = kml;
            $.get("data/fkk.kml", function(kml) {
                _fkk = kml;
                $.get("data/hallenbaeder.kml", function(kml) {
                    _hallenbaeder = kml;
                    $.ajax({
			url: "data/all.json",
			type: 'GET',
			dataType: 'json',
			cache: false,
			success: function (json) {
                            _quality = json;
                            initMap();
			}
                    });
                });
            });
        });
    });
}

function initMap() {
    var map = new L.Map('map');

    var min = 11;
    var max = 16;
    var reuse = true;

    //var baseUrl = 'http://mamanoke.de/tiles/badeseen/';
    var baseUrl = 'http://services.codefor.de/static/badeseen/';
    var errorTile = baseUrl + 'error.png';

    var osmCopyright = "Map data © 2012 OpenStreetMap contributors";

    var center = new L.LatLng(52.51, 13.37628);
    map.setView(center, min);

    var icons = {
        'blau': L.icon({
            iconUrl: 'img/blau.png',
            iconSize:     [32, 39], // size of the icon width,height
            iconAnchor:   [14, 45], // point of the icon which will correspond to marker's location
            popupAnchor:  [4,-46]   // point from which the popup should open relative to the iconAnchor
        }),
        'gelb': L.icon({
            iconUrl: 'img/gelb.png',
            iconSize:     [32, 37],
            iconAnchor:   [14, 39],
            popupAnchor:  [4,-46]
        }),
        'rot': L.icon({
            iconUrl: 'img/rot.png',
            iconSize:     [26, 45],
            iconAnchor:   [13, 44],
            popupAnchor:  [4,-46]
        }),
        'freibad': L.icon({
            iconUrl: 'img/freibad.png',
            iconSize:     [23, 32],
            iconAnchor:   [11, 26],
            popupAnchor:  [4,-46]
        }),
        'fkk': L.icon({
            iconUrl: 'img/fkk.png',
            iconSize:     [22, 26],
            iconAnchor:   [11, 26],
            popupAnchor:  [4,-46]
        }),
        'hallenbad': L.icon({
            iconUrl: 'img/hallenbad.png',
            iconSize:  [35, 21],
            iconAnchor: [11, 26],
            popupAnchor: [4,-46]
        }),
        'fernsehturm': L.icon({
            iconUrl: 'img/fernsehturm.png',
            iconSize: [27, 125],
            iconAnchor: [8,111]
        }),
        'funkturm': L.icon({
            iconUrl: 'img/funkturm.png',
            iconSize: [36, 110],
            iconAnchor: [16,108]
        })
    };

    var marker = {
        'fernsehturm': L.marker([52.520841,13.409405],{icon: icons.fernsehturm}).addTo(map),
        'funkturm': L.marker([52.5050681,13.278211400000032],{icon: icons.funkturm}).addTo(map)
    };

    var base = {
        'Hintergrund': new L.TileLayer(baseUrl + 'hintergrund/{z}/{x}/{y}.png', {
            minZoom: min,
            maxZoom: max,
            attribution: osmCopyright,
            errorTileUrl: errorTile,
            zIndex: 0,
            reuseTiles: reuse
        }).addTo(map),
        'Grau': new L.TileLayer(baseUrl + 'grau/{z}/{x}/{y}.png', {
            minZoom: min,
            maxZoom: max,
            attribution: osmCopyright,
            errorTileUrl: errorTile,
            zIndex: 1,
            reuseTiles: reuse
        }).addTo(map),
    };

    var overlay = {
        'Natur': new L.TileLayer(baseUrl + 'natur/{z}/{x}/{y}.png', {
            minZoom: min,
            maxZoom: max,
            attribution: osmCopyright,
            errorTileUrl: errorTile,
            zIndex: 1,
            reuseTiles: reuse
        }),
        'BVG Haltestellen': new L.TileLayer(baseUrl + 'bvg/{z}/{x}/{y}.png', {
            minZoom: min,
            maxZoom: max,
            attribution: osmCopyright,
            errorTileUrl: errorTile,
            zIndex: 4,
            reuseTiles: reuse
        }),
        'Badestellen': new L.layerGroup().addTo(map),
        'Freibäder': new L.layerGroup(),
        'FKK-Baden': new L.layerGroup(),
        'Hallenbäder': new L.layerGroup(),
        'Hundebadestellen': new L.TileLayer(baseUrl + 'hunde/{z}/{x}/{y}.png', {
            minZoom: min,
            maxZoom: max,
            attribution: osmCopyright,
            errorTileUrl: errorTile,
            zIndex: 6,
            reuseTiles: reuse
        }),
    };

    L.control.layers({}, overlay, {collapsed: false}).addTo(map);

    // Badestellen
    $(_badestellen).find("Placemark").each(function(){
        var description = $(this).find("description").text();
        var name = $(this).find("name").text();
        var farbe;
        var sicht = "";
        var overall;
        var date;
        var url;

        for (var i = 0; i<_quality.index.length; i++) {
            if (_quality.index[i].rss_name == name) {
                farbe = _quality.index[i].farbe;
                sicht = (_quality.index[i].sicht);
                var s = _quality.index[i].dat.split('-');
                date = s[2] + '.' + s[1] + '.' + s[0];
                url = unescape(_quality.index[i].badestellelink.replace("[","").replace("]",""));
		url = url.split("|")[0];
                url = url.substr(1, url.length);
                url = 'http://www.berlin.de/' + url;
            }
        }

        var koordinaten = $(this).find("coordinates").text();
        var k = koordinaten.split(",");
        var lon = parseFloat(k[0]);
        var lat = parseFloat(k[1]);
        var icon;

        if (farbe === 'gruen.jpg') {
            icon = icons['blau'];
            overall = 'gut';
        } else if(farbe === 'gelb.jpg') {
            icon = icons['gelb'];
            overall = 'mittel';
        } else {
            icon = icons['rot'];
            overall = 'schlecht';
        }

        var marker = L.marker([lat,lon],{icon: icon});
        marker.bindPopup(''+ name + '
Sichttiefe: ' + sicht + ' cm
 Messdatum: ' + date + '
 Wasserqualität: ' + overall + '
'+ 'Link');
        marker.on('click', function(e){
            marker.openPopup();
        });
        overlay['Badestellen'].addLayer(marker);
    });

    // Freibad
    $(_freibaeder).find("Placemark").each(function(){
        var description = $(this).find("description").text();
        var name = $(this).find("name").text();
        var koordinaten = $(this).find("coordinates").text();
        var k = koordinaten.split(",");
        var lon = parseFloat(k[0]);
        var lat = parseFloat(k[1]);
        var marker = L.marker([lat,lon],{icon: icons['freibad']});
        marker.bindPopup(''+ name + '
' + 'Link');
        marker.on('click', function(e){
            marker.openPopup();
        });
        overlay['Freibäder'].addLayer(marker);
    });

    // FKK
    $(_fkk).find("Placemark").each(function(){
        //var description = $b.find("description").text();
        var name = $(this).find("name").text();
        var koordinaten = $(this).find("coordinates").text();
        var k = koordinaten.split(",");
        var lon = parseFloat(k[0]);
        var lat = parseFloat(k[1]);
        var marker = L.marker([lat,lon],{icon: icons['fkk']});
        marker.bindPopup(name);
        marker.on('click', function(e){
           marker.openPopup();
        });
        overlay['FKK-Baden'].addLayer(marker);
    });

    // Hallenbaeder
    $(_hallenbaeder).find("Placemark").each(function(){
        var description = $(this).find("description").text();
        var name = $(this).find("name").text();
        var koordinaten = $(this).find("coordinates").text();
        var k = koordinaten.split(",");
        var lon = parseFloat(k[0]);
        var lat = parseFloat(k[1]);
        var marker = L.marker([lat,lon],{icon: icons['hallenbad']});
        marker.bindPopup(''+ name + '
' + 'Link');
        marker.on('click', function(e){
            marker.openPopup();
        });
        overlay['Hallenbäder'].addLayer(marker);
    });
}<commit_msg>Update map.js<commit_after>var _badestellen,_freibaeder,_fkk,_hallenbaeder;

function init() {
    $.get('data/badestellen.kml', function(kml) {
        _badestellen = kml;
        $.get("data/freibaeder.kml", function(kml) {
            _freibaeder = kml;
            $.get("data/fkk.kml", function(kml) {
                _fkk = kml;
                $.get("data/hallenbaeder.kml", function(kml) {
                    _hallenbaeder = kml;
                    $.ajax({
			url: "data/all.json",
			type: 'GET',
			dataType: 'json',
			cache: false,
			success: function (json) {
                            _quality = json;
                            initMap();
			}
                    });
                });
            });
        });
    });
}

function initMap() {
    var map = new L.Map('map');

    var min = 11;
    var max = 16;
    var reuse = true;

    //var baseUrl = 'http://mamanoke.de/tiles/badeseen/';
    var baseUrl = 'http://services.codefor.de/static/badeseen/';
    var errorTile = baseUrl + 'error.png';

    var osmCopyright = "Map data © 2012 OpenStreetMap contributors";

    var center = new L.LatLng(52.51, 13.37628);
    map.setView(center, min);

    var icons = {
        'blau': L.icon({
            iconUrl: 'img/blau.png',
            iconSize:     [32, 39], // size of the icon width,height
            iconAnchor:   [14, 45], // point of the icon which will correspond to marker's location
            popupAnchor:  [4,-46]   // point from which the popup should open relative to the iconAnchor
        }),
        'gelb': L.icon({
            iconUrl: 'img/gelb.png',
            iconSize:     [32, 37],
            iconAnchor:   [14, 39],
            popupAnchor:  [4,-46]
        }),
        'rot': L.icon({
            iconUrl: 'img/rot.png',
            iconSize:     [26, 45],
            iconAnchor:   [13, 44],
            popupAnchor:  [4,-46]
        }),
        'freibad': L.icon({
            iconUrl: 'img/freibad.png',
            iconSize:     [23, 32],
            iconAnchor:   [11, 26],
            popupAnchor:  [4,-46]
        }),
        'fkk': L.icon({
            iconUrl: 'img/fkk.png',
            iconSize:     [22, 26],
            iconAnchor:   [11, 26],
            popupAnchor:  [4,-46]
        }),
        'hallenbad': L.icon({
            iconUrl: 'img/hallenbad.png',
            iconSize:  [35, 21],
            iconAnchor: [11, 26],
            popupAnchor: [4,-46]
        }),
        'fernsehturm': L.icon({
            iconUrl: 'img/fernsehturm.png',
            iconSize: [27, 125],
            iconAnchor: [8,111]
        }),
        'funkturm': L.icon({
            iconUrl: 'img/funkturm.png',
            iconSize: [36, 110],
            iconAnchor: [16,108]
        })
    };

    var marker = {
        'fernsehturm': L.marker([52.520841,13.409405],{icon: icons.fernsehturm}).addTo(map),
        'funkturm': L.marker([52.5050681,13.278211400000032],{icon: icons.funkturm}).addTo(map)
    };

    var base = {
        'Hintergrund': new L.TileLayer(baseUrl + 'hintergrund/{z}/{x}/{y}.png', {
            minZoom: min,
            maxZoom: max,
            attribution: osmCopyright,
            errorTileUrl: errorTile,
            zIndex: 0,
            reuseTiles: reuse
        }).addTo(map),
        'Grau': new L.TileLayer(baseUrl + 'grau/{z}/{x}/{y}.png', {
            minZoom: min,
            maxZoom: max,
            attribution: osmCopyright,
            errorTileUrl: errorTile,
            zIndex: 1,
            reuseTiles: reuse
        }).addTo(map),
    };

    var overlay = {
        'Natur': new L.TileLayer(baseUrl + 'natur/{z}/{x}/{y}.png', {
            minZoom: min,
            maxZoom: max,
            attribution: osmCopyright,
            errorTileUrl: errorTile,
            zIndex: 1,
            reuseTiles: reuse
        }),
        'BVG Haltestellen': new L.TileLayer(baseUrl + 'bvg/{z}/{x}/{y}.png', {
            minZoom: min,
            maxZoom: max,
            attribution: osmCopyright,
            errorTileUrl: errorTile,
            zIndex: 4,
            reuseTiles: reuse
        }),
        'Badestellen': new L.layerGroup().addTo(map),
        'Freibäder': new L.layerGroup(),
        'FKK-Baden': new L.layerGroup(),
        'Hallenbäder': new L.layerGroup(),
        'Hundebadestellen': new L.TileLayer(baseUrl + 'hunde/{z}/{x}/{y}.png', {
            minZoom: min,
            maxZoom: max,
            attribution: osmCopyright,
            errorTileUrl: errorTile,
            zIndex: 6,
            reuseTiles: reuse
        }),
    };

    L.control.layers({}, overlay, {collapsed: false}).addTo(map);

    // Badestellen
    $(_badestellen).find("Placemark").each(function(){
        var description = $(this).find("description").text();
        var name = $(this).find("name").text();
        var farbe;
        var sicht = "";
        var overall;
        var date;
        var url;

        for (var i = 0; i<_quality.index.length; i++) {
            if (_quality.index[i].rss_name == name) {
                farbe = _quality.index[i].farbe;
                sicht = (_quality.index[i].sicht);
                var s = _quality.index[i].dat.split('-');
                date = s[2] + '.' + s[1] + '.' + s[0];
                url = unescape(_quality.index[i].badestellelink.replace("[","").replace("]",""));
		url = url.split("|")[0];
                url = url.substr(1, url.length);
                url = 'http://www.berlin.de/' + url;
            }
        }

        var koordinaten = $(this).find("coordinates").text();
        var k = koordinaten.split(",");
        var lon = parseFloat(k[0]);
        var lat = parseFloat(k[1]);
        var icon;

        if (farbe === 'gruen.jpg') {
            icon = icons['blau'];
            overall = 'gut';
        } else if(farbe === 'gelb.jpg') {
            icon = icons['gelb'];
            overall = 'vom Baden wird abgeraten';
        } else {
            icon = icons['rot'];
            overall = 'Baden verboten';
        }

        var marker = L.marker([lat,lon],{icon: icon});
        marker.bindPopup(''+ name + '
Sichttiefe: ' + sicht + ' cm
 Messdatum: ' + date + '
 Wasserqualität: ' + overall + '
'+ 'Link');
        marker.on('click', function(e){
            marker.openPopup();
        });
        overlay['Badestellen'].addLayer(marker);
    });

    // Freibad
    $(_freibaeder).find("Placemark").each(function(){
        var description = $(this).find("description").text();
        var name = $(this).find("name").text();
        var koordinaten = $(this).find("coordinates").text();
        var k = koordinaten.split(",");
        var lon = parseFloat(k[0]);
        var lat = parseFloat(k[1]);
        var marker = L.marker([lat,lon],{icon: icons['freibad']});
        marker.bindPopup(''+ name + '
' + 'Link');
        marker.on('click', function(e){
            marker.openPopup();
        });
        overlay['Freibäder'].addLayer(marker);
    });

    // FKK
    $(_fkk).find("Placemark").each(function(){
        //var description = $b.find("description").text();
        var name = $(this).find("name").text();
        var koordinaten = $(this).find("coordinates").text();
        var k = koordinaten.split(",");
        var lon = parseFloat(k[0]);
        var lat = parseFloat(k[1]);
        var marker = L.marker([lat,lon],{icon: icons['fkk']});
        marker.bindPopup(name);
        marker.on('click', function(e){
           marker.openPopup();
        });
        overlay['FKK-Baden'].addLayer(marker);
    });

    // Hallenbaeder
    $(_hallenbaeder).find("Placemark").each(function(){
        var description = $(this).find("description").text();
        var name = $(this).find("name").text();
        var koordinaten = $(this).find("coordinates").text();
        var k = koordinaten.split(",");
        var lon = parseFloat(k[0]);
        var lat = parseFloat(k[1]);
        var marker = L.marker([lat,lon],{icon: icons['hallenbad']});
        marker.bindPopup(''+ name + '
' + 'Link');
        marker.on('click', function(e){
            marker.openPopup();
        });
        overlay['Hallenbäder'].addLayer(marker);
    });
}
<|endoftext|>


<commit_before>const path = require(`path`)
const fs = require(`fs-extra`)

const { promisifiedSpawn } = require(`../utils/promisified-spawn`)
const { registryUrl } = require(`./verdaccio-config`)

const installPackages = async ({ packagesToInstall, yarnWorkspaceRoot }) => {
  console.log(
    `Installing packages from local registry:\n${packagesToInstall
      .map(packageAndVersion => ` - ${packageAndVersion}`)
      .join(`\n`)}`
  )
  let installCmd
  if (yarnWorkspaceRoot) {
    // this is very hacky - given root, we run `yarn workspaces info`
    // to get list of all workspaces and their locations, and manually
    // edit package.json file for packages we want to install
    // to make sure there are no mismatched versions of same package
    // in workspaces which should preserve node_modules structure
    // (packages being mostly hoisted to top-level node_modules)

    const { stdout } = await promisifiedSpawn([
      `yarn`,
      [`workspaces`, `info`, `--json`],
      { stdio: `pipe` },
    ])

    const workspacesLayout = JSON.parse(JSON.parse(stdout).data)

    const handleDeps = deps => {
      if (!deps) {
        return false
      }

      let changed = false
      Object.keys(deps).forEach(depName => {
        if (packagesToInstall.includes(depName)) {
          deps[depName] = `gatsby-dev`
          changed = true
        }
      })
      return changed
    }

    Object.keys(workspacesLayout).forEach(workspaceName => {
      const { location } = workspacesLayout[workspaceName]
      const pkgJsonPath = path.join(yarnWorkspaceRoot, location, `package.json`)
      if (!fs.existsSync(pkgJsonPath)) {
        return
      }
      const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, `utf8`))

      let changed = false
      changed |= handleDeps(pkg.dependencies)
      changed |= handleDeps(pkg.devDependencies)
      changed |= handleDeps(pkg.peerDependencies)

      if (changed) {
        console.log(`Changing deps in ${pkgJsonPath} to use @gatsby-dev`)
        fs.outputJSONSync(pkgJsonPath, pkg, {
          spaces: 2,
        })
      }
    })

    // package.json files are changed - so we just want to install
    // using verdaccio registry
    installCmd = [`yarn`, [`install`, `--registry=${registryUrl}`]]
  } else {
    installCmd = [
      `yarn`,
      [
        `add`,
        ...packagesToInstall.map(packageName => `${packageName}@gatsby-dev`),
        `--registry=${registryUrl}`,
        `--exact`,
      ],
    ]
  }

  try {
    await promisifiedSpawn(installCmd)

    console.log(`Installation complete`)
  } catch {
    console.error(`Installation failed`)
  }
}

exports.installPackages = installPackages
<commit_msg>chore(gatsby-dev-cli): Log error if installation fails (#17364)<commit_after>const path = require(`path`)
const fs = require(`fs-extra`)

const { promisifiedSpawn } = require(`../utils/promisified-spawn`)
const { registryUrl } = require(`./verdaccio-config`)

const installPackages = async ({ packagesToInstall, yarnWorkspaceRoot }) => {
  console.log(
    `Installing packages from local registry:\n${packagesToInstall
      .map(packageAndVersion => ` - ${packageAndVersion}`)
      .join(`\n`)}`
  )
  let installCmd
  if (yarnWorkspaceRoot) {
    // this is very hacky - given root, we run `yarn workspaces info`
    // to get list of all workspaces and their locations, and manually
    // edit package.json file for packages we want to install
    // to make sure there are no mismatched versions of same package
    // in workspaces which should preserve node_modules structure
    // (packages being mostly hoisted to top-level node_modules)

    const { stdout } = await promisifiedSpawn([
      `yarn`,
      [`workspaces`, `info`, `--json`],
      { stdio: `pipe` },
    ])

    const workspacesLayout = JSON.parse(JSON.parse(stdout).data)

    const handleDeps = deps => {
      if (!deps) {
        return false
      }

      let changed = false
      Object.keys(deps).forEach(depName => {
        if (packagesToInstall.includes(depName)) {
          deps[depName] = `gatsby-dev`
          changed = true
        }
      })
      return changed
    }

    Object.keys(workspacesLayout).forEach(workspaceName => {
      const { location } = workspacesLayout[workspaceName]
      const pkgJsonPath = path.join(yarnWorkspaceRoot, location, `package.json`)
      if (!fs.existsSync(pkgJsonPath)) {
        return
      }
      const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, `utf8`))

      let changed = false
      changed |= handleDeps(pkg.dependencies)
      changed |= handleDeps(pkg.devDependencies)
      changed |= handleDeps(pkg.peerDependencies)

      if (changed) {
        console.log(`Changing deps in ${pkgJsonPath} to use @gatsby-dev`)
        fs.outputJSONSync(pkgJsonPath, pkg, {
          spaces: 2,
        })
      }
    })

    // package.json files are changed - so we just want to install
    // using verdaccio registry
    installCmd = [`yarn`, [`install`, `--registry=${registryUrl}`]]
  } else {
    installCmd = [
      `yarn`,
      [
        `add`,
        ...packagesToInstall.map(packageName => `${packageName}@gatsby-dev`),
        `--registry=${registryUrl}`,
        `--exact`,
      ],
    ]
  }

  try {
    await promisifiedSpawn(installCmd)

    console.log(`Installation complete`)
  } catch (error) {
    console.error(`Installation failed`, error)
  }
}

exports.installPackages = installPackages
<|endoftext|>