<commit_before>/*global angular, $, moment */

(function () {
    'use strict';
    angular.module('Calendar', []);
    angular.module('Calendar').controller('CalendarCtrl', CalendarCtrl);

    CalendarCtrl.$inject = ['CalendarService', 'calendarConfig', 'profileService', '$scope', '$timeout'];

    function CalendarCtrl(CalendarService, calendarConfig, profileService, $scope, $timeout) {
        var vm = this;
        vm.events = [];
        vm.calendarView = "month";
        vm.viewDate = new Date();
        vm.eventLocationDetails = {};
        vm.travelMode = null;
        vm.displayDeleteModal = false;
        vm.displaySuccess = false;
        vm.initialAddress = profileService.currentUserLocation || profileService.getCurrentUserLocation();

        vm.changePriorLocation = changePriorLocation;
        vm.closeMeetingModal = closeMeetingModal;
        vm.closeDeleteModal = closeDeleteModal;
        vm.saveEvent = saveEvent;
        vm.deleteEvent = deleteEvent;
        vm.alterEventStart = alterEventStart;
        vm.eventAction = [
            {
                label: ''
            }, {
                label: '',
                onClick: function (args) {
                    vm.displayDeleteModal = true;

                    $timeout(function () {
                        $("#modal2").modal('show');
                    }, 100);

                    vm.currentEventId = args.calendarEvent.id;
                }
        }];

        function closeDeleteModal() {
            $("#modal2").modal('hide');
            $timeout(function () {
                vm.displayDeleteModal = false;
            }, 1000);
        }

        init();

        function init() {

            initEventModal();

            CalendarService.fetchEvents().then(function (data) {
                var eventList = data.data.Items;
                for (var i = 0; i < eventList.length; i++) {
                    vm.events.push({
                        id: eventList[i].id,
                        title:eventList[i].eventTitle,
                        color: calendarConfig.colorTypes.info,
                        startsAt: new Date(eventList[i].eventStart),
                        endsAt: new Date(eventList[i].eventEnd),
                        eventTitle: eventList[i].eventTitle,
                        eventStart: eventList[i].eventStart,
                        eventEnd: eventList[i].eventEnd,
                        destinationPlaceId: eventList[i].destination,
                        origin: eventList[i].origin,
                        travelMode: eventList[i].travelMode,
                        actions: vm.eventAction,
                        draggable: true
                    });
                }
            })
        }

   vm.eventTimesChanged = function(event) {
        vm.viewDate = event.startsAt;
    CalendarService.saveMeeting(event, vm.forceSaveEvent).then(function (data) {
        console.log(data);
    });
    }

        function initEventModal() {
            vm.selectedPriorLocation = "home";
            vm.travelModeArray = [];
            vm.otherLocationDetails = {};
            vm.destinationPlaceId = null;
            vm.originPlaceId = null;
            vm.eventStartDate = '';
            vm.eventEndDate = '';
            vm.displayTravelModes = false;
            vm.forceSaveEvent = false;
            vm.displayModalError = false;
            vm.scheduleModalError = false;
            vm.eventAutocomplete = '';
            vm.otherLocation = '';
            vm.eventForm = {
                eventTitle: "",
                eventStart: null,
                eventEnd: null
            };

            vm.eventStart = new Date();
            vm.eventEnd = moment().add("hours", 1);
            vm.startDateOptions = {
                minDate: new Date()
            }
            vm.endDateOptions = {
                minDate: vm.eventStart
            }
        }

        function closeMeetingModal() {
            $("#eventModal").modal('hide');
            initEventModal();
        }

        function changeLocation() {
            vm.displayTravelModes = false;
            vm.travelMode = null;
            if (!vm.originPlaceId) {
                vm.originPlaceId = profileService.homeLocation.place_id;
            }
            CalendarService.fetchTransitDetails(vm.originPlaceId, vm.destinationPlaceId).then(function (data) {
                vm.travelModeArray = data;
                vm.displayTravelModes = true;
            });
        }

        $scope.$watch(function () {
            return vm.eventLocationDetails.place_id;
        }, function (newValue) {
            if (newValue) {
                vm.destinationPlaceId = newValue;
                changeLocation();
            }
        });

        $scope.$watch(function () {
            return vm.otherLocationDetails.place_id;
        }, function (newValue) {
            if (newValue) {
                vm.originPlaceId = newValue;
                changeLocation();
            }
        });

        function changePriorLocation() {
            vm.displayTravelModes = false;
            vm.travelMode = null;
            vm.otherLocation = null;
            vm.otherLocationDetails = {};
            switch (vm.selectedPriorLocation) {
                case "home":
                    vm.originPlaceId = profileService.homeLocation.place_id;
                    changeLocation();
                    break;
                case "work":
                    vm.originPlaceId = profileService.workLocation.place_id;
                    changeLocation();
                    break;
            }
        }

        function saveEvent() {
            vm.eventForm.originPlaceId = vm.originPlaceId;
            vm.eventForm.destinationPlaceId = vm.destinationPlaceId;
            vm.eventForm.eventStart = new Date(vm.eventStart).getTime();
            vm.eventForm.eventEnd = new Date(vm.eventEnd).getTime();
            vm.eventForm.travelMode = {
                mode: vm.travelMode.mode,
                distance: vm.travelMode.value.distance,
                time: vm.travelMode.value.duration
            };
            CalendarService.saveMeeting(vm.eventForm, vm.forceSaveEvent).then(function (data) {
                if (data.data.errorMessage && data.data.errorMessage == "Conflict") {
                    vm.displayModalError = true;
                    vm.forceSaveEvent = true;
                    vm.scheduleModalError = "This event conflicts with another scheduled event. Click Continue to proceed anyways."
                } else {
                    var id = data.data;
                    vm.events.push({
                        id: id,
                        title: vm.eventForm.eventTitle,
                        color: calendarConfig.colorTypes.info,
                        startsAt: new Date(vm.eventForm.eventStart),
                        endsAt: new Date(vm.eventForm.eventEnd),
                        actions: vm.eventAction
                    });
                    closeMeetingModal();
                    vm.successMessage = "Event has been added successfully";
                    vm.displaySuccess = true;
                    $timeout(function () {
                        vm.displaySuccess = false;
                    }, 3000)
                }
            });
        }

        function alterEventStart() {
            if (new Date(vm.eventStart).getTime() > new Date(vm.eventEnd).getTime()) {
                vm.eventEnd = moment(vm.eventStart).add("hours", 1);
            }
            vm.endDateOptions.minDate = vm.eventStart;
        }

        function deleteEvent() {
            CalendarService.deleteEvent(vm.currentEventId).then(function (data) {
                if (!data.data.errorMessage) {
                    for (var i = 0; i < vm.events.length; i++) {
                        if (vm.events[i].id === vm.currentEventId) {
                            vm.events.splice(i, 1);
                            vm.successMessage = "Event has been successfully deleted";
                            vm.displaySuccess = true;
                            closeDeleteModal();
                            $timeout(function () {
                                vm.displaySuccess = false;
                            }, 3000)
                            break;
                        }
                    }
                }
            });
        }
    }
})();
<commit_msg>Added modal after clicking on edit<commit_after>/*global angular, $, moment */

