<commit_before>// Simulate config options from your production environment by
// customising the .env file in your project's root folder.
require('newrelic');
require('dotenv').load();

// Require keystone
var newrelic = require('newrelic');
var keystone = require('keystone');

// Initialise Keystone with your project's configuration.
// See http://keystonejs.com/guide/config for available options
// and documentation.

keystone.init({
	'cloudinary config': 'cloudinary://695316824865783:k0S8UONMrXUYsJj2I4Ii-yferjU@hsnbgtcq2',

	'name': 'KeystoneJS',
	'brand': 'KeystoneJS',

	'less': 'public',

	'static': 'public',
	'favicon': 'public/favicon.ico',
	'views': 'templates/views',
	'view engine': 'jade',

	'emails': 'templates/emails',

	'auto update': true,
	'session': true,
	'session store': 'mongo',
	'auth': true,
	'user model': 'User'

});

// Load your project's Models

keystone.import('models');

// Your cookie secret is used to secure session cookies. This environment
// variable was added to your Heroku config for you if you used the "Deploy to
// Heroku" button. The secret below will be used for development.
// You may want to set it to something private and secure.

if (!keystone.get('cookie secret')) {
	keystone.set('cookie secret', '----change-me-to-something-secret----');
}

// Setup common locals for your templates. The following are required for the
// bundled templates and layouts. Any runtime locals (that should be set uniquely
// for each request) should be added to ./routes/middleware.js

keystone.set('locals', {
	_: require('underscore'),
	env: keystone.get('env'),
	utils: keystone.utils,
	editable: keystone.content.editable
});

// Load your project's Routes

keystone.set('routes', require('./routes'));

// Setup common locals for your emails. The following are required by Keystone's
// default email templates, you may remove them if you're using your own.

// You should ensure you have the EMAIL_HOSTNAME environment variable set on
// your production / staging servers, or images and links in your emails will
// default to http://localhost:3000.

var email_hostname = process.env.EMAIL_HOSTNAME || 'localhost:3000';

keystone.set('email locals', {
	server: 'http://' + email_hostname,
	logo_src: 'http://' + email_hostname + '/images/logo-email.gif',
	logo_width: 194,
	logo_height: 76,
	theme: {
		email_bg: '#f9f9f9',
		link_color: '#2697de',
		buttons: {
			color: '#fff',
			background_color: '#2697de',
			border_color: '#1a7cb7'
		}
	}
});

// Load your project's email test routes

keystone.set('email tests', require('./routes/emails'));

// Configure the navigation bar in Keystone's Admin UI

keystone.set('nav', {
	'posts': ['posts', 'post-categories'],
	'galleries': 'galleries',
	'enquiries': 'enquiries',
	'users': 'users'
});

// Start Keystone to connect to your database and initialise the web server
keystone.start();<commit_msg>make it better<commit_after>// Simulate config options from your production environment by
// customising the .env file in your project's root folder.
require('dotenv').load();

// Require keystone
var newrelic = require('newrelic');
var keystone = require('keystone');

// Initialise Keystone with your project's configuration.
// See http://keystonejs.com/guide/config for available options
// and documentation.

keystone.init({
	'cloudinary config': 'cloudinary://695316824865783:k0S8UONMrXUYsJj2I4Ii-yferjU@hsnbgtcq2',

	'name': 'KeystoneJS',
	'brand': 'KeystoneJS',

	'less': 'public',

	'static': 'public',
	'favicon': 'public/favicon.ico',
	'views': 'templates/views',
	'view engine': 'jade',

	'emails': 'templates/emails',

	'auto update': true,
	'session': true,
	'session store': 'mongo',
	'auth': true,
	'user model': 'User'

});

// Load your project's Models

keystone.import('models');

// Your cookie secret is used to secure session cookies. This environment
// variable was added to your Heroku config for you if you used the "Deploy to
// Heroku" button. The secret below will be used for development.
// You may want to set it to something private and secure.

if (!keystone.get('cookie secret')) {
	keystone.set('cookie secret', '----change-me-to-something-secret----');
}

// Setup common locals for your templates. The following are required for the
// bundled templates and layouts. Any runtime locals (that should be set uniquely
// for each request) should be added to ./routes/middleware.js

keystone.set('locals', {
	_: require('underscore'),
	env: keystone.get('env'),
	utils: keystone.utils,
	editable: keystone.content.editable
});

// Load your project's Routes

keystone.set('routes', require('./routes'));

// Setup common locals for your emails. The following are required by Keystone's
// default email templates, you may remove them if you're using your own.

// You should ensure you have the EMAIL_HOSTNAME environment variable set on
// your production / staging servers, or images and links in your emails will
// default to http://localhost:3000.

var email_hostname = process.env.EMAIL_HOSTNAME || 'localhost:3000';

keystone.set('email locals', {
	server: 'http://' + email_hostname,
	logo_src: 'http://' + email_hostname + '/images/logo-email.gif',
	logo_width: 194,
	logo_height: 76,
	theme: {
		email_bg: '#f9f9f9',
		link_color: '#2697de',
		buttons: {
			color: '#fff',
			background_color: '#2697de',
			border_color: '#1a7cb7'
		}
	}
});

// Load your project's email test routes

keystone.set('email tests', require('./routes/emails'));

// Configure the navigation bar in Keystone's Admin UI

keystone.set('nav', {
	'posts': ['posts', 'post-categories'],
	'galleries': 'galleries',
	'enquiries': 'enquiries',
	'users': 'users'
});

// Start Keystone to connect to your database and initialise the web server
keystone.start();<|endoftext|>


<commit_before>var check = require("validator").check,
    fs    = require("fs");

var Validator = {
  validationErrors: [],

  // validates an object and return, return its errors
  validate: function(modelName, object, callback) {
    var validationsFilePath = __dirname + "/../app/validations/" + modelName + ".validations.json";
    var that = this;

    fs.stat(validationsFilePath, function(err) {
      if (err) {
        return console.log("Error reading validations file.");

      } else {
        var content = fs.readFileSync(validationsFilePath, "utf8"),
            validations = JSON.parse(content);

        that.validationErrors = [];

        for (var fieldValidationIndex in validations) {
          for (var fieldName in validations[fieldValidationIndex]) {
            that.validateField(fieldName, validations[fieldValidationIndex][fieldName], object[fieldName]);
          }
        }

        return callback((that.validationErrors.length > 0 ? that.validationErrors : null));
      }
    });
  },

  // adds an error to the collection
  addErrorsToMessages: function(req, errors) {
    for (var errorIndex in errors) {
      this.messages.addMessage(req, "error", errors[errorIndex]);
    }
  },

  // validates a field with it's specified validations
  validateField: function(fieldName, fieldValidations, value) {
    for (var validatorIndex in fieldValidations) {
      for (var validator in fieldValidations[validatorIndex]) {
        this.useValidator(fieldName, validator, fieldValidations[validatorIndex][validator], value);
      }
    }
  },

  // uses a specified validator with a specified value
  useValidator: function(fieldName, validatorName, argument, value) {
    // todo: find another way, I hate this switch.
    switch (validatorName) {
      case "minimumLength":
        return this.validatorMinimumLength(fieldName, value, argument);
      default:
        return console.log("Validator (" + validatorName + ") has not been found.");
    }
  },

  // minimumLength validator
  validatorMinimumLength: function(fieldName, value, length) {
    var errorMessage = "The value entered for \"" + fieldName + "\" (" + value + ") is too short (minimum of " + length + " character(s)).";

    try {
      return check(value, errorMessage).len(length);
    } catch (e) {
      return this.validationErrors.push(e.message);
    }
  }
};

module.exports = Validator;<commit_msg>Objects should be able to be saved even without validations file.<commit_after>var check = require("validator").check,
    fs    = require("fs");

var Validator = {
  validationErrors: [],

  // validates an object and return, return its errors
  validate: function(modelName, object, callback) {
    var validationsFilePath = __dirname + "/../app/validations/" + modelName + ".validations.json";
    var that = this;

    fs.stat(validationsFilePath, function(err) {
      if (err) {
        console.log("Error reading validations file.");
        return callback(null);

      } else {
        var content = fs.readFileSync(validationsFilePath, "utf8"),
            validations = JSON.parse(content);

        that.validationErrors = [];

        for (var fieldValidationIndex in validations) {
          for (var fieldName in validations[fieldValidationIndex]) {
            that.validateField(fieldName, validations[fieldValidationIndex][fieldName], object[fieldName]);
          }
        }

        return callback((that.validationErrors.length > 0 ? that.validationErrors : null));
      }
    });
  },

  // adds an error to the collection
  addErrorsToMessages: function(req, errors) {
    for (var errorIndex in errors) {
      this.messages.addMessage(req, "error", errors[errorIndex]);
    }
  },

  // validates a field with it's specified validations
  validateField: function(fieldName, fieldValidations, value) {
    for (var validatorIndex in fieldValidations) {
      for (var validator in fieldValidations[validatorIndex]) {
        this.useValidator(fieldName, validator, fieldValidations[validatorIndex][validator], value);
      }
    }
  },

  // uses a specified validator with a specified value
  useValidator: function(fieldName, validatorName, argument, value) {
    // todo: find another way, I hate this switch.
    switch (validatorName) {
      case "minimumLength":
        return this.validatorMinimumLength(fieldName, value, argument);
      default:
        return console.log("Validator (" + validatorName + ") has not been found.");
    }
  },

  // minimumLength validator
  validatorMinimumLength: function(fieldName, value, length) {
    var errorMessage = "The value entered for \"" + fieldName + "\" (" + value + ") is too short (minimum of " + length + " character(s)).";

    try {
      return check(value, errorMessage).len(length);
    } catch (e) {
      return this.validationErrors.push(e.message);
    }
  }
};

module.exports = Validator;
<|endoftext|>


<commit_before>var _ = require('eakwell');
var THREE = require('three');

var Posit = require('./posit.js').Posit;
var VideoSource = require('./videoSource.js');

