<commit_before>var config = require('config');
var mapModule = require('map');
var plugins = require('./leaflet_plugins');
var polyUtil = require('./polyline_encoded.js');
var routeboxer = require('./leaflet_routeboxer.js');
var leaflet_label = require('./leaflet_label/leaflet.label-src.js');

var center = config.geocode().center.split(',').map(parseFloat)
if (config.map_provider && config.map_provider() !== 'AmigoCloud') {
  L.mapbox.accessToken = config.mapbox_access_token();
}

module.exports = function(el) {
  var map, realtime, southWest, northEast, blurLayer;

  if (config.map_provider && config.map_provider() === 'AmigoCloud') {
    southWest = L.latLng(35.946877085397,-123.480610897013);
    northEast = L.latLng(40.763279543715,-118.789317362500);
    map = (new L.amigo.map(el, {
      amigoLogo: 'right',
      loadAmigoLayers: false,
      inertia: false,
      zoomAnimation: $('.hide-map').css('display') !== 'none',
      maxBounds: L.latLngBounds(southWest, northEast),
      minZoom: 8
    })).setView([center[1], center[0]], config.geocode().zoom);

    L.amigo.auth.setToken(config.support_data_token());

    blurLayer = L.tileLayer(
    'https://www.amigocloud.com/api/v1/users/'+
	'23/projects/3019/datasets/23835/tiles/{z}/{x}/{y}.png?' +
	'token=' + config.support_data_token(),
      {
        name: 'Uncovered Area'
      }
    );

    map.addAuthLayer({
      id: config.mapbox_map_id(),
      accessToken: config.mapbox_access_token(),
      name: 'Gray',
      provider: 'mapbox'
    });
    map.addBaseLayer(L.amigo.AmigoGray);
    map.layersControl.addBaseLayer(
      L.bingLayer(
        config.bing_key(),
	{
	  type: 'Road',
	  attribution: 'Bing Maps'
	}
      ),
      'Bing Road'
    );
    map.layersControl.addOverlay(blurLayer);
    blurLayer.addTo(map);

    module.exports.activeMap = map;

    map.realtimeControl = L.control.toggleRealTime().addTo(map);

    realtime = mapModule.realtime();
    console.log("entre amigo", map)

  } else {
    console.log("entre mapaboxs");
    map = L.mapbox.map(el, config.mapbox_map_id(), {
      attributionControl: false,
      inertia: false,
      zoomAnimation: false
    }).setView([center[1], center[0]], config.geocode().zoom);
  }

  return map;
};

module.exports.getMap = function () {
  return this.activeMap;
};

module.exports.cleanRoute = function() {
    module.exports.activeRoute.removeLayer();
    module.exports.activeRoute = null;
};

module.exports.polyline_creadas = [];
module.exports.marker_creadas = [];

module.exports.getpolyline_creadas = function () {
  return this.polyline_creadas;
};

module.exports.getMarker_creadas = function () {
  return this.marker_creadas;
};

module.exports.cleanPolyline = function() {
    var polyline_creadas = this.getpolyline_creadas();
    var map = this.activeMap;
    for (i in polyline_creadas) {
        try {
                map.removeLayer(polyline_creadas[i]);
                console.log("elimina el mapa?");
            } catch (e) {
                console.log("problema al eliminar " + e);
            }

  }
  this.polyline_creadas = [];

};

module.exports.cleanMarker = function() {
    var map = this.activeMap;
    for (i in this.marker_creadas) {
        try {
                map.removeLayer(this.marker_creadas[i]);
                console.log("elimina el mapa?");
            } catch (e) {
                console.log("problema al eliminar " + e);
            }
    }

  this.marker_creadas = [];

};