(function () {
    'use strict';
    angular.module('Calendar', []);
    angular.module('Calendar').controller('CalendarCtrl', CalendarCtrl);

    CalendarCtrl.$inject = ['CalendarService', 'calendarConfig', 'profileService', '$scope', '$timeout'];

    function CalendarCtrl(CalendarService, calendarConfig, profileService, $scope, $timeout) {
        var vm = this;
        vm.events = [];
        vm.calendarView = "month";
        vm.viewDate = new Date();
        vm.eventLocationDetails = {};
        vm.travelMode = null;
        vm.displayDeleteModal = false;
        vm.displayEditModal = false;
        vm.displaySuccess = false;
        vm.initialAddress = profileService.currentUserLocation || profileService.getCurrentUserLocation();
        vm.editEventObject = [];

        vm.changePriorLocation = changePriorLocation;
        vm.closeMeetingModal = closeMeetingModal;
        vm.closeDeleteModal = closeDeleteModal;
        vm.editEvent = editEvent;
        vm.saveEvent = saveEvent;
        vm.deleteEvent = deleteEvent;
        vm.alterEventStart = alterEventStart;
        vm.eventAction = [
            {
                label: '',
                onClick: function (args) {
                    vm.displayEditModal = true;
                    vm.currentEventId = args.calendarEvent.id;

                    for (var i = 0; i < vm.events.length; i++) {
                        if (vm.events[i].id === vm.currentEventId) {
                            console.log(vm.events[i]);
                            var editEvent = vm.events[i]
                            vm.selectedPriorLocation = "";
                            vm.travelModeArray = [];
                            vm.otherLocationDetails = {};
                            vm.destinationPlaceId = null;
                            vm.originPlaceId = null;
                            vm.eventStartDate = '';
                            vm.eventEndDate = '';
                            vm.displayTravelModes = true;
                            vm.forceSaveEvent = false;
                            vm.displayModalError = false;
                            vm.scheduleModalError = false;
                            vm.eventAutocomplete = editEvent.destinationPlaceId;
                            vm.otherLocation = '';
                            vm.eventForm = {
                                eventTitle: editEvent.eventTitle,
                                eventStart: null,
                                eventEnd: null
                            };

                            vm.eventStart = new Date(editEvent.eventStart);
                            vm.eventEnd = new Date(editEvent.eventEnd);//moment().add("hours", 1);
                            vm.startDateOptions = {
                                minDate: new Date()
                            }
                            vm.endDateOptions = {
                                minDate: vm.eventStart
                            }
                            break;
                        }
                    }

                    $timeout(function () {
                        $("#eventModal").modal('show');
                    }, 100);

                }
            }, {
                label: '',
                onClick: function (args) {
                    vm.displayDeleteModal = true;

                    $timeout(function () {
                        $("#modal2").modal('show');
                    }, 100);

                    vm.currentEventId = args.calendarEvent.id;
                }
        }];

        function closeDeleteModal() {
            $("#modal2").modal('hide');
            $timeout(function () {
                vm.displayDeleteModal = false;
            }, 1000);
        }

        function closeEditModal() {
            $("#eventModal").modal('hide');
            $timeout(function () {
                vm.displayEditModal = false;
            }, 1000);
            initEventModal();
        }

        init();

        function init() {

            initEventModal();

            CalendarService.fetchEvents().then(function (data) {
                var eventList = data.data.Items;
                for (var i = 0; i < eventList.length; i++) {
                    vm.events.push({
                        id: eventList[i].id,
                        title:eventList[i].eventTitle,
                        color: calendarConfig.colorTypes.info,
                        startsAt: new Date(eventList[i].eventStart),
                        endsAt: new Date(eventList[i].eventEnd),
                        eventTitle: eventList[i].eventTitle,
                        eventStart: eventList[i].eventStart,
                        eventEnd: eventList[i].eventEnd,
                        destinationPlaceId: eventList[i].destination,
                        origin: eventList[i].origin,
                        travelMode: eventList[i].travelMode,
                        actions: vm.eventAction,
                        draggable: true,
                        resizable:true
                    });
                }
            })
        }

   vm.eventTimesChanged = function(event) {
        vm.viewDate = event.startsAt;
    CalendarService.saveMeeting(event, vm.forceSaveEvent).then(function (data) {
        console.log(data);
    });
    }

        function initEventModal() {
            vm.selectedPriorLocation = "home";
            vm.travelModeArray = [];
            vm.otherLocationDetails = {};
            vm.destinationPlaceId = null;
            vm.originPlaceId = null;
            vm.eventStartDate = '';
            vm.eventEndDate = '';
            vm.displayTravelModes = false;
            vm.forceSaveEvent = false;
            vm.displayModalError = false;
            vm.scheduleModalError = false;
            vm.eventAutocomplete = '';
            vm.otherLocation = '';
            vm.eventForm = {
                eventTitle: "",
                eventStart: null,
                eventEnd: null
            };

            vm.eventStart = new Date();
            vm.eventEnd = moment().add("hours", 1);
            vm.startDateOptions = {
                minDate: new Date()
            }
            vm.endDateOptions = {
                minDate: vm.eventStart
            }
        }

        function closeMeetingModal() {
            $("#eventModal").modal('hide');
            initEventModal();
        }

        function changeLocation() {
            vm.displayTravelModes = false;
            vm.travelMode = null;
            if (!vm.originPlaceId) {
                vm.originPlaceId = profileService.homeLocation.place_id;
            }
            CalendarService.fetchTransitDetails(vm.originPlaceId, vm.destinationPlaceId).then(function (data) {
                vm.travelModeArray = data;
                vm.displayTravelModes = true;
            });
        }

        $scope.$watch(function () {
            return vm.eventLocationDetails.place_id;
        }, function (newValue) {
            if (newValue) {
                vm.destinationPlaceId = newValue;
                changeLocation();
            }
        });

        $scope.$watch(function () {
            return vm.otherLocationDetails.place_id;
        }, function (newValue) {
            if (newValue) {
                vm.originPlaceId = newValue;
                changeLocation();
            }
        });

        function changePriorLocation() {
            vm.displayTravelModes = false;
            vm.travelMode = null;
            vm.otherLocation = null;
            vm.otherLocationDetails = {};
            switch (vm.selectedPriorLocation) {
                case "home":
                    vm.originPlaceId = profileService.homeLocation.place_id;
                    changeLocation();
                    break;
                case "work":
                    vm.originPlaceId = profileService.workLocation.place_id;
                    changeLocation();
                    break;
            }
        }

        function saveEvent() {
            vm.eventForm.originPlaceId = vm.originPlaceId;
            vm.eventForm.destinationPlaceId = vm.destinationPlaceId;
            vm.eventForm.eventStart = new Date(vm.eventStart).getTime();
            vm.eventForm.eventEnd = new Date(vm.eventEnd).getTime();
            vm.eventForm.travelMode = {
                mode: vm.travelMode.mode,
                distance: vm.travelMode.value.distance,
                time: vm.travelMode.value.duration
            };
            CalendarService.saveMeeting(vm.eventForm, vm.forceSaveEvent).then(function (data) {
                if (data.data.errorMessage && data.data.errorMessage == "Conflict") {
                    vm.displayModalError = true;
                    vm.forceSaveEvent = true;
                    vm.scheduleModalError = "This event conflicts with another scheduled event. Click Continue to proceed anyways."
                } else {
                    var id = data.data;
                    vm.events.push({
                        id: id,
                        title: vm.eventForm.eventTitle,
                        color: calendarConfig.colorTypes.info,
                        startsAt: new Date(vm.eventForm.eventStart),
                        endsAt: new Date(vm.eventForm.eventEnd),
                        actions: vm.eventAction
                    });
                    closeMeetingModal();
                    vm.successMessage = "Event has been added successfully";
                    vm.displaySuccess = true;
                    $timeout(function () {
                        vm.displaySuccess = false;
                    }, 3000)
                }
            });
        }

        function alterEventStart() {
            if (new Date(vm.eventStart).getTime() > new Date(vm.eventEnd).getTime()) {
                vm.eventEnd = moment(vm.eventStart).add("hours", 1);
            }
            vm.endDateOptions.minDate = vm.eventStart;
        }

        function deleteEvent() {
            CalendarService.deleteEvent(vm.currentEventId).then(function (data) {
                if (!data.data.errorMessage) {
                    for (var i = 0; i < vm.events.length; i++) {
                        if (vm.events[i].id === vm.currentEventId) {
                            vm.events.splice(i, 1);
                            vm.successMessage = "Event has been successfully deleted";
                            vm.displaySuccess = true;
                            closeDeleteModal();
                            $timeout(function () {
                                vm.displaySuccess = false;
                            }, 3000)
                            break;
                        }
                    }
                }
            });
        }

        function editEvent() {
            console.log("Edit meeting pressed");
            console.log(vm.currentEventId)

        }
    }
})();
<|endoftext|>


<commit_before>var exec = require('child_process').exec;
var SerialPort = require("serialport").SerialPort
var serialPort = new SerialPort("/dev/ttyAMA0", {
  baudrate: 19200
}, false); // this is the openImmediately flag [default is true]
var host = "http://109.123.70.141:8545";
var mqtt = require('mqtt');
var client = mqtt.connect('ws://opantwerpen.be:15674');
var code;

var Web3 = require('web3');
var contractabi = {
  "bytecode": "60606040526000805560018054600160a060020a0319163317905560f6806100276000396000f3606060405260e060020a600035046333ac20098114602e57806384394e6f146037578063fa52c7d8146060575b005b60776000545b90565b6077600160a060020a033316600090815260026020526040812054600114156089575060016034565b607760043560026020526000908152604090205481565b60408051918252519081900360200190f35b6040812060019081905581548101825554600160a060020a03168134606082818181858883f1505060408051600160a060020a033316815290517fc950a438e6ad1cf066a2ec63cd7e6753ed8e6fe1d55949e889204d0f0230a23f94509081900360200192509050a1603456",
  "abi": [{
    "constant": true,
    "inputs": [],
    "name": "countValidations",
    "outputs": [{
      "name": "count",
      "type": "uint256"
    }],
    "type": "function"
  }, {
    "constant": false,
    "inputs": [],
    "name": "addValidation",
    "outputs": [{
      "name": "returnCode",
      "type": "uint256"
    }],
    "type": "function"
  }, {
    "constant": true,
    "inputs": [{
      "name": "",
      "type": "address"
    }],
    "name": "validators",
    "outputs": [{
      "name": "",
      "type": "uint256"
    }],
    "type": "function"
  }, {
    "inputs": [],
    "type": "constructor"
  }, {
    "anonymous": false,
    "inputs": [{
      "indexed": false,
      "name": "validator",
      "type": "address"
    }],
    "name": "ValidationAdded",
    "type": "event"
  }]
};

web3 = new Web3();

var writingtothelcd = false;

function schrijflcd(text, cb) {
  if (writingtothelcd === true) {
    console.log('still writing to the LCD... queueing command');
    return setTimeout(function() {
      schrijflcd(text)
    }, 500);
  }
  console.log("Writing to LCD: [" + text + "]");
  writingtothelcd = true;
  serialPort.write(String.fromCharCode(17) + String.fromCharCode(12) + (text + "                                ").substring(0, 32), function(err, results) {
    //serialPort.close();
    console.log("Done writing to LCD");
    writingtothelcd = false;
    if (cb) cb();
  });
}

var lidstatus = "closed";

function beweeglid(command, cb) {
  var richting = "";
  switch (command) {
    case 'open':
      if (lidstatus !== 'closed') {
        console.log('nope -lid is open');
        return;
      }
      doelid("1", function() {
        console.log('opened');
        lidstatus = 'opened';
        cb();
      });
      break;
    case 'close':
      if (lidstatus !== 'opened') {
        console.log('nope - lid is closed');
        return;
      }
      doelid("0", function() {
        cb();
        lidstatus = 'closed';
      });
      break;
  }
}

function doelid(command, cb) {
  child = exec(__dirname + "/motor 730 0 " + command, function(error, stdout, stderr) {
    if (error !== null) {
      console.log('exec error: ' + error);
    }
    console.log('command finished', command);
    cb();
  });
}

serialPort.open(function(error) {
  if (error) {
    console.log('failed to open: ' + error);
  } else {
    console.log('open');
    schrijflcd("Welkom bij de poezendoos");

    web3.setProvider(new web3.providers.HttpProvider(host));

    client.on('connect', function() {
      client.subscribe('poezendoos');
      client.publish('poezendoos', 'Poezendoos online!');
    });

    generateCode();
    client.subscribe(['poezendoos/service','poezendoos/' + code]);
    client.publish('poezendoos/' + code, 'command|listening');
    schrijflcd("   poezendoos" + String.fromCharCode(13) + "     " + code);

    client.on('message', function(topic, message) {
      // message is Buffer
      //console.log(message.toString());
      var msg = message.toString();

      var commandarray = msg.split("|");

      console.log(commandarray);
      // Check command and do something
      if (commandarray[0] === 'checkContract') {
        var contractaddress = commandarray[1];
        var pincode = commandarray[2];

        schrijflcd(" de poezendoos " + String.fromCharCode(13) + " kijkt het na...");

        checkContract(contractaddress, function(result) {
          console.log("ik heb een result: ", result);
          if (result > 1) {
            schrijflcd('u heeft ' + result + ' validaties');
            openDoor();
            client.publish(pincode, 'doosisopen');
          } else {
            schrijflcd('u heeft ' + result + ' validaties. Dat is niet genoeg');
          }
        });
        // check if the contract is valid.
        // checkContract(contractaddress, useraccount, function(result){
        //  if(result){
        //    openDoor();
        //  }
        // });
      };
      if (commandarray[0] === 'sluitDoos') {
        console.log('doos gaat dicht.');
        client.unsubscribe('poezendoos/' + code);
        closeDoor();
      }

      //client.end();

    });
  }
});

// HELPER functions //
function openDoor() {

  beweeglid('open', function() {
    schrijflcd('de doos is open');
  });

};

function closeDoor() {
  beweeglid('close', function() {
    schrijflcd('de doos is terug toe');
    console.log('closed');
    generateCode();
    client.subscribe('poezendoos/' + code);
    client.publish('poezendoos/' + code, 'command|listening');
    schrijflcd("   poezendoos" + String.fromCharCode(13) + "     " + code);
  });
};

function generateCode() {
  code = Math.floor(Math.random() * 90000) + 10000;
  //console.log(code);
  //fn(code);
};

