<commit_before>/**
 * List
 * @constructor
*/
function _List(){
  this.vue = new App.Vue({
    el: '.list',
    data: {
      tabs: [
        {
          name: 'Torrents',
          id: 'torrents',
          state: false,
          columns: [
            'name',
            'size',
            'progress',
            'up',
            'down'
          ]
        },
        {
          name: 'Directories',
          id: 'directories',
          state: true,
          columns: [
            'name',
            'size',
            'date',
            'owner'
          ]
        }
      ],
      columns: [
        {
          name: 'Name',
          id: 'name',
          important: true,
          state: ''
        },
        {
          name: 'Size',
          id: 'size',
          important: true,
          state: ''
        },
        {
          name: 'Date',
          id: 'date',
          state: ''
        },
        {
          name: 'Owner',
          id: 'owner',
          state: ''
        },
        {
          name: 'Progress',
          id: 'progress',
          state: 'hide'
        },
        {
          name: 'Up',
          id: 'up',
          state: 'hide'
        },
        {
          name: 'Down',
          id: 'down',
          state: 'hide'
        }
      ],
      lines: []
    }
  })
}

/**
 * Switch between all tables
 * @param {string} tabId - Id of the table
*/
_List.prototype.switchTab = function(tabId){
  var self = this
  for(var t in this.vue.$data.tabs){
    var tab = this.vue.$data.tabs[t]

    if(tab.id === tabId){
      tab.state = true
      for(var c in this.vue.$data.columns){
        var column = this.vue.$data.columns[c]

        if(tab.columns.indexOf(column.id) !== -1){
          column.state = ''
        }
      }
    } else {
      tab.state = false
      for(var c in this.vue.$data.columns){
        var column = this.vue.$data.columns[c]

        if(tab.columns.indexOf(column.id) !== -1 && !column.important){
          column.state = 'hide'
        }
      }
    }
  }
}

/**
 * Add lines to table
 * @param {object} line - Line to add
*/
_List.prototype.addLine = function(line){
  this.vue.$data.lines.push(line)
}

/**
 * Remove lines to table
 * @param {object} line - Line to remove
*/
_List.prototype.removeLine = function(line){
  for(var l in this.vue.$data.lines){
    if(this.vue.$data.lines[l].name === line.name){
      this.vue.$data.lines.splice(l, 1)
      return
    }
  }
}

/**
 * Clear all lines into the table
*/
_List.prototype.clearLines = function(){
  this.vue.$data.lines = []
}

/**
 * Update all lines into the table
 * And remove absent lines
*/
_List.prototype.updateLines = function(lines){
   var self = this
  $.each(lines, function(index, value){

    var li = $.indexOfO(self.vue.$data.lines, function(e){ return e.name === value.name })
    if(li !== -1){
      var line = self.vue.$data.lines[li]
      $.each(value, function(i, v){
        line[i] = v
      })
    } else {
      self.addLine(value)
    }
  })

  var vueLines = self.vue.$data.lines.slice(0)
  for(var key in vueLines){
    console.log(key)
    var line = vueLines[key]
    var li = $.indexOfO(lines, function(e){ return e.name === line.name })
    if(li === -1){
      self.removeLine(line)
    }
  }
}

_List.prototype.sortLines = function(by, direction){
  var dir = direction === 'asc' ? -1 : 1
  if(typeof this.vue.$data.lines[0][by] !== 'undefined'){
    this.vue.$data.lines.sort(function(a, b){
      if(a[by] < b[by]){
        return dir
      } else if (a[by] > b[by]){
        return -dir
      } else {
        return 0
      }
    })
  }
}

App.List = new _List()
<commit_msg>add sort on click<commit_after>/**
 * List
 * @constructor
*/
function _List(){
  var self = this
  this.vue = new App.Vue({
    el: '.list',
    data: {
      tabs: [
        {
          name: 'Torrents',
          id: 'torrents',
          state: false,
          columns: [
            'name',
            'size',
            'progress',
            'up',
            'down'
          ]
        },
        {
          name: 'Directories',
          id: 'directories',
          state: true,
          columns: [
            'name',
            'size',
            'date',
            'owner'
          ]
        }
      ],
      columns: [
        {
          name: 'Name',
          id: 'name',
          important: true,
          state: '',
          sort: 'asc'
        },
        {
          name: 'Size',
          id: 'size',
          important: true,
          state: '',
          sort: 'asc'
        },
        {
          name: 'Date',
          id: 'date',
          state: '',
          sort: 'asc'
        },
        {
          name: 'Owner',
          id: 'owner',
          state: '',
          sort: 'asc'
        },
        {
          name: 'Progress',
          id: 'progress',
          state: 'hide',
          sort: 'asc'
        },
        {
          name: 'Up',
          id: 'up',
          state: 'hide',
          sort: 'asc'
        },
        {
          name: 'Down',
          id: 'down',
          state: 'hide',
          sort: 'asc'
        }
      ],
      lines: []
    }
  })

  $('.list').on('click', 'th', function(){
    var clickedColumn = $(this)
    var col = self.vue.$data.columns[$.indexOfO(self.vue.$data.columns, function(e){ return e.id === clickedColumn.attr('id') })]
    if(col.sort === 'asc'){
      col.sort = 'desc'
    } else {
      col.sort = 'asc'
    }
    self.sortLines(col.id, col.sort)
  })
}

/**
 * Switch between all tables
 * @param {string} tabId - Id of the table
*/
_List.prototype.switchTab = function(tabId){
  var self = this
  for(var t in this.vue.$data.tabs){
    var tab = this.vue.$data.tabs[t]

    if(tab.id === tabId){
      tab.state = true
      for(var c in this.vue.$data.columns){
        var column = this.vue.$data.columns[c]

        if(tab.columns.indexOf(column.id) !== -1){
          column.state = ''
        }
      }
    } else {
      tab.state = false
      for(var c in this.vue.$data.columns){
        var column = this.vue.$data.columns[c]

        if(tab.columns.indexOf(column.id) !== -1 && !column.important){
          column.state = 'hide'
        }
      }
    }
  }
}

/**
 * Add lines to table
 * @param {object} line - Line to add
*/
_List.prototype.addLine = function(line){
  this.vue.$data.lines.push(line)
}

/**
 * Remove lines to table
 * @param {object} line - Line to remove
*/
_List.prototype.removeLine = function(line){
  for(var l in this.vue.$data.lines){
    if(this.vue.$data.lines[l].name === line.name){
      this.vue.$data.lines.splice(l, 1)
      return
    }
  }
}

/**
 * Clear all lines into the table
*/
_List.prototype.clearLines = function(){
  this.vue.$data.lines = []
}

/**
 * Update all lines into the table
 * And remove absent lines
*/
_List.prototype.updateLines = function(lines){
   var self = this

   //updates lines
  $.each(lines, function(index, value){
    var li = $.indexOfO(self.vue.$data.lines, function(e){ return e.name === value.name })
    if(li !== -1){
      var line = self.vue.$data.lines[li]
      $.each(value, function(i, v){
        line[i] = v
      })
    } else {
      self.addLine(value)
    }
  })

  //remove old lines
  var vueLines = self.vue.$data.lines.slice(0)
  for(var key in vueLines){
    var line = vueLines[key]
    var li = $.indexOfO(lines, function(e){ return e.name === line.name })
    if(li === -1){
      self.removeLine(line)
    }
  }
}

_List.prototype.sortLines = function(by, direction){
  var dir = direction === 'asc' ? -1 : 1
  if(typeof this.vue.$data.lines[0][by] !== 'undefined'){
    this.vue.$data.lines.sort(function(a, b){
      if(a[by] < b[by]){
        return dir
      } else if (a[by] > b[by]){
        return -dir
      } else {
        return 0
      }
    })
  }
}

App.List = new _List()
<|endoftext|>


<commit_before>// Update with your config settings.
require('dotenv').config();

module.exports = {
  development: {
    client: 'pg',
    //connection: 'postgres://localhost/microlens'
    connection: process.env.DATABASE_URL
  },
  production: {
    client: 'pg',
    connection: process.env.DATABASE_URL
}

}
<commit_msg>modified db connection<commit_after>// Update with your config settings.
require('dotenv').config({silent:true});

module.exports = {
  development: {
   client: 'pg',
   connection: process.env.DATABASE_URL || 'postgres://localhost:5432/mycro'
 },
 production: {
   client: 'pg',
   connection: process.env.DATABASE_URL
 }
};
<|endoftext|>