var ColorTracker = function(cb, width, height) {
  width = width || 640;
  height = height || 480;

  var tracksPerSecond = 4;

  var source = new VideoSource(width, height);

  // Register a named color with the tracker
  // Colors that differ less than the given thresholds
  // in HSL color space are considered for tracking
  var registerColor = function(name, color, deviation) {
    var hsl = color.getHSL();
    var pixelColor = new THREE.Color();
    tracking.ColorTracker.registerColor(name, function(r, g, b) {
      pixelColor.setRGB(r / 255, g / 255, b / 255);
      var hslPixel = pixelColor.getHSL();
      return Math.abs(hslPixel.h - hsl.h) < deviation.dh &&
             Math.abs(hslPixel.s - hsl.s) < deviation.ds &&
             Math.abs(hslPixel.l - hsl.l) < deviation.dl;
    });
  };

  var deviations = {
    apple: {dh: 0.1, ds: 0.3, dl: 0.3},
    cardinal: {dh: 0.1, ds: 0.15, dl: 0.15},
    magenta: {dh: 0.1, ds: 0.3, dl: 0.3},
    cyan: {dh: 0.1, ds: 0.3, dl: 0.3}
  };

  var colorDefinitions = {
    apple: new THREE.Color(137 / 255, 193 / 255, 114 / 255),
    cardinal: new THREE.Color(115 / 255, 38  / 255, 93  / 255)
  };

  // Make custom colors known to tracker
  var registerColors = function() {
    _.each(colorDefinitions, function(color, name) {
      registerColor(name, color, deviations[name]);
    });
  };

  registerColors();

  // Combinations of color that represent a single entity
  var colorCombos = {
    head: ['apple'],
    // left: ['magenta', 'cyan'],
    // right: ['cardinal', 'cyan'],
    ground: ['cardinal']
  };

  var colors;
  var tracker;

  // Initialize tracker with all colors needed
  var configureTracker = function(combos) {
    colors = _.unique(_.flatten(_.values(combos)));
    tracker = new tracking.ColorTracker(colors);
  };

  configureTracker(colorCombos);

  // Return all blobs that match any of the used colors
  var detectBlobs = function(imageData) {
    var blobs;
    // Register for track event
    tracker.once('track', function(e) {
      blobs = _.map(e.data, function(rect) {
        // Convert to the simpler center + radius format
        return {
          color: rect.color,
          position: {
            x: rect.x + (rect.width / 2),
            y: rect.y + (rect.height / 2)
          },
          radius: (rect.width + rect.height) / 4
        };
      });
    });
    // Emit track event
    tracker.track(imageData.data, width, height);
    return blobs;
  };

  // Draw rectangles around blobs
  var drawBlobs = function(blobs, context) {
    _.each(blobs, function(blob) {
      context.strokeStyle = blob.color;
      context.strokeRect(blob.position.x - blob.radius, blob.position.y - blob.radius, blob.radius * 2, blob.radius * 2);
      context.font = '11px Helvetica';
      context.fillStyle = "#fff";
      context.fillText(blob.color, blob.position.x - blob.radius, blob.position.y + blob.radius + 11);
      context.fillText('x: ' + blob.position.x + 'px', blob.position.x - blob.radius, blob.position.y + blob.radius + 22);
      context.fillText('y: ' + blob.position.y + 'px', blob.position.x - blob.radius, blob.position.y + blob.radius + 33);
    });
  };

  // Combine adjacent blobs to form groups
  var makeContactGroups = function(blobs) {
    blobs = _.clone(blobs);
    var groups = [];
    var blob;
    while(blob = blobs.pop()) {
      // Find an existing group that this blob makes contact with
      var group = _.find(groups, function(group) {
        return _.any(group, function(blo) {
          var mergeThreshold = 5; // px
          // Check actual distance between blob borders
          var dist = distance(blob.position, blo.position) - blob.radius - blo.radius;
          return dist < mergeThreshold;
        });
      });
      if(group) {
        // Add to existing group
        group.push(blob);
      } else {
        // Start new group
        groups.push([blob]);
      }
    }
    return groups;
  };

  // Return all color groups forming a
  // four corner marker in the given image
  var detectMarkers = function(blobs) {
    // Group adjacent blobs to form markers
    var groups = makeContactGroups(blobs);
    // if(groups.length) console.log(groups);
    // Find a matching group for every body part
    var markers = _.map(colorCombos, function(combo) {
      var group = _.find(groups, function(group) {
        // Check if the set of used colors is the same
        if(group.length != 4) return false;
        var groupColors = _.unique(_.map(group, 'color'));
        return !_.difference(groupColors, combo).length;
      });
      return group ? _.map(group, 'position') : null;
    });
    //XXX Order corners correctly
    return markers;
  };

  // Return the real world position and
  // orientation of the given marker
  var poseFromMarker = function(marker) {
    var markerSize = 70; // mm
    var posit = new Posit(markerSize, width);
    // Corners must be centered on canvas
    var corners = _.map(marker, function(corner) {
      return {
        x: corner.x - (width / 2),
        y: (height / 2) - corner.y
      };
    });
    var pose = posit.pose(corners);
    console.log(marker);
    console.log(pose);
    return {
      position: pose.bestTranslation,
      rotation: pose.bestRotation
    };
  };

  // Adjust color deviations to yield
  // more stable tracker performance
  var calibrateColors = function(imageData) {
    // Calibrate each color separately
    _.each(colorDefinitions, function(color, name) {
      // Return number of markers found for this color with given calibration
      var matchesForDeviation = function(deviation) {
        deviations[name].dh = deviation;
        registerColors();
        var blobs = detectBlobs(imageData);
        var matchingBlobs = _.select(blobs, function(blob) {
          return blob.color == name;
        });
        return matchingBlobs.length;
      };
      var steps = 10;
      // Increase deviation until we first find a marker of this color
      var minDeviation = _.step(0.0, 1.0, steps, function(step) {
        if(matchesForDeviation(step) == 1) return step;
      });
      // Decrease deviation until we find only one marker
      var maxDeviation = _.step(0.0, 1.0, steps, function(step) {
        if(matchesForDeviation(1 - step) == 1) return 1 - step;
      });
      // Set final deviation to average of extremes
      deviations[name].dh = (minDeviation * 0.75 + maxDeviation * 0.25);
      console.log("Final deviation for " + name + ": " + deviations[name].dh);
    });
    registerColors();
  };

  // Replace reference colors with actual colors found in the image
  var repickColors = function(imageData) {
    var blobs = detectBlobs(imageData);
    _.each(blobs, function(blob) {
      var color = colorDefinitions[blob.color];
      if(!color) return;
      var pixel = colorAround(source.context, blob.position.x, blob.position.y);
      color.copy(pixel);
    });
    registerColors();
  };

  // Average color surrounding the given coordinates
  var colorAround = function(context, x, y) {
    var sum = {
      r: 0,
      g: 0,
      b: 0
    };
    var radius = 5;
    var steps = 0;
    _.step(x - radius, x + radius, radius * 2 + 1, function(sx) {
      _.step(x - radius, y + radius, radius * 2 + 1, function(sy) {
        var pixel = context.getImageData(sx, sy, 1, 1).data;
        if(pixel) {
          sum.r += pixel[0];
          sum.g += pixel[1];
          sum.b += pixel[2];
          steps++;
        }
      });
    });
    return new THREE.Color(sum.r / steps / 255, sum.g / steps / 255, sum.b / steps / 255);
  };

  // Find camera height and orientation
  // and adjust calibration accordingly
  var fovX = 70; // Degrees
  var fovY = 60;
  var radiusAtOneMeter = 15 / 640 * width;
  var camHeight = 60;
  var camRotation = 0; // Radians

  var calibrateSpace = function(imageData) {
    var blobs = detectBlobs(imageData);
    var groundMarkers = _.select(blobs, function(blob) {
      return blob.color == colorCombos.ground[0];
    });
    if(groundMarkers.length >= 2) {
      // Zero camera configuration to receive raw values
      camHeight = 0;
      camRotation = 0;
      // Find ground markers in camera space
      var positions = _.map(groundMarkers, function(marker) {
        return getBlobPosition(marker);
      });
      // Find angle between the vector from one marker to the other and the ground
      var firstIsGreater = positions[0].y > positions[1].y;
      var higherPos = firstIsGreater ? positions[0] : positions[1];
      var lowerPos  = firstIsGreater ? positions[1] : positions[0];
      var groundLine = higherPos.sub(lowerPos);
      var realGroundLine = groundLine.copy().setY(0);
      // Set camera rotation
      camRotation = groundLine.angleTo(realGroundLine);
      // Estimate marker positions again to determine ground level
      var positions = _.map(groundMarkers, function(marker) {
        return getBlobPosition(marker);
      });
      // Set camera height
      camHeight = -positions[0].y;
    } else {
      console.error("Calibration failed: Could not find ground markers");
    }
  };

  var calibrate = function() {
    var imageData = source.getData();
    // Make sure we find each marker exactly once
    calibrateColors(imageData);
    // Update colors to match actual colors found
    // repickColors(imageData);
    // Recalibrate for new colors
    // calibrateColors(imageData);
    // Now that we find all the markers, position the camera space
    // calibrateSpace(imageData);
  };

  // Get blob position in world space
  var getBlobPosition = function(blob) {
    var depth = radiusAtOneMeter / blob.radius;
    var angleX = -fovX * (blob.position.x / width - 0.5);
    var angleY = fovY * (blob.position.y / height - 0.5);
    var yAxis = new THREE.Vector3(0, 1, 0);
    var rotY = (new THREE.Quaternion()).setFromAxisAngle(yAxis, THREE.Math.degToRad(angleX));
    var xAxis = new THREE.Vector3(1, 0, 0);
    var camRot = (new THREE.Quaternion()).setFromAxisAngle(xAxis, camRotation);
    xAxis.applyQuaternion(rotY);
    var rotX = (new THREE.Quaternion()).setFromAxisAngle(xAxis, THREE.Math.degToRad(angleY));
    var position = new THREE.Vector3(0, 0, depth);
    position.applyQuaternion(rotY).applyQuaternion(rotX).applyQuaternion(camRot).multiplyScalar(200);
    position.setY(position.y + camHeight);
    // console.log(position);
    return position;
  };

  // Return head position if found
  var getHeadPosition = function(blobs) {
    var headBlob = _.find(blobs, function(blob) {
      return blob.color == colorCombos.head[0];
    });
    if(headBlob) {
      return getBlobPosition(headBlob);
    }
  };

  // Detect the world positions of
  // all body parts using the given image
  var getBodyParts = function(imageData) {
    var blobs = detectBlobs(imageData);
    var head = getHeadPosition(blobs);
    // var markers = detectMarkers(blobs);

    var markers = {
      head: {
        position: head
      },
      left: {
        position: head,
        active: false
      },
      right: {
        position: head,
        active: false
      }
    };

    // Draw rectangles back onto canvas
    drawBlobs(blobs, source.context);

    return markers;

    // var poses = _.map(markers, function(marker) {
    //   return marker && poseFromMarker(marker);
    // });
    // return poses;
  };

  var lastNow;

  var tick = function() {
    if(!self.running) return;
    // Rate limit detector to give garbage collector some time between frames
    requestAnimationFrame(tick);
    var now = new Date().getTime();
    var delta = now - (lastNow || now);
    if(delta && delta < 1000 / tracksPerSecond) return;
    lastNow = now;
    // Get image pixels
    var imageData = source.getData();
    if(!imageData) return;
    // Detect head and hand positions and orientations
    var body = getBodyParts(imageData);
    cb(body);
  };

  var self = {
    running: false,
    videoSource: source,

    start: function() {
      if(self.running) return _.promiseFrom(null);
      self.running = true;
      return source.play().then(tick);
    },

    stop: function() {
      self.running = false;
      return source.pause();
    },

    calibrate: function(cb) {
      source.play().then(function() {
        _.waitFor(function() {
          return source.getData();
        }, function() {
          calibrate();
          cb();
        });
      });
    }
  };

  return self;
};

var distance = function(p1, p2) {
  return Math.sqrt(_.square(p1.x - p2.x) + _.square(p1.y - p2.y));
};

module.exports = ColorTracker;
<commit_msg>Configure tracker settings<commit_after>var _ = require('eakwell');
var THREE = require('three');

var Posit = require('./posit.js').Posit;
var VideoSource = require('./videoSource.js');

