<commit_before>/**
 * WARNING: This demo is a barebones implementation designed for development and evaluation
 * purposes only. It is definitely NOT production ready and does not aim to be so. Exposing the
 * demo to the public as is would introduce security risks for the host.
 **/

var express = require('express');
var expressWs = require('express-ws');
var os = require('os');
var pty = require('node-pty');

// Whether to use binary transport.
const USE_BINARY = os.platform() !== "win32";

function startServer() {
  var app = express();
  expressWs(app);

  var terminals = {},
    unsentOutput = {},
    temporaryDisposable = {};

  app.use('/xterm.css', express.static(__dirname + '/../css/xterm.css'));
  app.get('/logo.png', (req, res) => {
    res.sendFile(__dirname + '/logo.png');
  });

  app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
  });

  app.get('/test', (req, res) => {
    res.sendFile(__dirname + '/test.html');
  });

  app.get('/style.css', (req, res) => {
    res.sendFile(__dirname + '/style.css');
  });

  app.use('/dist', express.static(__dirname + '/dist'));
  app.use('/src', express.static(__dirname + '/src'));

  app.post('/terminals', (req, res) => {
    const env = Object.assign({}, process.env);
    env['COLORTERM'] = 'truecolor';
    var cols = parseInt(req.query.cols),
      rows = parseInt(req.query.rows),
      term = pty.spawn(process.platform === 'win32' ? 'pwsh.exe' : 'bash', [], {
        name: 'xterm-256color',
        cols: cols || 80,
        rows: rows || 24,
        cwd: process.platform === 'win32' ? undefined : env.PWD,
        env: env,
        encoding: USE_BINARY ? null : 'utf8'
      });

    console.log('Created terminal with PID: ' + term.pid);
    terminals[term.pid] = term;
    unsentOutput[term.pid] = '';
    temporaryDisposable[term.pid] = term.onData(function(data) {
      unsentOutput[term.pid] += data;
    });
    res.send(term.pid.toString());
    res.end();
  });

  app.post('/terminals/:pid/size', (req, res) => {
    var pid = parseInt(req.params.pid),
        cols = parseInt(req.query.cols),
        rows = parseInt(req.query.rows),
        term = terminals[pid];

    term.resize(cols, rows);
    console.log('Resized terminal ' + pid + ' to ' + cols + ' cols and ' + rows + ' rows.');
    res.end();
  });

  app.ws('/terminals/:pid', function (ws, req) {
    var term = terminals[parseInt(req.params.pid)];
    console.log('Connected to terminal ' + term.pid);
    temporaryDisposable[term.pid].dispose();
    delete temporaryDisposable[term.pid];
    ws.send(unsentOutput[term.pid]);
    delete unsentOutput[term.pid];

    // unbuffered delivery after user input
    let userInput = false;

    // string message buffering
    function buffer(socket, timeout, maxSize) {
      let s = '';
      let sender = null;
      return (data) => {
        s += data;
        if (s.length > maxSize || userInput) {
          userInput = false;
          socket.send(s);
          s = '';
          if (sender) {
            clearTimeout(sender);
            sender = null;
          }
        } else if (!sender) {
          sender = setTimeout(() => {
            socket.send(s);
            s = '';
            sender = null;
          }, timeout);
        }
      };
    }
    // binary message buffering
    function bufferUtf8(socket, timeout, maxSize) {
      let buffer = [];
      let sender = null;
      let length = 0;
      return (data) => {
        buffer.push(data);
        length += data.length;
        if (length > maxSize || userInput) {
          userInput = false;
          socket.send(Buffer.concat(buffer, length));
          buffer = [];
          length = 0;
          if (sender) {
            clearTimeout(sender);
            sender = null;
          }
        } else if (!sender) {
          sender = setTimeout(() => {
            socket.send(Buffer.concat(buffer, length));
            buffer = [];
            sender = null;
            length = 0;
          }, timeout);
        }
      };
    }
    const send = (USE_BINARY ? bufferUtf8 : buffer)(ws, 5, 262144);

    // WARNING: This is a naive implementation that will not throttle the flow of data. This means
    // it could flood the communication channel and make the terminal unresponsive. Learn more about
    // the problem and how to implement flow control at https://xtermjs.org/docs/guides/flowcontrol/
    term.onData(function(data) {
      try {
        send(data);
      } catch (ex) {
        // The WebSocket is not open, ignore
      }
    });
    ws.on('message', function(msg) {
      term.write(msg);
      userInput = true;
    });
    ws.on('close', function () {
      term.kill();
      console.log('Closed terminal ' + term.pid);
      // Clean things up
      delete terminals[term.pid];
    });
  });

  var port = process.env.PORT || 3000,
      host = os.platform() === 'win32' ? '127.0.0.1' : '0.0.0.0';

  console.log('App listening to http://127.0.0.1:' + port);
  app.listen(port, host);
}

module.exports = startServer;
<commit_msg>Avoid GC pressure from server data buffer<commit_after>/**
 * WARNING: This demo is a barebones implementation designed for development and evaluation
 * purposes only. It is definitely NOT production ready and does not aim to be so. Exposing the
 * demo to the public as is would introduce security risks for the host.
 **/

var express = require('express');
var expressWs = require('express-ws');
var os = require('os');
var pty = require('node-pty');

// Whether to use binary transport.
const USE_BINARY = os.platform() !== "win32";

function startServer() {
  var app = express();
  expressWs(app);

  var terminals = {},
    unsentOutput = {},
    temporaryDisposable = {};

  app.use('/xterm.css', express.static(__dirname + '/../css/xterm.css'));
  app.get('/logo.png', (req, res) => {
    res.sendFile(__dirname + '/logo.png');
  });

  app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
  });

  app.get('/test', (req, res) => {
    res.sendFile(__dirname + '/test.html');
  });

  app.get('/style.css', (req, res) => {
    res.sendFile(__dirname + '/style.css');
  });

  app.use('/dist', express.static(__dirname + '/dist'));
  app.use('/src', express.static(__dirname + '/src'));

  app.post('/terminals', (req, res) => {
    const env = Object.assign({}, process.env);
    env['COLORTERM'] = 'truecolor';
    var cols = parseInt(req.query.cols),
      rows = parseInt(req.query.rows),
      term = pty.spawn(process.platform === 'win32' ? 'pwsh.exe' : 'bash', [], {
        name: 'xterm-256color',
        cols: cols || 80,
        rows: rows || 24,
        cwd: process.platform === 'win32' ? undefined : env.PWD,
        env: env,
        encoding: USE_BINARY ? null : 'utf8'
      });

    console.log('Created terminal with PID: ' + term.pid);
    terminals[term.pid] = term;
    unsentOutput[term.pid] = '';
    temporaryDisposable[term.pid] = term.onData(function(data) {
      unsentOutput[term.pid] += data;
    });
    res.send(term.pid.toString());
    res.end();
  });

  app.post('/terminals/:pid/size', (req, res) => {
    var pid = parseInt(req.params.pid),
        cols = parseInt(req.query.cols),
        rows = parseInt(req.query.rows),
        term = terminals[pid];

    term.resize(cols, rows);
    console.log('Resized terminal ' + pid + ' to ' + cols + ' cols and ' + rows + ' rows.');
    res.end();
  });

  app.ws('/terminals/:pid', function (ws, req) {
    var term = terminals[parseInt(req.params.pid)];
    console.log('Connected to terminal ' + term.pid);
    temporaryDisposable[term.pid].dispose();
    delete temporaryDisposable[term.pid];
    ws.send(unsentOutput[term.pid]);
    delete unsentOutput[term.pid];

    // unbuffered delivery after user input
    let userInput = false;

    // string message buffering
    function buffer(socket, timeout, maxSize) {
      let s = '';
      let sender = null;
      return (data) => {
        s += data;
        if (s.length > maxSize || userInput) {
          userInput = false;
          socket.send(s);
          s = '';
          if (sender) {
            clearTimeout(sender);
            sender = null;
          }
        } else if (!sender) {
          sender = setTimeout(() => {
            socket.send(s);
            s = '';
            sender = null;
          }, timeout);
        }
      };
    }
    // binary message buffering
    function bufferUtf8(socket, timeout, maxSize) {
      const dataBuffer = new Uint8Array(maxSize);
      let sender = null;
      let length = 0;
      return (data) => {
        function flush() {
          socket.send(Buffer.from(dataBuffer.buffer, 0, length));
          length = 0;
          if (sender) {
            clearTimeout(sender);
            sender = null;
          }
        }
        if (length + data.length > maxSize) {
          flush();
        }
        dataBuffer.set(data, length);
        length += data.length;
        if (length > maxSize || userInput) {
          userInput = false;
          flush();
        } else if (!sender) {
          sender = setTimeout(() => {
            sender = null;
            flush();
          }, timeout);
        }
      };
    }
    const send = (USE_BINARY ? bufferUtf8 : buffer)(ws, 5, 262144);

    // WARNING: This is a naive implementation that will not throttle the flow of data. This means
    // it could flood the communication channel and make the terminal unresponsive. Learn more about
    // the problem and how to implement flow control at https://xtermjs.org/docs/guides/flowcontrol/
    term.onData(function(data) {
      try {
        send(data);
      } catch (ex) {
        // The WebSocket is not open, ignore
      }
    });
    ws.on('message', function(msg) {
      term.write(msg);
      userInput = true;
    });
    ws.on('close', function () {
      term.kill();
      console.log('Closed terminal ' + term.pid);
      // Clean things up
      delete terminals[term.pid];
    });
  });

  var port = process.env.PORT || 3000,
      host = os.platform() === 'win32' ? '127.0.0.1' : '0.0.0.0';

  console.log('App listening to http://127.0.0.1:' + port);
  app.listen(port, host);
}

module.exports = startServer;
<|endoftext|>