<commit_before>describe('Simple Agent', function() {
    it('should exist', function() {
	expect(SimpleAgent).toBeDefined();
    });
    it('should be instantiated', function() {
	expect(new SimpleAgent()).toBeDefined();
    });

    it('should be able to ask a problemSystem for possibilities in that systems world', function() {
	var problemMock = {};
	    problemMock.getPossibleActions = function() {
		return [{state: {x: 0}, action: "left"},
			{state: {x: 2}, action: "right"}
		       ];
	    }

	var a = new SimpleAgent(problemMock);
	expect(a.getPossibleActions()).toEqual(problemMock.getPossibleActions());
    });

     describe('should choose an action from possible states using some solver', function() {
	 it('case1: mock returns first state', function() {
	     var problemMock = {};
	     problemMock.getPossibleActions = function() {
		 return [{state: {x: 0}, action: "left"},
			 {state: {x: 2}, action: "right"}

			];
	     }

	     var solverMock = {};
	     solverMock.evaluate = function(states) {
		 return states[0];
	     }
	     var a = new SimpleAgent(problemMock, solverMock);
	     expect(a.chooseAction()).toEqual({state: {x: 0}, action: "left"});
	 });

	 it('case2: mock returns second state', function() {
	     var problemMock = {};
	     problemMock.getPossibleActions = function() {
		 return [{state: {x: 0}, action: "left"},
			 {state: {x: 2}, action: "right"}

			];
	     }

	     var solverMock = {};
	     solverMock.evaluate = function(states) {
		 return states[1];
	     }
	     var a = new SimpleAgent(problemMock, solverMock);
	     expect(a.chooseAction()).toEqual({state: {x: 2}, action: "right"});
	 });
	 it('case3: using an actual instantiation of a function approximator', function() {
	     var problemMock = {};
	     problemMock.getPossibleActions = function() {
		 return [{state: {x: 0}, action: "left"},
			 {state: {x: 2}, action: "right"}

			];
	     }

	     var nonexplorerfa = new FunctionApproximator(null,null,0,null);
	     nonexplorerfa.addValueFunction(
		 nonexplorerfa.createValueFunction(function(s) { return s.x; } )
	     );

	     var a = new SimpleAgent(problemMock, nonexplorerfa);
	     expect(a.chooseAction()).toEqual({state: {x: 2}, action: "right"});
	 });
     });
    it('should be instantiated with a tick of 0, meaning it hasnt done anything to manipulate the problem', function() {
	var sa = new SimpleAgent();
	expect(sa.getTicked()).toBe(0);
    });

    it('should ticked++ when an action is performed', function() {
	 var problemMock = {};
	     problemMock.tick = function() {}
	     problemMock.currentState = function() {return 0;}

	var sa = new SimpleAgent(problemMock);
	expect(sa.getTicked()).toBe(0);
	sa.performAction("left");
	expect(sa.getTicked()).toBe(1);

    })

    it('should know how many actions it performed', function() {
	 var problemMock = {
	     i: 0
	 };
	     problemMock.tick = function() {
		 this.i++;
	     }
	     problemMock.currentState = function() {
		 return {x: this.i};
	     }

	var sa = new SimpleAgent(problemMock);

	sa.performAction("right");
	expect(problemMock.i).toBe(1);
	expect(problemMock.currentState()).toEqual({x: 1});

	sa.performAction("right");
	expect(problemMock.i).toBe(2);
 	expect(problemMock.currentState()).toEqual({x: 2});

    });

    it('should keep a history of all its transitioned states', function() {
	var problemMock = {
	    i: 0
	};
	problemMock.tick = function() {
	    this.i++;
	}
	problemMock.currentState = function() {
	    return {x: this.i};
	}

	var sa = new SimpleAgent(problemMock);

	sa.performAction("right");
	sa.performAction("root");
	sa.performAction("right");

	expect(sa.history.length).toBe(3);
	expect(sa.history).toEqual( [{state: {x:0}, action: "right"}, {state: {x:1}, action: "root"}, {state: {x:2}, action: "right"}]);
    });

    it('should reeavaluate all weights for each of its chosen actions', function() {
	var problemMock = {
	    i: 0
	};
	problemMock.tick = function() {
	    this.i++;
	}
	problemMock.currentState = function() {
	    return {x: this.i};
	}

	var counter = 0;
	var solverMock = {};
	solverMock.evaluate = function(states) {
	    counter++;
	}
	var a = new SimpleAgent(problemMock, solverMock);

	a.performAction("right");
	a.performAction("root");
	a.performAction("right");

	a.reevaluateActions();
	expect(counter).toBe(3);
	a.performAction("right");
	a.performAction("root");
	a.performAction("right");

	a.reevaluateActions();
	expect(counter).toBe(6)
    });

});
<commit_msg>fixed spec<commit_after>describe('Simple Agent', function() {
    it('should exist', function() {
	expect(SimpleAgent).toBeDefined();
    });
    it('should be instantiated', function() {
	expect(new SimpleAgent()).toBeDefined();
    });

    it('should be able to ask a problemSystem for possibilities in that systems world', function() {
	var problemMock = {};
	    problemMock.getPossibleActions = function() {
		return [{state: {x: 0}, action: "left"},
			{state: {x: 2}, action: "right"}
		       ];
	    }

	var a = new SimpleAgent(problemMock);
	expect(a.getPossibleActions()).toEqual(problemMock.getPossibleActions());
    });

     describe('should choose an action from possible states using some solver', function() {
	 it('case1: mock returns first state', function() {
	     var problemMock = {};
	     problemMock.getPossibleActions = function() {
		 return [{state: {x: 0}, action: "left"},
			 {state: {x: 2}, action: "right"}

			];
	     }

	     var solverMock = {};
	     solverMock.evaluate = function(states) {
		 return states[0];
	     }
	     var a = new SimpleAgent(problemMock, solverMock);
	     expect(a.chooseAction()).toEqual({state: {x: 0}, action: "left"});
	 });

	 it('case2: mock returns second state', function() {
	     var problemMock = {};
	     problemMock.getPossibleActions = function() {
		 return [{state: {x: 0}, action: "left"},
			 {state: {x: 2}, action: "right"}

			];
	     }

	     var solverMock = {};
	     solverMock.evaluate = function(states) {
		 return states[1];
	     }
	     var a = new SimpleAgent(problemMock, solverMock);
	     expect(a.chooseAction()).toEqual({state: {x: 2}, action: "right"});
	 });
	 it('case3: using an actual instantiation of a function approximator', function() {
	     var problemMock = {};
	     problemMock.getPossibleActions = function() {
		 return [{state: {x: 0}, action: "left"},
			 {state: {x: 2}, action: "right"}

			];
	     }

	     var nonexplorerfa = new FunctionApproximator(null,null,0,null);
	     nonexplorerfa.addValueFunction(
		 nonexplorerfa.createValueFunction(function(s) { return s.x; } )
	     );

	     var a = new SimpleAgent(problemMock, nonexplorerfa);
	     expect(a.chooseAction()).toEqual({state: {x: 2}, action: "right"});
	 });
     });
    it('should be instantiated with a tick of 0, meaning it hasnt done anything to manipulate the problem', function() {
	var sa = new SimpleAgent();
	expect(sa.getTicked()).toBe(0);
    });

    it('should ticked++ when an action is performed', function() {
	 var problemMock = {};
	     problemMock.tick = function() {}
	     problemMock.currentState = function() {return 0;}

	var sa = new SimpleAgent(problemMock);
	expect(sa.getTicked()).toBe(0);
	sa.performAction("left");
	expect(sa.getTicked()).toBe(1);

    })

    it('should know how many actions it performed', function() {
	 var problemMock = {
	     i: 0
	 };
	     problemMock.tick = function() {
		 this.i++;
	     }
	     problemMock.currentState = function() {
		 return {x: this.i};
	     }

	var sa = new SimpleAgent(problemMock);

	sa.performAction("right");
	expect(problemMock.i).toBe(1);
	expect(problemMock.currentState()).toEqual({x: 1});

	sa.performAction("right");
	expect(problemMock.i).toBe(2);
 	expect(problemMock.currentState()).toEqual({x: 2});

    });

    it('should keep a history of all its transitioned states', function() {
	var problemMock = {
	    i: 0
	};
	problemMock.tick = function() {
	    this.i++;
	}
	problemMock.currentState = function() {
	    return {x: this.i};
	}

	var sa = new SimpleAgent(problemMock);

	sa.performAction("right");
	sa.performAction("root");
	sa.performAction("right");

	expect(sa.history.length).toBe(3);
	expect(sa.history).toEqual( [{state: {x:0}, action: "right"}, {state: {x:1}, action: "root"}, {state: {x:2}, action: "right"}]);
    });

    it('should reeavaluate all weights for each of its chosen actions', function() {
	var problemMock = {
	    i: 0
	};
	problemMock.tick = function() {
	    this.i++;
	}
	problemMock.currentState = function() {
	    return {x: this.i};
	}

	var counter = 0;
	var solverMock = {};

	solverMock.correct = function() {
	    counter++;
	}
	var a = new SimpleAgent(problemMock, solverMock);

	a.performAction("right");
	a.performAction("root");
	a.performAction("right");

	a.reevaluateActions();
	expect(counter).toBe(3);
	a.performAction("right");
	a.performAction("root");
	a.performAction("right");

	a.reevaluateActions();
	expect(counter).toBe(6)
    });

});
<|endoftext|>


<commit_before>(function(app) {
  'use strict';

  var helper = app.helper || require('../helper.js');

  var ModuleUnit = function(props) {
    this.module = props.module;
    this.port = props.port;
  };

  ModuleUnit.prototype.equal = function(other) {
    return Object.keys(this).every(function(key) {
      return helper.equal(this[key], other[key]);
    }.bind(this));
  };

  ModuleUnit.prototype.portType = function() {
    return this.port.type();
  };

  ModuleUnit.prototype.portSocketConnected = function(value) {
    return this.port.socketConnected(value);
  };

  ModuleUnit.prototype.circuitElementMember = function() {
    return this.module.circuitElementMember(this.port.name());
  };

  ModuleUnit.prototype.plugPosition = function() {
    return this.module.plugPosition(this.port);
  };

  ModuleUnit.prototype.socketPosition = function() {
    return this.module.socketPosition(this.port);
  };

  ModuleUnit.prototype.addRelation = function(relation) {
    this.module.relations().push(relation);
    this.port.relations().push(relation);
  };

  ModuleUnit.prototype.removeRelation = function(relation) {
    helper.remove(this.module.relations(), relation);
    helper.remove(this.port.relations(), relation);
  };

  if (typeof module !== 'undefined' && module.exports)
    module.exports = ModuleUnit;
  else
    app.ModuleUnit = ModuleUnit;
})(this.app || (this.app = {}));
<commit_msg>Add method to get/set the visibility of the port of module-unit<commit_after>(function(app) {
  'use strict';

  var helper = app.helper || require('../helper.js');

  var ModuleUnit = function(props) {
    this.module = props.module;
    this.port = props.port;
  };

  ModuleUnit.prototype.equal = function(other) {
    return Object.keys(this).every(function(key) {
      return helper.equal(this[key], other[key]);
    }.bind(this));
  };

  ModuleUnit.prototype.portType = function() {
    return this.port.type();
  };

  ModuleUnit.prototype.portVisible = function(value) {
    return this.port.visible(value);
  };

  ModuleUnit.prototype.portSocketConnected = function(value) {
    return this.port.socketConnected(value);
  };

  ModuleUnit.prototype.circuitElementMember = function() {
    return this.module.circuitElementMember(this.port.name());
  };

  ModuleUnit.prototype.plugPosition = function() {
    return this.module.plugPosition(this.port);
  };

  ModuleUnit.prototype.socketPosition = function() {
    return this.module.socketPosition(this.port);
  };

  ModuleUnit.prototype.addRelation = function(relation) {
    this.module.relations().push(relation);
    this.port.relations().push(relation);
  };

  ModuleUnit.prototype.removeRelation = function(relation) {
    helper.remove(this.module.relations(), relation);
    helper.remove(this.port.relations(), relation);
  };

  if (typeof module !== 'undefined' && module.exports)
    module.exports = ModuleUnit;
  else
    app.ModuleUnit = ModuleUnit;
})(this.app || (this.app = {}));
<|endoftext|>


<commit_before>var LON = '2.428462';
var LAT = '46.538192';

function initCarto() {
  OSM = L.tileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
    attribution: '© OpenStreetMap'
  });

  position = get_position() || default_gestionnaire_position();

  map = L.map("map", {
    center: new L.LatLng(position.lat, position.lon),
    zoom: position.zoom,
    layers: [OSM],
    scrollWheelZoom: false
  });

  icon = L.icon({
    iconUrl: '/assets/marker-icon.png',
    //shadowUrl: 'leaf-shadow.png',

    iconSize: [34.48, 40], // size of the icon
    //shadowSize:   [50, 64], // size of the shadow
    iconAnchor: [20, 20] // point of the icon which will correspond to marker's location
    //shadowAnchor: [4, 62],  // the same for the shadow
    //popupAnchor:  [-3, -76] // point from which the popup should open relative to the iconAnchor
  });

  if (qp_active())
    display_qp(JSON.parse($("#quartier_prioritaires").val()));

  if (cadastre_active())
    display_cadastre(JSON.parse($("#cadastres").val()));

  freeDraw = new L.FreeDraw();
  freeDraw.options.setSmoothFactor(4);
  freeDraw.options.simplifyPolygon = false;

  map.addLayer(freeDraw);

  if ($("#json_latlngs").val() != '' && $("#json_latlngs").val() != '[]') {
    map.setZoom(18);

    $.each($.parseJSON($("#json_latlngs").val()), function (i, val) {
      freeDraw.createPolygon(val);
    });

    map.fitBounds(freeDraw.polygons[0].getBounds());
  }
  else if (position.lat == LAT && position.lon == LON)
    map.setView(new L.LatLng(position.lat, position.lon), position.zoom);

  add_event_freeDraw();
  add_event_search_address();
}

