<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 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 markerform = new L.marker([from[0],from[1]], {icon: IconStart, draggable: true}).bindPopup('From').addTo(map);
    var markerto = new L.marker([to[0],to[1]], {icon: IconEnd, draggable: true}).bindPopup('to').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 circle = L.circle([to[0], to[1]], {
    //    radius: 6,
    //      color: 'black',
    //      weight: 2,
    //      opacity: 1,
    //      fillColor: 'white',
    //      fillOpacity: 1.0
    //}).bindPopup(name).addTo(map);

    var IconStart = L.icon({
        iconUrl: 'assets/images/graphics/icono.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 20],
        popupAnchor:  [0, -50]
    });

    L.marker([to[0], to[1]], {icon: IconStart}).addTo(map);
    //var circle = L.circle([to[0], to[1]], 400, {
    //    color: '#000',
    //    weight: 2,
    //    fillColor: '#ffffff',
    //    fillOpacity: 1
    //}).bindPopup(name).addTo(map);

    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= '';
        console.log("imprime mode ->", mode);
        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);
        console.log("pintamos datos ->", this.polyline_creadas);
        //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 console<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 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 markerform = new L.marker([from[0],from[1]], {icon: IconStart, draggable: true}).bindPopup('From').addTo(map);
    var markerto = new L.marker([to[0],to[1]], {icon: IconEnd, draggable: true}).bindPopup('to').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 circle = L.circle([to[0], to[1]], {
    //    radius: 6,
    //      color: 'black',
    //      weight: 2,
    //      opacity: 1,
    //      fillColor: 'white',
    //      fillOpacity: 1.0
    //}).bindPopup(name).addTo(map);

    //var IconStart = L.icon({
    //    iconUrl: 'assets/images/graphics/icono.svg',
    //    iconSize: [40, 55],
    //    iconAnchor: [20, 20],
    //    popupAnchor:  [0, -50]
    //});

    //L.marker([to[0], to[1]], {icon: IconStart}).addTo(map);

    var circle = L.circle([to[0], to[1]], 400, {
        color: '#000',
        weight: 2,
        fillColor: '#ffffff',
        fillOpacity: 1
    }).bindPopup(name).addTo(map);

    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= '';
        console.log("imprime mode ->", mode);
        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);
        console.log("pintamos datos ->", this.polyline_creadas);
        //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>// ==UserScript==
// @name         Gleam.io Autosolve
// @namespace    GLEAM
// @version      1.3
// @description  lets save some time
// @author       Tackyou
// @license      https://raw.githubusercontent.com/Tackyou/Gleam.io-Autosolve/master/LICENSE
// @icon         http://i.imgur.com/6PuVE2l.png
// @match        *gleam.io/*
// @supportURL   https://github.com/Tackyou/Gleam.io-Autosolve/issues
// @updateURL    https://raw.githubusercontent.com/Tackyou/Gleam.io-Autosolve/master/gleamio.user.js
// @downloadURL  https://raw.githubusercontent.com/Tackyou/Gleam.io-Autosolve/master/gleamio.user.js
// @grant        none
// ==/UserScript==

console.log('[GLEAM] Welcome!');
if ($("#current-entries") !== null) {
    $('.span4.blue-square.ng-scope').after('
NaNWinning Chance
');
    $("div.square-row.row-fluid.center.ng-scope > .span4").width('25%');
    setTimeout(setChance, 250);
}
function setChance(){
    var own = parseInt($(".status.ng-binding").text());
    var total = parseInt($(".current.ng-binding").text());
    var chance = Math.round(10000 * own / total) / 100;
    $("#winning-chance").text(chance+"%");
}
var gi = 0;
var gleam = setInterval(function(){
        if($("[ng-click*='entry_method']").length>0){
            if($("div.redeem-container").length<1 || $("div.redeem-container").is(':hidden')){
                $('.entry_details .visit-trigger a.btn').trigger('click');
                $("[ng-click*='entry_method']").trigger('click');
                $("[ng-class*='tallyIcon']").trigger('click');
                console.log('[GLEAM] Action performed');
                setChance();
            }else{
                console.log('[GLEAM] already completed');
                $('div.incentive-description h3.ng-binding.ng-scope').append('
Already completed!
');
                clearInterval(gleam);
            }
        }
        gi++;
        if(gi>6){
            clearInterval(gleam);
            setChance();
        }
}, 500);
<commit_msg>Reworked the whole script, more stable now<commit_after>// ==UserScript==
// @name         Gleam.io Autosolve
// @namespace    GLEAM
// @version      1.4
// @description  lets save some time
// @author       Tackyou
// @license      https://raw.githubusercontent.com/Tackyou/Gleam.io-Autosolve/master/LICENSE
// @icon         http://i.imgur.com/6PuVE2l.png
// @match        *gleam.io/*
// @supportURL   https://github.com/Tackyou/Gleam.io-Autosolve/issues
// @updateURL    https://raw.githubusercontent.com/Tackyou/Gleam.io-Autosolve/master/gleamio.user.js
// @downloadURL  https://raw.githubusercontent.com/Tackyou/Gleam.io-Autosolve/master/gleamio.user.js
// @grant        none
// ==/UserScript==

var wo = window.open;
window.open = function(){
   return;
}
var processed = [];
console.log('[GLEAM] Welcome!');
$(function(){
    gleam();
    if ($("#current-entries") !== null) {
        $('.span4.blue-square.ng-scope').after('
NaNWinning Chance
');
        $("div.square-row.row-fluid.center.ng-scope > .span4").width('25%');
        setTimeout(setChance, 400);
    }
});
function gleam(){
    if($("div.redeem-container").is(':visible')){
        console.log('[GLEAM] already completed');
        $('div.incentive-description h3.ng-binding.ng-scope').append('
Already completed!
');
    }else{
        var y = 0, x = setInterval(function(){
            y++;
            var g = 0;
            $('.entry-method').each(function(index){
                g++;
                var elem = $(this);
                if(!elem.hasClass('completed-entry-method') && processed.indexOf(g)==-1){
                    var type = $('span.icon-wrapper i', elem);
                    var text = '#'+g+' '+$.trim($('.text .ng-binding.ng-scope', elem).text());
                    console.log("[GLEAM] Processing: "+text);
                    if(type.hasClass('fa-heart')){
                        checkStatus(elem);
                    }else{
                        $('.entry_details a.btn', elem).trigger('click');
                        $('.tally', elem).trigger('click');
                        setTimeout(function(){setChance();checkStatus(elem);},400);
                    }
                    processed.push(g);
                }
            });
            if(y == 20){
                clearInterval(x);
                setTimeout(function(){setChance();},1500);
                window.open = wo;
            }
        }, 1000);
    }
}
function checkStatus(elem){
    var i = 0;
    var v = setInterval(function(){
        i++;
        var tally = $("[ng-class*='tallyIcon']", elem);
        if(!tally.hasClass('fa-spin') || i == 100){
            if(tally.hasClass('fa-chevron-down')){
                $('.tally', elem).trigger('click');
            }
            if(!tally.hasClass('fa-check') && !tally.hasClass('fa-clock-o')){
                $('.tally', elem).css('background', '#F2C32E');
            }
            clearInterval(v);
        }
    }, 100);
}
function setChance(){
    var own = parseInt($(".status.ng-binding").text());
    var total = parseInt($(".current.ng-binding").text());
    var chance = Math.round(10000 * own / total) / 100;
    $("#winning-chance").text(chance+"%");
}
<|endoftext|>


<commit_before>var $ = require('jquery');
var _ = require('underscore');
var cdb = require('cartodb.js');
var PecanView = require('../../../../../javascripts/cartodb/common/dialogs/pecan/pecan_view');
var BackgroundPollingModel = require('../../../../../javascripts/cartodb/common/background_polling/background_polling_model');

describe("PecanView", function() {

  function stubTable(table, opts) {
    var fakeData = sinon.stub(table, 'data');

    var isGeoreferenced = sinon.stub(table, "isGeoreferenced");

    isGeoreferenced.return(function() {
      return (!opts || opts.isGeoreferenced === undefined) ? true : opts.isGeoreferenced
    });

    var query_schema = (opts && opts.query_schema) ? opts.query_schema : {
      cartodb_id: "number",
      the_geom: "geometry",
      something: "string",
      created_at: "number",
      updated_at: "number"
    };

    fakeData.returns({
      query_schema: query_schema,
      table: {
        get: function(p) {
          if (p === 'rows_counted') {
            return (opts && opts.row_count) ? opts.row_count : 100
          }
          if (p === 'geometry_types') {
            return ["ST_Point"]
          }
        }
      }
    });
  }

  beforeEach(function() {
    window.user_data = { username: 'test' };

    this.user = jasmine.createSpy('cdb.admin.User');

    this.backgroundPollingModel = new BackgroundPollingModel({}, {
      user: this.user
    });

    spyOn(this.backgroundPollingModel, "addAnalysis")

    this.table = new cdb.admin.CartoDBTableMetadata({
      id: 'table_id',
      name: 'table_name'
    });
  });

  describe("View", function() {

    it("should exclude certain columns", function() {
      var contain = false;

      var view = new PecanView({
        table: this.table,
        backgroundPollingModel: this.backgroundPollingModel
      });

      contain = _.every(['id', 'cartodb_id', 'lat', 'lon', 'lng', 'long', 'latitude', 'longitude'], function(column) {
        return _.contains(view._EXCLUDED_COLUMNS, column);
      });

      expect(contain).toEqual(true);
    });

    it("should create an analysis if the table size is OK", function() {
      stubTable(this.table, { row_count: 100 });

      var view = new PecanView({
        table: this.table,
        backgroundPollingModel: this.backgroundPollingModel
      });

      expect(view.backgroundPollingModel.addAnalysis).toHaveBeenCalled();
    });

    it("should not create an analysis if the table is not georeferenced", function() {
      stubTable(this.table, { row_count: 100, isGeoreferenced: false });

      var view = new PecanView({
        table: this.table,
        backgroundPollingModel: this.backgroundPollingModel
      });

      expect(view.backgroundPollingModel.addAnalysis).not.toHaveBeenCalled();
    });

    it("should not create an analysis if the numer of rows is > _MAX_ROWS", function() {
      stubTable(this.table, { row_count: PecanView.prototype._MAX_ROWS + 1 });

      var view = new PecanView({
        table: this.table,
        backgroundPollingModel: this.backgroundPollingModel
      });

      expect(view.backgroundPollingModel.addAnalysis).not.toHaveBeenCalled();
    });

    it("should not create an analysis if the number of columns is > _MAX_COLS", function() {

      var query_schema = {
        cartodb_id: "number",
        the_geom: "geometry",
        created_at: "number",
        updated_at: "number"
      };

      for (var i = 0; i < PecanView.prototype._MAX_COLS; i++) {
        query_schema["col_" + i] = _.shuffle(["boolean", "number", "string"])[0]
      }

      stubTable(this.table, { query_schema: query_schema });

      var view = new PecanView({
        table: this.table,
        backgroundPollingModel: this.backgroundPollingModel
      });

      expect(view.backgroundPollingModel.addAnalysis).not.toHaveBeenCalled();
    });

    it("should generate a collection of columns based on the schema", function() {
      stubTable(this.table);

      var view = new PecanView({
        table: this.table,
        backgroundPollingModel: this.backgroundPollingModel
      });

      expect(view.columns.length).toBe(2);
      expect(view.columns.at(0).get("name")).toBe("the_geom");
      expect(view.columns.at(0).get("geometry_type")).toBe("point");

      expect(view.columns.at(1).get("name")).toBe("something");
      expect(view.columns.at(1).get("geometry_type")).toBe("point");
    });

  });
});
<commit_msg>Fixes spec<commit_after>var $ = require('jquery');
var _ = require('underscore');
var cdb = require('cartodb.js');
var PecanView = require('../../../../../javascripts/cartodb/common/dialogs/pecan/pecan_view');
var BackgroundPollingModel = require('../../../../../javascripts/cartodb/common/background_polling/background_polling_model');

describe("PecanView", function() {

  function stubTable(table, opts) {
    var fakeData = sinon.stub(table, 'data');

    var isGeoreferenced = sinon.stub(table, "isGeoreferenced");

    isGeoreferenced.return(function() {
      return (!opts || opts && opts.isGeoreferenced === undefined) ? true : opts.isGeoreferenced
    });

    var query_schema = (opts && opts.query_schema) ? opts.query_schema : {
      cartodb_id: "number",
      the_geom: "geometry",
      something: "string",
      created_at: "number",
      updated_at: "number"
    };

    fakeData.returns({
      query_schema: query_schema,
      table: {
        get: function(p) {
          if (p === 'rows_counted') {
            return (opts && opts.row_count) ? opts.row_count : 100
          }
          if (p === 'geometry_types') {
            return ["ST_Point"]
          }
        }
      }
    });
  }

  beforeEach(function() {
    window.user_data = { username: 'test' };

    this.user = jasmine.createSpy('cdb.admin.User');

    this.backgroundPollingModel = new BackgroundPollingModel({}, {
      user: this.user
    });

    spyOn(this.backgroundPollingModel, "addAnalysis")

    this.table = new cdb.admin.CartoDBTableMetadata({
      id: 'table_id',
      name: 'table_name'
    });
  });

  describe("View", function() {

    it("should exclude certain columns", function() {
      var contain = false;

      var view = new PecanView({
        table: this.table,
        backgroundPollingModel: this.backgroundPollingModel
      });

      contain = _.every(['id', 'cartodb_id', 'lat', 'lon', 'lng', 'long', 'latitude', 'longitude'], function(column) {
        return _.contains(view._EXCLUDED_COLUMNS, column);
      });

      expect(contain).toEqual(true);
    });

    it("should create an analysis if the table size is OK", function() {
      stubTable(this.table, { row_count: 100 });

      var view = new PecanView({
        table: this.table,
        backgroundPollingModel: this.backgroundPollingModel
      });

      expect(view.backgroundPollingModel.addAnalysis).toHaveBeenCalled();
    });

    it("should not create an analysis if the table is not georeferenced", function() {
      stubTable(this.table, { row_count: 100, isGeoreferenced: false });

      var view = new PecanView({
        table: this.table,
        backgroundPollingModel: this.backgroundPollingModel
      });

      expect(view.backgroundPollingModel.addAnalysis).not.toHaveBeenCalled();
    });

    it("should not create an analysis if the numer of rows is > _MAX_ROWS", function() {
      stubTable(this.table, { row_count: PecanView.prototype._MAX_ROWS + 1 });

      var view = new PecanView({
        table: this.table,
        backgroundPollingModel: this.backgroundPollingModel
      });

      expect(view.backgroundPollingModel.addAnalysis).not.toHaveBeenCalled();
    });

    it("should not create an analysis if the number of columns is > _MAX_COLS", function() {

      var query_schema = {
        cartodb_id: "number",
        the_geom: "geometry",
        created_at: "number",
        updated_at: "number"
      };

      for (var i = 0; i < PecanView.prototype._MAX_COLS; i++) {
        query_schema["col_" + i] = _.shuffle(["boolean", "number", "string"])[0]
      }

      stubTable(this.table, { query_schema: query_schema });

      var view = new PecanView({
        table: this.table,
        backgroundPollingModel: this.backgroundPollingModel
      });

      expect(view.backgroundPollingModel.addAnalysis).not.toHaveBeenCalled();
    });

    it("should generate a collection of columns based on the schema", function() {
      stubTable(this.table);

      var view = new PecanView({
        table: this.table,
        backgroundPollingModel: this.backgroundPollingModel
      });

      expect(view.columns.length).toBe(2);
      expect(view.columns.at(0).get("name")).toBe("the_geom");
      expect(view.columns.at(0).get("geometry_type")).toBe("point");

      expect(view.columns.at(1).get("name")).toBe("something");
      expect(view.columns.at(1).get("geometry_type")).toBe("point");
    });

  });
});
<|endoftext|>


<commit_before>define("dijit/ProgressBar", ["dojo", "dijit", "text!dijit/templates/ProgressBar.html", "dojo/fx", "dojo/number", "dijit/_Widget", "dijit/_TemplatedMixin"], function(dojo, dijit) {

dojo.declare("dijit.ProgressBar", [dijit._Widget, dijit._TemplatedMixin], {
	// summary:
	//		A progress indication widget, showing the amount completed
	//		(often the percentage completed) of a task.
	//
	// example:
	// |

	// |

	// progress: [const] String (Percentage or Number)
	//		Number or percentage indicating amount of task completed.
	// 		Deprecated.   Use "value" instead.
	progress: "0",

	// value: String (Percentage or Number)
	//		Number or percentage indicating amount of task completed.
	// 		With "%": percentage value, 0% <= progress <= 100%, or
	// 		without "%": absolute value, 0 <= progress <= maximum.
	//		Infinity means that the progress bar is indeterminate.
	value: "",

	// maximum: [const] Float
	//		Max sample number
	maximum: 100,

	// places: [const] Number
	//		Number of places to show in values; 0 by default
	places: 0,

	// indeterminate: [const] Boolean
	// 		If false: show progress value (number or percentage).
	// 		If true: show that a process is underway but that the amount completed is unknown.
	// 		Deprecated.   Use "value" instead.
	indeterminate: false,

	// label: String?
	//		Label on progress bar.   Defaults to percentage for determinate progress bar and
	//		blank for indeterminate progress bar.
	label:"",

	// name: String
	//		this is the field name (for a form) if set. This needs to be set if you want to use
	//		this widget in a dijit.form.Form widget (such as dijit.Dialog)
	name: '',

	templateString: dojo.cache("dijit", "templates/ProgressBar.html"),

	// _indeterminateHighContrastImagePath: [private] dojo._URL
	//		URL to image to use for indeterminate progress bar when display is in high contrast mode
	_indeterminateHighContrastImagePath:
		dojo.moduleUrl("dijit", "themes/a11y/indeterminate_progress.gif"),

	postMixInProperties: function(){
		this.inherited(arguments);
		if(!("value" in this.params)){
			this.value = this.indeterminate ? Infinity : this.progress;
		}
	},

	buildRendering: function(){
		this.inherited(arguments);
		this.indeterminateHighContrastImage.setAttribute("src",
			this._indeterminateHighContrastImagePath.toString());
		this.update();
	},

	update: function(/*Object?*/attributes){
		// summary:
		//		Internal method to change attributes of ProgressBar, similar to set(hash).  Users should call
		//		set("value", ...) rather than calling this method directly.
		// attributes:
		//		May provide progress and/or maximum properties on this parameter;
		//		see attribute specs for details.
		// example:
		//	|	myProgressBar.update({'indeterminate': true});
		//	|	myProgressBar.update({'progress': 80});
		//	|	myProgressBar.update({'indeterminate': true, label:"Loading ..." })
		// tags:
		//		private

		// TODO: deprecate this method and use set() instead

		dojo.mixin(this, attributes || {});
		var tip = this.internalProgress, ap = this.domNode;
		var percent = 1;
		if(this.indeterminate){
			dijit.removeWaiState(ap, "valuenow");
			dijit.removeWaiState(ap, "valuemin");
			dijit.removeWaiState(ap, "valuemax");
		}else{
			if(String(this.progress).indexOf("%") != -1){
				percent = Math.min(parseFloat(this.progress)/100, 1);
				this.progress = percent * this.maximum;
			}else{
				this.progress = Math.min(this.progress, this.maximum);
				percent = this.progress / this.maximum;
			}

			dijit.setWaiState(ap, "describedby", this.labelNode.id);
			dijit.setWaiState(ap, "valuenow", this.progress);
			dijit.setWaiState(ap, "valuemin", 0);
			dijit.setWaiState(ap, "valuemax", this.maximum);
		}
		this.labelNode.innerHTML = this.report(percent);

		dojo.toggleClass(this.domNode, "dijitProgressBarIndeterminate", this.indeterminate);
		tip.style.width = (percent * 100) + "%";
		this.onChange();
	},

	_setValueAttr: function(v){
		this._set("value", v);
		if(v == Infinity){
			this.update({indeterminate:true});
		}else{
			this.update({indeterminate:false, progress:v});
		}
	},

	_setLabelAttr: function(label){
		this._set("label", label);
		this.update();
	},

	_setIndeterminateAttr: function(indeterminate){
		// Deprecated, use set("value", ...) instead
		this.indeterminate = indeterminate;
		this.update();
	},

	report: function(/*float*/percent){
		// summary:
		//		Generates message to show inside progress bar (normally indicating amount of task completed).
		//		May be overridden.
		// tags:
		//		extension

		return this.label ? this.label :
				(this.indeterminate ? " " : dojo.number.format(percent, { type: "percent", places: this.places, locale: this.lang }));
	},

	onChange: function(){
		// summary:
		//		Callback fired when progress updates.
		// tags:
		//		extension
	}
});

return dijit.ProgressBar;
});
<commit_msg>added AMD loader, refs #12672 \!strict<commit_after>define([
  "dojo",
  ".",
  "dojo/text!./templates/ProgressBar.html",
  "dojo/fx",
  "dojo/number",
  "./_Widget",
  "./_TemplatedMixin"], function(dojo, dijit) {
	//  module:
	//    dijit/ProgressBar
	//  summary:
	//		TODOC
	//

dojo.declare("dijit.ProgressBar", [dijit._Widget, dijit._TemplatedMixin], {
	// summary:
	//		A progress indication widget, showing the amount completed
	//		(often the percentage completed) of a task.
	//
	// example:
	// |

	// |

	// progress: [const] String (Percentage or Number)
	//		Number or percentage indicating amount of task completed.
	// 		Deprecated.   Use "value" instead.
	progress: "0",

	// value: String (Percentage or Number)
	//		Number or percentage indicating amount of task completed.
	// 		With "%": percentage value, 0% <= progress <= 100%, or
	// 		without "%": absolute value, 0 <= progress <= maximum.
	//		Infinity means that the progress bar is indeterminate.
	value: "",

	// maximum: [const] Float
	//		Max sample number
	maximum: 100,

	// places: [const] Number
	//		Number of places to show in values; 0 by default
	places: 0,

	// indeterminate: [const] Boolean
	// 		If false: show progress value (number or percentage).
	// 		If true: show that a process is underway but that the amount completed is unknown.
	// 		Deprecated.   Use "value" instead.
	indeterminate: false,

	// label: String?
	//		Label on progress bar.   Defaults to percentage for determinate progress bar and
	//		blank for indeterminate progress bar.
	label:"",

	// name: String
	//		this is the field name (for a form) if set. This needs to be set if you want to use
	//		this widget in a dijit.form.Form widget (such as dijit.Dialog)
	name: '',

	templateString: dojo.cache("dijit", "templates/ProgressBar.html"),

	// _indeterminateHighContrastImagePath: [private] dojo._URL
	//		URL to image to use for indeterminate progress bar when display is in high contrast mode
	_indeterminateHighContrastImagePath:
		dojo.moduleUrl("dijit", "themes/a11y/indeterminate_progress.gif"),

	postMixInProperties: function(){
		this.inherited(arguments);
		if(!("value" in this.params)){
			this.value = this.indeterminate ? Infinity : this.progress;
		}
	},

	buildRendering: function(){
		this.inherited(arguments);
		this.indeterminateHighContrastImage.setAttribute("src",
			this._indeterminateHighContrastImagePath.toString());
		this.update();
	},

	update: function(/*Object?*/attributes){
		// summary:
		//		Internal method to change attributes of ProgressBar, similar to set(hash).  Users should call
		//		set("value", ...) rather than calling this method directly.
		// attributes:
		//		May provide progress and/or maximum properties on this parameter;
		//		see attribute specs for details.
		// example:
		//	|	myProgressBar.update({'indeterminate': true});
		//	|	myProgressBar.update({'progress': 80});
		//	|	myProgressBar.update({'indeterminate': true, label:"Loading ..." })
		// tags:
		//		private

		// TODO: deprecate this method and use set() instead

		dojo.mixin(this, attributes || {});
		var tip = this.internalProgress, ap = this.domNode;
		var percent = 1;
		if(this.indeterminate){
			dijit.removeWaiState(ap, "valuenow");
			dijit.removeWaiState(ap, "valuemin");
			dijit.removeWaiState(ap, "valuemax");
		}else{
			if(String(this.progress).indexOf("%") != -1){
				percent = Math.min(parseFloat(this.progress)/100, 1);
				this.progress = percent * this.maximum;
			}else{
				this.progress = Math.min(this.progress, this.maximum);
				percent = this.progress / this.maximum;
			}

			dijit.setWaiState(ap, "describedby", this.labelNode.id);
			dijit.setWaiState(ap, "valuenow", this.progress);
			dijit.setWaiState(ap, "valuemin", 0);
			dijit.setWaiState(ap, "valuemax", this.maximum);
		}
		this.labelNode.innerHTML = this.report(percent);

		dojo.toggleClass(this.domNode, "dijitProgressBarIndeterminate", this.indeterminate);
		tip.style.width = (percent * 100) + "%";
		this.onChange();
	},

	_setValueAttr: function(v){
		this._set("value", v);
		if(v == Infinity){
			this.update({indeterminate:true});
		}else{
			this.update({indeterminate:false, progress:v});
		}
	},

	_setLabelAttr: function(label){
		this._set("label", label);
		this.update();
	},

	_setIndeterminateAttr: function(indeterminate){
		// Deprecated, use set("value", ...) instead
		this.indeterminate = indeterminate;
		this.update();
	},

	report: function(/*float*/percent){
		// summary:
		//		Generates message to show inside progress bar (normally indicating amount of task completed).
		//		May be overridden.
		// tags:
		//		extension

		return this.label ? this.label :
				(this.indeterminate ? " " : dojo.number.format(percent, { type: "percent", places: this.places, locale: this.lang }));
	},

	onChange: function(){
		// summary:
		//		Callback fired when progress updates.
		// tags:
		//		extension
	}
});

return dijit.ProgressBar;
});
<|endoftext|>


<commit_before>/*    Copyright 2016 Firewalla LLC
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    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/>.
 */

'use strict'

const log = require("../../net2/logger")('diag');

const express = require('express');
const path = require('path');

const port = 8835

const Promise = require('bluebird')

const exec = require('child-process-promise').exec
const fs = require('fs')
Promise.promisifyAll(fs)

const Config = require('../../net2/config.js');
const sysManager = require('../../net2/SysManager.js');

const jsonfile = require('jsonfile');
const writeFileAsync = Promise.promisify(jsonfile.writeFile);

const { wrapIptables } = require('../../net2/Iptables.js')

const sem = require('../../sensor/SensorEventManager.js').getInstance();

const Mode = require('../../net2/Mode.js');

const VIEW_PATH = 'view';
const STATIC_PATH = 'static';

const errorCodes = {
  "firekick": 101,
  "firemain": 102,
  "fireapi": 103,
  "firemon": 104,
  "memory": 201,
  "database": 301,
  "databaseConnectivity": 302,
  "gid": 401,
  "ip": 501
}

class App {
  constructor() {
    this.app = express();

    this.app.engine('mustache', require('mustache-express')());
    this.app.set('view engine', 'mustache');

    this.app.set('views', path.join(__dirname, VIEW_PATH));
    //this.app.disable('view cache'); //for debug only

    this.routes();
  }

  getSystemTime() {
    return new Date() / 1000
  }

  async getSystemServices() {
    const fireKickCmd = "systemctl is-active firekick"
    const fireMainCmd = "systemctl is-active firemain"
    const fireApiCmd = "systemctl is-active fireapi"
    const fireMonCmd = "systemctl is-active firemon"

    try {
      await exec(fireKickCmd)
    } catch (err) {
      log.error("firekick is not alive", err);
      return errorCodes.firekick
    }

    try {
      await exec(fireMainCmd)
    } catch (err) {
      log.error("firemain is not alive", err);
      return errorCodes.firemain
    }

    try {
      await exec(fireApiCmd)
    } catch (err) {
      log.error("fireapi is not alive", err);
      return errorCodes.fireapi
    }

    try {
      await exec(fireMonCmd)
    } catch (err) {
      log.error("firemon is not alive", err);
      return errorCodes.firemon
    }

    return 0
  }

  getCloudConnectivity() {
    return this.connected
  }

  async getSystemMemory() {
    const result = await exec("free -m")
    const stdout = result.stdout
    const lines = stdout.split(/\n/g)

    for (var i = 0; i < lines.length; i++) {
      lines[i] = lines[i].split(/\s+/)
    }

    const allMem = parseInt(lines[1][1])

    if (allMem > 490) {
      return 0
    } else {
      return errorCodes.memory
    }
  }

  getNodeVersion() {
    return process.version
  }

  getUptime() {
    return require('os').uptime()
  }

  async getDatabase() {
    try {
      await exec("systemctl is-active redis-server")
    } catch (err) {
      log.error("Failed to check database", err);
      return errorCodes.database
    }

    return 0
  }

  async getDatabaseConnectivity() {
    try {
      await exec("redis-cli get mode")
    } catch (err) {
      log.error("Failed to check database connection status", err);
      return errorCodes.databaseConnectivity
    }
    return 0
  }

  async getGID() {
    try {
      const gid = await exec("redis-cli hget sys:ept gid")
      return gid && gid.stdout && gid.stdout.substring(0, 8)
    } catch (err) {
      log.error("Failed to get gid", err);
      return null
    }
  }

  async getFullGID() {
    try {
      const gid = await exec("redis-cli hget sys:ept gid")
      return gid && gid.stdout && gid.stdout.replace("\n", "")
    } catch (err) {
      log.error("Failed to get gid", err);
      return null
    }
  }

  async getPrimaryIP() {
    const config = Config.getConfig(true);
    const eths = require('os').networkInterfaces()[config.monitoringInterface];

    if (eths) {
      for (let index = 0; index < eths.length; index++) {
        const eth = eths[index]
        if (eth.family == "IPv4") {
          return eth.address
        }
      }
    }

    return ''
  }

  async getQRImage() {
    if (!this.broadcastInfo) {
      return null;
    }

    try {
      const imagePath = `${__dirname}/static/firewalla_pairing_info.png`;
      const jsonPath = "/tmp/pairing.info.json";

      const pairingInfo = JSON.parse(JSON.stringify(this.broadcastInfo));
      pairingInfo.type = "pairing";
      delete pairingInfo.keyhint;
      delete pairingInfo.service;
      delete pairingInfo.mid;
      delete pairingInfo.verifymode;

      await writeFileAsync(jsonPath, pairingInfo);

      const cmd = `cat ${jsonPath} | qrencode -o ${imagePath}`;

      await exec(cmd);
      return imagePath;
    } catch (err) {
      log.error("Failed to get QRImage", err);
      return null
    }
  }

  routes() {
    this.router = express.Router();

    this.app.use('/' + VIEW_PATH, this.router);
    this.app.use('/' + STATIC_PATH, express.static(path.join(__dirname, STATIC_PATH)));

    this.app.use('/log', (req, res) => {
      const filename = "/home/pi/logs/FireKick.log";
      (async () => {
        const gid = await this.getFullGID()
        await fs.accessAsync(filename, fs.constants.F_OK)
        //tail -n 1000 /home/pi/logs/FireKick.log | sed -r   "s/0-9]{1,2}(;[0-9]{1,2})?)?[mGK]//g"
        const result = (await exec(`tail -n 1000 ${filename}`)).stdout
        let lines = result.split("\n")
        lines = lines.map((originLine) => {
          let line = originLine
          line = line.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, '')
          line = line.replace(new RegExp(gid, "g"), "<****gid****>")
          line = line.replace(/type in this key:.*$/g, "type in this key: <****key****>")
          line = line.replace(/Inviting .{10,40} to group/g, "Inviting <****rid****> to group")
          line = line.replace(/Set SYS:EPT.*/, "Set SYS:EPT<****token****>")
          return line
        })

        res.setHeader('content-type', 'text/plain');
        res.end(lines.join("\n"))
      })().catch((err) => {
        log.error("Failed to fetch log", err);
        res.status(404).send('')
      })
    });

    this.app.use('/pairing', (req, res) => {
      if (this.broadcastInfo) {
        res.json(this.broadcastInfo);
      } else {
        res.status(501).send('');
      }
    });

    this.app.use('/pair/ping', (req, res) => {
      res.json({});
    });

    this.app.use('/pair/ready', async (req, res) => {
      try {
        const values = await this.getPairingStatus();
        if(values.success) {
          res.json({
            ready: true
          });
        } else {
          res.json({
            ready: false,
            content: values
          });
        }
      } catch(err) {
        log.error("Failed to process request", err);
        res.json({
          ready: false
        });
      }
    });

    this.app.use('*', async (req, res) => {
      log.info("Got a request in *")

      try {
        const values = await this.getPairingStatus();
        if(values.error) {
          log.error("Failed to process request", err);
          res.status(500).send({})
        } else {
          res.render('welcome', values)
        }
      } catch(err) {
        log.error("Failed to process request", err);
        res.status(500).send({})
      }
    })
  }

  async getPairingStatus() {
    try {
      const time = this.getSystemTime()
      const ip = await this.getPrimaryIP();
      const gid = await this.getGID()
      const database = await this.getDatabase()
      const uptime = this.getUptime()
      const nodeVersion = this.getNodeVersion()
      const memory = await this.getSystemMemory()
      const connected = this.getCloudConnectivity()
      const systemServices = await this.getSystemServices()
      const expireDate = this.expireDate;
      const qrImagePath = await this.getQRImage()

      let success = true
      let values = {
        now: new Date() / 1000
      }

      if(!this.broadcastInfo) {
        values.err_binding = true
        success = false;
      }

      if(qrImagePath) {
        values.qrImage = true;
      } else {
        success = false;
      }

      if(ip == "") {
        values.err_ip = true
        success = false
      } else {
        values.ip = ip
      }

      if(gid == null) {
        values.err_config = true
        success = false
      }

      if(database != 0) {
        values.err_database = true
        success = false
      }

      if(memory != 0) {
        values.err_memory = true
        success = false
      }

      if(connected != true) {
        values.err_cloud = true
        success = false
      }

      if(systemServices != 0) {
        values.err_service = true
        success = false
      }

      values.success = success

      return values;

    } catch(err) {
      log.error("Failed to get pairing status, err:", err);
      return {
        success: false,
        error: true
      }
    }
  }

  async iptablesRedirection(create = true) {
    let interfaces = sysManager.getLogicInterfaces()
    if (await Mode.isRouterModeOn()) {
      interfaces = interfaces.filter(intf => intf.type != 'wan')
    }
    const IPv4List = interfaces.map(intf => intf.ip_address)

    log.info("", IPv4List);

    const action = create ? '-A' : '-D';

    for (const ip of IPv4List) {
      if (!ip) continue;

      log.info(create ? 'creating' : 'removing', `port forwording from 80 to ${port} on ${ip}`);
      const cmd = wrapIptables(`sudo iptables -w -t nat ${action} FW_PREROUTING -p tcp --destination ${ip} --destination-port 80 -j REDIRECT --to-ports ${port}`);
      await exec(cmd);
    }
  }

  start() {
    this.app.listen(port, () => {
      log.info(`Httpd listening on port ${port}!`)

      sem.on("DiagRedirectionRenew", (event) => {
        log.info("Renew port redirection")
        this.iptablesRedirection();
      })

    });
  }
}

module.exports = App
<commit_msg>Use '-I' instead of '-A' for 8835 redirection<commit_after>/*    Copyright 2016 Firewalla LLC
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    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/>.
 */

'use strict'

const log = require("../../net2/logger")('diag');

const express = require('express');
const path = require('path');

const port = 8835

const Promise = require('bluebird')

const exec = require('child-process-promise').exec
const fs = require('fs')
Promise.promisifyAll(fs)

const Config = require('../../net2/config.js');
const sysManager = require('../../net2/SysManager.js');

const jsonfile = require('jsonfile');
const writeFileAsync = Promise.promisify(jsonfile.writeFile);

const { wrapIptables } = require('../../net2/Iptables.js')

const sem = require('../../sensor/SensorEventManager.js').getInstance();

const Mode = require('../../net2/Mode.js');

const VIEW_PATH = 'view';
const STATIC_PATH = 'static';

const errorCodes = {
  "firekick": 101,
  "firemain": 102,
  "fireapi": 103,
  "firemon": 104,
  "memory": 201,
  "database": 301,
  "databaseConnectivity": 302,
  "gid": 401,
  "ip": 501
}

class App {
  constructor() {
    this.app = express();

    this.app.engine('mustache', require('mustache-express')());
    this.app.set('view engine', 'mustache');

    this.app.set('views', path.join(__dirname, VIEW_PATH));
    //this.app.disable('view cache'); //for debug only

    this.routes();
  }

  getSystemTime() {
    return new Date() / 1000
  }

  async getSystemServices() {
    const fireKickCmd = "systemctl is-active firekick"
    const fireMainCmd = "systemctl is-active firemain"
    const fireApiCmd = "systemctl is-active fireapi"
    const fireMonCmd = "systemctl is-active firemon"

    try {
      await exec(fireKickCmd)
    } catch (err) {
      log.error("firekick is not alive", err);
      return errorCodes.firekick
    }

    try {
      await exec(fireMainCmd)
    } catch (err) {
      log.error("firemain is not alive", err);
      return errorCodes.firemain
    }

    try {
      await exec(fireApiCmd)
    } catch (err) {
      log.error("fireapi is not alive", err);
      return errorCodes.fireapi
    }

    try {
      await exec(fireMonCmd)
    } catch (err) {
      log.error("firemon is not alive", err);
      return errorCodes.firemon
    }

    return 0
  }

  getCloudConnectivity() {
    return this.connected
  }

  async getSystemMemory() {
    const result = await exec("free -m")
    const stdout = result.stdout
    const lines = stdout.split(/\n/g)

    for (var i = 0; i < lines.length; i++) {
      lines[i] = lines[i].split(/\s+/)
    }

    const allMem = parseInt(lines[1][1])

    if (allMem > 490) {
      return 0
    } else {
      return errorCodes.memory
    }
  }

  getNodeVersion() {
    return process.version
  }

  getUptime() {
    return require('os').uptime()
  }

  async getDatabase() {
    try {
      await exec("systemctl is-active redis-server")
    } catch (err) {
      log.error("Failed to check database", err);
      return errorCodes.database
    }

    return 0
  }

  async getDatabaseConnectivity() {
    try {
      await exec("redis-cli get mode")
    } catch (err) {
      log.error("Failed to check database connection status", err);
      return errorCodes.databaseConnectivity
    }
    return 0
  }

  async getGID() {
    try {
      const gid = await exec("redis-cli hget sys:ept gid")
      return gid && gid.stdout && gid.stdout.substring(0, 8)
    } catch (err) {
      log.error("Failed to get gid", err);
      return null
    }
  }

  async getFullGID() {
    try {
      const gid = await exec("redis-cli hget sys:ept gid")
      return gid && gid.stdout && gid.stdout.replace("\n", "")
    } catch (err) {
      log.error("Failed to get gid", err);
      return null
    }
  }

  async getPrimaryIP() {
    const config = Config.getConfig(true);
    const eths = require('os').networkInterfaces()[config.monitoringInterface];

    if (eths) {
      for (let index = 0; index < eths.length; index++) {
        const eth = eths[index]
        if (eth.family == "IPv4") {
          return eth.address
        }
      }
    }

    return ''
  }

  async getQRImage() {
    if (!this.broadcastInfo) {
      return null;
    }

    try {
      const imagePath = `${__dirname}/static/firewalla_pairing_info.png`;
      const jsonPath = "/tmp/pairing.info.json";

      const pairingInfo = JSON.parse(JSON.stringify(this.broadcastInfo));
      pairingInfo.type = "pairing";
      delete pairingInfo.keyhint;
      delete pairingInfo.service;
      delete pairingInfo.mid;
      delete pairingInfo.verifymode;

      await writeFileAsync(jsonPath, pairingInfo);

      const cmd = `cat ${jsonPath} | qrencode -o ${imagePath}`;

      await exec(cmd);
      return imagePath;
    } catch (err) {
      log.error("Failed to get QRImage", err);
      return null
    }
  }

  routes() {
    this.router = express.Router();

    this.app.use('/' + VIEW_PATH, this.router);
    this.app.use('/' + STATIC_PATH, express.static(path.join(__dirname, STATIC_PATH)));

    this.app.use('/log', (req, res) => {
      const filename = "/home/pi/logs/FireKick.log";
      (async () => {
        const gid = await this.getFullGID()
        await fs.accessAsync(filename, fs.constants.F_OK)
        //tail -n 1000 /home/pi/logs/FireKick.log | sed -r   "s/0-9]{1,2}(;[0-9]{1,2})?)?[mGK]//g"
        const result = (await exec(`tail -n 1000 ${filename}`)).stdout
        let lines = result.split("\n")
        lines = lines.map((originLine) => {
          let line = originLine
          line = line.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, '')
          line = line.replace(new RegExp(gid, "g"), "<****gid****>")
          line = line.replace(/type in this key:.*$/g, "type in this key: <****key****>")
          line = line.replace(/Inviting .{10,40} to group/g, "Inviting <****rid****> to group")
          line = line.replace(/Set SYS:EPT.*/, "Set SYS:EPT<****token****>")
          return line
        })

        res.setHeader('content-type', 'text/plain');
        res.end(lines.join("\n"))
      })().catch((err) => {
        log.error("Failed to fetch log", err);
        res.status(404).send('')
      })
    });

    this.app.use('/pairing', (req, res) => {
      if (this.broadcastInfo) {
        res.json(this.broadcastInfo);
      } else {
        res.status(501).send('');
      }
    });

    this.app.use('/pair/ping', (req, res) => {
      res.json({});
    });

    this.app.use('/pair/ready', async (req, res) => {
      try {
        const values = await this.getPairingStatus();
        if(values.success) {
          res.json({
            ready: true
          });
        } else {
          res.json({
            ready: false,
            content: values
          });
        }
      } catch(err) {
        log.error("Failed to process request", err);
        res.json({
          ready: false
        });
      }
    });

    this.app.use('*', async (req, res) => {
      log.info("Got a request in *")

      try {
        const values = await this.getPairingStatus();
        if(values.error) {
          log.error("Failed to process request", err);
          res.status(500).send({})
        } else {
          res.render('welcome', values)
        }
      } catch(err) {
        log.error("Failed to process request", err);
        res.status(500).send({})
      }
    })
  }

  async getPairingStatus() {
    try {
      const time = this.getSystemTime()
      const ip = await this.getPrimaryIP();
      const gid = await this.getGID()
      const database = await this.getDatabase()
      const uptime = this.getUptime()
      const nodeVersion = this.getNodeVersion()
      const memory = await this.getSystemMemory()
      const connected = this.getCloudConnectivity()
      const systemServices = await this.getSystemServices()
      const expireDate = this.expireDate;
      const qrImagePath = await this.getQRImage()

      let success = true
      let values = {
        now: new Date() / 1000
      }

      if(!this.broadcastInfo) {
        values.err_binding = true
        success = false;
      }

      if(qrImagePath) {
        values.qrImage = true;
      } else {
        success = false;
      }

      if(ip == "") {
        values.err_ip = true
        success = false
      } else {
        values.ip = ip
      }

      if(gid == null) {
        values.err_config = true
        success = false
      }

      if(database != 0) {
        values.err_database = true
        success = false
      }

      if(memory != 0) {
        values.err_memory = true
        success = false
      }

      if(connected != true) {
        values.err_cloud = true
        success = false
      }

      if(systemServices != 0) {
        values.err_service = true
        success = false
      }

      values.success = success

      return values;

    } catch(err) {
      log.error("Failed to get pairing status, err:", err);
      return {
        success: false,
        error: true
      }
    }
  }

  async iptablesRedirection(create = true) {
    let interfaces = sysManager.getLogicInterfaces()
    if (await Mode.isRouterModeOn()) {
      interfaces = interfaces.filter(intf => intf.type != 'wan')
    }
    const IPv4List = interfaces.map(intf => intf.ip_address)

    log.info("", IPv4List);

    const action = create ? '-I' : '-D';

    for (const ip of IPv4List) {
      if (!ip) continue;

      log.info(create ? 'creating' : 'removing', `port forwording from 80 to ${port} on ${ip}`);
      const cmd = wrapIptables(`sudo iptables -w -t nat ${action} FW_PREROUTING -p tcp --destination ${ip} --destination-port 80 -j REDIRECT --to-ports ${port}`);
      await exec(cmd);
    }
  }

  start() {
    this.app.listen(port, () => {
      log.info(`Httpd listening on port ${port}!`)

      sem.on("DiagRedirectionRenew", (event) => {
        log.info("Renew port redirection")
        this.iptablesRedirection();
      })

    });
  }
}

module.exports = App
<|endoftext|>


<commit_before>
$(document).ready(function () {
  $("#contact-form-submit").prop("disabled",true);
    $("#contact-form-submit").click(function(){
      console.log("1")
      var contactFirst= $("#contact-first").val();
      var contactLast= $("#contact-last").val();
      var contactMessage= $("#contact-message").val();
      var contactPhone= $("#contact-phone").val();
      var contactEmail= $("#contact-email").val();
      emailjs.send("gmail","template_UPluqtLC",{firstname: contactFirst, lastname:contactLast,  message: contactMessage, phonenumber: contactPhone, email: contactEmail});
      console.log("2")
      alert("I'll be recieving your email shortly!");
      $("#contact_form")[0].reset();
    });
});

function enableBtn(){
  $("#contact-form-submit").prop("disabled",false);
}
//
//
//
// function submitContactForm() {
//
//     $('#contact-form-submit').on("click",function (e) {
//         e.preventDefault();
//         var contactFirst = $('#contact-first').val();
//         var contactLast = $('#contact-last').val();
//         var contactEmail = $('#contact-email').val();
//         var contactPhone = $('#contact-phone').val();
//         var contactMessage = $('#contact-message').val();
//
//         var url = "//docs.google.com/forms/d/e/1FAIpQLScq4L1Ri9teYVCUM88wYZWStatmKvAe49VLimhOlgiD3mxgYQ/viewform#responses";
//
//         var data = {
//             'entry.2005620554': contactFirst,
//             'entry.834360636': contactLast,
//             'entry.1045781291': contactEmail,
//             'entry.1166974658': contactPhone,
//             'entry.839337160': contactMessage
//         };
//         console.log(contactPhone)
//         $.ajax({
//             type: "POST",
//             url: url,
//             dataType: "json",
//             data: data,
//             'Content-Type':'application/x-www-form-urlencoded',
//             statusCode: {
//                 0: function () {
//                     // TEMP: CORS ERROR is returning a 401 but data is still getting passed through. Always return a success
//                     // window.location.href = "../volunteer";
//                     console.log("someothing")
//                 },
//                 200: function () {
//                     console.log("uuuuuuuuuuu")
//                 }
//             }
//         });
//     });
// }
<commit_msg>drafted new pop up message on contact page<commit_after>
$(document).ready(function () {
  $("#contact-form-submit").prop("disabled",true);
    $("#contact-form-submit").click(function(){
      console.log("1")
      var contactFirst= $("#contact-first").val();
      var contactLast= $("#contact-last").val();
      var contactMessage= $("#contact-message").val();
      var contactPhone= $("#contact-phone").val();
      var contactEmail= $("#contact-email").val();
      emailjs.send("gmail","template_UPluqtLC",{firstname: contactFirst, lastname:contactLast,  message: contactMessage, phonenumber: contactPhone, email: contactEmail});
      console.log("2")
      alert("Thank you for your message, I'll be recieving your email shortly!");
      $("#contact_form")[0].reset();
    });
});

function enableBtn(){
  $("#contact-form-submit").prop("disabled",false);
}
//
//
//
// function submitContactForm() {
//
//     $('#contact-form-submit').on("click",function (e) {
//         e.preventDefault();
//         var contactFirst = $('#contact-first').val();
//         var contactLast = $('#contact-last').val();
//         var contactEmail = $('#contact-email').val();
//         var contactPhone = $('#contact-phone').val();
//         var contactMessage = $('#contact-message').val();
//
//         var url = "//docs.google.com/forms/d/e/1FAIpQLScq4L1Ri9teYVCUM88wYZWStatmKvAe49VLimhOlgiD3mxgYQ/viewform#responses";
//
//         var data = {
//             'entry.2005620554': contactFirst,
//             'entry.834360636': contactLast,
//             'entry.1045781291': contactEmail,
//             'entry.1166974658': contactPhone,
//             'entry.839337160': contactMessage
//         };
//         console.log(contactPhone)
//         $.ajax({
//             type: "POST",
//             url: url,
//             dataType: "json",
//             data: data,
//             'Content-Type':'application/x-www-form-urlencoded',
//             statusCode: {
//                 0: function () {
//                     // TEMP: CORS ERROR is returning a 401 but data is still getting passed through. Always return a success
//                     // window.location.href = "../volunteer";
//                     console.log("someothing")
//                 },
//                 200: function () {
//                     console.log("uuuuuuuuuuu")
//                 }
//             }
//         });
//     });
// }
<|endoftext|>


<commit_before>'use strict';

const {
    run,
    series,
    parallel,
} = require('madrun');

const {version} = require('./package');

const dirs = [
    'bin/cloudcmd.js',
    'common',
    'server',
].join(' ');

const dirsTest = [
    'test',
    'bin/release.js',
    'webpack.config.js',
    'cssnano.config.js',
    '.webpack',
    'madrun.js',
    '{client,server,common}/**/*.spec.js',
].join(' ');

module.exports = {
    'start': () => 'node bin/cloudcmd.js',
    'start:dev': () => `NODE_ENV=development ${run('start')}`,
    'build:start': () => series(['build:client', 'start']),
    'build:start:dev': () => series(['build:client:dev', 'start:dev']),
    'lint': () => series(['putout', 'lint:*', 'spell']),
    'lint:server': () => `eslint -c .eslintrc.server ${dirs} --ignore-pattern *.spec.js`,
    'lint:test': () => `eslint --ignore-pattern '!.*' ${dirsTest}`,
    'lint:client': () => 'eslint --env browser client',
    'lint:css': () => 'stylelint css/*.css',
    'spell': () => 'yaspeller .',
    'fix:lint': () => series(['putout', 'lint:*'], '--fix'),
    'test': () => `tape 'test/**/*.js' '{client,common,server}/**/*.spec.js'`,
    'test:client': () => `tape 'test/client/**/*.js`,
    'test:server': () => `tape 'test/**/*.js' 'server/**/*.spec.js' 'common/**/*.spec.js'`,
    'wisdom': () => series(['lint', 'build', 'test']),
    'wisdom:type': () => 'bin/release.js',
    'docker:pull:node': () => 'docker pull node',
    'docker:pull:alpine': () => 'docker pull mhart/alpine-node',
    'docker:push': () => `docker push coderaiser/cloudcmd:${version}`,
    'docker:push:latest': () => 'docker push coderaiser/cloudcmd:latest',
    'docker:push:alpine': () => `docker push coderaiser/cloudcmd:${version}-alpine`,
    'docker:push:alpine:latest': () => 'docker push coderaiser/cloudcmd:latest-alpine',
    'docker:build': () => `docker build -t coderaiser/cloudcmd:${version} .`,
    'docker:build:alpine': () => `docker build -f Dockerfile.alpine -t coderaiser/cloudcmd:${version}-alpine .`,
    'docker': () => series(['docker:pull*', 'docker:build*', 'docker:tag*', 'docker:push*']),
    'docker-ci': () => series(['build', 'docker-login', 'docker']),
    'docker-login': () => 'docker login -u $DOCKER_USERNAME -p $DOCKER_PASSWORD',
    'docker:alpine': () => series([
        'docker:pull:alpine',
        'docker:build:alpine',
        'docker:tag:alpine',
        'docker:push:alpine',
        'docker:push:alpine:latest',
    ]),
    'docker:tag': () => `docker tag coderaiser/cloudcmd:${version} coderaiser/cloudcmd:latest`,
    'docker:tag:alpine': () => `docker tag coderaiser/cloudcmd:${version}-alpine coderaiser/cloudcmd:latest-alpine`,
    'docker:rm:version': () => `docker rmi -f coderaiser/cloudcmd:${version}`,
    'docker:rm:latest': () => 'docker rmi -f coderaiser/cloudcmd:latest',
    'docker:rm:alpine': () => `docker rmi -f coderaiser/cloudcmd:${version}-alpine`,
    'docker:rm:latest-alpine': () => 'docker rmi -f coderaiser/cloudcmd:latest-alpine',
    'docker:rm-old': () => `${parallel('docker:rm:*')} || true`,
    'coverage': () => `nyc ${run('test')}`,
    'report': () => 'nyc report --reporter=text-lcov | coveralls',
    '6to5': () => 'webpack --progress',
    '6to5:client': () => run('6to5', '--mode production'),
    '6to5:client:dev': () => `NODE_ENV=development ${run('6to5', '--progress --mode development')}`,
    'pre6to5:client': () => 'rimraf dist',
    'pre6to5:client:dev': () => 'rimraf dist-dev',
    'watch:client': () => run('6to5:client','--watch'),
    'watch:client:dev': () => run('6to5:client:dev', '--watch'),
    'watch:server': () => 'nodemon bin/cloudcmd.js',
    'watch:lint': () => `nodemon -w client -w server -w webpack.config.js -x ${series(['lint:client', 'lint:server'])}`,
    'watch:lint:client': () => `nodemon -w client -w webpack.config.js -x ${run('lint:client')}`,
    'watch:lint:server': () => `nodemon -w server -w common -x ${run('lint:server')}`,
    'watch:test': () => `nodemon -w client -w server -w test -w common -x ${run('test')}`,
    'watch:test:client': () => `nodemon -w client -w test/client -x ${run('test:client')}`,
    'watch:test:server': () => `nodemon -w client -w test/client -x ${run('test:server')}`,
    'watch:coverage': () => `nodemon -w server -w test -w common -x ${run('coverage')}`,
    'build': () => run('6to5:*'),
    'build:client': () => run('6to5:client'),
    'build:client:dev': () => run('6to5:client:dev'),
    'heroku-postbuild': () => run('6to5:client'),
    'putout': () => 'putout bin client server common test',
};

<commit_msg>chore(madrun) series -> run<commit_after>'use strict';

const {
    run,
    parallel
} = require('madrun');

const {version} = require('./package');

const dirs = [
    'bin/cloudcmd.js',
    'common',
    'server',
].join(' ');

const dirsTest = [
    'test',
    'bin/release.js',
    'webpack.config.js',
    'cssnano.config.js',
    '.webpack',
    'madrun.js',
    '{client,server,common}/**/*.spec.js',
].join(' ');

module.exports = {
    'start': () => 'node bin/cloudcmd.js',
    'start:dev': () => `NODE_ENV=development ${run('start')}`,
    'build:start': () => run(['build:client', 'start']),
    'build:start:dev': () => run(['build:client:dev', 'start:dev']),
    'lint': () => run(['putout', 'lint:*', 'spell']),
    'lint:server': () => `eslint -c .eslintrc.server ${dirs} --ignore-pattern *.spec.js`,
    'lint:test': () => `eslint --ignore-pattern '!.*' ${dirsTest}`,
    'lint:client': () => 'eslint --env browser client',
    'lint:css': () => 'stylelint css/*.css',
    'spell': () => 'yaspeller .',
    'fix:lint': () => run(['putout', 'lint:*'], '--fix'),
    'test': () => `tape 'test/**/*.js' '{client,common,server}/**/*.spec.js'`,
    'test:client': () => `tape 'test/client/**/*.js`,
    'test:server': () => `tape 'test/**/*.js' 'server/**/*.spec.js' 'common/**/*.spec.js'`,
    'wisdom': () => run(['lint', 'build', 'test']),
    'wisdom:type': () => 'bin/release.js',
    'docker:pull:node': () => 'docker pull node',
    'docker:pull:alpine': () => 'docker pull mhart/alpine-node',
    'docker:push': () => `docker push coderaiser/cloudcmd:${version}`,
    'docker:push:latest': () => 'docker push coderaiser/cloudcmd:latest',
    'docker:push:alpine': () => `docker push coderaiser/cloudcmd:${version}-alpine`,
    'docker:push:alpine:latest': () => 'docker push coderaiser/cloudcmd:latest-alpine',
    'docker:build': () => `docker build -t coderaiser/cloudcmd:${version} .`,
    'docker:build:alpine': () => `docker build -f Dockerfile.alpine -t coderaiser/cloudcmd:${version}-alpine .`,
    'docker': () => run(['docker:pull*', 'docker:build*', 'docker:tag*', 'docker:push*']),
    'docker-ci': () => run(['build', 'docker-login', 'docker']),
    'docker-login': () => 'docker login -u $DOCKER_USERNAME -p $DOCKER_PASSWORD',
    'docker:alpine': () => run([
        'docker:pull:alpine',
        'docker:build:alpine',
        'docker:tag:alpine',
        'docker:push:alpine',
        'docker:push:alpine:latest',
    ]),
    'docker:tag': () => `docker tag coderaiser/cloudcmd:${version} coderaiser/cloudcmd:latest`,
    'docker:tag:alpine': () => `docker tag coderaiser/cloudcmd:${version}-alpine coderaiser/cloudcmd:latest-alpine`,
    'docker:rm:version': () => `docker rmi -f coderaiser/cloudcmd:${version}`,
    'docker:rm:latest': () => 'docker rmi -f coderaiser/cloudcmd:latest',
    'docker:rm:alpine': () => `docker rmi -f coderaiser/cloudcmd:${version}-alpine`,
    'docker:rm:latest-alpine': () => 'docker rmi -f coderaiser/cloudcmd:latest-alpine',
    'docker:rm-old': () => `${parallel('docker:rm:*')} || true`,
    'coverage': () => `nyc ${run('test')}`,
    'report': () => 'nyc report --reporter=text-lcov | coveralls',
    '6to5': () => 'webpack --progress',
    '6to5:client': () => run('6to5', '--mode production'),
    '6to5:client:dev': () => `NODE_ENV=development ${run('6to5', '--progress --mode development')}`,
    'pre6to5:client': () => 'rimraf dist',
    'pre6to5:client:dev': () => 'rimraf dist-dev',
    'watch:client': () => run('6to5:client','--watch'),
    'watch:client:dev': () => run('6to5:client:dev', '--watch'),
    'watch:server': () => 'nodemon bin/cloudcmd.js',
    'watch:lint': () => `nodemon -w client -w server -w webpack.config.js -x ${run(['lint:client', 'lint:server'])}`,
    'watch:lint:client': () => `nodemon -w client -w webpack.config.js -x ${run('lint:client')}`,
    'watch:lint:server': () => `nodemon -w server -w common -x ${run('lint:server')}`,
    'watch:test': () => `nodemon -w client -w server -w test -w common -x ${run('test')}`,
    'watch:test:client': () => `nodemon -w client -w test/client -x ${run('test:client')}`,
    'watch:test:server': () => `nodemon -w client -w test/client -x ${run('test:server')}`,
    'watch:coverage': () => `nodemon -w server -w test -w common -x ${run('coverage')}`,
    'build': () => run('6to5:*'),
    'build:client': () => run('6to5:client'),
    'build:client:dev': () => run('6to5:client:dev'),
    'heroku-postbuild': () => run('6to5:client'),
    'putout': () => 'putout bin client server common test',
};

<|endoftext|>


<commit_before>
define(function(require, exports, module) {

// TODO: Move this out of here
require("pilot/fixoldbrowsers");

var CANON = require("pilot/canon");
var EDITOR = require("ace/editor").Editor;
var RENDERER = require("ace/virtual_renderer").VirtualRenderer;
var THEME_TEXTMATE = require("ace/theme/textmate");

Ext.ux.AceEditor = Ext.extend(Ext.BoxComponent, {

    initComponent: function() {
        Ext.ux.AceEditor.superclass.initComponent.call(this);
        var self = this;

        self.value = null;

        self.addEvents(
            "editor-save",
            "editor-saveas"
        );
        CANON.addCommand({
            name: "save",
            exec: function(env, args, request) {
                self.fireEvent('editor-save', self);
            }
        });
        CANON.addCommand({
            name: "saveas",
            exec: function(env, args, request) {
                self.fireEvent('editor-saveas', self);
            }
        });
    },

    onRender: function() {
        Ext.BoxComponent.superclass.onRender.apply(this, arguments);

        this.editor = new EDITOR(new RENDERER(this.el.dom, THEME_TEXTMATE));
        this.editor.resize();

        if(this.value!==null) {
            this.setValue(this.value[0], this.value[1]);
        }

        var self = this;
        this.editor.getDocument().addEventListener("changeDelta", function() {
            self.fireEvent('editor-changeDelta', self);
        });
    },

    onResize: function( aw, ah ){
        if(this.editor) {
            this.editor.resize();
        }
    },

    getValue: function() {
        return this.editor.getDocument().getValue();
    },

    setValue: function(value, options) {
        if(!this.editor) {
            this.value = [value, options];
            return;
        }
        this.value = null;

        options = options || {};

        var doc = this.editor.getDocument(),
            ext,
            mode;

        if(typeof options.basename != "undefined" && (ext = options.basename.match(/\.([\w]+)$/))) {
            switch(ext[1]) {
                case "xml":
                case "xhtml":
                case "rdf":
                    mode = require("ace/mode/xml").Mode;
                    break;
                case "htm":
                case "html":
                    mode = require("ace/mode/html").Mode;
                    break;
                case "js":
                case "json":
                    mode = require("ace/mode/javascript").Mode;
                    break;
                case "css":
                    mode = require("ace/mode/css").Mode;
                    break;
                case "py":
                    mode = require("ace/mode/python").Mode;
                    break;
                case "php":
                    mode = require("ace/mode/php").Mode;
                    break;
                default:
                    mode = require("ace/mode/text").Mode;
                    break;
            }
        } else {
            mode = require("ace/mode/text").Mode;
        }
        doc.setMode(new mode());
        doc.setValue(value);
    }
});

});<commit_msg>removed extjs wrapper<commit_after><|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 () {
  console.log("draw marker" , this.collision_group);
  this.collision_group.onAdd(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);
    //this.marker_collision_group.push(marker);
};

module.exports.drawRouteAmigo = function(legs,mode) {
    console.log("mode ->", mode);
    console.log("color ->",legs.routeColor);
    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
        };

      console.log("color ruta ->" , color);
      route = new L.Polyline(L.PolylineUtil.decode(route, 5), color_options);
      this.polyline_creadas.push(route);
      var boxes = L.RouteBoxer.box(route, 5);
      var boxpolys = new Array(boxes.length);
      route.addTo(this.activeMap);
      //var collision_group = L.layerGroup.collision({margin:5});
      //collision_group.addLayer(this.marker_collision_group);
      //collision_group.onAdd(this.activeMap);
      //this.collision_group = collision_group;
      //this.activeMap.fitBounds(bounds);
};

<commit_msg>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 () {
  console.log("draw marker" , this.collision_group);
  this.collision_group.onAdd(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);
    //this.marker_collision_group.push(marker);
};

module.exports.drawRouteAmigo = function(legs,mode) {
    console.log("mode ->", mode);
    console.log("color ->",legs.routeColor);
    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
        };

      console.log("polyline decode ->",L.PolylineUtil.decode(route, 5));
      console.log("color ruta ->" , color);
      route = new L.Polyline(L.PolylineUtil.decode(route, 5), color_options);
      this.polyline_creadas.push(route);
      var boxes = L.RouteBoxer.box(route, 5);
      var boxpolys = new Array(boxes.length);
      route.addTo(this.activeMap);
      //var collision_group = L.layerGroup.collision({margin:5});
      //collision_group.addLayer(this.marker_collision_group);
      //collision_group.onAdd(this.activeMap);
      //this.collision_group = collision_group;
      //this.activeMap.fitBounds(bounds);
};