var ColorTracker = function(cb, width, height) {
  width = width || 640;
  height = height || 480;

  var tracksPerSecond = 4;

  var source = new VideoSource(width, height);

  // Register a named color with the tracker
  // Colors that differ less than the given thresholds
  // in HSL color space are considered for tracking
  var registerColor = function(name, color, deviation) {
    // var hsl = color.getHSL();
    var pixelColor = new THREE.Color();
    tracking.ColorTracker.registerColor(name, function(r, g, b) {
      pixelColor.setRGB(r / 255, g / 255, b / 255);
      return Math.abs(pixelColor.r - color.r) + Math.abs(pixelColor.g - color.g) +  Math.abs(pixelColor.b - color.b) / 3 < deviation.dh;
      // var hslPixel = pixelColor.getHSL();
      // return Math.abs(hslPixel.h - hsl.h) < deviation.dh &&
      //        Math.abs(hslPixel.s - hsl.s) < deviation.ds &&
      //        Math.abs(hslPixel.l - hsl.l) < deviation.dl;
    });
  };

  var deviations = {
    apple: {dh: 0.15, ds: 0.3, dl: 0.2},
    cardinal: {dh: 0.1, ds: 0.15, dl: 0.15},
    magenta: {dh: 0.1, ds: 0.3, dl: 0.3},
    cyan: {dh: 0.1, ds: 0.3, dl: 0.3}
  };

  var colorDefinitions = {
    apple: new THREE.Color(137 / 255, 193 / 255, 114 / 255),
    cardinal: new THREE.Color(115 / 255, 38  / 255, 93  / 255)
  };

  // Make custom colors known to tracker
  var registerColors = function() {
    _.each(colorDefinitions, function(color, name) {
      registerColor(name, color, deviations[name]);
    });
  };

  registerColors();

  // Combinations of color that represent a single entity
  var colorCombos = {
    head: ['apple'],
    // left: ['magenta', 'cyan'],
    // right: ['cardinal', 'cyan'],
    ground: ['cardinal']
  };

  var colors;
  var tracker;

  // Initialize tracker with all colors needed
  var configureTracker = function(combos) {
    colors = _.unique(_.flatten(_.values(combos)));
    tracker = new tracking.ColorTracker(colors);
    tracker.setMinDimension(10);
    tracker.setMaxDimension(height * 2 / 3);
    tracker.setMinGroupSize(50);
  };

  configureTracker(colorCombos);

  // Return all blobs that match any of the used colors
  var detectBlobs = function(imageData) {
    var blobs;
    // Register for track event
    tracker.once('track', function(e) {
      blobs = _.map(e.data, function(rect) {
        // Convert to the simpler center + radius format
        return {
          color: rect.color,
          position: {
            x: rect.x + (rect.width / 2),
            y: rect.y + (rect.height / 2)
          },
          radius: (rect.width + rect.height) / 4
        };
      });
    });
    // Emit track event
    tracker.track(imageData.data, width, height);
    return blobs;
  };

  // Draw rectangles around blobs
  var drawBlobs = function(blobs, context) {
    _.each(blobs, function(blob) {
      context.strokeStyle = blob.color;
      context.strokeRect(blob.position.x - blob.radius, blob.position.y - blob.radius, blob.radius * 2, blob.radius * 2);
      context.font = '11px Helvetica';
      context.fillStyle = "#fff";
      context.fillText(blob.color, blob.position.x - blob.radius, blob.position.y + blob.radius + 11);
      context.fillText('x: ' + blob.position.x + 'px', blob.position.x - blob.radius, blob.position.y + blob.radius + 22);
      context.fillText('y: ' + blob.position.y + 'px', blob.position.x - blob.radius, blob.position.y + blob.radius + 33);
    });
  };

  // Combine adjacent blobs to form groups
  var makeContactGroups = function(blobs) {
    blobs = _.clone(blobs);
    var groups = [];
    var blob;
    while(blob = blobs.pop()) {
      // Find an existing group that this blob makes contact with
      var group = _.find(groups, function(group) {
        return _.any(group, function(blo) {
          var mergeThreshold = 5; // px
          // Check actual distance between blob borders
          var dist = distance(blob.position, blo.position) - blob.radius - blo.radius;
          return dist < mergeThreshold;
        });
      });
      if(group) {
        // Add to existing group
        group.push(blob);
      } else {
        // Start new group
        groups.push([blob]);
      }
    }
    return groups;
  };

  // Return all color groups forming a
  // four corner marker in the given image
  var detectMarkers = function(blobs) {
    // Group adjacent blobs to form markers
    var groups = makeContactGroups(blobs);
    // if(groups.length) console.log(groups);
    // Find a matching group for every body part
    var markers = _.map(colorCombos, function(combo) {
      var group = _.find(groups, function(group) {
        // Check if the set of used colors is the same
        if(group.length != 4) return false;
        var groupColors = _.unique(_.map(group, 'color'));
        return !_.difference(groupColors, combo).length;
      });
      return group ? _.map(group, 'position') : null;
    });
    //XXX Order corners correctly
    return markers;
  };

  // Return the real world position and
  // orientation of the given marker
  var poseFromMarker = function(marker) {
    var markerSize = 70; // mm
    var posit = new Posit(markerSize, width);
    // Corners must be centered on canvas
    var corners = _.map(marker, function(corner) {
      return {
        x: corner.x - (width / 2),
        y: (height / 2) - corner.y
      };
    });
    var pose = posit.pose(corners);
    console.log(marker);
    console.log(pose);
    return {
      position: pose.bestTranslation,
      rotation: pose.bestRotation
    };
  };

  // Adjust color deviations to yield
  // more stable tracker performance
  var calibrateColors = function(imageData) {
    // Calibrate each color separately
    _.each(colorDefinitions, function(color, name) {
      // Return number of markers found for this color with given calibration
      var matchesForDeviation = function(deviation) {
        deviations[name].dh = deviation;
        registerColors();
        var blobs = detectBlobs(imageData);
        var matchingBlobs = _.select(blobs, function(blob) {
          return blob.color == name;
        });
        return matchingBlobs.length;
      };
      var steps = 30;
      // Increase deviation until we first find a marker of this color
      var minDeviation = _.step(0.0, 1.0, steps, function(step) {
        if(matchesForDeviation(step) == 1) return step;
      });
      // Decrease deviation until we find only one marker
      var maxDeviation = _.step(0.0, 1.0, steps, function(step) {
        if(matchesForDeviation(1 - step) == 1) return 1 - step;
      });
      // Set final deviation to average of extremes
      deviations[name].dh = (minDeviation * 0.75 + maxDeviation * 0.25);
      console.log("Final deviation for " + name + ": " + deviations[name].dh);
    });
    registerColors();
  };

  // Replace reference colors with actual colors found in the image
  var repickColors = function(imageData) {
    var blobs = detectBlobs(imageData);
    _.each(blobs, function(blob) {
      var color = colorDefinitions[blob.color];
      if(!color) return;
      var pixel = colorAround(source.context, blob.position.x, blob.position.y);
      color.copy(pixel);
    });
    registerColors();
  };

  // Average color surrounding the given coordinates
  var colorAround = function(context, x, y) {
    var sum = {
      r: 0,
      g: 0,
      b: 0
    };
    var radius = 5;
    var steps = 0;
    _.step(x - radius, x + radius, radius * 2 + 1, function(sx) {
      _.step(x - radius, y + radius, radius * 2 + 1, function(sy) {
        var pixel = context.getImageData(sx, sy, 1, 1).data;
        if(pixel) {
          sum.r += pixel[0];
          sum.g += pixel[1];
          sum.b += pixel[2];
          steps++;
        }
      });
    });
    return new THREE.Color(sum.r / steps / 255, sum.g / steps / 255, sum.b / steps / 255);
  };

  // Find camera height and orientation
  // and adjust calibration accordingly
  var fovX = 70; // Degrees
  var fovY = 60;
  var radiusAtOneMeter = 15 / 640 * width;
  var camHeight = 60;
  var camRotation = 0; // Radians

  var calibrateSpace = function(imageData) {
    var blobs = detectBlobs(imageData);
    var groundMarkers = _.select(blobs, function(blob) {
      return blob.color == colorCombos.ground[0];
    });
    if(groundMarkers.length >= 2) {
      // Zero camera configuration to receive raw values
      camHeight = 0;
      camRotation = 0;
      // Find ground markers in camera space
      var positions = _.map(groundMarkers, function(marker) {
        return getBlobPosition(marker);
      });
      // Find angle between the vector from one marker to the other and the ground
      var firstIsGreater = positions[0].y > positions[1].y;
      var higherPos = firstIsGreater ? positions[0] : positions[1];
      var lowerPos  = firstIsGreater ? positions[1] : positions[0];
      var groundLine = higherPos.sub(lowerPos);
      var realGroundLine = groundLine.copy().setY(0);
      // Set camera rotation
      camRotation = groundLine.angleTo(realGroundLine);
      // Estimate marker positions again to determine ground level
      var positions = _.map(groundMarkers, function(marker) {
        return getBlobPosition(marker);
      });
      // Set camera height
      camHeight = -positions[0].y;
    } else {
      console.error("Calibration failed: Could not find ground markers");
    }
  };

  var calibrate = function() {
    var imageData = source.getData();
    // Make sure we find each marker exactly once
    calibrateColors(imageData);
    // Update colors to match actual colors found
    // repickColors(imageData);
    // Recalibrate for new colors
    // calibrateColors(imageData);
    // Now that we find all the markers, position the camera space
    // calibrateSpace(imageData);
  };

  // Get blob position in world space
  var getBlobPosition = function(blob) {
    var depth = radiusAtOneMeter / blob.radius;
    var angleX = -fovX * (blob.position.x / width - 0.5);
    var angleY = fovY * (blob.position.y / height - 0.5);
    var yAxis = new THREE.Vector3(0, 1, 0);
    var rotY = (new THREE.Quaternion()).setFromAxisAngle(yAxis, THREE.Math.degToRad(angleX));
    var xAxis = new THREE.Vector3(1, 0, 0);
    var camRot = (new THREE.Quaternion()).setFromAxisAngle(xAxis, camRotation);
    xAxis.applyQuaternion(rotY);
    var rotX = (new THREE.Quaternion()).setFromAxisAngle(xAxis, THREE.Math.degToRad(angleY));
    var position = new THREE.Vector3(0, 0, depth);
    position.applyQuaternion(rotY).applyQuaternion(rotX).applyQuaternion(camRot).multiplyScalar(200);
    position.setY(position.y + camHeight);
    // console.log(position);
    return position;
  };

  // Return head position if found
  var getHeadPosition = function(blobs) {
    var headBlob = _.find(blobs, function(blob) {
      return blob.color == colorCombos.head[0];
    });
    if(headBlob) {
      return getBlobPosition(headBlob);
    }
  };

  // Detect the world positions of
  // all body parts using the given image
  var getBodyParts = function(imageData) {
    var blobs = detectBlobs(imageData);
    var head = getHeadPosition(blobs);
    // var markers = detectMarkers(blobs);

    var markers = {
      head: {
        position: head
      },
      left: {
        position: head,
        active: false
      },
      right: {
        position: head,
        active: false
      }
    };

    // Draw rectangles back onto canvas
    drawBlobs(blobs, source.context);

    return markers;

    // var poses = _.map(markers, function(marker) {
    //   return marker && poseFromMarker(marker);
    // });
    // return poses;
  };

  var lastNow;

  var tick = function() {
    if(!self.running) return;
    // Rate limit detector to give garbage collector some time between frames
    requestAnimationFrame(tick);
    var now = new Date().getTime();
    var delta = now - (lastNow || now);
    if(delta && delta < 1000 / tracksPerSecond) return;
    lastNow = now;
    // Get image pixels
    var imageData = source.getData();
    if(!imageData) return;
    // Detect head and hand positions and orientations
    var body = getBodyParts(imageData);
    cb(body);
  };

  var self = {
    running: false,
    videoSource: source,

    start: function() {
      if(self.running) return _.promiseFrom(null);
      self.running = true;
      return source.play().then(tick);
    },

    stop: function() {
      self.running = false;
      return source.pause();
    },

    calibrate: function(cb) {
      source.play().then(function() {
        _.waitFor(function() {
          return source.getData();
        }, function() {
          calibrate();
          cb();
        });
      });
    }
  };

  return self;
};

