<commit_before>var __ = require('underscore');
var util = require('util');

var utils = require('../../../util/utils');
var $ = utils.getLocaleString;

function VirtualMachine(cli, serviceClients, resourceGroupName, params) {
  this.cli = cli;
  this.serviceClients = serviceClients;
  this.resourceGroupName = resourceGroupName;
  this.params = params;
}

__.extend(VirtualMachine.prototype, {
  getVMByIdExpanded: function (referenceUri, depth, memoize, dependencies, _) {
    referenceUri = referenceUri.toLowerCase();
    if (memoize[referenceUri]) {
      return memoize[referenceUri];
    }

    var resourceInfo = utils.parseResourceReferenceUri(referenceUri);
    var expandedVM = this.getVMByNameExpanded(resourceInfo.resourceGroupName, resourceInfo.resourceName, depth, memoize, dependencies, _);
    return expandedVM;
  },

  getVMByNameExpanded: function (resourceGroupName, vmName, depth, memoize, dependencies, _) {
    var vm = this.getVM(resourceGroupName, vmName, _);
    var expandedVM = this._expandVM(vm, depth, memoize, dependencies, _);
    return expandedVM;
  },

  getVMById: function (referenceUri, _) {
    var resourceInfo = utils.parseResourceReferenceUri(referenceUri);
    return this.getVM(resourceInfo.resourceGroupName, resourceInfo.resourceName, _);
  },

  getVM: function (resourceGroupName, vmName, _) {
    var progress = this.cli.interaction.progress(util.format($('Looking up the VM "%s"'), vmName));
    try {
      var virtualMachine = this.serviceClients.computeManagementClient.virtualMachines.get(resourceGroupName, vmName, _);
      return virtualMachine;
    } catch (e) {
      if (e.code === 'ResourceNotFound') {
        return null;
      }
      throw e;
    } finally {
      progress.end();
    }
  },

  getVMList: function (resourceGroupName, _) {
    var vms;
    var progress = this.cli.interaction.progress($('Getting virtual machines'));
    try {
      vms = this.serviceClients.computeManagementClient.virtualMachines.list(resourceGroupName, _);
    } finally {
      progress.end();
    }

    return vms;
  },

  deleteVM: function (resourceGroupName, vmName, _) {
    var progress = this.cli.interaction.progress(util.format($('Deleting the virtual machine "%s"'), vmName));
    try {
      this.serviceClients.computeManagementClient.virtualMachines.deleteMethod(resourceGroupName, vmName, _);
    } finally {
      progress.end();
    }
  },

  stopVM: function (resourceGroupName, vmName, _) {
    var progress = this.cli.interaction.progress(util.format($('Stopping the virtual machine "%s"'), vmName));
    try {
      this.serviceClients.computeManagementClient.virtualMachines.stop(resourceGroupName, vmName, _);
    } finally {
      progress.end();
    }
  },

  restartVM: function (resourceGroupName, vmName, _) {
    var progress = this.cli.interaction.progress(util.format($('Restarting the virtual machine "%s"'), vmName));
    try {
      this.serviceClients.computeManagementClient.virtualMachines.restart(resourceGroupName, vmName, _);
    } finally {
      progress.end();
    }
  },

  startVM: function (resourceGroupName, vmName, _) {
    var progress = this.cli.interaction.progress(util.format($('Starting the virtual machine "%s"'), vmName));
    try {
      this.serviceClients.computeManagementClient.virtualMachines.start(resourceGroupName, vmName, _);
    } finally {
      progress.end();
    }
  },

  deallocateVM: function (resourceGroupName, vmName, _) {
    var progress = this.cli.interaction.progress(util.format($('Deallocating the virtual machine "%s"'), vmName));
    try {
      this.serviceClients.computeManagementClient.virtualMachines.deallocate(resourceGroupName, vmName, _);
    } finally {
      progress.end();
    }
  },

  captureVM: function (resourceGroupName, vmName, params, _) {
    var progress = this.cli.interaction.progress(util.format($('Capturing the virtual machine "%s"'), vmName));
    try {
      var result = this.serviceClients.computeManagementClient.virtualMachines.capture(resourceGroupName, vmName, params, _);
      return result;
    } finally {
      progress.end();
    }
  },

  generalizeVM: function (resourceGroupName, vmName, _) {
    var progress = this.cli.interaction.progress(util.format($('Generalizing the virtual machine "%s"'), vmName));
    try {
      this.serviceClients.computeManagementClient.virtualMachines.generalize(resourceGroupName, vmName, _);
    } finally {
      progress.end();
    }
  },

  getInstanceView: function (resourceGroupName, vmName, _) {
    var progress = this.cli.interaction.progress(util.format($('Getting instance view of virtual machine "%s"'), vmName));
    try {
      var result = this.serviceClients.computeManagementClient.virtualMachines.getWithInstanceView(resourceGroupName, vmName, _);
      return result;
    } catch (e) {
      if (e.code === 'ResourceNotFound') {
        return null;
      }
      throw e;
    } finally {
      progress.end();
    }
  },

  createOrUpdateVM: function (resourceGroupName, virtualMachine, isNewVM, _) {
    var progressMessage = util.format($('%s VM "%s"'), (isNewVM ? 'Creating' : 'Updating'), virtualMachine.name);
    var progress = this.cli.interaction.progress(progressMessage);
    try {
      if (!isNewVM) {
        // In it's current version Azure API throws an error if we try to update this fields.
        // They were not set by user, but returned using 'vm get' command.
        if (virtualMachine.resources) {
          delete virtualMachine.resources;
        }
        if (virtualMachine.oSProfile.windowsConfiguration && virtualMachine.oSProfile.windowsConfiguration.additionalUnattendContents) {
          delete virtualMachine.oSProfile.windowsConfiguration.additionalUnattendContents;
        }
        if (virtualMachine.extensions) {
          delete virtualMachine.extensions;
        }
      }

      var vmResult = this.serviceClients.computeManagementClient.virtualMachines.createOrUpdate(resourceGroupName, virtualMachine, _);
      if (vmResult.error) {
        throw new Error(util.format($('VM has been created or updated, but there was an error during provisioning. Error: %s'), vmResult.error.message));
      }
      return vmResult;
    } finally {
      progress.end();
    }
  },

  getVMSizesByVMName: function (resourceGroupName, vmName, _) {
    var sizeResult;
    var progress = this.cli.interaction.progress(util.format($('Getting virtual machine sizes available for the VM "%s"'), vmName));
    try {
      sizeResult = this.serviceClients.computeManagementClient.virtualMachines.listAvailableSizes(resourceGroupName, vmName, _);
    } finally {
      progress.end();
    }

    return sizeResult;
  },

  getVMSizesByLocationName: function (location, _) {
    var sizeResult;
    var progress = this.cli.interaction.progress(util.format($('Listing virtual machine sizes available in the location "%s"'), location));
    try {
      sizeResult = this.serviceClients.computeManagementClient.virtualMachineSizes.list(location, _);
    } finally {
      progress.end();
    }

    return sizeResult;
  },

  getVMExtension: function (resourceGroupName, vmName, extensionName, _) {
    var progress = this.cli.interaction.progress(util.format($('Looking up extension "%s", VM: "%s"'), extensionName, vmName));
    try {
      var result = this.serviceClients.computeManagementClient.virtualMachineExtensions.getInstanceView(resourceGroupName, vmName, extensionName, _);
      return result;
    } catch (e) {
      if (e.code === 'ResourceNotFound') {
        return null;
      }
      throw e;
    } finally {
      progress.end();
    }
  },

  createOrUpdateVMExtension: function (resourceGroupName, vmName, vmExtension, isNewExtension, _) {
    var progressMessage = util.format($('%s extension "%s", VM: "%s"'), (isNewExtension ? 'Installing' : 'Updating'), vmExtension.name, vmName);
    var progress = this.cli.interaction.progress(progressMessage);
    try {
      var result = this.serviceClients.computeManagementClient.virtualMachineExtensions.createOrUpdate(resourceGroupName, vmName, vmExtension, _);
      return result;
    } finally {
      progress.end();
    }
  },

  deleteVMExtension: function (resourceGroupName, vmName, extensionName, _) {
   var progress = this.cli.interaction.progress(util.format($('Uninstalling extension "%s", VM: "%s"'), extensionName, vmName));
    try {
      var result = this.serviceClients.computeManagementClient.virtualMachineExtensions.deleteMethod(resourceGroupName, vmName, extensionName, _);
      return result;
    } finally {
      progress.end();
    }
  },

  _expandVM: function (vm, depth, memoize, dependencies, _) {
    if (depth === 0 || vm === null) {
      return vm;
    }

    if (depth !== -1) {
      depth--;
    }

    var virtualMachine = vm.virtualMachine;
    var referenceUri = virtualMachine.id.toLowerCase();
    memoize[referenceUri] = vm;

    if (utils.hasValidProperty(virtualMachine, 'networkProfile')) {
      var networkProfile = virtualMachine.networkProfile;
      if (networkProfile.networkInterfaces instanceof  Array) {
        for (var i = 0; i < networkProfile.networkInterfaces.length; i++) {
          var networkInterface = networkProfile.networkInterfaces[i];
          var netReferenceUri = networkInterface.referenceUri.toLocaleLowerCase();
          if (!memoize[netReferenceUri]) {
            // expand related resource only if it is not expanded before in the chain
            networkInterface.expanded = dependencies.networkNic.getNICByIdExpanded(netReferenceUri, depth, memoize, dependencies, _);
          }
        }
      }
    }

    if (utils.hasValidProperty(virtualMachine, 'availabilitySetReference')) {
      var availabilitySetRef = virtualMachine.availabilitySetReference;
      if (availabilitySetRef.referenceUri !== null && availabilitySetRef.referenceUri !== undefined) {
        var availReferenceUri = availabilitySetRef.referenceUri.toLocaleLowerCase();
        if (!memoize[availReferenceUri]) {
          // expand related resource only if it is not expanded before in the chain
          availabilitySetRef.expanded = dependencies.availabilitySet.getAvailSetByIdExpanded(availReferenceUri, depth, memoize, dependencies, _);
        }
      }
    }

    return memoize[referenceUri];
  }
});