<|endoftext|>


<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

// MODULES //

var logger = require( 'debug' );
var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive;
var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' ).primitives;

// VARIABLES //

var debug = logger( 'plot:set:line-width' );

// MAIN //

/**
* Sets the data line width(s).
*
* @private
* @param {(NonNegativeInteger|Array<NonNegativeInteger>)} v - width
* @throws {TypeError} must be a nonnegative integer or nonnegative integer array
* @returns {void}
*/
function set( v ) {
	/* eslint-disable no-invalid-this */
	var isInt = isNonNegativeInteger( v );
	if (
		!isInt &&
		!isNonNegativeIntegerArray( v )
	) {
		throw new TypeError( 'invalid value. `lineWidth` must be a nonnegative integer or nonnegative integer array. Value: `' + v + '.`' );
	}
	if ( isInt ) {
		v = [ v ];
	} else {
		v = v.slice();
	}
	debug( 'Current value: %d.', this._lineWidth );

	this._lineWidth = v;
	debug( 'New Value: %d.', this._lineWidth );

	this.emit( 'change' );
}

// EXPORTS //

module.exports = set;
<commit_msg>Fix logging<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

// MODULES //

var logger = require( 'debug' );
var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive;
var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' ).primitives;

// VARIABLES //

var debug = logger( 'plot:set:line-width' );

// MAIN //

/**
* Sets the data line width(s).
*
* @private
* @param {(NonNegativeInteger|Array<NonNegativeInteger>)} v - width
* @throws {TypeError} must be a nonnegative integer or nonnegative integer array
* @returns {void}
*/
function set( v ) {
	/* eslint-disable no-invalid-this */
	var isInt = isNonNegativeInteger( v );
	if (
		!isInt &&
		!isNonNegativeIntegerArray( v )
	) {
		throw new TypeError( 'invalid value. `lineWidth` must be a nonnegative integer or nonnegative integer array. Value: `' + v + '.`' );
	}
	if ( isInt ) {
		v = [ v ];
	} else {
		v = v.slice();
	}
	debug( 'Current value: %s.', JSON.stringify( this._lineWidth ) );

	this._lineWidth = v;
	debug( 'New Value: %s.', JSON.stringify( this._lineWidth ) );

	this.emit( 'change' );
}

// EXPORTS //

module.exports = set;
<|endoftext|>