<commit_before>(function() {
    "use strict";

    angular
        .module("VinculacionApp")
        .run(run);

    run.$inject = ['$rootScope', '$location', '$cookieStore', '$http', '$state',
                    '$timeout'];

    function run ($rootScope, $location, $cookieStore, $http, $state, $timeout) {

        $rootScope.links = [];
        $rootScope.stateLoading = false;
        $rootScope.hideLoading = true;
        $rootScope.generalLoading = true;

        let stateUrl = "";

        // keep user logged in after page refresh
        $rootScope.globals = $cookieStore.get('globals') || {};
        if ($rootScope.globals.token) {
            $http.defaults.headers.common['Authorization'] =
            $rootScope.globals.token; // jshint ignore:line
        }

        $rootScope.$on('$locationChangeStart', function (event, next, current) {
            // redirect to login page if not logged in
            if ($location.path() !== '/' && !$rootScope.globals.token) {
                $location.path('/');
            }

            if($location.path() === '/' && $rootScope.globals.token) {
                $location.path('/home');
            }
        });

        $rootScope.$on('$stateChangeStart', stateChangeStart);

        $rootScope.$on('$stateChangeSuccess', stateChangeSuccess);

        function stateChangeStart (event, toState) {
            $rootScope.stateLoading = true;
            stateUrl = toState.url;
        }

        function stateChangeSuccess (event) {
            $timeout(function(){
                $timeout(changeViewStyles, $rootScope.generalLoading ? 1 : 100);
                $rootScope.stateLoading = false;
                $rootScope.generalLoading = true;
            }, $rootScope.generalLoading ? 500 : 100);
        }

        function changeViewStyles () {
            switch(stateUrl) {
                case "/home":
                    $rootScope.viewTitle = "Vinculacion | Home";
                    $rootScope.viewStyles = "main home";
                break;
                case "/proyectos":
                    $rootScope.viewTitle = "Vinculacion | Proyectos";
                    $rootScope.viewStyles = "main projects";
                break;
                case "/proyectos/{projectId}":
                    $rootScope.viewTitle = "Vinculacion | Proyecto";
                    $rootScope.viewStyles = "main project";
                break;
                case "/solicitudes":
                    $rootScope.viewTitle = "Vinculacion | Solicitudes";
                    $rootScope.viewStyles = "main requests";
                break;
                case "/nuevo-proyecto":
                    $rootScope.viewTitle = "Vinculacion | Nuevo Proyecto";
                    $rootScope.viewStyles = "main addproject";
                break;
                case "/":
                    $rootScope.viewTitle = "Vinculacion | Bienvenido";
                    $rootScope.viewStyles = "landing";
                break;
            }
        }

    }
})();<commit_msg>Refactor and cleanup<commit_after>(function () {
    "use strict";

    angular
        .module("VinculacionApp")
        .run(run);

    run.$inject = ['$rootScope', '$location', '$cookieStore', '$http', '$state',
                    '$timeout'];

    function run ($rootScope, $location, $cookieStore, $http, $state, $timeout) {

        $rootScope.links = [];
        $rootScope.stateLoading = false;
        $rootScope.hideLoading = true;
        $rootScope.generalLoading = true;

        let stateUrl = "";

        getBasicAuthentication();

        $rootScope.$on('$locationChangeStart', locationChangeStart);

        $rootScope.$on('$stateChangeStart', stateChangeStart);

        $rootScope.$on('$stateChangeSuccess', stateChangeSuccess);

        function getBasicAuthentication () {
            $rootScope.globals = $cookieStore.get('globals') || {};

            if ($rootScope.globals.token) {
                $http.defaults.headers.common['Authorization'] =
                $rootScope.globals.token;
            }
        }

        function locationChangeStart (event, next, current) {
            if ($location.path() !== '/' && !$rootScope.globals.token) {
                $location.path('/');
            }

            if($location.path() === '/' && $rootScope.globals.token) {
                $location.path('/home');
            }
        }

        function stateChangeStart (event, toState) {
            $rootScope.stateLoading = true;
            stateUrl = toState.url;
        }

        function stateChangeSuccess (event) {
            $timeout(function(){
                $timeout(changeViewStyles, $rootScope.generalLoading ? 1 : 100);
                $rootScope.stateLoading = false;
                $rootScope.generalLoading = true;
            }, $rootScope.generalLoading ? 500 : 100);
        }

        function changeViewStyles () {
            switch(stateUrl) {
                case "/home":
                    $rootScope.viewTitle = "Vinculacion | Home";
                    $rootScope.viewStyles = "main home";
                break;
                case "/proyectos":
                    $rootScope.viewTitle = "Vinculacion | Proyectos";
                    $rootScope.viewStyles = "main projects";
                break;
                case "/proyectos/{projectId}":
                    $rootScope.viewTitle = "Vinculacion | Proyecto";
                    $rootScope.viewStyles = "main project";
                break;
                case "/solicitudes":
                    $rootScope.viewTitle = "Vinculacion | Solicitudes";
                    $rootScope.viewStyles = "main requests";
                break;
                case "/nuevo-proyecto":
                    $rootScope.viewTitle = "Vinculacion | Nuevo Proyecto";
                    $rootScope.viewStyles = "main addproject";
                break;
                case "/":
                    $rootScope.viewTitle = "Vinculacion | Bienvenido";
                    $rootScope.viewStyles = "landing";
                break;
            }
        }

    }
})();<|endoftext|>


<commit_before>var map;
var service;
var actualPosition;
var markers = [];
var defaultMarkerColor = "FE7569";
var somePlaceIsSelected = false;

function initMap() {
    var myLatLng = {lat: 52.54063980000001, lng: -1.8916148000000703};
    var mapDiv = document.getElementById('map');
    map = new google.maps.Map(mapDiv, {
        center: myLatLng,
        zoom: 16
    });

    var infoWindow = new google.maps.InfoWindow({map: map});

    // Try HTML5 geolocation.
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            actualPosition = {
                lat: position.coords.latitude,
                lng: position.coords.longitude
            };
            createMarkerOnMap(actualPosition, "Vaše poloha", "FFFFFF")

            map.setCenter(actualPosition);
            console.log("map initialized");

        }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
        });
    } else {
        // Browser doesn't support Geolocation
        handleLocationError(false, infoWindow, map.getCenter());
    }
}

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
    infoWindow.setPosition(pos);
    infoWindow.setContent(browserHasGeolocation ?
        'Error: The Geolocation service failed.' :
        'Error: Your browser doesn\'t support geolocation.');
}

function getNearbyLocations() {
    for( var i = 0; i < markers.length; i++ ) {
        markers[i].marker.setMap(null);
    }
    markers = [];
    var request = {
        location: actualPosition,
        radius: document.getElementById('radius-input').value,
        types: ['restaurant'],
    };
    service = new google.maps.places.PlacesService(map);
    service.nearbySearch(request, markNearbyPlaces);
}

function markNearbyPlaces(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
        var userId = localStorage.getItem("id");
        var userPlaces;
        if(userId != null && userId != undefined){
            makeCorsRequest("GET", "https://ivebeenthereapi-matyapav.rhcloud.com/userPlaces/"+userId, null, function (responseText) {
                if(responseText){
                    userPlaces = JSON.parse(responseText);
                }
                results.forEach(function (v,i) {
                    var place = results[i];
                    var marker = null;
                    var color = null;
                    var clickedColor = null;
                    var isInUsersPlaces = false;
                    userPlaces.forEach(function (userPlace) {
                        if(userPlace != null) {
                            if (encodeURIComponent(userPlace.name) == encodeURIComponent(place.name)) {
                                isInUsersPlaces = true;
                            }
                        }
                    });
                    if(isInUsersPlaces){
                        color = "00ff00";
                        clickedColor = "006400";
                    }else{
                        color = defaultMarkerColor;
                        clickedColor = "ff0000";
                    }
                    var marker = createMarkerOnMap(place.geometry.location, place.name, color);
                    markers.push({marker: marker, color: color});
                    marker.addListener('click', function(){
                        markers.forEach(function (v,i) {
                            setMarkerColor(markers[i].marker, markers[i].color);
                        });
                        setMarkerColor(marker, clickedColor)
                        showInfoAboutPlace(place, marker, isInUsersPlaces);
                    });
                });
            });
        }
    }
}

function createMarkerOnMap(position, title, pinColor) {
    var pinImage = new google.maps.MarkerImage("https://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor,
        new google.maps.Size(21, 34),
        new google.maps.Point(0, 0),
        new google.maps.Point(10, 34));
    var pinShadow = new google.maps.MarkerImage("https://chart.apis.google.com/chart?chst=d_map_pin_shadow",
        new google.maps.Size(40, 37),
        new google.maps.Point(0, 0),
        new google.maps.Point(12, 35));

    var marker = new google.maps.Marker({
        position: position,
        map: map,
        icon: pinImage,
        shadow: pinShadow,
        title: title
    });
    return marker;
}

function showInfoAboutPlace(place,marker, alreadyVisited){

    document.getElementById('place-name').innerText = place.name;
    document.getElementById('place-address').innerText = place.vicinity;
    if(place.opening_hours != null){
        document.getElementById('place-open').innerText = place.opening_hours.open_now? 'Ano':'Ne';
    }else{
        document.getElementById('place-open').innerText = "-";
    }

    document.getElementById('actions').style = "visibility: visible";

    somePlaceIsSelected = true;
    console.log(place)
    if(!alreadyVisited) {
        document.getElementById('iwasthere').addEventListener('click', function () {
            var placeObj = {name: place.name, address: place.vicinity};
            userId = localStorage.getItem("id");
            markPlaceForUser(placeObj, userId);
            for(var i=0; i< markers.length; i++){
                if(markers[i].marker = marker){
                    markers[i].color = "00ff00";
                }
            }
        })
    }else{
        document.getElementById('iwasthere').innerHTML = "Nebyl jsem tady.";
        //TODO unseen place
    }
}

function setMarkerColor(marker, color) {
    marker.setIcon(new google.maps.MarkerImage("https://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|"+color ,
        new google.maps.Size(21, 34),
        new google.maps.Point(0, 0),
        new google.maps.Point(10, 34)));
}<commit_msg>Implementing "I was there" action #20.5<commit_after>var map;
var service;
var actualPosition;
var markers = [];
var defaultMarkerColor = "FE7569";
var somePlaceIsSelected = false;

function initMap() {
    var myLatLng = {lat: 52.54063980000001, lng: -1.8916148000000703};
    var mapDiv = document.getElementById('map');
    map = new google.maps.Map(mapDiv, {
        center: myLatLng,
        zoom: 16
    });

    var infoWindow = new google.maps.InfoWindow({map: map});

    // Try HTML5 geolocation.
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            actualPosition = {
                lat: position.coords.latitude,
                lng: position.coords.longitude
            };
            createMarkerOnMap(actualPosition, "Vaše poloha", "FFFFFF")

            map.setCenter(actualPosition);
            console.log("map initialized");

        }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
        });
    } else {
        // Browser doesn't support Geolocation
        handleLocationError(false, infoWindow, map.getCenter());
    }
}

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
    infoWindow.setPosition(pos);
    infoWindow.setContent(browserHasGeolocation ?
        'Error: The Geolocation service failed.' :
        'Error: Your browser doesn\'t support geolocation.');
}

function getNearbyLocations() {
    for( var i = 0; i < markers.length; i++ ) {
        markers[i].marker.setMap(null);
    }
    markers = [];
    var request = {
        location: actualPosition,
        radius: document.getElementById('radius-input').value,
        types: ['restaurant'],
    };
    service = new google.maps.places.PlacesService(map);
    service.nearbySearch(request, markNearbyPlaces);
}

function markNearbyPlaces(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
        var userId = localStorage.getItem("id");
        var userPlaces;
        if(userId != null && userId != undefined){
            makeCorsRequest("GET", "https://ivebeenthereapi-matyapav.rhcloud.com/userPlaces/"+userId, null, function (responseText) {
                if(responseText){
                    userPlaces = JSON.parse(responseText);
                }
                results.forEach(function (v,i) {
                    var place = results[i];
                    var marker = null;
                    var color = null;
                    var clickedColor = null;
                    var isInUsersPlaces = false;
                    userPlaces.forEach(function (userPlace) {
                        if(userPlace != null) {
                            if (encodeURIComponent(userPlace.name) == encodeURIComponent(place.name)) {
                                isInUsersPlaces = true;
                            }
                        }
                    });
                    if(isInUsersPlaces){
                        color = "00ff00";
                        clickedColor = "006400";
                    }else{
                        color = defaultMarkerColor;
                        clickedColor = "ff0000";
                    }
                    var marker = createMarkerOnMap(place.geometry.location, place.name, color);
                    markers.push({marker: marker, color: color});
                    marker.addListener('click', function(){
                        markers.forEach(function (v,i) {
                            setMarkerColor(markers[i].marker, markers[i].color);
                        });
                        setMarkerColor(marker, clickedColor)
                        showInfoAboutPlace(place, marker, isInUsersPlaces);
                    });
                });
            });
        }
    }
}