var distance = function(p1, p2) {
  return Math.sqrt(_.square(p1.x - p2.x) + _.square(p1.y - p2.y));
};

module.exports = ColorTracker;
<|endoftext|>


<commit_before>'use strict';
var util = require('util'),
    fs = require('fs'),
    generators = require('yeoman-generator'),
    exec = require('child_process').exec,
    chalk = require('chalk'),
    _ = require('lodash'),
    glob = require('glob'),
    scriptBase = require('../generator-base');

const constants = require('../generator-constants');

var HerokuGenerator = generators.Base.extend({});

util.inherits(HerokuGenerator, scriptBase);

module.exports = HerokuGenerator.extend({
    constructor: function () {
        generators.Base.apply(this, arguments);
    },
    initializing: function () {
        this.log(chalk.bold('Heroku configuration is starting'));
        this.env.options.appPath = this.config.get('appPath') || constants.CLIENT_MAIN_SRC_DIR;
        this.baseName = this.config.get('baseName');
        this.packageName = this.config.get('packageName');
        this.packageFolder = this.config.get('packageFolder');
        this.hibernateCache = this.config.get('hibernateCache');
        this.databaseType = this.config.get('databaseType');
        this.prodDatabaseType = this.config.get('prodDatabaseType');
        this.angularAppName = this.getAngularAppName();
        this.buildTool = this.config.get('buildTool');
        this.applicationType = this.config.get('applicationType');
        this.herokuAppName = this.config.get('herokuAppName');
    },

    prompting: function () {
        var done = this.async();

        if (this.herokuAppName) {
            exec('heroku apps:info --json', function (err, stdout) {
                if (err) {
                    this.abort = true;
                    this.log.error(err);
                } else {
                    var json = JSON.parse(stdout);
                    this.herokuAppName = json['app']['name'];
                    this.log(`Deploying as existing app: ${chalk.bold(this.herokuAppName)}`);
                    this.herokuAppExists = true;
                    this.config.set('herokuAppName', this.herokuAppName);
                }
                done();
            }.bind(this));
        } else {
            var prompts = [
                {
                    type: 'input',
                    name: 'herokuAppName',
                    message: 'Name to deploy as:',
                    default: this.baseName
                },
                {
                    type: 'list',
                    name: 'herokuRegion',
                    message: 'On which region do you want to deploy ?',
                    choices: ['us', 'eu'],
                    default: 0
                }];

            this.prompt(prompts).then(function (props) {
                this.herokuAppName = _.kebabCase(props.herokuAppName);
                this.herokuRegion = props.herokuRegion;
                this.herokuAppExists = false;
                done();
            }.bind(this));
        }
    },
    configuring: {
        checkInstallation: function () {
            if (this.abort) return;
            var done = this.async();

            exec('heroku --version', function (err) {
                if (err) {
                    this.log.error('You don\'t have the Heroku Toolbelt installed. ' +
                        'Download it from https://toolbelt.heroku.com/');
                    this.abort = true;
                }
                done();
            }.bind(this));
        }
    },

    default: {
        insight: function () {
            var insight = this.insight();
            insight.trackWithEvent('generator', 'heroku');
        },

        gitInit: function () {
            if (this.abort) return;
            var done = this.async();

            try {
                fs.lstatSync('.git');
                this.log(chalk.bold('\nUsing existing Git repository'));
                done();
            } catch (e) {
                // An exception is thrown if the folder doesn't exist
                this.log(chalk.bold('\nInitializing Git repository'));
                var child = exec('git init', {}, function (err, stdout, stderr) {
                    done();
                }.bind(this));
                child.stdout.on('data', function (data) {
                    this.log(data.toString());
                }.bind(this));
            }
        },

        installHerokuDeployPlugin: function () {
            if (this.abort) return;
            var done = this.async();
            this.log(chalk.bold('\nInstalling Heroku CLI deployment plugin'));
            var child = exec('heroku plugins:install heroku-cli-deploy', function (err, stdout) {
                if (err) {
                    this.abort = true;
                    this.log.error(err);
                }
                done();
            }.bind(this));

            child.stdout.on('data', function (data) {
                this.log(data.toString());
            }.bind(this));
        },

        herokuCreate: function () {
            if (this.abort || this.herokuAppExists) return;
            var done = this.async();

            var regionParams = (this.herokuRegion !== 'us') ? ' --region ' + this.herokuRegion : '';

            this.log(chalk.bold('\nCreating Heroku application and setting up node environment'));
            var herokuCreateCmd = 'heroku create ' + this.herokuAppName + regionParams;
            this.log(herokuCreateCmd);

            var child = exec(herokuCreateCmd, {}, function (err, stdout, stderr) {
                if (err) {
                    if (stderr.indexOf('Name is already taken') > -1) {
                        var prompts = [
                            {
                                type: 'list',
                                name: 'herokuForceName',
                                message: 'The Heroku app "' + chalk.cyan(this.herokuAppName) + '" already exists! Use it anyways?',
                                choices: [{
                                    value: 'Yes',
                                    name: 'Yes, I have access to it'
                                }, {
                                    value: 'No',
                                    name: 'No, generate a random name'
                                }],
                                default: 0
                            }];

                        this.log('');
                        this.prompt(prompts).then(function (props) {
                            var getHerokuAppName = function(def, stdout) { return def; };
                            if (props.herokuForceName === 'Yes') {
                                herokuCreateCmd = 'heroku git:remote --app ' + this.herokuAppName;
                            } else {
                                herokuCreateCmd = 'heroku create ' + regionParams;

                                // Extract from "Created random-app-name-1234... done"
                                getHerokuAppName = function(def, stdout) { return stdout.substring(stdout.indexOf('https://') + 8, stdout.indexOf('.herokuapp')); };
                            }
                            exec(herokuCreateCmd, {}, function (err, stdout, stderr) {
                                if (err) {
                                    this.abort = true;
                                    this.log.error(err);
                                } else {
                                    this.herokuAppName = getHerokuAppName(this.herokuAppName, stdout);
                                    this.log(stdout.trim());
                                }
                                this.config.set('herokuAppName', this.herokuAppName);
                                done();
                            }.bind(this));
                        }.bind(this));
                    } else {
                        this.abort = true;
                        this.log.error(err);
                        done();
                    }
                } else {
                    done();
                }
            }.bind(this));

            child.stdout.on('data', function (data) {
                var output = data.toString();
                if (data.search('Heroku credentials') >= 0) {
                    this.abort = true;
                    this.log.error('Error: Not authenticated. Run \'heroku login\' to login to your heroku account and try again.');
                    done();
                } else {
                    this.log(output.trim());
                }
            }.bind(this));
        },

        herokuAddonsCreate: function() {
            if (this.abort) return;
            var done = this.async();

            var dbAddOn = '';
            if (this.prodDatabaseType === 'postgresql') {
                dbAddOn = 'heroku-postgresql --as DATABASE';
            } else if (this.prodDatabaseType === 'mysql') {
                dbAddOn = 'jawsdb:kitefin --as JAWSDB';
            } else if (this.prodDatabaseType === 'mariadb') {
                dbAddOn = 'jawsdb-maria:kitefin --as JAWSDB';
            } else if (this.prodDatabaseType === 'mongodb') {
                dbAddOn = 'mongolab:sandbox --as MONGODB';
            } else {
                return;
            }

            this.log(chalk.bold('\nProvisioning addons'));
            exec(`heroku addons:create ${dbAddOn}`, {}, function (err, stdout, stderr) {
                if (err) {
                    this.log('No new addons created');
                } else {
                    this.log(`Created ${dbAddOn}`);
                }
                done();
            }.bind(this));
        },

        configureJHipsterRegistry: function() {
            if (this.abort || this.herokuAppExists) return;
            var done = this.async();

            if (this.applicationType === 'microservice' || this.applicationType === 'gateway') {
                var prompts = [
                    {
                        type: 'input',
                        name: 'herokuJHipsterRegistry',
                        message: 'What is the URL of your JHipster Registry?'
                    }];

                this.log('');
                this.prompt(prompts).then(function (props) {
                    var configSetCmd = 'heroku config:set ' + 'JHIPSTER_REGISTRY_URL=' + props.herokuJHipsterRegistry + ' --app ' + this.herokuAppName;
                    var child = exec(configSetCmd, {}, function (err, stdout, stderr) {
                        if (err) {
                            this.abort = true;
                            this.log.error(err);
                        }
                        done();
                    }.bind(this));

                    child.stdout.on('data', function (data) {
                        this.log(data.toString());
                    }.bind(this));
                }.bind(this));
            } else {
                this.conflicter.resolve(function (err) {
                    done();
                });
            }
        },

        copyHerokuFiles: function () {
            if (this.abort) return;

            var done = this.async();
            this.log(chalk.bold('\nCreating Heroku deployment files'));

            this.template('_bootstrap-heroku.yml', constants.SERVER_MAIN_RES_DIR + '/config/bootstrap-heroku.yml');
            this.template('_application-heroku.yml', constants.SERVER_MAIN_RES_DIR + '/config/application-heroku.yml');
            this.template('_Procfile', 'Procfile');
            if (this.buildTool === 'gradle') {
                this.template('_heroku.gradle', 'gradle/heroku.gradle');
            }

            this.conflicter.resolve(function (err) {
                done();
            });
        },

        addHerokuBuildPlugin: function () {
            if (this.buildTool !== 'gradle') return;
            this.addGradlePlugin('gradle.plugin.com.heroku.sdk', 'heroku-gradle', '0.2.0');
            this.applyFromGradleScript('gradle/heroku');
        }
    },

    end: {
        productionBuild: function () {
            if (this.abort) return;
            var done = this.async();
            this.log(chalk.bold('\nBuilding application'));

            var child = this.buildApplication(this.buildTool, 'prod', function (err) {
                if (err) {
                    this.abort = true;
                    this.log.error(err);
                }
                done();
            }.bind(this));

            this.buildCmd = child.buildCmd;

            child.stdout.on('data', function (data) {
                var line = data.toString().trim();
                if (line.length !== 0) this.log(line);
            }.bind(this));

        },

        productionDeploy: function () {
            if (this.abort) return;
            var done = this.async();
            this.log(chalk.bold('\nDeploying application'));

            var warFileWildcard = 'target/*.war';
            if (this.buildTool === 'gradle') {
                warFileWildcard = 'build/libs/*.war';
            }

            var files = glob.sync(warFileWildcard, {});
            var warFile = files[0];
            var herokuDeployCommand = `heroku deploy:jar ${warFile} --app ${this.herokuAppName}`;

            this.log(chalk.bold('\nUploading your application code.\nThis may take ' + chalk.cyan('several minutes') + ' depending on your connection speed...'));
            var child = exec(herokuDeployCommand, function (err, stdout) {
                if (err) {
                    this.abort = true;
                    this.log.error(err);
                }
                this.log(chalk.green('\nYour app should now be live. To view it run\n\t' + chalk.bold('heroku open')));
                this.log(chalk.yellow('And you can view the logs with this command\n\t' + chalk.bold('heroku logs --tail')));
                this.log(chalk.yellow('After application modification, redeploy it with\n\t' + chalk.bold('yo jhipster:heroku')));
                done();
            }.bind(this));

            child.stdout.on('data', function (data) {
                var line = data.toString().trimRight();
                if (line.trim().length !== 0) this.log(line);
            }.bind(this));
        }
    }
});
<commit_msg>Report error if Heroku app is missing. Fixes #4875<commit_after>'use strict';
var util = require('util'),
    fs = require('fs'),
    generators = require('yeoman-generator'),
    exec = require('child_process').exec,
    chalk = require('chalk'),
    _ = require('lodash'),
    glob = require('glob'),
    scriptBase = require('../generator-base');

