<commit_before>
// Construct map, center if no location provided
var map = L.map('map', { maxZoom: 13 } );
var hash = new L.Hash(map);
if (!window.location.hash) {
    map.setView([37.958, -120.976], 8);
}

// Make the base map; a raster tile relief map from ESRI
var esriRelief = 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Shaded_Relief/MapServer/tile/{z}/{y}/{x}';

var basemap = L.tileLayer(esriRelief, {
  attribution: 'ESRI shaded relief, NHDPlus v2',
  maxZoom: 13
});
//basemap.addTo(map);

// Add a single GeoJSON vector file for state boundaries
// This was loaded statically as a script; could also be AJAX
var stateLayer = new L.geoJson(usStates);
stateLayer.setStyle({ "color": "#444",
                      "weight": 1,
                      "fill": false,
                      "opacity": 1.0 });
stateLayer.addTo(map);

var nlcdlayer = L.tileLayer('/nlcd/{z}/{x}/{y}.png',{tms:true}).addTo(map);

var requestsPool = {
  requests: {}, //list of urls
  timeouts: {},
  timeout:  1000*60*10, //In milliseconds
  fetch: function(url) {
    if(requestsPool.exists(url))
      return requestsPool.requests[url];

    requestsPool.timeouts[url] = setTimeout(function(u) {
        requestsPool.remove(u);
    }.bind(this, url), requestsPool.timeout); //Defining the timeout

    requestsPool.requests[url] = $.getJSON(url);
    return requestsPool.requests[url];
  },
  exists: function(url) {
    return requestsPool.requests.hasOwnProperty(url); //Return the Timeout ID if present or undefined
  },
  remove: function(url) {
    requestsPool.cancel(url);
    delete requestsPool.requests[url];
  },
  cancel: function(url) {
    clearTimeout(requestsPool.timeouts[url]); //cancel the timeout
    delete requestsPool.timeouts[url];
  }
}

var riverinfo = {};

function StyleTheRivers(feature){
  requestsPool.fetch('/gauges/reachflow/'+feature.properties.huc8)
  .done(function(val){
    riverinfo[feature.properties.huc8]=val;
    $('.h'+feature.properties.huc8).css('stroke', (val.drank!==null)?grad_colours[Math.floor((grad_colours.length-1)*val.drank)]:'#FF00DE' );
    $('.h'+feature.properties.huc8).css('stroke-width', ((val.drank!==null)?(6*val.drank+2).toString():'2')+'px' );
  });
}
//$.getJSON('/gauges/reachflow/'+feature.properties.huc8, function(data){

// Style the river lines; width depends on its Strahler number
function riverStyle(feature) {
  return "stroke-width: " + feature.properties.strahler * map.getZoom()/13 + "px;stroke:#FF00DE;";
}

function riverClass(feature){
  StyleTheRivers(feature);
  return "river h" + feature.properties.huc8;
}

// Make the river overlay layer, vector tiles from our TileStache/Gunicorn server
var geojsonURL = "/rivers/{z}/{x}/{y}.json";
var riverLayer = new L.TileLayer.d3_geoJSON(geojsonURL, {
  class: riverClass,
  style: riverStyle
});
map.addLayer(riverLayer);

var countystyle = {
  "color":       "black",
  "fillColor":   "gray",
  "stroke":      "black",
  "fill":        "gray",
  "weight":      3,
  "fillOpacity": 0.65
};

function highlightCounty(e) {
    var layer = e.target;

    layer.setStyle({
        weight: 5,
        color: '#666',
        dashArray: '',
        fillOpacity: 0.7
    });

    if (!L.Browser.ie && !L.Browser.opera) {
        layer.bringToFront();
    }

    console.log(layer.feature.properties);
}

function resetCounty(e) {
    counties.resetStyle(e.target);
}

function zoomToFeature(e) {
    map.fitBounds(e.target.getBounds());
}

function onEachCounty(feature, layer) {
    layer.on({
        mouseover: highlightCounty,
        mouseout:  resetCounty,
        click:     zoomToFeature
    });
}

var counties = new L.geoJson(null,{style:countystyle,onEachFeature:onEachCounty}).addTo(map);
$.getJSON("/counties.json",
  function(data) {
    $(data.features.slice(0,20)).each(function(key, data) {
      console.log(data);
      data.id = data.properties.STATE+data.properties.COUNTY;
      counties.addData(data);
    });
  }
);

map.on('dragend', function(e) {
  //$('#spinnerBox').fadeIn();
  getStations();
});

map.on('zoomend', function() {
  getStations();
});

var markers = new L.FeatureGroup();
map.addLayer(markers);

var grad_colours = ['#b2182b','#d6604d','#f4a582','#fddbc7','#f7f7f7','#d1e5f0','#92c5de','#4393c3','#2166ac']

var baseLayers = {
  "Terrain": basemap,
  "NLCD":    nlcdlayer,
};

var overlays = {
  "Rivers":         riverLayer,
  "Gauge Stations": markers,
  "Counties":       counties
};

L.control.layers(baseLayers, overlays).addTo(map);

function getStations() {
  // Clear markers before getting new ones
  markers.clearLayers();

  // Get map bounds from Leaflet.  getBounds() returns an object
  var bbox = map.getBounds();

  var addy = "/gauges/list/xmin/ymin/xmax/ymax";
  addy     = addy.replace("xmin",bbox._southWest.lng);
  addy     = addy.replace("ymin",bbox._southWest.lat);
  addy     = addy.replace("xmax",bbox._northEast.lng);
  addy     = addy.replace("ymax",bbox._northEast.lat);

  //use jQuery's getJSON() to call the SODA API for NYC 311
  $.getJSON(addy, function(data) {
    //iterate over each 311 complaint, add a marker to the map
    _.each(data, function(marker){
      var markerItem = L.circleMarker(
        [marker.lat,marker.lng],
        {
          radius:      5,
          color:       'black',
          fillColor:   (marker.drank!==null)?grad_colours[Math.floor((grad_colours.length-1)*marker.drank)]:'#FF00DE',
          fillOpacity: 1
        }
      );
      markerItem.on('mouseover', function(){
        $('#headerbar').html(marker.name);
        $('#bottomright').html(
          'Stage: ' + marker.svalue + ' ft
' +
          ''+marker.sdt+'
' +
          'Discharge: ' + marker.dvalue + ' cfs
' +
          ''+marker.ddt+'
' +
          'Rank: ' + marker.drank.toFixed(2) + '
' +
          'More info here'
          );
      });

      // markerItem.bindPopup(
      //   '
' + marker.complaint_type + '
'
      //   + (new Date(marker.created_date)).toDateString()
      //   + ((marker.incident_address != null) ? '
' + marker.incident_address : '')
      // );

      markers.addLayer(markerItem);
    });
    map.addLayer(markers);
  });
}

function colourCounties(style,percentile_max){
  $.getJSON('/county/'+style+'.css?percentile_max='+percentile_max,function(data){

  });
}

$('.nlcdgrad').hover(function(e){
  var classname = $(e.target).data('classname');
  $('#nlcdexplanation').html(classname);
}, function(){
  $('#nlcdexplanation').html('NLCD Legend (hover over colours for details)');
})

$(document).ready(function(){
  getStations();
});<commit_msg>Try again<commit_after>
// Construct map, center if no location provided
var map = L.map('map', { maxZoom: 13 } );
var hash = new L.Hash(map);
if (!window.location.hash) {
    map.setView([37.958, -120.976], 8);
}

// Make the base map; a raster tile relief map from ESRI
var esriRelief = 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Shaded_Relief/MapServer/tile/{z}/{y}/{x}';

var basemap = L.tileLayer(esriRelief, {
  attribution: 'ESRI shaded relief, NHDPlus v2',
  maxZoom: 13
});
//basemap.addTo(map);

// Add a single GeoJSON vector file for state boundaries
// This was loaded statically as a script; could also be AJAX
var stateLayer = new L.geoJson(usStates);
stateLayer.setStyle({ "color": "#444",
                      "weight": 1,
                      "fill": false,
                      "opacity": 1.0 });
stateLayer.addTo(map);

var nlcdlayer = L.tileLayer('/nlcd/{z}/{x}/{y}.png',{tms:true}).addTo(map);

var requestsPool = {
  requests: {}, //list of urls
  timeouts: {},
  timeout:  1000*60*10, //In milliseconds
  fetch: function(url) {
    if(requestsPool.exists(url))
      return requestsPool.requests[url];

    requestsPool.timeouts[url] = setTimeout(function(u) {
        requestsPool.remove(u);
    }.bind(this, url), requestsPool.timeout); //Defining the timeout

    requestsPool.requests[url] = $.getJSON(url);
    return requestsPool.requests[url];
  },
  exists: function(url) {
    return requestsPool.requests.hasOwnProperty(url); //Return the Timeout ID if present or undefined
  },
  remove: function(url) {
    requestsPool.cancel(url);
    delete requestsPool.requests[url];
  },
  cancel: function(url) {
    clearTimeout(requestsPool.timeouts[url]); //cancel the timeout
    delete requestsPool.timeouts[url];
  }
}

var riverinfo = {};

function StyleTheRivers(feature){
  requestsPool.fetch('/gauges/reachflow/'+feature.properties.huc8)
  .done(function(val){
    riverinfo[feature.properties.huc8]=val;
    $('.h'+feature.properties.huc8).css('stroke', (val.drank!==null)?grad_colours[Math.floor((grad_colours.length-1)*val.drank)]:'#FF00DE' );
    $('.h'+feature.properties.huc8).css('stroke-width', ((val.drank!==null)?(6*val.drank+2).toString():'2')+'px' );
  });
}
//$.getJSON('/gauges/reachflow/'+feature.properties.huc8, function(data){

// Style the river lines; width depends on its Strahler number
function riverStyle(feature) {
  return "stroke-width: " + feature.properties.strahler * map.getZoom()/13 + "px;stroke:#FF00DE;";
}

function riverClass(feature){
  StyleTheRivers(feature);
  return "river h" + feature.properties.huc8;
}

// Make the river overlay layer, vector tiles from our TileStache/Gunicorn server
var geojsonURL = "/rivers/{z}/{x}/{y}.json";
var riverLayer = new L.TileLayer.d3_geoJSON(geojsonURL, {
  class: riverClass,
  style: riverStyle
});
map.addLayer(riverLayer);

var countystyle = {
  "color":       "black",
  "fillColor":   "gray",
  "stroke":      "black",
  "fill":        "gray",
  "weight":      3,
  "fillOpacity": 0.65
};

function highlightCounty(e) {
    var layer = e.target;

    layer.setStyle({
        weight: 5,
        color: '#666',
        dashArray: '',
        fillOpacity: 0.7
    });

    if (!L.Browser.ie && !L.Browser.opera) {
        layer.bringToFront();
    }

    console.log(layer.feature.properties);
}

function resetCounty(e) {
    counties.resetStyle(e.target);
}

function zoomToFeature(e) {
    map.fitBounds(e.target.getBounds());
}

function onEachCounty(feature, layer) {
  layer.attr('id',data.properties.STATE+data.properties.COUNTY);
  layer.on({
      mouseover: highlightCounty,
      mouseout:  resetCounty,
      click:     zoomToFeature
  });
}

var counties = new L.geoJson(null,{style:countystyle,onEachFeature:onEachCounty}).addTo(map);
$.getJSON("/counties.json",
  function(data) {
    $(data.features.slice(0,20)).each(function(key, data) {
      console.log(data);
      counties.addData(data);
    });
  }
);

map.on('dragend', function(e) {
  //$('#spinnerBox').fadeIn();
  getStations();
});

map.on('zoomend', function() {
  getStations();
});

var markers = new L.FeatureGroup();
map.addLayer(markers);

var grad_colours = ['#b2182b','#d6604d','#f4a582','#fddbc7','#f7f7f7','#d1e5f0','#92c5de','#4393c3','#2166ac']

var baseLayers = {
  "Terrain": basemap,
  "NLCD":    nlcdlayer,
};