function checkContract(contractaddress, fn) {
  console.log("Checking contract: ", contractaddress);
  console.log("Checking balance: ", web3.eth.getBalance(contractaddress).toNumber(10));
  var MyContract = web3.eth.contract(contractabi.abi);
  //console.log("Mycontract: ", MyContract);
  console.log('get contract from blockchain');
  var myContractInstance = MyContract.at(contractaddress);
  console.log('run countValidations');
  var result = myContractInstance.countValidations().toNumber(10);
  console.log("got result: ", result);
  fn(result);
};
<commit_msg>console.log channels where we are listening....<commit_after>var exec = require('child_process').exec;
var SerialPort = require("serialport").SerialPort
var serialPort = new SerialPort("/dev/ttyAMA0", {
  baudrate: 19200
}, false); // this is the openImmediately flag [default is true]
var host = "http://109.123.70.141:8545";
var mqtt = require('mqtt');
var client = mqtt.connect('ws://opantwerpen.be:15674');
var code;

var Web3 = require('web3');
var contractabi = {
  "bytecode": "60606040526000805560018054600160a060020a0319163317905560f6806100276000396000f3606060405260e060020a600035046333ac20098114602e57806384394e6f146037578063fa52c7d8146060575b005b60776000545b90565b6077600160a060020a033316600090815260026020526040812054600114156089575060016034565b607760043560026020526000908152604090205481565b60408051918252519081900360200190f35b6040812060019081905581548101825554600160a060020a03168134606082818181858883f1505060408051600160a060020a033316815290517fc950a438e6ad1cf066a2ec63cd7e6753ed8e6fe1d55949e889204d0f0230a23f94509081900360200192509050a1603456",
  "abi": [{
    "constant": true,
    "inputs": [],
    "name": "countValidations",
    "outputs": [{
      "name": "count",
      "type": "uint256"
    }],
    "type": "function"
  }, {
    "constant": false,
    "inputs": [],
    "name": "addValidation",
    "outputs": [{
      "name": "returnCode",
      "type": "uint256"
    }],
    "type": "function"
  }, {
    "constant": true,
    "inputs": [{
      "name": "",
      "type": "address"
    }],
    "name": "validators",
    "outputs": [{
      "name": "",
      "type": "uint256"
    }],
    "type": "function"
  }, {
    "inputs": [],
    "type": "constructor"
  }, {
    "anonymous": false,
    "inputs": [{
      "indexed": false,
      "name": "validator",
      "type": "address"
    }],
    "name": "ValidationAdded",
    "type": "event"
  }]
};

web3 = new Web3();

var writingtothelcd = false;

function schrijflcd(text, cb) {
  if (writingtothelcd === true) {
    console.log('still writing to the LCD... queueing command');
    return setTimeout(function() {
      schrijflcd(text)
    }, 500);
  }
  console.log("Writing to LCD: [" + text + "]");
  writingtothelcd = true;
  serialPort.write(String.fromCharCode(17) + String.fromCharCode(12) + (text + "                                ").substring(0, 32), function(err, results) {
    //serialPort.close();
    console.log("Done writing to LCD");
    writingtothelcd = false;
    if (cb) cb();
  });
}

var lidstatus = "closed";

function beweeglid(command, cb) {
  var richting = "";
  switch (command) {
    case 'open':
      if (lidstatus !== 'closed') {
        console.log('nope -lid is open');
        return;
      }
      doelid("1", function() {
        console.log('opened');
        lidstatus = 'opened';
        cb();
      });
      break;
    case 'close':
      if (lidstatus !== 'opened') {
        console.log('nope - lid is closed');
        return;
      }
      doelid("0", function() {
        cb();
        lidstatus = 'closed';
      });
      break;
  }
}

function doelid(command, cb) {
  child = exec(__dirname + "/motor 730 0 " + command, function(error, stdout, stderr) {
    if (error !== null) {
      console.log('exec error: ' + error);
    }
    console.log('command finished', command);
    cb();
  });
}

serialPort.open(function(error) {
  if (error) {
    console.log('failed to open: ' + error);
  } else {
    console.log('open');
    schrijflcd("Welkom bij de poezendoos");

    web3.setProvider(new web3.providers.HttpProvider(host));

    client.on('connect', function() {
      client.subscribe('poezendoos');
      client.publish('poezendoos', 'Poezendoos online!');
    });

    generateCode();
    var channels = ['poezendoos/service','poezendoos/' + code];
    console.log("Poezendoos channels:",channels);
    client.subscribe(channels);
    client.publish('poezendoos/' + code, 'command|listening');
    schrijflcd("   poezendoos" + String.fromCharCode(13) + "     " + code);

    client.on('message', function(topic, message) {
      // message is Buffer
      //console.log(message.toString());
      var msg = message.toString();

      var commandarray = msg.split("|");

      console.log(commandarray);
      // Check command and do something
      if (commandarray[0] === 'checkContract') {
        var contractaddress = commandarray[1];
        var pincode = commandarray[2];

        schrijflcd(" de poezendoos " + String.fromCharCode(13) + " kijkt het na...");

        checkContract(contractaddress, function(result) {
          console.log("ik heb een result: ", result);
          if (result > 1) {
            schrijflcd('u heeft ' + result + ' validaties');
            openDoor();
            client.publish(pincode, 'doosisopen');
          } else {
            schrijflcd('u heeft ' + result + ' validaties. Dat is niet genoeg');
          }
        });
        // check if the contract is valid.
        // checkContract(contractaddress, useraccount, function(result){
        //  if(result){
        //    openDoor();
        //  }
        // });
      };
      if (commandarray[0] === 'sluitDoos') {
        console.log('doos gaat dicht.');
        client.unsubscribe('poezendoos/' + code);
        closeDoor();
      }

      //client.end();

    });
  }
});

// HELPER functions //
function openDoor() {

  beweeglid('open', function() {
    schrijflcd('de doos is open');
  });

};

function closeDoor() {
  beweeglid('close', function() {
    schrijflcd('de doos is terug toe');
    console.log('closed');
    generateCode();
    client.subscribe('poezendoos/' + code);
    client.publish('poezendoos/' + code, 'command|listening');
    schrijflcd("   poezendoos" + String.fromCharCode(13) + "     " + code);
  });
};

function generateCode() {
  code = Math.floor(Math.random() * 90000) + 10000;
  //console.log(code);
  //fn(code);
};

function checkContract(contractaddress, fn) {
  console.log("Checking contract: ", contractaddress);
  console.log("Checking balance: ", web3.eth.getBalance(contractaddress).toNumber(10));
  var MyContract = web3.eth.contract(contractabi.abi);
  //console.log("Mycontract: ", MyContract);
  console.log('get contract from blockchain');
  var myContractInstance = MyContract.at(contractaddress);
  console.log('run countValidations');
  var result = myContractInstance.countValidations().toNumber(10);
  console.log("got result: ", result);
  fn(result);
};
<|endoftext|>


<commit_before>/*!
 * mempoolentry.js - mempool entry object for bcoin
 * Copyright (c) 2014-2017, Christopher Jeffrey (MIT License).
 * https://github.com/bcoin-org/bcoin
 */

'use strict';

var policy = require('../protocol/policy');
var util = require('../utils/util');
var Script = require('../script/script');

/**
 * Represents a mempool entry.
 * @alias module:mempool.MempoolEntry
 * @constructor
 * @param {Object} options
 * @param {TX} options.tx - Transaction in mempool.
 * @param {Number} options.height - Entry height.
 * @param {Number} options.priority - Entry priority.
 * @param {Number} options.ts - Entry time.
 * @param {Amount} options.value - Value of on-chain coins.
 * @property {TX} tx
 * @property {Number} height
 * @property {Number} priority
 * @property {Number} ts
 * @property {Amount} value
 */

function MempoolEntry(options) {
  if (!(this instanceof MempoolEntry))
    return new MempoolEntry(options);

  this.tx = null;
  this.height = -1;
  this.size = 0;
  this.sigops = 0;
  this.priority = 0;
  this.fee = 0;
  this.ts = 0;
  this.value = 0;
  this.dependencies = false;
  this.descFee = 0;
  this.descSize = 0;

  if (options)
    this.fromOptions(options);
}

/**
 * Inject properties from options object.
 * @private
 * @param {Object} options
 */

MempoolEntry.prototype.fromOptions = function fromOptions(options) {
  this.tx = options.tx;
  this.height = options.height;
  this.size = options.size;
  this.sigops = options.sigops;
  this.priority = options.priority;
  this.fee = options.fee;
  this.ts = options.ts;
  this.value = options.value;
  this.dependencies = options.dependencies;
  this.descFee = options.descFee;
  this.descSize = options.descSize;
  return this;
};

/**
 * Instantiate mempool entry from options.
 * @param {Object} options
 * @returns {MempoolEntry}
 */

MempoolEntry.fromOptions = function fromOptions(options) {
  return new MempoolEntry().fromOptions(options);
};

/**
 * Inject properties from transaction.
 * @private
 * @param {TX} tx
 * @param {Number} height
 */

MempoolEntry.prototype.fromTX = function fromTX(tx, view, height) {
  var flags = Script.flags.STANDARD_VERIFY_FLAGS;
  var priority = tx.getPriority(view, height);
  var value = tx.getChainValue(view);
  var sigops = tx.getSigopsCost(view, flags);
  var dependencies = false;
  var size = tx.getVirtualSize();
  var fee = tx.getFee(view);
  var i, input;

  for (i = 0; i < tx.inputs.length; i++) {
    input = tx.inputs[i];
    if (view.getHeight(input) === -1) {
      dependencies = true;
      break;
    }
  }

  this.tx = tx;
  this.height = height;
  this.size = size;
  this.sigops = sigops;
  this.priority = priority;
  this.fee = fee;
  this.ts = util.now();
  this.value = value;
  this.dependencies = dependencies;
  this.descFee = fee;
  this.descSize = size;

  return this;
};

/**
 * Create a mempool entry from a TX.
 * @param {TX} tx
 * @param {Number} height - Entry height.
 * @returns {MempoolEntry}
 */

MempoolEntry.fromTX = function fromTX(tx, view, height) {
  return new MempoolEntry().fromTX(tx, view, height);
};

/**
 * Calculate priority, taking into account
 * the entry height delta, modified size,
 * and chain value.
 * @param {Number} height
 * @returns {Number} Priority.
 */

MempoolEntry.prototype.getPriority = function getPriority(height) {
  var heightDelta = height - this.height;
  var modSize = this.tx.getModifiedSize(this.size);
  var deltaPriority = (heightDelta * this.value) / modSize;
  var result = this.priority + Math.floor(deltaPriority);
  if (result < 0)
    result = 0;
  return result;
};

/**
 * Get fee.
 * @returns {Amount}
 */

MempoolEntry.prototype.getFee = function getFee() {
  return this.fee;
};