function default_gestionnaire_position() {
  return {lon: LON, lat: LAT, zoom: 5}
}

function get_external_data(latLngs) {
  if (qp_active())
    display_qp(get_qp(latLngs));

  if (cadastre_active()) {
    polygons = {"type": "FeatureCollection", "features": []};

    for (i = 0; i < latLngs.length; i++)
      polygons.features.push(feature_polygon_latLngs(latLngs[i]))

    cadastre_list = [{zoom_error: true}];

    if (turf_area(polygons) < 300000)
      cadastre_list = get_cadastre(latLngs);

    display_cadastre(cadastre_list);
  }
}

function feature_polygon_latLngs(coordinates) {
  return ({
    "type": "Feature",
    "properties": {},
    "geometry": {
      "type": "Polygon",
      "coordinates": [
        JSON.parse(L.FreeDraw.Utilities.getJsonPolygons([coordinates]))['latLngs']
      ]
    }
  })
}

function add_event_freeDraw() {
  freeDraw.on('markers', function (e) {
    $("#json_latlngs").val(JSON.stringify(e.latLngs));

    add_event_edit();

    get_external_data(e.latLngs);
  });

  $("#map").on('click', function(){
    freeDraw.setMode(L.FreeDraw.MODES.VIEW);
  });

  $("#new").on('click', function (e) {
    freeDraw.setMode(L.FreeDraw.MODES.CREATE);
  });

  $("#delete").on('click', function (e) {
    freeDraw.setMode(L.FreeDraw.MODES.DELETE);
  });
}

function add_event_edit (){
  $(".leaflet-container g path").on('click', function (e) {
    setTimeout(function(){freeDraw.setMode(L.FreeDraw.MODES.EDIT | L.FreeDraw.MODES.DELETE)}, 50);
  });
}

function get_position() {
  var position;

  $.ajax({
    url: '/users/dossiers/' + dossier_id + '/carte/position',
    dataType: 'json',
    async: false
  }).done(function (data) {
    position = data
  });

  return position;
}

function get_address_point(request) {
  $.ajax({
    url: '/ban/address_point?request=' + request,
    dataType: 'json',
    async: true
  }).done(function (data) {
    if (data.lat != null) {
      map.setView(new L.LatLng(data.lat, data.lon), data.zoom);
      //L.marker([data.lat, data.lon], {icon: icon}).addTo(map);
    }
  });
}

function jsObject_to_array(qp_list) {
  return Object.keys(qp_list).map(function (v) {
    return qp_list[v];
  });
}

function add_event_search_address() {
  $("#search-by-address input[type='address']").bind('typeahead:select', function (ev, seggestion) {
    get_address_point(seggestion['label']);
  });

  $("#search-by-address input[type='address']").keypress(function (e) {
    if (e.keyCode == 13)
      get_address_point($(this).val());
  });
}
<commit_msg>[fix #1047] Fix encoding problem in carto with IE<commit_after>var LON = '2.428462';
var LAT = '46.538192';

function initCarto() {
  OSM = L.tileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
    attribution: '© OpenStreetMap'
  });

  position = get_position() || default_gestionnaire_position();

  map = L.map("map", {
    center: new L.LatLng(position.lat, position.lon),
    zoom: position.zoom,
    layers: [OSM],
    scrollWheelZoom: false
  });

  icon = L.icon({
    iconUrl: '/assets/marker-icon.png',
    //shadowUrl: 'leaf-shadow.png',

    iconSize: [34.48, 40], // size of the icon
    //shadowSize:   [50, 64], // size of the shadow
    iconAnchor: [20, 20] // point of the icon which will correspond to marker's location
    //shadowAnchor: [4, 62],  // the same for the shadow
    //popupAnchor:  [-3, -76] // point from which the popup should open relative to the iconAnchor
  });

  if (qp_active())
    display_qp(JSON.parse($("#quartier_prioritaires").val()));

  if (cadastre_active())
    display_cadastre(JSON.parse($("#cadastres").val()));

  freeDraw = new L.FreeDraw();
  freeDraw.options.setSmoothFactor(4);
  freeDraw.options.simplifyPolygon = false;

  map.addLayer(freeDraw);

  if ($("#json_latlngs").val() != '' && $("#json_latlngs").val() != '[]') {
    map.setZoom(18);

    $.each($.parseJSON($("#json_latlngs").val()), function (i, val) {
      freeDraw.createPolygon(val);
    });

    map.fitBounds(freeDraw.polygons[0].getBounds());
  }
  else if (position.lat == LAT && position.lon == LON)
    map.setView(new L.LatLng(position.lat, position.lon), position.zoom);

  add_event_freeDraw();
  add_event_search_address();
}

function default_gestionnaire_position() {
  return {lon: LON, lat: LAT, zoom: 5}
}

function get_external_data(latLngs) {
  if (qp_active())
    display_qp(get_qp(latLngs));

  if (cadastre_active()) {
    polygons = {"type": "FeatureCollection", "features": []};

    for (i = 0; i < latLngs.length; i++)
      polygons.features.push(feature_polygon_latLngs(latLngs[i]))

    cadastre_list = [{zoom_error: true}];

    if (turf_area(polygons) < 300000)
      cadastre_list = get_cadastre(latLngs);

    display_cadastre(cadastre_list);
  }
}

function feature_polygon_latLngs(coordinates) {
  return ({
    "type": "Feature",
    "properties": {},
    "geometry": {
      "type": "Polygon",
      "coordinates": [
        JSON.parse(L.FreeDraw.Utilities.getJsonPolygons([coordinates]))['latLngs']
      ]
    }
  })
}

function add_event_freeDraw() {
  freeDraw.on('markers', function (e) {
    $("#json_latlngs").val(JSON.stringify(e.latLngs));

    add_event_edit();

    get_external_data(e.latLngs);
  });

  $("#map").on('click', function(){
    freeDraw.setMode(L.FreeDraw.MODES.VIEW);
  });

  $("#new").on('click', function (e) {
    freeDraw.setMode(L.FreeDraw.MODES.CREATE);
  });

  $("#delete").on('click', function (e) {
    freeDraw.setMode(L.FreeDraw.MODES.DELETE);
  });
}

function add_event_edit (){
  $(".leaflet-container g path").on('click', function (e) {
    setTimeout(function(){freeDraw.setMode(L.FreeDraw.MODES.EDIT | L.FreeDraw.MODES.DELETE)}, 50);
  });
}

function get_position() {
  var position;

  $.ajax({
    url: '/users/dossiers/' + dossier_id + '/carte/position',
    dataType: 'json',
    async: false
  }).done(function (data) {
    position = data
  });

  return position;
}

function get_address_point(request) {
  $.get('/ban/address_point', { request: request })
    .done(function (data) {
      if (data.lat !== null) {
        map.setView(new L.LatLng(data.lat, data.lon), data.zoom);
      }
    });
}

function jsObject_to_array(qp_list) {
  return Object.keys(qp_list).map(function (v) {
    return qp_list[v];
  });
}

function add_event_search_address() {
  $("#search-by-address input[type='address']").bind('typeahead:select', function (ev, seggestion) {
    get_address_point(seggestion['label']);
  });

  $("#search-by-address input[type='address']").keypress(function (e) {
    if (e.keyCode == 13)
      get_address_point($(this).val());
  });
}
<|endoftext|>


<commit_before>// ==UserScript==
// @name         pr0gramm-tags
// @namespace    http://github.net/mopsalarm/pr0gramm-tags
// @version      0.1.0
// @description  Allow better searches
// @author       Mopsalarm
// @match        http://pr0gramm.com/*
// @match        https://pr0gramm.com/*
// @grant        none
// @run-at       document-idle
// ==/UserScript==

(function () {
    'use strict';

    var orgGet = p.api.get;
    p.api.get = function (endpoint, opts, success, error) {
        if (endpoint === "items.get") {
            var hasSpecialPrefix = (opts.tags || "")[0] === "?";
            if (hasSpecialPrefix) {
                opts.tags = opts.tags.slice(1);
                return jQuery.ajax({
                    type: "GET",
                    url: "//app.pr0gramm.com/api/categories/v1/general",
                    success: success,
                    error: error,
                    dataType: "json",
                    data: opts
                });
            }
        }

        return orgGet.apply(this, arguments);
    };
})();
<commit_msg>Fix feed on promoted.<commit_after>// ==UserScript==
// @name         pr0gramm-tags
// @namespace    http://github.net/mopsalarm/pr0gramm-tags
// @version      0.2.0
// @description  Allow better searches
// @author       Mopsalarm
// @match        http://pr0gramm.com/*
// @match        https://pr0gramm.com/*
// @grant        none
// @run-at       document-idle
// ==/UserScript==

(function () {
    'use strict';

    var orgGet = p.api.get;
    p.api.get = function (endpoint, opts, success, error) {
        if (endpoint === "items.get") {
            var hasSpecialPrefix = (opts.tags || "")[0] === "?";
            if (hasSpecialPrefix) {
                opts.tags = opts.tags.slice(1);
                return jQuery.ajax({
                    type: "GET",
                    url: "//app.pr0gramm.com/api/categories/v1/general",
                    success: function (data) {
                        if (data && data.items) {
                            data.items.forEach(function (item) {
                                // dirrty!
                                item.promoted = item.id;
                            })
                        }

                        success(data);
                    },
                    error: error,
                    dataType: "json",
                    data: opts
                });
            }
        }

        return orgGet.apply(this, arguments);
    };
})();
<|endoftext|>


<commit_before>/* npm packages */
require('connect-mongo');
const bodyParser = require('body-parser');
const config = require('config');
const express = require('express');
const passport = require('passport');
const restful = require('node-restful');
const mongoose = require('mongoose');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const fs = require('fs');
const https = require('https');
const http = require('http');

require('./handlers/auth');
Promise = require('bluebird'); // eslint-disable-line no-native-reassign

/* app imports */
const {APIError, correlationId, errorHandler} = require('./helpers/APIError');
const apiRoute = require('./routes/api')
  , authRoute = require('./routes/auth');

/* global constants */
var options = {
  pfx: fs.readFileSync('../keys/server.pfx'),
  passphrase: 'guojun@123'
};
const server = express();

/* --- Database --- */
mongoose.Promise = Promise;
mongoose.set('debug', true);
const dbConfig = config.get('dbConfig');
if (config.util.getEnv('NODE_ENV') !== 'standalone') {
  mongoose.connect(`mongodb://${dbConfig.host}:${dbConfig.port}/${dbConfig.name}`, dbConfig.options);
}

/* --- API middleware --- */
server.set('view engine', 'ejs');
// body parser setup
server.use(bodyParser.urlencoded({extended: true}));
server.use(bodyParser.json());
server.use(cookieParser());
server.use(session({
  secret: 'keyboard cat',
  resave: true,
  saveUninitialized: true
}));
server.use(passport.initialize());
server.use(passport.session());