module.exports.marker_map = function(from, to, map){
    console.log("mapa from ->", from);
    console.log("mapa to ->", to);
     var IconStart = L.icon({
        iconUrl: 'assets/images/graphics/start.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });
    var IconEnd = L.icon({
        iconUrl: 'assets/images/graphics/end.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });

    //L.marker([37.35337508231001,-121.93626880645752], {icon: IconStart}).bindPopup('From').addTo(map);
    //L.marker([37.44377324953697,-122.16601610183714], {icon: IconEnd}).bindPopup('to').addTo(map);
    //var leaflet_label = new L.marker([from[0],from[1]], {icon: IconStart, draggable: true});
    //leaflet_label.bindLabel('From');
    //leaflet_label.addTo(map);
    var markerform = new L.marker([from[0],from[1]], {icon: IconStart, draggable: true})
        .addTo(map);
    var markerto = new L.marker([to[0],to[1]], {icon: IconEnd, draggable: true})
        .addTo(map);

    var _this = this;
    markerform.on('dragend', function(e){
       var marker = e.target;
       var result = marker.getLatLng();
       console.log("cordenadas drag from ->",result);
       _this.cleanPolyline();
    });

    markerto.on('dragend', function(e){
        var marker = e.target;
        var result = marker.getLatLng();
        console.log("cordenadas drag to ->",result);
        _this.cleanPolyline();
    });

    this.marker_creadas.push(markerform);
    this.marker_creadas.push(markerto);
};

module.exports.marker_map_point = function(to, map){

    //console.log("mapa point to ->", to);
    var name = to[2];

//    var myIcon = L.divIcon({className: 'leaflet-div-icon'});
//// you can set .my-div-icon styles in CSS
//
//    L.marker([to[0], to[1]], {icon: myIcon}).addTo(map);

    //var myIcon = L.CircleMarker({
    //    iconUrl: 'assets/images/graphics/icono.svg',
    //    iconSize: [20, 20],
    //    iconAnchor: [10, 10],
    //    labelAnchor: [6, 0] // as I want the label to appear 2px past the icon (10 + 2 - 6)
    //});
    //L.marker([to[0], to[1]], {
    //    icon: myIcon
    //}).bindLabel(name, {
    //    noHide: true,
    //    direction: 'auto'
    //}).addTo(map);

    //var circle = L.circle([to[0], to[1]], 700, {
    //    color: '#000',
    //    weight: 3,
    //    fillColor: '#ffffff',
    //    fillOpacity: 1
    //}).bindLabel(name, {
    //    noHide: true,
    //    direction: 'auto'
    //}).addTo(map);

    var markers = [
      L.marker([to[0], to[1]])
    ];
    var layer = L.layerGroup(markers).addTo(map).eachLayer(function(layer){layer.showLabel()});

    //for( i in layer._layers)
    //  layer._layers[i].showLabel();

    //var myZoom = {
    //  start:  map.getZoom(),
    //  end: map.getZoom()
    //};
    ////console.log(myZoom);
    //map.on('zoomstart', function(e) {
    //   myZoom.start = map.getZoom();
    //    //console.log("start zoom 400 ", myZoom.start);
    //});
    //
    //map.on('zoomend', function(e) {
    //    myZoom.end = map.getZoom();
    //     //console.log("End zoom ", myZoom.end);
    //    var diff = myZoom.start - myZoom.end;
    //    if (diff > 0) {
    //        circle.setRadius(circle.getRadius() * 2);
    //    } else if (diff < 0) {
    //        circle.setRadius(circle.getRadius() / 2);
    //    }
    //});

    //this.polyline_creadas.push(circle);
};

module.exports.drawRouteAmigo = function(route,mode) {
      var color = '#000';
      var weight = 5;
      var dasharray= '';

        if (mode=="CAR") {
            color = '#9E9E9E';
            dasharray= '6';
            weight = 3;

        }else if(mode=="BICYCLE") {
            color = '#FF0000';
            dasharray= '6';
            weight = 3;

        }else if(mode=="SUBWAY" || mode=="RAIL") {
            color = '#FF0000';
             weight = 8;

        }
        else if(mode == "WALK") {
            color = '#0BC8F4';
            dasharray= '6';
             weight = 3;
        }
        else if(mode=="BUS") {
            color = '#FEF0B5';
             weight = 8;
        }

       var color_options = {
            color: color,
            opacity: 1,
            weight: weight,
            dashArray: dasharray
        };

      route = new L.Polyline(L.PolylineUtil.decode(route, 5), color_options);
      this.polyline_creadas.push(route);
        //module.exports.polyline_creadas.push(route);
      var boxes = L.RouteBoxer.box(route, 5);
      var bounds = new L.LatLngBounds([]);
      var boxpolys = new Array(boxes.length);

      for (var i = 0; i < boxes.length; i++) {
        bounds.extend(boxes[i]);
      }
      route.addTo(this.activeMap);
      this.activeMap.fitBounds(bounds);
};

<commit_msg>adding elemtes<commit_after>var config = require('config');
var mapModule = require('map');
var plugins = require('./leaflet_plugins');
var polyUtil = require('./polyline_encoded.js');
var routeboxer = require('./leaflet_routeboxer.js');
var leaflet_label = require('./leaflet_label/leaflet.label-src.js');

var center = config.geocode().center.split(',').map(parseFloat)
if (config.map_provider && config.map_provider() !== 'AmigoCloud') {
  L.mapbox.accessToken = config.mapbox_access_token();
}

module.exports = function(el) {
  var map, realtime, southWest, northEast, blurLayer;

  if (config.map_provider && config.map_provider() === 'AmigoCloud') {
    southWest = L.latLng(35.946877085397,-123.480610897013);
    northEast = L.latLng(40.763279543715,-118.789317362500);
    map = (new L.amigo.map(el, {
      amigoLogo: 'right',
      loadAmigoLayers: false,
      inertia: false,
      zoomAnimation: $('.hide-map').css('display') !== 'none',
      maxBounds: L.latLngBounds(southWest, northEast),
      minZoom: 8
    })).setView([center[1], center[0]], config.geocode().zoom);

    L.amigo.auth.setToken(config.support_data_token());

    blurLayer = L.tileLayer(
    'https://www.amigocloud.com/api/v1/users/'+
	'23/projects/3019/datasets/23835/tiles/{z}/{x}/{y}.png?' +
	'token=' + config.support_data_token(),
      {
        name: 'Uncovered Area'
      }
    );

    map.addAuthLayer({
      id: config.mapbox_map_id(),
      accessToken: config.mapbox_access_token(),
      name: 'Gray',
      provider: 'mapbox'
    });
    map.addBaseLayer(L.amigo.AmigoGray);
    map.layersControl.addBaseLayer(
      L.bingLayer(
        config.bing_key(),
	{
	  type: 'Road',
	  attribution: 'Bing Maps'
	}
      ),
      'Bing Road'
    );
    map.layersControl.addOverlay(blurLayer);
    blurLayer.addTo(map);

    module.exports.activeMap = map;

    map.realtimeControl = L.control.toggleRealTime().addTo(map);

    realtime = mapModule.realtime();
    console.log("entre amigo", map)

  } else {
    console.log("entre mapaboxs");
    map = L.mapbox.map(el, config.mapbox_map_id(), {
      attributionControl: false,
      inertia: false,
      zoomAnimation: false
    }).setView([center[1], center[0]], config.geocode().zoom);
  }

  return map;
};

module.exports.getMap = function () {
  return this.activeMap;
};

module.exports.cleanRoute = function() {
    module.exports.activeRoute.removeLayer();
    module.exports.activeRoute = null;
};

module.exports.polyline_creadas = [];
module.exports.marker_creadas = [];

module.exports.getpolyline_creadas = function () {
  return this.polyline_creadas;
};

module.exports.getMarker_creadas = function () {
  return this.marker_creadas;
};

module.exports.cleanPolyline = function() {
    var polyline_creadas = this.getpolyline_creadas();
    var map = this.activeMap;
    for (i in polyline_creadas) {
        try {
                map.removeLayer(polyline_creadas[i]);
                console.log("elimina el mapa?");
            } catch (e) {
                console.log("problema al eliminar " + e);
            }

  }
  this.polyline_creadas = [];

};

module.exports.cleanMarker = function() {
    var map = this.activeMap;
    for (i in this.marker_creadas) {
        try {
                map.removeLayer(this.marker_creadas[i]);
                console.log("elimina el mapa?");
            } catch (e) {
                console.log("problema al eliminar " + e);
            }
    }

  this.marker_creadas = [];

};

module.exports.marker_map = function(from, to, map){
    console.log("mapa from ->", from);
    console.log("mapa to ->", to);
     var IconStart = L.icon({
        iconUrl: 'assets/images/graphics/start.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });
    var IconEnd = L.icon({
        iconUrl: 'assets/images/graphics/end.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });

    //L.marker([37.35337508231001,-121.93626880645752], {icon: IconStart}).bindPopup('From').addTo(map);
    //L.marker([37.44377324953697,-122.16601610183714], {icon: IconEnd}).bindPopup('to').addTo(map);
    //var leaflet_label = new L.marker([from[0],from[1]], {icon: IconStart, draggable: true});
    //leaflet_label.bindLabel('From');
    //leaflet_label.addTo(map);
    var markerform = new L.marker([from[0],from[1]], {icon: IconStart, draggable: true})
        .addTo(map);
    var markerto = new L.marker([to[0],to[1]], {icon: IconEnd, draggable: true})
        .addTo(map);

    var _this = this;
    markerform.on('dragend', function(e){
       var marker = e.target;
       var result = marker.getLatLng();
       console.log("cordenadas drag from ->",result);
       _this.cleanPolyline();
    });

    markerto.on('dragend', function(e){
        var marker = e.target;
        var result = marker.getLatLng();
        console.log("cordenadas drag to ->",result);
        _this.cleanPolyline();
    });

    this.marker_creadas.push(markerform);
    this.marker_creadas.push(markerto);
};

module.exports.marker_map_point = function(to, map){

    //console.log("mapa point to ->", to);
    var name = to[2];

//    var myIcon = L.divIcon({className: 'leaflet-div-icon'});
//// you can set .my-div-icon styles in CSS
//
//    L.marker([to[0], to[1]], {icon: myIcon}).addTo(map);

    //var myIcon = L.CircleMarker({
    //    iconUrl: 'assets/images/graphics/icono.svg',
    //    iconSize: [20, 20],
    //    iconAnchor: [10, 10],
    //    labelAnchor: [6, 0] // as I want the label to appear 2px past the icon (10 + 2 - 6)
    //});
    //L.marker([to[0], to[1]], {
    //    icon: myIcon
    //}).bindLabel(name, {
    //    noHide: true,
    //    direction: 'auto'
    //}).addTo(map);

    //var circle = L.circle([to[0], to[1]], 700, {
    //    color: '#000',
    //    weight: 3,
    //    fillColor: '#ffffff',
    //    fillOpacity: 1
    //}).bindLabel(name, {
    //    noHide: true,
    //    direction: 'auto'
    //}).addTo(map);

    var IconEnd = L.icon({
        iconUrl: 'assets/images/graphics/icono.svg',
        iconSize: [20, 20],
        iconAnchor: [0, 0],
        popupAnchor:  [-3, -76]
    });
    var markers = [
      L.marker([to[0], to[1]], {icon: IconEnd})
    ];
    var layer = L.layerGroup(markers).addTo(map).eachLayer(function(layer){layer.showLabel()});

    //for( i in layer._layers)
    //  layer._layers[i].showLabel();

    //var myZoom = {
    //  start:  map.getZoom(),
    //  end: map.getZoom()
    //};
    ////console.log(myZoom);
    //map.on('zoomstart', function(e) {
    //   myZoom.start = map.getZoom();
    //    //console.log("start zoom 400 ", myZoom.start);
    //});
    //
    //map.on('zoomend', function(e) {
    //    myZoom.end = map.getZoom();
    //     //console.log("End zoom ", myZoom.end);
    //    var diff = myZoom.start - myZoom.end;
    //    if (diff > 0) {
    //        circle.setRadius(circle.getRadius() * 2);
    //    } else if (diff < 0) {
    //        circle.setRadius(circle.getRadius() / 2);
    //    }
    //});

    //this.polyline_creadas.push(circle);
};

module.exports.drawRouteAmigo = function(route,mode) {
      var color = '#000';
      var weight = 5;
      var dasharray= '';

        if (mode=="CAR") {
            color = '#9E9E9E';
            dasharray= '6';
            weight = 3;

        }else if(mode=="BICYCLE") {
            color = '#FF0000';
            dasharray= '6';
            weight = 3;

        }else if(mode=="SUBWAY" || mode=="RAIL") {
            color = '#FF0000';
             weight = 8;

        }
        else if(mode == "WALK") {
            color = '#0BC8F4';
            dasharray= '6';
             weight = 3;
        }
        else if(mode=="BUS") {
            color = '#FEF0B5';
             weight = 8;
        }

       var color_options = {
            color: color,
            opacity: 1,
            weight: weight,
            dashArray: dasharray
        };

      route = new L.Polyline(L.PolylineUtil.decode(route, 5), color_options);
      this.polyline_creadas.push(route);
        //module.exports.polyline_creadas.push(route);
      var boxes = L.RouteBoxer.box(route, 5);
      var bounds = new L.LatLngBounds([]);
      var boxpolys = new Array(boxes.length);

      for (var i = 0; i < boxes.length; i++) {
        bounds.extend(boxes[i]);
      }
      route.addTo(this.activeMap);
      this.activeMap.fitBounds(bounds);
};

<|endoftext|>


<commit_before>/*
 * 不枝雀
 * 2017-5-1 18:33:41
 */
var stylesheet_Map = {};
var documentStyle = document.documentElement.style;
var stylePrefix = function (documentStyle) {
    if ("-webkit-transform" in documentStyle) return "-webkit-";
    if ("-moz-transform" in documentStyle) return "-moz-";
    if ("msImeAlign" in documentStyle || "msTransform" in documentStyle) return "-ms-";
    if ("-o-transform" in documentStyle) return "-o-";
    return "";
}(documentStyle);
var nodePrefix = stylePrefix.slice(1, stylePrefix.length - 1);
/**
 * 将中划线转成驼峰式
 * @param {string} key
 */
var transformNodeKey = function (key) {
    key = key.replace(/^\-+/, "").replace(/\-+(\w)/g, function (m, w) {
        return w.toUpperCase();
    });
    if (/^(?:webkit|moz|ms|o)[A-Z]/.test(key)) {
        key = key.replace(/^(?:webkit|moz|ms|o)([A-Z])/, (_, m) => m.toLowerCase());
    }
    if (nodePrefix && !(key in documentStyle)) {
        var temp = nodePrefix + key.replace(/^[a-z]/, m => m.toUpperCase());
        if (temp in documentStyle) {
            key = temp;
        }
    }
    return key;
};
/**
 * 将驼峰式命名转成中划线命名
 * @param {string} key
 */
var transformCssKey = function (key) {
    key = key.replace(/[A-Z]/g, function (m) {
        return "-" + m.toLowerCase();
    });
    if (/^\-?(?:webkit|moz|ms|o)\-/.test(key)) {
        key = key.replace(/^\-?(?:webkit|moz|ms|o)\-/, '');
    }
    if (nodePrefix && !(key in documentStyle)) {
        var temp = stylePrefix + key;
        if (temp in documentStyle) {
            key = temp;
        }
    }
    return key;
};
var isWorseIE = /msie\s+[2-8]/i.test(navigator.userAgent);
/**
 * 将样式绑定到dom元素
 * @param {Element} targetNode
 * @param {string|object} oStyle
 * @param {string|} oValue
 */
var cssTargetNode = function (targetNode, oStyle, oValue) {
    var styleobject = targetNode.style;
    if (typeof oStyle === "string") {
        if (typeof oValue === "string") {
            styleobject[transformNodeKey(oStyle)] = oValue;
            return;
        } else {
            try {
                oStyle = parseKV(oStyle, ';', ':');
            } catch (e) { }
        }
    }
    if (oStyle instanceof Object) {
        if (isWorseIE) {

            for (var k in oStyle) {
                var key = transformNodeKey(k);
                if (key in styleobject) {
                    try {
                        styleobject[key] = oStyle[k];
                    } catch (e) {
                        console.warn(key, oStyle[k], "无效");
                    }
                }
            }
        } else {
            for (var k in oStyle) {
                var key = transformNodeKey(k);
                if (key in styleobject) styleobject[key] = oStyle[k];
            }
        }
    }
};
/**
 * 将样式绑定到选择器
 * @param {string} targetSelector
 * @param {string|object} oStyle
 * @param {string|} oValue
 */
var cssTargetSelector = function (targetSelector, oStyle, oValue) {
    var stylesheet = stylesheet_Map[targetSelector];
    if (!stylesheet) {
        stylesheet = document.createElement("style");
        stylesheet.type = "text/css";
        stylesheet_Map[targetSelector] = stylesheet;
        document.getElementsByTagName("head")[0].appendChild(stylesheet);
    }
    var styleobject = {};
    if (typeof oStyle === "string") {
        if (typeof oValue === "string") {
            var key = transformCssKey(oStyle);
            styleobject[key] = oValue;
        } else {
            oStyle.replace(/^;+|;+$/g, "").split(/;+/).map(function (kv) {
                var [k, v] = kv.split(":");
                delete styleobject[k];
                if (k) styleobject[k] = v || '';
            });
        }
    } else if (oStyle instanceof Object) {
        for (var k in oStyle) {
            var key = transformCssKey(k);
            styleobject[key] = oStyle[k];
        }
    }
    var rowStyles = [];
    var styleSheet = stylesheet.styleSheet;
    var cssText = stylesheet.savedText || (styleSheet ? styleSheet.cssText : stylesheet.innerHTML).replace(/^[\s\S]*?\{([\s\S]*?)\}[\s\S]*?$/, "$1");
    cssText.split(";").forEach(function (kv) {
        var k = kv.replace(/^(.*?)\:.*$/, "$1");
        if (k && !(k in styleobject)) rowStyles.push(kv);
    });
    for (var k in styleobject) {
        if (styleobject[k]) {
            rowStyles.push(k + ":" + styleobject[k]);
        }
    }
    var innerCss = `${targetSelector}{${rowStyles.join(";")}}`;
    innerCss = color.transform(innerCss);
    cssTargetStyleSheet(stylesheet, innerCss);
};

function cssTargetStyleSheet(stylesheet, innerCss) {
    var styleSheet = stylesheet.styleSheet;
    if (styleSheet) {
        //IE
        styleSheet.cssText = innerCss;
    } else {
        stylesheet.innerHTML = innerCss;
    }
}

/**
 * 函数的入口
 * @param {string|Element} target
 * @param {object|string} oStyle
 * @param {|string} oValue
 */
var css = function (target, oStyle, oValue) {
    if (isNode(target)) {
        if (/^style$/i.test(target.tagName)) {
            cssTargetStyleSheet(target, oStyle, oValue);
        } else {
            cssTargetNode(target, oStyle, oValue);
        }
    }
    else if (isString(target)) cssTargetSelector(target, oStyle, oValue);
};<commit_msg>css支持为不带单位的数字加上单位<commit_after>/*
 * 不枝雀
 * 2017-5-1 18:33:41
 */
var stylesheet_Map = {};
var documentStyle = document.documentElement.style;
var stylePrefix = function (documentStyle) {
    if ("-webkit-transform" in documentStyle) return "-webkit-";
    if ("-moz-transform" in documentStyle) return "-moz-";
    if ("msImeAlign" in documentStyle || "msTransform" in documentStyle) return "-ms-";
    if ("-o-transform" in documentStyle) return "-o-";
    return "";
}(documentStyle);
var ratioPropReg = /(?:opacity|line\-height|lineHeight)$/i;
var nodePrefix = stylePrefix.slice(1, stylePrefix.length - 1);
var transfromSimpleValue = function (value) {
    if (isFinite(value)) return fromOffset(+value || 0);
    return value;
};
var transformValue = function (value, k) {
    if (ratioPropReg.test(k)) return value;
    if (/^[\w\s\.]+$/.test(value)) return isFinite(value) ? transfromSimpleValue(value) : value.split(/\s/).map(transfromSimpleValue).join(' ');
    return value;
};
/**
 * 将中划线转成驼峰式
 * @param {string} key
 */
var transformNodeKey = function (key) {
    key = key.replace(/^\-+/, "").replace(/\-+(\w)/g, function (m, w) {
        return w.toUpperCase();
    });
    if (/^(?:webkit|moz|ms|o)[A-Z]/.test(key)) {
        key = key.replace(/^(?:webkit|moz|ms|o)([A-Z])/, (_, m) => m.toLowerCase());
    }
    if (nodePrefix && !(key in documentStyle)) {
        var temp = nodePrefix + key.replace(/^[a-z]/, m => m.toUpperCase());
        if (temp in documentStyle) {
            key = temp;
        }
    }
    return key;
};
/**
 * 将驼峰式命名转成中划线命名
 * @param {string} key
 */
var transformCssKey = function (key) {
    key = key.replace(/[A-Z]/g, function (m) {
        return "-" + m.toLowerCase();
    });
    if (/^\-?(?:webkit|moz|ms|o)\-/.test(key)) {
        key = key.replace(/^\-?(?:webkit|moz|ms|o)\-/, '');
    }
    if (nodePrefix && !(key in documentStyle)) {
        var temp = stylePrefix + key;
        if (temp in documentStyle) {
            key = temp;
        }
    }
    return key;
};
var isWorseIE = /msie\s+[2-8]/i.test(navigator.userAgent);
/**
 * 将样式绑定到dom元素
 * @param {Element} targetNode
 * @param {string|object} oStyle
 * @param {string|} oValue
 */
var cssTargetNode = function (targetNode, oStyle, oValue) {
    var styleobject = targetNode.style;
    if (typeof oStyle === "string") {
        if (typeof oValue === "string") {
            styleobject[transformNodeKey(oStyle)] = transfromSimpleValue(oValue);
            return;
        } else {
            try {
                oStyle = parseKV(oStyle, ';', ':');
            } catch (e) { }
        }
    }
    if (oStyle instanceof Object) {
        if (isWorseIE) {

            for (var k in oStyle) {
                var key = transformNodeKey(k);
                if (key in styleobject) {
                    try {
                        styleobject[key] = transfromSimpleValue(oStyle[k]);
                    } catch (e) {
                        console.warn(key, oStyle[k], "无效");
                    }
                }
            }
        } else {
            for (var k in oStyle) {
                var key = transformNodeKey(k);
                if (key in styleobject) styleobject[key] = transfromSimpleValue(oStyle[k]);
            }
        }
    }
};
/**
 * 将样式绑定到选择器
 * @param {string} targetSelector
 * @param {string|object} oStyle
 * @param {string|} oValue
 */
var cssTargetSelector = function (targetSelector, oStyle, oValue) {
    var stylesheet = stylesheet_Map[targetSelector];
    if (!stylesheet) {
        stylesheet = document.createElement("style");
        stylesheet.type = "text/css";
        stylesheet_Map[targetSelector] = stylesheet;
        document.getElementsByTagName("head")[0].appendChild(stylesheet);
    }
    var styleobject = {};
    if (typeof oStyle === "string") {
        if (typeof oValue === "string") {
            var key = transformCssKey(oStyle);
            styleobject[key] = oValue;
        } else {
            oStyle.replace(/^;+|;+$/g, "").split(/;+/).map(function (kv) {
                var [k, v] = kv.split(":");
                delete styleobject[k];
                if (k) styleobject[k] = v || '';
            });
        }
    } else if (oStyle instanceof Object) {
        for (var k in oStyle) {
            var key = transformCssKey(k);
            styleobject[key] = oStyle[k];
        }
    }
    var rowStyles = [];
    var styleSheet = stylesheet.styleSheet;
    var cssText = stylesheet.savedText || (styleSheet ? styleSheet.cssText : stylesheet.innerHTML).replace(/^[\s\S]*?\{([\s\S]*?)\}[\s\S]*?$/, "$1");
    cssText.split(";").forEach(function (kv) {
        var k = kv.replace(/^(.*?)\:.*$/, "$1");
        if (k && !(k in styleobject)) rowStyles.push(kv);
    });
    for (var k in styleobject) {
        if (styleobject[k]) {
            rowStyles.push(k + ":" + transfromSimpleValue(styleobject[k]));
        }
    }
    var innerCss = `${targetSelector}{${rowStyles.join(";")}}`;
    innerCss = color.transform(innerCss);
    cssTargetStyleSheet(stylesheet, innerCss);
};

function cssTargetStyleSheet(stylesheet, innerCss) {
    var styleSheet = stylesheet.styleSheet;
    if (styleSheet) {
        //IE
        styleSheet.cssText = innerCss;
    } else {
        stylesheet.innerHTML = innerCss;
    }
}

/**
 * 函数的入口
 * @param {string|Element} target
 * @param {object|string} oStyle
 * @param {|string} oValue
 */
var css = function (target, oStyle, oValue) {
    if (isNode(target)) {
        if (/^style$/i.test(target.tagName)) {
            cssTargetStyleSheet(target, oStyle, oValue);
        } else {
            cssTargetNode(target, oStyle, oValue);
        }
    }
    else if (isString(target)) cssTargetSelector(target, oStyle, oValue);
};<|endoftext|>


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

var program = require('commander');
var fs = require('fs');
var winston = require('winston');
var which = require('which').sync;
var path = require('path');
var thresher = require('thresher');

program
  .version('0.2.1')
  .option('-u, --url <url>',
          'URL to scrape')
  .option('-r, --urllist <path>',
          'path to file with list of URLs to scrape (one per line)')
  .option('-s, --scraper <path>',
          'path to scraper definition (in JSON format)')
  .option('-o, --output <path>',
          'where to output results ' +
          '(directory will be created if it doesn\'t exist',
          'output')
  .option('-r, --ratelimit <int>',
          'maximum number of scrapes per minute (default 3)', 3)
  .option('-l, --loglevel <level>',
          'amount of information to log ' +
          '(silent, verbose, info*, data, warn, error, or debug)',
          'info')
  .parse(process.argv);

// set up logging
var loglevels = ['silent', 'verbose', 'info', 'data',
                 'warn', 'error', 'debug'];
if (loglevels.indexOf(program.loglevel) == -1) {
  winston.error('Loglevel must be one of: ',
                'quiet, verbose, data, info, warn, error, debug');
  process.exit(1);
}

log = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)({ level: program.loglevel })
  ]
});
log.cli();

if (!(program.url || program.urllist)) {
  log.error('You must provide a URL or list of URLs to scrape');
  process.exit(1);
}

if (!program.scraper) {
  log.error('You must provide a scraper definition');
  process.exit(1);
}

log.info('quickscrape launched with...');
if (program.url) {
  log.info('- URL: ' + program.url);
} else {
  log.info('- URLs from file: ' + program.urls);
}
log.info('- Scraper:', program.scraper);
log.info('- Rate limit:', program.ratelimit, 'per minute');
log.info('- Log level:', program.loglevel);

// load list of URLs from a file
var loadUrls = function(path) {
  var list = fs.readFileSync(path, {
    encoding: 'utf8'
  });
  return list.split('\n').map(function(cv) {
    return cv.trim();
  });
}

urllist = program.url ? [program.url] : loadUrls(program.urllist);
log.info('urls to scrape:', urllist.length);

// load the scraper definition
var rawdef = fs.readFileSync(program.scraper, 'utf8');
var definition = JSON.parse(rawdef);

// check definition
thresher.scraperJSON.checkDefinition(definition);

// this is the callback we pass to the scraper, so the program
// can exit when all asynchronous file and download tasks have finished
var finish = function() {
  log.info('all tasks completed');
  process.exit(0);
}

// create output directory
if (!fs.existsSync(program.output)) {
    log.debug('creating output directory: ' + program.output);
    fs.mkdirSync(program.output);
}
process.chdir(program.output);
tld = process.cwd();

// set up crude rate-limiting
mintime = 60000 / program.ratelimit;
lasttime = new Date().getTime();

// asynchronously process a URL
var processUrl = function(url, definition,
                          loglevel, cb) {
  log.info('processing URL:', url);
  try {
    // url-specific output dir
    var dir = url.replace(/\/+/g, '_').replace(/:/g, '');
    dir = path.join(tld, dir);
    if (!fs.existsSync(dir)) {
        log.debug('creating output directory: ' + dir);
        fs.mkdirSync(dir);
    }
    process.chdir(dir);
    // run scraper
    thresher.scrape.scrape(url, definition.elements, function() {
      log.debug('changing back to top-level directory');
      process.chdir(tld);
      cb();
    }, loglevel);
  } catch(e) {
    log.error(e);
    log.error(e.trace);
  }
}

// perform a rate-limited loop over the urls using
// (algorithmically, not actually) recursive
// setTimeOut callbacks
var processNext = function(i, definition, finish,
                           loglevel) {
  if (i == urllist.length) {
    finish();
  }
  if (i == 0) {
    var timeleft = 0;
  } else {
    // rate-limit
    var now = new Date().getTime();
    var diff = now - lasttime;
    var timeleft = Math.max(mintime - diff, 0);
    log.info('waiting', Math.round(timeleft/1000),
             'seconds before next scrape');
  }
  var nextUrl = urllist[i];
  setTimeout(function() {
    processUrl(nextUrl, definition, loglevel, function() {
      lasttime = new Date().getTime();
      processNext(i + 1, definition, finish, loglevel);
    });
  }, timeleft + 1000);
}

processNext(0, definition, finish, program.loglevel)
<commit_msg>add scraper detection using new thresher ScraperBox API<commit_after>#!/usr/bin/env node

var program = require('commander');
var fs = require('fs');
var winston = require('winston');
var which = require('which').sync;
var path = require('path');
var thresher = require('thresher');
var ScraperBox = thresher.scraperbox;

program
  .version('0.2.1')
  .option('-u, --url <url>',
          'URL to scrape')
  .option('-r, --urllist <path>',
          'path to file with list of URLs to scrape (one per line)')
  .option('-s, --scraper <path>',
          'path to scraper definition (in JSON format)')
  .option('-d, --scraperdir <path>',
          'path to directory containing scraper definitions (in JSON format)')
  .option('-o, --output <path>',
          'where to output results ' +
          '(directory will be created if it doesn\'t exist',
          'output')
  .option('-r, --ratelimit <int>',
          'maximum number of scrapes per minute (default 3)', 3)
  .option('-l, --loglevel <level>',
          'amount of information to log ' +
          '(silent, verbose, info*, data, warn, error, or debug)',
          'info')
  .parse(process.argv);

// set up logging
var loglevels = ['silent', 'verbose', 'info', 'data',
                 'warn', 'error', 'debug'];
if (loglevels.indexOf(program.loglevel) == -1) {
  winston.error('Loglevel must be one of: ',
                'quiet, verbose, data, info, warn, error, debug');
  process.exit(1);
}

log = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)({ level: program.loglevel })
  ]
});
log.cli();