/**
 * Calculate fee rate.
 * @returns {Rate}
 */

MempoolEntry.prototype.getRate = function getRate() {
  return policy.getRate(this.size, this.fee);
};

/**
 * Calculate fee cumulative descendant rate.
 * @returns {Rate}
 */

MempoolEntry.prototype.getDescRate = function getDescRate() {
  return policy.getRate(this.descSize, this.descFee);
};

/**
 * Test whether the entry is free with
 * the current priority (calculated by
 * current height).
 * @param {Number} height
 * @returns {Boolean}
 */

MempoolEntry.prototype.isFree = function isFree(height) {
  var priority = this.getPriority(height);
  return priority > policy.FREE_THRESHOLD;
};

/*
 * Expose
 */

module.exports = MempoolEntry;
<commit_msg>mempool: use virtual size weighted against sigops.<commit_after>/*!
 * mempoolentry.js - mempool entry object for bcoin
 * Copyright (c) 2014-2017, Christopher Jeffrey (MIT License).
 * https://github.com/bcoin-org/bcoin
 */

'use strict';

var policy = require('../protocol/policy');
var util = require('../utils/util');
var Script = require('../script/script');

/**
 * Represents a mempool entry.
 * @alias module:mempool.MempoolEntry
 * @constructor
 * @param {Object} options
 * @param {TX} options.tx - Transaction in mempool.
 * @param {Number} options.height - Entry height.
 * @param {Number} options.priority - Entry priority.
 * @param {Number} options.ts - Entry time.
 * @param {Amount} options.value - Value of on-chain coins.
 * @property {TX} tx
 * @property {Number} height
 * @property {Number} priority
 * @property {Number} ts
 * @property {Amount} value
 */

function MempoolEntry(options) {
  if (!(this instanceof MempoolEntry))
    return new MempoolEntry(options);

  this.tx = null;
  this.height = -1;
  this.size = 0;
  this.sigops = 0;
  this.priority = 0;
  this.fee = 0;
  this.ts = 0;
  this.value = 0;
  this.dependencies = false;
  this.descFee = 0;
  this.descSize = 0;

  if (options)
    this.fromOptions(options);
}

/**
 * Inject properties from options object.
 * @private
 * @param {Object} options
 */

MempoolEntry.prototype.fromOptions = function fromOptions(options) {
  this.tx = options.tx;
  this.height = options.height;
  this.size = options.size;
  this.sigops = options.sigops;
  this.priority = options.priority;
  this.fee = options.fee;
  this.ts = options.ts;
  this.value = options.value;
  this.dependencies = options.dependencies;
  this.descFee = options.descFee;
  this.descSize = options.descSize;
  return this;
};

/**
 * Instantiate mempool entry from options.
 * @param {Object} options
 * @returns {MempoolEntry}
 */

MempoolEntry.fromOptions = function fromOptions(options) {
  return new MempoolEntry().fromOptions(options);
};

/**
 * Inject properties from transaction.
 * @private
 * @param {TX} tx
 * @param {Number} height
 */

MempoolEntry.prototype.fromTX = function fromTX(tx, view, height) {
  var flags = Script.flags.STANDARD_VERIFY_FLAGS;
  var value = tx.getChainValue(view);
  var sigops = tx.getSigopsCost(view, flags);
  var size = tx.getSigopsSize(sigops);
  var priority = tx.getPriority(view, height, size);
  var fee = tx.getFee(view);
  var dependencies = false;
  var i, input;

  for (i = 0; i < tx.inputs.length; i++) {
    input = tx.inputs[i];
    if (view.getHeight(input) === -1) {
      dependencies = true;
      break;
    }
  }

  this.tx = tx;
  this.height = height;
  this.size = size;
  this.sigops = sigops;
  this.priority = priority;
  this.fee = fee;
  this.ts = util.now();
  this.value = value;
  this.dependencies = dependencies;
  this.descFee = fee;
  this.descSize = size;

  return this;
};

/**
 * Create a mempool entry from a TX.
 * @param {TX} tx
 * @param {Number} height - Entry height.
 * @returns {MempoolEntry}
 */

MempoolEntry.fromTX = function fromTX(tx, view, height) {
  return new MempoolEntry().fromTX(tx, view, height);
};

/**
 * Calculate priority, taking into account
 * the entry height delta, modified size,
 * and chain value.
 * @param {Number} height
 * @returns {Number} Priority.
 */

MempoolEntry.prototype.getPriority = function getPriority(height) {
  var heightDelta = height - this.height;
  var modSize = this.tx.getModifiedSize(this.size);
  var deltaPriority = (heightDelta * this.value) / modSize;
  var result = this.priority + Math.floor(deltaPriority);
  if (result < 0)
    result = 0;
  return result;
};

/**
 * Get fee.
 * @returns {Amount}
 */

MempoolEntry.prototype.getFee = function getFee() {
  return this.fee;
};

/**
 * Calculate fee rate.
 * @returns {Rate}
 */

MempoolEntry.prototype.getRate = function getRate() {
  return policy.getRate(this.size, this.fee);
};

/**
 * Calculate fee cumulative descendant rate.
 * @returns {Rate}
 */

MempoolEntry.prototype.getDescRate = function getDescRate() {
  return policy.getRate(this.descSize, this.descFee);
};

/**
 * Test whether the entry is free with
 * the current priority (calculated by
 * current height).
 * @param {Number} height
 * @returns {Boolean}
 */

MempoolEntry.prototype.isFree = function isFree(height) {
  var priority = this.getPriority(height);
  return priority > policy.FREE_THRESHOLD;
};

/*
 * Expose
 */

module.exports = MempoolEntry;
<|endoftext|>


<commit_before>/*global define, exports*/
/*jshint maxlen:false*/
/*jshint -W098*/ // ignore unused gpf
/*global __gpf__*/
(function (root, factory) {
    "use strict";

    /**
     * Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
     * Rhino, and plain browser loading.
     *
     * 2014-12-04 ABZ Extended for PhantomJS
     * 2015-05-29 ABZ Modified to catch former value of gpf
     */
    if (typeof define === "function" && define.amd) {
        define(["exports"], factory);
    } else if (typeof exports !== "undefined") {
        factory(exports);
    } else if (typeof module !== "undefined" && module.exports) {
        factory(module.exports);
    } else {
        var newGpf = {};
        factory(newGpf);
        root.gpf = newGpf;
    }
}(this, function (/*gpf:no-reduce*/gpf) {
    "use strict";
    /*jshint -W030*/ // Is used as a placeholder for injecting modules
    __gpf__;
}));<commit_msg>ESLint fixes<commit_after>/*global define, exports*/
/*jshint maxlen:false*/
/*jshint -W098*/ // ignore unused gpf
/*eslint no-unused-vars: 0*/ // ignore unused gpf
/*global __gpf__*/
(function (root, factory) {
    "use strict";

    /**
     * Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
     * Rhino, and plain browser loading.
     *
     * 2014-12-04 ABZ Extended for PhantomJS
     * 2015-05-29 ABZ Modified to catch former value of gpf
     */
    if (typeof define === "function" && define.amd) {
        define(["exports"], factory);
    } else if (typeof exports !== "undefined") {
        factory(exports);
    } else if (typeof module !== "undefined" && module.exports) {
        factory(module.exports);
    } else {
        var newGpf = {};
        factory(newGpf);
        root.gpf = newGpf;
    }
}(this, function (/*gpf:no-reduce*/gpf) {
    "use strict";
    /*jshint -W030*/ // Is used as a placeholder for injecting modules
    __gpf__;
}));
<|endoftext|>


<commit_before>var http = require('http');

module.exports = function(config) {
	return function(req, res, next) {
		if(/\.[\w]+$/.test(req.path)) {
			var err = new Error(http.STATUS_CODES[404]);
			err.status = 404;
			next(err);
		} else
			next();
	};
};
<commit_msg>Add path to Error message in static404.<commit_after>module.exports = function(config) {
	return function(req, res, next) {
		if(/\.[\w]+$/.test(req.path)) {
			var err = new Error('Not found: ' + req.path);
			err.status = 404;
			next(err);
		} else
			next();
	};
};
<|endoftext|>


<commit_before>// @flow

import { table } from 'table';
import { red } from 'chalk';
import R from 'ramda';

import { config } from '../config';
import gql from '../gql';
import { runGQLQuery } from '../query';
import {
  printProjectConfigurationError,
  printGraphQLErrors,
} from '../printErrors';

import typeof Yargs from 'yargs';
import type { BaseArgs } from '.';

export const command = 'customer';
export const description = 'Show customer details for a given project name';

export function builder(yargs: Yargs) {
  return yargs
    .usage(`$0 ${command} - ${description}`)
    .options({
      project: {
        demandOption: false,
        describe: 'Specify a project for the customer',
        type: 'string',
      },
    })
    .alias('p', 'project')
    .example(
      `$0 ${command}`,
      'Show customer details for the project configured in .lagoon.yml',
    )
    .example(
      `$0 ${command} -p myproject`,
      'Show customer details for the project "myproject"',
    );
}

type GetCustomerDetailsArgs = {
  project: string,
  clog: typeof console.log,
  cerr: typeof console.error,
};

export async function getCustomerDetails({
  project,
  clog,
  cerr,
}:
GetCustomerDetailsArgs): Promise<number> {
  const query = gql`
    query CustomerByProjectName($project: String!) {
      projectByName(name: $project) {
        customer {
          name
          comment
          private_key
          sshKeys {
            name
            keyValue
            keyType
            created
          }
          created
        }
      }
    }
  `;

  const result = await runGQLQuery({
    cerr,
    query,
    variables: { project },
  });

  const { errors } = result;
  if (errors != null) {
    return printGraphQLErrors(cerr, ...errors);
  }

  const customer = R.path(['data', 'projectByName', 'customer'], result);

  if (customer == null) {
    clog(red(`No customer found for project '${project}'!`));
    return 0;
  }

  const formatDeployPrivateKey = R.ifElse(
    R.identity,
    R.always('\u221A'),
    R.always('\u2717'),
  );
  const formatSshKeys = R.map(R.prop('name'));

  clog(`Customer details for project '${project}':`);
  clog(table([
    ['Name', R.prop('name', customer)],
    ['Comment', R.prop('comment', customer)],
    [
      'Deploy Private Key',
      formatDeployPrivateKey(R.prop('private_key', customer)),
    ],
    [
      'SSH Keys',
      R.join(', ', formatSshKeys(R.propOr([], 'sshKeys', customer))),
    ],
    ['Created', R.prop('created', customer)],
  ]));

  return 0;
}

type Args = BaseArgs & {
  argv: {
    project: ?string,
  },
};

export async function handler({ argv, clog, cerr }: Args): Promise<number> {
  const project = R.prop('project', argv) || R.prop('project', config);

  if (project == null) {
    return printProjectConfigurationError(cerr);
  }

  return getCustomerDetails({ project, clog, cerr });
}
<commit_msg>Format<commit_after>// @flow