module.exports = VirtualMachine;<commit_msg>Fixing issue https://github.com/MSOpenTech/azure-xplat-cli-pr/issues/392<commit_after>var __ = require('underscore');
var util = require('util');

var utils = require('../../../util/utils');
var $ = utils.getLocaleString;

function VirtualMachine(cli, serviceClients, resourceGroupName, params) {
  this.cli = cli;
  this.serviceClients = serviceClients;
  this.resourceGroupName = resourceGroupName;
  this.params = params;
}

__.extend(VirtualMachine.prototype, {
  getVMByIdExpanded: function (referenceUri, depth, memoize, dependencies, _) {
    referenceUri = referenceUri.toLowerCase();
    if (memoize[referenceUri]) {
      return memoize[referenceUri];
    }

    var resourceInfo = utils.parseResourceReferenceUri(referenceUri);
    var expandedVM = this.getVMByNameExpanded(resourceInfo.resourceGroupName, resourceInfo.resourceName, depth, memoize, dependencies, _);
    return expandedVM;
  },

  getVMByNameExpanded: function (resourceGroupName, vmName, depth, memoize, dependencies, _) {
    var vm = this.getVM(resourceGroupName, vmName, _);
    var expandedVM = this._expandVM(vm, depth, memoize, dependencies, _);
    return expandedVM;
  },

  getVMById: function (referenceUri, _) {
    var resourceInfo = utils.parseResourceReferenceUri(referenceUri);
    return this.getVM(resourceInfo.resourceGroupName, resourceInfo.resourceName, _);
  },

  getVM: function (resourceGroupName, vmName, _) {
    var progress = this.cli.interaction.progress(util.format($('Looking up the VM "%s"'), vmName));
    try {
      var virtualMachine = this.serviceClients.computeManagementClient.virtualMachines.get(resourceGroupName, vmName, _);
      return virtualMachine;
    } catch (e) {
      if (e.code === 'ResourceNotFound') {
        return null;
      }
      throw e;
    } finally {
      progress.end();
    }
  },

  getVMList: function (resourceGroupName, _) {
    var vms;
    var progress = this.cli.interaction.progress($('Getting virtual machines'));
    try {
      vms = this.serviceClients.computeManagementClient.virtualMachines.list(resourceGroupName, _);
    } finally {
      progress.end();
    }

    return vms;
  },

  deleteVM: function (resourceGroupName, vmName, _) {
    var progress = this.cli.interaction.progress(util.format($('Deleting the virtual machine "%s"'), vmName));
    try {
      this.serviceClients.computeManagementClient.virtualMachines.deleteMethod(resourceGroupName, vmName, _);
    } finally {
      progress.end();
    }
  },

  stopVM: function (resourceGroupName, vmName, _) {
    var progress = this.cli.interaction.progress(util.format($('Stopping the virtual machine "%s"'), vmName));
    try {
      this.serviceClients.computeManagementClient.virtualMachines.powerOff(resourceGroupName, vmName, _);
    } finally {
      progress.end();
    }
  },

  restartVM: function (resourceGroupName, vmName, _) {
    var progress = this.cli.interaction.progress(util.format($('Restarting the virtual machine "%s"'), vmName));
    try {
      this.serviceClients.computeManagementClient.virtualMachines.restart(resourceGroupName, vmName, _);
    } finally {
      progress.end();
    }
  },

  startVM: function (resourceGroupName, vmName, _) {
    var progress = this.cli.interaction.progress(util.format($('Starting the virtual machine "%s"'), vmName));
    try {
      this.serviceClients.computeManagementClient.virtualMachines.start(resourceGroupName, vmName, _);
    } finally {
      progress.end();
    }
  },

  deallocateVM: function (resourceGroupName, vmName, _) {
    var progress = this.cli.interaction.progress(util.format($('Deallocating the virtual machine "%s"'), vmName));
    try {
      this.serviceClients.computeManagementClient.virtualMachines.deallocate(resourceGroupName, vmName, _);
    } finally {
      progress.end();
    }
  },

  captureVM: function (resourceGroupName, vmName, params, _) {
    var progress = this.cli.interaction.progress(util.format($('Capturing the virtual machine "%s"'), vmName));
    try {
      var result = this.serviceClients.computeManagementClient.virtualMachines.capture(resourceGroupName, vmName, params, _);
      return result;
    } finally {
      progress.end();
    }
  },

  generalizeVM: function (resourceGroupName, vmName, _) {
    var progress = this.cli.interaction.progress(util.format($('Generalizing the virtual machine "%s"'), vmName));
    try {
      this.serviceClients.computeManagementClient.virtualMachines.generalize(resourceGroupName, vmName, _);
    } finally {
      progress.end();
    }
  },

  getInstanceView: function (resourceGroupName, vmName, _) {
    var progress = this.cli.interaction.progress(util.format($('Getting instance view of virtual machine "%s"'), vmName));
    try {
      var result = this.serviceClients.computeManagementClient.virtualMachines.getWithInstanceView(resourceGroupName, vmName, _);
      return result;
    } catch (e) {
      if (e.code === 'ResourceNotFound') {
        return null;
      }
      throw e;
    } finally {
      progress.end();
    }
  },

  createOrUpdateVM: function (resourceGroupName, virtualMachine, isNewVM, _) {
    var progressMessage = util.format($('%s VM "%s"'), (isNewVM ? 'Creating' : 'Updating'), virtualMachine.name);
    var progress = this.cli.interaction.progress(progressMessage);
    try {
      if (!isNewVM) {
        // In it's current version Azure API throws an error if we try to update this fields.
        // They were not set by user, but returned using 'vm get' command.
        if (virtualMachine.resources) {
          delete virtualMachine.resources;
        }
        if (virtualMachine.oSProfile.windowsConfiguration && virtualMachine.oSProfile.windowsConfiguration.additionalUnattendContents) {
          delete virtualMachine.oSProfile.windowsConfiguration.additionalUnattendContents;
        }
        if (virtualMachine.extensions) {
          delete virtualMachine.extensions;
        }
      }

      var vmResult = this.serviceClients.computeManagementClient.virtualMachines.createOrUpdate(resourceGroupName, virtualMachine, _);
      if (vmResult.error) {
        throw new Error(util.format($('VM has been created or updated, but there was an error during provisioning. Error: %s'), vmResult.error.message));
      }
      return vmResult;
    } finally {
      progress.end();
    }
  },

  getVMSizesByVMName: function (resourceGroupName, vmName, _) {
    var sizeResult;
    var progress = this.cli.interaction.progress(util.format($('Getting virtual machine sizes available for the VM "%s"'), vmName));
    try {
      sizeResult = this.serviceClients.computeManagementClient.virtualMachines.listAvailableSizes(resourceGroupName, vmName, _);
    } finally {
      progress.end();
    }

    return sizeResult;
  },

  getVMSizesByLocationName: function (location, _) {
    var sizeResult;
    var progress = this.cli.interaction.progress(util.format($('Listing virtual machine sizes available in the location "%s"'), location));
    try {
      sizeResult = this.serviceClients.computeManagementClient.virtualMachineSizes.list(location, _);
    } finally {
      progress.end();
    }

    return sizeResult;
  },

  getVMExtension: function (resourceGroupName, vmName, extensionName, _) {
    var progress = this.cli.interaction.progress(util.format($('Looking up extension "%s", VM: "%s"'), extensionName, vmName));
    try {
      var result = this.serviceClients.computeManagementClient.virtualMachineExtensions.getInstanceView(resourceGroupName, vmName, extensionName, _);
      return result;
    } catch (e) {
      if (e.code === 'ResourceNotFound') {
        return null;
      }
      throw e;
    } finally {
      progress.end();
    }
  },

  createOrUpdateVMExtension: function (resourceGroupName, vmName, vmExtension, isNewExtension, _) {
    var progressMessage = util.format($('%s extension "%s", VM: "%s"'), (isNewExtension ? 'Installing' : 'Updating'), vmExtension.name, vmName);
    var progress = this.cli.interaction.progress(progressMessage);
    try {
      var result = this.serviceClients.computeManagementClient.virtualMachineExtensions.createOrUpdate(resourceGroupName, vmName, vmExtension, _);
      return result;
    } finally {
      progress.end();
    }
  },

  deleteVMExtension: function (resourceGroupName, vmName, extensionName, _) {
   var progress = this.cli.interaction.progress(util.format($('Uninstalling extension "%s", VM: "%s"'), extensionName, vmName));
    try {
      var result = this.serviceClients.computeManagementClient.virtualMachineExtensions.deleteMethod(resourceGroupName, vmName, extensionName, _);
      return result;
    } finally {
      progress.end();
    }
  },

  _expandVM: function (vm, depth, memoize, dependencies, _) {
    if (depth === 0 || vm === null) {
      return vm;
    }

    if (depth !== -1) {
      depth--;
    }

    var virtualMachine = vm.virtualMachine;
    var referenceUri = virtualMachine.id.toLowerCase();
    memoize[referenceUri] = vm;

    if (utils.hasValidProperty(virtualMachine, 'networkProfile')) {
      var networkProfile = virtualMachine.networkProfile;
      if (networkProfile.networkInterfaces instanceof  Array) {
        for (var i = 0; i < networkProfile.networkInterfaces.length; i++) {
          var networkInterface = networkProfile.networkInterfaces[i];
          var netReferenceUri = networkInterface.referenceUri.toLocaleLowerCase();
          if (!memoize[netReferenceUri]) {
            // expand related resource only if it is not expanded before in the chain
            networkInterface.expanded = dependencies.networkNic.getNICByIdExpanded(netReferenceUri, depth, memoize, dependencies, _);
          }
        }
      }
    }

    if (utils.hasValidProperty(virtualMachine, 'availabilitySetReference')) {
      var availabilitySetRef = virtualMachine.availabilitySetReference;
      if (availabilitySetRef.referenceUri !== null && availabilitySetRef.referenceUri !== undefined) {
        var availReferenceUri = availabilitySetRef.referenceUri.toLocaleLowerCase();
        if (!memoize[availReferenceUri]) {
          // expand related resource only if it is not expanded before in the chain
          availabilitySetRef.expanded = dependencies.availabilitySet.getAvailSetByIdExpanded(availReferenceUri, depth, memoize, dependencies, _);
        }
      }
    }

    return memoize[referenceUri];
  }
});