if (program.scraper && program.scraperdir) {
  log.error('Please use either --scraper or --scraperdir, not both');
  process.exit(1);
}

if (!(program.url || program.urllist)) {
  log.error('You must provide a URL or list of URLs to scrape');
  process.exit(1);
}

if (!(program.scraper || program.scraperdir)) {
  log.error('You must provide a scraper definition');
  process.exit(1);
}

log.info('quickscrape launched with...');
if (program.url) {
  log.info('- URL: ' + program.url);
} else {
  log.info('- URLs from file: ' + program.urls);
}
if (program.scraper) {
  log.info('- Scraper:', program.scraper);
}
if (program.scraperdir) {
  log.info('- Scraperdir:', program.scraperdir);
}
log.info('- Rate limit:', program.ratelimit, 'per minute');
log.info('- Log level:', program.loglevel);

// load list of URLs from a file
var loadUrls = function(path) {
  var list = fs.readFileSync(path, {
    encoding: 'utf8'
  });
  return list.split('\n').map(function(cv) {
    return cv.trim();
  });
}

urllist = program.url ? [program.url] : loadUrls(program.urllist);
log.info('urls to scrape:', urllist.length);

// load the scraper definition(s)
var scrapers = new ScraperBox(program.scraperdir);
if (program.scraper) {
  scrapers.addScraper(program.scraper);
}

