<commit_before>var Promise = require('es6-promise').Promise;
var browserify = require('browserify');
var path = require('path');
var UglifyJS = require("uglify-js");
var fs = require('../utils/fs');
var File = require('../utils/file');
var log = require('../utils/log');

function Browserify(location, destination, options){
    this.location = location;
    this.destination = destination;
    this.options = options;
    this.checkForDeboweify();
}

Browserify.prototype.checkForDeboweify = function(){
    var options = this.options;
    if (options.browserify && options.browserify.transform.indexOf('debowerify')==-1){ return false; }
    log.onError([
        'The browserify transform `debowerify` does not currenlty work with `vendorBundle`.',
        'Please remove `debowerify` from browserify.transform within your package.json.',
        ' * https://github.com/eugeneware/debowerify/issues/62'
    ].join('\n'));
};

Browserify.prototype.buildVendor = function(options){
    var self = this;
    if (!options.vendorBundle) return Promise.resolve();
    delete this.options.entries;
    return new Promise(function(resolve, reject) {
        var v_ws = fs.createWriteStream(path.resolve(self.destination, 'vendor.js'));
        browserify()
            .require(options.vendorBundle)
            .bundle().pipe(v_ws)
            .on('end', resolve);
        v_ws.on('error', reject);
    });
};

Browserify.prototype.mapExternalFiles = function() {
    if (!this.options.vendorBundle) return;
    var options = this.options;
    return this.options.vendorBundle.map(function (v) {
        var dependency = (typeof v === 'string') ? v : v.expose;
        if (options.browser[dependency]){
            log.warn(['You have `browser.' + dependency + '` within your package.json.',
                'This may cause problems. Ensure within the `vendorBundle` you have:',
            ' * bower_components: have the full path  e.g. {file:\'./bower_components/path/' + dependency + '.js\',expose:\'' + dependency + '\'}',
            ' * node_module: have the node name within the `vendorBundle` e.g. \'' + dependency + '\'',
            ''].join('\n'))
        }
        return dependency;
    });
};

Browserify.prototype.file = function(fileObj) {
    var self = this;
    var options = this.options || {};
    var vendor = self.mapExternalFiles();
    return new Promise(function(resolve, reject) {
        options.entries = fileObj.path;
        var b_ws = fs.createWriteStream(path.resolve(self.destination, fileObj.name));
        var b = browserify(options);
        if (vendor){
            b.external(vendor);
        }
        b.require(fileObj.path, {expose: fileObj.name.split('.')[0]});
        b.bundle().pipe(b_ws);
        b.on('end', resolve);
        b_ws.on('error', reject);
    });
};

Browserify.prototype.write = function(){
    var self = this;
    var options = this.options || {};
    return fs.glob(this.location + '/*.js').then(function(fileObjs){
        if (fileObjs.length===0){
            log.info('no .js files found within `' + self.location + '`');
        }
        var promises = [];
        fileObjs.forEach(function (fileObj, i) {
            promises.push(self.file(fileObj));
        });
        if (options.vendorBundle){
            promises.push(self.buildVendor(options));
        }
        return Promise.all(promises);
    }).then(function(fileObjs){
        var promises = [];
        fileObjs.forEach(function (fileObj, i) {
            promises.push(self.minify(fileObj));
        });
        return Promise.all(promises);
    }).then(function(fileObjs){
        return fs.write(fileObjs);
    });
};

Browserify.prototype.minify = function(fileObj){
    var newFile = new File({ path: fileObj.path });
    newFile.name = fileObj.name.replace('.js','.min.js');
    newFile.dir = this.destination;
    newFile.contents = UglifyJS.minify(fileObj.path).code;
    return Promise.resolve(newFile);
};

module.exports = Browserify;<commit_msg>fix bug if object doesnt exist<commit_after>var Promise = require('es6-promise').Promise;
var browserify = require('browserify');
var path = require('path');
var UglifyJS = require("uglify-js");
var fs = require('../utils/fs');
var File = require('../utils/file');
var log = require('../utils/log');

function Browserify(location, destination, options){
    this.location = location;
    this.destination = destination;
    this.options = options;
    this.checkForDeboweify();
}

Browserify.prototype.checkForDeboweify = function(){
    var options = this.options;
    if (options.browserify && options.browserify.transform && options.browserify.transform.indexOf('debowerify')>-1){
        log.onError([
            'The browserify transform `debowerify` does not currenlty work with `vendorBundle`.',
            'Please remove `debowerify` from browserify.transform within your package.json.',
            ' * https://github.com/eugeneware/debowerify/issues/62'
        ].join('\n'));
    }
};

Browserify.prototype.buildVendor = function(options){
    var self = this;
    if (!options.vendorBundle) return Promise.resolve();
    delete this.options.entries;
    return new Promise(function(resolve, reject) {
        var v_ws = fs.createWriteStream(path.resolve(self.destination, 'vendor.js'));
        browserify()
            .require(options.vendorBundle)
            .bundle().pipe(v_ws)
            .on('end', resolve);
        v_ws.on('error', reject);
    });
};

Browserify.prototype.mapExternalFiles = function() {
    if (!this.options.vendorBundle) return;
    var options = this.options;
    return this.options.vendorBundle.map(function (v) {
        var dependency = (typeof v === 'string') ? v : v.expose;
        if (options.browser && options.browser[dependency]){
            log.warn(['You have `browser.' + dependency + '` within your package.json.',
                'This may cause problems. Ensure within the `vendorBundle` you have:',
            ' * bower_components: have the full path  e.g. {file:\'./bower_components/path/' + dependency + '.js\',expose:\'' + dependency + '\'}',
            ' * node_module: have the node name within the `vendorBundle` e.g. \'' + dependency + '\'',
            ''].join('\n'))
        }
        return dependency;
    });
};

Browserify.prototype.file = function(fileObj) {
    var self = this;
    var options = this.options || {};
    var vendor = self.mapExternalFiles();
    return new Promise(function(resolve, reject) {
        options.entries = fileObj.path;
        var b_ws = fs.createWriteStream(path.resolve(self.destination, fileObj.name));
        var b = browserify(options);
        if (vendor){
            b.external(vendor);
        }
        b.require(fileObj.path, {expose: fileObj.name.split('.')[0]});
        b.bundle().pipe(b_ws);
        b.on('end', resolve);
        b_ws.on('error', reject);
    });
};

Browserify.prototype.write = function(){
    var self = this;
    var options = this.options || {};
    return fs.glob(this.location + '/*.js').then(function(fileObjs){
        if (fileObjs.length===0){
            log.info('no .js files found within `' + self.location + '`');
        }
        var promises = [];
        fileObjs.forEach(function (fileObj, i) {
            promises.push(self.file(fileObj));
        });
        if (options.vendorBundle){
            promises.push(self.buildVendor(options));
        }
        return Promise.all(promises);
    }).then(function(fileObjs){
        var promises = [];
        fileObjs.forEach(function (fileObj, i) {
            promises.push(self.minify(fileObj));
        });
        return Promise.all(promises);
    }).then(function(fileObjs){
        return fs.write(fileObjs);
    });
};

Browserify.prototype.minify = function(fileObj){
    var newFile = new File({ path: fileObj.path });
    newFile.name = fileObj.name.replace('.js','.min.js');
    newFile.dir = this.destination;
    newFile.contents = UglifyJS.minify(fileObj.path).code;
    return Promise.resolve(newFile);
};

module.exports = Browserify;<|endoftext|>


<commit_before>require('./database.test');
<commit_msg>Commenting out tests<commit_after>/**
 * Commenting out the database tests for when deploying onto travis until a method of
 * connecting to the database for travis is created that is safe while also protecting
 * the database contents.
 */
// require('./database.test');
<|endoftext|>


<commit_before>/**
 * CareWheels - Individual Status Controller
 *
 */
angular.module('careWheels')
  .controller('individualStatusController', function ($scope, $ionicPopup, GroupInfo, PaymentService, $fileLogger, fileloggerService) {

    fileloggerService.initLogComponent();

    /**
     * grabs the analysis of the member selected on the previous view
     */
    var analysis = GroupInfo.getSelectedMemberIndex();
    //console.log(analysis); ////////////testing

    var timeNow = new Date().getHours();
    var phoneNumberError = false;

    function convertMedsOrMealsAlertLevelToColor(sensorArray) {

      var coloredArray = [];

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

        if(sensorArray[i] == 0) {
          coloredArray[i] = "blue";
        }

        if(sensorArray[i] == 1) {
          coloredArray[i] = "yellow";
        }

        if(sensorArray[i] == 2) {
          coloredArray[i] = "red";
        }
      }

      return coloredArray;
    }

    function convertPresenceAlertLevelToColor(sensorArray) {

      var coloredArray = [];

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

        if(sensorArray[i] == false) {
          coloredArray[i] = "grey";
        }

        if(sensorArray[i] == true) {
          coloredArray[i] = "blue";
        }
      }

      return coloredArray;
    }

    function convertHitsToString(hitsArray) {

      var stringArray = [];
      var asterisks = "";

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

        for(var j = 0; j < hitsArray[i]; j++) {
          if(j > 5) {
            break;
          }

          asterisks += "* ";
        }

        stringArray[i] = asterisks;
        asterisks = "";
      }

      return stringArray;
    }

    $scope.currentHour = new Date().getHours();
    $scope.getNumber = function(num) {
      return new Array(num);
    }

    $scope.data = {

      presence: {
        value: convertPresenceAlertLevelToColor(analysis.analysisData.presenceByHour)
      },

      meals: {
        value: convertMedsOrMealsAlertLevelToColor(analysis.analysisData.fridgeRollingAlertLevel),
        hits: convertHitsToString(analysis.analysisData.fridgeHitsByHour)
      },

      meds: {
        value: convertMedsOrMealsAlertLevelToColor(analysis.analysisData.medsRollingAlertLevel),
        hits: convertHitsToString(analysis.analysisData.medsHitsByHour)
      }

    };

  // console.log("Calling Call Payment:");
  // PaymentService.call(analysis.name, 1.0, 'Red');
  // console.log("Calling sensorDataView Payment:");
  // PaymentService.sensorDataView(1.0, 'Blue');

  /**
   * The following several functions are used to display text on the
   * individualStatus page. This is so that you can check if the page
   * is populating as expected based on the data that was analyzed.
   * To use them paste the following in indiviualStatus.html within
   * the ion-content tag:
   *
{{showMacguffin()}}

   *
{{showName()}}

   *
{{showPhoneNumber()}}

   *
{{showPresence()}}

   *
{{showMeals()}}

   *
{{showMeds()}}

   *
{{showFridgeHits()}}

   *
{{showMedsHits()}}

   *
{{showTime()}}

   */
  $scope.showMacguffin = function() {
    return analysis;
  };

  $scope.showName = function() {
    var test = analysis.name;
    return test;
  };

  $scope.showPhoneNumber = function() {
    var test = analysis.phoneNumber;
    return test;
  };

  $scope.showPresence = function() {
    var test = analysis.analysisData.presenceByHour;
    return test;
  };

  $scope.showMeals = function() {
    var test = analysis.analysisData.fridgeRollingAlertLevel;
    return test;
  };

  $scope.showMeds = function() {
    var test = analysis.analysisData.medsRollingAlertLevel;
    return test;
  };

  $scope.showFridgeHits = function() {
    var test = analysis.analysisData.fridgeHitsByHour;
    return test;
  };

  $scope.showMedsHits = function() {
    var test = analysis.analysisData.medsHitsByHour;
    return test;
  };

  $scope.showTime = function() {
    return timeNow;
  };

  /**
   * This function returns the color for the call button.
   */
 $scope.getCallButtonColor = function () {
   //console.log("getCallButtonColor();", analysis);

   // check for null params
   if (analysis.analysisData.fridgeAlertLevel == null || analysis.analysisData.medsAlertLevel == null)
     return 'button-dark disableCallButton';

   var fridge = parseInt(analysis.analysisData.fridgeAlertLevel);
   var meds = parseInt(analysis.analysisData.medsAlertLevel);

   // this string must match the defined css class names
   var returnString = '';

   // check for acceptable bounds or null phone number disable button if true
   if (meds < 0 || meds > 2 || fridge < 0 || fridge > 2 || analysis.phoneNumber == null) {
     returnString += 'disableCallButton'; // error state
   }

   // check for color status of button
   if (fridge == 2 || meds == 2) {
     returnString += ' button-assertive';
   }
   else if (fridge == 1 || meds == 1) {
     returnString += ' button-energized';
   }
   else {
     returnString += ' button-dark disableCallButton';
   }
   // done
   return returnString;
 };

  /**
   * This function takes the phone number string returned from Cyclos (which
   * us in the incorrect format), and it changes the string to a format
   * necessary for making a call. Note: if no phone number is put on the
   * Cyclos server, the number (000) 000-0000 will be inserted. This indicates
   * that the number needs to be placed in the system.
   */
  $scope.getPhoneNumber = function() {
    //console.log('hit getPhoneNumber()');
    //console.log(analysis);
    var cyclosPhoneNumber = analysis.phoneNumber;

    if (cyclosPhoneNumber == null){
      cyclosPhoneNumber = "+00000000000"
      phoneNumberError = true;             // this will trigger popup when phone button is pressed
     }

      //console.log(cyclosPhoneNumber);
      var callString = "tel:";
      callString = callString + cyclosPhoneNumber.substring(2, 5) + "-" + cyclosPhoneNumber.substring(5, 8) + "-" + cyclosPhoneNumber.substring(8);
      //console.log(callString);
      var alertNum = analysis.analysisData.fridgeAlertLevel;
      if (analysis.analysisData.medsAlertLevel > alertNum) {
        alertNum = analysis.analysisData.medsAlertLevel;
      }
      var alertLevel;
      if (alertNum === 1) {
        alertLevel = 'yellow';
      }
      else {
        alertLevel = 'red';
      }
      PaymentService.call(analysis.name, 0.1, alertLevel);
      return callString;
    };

    // button press event
    $scope.checkPhoneError = function(){
      if(phoneNumberError)
        displayError();
        $fileLogger.log('error', 'There is no phone number for ' + analysis.name);
    };

    $scope.name = analysis.name;
    $scope.phoneNumber = analysis.phoneNumber;

    // An error popup dialog
    function displayError() {
      phoneNumberError = true;
      var alertPopup = $ionicPopup.alert({
        title: '
There is no phone number for this member.
',
        template: '
Please contact the system administrator.
',
        buttons: [{ // Array[Object] (optional). Buttons to place in the popup footer.
          text: 'Okay',
          type: 'button-calm'
        }]
      });
      alertPopup.then(function (res) {

      });
    }
  });