function createMarkerOnMap(position, title, pinColor) {
    var pinImage = new google.maps.MarkerImage("https://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor,
        new google.maps.Size(21, 34),
        new google.maps.Point(0, 0),
        new google.maps.Point(10, 34));
    var pinShadow = new google.maps.MarkerImage("https://chart.apis.google.com/chart?chst=d_map_pin_shadow",
        new google.maps.Size(40, 37),
        new google.maps.Point(0, 0),
        new google.maps.Point(12, 35));

    var marker = new google.maps.Marker({
        position: position,
        map: map,
        icon: pinImage,
        shadow: pinShadow,
        title: title
    });
    return marker;
}

function showInfoAboutPlace(place,marker, alreadyVisited){

    document.getElementById('place-name').innerText = place.name;
    document.getElementById('place-address').innerText = place.vicinity;
    if(place.opening_hours != null){
        document.getElementById('place-open').innerText = place.opening_hours.open_now? 'Ano':'Ne';
    }else{
        document.getElementById('place-open').innerText = "-";
    }

    document.getElementById('actions').style = "visibility: visible";

    somePlaceIsSelected = true;
    console.log(place)
    if(!alreadyVisited) {
        document.getElementById('iwasthere').innerHTML = "Byl jsem tu.";
        document.getElementById('iwasthere').addEventListener('click', function () {
            var placeObj = {name: place.name, address: place.vicinity};
            userId = localStorage.getItem("id");
            markPlaceForUser(placeObj, userId);
            for(var i=0; i< markers.length; i++){
                if(markers[i].marker = marker){
                    markers[i].color = "00ff00";
                }
            }
        })
    }else{
        document.getElementById('iwasthere').innerHTML = "Nebyl jsem tady.";
        //TODO unseen place
    }
}

function setMarkerColor(marker, color) {
    marker.setIcon(new google.maps.MarkerImage("https://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|"+color ,
        new google.maps.Size(21, 34),
        new google.maps.Point(0, 0),
        new google.maps.Point(10, 34)));
}<|endoftext|>


<commit_before>function init(minLat, minLon, maxLat, maxLon) {
    var bb = new google.maps.LatLngBounds(new google.maps.LatLng(minLat, minLon),
					  new google.maps.LatLng(maxLat, maxLon));
    var map = new google.maps.Map(document.getElementById("map_canvas"), { zoom: 6,
									   mapTypeId: google.maps.MapTypeId.ROADMAP,
									   center: bb.getCenter() });
    var directionsDisplay = new google.maps.DirectionsRenderer();
    directionsDisplay.setMap(map);
    var directionsService = new google.maps.DirectionsService();

    $('body').layout({ defaults: { spacing_open: 0 },
                       applyDefaultStyles: true,
                       west: { size: 320 },
                       north: { innerHeight: 30 },
                       center: { onresize_end: function () { google.maps.event.trigger(map, "resize"); } } });
    map.fitBounds(bb);

    var placeService = new google.maps.places.PlacesService(map);

    var geocoder = new google.maps.Geocoder();
    var autocomplete = {
      //This bit uses the geocoder to fetch address values
      source: function(request, response) {
          geocoder.geocode( {'address': request.term, 'bounds': bb }, function(results, status) {
          response($.map(results, function(item) {
            return {
              label: item.formatted_address,
              value: item.formatted_address,
            }
          }));
	  })},
    }
    $("#from-input").autocomplete(autocomplete);
    $("#to-input").autocomplete(autocomplete);

    $("#plan-button").button();
    $("form#directions-form").submit(function() {
	$('#error-widget').hide();

	var oldPlanButtonVal = $("#plan-button").val();

	$("#plan-button").attr('disabled', 'disabled');
	$("#plan-button").val("Working...");

	var request = {
            origin: $("#from-input").val(),
            destination: $("#to-input").val(),
            travelMode: google.maps.DirectionsTravelMode.DRIVING
	};

	directionsService.route(request, function(response, status) {
	    $("#plan-button").removeAttr('disabled');
	    $("#plan-button").val(oldPlanButtonVal);

	    if (status == google.maps.DirectionsStatus.OK) {
		directionsDisplay.setDirections(response);
	    } else {
		$('#error-widget').show();
		console.log("Error processing directions!");
	    }
	});

	return false;
    });

    $("#reverse-button").button({
	text: false,
	icons: {
	    primary: 'ui-icon-shuffle'
	}
    }).click(function() {
	var fromval = $("#from-input").val();
	$("#from-input").val($("#to-input").val());
	$("#to-input").val(fromval);
    });
}
<commit_msg>Blur from/to input fields on form submit<commit_after>function init(minLat, minLon, maxLat, maxLon) {
    var bb = new google.maps.LatLngBounds(new google.maps.LatLng(minLat, minLon),
					  new google.maps.LatLng(maxLat, maxLon));
    var map = new google.maps.Map(document.getElementById("map_canvas"), { zoom: 6,
									   mapTypeId: google.maps.MapTypeId.ROADMAP,
									   center: bb.getCenter() });
    var directionsDisplay = new google.maps.DirectionsRenderer();
    directionsDisplay.setMap(map);
    var directionsService = new google.maps.DirectionsService();

    $('body').layout({ defaults: { spacing_open: 0 },
                       applyDefaultStyles: true,
                       west: { size: 320 },
                       north: { innerHeight: 30 },
                       center: { onresize_end: function () { google.maps.event.trigger(map, "resize"); } } });
    map.fitBounds(bb);

    var placeService = new google.maps.places.PlacesService(map);

    var geocoder = new google.maps.Geocoder();
    var autocomplete = {
      //This bit uses the geocoder to fetch address values
      source: function(request, response) {
          geocoder.geocode( {'address': request.term, 'bounds': bb }, function(results, status) {
          response($.map(results, function(item) {
            return {
              label: item.formatted_address,
              value: item.formatted_address,
            }
          }));
	  })},
    }
    $("#from-input").autocomplete(autocomplete);
    $("#to-input").autocomplete(autocomplete);

    $("#plan-button").button();
    $("form#directions-form").submit(function() {
	$('#error-widget').hide();
	$('#from-input').blur();
	$('#to-input').blur();

	var oldPlanButtonVal = $("#plan-button").val();

	$("#plan-button").attr('disabled', 'disabled');
	$("#plan-button").val("Working...");

	var request = {
            origin: $("#from-input").val(),
            destination: $("#to-input").val(),
            travelMode: google.maps.DirectionsTravelMode.DRIVING
	};

	directionsService.route(request, function(response, status) {
	    $("#plan-button").removeAttr('disabled');
	    $("#plan-button").val(oldPlanButtonVal);

	    if (status == google.maps.DirectionsStatus.OK) {
		directionsDisplay.setDirections(response);
	    } else {
		$('#error-widget').show();
		console.log("Error processing directions!");
	    }
	});

	return false;
    });

    $("#reverse-button").button({
	text: false,
	icons: {
	    primary: 'ui-icon-shuffle'
	}
    }).click(function() {
	var fromval = $("#from-input").val();
	$("#from-input").val($("#to-input").val());
	$("#to-input").val(fromval);
    });
}
<|endoftext|>


<commit_before>// set up the map
var map = new L.Map('map').fitWorld();

// create the tile layer with correct attribution
var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var osmAttrib='Map data © OpenStreetMap contributors';
var osm = new L.TileLayer(osmUrl, {attribution: osmAttrib});

// start the map in Karlsruhe, Germany
//map.setView(new L.LatLng(49.00, 8.40), 15);
map.addLayer(osm);

// markers for containers
var clothesMarker = L.AwesomeMarkers.icon({
  prefix: 'ion',
  icon: 'tshirt',
  markerColor: 'cadetblue'
});

var glassMarker = L.AwesomeMarkers.icon({
  prefix: 'ion',
  icon: 'wineglass',
  markerColor: 'blue'
});

var batteriesMarker = L.AwesomeMarkers.icon({
  prefix: 'ion',
  icon: 'battery-low',
  markerColor: 'orange'
});

// OverPassAPI overlays
var clothesLayer = new L.OverPassLayer({
  query: "node['amenity'='recycling']['recycling:clothes'='yes']({{bbox}});out;",
  markerIcon: clothesMarker,
});

var glassLayer = new L.OverPassLayer({
  query: "node['amenity'='recycling']['recycling:glass'='yes']({{bbox}});out;",
  markerIcon: glassMarker,
});

var batteriesLayer = new L.OverPassLayer({
  query: "node['amenity'='recycling']['recycling:batteries'='yes']({{bbox}});out;",
  markerIcon: batteriesMarker,
});

map.addLayer(clothesLayer);
map.addLayer(glassLayer);
map.addLayer(batteriesLayer);

// Layer control (switch on/off layers)
var baseMap = {
    "Base": osm
};

var overlayMaps = {
    "Clothes": clothesLayer,
    "Glass": glassLayer,
    "Batteries": batteriesLayer
};

L.control.layers(baseMap, overlayMaps).addTo(map);
<commit_msg>Add icons to layers control and make it open by default<commit_after>// set up the map
var map = new L.Map('map').fitWorld();

// create the tile layer with correct attribution
var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var osmAttrib='Map data © OpenStreetMap contributors';
var osm = new L.TileLayer(osmUrl, {attribution: osmAttrib});

// start the map in Karlsruhe, Germany
//map.setView(new L.LatLng(49.00, 8.40), 15);
map.addLayer(osm);

// markers for containers
var clothesMarker = L.AwesomeMarkers.icon({
  prefix: 'ion',
  icon: 'tshirt',
  markerColor: 'cadetblue'
});

var glassMarker = L.AwesomeMarkers.icon({
  prefix: 'ion',
  icon: 'wineglass',
  markerColor: 'blue'
});

var batteriesMarker = L.AwesomeMarkers.icon({
  prefix: 'ion',
  icon: 'battery-low',
  markerColor: 'orange'
});

// OverPassAPI overlays
var clothesLayer = new L.OverPassLayer({
  query: 'node["amenity"="recycling"]["recycling:clothes"="yes"]({{bbox}});out;',
  markerIcon: clothesMarker,
});

var glassLayer = new L.OverPassLayer({
  query: 'node["amenity"="recycling"]["recycling:glass"="yes"]({{bbox}});out;',
  markerIcon: glassMarker,
});

var batteriesLayer = new L.OverPassLayer({
  query: 'node["amenity"="recycling"]["recycling:batteries"="yes"]({{bbox}});out;',
  markerIcon: batteriesMarker,
});

map.addLayer(clothesLayer);
map.addLayer(glassLayer);
map.addLayer(batteriesLayer);

// Layer control (switch on/off layers)
var overlays = {
  ' Batteries': batteriesLayer,
  ' Clothes': clothesLayer,
  ' Glass': glassLayer
};

L.control.layers({}, overlays, {collapsed: false}).addTo(map);
<|endoftext|>


<commit_before>
App.Map = function(tiles, player) {
  this.tiles     = tiles;
  this.width     = tiles.length;
  this.height    = tiles[0].length;
  this.scheduler = new ROT.Scheduler.Simple();
  this.engine    = new ROT.Engine(this.scheduler);
  this.entities  = [];
  // add entities:
  this.addEntityAtRandPos(player);
  for (var i=0; i<50; i++) {
    var fungus;
    if (Math.random()>0.25) {
      fungus = new App.Entity(App.Templates.fungus);
    } else {
      fungus = new App.Entity(App.Templates.poisonousFungus);
    }
    this.addEntityAtRandPos(fungus);
  }
};