module.exports = VirtualMachine;<|endoftext|>


<commit_before>'use strict';

require('dotenv').config();

const util = require('util');
const fs = require('fs');
const path = require('path');
const webPush = require('web-push');

webPush.setGCMAPIKey(process.env.GCM_API_KEY);

const NOTIFICATION_KEY = process.env.NOTIFICATIONS_KEY;
console.log("NOTIFICATION_KEY:", NOTIFICATION_KEY);
console.log("GCM_API_KEY:", process.env.GCM_API_KEY);

let storedPushCredentials = [];

/* TODO: SECURE DIAGNOSTIC ENDPOINT BEFORE HACKATHON */

exports.credentials = function(req, res) {
  res.json(storedPushCredentials);
}

exports.clearCredentials = function(req, res) {
  storedPushCredentials = [];
  res.json(storedPushCredentials);
}

/**
 * Publishes a notification
 */
exports.publish = function(req, res) {

    req.checkBody('apikey', 'API Key must not be empty').notEmpty();
    req.checkBody('apikey', 'API Key is incorrect').notificationKeyValid(NOTIFICATION_KEY);
    req.checkBody('text', 'Payload must not be empty').notEmpty();

    const errors = req.validationErrors();
    if (errors) {
        res.status(400).send('There have been validation errors: ' + util.inspect(errors));
        return;
    }

  const pushPayload = {
    text: req.body.text || "Static server notification payload...",
    icon: req.body.icon || req.protocol + '://' + req.get('host') + '/apple-touch-icon.png'
  }

  storedPushCredentials.forEach(function(pushCredentials, i) {

    webPush.sendNotification(pushCredentials, JSON.stringify(pushPayload))
    .then(function() {
      console.log("Push notification sent successfully");
    }).catch(function(error) {
      console.log(error);
    });

  }); //end forEach

  res.sendStatus(201);
};

/**
 * Subscribes a client to notifications
 */
exports.subscribe = function(req, res) {
  const newPushCredentials = {
    endpoint: req.body.endpoint,
    keys: {
      p256dh: req.body.p256dh,
      auth: req.body.auth
    }
  };

   const found = storedPushCredentials.some(function (element) {
    return element.endpoint === newPushCredentials.endpoint;
  });

  if (!found) {
    console.log("Pushing");
    storedPushCredentials.push(newPushCredentials);
  }

  res.sendStatus(200);
};<commit_msg>Remove console.log of environment vars<commit_after>'use strict';

require('dotenv').config();

const util = require('util');
const fs = require('fs');
const path = require('path');
const webPush = require('web-push');

webPush.setGCMAPIKey(process.env.GCM_API_KEY);

const NOTIFICATION_KEY = process.env.NOTIFICATIONS_KEY;

let storedPushCredentials = [];

/* TODO: SECURE DIAGNOSTIC ENDPOINT BEFORE HACKATHON */

exports.credentials = function(req, res) {
  res.json(storedPushCredentials);
}

exports.clearCredentials = function(req, res) {
  storedPushCredentials = [];
  res.json(storedPushCredentials);
}

/**
 * Publishes a notification
 */
exports.publish = function(req, res) {

    req.checkBody('apikey', 'API Key must not be empty').notEmpty();
    req.checkBody('apikey', 'API Key is incorrect').notificationKeyValid(NOTIFICATION_KEY);
    req.checkBody('text', 'Payload must not be empty').notEmpty();

    const errors = req.validationErrors();
    if (errors) {
        res.status(400).send('There have been validation errors: ' + util.inspect(errors));
        return;
    }

  const pushPayload = {
    text: req.body.text || "Static server notification payload...",
    icon: req.body.icon || req.protocol + '://' + req.get('host') + '/apple-touch-icon.png'
  }

  storedPushCredentials.forEach(function(pushCredentials, i) {

    webPush.sendNotification(pushCredentials, JSON.stringify(pushPayload))
    .then(function() {
      console.log("Push notification sent successfully");
    }).catch(function(error) {
      console.log(error);
    });

  }); //end forEach

  res.sendStatus(201);
};

/**
 * Subscribes a client to notifications
 */
exports.subscribe = function(req, res) {
  const newPushCredentials = {
    endpoint: req.body.endpoint,
    keys: {
      p256dh: req.body.p256dh,
      auth: req.body.auth
    }
  };

   const found = storedPushCredentials.some(function (element) {
    return element.endpoint === newPushCredentials.endpoint;
  });

  if (!found) {
    console.log("Pushing");
    storedPushCredentials.push(newPushCredentials);
  }

  res.sendStatus(200);
};
<|endoftext|>


<commit_before>var SPI = require('spi');
var median = require('median')
var average = [];
var lastAverage;
var averageCount =0;
var signalMax = 0;
var signalMin = 4096;
var peakToPeak;

var spi = new SPI.Spi('/dev/spidev0.1', {
    'mode': SPI.MODE['MODE_0'],  // always set mode as the first option
    'chipSelect': SPI.CS['none'] // 'none', 'high' - defaults to low
  }, function(s){
    s.maxSpeed(6000000);
    s.open();
  });

var txbuf = new Buffer([ 0x23, 0x48, 0xAF, 0x19, 0x19, 0x19 ]);
var rxbuf = new Buffer([ 0x00, 0x00, 0x00]);

setInterval(function(){
  spi.read(rxbuf, function(device, buf) {
    //console.log(buf.readUInt16BE(0));
    var sample = buf.readUInt16BE(0);
    if (sample > signalMax)
         {
            signalMax = sample;  // save just the max levels
         }
         else if (sample < signalMin)
         {
            signalMin = sample;  // save just the min levels
         }
  });
},1);

setInterval(function(){
 peakToPeak = 0;
 peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude
 if(average.length == 20){
   var first = average.pop();
 }
 average.push(peakToPeak);
 var outString = "";
 for(var i = 0; i<peakToPeak/10;i++){
   outString += " ";
 }
 outString += "*";
 var value = median(average);
 console.log("median value is " + value + " First was: "+ first + " Array: " + average.toString());
 //console.log(outString);
 signalMax = 0;
 signalMin = 4096;
},50);
<commit_msg>add median output<commit_after>var SPI = require('spi');
var median = require('median')
var average = [];
var lastAverage;
var averageCount =0;
var signalMax = 0;
var signalMin = 4096;
var peakToPeak;

var spi = new SPI.Spi('/dev/spidev0.1', {
    'mode': SPI.MODE['MODE_0'],  // always set mode as the first option
    'chipSelect': SPI.CS['none'] // 'none', 'high' - defaults to low
  }, function(s){
    s.maxSpeed(6000000);
    s.open();
  });

var txbuf = new Buffer([ 0x23, 0x48, 0xAF, 0x19, 0x19, 0x19 ]);
var rxbuf = new Buffer([ 0x00, 0x00, 0x00]);

setInterval(function(){
  spi.read(rxbuf, function(device, buf) {
    //console.log(buf.readUInt16BE(0));
    var sample = buf.readUInt16BE(0);
    if (sample > signalMax)
         {
            signalMax = sample;  // save just the max levels
         }
         else if (sample < signalMin)
         {
            signalMin = sample;  // save just the min levels
         }
  });
},1);

setInterval(function(){
 peakToPeak = 0;
 peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude
 if(average.length == 20){
   var first = average.pop();
 }
 average.unshift(peakToPeak);
 var outString = "";
 for(var i = 0; i<peakToPeak/10;i++){
   outString += " ";
 }
 outString += "*";
 var value = median(average);
 console.log("median value is " + value + " First was: "+ first + " Array: " + average.toString());
 //console.log(outString);
 signalMax = 0;
 signalMin = 4096;
},50);
<|endoftext|>


<commit_before>//$(document).ready(function() {
//    var $sharedMapSelectionButton = $('#sharedMapSelectionButton');
//    $sharedMapSelectionButton.click(handleSharedMapSelectionButton);
//    var $actionLink = $('#action-a');
//    $actionLink.click(handleSharedMapSelectionLink);
//});

var initialiseAddMapPopup = function() {
    var $sharedMapSelectionButton = $('#sharedMapSelectionButton');
    $sharedMapSelectionButton.click(handleSharedMapSelectionButton);
    var $actionLink = $('#action-a');
    $actionLink.click(handleSharedMapSelectionLink);
};

var handleSharedMapSelectionLink = function(event) {
    event.preventDefault();
    var $sharedMapSelectionButton = $('#sharedMapSelectionButton');
    $sharedMapSelectionButton.text('hhhhhhhhhhhhhh');
};