var overlays = {
  "Rivers":         riverLayer,
  "Gauge Stations": markers,
  "Counties":       counties
};

L.control.layers(baseLayers, overlays).addTo(map);

function getStations() {
  // Clear markers before getting new ones
  markers.clearLayers();

  // Get map bounds from Leaflet.  getBounds() returns an object
  var bbox = map.getBounds();

  var addy = "/gauges/list/xmin/ymin/xmax/ymax";
  addy     = addy.replace("xmin",bbox._southWest.lng);
  addy     = addy.replace("ymin",bbox._southWest.lat);
  addy     = addy.replace("xmax",bbox._northEast.lng);
  addy     = addy.replace("ymax",bbox._northEast.lat);

  //use jQuery's getJSON() to call the SODA API for NYC 311
  $.getJSON(addy, function(data) {
    //iterate over each 311 complaint, add a marker to the map
    _.each(data, function(marker){
      var markerItem = L.circleMarker(
        [marker.lat,marker.lng],
        {
          radius:      5,
          color:       'black',
          fillColor:   (marker.drank!==null)?grad_colours[Math.floor((grad_colours.length-1)*marker.drank)]:'#FF00DE',
          fillOpacity: 1
        }
      );
      markerItem.on('mouseover', function(){
        $('#headerbar').html(marker.name);
        $('#bottomright').html(
          'Stage: ' + marker.svalue + ' ft
' +
          ''+marker.sdt+'
' +
          'Discharge: ' + marker.dvalue + ' cfs
' +
          ''+marker.ddt+'
' +
          'Rank: ' + marker.drank.toFixed(2) + '
' +
          'More info here'
          );
      });

      // markerItem.bindPopup(
      //   '
' + marker.complaint_type + '
'
      //   + (new Date(marker.created_date)).toDateString()
      //   + ((marker.incident_address != null) ? '
' + marker.incident_address : '')
      // );

      markers.addLayer(markerItem);
    });
    map.addLayer(markers);
  });
}

function colourCounties(style,percentile_max){
  $.getJSON('/county/'+style+'.css?percentile_max='+percentile_max,function(data){

  });
}

$('.nlcdgrad').hover(function(e){
  var classname = $(e.target).data('classname');
  $('#nlcdexplanation').html(classname);
}, function(){
  $('#nlcdexplanation').html('NLCD Legend (hover over colours for details)');
})

$(document).ready(function(){
  getStations();
});<|endoftext|>


<commit_before>
// Construct map, center if no location provided
var map = L.map('map', { maxZoom: 13 } );
var hash = new L.Hash(map);
if (!window.location.hash) {
    map.setView([37.958, -120.976], 8);
}

// Make the base map; a raster tile relief map from ESRI
var esriRelief = 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Shaded_Relief/MapServer/tile/{z}/{y}/{x}';

var basemap = L.tileLayer(esriRelief, {
  attribution: 'ESRI shaded relief, NHDPlus v2',
  maxZoom: 13
});
//basemap.addTo(map);

// Add a single GeoJSON vector file for state boundaries
// This was loaded statically as a script; could also be AJAX
var stateLayer = new L.geoJson(usStates);
stateLayer.setStyle({ "color": "#444",
                      "weight": 1,
                      "fill": false,
                      "opacity": 1.0 });
stateLayer.addTo(map);

var nlcdlayer = L.tileLayer('/nlcd/{z}/{x}/{y}.png',{tms:true}).addTo(map);

var requestsPool = {
  requests: {}, //list of urls
  timeouts: {},
  timeout:  1000*60*10, //In milliseconds
  fetch: function(url) {
    if(requestsPool.exists(url))
      return requestsPool.requests[url];

    requestsPool.timeouts[url] = setTimeout(function(u) {
        requestsPool.remove(u);
    }.bind(this, url), requestsPool.timeout); //Defining the timeout

    requestsPool.requests[url] = $.getJSON(url);
    return requestsPool.requests[url];
  },
  exists: function(url) {
    return requestsPool.requests.hasOwnProperty(url); //Return the Timeout ID if present or undefined
  },
  remove: function(url) {
    requestsPool.cancel(url);
    delete requestsPool.requests[url];
  },
  cancel: function(url) {
    clearTimeout(requestsPool.timeouts[url]); //cancel the timeout
    delete requestsPool.timeouts[url];
  }
}

var riverinfo = {};

function StyleTheRivers(feature){
  requestsPool.fetch('/gauges/reachflow/'+feature.properties.huc8)
  .done(function(val){
    riverinfo[feature.properties.huc8]=val;
    $('.h'+feature.properties.huc8).css('stroke', (val.drank!==null)?grad_colours[Math.floor((grad_colours.length-1)*val.drank)]:'#FF00DE' );
    $('.h'+feature.properties.huc8).css('stroke-width', ((val.drank!==null)?(6*val.drank+2).toString():'2')+'px' );
  });
}
//$.getJSON('/gauges/reachflow/'+feature.properties.huc8, function(data){

// Style the river lines; width depends on its Strahler number
function riverStyle(feature) {
  return "stroke-width: " + feature.properties.strahler * map.getZoom()/13 + "px;stroke:#FF00DE;";
}

function riverClass(feature){
  StyleTheRivers(feature);
  return "river h" + feature.properties.huc8;
}

// Make the river overlay layer, vector tiles from our TileStache/Gunicorn server
var geojsonURL = "/rivers/{z}/{x}/{y}.json";
var riverLayer = new L.TileLayer.d3_geoJSON(geojsonURL, {
  class: riverClass,
  style: riverStyle
});
map.addLayer(riverLayer);

var countystyle = {
  "color":       "black",
  "fillColor":   "gray",
  "stroke":      "black",
  "fill":        "gray",
  "weight":      3,
  "fillOpacity": 0.65
};

function highlightCounty(e) {
    var layer = e.target;

    layer.setStyle({
        weight: 5,
        color: '#666',
        dashArray: '',
        fillOpacity: 0.7
    });

    if (!L.Browser.ie && !L.Browser.opera) {
        layer.bringToFront();
    }

    console.log(layer.feature.properties);
}

function resetCounty(e) {
    counties.resetStyle(e.target);
}

function zoomToFeature(e) {
    map.fitBounds(e.target.getBounds());
}

function onEachCounty(feature, layer) {
    layer.on({
        mouseover: highlightCounty,
        mouseout:  resetCounty,
        click:     zoomToFeature
    });
}

var counties = new L.geoJson(null,{style:countystyle,onEachFeature:onEachCounty}).addTo(map);
$.getJSON("/counties.json",
  function(data) {
    $(data.features.slice(0,20)).each(function(key, data) {
      console.log(data);
      data.id = data.properties.state+data.properties.county;
      counties.addData(data);
    });
  }
);

map.on('dragend', function(e) {
  //$('#spinnerBox').fadeIn();
  getStations();
});

map.on('zoomend', function() {
  getStations();
});

var markers = new L.FeatureGroup();
map.addLayer(markers);

var grad_colours = ['#b2182b','#d6604d','#f4a582','#fddbc7','#f7f7f7','#d1e5f0','#92c5de','#4393c3','#2166ac']

var baseLayers = {
  "Terrain": basemap,
  "NLCD":    nlcdlayer,
};

var overlays = {
  "Rivers":         riverLayer,
  "Gauge Stations": markers,
  "Counties":       counties
};

L.control.layers(baseLayers, overlays).addTo(map);

function getStations() {
  // Clear markers before getting new ones
  markers.clearLayers();

  // Get map bounds from Leaflet.  getBounds() returns an object
  var bbox = map.getBounds();

  var addy = "/gauges/list/xmin/ymin/xmax/ymax";
  addy     = addy.replace("xmin",bbox._southWest.lng);
  addy     = addy.replace("ymin",bbox._southWest.lat);
  addy     = addy.replace("xmax",bbox._northEast.lng);
  addy     = addy.replace("ymax",bbox._northEast.lat);

  //use jQuery's getJSON() to call the SODA API for NYC 311
  $.getJSON(addy, function(data) {
    //iterate over each 311 complaint, add a marker to the map
    _.each(data, function(marker){
      var markerItem = L.circleMarker(
        [marker.lat,marker.lng],
        {
          radius:      5,
          color:       'black',
          fillColor:   (marker.drank!==null)?grad_colours[Math.floor((grad_colours.length-1)*marker.drank)]:'#FF00DE',
          fillOpacity: 1
        }
      );
      markerItem.on('mouseover', function(){
        $('#headerbar').html(marker.name);
        $('#bottomright').html(
          'Stage: ' + marker.svalue + ' ft
' +
          ''+marker.sdt+'
' +
          'Discharge: ' + marker.dvalue + ' cfs
' +
          ''+marker.ddt+'
' +
          'Rank: ' + marker.drank.toFixed(2) + '
' +
          'More info here'
          );
      });

      // markerItem.bindPopup(
      //   '
' + marker.complaint_type + '
'
      //   + (new Date(marker.created_date)).toDateString()
      //   + ((marker.incident_address != null) ? '
' + marker.incident_address : '')
      // );

      markers.addLayer(markerItem);
    });
    map.addLayer(markers);
  });
}

function colourCounties(style,percentile_max){
  $.getJSON('/county/'+style+'.css?percentile_max='+percentile_max,function(data){

  });
}

$('.nlcdgrad').hover(function(e){
  var classname = $(e.target).data('classname');
  $('#nlcdexplanation').html(classname);
}, function(){
  $('#nlcdexplanation').html('NLCD Legend (hover over colours for details)');
})

$(document).ready(function(){
  getStations();
});<commit_msg>Now id<commit_after>
// Construct map, center if no location provided
var map = L.map('map', { maxZoom: 13 } );
var hash = new L.Hash(map);
if (!window.location.hash) {
    map.setView([37.958, -120.976], 8);
}

// Make the base map; a raster tile relief map from ESRI
var esriRelief = 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Shaded_Relief/MapServer/tile/{z}/{y}/{x}';

var basemap = L.tileLayer(esriRelief, {
  attribution: 'ESRI shaded relief, NHDPlus v2',
  maxZoom: 13
});
//basemap.addTo(map);

// Add a single GeoJSON vector file for state boundaries
// This was loaded statically as a script; could also be AJAX
var stateLayer = new L.geoJson(usStates);
stateLayer.setStyle({ "color": "#444",
                      "weight": 1,
                      "fill": false,
                      "opacity": 1.0 });
stateLayer.addTo(map);

var nlcdlayer = L.tileLayer('/nlcd/{z}/{x}/{y}.png',{tms:true}).addTo(map);

var requestsPool = {
  requests: {}, //list of urls
  timeouts: {},
  timeout:  1000*60*10, //In milliseconds
  fetch: function(url) {
    if(requestsPool.exists(url))
      return requestsPool.requests[url];

    requestsPool.timeouts[url] = setTimeout(function(u) {
        requestsPool.remove(u);
    }.bind(this, url), requestsPool.timeout); //Defining the timeout

    requestsPool.requests[url] = $.getJSON(url);
    return requestsPool.requests[url];
  },
  exists: function(url) {
    return requestsPool.requests.hasOwnProperty(url); //Return the Timeout ID if present or undefined
  },
  remove: function(url) {
    requestsPool.cancel(url);
    delete requestsPool.requests[url];
  },
  cancel: function(url) {
    clearTimeout(requestsPool.timeouts[url]); //cancel the timeout
    delete requestsPool.timeouts[url];
  }
}

var riverinfo = {};

function StyleTheRivers(feature){
  requestsPool.fetch('/gauges/reachflow/'+feature.properties.huc8)
  .done(function(val){
    riverinfo[feature.properties.huc8]=val;
    $('.h'+feature.properties.huc8).css('stroke', (val.drank!==null)?grad_colours[Math.floor((grad_colours.length-1)*val.drank)]:'#FF00DE' );
    $('.h'+feature.properties.huc8).css('stroke-width', ((val.drank!==null)?(6*val.drank+2).toString():'2')+'px' );
  });
}
//$.getJSON('/gauges/reachflow/'+feature.properties.huc8, function(data){