// tiles:

App.Map.prototype.getTile = function(x, y) {
  if (x<0 || x>=this.width || y<0 || y>=this.height) {
    return App.Tiles.null;
  }
  return this.tiles[x][y] || App.Tiles.null;
};

App.Map.prototype.getRandFloorPos = function() {
  var x, y;
  do {
    x = Math.floor(Math.random()*this.width);
    y = Math.floor(Math.random()*this.height);
  } while (!this.isOpen(x, y));
  return {x:x, y:y};
};

App.Map.prototype.dig = function(x, y) {
  if (this.getTile(x,y).isDiggable) {
    this.tiles[x][y] = App.Tiles.floor;
  }
};

App.Map.prototype.isOpen = function(x, y) {
  return this.getTile(x,y).isWalkable && !this.getEntityAt(x,y);
};

// entities:

App.Map.prototype.getEntityAt = function(x, y) {
  for (var i=0; i<this.entities.length; i++) {
    var entity = this.entities[i];
    if (entity.x==x && entity.y==y) {
      return entity;
    }
  }
  return null;
};

App.Map.prototype.addEntity = function(entity) {
  if (entity.x<0 || entity.x>=this.width || entity.y<0 || entity.y>=this.height) {
    throw new Error('addEntity: entity out of map bounds');
  }
  entity.map = this;
  this.entities.push(entity);
  if (entity.hasMixin('Acting')) {
    this.scheduler.add(entity, true);
  }
};

App.Map.prototype.addEntityAtRandPos = function(entity) {
  var pos  = this.getRandFloorPos();
  entity.x = pos.x;
  entity.y = pos.y;
  this.addEntity(entity);
};

App.Map.prototype.removeEntity = function(entity) {
  for (var i=0; i<this.entities.length; i++) {
    if (this.entities[i] == entity) {
      this.entities.splice(i, 1);
      break;
    }
  }
  if (entity.hasMixin('Acting')) {
    this.scheduler.remove(entity);
  }
};

App.Map.prototype.getEntitiesWithinRadius = function(x, y, radius) {
  var entities = [];
  var left   = x-radius;
  var right  = x+radius;
  var top    = y-radius;
  var bottom = y+radius;
  for (var i=0; i<this.entities.length; i++) {
    var e = this.entities[i];
    if (e.x>=left && e.x<=right && e.y>=top && e.y<=bottom) {
      entities.push(e);
    }
  }
  return entities;
};
<commit_msg>to get surrounding positions:  map.getAllPosAround(x,y)<commit_after>
App.Map = function(tiles, player) {
  this.tiles     = tiles;
  this.width     = tiles.length;
  this.height    = tiles[0].length;
  this.scheduler = new ROT.Scheduler.Simple();
  this.engine    = new ROT.Engine(this.scheduler);
  this.entities  = [];
  // add entities:
  this.addEntityAtRandPos(player);
  for (var i=0; i<50; i++) {
    var fungus;
    if (Math.random()>0.25) {
      fungus = new App.Entity(App.Templates.fungus);
    } else {
      fungus = new App.Entity(App.Templates.poisonousFungus);
    }
    this.addEntityAtRandPos(fungus);
  }
};

// tiles & tile positions:

App.Map.prototype.getTile = function(x, y) {
  if (x<0 || x>=this.width || y<0 || y>=this.height) {
    return App.Tiles.null;
  }
  return this.tiles[x][y] || App.Tiles.null;
};

App.Map.prototype.getRandFloorPos = function() {
  var x, y;
  do {
    x = Math.floor(Math.random()*this.width);
    y = Math.floor(Math.random()*this.height);
  } while (!this.isOpen(x, y));
  return {x:x, y:y};
};

App.Map.prototype.dig = function(x, y) {
  if (this.getTile(x,y).isDiggable) {
    this.tiles[x][y] = App.Tiles.floor;
  }
};

App.Map.prototype.isOpen = function(x, y) {
  return this.getTile(x,y).isWalkable && !this.getEntityAt(x,y);
};

App.Map.prototype.getAllPosAround = function(x, y) {
  var positions = [];
  for (var dx=-1; dx<2; dx++) {
    for (var dy=-1; dy<2; dy++) {
      if (dx==0 && dy==0) { continue; }
      positions.push({x:x+dx, y:y+dy});
    }
  }
  return positions.randomize();
}

// entities:

App.Map.prototype.getEntityAt = function(x, y) {
  for (var i=0; i<this.entities.length; i++) {
    var entity = this.entities[i];
    if (entity.x==x && entity.y==y) {
      return entity;
    }
  }
  return null;
};

App.Map.prototype.addEntity = function(entity) {
  if (entity.x<0 || entity.x>=this.width || entity.y<0 || entity.y>=this.height) {
    throw new Error('addEntity: entity out of map bounds');
  }
  entity.map = this;
  this.entities.push(entity);
  if (entity.hasMixin('Acting')) {
    this.scheduler.add(entity, true);
  }
};

App.Map.prototype.addEntityAtRandPos = function(entity) {
  var pos  = this.getRandFloorPos();
  entity.x = pos.x;
  entity.y = pos.y;
  this.addEntity(entity);
};

App.Map.prototype.removeEntity = function(entity) {
  for (var i=0; i<this.entities.length; i++) {
    if (this.entities[i] == entity) {
      this.entities.splice(i, 1);
      break;
    }
  }
  if (entity.hasMixin('Acting')) {
    this.scheduler.remove(entity);
  }
};

App.Map.prototype.getEntitiesWithinRadius = function(x, y, radius) {
  var entities = [];
  var left   = x-radius;
  var right  = x+radius;
  var top    = y-radius;
  var bottom = y+radius;
  for (var i=0; i<this.entities.length; i++) {
    var e = this.entities[i];
    if (e.x>=left && e.x<=right && e.y>=top && e.y<=bottom) {
      entities.push(e);
    }
  }
  return entities;
};
<|endoftext|>


<commit_before>/*
 * Lunchpad frontend main app
 *
 * New Version for socket.io and angular
 *
 * @author Markus Riegel <riegel.markus@googlemail.com>
 */

angular.module('lunchpad',[
	'ngAnimate',
	'ngRoute',

	'viewVenuesController',
	'viewVenueDetailController',
	'viewSettingsController',

	'lpConfig',
	'lpError'
])

.config(['$routeProvider','LpConfigProvider',
	function($routeProvider,LpConfigProvider){
		var LpConfig = LpConfigProvider.$get();

		$routeProvider.
			when('/venues', {

				templateUrl: LpConfig.getTemplate('view.venues'),
				controller: 'ViewVenuesController'

			}).
			when('/venue/:venueId', {

				templateUrl: LpConfig.getTemplate('view.venuedetail'),
				controller: 'ViewVenueDetailController'

			}).
			when('/settings', {

				templateUrl: LpConfig.getTemplate('view.settings'),
				controller: 'ViewSettingsController'

			}).
			otherwise({

				redirectTo: '/venues'

			});
	}
])

.provider('$anchorScroll',function() {
	this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
		function scroll() {}
		return scroll;
	}];
})

.controller('ViewController',[
'$scope', '$location',
function($scope, $location){

	$scope.$on('$locationChangeStart', function(event, targetRoute, currentRoute){
		// get relevant route from route
		var naviName = targetRoute.split('#')[1].split('/')[1];
		console.log(naviName);
		if( naviName === 'venues'){
			console.log('back!');
			$scope.stateAnimClass = 'back';
		} else {
			console.log('front!');
			$scope.stateAnimClass = '';
		}
	});

}]);
<commit_msg>config for ng-animate<commit_after>/*
 * Lunchpad frontend main app
 *
 * New Version for socket.io and angular
 *
 * @author Markus Riegel <riegel.markus@googlemail.com>
 */

angular.module('lunchpad',[
	'ngAnimate',
	'ngRoute',

	'viewVenuesController',
	'viewVenueDetailController',
	'viewSettingsController',

	'lpConfig',
	'lpError'
])

.config(['$routeProvider','LpConfigProvider','$animateProvider',
	function($routeProvider,LpConfigProvider,$animateProvider){
		var LpConfig = LpConfigProvider.$get();

		$routeProvider.
			when('/venues', {

				templateUrl: LpConfig.getTemplate('view.venues'),
				controller: 'ViewVenuesController'

			}).
			when('/venue/:venueId', {

				templateUrl: LpConfig.getTemplate('view.venuedetail'),
				controller: 'ViewVenueDetailController'

			}).
			when('/settings', {

				templateUrl: LpConfig.getTemplate('view.settings'),
				controller: 'ViewSettingsController'

			}).
			otherwise({

				redirectTo: '/venues'

			});

		$animateProvider.classNameFilter(/lunch-animate/);
	}
])

.provider('$anchorScroll',function() {
	this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
		function scroll() {}
		return scroll;
	}];
})

.controller('ViewController',[
'$scope', '$location',
function($scope, $location){

	$scope.$on('$locationChangeStart', function(event, targetRoute, currentRoute){
		// get relevant route from route
		var naviName = targetRoute.split('#')[1].split('/')[1];
		console.log(naviName);
		if( naviName === 'venues'){
			console.log('back!');
			$scope.stateAnimClass = 'back';
		} else {
			console.log('front!');
			$scope.stateAnimClass = '';
		}
	});

}]);
<|endoftext|>