// this is the callback we pass to the scraper, so the program
// can exit when all asynchronous file and download tasks have finished
var finish = function() {
  log.info('all tasks completed');
  process.exit(0);
}

// create output directory
if (!fs.existsSync(program.output)) {
    log.debug('creating output directory: ' + program.output);
    fs.mkdirSync(program.output);
}
process.chdir(program.output);
tld = process.cwd();

// set up crude rate-limiting
mintime = 60000 / program.ratelimit;
lasttime = new Date().getTime();

// asynchronously process a URL
var processUrl = function(url, scrapers,
                          loglevel, cb) {
  log.info('processing URL:', url);
  var definition = scrapers.getScraper(url);
  try {
    // url-specific output dir
    var dir = url.replace(/\/+/g, '_').replace(/:/g, '');
    dir = path.join(tld, dir);
    if (!fs.existsSync(dir)) {
        log.debug('creating output directory: ' + dir);
        fs.mkdirSync(dir);
    }
    process.chdir(dir);
    // run scraper
    thresher.scrape.scrape(url, definition.elements, function() {
      log.debug('changing back to top-level directory');
      process.chdir(tld);
      cb();
    }, loglevel);
  } catch(e) {
    log.error(e);
    log.error(e.trace);
  }
}

// perform a rate-limited loop over the urls using
// (algorithmically, not actually) recursive
// setTimeOut callbacks
var processNext = function(i, scrapers, finish,
                           loglevel) {
  if (i == urllist.length) {
    finish();
  }
  if (i == 0) {
    var timeleft = 0;
  } else {
    // rate-limit
    var now = new Date().getTime();
    var diff = now - lasttime;
    var timeleft = Math.max(mintime - diff, 0);
    log.info('waiting', Math.round(timeleft/1000),
             'seconds before next scrape');
  }
  var nextUrl = urllist[i];
  setTimeout(function() {
    processUrl(nextUrl, scrapers, loglevel, function() {
      lasttime = new Date().getTime();
      processNext(i + 1, scrapers, finish, loglevel);
    });
  }, timeleft + 1000);
}

processNext(0, scrapers, finish, program.loglevel)
<|endoftext|>


<commit_before>var config = require('config');
var mapModule = require('map');
var plugins = require('./leaflet_plugins');
var polyUtil = require('./polyline_encoded.js');
var routeboxer = require('./leaflet_routeboxer.js');
var leaflet_label = require('./leaflet_label/leaflet.label-src.js');
var collision = require('./leaflet_layergroup_collision.js');
var session = require('session');

var center = config.geocode().center.split(',').map(parseFloat)
if (config.map_provider && config.map_provider() !== 'AmigoCloud') {
  L.mapbox.accessToken = config.mapbox_access_token();
}

module.exports = function(el) {
  var map, realtime, southWest, northEast, blurLayer;

  if (config.map_provider && config.map_provider() === 'AmigoCloud') {
    southWest = L.latLng(35.946877085397,-123.480610897013);
    northEast = L.latLng(40.763279543715,-118.789317362500);
    map = (new L.amigo.map(el, {
      amigoLogo: 'right',
      loadAmigoLayers: false,
      inertia: false,
      zoomAnimation: $('.hide-map').css('display') !== 'none',
      maxBounds: L.latLngBounds(southWest, northEast),
      minZoom: 8
    })).setView([center[1], center[0]], config.geocode().zoom);

    L.amigo.auth.setToken(config.support_data_token());

    blurLayer = L.tileLayer(
    'https://www.amigocloud.com/api/v1/users/'+
	'23/projects/3019/datasets/23835/tiles/{z}/{x}/{y}.png?' +
	'token=' + config.support_data_token(),
      {
        name: 'Uncovered Area'
      }
    );

    map.addAuthLayer({
      id: config.mapbox_map_id(),
      accessToken: config.mapbox_access_token(),
      name: 'Gray',
      provider: 'mapbox'
    });
    map.addBaseLayer(L.amigo.AmigoGray);
    map.layersControl.addBaseLayer(
      L.bingLayer(
        config.bing_key(),
	{
	  type: 'Road',
	  attribution: 'Bing Maps'
	}
      ),
      'Bing Road'
    );
    map.layersControl.addOverlay(blurLayer);
    blurLayer.addTo(map);

    module.exports.activeMap = map;

    map.realtimeControl = L.control.toggleRealTime().addTo(map);

    realtime = mapModule.realtime();

  } else {

    map = L.mapbox.map(el, config.mapbox_map_id(), {
      attributionControl: false,
      inertia: false,
      zoomAnimation: false
    }).setView([center[1], center[0]], config.geocode().zoom);
  }

  return map;
};

module.exports.getMap = function () {
  return this.activeMap;
};

module.exports.cleanRoute = function() {
    module.exports.activeRoute.removeLayer();
    module.exports.activeRoute = null;
};

module.exports.polyline_creadas = [];
module.exports.marker_creadas = [];
module.exports.makerpoint_creadas = [];
module.exports.collision_group = {};
module.exports.marker_collision_group = [];

module.exports.drawMakerCollision = function () {
    var collision_group = L.layerGroup.collision({margin:5});
    collision_group.addLayer(this.marker_collision_group);
    console.log("final -> collision_group", collision_group);
};

module.exports.getpolyline_creadas = function () {
  return this.polyline_creadas;
};

module.exports.getMarker_creadas = function () {
  return this.marker_creadas;
};

module.exports.cleanPolyline = function() {
    var polyline_creadas = this.getpolyline_creadas();
    var map = this.activeMap;
    for (i in polyline_creadas) {
        try {
                map.removeLayer(polyline_creadas[i]);

            } catch (e) {
                console.log("problema al eliminar " + e);
            }

  }
  this.polyline_creadas = [];

};

module.exports.cleanMarker = function() {
    var map = this.activeMap;
    for (i in this.marker_creadas) {
        try {
                map.removeLayer(this.marker_creadas[i]);

            } catch (e) {
                console.log("problema al eliminar " + e);
            }
    }

  this.marker_creadas = [];

};

module.exports.cleanMarkerpoint = function() {
    var map = this.activeMap;
    for (i in this.makerpoint_creadas) {
        try {
                map.removeLayer(this.makerpoint_creadas[i]);

            } catch (e) {
                console.log("problema al eliminar " + e);
            }
    }

  this.makerpoint_creadas = [];

};