// error handling specific to body parser only
server.use((error, request, response, next) => {
  if (error instanceof SyntaxError || error instanceof TypeError) {
    // console.error(error);
    return next(new APIError(400, 'Bad Request', 'Malformed JSON.'));
  }
  return next();
});

// config auth route
server.use('/', authRoute);
server.use('/api', apiRoute);

// response headers setup
server.use((request, response, next) => {
  response.header('Access-Control-Allow-Origin', '*');
  response.header('Access-Control-Allow-Headers', 'Content-Type,Authorization,Correlation-Id');
  response.header('Access-Control-Allow-Methods', 'GET,POST,PATCH,DELETE');
  response.header('Access-Control-Expose-Headers', 'Correlation-Id');
  response.header('Correlation-Id', correlationId);
  response.header('Content-Type', 'application/json');
  return next();
});

/* Generic 404 error-maker for routes that do not contain resources */
server.get('*', (request, response, next) => {
  const err = new APIError(404, 'Resource Not Found.', `${request.path} is not valid path to a API resource.`);
  return next(err);
});

server.use(errorHandler);

const httpServer = http.createServer(server);
const httpsServer = https.createServer(options, server);

httpServer.listen(3000, () => {
  console.log('API express server is listening on port 3000...');
});
httpsServer.listen(3001, () => {
  console.log('API express server is listening on port 3001...');
});
<commit_msg>modify router<commit_after>/* npm packages */
require('connect-mongo');
const bodyParser = require('body-parser');
const config = require('config');
const express = require('express');
const passport = require('passport');
const restful = require('node-restful');
const mongoose = require('mongoose');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const fs = require('fs');
const https = require('https');
const http = require('http');

require('./handlers/auth');
Promise = require('bluebird'); // eslint-disable-line no-native-reassign

/* app imports */
const {APIError, correlationId, errorHandler} = require('./helpers/APIError');
const apiRoute = require('./routes/api')
  , authRoute = require('./routes/auth');

/* global constants */
var options = {
  pfx: fs.readFileSync('../keys/server.pfx'),
  passphrase: 'guojun@123'
};
const server = express();

/* --- Database --- */
mongoose.Promise = Promise;
mongoose.set('debug', true);
const dbConfig = config.get('dbConfig');
if (config.util.getEnv('NODE_ENV') !== 'standalone') {
  mongoose.connect(`mongodb://${dbConfig.host}:${dbConfig.port}/${dbConfig.name}`, dbConfig.options);
}

/* --- API middleware --- */
server.set('view engine', 'ejs');
// body parser setup
server.use(bodyParser.urlencoded({extended: true}));
server.use(bodyParser.json());
server.use(cookieParser());
server.use(session({
  secret: 'keyboard cat',
  resave: true,
  saveUninitialized: true
}));
server.use(passport.initialize());
server.use(passport.session());

// error handling specific to body parser only
server.use((error, request, response, next) => {
  if (error instanceof SyntaxError || error instanceof TypeError) {
    // console.error(error);
    return next(new APIError(400, 'Bad Request', 'Malformed JSON.'));
  }
  return next();
});

// response headers setup
server.use((request, response, next) => {
  response.header('Access-Control-Allow-Origin', '*');
  response.header('Access-Control-Allow-Headers', 'Content-Type,Authorization,Correlation-Id');
  response.header('Access-Control-Allow-Methods', 'GET,POST,PATCH,DELETE');
  response.header('Access-Control-Expose-Headers', 'Correlation-Id');
  response.header('Correlation-Id', correlationId);
  response.header('Content-Type', 'application/json');
  return next();
});

// config auth route
server.use('/', authRoute);
server.use('/api', apiRoute);

/* Generic 404 error-maker for routes that do not contain resources */
server.get('*', (request, response, next) => {
  const err = new APIError(404, 'Resource Not Found.', `${request.path} is not valid path to a API resource.`);
  return next(err);
});

server.use(errorHandler);

const httpServer = http.createServer(server);
const httpsServer = https.createServer(options, server);

httpServer.listen(3000, () => {
  console.log('API express server is listening on port 3000...');
});
httpsServer.listen(3001, () => {
  console.log('API express server is listening on port 3001...');
});
<|endoftext|>


<commit_before>
// ----------------------------------------------------------------
// Static classes

class Log {
  // Common line setting
  static get LOG_LENGTH() { return 96; }
  static get LOG_CHARACTER() { return '-'; }

  // View permission
  static get LOG_VIEW() { return true; }
  static get LOG_VIEW_OBJECT() { return true; }
  static get LOG_VIEW_CLASS() { return true; }
  static get LOG_VIEW_CLASS_KEY() { return true; }
  static get LOG_VIEW_ERROR() { return true; }
  static get LOG_VIEW_CAUTION() { return true; }

  // Align definition
  static get ALIGN_LEFT() { return 0; }
  static get ALIGN_CENTER() { return 1; }
  static get ALIGN_RIGHT() { return 2; }

  // Arrow definition
  static get ARROW_OUTPUT() { return ' ---> '; }
  static get ARROW_INPUT() { return ' <--- '; }

  // Length definition
  static get CLASS_LENGTH() { return 24; }
  static get KEY_LENGTH() { return 24; }

  // Style definition
  static get STYLE_COLOR_RED() { return 'color:#f00;'; }
  static get STYLE_COLOR_GREEN() { return 'color:#0f0;'; }
  static get STYLE_COLOR_BLUE() { return 'color:#00f;'; }
  static get STYLE_COLOR_YELLOW() { return 'color:#ff0;'; }
  static get STYLE_COLOR_MAGENTA() { return 'color:#f0f;'; }
  static get STYLE_COLOR_CYAN() { return 'color:#0ff;'; }

  static get STYLE_CLASS() { return 'color:#222;'; }
  static get STYLE_KEY() { return 'color:#828;'; }
  static get STYLE_VALUE() { return 'color:#228;'; }

  static get STYLE_ERROR_LINE() { return 'color:#f00;'; }
  static get STYLE_ERROR_HEADER() { return 'color:#a00;'; }
  static get STYLE_ERROR_CONTENT() { return 'color:#111;'; }

  static get STYLE_CAUTION_LINE() { return 'color:#aa0;'; }
  static get STYLE_CAUTION_HEADER() { return 'color:#440;'; }
  static get STYLE_CAUTION_CONTENT() { return 'color:#111;'; }

  static logError(...array) {
    // View permission
    if (this.LOG_VIEW_ERROR) {
      // Draw line
      this.log(null, null, this.STYLE_ERROR_LINE);
      // Write title
      this.log('ERROR', this.ALIGN_CENTER, this.STYLE_ERROR_HEADER);
      // Write array
      for (let i = 0; i < array.length; i++) {
        this.log(array[i], this.ALIGN_LEFT, this.STYLE_ERROR_CONTENT);
      }
      // Draw line
      this.log(null, null, this.STYLE_ERROR_LINE);
    }
  }

  static logCaution(...array) {
    // View permission
    if (this.LOG_VIEW_CAUTION) {
      // Draw line
      this.log(null, null, this.STYLE_CAUTION_LINE);
      // Write title
      this.log('CAUTION', this.ALIGN_CENTER, this.STYLE_CAUTION_HEADER);
      // Write array
      for (let i = 0; i < array.length; i++) {
        this.log(array[i], this.ALIGN_LEFT, this.STYLE_CAUTION_CONTENT);
      }
      // Draw line
      this.log(null, null, this.STYLE_CAUTION_LINE);
    }
  }

  static logObj(_obj) {
    // View permission
    if (this.LOG_VIEW_OBJECT) {
      // Write object
      console.log(_obj);
    }
  }

  static logClass(_class = 'Class', _value = 'value', _style1 = this.STYLE_CLASS, _style2 = this.STYLE_VALUE) {
    // View permission
    if (this.LOG_VIEW_CLASS) {
      // Set style
      let result = '%c';
      // Write class
      result += _class;
      // Set spacing
      const classLength = _class.length;
      for (let i = 0; i < this.CLASS_LENGTH - classLength; i++) {
        result += ' ';
      }
      // Set style
      result += ': %c';
      // Write value
      result += _value;

      // Write result
      console.log(result, _style1, _style2);
    }
  }

  static logClassKey(_class = 'Class', _key = 'key', _value = 'value', _arrow = Log.ARROW_OUTPUT, _style1 = this.STYLE_CLASS, _style2 = this.STYLE_KEY, _style3 = this.STYLE_VALUE) {
    // View permission
    if (this.LOG_VIEW_CLASS_KEY) {
      // Set style
      let result = '%c';
      // Write class
      result += _class;
      // Set spacing
      const classLength = _class.length;
      for (let i = 0; i < this.CLASS_LENGTH - classLength; i++) {
        result += ' ';
      }
      // Set style
      result += ': %c';
      // Write key
      result += _key;
      // Set spacing
      const keyLength = _key.length;
      for (let i = 0; i < this.KEY_LENGTH - keyLength; i++) {
        result += ' ';
      }
      // Set style
      result += '%c';
      // Write arrow
      result += _arrow;
      // Set style
      result += '%c';
      // Write value
      result += _value;

      // Write result
      console.log(result, _style1, _style2, this.STYLE_RESET, _style3);
    }
  }

  static log(_string, _align = this.ALIGN_LEFT, _style = this.STYLE_RESET) {
    // View permission
    if (this.LOG_VIEW) {
      let result = '';

      // String is null
      if (_string == null) {
        // Draw line
        for (let i = 0; i < this.LOG_LENGTH; i++) {
          result += this.LOG_CHARACTER;

        }
        // String exists
      } else {
        // Align left
        if (_align == this.ALIGN_LEFT) {
          // Write string
          result = _string;

          // Align center
        } else if (_align == this.ALIGN_CENTER) {
          // Set spacing
          const strLength = _string.length;
          for (let i = 0; i < (this.LOG_LENGTH / 2) - (strLength / 2); i++) {
            result += ' ';
          }
          // Write string
          result += _string;

          // Align right
        } else if (_align == this.ALIGN_RIGHT) {
          // Set spacing
          const strLength = _string.length;
          for (let i = 0; i < this.LOG_LENGTH - strLength; i++) {
            result += ' ';
          }
          // Write string
          result += _string;
        }
      }

      // Set style
      // Write result
      console.log(`%c${result}`, _style);
    }
  }
}

class LocalStorage {
  // Check localStorage support
  static get SUPPORT() {
    let result = true;
    if (!localStorage) {
      result = false;
    }
    return result;
  }

  // Build key
  static buildKey(_key) {
      return `${Project.NAME_KEY}.${_key}`;
  }

  // All clear localStorage
  static clear() {
    // Check support
    if (this.SUPPORT) {
      Log.logClass('Local Storage', 'All Clear.');
      // Clear
      localStorage.clear();
    }
  }

  // getItem from localStorage
  static getItem(_key = 'key') {
    _key = this.buildKey(_key);
    // Check support
    if (this.SUPPORT) {
      const _val = localStorage.getItem(_key);
      Log.logClassKey('Local Storage', _key, _val, Log.ARROW_OUTPUT);
      // Get
      return _val;
    }
  }