var handleSharedMapSelectionButton = function(event) {

};

var addSharedMapCallbackA = function(t, options) {
    return t.popup({
        title: 'Select a Maprosoft map',
        items: getSharedMapPopupItemsUsingPromise,
        search: {
            count: 5,
            placeholder: 'Search shared maps',
            empty: 'No share map found'
        }
    });
};

var addSharedMapCallbackB = function(t, options) {
    return t.popup({
        title: 'Select a Maprosoft map',
        items: getSharedMapPopupItemsDirectly,
        search: {
            count: 5,
            placeholder: 'Search shared maps',
            empty: 'No share map found'
        }
    });
};

var addSharedMapCallbackC = function(t, options) {
    return t.popup({
        title: 'Select a Maprosoft map',
        items: getSharedMapPopupItemsDirectly(t, options),
        search: {
            count: 5,
            placeholder: 'Search shared maps',
            empty: 'No share map found'
        }
    });
};

var addLocationMapCallback = function(t) {
    return t.popup({
        title: 'Enter a location',
        url: './location-entry.html',
        height: 250
    });
};

var handleAddMapCallback = function(t) {
    initialiseAddMapPopup();
    return t.popup({
        title: 'Add a map',
        url: './add-map-popup.html',
        height: 300
    });
};

var buildSharedMapPopupItem = function(t, teamName, sharedMapName) {
    var encodedSharedMapName = encodeURIComponent(sharedMapName);
    var encodedTeamName = encodeURIComponent(teamName);
    var sharedMapUrl = 'https://www.maprosoft.com/app/shared/' + encodedTeamName + '/' + encodedSharedMapName;
    return {
        text: sharedMapName,
        url: sharedMapUrl,
        callback: function (t) {
            return t.attach({
                url: sharedMapUrl,
                name: sharedMapName
            })
                .then(function () {
                    return t.closePopup();
                });
        }
    };
};

var buildSharedMapPopupItems = function(t, sharedMapInfo) {
    var teamName = sharedMapInfo.teamName;
    var popupItems = Object.keys(sharedMapInfo.mapNames).map(function (index) {
        var sharedMapName = sharedMapInfo.mapNames[index];
        return buildSharedMapPopupItem(t, teamName, sharedMapName);
    });
    return popupItems;
};

var getSharedMapPopupItemsXxxxxxxxxxxx = function(t, options) {
    var Promise = TrelloPowerUp.Promise;
    return Promise.all([
        t.get('board', 'shared', CACHED_SHARED_MAP_INFO_KEY),
        t.get('board', 'shared', TEAM_NAME_KEY),
        t.get('board', 'shared', TEAM_TOKEN_KEY)
    ])
        .spread(function(sharedMapInfoJson, teamName, token) {
            if (teamName && token && sharedMapInfoJson) {
                var sharedMapInfo = JSON.parse(sharedMapInfoJson);
            } else {
                var sharedMapInfo = null;
                return t.overlay({
                    url: './no-settings.html',
                    args: {}
                })
                    .then(function () {
                        return t.closePopup();
                    });
            }
            if (sharedMapInfo && sharedMapInfo.mapNames) {
                return buildSharedMapPopupItems(t, sharedMapInfo);
            } else {
                // If we don't have anything let's go fetch it
                if (teamName) {
                    var teamKey = teamName;
                } else {
                    var teamKey = 'demo';
                }
                return getFreshMapInfo(teamKey).then(function(retrievedSharedMapInfo) {
                    var sharedMapInfoJson = JSON.stringify(retrievedSharedMapInfo);
                    t.set('board', 'shared', CACHED_SHARED_MAP_INFO_KEY, sharedMapInfoJson).then(function() {
                        // saved for next time
                    });
                    return buildSharedMapPopupItems(t, retrievedSharedMapInfo);
                });
            }
        });
};

var getSharedMapPopupItemsSSSSSSSSSSSS = function(t, options) {
    var Promise = TrelloPowerUp.Promise;
    return Promise.join(
        t.get('board', 'shared', CACHED_SHARED_MAP_INFO_KEY),
        t.get('board', 'shared', TEAM_NAME_KEY),
        t.get('board', 'shared', TEAM_TOKEN_KEY),
        function(sharedMapInfoJson, teamName, token) {
            if (teamName && token && sharedMapInfoJson) {
                //var sharedMapInfo = JSON.parse(sharedMapInfoJson);
                if (teamName) {
                    var teamKey = teamName;
                } else {
                    var teamKey = 'demo';
                }
                return getFreshMapInfo(teamKey).then(function(retrievedSharedMapInfo) {
                    var sharedMapInfoJson = JSON.stringify(retrievedSharedMapInfo);
                    t.set('board', 'shared', CACHED_SHARED_MAP_INFO_KEY, sharedMapInfoJson).then(function() {
                        // saved for next time
                    });
                    return buildSharedMapPopupItems(t, retrievedSharedMapInfo);
                });
            } else {
                return t.overlay({
                    url: './no-settings.html',
                    args: {}
                })
                    .then(function () {
                        return t.closePopup();
                    });
            }
        }
    );
};

var getSharedMapPopupItemsUsingPromise = function(t, options) {
    var teamKey = 'demo';
    return getFreshMapInfo(teamKey)
        .then(function(retrievedSharedMapInfo) {
            var sharedMapInfoJson = JSON.stringify(retrievedSharedMapInfo);
            return t.set('board', 'shared', CACHED_SHARED_MAP_INFO_KEY, sharedMapInfoJson).then(function() {
                // saved for next time
            }).then(function() {
                return buildSharedMapPopupItems(t, retrievedSharedMapInfo);
            });
        });
};

var getSharedMapPopupItemsDirectly = function(t, options) {
    var sharedMapInfo = {
        teamName: "mock",
        mapNames: ["aaaaa", "bbbbb", "ccccc", "ddddd", "eeeee", "fffff", "ggggg"]
    };
    return buildSharedMapPopupItems(t, sharedMapInfo);
};
<commit_msg>update<commit_after>//$(document).ready(function() {
//    var $sharedMapSelectionButton = $('#sharedMapSelectionButton');
//    $sharedMapSelectionButton.click(handleSharedMapSelectionButton);
//    var $actionLink = $('#action-a');
//    $actionLink.click(handleSharedMapSelectionLink);
//});

var initialiseAddMapPopup = function() {
    var $sharedMapSelectionButton = $('#sharedMapSelectionButton');
    $sharedMapSelectionButton.click(handleSharedMapSelectionButton);
    var $actionLink = $('#action-a');
    $actionLink.click(handleSharedMapSelectionLink);
};

var handleSharedMapSelectionLink = function(event) {
    event.preventDefault();
    var $sharedMapSelectionButton = $('#sharedMapSelectionButton');
    $sharedMapSelectionButton.text('hhhhhhhhhhhhhh');
};

var handleSharedMapSelectionButton = function(event) {

};

var addSharedMapCallbackA = function(t, options) {
    return t.popup({
        title: 'Select a Maprosoft map',
        items: getSharedMapPopupItemsUsingPromise,
        search: {
            count: 5,
            placeholder: 'Search shared maps',
            empty: 'No share map found'
        }
    });
};

var addSharedMapCallbackB = function(t, options) {
    return t.popup({
        title: 'Select a Maprosoft map',
        items: getSharedMapPopupItemsDirectly,
        search: {
            count: 5,
            placeholder: 'Search shared maps',
            empty: 'No share map found'
        }
    });
};

var addSharedMapCallbackC = function(t, options) {
    return t.popup({
        title: 'Select a Maprosoft map',
        items: getSharedMapPopupItemsDirectly(t, options),
        search: {
            count: 5,
            placeholder: 'Search shared maps',
            empty: 'No share map found'
        }
    });
};

var addLocationMapCallback = function(t) {
    return t.popup({
        title: 'Enter a location',
        url: './location-entry.html',
        height: 250
    });
};

var handleAddMapCallback = function(t) {

    setTimeout(function() {
        initialiseAddMapPopup();
    }, 5000);
    return t.popup({
        title: 'Add a map',
        url: './add-map-popup.html',
        height: 300
    });
};

var buildSharedMapPopupItem = function(t, teamName, sharedMapName) {
    var encodedSharedMapName = encodeURIComponent(sharedMapName);
    var encodedTeamName = encodeURIComponent(teamName);
    var sharedMapUrl = 'https://www.maprosoft.com/app/shared/' + encodedTeamName + '/' + encodedSharedMapName;
    return {
        text: sharedMapName,
        url: sharedMapUrl,
        callback: function (t) {
            return t.attach({
                url: sharedMapUrl,
                name: sharedMapName
            })
                .then(function () {
                    return t.closePopup();
                });
        }
    };
};

var buildSharedMapPopupItems = function(t, sharedMapInfo) {
    var teamName = sharedMapInfo.teamName;
    var popupItems = Object.keys(sharedMapInfo.mapNames).map(function (index) {
        var sharedMapName = sharedMapInfo.mapNames[index];
        return buildSharedMapPopupItem(t, teamName, sharedMapName);
    });
    return popupItems;
};