const constants = require('../generator-constants');

var HerokuGenerator = generators.Base.extend({});

util.inherits(HerokuGenerator, scriptBase);

module.exports = HerokuGenerator.extend({
    constructor: function () {
        generators.Base.apply(this, arguments);
    },
    initializing: function () {
        this.log(chalk.bold('Heroku configuration is starting'));
        this.env.options.appPath = this.config.get('appPath') || constants.CLIENT_MAIN_SRC_DIR;
        this.baseName = this.config.get('baseName');
        this.packageName = this.config.get('packageName');
        this.packageFolder = this.config.get('packageFolder');
        this.hibernateCache = this.config.get('hibernateCache');
        this.databaseType = this.config.get('databaseType');
        this.prodDatabaseType = this.config.get('prodDatabaseType');
        this.angularAppName = this.getAngularAppName();
        this.buildTool = this.config.get('buildTool');
        this.applicationType = this.config.get('applicationType');
        this.herokuAppName = this.config.get('herokuAppName');
    },

    prompting: function () {
        var done = this.async();

        if (this.herokuAppName) {
            exec('heroku apps:info --json', function (err, stdout) {
                if (err) {
                    this.config.set('herokuAppName', null);
                    this.abort = true;
                    this.log.error(`Could not find app: ${chalk.cyan(this.herokuAppName)}`);
                    this.log.error('Run the generator again to create a new app.');
                } else {
                    var json = JSON.parse(stdout);
                    this.herokuAppName = json['app']['name'];
                    this.log(`Deploying as existing app: ${chalk.bold(this.herokuAppName)}`);
                    this.herokuAppExists = true;
                    this.config.set('herokuAppName', this.herokuAppName);
                }
                done();
            }.bind(this));
        } else {
            var prompts = [
                {
                    type: 'input',
                    name: 'herokuAppName',
                    message: 'Name to deploy as:',
                    default: this.baseName
                },
                {
                    type: 'list',
                    name: 'herokuRegion',
                    message: 'On which region do you want to deploy ?',
                    choices: ['us', 'eu'],
                    default: 0
                }];

            this.prompt(prompts).then(function (props) {
                this.herokuAppName = _.kebabCase(props.herokuAppName);
                this.herokuRegion = props.herokuRegion;
                this.herokuAppExists = false;
                done();
            }.bind(this));
        }
    },
    configuring: {
        checkInstallation: function () {
            if (this.abort) return;
            var done = this.async();

            exec('heroku --version', function (err) {
                if (err) {
                    this.log.error('You don\'t have the Heroku Toolbelt installed. ' +
                        'Download it from https://toolbelt.heroku.com/');
                    this.abort = true;
                }
                done();
            }.bind(this));
        }
    },

    default: {
        insight: function () {
            var insight = this.insight();
            insight.trackWithEvent('generator', 'heroku');
        },

        gitInit: function () {
            if (this.abort) return;
            var done = this.async();

            try {
                fs.lstatSync('.git');
                this.log(chalk.bold('\nUsing existing Git repository'));
                done();
            } catch (e) {
                // An exception is thrown if the folder doesn't exist
                this.log(chalk.bold('\nInitializing Git repository'));
                var child = exec('git init', {}, function (err, stdout, stderr) {
                    done();
                }.bind(this));
                child.stdout.on('data', function (data) {
                    this.log(data.toString());
                }.bind(this));
            }
        },

        installHerokuDeployPlugin: function () {
            if (this.abort) return;
            var done = this.async();
            this.log(chalk.bold('\nInstalling Heroku CLI deployment plugin'));
            var child = exec('heroku plugins:install heroku-cli-deploy', function (err, stdout) {
                if (err) {
                    this.abort = true;
                    this.log.error(err);
                }
                done();
            }.bind(this));

            child.stdout.on('data', function (data) {
                this.log(data.toString());
            }.bind(this));
        },

        herokuCreate: function () {
            if (this.abort || this.herokuAppExists) return;
            var done = this.async();

            var regionParams = (this.herokuRegion !== 'us') ? ' --region ' + this.herokuRegion : '';

            this.log(chalk.bold('\nCreating Heroku application and setting up node environment'));
            var herokuCreateCmd = 'heroku create ' + this.herokuAppName + regionParams;
            this.log(herokuCreateCmd);

            var child = exec(herokuCreateCmd, {}, function (err, stdout, stderr) {
                if (err) {
                    if (stderr.indexOf('Name is already taken') > -1) {
                        var prompts = [
                            {
                                type: 'list',
                                name: 'herokuForceName',
                                message: 'The Heroku app "' + chalk.cyan(this.herokuAppName) + '" already exists! Use it anyways?',
                                choices: [{
                                    value: 'Yes',
                                    name: 'Yes, I have access to it'
                                }, {
                                    value: 'No',
                                    name: 'No, generate a random name'
                                }],
                                default: 0
                            }];

                        this.log('');
                        this.prompt(prompts).then(function (props) {
                            var getHerokuAppName = function(def, stdout) { return def; };
                            if (props.herokuForceName === 'Yes') {
                                herokuCreateCmd = 'heroku git:remote --app ' + this.herokuAppName;
                            } else {
                                herokuCreateCmd = 'heroku create ' + regionParams;

                                // Extract from "Created random-app-name-1234... done"
                                getHerokuAppName = function(def, stdout) { return stdout.substring(stdout.indexOf('https://') + 8, stdout.indexOf('.herokuapp')); };
                            }
                            exec(herokuCreateCmd, {}, function (err, stdout, stderr) {
                                if (err) {
                                    this.abort = true;
                                    this.log.error(err);
                                } else {
                                    this.herokuAppName = getHerokuAppName(this.herokuAppName, stdout);
                                    this.log(stdout.trim());
                                }
                                this.config.set('herokuAppName', this.herokuAppName);
                                done();
                            }.bind(this));
                        }.bind(this));
                    } else {
                        this.abort = true;
                        this.log.error(err);
                        done();
                    }
                } else {
                    done();
                }
            }.bind(this));

            child.stdout.on('data', function (data) {
                var output = data.toString();
                if (data.search('Heroku credentials') >= 0) {
                    this.abort = true;
                    this.log.error('Error: Not authenticated. Run \'heroku login\' to login to your heroku account and try again.');
                    done();
                } else {
                    this.log(output.trim());
                }
            }.bind(this));
        },

        herokuAddonsCreate: function() {
            if (this.abort) return;
            var done = this.async();

            var dbAddOn = '';
            if (this.prodDatabaseType === 'postgresql') {
                dbAddOn = 'heroku-postgresql --as DATABASE';
            } else if (this.prodDatabaseType === 'mysql') {
                dbAddOn = 'jawsdb:kitefin --as JAWSDB';
            } else if (this.prodDatabaseType === 'mariadb') {
                dbAddOn = 'jawsdb-maria:kitefin --as JAWSDB';
            } else if (this.prodDatabaseType === 'mongodb') {
                dbAddOn = 'mongolab:sandbox --as MONGODB';
            } else {
                return;
            }

            this.log(chalk.bold('\nProvisioning addons'));
            exec(`heroku addons:create ${dbAddOn}`, {}, function (err, stdout, stderr) {
                if (err) {
                    this.log('No new addons created');
                } else {
                    this.log(`Created ${dbAddOn}`);
                }
                done();
            }.bind(this));
        },

        configureJHipsterRegistry: function() {
            if (this.abort || this.herokuAppExists) return;
            var done = this.async();

            if (this.applicationType === 'microservice' || this.applicationType === 'gateway') {
                var prompts = [
                    {
                        type: 'input',
                        name: 'herokuJHipsterRegistry',
                        message: 'What is the URL of your JHipster Registry?'
                    }];

                this.log('');
                this.prompt(prompts).then(function (props) {
                    var configSetCmd = 'heroku config:set ' + 'JHIPSTER_REGISTRY_URL=' + props.herokuJHipsterRegistry + ' --app ' + this.herokuAppName;
                    var child = exec(configSetCmd, {}, function (err, stdout, stderr) {
                        if (err) {
                            this.abort = true;
                            this.log.error(err);
                        }
                        done();
                    }.bind(this));

                    child.stdout.on('data', function (data) {
                        this.log(data.toString());
                    }.bind(this));
                }.bind(this));
            } else {
                this.conflicter.resolve(function (err) {
                    done();
                });
            }
        },

        copyHerokuFiles: function () {
            if (this.abort) return;

            var done = this.async();
            this.log(chalk.bold('\nCreating Heroku deployment files'));

            this.template('_bootstrap-heroku.yml', constants.SERVER_MAIN_RES_DIR + '/config/bootstrap-heroku.yml');
            this.template('_application-heroku.yml', constants.SERVER_MAIN_RES_DIR + '/config/application-heroku.yml');
            this.template('_Procfile', 'Procfile');
            if (this.buildTool === 'gradle') {
                this.template('_heroku.gradle', 'gradle/heroku.gradle');
            }

            this.conflicter.resolve(function (err) {
                done();
            });
        },

        addHerokuBuildPlugin: function () {
            if (this.buildTool !== 'gradle') return;
            this.addGradlePlugin('gradle.plugin.com.heroku.sdk', 'heroku-gradle', '0.2.0');
            this.applyFromGradleScript('gradle/heroku');
        }
    },

    end: {
        productionBuild: function () {
            if (this.abort) return;
            var done = this.async();
            this.log(chalk.bold('\nBuilding application'));

            var child = this.buildApplication(this.buildTool, 'prod', function (err) {
                if (err) {
                    this.abort = true;
                    this.log.error(err);
                }
                done();
            }.bind(this));

            this.buildCmd = child.buildCmd;

            child.stdout.on('data', function (data) {
                var line = data.toString().trim();
                if (line.length !== 0) this.log(line);
            }.bind(this));

        },

        productionDeploy: function () {
            if (this.abort) return;
            var done = this.async();
            this.log(chalk.bold('\nDeploying application'));

            var warFileWildcard = 'target/*.war';
            if (this.buildTool === 'gradle') {
                warFileWildcard = 'build/libs/*.war';
            }

            var files = glob.sync(warFileWildcard, {});
            var warFile = files[0];
            var herokuDeployCommand = `heroku deploy:jar ${warFile} --app ${this.herokuAppName}`;

            this.log(chalk.bold('\nUploading your application code.\nThis may take ' + chalk.cyan('several minutes') + ' depending on your connection speed...'));
            var child = exec(herokuDeployCommand, function (err, stdout) {
                if (err) {
                    this.abort = true;
                    this.log.error(err);
                }
                this.log(chalk.green('\nYour app should now be live. To view it run\n\t' + chalk.bold('heroku open')));
                this.log(chalk.yellow('And you can view the logs with this command\n\t' + chalk.bold('heroku logs --tail')));
                this.log(chalk.yellow('After application modification, redeploy it with\n\t' + chalk.bold('yo jhipster:heroku')));
                done();
            }.bind(this));

            child.stdout.on('data', function (data) {
                var line = data.toString().trimRight();
                if (line.trim().length !== 0) this.log(line);
            }.bind(this));
        }
    }
});
<|endoftext|>