  // setItem from localStorage
  static setItem(_key = 'key', _val = 'value') {
    _key = this.buildKey(_key);
    // Check support
    if (this.SUPPORT) {
      Log.logClassKey('Local Storage', _key, _val, Log.ARROW_INPUT);
      // Set
      localStorage.setItem(_key, _val);
    }
  }

  // removeItem from localStorage
  static removeItem(_key = 'key') {
    _key = this.buildKey(_key);
    // Check support
    if (this.SUPPORT) {
      Log.logClassKey('Local Storage', _key, 'null', Log.ARROW_INPUT);
      // Remove
      localStorage.removeItem(_key);
    }
  }
}

class SetEvent {
  static setOn(
    trigger = 'click',
    selector = null,
    func = () => {}
  ) {
    if (selector != null) {
      $(document).on(trigger, selector, () => {
        func();
      });
    } else {
      $(document).on(trigger, () => {
        func();
      });
    }
  }

  static setOff(
    trigger = 'click',
    selector = null
  ) {
    if (selector != null) {
      $(document).off(trigger, selector);
    } else {
      $(document).off(trigger);
    }
  }
}

class SHA256 {
  static getHash(_string = null) {
    if (_string != null) {
      let shaObject = new jsSHA("SHA-256", "TEXT", 1);
      shaObject.update(_string);
      return shaObject.getHash("HEX");
    }
    return null;
  }
}
<commit_msg>Change func exec to setOn in SetEvent<commit_after>
// ----------------------------------------------------------------
// Static classes

class Log {
  // Common line setting
  static get LOG_LENGTH() { return 96; }
  static get LOG_CHARACTER() { return '-'; }

  // View permission
  static get LOG_VIEW() { return true; }
  static get LOG_VIEW_OBJECT() { return true; }
  static get LOG_VIEW_CLASS() { return true; }
  static get LOG_VIEW_CLASS_KEY() { return true; }
  static get LOG_VIEW_ERROR() { return true; }
  static get LOG_VIEW_CAUTION() { return true; }

  // Align definition
  static get ALIGN_LEFT() { return 0; }
  static get ALIGN_CENTER() { return 1; }
  static get ALIGN_RIGHT() { return 2; }

  // Arrow definition
  static get ARROW_OUTPUT() { return ' ---> '; }
  static get ARROW_INPUT() { return ' <--- '; }

  // Length definition
  static get CLASS_LENGTH() { return 24; }
  static get KEY_LENGTH() { return 24; }

  // Style definition
  static get STYLE_COLOR_RED() { return 'color:#f00;'; }
  static get STYLE_COLOR_GREEN() { return 'color:#0f0;'; }
  static get STYLE_COLOR_BLUE() { return 'color:#00f;'; }
  static get STYLE_COLOR_YELLOW() { return 'color:#ff0;'; }
  static get STYLE_COLOR_MAGENTA() { return 'color:#f0f;'; }
  static get STYLE_COLOR_CYAN() { return 'color:#0ff;'; }

  static get STYLE_CLASS() { return 'color:#222;'; }
  static get STYLE_KEY() { return 'color:#828;'; }
  static get STYLE_VALUE() { return 'color:#228;'; }

  static get STYLE_ERROR_LINE() { return 'color:#f00;'; }
  static get STYLE_ERROR_HEADER() { return 'color:#a00;'; }
  static get STYLE_ERROR_CONTENT() { return 'color:#111;'; }

  static get STYLE_CAUTION_LINE() { return 'color:#aa0;'; }
  static get STYLE_CAUTION_HEADER() { return 'color:#440;'; }
  static get STYLE_CAUTION_CONTENT() { return 'color:#111;'; }

  static logError(...array) {
    // View permission
    if (this.LOG_VIEW_ERROR) {
      // Draw line
      this.log(null, null, this.STYLE_ERROR_LINE);
      // Write title
      this.log('ERROR', this.ALIGN_CENTER, this.STYLE_ERROR_HEADER);
      // Write array
      for (let i = 0; i < array.length; i++) {
        this.log(array[i], this.ALIGN_LEFT, this.STYLE_ERROR_CONTENT);
      }
      // Draw line
      this.log(null, null, this.STYLE_ERROR_LINE);
    }
  }

  static logCaution(...array) {
    // View permission
    if (this.LOG_VIEW_CAUTION) {
      // Draw line
      this.log(null, null, this.STYLE_CAUTION_LINE);
      // Write title
      this.log('CAUTION', this.ALIGN_CENTER, this.STYLE_CAUTION_HEADER);
      // Write array
      for (let i = 0; i < array.length; i++) {
        this.log(array[i], this.ALIGN_LEFT, this.STYLE_CAUTION_CONTENT);
      }
      // Draw line
      this.log(null, null, this.STYLE_CAUTION_LINE);
    }
  }

  static logObj(_obj) {
    // View permission
    if (this.LOG_VIEW_OBJECT) {
      // Write object
      console.log(_obj);
    }
  }

  static logClass(_class = 'Class', _value = 'value', _style1 = this.STYLE_CLASS, _style2 = this.STYLE_VALUE) {
    // View permission
    if (this.LOG_VIEW_CLASS) {
      // Set style
      let result = '%c';
      // Write class
      result += _class;
      // Set spacing
      const classLength = _class.length;
      for (let i = 0; i < this.CLASS_LENGTH - classLength; i++) {
        result += ' ';
      }
      // Set style
      result += ': %c';
      // Write value
      result += _value;

      // Write result
      console.log(result, _style1, _style2);
    }
  }

  static logClassKey(_class = 'Class', _key = 'key', _value = 'value', _arrow = Log.ARROW_OUTPUT, _style1 = this.STYLE_CLASS, _style2 = this.STYLE_KEY, _style3 = this.STYLE_VALUE) {
    // View permission
    if (this.LOG_VIEW_CLASS_KEY) {
      // Set style
      let result = '%c';
      // Write class
      result += _class;
      // Set spacing
      const classLength = _class.length;
      for (let i = 0; i < this.CLASS_LENGTH - classLength; i++) {
        result += ' ';
      }
      // Set style
      result += ': %c';
      // Write key
      result += _key;
      // Set spacing
      const keyLength = _key.length;
      for (let i = 0; i < this.KEY_LENGTH - keyLength; i++) {
        result += ' ';
      }
      // Set style
      result += '%c';
      // Write arrow
      result += _arrow;
      // Set style
      result += '%c';
      // Write value
      result += _value;

      // Write result
      console.log(result, _style1, _style2, this.STYLE_RESET, _style3);
    }
  }

  static log(_string, _align = this.ALIGN_LEFT, _style = this.STYLE_RESET) {
    // View permission
    if (this.LOG_VIEW) {
      let result = '';

      // String is null
      if (_string == null) {
        // Draw line
        for (let i = 0; i < this.LOG_LENGTH; i++) {
          result += this.LOG_CHARACTER;

        }
        // String exists
      } else {
        // Align left
        if (_align == this.ALIGN_LEFT) {
          // Write string
          result = _string;

          // Align center
        } else if (_align == this.ALIGN_CENTER) {
          // Set spacing
          const strLength = _string.length;
          for (let i = 0; i < (this.LOG_LENGTH / 2) - (strLength / 2); i++) {
            result += ' ';
          }
          // Write string
          result += _string;

          // Align right
        } else if (_align == this.ALIGN_RIGHT) {
          // Set spacing
          const strLength = _string.length;
          for (let i = 0; i < this.LOG_LENGTH - strLength; i++) {
            result += ' ';
          }
          // Write string
          result += _string;
        }
      }

      // Set style
      // Write result
      console.log(`%c${result}`, _style);
    }
  }
}

class LocalStorage {
  // Check localStorage support
  static get SUPPORT() {
    let result = true;
    if (!localStorage) {
      result = false;
    }
    return result;
  }

  // Build key
  static buildKey(_key) {
      return `${Project.NAME_KEY}.${_key}`;
  }

  // All clear localStorage
  static clear() {
    // Check support
    if (this.SUPPORT) {
      Log.logClass('Local Storage', 'All Clear.');
      // Clear
      localStorage.clear();
    }
  }

  // getItem from localStorage
  static getItem(_key = 'key') {
    _key = this.buildKey(_key);
    // Check support
    if (this.SUPPORT) {
      const _val = localStorage.getItem(_key);
      Log.logClassKey('Local Storage', _key, _val, Log.ARROW_OUTPUT);
      // Get
      return _val;
    }
  }

  // setItem from localStorage
  static setItem(_key = 'key', _val = 'value') {
    _key = this.buildKey(_key);
    // Check support
    if (this.SUPPORT) {
      Log.logClassKey('Local Storage', _key, _val, Log.ARROW_INPUT);
      // Set
      localStorage.setItem(_key, _val);
    }
  }

  // removeItem from localStorage
  static removeItem(_key = 'key') {
    _key = this.buildKey(_key);
    // Check support
    if (this.SUPPORT) {
      Log.logClassKey('Local Storage', _key, 'null', Log.ARROW_INPUT);
      // Remove
      localStorage.removeItem(_key);
    }
  }
}

class SetEvent {
  static setOn(
    trigger = 'click',
    selector = null,
    func = () => {}
  ) {
    if (selector != null) {
      $(document).on(trigger, selector, func);
    } else {
      $(document).on(trigger, func);
    }
  }

  static setOff(
    trigger = 'click',
    selector = null
  ) {
    if (selector != null) {
      $(document).off(trigger, selector);
    } else {
      $(document).off(trigger);
    }
  }
}

class SHA256 {
  static getHash(_string = null) {
    if (_string != null) {
      let shaObject = new jsSHA("SHA-256", "TEXT", 1);
      shaObject.update(_string);
      return shaObject.getHash("HEX");
    }
    return null;
  }
}
<|endoftext|>