var getSharedMapPopupItemsXxxxxxxxxxxx = function(t, options) {
    var Promise = TrelloPowerUp.Promise;
    return Promise.all([
        t.get('board', 'shared', CACHED_SHARED_MAP_INFO_KEY),
        t.get('board', 'shared', TEAM_NAME_KEY),
        t.get('board', 'shared', TEAM_TOKEN_KEY)
    ])
        .spread(function(sharedMapInfoJson, teamName, token) {
            if (teamName && token && sharedMapInfoJson) {
                var sharedMapInfo = JSON.parse(sharedMapInfoJson);
            } else {
                var sharedMapInfo = null;
                return t.overlay({
                    url: './no-settings.html',
                    args: {}
                })
                    .then(function () {
                        return t.closePopup();
                    });
            }
            if (sharedMapInfo && sharedMapInfo.mapNames) {
                return buildSharedMapPopupItems(t, sharedMapInfo);
            } else {
                // If we don't have anything let's go fetch it
                if (teamName) {
                    var teamKey = teamName;
                } else {
                    var teamKey = 'demo';
                }
                return getFreshMapInfo(teamKey).then(function(retrievedSharedMapInfo) {
                    var sharedMapInfoJson = JSON.stringify(retrievedSharedMapInfo);
                    t.set('board', 'shared', CACHED_SHARED_MAP_INFO_KEY, sharedMapInfoJson).then(function() {
                        // saved for next time
                    });
                    return buildSharedMapPopupItems(t, retrievedSharedMapInfo);
                });
            }
        });
};

var getSharedMapPopupItemsSSSSSSSSSSSS = function(t, options) {
    var Promise = TrelloPowerUp.Promise;
    return Promise.join(
        t.get('board', 'shared', CACHED_SHARED_MAP_INFO_KEY),
        t.get('board', 'shared', TEAM_NAME_KEY),
        t.get('board', 'shared', TEAM_TOKEN_KEY),
        function(sharedMapInfoJson, teamName, token) {
            if (teamName && token && sharedMapInfoJson) {
                //var sharedMapInfo = JSON.parse(sharedMapInfoJson);
                if (teamName) {
                    var teamKey = teamName;
                } else {
                    var teamKey = 'demo';
                }
                return getFreshMapInfo(teamKey).then(function(retrievedSharedMapInfo) {
                    var sharedMapInfoJson = JSON.stringify(retrievedSharedMapInfo);
                    t.set('board', 'shared', CACHED_SHARED_MAP_INFO_KEY, sharedMapInfoJson).then(function() {
                        // saved for next time
                    });
                    return buildSharedMapPopupItems(t, retrievedSharedMapInfo);
                });
            } else {
                return t.overlay({
                    url: './no-settings.html',
                    args: {}
                })
                    .then(function () {
                        return t.closePopup();
                    });
            }
        }
    );
};

var getSharedMapPopupItemsUsingPromise = function(t, options) {
    var teamKey = 'demo';
    return getFreshMapInfo(teamKey)
        .then(function(retrievedSharedMapInfo) {
            var sharedMapInfoJson = JSON.stringify(retrievedSharedMapInfo);
            return t.set('board', 'shared', CACHED_SHARED_MAP_INFO_KEY, sharedMapInfoJson).then(function() {
                // saved for next time
            }).then(function() {
                return buildSharedMapPopupItems(t, retrievedSharedMapInfo);
            });
        });
};

var getSharedMapPopupItemsDirectly = function(t, options) {
    var sharedMapInfo = {
        teamName: "mock",
        mapNames: ["aaaaa", "bbbbb", "ccccc", "ddddd", "eeeee", "fffff", "ggggg"]
    };
    return buildSharedMapPopupItems(t, sharedMapInfo);
};
<|endoftext|>


<commit_before>var React = require('../react');
var log = require('../logger');
var _ = require('../utils/mindash');
var uuid = require('../utils/uuid');
var StoreObserver = require('../storeObserver');
var getFetchResult = require('./getFetchResult');
var getClassName = require('../utils/getClassName');

var RESERVED_FUNCTIONS = [
  'contextTypes',
  'componentDidMount',
  'onStoreChanged',
  'componentWillUnmount',
  'getInitialState',
  'getState',
  'render'
];

function createContainer(InnerComponent, config) {
  config = config || {};

  if (!InnerComponent) {
    throw new Error('Must specify an inner component');
  }

  var observer;
  var id = uuid.type('Component');
  var innerComponentDisplayName = InnerComponent.displayName || getClassName(InnerComponent);
  var contextTypes = _.extend({
    marty: React.PropTypes.object
  }, config.contextTypes);

  var Container = React.createClass(_.extend({
    contextTypes: contextTypes,
    componentDidMount() {
      var component = {
        id: id,
        displayName: innerComponentDisplayName
      };

      observer = new StoreObserver({
        component: component,
        onStoreChanged: this.onStoreChanged,
        stores: getStoresToListenTo(this.listenTo, component)
      });
    },
    componentWillReceiveProps(props) {
      this.props = props;
      this.setState(this.getState(props));
    },
    onStoreChanged() {
      this.setState(this.getState());
    },
    componentWillUnmount() {
      if (observer) {
        observer.dispose();
      }
    },
    getInitialState() {
      return this.getState();
    },
    getState(props) {
      return {
        result: getFetchResult(this)
      };
    },
    done(results) {
      return <InnerComponent ref="innerComponent" {...this.props} {...results} />;
    },
    getInnerComponent() {
      return this.refs.innerComponent;
    },
    render() {
      var container = this;

      return this.state.result.when({
        done(results) {
          if (_.isFunction(container.done)) {
            return container.done(results);
          }

          throw new Error('The `done` handler must be a function');
        },
        pending() {
          if (_.isFunction(container.pending)) {
            return container.pending();
          }

          return

;
        },
        failed(error) {
          if (_.isFunction(container.failed)) {
            return container.failed(error);
          }

          throw error;
        }
      });
    }
  }, _.omit(config, RESERVED_FUNCTIONS)));

  Container.InnerComponent = InnerComponent;
  Container.displayName = innerComponentDisplayName + 'Container';

  return Container;
}

module.exports = createContainer;

function getStoresToListenTo(stores, component) {
  if (!stores) {
    return [];
  }

  if (!_.isArray(stores)) {
    stores = [stores];
  }

  return _.filter(stores, function (store) {
    var isStore = store.constructor.type === 'Store';

    if (!isStore) {
      log.warn(
        'Warning: Trying to listen to something that isn\'t a store',
        store,
        component.displayName
      );
    }

    return isStore;
  });
}
<commit_msg>:green_heart: Linting<commit_after>var React = require('../react');
var log = require('../logger');
var _ = require('../utils/mindash');
var uuid = require('../utils/uuid');
var StoreObserver = require('../storeObserver');
var getFetchResult = require('./getFetchResult');
var getClassName = require('../utils/getClassName');

var RESERVED_FUNCTIONS = [
  'contextTypes',
  'componentDidMount',
  'onStoreChanged',
  'componentWillUnmount',
  'getInitialState',
  'getState',
  'render'
];

function createContainer(InnerComponent, config) {
  config = config || {};

  if (!InnerComponent) {
    throw new Error('Must specify an inner component');
  }

  var observer;
  var id = uuid.type('Component');
  var innerComponentDisplayName = InnerComponent.displayName || getClassName(InnerComponent);
  var contextTypes = _.extend({
    marty: React.PropTypes.object
  }, config.contextTypes);

  var Container = React.createClass(_.extend({
    contextTypes: contextTypes,
    componentDidMount() {
      var component = {
        id: id,
        displayName: innerComponentDisplayName
      };

      observer = new StoreObserver({
        component: component,
        onStoreChanged: this.onStoreChanged,
        stores: getStoresToListenTo(this.listenTo, component)
      });
    },
    componentWillReceiveProps(props) {
      this.props = props;
      this.setState(this.getState(props));
    },
    onStoreChanged() {
      this.setState(this.getState());
    },
    componentWillUnmount() {
      if (observer) {
        observer.dispose();
      }
    },
    getInitialState() {
      return this.getState();
    },
    getState() {
      return {
        result: getFetchResult(this)
      };
    },
    done(results) {
      return <InnerComponent ref="innerComponent" {...this.props} {...results} />;
    },
    getInnerComponent() {
      return this.refs.innerComponent;
    },
    render() {
      var container = this;

      return this.state.result.when({
        done(results) {
          if (_.isFunction(container.done)) {
            return container.done(results);
          }

          throw new Error('The `done` handler must be a function');
        },
        pending() {
          if (_.isFunction(container.pending)) {
            return container.pending();
          }

          return

;
        },
        failed(error) {
          if (_.isFunction(container.failed)) {
            return container.failed(error);
          }

          throw error;
        }
      });
    }
  }, _.omit(config, RESERVED_FUNCTIONS)));

  Container.InnerComponent = InnerComponent;
  Container.displayName = innerComponentDisplayName + 'Container';

  return Container;
}

module.exports = createContainer;