<commit_before>/******************************************************************************
   Password strength analyzer

   Use analyze(text) to analyze and get a score of how strong, or
   unguessable, the password or passphrase is. A zero-length input
   will yield a score of 0, which is the worst, and the higher the
   score the stronger the password. In addition a word is also
   attributed including a color.

   It uses two metrics to calculate a score: Basic16 and Comprehensive8
   The one producing the largest score is the result.

   Basic16 yields 4 points for each of the first 7 characters after
   which 8 points are awarded subsequent characters. A score of 100 is
   awarded 16 characters, which is why it's called Basic16.

   Comprehensive8 yields 4 points for each character and an additional
   17 points for each uppercase character, digit or symbol. Inputting
   a second unique uppercase character, digit or symbol yields an
   additional 8 points, and a third adds extra 4 points. If no
   lowercse characters are found then 17 points are deducted, and if
   the text does not appear in the word list then 17 points are added.

   The word lists used were provided by Open Wall:
     http://download.openwall.net/pub/wordlists/passwords/

   Deps: jQuery, XRegExp
 ******************************************************************************/
"use strict";
function Psw(path) {
  this.loadPath = path || "wordlist.json";
  this.wordlist = [];
  this.wordObject = {};
  var self = this;

  if (localStorage["wordlist"] != null) {
     self.wordObject = JSON.parse(localStorage["wordlist"]);
     self.wordlist = self.wordObject.wordlist;
     console.log("Loaded wordlist from local storage!");
  } else {
     $.ajax({
       "type" : "GET",
       "url" : self.loadPath,
       "success" : function(data, status, xhr) {
          console.log("Loaded wordlist from \"" + self.loadPath + "\"");
          localStorage["wordlist"] = JSON.stringify(data);
          self.wordObject = JSON.parse(localStorage["wordlist"]);
          self.wordlist = self.wordObject.wordlist;
         },
       "error" : function(xhr, status, error) {
          console.log("Error" + error);
       }
    });
 }
}
window["Psw"] = Psw;

Psw.prototype.analyze = function(text) {
  var score = this.calcScore(text);
  var meaning = this.scoreMeaning(score);
  return {
    "score": score,
    "meaning": meaning[0],
    "color": meaning[1]
  };
};
Psw.prototype["analyze"] = Psw.prototype.analyze;

/**************************************/

Psw.prototype.calcScore = function(text) {
  if (text == undefined || text.length == 0) {
    return 0;
  }
  return Math.max(this.calcBasic16(text), this.calcComp8(text));
};
Psw.prototype["calcScore"] = Psw.prototype.calcScore;

/**
 * 8 segments: dreadful (1-16), bad (17-33), poor (34-50), fair
 * (51-67), good (68-84), great (85-99), excellent (100-115), fantastic (116+)
 */
Psw.prototype.scoreMeaning = function(score) {
  if (score > 0 && score <= 16) {
    return ["Dreadful", "#FF0000"];
  }
  else if (score > 16 && score <= 33) {
    return ["Bad", "#FF6600"];
  }
  else if (score > 33 && score <= 50) {
    return ["Poor", "#FF9900"];
  }
  else if (score > 50 && score <= 67) {
    return ["Fair", "#FFCC00"];
  }
  else if (score > 67 && score <= 84) {
    return ["Good", "#FFFF00"];
  }
  else if (score > 84 && score <= 99) {
    return ["Great", "#CCFF00"];
  }
  else if (score > 99 && score <= 115) {
    return ["Excellent", "#99FF00"];
  }
  else if (score > 115) {
    return ["Fantastic", "#00FF00"];
  }
  else {
    return ["", ""];
  }
};
Psw.prototype["scoreMeaning"] = Psw.prototype.scoreMeaning;

Psw.prototype.calcBasic16 = function(text) {
  var score = 0, len = text.length;
  score = Math.min(len, 7) * 4;
  if (len > 7) {
    score += (len - 7) * 8;
  }
  return score;
};
Psw.prototype["calcBasic16"] = Psw.prototype.calcBasic16;

Psw.prototype.calcComp8 = function(text) {
  var score = 0, len = text.length;
  var upsq = this.countCmp(text, this.isUpper, true);
  var digsq = this.countCmp(text, this.isDigit, true);
  var symsq = this.countCmp(text, this.isSymbol, true);
  var los = this.countCmp(text, this.isLower);

  score = len * 4;

  function unqPoints(num) {
    return (num >= 1 ? 17 : 0) + (num >= 2 ? 8 : 0) + (num >= 3 ? 4 : 0);
  }
  score += unqPoints(upsq) + unqPoints(digsq) + unqPoints(symsq);

  if (los == 0) score -= 17;

  if (this.checkWordList(text)) {
    score += 17;
  }

  return score;
};
Psw.prototype["calcComp8"] = Psw.prototype.calcComp8;

/**
 * Note that XRegExp is used because we want to be able to check for
 * Unicode uppercase characters, not only ASCII, and toUpperCase() is
 * not useful since it lets non-uppercase characters pass through..
 */
Psw.prototype.isUpper = function(text) {
  return XRegExp("^\\p{Lu}$").test(text);
};
Psw.prototype["isUpper"] = Psw.prototype.isUpper;

Psw.prototype.isLower = function(text) {
  return XRegExp("^\\p{Ll}$").test(text);
};
Psw.prototype["isLower"] = Psw.prototype.isLower;

Psw.prototype.isDigit = function(text) {
  return /^\d$/.test(text);
};
Psw.prototype["isDigit"] = Psw.prototype.isDigit;