import { table } from 'table';
import { red } from 'chalk';
import R from 'ramda';

import { config } from '../config';
import gql from '../gql';
import { runGQLQuery } from '../query';
import {
  printProjectConfigurationError,
  printGraphQLErrors,
} from '../printErrors';

import typeof Yargs from 'yargs';
import type { BaseArgs } from '.';

export const command = 'customer';
export const description = 'Show customer details for a given project name';

export function builder(yargs: Yargs) {
  return yargs
    .usage(`$0 ${command} - ${description}`)
    .options({
      project: {
        demandOption: false,
        describe: 'Specify a project for the customer',
        type: 'string',
      },
    })
    .alias('p', 'project')
    .example(
      `$0 ${command}`,
      'Show customer details for the project configured in .lagoon.yml',
    )
    .example(
      `$0 ${command} -p myproject`,
      'Show customer details for the project "myproject"',
    );
}

type GetCustomerDetailsArgs = {
  project: string,
  clog: typeof console.log,
  cerr: typeof console.error,
};

export async function getCustomerDetails({
  project,
  clog,
  cerr,
}:
GetCustomerDetailsArgs): Promise<number> {
  const query = gql`
    query CustomerByProjectName($project: String!) {
      projectByName(name: $project) {
        customer {
          name
          comment
          private_key
          sshKeys {
            name
            keyValue
            keyType
            created
          }
          created
        }
      }
    }
  `;

  const result = await runGQLQuery({
    cerr,
    query,
    variables: { project },
  });

  const { errors } = result;
  if (errors != null) {
    return printGraphQLErrors(cerr, ...errors);
  }

  const customer = R.path(['data', 'projectByName', 'customer'], result);

  if (customer == null) {
    clog(red(`No customer found for project '${project}'!`));
    return 0;
  }

  const formatDeployPrivateKey = R.ifElse(
    R.identity,
    R.always('\u221A'),
    R.always('\u2717'),
  );
  const formatSshKeys = R.map(R.prop('name'));

  clog(`Customer details for project '${project}':`);
  clog(
    table([
      ['Name', R.prop('name', customer)],
      ['Comment', R.prop('comment', customer)],
      [
        'Deploy Private Key',
        formatDeployPrivateKey(R.prop('private_key', customer)),
      ],
      [
        'SSH Keys',
        R.join(', ', formatSshKeys(R.propOr([], 'sshKeys', customer))),
      ],
      ['Created', R.prop('created', customer)],
    ]),
  );

  return 0;
}

type Args = BaseArgs & {
  argv: {
    project: ?string,
  },
};

export async function handler({ argv, clog, cerr }: Args): Promise<number> {
  const project = R.prop('project', argv) || R.prop('project', config);

  if (project == null) {
    return printProjectConfigurationError(cerr);
  }

  return getCustomerDetails({ project, clog, cerr });
}
<|endoftext|>


<commit_before>'use strict'

var isNode = (typeof window === 'undefined');

var path, slash, child_process;

var requireHack = require;

if (isNode) {
  path = requireHack("path");
  slash = requireHack("slash");
  child_process = requireHack("child_process");
}

function send(receiver, message) {
  if (!receiver) return;

  if (isNode) {
    receiver.send(message);
  } else {
    receiver.postMessage(message);
  }
}

function createProcess(script, cwd) {
  if (isNode) {
    let p = child_process.fork(path.join(process.cwd(), script), {
      cwd: toAbsPath(cwd),
      // pipe stdout/stderr into this process
      silent: true
    });

    // handle stdout of child
    p.stdout.on("data", (data) => {
      process.stdout.write(`[Indexing] (${cwd}) ${data}`);
    });

    // handle stderr of child
    p.stderr.on("data", (data) => {
      process.stderr.write(`[Indexing] (${cwd}) ${data}`);
    });

    return p;
  }

  // in Browser:
  return new Worker(script);
}

// Object that holds workers for server subdirectories,
// e.g. '/lively4-core'
var workers = {};
var indexStatus = {};

var promiseCallbacks = {};
var workerReadyPromise;
// rootFolder is an absolute directory to where the server serves,
// e.g. where the lively4-core folder is found
var rootFolder = null;
var idxFileName = "index.l4idx";

var curMsgId = 0;

// *** Exported methods ***

export function setRootFolder(filepath) {
  // becomes e.g. "C:/felix/bla" on Windows
  if (isNode) {
    rootFolder = slash(path.resolve(filepath));
  } else {
    rootFolder = filepath;
  }
}

export function startWorker(subdir) {
  return new Promise((resolve, reject) => {
    if (!rootFolder) {
      throw new Error("startWorker: no root folder set");
    }

    if (workers[subdir]) {
      console.log("[Indexing] Worker already exists");
      resolve();
      return;
    }

    console.log("[Indexing] Starting new worker for " + subdir);
    try {
      let script = isNode ? __dirname + "../server/lunr-node-search-worker.js" : "./src/external/lively4-search/client/lunr-es6-search-worker-wrapper.js";
      workers[subdir] = createProcess(script, subdir);
    } catch (err) {
      console.log("[Indexing] Error starting new worker for " + subdir + ": " + err);
      reject(err);
      return;
    }

    let messageHandler = function(m) {
      // web workers hide the sent message behind the data key
      if (!isNode) {
        m = m.data;
      }
      switch (m.type) {
        case "worker-ready":
          resolve();
          break;
        case "search-response":
          handleSearchResponse(m.msgId, m.message);
          break;
        case "init-response":
          handleInitResponse(m.msgId, m.message, subdir);
          break;
        case "index-status-response":
          handleIndexStatusResponse(m.msgId, m.message, subdir);
          break;
        case "error":
          console.log("[Indexing] Error (" + subdir + "): " + m.message);
          break;
        default:
          console.log("[Indexing] Unknown message:", m);
      }
    }

    if (isNode) {
      workers[subdir].on("message", messageHandler);
    } else {
      workers[subdir].onmessage = messageHandler;
    }
  });
}

function stopWorker(subdir) {
  console.log("stop", subdir);
  send(workers[subdir], {
    type: "stop"
  });

  delete workers[subdir];
  delete indexStatus[subdir];
}

export function createIndex(subdir, options) {
  return startWorker(subdir).then(() => {
    return new Promise((resolve, reject) => {
      if (!rootFolder) {
        console.log("[Indexing] Cannot create index, no root folder set");
        reject("Error: no root folder set");
        return;
      }

      if (indexStatus[subdir] === "ready") {
        console.log("[Indexing] Index already exists");
        resolve();
        return;
      }

      if (indexStatus[subdir] === "indexing") {
        reject();
        return;
      }

      var msgId = getNextMsgId();
      promiseCallbacks[msgId] = {
        resolve: resolve,
        reject: reject
      };

      send(workers[subdir], {
        type: "init",
        msgId: msgId,
        options: options
      });

      indexStatus[subdir] = "indexing";
    });
  });
}

export function removeIndex(subdir, options) {
  return startWorker(subdir).then(() => {
    send(workers[subdir], {
      type: "removeIndex"
    });

    stopWorker(subdir);

    delete indexStatus[subdir];
  });
}

export function setup(options) {
  return new Promise((resolve, reject) => {

    let fetchStatus =  () => {
      createIndex(options.path, options).then( () => {
        resolve();
        clearInterval(interval);
      }, () => {
        console.log("[Indexing] Waiting for index: " + options.name)
      });
    };

    fetchStatus();
    let interval = setInterval(fetchStatus, 5000);
  });
}

export function search(subdir, query) {
  if (!workers[subdir]) {
    console.log("[Indexing] Cannot search, no index created for " + subdir);
    return Promise.reject();
  }

  var msgId = getNextMsgId();
  promiseCallbacks[msgId] = {};

  var p = new Promise((resolve, reject) => {
    promiseCallbacks[msgId].resolve = resolve;
    promiseCallbacks[msgId].reject = reject;
  });

  send(workers[subdir], {
    type: "search",
    msgId: msgId,
    query: query
  });

  return p;
}

export function getStatus(subdir, options) {
  return startWorker(subdir).then(() => {
    if (indexStatus[subdir]) {
      return Promise.resolve(indexStatus[subdir]);
    }
    var msgId = getNextMsgId();
    promiseCallbacks[msgId] = {};

    var p = new Promise((resolve, reject) => {
      promiseCallbacks[msgId].resolve = resolve;
      promiseCallbacks[msgId].reject = reject;
    });

    send(workers[subdir], {
      type: "checkIndexFile",
      msgId: msgId,
      options: options
    });

    return p;
  });
}

export function find(pattern) {
  return search(this.path, pattern).then( (result) => {
    return result.map( (res) => {
      res.path = join(this.path, res.ref);
      res.type = "dropbox";
      return res;
    });
  });
}

function handleSearchResponse(msgId, result) {
  if (!promiseCallbacks[msgId]) {
    console.log(`[Indexing] No promise registered for ${msgId}`);
    return;
  }

  var resolve = promiseCallbacks[msgId].resolve;
  delete promiseCallbacks[msgId];

  resolve(result);
}

function handleInitResponse(msgId, result, subdir) {
  // Worker does not send a msgId, when it had to create the
  // requested index, because the msgId was already used to
  // signal that the index did not exist.
  if (!msgId) {
    // index has been created now,
    // so next call to createIndex will resolve immediately
    indexStatus[subdir] = "ready";
    return;
  }

  if (!promiseCallbacks[msgId]) {
    // this should never happen!
    console.log(`[Indexing] No promise registered for ${msgId}`);
    return;
  }

  var resolve = promiseCallbacks[msgId].resolve;
  var reject = promiseCallbacks[msgId].reject;
  delete promiseCallbacks[msgId];

  if (result === "ready") {
    // index was requested and just had to be loaded from disk
    indexStatus[subdir] = "ready";
    resolve();
  } else {
    // index was requested, does not exist and is being built now
    indexStatus[subdir] = "indexing";
    reject();
  }
}

function handleIndexStatusResponse(msgId, result, subdir) {
  if (!promiseCallbacks[msgId]) {
    // this should never happen!
    console.log(`[Indexing] No promise registered for ${msgId}`);
    return;
  }

  var resolve = promiseCallbacks[msgId].resolve;
  delete promiseCallbacks[msgId];

  resolve(result);

  if (result === "unavailable") {
    stopWorker(subdir);
  }
}

export function addFile(serverRelPath) {
  // e.g. serverRelPath == "/lively4-core/src/client/foo.js"
  serverRelPath = slash(serverRelPath);
  // find corresponding index
  var subdir = getIndexSubdir(serverRelPath);

  if (!subdir || !workers[subdir]) {
    console.log("[Indexing] Cannot add file, no index created for " + serverRelPath);
    return;
  }

  var absPath = toAbsPath(serverRelPath);
  send(workers[subdir], {
    type: "addFile",
    idxRelPath: toIdxRelPath(subdir, absPath)
  });
}