<commit_before>(function(){
  var crypt = require('crypt'),
      utf8 = require('charenc').utf8,
      bin = require('charenc').bin,

  // The core
  md5 = function (message) {
    // Convert to byte array
    if (message.constructor == String)
      message = utf8.stringToBytes(message);
    else if (typeof message != 'object')
      message = message.toString();
    // else, assume byte array already

    var m = crypt.bytesToWords(message),
        l = message.length * 8,
        a =  1732584193,
        b = -271733879,
        c = -1732584194,
        d =  271733878;

    // Swap endian
    for (var i = 0; i < m.length; i++) {
      m[i] = ((m[i] <<  8) | (m[i] >>> 24)) & 0x00FF00FF |
             ((m[i] << 24) | (m[i] >>>  8)) & 0xFF00FF00;
    }

    // Padding
    m[l >>> 5] |= 0x80 << (l % 32);
    m[(((l + 64) >>> 9) << 4) + 14] = l;

    // Method shortcuts
    var FF = md5._ff,
        GG = md5._gg,
        HH = md5._hh,
        II = md5._ii;

    for (var i = 0; i < m.length; i += 16) {

      var aa = a,
          bb = b,
          cc = c,
          dd = d;

      a = FF(a, b, c, d, m[i+ 0],  7, -680876936);
      d = FF(d, a, b, c, m[i+ 1], 12, -389564586);
      c = FF(c, d, a, b, m[i+ 2], 17,  606105819);
      b = FF(b, c, d, a, m[i+ 3], 22, -1044525330);
      a = FF(a, b, c, d, m[i+ 4],  7, -176418897);
      d = FF(d, a, b, c, m[i+ 5], 12,  1200080426);
      c = FF(c, d, a, b, m[i+ 6], 17, -1473231341);
      b = FF(b, c, d, a, m[i+ 7], 22, -45705983);
      a = FF(a, b, c, d, m[i+ 8],  7,  1770035416);
      d = FF(d, a, b, c, m[i+ 9], 12, -1958414417);
      c = FF(c, d, a, b, m[i+10], 17, -42063);
      b = FF(b, c, d, a, m[i+11], 22, -1990404162);
      a = FF(a, b, c, d, m[i+12],  7,  1804603682);
      d = FF(d, a, b, c, m[i+13], 12, -40341101);
      c = FF(c, d, a, b, m[i+14], 17, -1502002290);
      b = FF(b, c, d, a, m[i+15], 22,  1236535329);

      a = GG(a, b, c, d, m[i+ 1],  5, -165796510);
      d = GG(d, a, b, c, m[i+ 6],  9, -1069501632);
      c = GG(c, d, a, b, m[i+11], 14,  643717713);
      b = GG(b, c, d, a, m[i+ 0], 20, -373897302);
      a = GG(a, b, c, d, m[i+ 5],  5, -701558691);
      d = GG(d, a, b, c, m[i+10],  9,  38016083);
      c = GG(c, d, a, b, m[i+15], 14, -660478335);
      b = GG(b, c, d, a, m[i+ 4], 20, -405537848);
      a = GG(a, b, c, d, m[i+ 9],  5,  568446438);
      d = GG(d, a, b, c, m[i+14],  9, -1019803690);
      c = GG(c, d, a, b, m[i+ 3], 14, -187363961);
      b = GG(b, c, d, a, m[i+ 8], 20,  1163531501);
      a = GG(a, b, c, d, m[i+13],  5, -1444681467);
      d = GG(d, a, b, c, m[i+ 2],  9, -51403784);
      c = GG(c, d, a, b, m[i+ 7], 14,  1735328473);
      b = GG(b, c, d, a, m[i+12], 20, -1926607734);

      a = HH(a, b, c, d, m[i+ 5],  4, -378558);
      d = HH(d, a, b, c, m[i+ 8], 11, -2022574463);
      c = HH(c, d, a, b, m[i+11], 16,  1839030562);
      b = HH(b, c, d, a, m[i+14], 23, -35309556);
      a = HH(a, b, c, d, m[i+ 1],  4, -1530992060);
      d = HH(d, a, b, c, m[i+ 4], 11,  1272893353);
      c = HH(c, d, a, b, m[i+ 7], 16, -155497632);
      b = HH(b, c, d, a, m[i+10], 23, -1094730640);
      a = HH(a, b, c, d, m[i+13],  4,  681279174);
      d = HH(d, a, b, c, m[i+ 0], 11, -358537222);
      c = HH(c, d, a, b, m[i+ 3], 16, -722521979);
      b = HH(b, c, d, a, m[i+ 6], 23,  76029189);
      a = HH(a, b, c, d, m[i+ 9],  4, -640364487);
      d = HH(d, a, b, c, m[i+12], 11, -421815835);
      c = HH(c, d, a, b, m[i+15], 16,  530742520);
      b = HH(b, c, d, a, m[i+ 2], 23, -995338651);

      a = II(a, b, c, d, m[i+ 0],  6, -198630844);
      d = II(d, a, b, c, m[i+ 7], 10,  1126891415);
      c = II(c, d, a, b, m[i+14], 15, -1416354905);
      b = II(b, c, d, a, m[i+ 5], 21, -57434055);
      a = II(a, b, c, d, m[i+12],  6,  1700485571);
      d = II(d, a, b, c, m[i+ 3], 10, -1894986606);
      c = II(c, d, a, b, m[i+10], 15, -1051523);
      b = II(b, c, d, a, m[i+ 1], 21, -2054922799);
      a = II(a, b, c, d, m[i+ 8],  6,  1873313359);
      d = II(d, a, b, c, m[i+15], 10, -30611744);
      c = II(c, d, a, b, m[i+ 6], 15, -1560198380);
      b = II(b, c, d, a, m[i+13], 21,  1309151649);
      a = II(a, b, c, d, m[i+ 4],  6, -145523070);
      d = II(d, a, b, c, m[i+11], 10, -1120210379);
      c = II(c, d, a, b, m[i+ 2], 15,  718787259);
      b = II(b, c, d, a, m[i+ 9], 21, -343485551);

      a = (a + aa) >>> 0;
      b = (b + bb) >>> 0;
      c = (c + cc) >>> 0;
      d = (d + dd) >>> 0;
    }

    return crypt.endian([a, b, c, d]);
  };

  // Auxiliary functions
  md5._ff  = function (a, b, c, d, x, s, t) {
    var n = a + (b & c | ~b & d) + (x >>> 0) + t;
    return ((n << s) | (n >>> (32 - s))) + b;
  };
  md5._gg  = function (a, b, c, d, x, s, t) {
    var n = a + (b & d | c & ~d) + (x >>> 0) + t;
    return ((n << s) | (n >>> (32 - s))) + b;
  };
  md5._hh  = function (a, b, c, d, x, s, t) {
    var n = a + (b ^ c ^ d) + (x >>> 0) + t;
    return ((n << s) | (n >>> (32 - s))) + b;
  };
  md5._ii  = function (a, b, c, d, x, s, t) {
    var n = a + (c ^ (b | ~d)) + (x >>> 0) + t;
    return ((n << s) | (n >>> (32 - s))) + b;
  };

  // Package private blocksize
  md5._blocksize = 16;
  md5._digestsize = 16;

  module.exports = function (message, options) {
    var digestbytes = crypt.wordsToBytes(md5(message));
    return options && options.asBytes ? digestbytes :
        options && options.asString ? bin.bytesToString(digestbytes) :
        crypt.bytesToHex(digestbytes);
  };

})();
<commit_msg>use Array.isArray() instead of typeof<commit_after>(function(){
  var crypt = require('crypt'),
      utf8 = require('charenc').utf8,
      bin = require('charenc').bin,

  // The core
  md5 = function (message) {
    // Convert to byte array
    if (message.constructor == String)
      message = utf8.stringToBytes(message);
    else if (!Array.isArray(message))
      message = message.toString();
    // else, assume byte array already

    var m = crypt.bytesToWords(message),
        l = message.length * 8,
        a =  1732584193,
        b = -271733879,
        c = -1732584194,
        d =  271733878;

    // Swap endian
    for (var i = 0; i < m.length; i++) {
      m[i] = ((m[i] <<  8) | (m[i] >>> 24)) & 0x00FF00FF |
             ((m[i] << 24) | (m[i] >>>  8)) & 0xFF00FF00;
    }

    // Padding
    m[l >>> 5] |= 0x80 << (l % 32);
    m[(((l + 64) >>> 9) << 4) + 14] = l;

    // Method shortcuts
    var FF = md5._ff,
        GG = md5._gg,
        HH = md5._hh,
        II = md5._ii;

    for (var i = 0; i < m.length; i += 16) {

      var aa = a,
          bb = b,
          cc = c,
          dd = d;

      a = FF(a, b, c, d, m[i+ 0],  7, -680876936);
      d = FF(d, a, b, c, m[i+ 1], 12, -389564586);
      c = FF(c, d, a, b, m[i+ 2], 17,  606105819);
      b = FF(b, c, d, a, m[i+ 3], 22, -1044525330);
      a = FF(a, b, c, d, m[i+ 4],  7, -176418897);
      d = FF(d, a, b, c, m[i+ 5], 12,  1200080426);
      c = FF(c, d, a, b, m[i+ 6], 17, -1473231341);
      b = FF(b, c, d, a, m[i+ 7], 22, -45705983);
      a = FF(a, b, c, d, m[i+ 8],  7,  1770035416);
      d = FF(d, a, b, c, m[i+ 9], 12, -1958414417);
      c = FF(c, d, a, b, m[i+10], 17, -42063);
      b = FF(b, c, d, a, m[i+11], 22, -1990404162);
      a = FF(a, b, c, d, m[i+12],  7,  1804603682);
      d = FF(d, a, b, c, m[i+13], 12, -40341101);
      c = FF(c, d, a, b, m[i+14], 17, -1502002290);
      b = FF(b, c, d, a, m[i+15], 22,  1236535329);

      a = GG(a, b, c, d, m[i+ 1],  5, -165796510);
      d = GG(d, a, b, c, m[i+ 6],  9, -1069501632);
      c = GG(c, d, a, b, m[i+11], 14,  643717713);
      b = GG(b, c, d, a, m[i+ 0], 20, -373897302);
      a = GG(a, b, c, d, m[i+ 5],  5, -701558691);
      d = GG(d, a, b, c, m[i+10],  9,  38016083);
      c = GG(c, d, a, b, m[i+15], 14, -660478335);
      b = GG(b, c, d, a, m[i+ 4], 20, -405537848);
      a = GG(a, b, c, d, m[i+ 9],  5,  568446438);
      d = GG(d, a, b, c, m[i+14],  9, -1019803690);
      c = GG(c, d, a, b, m[i+ 3], 14, -187363961);
      b = GG(b, c, d, a, m[i+ 8], 20,  1163531501);
      a = GG(a, b, c, d, m[i+13],  5, -1444681467);
      d = GG(d, a, b, c, m[i+ 2],  9, -51403784);
      c = GG(c, d, a, b, m[i+ 7], 14,  1735328473);
      b = GG(b, c, d, a, m[i+12], 20, -1926607734);

      a = HH(a, b, c, d, m[i+ 5],  4, -378558);
      d = HH(d, a, b, c, m[i+ 8], 11, -2022574463);
      c = HH(c, d, a, b, m[i+11], 16,  1839030562);
      b = HH(b, c, d, a, m[i+14], 23, -35309556);
      a = HH(a, b, c, d, m[i+ 1],  4, -1530992060);
      d = HH(d, a, b, c, m[i+ 4], 11,  1272893353);
      c = HH(c, d, a, b, m[i+ 7], 16, -155497632);
      b = HH(b, c, d, a, m[i+10], 23, -1094730640);
      a = HH(a, b, c, d, m[i+13],  4,  681279174);
      d = HH(d, a, b, c, m[i+ 0], 11, -358537222);
      c = HH(c, d, a, b, m[i+ 3], 16, -722521979);
      b = HH(b, c, d, a, m[i+ 6], 23,  76029189);
      a = HH(a, b, c, d, m[i+ 9],  4, -640364487);
      d = HH(d, a, b, c, m[i+12], 11, -421815835);
      c = HH(c, d, a, b, m[i+15], 16,  530742520);
      b = HH(b, c, d, a, m[i+ 2], 23, -995338651);

      a = II(a, b, c, d, m[i+ 0],  6, -198630844);
      d = II(d, a, b, c, m[i+ 7], 10,  1126891415);
      c = II(c, d, a, b, m[i+14], 15, -1416354905);
      b = II(b, c, d, a, m[i+ 5], 21, -57434055);
      a = II(a, b, c, d, m[i+12],  6,  1700485571);
      d = II(d, a, b, c, m[i+ 3], 10, -1894986606);
      c = II(c, d, a, b, m[i+10], 15, -1051523);
      b = II(b, c, d, a, m[i+ 1], 21, -2054922799);
      a = II(a, b, c, d, m[i+ 8],  6,  1873313359);
      d = II(d, a, b, c, m[i+15], 10, -30611744);
      c = II(c, d, a, b, m[i+ 6], 15, -1560198380);
      b = II(b, c, d, a, m[i+13], 21,  1309151649);
      a = II(a, b, c, d, m[i+ 4],  6, -145523070);
      d = II(d, a, b, c, m[i+11], 10, -1120210379);
      c = II(c, d, a, b, m[i+ 2], 15,  718787259);
      b = II(b, c, d, a, m[i+ 9], 21, -343485551);

      a = (a + aa) >>> 0;
      b = (b + bb) >>> 0;
      c = (c + cc) >>> 0;
      d = (d + dd) >>> 0;
    }

    return crypt.endian([a, b, c, d]);
  };

  // Auxiliary functions
  md5._ff  = function (a, b, c, d, x, s, t) {
    var n = a + (b & c | ~b & d) + (x >>> 0) + t;
    return ((n << s) | (n >>> (32 - s))) + b;
  };
  md5._gg  = function (a, b, c, d, x, s, t) {
    var n = a + (b & d | c & ~d) + (x >>> 0) + t;
    return ((n << s) | (n >>> (32 - s))) + b;
  };
  md5._hh  = function (a, b, c, d, x, s, t) {
    var n = a + (b ^ c ^ d) + (x >>> 0) + t;
    return ((n << s) | (n >>> (32 - s))) + b;
  };
  md5._ii  = function (a, b, c, d, x, s, t) {
    var n = a + (c ^ (b | ~d)) + (x >>> 0) + t;
    return ((n << s) | (n >>> (32 - s))) + b;
  };

  // Package private blocksize
  md5._blocksize = 16;
  md5._digestsize = 16;

  module.exports = function (message, options) {
    var digestbytes = crypt.wordsToBytes(md5(message));
    return options && options.asBytes ? digestbytes :
        options && options.asString ? bin.bytesToString(digestbytes) :
        crypt.bytesToHex(digestbytes);
  };

})();
<|endoftext|>