<commit_before>(function(root, factory) {
    if (typeof exports === 'object') { // Node.js
        module.exports = factory();
    } else if (typeof define === 'function' && define.amd) { // Require.JS
        define(factory);
    } else { // Browser globals
        root.jef = root.jef || {};
        root.jef.domdiff = factory();
    }
})(this, function() {
    'use strict';

    /**
     * Test if given nodes are the same.
     *
     * @param {Element} a
     * @param {Element} b
     * @return {Boolean}
     */
    function nodeSame(a, b) {
        if (a.nodeType !== b.nodeType) {
            return false;
        }
        if (a.nodeName !== b.nodeName) {
            return false;
        }
        return true;
    }

    /**
     * Test if given ndoes are leafs;
     * Don't have children
     *
     * @param {Element} a
     * @param {Element} b
     * @return {Boolean}
     */
    function nodeLeaf(a, b) {
        return nodeLength(a) === 0
        && nodeLength(b) === 0;
    }

    /**
     * Find common attributes in elements 'a' & 'b'
     * and return array of common attribites names
     *
     * @param {NamedNodeMap} a
     * @param {NamedNodeMap} b
     * @return {Array}
     */
    function attrIntersection(aAttr, bAttr) {
        var name, result = [];
        Array.prototype.forEach.call(aAttr, function(value) {
            name = value.nodeName;
            if (name && bAttr[name]) {
                result.push(name);
            }
        });
        return result;
    }

    /**
     * Find attributes in 'a' that do not exists in 'b'
     * and return array of different attribitutes names
     *
     * @param {NamedNodeMap} a
     * @param {Array} b
     * @return {Array}
     */
    function attrDifference(aAttr, bArray) {
        var result = [];
        Array.prototype.forEach.call(aAttr, function(value) {
            if (-1 === bArray.indexOf(value.nodeName)) {
                result.push(value.nodeName);
            }
        });
        return result;
    }

    /**
     * Helper function, testing if attribute is the same in two given elements.
     *
     * @param {Element} a
     * @param {Element} b
     * @param {String} name
     * @return {Boolean}
     */
    function nodeAttrValueEqual(a, b, name) {
        return a.attributes[name].value === b.attributes[name].value;
    }

    /**
     * Prepare action to remove attribute {name} from given {node}
     *
     * @param {NamespaceString} namespace
     * @param {String} name
     * @return {String}
     */
    function nodeAttrRemove(namespace, name) {
        return namespace + '.removeAttribute("'+ name +'");\n';
    }

    /**
     * Prepare action to replace attribute value;
     *
     * @param {NamespaceString} fromNamespace
     * @param {NamespaceString} toNamespace
     * @param {String} name
     * @return {String}
     */
    function nodeAttrReplace(fromNamespace, toNamespace, name) {
        return toNamespace + '.setAttribute("'+ name +'", '+ fromNamespace +'.getAttribute("'+ name +'"));\n';
    }

    /**
     * Check if given nodes are exacly the same
     * (textContent and nodeName are equal)
     *
     * @param {Element} a
     * @param {Element} b
     * @return {Boolean}
     */
    function nodeExactly(a, b) {
        return a.textContent === b.textContent
        && nodeSame(a, b);
    }

    /**
     * Helper function to generate node actions
     *
     * @param {String} namespace
     * @param {String} action
     * @param {String} nodePath
     * @return {String}
     */
    function nodeAction(namespace, action, nodePath) {
        return namespace + '.'+ action +'(' + nodePath + ');\n';
    }

    /**
     * Generate action to remove namespace from dom
     *
     * @param {NamespaceString} namespace
     * @return {String}
     */
    function nodeRemove(namespace) {
        return nodeAction(namespace.parent(), 'removeChild', namespace);
    }

    /**
     * Generate action to replace {new} with {old}
     *
     * @param {NamespaceString} newNamespace
     * @param {NamespaceString} oldNamespace
     * @return {String}
     */
    function nodeReplace(newNamespace, oldNamespace) {
        return oldNamespace.parent() + '.replaceChild('+ newNamespace +', '+ oldNamespace +');\n';
    }

    /**
     * Generate action to append {newNamespace} into {namespace}
     *
     * @param {NamespaceString} newNamespace
     * @param {NamespaceString} namespace
     * @return {String}
     */
    function nodeAppend(newNamespace, namespace) {
        return nodeAction(namespace, 'appendChild', newNamespace);
    }

    /**
     * Retrive number of children for given node
     *
     * @param {Element} node
     * @return {Integer}
     */
    function nodeLength(node) {
        return node.childNodes.length;
    }

    /**
     * Retrive child node at {index} for given element;
     *
     * @param {Element} node
     * @param {Integer} index
     * @return {Element}
     */
    function nodeRetrieve(node, index) {
        return node.childNodes[index];
    }

    /**
     * Namespace object
     *
     * @constructor
     */
    function NamespaceString(namespace, index) {
        this.namespace = namespace;
        this.index = index || 0;
    };
    NamespaceString.prototype.parent = function() {
        return this;
    };
    NamespaceString.prototype.toString = function() {
        return this.namespace;
    };
    NamespaceString.prototype.pop = function() {
        --this.index;
        return this;
    };
    NamespaceString.prototype.push = function() {
        ++this.index;
        return this;
    };
    NamespaceString.prototype.next = function(index) {
        return new NamespaceNext(this, index);
    };

    /**
     * Generalisation of namespace
     *
     * @constructor
     */
    function NamespaceNext(namespace, index) {
        NamespaceString.call(this, namespace, index)
    };
    NamespaceNext.prototype = Object.create(NamespaceString.prototype);
    NamespaceNext.prototype.parent = function() {
        return this.namespace;
    };
    NamespaceNext.prototype.toString = function() {
        return this.namespace + '.childNodes[' + this.index + ']';
    };

    /**
     * Calculate diff actions to make 'a' attributes the exactly the same as in 'b'
     *
     * @param {Element} a
     * @param {Element} b
     * @param {NamespaceString} namespaceA
     * @param {NamespaceString} namespaceB
     * @return {String}
     */
    function diffattributes(a, b, namespaceA, namespaceB) {
        var common, remove, create, result = '';

        // Calculate changes in attributes
        common = attrIntersection(a.attributes, b.attributes);
        remove = attrDifference(a.attributes, common);
        create = attrDifference(b.attributes, common);

        // Generate actions
        common.forEach(function(name) {
            if (!nodeAttrValueEqual(a, b, name)) {
                result += nodeAttrReplace(namespaceB, namespaceA, name);
            }
        });
        remove.forEach(function(name) {
            result += nodeAttrRemove(namespaceA, name);
        });
        create.forEach(function(name) {
            result += nodeAttrReplace(namespaceB, namespaceA, name);
        });

        return result;
    }

    /**
     * Create DOM API diff from given elements
     *
     * @param {Element} a
     * @param {Element} b
     * @return {Stirng}
     */
    function diff(rootA, rootB) {
        /**
         * Helper function
         *
         * @param {Element} a
         * @param {Element} b
         * @param {NamespaceString} namespaceA
         * @param {NamespaceString} namespaceB
         * @return {Stirng}
         */
        function diffrecursive(a, b, namespaceA, namespaceB) {
            var i, length, delta, isLeaf, isSame,
                result = '';

            isLeaf = nodeLeaf(a, b);
            isSame = nodeSame(a, b);

            // Node are the same so compare difference in attributes
            // Add attributes only for element type nodes
            if (isSame && a.nodeType === 1) {
                result += diffattributes(a, b, namespaceA, namespaceB);
            }

            // Nodes are the same, compare children
            if (!isLeaf && isSame) {
                length = nodeLength(a);
                delta = length - nodeLength(b);

                // Create namespace for children
                namespaceA = namespaceA.next();
                namespaceB = namespaceB.next();

                if (delta > 0) {
                    // 'b' has leser length so we need to reduce
                    // 'a' loop length to 'b' length; if we haven't do this
                    // then we would have null elements in nodeB var
                    length -= delta;
                }

                for (i = 0; i < length; i++) {
                    result += diffrecursive(
                        nodeRetrieve(a, i),
                        nodeRetrieve(b, i),
                        namespaceA,
                        namespaceB
                    );

                    // Push namespace child further
                    namespaceA.push();
                    namespaceB.push();
                }

                if (delta > 0) {
                    // remove unused elements form 'a' node
                    do {
                        // We use the same 'path' for removed elements because
                        // When removing elementa at index 1, element at index 2 changes its possition
                        // and became element at position 1
                        result += nodeRemove(namespaceA);
                    } while(--delta > 0);
                } else if (delta < 0) {
                    // the 'a' node have less children than the 'b' node
                    // then since we compare all common 'a' and 'b' nodes
                    // then we need add remaining 'b' nodes
                    do {
                        result += nodeAppend(
                            namespaceB,
                            namespaceA.parent()
                        );
                    } while(++delta < 0);
                }
            }
            // No relation, use b remove a
            else if (!nodeExactly(a, b)){
                result += nodeReplace(
                    namespaceB,
                    namespaceA
                );

                // When we replace element A with B then B's children number decremented
                namespaceB.pop();
            }

            return result;
        }

        // Perform two node comparision
        return diffrecursive(
            rootA,
            rootB,
            new NamespaceString('aElement'),
            new NamespaceString('bElement')
        );
    }

    /**
     * Apply on element 'a' changes from 'b' using given diff
     *
     * @param {Element} a
     * @param {Element} b
     * @param {String} diff
     */
    function applyDiff(a, b, diff) {
        return new Function('aElement', 'bElement', diff)(a, b);
    }

    var exports = {};

    exports.diff = diff;
    exports.applyDiff = applyDiff;
    exports.attrDifference = attrDifference;
    exports.attrIntersection = attrIntersection;
    exports.nodeSame = nodeSame;
    exports.nodeLeaf = nodeLeaf;
    exports.nodeExactly = nodeExactly;
    exports.NamespaceString = NamespaceString;
    exports.NamespaceNext = NamespaceNext;

    return exports;
});
<commit_msg>Update diffdom.js to implement "amdefine"<commit_after>if (typeof define !== 'function') {
    var define = require('amdefine')(module)
}