export function removeFile(serverRelPath) {
  // e.g. serverRelPath == "/lively4-core/src/client/foo.js"
  serverRelPath = slash(serverRelPath);
  // find corresponding index
  var subdir = getIndexSubdir(serverRelPath);
  if (!subdir) {
    // no index found for the serverRelPath, so dont remove it
    return;
  }
  if (!workers[subdir]) {
    console.log("[Indexing] Cannot remove file, no index created for " + subdir);
    return;
  }

  var absPath = toAbsPath(serverRelPath);
  send(workers[subdir], {
    type: "removeFile",
    idxRelPath: toIdxRelPath(subdir, absPath)
  });
}

// *** Helper methods ***

function getIndexSubdir(filepath) {
  return Object.keys(workers).find(function(subidx) {
    return filepath.indexOf(subidx + "/") == 0;
  });
}

function toAbsPath(serverRelPath) {
  return slash(path.join(rootFolder, serverRelPath));
}

function toIdxRelPath(subdir, absPath) {
  if (!rootFolder) {
    return;
  }

  // remove e.g. <rootFolder>/lively4-core/ (including the last slash, therefore + 1)
  return slash(absPath.slice(rootFolder.length + subdir.length + 1));
}

function getNextMsgId() {
  curMsgId++;
  return curMsgId;
}

function join(path1, path2) {
  if (path1[path1.length-1] != "/") {
    path1 += "/";
  }
  if (path2[0] == "/") {
    path2 = path2.slice(1, path2.length);
  }
  return path1 + path2;
}
<commit_msg>fix process path<commit_after>'use strict'

var isNode = (typeof window === 'undefined');

var path, slash, child_process;

var requireHack = require;

if (isNode) {
  path = requireHack("path");
  slash = requireHack("slash");
  child_process = requireHack("child_process");
}

function send(receiver, message) {
  if (!receiver) return;

  if (isNode) {
    receiver.send(message);
  } else {
    receiver.postMessage(message);
  }
}

function createProcess(script, cwd) {
  if (isNode) {
    let p = child_process.fork(path.join(process.cwd(), script), {
      cwd: toAbsPath(cwd),
      // pipe stdout/stderr into this process
      silent: true
    });

    // handle stdout of child
    p.stdout.on("data", (data) => {
      process.stdout.write(`[Indexing] (${cwd}) ${data}`);
    });

    // handle stderr of child
    p.stderr.on("data", (data) => {
      process.stderr.write(`[Indexing] (${cwd}) ${data}`);
    });

    return p;
  }

  // in Browser:
  return new Worker(script);
}

// Object that holds workers for server subdirectories,
// e.g. '/lively4-core'
var workers = {};
var indexStatus = {};

var promiseCallbacks = {};
var workerReadyPromise;
// rootFolder is an absolute directory to where the server serves,
// e.g. where the lively4-core folder is found
var rootFolder = null;
var idxFileName = "index.l4idx";

var curMsgId = 0;

// *** Exported methods ***

export function setRootFolder(filepath) {
  // becomes e.g. "C:/felix/bla" on Windows
  if (isNode) {
    rootFolder = slash(path.resolve(filepath));
  } else {
    rootFolder = filepath;
  }
}

export function startWorker(subdir) {
  return new Promise((resolve, reject) => {
    if (!rootFolder) {
      throw new Error("startWorker: no root folder set");
    }

    if (workers[subdir]) {
      console.log("[Indexing] Worker already exists");
      resolve();
      return;
    }

    console.log("[Indexing] Starting new worker for " + subdir);
    try {
      let script = isNode ? __dirname + "/../server/lunr-node-search-worker.js" : "./src/external/lively4-search/client/lunr-es6-search-worker-wrapper.js";
      workers[subdir] = createProcess(script, subdir);
    } catch (err) {
      console.log("[Indexing] Error starting new worker for " + subdir + ": " + err);
      reject(err);
      return;
    }

    let messageHandler = function(m) {
      // web workers hide the sent message behind the data key
      if (!isNode) {
        m = m.data;
      }
      switch (m.type) {
        case "worker-ready":
          resolve();
          break;
        case "search-response":
          handleSearchResponse(m.msgId, m.message);
          break;
        case "init-response":
          handleInitResponse(m.msgId, m.message, subdir);
          break;
        case "index-status-response":
          handleIndexStatusResponse(m.msgId, m.message, subdir);
          break;
        case "error":
          console.log("[Indexing] Error (" + subdir + "): " + m.message);
          break;
        default:
          console.log("[Indexing] Unknown message:", m);
      }
    }

    if (isNode) {
      workers[subdir].on("message", messageHandler);
    } else {
      workers[subdir].onmessage = messageHandler;
    }
  });
}

function stopWorker(subdir) {
  console.log("stop", subdir);
  send(workers[subdir], {
    type: "stop"
  });

  delete workers[subdir];
  delete indexStatus[subdir];
}

export function createIndex(subdir, options) {
  return startWorker(subdir).then(() => {
    return new Promise((resolve, reject) => {
      if (!rootFolder) {
        console.log("[Indexing] Cannot create index, no root folder set");
        reject("Error: no root folder set");
        return;
      }

      if (indexStatus[subdir] === "ready") {
        console.log("[Indexing] Index already exists");
        resolve();
        return;
      }

      if (indexStatus[subdir] === "indexing") {
        reject();
        return;
      }

      var msgId = getNextMsgId();
      promiseCallbacks[msgId] = {
        resolve: resolve,
        reject: reject
      };

      send(workers[subdir], {
        type: "init",
        msgId: msgId,
        options: options
      });

      indexStatus[subdir] = "indexing";
    });
  });
}

export function removeIndex(subdir, options) {
  return startWorker(subdir).then(() => {
    send(workers[subdir], {
      type: "removeIndex"
    });

    stopWorker(subdir);

    delete indexStatus[subdir];
  });
}

export function setup(options) {
  return new Promise((resolve, reject) => {

    let fetchStatus =  () => {
      createIndex(options.path, options).then( () => {
        resolve();
        clearInterval(interval);
      }, () => {
        console.log("[Indexing] Waiting for index: " + options.name)
      });
    };

    fetchStatus();
    let interval = setInterval(fetchStatus, 5000);
  });
}

export function search(subdir, query) {
  if (!workers[subdir]) {
    console.log("[Indexing] Cannot search, no index created for " + subdir);
    return Promise.reject();
  }

  var msgId = getNextMsgId();
  promiseCallbacks[msgId] = {};

  var p = new Promise((resolve, reject) => {
    promiseCallbacks[msgId].resolve = resolve;
    promiseCallbacks[msgId].reject = reject;
  });

  send(workers[subdir], {
    type: "search",
    msgId: msgId,
    query: query
  });

  return p;
}

export function getStatus(subdir, options) {
  return startWorker(subdir).then(() => {
    if (indexStatus[subdir]) {
      return Promise.resolve(indexStatus[subdir]);
    }
    var msgId = getNextMsgId();
    promiseCallbacks[msgId] = {};

    var p = new Promise((resolve, reject) => {
      promiseCallbacks[msgId].resolve = resolve;
      promiseCallbacks[msgId].reject = reject;
    });

    send(workers[subdir], {
      type: "checkIndexFile",
      msgId: msgId,
      options: options
    });

    return p;
  });
}

export function find(pattern) {
  return search(this.path, pattern).then( (result) => {
    return result.map( (res) => {
      res.path = join(this.path, res.ref);
      res.type = "dropbox";
      return res;
    });
  });
}

function handleSearchResponse(msgId, result) {
  if (!promiseCallbacks[msgId]) {
    console.log(`[Indexing] No promise registered for ${msgId}`);
    return;
  }

  var resolve = promiseCallbacks[msgId].resolve;
  delete promiseCallbacks[msgId];

  resolve(result);
}

function handleInitResponse(msgId, result, subdir) {
  // Worker does not send a msgId, when it had to create the
  // requested index, because the msgId was already used to
  // signal that the index did not exist.
  if (!msgId) {
    // index has been created now,
    // so next call to createIndex will resolve immediately
    indexStatus[subdir] = "ready";
    return;
  }

  if (!promiseCallbacks[msgId]) {
    // this should never happen!
    console.log(`[Indexing] No promise registered for ${msgId}`);
    return;
  }

  var resolve = promiseCallbacks[msgId].resolve;
  var reject = promiseCallbacks[msgId].reject;
  delete promiseCallbacks[msgId];

  if (result === "ready") {
    // index was requested and just had to be loaded from disk
    indexStatus[subdir] = "ready";
    resolve();
  } else {
    // index was requested, does not exist and is being built now
    indexStatus[subdir] = "indexing";
    reject();
  }
}

function handleIndexStatusResponse(msgId, result, subdir) {
  if (!promiseCallbacks[msgId]) {
    // this should never happen!
    console.log(`[Indexing] No promise registered for ${msgId}`);
    return;
  }

  var resolve = promiseCallbacks[msgId].resolve;
  delete promiseCallbacks[msgId];

  resolve(result);

  if (result === "unavailable") {
    stopWorker(subdir);
  }
}

export function addFile(serverRelPath) {
  // e.g. serverRelPath == "/lively4-core/src/client/foo.js"
  serverRelPath = slash(serverRelPath);
  // find corresponding index
  var subdir = getIndexSubdir(serverRelPath);

  if (!subdir || !workers[subdir]) {
    console.log("[Indexing] Cannot add file, no index created for " + serverRelPath);
    return;
  }

  var absPath = toAbsPath(serverRelPath);
  send(workers[subdir], {
    type: "addFile",
    idxRelPath: toIdxRelPath(subdir, absPath)
  });
}

export function removeFile(serverRelPath) {
  // e.g. serverRelPath == "/lively4-core/src/client/foo.js"
  serverRelPath = slash(serverRelPath);
  // find corresponding index
  var subdir = getIndexSubdir(serverRelPath);
  if (!subdir) {
    // no index found for the serverRelPath, so dont remove it
    return;
  }
  if (!workers[subdir]) {
    console.log("[Indexing] Cannot remove file, no index created for " + subdir);
    return;
  }

  var absPath = toAbsPath(serverRelPath);
  send(workers[subdir], {
    type: "removeFile",
    idxRelPath: toIdxRelPath(subdir, absPath)
  });
}

// *** Helper methods ***

function getIndexSubdir(filepath) {
  return Object.keys(workers).find(function(subidx) {
    return filepath.indexOf(subidx + "/") == 0;
  });
}

function toAbsPath(serverRelPath) {
  return slash(path.join(rootFolder, serverRelPath));
}

function toIdxRelPath(subdir, absPath) {
  if (!rootFolder) {
    return;
  }

  // remove e.g. <rootFolder>/lively4-core/ (including the last slash, therefore + 1)
  return slash(absPath.slice(rootFolder.length + subdir.length + 1));
}