<commit_before>var NHLScore = {
	league: 'NHL',
	updateURL: 'http://live.nhle.com/GameData/RegularSeasonScoreboardv3.jsonp',
	getGameArray: function(rawData) {
		rawData = rawData.replace('loadScoreboard(','');
		rawData = rawData.substring(0,(rawData.length-2));
		return JSON.parse(rawData).games;
	},
	parseRawGame: function(rawGame) {
		var gameDate; //make date from rawGame data
		var gameState = '';
		switch (rawGame.gs) {
			case '1':
				gameState = 'scheduled';
				break;
			case '3':
				if (rawGame.ts.indexOf('END') !== -1) {
					gameState = 'intermission';
				} else {
					gameState = 'progress';
				}
				break;
			case '4':
				if (rawGame.ts.indexOf('SHOOTOUT') !== -1) {
					gameState = 'shootout';
				} else {
					gameState = 'overtime';
				}
				break;
			case '5':
				gameState = 'ended';
				break;
		}
		this.gameId = rawGame.id;
		this.state = gameState;
		this.date = gameDate;
		this.gameTime = rawGame.tsc;
		this.awayTeam = rawGame.atn;
		this.awayScore = rawGame.ats;
		this.homeTeam = rawGame.htn;
		this.homeScore = rawGame.hts;
	},
	makeGameLink: function() {
		var linkStub = 'http://www.nhl.com/gamecenter/en/icetracker?id=';
		return linkStub + this.gameId;
	}
};

module.exports = NHLScore;<commit_msg>parse nhl dates<commit_after>var NHLScore = {
	league: 'NHL',
	updateURL: 'http://live.nhle.com/GameData/RegularSeasonScoreboardv3.jsonp',
	getGameArray: function(rawData) {
		rawData = rawData.replace('loadScoreboard(','');
		rawData = rawData.substring(0,(rawData.length-2));
		return JSON.parse(rawData).games;
	},
	parseRawGame: function(rawGame) {
		var date = new Date();
		var arr = rawGame.ts.split(' ');
		var dateArr = arr[arr.length-1].split('/');
		d.setMonth(parseInt(dateArr[0])-1);
		d.setDate(parseInt(dateArr[1]));
		var gameState = '';
		switch (rawGame.gs) {
			case '1':
				gameState = 'scheduled';
				var arr = rawGame.ts.split(' ');
				var dateArr = arr[arr.length-1].split('/');
				d.setMonth(parseInt(dateArr[0])-1);
				d.setDate(parseInt(dateArr[1]));
				break;
			case '3':
				if (rawGame.ts.indexOf('END') !== -1) {
					gameState = 'intermission';
				} else {
					gameState = 'progress';
				}
				break;
			case '4':
				if (rawGame.ts.indexOf('SHOOTOUT') !== -1) {
					gameState = 'shootout';
				} else {
					gameState = 'overtime';
				}
				break;
			case '5':
				gameState = 'ended';
				var arr = rawGame.ts.split(' ');
				var dateArr = arr[arr.length-1].split('/');
				d.setMonth(parseInt(dateArr[0])-1);
				d.setDate(parseInt(dateArr[1]));
				break;
		}
		this.gameId = rawGame.id;
		this.state = gameState;
		this.date = date.toDateString();
		this.gameTime = rawGame.tsc;
		this.awayTeam = rawGame.atn;
		this.awayScore = rawGame.ats;
		this.homeTeam = rawGame.htn;
		this.homeScore = rawGame.hts;
	},
	makeGameLink: function() {
		var linkStub = 'http://www.nhl.com/gamecenter/en/icetracker?id=';
		return linkStub + this.gameId;
	}
};

module.exports = NHLScore;<|endoftext|>


<commit_before>var OBB = {

	// Check for a collision.
	// A and B have to be fo type Phaser.Physic.Arcade.Body
	collisionCheck: function  (A, B) {
		var ARect = OBB.createRectangle(A);
		var BRect = OBB.createRectangle(B);

		return OBB.isecRects(ARect, BRect);
	},

	// We assume a vector consisting of [halfWidth, halfHeight], which can be used to point from the center to the edges
	// We need to rotate this vector in order to create the rotated rectangle
	rotateVector: function (vector, radians) {
		var x = vector[0] * Math.cos(radians) - vector[1] * Math.sin(radians);
		var y = vector[0] * Math.sin(radians) + vector[1] * Math.cos(radians);

		return [x, y];
	},

	// This function takes a center point (in this format [x,y]) and a rotated vector (in this format [x,y])
	// and returns a rectangle in this format: [x1, y1, x2, y2, x3, y3, x4, y4]
	createRectangle: function (body) {
		var center = [body.center.x, body.center.y];

		var vector1 = OBB.rotateVector([body.halfWidth, body.halfHeight], Phaser.Math.degToRad(body.rotation));
		var vector2 = OBB.rotateVector([body.halfWidth, body.halfHeight], Phaser.Math.degToRad(-body.rotation));

		var x1 = center[0] + vector1[0],
		y1 = center[1] + vector1[1],

		x2 = center[0] + vector2[0],
		y2 = center[1] - vector2[1],

		x3 = center[0] - vector1[0],
		y3 = center[1] - vector1[1],

		x4 = center[0] - vector2[0],
		y4 = center[1] + vector2[1];

		return [x1, y1, x2, y2, x3, y3, x4, y4];
	},

	// Source: https://gist.github.com/shamansir/3007244
	edgeTest:function (p1, p2, p3, r2) {
		var rot = [ -(p2[1] - p1[1]),
					  p2[0] - p1[0] ];

		var ref = (rot[0] * (p3[0] - p1[0]) +
				   rot[1] * (p3[1] - p1[1])) >= 0;

		for (var i = 0, il = r2.length; i < il; i+=2) {
			if (((rot[0] * (r2[i]   - p1[0]) +
				  rot[1] * (r2[i+1] - p1[1])) >= 0) === ref) return false;
		}

		return true;
	},

	// source: https://gist.github.com/shamansir/3007244
	isecRects: function (r1, r2) {
		if (!r1 || !r2) throw new Error('Rects are not accessible');

		var pn, px;
		for (var pi = 0, pl = r1.length; pi < pl; pi += 2) {
			pn = (pi === (pl - 2)) ? 0 : pi + 2; // next point
			px = (pn === (pl - 2)) ? 0 : pn + 2;
			if (OBB.edgeTest([r1[pi], r1[pi+1]],
						 [r1[pn], r1[pn+1]],
						 [r1[px], r1[px+1]], r2)) return false;
		}
		for (var pi = 0, pl = r2.length; pi < pl; pi += 2) {
			pn = (pi === (pl - 2)) ? 0 : pi + 2; // next point
			px = (pn === (pl - 2)) ? 0 : pn + 2;
			if (OBB.edgeTest([r2[pi], r2[pi+1]],
						 [r2[pn], r2[pn+1]],
						 [r2[px], r2[px+1]], r1)) return false;
		}
		return true;
	},

	// Overwrite the seperate function for OBB collision detection
	separate: function (body1, body2, processCallback, callbackContext, overlapOnly) {
		if (!body1.enable || !body2.enable)
		{
			return false;
		}

		//  Is there a custom process callback? If it returns true then we can carry on, otherwise we should abort.
		if (processCallback && processCallback.call(callbackContext, body1.sprite, body2.sprite) === false)
		{
			return false;
		}

		return OBB.collisionCheck(body1, body2);
	},

	// This function is used to overwrite the seperate function of a Phase.Arcade.World instance.
	setOBB: function (gameRef) {
		OBB.game = gameRef;
		gameRef.physics.arcade.separate = OBB.separate;
	}

};