define(function() {
    'use strict';

    /**
     * Test if given nodes are the same.
     *
     * @param {Element} a
     * @param {Element} b
     * @return {Boolean}
     */
    function nodeSame(a, b) {
        if (a.nodeType !== b.nodeType) {
            return false;
        }
        if (a.nodeName !== b.nodeName) {
            return false;
        }
        return true;
    }

    /**
     * Test if given ndoes are leafs;
     * Don't have children
     *
     * @param {Element} a
     * @param {Element} b
     * @return {Boolean}
     */
    function nodeLeaf(a, b) {
        return nodeLength(a) === 0
        && nodeLength(b) === 0;
    }

    /**
     * Find common attributes in elements 'a' & 'b'
     * and return array of common attribites names
     *
     * @param {NamedNodeMap} a
     * @param {NamedNodeMap} b
     * @return {Array}
     */
    function attrIntersection(aAttr, bAttr) {
        var name, result = [];
        Array.prototype.forEach.call(aAttr, function(value) {
            name = value.nodeName;
            if (name && bAttr[name]) {
                result.push(name);
            }
        });
        return result;
    }

    /**
     * Find attributes in 'a' that do not exists in 'b'
     * and return array of different attribitutes names
     *
     * @param {NamedNodeMap} a
     * @param {Array} b
     * @return {Array}
     */
    function attrDifference(aAttr, bArray) {
        var result = [];
        Array.prototype.forEach.call(aAttr, function(value) {
            if (-1 === bArray.indexOf(value.nodeName)) {
                result.push(value.nodeName);
            }
        });
        return result;
    }

    /**
     * Helper function, testing if attribute is the same in two given elements.
     *
     * @param {Element} a
     * @param {Element} b
     * @param {String} name
     * @return {Boolean}
     */
    function nodeAttrValueEqual(a, b, name) {
        return a.attributes[name].value === b.attributes[name].value;
    }

    /**
     * Prepare action to remove attribute {name} from given {node}
     *
     * @param {NamespaceString} namespace
     * @param {String} name
     * @return {String}
     */
    function nodeAttrRemove(namespace, name) {
        return namespace + '.removeAttribute("'+ name +'");\n';
    }

    /**
     * Prepare action to replace attribute value;
     *
     * @param {NamespaceString} fromNamespace
     * @param {NamespaceString} toNamespace
     * @param {String} name
     * @return {String}
     */
    function nodeAttrReplace(fromNamespace, toNamespace, name) {
        return toNamespace + '.setAttribute("'+ name +'", '+ fromNamespace +'.getAttribute("'+ name +'"));\n';
    }

    /**
     * Check if given nodes are exacly the same
     * (textContent and nodeName are equal)
     *
     * @param {Element} a
     * @param {Element} b
     * @return {Boolean}
     */
    function nodeExactly(a, b) {
        return a.textContent === b.textContent
        && nodeSame(a, b);
    }

    /**
     * Helper function to generate node actions
     *
     * @param {String} namespace
     * @param {String} action
     * @param {String} nodePath
     * @return {String}
     */
    function nodeAction(namespace, action, nodePath) {
        return namespace + '.'+ action +'(' + nodePath + ');\n';
    }

    /**
     * Generate action to remove namespace from dom
     *
     * @param {NamespaceString} namespace
     * @return {String}
     */
    function nodeRemove(namespace) {
        return nodeAction(namespace.parent(), 'removeChild', namespace);
    }

    /**
     * Generate action to replace {new} with {old}
     *
     * @param {NamespaceString} newNamespace
     * @param {NamespaceString} oldNamespace
     * @return {String}
     */
    function nodeReplace(newNamespace, oldNamespace) {
        return oldNamespace.parent() + '.replaceChild('+ newNamespace +', '+ oldNamespace +');\n';
    }

    /**
     * Generate action to append {newNamespace} into {namespace}
     *
     * @param {NamespaceString} newNamespace
     * @param {NamespaceString} namespace
     * @return {String}
     */
    function nodeAppend(newNamespace, namespace) {
        return nodeAction(namespace, 'appendChild', newNamespace);
    }

    /**
     * Retrive number of children for given node
     *
     * @param {Element} node
     * @return {Integer}
     */
    function nodeLength(node) {
        return node.childNodes.length;
    }

    /**
     * Retrive child node at {index} for given element;
     *
     * @param {Element} node
     * @param {Integer} index
     * @return {Element}
     */
    function nodeRetrieve(node, index) {
        return node.childNodes[index];
    }

    /**
     * Namespace object
     *
     * @constructor
     */
    function NamespaceString(namespace, index) {
        this.namespace = namespace;
        this.index = index || 0;
    };
    NamespaceString.prototype.parent = function() {
        return this;
    };
    NamespaceString.prototype.toString = function() {
        return this.namespace;
    };
    NamespaceString.prototype.pop = function() {
        --this.index;
        return this;
    };
    NamespaceString.prototype.push = function() {
        ++this.index;
        return this;
    };
    NamespaceString.prototype.next = function(index) {
        return new NamespaceNext(this, index);
    };

    /**
     * Generalisation of namespace
     *
     * @constructor
     */
    function NamespaceNext(namespace, index) {
        NamespaceString.call(this, namespace, index)
    };
    NamespaceNext.prototype = Object.create(NamespaceString.prototype);
    NamespaceNext.prototype.parent = function() {
        return this.namespace;
    };
    NamespaceNext.prototype.toString = function() {
        return this.namespace + '.childNodes[' + this.index + ']';
    };

    /**
     * Calculate diff actions to make 'a' attributes the exactly the same as in 'b'
     *
     * @param {Element} a
     * @param {Element} b
     * @param {NamespaceString} namespaceA
     * @param {NamespaceString} namespaceB
     * @return {String}
     */
    function diffattributes(a, b, namespaceA, namespaceB) {
        var common, remove, create, result = '';

        // Calculate changes in attributes
        common = attrIntersection(a.attributes, b.attributes);
        remove = attrDifference(a.attributes, common);
        create = attrDifference(b.attributes, common);

        // Generate actions
        common.forEach(function(name) {
            if (!nodeAttrValueEqual(a, b, name)) {
                result += nodeAttrReplace(namespaceB, namespaceA, name);
            }
        });
        remove.forEach(function(name) {
            result += nodeAttrRemove(namespaceA, name);
        });
        create.forEach(function(name) {
            result += nodeAttrReplace(namespaceB, namespaceA, name);
        });

        return result;
    }

    /**
     * Create DOM API diff from given elements
     *
     * @param {Element} a
     * @param {Element} b
     * @return {Stirng}
     */
    function diff(rootA, rootB) {
        /**
         * Helper function
         *
         * @param {Element} a
         * @param {Element} b
         * @param {NamespaceString} namespaceA
         * @param {NamespaceString} namespaceB
         * @return {Stirng}
         */
        function diffrecursive(a, b, namespaceA, namespaceB) {
            var i, length, delta, isLeaf, isSame,
                result = '';

            isLeaf = nodeLeaf(a, b);
            isSame = nodeSame(a, b);

            // Node are the same so compare difference in attributes
            // Add attributes only for element type nodes
            if (isSame && a.nodeType === 1) {
                result += diffattributes(a, b, namespaceA, namespaceB);
            }

            // Nodes are the same, compare children
            if (!isLeaf && isSame) {
                length = nodeLength(a);
                delta = length - nodeLength(b);

                // Create namespace for children
                namespaceA = namespaceA.next();
                namespaceB = namespaceB.next();

                if (delta > 0) {
                    // 'b' has leser length so we need to reduce
                    // 'a' loop length to 'b' length; if we haven't do this
                    // then we would have null elements in nodeB var
                    length -= delta;
                }

                for (i = 0; i < length; i++) {
                    result += diffrecursive(
                        nodeRetrieve(a, i),
                        nodeRetrieve(b, i),
                        namespaceA,
                        namespaceB
                    );

                    // Push namespace child further
                    namespaceA.push();
                    namespaceB.push();
                }

                if (delta > 0) {
                    // remove unused elements form 'a' node
                    do {
                        // We use the same 'path' for removed elements because
                        // When removing elementa at index 1, element at index 2 changes its possition
                        // and became element at position 1
                        result += nodeRemove(namespaceA);
                    } while(--delta > 0);
                } else if (delta < 0) {
                    // the 'a' node have less children than the 'b' node
                    // then since we compare all common 'a' and 'b' nodes
                    // then we need add remaining 'b' nodes
                    do {
                        result += nodeAppend(
                            namespaceB,
                            namespaceA.parent()
                        );
                    } while(++delta < 0);
                }
            }
            // No relation, use b remove a
            else if (!nodeExactly(a, b)){
                result += nodeReplace(
                    namespaceB,
                    namespaceA
                );

                // When we replace element A with B then B's children number decremented
                namespaceB.pop();
            }

            return result;
        }

        // Perform two node comparision
        return diffrecursive(
            rootA,
            rootB,
            new NamespaceString('aElement'),
            new NamespaceString('bElement')
        );
    }

    /**
     * Apply on element 'a' changes from 'b' using given diff
     *
     * @param {Element} a
     * @param {Element} b
     * @param {String} diff
     */
    function applyDiff(a, b, diff) {
        return new Function('aElement', 'bElement', diff)(a, b);
    }

    return {
        'diff': diff,
        'applyDiff': applyDiff,
        'attrDifference': attrDifference,
        'attrIntersection': attrIntersection,
        'nodeSame': nodeSame,
        'nodeLeaf': nodeLeaf,
        'nodeExactly': nodeExactly,
        'NamespaceString': NamespaceString,
        'NamespaceNext': NamespaceNext
    }
});
<|endoftext|>


<commit_before>var url = require("url");
var express = require("express");
var bodyParser = require("body-parser");
var path = require('path');

var app = express();
var phrases = ["There's no such thing as a free lunch",
"The pen is mightier than the sword",
"Keep your friends close and your enemies closer",
"There's no place like home",
"The early bird catches the worm",
"Actions speak louder than words",
"Don't bite the hand that feeds you",
"There's no time like the present",
"A penny saved is a penny earned",
"You can't judge a book by its cover",
"Two heads are better than one",
"A chain is only as strong as its weakest link",
"You can lead a horse to water, but you can't make him drink",
"It's a small world",
"Over the hill",
"Put in my two cents",
"Make love, not war",
"An apple a day keeps the doctors away",
"April showers bring May flowers",
"Somewhere over the rainbow",
"The grass is always greener on the other side"]

var gameStates = {};
app.use(bodyParser.json());
app.use(express.static(path.resolve("../frontend")));

app.get("/about", function(req, res) {
    res.sendFile("about.html", { root: __dirname + "/../frontend" });
});

//Actual game page
app.get("/[a-z]{4}\\\\?", function(req, res) {
    var game = get_url(req.url);
    if(!isCurrentGame(game))
        res.sendFile("nogame.html", { root: __dirname + "/../frontend" });
    else
        res.sendFile("game.html", { root: __dirname + "/../frontend" });
});

app.get("/[a-z]{4}/get_response.json", function(req, res) {
    var game = get_url(req.url);
    var id = req.query.num;
    var ret = {};
    if(id == -1) {
        ret["response"] = gameStates[game]["phrase"];
    } else {
        ret["response"] = gameStates[game]["players"][id]["response"];
    }
    res.send(JSON.stringify(ret));
});

app.get("/[a-z]{4}/get_players.json", function(req, res) {
    var game = get_url(req.url);
    var handles = [];
    gameStates[game]["players"].forEach(function(p) {
        handles.push(p["handle"]);
    });
    var ret = {
        "players" : handles
    };
    res.send(JSON.stringify(ret));
});

app.get("/[a-z]{4}/get_results.json", function(req, res) {
    var game = get_url(req.url);
    var ret = {
        "results" : gameStates[game]["players"],
        "phrase" : gameStates[game]["phrase"]
    }
    res.send(JSON.stringify(ret));
    gameStates[game]["deathCounter"]--;
    if(gameStates[game]["deathCounter"] == 0){
        removeGame(game);
    }
});

app.get("/[a-z]{4}/get_turn.json", function(req, res) {
    var game = get_url(req.url);
    var ret = {
        "turn" : gameStates[game]["turn"]
    };
    res.send(JSON.stringify(ret));
});

app.get("/[a-z]{4}/get_maxPlayers.json", function(req, res) {
    var game = get_url(req.url);
    var ret = {
        "maxPlayers" : gameStates[game]["size"]
    };
    res.send(JSON.stringify(ret));
});

app.post("/request_room.json", function(req, res) {
    var size = req.body.size;
    var url = getRandomURL();
    gameStates[url] = {};
    gameStates[url]["turn"] = -1;
    gameStates[url]["phrase"] = getRandomPhrase();
    gameStates[url]["finished"] = false;
    gameStates[url]["size"] = size;
    gameStates[url]["num_players"] = 0;
    gameStates[url]["deathCounter"] = gameStates[url]["size"];
    gameStates[url].players = [];
    console.log(JSON.stringify(gameStates));
    var ret = {
        "url" : url
    };
    res.send(JSON.stringify(ret));
});