// Style the river lines; width depends on its Strahler number
function riverStyle(feature) {
  return "stroke-width: " + feature.properties.strahler * map.getZoom()/13 + "px;stroke:#FF00DE;";
}

function riverClass(feature){
  StyleTheRivers(feature);
  return "river h" + feature.properties.huc8;
}

// Make the river overlay layer, vector tiles from our TileStache/Gunicorn server
var geojsonURL = "/rivers/{z}/{x}/{y}.json";
var riverLayer = new L.TileLayer.d3_geoJSON(geojsonURL, {
  class: riverClass,
  style: riverStyle
});
map.addLayer(riverLayer);

var countystyle = {
  "color":       "black",
  "fillColor":   "gray",
  "stroke":      "black",
  "fill":        "gray",
  "weight":      3,
  "fillOpacity": 0.65
};

function highlightCounty(e) {
    var layer = e.target;

    layer.setStyle({
        weight: 5,
        color: '#666',
        dashArray: '',
        fillOpacity: 0.7
    });

    if (!L.Browser.ie && !L.Browser.opera) {
        layer.bringToFront();
    }

    console.log(layer.feature.properties);
}

function resetCounty(e) {
    counties.resetStyle(e.target);
}

function zoomToFeature(e) {
    map.fitBounds(e.target.getBounds());
}

function onEachCounty(feature, layer) {
    layer.on({
        mouseover: highlightCounty,
        mouseout:  resetCounty,
        click:     zoomToFeature
    });
}

var counties = new L.geoJson(null,{style:countystyle,onEachFeature:onEachCounty}).addTo(map);
$.getJSON("/counties.json",
  function(data) {
    $(data.features.slice(0,20)).each(function(key, data) {
      console.log(data);
      data.id = data.properties.STATE+data.properties.COUNTY;
      counties.addData(data);
    });
  }
);

map.on('dragend', function(e) {
  //$('#spinnerBox').fadeIn();
  getStations();
});

map.on('zoomend', function() {
  getStations();
});

var markers = new L.FeatureGroup();
map.addLayer(markers);

var grad_colours = ['#b2182b','#d6604d','#f4a582','#fddbc7','#f7f7f7','#d1e5f0','#92c5de','#4393c3','#2166ac']

var baseLayers = {
  "Terrain": basemap,
  "NLCD":    nlcdlayer,
};

var overlays = {
  "Rivers":         riverLayer,
  "Gauge Stations": markers,
  "Counties":       counties
};

L.control.layers(baseLayers, overlays).addTo(map);

function getStations() {
  // Clear markers before getting new ones
  markers.clearLayers();

  // Get map bounds from Leaflet.  getBounds() returns an object
  var bbox = map.getBounds();

  var addy = "/gauges/list/xmin/ymin/xmax/ymax";
  addy     = addy.replace("xmin",bbox._southWest.lng);
  addy     = addy.replace("ymin",bbox._southWest.lat);
  addy     = addy.replace("xmax",bbox._northEast.lng);
  addy     = addy.replace("ymax",bbox._northEast.lat);

  //use jQuery's getJSON() to call the SODA API for NYC 311
  $.getJSON(addy, function(data) {
    //iterate over each 311 complaint, add a marker to the map
    _.each(data, function(marker){
      var markerItem = L.circleMarker(
        [marker.lat,marker.lng],
        {
          radius:      5,
          color:       'black',
          fillColor:   (marker.drank!==null)?grad_colours[Math.floor((grad_colours.length-1)*marker.drank)]:'#FF00DE',
          fillOpacity: 1
        }
      );
      markerItem.on('mouseover', function(){
        $('#headerbar').html(marker.name);
        $('#bottomright').html(
          'Stage: ' + marker.svalue + ' ft
' +
          ''+marker.sdt+'
' +
          'Discharge: ' + marker.dvalue + ' cfs
' +
          ''+marker.ddt+'
' +
          'Rank: ' + marker.drank.toFixed(2) + '
' +
          'More info here'
          );
      });

      // markerItem.bindPopup(
      //   '
' + marker.complaint_type + '
'
      //   + (new Date(marker.created_date)).toDateString()
      //   + ((marker.incident_address != null) ? '
' + marker.incident_address : '')
      // );

      markers.addLayer(markerItem);
    });
    map.addLayer(markers);
  });
}

function colourCounties(style,percentile_max){
  $.getJSON('/county/'+style+'.css?percentile_max='+percentile_max,function(data){

  });
}

$('.nlcdgrad').hover(function(e){
  var classname = $(e.target).data('classname');
  $('#nlcdexplanation').html(classname);
}, function(){
  $('#nlcdexplanation').html('NLCD Legend (hover over colours for details)');
})

$(document).ready(function(){
  getStations();
});<|endoftext|>


<commit_before>// ==UserScript==
// @name         LeproFriends
// @version      0.2.5
// @description  Add friends to your Voyages page.
// @author       tamtamchik
// @require      https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js
// @include      http://mush.twinoid.com/me*
// @include      http://mush.twinoid.com/u/profile/*
// @downloadURL  https://github.com/tamtamchik/mush-scripts/raw/master/leproFriends.user.js
// ==/UserScript==