function getStoresToListenTo(stores, component) {
  if (!stores) {
    return [];
  }

  if (!_.isArray(stores)) {
    stores = [stores];
  }

  return _.filter(stores, function (store) {
    var isStore = store.constructor.type === 'Store';

    if (!isStore) {
      log.warn(
        'Warning: Trying to listen to something that isn\'t a store',
        store,
        component.displayName
      );
    }

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


<commit_before>/*jshint node: true, -W106 */
'use strict';

/*
* Name : mapChartFlowModel.js
* Module : Lib::DataTier::mapChartFlowModel
* Location : /lib/dataTier/flow
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-05-15   Filippo Rampado    Initial code
* =========================================================
*/
var FlowModel = require('./flowModel.js');
var Helper = require('../../helpers/functionHelper.js');

function MapChartFlowModel(params) {
	if(params===undefined || params.ID===undefined || typeof params.ID !== 'string'|| params.ID.trim() === ''){ // ID field is required
		console.log('Error: 232');
		return;
	}

	params.type = 'MapChartFlow';
	this.parent.constructor.call(this, params);

	this._latitudeKey=null;
	this._longitudeKey=null;
	this._objectKey=null;
	this._latitudeFormat='coordinates';
	this._longitudeFormat='coordinates';
	this._marker={
		type: 'shape',//shape, icon, text
		shape: 'circle',//circle, triangle, square, diamond
		//icon: null,//path
		//text: null,//string
		//color: '#000'	//HEX
	};
	this._trace={
		type: 'none',//none, line, poly
		coordinates: []
		//strokeColor: '#FFF'	//HEX
		//fillColor: '#FFF'	//HEX
	};
	this._trailLength=3;//length of trail
	this._maxItemsSaved=500; //items saved

	this.updateProperties(params);
}

MapChartFlowModel.prototype = Object.create(FlowModel.prototype);
MapChartFlowModel.prototype.constructor = MapChartFlowModel;
MapChartFlowModel.prototype.parent = FlowModel.prototype;

MapChartFlowModel.prototype.updateProperties = function(params){
	if (params!==undefined){
		var prop=this.parent.updateProperties.call(this, params);
		if(params.longitudeKey!==undefined && typeof params.longitudeKey === 'string'){
			this._longitudeKey=prop.longitudeKey=params.longitudeKey;
		}
		if(params.latitudeKey!==undefined && typeof params.latitudeKey === 'string'){
			this._latitudeKey=prop.latitudeKey=params.latitudeKey;
		}
		if(params.objectKey!==undefined && typeof params.objectKey === 'string'){
			this._objectKey=prop.objectKey=params.objectKey;
		}
		if(params.longitudeFormat!==undefined && Helper.isValidMapFormat(params.longitudeFormat)){
			this._longitudeFormat=prop.longitudeFormat=params.longitudeFormat;
		}
		if(params.latitudeFormat!==undefined && Helper.isValidMapFormat(params.latitudeFormat)){
			this._latitudeFormat=prop.latitudeFormat=params.latitudeFormat;
		}
		if(params.marker!==undefined && Helper.isValidMapMarker(params.marker)){
			this._marker=prop.marker=params.marker;
		}
		if(params.trace!==undefined && Helper.isValidTrace(params.trace)){
			this._trace=prop.trace=params.trace;
		}
		if(params.trailLength!==undefined && typeof params.trailLength==='number' && params.trailLength>=1){
			this._trailLength=prop.trailLength=params.trailLength;
		}
		if(params.maxItemsSaved!==undefined && typeof params.maxItemsSaved==='number' && params.maxItemsSaved>=0){
			this._maxItemsSaved=prop.maxItemsSaved=params.maxItemsSaved;
		}
		return prop;
	}
	return 233;
};

MapChartFlowModel.prototype.addRecord = function(record){
	if(record!==undefined && record!==null && typeof record === 'object'){
		this._records.push(record);
		var index=this._records.length-1;
		var ID=this.generateNorrisRecordID(index);
		this._records[index].norrisRecordID=ID;
		this.validateRecord(index);
		return ID;
	}
	return 133;
};

MapChartFlowModel.prototype.updateRecord = function(ID, record){
	if (record === undefined || record === null || Array.isArray(record) ||
		record[this._latitudeKey] === undefined ||
		record[this._longitudeKey] === undefined ||
		record[this._objectKey] === undefined
		){
		return 131;
	}
	if (typeof ID==='string' && ID.indexOf(this._ID) !== -1) {
		var records=this._records.length;
		var i=0;
		var found=false;
		while (i<records && (!found)){
			if (this._records[i].norrisRecordID===ID){
				found=true;
			}
			else{
				i++;
			}
		}//while
		if (found){//in records[i] there is the ID
			record.norrisRecordID=this._records[i].norrisRecordID;
			this._records[i]=record;
			this.validateRecord(i);
			return true;
		}
		//no ID in records
		return 132;
	}
	//invalid ID
	return 132;
};

MapChartFlowModel.prototype.updateMovie = function(params){
	if (params === undefined || params === null || Array.isArray(params)){
		return 131;
	}
	var found=false;
	var recordsID=[];
	var i=0;
	for (var keyParam in params) {
		if(params[keyParam][this._latitudeKey] === undefined ||
			params[keyParam][this._longitudeKey] === undefined ||
			params[keyParam][this._objectKey] === undefined){
			console.log('Invalid record : ');
			console.dir(params[keyParam]);
		}else{
			found=false;
			for (var keyRecord in this._records) {
				if(params[keyParam][this._objectKey]===this._records[keyRecord][this._objectKey]){
					found=true;
					params[keyParam].norrisRecordID=this._records[keyRecord].norrisRecordID;
					recordsID.push(this._records[keyRecord].norrisRecordID);
					break;
				}
			}
			if(!found){
				params[keyParam].norrisRecordID=this.generateNorrisRecordID(i);
			}
			recordsID.push(params[keyParam].norrisRecordID);
		}
		i++;
	}
	this._records=params;
	for (var key in this._records) {
		this.validateRecord(key);
	}
	return recordsID;
};

MapChartFlowModel.prototype.deleteRecord = function(ID){
	if (ID!==undefined && typeof ID==='string' && ID.indexOf(this._ID) !== -1) {
		var records=this._records.length;
		var i=0;
		var found=false;
		while (i<records && (!found)){
			if (this._records[i].norrisRecordID===ID){
				found=true;
			}
			else{
				i++;
			}
		}//while
		if (found){//in records[i] there is the ID_index
			this._records.splice(i, 1);
			return true;
		}
	}
	return 134;
};

MapChartFlowModel.prototype.getProperties = function(){
	var prop=this.parent.getProperties.call(this);
	prop.longitudeKey=this._longitudeKey;
	prop.latitudeKey=this._latitudeKey;
	prop.objectKey=this._objectKey;
	prop.longitudeFormat=this._longitudeFormat;
	prop.latitudeFormat=this._latitudeFormat;
	prop.marker=this._marker;
	prop.trace=this._trace;
	prop.trailLength=this._trailLength;
	prop.maxItemsSaved=this._maxItemsSaved;
	return prop;
};

MapChartFlowModel.prototype.getRecordByID = function(ID){
	if (typeof ID==='string' && ID.indexOf(this._ID) !== -1) {
		var records=this._records.length;
		var i=0;
		var found=false;
		while (i<records && (!found)){
			if (this._records[i].norrisRecordID===ID){
				found=true;
			}
			else{
				i++;
			}
		}//while
		if (found){//in records[i] there is the ID
			return this._records[i];
		}
		//no ID in records
	}
	return 135;
};

module.exports = MapChartFlowModel;<commit_msg>fix control valid params<commit_after>/*jshint node: true, -W106 */
'use strict';

/*
* Name : mapChartFlowModel.js
* Module : Lib::DataTier::mapChartFlowModel
* Location : /lib/dataTier/flow
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-05-15   Filippo Rampado    Initial code
* =========================================================
*/
var FlowModel = require('./flowModel.js');
var Helper = require('../../helpers/functionHelper.js');

function MapChartFlowModel(params) {
	if(params===undefined || params.ID===undefined || typeof params.ID !== 'string'|| params.ID.trim() === ''){ // ID field is required
		console.log('Error: 232');
		return;
	}

	params.type = 'MapChartFlow';
	this.parent.constructor.call(this, params);

	this._latitudeKey=null;
	this._longitudeKey=null;
	this._objectKey=null;
	this._latitudeFormat='coordinates';
	this._longitudeFormat='coordinates';
	this._marker={
		type: 'shape',//shape, icon, text
		shape: 'circle',//circle, triangle, square, diamond
		//icon: null,//path
		//text: null,//string
		//color: '#000'	//HEX
	};
	this._trace={
		type: 'none',//none, line, poly
		coordinates: []
		//strokeColor: '#FFF'	//HEX
		//fillColor: '#FFF'	//HEX
	};
	this._trailLength=3;//length of trail
	this._maxItemsSaved=500; //items saved

	this.updateProperties(params);
}

MapChartFlowModel.prototype = Object.create(FlowModel.prototype);
MapChartFlowModel.prototype.constructor = MapChartFlowModel;
MapChartFlowModel.prototype.parent = FlowModel.prototype;

MapChartFlowModel.prototype.updateProperties = function(params){
	if (params!==undefined){
		var prop=this.parent.updateProperties.call(this, params);
		if(params.longitudeKey!==undefined && typeof params.longitudeKey === 'string'){
			this._longitudeKey=prop.longitudeKey=params.longitudeKey;
		}
		if(params.latitudeKey!==undefined && typeof params.latitudeKey === 'string'){
			this._latitudeKey=prop.latitudeKey=params.latitudeKey;
		}
		if(params.objectKey!==undefined && typeof params.objectKey === 'string'){
			this._objectKey=prop.objectKey=params.objectKey;
		}
		if(params.longitudeFormat!==undefined && Helper.isValidMapFormat(params.longitudeFormat)){
			this._longitudeFormat=prop.longitudeFormat=params.longitudeFormat;
		}
		if(params.latitudeFormat!==undefined && Helper.isValidMapFormat(params.latitudeFormat)){
			this._latitudeFormat=prop.latitudeFormat=params.latitudeFormat;
		}
		if(params.marker!==undefined && Helper.isValidMapMarker(params.marker)){
			this._marker=prop.marker=params.marker;
		}
		if(params.trace!==undefined && Helper.isValidTrace(params.trace)){
			this._trace=prop.trace=params.trace;
		}
		if(params.trailLength!==undefined && typeof params.trailLength==='number' && params.trailLength>=1){
			this._trailLength=prop.trailLength=params.trailLength;
		}
		if(params.maxItemsSaved!==undefined && typeof params.maxItemsSaved==='number' && params.maxItemsSaved>=0){
			this._maxItemsSaved=prop.maxItemsSaved=params.maxItemsSaved;
		}
		return prop;
	}
	return 233;
};

MapChartFlowModel.prototype.addRecord = function(record){
	if(record!==undefined && record!==null && typeof record === 'object'){
		this._records.push(record);
		var index=this._records.length-1;
		var ID=this.generateNorrisRecordID(index);
		this._records[index].norrisRecordID=ID;
		this.validateRecord(index);
		return ID;
	}
	return 133;
};

MapChartFlowModel.prototype.updateRecord = function(ID, record){
	if (record === undefined || record === null || Array.isArray(record) ||
		record[this._latitudeKey] === undefined ||
		record[this._longitudeKey] === undefined ||
		record[this._objectKey] === undefined
		){
		return 131;
	}
	if (typeof ID==='string' && ID.indexOf(this._ID) !== -1) {
		var records=this._records.length;
		var i=0;
		var found=false;
		while (i<records && (!found)){
			if (this._records[i].norrisRecordID===ID){
				found=true;
			}
			else{
				i++;
			}
		}//while
		if (found){//in records[i] there is the ID
			record.norrisRecordID=this._records[i].norrisRecordID;
			this._records[i]=record;
			this.validateRecord(i);
			return true;
		}
		//no ID in records
		return 132;
	}
	//invalid ID
	return 132;
};

MapChartFlowModel.prototype.updateMovie = function(params){
	if (params === undefined || params === null || !Array.isArray(params)){
		return 131;
	}
	var found=false;
	var recordsID=[];
	var i=0;
	for (var keyParam in params) {
		if(params[keyParam][this._latitudeKey] === undefined ||
			params[keyParam][this._longitudeKey] === undefined ||
			params[keyParam][this._objectKey] === undefined){
			console.log('Invalid record : ');
			console.dir(params[keyParam]);
		}else{
			found=false;
			for (var keyRecord in this._records) {
				if(params[keyParam][this._objectKey]===this._records[keyRecord][this._objectKey]){
					found=true;
					params[keyParam].norrisRecordID=this._records[keyRecord].norrisRecordID;
					recordsID.push(this._records[keyRecord].norrisRecordID);
					break;
				}
			}
			if(!found){
				params[keyParam].norrisRecordID=this.generateNorrisRecordID(i);
			}
			recordsID.push(params[keyParam].norrisRecordID);
		}
		i++;
	}
	this._records=params;
	for (var key in this._records) {
		this.validateRecord(key);
	}
	return recordsID;
};

MapChartFlowModel.prototype.deleteRecord = function(ID){
	if (ID!==undefined && typeof ID==='string' && ID.indexOf(this._ID) !== -1) {
		var records=this._records.length;
		var i=0;
		var found=false;
		while (i<records && (!found)){
			if (this._records[i].norrisRecordID===ID){
				found=true;
			}
			else{
				i++;
			}
		}//while
		if (found){//in records[i] there is the ID_index
			this._records.splice(i, 1);
			return true;
		}
	}
	return 134;
};

MapChartFlowModel.prototype.getProperties = function(){
	var prop=this.parent.getProperties.call(this);
	prop.longitudeKey=this._longitudeKey;
	prop.latitudeKey=this._latitudeKey;
	prop.objectKey=this._objectKey;
	prop.longitudeFormat=this._longitudeFormat;
	prop.latitudeFormat=this._latitudeFormat;
	prop.marker=this._marker;
	prop.trace=this._trace;
	prop.trailLength=this._trailLength;
	prop.maxItemsSaved=this._maxItemsSaved;
	return prop;
};

MapChartFlowModel.prototype.getRecordByID = function(ID){
	if (typeof ID==='string' && ID.indexOf(this._ID) !== -1) {
		var records=this._records.length;
		var i=0;
		var found=false;
		while (i<records && (!found)){
			if (this._records[i].norrisRecordID===ID){
				found=true;
			}
			else{
				i++;
			}
		}//while
		if (found){//in records[i] there is the ID
			return this._records[i];
		}
		//no ID in records
	}
	return 135;
};

module.exports = MapChartFlowModel;<|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
"use strict";

const ImportEagerContextDependency = require("./ImportEagerContextDependency");
const ImportEagerWeakContextDependency = require("./ImportEagerWeakContextDependency");
const ImportLazyOnceContextDependency = require("./ImportLazyOnceContextDependency");
const ImportLazyContextDependency = require("./ImportLazyContextDependency");
const ImportDependenciesBlock = require("./ImportDependenciesBlock");
const ImportEagerDependency = require("./ImportEagerDependency");
const ContextDependencyHelpers = require("./ContextDependencyHelpers");
const UnsupportedFeatureWarning = require("../UnsupportedFeatureWarning");

class ImportParserPlugin {
	constructor(options) {
		this.options = options;
	}

	apply(parser) {
		const options = this.options;

		parser.plugin(["call System.import", "import-call"], (expr) => {
			if(expr.arguments.length !== 1)
				throw new Error("Incorrect number of arguments provided to 'import(module: string) -> Promise'.");

			const param = parser.evaluateExpression(expr.arguments[0]);

			let chunkName = null;
			let mode = "lazy";

			const importOptions = parser.getCommentOptions(expr.range);
			if(importOptions) {
				if(typeof importOptions.webpackChunkName !== "undefined") {
					if(typeof importOptions.webpackChunkName !== "string")
						parser.state.module.warnings.push(new UnsupportedFeatureWarning(parser.state.module, `\`webpackChunkName\` expected a string, but received: ${importOptions.webpackChunkName}.`));
					else
						chunkName = importOptions.webpackChunkName;
				}
				if(typeof importOptions.webpackMode !== "undefined") {
					if(typeof importOptions.webpackMode !== "string")
						parser.state.module.warnings.push(new UnsupportedFeatureWarning(parser.state.module, `\`webpackMode\` expected a string, but received: ${importOptions.webpackMode}.`));
					else
						mode = importOptions.webpackMode;
				}
			}

			if(param.isString()) {
				if(mode !== "lazy" && mode !== "eager" && mode !== "eager-weak") {
					parser.state.module.warnings.push(new UnsupportedFeatureWarning(parser.state.module, `\`webpackMode\` expected 'lazy' or 'eager', but received: ${mode}.`));
				}

				if(mode === "eager") {
					const dep = new ImportEagerDependency(param.string, expr.range);
					parser.state.current.addDependency(dep);
				} else {
					// both lazy and eager-weak modes use this; eager-weak needs the chunks created, but will expect them pre-served
					const depBlock = new ImportDependenciesBlock(param.string, expr.range, chunkName, parser.state.module, expr.loc, mode);
					parser.state.current.addBlock(depBlock);
				}
				return true;
			} else {
				if(mode !== "lazy" && mode !== "lazy-once" && mode !== "eager" && mode !== "eager-weak") {
					parser.state.module.warnings.push(new UnsupportedFeatureWarning(parser.state.module, `\`webpackMode\` expected 'lazy', 'lazy-once' or 'eager', but received: ${mode}.`));
				}

				let Dep = ImportLazyContextDependency;
				if(mode === "eager") {
					Dep = ImportEagerContextDependency;
				} else if(mode === "eager-weak") {
					Dep = ImportEagerWeakContextDependency;
				} else if(mode === "lazy-once") {
					Dep = ImportLazyOnceContextDependency;
				}
				const dep = ContextDependencyHelpers.create(Dep, expr.range, param, expr, options, chunkName);
				if(!dep) return;
				dep.loc = expr.loc;
				dep.optional = !!parser.scope.inTry;
				parser.state.current.addDependency(dep);
				return true;
			}
		});
	}
}
module.exports = ImportParserPlugin;
<commit_msg>fix($warning): mention eager-weak in warnings<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
"use strict";

const ImportEagerContextDependency = require("./ImportEagerContextDependency");
const ImportEagerWeakContextDependency = require("./ImportEagerWeakContextDependency");
const ImportLazyOnceContextDependency = require("./ImportLazyOnceContextDependency");
const ImportLazyContextDependency = require("./ImportLazyContextDependency");
const ImportDependenciesBlock = require("./ImportDependenciesBlock");
const ImportEagerDependency = require("./ImportEagerDependency");
const ContextDependencyHelpers = require("./ContextDependencyHelpers");
const UnsupportedFeatureWarning = require("../UnsupportedFeatureWarning");

class ImportParserPlugin {
	constructor(options) {
		this.options = options;
	}

	apply(parser) {
		const options = this.options;

		parser.plugin(["call System.import", "import-call"], (expr) => {
			if(expr.arguments.length !== 1)
				throw new Error("Incorrect number of arguments provided to 'import(module: string) -> Promise'.");

			const param = parser.evaluateExpression(expr.arguments[0]);

			let chunkName = null;
			let mode = "lazy";

			const importOptions = parser.getCommentOptions(expr.range);
			if(importOptions) {
				if(typeof importOptions.webpackChunkName !== "undefined") {
					if(typeof importOptions.webpackChunkName !== "string")
						parser.state.module.warnings.push(new UnsupportedFeatureWarning(parser.state.module, `\`webpackChunkName\` expected a string, but received: ${importOptions.webpackChunkName}.`));
					else
						chunkName = importOptions.webpackChunkName;
				}
				if(typeof importOptions.webpackMode !== "undefined") {
					if(typeof importOptions.webpackMode !== "string")
						parser.state.module.warnings.push(new UnsupportedFeatureWarning(parser.state.module, `\`webpackMode\` expected a string, but received: ${importOptions.webpackMode}.`));
					else
						mode = importOptions.webpackMode;
				}
			}

			if(param.isString()) {
				if(mode !== "lazy" && mode !== "eager" && mode !== "eager-weak") {
					parser.state.module.warnings.push(new UnsupportedFeatureWarning(parser.state.module, `\`webpackMode\` expected 'lazy', 'eager' or 'eager-weak', but received: ${mode}.`));
				}

				if(mode === "eager") {
					const dep = new ImportEagerDependency(param.string, expr.range);
					parser.state.current.addDependency(dep);
				} else {
					// both lazy and eager-weak modes use this; eager-weak needs the chunks created, but will expect them pre-served
					const depBlock = new ImportDependenciesBlock(param.string, expr.range, chunkName, parser.state.module, expr.loc, mode);
					parser.state.current.addBlock(depBlock);
				}
				return true;
			} else {
				if(mode !== "lazy" && mode !== "lazy-once" && mode !== "eager" && mode !== "eager-weak") {
					parser.state.module.warnings.push(new UnsupportedFeatureWarning(parser.state.module, `\`webpackMode\` expected 'lazy', 'lazy-once', 'eager' or 'eager-weak', but received: ${mode}.`));
				}

				let Dep = ImportLazyContextDependency;
				if(mode === "eager") {
					Dep = ImportEagerContextDependency;
				} else if(mode === "eager-weak") {
					Dep = ImportEagerWeakContextDependency;
				} else if(mode === "lazy-once") {
					Dep = ImportLazyOnceContextDependency;
				}
				const dep = ContextDependencyHelpers.create(Dep, expr.range, param, expr, options, chunkName);
				if(!dep) return;
				dep.loc = expr.loc;
				dep.optional = !!parser.scope.inTry;
				parser.state.current.addDependency(dep);
				return true;
			}
		});
	}
}
module.exports = ImportParserPlugin;
<|endoftext|>


<commit_before>/*
Layout of the AppLink object:

+---------------------------------+
|       +-----------------+       |
|       |   +---------+   |       |
|       |   |         |   |       |
|       |   | PICTURE |   |       |
|       |   |         |   |       |
|       |   +---------+   |       |
|       |                 |       |
|       |   +---------+   |       |
|       |   |  NAME   |   |       |
|       |   +---------+   |       |
|       |                 |       |
|       |    HYPERLINK    |       |
|       +-----------------+       |
|            CONTAINER            |
+---------------------------------+

*/

function loadAppLinks(appLinkInfo, container) {

  // AppLink Object declaration
  function AppLink (name, image, link, color, tabindex) {

    // Create picture
    this.picture = document.createElement('img');
    this.picture.setAttribute('class', 'appLinkPic');
    this.picture.src = image;
    this.picture.alt = name;
    if (color) this.picture.style.backgroundColor = color;

    // Create Name
    this.name = document.createElement('p');
    this.name.setAttribute('class', 'appLinkName');
    this.name.textContent = name;

    // Create HyperLink
    this.hyperLink = document.createElement('a');
    this.hyperLink.setAttribute('class', 'appLinkHyperLink');
    this.hyperLink.setAttribute('href', link);
    this.hyperLink.setAttribute('onclick', 'putSearchQuery(this)');
    this.hyperLink.setAttribute('ontouchstart', '');
    if (tabindex) this.hyperLink.setAttribute('tabindex', tabindex);
    this.hyperLink.appendChild(this.picture);
    this.hyperLink.appendChild(this.name);

    // Create Container
    this.container = document.createElement('div');
    this.container.setAttribute('class', 'appLinkContainer');
    this.container.appendChild(this.hyperLink);
  }

  if (!container) container = document.body

  // Create a link for every sub-array within appLinkInfo.
  for (var i = 0; i < appLinkInfo.names.length; i++) {
    var tmp = new AppLink(appLinkInfo.names[i], appLinkInfo.imageurls[i], appLinkInfo.links[i], appLinkInfo.backgroundColors[i], i+1);
    container.appendChild(tmp.container);
  }

  // Extend container to contain all AppLinks
  var clearFix = document.createElement('div');
  clearFix.setAttribute('class', 'clearfix');
  container.appendChild(clearFix);

  rootSearchTree = appLinkInfo.aliases;
}
<commit_msg>Older versions of IE now show the link name<commit_after>/*
Layout of the AppLink object:

+---------------------------------+
|       +-----------------+       |
|       |   +---------+   |       |
|       |   |         |   |       |
|       |   | PICTURE |   |       |
|       |   |         |   |       |
|       |   +---------+   |       |
|       |                 |       |
|       |   +---------+   |       |
|       |   |  NAME   |   |       |
|       |   +---------+   |       |
|       |                 |       |
|       |    HYPERLINK    |       |
|       +-----------------+       |
|            CONTAINER            |
+---------------------------------+

*/

function loadAppLinks(appLinkInfo, container) {

  // AppLink Object declaration
  function AppLink (name, image, link, color, tabindex) {

    // Create picture
    this.picture = document.createElement('img');
    this.picture.setAttribute('class', 'appLinkPic');
    this.picture.src = image;
    this.picture.alt = name;
    if (color) this.picture.style.backgroundColor = color;

    // Create Name
    this.name = document.createElement('p');
    this.name.setAttribute('class', 'appLinkName');
    this.name.appendChild(document.createTextNode(name));

    // Create HyperLink
    this.hyperLink = document.createElement('a');
    this.hyperLink.setAttribute('class', 'appLinkHyperLink');
    this.hyperLink.setAttribute('href', link);
    this.hyperLink.setAttribute('onclick', 'putSearchQuery(this)');
    this.hyperLink.setAttribute('ontouchstart', '');
    if (tabindex) this.hyperLink.setAttribute('tabindex', tabindex);
    this.hyperLink.appendChild(this.picture);
    this.hyperLink.appendChild(this.name);

    // Create Container
    this.container = document.createElement('div');
    this.container.setAttribute('class', 'appLinkContainer');
    this.container.appendChild(this.hyperLink);
  }

  if (!container) container = document.body

  // Create a link for every sub-array within appLinkInfo.
  for (var i = 0; i < appLinkInfo.names.length; i++) {
    var tmp = new AppLink(appLinkInfo.names[i], appLinkInfo.imageurls[i], appLinkInfo.links[i], appLinkInfo.backgroundColors[i], i+1);
    container.appendChild(tmp.container);
  }

  // Extend container to contain all AppLinks
  var clearFix = document.createElement('div');
  clearFix.setAttribute('class', 'clearfix');
  container.appendChild(clearFix);

  rootSearchTree = appLinkInfo.aliases;
}
<|endoftext|>


<commit_before>var asciify = {};

asciify.maps = {
    "TEN": "@#%*+=-:. ",
    "FIVE": "@=:. ",
    "TWO": "@ "
};

asciify.defaults = {
    width: 100,
    map: asciify.maps.TEN,
    resolutionY: 0.6
};

asciify.asciify = function(image, config) {
    var options = asciify.defaults;
    if (config && typeof config === "object" && !Array.isArray(config)) {
        Object.keys(config).forEach(function(key){
            options[key] = config[key];
        });
    }

    if (image) {
        var map = options.map;
        var width = options.width;
        var resolutionY = options.resolutionY;

        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext("2d");

        if (image instanceof HTMLCanvasElement ||
            image instanceof Image || image instanceof HTMLImageElement || image instanceof HTMLVideoElement) {
            var ratio = image.width / image.height;
            canvas.width = width;
            canvas.height = width / ratio * resolutionY;
            ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
        } else {
            return false;
        }

        var data = ctx.getImageData(0,0,canvas.width,canvas.height).data;

        for (i=0; i<data.length; i+=4)  { // greyscale the image
            var brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2];
            data[i] = brightness;
        }

        var asciiPixels = [];

        for (i=0; i<data.length; i+=4) { // do reds only, since it is greyscale

            var rchar = map[Math.round((map.length-1)*data[i]/255)];
            asciiPixels.push(rchar);

            if (Math.ceil((i+1)/4) % width == 0) {
                asciiPixels.push("\n");
            }
        }

        return asciiPixels.join("");
    } else {
        return false;
    }
};<commit_msg>Add new brightness maps<commit_after>var asciify = {};

asciify.maps = {
    "TEN": "@#%*+=-:. ",
    "FIVE": "@=:. ",
    "FOUR_BLOCK": "█▓▒░",
    "TWO": "@ ",
    "TWO_BLOCK": "█ "
};

asciify.defaults = {
    width: 100,
    map: asciify.maps.TEN,
    resolutionY: 0.6
};

asciify.asciify = function(image, config) {
    var options = asciify.defaults;
    if (config && typeof config === "object" && !Array.isArray(config)) {
        Object.keys(config).forEach(function(key){
            options[key] = config[key];
        });
    }

    if (image) {
        var map = options.map;
        var width = options.width;
        var resolutionY = options.resolutionY;

        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext("2d");

        if (image instanceof HTMLCanvasElement ||
            image instanceof Image || image instanceof HTMLImageElement || image instanceof HTMLVideoElement) {
            var ratio = image.width / image.height;
            canvas.width = width;
            canvas.height = width / ratio * resolutionY;
            ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
        } else {
            return false;
        }

        var data = ctx.getImageData(0,0,canvas.width,canvas.height).data;

        for (i=0; i<data.length; i+=4)  { // greyscale the image
            var brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2];
            data[i] = brightness;
        }

        var asciiPixels = [];

        for (i=0; i<data.length; i+=4) { // do reds only, since it is greyscale

            var rchar = map[Math.round((map.length-1)*data[i]/255)];
            asciiPixels.push(rchar);

            if (Math.ceil((i+1)/4) % width == 0) {
                asciiPixels.push("\n");
            }
        }

        return asciiPixels.join("");
    } else {
        return false;
    }
};<|endoftext|>