OBB.debug = {

	drawVertices: function (body, color) {
		var color = color ? color : 0xff0000; // RED
		if (!body.obbDebug)
			body.obbDebug = OBB.game.add.graphics(0, 0);

		var r = OBB.createRectangle(body);;

		if (body.obbDebug)
			body.obbDebug.destroy();
		// add a new graphics object
		body.obbDebug = OBB.game.add.graphics(0, 0);

		// add the vertices
		body.obbDebug.lineStyle(1, color);
		body.obbDebug.drawCircle(r[0], r[1], 10);
		body.obbDebug.drawCircle(r[2], r[3], 10);
		body.obbDebug.drawCircle(r[4], r[5], 10);
		body.obbDebug.drawCircle(r[6], r[7], 10);
	}

};
<commit_msg>Add a simple bounce handler<commit_after>var OBB = {

	// Check for a collision.
	// A and B have to be of type Phaser.Physic.Arcade.Body
	collisionCheck: function  (A, B) {
		var ARect = OBB.createRectangle(A);
		var BRect = OBB.createRectangle(B);

		if (OBB.isecRects(ARect, BRect)) {
			this.bounceHandlerX(A, B);
			this.bounceHandlerY(A, B);
			return true;
		}

		return false;
	},

	// We assume a vector consisting of [halfWidth, halfHeight], which can be used to point from the center to the edges
	// We need to rotate this vector in order to create the rotated rectangle
	rotateVector: function (vector, radians) {
		var x = vector[0] * Math.cos(radians) - vector[1] * Math.sin(radians);
		var y = vector[0] * Math.sin(radians) + vector[1] * Math.cos(radians);

		return [x, y];
	},

	// This function takes a center point (in this format [x,y]) and a rotated vector (in this format [x,y])
	// and returns a rectangle in this format: [x1, y1, x2, y2, x3, y3, x4, y4]
	createRectangle: function (body) {
		var center = [body.center.x, body.center.y];

		var vector1 = OBB.rotateVector([body.halfWidth, body.halfHeight], Phaser.Math.degToRad(body.rotation));
		var vector2 = OBB.rotateVector([body.halfWidth, body.halfHeight], Phaser.Math.degToRad(-body.rotation));

		var x1 = center[0] + vector1[0],
		y1 = center[1] + vector1[1],

		x2 = center[0] + vector2[0],
		y2 = center[1] - vector2[1],

		x3 = center[0] - vector1[0],
		y3 = center[1] - vector1[1],

		x4 = center[0] - vector2[0],
		y4 = center[1] + vector2[1];

		return [x1, y1, x2, y2, x3, y3, x4, y4];
	},

	// Source: https://gist.github.com/shamansir/3007244
	edgeTest:function (p1, p2, p3, r2) {
		var rot = [ -(p2[1] - p1[1]),
					  p2[0] - p1[0] ];

		var ref = (rot[0] * (p3[0] - p1[0]) +
				   rot[1] * (p3[1] - p1[1])) >= 0;

		for (var i = 0, il = r2.length; i < il; i+=2) {
			if (((rot[0] * (r2[i]   - p1[0]) +
				  rot[1] * (r2[i+1] - p1[1])) >= 0) === ref) return false;
		}

		return true;
	},

	// source: https://gist.github.com/shamansir/3007244
	isecRects: function (r1, r2) {
		if (!r1 || !r2) throw new Error('Rects are not accessible');

		var pn, px;
		for (var pi = 0, pl = r1.length; pi < pl; pi += 2) {
			pn = (pi === (pl - 2)) ? 0 : pi + 2; // next point
			px = (pn === (pl - 2)) ? 0 : pn + 2;
			if (OBB.edgeTest([r1[pi], r1[pi+1]],
						 [r1[pn], r1[pn+1]],
						 [r1[px], r1[px+1]], r2)) return false;
		}
		for (var pi = 0, pl = r2.length; pi < pl; pi += 2) {
			pn = (pi === (pl - 2)) ? 0 : pi + 2; // next point
			px = (pn === (pl - 2)) ? 0 : pn + 2;
			if (OBB.edgeTest([r2[pi], r2[pi+1]],
						 [r2[pn], r2[pn+1]],
						 [r2[px], r2[px+1]], r1)) return false;
		}
		return true;
	},

	// Overwrite the seperate function for OBB collision detection
	separate: function (body1, body2, processCallback, callbackContext, overlapOnly) {
		if (!body1.enable || !body2.enable)
		{
			return false;
		}

		//  Is there a custom process callback? If it returns true then we can carry on, otherwise we should abort.
		if (processCallback && processCallback.call(callbackContext, body1.sprite, body2.sprite) === false)
		{
			return false;
		}

		return OBB.collisionCheck(body1, body2);
	},

	// Source: separateX-function in https://github.com/photonstorm/phaser/blob/master/src/physics/arcade/World.js
	bounceHandlerX: function (body1, body2) {
		var overlap = 1;
		var v1 = body1.velocity.x;
		var v2 = body2.velocity.x;

		if (!body1.immovable && !body2.immovable)
		{
			overlap *= 0.5;

			body1.x = body1.x - overlap;
			body2.x += overlap;

			var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1);
			var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1);
			var avg = (nv1 + nv2) * 0.5;

			nv1 -= avg;
			nv2 -= avg;

			body1.velocity.x = avg + nv1 * body1.bounce.x;
			body2.velocity.x = avg + nv2 * body2.bounce.x;
		}
		else if (!body1.immovable)
		{
			body1.x = body1.x - overlap;
			body1.velocity.x = v2 - v1 * body1.bounce.x;

			//  This is special case code that handles things like vertically moving platforms you can ride
			if (body2.moves)
			{
				body1.y += (body2.y - body2.prev.y) * body2.friction.y;
			}
		}
		else if (!body2.immovable)
		{
			body2.x += overlap;
			body2.velocity.x = v1 - v2 * body2.bounce.x;

			//  This is special case code that handles things like vertically moving platforms you can ride
			if (body1.moves)
			{
				body2.y += (body1.y - body1.prev.y) * body1.friction.y;
			}
		}

		return true;
	},

	// Source: separateX-function in https://github.com/photonstorm/phaser/blob/master/src/physics/arcade/World.js
	bounceHandlerY: function (body1, body2) {
		var overlap = 1;
		var v1 = body1.velocity.y;
		var v2 = body2.velocity.y;

		if (!body1.immovable && !body2.immovable)
		{
			overlap *= 0.5;

			body1.y = body1.y - overlap;
			body2.y += overlap;

			var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1);
			var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1);
			var avg = (nv1 + nv2) * 0.5;

			nv1 -= avg;
			nv2 -= avg;

			body1.velocity.y = avg + nv1 * body1.bounce.y;
			body2.velocity.y = avg + nv2 * body2.bounce.y;
		}
		else if (!body1.immovable)
		{
			body1.y = body1.y - overlap;
			body1.velocity.y = v2 - v1 * body1.bounce.y;

			//  This is special case code that handles things like vertically moving platforms you can ride
			if (body2.moves)
			{
				body1.x += (body2.x - body2.prev.x) * body2.friction.x;
			}
		}
		else if (!body2.immovable)
		{
			body2.y += overlap;
			body2.velocity.y = v1 - v2 * body2.bounce.y;

			//  This is special case code that handles things like vertically moving platforms you can ride
			if (body1.moves)
			{
				body2.x += (body1.x - body1.prev.x) * body1.friction.x;
			}
		}

		return true;
	},

	// This function is used to overwrite the seperate function of a Phase.Arcade.World instance.
	setOBB: function (gameRef) {
		OBB.game = gameRef;
		gameRef.physics.arcade.separate = OBB.separate;
	}

};

OBB.debug = {

	drawVertices: function (body, color) {
		var color = color ? color : 0xff0000; // RED
		if (!body.obbDebug)
			body.obbDebug = OBB.game.add.graphics(0, 0);

		var r = OBB.createRectangle(body);;

		if (body.obbDebug)
			body.obbDebug.destroy();
		// add a new graphics object
		body.obbDebug = OBB.game.add.graphics(0, 0);

		// add the vertices
		body.obbDebug.lineStyle(1, color);
		body.obbDebug.drawCircle(r[0], r[1], 10);
		body.obbDebug.drawCircle(r[2], r[3], 10);
		body.obbDebug.drawCircle(r[4], r[5], 10);
		body.obbDebug.drawCircle(r[6], r[7], 10);
	}

};
<|endoftext|>


<commit_before>UI.Component.implement({
	options: {
		// Resize options
		resizer: {
			'class': 'ui-resizer'
		},
		resizable: false,
		resizeLimitX: [100, screen.width],
		resizeLimitY: [100, screen.height]
	},

	_initResizer: function(){
		this.resizeHandlers = [];

		this.resizer = new Element('div', this.options.resizer)
		.addEvents({
			click: function(e){
				e.stop();
			},
			mousedown: function(e) {
				e.stop();
			}
		}).inject(this.element, 'bottom');

		this.resizeHandlers.push(this.resizer);

		this.enableResize(0);

		if (this.options.resizeBorders) {
			this.options.resizeBorders.each(function(border,i){
				this.resizeHandlers.push(new Element('div', {
					style: border+": 0",
					'class': 'ui-resizer-'+border
				})
				.addEvents({
					click: function(e){
						e.stop();
					},
					mousedown: function(e) {
						e.stop();
					}
				}).inject(this.element, 'bottom'));

				this.enableResize(i+1);
			},this);
		}
	},

	enableResize: function(i){
		var self = this;
		var options = {
			handle: this.resizeHandlers[i],
			limit: {
				x: self.options.resizeLimitX,
				y: self.options.resizeLimitY
			},
			modifiers: {
				'x': 'width',
				'y': 'height'
			},
			onStart: function(el){
				self.fireEvent('resizeStart', el);
			},
			onDrag: function(el){
				self.fireEvent('resizeDrag', el);
				self.fireEvent('resize', el);
			},
			onComplete: function(el){
				self.fireEvent('resizeComplete', el);
			}
		};

		if (i == 1 || i == 3) options.modifiers.x = false;
		if (i == 2 || i == 4) options.modifiers.y = false;

		if (i == 1 || i == 4) {
			this.dragHandlers.push(this.resizeHandlers[i]);
			options.invert = true;
		}

		this.element.makeResizable(options);

		return this;
	}
});<commit_msg>Work on drag on resize events<commit_after>UI.Component.implement({
	options: {
		// Resize options
		resizer: {
			'class': 'ui-resizer'
		},
		resizable: false,
		resizeLimitX: [100, screen.width],
		resizeLimitY: [100, screen.height]
	},

	_initResizer: function(){
		this.resizeHandlers = [];

		this.resizer = new Element('div', this.options.resizer)
		.addEvents({
			click: function(e){
				e.stop();
			},
			mousedown: function(e) {
				e.stop();
			}
		}).inject(this.element, 'bottom');

		this.resizeHandlers.push(this.resizer);

		this.enableResize(0);

		if (this.options.resizeBorders) {
			this.options.resizeBorders.each(function(border,i){
				this.resizeHandlers.push(new Element('div', {
					style: border+": 0",
					'class': 'ui-resizer-'+border
				})
				.addEvents({
					click: function(e){
						e.stop();
					},
					mousedown: function(e) {
						e.stop();
					}
				}).inject(this.element, 'bottom'));

				this.enableResize(i+1);
			},this);
		}
	},

	enableResize: function(i){
		var self = this;
		var options = {
			handle: this.resizeHandlers[i],
			limit: {
				x: self.options.resizeLimitX,
				y: self.options.resizeLimitY
			},
			modifiers: {
				'x': 'width',
				'y': 'height'
			},
			onStart: function(el){
				self.fireEvent('resizeStart', el);
			},
			onDrag: function(el, ev){
				self.fireEvent('resizeDrag', [el, ev]);
				self.fireEvent('resize', el);
			},
			onComplete: function(el){
				self.fireEvent('resizeComplete', el);
			}
		};

		if (i == 1 || i == 3) options.modifiers.x = false;
		if (i == 2 || i == 4) options.modifiers.y = false;

		if (i == 1 || i == 4) {
			this.dragHandlers.push(this.resizeHandlers[i]);
			options.invert = true;
		}

		this.element.makeResizable(options);

		return this;
	}
});<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'

export class DropFiles extends React.Component {
	static propTypes = {
		setDraggedOver: PropTypes.func,
		onDrop : PropTypes.func.isRequired,
		multiple : PropTypes.boolean
	}

	// state = {
	// 	isDragging: false
	// }

	node = React.createRef()

	// Copied from:
	// https://github.com/react-dropzone/react-dropzone/blob/master/src/index.js
	dragTargets = []

	setDraggedOver = (draggedOver) => {
		const { setDraggedOver } = this.props
		if (setDraggedOver) {
			setDraggedOver(draggedOver)
		}
	}

	// Must be `preventDefault`-ed for some weird reasons.
	onDragOver = (event) => {
		event.preventDefault()
		event.stopPropagation()
	}

	// `event` is always triggered when gragging from another window to the browser window.
	onDragEnter = (event) => {
		event.preventDefault()
		event.stopPropagation()

		// Copied from:
		// https://github.com/react-dropzone/react-dropzone/blob/master/src/index.js
		// Count the dropzone and any children that are entered.
		if (this.dragTargets.indexOf(event.target) === -1) {
			this.dragTargets.push(event.target)
		}

		// `event.dataTransfer.files` are only accessible on "drop" event.
		// `event.dataTransfer.items` are only accessible in Chrome and FireFox while dragging.
		// https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer/items
		if (isDraggingFiles(event)) {
			this.setDraggedOver(true)
		}
	}