(function() {
    'use strict';

    // Motion Twin Code ========================================================

    var HxOverrides = function() { };
    HxOverrides.__name__ = ["HxOverrides"];
    HxOverrides.strDate = function(s) {
        var _g = s.length;
        switch(_g) {
            case 8:
                var k = s.split(":");
                var d = new Date();
                d.setTime(0);
                d.setUTCHours(k[0]);
                d.setUTCMinutes(k[1]);
                d.setUTCSeconds(k[2]);
                return d;
            case 10:
                var k1 = s.split("-");
                return new Date(k1[0],k1[1] - 1,k1[2],0,0,0);
            case 19:
                var k2 = s.split(" ");
                var y = k2[0].split("-");
                var t = k2[1].split(":");
                return new Date(y[0],y[1] - 1,y[2],t[0],t[1],t[2]);
            default:
                throw new js__$Boot_HaxeError("Invalid date format : " + s);
        }
    };
    HxOverrides.cca = function(s,index) {
        var x = s.charCodeAt(index);
        if(x != x) return undefined;
        return x;
    };
    HxOverrides.substr = function(s,pos,len) {
        if(pos != null && pos != 0 && len != null && len < 0) return "";
        if(len == null) len = s.length;
        if(pos < 0) {
            pos = s.length + pos;
            if(pos < 0) pos = 0;
        } else if(len < 0) len = s.length + len - pos;
        return s.substr(pos,len);
    };
    HxOverrides.indexOf = function(a,obj,i) {
        var len = a.length;
        if(i < 0) {
            i += len;
            if(i < 0) i = 0;
        }
        while(i < len) {
            if(a[i] === obj) return i;
            i++;
        }
        return -1;
    };
    HxOverrides.remove = function(a,obj) {
        var i = HxOverrides.indexOf(a,obj,0);
        if(i == -1) return false;
        a.splice(i,1);
        return true;
    };
    HxOverrides.iter = function(a) {
        return { cur : 0, arr : a, hasNext : function() {
            return this.cur < this.arr.length;
        }, next : function() {
            return this.arr[this.cur++];
        }};
    };

    var haxe_ds_IntMap = function() {
      this.h = { };
    };
    haxe_ds_IntMap.__name__ = ["haxe","ds","IntMap"];
    haxe_ds_IntMap.prototype = {
        set: function(key,value) {
            this.h[key] = value;
        }
        ,get: function(key) {
            return this.h[key];
        }
        ,exists: function(key) {
            return this.h.hasOwnProperty(key);
        }
        ,keys: function() {
            var a = [];
            for( var key in this.h ) {
                if(this.h.hasOwnProperty(key)) a.push(key | 0);
            }
            return HxOverrides.iter(a);
        }
        ,__class__: haxe_ds_IntMap
    };
    var tid_ContactDecoder = function(data) {
        if(data == null) this.data = ""; else this.data = data;
        this.pos = 0;
        this.nbits = 0;
        this.bits = 0;
    };
    tid_ContactDecoder.__name__ = ["tid","ContactDecoder"];
    tid_ContactDecoder.initInvChars = function() {
        var a = [];
        var _g = 0;
        while(_g < 64) {
            var i = _g++;
            a[HxOverrides.cca(tid_ContactDecoder.ENCODE,i)] = i;
        }
        return a;
    };
    tid_ContactDecoder.prototype = {
        _r: function(n) {
            while(this.nbits < n) {
                var c = tid_ContactDecoder.DECODE[(function($this) {
                    var $r;
                    var index = $this.pos++;
                    $r = HxOverrides.cca($this.data,index);
                    return $r;
                }(this))];
                if(c == null) throw new js__$Boot_HaxeError("EOF");
                this.nbits += 6;
                this.bits <<= 6;
                this.bits |= c;
            }
            this.nbits -= n;
            return this.bits >> this.nbits & (1 << n) - 1;
        }
        ,read: function() {
            var len = this.data.length;
            var h = new haxe_ds_IntMap();
            while(this.pos < len) {
                var k = this._r(29);
                var v = this._r(1);
                h.h[k] = v;
            }
            return h;
        }
        ,__class__: tid_ContactDecoder
    };

    tid_ContactDecoder.ENCODE = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
    tid_ContactDecoder.DECODE = tid_ContactDecoder.initInvChars();

    // Lepro Code ==============================================================

    function LeproFriends() {
        this.friends = [];
        this.games = [];
        this.username = $(window.sessionStorage.tid_bar).find('span.name').text();

        var href = '';
        if (window.location.pathname != '/me') {
            href = window.location.pathname;
        } else {
            href = $('
').html(window.sessionStorage.tid_bar).contents()
                .find('.twinoidAvatar').parent().attr('href');
        }
        this.me = href.substr(href.lastIndexOf('/') + 1);
    }

    LeproFriends.prototype.getFriends = function (data) {
        if (window.sessionStorage.tid_contact) {
            var contacts = new tid_ContactDecoder(window.sessionStorage.tid_contact);
            this.friends = contacts.read();
        } else {
            setTimeout($.proxy(this.getFriends, this), 100);
        }
    };

    LeproFriends.prototype.getGames = function (data) {
        var els = $(document).find('#cdTrips a.butmini');

        this.games = $.map(els, function (el) {
            return $(el).attr('href').trim();
        });
    };

    LeproFriends.prototype.findGamesWithFriends = function () {
        var i = 0, j = 1, self = this;
        var promise = $.when();

        $.each(this.games, function (game) {
            promise = promise.then(function(){
                return $.get(self.games[game]);
            }).then(function(data){
                var last = (game == self.games.length - 1);
                var num = self.games.length - i++;
                self.checkGame(data, self.games[game], num,last);
            });
        });
    };

    LeproFriends.prototype.checkGame = function (data, url, num, last) {
        var self = this;
        var $page = $($.parseHTML(data));
        var els = $page.find('.player a');
        var casting = $page.find('#producer');

        var $users = $.map(els, function (el) {
            return $(el);
        });

        var res = $users.filter(function ($el) {
            var href = $el.attr('href');
            var user = href.substr(href.lastIndexOf('/') + 1);
            if (user == self.me) return false;
            return self.friends.h.hasOwnProperty(user);
        });

        var $list = $('
');
        $.each(res, function (i) {
            var uclass = (res[i].text() == self.username) ? 'tid_userUnknown' : 'tid_userFriend';
            res[i]
                .addClass('tid_user tid_userBg ' + uclass + ' tid_parsed')
                .css('margin','2px')
                .css('display','inline-block');

            $list.append(res[i]).append('
');
        });

        // A bit crappy, but will do the job...
        if (casting.length) {
            $list.hide();
            var castingName = $(casting).find('a');
            var $toggler = $(castingName);
            $toggler
                .attr('href','#')
                .on('click', $.proxy(self.toggleShow, self));
            $('.butmini[href="' + url +'"]').after($toggler);
            $toggler.after($list);
        } else {
            $list.show();
            $('.butmini[href="' + url +'"]').after($list);
        }
    };

    LeproFriends.prototype.toggleShow = function(event) {
        $(event.target).next().toggle();
        return false;
    };

    var lepro = new LeproFriends();
    lepro.getFriends();

    var d = $.Deferred();

    d.then($.proxy(lepro.getGames, lepro))
     .then($.proxy(lepro.findGamesWithFriends, lepro));

    d.resolve();

})();
<commit_msg>loaded added<commit_after>// ==UserScript==
// @name         LeproFriends
// @version      0.2.6
// @description  Add friends to your Voyages page.
// @author       tamtamchik
// @require      https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js
// @include      http://mush.twinoid.com/me*
// @include      http://mush.twinoid.com/u/profile/*
// @downloadURL  https://github.com/tamtamchik/mush-scripts/raw/master/leproFriends.user.js
// ==/UserScript==

(function() {
    'use strict';

    // Motion Twin Code ========================================================

    var HxOverrides = function() { };
    HxOverrides.__name__ = ["HxOverrides"];
    HxOverrides.strDate = function(s) {
        var _g = s.length;
        switch(_g) {
            case 8:
                var k = s.split(":");
                var d = new Date();
                d.setTime(0);
                d.setUTCHours(k[0]);
                d.setUTCMinutes(k[1]);
                d.setUTCSeconds(k[2]);
                return d;
            case 10:
                var k1 = s.split("-");
                return new Date(k1[0],k1[1] - 1,k1[2],0,0,0);
            case 19:
                var k2 = s.split(" ");
                var y = k2[0].split("-");
                var t = k2[1].split(":");
                return new Date(y[0],y[1] - 1,y[2],t[0],t[1],t[2]);
            default:
                throw new js__$Boot_HaxeError("Invalid date format : " + s);
        }
    };
    HxOverrides.cca = function(s,index) {
        var x = s.charCodeAt(index);
        if(x != x) return undefined;
        return x;
    };
    HxOverrides.substr = function(s,pos,len) {
        if(pos != null && pos != 0 && len != null && len < 0) return "";
        if(len == null) len = s.length;
        if(pos < 0) {
            pos = s.length + pos;
            if(pos < 0) pos = 0;
        } else if(len < 0) len = s.length + len - pos;
        return s.substr(pos,len);
    };
    HxOverrides.indexOf = function(a,obj,i) {
        var len = a.length;
        if(i < 0) {
            i += len;
            if(i < 0) i = 0;
        }
        while(i < len) {
            if(a[i] === obj) return i;
            i++;
        }
        return -1;
    };
    HxOverrides.remove = function(a,obj) {
        var i = HxOverrides.indexOf(a,obj,0);
        if(i == -1) return false;
        a.splice(i,1);
        return true;
    };
    HxOverrides.iter = function(a) {
        return { cur : 0, arr : a, hasNext : function() {
            return this.cur < this.arr.length;
        }, next : function() {
            return this.arr[this.cur++];
        }};
    };

    var haxe_ds_IntMap = function() {
      this.h = { };
    };
    haxe_ds_IntMap.__name__ = ["haxe","ds","IntMap"];
    haxe_ds_IntMap.prototype = {
        set: function(key,value) {
            this.h[key] = value;
        }
        ,get: function(key) {
            return this.h[key];
        }
        ,exists: function(key) {
            return this.h.hasOwnProperty(key);
        }
        ,keys: function() {
            var a = [];
            for( var key in this.h ) {
                if(this.h.hasOwnProperty(key)) a.push(key | 0);
            }
            return HxOverrides.iter(a);
        }
        ,__class__: haxe_ds_IntMap
    };
    var tid_ContactDecoder = function(data) {
        if(data == null) this.data = ""; else this.data = data;
        this.pos = 0;
        this.nbits = 0;
        this.bits = 0;
    };
    tid_ContactDecoder.__name__ = ["tid","ContactDecoder"];
    tid_ContactDecoder.initInvChars = function() {
        var a = [];
        var _g = 0;
        while(_g < 64) {
            var i = _g++;
            a[HxOverrides.cca(tid_ContactDecoder.ENCODE,i)] = i;
        }
        return a;
    };
    tid_ContactDecoder.prototype = {
        _r: function(n) {
            while(this.nbits < n) {
                var c = tid_ContactDecoder.DECODE[(function($this) {
                    var $r;
                    var index = $this.pos++;
                    $r = HxOverrides.cca($this.data,index);
                    return $r;
                }(this))];
                if(c == null) throw new js__$Boot_HaxeError("EOF");
                this.nbits += 6;
                this.bits <<= 6;
                this.bits |= c;
            }
            this.nbits -= n;
            return this.bits >> this.nbits & (1 << n) - 1;
        }
        ,read: function() {
            var len = this.data.length;
            var h = new haxe_ds_IntMap();
            while(this.pos < len) {
                var k = this._r(29);
                var v = this._r(1);
                h.h[k] = v;
            }
            return h;
        }
        ,__class__: tid_ContactDecoder
    };

    tid_ContactDecoder.ENCODE = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
    tid_ContactDecoder.DECODE = tid_ContactDecoder.initInvChars();

    // Lepro Code ==============================================================

    function LeproFriends() {
        this.friends = [];
        this.games = [];
        this.username = '';
        this.me = '';
        $('.butmini').after('');
    }

    LeproFriends.prototype.getSessionData = function (data) {
        if (window.sessionStorage.tid_contact) {
            var contacts = new tid_ContactDecoder(window.sessionStorage.tid_contact);
            this.friends = contacts.read();
            this.username = $(window.sessionStorage.tid_bar).find('span.name').text();
            var href = (window.location.pathname != '/me') ?
            window.location.pathname :
            $('
').html(window.sessionStorage.tid_bar)
                .contents().find('.twinoidAvatar').parent().attr('href');
            this.me = href.substr(href.lastIndexOf('/') + 1);
        } else {
            setTimeout($.proxy(this.getSessionData, this), 100);
        }
    };

    LeproFriends.prototype.getGames = function (data) {
        var els = $(document).find('#cdTrips a.butmini');

        this.games = $.map(els, function (el) {
            return $(el).attr('href').trim();
        });
    };

    LeproFriends.prototype.findGamesWithFriends = function () {
        var i = 0, j = 1, self = this;
        var promise = $.when();

        $.each(this.games, function (game) {
            promise = promise.then(function(){
                return $.get(self.games[game]);
            }).then(function(data){
                var last = (game == self.games.length - 1);
                var num = self.games.length - i++;
                self.checkGame(data, self.games[game], num,last);
            });
        });
    };

    LeproFriends.prototype.checkGame = function (data, url, num, last) {
        var self = this;
        var $page = $($.parseHTML(data));
        var els = $page.find('.player a');
        var casting = $page.find('#producer');

        var $users = $.map(els, function (el) {
            return $(el);
        });

        var res = $users.filter(function ($el) {
            var href = $el.attr('href');
            var user = href.substr(href.lastIndexOf('/') + 1);
            if (user == self.me) return false;
            return self.friends.h.hasOwnProperty(user);
        });

        var $list = $('
');
        $.each(res, function (i) {
            var uclass = (res[i].text() == self.username) ? 'tid_userUnknown' : 'tid_userFriend';
            res[i]
                .addClass('tid_user tid_userBg ' + uclass + ' tid_parsed')
                .css('margin','2px')
                .css('display','inline-block');

            $list.append(res[i]).append('
');
        });
        $('.butmini[href="' + url +'"]').next().remove();

        // A bit crappy, but will do the job...
        if (casting.length) {
            $list.hide();
            var castingName = $(casting).find('a');
            var $toggler = $(castingName);
            $toggler
                .attr('href','#')
                .on('click', $.proxy(self.toggleShow, self));
            $('.butmini[href="' + url +'"]').after($toggler);
            $toggler.after($list);
        } else {
            $list.show();
            $('.butmini[href="' + url +'"]').after($list);
        }
    };

    LeproFriends.prototype.toggleShow = function(event) {
        $(event.target).next().toggle();
        return false;
    };

    var lepro = new LeproFriends();
    var d = $.Deferred();

    d.then($.proxy(lepro.getSessionData, lepro))
        .then($.proxy(lepro.getGames, lepro))
        .then($.proxy(lepro.findGamesWithFriends, lepro));

    d.resolve();

})();
<|endoftext|>


<commit_before>/*
1.Напишите функцию compareObjects, которая принимает 2 объекта и название числового свойства,
по которому нужно выполнить сравнение объектов, и выводит в консоль свойство name того объекта,
у которого значение переданного свойства больше.
2.Создайте один объект с помощью литерала, второй через конструктор.
3.Вызовите написанную функцию и передайте два созданных объекта и свойство для сравнения
*/
var obj1 = {};
obj1.name = 'Kevin';
obj1.age = 13;

function ObjConstr( name, age ) {
  this.name = name,
  this.age = age
}
var obj2 = new ObjConstr( 'John', 33 );

function compareObjects( first, second, age ) {
  if ( first.age > second.age ) {

    return console.log( first.name );
  }

  return console.log( second.name );
}
compareObjects( obj1, obj2, 'age' );

/*
1.Создайте коллекцию из 5 музыкальных песен, где каждая песня содержит следующую информацию:
played - количество раз песня была проиграна (определить случайным образом), name - имя песни.
2.Напишите функцию favoriteSong, которая принимает коллекцию из песен,
и возвращает следующую информацию: название песни, сколько раз песня была проиграна, индекс песни в коллекции.
3.Вызовите функцию favoriteSong и передайте ей созданную коллекцию
*/
var collection = [ {played: 4, name: 'Song1'}, {played: 2, name: 'Song2'},
                   {played: 0, name: 'Song3'}, {played: 9, name: 'Song4'},
                   {played: 5, name: 'Song5'} ];

function favoriteSong( item ) {

  var most = Math.max.apply( null, item.map(function( count ) {
    return count.played;
  }));

  for (var i = 0; i < item.length; i++) {
    if (item[i].played === most) {
      return console.log( "Песня " + item[i].name + ', была проиграна: ' + item[i].played + ' раз, index: ' + i );
    }
  }
}
favoriteSong(collection);

/*
1.Опишите конструктор объектов (класс) Calculator с двумя методами:
add - принимает число и прибавляет его к предыдущему,
getCurrentSum - принимает индекс и возвращает результирующее число на шаге указынном в индексе
(если индекса нет, возвращает текущую сумму).
2.Создайте два экземпляра класса Calculator
3.Добавьте в первый объект числа 3,8,11 и во второй 5,12,17.
4.Выведите в консоль сумму:
 - всех чисел всех объектов, убедитесь (56)
 - сумму чисел всех объектов на втором шаге (28)
 - для одного объекта сумму после третьего шага и общую результирующую сумму (должна совпадать)
*/
function Calculator(  ) {
  var arg = arguments,
      result = 0;

  for (var i = 0, m = arg.length; i < m; ++i) {
    result += +arg[i];
  }

  this.add = function() {
    var adding = arguments,
        sum = 0;

    for (var i = 0, n = adding.length; i < n; ++i) {
      sum += +adding[i];
    }

    return result += sum;
  },

  this.getCurrentSum = function( index ) {

    if ( typeof index === 'undefined' ) {
      return result;
    }

    result = 0;
    for (var i = 0; i < index; ++i) {
      result += +arg[i];
    }

    return result;
  }
}
var calc1 = new Calculator( 3, 8, 11 );
var calc2 = new Calculator( 5, 12, 17 );

var sum1 = calc1.add();
var sum2 = calc2.add();
var total = sum1 + sum2;
console.log( total );

var step1 = calc1.getCurrentSum(2);
var step2 = calc2.getCurrentSum(2);
var steps = step1 + step2;
console.log( steps );

var step3 = calc2.getCurrentSum(3);
console.log( sum1 + step3 === total );
<commit_msg>renew calculator<commit_after>/*
1.Напишите функцию compareObjects, которая принимает 2 объекта и название числового свойства,
по которому нужно выполнить сравнение объектов, и выводит в консоль свойство name того объекта,
у которого значение переданного свойства больше.
2.Создайте один объект с помощью литерала, второй через конструктор.
3.Вызовите написанную функцию и передайте два созданных объекта и свойство для сравнения
*/
var obj1 = {};
obj1.name = 'Kevin';
obj1.age = 13;

function ObjConstr( name, age ) {
  this.name = name,
  this.age = age
}
var obj2 = new ObjConstr( 'John', 33 );

function compareObjects( first, second, age ) {
  if ( first.age > second.age ) {

    return console.log( first.name );
  }

  return console.log( second.name );
}
compareObjects( obj1, obj2, 'age' );

/*
1.Создайте коллекцию из 5 музыкальных песен, где каждая песня содержит следующую информацию:
played - количество раз песня была проиграна (определить случайным образом), name - имя песни.
2.Напишите функцию favoriteSong, которая принимает коллекцию из песен,
и возвращает следующую информацию: название песни, сколько раз песня была проиграна, индекс песни в коллекции.
3.Вызовите функцию favoriteSong и передайте ей созданную коллекцию
*/
var collection = [ {played: 4, name: 'Song1'}, {played: 2, name: 'Song2'},
                   {played: 0, name: 'Song3'}, {played: 9, name: 'Song4'},
                   {played: 5, name: 'Song5'} ];

function favoriteSong( item ) {

  var most = Math.max.apply( null, item.map(function( count ) {
    return count.played;
  }));

  for (var i = 0; i < item.length; i++) {
    if (item[i].played === most) {
      return console.log( "Песня " + item[i].name + ', была проиграна: ' + item[i].played + ' раз, index: ' + i );
    }
  }
}
favoriteSong(collection);

/*
1.Опишите конструктор объектов (класс) Calculator с двумя методами:
add - принимает число и прибавляет его к предыдущему,
getCurrentSum - принимает индекс и возвращает результирующее число на шаге указынном в индексе
(если индекса нет, возвращает текущую сумму).
2.Создайте два экземпляра класса Calculator
3.Добавьте в первый объект числа 3,8,11 и во второй 5,12,17.
4.Выведите в консоль сумму:
 - всех чисел всех объектов, убедитесь (56)
 - сумму чисел всех объектов на втором шаге (28)
 - для одного объекта сумму после третьего шага и общую результирующую сумму (должна совпадать)
*/
function Calculator() {
  var sum = 0,
      arr = [];

  this.add = function() {
    for (var i = 0; i < arguments.length; i++) {
      sum += arguments[i];
      arr.push( sum );
    }

    return sum;
  },

  this.getCurrentSum = function( index ) {
    if ( typeof index === 'undefined' ) {
      return arr[arr.length - 1];
    }

    return arr[index - 1];
  }
}
var calc1 = new Calculator();
var calc2 = new Calculator();

var sum1 = calc1.add( 3, 8, 11 );
var sum2 = calc2.add( 5, 12, 17 );
var total = sum1 + sum2;
console.log( total );

var step1 = calc1.getCurrentSum(2);
var step2 = calc2.getCurrentSum(2);
var steps = step1 + step2;
console.log( steps );

var step3 = calc2.getCurrentSum(3);
console.log( sum1 + step3 === total );
<|endoftext|>


<commit_before>"use strict";

var React       = require('react');
var Environment = require('./environment');
var matchRoutes   = require('./matchRoutes');

/**
 * A container component which captures <a> clicks and, if there's a matching
 * route defined, routes them.
 */
var CaptureClicks = React.createClass({
  displayName: 'CaptureClicks',

  propTypes: {
    component: React.PropTypes.func.isRequired,
    environment: React.PropTypes.object
  },

  getDefaultProps: function() {
    return {
      component: React.DOM.div,
      environment: Environment.defaultEnvironment,
      gotoURL: function(url) {
        // We should really just be allowing the event's default action, be we
        // can't make the decision to do that synchronously.
        window.location.href = url;
      }
    }
  },

  onClick: function(event) {
    if (this.props.onClick) {
      this.props.onClick(event);
    }

    // Ignore canceled events, modified clicks, and right clicks.
    if (event.defaultPrevented) { return; }
    if (event.metaKey || event.ctrlKey || event.shiftKey) { return; }
    if (event.button !== 0) { return; }

    // Get the <a> element.
    var el = event.target;
    while (el && el.nodeName !== 'A') {
      el = el.parentNode;
    }

    // Ignore clicks from non-a elements.
    if (!el) { return; }

    // Ignore the click if the element has a target.
    if (el.target && el.target !== '_self') { return; }

    // Ignore the click if it's a download link. (We use this method of
    // detecting the presence of the attribute for old IE versions.)
    if (!!el.attributes.download) { return; }

    // Ignore links that don't share a protocol and host with ours.
    if (el.protocol !== location.protocol) { return; }
    if (el.host !== location.host) { return; }

    var pathname = el.pathname;
    if (el.pathname.charAt(0) !== '/') {
      // Make sure IE has a leading slash.
      pathname = '/' + pathname;
    }

    // Try to find a matching path in available routes.
    var environment = this.props.environment;
    event.preventDefault();
    environment.navigate(
      pathname,
      {
        onBeforeNavigation: function(path, navigation) {
          if (!navigation.match || !navigation.match.match) {
            this.props.gotoURL(el.href);
            return false;
          }
        }.bind(this)
      },
      function (err, info) {
        if (err) {
          throw err;
        }
      }
    );
  },

  render: function() {
    var props = {
      onClick: this.onClick
    };
    return this.transferPropsTo(this.props.component(props, this.props.children));
  }

});

module.exports = CaptureClicks;
<commit_msg>Ignore rel="external" links<commit_after>"use strict";

var React       = require('react');
var Environment = require('./environment');
var matchRoutes   = require('./matchRoutes');

/**
 * A container component which captures <a> clicks and, if there's a matching
 * route defined, routes them.
 */
var CaptureClicks = React.createClass({
  displayName: 'CaptureClicks',

  propTypes: {
    component: React.PropTypes.func.isRequired,
    environment: React.PropTypes.object
  },

  getDefaultProps: function() {
    return {
      component: React.DOM.div,
      environment: Environment.defaultEnvironment,
      gotoURL: function(url) {
        // We should really just be allowing the event's default action, be we
        // can't make the decision to do that synchronously.
        window.location.href = url;
      }
    }
  },

  onClick: function(event) {
    if (this.props.onClick) {
      this.props.onClick(event);
    }

    // Ignore canceled events, modified clicks, and right clicks.
    if (event.defaultPrevented) { return; }
    if (event.metaKey || event.ctrlKey || event.shiftKey) { return; }
    if (event.button !== 0) { return; }

    // Get the <a> element.
    var el = event.target;
    while (el && el.nodeName !== 'A') {
      el = el.parentNode;
    }

    // Ignore clicks from non-a elements.
    if (!el) { return; }

    // Ignore the click if the element has a target.
    if (el.target && el.target !== '_self') { return; }

    // Ignore the click if it's a download link. (We use this method of
    // detecting the presence of the attribute for old IE versions.)
    if (!!el.attributes.download) { return; }

    // Ignore links that don't share a protocol and host with ours.
    if (el.protocol !== location.protocol) { return; }
    if (el.host !== location.host) { return; }

    // Ignore 'rel="external"' links.
    if (el.rel && /(?:^|\s+)external(?:\s+|$)/.test(el.rel)) { return; }

    var pathname = el.pathname;
    if (el.pathname.charAt(0) !== '/') {
      // Make sure IE has a leading slash.
      pathname = '/' + pathname;
    }

    // Try to find a matching path in available routes.
    var environment = this.props.environment;
    event.preventDefault();
    environment.navigate(
      pathname,
      {
        onBeforeNavigation: function(path, navigation) {
          if (!navigation.match || !navigation.match.match) {
            this.props.gotoURL(el.href);
            return false;
          }
        }.bind(this)
      },
      function (err, info) {
        if (err) {
          throw err;
        }
      }
    );
  },

  render: function() {
    var props = {
      onClick: this.onClick
    };
    return this.transferPropsTo(this.props.component(props, this.props.children));
  }

});

module.exports = CaptureClicks;
<|endoftext|>


<commit_before>'use strict';

function ConsoleLogger() {

    this.error = function () {
        if (this.enabled) {
            console.error.apply(this, arguments);
        }
    };

    this.warn = function () {
        if (this.enabled) {
            console.warn.apply(this, arguments);
        }
    };

    this.info = function () {
        if (this.enabled) {
            console.info.apply(this, arguments);
        }
    };

    this.log = function () {
        if (this.enabled) {
            console.log.apply(this, arguments);
        }
    };

    this.debug = function () {
        if (this.enabled) {
            console.log.apply(this, arguments);
        }
    };
}

ConsoleLogger.prototype.enabled = true;

module.exports = ConsoleLogger;
<commit_msg>Make ConsoleLogger log level configurable<commit_after>'use strict';

var DEBUG = 1;
var INFO = 2;
var WARN = 3;
var ERROR = 4;

/**
 * Configurable console logger, default level is INFO
 *
 * @constructor
 */
function ConsoleLogger() {

    this.error = function () {
        if (loggingLevel(ERROR)) {
            console.error.apply(this, arguments);
        }
    };

    this.warn = function () {
        if (loggingLevel(WARN)) {
            console.warn.apply(this, arguments);
        }
    };

    this.info = function () {
        if (loggingLevel(INFO)) {
            console.info.apply(this, arguments);
        }
    };

    this.log = function () {
        if (loggingLevel(INFO)) {
            console.log.apply(this, arguments);
        }
    };

    this.debug = function () {
        if (loggingLevel(DEBUG)) {
            console.log.apply(this, arguments);
        }
    };

    this.setLevelToInfo = function () {
        setLevel(INFO);
    };

    this.setLevelToDebug = function() {
        setLevel(DEBUG);
    };

    this.setLevelToWarning = function() {
        setLevel(WARN);
    };

    this.setLevelToError = function() {
        setLevel(ERROR);
    };
}

function setLevel(newLevel) {
    ConsoleLogger.prototype.__level = newLevel;
}

function loggingLevel(logLevel) {
    return logLevel >= ConsoleLogger.prototype.__level;
}

ConsoleLogger.prototype.__level = INFO;

module.exports = ConsoleLogger;
<|endoftext|>


<commit_before>// node-inspector version of on webkit-inspector/DebuggerAgent.cpp

var convert = require('./convert.js'),
  async = require('async');

function DebuggerAgent(session) {
  this._session = session;
}

DebuggerAgent.prototype = {
  canSetScriptSource: function(params, done) {
    // live-edit is not implemented yet
    done(null, { result: false });
  },

  enable: function(params, done) {
    this._session.attach(done);
  },

  disable: function(params, done) {
    this._session.disableDebugger(done);
  },

  resume: function(params, done) {
    this._sendContinue(undefined, done);
  },

  _sendContinue: function(stepAction, done) {
    var args = stepAction ? { stepaction: stepAction } : undefined;
    this._session.sendDebugRequest('continue', args, function(error, result) {
      done(error);
      if (!error)
        this._session.sendInspectorEvent('Debugger.resumed');
    }.bind(this));
  },

  pause: function(params, done) {
    this._session.sendDebugRequest('suspend', {}, function(error, result) {
      done(error);
      if (!error)
        this._session.sendPausedEvent();
    }.bind(this));
  },

  stepOver: function(params, done) {
    this._sendContinue('next', done);
  },

  stepInto: function(params, done) {
    this._sendContinue('in', done);
  },

  stepOut: function(params, done) {
    this._sendContinue('out', done);
  },

  continueToLocation: function(params, done) {
    var requestParams = {
      type: 'scriptId',
      target: parseInt(params.location.scriptId),
      line: params.location.lineNumber,
      column: params.location.columnNumber,
    };

    this._session.sendDebugRequest('setbreakpoint', requestParams, function(error, response) {
      if (error != null) {
        done(error);
        return;
      }

      this._session.continueToLocationBreakpointId = response.breakpoint;
      this._session.sendDebugRequest('continue', undefined, function(error, response) {
        done(error);
      });
    }.bind(this));
  },

  getScriptSource: function(params, done) {
    this._session.getScriptSource(params.scriptId, done);
  },

  setPauseOnExceptions: function(params, done) {
    var requestParams = {
      flags: [
        {
          name: 'breakOnCaughtException',
          value: params.state
        }
      ]
    };
    this._session.sendDebugRequest('flags', requestParams, function(error, response) {
      done(error, null);
    });
  },

  // TODO(bajtos) Keep track of breakpoints - see implementation in session.js

  setBreakpointByUrl: function(params, done) {
    // TODO(bajtos) - handle params.urlRegex
    var requestParams = {
      type: 'script',
      target: convert.inspectorUrlToV8Name(params.url),
      line: params.lineNumber,
      column: params.columnNumber,
      condition: params.condition,
    };

    this._session.sendDebugRequest('setbreakpoint', requestParams, function(error, response) {
      if (error != null) {
        done(error);
        return;
      }

      done(null, {
        breakpointId: response.breakpoint.toString(),
        locations: response.actual_locations.map(convert.v8LocationToInspectorLocation),
      });
    });
  },

  removeBreakpoint: function(params, done) {
    var requestParams = {
      breakpoint: params.breakpointId
    };

    this._session.sendDebugRequest('clearbreakpoint', requestParams, function(error, response) {
      done(error, null);
    });
  },

  setBreakpointsActive: function(params, done) {
    this._session.sendDebugRequest('listbreakpoints', {}, function(error, response) {
      if (error) {
        done(error);
        return;
      }

      function setBreakpointState(bp, next) {
        var req = { breakpoint: bp.number, enabled: params.active };
        this._session.sendDebugRequest('changebreakpoint', req, next);
      }

      async.eachSeries(response.breakpoints, setBreakpointState.bind(this), done);
    }.bind(this));
  },

  setOverlayMessage: function(params, done) {
    done();
  },

  evaluateOnCallFrame: function (params, done) {
    var self = this;
    var expression = params.expression;
    var frame = Number(params.callFrameId);

    self._session.sendDebugRequest(
      'evaluate',
      {
        expression: params.expression,
        frame: frame
      },
      function (err, result) {
        // Errors from V8 are actually just messages, so we need to fill them out a bit.
        if (err) {
          err = convert.v8ErrorToInspectorError(err);
        }

        done(null, {
          result: err || convert.v8ResultToInspectorResult(result),
          wasThrown: !!err
        });
      }
    );
  },

  getFunctionDetails: function(params, done) {
    var handle = params.functionId;
    this._session.sendDebugRequest(
      'lookup',
      {
        handles: [ handle ],
        includeSource: false,
      },
      function (error, responseBody) {
        if (error) {
          done(error);
        } else {
          done(null, convert.v8FunctionLookupToFunctionDetails(responseBody[handle]));
        }
      }.bind(this));
  }
}

exports.DebuggerAgent = DebuggerAgent;
<commit_msg>Fixed DebuggerAgent.setPauseOnExceptions.<commit_after>// node-inspector version of on webkit-inspector/DebuggerAgent.cpp

var convert = require('./convert.js'),
  async = require('async');

function DebuggerAgent(session) {
  this._session = session;
}

DebuggerAgent.prototype = {
  canSetScriptSource: function(params, done) {
    // live-edit is not implemented yet
    done(null, { result: false });
  },

  enable: function(params, done) {
    this._session.attach(done);
  },

  disable: function(params, done) {
    this._session.disableDebugger(done);
  },

  resume: function(params, done) {
    this._sendContinue(undefined, done);
  },

  _sendContinue: function(stepAction, done) {
    var args = stepAction ? { stepaction: stepAction } : undefined;
    this._session.sendDebugRequest('continue', args, function(error, result) {
      done(error);
      if (!error)
        this._session.sendInspectorEvent('Debugger.resumed');
    }.bind(this));
  },

  pause: function(params, done) {
    this._session.sendDebugRequest('suspend', {}, function(error, result) {
      done(error);
      if (!error)
        this._session.sendPausedEvent();
    }.bind(this));
  },

  stepOver: function(params, done) {
    this._sendContinue('next', done);
  },

  stepInto: function(params, done) {
    this._sendContinue('in', done);
  },

  stepOut: function(params, done) {
    this._sendContinue('out', done);
  },

  continueToLocation: function(params, done) {
    var requestParams = {
      type: 'scriptId',
      target: parseInt(params.location.scriptId),
      line: params.location.lineNumber,
      column: params.location.columnNumber,
    };

    this._session.sendDebugRequest('setbreakpoint', requestParams, function(error, response) {
      if (error != null) {
        done(error);
        return;
      }

      this._session.continueToLocationBreakpointId = response.breakpoint;
      this._session.sendDebugRequest('continue', undefined, function(error, response) {
        done(error);
      });
    }.bind(this));
  },

  getScriptSource: function(params, done) {
    this._session.getScriptSource(params.scriptId, done);
  },

  setPauseOnExceptions: function(params, done) {
    var args = [
      { type: 'all', enabled: params.state == 'all' },
      { type: 'uncaught', enabled: params.state == 'uncaught' },
    ];

    async.eachSeries(
      args,
      function(arg, next) {
        this._session.sendDebugRequest('setexceptionbreak', arg, next);
      }.bind(this),
      done);
  },

  // TODO(bajtos) Keep track of breakpoints - see implementation in session.js

  setBreakpointByUrl: function(params, done) {
    // TODO(bajtos) - handle params.urlRegex
    var requestParams = {
      type: 'script',
      target: convert.inspectorUrlToV8Name(params.url),
      line: params.lineNumber,
      column: params.columnNumber,
      condition: params.condition,
    };

    this._session.sendDebugRequest('setbreakpoint', requestParams, function(error, response) {
      if (error != null) {
        done(error);
        return;
      }

      done(null, {
        breakpointId: response.breakpoint.toString(),
        locations: response.actual_locations.map(convert.v8LocationToInspectorLocation),
      });
    });
  },

  removeBreakpoint: function(params, done) {
    var requestParams = {
      breakpoint: params.breakpointId
    };

    this._session.sendDebugRequest('clearbreakpoint', requestParams, function(error, response) {
      done(error, null);
    });
  },

  setBreakpointsActive: function(params, done) {
    this._session.sendDebugRequest('listbreakpoints', {}, function(error, response) {
      if (error) {
        done(error);
        return;
      }

      function setBreakpointState(bp, next) {
        var req = { breakpoint: bp.number, enabled: params.active };
        this._session.sendDebugRequest('changebreakpoint', req, next);
      }

      async.eachSeries(response.breakpoints, setBreakpointState.bind(this), done);
    }.bind(this));
  },

  setOverlayMessage: function(params, done) {
    done();
  },

  evaluateOnCallFrame: function (params, done) {
    var self = this;
    var expression = params.expression;
    var frame = Number(params.callFrameId);

    self._session.sendDebugRequest(
      'evaluate',
      {
        expression: params.expression,
        frame: frame
      },
      function (err, result) {
        // Errors from V8 are actually just messages, so we need to fill them out a bit.
        if (err) {
          err = convert.v8ErrorToInspectorError(err);
        }

        done(null, {
          result: err || convert.v8ResultToInspectorResult(result),
          wasThrown: !!err
        });
      }
    );
  },

  getFunctionDetails: function(params, done) {
    var handle = params.functionId;
    this._session.sendDebugRequest(
      'lookup',
      {
        handles: [ handle ],
        includeSource: false,
      },
      function (error, responseBody) {
        if (error) {
          done(error);
        } else {
          done(null, convert.v8FunctionLookupToFunctionDetails(responseBody[handle]));
        }
      }.bind(this));
  }
}

exports.DebuggerAgent = DebuggerAgent;
<|endoftext|>


<commit_before>var wishlist = function () {
  this.data;
};

wishlist.prototype.load = function(code, callback) {
  var _this = this;
  $.get("/wishlist/" + code, function (data) {
    _this.data = data;
    callback(_this.data);
  });
};

wishlist.prototype.save = function(data, callback) {
  $.post("/wishlist/", data, function () {
    callback();
  });
};

wishlist.prototype.createNew = function(callback) {
  var _this = this;

  var def = {
    title : "Default"
  };

  $.post("/wishlist/", def, function(data) {
    _this.data = data;
    callback();
  });
};

wishlist.prototype.wishlistAsHTML = function(box) {
  box.append($('<input type="text" class="title">').val(this.data.title));
  var ul = $('<ul>');
  box.append(ul);
  $.each(this.data.wishes, function (i, v) {
    var li = $('<li>');
    var desc = $('<input type="text" class="description">').val(v.description);
    var url = $('<input type="text" class="url">').val(v.url);
    ul.append(li);
    li.append(desc);
    li.append(url);
  });

  // Make one last empty set of boxes
  desc = $('<input type="text" class="description last">');
  url = $('<input type="text" class="url last">');
  li = $('<li>');
  ul.append(li);
  li.append(desc);
  li.append(url);

  return box;
}

var app = function () {
  this.$content = $('div.span10');
  this.$create = $('#create-wishlist');
  this.clickers();
};

app.prototype.newWishlist = function () {
  var _this = this;
  this.wishlist = new wishlist();
  this.wishlist.createNew(function () {

    _this.$content.empty();
    _this.wishlist.wishlistAsHTML(_this.$content);
    window.history.pushState(null, "lol", _this.wishlist.data.code);
  });
};

app.prototype.saveWishlist = function () {
  var _this = this;

};

app.prototype.loadWishlist = function (code) {
  var _this = this;
  this.wishlist = new wishlist();
  this.wishlist.load(code, function (data) {
    _this.$content.empty();
    _this.wishlist.wishlistAsHTML(_this.$content);
  });
};

app.prototype.clickers = function () {
  var _this = this;
  this.$create.click(function () {
    _this.newWishlist();
  });
};<commit_msg>Make sure the list of wishes exists before generating html<commit_after>var wishlist = function () {
  this.data;
};

wishlist.prototype.load = function(code, callback) {
  var _this = this;
  $.get("/wishlist/" + code, function (data) {
    _this.data = data;
    callback(_this.data);
  });
};

wishlist.prototype.save = function(data, callback) {
  $.post("/wishlist/", data, function () {
    callback();
  });
};

wishlist.prototype.createNew = function(callback) {
  var _this = this;

  var def = {
    title : "Default"
  };

  $.post("/wishlist/", def, function(data) {
    _this.data = data;
    callback();
  });
};

wishlist.prototype.wishlistAsHTML = function(box) {
  box.append($('<input type="text" class="title">').val(this.data.title));
  var ul = $('<ul>');
  box.append(ul);
  if(this.data.wishes) {
    $.each(this.data.wishes, function (i, v) {
      var li = $('<li>');
      var desc = $('<input type="text" class="description">').val(v.description);
      var url = $('<input type="text" class="url">').val(v.url);
      ul.append(li);
      li.append(desc);
      li.append(url);
    });
  }

  // Make one last empty set of boxes
  desc = $('<input type="text" class="description last">');
  url = $('<input type="text" class="url last">');
  li = $('<li>');
  ul.append(li);
  li.append(desc);
  li.append(url);

  return box;
}

var app = function () {
  this.$content = $('div.span10');
  this.$create = $('#create-wishlist');
  this.clickers();
};

app.prototype.newWishlist = function () {
  var _this = this;
  this.wishlist = new wishlist();
  this.wishlist.createNew(function () {

    _this.$content.empty();
    _this.wishlist.wishlistAsHTML(_this.$content);
    window.history.pushState(null, "lol", _this.wishlist.data.code);
  });
};

app.prototype.saveWishlist = function () {
  var _this = this;

};

app.prototype.loadWishlist = function (code) {
  var _this = this;
  this.wishlist = new wishlist();
  this.wishlist.load(code, function (data) {
    _this.$content.empty();
    _this.wishlist.wishlistAsHTML(_this.$content);
  });
};

app.prototype.clickers = function () {
  var _this = this;
  this.$create.click(function () {
    _this.newWishlist();
  });
};<|endoftext|>


<commit_before>Mailer.config({
  from: 'John Doe <from@domain.com',
  replyTo: 'John Doe <from@domain.com'
});

Meteor.startup(function() {

  Mailer.init({
    templates: Templates,     // Global Templates namespace, see lib/templates.js.
    helpers: TemplateHelpers, // Global template helper namespace.
    layout: {
      name: 'emailLayout',
      path: 'layout.html',   // Relative to 'private' dir.
      scss: 'layout.scss'
    }
  });

});
<commit_msg>Fix typos in Mailer Config<commit_after>Mailer.config({
  from: 'John Doe <from@domain.com>',
  replyTo: 'John Doe <from@domain.com>'
});

Meteor.startup(function() {

  Mailer.init({
    templates: Templates,     // Global Templates namespace, see lib/templates.js.
    helpers: TemplateHelpers, // Global template helper namespace.
    layout: {
      name: 'emailLayout',
      path: 'layout.html',   // Relative to 'private' dir.
      scss: 'layout.scss'
    }
  });

});
<|endoftext|>


<commit_before>var crdt       = require('../..')
var connect    = require('express') //require('connect')
var es         = require('event-stream')
var createShoe = require('shoe')
var heartbeat  = require('./heartbeat')

var app = connect()
  .use(connect.static(__dirname))

var doc = new crdt.Doc()
heartbeat(doc, 'Server')

doc.on('row_update', function (row) {
  console.log(row.toJSON())
})

var shoe = createShoe(function (sock) {
    //connect to the crdt stream
    sock
      .pipe(doc.createStream())
      .pipe(sock)
})

/*var n = doc.set('server', {
  name: 'server', create: new Date(), heartbeat: Date.now()
})
*/

app.on('log', console.log)
shoe.install(app.listen(3000), '/simple')

<commit_msg>use connect instead of express<commit_after>var crdt       = require('../..')
var connect    = require('connect')
var es         = require('event-stream')
var createShoe = require('shoe')
var heartbeat  = require('./heartbeat')

var app = connect()
  .use(connect.static(__dirname))

var doc = new crdt.Doc()
heartbeat(doc, 'Server')

doc.on('row_update', function (row) {
  console.log(row.toJSON())
})

var shoe = createShoe(function (sock) {
    //connect to the crdt stream
    sock
      .pipe(doc.createStream())
      .pipe(sock)
})

/*var n = doc.set('server', {
  name: 'server', create: new Date(), heartbeat: Date.now()
})
*/

app.on('log', console.log)
shoe.install(app.listen(3000), '/simple')

<|endoftext|>


<commit_before>// remap jQuery to $
(function($) {

  $(function() {

    // Resizable
	  var mouseMoveHandler = function(e) {
	    var initial = e.data.initial,
          u = Math.min(Math.max(initial.uHeight + (e.pageY - initial.offTop), initial.min), initial.max),
          b = Math.min(Math.max(initial.bHeight - (e.pageY - initial.offTop), initial.min), initial.max);
      initial.up.height(u);
      initial.below.height(b);

      $('#iframe-cover').height(initial.up.height()); // iframe fix
    };
    var mouseUpHandler = function(e) {
      $(document)
        .unbind('mousemove', mouseMoveHandler)
        .unbind('mouseup', mouseUpHandler);

      $('#iframe-cover').hide(); // iframe fix
      if (e.data.initial.below.height() === 0) {
        $('#main').removeClass('opened');
        Pontoon.common.postMessage("MODE", "Advanced");
      } else {
        $('#main').addClass('opened');
        Pontoon.common.postMessage("MODE", "Basic");
      }
    };
	  $('#logo, #drag').bind('mousedown', function(e) {
      e.preventDefault();

      var up = $('#source'),
          below = $('#entitylist'),
          data = {
            up: up,
            below: below,
            uHeight: up.height(),
            bHeight: below.height(),
            offTop: e.pageY,
            min: 0,
            max: $(document).height()
          };

      // iframe fix: Prevent iframes from capturing the mousemove events during a drag
      $('#iframe-cover').show().height(up.height());

      $(document)
        .bind('mousemove', { initial: data }, mouseMoveHandler)
        .bind('mouseup', { initial: data }, mouseUpHandler);
    });

    // Resize iframe with window
    $(window).resize(function () {
      $('#source').height($(document).height() - $('#main').height());
    });

    // Show error message
    function showError(message) {
      $('#project-load').hide();
      $("#install").css('visibility', 'visible');
      Pontoon.common.showError(message);
      $('#intro').css('display', 'table').hide().fadeIn();
    }

    // Validate URL
    function checkURL() {
      // Initialize Pontoon only if project code supports it
      function receiveMessage(e) {
        // TODO: Check origin - hardcode Pontoon domain name
        if (JSON.parse(e.data).type === "SUPPORTED") {
          // Show header and iframe with appropriate height
          $('#main').slideDown(function() {
            $('#source').show().height($(document).height() - $(this).height());
            $('#project-load').hide();
          });
          Pontoon.init(window, $('#source').get(0).contentWindow, locale);
          window.removeEventListener("message", receiveMessage, false);
        }
      }
      window.addEventListener("message", receiveMessage, false);

      // Load project page into iframe
      $('#source').attr('src', url);

      // Show error message if no callback for 5 seconds: Pontoon/iframe not supported, 404…
      var i = 0,
          interval = setInterval(function() {
            if (i < 50) {
              i++;
              if (Pontoon.app) { // Set in Pontoon.init() which is called on "supported"
                clearInterval(interval);
              }
            } else {
              clearInterval(interval);
              showError('Oops, website is not supported by Pontoon. Check instructions below.');
            }
          }, 100);

      // If loading page fails, don't wait 5 seconds to trigger error (ignore localhost)
      if (!url.split('://')[1] || url.split('://')[1].indexOf('localhost') !== 0) {
        $.ajax({
          url: base + 'checkurl/',
          data: {url: url},
          timeout: 4500,
          success: function(data) {
            if (data === "invalid") {
              clearInterval(interval);
              showError('Oops, website could not be found.');
            }
          }
        });
      }
    }

    // MAIN CODE

    // Dynamically set Demo URL
    var l = window.location;
    $('#demo').attr('href', '/locale/de/url/' + l.protocol + '//' + l.hostname + '/pontoon/hooks/php/test/testpilot/');

    // Empty iframe if cached
    $('#source').removeAttr("src");

    // Check for params
    var locale = $('#server').data('locale'),
        url = $('#server').data('url'),
        acceptLanguage = $('#server').data('accept-language'),
        base = $('base').attr('href');

    // Set include script URL
    $("#install code").html('<script src="' + base + 'static/js/project/pontoon.js"></script>');

    // Translate
    if (locale && url) {
      $('.url').val(url);
      // Set locale
      var escapedLocale = locale.replace(".", "\\.").replace("@", "\\@"),
          escapedLocaleElement = $('.locale .menu .language.' + escapedLocale);
      if (escapedLocaleElement.length) { // Locale on the list
        $('.locale .button .language').addClass(escapedLocale).html(escapedLocaleElement.html());
        checkURL();
      } else {
        showError('Oops, locale not supported.');
      }

    // Intro
    } else {
      if ($('.locale .menu .language.' + acceptLanguage).length === 0) { // Locale not on the list
        acceptLanguage = $('.locale .menu .language:first').attr('class').split(' ')[1];
      }
      $('.locale .button .language').addClass(acceptLanguage).html($('.locale .menu .language.' + acceptLanguage).html());
      $('#install').css('visibility', 'visible');
      $('#project-load').hide();
      $('#intro').css('display', 'table').hide().fadeIn(function() {});
    }

  });

}(this.jQuery));

// usage: log('inside coolFunc',this,arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function() {
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if (this.console) {
    console.log(Array.prototype.slice.call(arguments));
  }
};

// catch all document.write() calls
(function(doc) {
  var write = doc.write;
  doc.write = function(q) {
    log('document.write(): ', arguments);
    if (/docwriteregexwhitelist/.test(q)) {
      write.apply(doc,arguments);
    }
  };
}(document));
<commit_msg>Set demo url and include script url at once<commit_after>// remap jQuery to $
(function($) {

  $(function() {

    // Resizable
	  var mouseMoveHandler = function(e) {
	    var initial = e.data.initial,
          u = Math.min(Math.max(initial.uHeight + (e.pageY - initial.offTop), initial.min), initial.max),
          b = Math.min(Math.max(initial.bHeight - (e.pageY - initial.offTop), initial.min), initial.max);
      initial.up.height(u);
      initial.below.height(b);

      $('#iframe-cover').height(initial.up.height()); // iframe fix
    };
    var mouseUpHandler = function(e) {
      $(document)
        .unbind('mousemove', mouseMoveHandler)
        .unbind('mouseup', mouseUpHandler);

      $('#iframe-cover').hide(); // iframe fix
      if (e.data.initial.below.height() === 0) {
        $('#main').removeClass('opened');
        Pontoon.common.postMessage("MODE", "Advanced");
      } else {
        $('#main').addClass('opened');
        Pontoon.common.postMessage("MODE", "Basic");
      }
    };
	  $('#logo, #drag').bind('mousedown', function(e) {
      e.preventDefault();

      var up = $('#source'),
          below = $('#entitylist'),
          data = {
            up: up,
            below: below,
            uHeight: up.height(),
            bHeight: below.height(),
            offTop: e.pageY,
            min: 0,
            max: $(document).height()
          };

      // iframe fix: Prevent iframes from capturing the mousemove events during a drag
      $('#iframe-cover').show().height(up.height());

      $(document)
        .bind('mousemove', { initial: data }, mouseMoveHandler)
        .bind('mouseup', { initial: data }, mouseUpHandler);
    });

    // Resize iframe with window
    $(window).resize(function () {
      $('#source').height($(document).height() - $('#main').height());
    });

    // Show error message
    function showError(message) {
      $('#project-load').hide();
      $("#install").css('visibility', 'visible');
      Pontoon.common.showError(message);
      $('#intro').css('display', 'table').hide().fadeIn();
    }

    // Validate URL
    function checkURL() {
      // Initialize Pontoon only if project code supports it
      function receiveMessage(e) {
        // TODO: Check origin - hardcode Pontoon domain name
        if (JSON.parse(e.data).type === "SUPPORTED") {
          // Show header and iframe with appropriate height
          $('#main').slideDown(function() {
            $('#source').show().height($(document).height() - $(this).height());
            $('#project-load').hide();
          });
          Pontoon.init(window, $('#source').get(0).contentWindow, locale);
          window.removeEventListener("message", receiveMessage, false);
        }
      }
      window.addEventListener("message", receiveMessage, false);

      // Load project page into iframe
      $('#source').attr('src', url);

      // Show error message if no callback for 5 seconds: Pontoon/iframe not supported, 404…
      var i = 0,
          interval = setInterval(function() {
            if (i < 50) {
              i++;
              if (Pontoon.app) { // Set in Pontoon.init() which is called on "supported"
                clearInterval(interval);
              }
            } else {
              clearInterval(interval);
              showError('Oops, website is not supported by Pontoon. Check instructions below.');
            }
          }, 100);

      // If loading page fails, don't wait 5 seconds to trigger error (ignore localhost)
      if (!url.split('://')[1] || url.split('://')[1].indexOf('localhost') !== 0) {
        $.ajax({
          url: base + 'checkurl/',
          data: {url: url},
          timeout: 4500,
          success: function(data) {
            if (data === "invalid") {
              clearInterval(interval);
              showError('Oops, website could not be found.');
            }
          }
        });
      }
    }

    // MAIN CODE

    // Empty iframe if cached
    $('#source').removeAttr("src");

    // Check for params
    var locale = $('#server').data('locale'),
        url = $('#server').data('url'),
        acceptLanguage = $('#server').data('accept-language'),
        base = $('base').attr('href');

    // Set Demo URL
    var l = window.location;
    $('#demo').attr('href', '/locale/de/url/' + l.protocol + '//' + l.hostname + '/pontoon/hooks/php/test/testpilot/');

    // Set include script URL
    $("#install code").html('<script src="' + base + 'static/js/project/pontoon.js"></script>');

    // Translate
    if (locale && url) {
      $('.url').val(url);
      // Set locale
      var escapedLocale = locale.replace(".", "\\.").replace("@", "\\@"),
          escapedLocaleElement = $('.locale .menu .language.' + escapedLocale);
      if (escapedLocaleElement.length) { // Locale on the list
        $('.locale .button .language').addClass(escapedLocale).html(escapedLocaleElement.html());
        checkURL();
      } else {
        showError('Oops, locale not supported.');
      }

    // Intro
    } else {
      if ($('.locale .menu .language.' + acceptLanguage).length === 0) { // Locale not on the list
        acceptLanguage = $('.locale .menu .language:first').attr('class').split(' ')[1];
      }
      $('.locale .button .language').addClass(acceptLanguage).html($('.locale .menu .language.' + acceptLanguage).html());
      $('#install').css('visibility', 'visible');
      $('#project-load').hide();
      $('#intro').css('display', 'table').hide().fadeIn(function() {});
    }

  });

}(this.jQuery));

// usage: log('inside coolFunc',this,arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function() {
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if (this.console) {
    console.log(Array.prototype.slice.call(arguments));
  }
};

// catch all document.write() calls
(function(doc) {
  var write = doc.write;
  doc.write = function(q) {
    log('document.write(): ', arguments);
    if (/docwriteregexwhitelist/.test(q)) {
      write.apply(doc,arguments);
    }
  };
}(document));
<|endoftext|>


<commit_before>contract('MetaCoin', function(accounts) {
  it("should put 10000 MetaCoin in the first account", function() {
    var meta = MetaCoin.deployed();

    return meta.getBalance.call(accounts[0]).then(function(balance) {
      assert.equal(balance.valueOf(), 10000, "10000 wasn't in the first account");
    });
  });
  it("should call a function that depends on a linked library", function() {
    var meta = MetaCoin.deployed();
    var metaCoinBalance;
    var metaCoinEthBalance;

    return meta.getBalance.call(accounts[0]).then(function(outCoinBalance) {
      metaCoinBalance = outCoinBalance.toNumber();
      return meta.getBalanceInEth.call(accounts[0]);
    }).then(function(outCoinBalanceEth) {
      metaCoinEthBalance = outCoinBalanceEth.toNumber();
    }).then(function() {
      assert.equal(metaCoinEthBalance, 2 * metaCoinBalance, "Library function returned unexpeced function, linkage may be broken");
    });
  });
  it("should send coin correctly", function() {
    var meta = MetaCoin.deployed();

    // Get initial balances of first and second account.
    var account_one = accounts[0];
    var account_two = accounts[1];

    var account_one_starting_balance;
    var account_two_starting_balance;
    var account_one_ending_balance;
    var account_two_ending_balance;

    var amount = 10;

    return meta.getBalance.call(account_one).then(function(balance) {
      account_one_starting_balance = balance.toNumber();
      return meta.getBalance.call(account_two);
    }).then(function(balance) {
      account_two_starting_balance = balance.toNumber();
      return meta.sendCoin(account_two, amount, {from: account_one});
    }).then(function() {
      return meta.getBalance.call(account_one);
    }).then(function(balance) {
      account_one_ending_balance = balance.toNumber();
      return meta.getBalance.call(account_two);
    }).then(function(balance) {
      account_two_ending_balance = balance.toNumber();

      assert.equal(account_one_ending_balance, account_one_starting_balance - amount, "Amount wasn't correctly taken from the sender");
      assert.equal(account_two_ending_balance, account_two_starting_balance + amount, "Amount wasn't correctly sent to the receiver");
    });
  });
});
<commit_msg>fix typo in message<commit_after>contract('MetaCoin', function(accounts) {
  it("should put 10000 MetaCoin in the first account", function() {
    var meta = MetaCoin.deployed();

    return meta.getBalance.call(accounts[0]).then(function(balance) {
      assert.equal(balance.valueOf(), 10000, "10000 wasn't in the first account");
    });
  });
  it("should call a function that depends on a linked library", function() {
    var meta = MetaCoin.deployed();
    var metaCoinBalance;
    var metaCoinEthBalance;

    return meta.getBalance.call(accounts[0]).then(function(outCoinBalance) {
      metaCoinBalance = outCoinBalance.toNumber();
      return meta.getBalanceInEth.call(accounts[0]);
    }).then(function(outCoinBalanceEth) {
      metaCoinEthBalance = outCoinBalanceEth.toNumber();
    }).then(function() {
      assert.equal(metaCoinEthBalance, 2 * metaCoinBalance, "Library function returned unexpected function, linkage may be broken");
    });
  });
  it("should send coin correctly", function() {
    var meta = MetaCoin.deployed();

    // Get initial balances of first and second account.
    var account_one = accounts[0];
    var account_two = accounts[1];

    var account_one_starting_balance;
    var account_two_starting_balance;
    var account_one_ending_balance;
    var account_two_ending_balance;

    var amount = 10;

    return meta.getBalance.call(account_one).then(function(balance) {
      account_one_starting_balance = balance.toNumber();
      return meta.getBalance.call(account_two);
    }).then(function(balance) {
      account_two_starting_balance = balance.toNumber();
      return meta.sendCoin(account_two, amount, {from: account_one});
    }).then(function() {
      return meta.getBalance.call(account_one);
    }).then(function(balance) {
      account_one_ending_balance = balance.toNumber();
      return meta.getBalance.call(account_two);
    }).then(function(balance) {
      account_two_ending_balance = balance.toNumber();

      assert.equal(account_one_ending_balance, account_one_starting_balance - amount, "Amount wasn't correctly taken from the sender");
      assert.equal(account_two_ending_balance, account_two_starting_balance + amount, "Amount wasn't correctly sent to the receiver");
    });
  });
});
<|endoftext|>


<commit_before>odoo.define('pos_order_note.tour', function(require) {
    "use strict";

    var core = require('web.core');
    var tour = require('web_tour.tour');

    var _t = core._t;

    tour.register('pos_order_note_tour', {
        url: "/web",
    }, [{
        trigger: '.o_app[data-menu-xmlid="point_of_sale.menu_point_root"], .oe_menu_toggler[data-menu-xmlid="point_of_sale.menu_point_root"]',
        content: _t("Ready to launch your point of sale? Click here."),
        position: 'bottom',
    }, {
        trigger: ".o_pos_kanban button.oe_kanban_action_button",
        content: _t("
Click to start the point of sale interface. It runs on tablets, laptops, or industrial hardware.

Once the session launched, the system continues to run without an internet connection.
"),
        position: "bottom"
    }, {
        trigger: ".tables .table",
        content: _t("
Click on table
"),
        position: "bottom"
    }, {
        trigger: ".product-list .product",
        content: _t("
Select the first product in the product list
"),
        position: "bottom"
    },
    {
        trigger: ".control-button:has(.fa-tag)",
        content: _t("
Click on Note button
"),
        position: "bottom"
    }, {
        trigger: ".product_note #1",
        content: _t("
Click on the first predefined note
"),
        position: "bottom"
    }, {
        trigger: ".product_note #2",
        content: _t("
Click on the second predefined note
"),
        position: "bottom"
    }, {
        trigger: ".popup-confirm-note .confirm",
        content: _t("
Click on Confirm button
"),
        position: "bottom"
    }, {
        trigger: ".control-button:has(.fa-tag)",
        content: _t("
Click on Note button
"),
        position: "bottom"
    }, {
        trigger: ".popup-confirm-note .order_type",
        content: _t("
Click on Order Note
"),
        position: "bottom"
    }, {
        trigger: ".product_note #3",
        content: _t("
Click on predefined note
"),
        position: "bottom"
    }, {
        trigger: ".popup-confirm-note .confirm",
        content: _t("
Click on Confirm button
"),
        position: "bottom"
    }, {
        trigger: ".control-buttons .order-submit",
        content: _t("
Click on Order button to send order to Order printer
"),
        position: "bottom"
    }
    ]);
});
<commit_msg>[CI] replace id to data-id in test<commit_after>odoo.define('pos_order_note.tour', function(require) {
    "use strict";

    var core = require('web.core');
    var tour = require('web_tour.tour');

    var _t = core._t;

    tour.register('pos_order_note_tour', {
        url: "/web",
    }, [{
        trigger: '.o_app[data-menu-xmlid="point_of_sale.menu_point_root"], .oe_menu_toggler[data-menu-xmlid="point_of_sale.menu_point_root"]',
        content: _t("Ready to launch your point of sale? Click here."),
        position: 'bottom',
    }, {
        trigger: ".o_pos_kanban button.oe_kanban_action_button",
        content: _t("
Click to start the point of sale interface. It runs on tablets, laptops, or industrial hardware.

Once the session launched, the system continues to run without an internet connection.
"),
        position: "bottom"
    }, {
        trigger: ".tables .table",
        content: _t("
Click on table
"),
        position: "bottom"
    }, {
        trigger: ".product-list .product",
        content: _t("
Select the first product in the product list
"),
        position: "bottom"
    },
    {
        trigger: ".control-button:has(.fa-tag)",
        content: _t("
Click on Note button
"),
        position: "bottom"
    }, {
        trigger: ".product_note [data-id='1']",
        content: _t("
Click on the first predefined note
"),
        position: "bottom"
    }, {
        trigger: ".product_note [data-id='2']",
        content: _t("
Click on the second predefined note
"),
        position: "bottom"
    }, {
        trigger: ".popup-confirm-note .confirm",
        content: _t("
Click on Confirm button
"),
        position: "bottom"
    }, {
        trigger: ".control-button:has(.fa-tag)",
        content: _t("
Click on Note button
"),
        position: "bottom"
    }, {
        trigger: ".popup-confirm-note .order_type",
        content: _t("
Click on Order Note
"),
        position: "bottom"
    }, {
        trigger: ".product_note [data-id='3']",
        content: _t("
Click on predefined note
"),
        position: "bottom"
    }, {
        trigger: ".popup-confirm-note .confirm",
        content: _t("
Click on Confirm button
"),
        position: "bottom"
    }, {
        trigger: ".control-buttons .order-submit",
        content: _t("
Click on Order button to send order to Order printer
"),
        position: "bottom"
    }
    ]);
});
<|endoftext|>


<commit_before>'use strict';

var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
chai.should();

var ContentReader = require('../index');

describe('Content-reader', function () {
  describe(': getEntryById', function () {
    var reader;

    // create reader to use for tests
    before(function (done) {
      reader = new ContentReader(
        'k93yc4pkke22',
        '8df52946b77b1862ea5650ddb4b3b41a3047303d11defbdb0f8cb5fb8c2738b0');
      done();
    });

    it('should return an article when passed the article id', function () {
      let actual = reader.getEntryById('4V2Ze2uOZy60k8CeUc0Gsu', { include: 1 }).then(entry => {
        var parsedEntry = reader.parse.it(entry);

        parsedEntry.should.have.deep.property('id', '4V2Ze2uOZy60k8CeUc0Gsu');
        parsedEntry.should.have.property('meta').that.is.an('object');
        parsedEntry.should.have.deep.property('contentType', 'article');
        parsedEntry.should.have.property('fields').that.is.an('object');
        parsedEntry.should.have.property('bubba').that.is.an('object');
      })
      .catch(err => {
        console.log(err.stack);
      });
    });

  });
});
<commit_msg>should have been moved during renaming<commit_after><|endoftext|>