app.post("/[a-z]{4}/join", function(req, res) {
    game = get_url(req.url);
    var handle = req.body.handle;
    var id = gameStates[game]["num_players"];
    gameStates[game]["players"][id] = {"handle" : handle};
    var ret = {
        "id" : id
    };
    res.send(ret)
    gameStates[game]["num_players"]++;

    if(gameStates[game]["num_players"] == gameStates[game]["size"]) {
        gameStates[game]["turn"] = 0;
    }
});

app.post("/[a-z]{4}/send_response", function(req, res) {
    var id = gameStates[game]["turn"];
    gameStates[game]["players"][id]["response"] = req.body.response;
    gameStates[game]["turn"]++;
});

var removeGame = function(game) {
    gameStates[game] = null;
    delete gameStates[game];
    console.log("removed game: %s", game);
}

//returns
var isCurrentGame = function(game) {
    if(gameStates[game]) {
        return true;
    }
    return false;
}

var get_url = function(x) {
    var path = url.parse(x).pathname;
    return path.split("/")[1];
}

/*
 * Obtain a random string of four lowercase alpha characters.
 * Use intended for URL generation for a room.
 */
var getRandomURL = function() {
    var text = "";
    var possible = "abcdefghhijklmnopqrstuvwxyz";
    do{
        for (var i = 0; i < 4; ++i) {
            text += possible.charAt(Math.floor(Math.random() * possible.length));
        }
    }while(isCurrentGame(text));

    return text;
};

var getRandomPhrase = function() {
    return phrases[Math.floor(Math.random() * phrases.length)];
};

var server = app.listen(80, function() {
    console.log("Server started.");
});
<commit_msg>added callback to sendresponse<commit_after>var url = require("url");
var express = require("express");
var bodyParser = require("body-parser");
var path = require('path');

var app = express();
var phrases = ["There's no such thing as a free lunch",
"The pen is mightier than the sword",
"Keep your friends close and your enemies closer",
"There's no place like home",
"The early bird catches the worm",
"Actions speak louder than words",
"Don't bite the hand that feeds you",
"There's no time like the present",
"A penny saved is a penny earned",
"You can't judge a book by its cover",
"Two heads are better than one",
"A chain is only as strong as its weakest link",
"You can lead a horse to water, but you can't make him drink",
"It's a small world",
"Over the hill",
"Put in my two cents",
"Make love, not war",
"An apple a day keeps the doctors away",
"April showers bring May flowers",
"Somewhere over the rainbow",
"The grass is always greener on the other side"]

var gameStates = {};
app.use(bodyParser.json());
app.use(express.static(path.resolve("../frontend")));

app.get("/about", function(req, res) {
    res.sendFile("about.html", { root: __dirname + "/../frontend" });
});

//Actual game page
app.get("/[a-z]{4}\\\\?", function(req, res) {
    var game = get_url(req.url);
    if(!isCurrentGame(game))
        res.sendFile("nogame.html", { root: __dirname + "/../frontend" });
    else
        res.sendFile("game.html", { root: __dirname + "/../frontend" });
});

app.get("/[a-z]{4}/get_response.json", function(req, res) {
    var game = get_url(req.url);
    var id = req.query.num;
    var ret = {};
    if(id == -1) {
        ret["response"] = gameStates[game]["phrase"];
    } else {
        ret["response"] = gameStates[game]["players"][id]["response"];
    }
    res.send(JSON.stringify(ret));
});

app.get("/[a-z]{4}/get_players.json", function(req, res) {
    var game = get_url(req.url);
    var handles = [];
    gameStates[game]["players"].forEach(function(p) {
        handles.push(p["handle"]);
    });
    var ret = {
        "players" : handles
    };
    res.send(JSON.stringify(ret));
});

app.get("/[a-z]{4}/get_results.json", function(req, res) {
    var game = get_url(req.url);
    var ret = {
        "results" : gameStates[game]["players"],
        "phrase" : gameStates[game]["phrase"]
    }
    res.send(JSON.stringify(ret));
    gameStates[game]["deathCounter"]--;
    if(gameStates[game]["deathCounter"] == 0){
        removeGame(game);
    }
});

app.get("/[a-z]{4}/get_turn.json", function(req, res) {
    var game = get_url(req.url);
    var ret = {
        "turn" : gameStates[game]["turn"]
    };
    res.send(JSON.stringify(ret));
});

app.get("/[a-z]{4}/get_maxPlayers.json", function(req, res) {
    var game = get_url(req.url);
    var ret = {
        "maxPlayers" : gameStates[game]["size"]
    };
    res.send(JSON.stringify(ret));
});

app.post("/request_room.json", function(req, res) {
    var size = req.body.size;
    var url = getRandomURL();
    gameStates[url] = {};
    gameStates[url]["turn"] = -1;
    gameStates[url]["phrase"] = getRandomPhrase();
    gameStates[url]["finished"] = false;
    gameStates[url]["size"] = size;
    gameStates[url]["num_players"] = 0;
    gameStates[url]["deathCounter"] = gameStates[url]["size"];
    gameStates[url].players = [];
    console.log(JSON.stringify(gameStates));
    var ret = {
        "url" : url
    };
    res.send(JSON.stringify(ret));
});

app.post("/[a-z]{4}/join", function(req, res) {
    game = get_url(req.url);
    var handle = req.body.handle;
    var id = gameStates[game]["num_players"];
    gameStates[game]["players"][id] = {"handle" : handle};
    var ret = {
        "id" : id
    };
    res.send(ret)
    gameStates[game]["num_players"]++;

    if(gameStates[game]["num_players"] == gameStates[game]["size"]) {
        gameStates[game]["turn"] = 0;
    }
});

app.post("/[a-z]{4}/send_response", function(req, res) {
    var id = gameStates[game]["turn"];
    gameStates[game]["players"][id]["response"] = req.body.response;
    gameStates[game]["turn"]++;
    res.send("");
});

var removeGame = function(game) {
    gameStates[game] = null;
    delete gameStates[game];
    console.log("removed game: %s", game);
}

//returns
var isCurrentGame = function(game) {
    if(gameStates[game]) {
        return true;
    }
    return false;
}

var get_url = function(x) {
    var path = url.parse(x).pathname;
    return path.split("/")[1];
}

/*
 * Obtain a random string of four lowercase alpha characters.
 * Use intended for URL generation for a room.
 */
var getRandomURL = function() {
    var text = "";
    var possible = "abcdefghhijklmnopqrstuvwxyz";
    do{
        for (var i = 0; i < 4; ++i) {
            text += possible.charAt(Math.floor(Math.random() * possible.length));
        }
    }while(isCurrentGame(text));

    return text;
};

var getRandomPhrase = function() {
    return phrases[Math.floor(Math.random() * phrases.length)];
};

var server = app.listen(80, function() {
    console.log("Server started.");
});
<|endoftext|>


<commit_before>/**
 * This is the main chart entry point, wrapping sharing-time-ui.js (which itself
 * wraps sharing-time.js).  This script is used to manage things like ajax access, orientation
 * changes, etc.
 */

(function() {

	var _defaults = {

	};

	/**
	 * SharingTime chart.  params should have, at the minimum, the endpoint for data:
	 * { dataUrl:....}
	 */
	var SharingTimeChart = window.SharingTimeChart = function(params) {
		params = params || {};
		var p = $.extend({}, _defaults);
		$.extend(p, params);

		this.sharingTime = null;
        this.ui = null;
		this.panFuncs = null;

		this.HORIZONTAL = "horizontal";
		this.VERTICAL = "vertical";

		this.load = function(options, requestParameters) {
            this.options = options;
			this.ui = new SharingTimeUI();
			requestParameters = requestParameters || {};
			var finalReqParams = $.extend({ a: params.a, d: params.d, nfsid: params.nfsid }, requestParameters);

            this.sharingTime = SharingTime.getInstance(params.data.data);
            this.ui.initialize(this.sharingTime, options);
            this.panFuncs = { "left":this.ui.panLeft, "up":this.ui.panUp, "right":this.ui.panRight, "down":this.ui.panDown };
		};

		/**
		 * Pan the chart in the given direction.
		 * @param direction One of "left", "up", "down", "right"
		 */
		this.pan = function(direction) {
			panFuncs[direction]();
		};

		/**
		 * Recenters the chart to the currently focused individual.
		 */
		this.recenter = function() {
			this.ui.recenter();
		};

		/**
		 * Sets the orientation of the chart.
		 * @param orientation Either "horizontal" or "vertical"
		 */
		this.setOrientation = function(orientation) {
			this.ui.redraw({ orientation:orientation });
		};

        this.refocus = function(personId){
            // Remove people
            $('#chart').children('div').remove();
            // Clear canvas now
            var canvas = $('#chartCanvas')[0];
            var context = canvas.getContext('2d');
            context.clearRect(0, 0, canvas.width, canvas.height);
            this.sharingTime.refocus(personId);
            // clear existing stuff
            this.ui.redraw();
        };
	};
})();
<commit_msg>Fixed panning buttons again<commit_after>/**
 * This is the main chart entry point, wrapping sharing-time-ui.js (which itself
 * wraps sharing-time.js).  This script is used to manage things like ajax access, orientation
 * changes, etc.
 */

(function() {

	var _defaults = {

	};

	/**
	 * SharingTime chart.  params should have, at the minimum, the endpoint for data:
	 * { dataUrl:....}
	 */
	var SharingTimeChart = window.SharingTimeChart = function(params) {
		params = params || {};
		var p = $.extend({}, _defaults);
		$.extend(p, params);

		this.sharingTime = null;
        this.ui = null;
		this.panFuncs = null;

		this.HORIZONTAL = "horizontal";
		this.VERTICAL = "vertical";

		this.load = function(options, requestParameters) {
            this.options = options;
			this.ui = new SharingTimeUI();
			requestParameters = requestParameters || {};
			var finalReqParams = $.extend({ a: params.a, d: params.d, nfsid: params.nfsid }, requestParameters);

            this.sharingTime = SharingTime.getInstance(params.data.data);
            this.ui.initialize(this.sharingTime, options);
            this.panFuncs = {
                "left":this.ui.panLeft,
                "up":this.ui.panUp,
                "right":this.ui.panRight,
                "down":this.ui.panDown
            };
		};

		/**
		 * Pan the chart in the given direction.
		 * @param direction One of "left", "up", "down", "right"
		 */
		this.pan = function(direction) {
			this.panFuncs[direction]();
		};

		/**
		 * Recenters the chart to the currently focused individual.
		 */
		this.recenter = function() {
			this.ui.recenter();
		};

		/**
		 * Sets the orientation of the chart.
		 * @param orientation Either "horizontal" or "vertical"
		 */
		this.setOrientation = function(orientation) {
			this.ui.redraw({ orientation:orientation });
		};

        this.refocus = function(personId){
            // Remove people
            $('#chart').children('div').remove();
            // Clear canvas now
            var canvas = $('#chartCanvas')[0];
            var context = canvas.getContext('2d');
            context.clearRect(0, 0, canvas.width, canvas.height);
            this.sharingTime.refocus(personId);
            // clear existing stuff
            this.ui.redraw();
        };
	};
})();
<|endoftext|>