	onDragLeave = (event) => {
		event.preventDefault()
		event.stopPropagation()

		// Copied from:
		// https://github.com/react-dropzone/react-dropzone/blob/master/src/index.js
		// Only deactivate once the dropzone and all children have been left.
		this.dragTargets = this.dragTargets.filter(_ => _ !== event.target && this.node.current.contains(_))
		if (this.dragTargets.length > 0) {
			return
		}

		this.setDraggedOver(false)
	}

	onDrop = (event) => {
		const { onDrop, multiple } = this.props

		event.preventDefault()
		event.stopPropagation()

		// Reset.
		this.dragTargets = []

		this.setDraggedOver(false)

		const files = getFilesFromEvent(event)
		if (files.length > 0) {
			onDrop(multiple ? files : files[0])
			// Not clear why would it be called.
			// MDN says it's a "no-op".
			// https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItemList/clear
			// event.dataTransfer.clearData()
		}
	}

	componentDidMount() {
		const div = this.node.current
		div.addEventListener('dragenter', this.onDragEnter)
		div.addEventListener('dragleave', this.onDragLeave)
		div.addEventListener('dragover', this.onDragOver)
		div.addEventListener('drop', this.onDrop)
	}

	componentWillUnmount() {
		const div = this.node.current
		div.removeEventListener('dragenter', this.onDragEnter)
		div.removeEventListener('dragleave', this.onDragLeave)
		div.removeEventListener('dragover', this.onDragOver)
		div.removeEventListener('drop', this.onDrop)
	}

	render() {
		return React.createElement('div', {
			ref: this.node,
			...this.props
		})
	}
}

// Copied from:
// https://github.com/react-dropzone/react-dropzone/blob/master/src/utils/index.js
export const supportsMultipleFileUploadOnInputElement =
	typeof document !== 'undefined' && document && document.createElement
		? 'multiple' in document.createElement('input')
		: true

// Copied from:
// https://github.com/react-dropzone/react-dropzone/blob/master/src/utils/index.js
function isDraggingFiles(event) {
	// If `event.dataTransfer` is not available then `event.target.files` fallback is used.
	if (!event.dataTransfer) {
		return true
	}
	// https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer/types
	// https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types#file
	return Array.prototype.some.call(
		event.dataTransfer.types,
		type => type === 'Files' || type === 'application/x-moz-file'
	)
}

// Copied from:
// https://github.com/react-dropzone/react-dropzone/blob/master/src/utils/index.js
export function getFilesFromEvent(event) {
	let dataTransferItemsList = []
	if (event.dataTransfer) {
		const dt = event.dataTransfer
		// NOTE: Only the 'drop' event has access to DataTransfer.files,
		// otherwise it will always be empty
		if (dt.files && dt.files.length) {
			dataTransferItemsList = dt.files
		} else if (dt.items && dt.items.length) {
			// During the drag even the dataTransfer.files is null
			// but Chrome implements some drag store, which is accesible via dataTransfer.items
			dataTransferItemsList = dt.items
		}
	} else if (event.target && event.target.files) {
		dataTransferItemsList = event.target.files
	}
	// Convert from DataTransferItemsList to the native Array
	return Array.prototype.slice.call(dataTransferItemsList)
}

// // Copied from:
// // https://github.com/react-dropzone/react-dropzone/blob/master/src/utils/index.js
// // Firefox versions prior to 53 return a bogus MIME type for every file drag, so dragovers with
// // that MIME type will always be accepted
// function isFileAccepted(file, accept) {
// 	return this.props.isFileAccepted(file) || (file.type === 'application/x-moz-file' || this.props.isFileTypeAccepted(file))
// }

// Deprecated.
export function CanDrop(type, drop)
{
	throw new Error('`react-dnd` has been removed from `react-responsive-ui` starting from version `0.14.124` due to being buggy and not supported. `react-dnd` has been replaced with simple native HTML file drag-n-drop. Use `<DropFileUpload/>` and `<DropMultiFileUpload/>` components for file upload instead of `DragAndDrop` and `CanDrop` decorators.')
}

// Deprecated.
export function DragAndDrop()
{
	throw new Error('`react-dnd` has been removed from `react-responsive-ui` starting from version `0.14.124` due to being buggy and not supported. `react-dnd` has been replaced with simple native HTML file drag-n-drop. `DragAndDrop` decorator is no longer needed and should be removed. Use `<DropFileUpload/>` and `<DropMultiFileUpload/>` components for file upload.')
}

// Deprecated.
// Native file drag'n'drop (single file)
export const File = 'File'

// Deprecated.
// Native file drag'n'drop (multiple files)
export const Files = 'Files'

// Deprecated.
// Native file drag'n'drop (single file)
export const FILE = File

// Deprecated.
// Native file drag'n'drop (multiple files)
export const FILES = Files<commit_msg>Fix props warning<commit_after>import React from 'react'
import PropTypes from 'prop-types'

export class DropFiles extends React.Component {
	static propTypes = {
		setDraggedOver: PropTypes.func,
		onDrop : PropTypes.func.isRequired,
		multiple : PropTypes.bool
	}

	// state = {
	// 	isDragging: false
	// }

	node = React.createRef()

	// Copied from:
	// https://github.com/react-dropzone/react-dropzone/blob/master/src/index.js
	dragTargets = []

	setDraggedOver = (draggedOver) => {
		const { setDraggedOver } = this.props
		if (setDraggedOver) {
			setDraggedOver(draggedOver)
		}
	}

	// Must be `preventDefault`-ed for some weird reasons.
	onDragOver = (event) => {
		event.preventDefault()
		event.stopPropagation()
	}

	// `event` is always triggered when gragging from another window to the browser window.
	onDragEnter = (event) => {
		event.preventDefault()
		event.stopPropagation()

		// Copied from:
		// https://github.com/react-dropzone/react-dropzone/blob/master/src/index.js
		// Count the dropzone and any children that are entered.
		if (this.dragTargets.indexOf(event.target) === -1) {
			this.dragTargets.push(event.target)
		}

		// `event.dataTransfer.files` are only accessible on "drop" event.
		// `event.dataTransfer.items` are only accessible in Chrome and FireFox while dragging.
		// https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer/items
		if (isDraggingFiles(event)) {
			this.setDraggedOver(true)
		}
	}

	onDragLeave = (event) => {
		event.preventDefault()
		event.stopPropagation()

		// Copied from:
		// https://github.com/react-dropzone/react-dropzone/blob/master/src/index.js
		// Only deactivate once the dropzone and all children have been left.
		this.dragTargets = this.dragTargets.filter(_ => _ !== event.target && this.node.current.contains(_))
		if (this.dragTargets.length > 0) {
			return
		}

		this.setDraggedOver(false)
	}

	onDrop = (event) => {
		const { onDrop, multiple } = this.props

		event.preventDefault()
		event.stopPropagation()

		// Reset.
		this.dragTargets = []

		this.setDraggedOver(false)

		const files = getFilesFromEvent(event)
		if (files.length > 0) {
			onDrop(multiple ? files : files[0])
			// Not clear why would it be called.
			// MDN says it's a "no-op".
			// https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItemList/clear
			// event.dataTransfer.clearData()
		}
	}

	componentDidMount() {
		const div = this.node.current
		div.addEventListener('dragenter', this.onDragEnter)
		div.addEventListener('dragleave', this.onDragLeave)
		div.addEventListener('dragover', this.onDragOver)
		div.addEventListener('drop', this.onDrop)
	}

	componentWillUnmount() {
		const div = this.node.current
		div.removeEventListener('dragenter', this.onDragEnter)
		div.removeEventListener('dragleave', this.onDragLeave)
		div.removeEventListener('dragover', this.onDragOver)
		div.removeEventListener('drop', this.onDrop)
	}

	render() {
		const {
			onDrop,
			setDraggedOver,
			multiple,
			...rest
		} = this.props

		return React.createElement('div', {
			ref: this.node,
			...rest
		})
	}
}

// Copied from:
// https://github.com/react-dropzone/react-dropzone/blob/master/src/utils/index.js
export const supportsMultipleFileUploadOnInputElement =
	typeof document !== 'undefined' && document && document.createElement
		? 'multiple' in document.createElement('input')
		: true

// Copied from:
// https://github.com/react-dropzone/react-dropzone/blob/master/src/utils/index.js
function isDraggingFiles(event) {
	// If `event.dataTransfer` is not available then `event.target.files` fallback is used.
	if (!event.dataTransfer) {
		return true
	}
	// https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer/types
	// https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types#file
	return Array.prototype.some.call(
		event.dataTransfer.types,
		type => type === 'Files' || type === 'application/x-moz-file'
	)
}

// Copied from:
// https://github.com/react-dropzone/react-dropzone/blob/master/src/utils/index.js
export function getFilesFromEvent(event) {
	let dataTransferItemsList = []
	if (event.dataTransfer) {
		const dt = event.dataTransfer
		// NOTE: Only the 'drop' event has access to DataTransfer.files,
		// otherwise it will always be empty
		if (dt.files && dt.files.length) {
			dataTransferItemsList = dt.files
		} else if (dt.items && dt.items.length) {
			// During the drag even the dataTransfer.files is null
			// but Chrome implements some drag store, which is accesible via dataTransfer.items
			dataTransferItemsList = dt.items
		}
	} else if (event.target && event.target.files) {
		dataTransferItemsList = event.target.files
	}
	// Convert from DataTransferItemsList to the native Array
	return Array.prototype.slice.call(dataTransferItemsList)
}

// // Copied from:
// // https://github.com/react-dropzone/react-dropzone/blob/master/src/utils/index.js
// // Firefox versions prior to 53 return a bogus MIME type for every file drag, so dragovers with
// // that MIME type will always be accepted
// function isFileAccepted(file, accept) {
// 	return this.props.isFileAccepted(file) || (file.type === 'application/x-moz-file' || this.props.isFileTypeAccepted(file))
// }

// Deprecated.
export function CanDrop(type, drop)
{
	throw new Error('`react-dnd` has been removed from `react-responsive-ui` starting from version `0.14.124` due to being buggy and not supported. `react-dnd` has been replaced with simple native HTML file drag-n-drop. Use `<DropFileUpload/>` and `<DropMultiFileUpload/>` components for file upload instead of `DragAndDrop` and `CanDrop` decorators.')
}

// Deprecated.
export function DragAndDrop()
{
	throw new Error('`react-dnd` has been removed from `react-responsive-ui` starting from version `0.14.124` due to being buggy and not supported. `react-dnd` has been replaced with simple native HTML file drag-n-drop. `DragAndDrop` decorator is no longer needed and should be removed. Use `<DropFileUpload/>` and `<DropMultiFileUpload/>` components for file upload.')
}

// Deprecated.
// Native file drag'n'drop (single file)
export const File = 'File'

// Deprecated.
// Native file drag'n'drop (multiple files)
export const Files = 'Files'

// Deprecated.
// Native file drag'n'drop (single file)
export const FILE = File

// Deprecated.
// Native file drag'n'drop (multiple files)
export const FILES = Files<|endoftext|>