function getNextMsgId() {
  curMsgId++;
  return curMsgId;
}

function join(path1, path2) {
  if (path1[path1.length-1] != "/") {
    path1 += "/";
  }
  if (path2[0] == "/") {
    path2 = path2.slice(1, path2.length);
  }
  return path1 + path2;
}
<|endoftext|>


<commit_before>
$(document).ready(function() {
	update_credits();
	update_shares();
});

/*
	Create a block with given width and background color,
	and append it to the given bar element.
*/
function create_block(username, width, isShare) {
	var block = $(document.createElement('td'));
	block.css({
		'width': width + '%',
		'background-color': '#' + color_generator(username)
	});
	var percent = $(document.createElement('span'));
	percent.text(width + '%');

	if (isShare) {
		block.attr("id", "usage" + username);
		if (username == "Free" && width > 0) {
			var get = $(document.createElement('a'));
			get.attr('id','getresourcesbutton');
			get.attr('href','#');
			get.text('get');
			get.click(get_resources_dialog);
			block.append(get);

			var share = $(document.createElement('a'));
			share.attr('id','shareresourcesbutton');
			share.attr('href','#');
			share.text('share');
			share.click(share_resources_dialog);
			block.append(share);

		} else if (username != "Me" && username != "Others" ) {
			var close = $(document.createElement('a'));
			close.attr('href','#');
			close.text('x');
			close.click(function() {
				$.post("../control/ajax_editshare",
						{ username: username, percent: 0 },
						function (data) {
							var json = eval('(' + data + ')');
							if (json.success) {
								update_shares();
							} else {
								alert(json.error);
							}
						});
			});
			block.append(close);
			percent.attr("title", "Click to change percent");
			percent.tooltip({cssClass:"tooltip"});
			percent.css("cursor", "pointer");
			percent.click(function() {
				change_percent(username, width);
			});
		}
	}

	if (username == "Others") {
		percent.attr("title", "Click to reveal");
		percent.tooltip({cssClass:"tooltip"});
		percent.css("cursor", "pointer");
		percent.click(function () { show_table(isShare) });
		// block.attr("id", "creditOthers");
	}
	block.append(percent);
	return block;
}

/*
	Create a name label with given width and append it to
	the given name table.
*/
function create_label(username, width, isShare) {
	var label = $(document.createElement('td'));
	if (isShare) {
		label.attr("id", "labelusage" + username);
	}
	label.text(username);
	label.css({
		'width': width + '%'
	});
	return label;
}

function add_other(type, username, percent) {
	var table;
	if (type == "credits") {
		table = $("#creditotherstable");
	} else if (type == "shares") {
		table = $("#usageotherstable");
	}
	var tr = $(document.createElement("tr"));
	tr.html("" + username + "	" + percent + "	");
	if (type == "shares") {
		var control = $(document.createElement("td"));
		var edit = $(document.createElement("button"));
		edit.text("Edit");
		edit.click(function() {
			change_percent(username, percent);
		});
		var close = $(document.createElement("button"));
		close.text("Delete");
		close.click(function() {
			$.post("../control/ajax_editshare",
					{ username: username, percent: 0 },
					function(data) {
						var json = eval('(' + data + ')');
						if (json.success) {
							update_shares();
						} else {
							alert(json.error);
						}
					});
			tr.remove();
		});
		control.append(edit);
		control.append(close);
		tr.append(control);
	}
	table.append(tr);
}