module.exports.marker_map = function(from, to){
     var IconStart = L.icon({
        iconUrl: 'assets/images/graphics/start.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });
    var IconEnd = L.icon({
        iconUrl: 'assets/images/graphics/end.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });

    var markerform = new L.marker([from[0],from[1]], {icon: IconStart, draggable: true})
        .addTo(this.activeMap);
    var markerto = new L.marker([to[0],to[1]], {icon: IconEnd, draggable: true})
        .addTo(this.activeMap);
    var _this = this;

    markerform.on('dragend', function(e){
       var marker = e.target;
       var result = marker.getLatLng();
       _this.cleanPolyline();
       _this.cleanMarkerpoint();
       var plan = session.plan();

            plan.setAddress('from', result.lng + ',' + result.lat, function(err, rees) {
                plan.updateRoutes();
          });
    });

    markerto.on('dragend', function(e){
       var marker = e.target;
       var result = marker.getLatLng();
       _this.cleanPolyline();
       _this.cleanMarkerpoint();
       var plan = session.plan();
            plan.setAddress('to', result.lng + ',' + result.lat, function(err, rees) {
                plan.updateRoutes();
          });
    });

    this.marker_creadas.push(markerform);
    this.marker_creadas.push(markerto);
};

module.exports.marker_map_point = function(to, map){

    var name = to[2];

    var IconEnd = L.icon({
        iconUrl: 'assets/images/graphics/icono.png',
        iconSize: [20, 20],
        iconAnchor: [0, 0],
        popupAnchor:  [-3, -76]
    });

    var markers = [
      L.marker([to[0], to[1]], {icon: IconEnd}).bindLabel(name)
    ];

    var marker = L.marker([to[0], to[1]], {icon: IconEnd}).bindLabel(name);

    var layer = L.layerGroup(markers).addTo(map).eachLayer(function(layer){layer.showLabel()});
    //console.log("antes del marker ->", this.collision_group);
    //this.collision_group.addLayer(marker);
    //console.log("inserto marker->", marker);
    //console.log("despues del marker ->", this.collision_group);
    //console.log("group ->", L.layerGroup(markers));
    this.makerpoint_creadas.push(layer);

    //var collision_group = L.layerGroup.collision({margin:5});
    //collision_group.addLayer(marker);
    //collision_group.onAdd(this.activeMap);
    //this.collision_group = collision_group;
    //console.log("collision_group -> ",collision_group);
    //this.marker_collision_group.push(marker);

    this.marker_collision_group.push(marker);
};

module.exports.drawRouteAmigo = function(legs,mode) {

    var route = legs.legGeometry.points;
    var circle_from = [legs.from.lat, legs.from.lon, legs.from.name];
    var circle_to = [legs.to.lat, legs.to.lon, legs.to.name];
    var color = '#000';
    var weight = 5;
    var dasharray= '';

        if (mode=="CAR") {
            color = '#9E9E9E';
            dasharray= '6';
            weight = 3;

        }else if(mode=="BICYCLE") {
            color = '#FF0000';
            if(!(legs.routeColor === undefined)) {
                color = "#"+legs.routeColor;
             }
            dasharray= '6';
            weight = 3;

        }else if(mode=="SUBWAY" || mode=="RAIL") {
             if(!(legs.routeColor === undefined)) {
                if (legs.routeColor != "" || legs.routeColor.length == 6) {
                    color = "#"+legs.routeColor;
                }

             }
             weight = 8;
             console.log("circle from ->", circle_from);
             console.log("circle to ->", circle_to);
             this.marker_map_point(circle_from, this.activeMap);
             this.marker_map_point(circle_to, this.activeMap);

        }
        else if(mode == "WALK") {
            color = '#0BC8F4';
            dasharray= '6';
             weight = 3;
        }

        else if(mode=="BUS") {
            //color = '#FEF0B5';
            if(!(legs.routeColor === undefined)) {
                if (legs.routeColor != "" || legs.routeColor.length == 6) {
                    color = "#"+legs.routeColor;
                }
             }
             weight = 5;
             console.log("circle from ->", circle_from);
             console.log("circle to ->", circle_to);
             this.marker_map_point(circle_from, this.activeMap);
             this.marker_map_point(circle_to, this.activeMap);
        }

       var color_options = {
            color: color,
            opacity: 1,
            weight: weight,
            dashArray: dasharray
        };

      var argpolyline = L.PolylineUtil.decode(route, 5);
      argpolyline.unshift(circle_from);
      console.log("color ruta ->" , color);
      route = new L.Polyline(argpolyline, color_options);
      this.polyline_creadas.push(route);
      var boxes = L.RouteBoxer.box(route, 5);
      var boxpolys = new Array(boxes.length);
      route.addTo(this.activeMap);
};

<commit_msg>datos de prueba<commit_after>var config = require('config');
var mapModule = require('map');
var plugins = require('./leaflet_plugins');
var polyUtil = require('./polyline_encoded.js');
var routeboxer = require('./leaflet_routeboxer.js');
var leaflet_label = require('./leaflet_label/leaflet.label-src.js');
var collision = require('./leaflet_layergroup_collision.js');
var session = require('session');

var center = config.geocode().center.split(',').map(parseFloat)
if (config.map_provider && config.map_provider() !== 'AmigoCloud') {
  L.mapbox.accessToken = config.mapbox_access_token();
}

module.exports = function(el) {
  var map, realtime, southWest, northEast, blurLayer;

  if (config.map_provider && config.map_provider() === 'AmigoCloud') {
    southWest = L.latLng(35.946877085397,-123.480610897013);
    northEast = L.latLng(40.763279543715,-118.789317362500);
    map = (new L.amigo.map(el, {
      amigoLogo: 'right',
      loadAmigoLayers: false,
      inertia: false,
      zoomAnimation: $('.hide-map').css('display') !== 'none',
      maxBounds: L.latLngBounds(southWest, northEast),
      minZoom: 8
    })).setView([center[1], center[0]], config.geocode().zoom);

    L.amigo.auth.setToken(config.support_data_token());

    blurLayer = L.tileLayer(
    'https://www.amigocloud.com/api/v1/users/'+
	'23/projects/3019/datasets/23835/tiles/{z}/{x}/{y}.png?' +
	'token=' + config.support_data_token(),
      {
        name: 'Uncovered Area'
      }
    );

    map.addAuthLayer({
      id: config.mapbox_map_id(),
      accessToken: config.mapbox_access_token(),
      name: 'Gray',
      provider: 'mapbox'
    });
    map.addBaseLayer(L.amigo.AmigoGray);
    map.layersControl.addBaseLayer(
      L.bingLayer(
        config.bing_key(),
	{
	  type: 'Road',
	  attribution: 'Bing Maps'
	}
      ),
      'Bing Road'
    );
    map.layersControl.addOverlay(blurLayer);
    blurLayer.addTo(map);

    module.exports.activeMap = map;

    map.realtimeControl = L.control.toggleRealTime().addTo(map);

    realtime = mapModule.realtime();

  } else {

    map = L.mapbox.map(el, config.mapbox_map_id(), {
      attributionControl: false,
      inertia: false,
      zoomAnimation: false
    }).setView([center[1], center[0]], config.geocode().zoom);
  }

  return map;
};

module.exports.getMap = function () {
  return this.activeMap;
};

module.exports.cleanRoute = function() {
    module.exports.activeRoute.removeLayer();
    module.exports.activeRoute = null;
};

module.exports.polyline_creadas = [];
module.exports.marker_creadas = [];
module.exports.makerpoint_creadas = [];
module.exports.collision_group = {};
module.exports.marker_collision_group = [];

module.exports.drawMakerCollision = function () {
    var collision_group = L.layerGroup.collision({margin:5});
    collision_group.addLayer(this.marker_collision_group);
    console.log("final -> collision_group", collision_group);
    collision_group.addTo(this.activeMap);
};

module.exports.getpolyline_creadas = function () {
  return this.polyline_creadas;
};

module.exports.getMarker_creadas = function () {
  return this.marker_creadas;
};

module.exports.cleanPolyline = function() {
    var polyline_creadas = this.getpolyline_creadas();
    var map = this.activeMap;
    for (i in polyline_creadas) {
        try {
                map.removeLayer(polyline_creadas[i]);

            } catch (e) {
                console.log("problema al eliminar " + e);
            }

  }
  this.polyline_creadas = [];

};

module.exports.cleanMarker = function() {
    var map = this.activeMap;
    for (i in this.marker_creadas) {
        try {
                map.removeLayer(this.marker_creadas[i]);

            } catch (e) {
                console.log("problema al eliminar " + e);
            }
    }

  this.marker_creadas = [];

};

module.exports.cleanMarkerpoint = function() {
    var map = this.activeMap;
    for (i in this.makerpoint_creadas) {
        try {
                map.removeLayer(this.makerpoint_creadas[i]);

            } catch (e) {
                console.log("problema al eliminar " + e);
            }
    }

  this.makerpoint_creadas = [];

};

module.exports.marker_map = function(from, to){
     var IconStart = L.icon({
        iconUrl: 'assets/images/graphics/start.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });
    var IconEnd = L.icon({
        iconUrl: 'assets/images/graphics/end.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });

    var markerform = new L.marker([from[0],from[1]], {icon: IconStart, draggable: true})
        .addTo(this.activeMap);
    var markerto = new L.marker([to[0],to[1]], {icon: IconEnd, draggable: true})
        .addTo(this.activeMap);
    var _this = this;

    markerform.on('dragend', function(e){
       var marker = e.target;
       var result = marker.getLatLng();
       _this.cleanPolyline();
       _this.cleanMarkerpoint();
       var plan = session.plan();

            plan.setAddress('from', result.lng + ',' + result.lat, function(err, rees) {
                plan.updateRoutes();
          });
    });

    markerto.on('dragend', function(e){
       var marker = e.target;
       var result = marker.getLatLng();
       _this.cleanPolyline();
       _this.cleanMarkerpoint();
       var plan = session.plan();
            plan.setAddress('to', result.lng + ',' + result.lat, function(err, rees) {
                plan.updateRoutes();
          });
    });

    this.marker_creadas.push(markerform);
    this.marker_creadas.push(markerto);
};

module.exports.marker_map_point = function(to, map){

    var name = to[2];

    var IconEnd = L.icon({
        iconUrl: 'assets/images/graphics/icono.png',
        iconSize: [20, 20],
        iconAnchor: [0, 0],
        popupAnchor:  [-3, -76]
    });

    var markers = [
      L.marker([to[0], to[1]], {icon: IconEnd}).bindLabel(name)
    ];

    var marker = L.marker([to[0], to[1]], {icon: IconEnd}).bindLabel(name);

    //var layer = L.layerGroup(markers).addTo(map).eachLayer(function(layer){layer.showLabel()});

    //console.log("antes del marker ->", this.collision_group);
    //this.collision_group.addLayer(marker);
    //console.log("inserto marker->", marker);
    //console.log("despues del marker ->", this.collision_group);
    //console.log("group ->", L.layerGroup(markers));

    //this.makerpoint_creadas.push(layer);

    //var collision_group = L.layerGroup.collision({margin:5});
    //collision_group.addLayer(marker);
    //collision_group.onAdd(this.activeMap);
    //this.collision_group = collision_group;
    //console.log("collision_group -> ",collision_group);
    //this.marker_collision_group.push(marker);

    this.marker_collision_group.push(marker);
};

module.exports.drawRouteAmigo = function(legs,mode) {

    var route = legs.legGeometry.points;
    var circle_from = [legs.from.lat, legs.from.lon, legs.from.name];
    var circle_to = [legs.to.lat, legs.to.lon, legs.to.name];
    var color = '#000';
    var weight = 5;
    var dasharray= '';

        if (mode=="CAR") {
            color = '#9E9E9E';
            dasharray= '6';
            weight = 3;

        }else if(mode=="BICYCLE") {
            color = '#FF0000';
            if(!(legs.routeColor === undefined)) {
                color = "#"+legs.routeColor;
             }
            dasharray= '6';
            weight = 3;

        }else if(mode=="SUBWAY" || mode=="RAIL") {
             if(!(legs.routeColor === undefined)) {
                if (legs.routeColor != "" || legs.routeColor.length == 6) {
                    color = "#"+legs.routeColor;
                }

             }
             weight = 8;
             console.log("circle from ->", circle_from);
             console.log("circle to ->", circle_to);
             this.marker_map_point(circle_from, this.activeMap);
             this.marker_map_point(circle_to, this.activeMap);

        }
        else if(mode == "WALK") {
            color = '#0BC8F4';
            dasharray= '6';
             weight = 3;
        }

        else if(mode=="BUS") {
            //color = '#FEF0B5';
            if(!(legs.routeColor === undefined)) {
                if (legs.routeColor != "" || legs.routeColor.length == 6) {
                    color = "#"+legs.routeColor;
                }
             }
             weight = 5;
             console.log("circle from ->", circle_from);
             console.log("circle to ->", circle_to);
             this.marker_map_point(circle_from, this.activeMap);
             this.marker_map_point(circle_to, this.activeMap);
        }

       var color_options = {
            color: color,
            opacity: 1,
            weight: weight,
            dashArray: dasharray
        };

      var argpolyline = L.PolylineUtil.decode(route, 5);
      argpolyline.unshift(circle_from);
      console.log("color ruta ->" , color);
      route = new L.Polyline(argpolyline, color_options);
      this.polyline_creadas.push(route);
      var boxes = L.RouteBoxer.box(route, 5);
      var boxpolys = new Array(boxes.length);
      route.addTo(this.activeMap);
};

<|endoftext|>


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

let program = require('commander')
let inquirer = require('inquirer')
let prompt = inquirer.createPromptModule()
let colors = require('../lib/colors-custom')
let configurationManager = require('../lib/ConfigurationManager.js')
let SSHConnection = require('../lib/SSHConnection')
let ConnectionConfiguration = require('../lib/ConnectionConfiguration')

async function getConnectionConfigurationProperty (message, name, defaultValue = null) {
    let inputNameInquirer = {
        type: 'input',
        message: message,
        name: name,
        default: defaultValue
    }

    let property = await prompt(inputNameInquirer)

    return property[name]
}

async function selectConnectionConfiguration () {
    let allConnectionConfigurationChoices = configurationManager.getConnectionConfigurationList()

    if (allConnectionConfigurationChoices.length === 0) {
        console.log(colors.error(new Error('no connection configuration found into "' + configurationManager.getConnectionConfigurationFilePath() + '". Please use "add" command.')))
        exit(1)
    }

    let selectConnectionConfigurationInquirer = {
        type: 'list',
        message: 'Select an connection',
        name: 'uuid',
        choices: allConnectionConfigurationChoices
    }

    let result = await prompt(selectConnectionConfigurationInquirer)
    let selectedConnectionConfiguration = null

    try {
        selectedConnectionConfiguration = configurationManager.getConnectionConfiguration(result.uuid)
    } catch (e) {
        exit(1)
    }

    return selectedConnectionConfiguration
}

function exit (code) {
    process.exit(code)
}

program
    .version('1.0.0')
    .description('A SSH manager to store a list of SSH connection configuration')

program
    .command('show')
    .description('show all projects SSH configurations')
    .action(() => {
        configurationManager.showConnectionConfigurations()
    })

program
    .command('delete')
    .description('delete an SSH connection configuration')
    .action(async () => {
        let projectConfiguration = await selectConnectionConfiguration()
        configurationManager.deleteConnectionConfiguration(projectConfiguration.uuid)
    })

program
    .command('add')
    .description('add a new SSH connection configuration')
    .action(async () => {
        let name = await getConnectionConfigurationProperty('Connection name', 'name')
        let description = await getConnectionConfigurationProperty('Description', 'description')
        let user = await getConnectionConfigurationProperty('User', 'user')
        let server = await getConnectionConfigurationProperty('Server', 'server')
        let port = await getConnectionConfigurationProperty('Port', 'port', 22)

        configurationManager.addConnectionConfiguration(name, description, user, server, port)
    })

program
    .command('connect')
    .description('start an SSH connection')
    .action(async () => {
        let projectConfiguration = await selectConnectionConfiguration()
        let cc = new ConnectionConfiguration(projectConfiguration)
        SSHConnection.init(cc)
        SSHConnection.start(exit)
    })

program.parse(process.argv)
<commit_msg>"connect" command is now default command<commit_after>#!/usr/bin/env node

let program = require('commander')
let inquirer = require('inquirer')
let prompt = inquirer.createPromptModule()
let colors = require('../lib/colors-custom')
let configurationManager = require('../lib/ConfigurationManager.js')
let SSHConnection = require('../lib/SSHConnection')
let ConnectionConfiguration = require('../lib/ConnectionConfiguration')

async function getConnectionConfigurationProperty (message, name, defaultValue = null) {
    let inputNameInquirer = {
        type: 'input',
        message: message,
        name: name,
        default: defaultValue
    }

    let property = await prompt(inputNameInquirer)

    return property[name]
}

async function selectConnectionConfiguration () {
    let allConnectionConfigurationChoices = configurationManager.getConnectionConfigurationList()

    if (allConnectionConfigurationChoices.length === 0) {
        console.log(colors.error(new Error('no connection configuration found into "' + configurationManager.getConnectionConfigurationFilePath() + '". Please use "add" command.')))
        exit(1)
    }

    let selectConnectionConfigurationInquirer = {
        type: 'list',
        message: 'Select an connection',
        name: 'uuid',
        choices: allConnectionConfigurationChoices
    }

    let result = await prompt(selectConnectionConfigurationInquirer)
    let selectedConnectionConfiguration = null

    try {
        selectedConnectionConfiguration = configurationManager.getConnectionConfiguration(result.uuid)
    } catch (e) {
        exit(1)
    }

    return selectedConnectionConfiguration
}

function exit (code) {
    process.exit(code)
}

async function connectAction () {
    let projectConfiguration = await selectConnectionConfiguration()
    let cc = new ConnectionConfiguration(projectConfiguration)
    SSHConnection.init(cc)
    SSHConnection.start(exit)
}

async function addAction () {
    let name = await getConnectionConfigurationProperty('Connection name', 'name')
    let description = await getConnectionConfigurationProperty('Description', 'description')
    let user = await getConnectionConfigurationProperty('User', 'user')
    let server = await getConnectionConfigurationProperty('Server', 'server')
    let port = await getConnectionConfigurationProperty('Port', 'port', 22)

    configurationManager.addConnectionConfiguration(name, description, user, server, port)
}

async function deleteAction () {
    let projectConfiguration = await selectConnectionConfiguration()
    configurationManager.deleteConnectionConfiguration(projectConfiguration.uuid)
}

program
    .version('1.0.0')
    .description('A SSH manager to store a list of SSH connection configuration')

program
    .command('show')
    .description('show all projects SSH configurations')
    .action(() => {
        configurationManager.showConnectionConfigurations()
    })

program
    .command('delete')
    .description('delete an SSH connection configuration')
    .action(deleteAction)

program
    .command('add')
    .description('add a new SSH connection configuration')
    .action(addAction)

program
    .command('connect')
    .description('start an SSH connection')
    .action(connectAction)

program.parse(process.argv)

// launch connect command if no argument given
if (program.args.length === 0) {
    connectAction()
}
<|endoftext|>


<commit_before>/**
    Framework for building object relational database apps
    Copyright (C) 2019  John Rogelstad

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
**/
/*jslint this, browser*/
import f from "../core.js";
import State from "../state.js";
import datasource from "../datasource.js";
const store = {};

store.feathers = f.prop({});

function settings() {
    let state;
    let doFetch;
    let that = {};

    that.feathers = f.prop({});

    // Send event to fetch feather data from the server.
    that.fetch = function (merge) {
        return new Promise(function (resolve) {
            state.send("fetch", {
                resolve: resolve,
                merge: merge
            });
        });
    };

    doFetch = function (context) {
        let payload = {
            method: "GET",
            path: "/settings/catalog"
        };

        function callback(result) {
            let merge;
            let data = result || {};

            data = data.data;
            if (context.merge) {
                merge = that.feathers();
                Object.keys(data).forEach(function (key) {
                    merge[key] = data[key];
                });
                data = merge;
            }
            that.feathers(data);
            state.send("fetched");
            context.resolve(data);
        }

        state.goto("/Busy");
        datasource.request(payload).then(callback);
    };

    state = State.define(function () {
        this.state("Ready", function () {
            this.event("fetch", function (context) {
                this.goto("/Busy", {
                    context: context
                });
            });
            this.state("New");
            this.state("Fetched", function () {
                this.state("Clean");
            });
        });

        this.state("Busy", function () {
            this.state("Fetching", function () {
                this.enter(doFetch);
            });
            this.event("fetched", function () {
                this.goto("/Ready/Fetched");
            });
            this.event("error", function () {
                this.goto("/Error");
            });
        });

        this.state("Error", function () {
            // Prevent exiting from this state
            this.canExit = function () {
                return false;
            };
        });
    });

    // Initialize
    state.goto();

    return that;
}

// Invoke catalog settings as an object
const catalog = (function () {
    let that = settings();

    /**
      Return a model specification (feather) including inherited properties.

      @param {String} Feather
      @param {Boolean} Include inherited or not. Defult = true.
      @return {String}
    */
    that.getFeather = function (feather, includeInherited) {
        let resultProps;
        let modelProps;
        let appendParent;
        let feathers = that.feathers();
        let result = {
            name: feather,
            inherits: "Object"
        };

        appendParent = function (child, parent) {
            let model = feathers[parent];
            let parentProps = model.properties;
            let childProps = child.properties;
            let modelOverloads = model.overloads || {};
            let keys = Object.keys(parentProps);

            if (parent !== "Object") {
                appendParent(child, model.inherits || "Object");
            }

            // Inherit properties from parent
            keys.forEach(function (key) {
                if (childProps[key] === undefined) {
                    childProps[key] = parentProps[key];
                    childProps[key].inheritedFrom = parent;
                }
            });

            // Inherit overloads from parent
            child.overloads = child.overloads || {};
            keys = Object.keys(modelOverloads);
            keys.forEach(function (key) {
                child.overloads[key] = modelOverloads[key];
            });

            return child;
        };

        if (!feathers[feather]) {
            return false;
        }

        // Add other attributes after nam
        Object.keys(feathers[feather]).forEach(function (key) {
            result[key] = feathers[feather][key];
        });

        // Want inherited properites before class properties
        if (includeInherited !== false && feather !== "Object") {
            result.properties = {};
            result = appendParent(result, result.inherits);
        } else {
            delete result.inherits;
        }

        // Now add local properties back in
        modelProps = feathers[feather].properties;
        resultProps = result.properties;
        Object.keys(modelProps).forEach(function (key) {
            resultProps[key] = modelProps[key];
        });

        return result;
    };

    /**
        Store global data.

        @param {String} Data type
        @param {String} Name of instance
        @param {Any} Value to store
        @return {Object} Instances of the data type
    */
    that.register = function (...args) {
        let property = args[0];
        let name = args[1];
        let value = args[2];

        if (!store[property]) {
            store[property] = f.prop({});
        }
        if (args.length > 1) {
            store[property]()[name] = value;
        }
        return store[property]();
    };

    /**
        Helper function for model creation. Does the following:
            * Adds a function "static" to the model factory which returns an
            object for holding static functions.
            * Adds a list function to the model factory if `createList` is true.
            * Registers the model in the catalog
            * Freezes the model

        @param {String} Feather name
        @param {Function} Model factory
        @param {Boolean} Flag whether to append list function to model
        @return {Function} model
    */
    that.registerModel = function (name, model, createList) {
        model.static = f.prop({});

        if (createList) {
            model.list = that.store().factories().list(name);
        }

        that.register("models", name, Object.freeze(model));

        return model;
    };

    that.unregister = function (property, name) {
        delete store[property]()[name];
    };

    that.feathers = store.feathers;

    /**
      Current sessionid.

      @param {String} Session Id
      @return {String}
    */
    that.sessionId = f.prop();

    // Expose global store data
    that.store = function () {
        return store;
    };

    that.register("models");

    return that;
}());

export default Object.freeze(catalog);<commit_msg>Swat<commit_after>/**
    Framework for building object relational database apps
    Copyright (C) 2019  John Rogelstad

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
**/
/*jslint this, browser*/
import f from "../core.js";
import State from "../state.js";
import datasource from "../datasource.js";
const store = {};

store.feathers = f.prop({});

function settings() {
    let state;
    let doFetch;
    let that = {};

    that.feathers = f.prop({});

    // Send event to fetch feather data from the server.
    that.fetch = function (merge) {
        return new Promise(function (resolve) {
            state.send("fetch", {
                resolve: resolve,
                merge: merge
            });
        });
    };

    doFetch = function (context) {
        let payload = {
            method: "GET",
            path: "/settings/catalog"
        };

        function callback(result) {
            let merge;
            let data = result || {};

            data = data.data;
            if (context.merge) {
                merge = that.feathers();
                Object.keys(data).forEach(function (key) {
                    merge[key] = data[key];
                });
                data = merge;
            }
            that.feathers(data);
            state.send("fetched");
            context.resolve(data);
        }

        state.goto("/Busy");
        datasource.request(payload).then(callback);
    };

    state = State.define(function () {
        this.state("Ready", function () {
            this.event("fetch", function (context) {
                this.goto("/Busy", {
                    context: context
                });
            });
            this.state("New");
            this.state("Fetched", function () {
                this.state("Clean");
            });
        });

        this.state("Busy", function () {
            this.state("Fetching", function () {
                this.enter(doFetch);
            });
            this.event("fetched", function () {
                this.goto("/Ready/Fetched");
            });
            this.event("error", function () {
                this.goto("/Error");
            });
        });

        this.state("Error", function () {
            // Prevent exiting from this state
            this.canExit = function () {
                return false;
            };
        });
    });

    // Initialize
    state.goto();

    return that;
}

// Invoke catalog settings as an object
const catalog = (function () {
    let that = settings();

    /**
      Return a model specification (feather) including inherited properties.

      @param {String} Feather
      @param {Boolean} Include inherited or not. Defult = true.
      @return {String}
    */
    that.getFeather = function (feather, includeInherited) {
        let resultProps;
        let modelProps;
        let appendParent;
        let feathers = that.feathers();
        let result = {
            name: feather,
            inherits: "Object"
        };

        appendParent = function (child, parent) {
            let model = feathers[parent];
            let parentProps = model.properties;
            let childProps = child.properties;
            let modelOverloads = model.overloads || {};
            let keys = Object.keys(parentProps);

            if (parent !== "Object") {
                appendParent(child, model.inherits || "Object");
            }

            // Inherit properties from parent
            keys.forEach(function (key) {
                if (childProps[key] === undefined) {
                    childProps[key] = parentProps[key];
                    childProps[key].inheritedFrom = parent;
                }
            });

            // Inherit overloads from parent
            child.overloads = child.overloads || {};
            keys = Object.keys(modelOverloads);
            keys.forEach(function (key) {
                child.overloads[key] = modelOverloads[key];
            });

            return child;
        };

        if (!feathers[feather]) {
            return false;
        }

        // Add other attributes after nam
        Object.keys(feathers[feather]).forEach(function (key) {
            result[key] = feathers[feather][key];
        });

        // Want inherited properites before class properties
        if (includeInherited !== false && feather !== "Object") {
            result.properties = {};
            result = appendParent(result, result.inherits);
        } else {
            delete result.inherits;
        }

        // Now add local properties back in
        modelProps = feathers[feather].properties;
        resultProps = result.properties;
        Object.keys(modelProps).forEach(function (key) {
            resultProps[key] = modelProps[key];
        });

        return result;
    };

    /**
        Store global data.

        @param {String} Data type
        @param {String} Name of instance
        @param {Any} Value to store
        @return {Object} Instances of the data type
    */
    that.register = function (...args) {
        let property = args[0];
        let name = args[1];
        let value = args[2];

        if (!store[property]) {
            store[property] = f.prop({});
        }
        if (args.length > 1) {
            store[property]()[name] = value;
        }
        return store[property]();
    };

    /**
        Helper function for model creation. Does the following:
            * Adds a function "static" to the model factory which returns an
            object for holding static functions.
            * Adds a list function to the model factory if `createList` is true.
            * Registers the model in the catalog
            * Freezes the model

        @param {String} Feather name
        @param {Function} Model factory
        @param {Boolean} Flag whether to append list function to model
        @return {Function} model
    */
    that.registerModel = function (name, model, createList) {
        model.static = f.prop({});

        if (createList) {
            model.list = that.store().factories().list(name);
        }

        that.register("models", name.toCamelCase(), Object.freeze(model));

        return model;
    };

    that.unregister = function (property, name) {
        delete store[property]()[name];
    };

    that.feathers = store.feathers;

    /**
      Current sessionid.

      @param {String} Session Id
      @return {String}
    */
    that.sessionId = f.prop();

    // Expose global store data
    that.store = function () {
        return store;
    };

    that.register("models");

    return that;
}());

export default Object.freeze(catalog);<|endoftext|>


<commit_before>var on = require('sendevent')
  , parse = require('./url')
  , find = require('./find')
  , replace = require('./replace')
  , connectionLost = require('./connectionLost')

var token
var latestHeartbeatTime

on('/instant/events', function(ev) {
  if (ev.token) {
    if (!token) token = ev.token
    if (token != ev.token) return location.reload()
    setInterval(function() {
      if (latestHeartbeatTime) {
        var diff = Date.now() - latestHeartbeatTime
        if (diff > 1000 * 12) connectionLost()
      }
    }, 1000 * 10)
  }

  if (typeof ev.heartbeat === 'number') {
    latestHeartbeatTime = Date.now()
  }

  // reload page if it contains an element with the given class name
  if (ev.className) {
    if (find.byClass(ev.className)) location.reload()
    return
  }

  // reload page if it contains an element that matches the given selector
  if (ev.selector) {
    if (find.bySelector(ev.selector)) location.reload()
    return
  }

  // resolve the URL
  var url = parse(ev.url)

  // Remove query and hash strings
  var normalizedLocationHref = location.href.split('#')[0].split('?')[0]

  // reload the page
  if (url.href == normalizedLocationHref) {
    location.reload()
    return
  }

  // look for a stylesheet
  var el = find.byURL('link', 'href', url)
  if (el) return replace(el, url.pathname + '?v=' + new Date().getTime())

  // look for a script
  el = find.byURL('script', 'src', url)
  if (el) location.reload()
})
<commit_msg>Reload '/' route when 'index.html' changes (Fixes #46)<commit_after>var on = require('sendevent')
  , parse = require('./url')
  , find = require('./find')
  , replace = require('./replace')
  , connectionLost = require('./connectionLost')

var token
var latestHeartbeatTime

on('/instant/events', function(ev) {
  if (ev.token) {
    if (!token) token = ev.token
    if (token != ev.token) return location.reload()
    setInterval(function() {
      if (latestHeartbeatTime) {
        var diff = Date.now() - latestHeartbeatTime
        if (diff > 1000 * 12) connectionLost()
      }
    }, 1000 * 10)
  }

  if (typeof ev.heartbeat === 'number') {
    latestHeartbeatTime = Date.now()
  }

  // reload page if it contains an element with the given class name
  if (ev.className) {
    if (find.byClass(ev.className)) location.reload()
    return
  }

  // reload page if it contains an element that matches the given selector
  if (ev.selector) {
    if (find.bySelector(ev.selector)) location.reload()
    return
  }

  // resolve the URL
  var url = parse(ev.url)

  // Remove query and hash strings
  var normalizedLocationHref = location.href.split('#')[0].split('?')[0]

  // reload the page
  if (url.href.replace('index.html','') == normalizedLocationHref) {
    location.reload()
    return
  }

  // look for a stylesheet
  var el = find.byURL('link', 'href', url)
  if (el) return replace(el, url.pathname + '?v=' + new Date().getTime())

  // look for a script
  el = find.byURL('script', 'src', url)
  if (el) location.reload()
})
<|endoftext|>


<commit_before><commit_msg>added jQuery to use onFirst<commit_after><|endoftext|>


<commit_before>// @flow strict
/* global MathJax */

import * as React from "react";
import loadScript from "./load-script";

import MathJaxContext, {
  type MathJaxObject,
  type MathJaxContextValue
} from "./context.js";

// MathJax expected to be a global and may be undefined
declare var MathJax: ?MathJaxObject;

type Props = {
  src: ?string,
  children: React.Node,
  didFinishTypeset: ?() => void,
  onLoad: ?() => void,
  input: "ascii" | "tex",
  delay: number,
  options: ?*,
  loading: React.Node,
  noGate: boolean,
  onError: (err: Error) => void
};

type State = MathJaxContextValue;

/**
 * MathJax Provider
 */
class Provider extends React.Component<Props, State> {
  static defaultProps = {
    src:
      "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-MML-AM_CHTML",
    input: "tex",
    didFinishTypeset: null,
    delay: 0,
    options: {},
    loading: null,
    noGate: false,
    onLoad: null,
    onError: (err: Error) => {
      console.error(err);
    }
  };

  constructor(props: Props) {
    super(props);

    this.state = {
      MathJax: undefined,
      // TODO: Ensure state gets updated when the input prop changes
      input: this.props.input,
      hasProviderAbove: true
    };
  }

  componentDidMount() {
    const src = this.props.src;

    if (src == null) {
      return this.onLoad();
    }

    loadScript(src, this.onLoad);
  }

  onLoad = () => {
    if (!MathJax || !MathJax.Hub) {
      this.props.onError(
        new Error("MathJax not really loaded even though onLoad called")
      );
      return;
    }

    const options = this.props.options;

    MathJax.Hub.Config(options);

    MathJax.Hub.Register.StartupHook("End", () => {
      if (!MathJax) {
        this.props.onError(
          new Error("MathJax became undefined in the middle of processing")
        );
        return;
      }
      MathJax.Hub.processSectionDelay = this.props.delay;

      if (this.props.didFinishTypeset) {
        this.props.didFinishTypeset();
      }
    });

    MathJax.Hub.Register.MessageHook("Math Processing Error", message => {
      if (this.props.onError) {
        this.props.onError(new Error(message));
      }
    });

    if (this.props.onLoad) {
      this.props.onLoad();
    }

    this.setState({
      MathJax
    });
  };

  render() {
    return (
      <MathJaxContext.Provider value={this.state}>
        {this.props.children}
      </MathJaxContext.Provider>
    );
  }
}

export default Provider;
<commit_msg>Fix MathJax checks<commit_after>// @flow strict
/* global MathJax */

import * as React from "react";
import loadScript from "./load-script";

import MathJaxContext, {
  type MathJaxObject,
  type MathJaxContextValue
} from "./context.js";

// MathJax expected to be a global and may be undefined
declare var MathJax: ?MathJaxObject;

type Props = {
  src: ?string,
  children: React.Node,
  didFinishTypeset: ?() => void,
  onLoad: ?() => void,
  input: "ascii" | "tex",
  delay: number,
  options: ?*,
  loading: React.Node,
  noGate: boolean,
  onError: (err: Error) => void
};

type State = MathJaxContextValue;

/**
 * MathJax Provider
 */
class Provider extends React.Component<Props, State> {
  static defaultProps = {
    src:
      "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-MML-AM_CHTML",
    input: "tex",
    didFinishTypeset: null,
    delay: 0,
    options: {},
    loading: null,
    noGate: false,
    onLoad: null,
    onError: (err: Error) => {
      console.error(err);
    }
  };

  constructor(props: Props) {
    super(props);

    this.state = {
      MathJax: undefined,
      // TODO: Ensure state gets updated when the input prop changes
      input: this.props.input,
      hasProviderAbove: true
    };
  }

  componentDidMount() {
    const src = this.props.src;

    if (src == null) {
      return this.onLoad();
    }

    loadScript(src, this.onLoad);
  }

  onLoad = () => {
    if (typeof MathJax === "undefined" || !MathJax || !MathJax.Hub) {
      this.props.onError(
        new Error("MathJax not really loaded even though onLoad called")
      );
      return;
    }

    const options = this.props.options;

    MathJax.Hub.Config(options);

    MathJax.Hub.Register.StartupHook("End", () => {
      if (typeof MathJax === "undefined" || !MathJax) {
        this.props.onError(
          new Error("MathJax became undefined in the middle of processing")
        );
        return;
      }
      MathJax.Hub.processSectionDelay = this.props.delay;

      if (this.props.didFinishTypeset) {
        this.props.didFinishTypeset();
      }
    });

    MathJax.Hub.Register.MessageHook("Math Processing Error", message => {
      if (this.props.onError) {
        this.props.onError(new Error(message));
      }
    });

    if (this.props.onLoad) {
      this.props.onLoad();
    }

    this.setState({
      MathJax
    });
  };

  render() {
    return (
      <MathJaxContext.Provider value={this.state}>
        {this.props.children}
      </MathJaxContext.Provider>
    );
  }
}

export default Provider;
<|endoftext|>


<commit_before>// import { take, call, put, select } from 'redux-saga/effects';
import { REQUEST_TOPICS } from './constants';
import { takeLatest } from 'redux-saga';
import { call, put } from 'redux-saga/effects';
import { requestTopicsSucceeded, requestTopicsFailed } from './actions';

export function fetchTopicsFromServer() {
  return fetch('http://localhost:3000/api/topics')
    .then(response => response.json());
}

function* fetchTopics() {
  try {
    const topics = yield call(fetchTopicsFromServer);
    yield put(requestTopicsSucceeded(topics));
  } catch (e) {
    yield put(requestTopicsFailed(e.message));
  }
}

export function* fetchTopicsSaga() {
  yield* takeLatest(REQUEST_TOPICS, fetchTopics);
}

// All sagas to be loaded
export default [
  fetchTopicsSaga,
];
<commit_msg>readability of saga<commit_after>// import { take, call, put, select } from 'redux-saga/effects';
import { REQUEST_TOPICS } from './constants';
import { takeLatest } from 'redux-saga';
import { call, put } from 'redux-saga/effects';
import { requestTopicsSucceeded, requestTopicsFailed } from './actions';

export function* fetchTopicsSaga() {
  yield* takeLatest(REQUEST_TOPICS, fetchTopics);
}

function* fetchTopics() {
  try {
    const topics = yield call(fetchTopicsFromServer);
    yield put(requestTopicsSucceeded(topics));
  } catch (e) {
    yield put(requestTopicsFailed(e.message));
  }
}

export function fetchTopicsFromServer() {
  return fetch('http://localhost:3000/api/topics')
    .then(response => response.json());
}

// All sagas to be loaded
export default [
  fetchTopicsSaga,
];
<|endoftext|>


<commit_before>import min from 'lodash/min'

import { BodyComponent } from 'mjml-core'

import widthParser from 'mjml-core/lib/helpers/widthParser'

export default class MjImage extends BodyComponent {
  static tagOmission = true

  static allowedAttributes = {
    alt: 'string',
    href: 'string',
    src: 'string',
    srcset: 'string',
    title: 'string',
    align: 'enum(left,center,right)',
    border: 'string',
    'border-bottom': 'string',
    'border-left': 'string',
    'border-right': 'string',
    'border-top': 'string',
    'border-radius': 'unit(px,%)',
    'container-background-color': 'string',
    padding: 'unit(px,%){1,4}',
    'padding-bottom': 'unit(px,%)',
    'padding-left': 'unit(px,%)',
    'padding-right': 'unit(px,%)',
    'padding-top': 'unit(px,%)',
    height: 'unit(px)',
    width: 'unit(px)',
  }

  static defaultAttributes = {
    align: 'center',
    border: '0',
    height: 'auto',
    padding: '10px 25px',
    target: '_blank',
  }

  getStyles() {
    const width = this.getContentWidth()
    const fullWidth = this.getAttribute('full-width') === 'full-width'

    const { parsedWidth, unit } = widthParser(width)

    return {
      img: {
        border: this.getAttribute('border'),
        'border-radius': this.getAttribute('border-radius'),
        display: 'block',
        outline: 'none',
        'text-decoration': 'none',
        height: this.getAttribute('height'),
        'min-width': fullWidth ? '100%' : null,
        width,
        'max-width': fullWidth ? '100%' : null,
      },
      td: {
        width: fullWidth ? null : `${parsedWidth}${unit}`,
      },
      table: {
        'min-width': fullWidth ? '100%' : null,
        'max-width': fullWidth ? '100%' : null,
        width: fullWidth ? `${parsedWidth}${unit}` : null,
        'border-collapse': 'collapse',
        'border-spacing': '0px',
      },
    }
  }

  getContentWidth() {
    const { containerWidth } = this.context
    const width = this.getAttribute('width')
                ? parseInt(this.getAttribute('width'), 10)
                : Infinity

    const paddingRight = this.getShorthandAttrValue('padding', 'right')
    const paddingLeft = this.getShorthandAttrValue('padding', 'left')
    const borderRight = this.getShorthandBorderValue('right')
    const borderLeft = this.getShorthandBorderValue('left')
    const allPaddings = paddingLeft + paddingRight + borderLeft + borderRight

    const contentWidth = min([
      parseInt(containerWidth, 10) - allPaddings,
      width + paddingLeft + paddingRight
    ])

    return `${contentWidth}px`
  }

  renderImage() {
    const height = this.getAttribute('height')

    const img = `

    `

    if (this.getAttribute('href')) {
      return `

          ${img}

      `
    }

    return img
  }

  render() {
    return `

              ${this.renderImage()}

    `
  }
}
<commit_msg>dont include padding in width if set width<commit_after>import min from 'lodash/min'

import { BodyComponent } from 'mjml-core'

import widthParser from 'mjml-core/lib/helpers/widthParser'

export default class MjImage extends BodyComponent {
  static tagOmission = true

  static allowedAttributes = {
    alt: 'string',
    href: 'string',
    src: 'string',
    srcset: 'string',
    title: 'string',
    align: 'enum(left,center,right)',
    border: 'string',
    'border-bottom': 'string',
    'border-left': 'string',
    'border-right': 'string',
    'border-top': 'string',
    'border-radius': 'unit(px,%)',
    'container-background-color': 'string',
    padding: 'unit(px,%){1,4}',
    'padding-bottom': 'unit(px,%)',
    'padding-left': 'unit(px,%)',
    'padding-right': 'unit(px,%)',
    'padding-top': 'unit(px,%)',
    height: 'unit(px)',
    width: 'unit(px)',
  }

  static defaultAttributes = {
    align: 'center',
    border: '0',
    height: 'auto',
    padding: '10px 25px',
    target: '_blank',
  }

  getStyles() {
    const width = this.getContentWidth()
    const fullWidth = this.getAttribute('full-width') === 'full-width'

    const { parsedWidth, unit } = widthParser(width)

    return {
      img: {
        border: this.getAttribute('border'),
        'border-radius': this.getAttribute('border-radius'),
        display: 'block',
        outline: 'none',
        'text-decoration': 'none',
        height: this.getAttribute('height'),
        'min-width': fullWidth ? '100%' : null,
        width,
        'max-width': fullWidth ? '100%' : null,
      },
      td: {
        width: fullWidth ? null : `${parsedWidth}${unit}`,
      },
      table: {
        'min-width': fullWidth ? '100%' : null,
        'max-width': fullWidth ? '100%' : null,
        width: fullWidth ? `${parsedWidth}${unit}` : null,
        'border-collapse': 'collapse',
        'border-spacing': '0px',
      },
    }
  }

  getContentWidth() {
    const { containerWidth } = this.context
    const width = this.getAttribute('width')
                ? parseInt(this.getAttribute('width'), 10)
                : Infinity

    const paddingRight = this.getShorthandAttrValue('padding', 'right')
    const paddingLeft = this.getShorthandAttrValue('padding', 'left')
    const borderRight = this.getShorthandBorderValue('right')
    const borderLeft = this.getShorthandBorderValue('left')
    const allPaddings = paddingLeft + paddingRight + borderLeft + borderRight

    const contentWidth = min([
      parseInt(containerWidth, 10) - allPaddings,
      width
    ])

    return `${contentWidth}px`
  }

  renderImage() {
    const height = this.getAttribute('height')

    const img = `

    `

    if (this.getAttribute('href')) {
      return `

          ${img}

      `
    }

    return img
  }

  render() {
    return `

              ${this.renderImage()}

    `
  }
}
<|endoftext|>