<commit_msg>Has crediting for calls and null error logging<commit_after>/**
 * CareWheels - Individual Status Controller
 *
 */
angular.module('careWheels')
  .controller('individualStatusController', function ($scope, $ionicPopup, GroupInfo, PaymentService, $fileLogger, fileloggerService) {

    fileloggerService.initLogComponent();

    /**
     * grabs the analysis of the member selected on the previous view
     */
    var analysis = GroupInfo.getSelectedMemberIndex();
    //console.log(analysis); ////////////testing

    var timeNow = new Date().getHours();
    var phoneNumberError = false;

    function convertMedsOrMealsAlertLevelToColor(sensorArray) {

      var coloredArray = [];

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

        if(sensorArray[i] == 0) {
          coloredArray[i] = "blue";
        }

        if(sensorArray[i] == 1) {
          coloredArray[i] = "yellow";
        }

        if(sensorArray[i] == 2) {
          coloredArray[i] = "red";
        }
      }

      return coloredArray;
    }

    function convertPresenceAlertLevelToColor(sensorArray) {

      var coloredArray = [];

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

        if(sensorArray[i] == false) {
          coloredArray[i] = "grey";
        }

        if(sensorArray[i] == true) {
          coloredArray[i] = "blue";
        }
      }

      return coloredArray;
    }

    function convertHitsToString(hitsArray) {

      var stringArray = [];
      var asterisks = "";

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

        for(var j = 0; j < hitsArray[i]; j++) {
          if(j > 5) {
            break;
          }

          asterisks += "* ";
        }

        stringArray[i] = asterisks;
        asterisks = "";
      }

      return stringArray;
    }

    $scope.currentHour = new Date().getHours();
    $scope.getNumber = function(num) {
      return new Array(num);
    }

    $scope.data = {

      presence: {
        value: convertPresenceAlertLevelToColor(analysis.analysisData.presenceByHour)
      },

      meals: {
        value: convertMedsOrMealsAlertLevelToColor(analysis.analysisData.fridgeRollingAlertLevel),
        hits: convertHitsToString(analysis.analysisData.fridgeHitsByHour)
      },

      meds: {
        value: convertMedsOrMealsAlertLevelToColor(analysis.analysisData.medsRollingAlertLevel),
        hits: convertHitsToString(analysis.analysisData.medsHitsByHour)
      }

    };

  // console.log("Calling Call Payment:");
  // PaymentService.call(analysis.name, 1.0, 'Red');
  // console.log("Calling sensorDataView Payment:");
  // PaymentService.sensorDataView(1.0, 'Blue');

  /**
   * The following several functions are used to display text on the
   * individualStatus page. This is so that you can check if the page
   * is populating as expected based on the data that was analyzed.
   * To use them paste the following in indiviualStatus.html within
   * the ion-content tag:
   *
{{showMacguffin()}}

   *
{{showName()}}

   *
{{showPhoneNumber()}}

   *
{{showPresence()}}

   *
{{showMeals()}}

   *
{{showMeds()}}

   *
{{showFridgeHits()}}

   *
{{showMedsHits()}}

   *
{{showTime()}}

   */
  $scope.showMacguffin = function() {
    return analysis;
  };

  $scope.showName = function() {
    var test = analysis.name;
    return test;
  };

  $scope.showPhoneNumber = function() {
    var test = analysis.phoneNumber;
    return test;
  };

  $scope.showPresence = function() {
    var test = analysis.analysisData.presenceByHour;
    return test;
  };

  $scope.showMeals = function() {
    var test = analysis.analysisData.fridgeRollingAlertLevel;
    return test;
  };

  $scope.showMeds = function() {
    var test = analysis.analysisData.medsRollingAlertLevel;
    return test;
  };

  $scope.showFridgeHits = function() {
    var test = analysis.analysisData.fridgeHitsByHour;
    return test;
  };

  $scope.showMedsHits = function() {
    var test = analysis.analysisData.medsHitsByHour;
    return test;
  };

  $scope.showTime = function() {
    return timeNow;
  };

  /**
   * This function returns the color for the call button.
   */
 $scope.getCallButtonColor = function () {
   //console.log("getCallButtonColor();", analysis);

   // check for null params
   if (analysis.analysisData.fridgeAlertLevel == null || analysis.analysisData.medsAlertLevel == null)
     return 'button-dark disableCallButton';

   var fridge = parseInt(analysis.analysisData.fridgeAlertLevel);
   var meds = parseInt(analysis.analysisData.medsAlertLevel);

   // this string must match the defined css class names
   var returnString = '';

   // check for acceptable bounds or null phone number disable button if true
   if (meds < 0 || meds > 2 || fridge < 0 || fridge > 2 || analysis.phoneNumber == null) {
     returnString += 'disableCallButton'; // error state
   }

   // check for color status of button
   if (fridge == 2 || meds == 2) {
     returnString += ' button-assertive';
   }
   else if (fridge == 1 || meds == 1) {
     returnString += ' button-energized';
   }
   else {
     returnString += ' button-dark disableCallButton';
   }
   // done
   return returnString;
 };

  /**
   * This function takes the phone number string returned from Cyclos (which
   * us in the incorrect format), and it changes the string to a format
   * necessary for making a call. Note: if no phone number is put on the
   * Cyclos server, the number (000) 000-0000 will be inserted. This indicates
   * that the number needs to be placed in the system.
   */
  $scope.getPhoneNumber = function() {
    //console.log('hit getPhoneNumber()');
    //console.log(analysis);
    var cyclosPhoneNumber = analysis.phoneNumber;

    if (cyclosPhoneNumber == null){
      cyclosPhoneNumber = "+00000000000"
      phoneNumberError = true;             // this will trigger popup when phone button is pressed
     }

      //console.log(cyclosPhoneNumber);
      var callString = "tel:";
      callString = callString + cyclosPhoneNumber.substring(2, 5) + "-" + cyclosPhoneNumber.substring(5, 8) + "-" + cyclosPhoneNumber.substring(8);
      //console.log(callString);
      var alertNum = analysis.analysisData.fridgeAlertLevel;
      if (analysis.analysisData.medsAlertLevel > alertNum) {
        alertNum = analysis.analysisData.medsAlertLevel;
      }
      var alertLevel;
      if (alertNum === 1) {
        alertLevel = 'yellow';
      }
      else {
        alertLevel = 'red';
      }
      return callString;
    };

    // button press event
    $scope.checkPhoneError = function(){
      if(phoneNumberError) {
        displayError();
        $fileLogger.log('error', 'There is no phone number for ' + analysis.name);
      }
      else {
        PaymentService.call(analysis.name, 0.1, alertLevel);
      }
    };

    $scope.name = analysis.name;
    $scope.phoneNumber = analysis.phoneNumber;

    // An error popup dialog
    function displayError() {
      phoneNumberError = true;
      var alertPopup = $ionicPopup.alert({
        title: '
There is no phone number for this member.
',
        template: '
Please contact the system administrator.
',
        buttons: [{ // Array[Object] (optional). Buttons to place in the popup footer.
          text: 'Okay',
          type: 'button-calm'
        }]
      });
      alertPopup.then(function (res) {

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


<commit_before>'use strict';

/* global CloudCmd */

const jonny = require('jonny');
const exec = require('execon');

const Storage = require('./storage');
const DOM = require('./');

module.exports = new BufferProto();

function BufferProto() {
    const Info = DOM.CurrentInfo;
    const CLASS = 'cut-file';
    const COPY = 'copy';
    const CUT = 'cut';
    const TITLE = 'Buffer';

    const Buffer  = {
        cut     : callIfEnabled.bind(null, cut),
        copy    : callIfEnabled.bind(null, copy),
        clear   : callIfEnabled.bind(null, clear),
        paste   : callIfEnabled.bind(null, paste)
    };

    function showMessage(msg) {
        DOM.Dialog.alert(TITLE, msg);
    }

    function getNames() {
        const files = DOM.getActiveFiles();
        const names = DOM.getFilenames(files);

        return names;
    }

    function addCutClass() {
        const files = DOM.getActiveFiles();

        files.forEach((element) => {
            element.classList.add(CLASS);
        });
    }

    function rmCutClass() {
        const files = DOM.getByClassAll(CLASS);

        [...files].forEach((element) => {
            element.classList.remove(CLASS);
        });
    }

    function callIfEnabled(callback) {
        const is = CloudCmd.config('buffer');

        if (is)
            return callback();

        showMessage('Buffer disabled in config!');
    }

    function copy() {
        const names = getNames();
        const from = Info.dirPath;

        clear();

        if (!names.length)
            return;

        Storage.remove(CUT)
            .set(COPY, {
                from : from,
                names: names
            });
    }

    function cut() {
        const names = getNames();
        const from = Info.dirPath;

        clear();

        if (!names.length)
            return;

        addCutClass();

        Storage
            .set(CUT, {
                from : from,
                names: names
            });
    }

    function clear() {
        Storage.remove(COPY)
            .remove(CUT);

        rmCutClass();
    }

    function paste() {
        const copy = Storage.get.bind(Storage, COPY);
        const cut = Storage.get.bind(Storage, CUT);

        exec.parallel([copy, cut], function(error, cp, ct) {
            const opStr = cp ? 'copy' : 'move';
            const opData = cp || ct;
            const Operation = CloudCmd.Operation;
            const msg = 'Path is same!';
            const path = Info.dirPath;

            if (!error && !cp && !ct)
                error = 'Buffer is empty!';

            if (error)
                return showMessage(error);

            const data = jonny.parse(opData);
            data.to = path;

            if (data.from === path)
                return showMessage(msg);

            Operation.show(opStr, data);
            clear();
        });
    }

    return Buffer;
}
<commit_msg>chore(buffer) rm " "<commit_after>'use strict';

/* global CloudCmd */

const jonny = require('jonny');
const exec = require('execon');

const Storage = require('./storage');
const DOM = require('./');

module.exports = new BufferProto();

function BufferProto() {
    const Info = DOM.CurrentInfo;
    const CLASS = 'cut-file';
    const COPY = 'copy';
    const CUT = 'cut';
    const TITLE = 'Buffer';

    const Buffer  = {
        cut     : callIfEnabled.bind(null, cut),
        copy    : callIfEnabled.bind(null, copy),
        clear   : callIfEnabled.bind(null, clear),
        paste   : callIfEnabled.bind(null, paste)
    };

    function showMessage(msg) {
        DOM.Dialog.alert(TITLE, msg);
    }

    function getNames() {
        const files = DOM.getActiveFiles();
        const names = DOM.getFilenames(files);

        return names;
    }

    function addCutClass() {
        const files = DOM.getActiveFiles();

        files.forEach((element) => {
            element.classList.add(CLASS);
        });
    }

    function rmCutClass() {
        const files = DOM.getByClassAll(CLASS);

        [...files].forEach((element) => {
            element.classList.remove(CLASS);
        });
    }

    function callIfEnabled(callback) {
        const is = CloudCmd.config('buffer');

        if (is)
            return callback();

        showMessage('Buffer disabled in config!');
    }

    function copy() {
        const names = getNames();
        const from = Info.dirPath;

        clear();

        if (!names.length)
            return;

        Storage.remove(CUT)
            .set(COPY, {
                from : from,
                names: names
            });
    }

    function cut() {
        const names = getNames();
        const from = Info.dirPath;

        clear();

        if (!names.length)
            return;

        addCutClass();

        Storage
            .set(CUT, {
                from : from,
                names: names
            });
    }

    function clear() {
        Storage.remove(COPY)
            .remove(CUT);

        rmCutClass();
    }

    function paste() {
        const copy = Storage.get.bind(Storage, COPY);
        const cut = Storage.get.bind(Storage, CUT);

        exec.parallel([copy, cut], function(error, cp, ct) {
            const opStr = cp ? 'copy' : 'move';
            const opData = cp || ct;
            const Operation = CloudCmd.Operation;
            const msg = 'Path is same!';
            const path = Info.dirPath;

            if (!error && !cp && !ct)
                error = 'Buffer is empty!';

            if (error)
                return showMessage(error);

            const data = jonny.parse(opData);
            data.to = path;

            if (data.from === path)
                return showMessage(msg);

            Operation.show(opStr, data);
            clear();
        });
    }

    return Buffer;
}
<|endoftext|>


<commit_before>let bucket = (sigmaDelta) => {
  if (sigmaDelta > 200) {
    return 4;
  }
  if (sigmaDelta > 300) {
    return 3;
  }
  if (sigmaDelta > 100) {
    return 2;
  }
  return 1;
}

let bucket_qualitative = (sigmaDeltaBucketed) => {
    if (sigmaDeltaBucketed === 4) {
        return "Rare";
    }
    if (sigmaDeltaBucketed === 3) {
        return "Unusual";
    }
    if (sigmaDeltaBucketed === 2) {
        return "Common";
    }
    if (sigmaDeltaBucketed === 1) {
        return "Very common";
    }
}

let bucket_name = (sigmaDeltaBucketed) => {
    if (sigmaDeltaBucketed === 4) {
        return "weird";
    }
    if (sigmaDeltaBucketed === 3) {
        return "odd";
    }
    if (sigmaDeltaBucketed === 2) {
        return "common";
    }
    if (sigmaDeltaBucketed === 1) {
        return "vcommon";
    }
}

module.exports = {
  bucket: bucket,
  bucket_qualitative: bucket_qualitative,
  bucket_name: bucket_name
};
<commit_msg>The bucketing was not correct oops<commit_after>let bucket = (sigmaDelta) => {
  if (sigmaDelta > 500) {
    return 4;
  }
  if (sigmaDelta > 300) {
    return 3;
  }
  if (sigmaDelta > 100) {
    return 2;
  }
  return 1;
}

let bucket_qualitative = (sigmaDeltaBucketed) => {
    if (sigmaDeltaBucketed === 4) {
        return "Rare";
    }
    if (sigmaDeltaBucketed === 3) {
        return "Unusual";
    }
    if (sigmaDeltaBucketed === 2) {
        return "Common";
    }
    if (sigmaDeltaBucketed === 1) {
        return "Very common";
    }
}

let bucket_name = (sigmaDeltaBucketed) => {
    if (sigmaDeltaBucketed === 4) {
        return "weird";
    }
    if (sigmaDeltaBucketed === 3) {
        return "odd";
    }
    if (sigmaDeltaBucketed === 2) {
        return "common";
    }
    if (sigmaDeltaBucketed === 1) {
        return "vcommon";
    }
}

module.exports = {
  bucket: bucket,
  bucket_qualitative: bucket_qualitative,
  bucket_name: bucket_name
};
<|endoftext|>


<commit_before>//==============================================================================
//==============================================================================
var buildbotmeta = {
    borderwidth : 1
}

function Point(x,y) {
    this.x  = x || 0;
    this.y = y || 0;
}

/**
 * storage class for animation data
 */
function Animation(framemap, framenumb, cols, rows, framewidth, frameheight, bordersize, initialFrame ) {
    this._currentframe = initialFrame || 0;
    this._frames = [];
    this._framemap = framemap;
    this._framewidth = framewidth;
    this._frameheight = frameheight;
    this._borderwidth = bordersize;

    /**
     * currently oscillates, can be changed to provide custom frame updating
     * on a per AnimatedSprite basis
     */
    this._frameupdate= function() {

	this._currentframe += 1;
	if( this._currentframe >= this._frames.length ) { this._currentframe = -(this._currentframe-1); }

    }

    this.initFrames = function(framenumb) {
	    var i = 0;
	    var done = false;
	    var top = new Point(0,0);

	    for (var row  = 0; row < rows && !done; row++) {
		for (var col = 0; col < cols && !done; col++) {
		    top = new Point( col * (frameheight+1)+(col+1)*bordersize, row * (framewidth+1) +(row+1)* bordersize);
		    console.log(top);
		    this._frames.push ( top );
		    i+=1;
		    if( i >= framenumb ) { done = true; }
		}
	    }
    }
    this.initFrames( framenumb );

    this.draw = function(ctx, dx, dy, dWidth, dHeight) {
	//absolute value of current frame index is used, allowing for negative frame counts
       	var curframe = this._currentframe<0? -1 * this._currentframe : this._currentframe;
	var frametop = this._frames[curframe];

	Pender.canvas.drawImage(Pender.getImage(0), frametop.x, frametop.y, this._framewidth, this._frameheight,
			     dx, dy, dWidth, dHeight);

	//Pender.ctx.drawImage( Pender.getImage(0), frametop.x, frametop.y, this._framewidth, this._frameheight, dx, dy, this._framewidth, this._frameheight   );
	//this._frameupdate();
    }

}

function AnimatedSprite(anim) {
    this.xpos = 0;
    this.ypos = 0;
    this.xvel = Math.random()*5;
    this.yvel = Math.random()*5;
    this.width = 128;
    this.height = 128;
    this._animation = anim;
    var self = this;

   this.draw = function(texid) {
	self.xpos = self.xpos+ self.xvel;
	self.ypos = self.ypos+ self.yvel;
	if( self.xpos < 0 || self.xpos >= 400-self.width/*Pender.canvas.width*/) {
	    self.xvel = self.xvel * -1;
	}
	if(self.ypos < 0 || self.ypos >= 400-self.height/*Pender.canvas.height */) {
	    self.yvel = self.yvel * -1;
	}

	this._animation.draw( texid, self.xpos, self.ypos, self.width, self.height );
    };
}

var Bots = new function () {
    this.numb = 10;
    this.bots = [];
    this.texid = 0;
    var self = this;
    this.init = function() {
	console.log("initing");
        texid = Pender.loadImage( "client/assets/build_bot_map.png" );
	for (var i = 0; i < self.numb; i++) {
	    console.log("newbot");
	    var anim = new Animation (texid, 9, 4, 3, 254, 254, 1);
	    self.bots.push (new AnimatedSprite(anim));
	}
    };

    this.draw = function() {
	Pender.canvas.clearRect(0,0,Pender.width,Pender.height);
	Pender.canvas.fillStyle = "rgb(0,0,0)";
	Pender.canvas.fillRect (10, 10, Pender.width, Pender.height);
	self.bots[0].draw(self.texid);
    };

    this.draw1 =  function() {
	Pender.canvas.clearRect(0,0,Pender.width, Pender.height);
      	for(var i = 0; i < self.numb; i++) {
	    self.bots[i].draw(self.texid);
	}
    };

}

function init() {
    Bots.init();
}

<commit_msg>client makes proper use of pender image utilities<commit_after>//==============================================================================
//==============================================================================
var buildbotmeta = {
    borderwidth : 1
}

function Point(x,y) {
    this.x  = x || 0;
    this.y = y || 0;
}

/**
 * storage class for animation data
 */
function Animation(framemap, framenumb, cols, rows, framewidth, frameheight, bordersize, initialFrame ) {
    this._currentframe = initialFrame || 0;
    this._frames = [];
    this._framemap = framemap;
    this._framewidth = framewidth;
    this._frameheight = frameheight;
    this._borderwidth = bordersize;

    /**
     * currently oscillates, can be changed to provide custom frame updating
     * on a per AnimatedSprite basis
     */
    this._frameupdate= function() {

	this._currentframe += 1;
	if( this._currentframe >= this._frames.length ) { this._currentframe = -(this._currentframe-1); }

    }

    this.initFrames = function(framenumb) {
	    var i = 0;
	    var done = false;
	    var top = new Point(0,0);

	    for (var row  = 0; row < rows && !done; row++) {
		for (var col = 0; col < cols && !done; col++) {
		    top = new Point( col * (frameheight+1)+(col+1)*bordersize, row * (framewidth+1) +(row+1)* bordersize);
		    console.log(top);
		    this._frames.push ( top );
		    i+=1;
		    if( i >= framenumb ) { done = true; }
		}
	    }
    }
    this.initFrames( framenumb );

    this.draw = function(texid, dx, dy, dWidth, dHeight) {
	//absolute value of current frame index is used, allowing for negative frame counts
       	var curframe = this._currentframe<0? -1 * this._currentframe : this._currentframe;
	var frametop = this._frames[curframe];

	Pender.canvas.drawImage(Pender.getImage(texid), frametop.x, frametop.y, this._framewidth, this._frameheight,
			     dx, dy, dWidth, dHeight);

	//Pender.ctx.drawImage( Pender.getImage(0), frametop.x, frametop.y, this._framewidth, this._frameheight, dx, dy, this._framewidth, this._frameheight   );
	//this._frameupdate();
    }

}

function AnimatedSprite(anim) {
    this.xpos = 0;
    this.ypos = 0;
    this.xvel = Math.random()*5;
    this.yvel = Math.random()*5;
    this.width = 128;
    this.height = 128;
    this._animation = anim;
    var self = this;

   this.draw = function(texid) {
	self.xpos = self.xpos+ self.xvel;
	self.ypos = self.ypos+ self.yvel;
	if( self.xpos < 0 || self.xpos >= 400-self.width/*Pender.canvas.width*/) {
	    self.xvel = self.xvel * -1;
	}
	if(self.ypos < 0 || self.ypos >= 400-self.height/*Pender.canvas.height */) {
	    self.yvel = self.yvel * -1;
	}

	this._animation.draw( texid, self.xpos, self.ypos, self.width, self.height );
    };
}

var Bots = new function () {
    this.numb = 10;
    this.bots = [];
    this.texid = 0;
    var self = this;
    this.init = function() {
	console.log("initing");
        texid = Pender.loadImage("client/assets/build_bot_map.png");
	for (var i = 0; i < self.numb; i++) {
	    console.log("newbot");
	    var anim = new Animation (texid, 9, 4, 3, 254, 254, 1);
	    self.bots.push (new AnimatedSprite(anim));
	}
    };

    this.draw = function() {
	Pender.canvas.clearRect(0,0,Pender.width,Pender.height);
	Pender.canvas.fillStyle = "rgb(0,0,0)";
	Pender.canvas.fillRect (10, 10, Pender.width, Pender.height);
	self.bots[0].draw(self.texid);
    };

    this.draw1 =  function() {
	Pender.canvas.clearRect(0,0,Pender.width, Pender.height);
      	for(var i = 0; i < self.numb; i++) {
	    self.bots[i].draw(self.texid);
	}
    };

}

function init() {
    Bots.init();
}

<|endoftext|>


<commit_before>'use strict';
// Karma configuration
// Generated on Tue Sep 10 2013 18:12:14 GMT+0200 (CEST)

var files = require('./files.conf.js');
var conf = require('./karma.shared.conf.js');

module.exports = function(config) {

    conf.files = files.testFilesBuild;

    conf.browserStack = {
        username: process.env.BROWSER_STACK_USERNAME,
        accessKey: process.env.BROWSER_STACK_ACCESS_KEY,
        project: process.env.TRAVIS_REPO_SLUG || 'stimuli@local',
        build: process.env.TRAVIS_BUILD_NUMBER,
        startTunnel: true,
        retryLimit: 5
    };
    conf.captureTimeout = 90000; // 1 min 30
    conf.logLevel = config.LOG_INFO;
    conf.reportSlowerThan = 30000;
    conf.disconnectTolerance = 5;
    conf.autoWatch = false;
    conf.singleRun = true;
    conf.disableCompression = true;
    conf.serverPort = 9876;
    conf.serverHost = '127.0.0.1';
    conf.clientHost = '127.0.0.1';
    conf.clientPort = 8080;
    conf.transports = ['xhr-polling'];
    conf.customLaunchers = {

        BS_FIREFOX: {
            base: 'BrowserStack',
            browser: 'firefox',
            browser_version: '24.0',
            os: 'Windows',
            os_version: 'XP'
        },

        BS_CHROME: {
            base: 'BrowserStack',
            browser: 'chrome',
            browser_version: '29.0',
            os: 'Windows',
            os_version: 'XP'
        },

        BS_IE8: {
            base: 'BrowserStack',
            browser: 'ie',
            browser_version: '8.0',
            os: 'Windows',
            os_version: 'XP'
        },

        BS_IE9: {
            base: 'BrowserStack',
            browser: 'ie',
            browser_version: '9.0',
            os: 'Windows',
            os_version: '7'
        },

        BS_IE10: {
            base: 'BrowserStack',
            browser: 'ie',
            browser_version: '10.0',
            os: 'Windows',
            os_version: '8'
        },

        BS_IE11: {
            base: 'BrowserStack',
            browser: 'ie',
            browser_version: '11.0',
            os: 'Windows',
            os_version: '7'
        },

        BS_SAFARI51: {
            base: 'BrowserStack',
            browser: 'safari',
            browser_version: '5.1',
            os: 'OS X',
            os_version: 'Snow Leopard'
        },

        BS_SAFARI6: {
            base: 'BrowserStack',
            browser: 'safari',
            browser_version: '6.0',
            os: 'OS X',
            os_version: 'Mountain Lion'
        },

        BS_OPERA16: {
            base: 'BrowserStack',
            os: 'OS X',
            browser: 'opera',
            os_version: 'Mountain Lion',
            browser_version: '16.0'
        },

        BS_ANDROID_4: {
            base: 'BrowserStack',
            os: 'android',
            device: 'HTC One X',
            browser: 'Android Browser',
            os_version: '4.0',
            browser_version: null
        },

        BS_ANDROID_41: {
            base: 'BrowserStack',
            os: 'android',
            device: 'Samsung Galaxy Note II',
            browser: 'Android Browser',
            os_version: '4.1',
            browser_version: null
        },

        BS_ANDROID_42: {
            base: 'BrowserStack',
            os: 'android',
            device: 'LG Nexus 4',
            browser: 'Android Browser',
            os_version: '4.2',
            browser_version: null
        },

        BS_IOS_6: {
            base: 'BrowserStack',
            os: 'ios',
            device: 'iPad 3rd (6.0)',
            browser: 'Mobile Safari',
            os_version: '6.0',
            browser_version: null
        }

    };

    config.set(conf);

};
<commit_msg>chore(build): Switch to Motorola Razr Maxx HD to test android 4.1<commit_after>'use strict';
// Karma configuration
// Generated on Tue Sep 10 2013 18:12:14 GMT+0200 (CEST)

var files = require('./files.conf.js');
var conf = require('./karma.shared.conf.js');

module.exports = function(config) {

    conf.files = files.testFilesBuild;

    conf.browserStack = {
        username: process.env.BROWSER_STACK_USERNAME,
        accessKey: process.env.BROWSER_STACK_ACCESS_KEY,
        project: process.env.TRAVIS_REPO_SLUG || 'stimuli@local',
        build: process.env.TRAVIS_BUILD_NUMBER,
        startTunnel: true,
        retryLimit: 5
    };
    conf.captureTimeout = 90000; // 1 min 30
    conf.logLevel = config.LOG_INFO;
    conf.reportSlowerThan = 30000;
    conf.disconnectTolerance = 5;
    conf.autoWatch = false;
    conf.singleRun = true;
    conf.disableCompression = true;
    conf.serverPort = 9876;
    conf.serverHost = '127.0.0.1';
    conf.clientHost = '127.0.0.1';
    conf.clientPort = 8080;
    conf.transports = ['xhr-polling'];
    conf.customLaunchers = {

        BS_FIREFOX: {
            base: 'BrowserStack',
            browser: 'firefox',
            browser_version: '24.0',
            os: 'Windows',
            os_version: 'XP'
        },

        BS_CHROME: {
            base: 'BrowserStack',
            browser: 'chrome',
            browser_version: '29.0',
            os: 'Windows',
            os_version: 'XP'
        },

        BS_IE8: {
            base: 'BrowserStack',
            browser: 'ie',
            browser_version: '8.0',
            os: 'Windows',
            os_version: 'XP'
        },

        BS_IE9: {
            base: 'BrowserStack',
            browser: 'ie',
            browser_version: '9.0',
            os: 'Windows',
            os_version: '7'
        },

        BS_IE10: {
            base: 'BrowserStack',
            browser: 'ie',
            browser_version: '10.0',
            os: 'Windows',
            os_version: '8'
        },

        BS_IE11: {
            base: 'BrowserStack',
            browser: 'ie',
            browser_version: '11.0',
            os: 'Windows',
            os_version: '7'
        },

        BS_SAFARI51: {
            base: 'BrowserStack',
            browser: 'safari',
            browser_version: '5.1',
            os: 'OS X',
            os_version: 'Snow Leopard'
        },

        BS_SAFARI6: {
            base: 'BrowserStack',
            browser: 'safari',
            browser_version: '6.0',
            os: 'OS X',
            os_version: 'Mountain Lion'
        },

        BS_OPERA16: {
            base: 'BrowserStack',
            os: 'OS X',
            browser: 'opera',
            os_version: 'Mountain Lion',
            browser_version: '16.0'
        },

        BS_ANDROID_4: {
            base: 'BrowserStack',
            os: 'android',
            device: 'HTC One X',
            browser: 'Android Browser',
            os_version: '4.0',
            browser_version: null
        },

        BS_ANDROID_41: {
            base: 'BrowserStack',
            os: 'android',
            device: 'Motorola Razr Maxx HD',
            browser: 'Android Browser',
            os_version: '4.1',
            browser_version: null
        },

        BS_ANDROID_42: {
            base: 'BrowserStack',
            os: 'android',
            device: 'LG Nexus 4',
            browser: 'Android Browser',
            os_version: '4.2',
            browser_version: null
        },

        BS_IOS_6: {
            base: 'BrowserStack',
            os: 'ios',
            device: 'iPad 3rd (6.0)',
            browser: 'Mobile Safari',
            os_version: '6.0',
            browser_version: null
        }

    };

    config.set(conf);

};
<|endoftext|>


<commit_before>var Batch = require('batch');
var debounce = require('debounce');
var geocode = require('geocode');
var Journey = require('journey');
var Location = require('location');
var log = require('./client/log')('plan');
var defaults = require('model-defaults');
var model = require('model');
var ProfileQuery = require('profile-query');
var ProfileScorer = require('otp-profile-score');
var qs = require('querystring');

var loadPlan = require('./load');
var store = require('./store');
var updateRoutes = require('./update-routes');

/**
 * Debounce updates to once every 50ms
 */

var DEBOUNCE_UPDATES = 5;
var LIMIT = 2;

/**
 * Expose `Plan`
 */

var Plan = module.exports = model('Plan')
  .use(defaults({
    bike: true,
    bikeShare: false,
    bus: true,
    car: false,
    days: 'M—F',
    end_time: (new Date()).getHours() + 4,
    from: '',
    from_valid: false,
    loading: true,
    options: [],
    query: new ProfileQuery(),
    scorer: new ProfileScorer(),
    start_time: (new Date()).getHours() - 1,
    to: '',
    to_valid: false,
    train: true,
    tripsPerYear: 235,
    walk: true
  }))
  .attr('bike')
  .attr('bikeShare')
  .attr('bus')
  .attr('car')
  .attr('days')
  .attr('end_time')
  .attr('from')
  .attr('from_id')
  .attr('from_ll')
  .attr('from_valid')
  .attr('loading')
  .attr('journey')
  .attr('options')
  .attr('query')
  .attr('scorer')
  .attr('start_time')
  .attr('to')
  .attr('to_id')
  .attr('to_ll')
  .attr('to_valid')
  .attr('train')
  .attr('tripsPerYear')
  .attr('walk');

/**
 * Expose `load`
 */

module.exports.load = function(ctx, next) {
  loadPlan(Plan, ctx, next);
};

/**
 * Sync plans with localStorage
 */

Plan.on('change', function(plan, name, val) {
  log('plan.%s changed to %s', name, val);

  // Store in localStorage & track the change
  if (name !== 'options' && name !== 'journey' && name !== 'loading') plan.store();
});

/**
 * Keep start/end times in sync
 */

Plan.on('change start_time', function(plan, val, prev) {
  if (val >= plan.end_time()) plan.end_time(val + 1);
});

Plan.on('change end_time', function(plan, val, prev) {
  if (val <= plan.start_time()) plan.start_time(val - 1);
});

/**
 * Update routes. Restrict to once every 25ms.
 */

Plan.prototype.updateRoutes = debounce(function(opts, callback) {
  updateRoutes(this, opts, callback);
}, DEBOUNCE_UPDATES);

/**
 * Geocode
 */

Plan.prototype.geocode = function(dest, callback) {
  if (!callback) callback = function() {};

  var plan = this;
  var address = plan[dest]();
  var ll = plan[dest + '_ll']();
  if (address && address.length > 0) {
    geocode(address, function(err, ll) {
      if (err) {
        callback(err);
      } else {
        plan[dest + '_ll'](ll);
        callback(null, ll);
      }
    });
  } else {
    callback(null, ll);
  }
};

/**
 * Save Journey
 */

Plan.prototype.saveJourney = function(callback) {
  var opts = {};
  var skipKeys = ['options', 'journey', 'scorer'];
  for (var key in this.attrs) {
    if (skipKeys.indexOf(key) !== -1 || key.indexOf('to') === 0 || key.indexOf('from') === 0) {
      continue;
    }
    opts[key] = this.attrs[key];
  }

  // Create new journey
  var journey = new Journey({
    locations: [{
      _id: this.from_id()
    }, {
      _id: this.to_id()
    }],
    opts: opts
  });

  // Save
  journey.save(callback);
};

/**
 * Valid coordinates
 */

Plan.prototype.validCoordinates = function() {
  return this.coordinateIsValid(this.from_ll()) && this.coordinateIsValid(this.to_ll());
};

/**
 * Set Address
 */

Plan.prototype.setAddress = function(name, address, callback, extra) {

  console.log("name", name);
  console.log("address", address);
  console.log("callback", callback);
  console.log("extra", extra);

  callback = callback || function() {}; // noop callback
  var location = new Location();
  var plan = this;
  var c = address.split(',');
  var isCoordinate = c.length === 2 && !isNaN(parseFloat(c[0])) && !isNaN(parseFloat(c[1]));

  if (!address || address.length < 1) return callback();

    console.log("Location declarada ->", location);

  if (isCoordinate) {

    console.log("Las cordenadas existen");
    location.coordinate({
      lat: parseFloat(c[1]),
      lng: parseFloat(c[0])
    });
  } else {

    console.log("se agrega la misma direccion");
    location.address(address);
  }
  console.log("Location luego de las asignaciones ->", location);
  console.log("location.coordenadas",  location.coordinate({lat: parseFloat(c[1]),lng: parseFloat(c[0]) }));
  console.log("location.address", location.address(address));

  location.save(function(err, res) {

      console.log("res", res);
    if (err) {
	if (isCoordinate) {
        console.log("properties", extra.properties);
	    var changes = {};
	    changes[name] = extra.properties.label;
	    changes[name + '_ll'] = location.coordinate();
	    changes[name + '_valid'] = true;

	    plan.set(changes);
	    callback(null, extra);
	} else {
	    callback(err);
	}
    } else {
      console.log("properties2", extra.properties);
      var changes = {};
      if (isCoordinate)
        changes[name] = res.body.address + ', ' + res.body.city + ', ' + res.body.state;
      else
        changes[name] = address;

      changes[name + '_ll'] = res.body.coordinate;
      changes[name + '_id'] = res.body._id;
      changes[name + '_valid'] = true;

      console.log("CHANGES PLAN SET", changes);
      plan.set(changes);
      callback(null, res.body);
    }
  });
};

/**
 * Set both addresses
 */

Plan.prototype.setAddresses = function(from, to, callback) {
  // Initialize the default locations
  var plan = this;

  Batch()
    .push(function(done) {
      plan.setAddress('from', from, done);
    })
    .push(function(done) {
      plan.setAddress('to', to, done);
    }).end(callback);
};

/**
 * Rescore Options
 */

Plan.prototype.rescoreOptions = function() {
  var scorer = this.scorer();
  var options = this.options();

  options.forEach(function(o) {
    o.rescore(scorer);
  });

  this.store();
};

/**
 * To Lower Case
 */

function toLowerCase(s) {
  return s ? s.toLowerCase() : '';
}

Plan.prototype.coordinateIsValid = function(c) {
  return !!c && !!parseFloat(c.lat) && !!parseFloat(c.lng) && parseFloat(c.lat) !== 0.0 && parseFloat(c.lng) !== 0.0;
};

/**
 * Modes as a CSV
 */

Plan.prototype.modesCSV = function() {
  var modes = [];
  if (this.bike()) modes.push('BICYCLE');
  if (this.bikeShare()) modes.push('BICYCLE_RENT');
  if (this.bus()) modes.push('BUSISH');
  if (this.train()) modes.push('TRAINISH');
  if (this.walk()) modes.push('WALK');
  if (this.car()) modes.push('CAR');

  return modes.join(',');
};

/**
 * Set modes from string
 */

Plan.prototype.setModes = function(csv) {
  if (!csv || csv.length < 1) return;
  var modes = csv.split ? csv.split(',') : csv;

  this.bike(modes.indexOf('BICYCLE') !== -1);
//  this.bikeShare(modes.indexOf('BICYCLE_RENT') !== -1);
  this.bikeShare(false);
  this.bus(true);
//  this.bus(modes.indexOf('BUSISH') !== -1);
  this.train(modes.indexOf('TRAINISH') !== -1);
  this.car(modes.indexOf('CAR') !== -1);
};

/**
 * Generate Query Parameters for this plan
 */

Plan.prototype.generateQuery = function() {
  var from = this.from_ll() || {};
  var to = this.to_ll() || {};

  // Transit modes
  var modes = [];//['WALK'];

  if (this.bikeShare()) modes.push('BICYCLE_RENT');

  if (this.car()) {
    modes.push('CAR');
  }
  if (this.bike()) {
    modes.push('BICYCLE');
  } else {
    modes.push('WALK');
  }
  if (this.bus()) modes.push('BUSISH');
  if (this.train()) modes.push('TRAINISH');
  if (modes.length==0) modes.push('WALK');

  var startTime = this.start_time();
  var endTime = this.end_time();
  var scorer = this.scorer();

  // Convert the hours into strings
  startTime += ':00';
  endTime = endTime === 24 ? '23:59' : endTime + ':00';

  return {
    date: this.nextDate(),
    mode: modes.join(','),
      time: startTime,
      fromPlace: (from.lat + ',' + from.lng),
      toPlace: (to.lat + ',' + to.lng),
      numItineraries: 3,
      maxWalkDistance: 20000,
      bikeSpeed: 10,
      bikeBoardCost: 15,
      walkReluctance: 10,
      clampInitialWait: 60,
//      waitAtBeginningFactor: 0.5,
      triangleSafetyFactor: 0.9,
      triangleSlopeFactor: 0.5,
      triangleTimeFactor: 0.9,
      optimize: 'QUICK'
  };
};

/**
 * Store in localStorage. Restrict this I/O to once every 25ms.
 */

Plan.prototype.store = debounce(function() {
  store(this);
}, DEBOUNCE_UPDATES);

/**
 * Clear localStorage
 */

Plan.prototype.clearStore = store.clear;

/**
 * Save URL
 */

Plan.prototype.saveURL = function() {
    console.log("Query planer change ciudad -> ", this.generateQueryString());
  window.history.replaceState(null, '', '/planner?' + this.generateQueryString());
};

/**
 * Get next date for day of the week
 */

Plan.prototype.nextDate = function() {
  var now = new Date();
  var date = now.getDate();
  var dayOfTheWeek = now.getDay();
  switch (this.days()) {
    case 'M—F':
      if (dayOfTheWeek === 0) now.setDate(date + 1);
      if (dayOfTheWeek === 6) now.setDate(date + 2);
      break;
    case 'Sat':
      now.setDate(date + (6 - dayOfTheWeek));
      break;
    case 'Sun':
      now.setDate(date + (7 - dayOfTheWeek));
      break;
  }
  return now.toISOString().split('T')[0];
};

/**
 * Generate `places` for transitive
 */

Plan.prototype.generatePlaces = function() {
  var fll = this.from_ll();
  var tll = this.to_ll();
  if (!fll || !tll) return [];

  return [{
    place_id: 'from',
    place_lat: fll.lat,
    place_lon: fll.lng,
    place_name: 'From'
  }, {
    place_id: 'to',
    place_lat: tll.lat,
    place_lon: tll.lng,
    place_name: 'To'
  }];
};

/**
 * Generate QueryString
 */

Plan.prototype.generateQueryString = function() {

    console.log("set this to ->", to);

  return qs.stringify({
    from: this.from(),
    to: this.to(),
    modes: this.modesCSV(),
    start_time: this.start_time(),
    end_time: this.end_time(),
    days: this.days()
  });
};
<commit_msg>remove bug to<commit_after>var Batch = require('batch');
var debounce = require('debounce');
var geocode = require('geocode');
var Journey = require('journey');
var Location = require('location');
var log = require('./client/log')('plan');
var defaults = require('model-defaults');
var model = require('model');
var ProfileQuery = require('profile-query');
var ProfileScorer = require('otp-profile-score');
var qs = require('querystring');

var loadPlan = require('./load');
var store = require('./store');
var updateRoutes = require('./update-routes');

/**
 * Debounce updates to once every 50ms
 */

var DEBOUNCE_UPDATES = 5;
var LIMIT = 2;

/**
 * Expose `Plan`
 */

var Plan = module.exports = model('Plan')
  .use(defaults({
    bike: true,
    bikeShare: false,
    bus: true,
    car: false,
    days: 'M—F',
    end_time: (new Date()).getHours() + 4,
    from: '',
    from_valid: false,
    loading: true,
    options: [],
    query: new ProfileQuery(),
    scorer: new ProfileScorer(),
    start_time: (new Date()).getHours() - 1,
    to: '',
    to_valid: false,
    train: true,
    tripsPerYear: 235,
    walk: true
  }))
  .attr('bike')
  .attr('bikeShare')
  .attr('bus')
  .attr('car')
  .attr('days')
  .attr('end_time')
  .attr('from')
  .attr('from_id')
  .attr('from_ll')
  .attr('from_valid')
  .attr('loading')
  .attr('journey')
  .attr('options')
  .attr('query')
  .attr('scorer')
  .attr('start_time')
  .attr('to')
  .attr('to_id')
  .attr('to_ll')
  .attr('to_valid')
  .attr('train')
  .attr('tripsPerYear')
  .attr('walk');

/**
 * Expose `load`
 */

module.exports.load = function(ctx, next) {
  loadPlan(Plan, ctx, next);
};

/**
 * Sync plans with localStorage
 */

Plan.on('change', function(plan, name, val) {
  log('plan.%s changed to %s', name, val);

  // Store in localStorage & track the change
  if (name !== 'options' && name !== 'journey' && name !== 'loading') plan.store();
});

/**
 * Keep start/end times in sync
 */

Plan.on('change start_time', function(plan, val, prev) {
  if (val >= plan.end_time()) plan.end_time(val + 1);
});

Plan.on('change end_time', function(plan, val, prev) {
  if (val <= plan.start_time()) plan.start_time(val - 1);
});

/**
 * Update routes. Restrict to once every 25ms.
 */

Plan.prototype.updateRoutes = debounce(function(opts, callback) {
  updateRoutes(this, opts, callback);
}, DEBOUNCE_UPDATES);

/**
 * Geocode
 */

Plan.prototype.geocode = function(dest, callback) {
  if (!callback) callback = function() {};

  var plan = this;
  var address = plan[dest]();
  var ll = plan[dest + '_ll']();
  if (address && address.length > 0) {
    geocode(address, function(err, ll) {
      if (err) {
        callback(err);
      } else {
        plan[dest + '_ll'](ll);
        callback(null, ll);
      }
    });
  } else {
    callback(null, ll);
  }
};

/**
 * Save Journey
 */

Plan.prototype.saveJourney = function(callback) {
  var opts = {};
  var skipKeys = ['options', 'journey', 'scorer'];
  for (var key in this.attrs) {
    if (skipKeys.indexOf(key) !== -1 || key.indexOf('to') === 0 || key.indexOf('from') === 0) {
      continue;
    }
    opts[key] = this.attrs[key];
  }

  // Create new journey
  var journey = new Journey({
    locations: [{
      _id: this.from_id()
    }, {
      _id: this.to_id()
    }],
    opts: opts
  });

  // Save
  journey.save(callback);
};

/**
 * Valid coordinates
 */

Plan.prototype.validCoordinates = function() {
  return this.coordinateIsValid(this.from_ll()) && this.coordinateIsValid(this.to_ll());
};

/**
 * Set Address
 */

Plan.prototype.setAddress = function(name, address, callback, extra) {

  console.log("name", name);
  console.log("address", address);
  console.log("callback", callback);
  console.log("extra", extra);

  callback = callback || function() {}; // noop callback
  var location = new Location();
  var plan = this;
  var c = address.split(',');
  var isCoordinate = c.length === 2 && !isNaN(parseFloat(c[0])) && !isNaN(parseFloat(c[1]));

  if (!address || address.length < 1) return callback();

    console.log("Location declarada ->", location);

  if (isCoordinate) {

    console.log("Las cordenadas existen");
    location.coordinate({
      lat: parseFloat(c[1]),
      lng: parseFloat(c[0])
    });
  } else {

    console.log("se agrega la misma direccion");
    location.address(address);
  }
  console.log("Location luego de las asignaciones ->", location);
  console.log("location.coordenadas",  location.coordinate({lat: parseFloat(c[1]),lng: parseFloat(c[0]) }));
  console.log("location.address", location.address(address));

  location.save(function(err, res) {

      console.log("res", res);
    if (err) {
	if (isCoordinate) {
        console.log("properties", extra.properties);
	    var changes = {};
	    changes[name] = extra.properties.label;
	    changes[name + '_ll'] = location.coordinate();
	    changes[name + '_valid'] = true;

	    plan.set(changes);
	    callback(null, extra);
	} else {
	    callback(err);
	}
    } else {
      console.log("properties2", extra.properties);
      var changes = {};
      if (isCoordinate)
        changes[name] = res.body.address + ', ' + res.body.city + ', ' + res.body.state;
      else
        changes[name] = address;

      changes[name + '_ll'] = res.body.coordinate;
      changes[name + '_id'] = res.body._id;
      changes[name + '_valid'] = true;

      console.log("CHANGES PLAN SET", changes);
      plan.set(changes);
      callback(null, res.body);
    }
  });
};

/**
 * Set both addresses
 */

Plan.prototype.setAddresses = function(from, to, callback) {
  // Initialize the default locations
  var plan = this;

  Batch()
    .push(function(done) {
      plan.setAddress('from', from, done);
    })
    .push(function(done) {
      plan.setAddress('to', to, done);
    }).end(callback);
};

/**
 * Rescore Options
 */

Plan.prototype.rescoreOptions = function() {
  var scorer = this.scorer();
  var options = this.options();

  options.forEach(function(o) {
    o.rescore(scorer);
  });

  this.store();
};

/**
 * To Lower Case
 */

function toLowerCase(s) {
  return s ? s.toLowerCase() : '';
}

Plan.prototype.coordinateIsValid = function(c) {
  return !!c && !!parseFloat(c.lat) && !!parseFloat(c.lng) && parseFloat(c.lat) !== 0.0 && parseFloat(c.lng) !== 0.0;
};

/**
 * Modes as a CSV
 */

Plan.prototype.modesCSV = function() {
  var modes = [];
  if (this.bike()) modes.push('BICYCLE');
  if (this.bikeShare()) modes.push('BICYCLE_RENT');
  if (this.bus()) modes.push('BUSISH');
  if (this.train()) modes.push('TRAINISH');
  if (this.walk()) modes.push('WALK');
  if (this.car()) modes.push('CAR');

  return modes.join(',');
};

/**
 * Set modes from string
 */

Plan.prototype.setModes = function(csv) {
  if (!csv || csv.length < 1) return;
  var modes = csv.split ? csv.split(',') : csv;

  this.bike(modes.indexOf('BICYCLE') !== -1);
//  this.bikeShare(modes.indexOf('BICYCLE_RENT') !== -1);
  this.bikeShare(false);
  this.bus(true);
//  this.bus(modes.indexOf('BUSISH') !== -1);
  this.train(modes.indexOf('TRAINISH') !== -1);
  this.car(modes.indexOf('CAR') !== -1);
};

/**
 * Generate Query Parameters for this plan
 */

Plan.prototype.generateQuery = function() {
  var from = this.from_ll() || {};
  var to = this.to_ll() || {};

  // Transit modes
  var modes = [];//['WALK'];

  if (this.bikeShare()) modes.push('BICYCLE_RENT');

  if (this.car()) {
    modes.push('CAR');
  }
  if (this.bike()) {
    modes.push('BICYCLE');
  } else {
    modes.push('WALK');
  }
  if (this.bus()) modes.push('BUSISH');
  if (this.train()) modes.push('TRAINISH');
  if (modes.length==0) modes.push('WALK');

  var startTime = this.start_time();
  var endTime = this.end_time();
  var scorer = this.scorer();

  // Convert the hours into strings
  startTime += ':00';
  endTime = endTime === 24 ? '23:59' : endTime + ':00';

  return {
    date: this.nextDate(),
    mode: modes.join(','),
      time: startTime,
      fromPlace: (from.lat + ',' + from.lng),
      toPlace: (to.lat + ',' + to.lng),
      numItineraries: 3,
      maxWalkDistance: 20000,
      bikeSpeed: 10,
      bikeBoardCost: 15,
      walkReluctance: 10,
      clampInitialWait: 60,
//      waitAtBeginningFactor: 0.5,
      triangleSafetyFactor: 0.9,
      triangleSlopeFactor: 0.5,
      triangleTimeFactor: 0.9,
      optimize: 'QUICK'
  };
};

/**
 * Store in localStorage. Restrict this I/O to once every 25ms.
 */

Plan.prototype.store = debounce(function() {
  store(this);
}, DEBOUNCE_UPDATES);

/**
 * Clear localStorage
 */

Plan.prototype.clearStore = store.clear;

/**
 * Save URL
 */

Plan.prototype.saveURL = function() {
    console.log("Query planer change ciudad -> ", this.generateQueryString());
  window.history.replaceState(null, '', '/planner?' + this.generateQueryString());
};

/**
 * Get next date for day of the week
 */

Plan.prototype.nextDate = function() {
  var now = new Date();
  var date = now.getDate();
  var dayOfTheWeek = now.getDay();
  switch (this.days()) {
    case 'M—F':
      if (dayOfTheWeek === 0) now.setDate(date + 1);
      if (dayOfTheWeek === 6) now.setDate(date + 2);
      break;
    case 'Sat':
      now.setDate(date + (6 - dayOfTheWeek));
      break;
    case 'Sun':
      now.setDate(date + (7 - dayOfTheWeek));
      break;
  }
  return now.toISOString().split('T')[0];
};

/**
 * Generate `places` for transitive
 */

Plan.prototype.generatePlaces = function() {
  var fll = this.from_ll();
  var tll = this.to_ll();
  if (!fll || !tll) return [];

  return [{
    place_id: 'from',
    place_lat: fll.lat,
    place_lon: fll.lng,
    place_name: 'From'
  }, {
    place_id: 'to',
    place_lat: tll.lat,
    place_lon: tll.lng,
    place_name: 'To'
  }];
};

/**
 * Generate QueryString
 */

Plan.prototype.generateQueryString = function() {

  return qs.stringify({
    from: this.from(),
    to: this.to(),
    modes: this.modesCSV(),
    start_time: this.start_time(),
    end_time: this.end_time(),
    days: this.days()
  });
};
<|endoftext|>


<commit_before>wwt.controllers.controller('DataVizController', ['$scope', '$rootScope', 'Util', function ($scope, $rootScope, util) {
  $scope.pages = ['Welcome', 'Position', 'Scale', 'Markers', 'Color Map', 'Date Time', 'Hover Text'];

  if ($scope.propertyMode) {
    $scope.pages.splice(0, 1);
    $scope.page = 'Position';
    initColumns();
  } else {
    $scope.page = 'Welcome';
  }

  $scope.buttonsEnabled = {
    next: false,
    back: false,
    finish: true
  };
  var l;
  $scope.log = function (s) {
    console.log(s || $scope.layer);
  };
  $scope.pasteExcel = function (e) {
    var ev = e.originalEvent;
    var pasteData = ev.clipboardData.getData('Text')
      .replace(/(\r\n|\r|\n)/g,'\r\n');//normalize line endings
    //console.log('paste data ok');
    $('#pasteRow').remove();
    //setTimeout(function () {
      //gc
      //console.log('cleaned');
     $scope.layerName = 'clipboard';
      l = $scope.layer = wwtlib.LayerManager.createSpreadsheetLayer($scope.layerMap, $scope.layerName, pasteData);

      initColumns();
      $scope.buttonsEnabled.next = $scope.buttonsEnabled.finish = 1;
    //}, 1);
  };
  var oldName =  'clipboard';
  $scope.setName = function(n){
    setTimeout(function(){
      l.set_name(n);
      var maps = wwtlib.LayerManager.get_allMaps()[l.referenceFrame].childMaps;
      maps[n] = maps[oldName];
      delete maps[oldName];
      oldName = n;
      wwt.detectNewLayers();
    },123)
  };
  function initColumns() {
    l = $scope.layer;
    $scope.columns = $scope.layer._table$1.header.map(function (c, i) {
      return {label: c, type: i};
    });
    l.computeDateDomainRange(0,-1);
    console.log('compute');
    var none = {label: 'None', index: -1};
    $scope.columns.splice(0, 0, none);
    l.psType = l.get_pointScaleType();
    sliders = {};
  }

  var sliders = {};
  var initExpSlider = function (sel, prop, initVal) {
    $scope[prop] = initVal;
    if (sliders[prop]) {
      return;
    }
    setTimeout(function () {
      var bar = $(sel);
      var off = parseInt(bar.css('left').replace('px', ''));
      sliders[prop] = new wwt.Move({
        el: bar,
        grid: 4,
        bounds: {y: [0, 0], x: [0 - off, 100 - off]},
        onstart: function () {
          bar.addClass('moving');
        },
        onmove: function () {
          var f = (this.css.left - 50) / 4;
          var v = $scope[prop];
          f = Math.min(Math.max(f, -12), 12);
          v = Math.pow(2, f);
          $scope.$applyAsync(function () {
            $scope[prop] = v;
            l['set_' + prop](v);
          });
        },
        oncomplete: function () {
          bar.removeClass('moving');
        }
      });
    }, 10);
  };

  var calcButtonState = function () {
    //console.log($scope.propertyMode);
    if (!$scope.propertyMode) {
      var i = $scope.pages.indexOf($scope.page);
      $scope.buttonsEnabled.next = $scope.page === 'Welcome' ? !!$scope.layer : i < $scope.pages.length - 1;
      $scope.buttonsEnabled.back = i > 0;
      $scope.buttonsEnabled.finish = !!$scope.layer;
    }
    if ($scope.page === 'Scale') {
      initExpSlider('.scale-factor .btn', 'scaleFactor', 1);
    }
    if ($scope.page === 'Date Time') {
      initExpSlider('.time-decay .btn', 'decay', 16);
    }
  };
  $scope.setPage = function (p) {
    $scope.page = p;
    calcButtonState();
  }
  calcButtonState();
  $scope.next = function () {
    var i = $scope.pages.indexOf($scope.page);
    $scope.page = $scope.pages[i + 1];
    calcButtonState();
  };
  $scope.back = function () {
    var i = $scope.pages.indexOf($scope.page);
    $scope.page = $scope.pages[i - 1];
    calcButtonState();
  };
  $scope.finish = function () {
    $scope.layer.version++;
    $scope.dialog.OK($scope.layer);
  };
}]);
<commit_msg>Make sliders in layer properties window be initialized with the current value. Remove unnecessary logging.<commit_after>wwt.controllers.controller('DataVizController', ['$scope', '$rootScope', 'Util', function ($scope, $rootScope, util) {
  $scope.pages = ['Welcome', 'Position', 'Scale', 'Markers', 'Color Map', 'Date Time', 'Hover Text'];

  if ($scope.propertyMode) {
    $scope.pages.splice(0, 1);
    $scope.page = 'Position';
    initColumns();
  } else {
    $scope.page = 'Welcome';
  }

  $scope.buttonsEnabled = {
    next: false,
    back: false,
    finish: true
  };
  var l;
  $scope.log = function (s) {
    console.log(s || $scope.layer);
  };
  $scope.pasteExcel = function (e) {
    var ev = e.originalEvent;
    var pasteData = ev.clipboardData.getData('Text')
      .replace(/(\r\n|\r|\n)/g,'\r\n');//normalize line endings
    //console.log('paste data ok');
    $('#pasteRow').remove();
    //setTimeout(function () {
      //gc
      //console.log('cleaned');
     $scope.layerName = 'clipboard';
      l = $scope.layer = wwtlib.LayerManager.createSpreadsheetLayer($scope.layerMap, $scope.layerName, pasteData);

      initColumns();
      $scope.buttonsEnabled.next = $scope.buttonsEnabled.finish = 1;
    //}, 1);
  };
  var oldName =  'clipboard';
  $scope.setName = function(n){
    setTimeout(function(){
      l.set_name(n);
      var maps = wwtlib.LayerManager.get_allMaps()[l.referenceFrame].childMaps;
      maps[n] = maps[oldName];
      delete maps[oldName];
      oldName = n;
      wwt.detectNewLayers();
    },123)
  };
  function initColumns() {
    l = $scope.layer;
    $scope.columns = $scope.layer._table$1.header.map(function (c, i) {
      return {label: c, type: i};
    });
    l.computeDateDomainRange(0,-1);
    var none = {label: 'None', index: -1};
    $scope.columns.splice(0, 0, none);
    l.psType = l.get_pointScaleType();
    sliders = {};
  }

  var sliders = {};
  var initExpSlider = function (sel, prop, initVal) {
    var value = $scope[prop];
    if (value == null) {
      value = l['get_' + prop]();
      if (value == null) {
        value = initVal;
      }
      $scope[prop] = value;
    }
    if (sliders[prop]) {
      return;
    }
    setTimeout(function () {
      var bar = $(sel);
      var pxValue = 4 * Math.round(Math.log2(value)) + 50;
      bar[0].style.left = pxValue.toString() + 'px';
      var off = parseInt(bar.css('left').replace('px', ''));
      sliders[prop] = new wwt.Move({
        el: bar,
        grid: 4,
        bounds: {y: [0, 0], x: [0 - off, 100 - off]},
        onstart: function () {
          bar.addClass('moving');
        },
        onmove: function () {
          var f = (this.css.left - 50) / 4;
          var v = $scope[prop];
          f = Math.min(Math.max(f, -12), 12);
          v = Math.pow(2, f);
          $scope.$applyAsync(function () {
            $scope[prop] = v;
            l['set_' + prop](v);
          });
        },
        oncomplete: function () {
          bar.removeClass('moving');
        }
      });
    }, 10);
  };

  var calcButtonState = function () {
    //console.log($scope.propertyMode);
    if (!$scope.propertyMode) {
      var i = $scope.pages.indexOf($scope.page);
      $scope.buttonsEnabled.next = $scope.page === 'Welcome' ? !!$scope.layer : i < $scope.pages.length - 1;
      $scope.buttonsEnabled.back = i > 0;
      $scope.buttonsEnabled.finish = !!$scope.layer;
    }
    if ($scope.page === 'Scale') {
      initExpSlider('.scale-factor .btn', 'scaleFactor', 1);
    }
    if ($scope.page === 'Date Time') {
      initExpSlider('.time-decay .btn', 'decay', 16);
    }
  };
  $scope.setPage = function (p) {
    $scope.page = p;
    calcButtonState();
  }
  calcButtonState();
  $scope.next = function () {
    var i = $scope.pages.indexOf($scope.page);
    $scope.page = $scope.pages[i + 1];
    calcButtonState();
  };
  $scope.back = function () {
    var i = $scope.pages.indexOf($scope.page);
    $scope.page = $scope.pages[i - 1];
    calcButtonState();
  };
  $scope.finish = function () {
    $scope.layer.version++;
    $scope.dialog.OK($scope.layer);
  };
}]);
<|endoftext|>


<commit_before>
var RG = require('./rg.js');

RG.Object = {};

RG.Object.Defense = function() {

    var _attack = 1;
    var _defense = 1;
    var _protection = 0;

    this.getAttack = function() {return _attack;};
    this.setAttack = function(attack) { _attack = attack; };

    /* Defense related methods.*/
    this.getDefense = function() { return _defense; };
    this.setDefense = function(defense) { _defense = defense; };

    this.getProtection = function() {return _protection;};
    this.setProtection = function(prot) {_protection = prot;};

};

RG.Object.Defense.prototype.copy = function(rhs) {
    this.setAttack(rhs.getAttack());
    this.setDefense(rhs.getDefense());
    this.setProtection(rhs.getProtection());
};

RG.Object.Defense.prototype.equals = function(rhs) {
    var res = this.getAttack() === rhs.getAttack() &&
        this.getDefense() === rhs.getDefense() &&
        this.getProtection() === rhs.getProtection();
    return res;
};

RG.Object.Defense.prototype.toJSON = function() {
    var json = {
        setAttack: this.getAttack(),
        setDefense: this.getDefense(),
        setProtection: this.getProtection()
    };
    return json;
};

RG.Object.Damage = function() {
    RG.Object.Defense.call(this);

    var _damage = new RG.Die(1, 4, 0);
    var _range = 1;

    /* Attack methods. */
    this.setAttackRange = function(range) {_range = range;};
    this.getAttackRange = function() {return _range; };

    this.setDamage = function(dStr) {
        if (typeof dStr === 'string') {
            _damage = RG.FACT.createDie(dStr);
        }
        else if (typeof dStr === 'object') {
            _damage = dStr;
        }
    };

    this.getDamage = function() {
        if (this.hasOwnProperty('getWeapon')) {
            var weapon = this.getWeapon();
            if (!RG.isNullOrUndef([weapon])) {
                return weapon.getDamage();
            }
        }
        return _damage.roll();
    };

    this.getDamageDie = function() {
        return _damage;
    };

    this.setDamageDie = function(str) {
        this.setDamage(str);
    };

};
RG.extend2(RG.Object.Damage, RG.Object.Defense);

RG.Object.Damage.prototype.copy = function(rhs) {
    RG.Object.Defense.prototype.copy.call(this, rhs);
    this.setAttackRange(rhs.getAttackRange());
    var die = new RG.Die();
    die.copy(rhs.getDamageDie());
    this.setDamage(die);
};

RG.Object.Damage.prototype.equals = function(rhs) {
    var res = RG.Object.Defense.prototype.equals.call(this, rhs);
    if (res) {
        res = this.getDamageDie().equals(rhs.getDamageDie());
        res = res && this.getAttackRange() === rhs.getAttackRange();
    }
    return res;
};

RG.Object.Damage.prototype.toString = function() {
    var msg = ' A: ' + this.getAttack() + ', D: ' + this.getDefense() + ', ';
    msg += 'Dmg: ' + this.getDamageDie().toString();
    msg += ',R:' + this.getAttackRange();
    return msg;
};

RG.Object.Damage.prototype.toJSON = function() {
    var json = RG.Object.Defense.prototype.toJSON.call(this);
    json.setAttackRange = this.getAttackRange();
    json.setDamage = this.getDamageDie().toString();
    return json;
};

/* Typed objects should inherit from this. */
RG.Object.Typed = function(propType, type) {
    this.type = type;
    this._propType = propType;

};

    RG.Object.Typed.prototype.getPropType = function() {return this._propType;};
RG.Object.Typed.prototype.getType = function() {return this.type;};

RG.Object.Typed.prototype.setPropType = function(propType) {
    var index = RG.PROP_TYPES.indexOf(propType);
    if (index >= 0) {
        this._propType = propType;
    }
    else {
        RG.err('Object.Typed', 'setPropType',
            'Unknown prop type: |' + propType + '|');
    }
};

RG.Object.Typed.prototype.setType = function(type) {
    this.type = type;
    RG.nullOrUndefError('Object.Typed: setType', 'arg |type|', type);
};

/* This object is used by all locatable objects in the game.  */
RG.Object.Locatable = function() { // {{{2
    RG.Object.Typed.call(this, null);
    this._x = null;
    this._y = null;
    this._level = null;

}; // }}} Object.Locatable
RG.extend2(RG.Object.Locatable, RG.Object.Typed);

    RG.Object.Locatable.prototype.setX = function(x) {this._x = x; };
    RG.Object.Locatable.prototype.setY = function(y) {this._y = y; };

    RG.Object.Locatable.prototype.getX = function() {return this._x;};
    RG.Object.Locatable.prototype.getY = function() {return this._y;};

    RG.Object.Locatable.prototype.getXY = function() {
        return [this._x, this._y];
    };

    /* Simple getters/setters for coordinates.*/
    RG.Object.Locatable.prototype.setXY = function(x, y) {
        this._x = x;
        this._y = y;
    };

/* Sets the level of this locatable object.*/
RG.Object.Locatable.prototype.setLevel = function(level) {
    this._level = level;
    RG.nullOrUndefError('Object.Locatable: setLevel', 'arg |level|', level);
};

/* Unsets the level to null. Throws error if level already null. */
RG.Object.Locatable.prototype.unsetLevel = function() {
    if (this._level) {
        this._level = null;
    }
    else {
        RG.err('Object.Locatable', 'unsetLevel',
            'Trying to unset already null level.');
    }
};

RG.Object.Locatable.prototype.getLevel = function() {
    return this._level;
};

/* Returns true if object is located at a position on a level.*/
RG.Object.Locatable.prototype.isLocated = function() {
    return (this._x !== null) && (this._y !== null) && (this._level !== null);
};

/* Returns true if locatables are in same position.*/
RG.Object.Locatable.prototype.isSamePos = function(obj) {
    if (this._x !== obj.getX()) {return false;}
    if (this._y !== obj.getY()) {return false;}
    if (this._level !== obj.getLevel()) {return false;}
    return true;
};

/* Object.Ownable moves with its owner. Thus, it's x-y position is
 * determined by the owner. This ensures that
 * for example item coordinates are up-to-date with the carrier.*/
RG.Object.Ownable = function(owner) {
    RG.Object.Typed.call(this, null);
    var _owner = owner;

    this.isSamePos = function(obj) {return _owner.isSamePos(obj);};

    this.getLevel = function() {return _owner.getLevel();};

    this.setOwner = function(owner) {
        if (RG.isNullOrUndef([owner])) {
            RG.err('Object.Ownable', 'setOwner', 'Owner cannot be null.');
        }
        else {
            _owner = owner;
        }
    };

    /* Returns the owner of this object.*/
    this.getOwner = function() {return _owner;};

    this.getX = function() {
        if (_owner !== null) {return _owner.getX();}
        return null;
    };

    this.getY = function() {
        if (_owner !== null) {return _owner.getY();}
        return null;
    };

    this.getLevel = function() {
        if (_owner !== null) {return _owner.getLevel();}
        return null;
    };

};
RG.extend2(RG.Object.Ownable, RG.Object.Typed);

module.exports = RG.Object;
<commit_msg>Added getCell for Locatable.<commit_after>
var RG = require('./rg.js');

RG.Object = {};

RG.Object.Defense = function() {

    var _attack = 1;
    var _defense = 1;
    var _protection = 0;

    this.getAttack = function() {return _attack;};
    this.setAttack = function(attack) { _attack = attack; };

    /* Defense related methods.*/
    this.getDefense = function() { return _defense; };
    this.setDefense = function(defense) { _defense = defense; };

    this.getProtection = function() {return _protection;};
    this.setProtection = function(prot) {_protection = prot;};

};

RG.Object.Defense.prototype.copy = function(rhs) {
    this.setAttack(rhs.getAttack());
    this.setDefense(rhs.getDefense());
    this.setProtection(rhs.getProtection());
};

RG.Object.Defense.prototype.equals = function(rhs) {
    var res = this.getAttack() === rhs.getAttack() &&
        this.getDefense() === rhs.getDefense() &&
        this.getProtection() === rhs.getProtection();
    return res;
};

RG.Object.Defense.prototype.toJSON = function() {
    var json = {
        setAttack: this.getAttack(),
        setDefense: this.getDefense(),
        setProtection: this.getProtection()
    };
    return json;
};

RG.Object.Damage = function() {
    RG.Object.Defense.call(this);
    let _damage = new RG.Die(1, 4, 0);
    let _range = 1;

    /* Attack methods. */
    this.setAttackRange = function(range) {_range = range;};
    this.getAttackRange = function() {return _range; };

    this.setDamage = function(dStr) {
        if (typeof dStr === 'string') {
            _damage = RG.FACT.createDie(dStr);
        }
        else if (typeof dStr === 'object') {
            _damage = dStr;
        }
    };

    this.getDamage = function() {
        if (this.hasOwnProperty('getWeapon')) {
            const weapon = this.getWeapon();
            if (!RG.isNullOrUndef([weapon])) {
                return weapon.getDamage();
            }
        }
        return _damage.roll();
    };

    this.getDamageDie = function() {
        return _damage;
    };

    this.setDamageDie = function(str) {
        this.setDamage(str);
    };

};
RG.extend2(RG.Object.Damage, RG.Object.Defense);

RG.Object.Damage.prototype.copy = function(rhs) {
    RG.Object.Defense.prototype.copy.call(this, rhs);
    this.setAttackRange(rhs.getAttackRange());
    const die = new RG.Die();
    die.copy(rhs.getDamageDie());
    this.setDamage(die);
};

RG.Object.Damage.prototype.equals = function(rhs) {
    var res = RG.Object.Defense.prototype.equals.call(this, rhs);
    if (res) {
        res = this.getDamageDie().equals(rhs.getDamageDie());
        res = res && this.getAttackRange() === rhs.getAttackRange();
    }
    return res;
};

RG.Object.Damage.prototype.toString = function() {
    var msg = ' A: ' + this.getAttack() + ', D: ' + this.getDefense() + ', ';
    msg += 'Dmg: ' + this.getDamageDie().toString();
    msg += ',R:' + this.getAttackRange();
    return msg;
};

RG.Object.Damage.prototype.toJSON = function() {
    var json = RG.Object.Defense.prototype.toJSON.call(this);
    json.setAttackRange = this.getAttackRange();
    json.setDamage = this.getDamageDie().toString();
    return json;
};

/* Typed objects should inherit from this. */
RG.Object.Typed = function(propType, type) {
    this.type = type;
    this._propType = propType;

};

    RG.Object.Typed.prototype.getPropType = function() {return this._propType;};
RG.Object.Typed.prototype.getType = function() {return this.type;};

RG.Object.Typed.prototype.setPropType = function(propType) {
    var index = RG.PROP_TYPES.indexOf(propType);
    if (index >= 0) {
        this._propType = propType;
    }
    else {
        RG.err('Object.Typed', 'setPropType',
            'Unknown prop type: |' + propType + '|');
    }
};

RG.Object.Typed.prototype.setType = function(type) {
    this.type = type;
    RG.nullOrUndefError('Object.Typed: setType', 'arg |type|', type);
};

/* This object is used by all locatable objects in the game.  */
RG.Object.Locatable = function() { // {{{2
    RG.Object.Typed.call(this, null);
    this._x = null;
    this._y = null;
    this._level = null;

}; // }}} Object.Locatable
RG.extend2(RG.Object.Locatable, RG.Object.Typed);

RG.Object.Locatable.prototype.setX = function(x) {this._x = x; };
RG.Object.Locatable.prototype.setY = function(y) {this._y = y; };

RG.Object.Locatable.prototype.getX = function() {return this._x;};
RG.Object.Locatable.prototype.getY = function() {return this._y;};

RG.Object.Locatable.prototype.getXY = function() {
    return [this._x, this._y];
};

/* Simple getters/setters for coordinates.*/
RG.Object.Locatable.prototype.setXY = function(x, y) {
    this._x = x;
    this._y = y;
};

RG.Object.Locatable.prototype.getCell = function() {
    return this._level.getMap().getCell(this._x, this._y);
};

/* Sets the level of this locatable object.*/
RG.Object.Locatable.prototype.setLevel = function(level) {
    this._level = level;
    RG.nullOrUndefError('Object.Locatable: setLevel', 'arg |level|', level);
};

/* Unsets the level to null. Throws error if level already null. */
RG.Object.Locatable.prototype.unsetLevel = function() {
    if (this._level) {
        this._level = null;
    }
    else {
        RG.err('Object.Locatable', 'unsetLevel',
            'Trying to unset already null level.');
    }
};

RG.Object.Locatable.prototype.getLevel = function() {
    return this._level;
};

/* Returns true if object is located at a position on a level.*/
RG.Object.Locatable.prototype.isLocated = function() {
    return (this._x !== null) && (this._y !== null) && (this._level !== null);
};

/* Returns true if locatables are in same position.*/
RG.Object.Locatable.prototype.isSamePos = function(obj) {
    if (this._x !== obj.getX()) {return false;}
    if (this._y !== obj.getY()) {return false;}
    if (this._level !== obj.getLevel()) {return false;}
    return true;
};

/* Object.Ownable moves with its owner. Thus, it's x-y position is
 * determined by the owner. This ensures that
 * for example item coordinates are up-to-date with the carrier.*/
RG.Object.Ownable = function(owner) {
    RG.Object.Typed.call(this, null);
    let _owner = owner;

    this.isSamePos = function(obj) {return _owner.isSamePos(obj);};

    this.getLevel = function() {return _owner.getLevel();};

    this.setOwner = function(owner) {
        if (RG.isNullOrUndef([owner])) {
            RG.err('Object.Ownable', 'setOwner', 'Owner cannot be null.');
        }
        else {
            _owner = owner;
        }
    };

    /* Returns the owner of this object.*/
    this.getOwner = function() {return _owner;};

    this.getX = function() {
        if (_owner !== null) {return _owner.getX();}
        return null;
    };

    this.getY = function() {
        if (_owner !== null) {return _owner.getY();}
        return null;
    };

    this.getLevel = function() {
        if (_owner !== null) {return _owner.getLevel();}
        return null;
    };

};
RG.extend2(RG.Object.Ownable, RG.Object.Typed);

module.exports = RG.Object;
<|endoftext|>


<commit_before>import UserService from 'services/UserService';

const service = new UserService({ apiURL: process.env.CONTROL_TOWER_URL });

/**
 * CONSTANTS
*/
const SET_USER = 'user/SET_USER';
const SET_USER_FAVOURITES = 'user/SET_USER_FAVOURITES';
const SET_USER_FAVOURITES_LOADING = 'user/SET_USER_FAVOURITES_LOADING';
const SET_USER_FAVOURITES_ERROR = 'user/SET_USER_FAVOURITES_ERROR';

/**
 * REDUCER
*/
const initialState = {
  favourites: []
};

export default function (state = initialState, action) {
  switch (action.type) {
    case SET_USER: {
      return Object.assign({}, state, action.payload);
    }

    case SET_USER_FAVOURITES: {
      return Object.assign({}, state, { favourites: action.payload });
    }

    default:
      return state;
  }
}

/**
 * ACTIONS
 * - setUser
 * - setFavourites
 * - toggleFavourite
*/
export function setUser(user) {
  return (dispatch) => {
    if (!user) {
      // If the user isn't logged in, we set the user variable as an empty object
      return;
    }

    const userObj = { ...user };
    if (userObj.token) {
      userObj.token = userObj.token.includes('Bearer') ? userObj.token : `Bearer ${userObj.token}`;
    }

    dispatch({ type: SET_USER, payload: userObj });

    // We must return it because it's a promise
    return dispatch(setFavourites());
  };
}

// FAVOURITES
export function setFavouriteLoading(payload) {
  return { type: SET_USER_FAVOURITES_LOADING, payload };
}

export function setFavouriteError(payload) {
  return { type: SET_USER_FAVOURITES_ERROR, payload };
}

export function setFavourites() {
  return (dispatch, getState) => {
    const { user } = getState();

    return service.setFavourites(user.token)
      .then(({ data }) => {
        dispatch({ type: SET_USER_FAVOURITES, payload: data });
      })
      .catch(() => {
        dispatch({ type: SET_USER_FAVOURITES, payload: [] });
      });
  };
}

export function toggleFavourite({ favourite = {}, resource, user }) {
  return (dispatch) => {
    if (favourite.id) {
      return service.deleteFavourite(favourite.id, user.token)
        .then(() => dispatch(setFavourites()))
        .catch((err) => {
          console.error(err);
        });
    }

    return service.createFavourite(resource.type, resource.id, user.token)
      .then(() => dispatch(setFavourites()))
      .catch((err) => {
        console.error(err);
      });
  };
}
<commit_msg>fix check to see if user is logged in or not<commit_after>import UserService from 'services/UserService';

const service = new UserService({ apiURL: process.env.CONTROL_TOWER_URL });

/**
 * CONSTANTS
*/
const SET_USER = 'user/SET_USER';
const SET_USER_FAVOURITES = 'user/SET_USER_FAVOURITES';
const SET_USER_FAVOURITES_LOADING = 'user/SET_USER_FAVOURITES_LOADING';
const SET_USER_FAVOURITES_ERROR = 'user/SET_USER_FAVOURITES_ERROR';

/**
 * REDUCER
*/
const initialState = {
  favourites: []
};

export default function (state = initialState, action) {
  switch (action.type) {
    case SET_USER: {
      return Object.assign({}, state, action.payload);
    }

    case SET_USER_FAVOURITES: {
      return Object.assign({}, state, { favourites: action.payload });
    }

    default:
      return state;
  }
}

/**
 * ACTIONS
 * - setUser
 * - setFavourites
 * - toggleFavourite
*/
export function setUser(user) {
  return (dispatch) => {
    if (!user || !user.id) {
      // If the user isn't logged in, we set the user variable as an empty object
      return;
    }

    const userObj = { ...user };
    if (userObj.token) {
      userObj.token = userObj.token.includes('Bearer') ? userObj.token : `Bearer ${userObj.token}`;
    }

    dispatch({ type: SET_USER, payload: userObj });

    // We must return it because it's a promise
    return dispatch(setFavourites());
  };
}

// FAVOURITES
export function setFavouriteLoading(payload) {
  return { type: SET_USER_FAVOURITES_LOADING, payload };
}

export function setFavouriteError(payload) {
  return { type: SET_USER_FAVOURITES_ERROR, payload };
}

export function setFavourites() {
  return (dispatch, getState) => {
    const { user } = getState();

    return service.setFavourites(user.token)
      .then(({ data }) => {
        dispatch({ type: SET_USER_FAVOURITES, payload: data });
      })
      .catch(() => {
        dispatch({ type: SET_USER_FAVOURITES, payload: [] });
      });
  };
}

export function toggleFavourite({ favourite = {}, resource, user }) {
  return (dispatch) => {
    if (favourite.id) {
      return service.deleteFavourite(favourite.id, user.token)
        .then(() => dispatch(setFavourites()))
        .catch((err) => {
          console.error(err);
        });
    }

    return service.createFavourite(resource.type, resource.id, user.token)
      .then(() => dispatch(setFavourites()))
      .catch((err) => {
        console.error(err);
      });
  };
}
<|endoftext|>