Psw.prototype.isSymbol = function(text) {
  return /^[!=\?\"\'#%\$§\/\\\(\)\[\]{}+\-\.,;:_<>\*`´\^~|]$/.test(text);
};
Psw.prototype["isSymbol"] = Psw.prototype.isSymbol;

Psw.prototype.countCmp = function(text, cmp, unique) {
  if (unique == undefined) {
    unique = false;
  }
  var cnt = 0;
  var txt = text.split("");
  if (unique) {
    txt = $.unique(txt.sort());
  }
  $.each(txt, function(index, value) {
    if (cmp(txt[index])) {
      cnt++;
    }
  });
  return cnt;
};
Psw.prototype["countCmp"] = Psw.prototype.countCmp;

/**
 * Returns false if found in the word list.
 */
Psw.prototype.checkWordList = function(text) {
  return this.wordlist.indexOf(text.toLowerCase()) == -1;
};
Psw.prototype["checkWordList"] = Psw.prototype.checkWordList
<commit_msg>fix for build in PHP web server<commit_after>/******************************************************************************
   Password strength analyzer

   Use analyze(text) to analyze and get a score of how strong, or
   unguessable, the password or passphrase is. A zero-length input
   will yield a score of 0, which is the worst, and the higher the
   score the stronger the password. In addition a word is also
   attributed including a color.

   It uses two metrics to calculate a score: Basic16 and Comprehensive8
   The one producing the largest score is the result.

   Basic16 yields 4 points for each of the first 7 characters after
   which 8 points are awarded subsequent characters. A score of 100 is
   awarded 16 characters, which is why it's called Basic16.

   Comprehensive8 yields 4 points for each character and an additional
   17 points for each uppercase character, digit or symbol. Inputting
   a second unique uppercase character, digit or symbol yields an
   additional 8 points, and a third adds extra 4 points. If no
   lowercse characters are found then 17 points are deducted, and if
   the text does not appear in the word list then 17 points are added.

   The word lists used were provided by Open Wall:
     http://download.openwall.net/pub/wordlists/passwords/

   Deps: jQuery, XRegExp
 ******************************************************************************/
"use strict";
function Psw(path) {
  this.loadPath = path || "wordlist.json";
  this.wordlist = [];
  this.wordObject = {};
  var self = this;

  if (localStorage["wordlist"] != null) {
     self.wordObject = JSON.parse(localStorage["wordlist"]);
     self.wordlist = self.wordObject.wordlist;
     console.log("Loaded wordlist from local storage!");
  } else {
     $.ajax({
       "type" : "GET",
       "url" : self.loadPath,
       "success" : function(data, status, xhr) {
          console.log("Loaded wordlist from \"" + self.loadPath + "\"");
          if (typeof data === "string") {
            var data = JSON.parse(data);
          }
          localStorage["wordlist"] = JSON.stringify(data);
          self.wordObject = JSON.parse(localStorage["wordlist"]);
          self.wordlist = self.wordObject.wordlist;
         },
       "error" : function(xhr, status, error) {
          console.log("Error" + error);
       }
    });
 }
}
window["Psw"] = Psw;

Psw.prototype.analyze = function(text) {
  var score = this.calcScore(text);
  var meaning = this.scoreMeaning(score);
  return {
    "score": score,
    "meaning": meaning[0],
    "color": meaning[1]
  };
};
Psw.prototype["analyze"] = Psw.prototype.analyze;

/**************************************/

Psw.prototype.calcScore = function(text) {
  if (text == undefined || text.length == 0) {
    return 0;
  }
  return Math.max(this.calcBasic16(text), this.calcComp8(text));
};
Psw.prototype["calcScore"] = Psw.prototype.calcScore;

/**
 * 8 segments: dreadful (1-16), bad (17-33), poor (34-50), fair
 * (51-67), good (68-84), great (85-99), excellent (100-115), fantastic (116+)
 */
Psw.prototype.scoreMeaning = function(score) {
  if (score > 0 && score <= 16) {
    return ["Dreadful", "#FF0000"];
  }
  else if (score > 16 && score <= 33) {
    return ["Bad", "#FF6600"];
  }
  else if (score > 33 && score <= 50) {
    return ["Poor", "#FF9900"];
  }
  else if (score > 50 && score <= 67) {
    return ["Fair", "#FFCC00"];
  }
  else if (score > 67 && score <= 84) {
    return ["Good", "#FFFF00"];
  }
  else if (score > 84 && score <= 99) {
    return ["Great", "#CCFF00"];
  }
  else if (score > 99 && score <= 115) {
    return ["Excellent", "#99FF00"];
  }
  else if (score > 115) {
    return ["Fantastic", "#00FF00"];
  }
  else {
    return ["", ""];
  }
};
Psw.prototype["scoreMeaning"] = Psw.prototype.scoreMeaning;

Psw.prototype.calcBasic16 = function(text) {
  var score = 0, len = text.length;
  score = Math.min(len, 7) * 4;
  if (len > 7) {
    score += (len - 7) * 8;
  }
  return score;
};
Psw.prototype["calcBasic16"] = Psw.prototype.calcBasic16;

Psw.prototype.calcComp8 = function(text) {
  var score = 0, len = text.length;
  var upsq = this.countCmp(text, this.isUpper, true);
  var digsq = this.countCmp(text, this.isDigit, true);
  var symsq = this.countCmp(text, this.isSymbol, true);
  var los = this.countCmp(text, this.isLower);

  score = len * 4;

  function unqPoints(num) {
    return (num >= 1 ? 17 : 0) + (num >= 2 ? 8 : 0) + (num >= 3 ? 4 : 0);
  }
  score += unqPoints(upsq) + unqPoints(digsq) + unqPoints(symsq);

  if (los == 0) score -= 17;

  if (this.checkWordList(text)) {
    score += 17;
  }

  return score;
};
Psw.prototype["calcComp8"] = Psw.prototype.calcComp8;

/**
 * Note that XRegExp is used because we want to be able to check for
 * Unicode uppercase characters, not only ASCII, and toUpperCase() is
 * not useful since it lets non-uppercase characters pass through..
 */
Psw.prototype.isUpper = function(text) {
  return XRegExp("^\\p{Lu}$").test(text);
};
Psw.prototype["isUpper"] = Psw.prototype.isUpper;

Psw.prototype.isLower = function(text) {
  return XRegExp("^\\p{Ll}$").test(text);
};
Psw.prototype["isLower"] = Psw.prototype.isLower;

Psw.prototype.isDigit = function(text) {
  return /^\d$/.test(text);
};
Psw.prototype["isDigit"] = Psw.prototype.isDigit;

Psw.prototype.isSymbol = function(text) {
  return /^[!=\?\"\'#%\$§\/\\\(\)\[\]{}+\-\.,;:_<>\*`´\^~|]$/.test(text);
};
Psw.prototype["isSymbol"] = Psw.prototype.isSymbol;

Psw.prototype.countCmp = function(text, cmp, unique) {
  if (unique == undefined) {
    unique = false;
  }
  var cnt = 0;
  var txt = text.split("");
  if (unique) {
    txt = $.unique(txt.sort());
  }
  $.each(txt, function(index, value) {
    if (cmp(txt[index])) {
      cnt++;
    }
  });
  return cnt;
};
Psw.prototype["countCmp"] = Psw.prototype.countCmp;

/**
 * Returns false if found in the word list.
 */
Psw.prototype.checkWordList = function(text) {
  return this.wordlist.indexOf(text.toLowerCase()) == -1;
};
Psw.prototype["checkWordList"] = Psw.prototype.checkWordList
<|endoftext|>


<commit_before>/**
 * Creates an object of type wgaPipeline for drawing whole genome alignment visualizations
 * @author Markus Ankenbrand <markus.ankenbrand@uni-wuerzburg.de>
 * @constructor
 * @param {Object} svg - jQuery object containing a svg DOM element. Visualizations will be drawn on this svg. Size may be changed by object methods. Previous content will be deleted.
 * @example
 * // initializes an wgaPipeline object (wga) on the svg element with id 'canvas'
 * var svg = $('#canvas');
 * var wga = new wgaPipeline(svg);
 */
function WgaPipeline(svg) {
	/**
	 * property to contain the svg DOM element
	 */
	this.svg = svg;
	/**
	 * property to store the data
	 * @property {Object}  karyo                        - the chromosome information
	 * @property {Array}   karyo.order                  - array of chromosome IDs in the desired order (circular layout)
	 * @property {Array}   karyo.genome_order           - array of genome IDs in the desired order (linear layout)
	 * @property {Object}  karyo.chromosomes            - the chromosome details, karyo IDs as keys
	 * @property {Number}  karyo.chromosomes.genome_id  - number of genome to which this chromosome belongs
	 * @property {Number}  karyo.chromosomes.length     - length in bp
	 * @property {Boolean} karyo.chromosomes.rc         - should the sequence be treated as its reverse complement
	 * @property {String}  karyo.chromosomes.seq        - sequence of the chromosome
	 * @property {Object}  features                     - the feature information, feature IDs as keys
	 * @property {String}  features.karyo               - the karyo ID
	 * @property {Number}  features.start               - start position on the sequence
	 * @property {Number}  features.end                 - end position on the sequence
	 * @property {Object}  links                        - the link information
	 * @property {String}  links.source                 - source feature of the link
	 * @property {String}  links.target                 - target feature of the link
	 * @property {Number}  links.identity               - identity of the link
	 */
	this.data = {};
	/**
	 * property to store configuration options
	 * @property {Number}  width                  - The width of the svg in px.
	 * @property {Number}  height                 - The height of the svg in px.
	 * @property {Object}  linear                 - The configuration options for the linear layout.
	 * @property {Number}  linear.genomeDistance  - The vertical distance between adjacent genomes in px.
	 * @property {Number}  linear.karyoHeight     - The height of each chromosome in px.
	 * @property {Number}  linear.karyoDistance   - The horizontal distance between adjacent chromosomes of the same genome in bp.
	 */
	this.conf = {
		width: 1000,
		height: 1000,
		linear: {
			genomeDistance: 300,
			karyoHeight: 30,
			karyoDistance: 10
		}
	};
}

/**
 * Sets the data of the WgaPipeline object.
 * For the required format see the example
 * @author Markus Ankenbrand <markus.ankenbrand@uni-wuerzburg.de>
 * @param {Object} data - Object containing karyo, link and feature information
 * @example
 * var svg = $('#canvas');
 * var wga = new wgaPipeline(svg);
 * var karyo = {
 * 	'order': ['c1', 'c2'],
 * 	'genome_order': ['0', '1'],
 * 	'chromosomes': {
 * 	'c1': {'genome_id': 0, 'length': 2000, 'rc': false, 'seq': null},
 * 	'c2': {'genome_id': 1, 'length': 1000, 'rc': false, 'seq': null}
 * 	}
 * };
 * var features = {
 * 	'f1': {'karyo': 'c1', 'start': 300, 'end': 800},
 * 	'f2': {'karyo': 'c2', 'start': 100, 'end': 600}
 * };
 * var links = [
 * 	{'source': 'f1', 'target': 'f2', 'identity': 90}
 * ];
 * wga.setData({'karyo': karyo, 'features': features, 'links': links};
 */
WgaPipeline.prototype.setData = function(data) {
	this.data = data;
};

/**
 * Calculates coordinates for the chromosomes to draw in the linear layout.
 * This function operates on the data property of the object and therefore needs no parameters.
 * This function is primarily meant for internal usage, the user should not need to call this directly.
 * @author Markus Ankenbrand <markus.ankenbrand@uni-wuerzburg.de>
 * @returns {Array} Array containing one Object for each element in data.karyo of the form {karyo: 'karyo_name', x:0, y:0, width:10, height:10}
 */
WgaPipeline.prototype.getLinearKaryoCoords = function() {
	var linearKaryoCoords = [];
	var genome_order = this.data.karyo.genome_order;
	var conf = this.conf;

	var total = [];
	var current = [];
	var i;
	// Initialize total with the negative of one karyoDistance - as there is one space less then karyos per genome
	for (i = 0; i < genome_order.length; i++) {
		total.push(-conf.linear.karyoDistance);
		current.push(0);
	}

	$.each(this.data.karyo.chromosomes, function(key, value) {
		total[genome_order.indexOf(value.genome_id)] += value.length + conf.linear.karyoDistance;
	});

	var maxTotalSize = Math.max.apply(null, total);

	for (i = 0; i < this.data.karyo.order.length; i++) {
		var key = this.data.karyo.order[i];
		var value = this.data.karyo.chromosomes[key];
		var coord = {
			'karyo': key,
			'x': (current[genome_order.indexOf(value.genome_id)] / maxTotalSize) * conf.width,
			'y': genome_order.indexOf(value.genome_id) * conf.linear.genomeDistance,
			'width': (value.length / maxTotalSize) * conf.width,
			'height': conf.linear.karyoHeight
		};
		current[genome_order.indexOf(value.genome_id)] += value.length + conf.linear.karyoDistance;
		linearKaryoCoords.push(coord);
	}

	return linearKaryoCoords;
};

/**
 * This function draws the karyos in the linear layout
 * @author Markus Ankenbrand and Sonja Hohlfeld
 * @param {Array} The array containing the coordinates as returned by getLinearKaryoCoords()
 */
<commit_msg>testing for correctly initialized svg height passes<commit_after>/**
 * Creates an object of type wgaPipeline for drawing whole genome alignment visualizations
 * @author Markus Ankenbrand <markus.ankenbrand@uni-wuerzburg.de>
 * @constructor
 * @param {Object} svg - jQuery object containing a svg DOM element. Visualizations will be drawn on this svg. Size may be changed by object methods. Previous content will be deleted.
 * @example
 * // initializes an wgaPipeline object (wga) on the svg element with id 'canvas'
 * var svg = $('#canvas');
 * var wga = new wgaPipeline(svg);
 */
function WgaPipeline(svg) {
	/**
	 * property to contain the svg DOM element
	 */
	this.svg = svg;
	/**
	 * property to store the data
	 * @property {Object}  karyo                        - the chromosome information
	 * @property {Array}   karyo.order                  - array of chromosome IDs in the desired order (circular layout)
	 * @property {Array}   karyo.genome_order           - array of genome IDs in the desired order (linear layout)
	 * @property {Object}  karyo.chromosomes            - the chromosome details, karyo IDs as keys
	 * @property {Number}  karyo.chromosomes.genome_id  - number of genome to which this chromosome belongs
	 * @property {Number}  karyo.chromosomes.length     - length in bp
	 * @property {Boolean} karyo.chromosomes.rc         - should the sequence be treated as its reverse complement
	 * @property {String}  karyo.chromosomes.seq        - sequence of the chromosome
	 * @property {Object}  features                     - the feature information, feature IDs as keys
	 * @property {String}  features.karyo               - the karyo ID
	 * @property {Number}  features.start               - start position on the sequence
	 * @property {Number}  features.end                 - end position on the sequence
	 * @property {Object}  links                        - the link information
	 * @property {String}  links.source                 - source feature of the link
	 * @property {String}  links.target                 - target feature of the link
	 * @property {Number}  links.identity               - identity of the link
	 */
	this.data = {};
	/**
	 * property to store configuration options
	 * @property {Number}  width                  - The width of the svg in px.
	 * @property {Number}  height                 - The height of the svg in px.
	 * @property {Object}  linear                 - The configuration options for the linear layout.
	 * @property {Number}  linear.genomeDistance  - The vertical distance between adjacent genomes in px.
	 * @property {Number}  linear.karyoHeight     - The height of each chromosome in px.
	 * @property {Number}  linear.karyoDistance   - The horizontal distance between adjacent chromosomes of the same genome in bp.
	 */
	this.conf = {
		width: 1000,
		height: 1000,
		linear: {
			genomeDistance: 300,
			karyoHeight: 30,
			karyoDistance: 10
		}
	};
	// Initialize svg size
	svg.height(this.conf.height);
}

/**
 * Sets the data of the WgaPipeline object.
 * For the required format see the example
 * @author Markus Ankenbrand <markus.ankenbrand@uni-wuerzburg.de>
 * @param {Object} data - Object containing karyo, link and feature information
 * @example
 * var svg = $('#canvas');
 * var wga = new wgaPipeline(svg);
 * var karyo = {
 * 	'order': ['c1', 'c2'],
 * 	'genome_order': ['0', '1'],
 * 	'chromosomes': {
 * 	'c1': {'genome_id': 0, 'length': 2000, 'rc': false, 'seq': null},
 * 	'c2': {'genome_id': 1, 'length': 1000, 'rc': false, 'seq': null}
 * 	}
 * };
 * var features = {
 * 	'f1': {'karyo': 'c1', 'start': 300, 'end': 800},
 * 	'f2': {'karyo': 'c2', 'start': 100, 'end': 600}
 * };
 * var links = [
 * 	{'source': 'f1', 'target': 'f2', 'identity': 90}
 * ];
 * wga.setData({'karyo': karyo, 'features': features, 'links': links};
 */
WgaPipeline.prototype.setData = function(data) {
	this.data = data;
};

/**
 * Calculates coordinates for the chromosomes to draw in the linear layout.
 * This function operates on the data property of the object and therefore needs no parameters.
 * This function is primarily meant for internal usage, the user should not need to call this directly.
 * @author Markus Ankenbrand <markus.ankenbrand@uni-wuerzburg.de>
 * @returns {Array} Array containing one Object for each element in data.karyo of the form {karyo: 'karyo_name', x:0, y:0, width:10, height:10}
 */
WgaPipeline.prototype.getLinearKaryoCoords = function() {
	var linearKaryoCoords = [];
	var genome_order = this.data.karyo.genome_order;
	var conf = this.conf;

	var total = [];
	var current = [];
	var i;
	// Initialize total with the negative of one karyoDistance - as there is one space less then karyos per genome
	for (i = 0; i < genome_order.length; i++) {
		total.push(-conf.linear.karyoDistance);
		current.push(0);
	}

	$.each(this.data.karyo.chromosomes, function(key, value) {
		total[genome_order.indexOf(value.genome_id)] += value.length + conf.linear.karyoDistance;
	});

	var maxTotalSize = Math.max.apply(null, total);

	for (i = 0; i < this.data.karyo.order.length; i++) {
		var key = this.data.karyo.order[i];
		var value = this.data.karyo.chromosomes[key];
		var coord = {
			'karyo': key,
			'x': (current[genome_order.indexOf(value.genome_id)] / maxTotalSize) * conf.width,
			'y': genome_order.indexOf(value.genome_id) * conf.linear.genomeDistance,
			'width': (value.length / maxTotalSize) * conf.width,
			'height': conf.linear.karyoHeight
		};
		current[genome_order.indexOf(value.genome_id)] += value.length + conf.linear.karyoDistance;
		linearKaryoCoords.push(coord);
	}

	return linearKaryoCoords;
};

/**
 * This function draws the karyos in the linear layout
 * @author Markus Ankenbrand and Sonja Hohlfeld
 * @param {Array} The array containing the coordinates as returned by getLinearKaryoCoords()
 */
WgaPipeline.prototype.drawLinearKaryo = function(coords) {

};
<|endoftext|>


<commit_before>module.exports = {
    auth: {
        type: {
            Account: 'account',
            Profile: 'profile',
            Role: 'role'
        },
        collection: {
            Account: 'accounts',
            Role: 'roles'
        }
    },
    master: {
        type: {
            Buyer: 'buyer',
            Supplier: 'supplier',
            uom: 'unit-of-measurement',
            Currency: 'currency',
            Vat: 'vat',
            Budget: 'budget',
            Machine: 'machine'
        },
        collection: {
            Buyer: 'buyers',
            Supplier: 'suppliers',
            uom: 'unit-of-measurements',
            Product: 'products',
            Machine: 'machines',
            Division: 'divisions',
            Unit: 'units',
            Category: 'categories',
            Currency: 'currencies',
            Vat: 'vats',
            Budget: 'budgets',
            ThreadSpecification : 'thread-specifications',
            UsterClassification: 'uster-classifications'
        }
    },
    purchasing: {
        type: {
            PurchaseOrder: 'purchase-order',
            DeliveryOrder: 'delivery-order',
            PurchaseRequest: 'purchase-request',
            UnitPaymentOrder:'unit-payment-order',
        },
        collection: {
            PurchaseOrder: 'purchase-orders',
            PurchaseOrderExternal: 'purchase-order-externals',
            DeliveryOrder: 'delivery-orders',
            UnitReceiptNote: 'unit-receipt-notes',
            PurchaseRequest: 'purchase-requests',
            UnitPaymentCorrectionNote:'unit-payment-correction-notes',
            UnitPaymentOrder:'unit-payment-orders'
        }
    },
    production:{
        spinning : {
            winding : {
                type:{
                    WindingQualitySampling : 'winding-quality-sampling'
                },
                collection:{
                    WindingQualitySampling : 'winding-quality-samplings'
                }
            }
        }
    }
}
<commit_msg>adding lot machine and winding production output<commit_after>module.exports = {
    auth: {
        type: {
            Account: 'account',
            Profile: 'profile',
            Role: 'role'
        },
        collection: {
            Account: 'accounts',
            Role: 'roles'
        }
    },
    master: {
        type: {
            Buyer: 'buyer',
            Supplier: 'supplier',
            uom: 'unit-of-measurement',
            Currency: 'currency',
            Vat: 'vat',
            Budget: 'budget',
            Machine: 'machine'
        },
        collection: {
            Buyer: 'buyers',
            Supplier: 'suppliers',
            uom: 'unit-of-measurements',
            Product: 'products',
            Machine: 'machines',
            Division: 'divisions',
            Unit: 'units',
            Category: 'categories',
            Currency: 'currencies',
            Vat: 'vats',
            Budget: 'budgets',
            ThreadSpecification : 'thread-specifications',
            UsterClassification: 'uster-classifications',
            LotMachine: 'lot-machines'
        }
    },
    purchasing: {
        type: {
            PurchaseOrder: 'purchase-order',
            DeliveryOrder: 'delivery-order',
            PurchaseRequest: 'purchase-request',
            UnitPaymentOrder:'unit-payment-order',
        },
        collection: {
            PurchaseOrder: 'purchase-orders',
            PurchaseOrderExternal: 'purchase-order-externals',
            DeliveryOrder: 'delivery-orders',
            UnitReceiptNote: 'unit-receipt-notes',
            PurchaseRequest: 'purchase-requests',
            UnitPaymentCorrectionNote:'unit-payment-correction-notes',
            UnitPaymentOrder:'unit-payment-orders'
        }
    },
    production:{
        spinning : {
            winding : {
                type:{
                    WindingQualitySampling : 'winding-quality-sampling',
                    WindingProductionOutput : 'winding-production-output'
                },
                collection:{
                    WindingQualitySampling : 'winding-quality-samplings',
                    WindingProductionOutput : 'winding-production-outputs'
                }
            }
        }
    }
}
<|endoftext|>


<commit_before>require('babel-polyfill');

import Promise from 'bluebird';
import orawrap from 'orawrap';
import oracledb from 'oracledb';
import fs from 'fs-promise';
import { Observable } from '@reactivex/rxjs';
import mssql from 'mssql';

import { oraWrapInst, config } from './index';

var msConnPool;
var oraConnPool;

/**
 * orawrap requires only the parameters that will be used be passed to it. This function removes the null args,
 * and creates a Promise around the orawrap execute function.
 * @param  {string} sql SQL string
 * @param  {object} bind Oracle bind variables
 * @param  {object} [opts]
 * @return {Promise}
 */
export function execute(sql, bind, opts, callingFunc) {

  if (!oraConnPool) {
    createOraPool();
  }
  const rnd = Math.random() * 100;
  console.time(rnd);
  return oraConnPool
    .then(pool => {
      console.log(pool._logStats());
      return pool.getConnection();
    })
    .then(conn => {
      const rnd = Math.random() * 100;
      if (callingFunc) {
        console.time(`${callingFunc} ${rnd}`);
      }
      return conn.execute(sql, bind, opts)
        .then(results => {
          if (callingFunc) {
            console.timeEnd(`${callingFunc} ${rnd}`);
          }
          conn.close();
          return results;
        })
    });
}

function createOraPool() {
  let oraPool = oracledb.createPool(config.database.oracle);
  oraConnPool = oraPool;
  return oraPool;
}

/**
 *
 * @return {Promise}
 */
function createMsConn() {
  config.database.sams.requestTimeout = 600000;
  let msConn = mssql.connect(config.database.sams);
  msConnPool = msConn;
  return msConn;
}

export function closeMsConn() {
  if (msConnPool) {
    msConnPool.then((connection) => {
      connection.close();
    });
  }
}

/**
 * create and execute a SQL query
 * @param {string} sql
 * @param {object} inputParams
 * @return {observable}
 */
export function msExecute(sql, inputParams) {
  return new Observable(observer => {
    if (!msConnPool) {
      createMsConn();
    }
    msConnPool
      .then((connection) => {
        var request = new mssql.Request(msConnPool);
        if (inputParams) {
          Object.keys(inputParams).forEach(paramName => {
            request.input(paramName, inputParams[paramName]);
          });
        }
        request.stream = true;
        request.query(sql);
        request.on('row', row => {
          observer.next(row);
        });
        request.on('error', err => {
          console.log('error == ', err);
          observer.error(err);
        });
        request.on('done', (returnValue, affected) => {
          observer.complete();
        });
      })
      .catch(error => console.log(`mssql error == ${error}`));
  });
}
<commit_msg>Removed instrumentation code<commit_after>require('babel-polyfill');

import Promise from 'bluebird';
import orawrap from 'orawrap';
import oracledb from 'oracledb';
import fs from 'fs-promise';
import { Observable } from '@reactivex/rxjs';
import mssql from 'mssql';

import { oraWrapInst, config } from './index';

var msConnPool;
var oraConnPool;

/**
 * orawrap requires only the parameters that will be used be passed to it. This function removes the null args,
 * and creates a Promise around the orawrap execute function.
 * @param  {string} sql SQL string
 * @param  {object} bind Oracle bind variables
 * @param  {object} [opts]
 * @return {Promise}
 */
export function execute(sql, bind, opts, callingFunc) {

  if (!oraConnPool) {
    createOraPool();
  }
  return oraConnPool
    .then(pool => pool.getConnection())
    .then(conn => conn.execute(sql, bind, opts)
        .then(results => {
          conn.close();
          return results;
        })
    );
}

function createOraPool() {
  let oraPool = oracledb.createPool(config.database.oracle);
  oraConnPool = oraPool;
  return oraPool;
}

/**
 *
 * @return {Promise}
 */
function createMsConn() {
  config.database.sams.requestTimeout = 600000;
  let msConn = mssql.connect(config.database.sams);
  msConnPool = msConn;
  return msConn;
}

export function closeMsConn() {
  if (msConnPool) {
    msConnPool.then((connection) => {
      connection.close();
    });
  }
}

/**
 * create and execute a SQL query
 * @param {string} sql
 * @param {object} inputParams
 * @return {observable}
 */
export function msExecute(sql, inputParams) {
  return new Observable(observer => {
    if (!msConnPool) {
      createMsConn();
    }
    msConnPool
      .then((connection) => {
        var request = new mssql.Request(msConnPool);
        if (inputParams) {
          Object.keys(inputParams).forEach(paramName => {
            request.input(paramName, inputParams[paramName]);
          });
        }
        request.stream = true;
        request.query(sql);
        request.on('row', row => {
          observer.next(row);
        });
        request.on('error', err => {
          console.log('error == ', err);
          observer.error(err);
        });
        request.on('done', (returnValue, affected) => {
          observer.complete();
        });
      })
      .catch(error => console.log(`mssql error == ${error}`));
  });
}
<|endoftext|>