/*
	Display the change percent dialog box
*/
function change_percent(username, percent) {
	var dialog = $(document.createElement("div"));
	dialog.attr("id", "changepercentdialog");
	dialog.html('
Change Percent
');
	var input = $(document.createElement("input"));
	input.attr("type", "text");
	input.val(percent);
	input.click(function () { $(this).val("") });
	var symbol = $(document.createElement("span"));
	symbol.html(" %
");
	var cancel = $(document.createElement("button"));
	cancel.text("Cancel");
	var save = $(document.createElement("button"));
	save.text("Save");
	cancel.click(function () {
		close_dialog();
		$(this).parent().remove();
	});
	save.click(function() {
		 save_percent(username, parseInt(input.val()));
	});
	dialog.append(input);
	dialog.append(symbol);
	dialog.append(cancel);
	dialog.append(save);
	$("#dialogframe").append(dialog);
	$("#dialogframe").fadeIn("fast");
	$("#overlay").fadeIn("fast");
	$("#changepercentdialog").fadeIn("fast");
}

/*
	Save the percent of the the block when click "save" on the
	change_percent dialog box
*/
function save_percent(username, percent) {
	$.post("../control/ajax_editshare",
			{ username: username, percent: percent },
			function (data) {
				var json = eval(data);
				if (json.success) {
					$("#changepercentdialog").remove();
					$("#dialogframe").hide();
					$("#overlay").hide();
					update_shares();
				} else {
					create_warning(json.error, $("#changepercentdialog h3"));
				}
	   		},
			"json");
}

/*
	Toggle display the tables for small percent users
*/
function show_table(isShare) {
	if (isShare) {
		$("#usageotherstable").toggle();
	} else {
		$("#creditotherstable").toggle();
	}
}

function get_resources_dialog() {
	$("#dialogframe").fadeIn("fast");
	$("#overlay").fadeIn("fast");
	$("#getresourcesdialog").fadeIn("fast");
	$(".cancel").click(close_dialog);
	$("#getresourcesaction").click(get_resources);
}

function share_resources_dialog() {
	$("#dialogframe").fadeIn("fast");
	$("#overlay").fadeIn("fast");
	$("#shareresourcesdialog").fadeIn("fast");
	$(".cancel").click(close_dialog);
	$("#shareresources").click(share_resources);
}

function close_dialog() {
    if ($(this).parent().children(".warning")) {
		$(this).parent().children(".warning").remove();
    }
	$(this).parent().hide();
	$("#dialogframe").hide();
	$("#overlay").hide();
}

function post_ajax(url, args, func) {
	$.post(url, args, function(data) {
		// check data
		// if data ok then:
		func(data)
		// else:
		// display content as raw html in a new popup
	});
}

function share_resources() {
	var username = $("#shareresourcesdialog #username").val();
	var percent = parseInt($("#shareresourcesdialog #percent").val());
	if ($("#shareresourcesdialog .warning")) {
	    $("#shareresourcesdialog .warning").remove();
	}
	if (percent > 0) {
		post_ajax("../control/ajax_createshare",
				{ username: username, percent: percent },
				function(data) {
					var json = eval('(' + data + ')');
					if (json.success) {
						$("#shareresourcesdialog").hide();
						$("#dialogframe").hide();
						$("#overlay").hide();
						update_shares();
					} else {
						create_warning(json.error, $("#shareresourcesdialog h3"));
					}
				});
	} else {
		create_warning("Percent must greater than 0", $("#shareresourcesdialog h3"));
	}
}

function get_resources() {
	var numvessels = parseInt($("#numvessels").val());
	var env = parseInt($("#environment").val());
	if ($("#getresourcesdialog .warning")) {
	    $("#getresourcesdialog .warning").remove();
	}
	$.post("../control/ajax_getvessels",
			{ numvessels: numvessels, env: env },
			function (data) {
				var json = eval('(' + data + ')');
				alert(json.mypercent);
				alert(json.success);
				if (json.success) {
					$("#getresourcesdialog").hide();
					$("#dialogframe").hide();
					$("#overlay").hide();
					update_shares();
				} else {
					create_warning(json.error, $("#getresourcesdialog h3"));
				}
			});
}

/*
	Create and insert a warning sign after the given position
*/

function create_warning(error, position) {
	var warning = $(document.createElement("p"));
	warning.html(error);
	warning.addClass("warning");
	warning.insertAfter(position);
}

/*
	Generate a color in hex notation for a username, which assigns different
	colors to different usernames.
*/
function color_generator(username) {
	var seeds = ['cc','ff'];
	var color = seeds[username.charCodeAt(0) % 2] +
				seeds[username.charCodeAt(1) % 2] +
				seeds[username.charCodeAt(username.length - 1) % 2];
	if (color == "ffffff") {
		color = "ffffcc";
	} else if (color == "cccccc") {
		color = "ccccff";
	}
	if (username == "Free") {
		color = "ffffff";
	} else if (username == "Me") {
		color = "cccccc";
	}
	return color;
}

function update_credits() {
	$.post("../control/ajax_getcredits",
			function (data) {
				$("#credits").empty();
				$("#creditnames").empty();
				$("#creditotherstable tr:gt(0)").empty();
				var json = eval('(' + data + ')');
				var total_others = 0;
				for (var i = 0; i < json[0].length; i++) {
					add_cell("credits", json[0][i].username, json[0][i].percent);
				}
				for (var i = 0; i < json[1].length; i++) {
					add_other("credits", json[1][i].username, json[1][i].percent);
					total_others += json[1][i].percent;
				}
				if (total_others > 0) {
					add_cell("credits", "Others", total_others);
				}
				add_cell("credits", json[2][0].username, json[2][0].percent);
				$("#vesselscredits").text(json[3] + " vessels credits");
				$("#creditotherstable tr:odd").addClass("odd");
				$("#creditotherstable tr:even").addClass("even");
			},
			"json");
}

function update_shares() {
	$.post("../control/ajax_getshares",
			function (data) {
				$("#usage").empty();
				$("#usagenames").empty();
				$("#usageotherstable tr:gt(0)").empty();
				var json = eval('(' + data + ')');
				var total_percent = 0;
				var total_others = 0;
				for (var i = 0; i < json[0].length; i++) {
					add_cell("shares", json[0][i].username, json[0][i].percent);
					total_percent += json[0][i].percent;
				}
				for (var i = 0; i < json[1].length; i++) {
					add_other("shares", json[1][i].username, json[1][i].percent);
					total_others += json[1][i].percent;
				}
				total_percent += total_others + json[2][0].percent;
				if (total_others > 0) {
					add_cell("shares", "Others", total_others);
				}
				add_cell("shares", json[2][0].username, json[2][0].percent);
				add_cell("shares", "Free", 100 - total_percent);
				$("#vesselsavailable").text(json[3] + " vessels available");
				update_numvessels(json[3]);
				$("#usageotherstable tr:odd").addClass("odd");
				$("#usageotherstable tr:even").addClass("even");
			},
			"json");
}

function add_cell(type, username, percent) {
	if (type == "credits") {
		var block = create_block(username, percent, false);
		var label = create_label(username, percent, false);
		$("#credits").append(block);
		$("#creditnames").append(label);
	} else if (type == "shares") {
		var block = create_block(username, percent, true);
		var label = create_label(username, percent, true);
		$("#usage").append(block);
		$("#usagenames").append(label);
	}
}

function update_numvessels(number) {
	$("#numvessels").empty();
	for (var i = 1; i <= number; i++) {
		var option = $(document.createElement("option"));
		option.val(i);
		option.text(i);
		$("#numvessels").append(option);
	}
}
<commit_msg>commentted out debugging code<commit_after>
$(document).ready(function() {
	update_credits();
	update_shares();
});

/*
	Create a block with given width and background color,
	and append it to the given bar element.
*/
function create_block(username, width, isShare) {
	var block = $(document.createElement('td'));
	block.css({
		'width': width + '%',
		'background-color': '#' + color_generator(username)
	});
	var percent = $(document.createElement('span'));
	percent.text(width + '%');

	if (isShare) {
		block.attr("id", "usage" + username);
		if (username == "Free" && width > 0) {
			var get = $(document.createElement('a'));
			get.attr('id','getresourcesbutton');
			get.attr('href','#');
			get.text('get');
			get.click(get_resources_dialog);
			block.append(get);

			var share = $(document.createElement('a'));
			share.attr('id','shareresourcesbutton');
			share.attr('href','#');
			share.text('share');
			share.click(share_resources_dialog);
			block.append(share);

		} else if (username != "Me" && username != "Others" ) {
			var close = $(document.createElement('a'));
			close.attr('href','#');
			close.text('x');
			close.click(function() {
				$.post("../control/ajax_editshare",
						{ username: username, percent: 0 },
						function (data) {
							var json = eval('(' + data + ')');
							if (json.success) {
								update_shares();
							} else {
								alert(json.error);
							}
						});
			});
			block.append(close);
			percent.attr("title", "Click to change percent");
			percent.tooltip({cssClass:"tooltip"});
			percent.css("cursor", "pointer");
			percent.click(function() {
				change_percent(username, width);
			});
		}
	}

	if (username == "Others") {
		percent.attr("title", "Click to reveal");
		percent.tooltip({cssClass:"tooltip"});
		percent.css("cursor", "pointer");
		percent.click(function () { show_table(isShare) });
		// block.attr("id", "creditOthers");
	}
	block.append(percent);
	return block;
}

/*
	Create a name label with given width and append it to
	the given name table.
*/
function create_label(username, width, isShare) {
	var label = $(document.createElement('td'));
	if (isShare) {
		label.attr("id", "labelusage" + username);
	}
	label.text(username);
	label.css({
		'width': width + '%'
	});
	return label;
}

function add_other(type, username, percent) {
	var table;
	if (type == "credits") {
		table = $("#creditotherstable");
	} else if (type == "shares") {
		table = $("#usageotherstable");
	}
	var tr = $(document.createElement("tr"));
	tr.html("" + username + "	" + percent + "	");
	if (type == "shares") {
		var control = $(document.createElement("td"));
		var edit = $(document.createElement("button"));
		edit.text("Edit");
		edit.click(function() {
			change_percent(username, percent);
		});
		var close = $(document.createElement("button"));
		close.text("Delete");
		close.click(function() {
			$.post("../control/ajax_editshare",
					{ username: username, percent: 0 },
					function(data) {
						var json = eval('(' + data + ')');
						if (json.success) {
							update_shares();
						} else {
							alert(json.error);
						}
					});
			tr.remove();
		});
		control.append(edit);
		control.append(close);
		tr.append(control);
	}
	table.append(tr);
}

/*
	Display the change percent dialog box
*/
function change_percent(username, percent) {
	var dialog = $(document.createElement("div"));
	dialog.attr("id", "changepercentdialog");
	dialog.html('
Change Percent
');
	var input = $(document.createElement("input"));
	input.attr("type", "text");
	input.val(percent);
	input.click(function () { $(this).val("") });
	var symbol = $(document.createElement("span"));
	symbol.html(" %
");
	var cancel = $(document.createElement("button"));
	cancel.text("Cancel");
	var save = $(document.createElement("button"));
	save.text("Save");
	cancel.click(function () {
		close_dialog();
		$(this).parent().remove();
	});
	save.click(function() {
		 save_percent(username, parseInt(input.val()));
	});
	dialog.append(input);
	dialog.append(symbol);
	dialog.append(cancel);
	dialog.append(save);
	$("#dialogframe").append(dialog);
	$("#dialogframe").fadeIn("fast");
	$("#overlay").fadeIn("fast");
	$("#changepercentdialog").fadeIn("fast");
}

/*
	Save the percent of the the block when click "save" on the
	change_percent dialog box
*/
function save_percent(username, percent) {
	$.post("../control/ajax_editshare",
			{ username: username, percent: percent },
			function (data) {
				var json = eval(data);
				if (json.success) {
					$("#changepercentdialog").remove();
					$("#dialogframe").hide();
					$("#overlay").hide();
					update_shares();
				} else {
					create_warning(json.error, $("#changepercentdialog h3"));
				}
	   		},
			"json");
}

/*
	Toggle display the tables for small percent users
*/
function show_table(isShare) {
	if (isShare) {
		$("#usageotherstable").toggle();
	} else {
		$("#creditotherstable").toggle();
	}
}

function get_resources_dialog() {
	$("#dialogframe").fadeIn("fast");
	$("#overlay").fadeIn("fast");
	$("#getresourcesdialog").fadeIn("fast");
	$(".cancel").click(close_dialog);
	$("#getresourcesaction").click(get_resources);
}

function share_resources_dialog() {
	$("#dialogframe").fadeIn("fast");
	$("#overlay").fadeIn("fast");
	$("#shareresourcesdialog").fadeIn("fast");
	$(".cancel").click(close_dialog);
	$("#shareresources").click(share_resources);
}

function close_dialog() {
    if ($(this).parent().children(".warning")) {
		$(this).parent().children(".warning").remove();
    }
	$(this).parent().hide();
	$("#dialogframe").hide();
	$("#overlay").hide();
}

function post_ajax(url, args, func) {
	$.post(url, args, function(data) {
		// check data
		// if data ok then:
		func(data)
		// else:
		// display content as raw html in a new popup
	});
}

function share_resources() {
	var username = $("#shareresourcesdialog #username").val();
	var percent = parseInt($("#shareresourcesdialog #percent").val());
	if ($("#shareresourcesdialog .warning")) {
	    $("#shareresourcesdialog .warning").remove();
	}
	if (percent > 0) {
		post_ajax("../control/ajax_createshare",
				{ username: username, percent: percent },
				function(data) {
					var json = eval('(' + data + ')');
					if (json.success) {
						$("#shareresourcesdialog").hide();
						$("#dialogframe").hide();
						$("#overlay").hide();
						update_shares();
					} else {
						create_warning(json.error, $("#shareresourcesdialog h3"));
					}
				});
	} else {
		create_warning("Percent must greater than 0", $("#shareresourcesdialog h3"));
	}
}

function get_resources() {
	var numvessels = parseInt($("#numvessels").val());
	var env = parseInt($("#environment").val());
	if ($("#getresourcesdialog .warning")) {
	    $("#getresourcesdialog .warning").remove();
	}
	$.post("../control/ajax_getvessels",
			{ numvessels: numvessels, env: env },
			function (data) {
				var json = eval('(' + data + ')');
				// alert(json.mypercent);
				// alert(json.success);
				if (json.success) {
					$("#getresourcesdialog").hide();
					$("#dialogframe").hide();
					$("#overlay").hide();
					update_shares();
				} else {
					create_warning(json.error, $("#getresourcesdialog h3"));
				}
			});
}

/*
	Create and insert a warning sign after the given position
*/

function create_warning(error, position) {
	var warning = $(document.createElement("p"));
	warning.html(error);
	warning.addClass("warning");
	warning.insertAfter(position);
}

/*
	Generate a color in hex notation for a username, which assigns different
	colors to different usernames.
*/
function color_generator(username) {
	var seeds = ['cc','ff'];
	var color = seeds[username.charCodeAt(0) % 2] +
				seeds[username.charCodeAt(1) % 2] +
				seeds[username.charCodeAt(username.length - 1) % 2];
	if (color == "ffffff") {
		color = "ffffcc";
	} else if (color == "cccccc") {
		color = "ccccff";
	}
	if (username == "Free") {
		color = "ffffff";
	} else if (username == "Me") {
		color = "cccccc";
	}
	return color;
}

function update_credits() {
	$.post("../control/ajax_getcredits",
			function (data) {
				$("#credits").empty();
				$("#creditnames").empty();
				$("#creditotherstable tr:gt(0)").empty();
				var json = eval('(' + data + ')');
				var total_others = 0;
				for (var i = 0; i < json[0].length; i++) {
					add_cell("credits", json[0][i].username, json[0][i].percent);
				}
				for (var i = 0; i < json[1].length; i++) {
					add_other("credits", json[1][i].username, json[1][i].percent);
					total_others += json[1][i].percent;
				}
				if (total_others > 0) {
					add_cell("credits", "Others", total_others);
				}
				add_cell("credits", json[2][0].username, json[2][0].percent);
				$("#vesselscredits").text(json[3] + " vessels credits");
				$("#creditotherstable tr:odd").addClass("odd");
				$("#creditotherstable tr:even").addClass("even");
			},
			"json");
}

function update_shares() {
	$.post("../control/ajax_getshares",
			function (data) {
				$("#usage").empty();
				$("#usagenames").empty();
				$("#usageotherstable tr:gt(0)").empty();
				var json = eval('(' + data + ')');
				var total_percent = 0;
				var total_others = 0;
				for (var i = 0; i < json[0].length; i++) {
					add_cell("shares", json[0][i].username, json[0][i].percent);
					total_percent += json[0][i].percent;
				}
				for (var i = 0; i < json[1].length; i++) {
					add_other("shares", json[1][i].username, json[1][i].percent);
					total_others += json[1][i].percent;
				}
				total_percent += total_others + json[2][0].percent;
				if (total_others > 0) {
					add_cell("shares", "Others", total_others);
				}
				add_cell("shares", json[2][0].username, json[2][0].percent);
				add_cell("shares", "Free", 100 - total_percent);
				$("#vesselsavailable").text(json[3] + " vessels available");
				update_numvessels(json[3]);
				$("#usageotherstable tr:odd").addClass("odd");
				$("#usageotherstable tr:even").addClass("even");
			},
			"json");
}

function add_cell(type, username, percent) {
	if (type == "credits") {
		var block = create_block(username, percent, false);
		var label = create_label(username, percent, false);
		$("#credits").append(block);
		$("#creditnames").append(label);
	} else if (type == "shares") {
		var block = create_block(username, percent, true);
		var label = create_label(username, percent, true);
		$("#usage").append(block);
		$("#usagenames").append(label);
	}
}

function update_numvessels(number) {
	$("#numvessels").empty();
	for (var i = 1; i <= number; i++) {
		var option = $(document.createElement("option"));
		option.val(i);
		option.text(i);
		$("#numvessels").append(option);
	}
}
<|endoftext|>