<commit_before>let $ = require('jquery')
let aes = require('crypto-js').AES
let Clipboard = require('clipboard')
let crypto = require('crypto')
let enc = require('crypto-js').enc.Utf8
let FileReadStream = require('namedfilestream/read')
let FileWriteStream = require('namedfilestream/write')
let signalhub = require('signalhub')
let swarm = require('webrtc-swarm')

let hash, hub, key, sw
let fileReadStream = null
let peers = []

attachListeners()
initialize()

function attachListeners () {
  new Clipboard('.btn') // eslint-disable-line

  window.onbeforeunload = x => reset()

  $(document).on('change', '#send-input', e => {
    // the user selected a file and wants to send it
    window.location.hash = '#'
    $('.url').val(`${window.location.origin}/#${key}`)
    $('body').attr('class', 'send')
    fileReadStream = new FileReadStream(
      e.target.files[0],
      { fields: ['name', 'size', 'type'] }
    )
    step(2)
  })

  $('a.back').click(function () {
    $('#total-downloads').remove()
    $('*[class*="peer"]').remove()
    $('#send-input').replaceWith(function () {
      return $(this).clone() // reinitialize the hidden file input
    })
    reset()
  })
}

function initialize () {
  step(1)
  hash = window.location.hash.substr(1)
  if (!hash) bootAnimation()
  key = hash || randomHex('24')
  hub = signalhub(`peertransfer-${key}`.substr(0, 7), [
    // 'https://signalhub.mafintosh.com/', // bug in lib?!
    'https://signalhub.perguth.de:65300/'
  ])
  sw = swarm(hub, {
    // The goal here is to protect the signaling data that's beeing exchanged
    // between peers on WebRTC connection establishment. It includes available
    // IP addresses (could be local ones!) among other things.
    wrap: (data, channel) => {
      if (!data.signal || channel === '/all') return data
      data.signal = JSON.stringify(data.signal)
      data.signal = aes.encrypt(data.signal, key).toString()
      return data
    },
    unwrap: (data, id) => {
      console.log('sw.me', sw.me, id, data.from)
      if (!data.signal) return data
      try {
        data.signal = (aes.decrypt(data.signal, key)).toString(enc)
      } catch (e) { return }
      data.signal = JSON.parse(data.signal)
      return data
    }
  })
  handlePeers()
}

function handlePeers () {
  sw.on('peer', peer => {
    peers.push(peer)
    if (!hash) {
      // sending files
      step(2)
      fileReadStream.on('end', x => {
        peer.destroy()
        peers.pop(peer)
      })
      fileReadStream.pipe(peer)
      return
    }
    // receiving files
    let writeStream = new FileWriteStream()
    writeStream.on('finish', x => {
      sw.close()
      peer.destroy()
      peers.pop(peer)
    })
    peer.pipe(writeStream).on('file', file => {
      let objectUrl = window.URL.createObjectURL(file)
      $('#step3 a').attr('href', objectUrl).attr('download', file.name)
      step(3)
    })
  })
}

function reset () {
  peers.forEach(peer => peer.destroy())
  peers = []
  hub.close()
  sw.close()
  initialize()
}

function bootAnimation () {
  let button = $('#step1 .button')
  button.css('cursor', 'pointer')
  button.click(function () {
    $('#send-input').click()
  })
  setTimeout(function () {
    button.attr('class', 'button green send')
    button.html('send a file')
    button.toggleClass('send')
    button.toggleClass('browse')
    button.css('cursor', 'pointer')
  }, 200)
}

function step (i) {
  let stage = $('#stage')
  let back = $('a.back')
  if (i === 1) back.fadeOut()
  else $('a.back').fadeIn()
  stage.css('top', (-(i - 1) * 100) + '%')
}

function randomHex (len) {
  // https://github.com/mafintosh/webrtc-swarm/commit/ce77175c7d48cf4fad11c5e40f8869ebf0d7f303#diff-1dd241c4cd3fd1dd89c570cee98b79dd
  return crypto.randomBytes(Math.ceil(len / 2))
    .toString('hex')
    .slice(0, len)
}
<commit_msg>remove console log<commit_after>let $ = require('jquery')
let aes = require('crypto-js').AES
let Clipboard = require('clipboard')
let crypto = require('crypto')
let enc = require('crypto-js').enc.Utf8
let FileReadStream = require('namedfilestream/read')
let FileWriteStream = require('namedfilestream/write')
let signalhub = require('signalhub')
let swarm = require('webrtc-swarm')

let hash, hub, key, sw
let fileReadStream = null
let peers = []

attachListeners()
initialize()

function attachListeners () {
  new Clipboard('.btn') // eslint-disable-line

  window.onbeforeunload = x => reset()

  $(document).on('change', '#send-input', e => {
    // the user selected a file and wants to send it
    window.location.hash = '#'
    $('.url').val(`${window.location.origin}/#${key}`)
    $('body').attr('class', 'send')
    fileReadStream = new FileReadStream(
      e.target.files[0],
      { fields: ['name', 'size', 'type'] }
    )
    step(2)
  })

  $('a.back').click(function () {
    $('#total-downloads').remove()
    $('*[class*="peer"]').remove()
    $('#send-input').replaceWith(function () {
      return $(this).clone() // reinitialize the hidden file input
    })
    reset()
  })
}

function initialize () {
  step(1)
  hash = window.location.hash.substr(1)
  if (!hash) bootAnimation()
  key = hash || randomHex('24')
  hub = signalhub(`peertransfer-${key}`.substr(0, 7), [
    // 'https://signalhub.mafintosh.com/', // bug in lib?!
    'https://signalhub.perguth.de:65300/'
  ])
  sw = swarm(hub, {
    // The goal here is to protect the signaling data that's beeing exchanged
    // between peers on WebRTC connection establishment. It includes available
    // IP addresses (could be local ones!) among other things.
    wrap: (data, channel) => {
      if (!data.signal || channel === '/all') return data
      data.signal = JSON.stringify(data.signal)
      data.signal = aes.encrypt(data.signal, key).toString()
      return data
    },
    unwrap: (data, id) => {
      if (!data.signal) return data
      try {
        data.signal = (aes.decrypt(data.signal, key)).toString(enc)
      } catch (e) { return }
      data.signal = JSON.parse(data.signal)
      return data
    }
  })
  handlePeers()
}

function handlePeers () {
  sw.on('peer', peer => {
    peers.push(peer)
    if (!hash) {
      // sending files
      step(2)
      fileReadStream.on('end', x => {
        peer.destroy()
        peers.pop(peer)
      })
      fileReadStream.pipe(peer)
      return
    }
    // receiving files
    let writeStream = new FileWriteStream()
    writeStream.on('finish', x => {
      sw.close()
      peer.destroy()
      peers.pop(peer)
    })
    peer.pipe(writeStream).on('file', file => {
      let objectUrl = window.URL.createObjectURL(file)
      $('#step3 a').attr('href', objectUrl).attr('download', file.name)
      step(3)
    })
  })
}

function reset () {
  peers.forEach(peer => peer.destroy())
  peers = []
  hub.close()
  sw.close()
  initialize()
}

function bootAnimation () {
  let button = $('#step1 .button')
  button.css('cursor', 'pointer')
  button.click(function () {
    $('#send-input').click()
  })
  setTimeout(function () {
    button.attr('class', 'button green send')
    button.html('send a file')
    button.toggleClass('send')
    button.toggleClass('browse')
    button.css('cursor', 'pointer')
  }, 200)
}

function step (i) {
  let stage = $('#stage')
  let back = $('a.back')
  if (i === 1) back.fadeOut()
  else $('a.back').fadeIn()
  stage.css('top', (-(i - 1) * 100) + '%')
}

function randomHex (len) {
  // https://github.com/mafintosh/webrtc-swarm/commit/ce77175c7d48cf4fad11c5e40f8869ebf0d7f303#diff-1dd241c4cd3fd1dd89c570cee98b79dd
  return crypto.randomBytes(Math.ceil(len / 2))
    .toString('hex')
    .slice(0, len)
}
<|endoftext|>


<commit_before>// Credit: Fixed and cleaned version of @melux's demo-zoom:
// https://gist.github.com/melux/50c0f994bfa1caf2c1a0

'use strict';

var customError   = require('es5-ext/error/custom')
  , element       = require('../valid-html-element')
  , getDimensions = require('./get-dimensions')
  , getPosition   = require('./get-position')
  , isImage       = require('../../html-image-element/is-html-image-element')
  , imgPromise    = require('../../html-image-element/#/promise');

module.exports = function (/* options */) {
	var wheelEventName, image, wrapDim, imageDim, onMove, zoom = 1, init
	  , options = Object(arguments[0]), checkAndInit;

	if (element(this).onmousewheel === undefined) {
		if (this.onwheel === undefined) {
			throw customError('Wheel event not supported',
				'WHEEL_EVENT_NOT_SUPPORTED');
		}
		wheelEventName = 'wheel';
	} else {
		wheelEventName = 'mousewheel';
	}

	image = element(this.firstElementChild);

	init = function () {
		imageDim = {
			width: options.width || image.naturalWidth,
			height: options.height || image.naturalHeight
		};

		if (!imageDim.width || !imageDim.height) {
			throw customError("No image dimensions detected", 'NO_DIMENSIONS');
		}

		wrapDim = getDimensions.call(this);
		if (!wrapDim.width || !wrapDim.height) {
			throw customError("No wrap dimensions detected", 'NO_DIMENSIONS');
		}

		this.style.overflow = 'hidden';
		this.style.position = 'relative';
		this.style.cursor = 'crosshair';

		this.addEventListener('mouseover', function () {
			image.style.position = 'absolute';
			image.style.top = '0';
			image.style.left = '0';
			image.style.width = (imageDim.width * zoom) + 'px';
			image.style.height = (imageDim.height * zoom) + 'px';
			image.style.maxWidth = 'none';
			image.style.maxHeight = 'none';
		}, false);

		this.addEventListener('mousemove', onMove = function (e) {
			var pos = getPosition.call(this)
			  , mX = e.pageX - pos.left
			  , mY = e.pageY - pos.top
			  , ratioX = mX / wrapDim.width
			  , ratioY = mY / wrapDim.height
			  , iX = mX - imageDim.width * zoom * ratioX
			  , iY = mY - imageDim.height * zoom * ratioY;

			image.style.left = iX + 'px';
			image.style.top = iY + 'px';
		}, false);

		this.addEventListener('mouseout', function (e) {
			image.style.position = '';
			image.style.top = '';
			image.style.left = '';
			image.style.width = '';
			image.style.height = '';
			image.style.maxWidth = '';
			image.style.maxHeight = '';
		}, false);

		this.addEventListener(wheelEventName, function (e) {
			var deltaY = 0, delta;

			e.preventDefault();

			if (e.deltaY) {
				deltaY = e.deltaY;
			} else if (e.wheelDelta) {
				deltaY = -e.wheelDelta;
			}

			delta = deltaY / 1200;

			if (((zoom + delta) <= 1) && ((zoom + delta) > 0) &&
					(((imageDim.width * (zoom + delta)) > wrapDim.width) ||
					((imageDim.height * (zoom + delta)) > wrapDim.height))) {
				zoom += delta;

				image.style.width = (imageDim.width * zoom) + 'px';
				image.style.height = (imageDim.height * zoom) + 'px';
			}

			onMove.call(this, e);
		}, false);
	}.bind(this);

	checkAndInit = function () {
		if (this.offsetWidth && this.offsetHeight) init();
		else setTimeout(checkAndInit, 200);
	}.bind(this);

	if (isImage(image)) imgPromise.call(image).end(checkAndInit);
	else checkAndInit();

	return this;
};
<commit_msg>Update up to changes in deferred package<commit_after>// Credit: Fixed and cleaned version of @melux's demo-zoom:
// https://gist.github.com/melux/50c0f994bfa1caf2c1a0

'use strict';

var customError   = require('es5-ext/error/custom')
  , element       = require('../valid-html-element')
  , getDimensions = require('./get-dimensions')
  , getPosition   = require('./get-position')
  , isImage       = require('../../html-image-element/is-html-image-element')
  , imgPromise    = require('../../html-image-element/#/promise');

module.exports = function (/* options */) {
	var wheelEventName, image, wrapDim, imageDim, onMove, zoom = 1, init
	  , options = Object(arguments[0]), checkAndInit;

	if (element(this).onmousewheel === undefined) {
		if (this.onwheel === undefined) {
			throw customError('Wheel event not supported',
				'WHEEL_EVENT_NOT_SUPPORTED');
		}
		wheelEventName = 'wheel';
	} else {
		wheelEventName = 'mousewheel';
	}

	image = element(this.firstElementChild);

	init = function () {
		imageDim = {
			width: options.width || image.naturalWidth,
			height: options.height || image.naturalHeight
		};

		if (!imageDim.width || !imageDim.height) {
			throw customError("No image dimensions detected", 'NO_DIMENSIONS');
		}

		wrapDim = getDimensions.call(this);
		if (!wrapDim.width || !wrapDim.height) {
			throw customError("No wrap dimensions detected", 'NO_DIMENSIONS');
		}

		this.style.overflow = 'hidden';
		this.style.position = 'relative';
		this.style.cursor = 'crosshair';

		this.addEventListener('mouseover', function () {
			image.style.position = 'absolute';
			image.style.top = '0';
			image.style.left = '0';
			image.style.width = (imageDim.width * zoom) + 'px';
			image.style.height = (imageDim.height * zoom) + 'px';
			image.style.maxWidth = 'none';
			image.style.maxHeight = 'none';
		}, false);

		this.addEventListener('mousemove', onMove = function (e) {
			var pos = getPosition.call(this)
			  , mX = e.pageX - pos.left
			  , mY = e.pageY - pos.top
			  , ratioX = mX / wrapDim.width
			  , ratioY = mY / wrapDim.height
			  , iX = mX - imageDim.width * zoom * ratioX
			  , iY = mY - imageDim.height * zoom * ratioY;

			image.style.left = iX + 'px';
			image.style.top = iY + 'px';
		}, false);

		this.addEventListener('mouseout', function (e) {
			image.style.position = '';
			image.style.top = '';
			image.style.left = '';
			image.style.width = '';
			image.style.height = '';
			image.style.maxWidth = '';
			image.style.maxHeight = '';
		}, false);

		this.addEventListener(wheelEventName, function (e) {
			var deltaY = 0, delta;

			e.preventDefault();

			if (e.deltaY) {
				deltaY = e.deltaY;
			} else if (e.wheelDelta) {
				deltaY = -e.wheelDelta;
			}

			delta = deltaY / 1200;

			if (((zoom + delta) <= 1) && ((zoom + delta) > 0) &&
					(((imageDim.width * (zoom + delta)) > wrapDim.width) ||
					((imageDim.height * (zoom + delta)) > wrapDim.height))) {
				zoom += delta;

				image.style.width = (imageDim.width * zoom) + 'px';
				image.style.height = (imageDim.height * zoom) + 'px';
			}

			onMove.call(this, e);
		}, false);
	}.bind(this);

	checkAndInit = function () {
		if (this.offsetWidth && this.offsetHeight) init();
		else setTimeout(checkAndInit, 200);
	}.bind(this);

	if (isImage(image)) imgPromise.call(image).done(checkAndInit);
	else checkAndInit();

	return this;
};
<|endoftext|>


<commit_before>const p5js_utils =
{
  isPaused: false
};

class P5JsUtils {
  static get UP(){    return 0; }
  static get RIGHT(){ return 1; }
  static get DOWN(){  return 2; }
  static get LEFT(){  return 3; }

  static colorAt(x, y, width){
    return P5JsUtils.colorAtInPixels(x, y, width, pixels);
  }

  static colorAtInPixels(x, y, width, pixels){
    let baseIdx = (round(x) + round(y) * width) * 4;
    return color(
              pixels[baseIdx + 0],
              pixels[baseIdx + 1],
              pixels[baseIdx + 2],
              pixels[baseIdx + 3]);
  }

  static get mousePoint(){
    return {x: mouseX, y: mouseY};
  }

  static colorsMatch(c1, c2){
    return      c1.levels[0] == c2.levels[0]
             && c1.levels[1] == c2.levels[1]
             && c1.levels[2] == c2.levels[2]
             && alpha(c1) == alpha(c2);
  }

  static get COLOR_ID_RED(){ return 0; }
  static get COLOR_ID_GREEN(){ return 1; }
  static get COLOR_ID_BLUE(){ return 2; }
  static get COLOR_ID_ORANGE(){ return 3; }
  static get COLOR_ID_YELLOW(){ return 4; }
  static get COLOR_ID_VIOLET(){ return 5; }

  static getRandomColorByID(colorId){
    switch(colorId) {
      case P5JsUtils.COLOR_ID_RED:    return P5JsUtils.getRandomRed();
      case P5JsUtils.COLOR_ID_GREEN:  return P5JsUtils.getRandomGreen();
      case P5JsUtils.COLOR_ID_BLUE:   return P5JsUtils.getRandomBlue();
      case P5JsUtils.COLOR_ID_ORANGE: return P5JsUtils.getRandomOrange();
      case P5JsUtils.COLOR_ID_YELLOW: return P5JsUtils.getRandomYellow();
      case P5JsUtils.COLOR_ID_VIOLET: return P5JsUtils.getRandomViolet();
      default: return P5JsUtils.getRandomColor();
    }
  }

  static getRandomRed(){
    return P5JsUtils.getRandomColor(155, 255, 1, 0, 0);
  }
  static getRandomGreen(){
    return P5JsUtils.getRandomColor(155, 255, 0, 1, 0);
  }
  static getRandomBlue(){
    return P5JsUtils.getRandomColor(155, 255, 0, 0, 1);
  }
  static getRandomOrange(){
    return P5JsUtils.getRandomColor(155, 255, 1, 0.5, 0);
  }
  static getRandomYellow(){
    return P5JsUtils.getRandomColor(155, 255, 1, 1, 0);
  }
  static getRandomViolet(){
    return P5JsUtils.getRandomColor(155, 255, 1, 0, 1);
  }

  static getRandomColor(minVal, maxVal, redFactor, greenFactor, blueFactor){
    minVal = minVal || 150;
    maxVal = maxVal || 255;
    if (redFactor == undefined) { redFactor = random(); }
    if (greenFactor == undefined) { greenFactor = random(); }
    if (blueFactor == undefined) { blueFactor = random(); }

    let baseVal = random(minVal, maxVal);
    let secondaryVal = baseVal * (0.1 + random(0, 0.5));

    let redLvl   = baseVal * redFactor + secondaryVal * (1 - redFactor);
    let greenLvl = baseVal * greenFactor + secondaryVal * (1 - greenFactor);
    let blueLvl  = baseVal * blueFactor + secondaryVal * (1 - blueFactor);
    return color(redLvl, greenLvl, blueLvl);
  }

  static toggleLoop(){
    if (p5js_utils.isPaused){
      loop();
      p5js_utils.isPaused = false;
    }else{
      noLoop();
      p5js_utils.isPaused = true;
    }
  }

  static drawSolidBoundary(fromX, fromY, toX, toY, options = {}){
    line(fromX, fromY, toX, toY);
    const dashesAbove = options['dashes_above'] === true;

    push();
    translate(fromX, fromY);
    if (fromY != toY){
      // rotate ... but currently assumes a horizontal line
    }

    const dashWidth = 20;
    const numDashes = Math.floor((toX - fromX) / dashWidth);
    let curX = 0;
    let startY  = dashesAbove ? 0 : dashWidth;
    let endY    = dashesAbove ? - dashWidth : 0;

    for (var i = 0; i<numDashes; i++){
      line (curX, startY, curX + dashWidth, endY);
      curX += dashWidth;
    }
    pop();
  }

  static drawRect(rectObj){
    rect(rectObj.x, rectObj.y, rectObj.width, rectObj.height);
  }

  static rotationBetweenVectors(v1, v2){
    let h1 = v1.heading();
    let h2 = v2.copy().rotate(-h1);
    return h2.heading();
  }

  static drawArrow(from, to){
    line(from.x, from.y, to.x, to.y);

    let segmentVector = createVector(to.x - from.x, to.y - from.y);
    let arrowVector = segmentVector.copy().setMag(8).rotate(0.1 * PI);

    line(to.x, to.y, to.x - arrowVector.x, to.y - arrowVector.y);
  }

  // Intent is to return a p5.Image from the 'file' input of
  // the canvas.drop(...) callback.
  static p5ImageFromFile(file){
    // async call, should have callback
    const img = createImg(file.data).hide();
    const gBuffer = createGraphics(img.width, img.height);

    gBuffer.image(img, 0, 0, img.width, img.height);
    gBuffer.loadPixels();

    const resultImage = createImage(img.width, img.height);
    resultImage.loadPixels();
    gBuffer.pixels.forEach((val, idx) => {
      resultImage.pixels[idx] = gBuffer.pixels[idx];
    });
    resultImage.updatePixels();
    return resultImage;
  }

  // Primary approach of temp canvas and copying over from:
  //   https://stackoverflow.com/a/32257161
  static saveCanvasArea(p5Canvas, rectArea){
    let fromCanvas = document.getElementById(p5Canvas.id());
    let tmpCanvas = document.createElement("canvas");

    tmpCanvas.style.display = 'none';
    document.body.appendChild(tmpCanvas);
    tmpCanvas.width = rectArea.width;
    tmpCanvas.height = rectArea.height;

    var tmpCtx = tmpCanvas.getContext('2d');
    tmpCtx.drawImage(
        fromCanvas,
        rectArea.x, rectArea.y, rectArea.width, rectArea.height,
        0,0, tmpCanvas.width, tmpCanvas.height
    );

    let filename  = "screenshot-partial";
    let extension = 'png';
    let mimeType  = 'image/png';

    // following block from: p5js.saveCanvas
    // https://github.com/processing/p5.js/blob/da8abf57c79a99736e3c6ccb8146abc115f3d84a/src/image/image.js#L190-L192
    tmpCanvas.toBlob(function(blob) {
      p5.prototype.downloadFile(blob, filename, extension);
    }, mimeType);

    tmpCanvas.parentNode.removeChild(tmpCanvas);
  }
}
<commit_msg>p5js/common - Add P5Js.applyStyleSet(...) to<commit_after>const p5js_utils =
{
  isPaused: false
};

class P5JsUtils {
  static get UP(){    return 0; }
  static get RIGHT(){ return 1; }
  static get DOWN(){  return 2; }
  static get LEFT(){  return 3; }

  static colorAt(x, y, width){
    return P5JsUtils.colorAtInPixels(x, y, width, pixels);
  }

  static colorAtInPixels(x, y, width, pixels){
    let baseIdx = (round(x) + round(y) * width) * 4;
    return color(
              pixels[baseIdx + 0],
              pixels[baseIdx + 1],
              pixels[baseIdx + 2],
              pixels[baseIdx + 3]);
  }

  static get mousePoint(){
    return {x: mouseX, y: mouseY};
  }

  static colorsMatch(c1, c2){
    return      c1.levels[0] == c2.levels[0]
             && c1.levels[1] == c2.levels[1]
             && c1.levels[2] == c2.levels[2]
             && alpha(c1) == alpha(c2);
  }

  static get COLOR_ID_RED(){ return 0; }
  static get COLOR_ID_GREEN(){ return 1; }
  static get COLOR_ID_BLUE(){ return 2; }
  static get COLOR_ID_ORANGE(){ return 3; }
  static get COLOR_ID_YELLOW(){ return 4; }
  static get COLOR_ID_VIOLET(){ return 5; }

  static getRandomColorByID(colorId){
    switch(colorId) {
      case P5JsUtils.COLOR_ID_RED:    return P5JsUtils.getRandomRed();
      case P5JsUtils.COLOR_ID_GREEN:  return P5JsUtils.getRandomGreen();
      case P5JsUtils.COLOR_ID_BLUE:   return P5JsUtils.getRandomBlue();
      case P5JsUtils.COLOR_ID_ORANGE: return P5JsUtils.getRandomOrange();
      case P5JsUtils.COLOR_ID_YELLOW: return P5JsUtils.getRandomYellow();
      case P5JsUtils.COLOR_ID_VIOLET: return P5JsUtils.getRandomViolet();
      default: return P5JsUtils.getRandomColor();
    }
  }

  static getRandomRed(){
    return P5JsUtils.getRandomColor(155, 255, 1, 0, 0);
  }
  static getRandomGreen(){
    return P5JsUtils.getRandomColor(155, 255, 0, 1, 0);
  }
  static getRandomBlue(){
    return P5JsUtils.getRandomColor(155, 255, 0, 0, 1);
  }
  static getRandomOrange(){
    return P5JsUtils.getRandomColor(155, 255, 1, 0.5, 0);
  }
  static getRandomYellow(){
    return P5JsUtils.getRandomColor(155, 255, 1, 1, 0);
  }
  static getRandomViolet(){
    return P5JsUtils.getRandomColor(155, 255, 1, 0, 1);
  }

  static getRandomColor(minVal, maxVal, redFactor, greenFactor, blueFactor){
    minVal = minVal || 150;
    maxVal = maxVal || 255;
    if (redFactor == undefined) { redFactor = random(); }
    if (greenFactor == undefined) { greenFactor = random(); }
    if (blueFactor == undefined) { blueFactor = random(); }

    let baseVal = random(minVal, maxVal);
    let secondaryVal = baseVal * (0.1 + random(0, 0.5));

    let redLvl   = baseVal * redFactor + secondaryVal * (1 - redFactor);
    let greenLvl = baseVal * greenFactor + secondaryVal * (1 - greenFactor);
    let blueLvl  = baseVal * blueFactor + secondaryVal * (1 - blueFactor);
    return color(redLvl, greenLvl, blueLvl);
  }

  static toggleLoop(){
    if (p5js_utils.isPaused){
      loop();
      p5js_utils.isPaused = false;
    }else{
      noLoop();
      p5js_utils.isPaused = true;
    }
  }

  static drawSolidBoundary(fromX, fromY, toX, toY, options = {}){
    line(fromX, fromY, toX, toY);
    const dashesAbove = options['dashes_above'] === true;

    push();
    translate(fromX, fromY);
    if (fromY != toY){
      // rotate ... but currently assumes a horizontal line
    }

    const dashWidth = 20;
    const numDashes = Math.floor((toX - fromX) / dashWidth);
    let curX = 0;
    let startY  = dashesAbove ? 0 : dashWidth;
    let endY    = dashesAbove ? - dashWidth : 0;

    for (var i = 0; i<numDashes; i++){
      line (curX, startY, curX + dashWidth, endY);
      curX += dashWidth;
    }
    pop();
  }

  static drawRect(rectObj){
    rect(rectObj.x, rectObj.y, rectObj.width, rectObj.height);
  }

  static rotationBetweenVectors(v1, v2){
    let h1 = v1.heading();
    let h2 = v2.copy().rotate(-h1);
    return h2.heading();
  }

  static drawArrow(from, to){
    line(from.x, from.y, to.x, to.y);

    let segmentVector = createVector(to.x - from.x, to.y - from.y);
    let arrowVector = segmentVector.copy().setMag(8).rotate(0.1 * PI);

    line(to.x, to.y, to.x - arrowVector.x, to.y - arrowVector.y);
  }

  // Intent is to return a p5.Image from the 'file' input of
  // the canvas.drop(...) callback.
  static p5ImageFromFile(file){
    // async call, should have callback
    const img = createImg(file.data).hide();
    const gBuffer = createGraphics(img.width, img.height);

    gBuffer.image(img, 0, 0, img.width, img.height);
    gBuffer.loadPixels();

    const resultImage = createImage(img.width, img.height);
    resultImage.loadPixels();
    gBuffer.pixels.forEach((val, idx) => {
      resultImage.pixels[idx] = gBuffer.pixels[idx];
    });
    resultImage.updatePixels();
    return resultImage;
  }

  // Primary approach of temp canvas and copying over from:
  //   https://stackoverflow.com/a/32257161
  static saveCanvasArea(p5Canvas, rectArea){
    let fromCanvas = document.getElementById(p5Canvas.id());
    let tmpCanvas = document.createElement("canvas");

    tmpCanvas.style.display = 'none';
    document.body.appendChild(tmpCanvas);
    tmpCanvas.width = rectArea.width;
    tmpCanvas.height = rectArea.height;

    var tmpCtx = tmpCanvas.getContext('2d');
    tmpCtx.drawImage(
        fromCanvas,
        rectArea.x, rectArea.y, rectArea.width, rectArea.height,
        0,0, tmpCanvas.width, tmpCanvas.height
    );

    let filename  = "screenshot-partial";
    let extension = 'png';
    let mimeType  = 'image/png';

    // following block from: p5js.saveCanvas
    // https://github.com/processing/p5.js/blob/da8abf57c79a99736e3c6ccb8146abc115f3d84a/src/image/image.js#L190-L192
    tmpCanvas.toBlob(function(blob) {
      p5.prototype.downloadFile(blob, filename, extension);
    }, mimeType);

    tmpCanvas.parentNode.removeChild(tmpCanvas);
  }

  static applyStyleSet(styleSet){
    if (styleSet.fillColor) { fill(styleSet.fillColor); }
    if (styleSet.noFill) { noFill(); }
    if (styleSet.strokeColor) { stroke(styleSet.strokeColor); }
    if (styleSet.noStroke) { noStroke(); }
    if (styleSet.strokeWeight) { strokeWeight(styleSet.strokeWeight); }
  }
}
<|endoftext|>


<commit_before>import { combineReducers } from 'redux';
import PostsReducer from './reducer_posts';

const rootReducer = combineReducers({
  posts: PostsReducer
});

export default rootReducer;
<commit_msg>Wiring up the reducer: formReducer to the app<commit_after>import { combineReducers } from 'redux';
import PostsReducer from './reducer_posts';
import { reducer as formReducer } from 'redux-form';

const rootReducer = combineReducers({
  posts: PostsReducer,
  form: formReducer
});

export default rootReducer;
<|endoftext|>


<commit_before>//
// Message
//

'use strict';

var mongoose = require('mongoose'),
    settings = require('./../config');

var ObjectId = mongoose.Schema.Types.ObjectId;

var MessageSchema = new mongoose.Schema({
    users: [{
        type: ObjectId,
        ref: 'User'
    }],
    owner: {
        type: ObjectId,
        ref: 'User',
        required: true
    },
    text: {
        type: String,
        required: true,
        trim: true
    },
    posted: {
        type: Date,
        default: Date.now
    }
});

if (settings.private.expire !== false) {
    var defaultExpire = 6 * 60; // 6 hours

    MessageSchema.index({ posted: 1 }, {
        expireAfterSeconds: (settings.private.expire || defaultExpire) * 60
    });
}

MessageSchema.index({ users: 1, posted: -1, _id: 1 });

// EXPOSE ONLY CERTAIN FIELDS
// This helps ensure that the client gets
// data that can be digested properly
MessageSchema.method('toJSON', function() {
    return {
        id: this._id,
        owner: this.owner,
        text: this.text,
        posted: this.posted
    };
});

module.exports = mongoose.model('UserMessage', MessageSchema);
<commit_msg>Message text is no longer trimmed<commit_after>//
// Message
//

'use strict';

var mongoose = require('mongoose'),
    settings = require('./../config');

var ObjectId = mongoose.Schema.Types.ObjectId;

var MessageSchema = new mongoose.Schema({
    users: [{
        type: ObjectId,
        ref: 'User'
    }],
    owner: {
        type: ObjectId,
        ref: 'User',
        required: true
    },
    text: {
        type: String,
        required: true
    },
    posted: {
        type: Date,
        default: Date.now
    }
});

if (settings.private.expire !== false) {
    var defaultExpire = 6 * 60; // 6 hours

    MessageSchema.index({ posted: 1 }, {
        expireAfterSeconds: (settings.private.expire || defaultExpire) * 60
    });
}

MessageSchema.index({ users: 1, posted: -1, _id: 1 });

// EXPOSE ONLY CERTAIN FIELDS
// This helps ensure that the client gets
// data that can be digested properly
MessageSchema.method('toJSON', function() {
    return {
        id: this._id,
        owner: this.owner,
        text: this.text,
        posted: this.posted
    };
});

module.exports = mongoose.model('UserMessage', MessageSchema);
<|endoftext|>


<commit_before>var win = Titanium.UI.currentWindow;

var b1 = Titanium.UI.createButton({
	title:'I am a Button',
	height:40,
	width:200,
	top:10
});

var b2 = Titanium.UI.createButton({
	title:'I am a Button',
	image:'../images/chat.png',
	width:200,
	height:40,
	top:60
});

var b3 = Titanium.UI.createButton({
	color:'#fff',
	backgroundImage:'../images/BUTT_grn_off.png',
	backgroundSelectedImage:'../images/BUTT_grn_on.png',
	backgroundDisabledImage: '../images/BUTT_drk_off.png',
	top:110,
	width:301,
	height:57,
	font:{fontSize:20,fontWeight:'bold',fontFamily:'Helvetica Neue'},
	title:'Click Me'
});

var buttonLabel = Titanium.UI.createLabel({
	color:'#f00',
	highlightedColor:'#0f0',
	backgroundColor:'transparent',
	width:'100',
	height:'auto',
	right:5,
	text:'Custom Label'
});

b3.add(buttonLabel);

var state = 0;
b3.addEventListener('click', function()
{
	switch (state)
	{
		case 0:
			b3.enabled=false;
			b3.title = 'I am Disabled';
			state++;

			setTimeout(function()
			{
				b3.enabled=true;
				b3.title = 'I am Enabled';
			},1000);

			break;
		case 1:
			b3.font = {fontSize:25,fontFamily:'Marker Felt', fontWeight:'bold'};
			b3.title = 'I am red';
			b3.backgroundImage = '../images/BUTT_red_off.png';
			b3.backgroundSelectedImage = '../images/BUTT_red_on.png';
			b3.color = '#222';
			state++;
			break;
		case 2:
			b3.width = 200;
			b3.color = '#fff';
			b3.title = 'White text';
			state=0;
			break;
	}
});

var b4 = Titanium.UI.createButton({
	title:'Hide/Show Button Above',
	width:200,
	height:40,
	top:175
});

var visible = true;
b4.addEventListener('click', function()
{
	if (!visible)
	{
		b3.show();
		visible=true;
	}
	else
	{
		b3.hide();
		visible=false;
	}
});

var b5 = Titanium.UI.createButton({
	width:200,
	height:40,
	top:225
});
var b5Label = Ti.UI.createLabel({
	text:'Label',
	width:50,
	height:20,
	color:'#336699'
});
b5.add(b5Label);

var b5ImageView = Ti.UI.createImageView({
	image:'../images/camera.png',
	left:10,
	height:33,
	width:33
});
b5.add(b5ImageView);
b5.addEventListener('touchstart', function()
{
	b5Label.color = 'red';
});
b5.addEventListener('touchend', function()
{
	b5Label.color = '#336699';
});
win.add(b1);
win.add(b3);
win.add(b4);

// add iphone specific tests
if (Titanium.Platform.name == 'iPhone OS')
{
	win.add(b2);
	win.add(b5);
}

var bhleft = Titanium.UI.createButton({
	title : 'H-Left',
	width : 50,
	height: 40,
	top : 300,
	left : 60
});
bhleft.addEventListener('click', function() {
	b1.textAlign = Titanium.UI.TEXT_ALIGNMENT_LEFT;
});

var bhcenter = Titanium.UI.createButton({
	title : 'H-Center',
	width : 50,
	height: 40,
	top : 300,
	left : 120
});
bhcenter.addEventListener('click', function() {
	b1.textAlign = Titanium.UI.TEXT_ALIGNMENT_CENTER;
});

var bhright = Titanium.UI.createButton({
	title : 'H-Right',
	width : 50,
	height: 40,
	top : 300,
	left : 180
});
bhright.addEventListener('click', function() {
	b1.textAlign = Titanium.UI.TEXT_ALIGNMENT_RIGHT;
});

var bvtop = Titanium.UI.createButton({
	title : 'V-Top',
	width : 50,
	height: 40,
	top : 350,
	left : 60
});
bvtop.addEventListener('click', function() {
	b1.verticalAlign = Titanium.UI.TEXT_VERTICAL_ALIGNMENT_TOP;
});

var bvcenter = Titanium.UI.createButton({
	title : 'V-Center',
	width : 50,
	height: 40,
	top : 350,
	left : 120
});
bvcenter.addEventListener('click', function() {
	b1.verticalAlign = Titanium.UI.TEXT_VERTICAL_ALIGNMENT_CENTER;
});

var bvbottom = Titanium.UI.createButton({
	title : 'V-Bottom',
	width : 50,
	height: 40,
	top : 350,
	left : 180
});
bvbottom.addEventListener('click', function() {
	b1.verticalAlign = Titanium.UI.TEXT_VERTICAL_ALIGNMENT_BOTTOM;
});

win.add(bhleft);
win.add(bhcenter);
win.add(bhright);
win.add(bvtop);
win.add(bvcenter);
win.add(bvbottom);<commit_msg>Controls > Button<commit_after>function button_control() {
	var win = Ti.UI.createWindow();

	var b1 = Titanium.UI.createButton({
		title:'I am a Button',
		height:40,
		width:200,
		top:10
	});

	var b2 = Titanium.UI.createButton({
		title:'I am a Button',
		image:'/images/chat.png',
		width:200,
		height:40,
		top:60
	});

	var b3 = Titanium.UI.createButton({
		color:'#fff',
		backgroundImage:'/images/BUTT_grn_off.png',
		backgroundSelectedImage:'/images/BUTT_grn_on.png',
		backgroundDisabledImage: '/images/BUTT_drk_off.png',
		top:110,
		width:301,
		height:57,
		font:{fontSize:20,fontWeight:'bold',fontFamily:'Helvetica Neue'},
		title:'Click Me'
	});

	var buttonLabel = Titanium.UI.createLabel({
		color:'#f00',
		highlightedColor:'#0f0',
		backgroundColor:'transparent',
		width:'100',
		height:'auto',
		right:5,
		text:'Custom Label'
	});

	b3.add(buttonLabel);

	var state = 0;
	b3.addEventListener('click', function()
	{
		switch (state)
		{
			case 0:
				b3.enabled=false;
				b3.title = 'I am Disabled';
				state++;

				setTimeout(function()
				{
					b3.enabled=true;
					b3.title = 'I am Enabled';
				},1000);

				break;
			case 1:
				b3.font = {fontSize:25,fontFamily:'Marker Felt', fontWeight:'bold'};
				b3.title = 'I am red';
				b3.backgroundImage = '/images/BUTT_red_off.png';
				b3.backgroundSelectedImage = '/images/BUTT_red_on.png';
				b3.color = '#222';
				state++;
				break;
			case 2:
				b3.width = 200;
				b3.color = '#fff';
				b3.title = 'White text';
				state=0;
				break;
		}
	});

	var b4 = Titanium.UI.createButton({
		title:'Hide/Show Button Above',
		width:200,
		height:40,
		top:175
	});

	var visible = true;
	b4.addEventListener('click', function()
	{
		if (!visible)
		{
			b3.show();
			visible=true;
		}
		else
		{
			b3.hide();
			visible=false;
		}
	});

	var b5 = Titanium.UI.createButton({
		width:200,
		height:40,
		top:225
	});
	var b5Label = Ti.UI.createLabel({
		text:'Label',
		width:50,
		height:20,
		color:'#336699'
	});
	b5.add(b5Label);

	var b5ImageView = Ti.UI.createImageView({
		image:'/images/camera.png',
		left:10,
		height:33,
		width:33
	});
	b5.add(b5ImageView);
	b5.addEventListener('touchstart', function()
	{
		b5Label.color = 'red';
	});
	b5.addEventListener('touchend', function()
	{
		b5Label.color = '#336699';
	});
	win.add(b1);
	win.add(b3);
	win.add(b4);

	// add iphone specific tests
	if (Titanium.Platform.name == 'iPhone OS')
	{
		win.add(b2);
		win.add(b5);
	}

	var bhleft = Titanium.UI.createButton({
		title : 'H-Left',
		width : 50,
		height: 40,
		top : 300,
		left : 60
	});
	bhleft.addEventListener('click', function() {
		b1.textAlign = Titanium.UI.TEXT_ALIGNMENT_LEFT;
	});

	var bhcenter = Titanium.UI.createButton({
		title : 'H-Center',
		width : 50,
		height: 40,
		top : 300,
		left : 120
	});
	bhcenter.addEventListener('click', function() {
		b1.textAlign = Titanium.UI.TEXT_ALIGNMENT_CENTER;
	});

	var bhright = Titanium.UI.createButton({
		title : 'H-Right',
		width : 50,
		height: 40,
		top : 300,
		left : 180
	});
	bhright.addEventListener('click', function() {
		b1.textAlign = Titanium.UI.TEXT_ALIGNMENT_RIGHT;
	});

	var bvtop = Titanium.UI.createButton({
		title : 'V-Top',
		width : 50,
		height: 40,
		top : 350,
		left : 60
	});
	bvtop.addEventListener('click', function() {
		b1.verticalAlign = Titanium.UI.TEXT_VERTICAL_ALIGNMENT_TOP;
	});

	var bvcenter = Titanium.UI.createButton({
		title : 'V-Center',
		width : 50,
		height: 40,
		top : 350,
		left : 120
	});
	bvcenter.addEventListener('click', function() {
		b1.verticalAlign = Titanium.UI.TEXT_VERTICAL_ALIGNMENT_CENTER;
	});

	var bvbottom = Titanium.UI.createButton({
		title : 'V-Bottom',
		width : 50,
		height: 40,
		top : 350,
		left : 180
	});
	bvbottom.addEventListener('click', function() {
		b1.verticalAlign = Titanium.UI.TEXT_VERTICAL_ALIGNMENT_BOTTOM;
	});

	win.add(bhleft);
	win.add(bhcenter);
	win.add(bhright);
	win.add(bvtop);
	win.add(bvcenter);
	win.add(bvbottom);

	return win;
}

module.exports = button_control;<|endoftext|>


<commit_before>var generators = require('yeoman-generator');
var path = require('path');
var _ = require('lodash');
var npmVersion = require('../lib/utils').npmVersion;

module.exports = generators.Base.extend({
  initializing: function () {
    this.pkg = this.fs.readJSON(this.destinationPath('package.json'), {});

    // Pre set the default props from the information we have at this point
    this.props = {
      name: this.pkg.name,
      description: this.pkg.description,
      version: this.pkg.version,
      homepage: this.pkg.homepage,
      repository: this.pkg.repository
    };

    this.mainFiles = [
      'documentjs.json',
      'readme.md',
      '_gitignore',
      'test/test.html',
      'test/test.js',
    ];

    this.srcFiles = [
      'plugin_test.js',
      'plugin.js',
      'plugin.md'
    ];
  },

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

    npmVersion(function(err, version){
      if(err) {
        done(err);
        return;
      }

      var prompts = [{
        name: 'name',
        message: 'Project name',
        when: !this.pkg.name,
        default: process.cwd().split(path.sep).pop()
      }, {
        name: 'folder',
        message: 'Project main folder',
        default: 'src'
      }, {
        name: 'description',
        message: 'Description',
        when: !this.pkg.description
      }, {
        name: 'homepage',
        message: 'Project homepage url',
        when: !this.pkg.homepage
      }, {
        name: 'githubAccount',
        message: 'GitHub username or organization',
        when: !this.pkg.repository
      }, {
        name: 'authorName',
        message: 'Author\'s Name',
        when: !this.pkg.author,
        store: true
      }, {
        name: 'authorEmail',
        message: 'Author\'s Email',
        when: !this.pkg.author,
        store: true
      }, {
        name: 'authorUrl',
        message: 'Author\'s Homepage',
        when: !this.pkg.author,
        store: true
      }, {
        name: 'keywords',
        message: 'Application keywords',
        when: !this.pkg.keywords,
        filter: _.words
      }, {
        name: 'npmVersion',
        message: 'NPM version used',
        default: version.major
      }];

      this.prompt(prompts, function (props) {
        this.props = _.extend(this.props, props);
        this.props.name = _.kebabCase(this.props.name);
        done();
      }.bind(this));
    }.bind(this));
  },

  writing: function () {
    var self = this;
    var jshintFolder = this.props.folder && this.props.folder !== '.' ?
      ' ./' + this.props.folder + '/' : '';
    var pkgJsonFields = {
      name: this.props.name,
      version: '0.0.0',
      description: this.props.description,
      homepage: this.props.homepage,
      repository: this.props.repository,
      author: {
        name: this.props.authorName,
        email: this.props.authorEmail,
        url: this.props.authorUrl
      },
      "scripts": {
        preversion: "npm test && npm run build",
        version: "git commit -am \"Update dist for release\" && git checkout -b release && git add -f dist/",
        postversion: "git push --tags && git checkout master && git branch -D release && git push",
        testee: "testee test/test.html --browsers firefox",
        test: "npm run jshint && npm run testee",
        jshint: "jshint ./*.js" + jshintFolder + " --config",
        "release:patch": "npm version patch && npm publish",
        "release:minor": "npm version minor && npm publish",
        "release:major": "npm version major && npm publish",
        build: "node build.js",
        document: "documentjs",
        develop: "done-serve --static --develop --port 8080"
      },
      main: "dist/cjs/" + this.props.name,
      browser: {
       transform: [ "cssify" ]
      },
      browserify: {
       transform: [ "cssify" ]
      },
      keywords: this.props.keywords,
      system: {
        main: this.props.name,
        configDependencies: [ 'live-reload' ],
        npmIgnore: [
          'documentjs',
          'testee',
          'generator-donejs',
          'donejs-cli',
          'steal-tools'
        ]
      }
    };

    if(this.props.folder && this.props.folder !== '.') {
      pkgJsonFields.system.directories = { lib: this.props.folder };
    }

    if(this.props.npmVersion >= 3) {
      pkgJsonFields.system.npmAlgorithm = 'flat';
    }

    if(!this.options.packages) {
      throw new Error('No DoneJS dependency package list provided!');
    }

    this.log('Writing package.json v' + this.options.version);

    var getDependency = function(name) {
      return self.options.packages.dependencies[name] ||
        self.options.packages.devDependencies[name];
    };

    this.fs.writeJSON('package.json', _.extend(pkgJsonFields, this.pkg, {
      dependencies: {
        'can': getDependency('can'),
        'jquery': getDependency('jquery')
      },
      devDependencies: {
        'documentjs': getDependency('documentjs'),
        'jshint': '^2.9.1',
        'cssify': '^0.6.0',
        'steal': getDependency('steal'),
        'steal-qunit': getDependency('steal-qunit'),
        'steal-tools': getDependency('steal-tools'),
        'testee': getDependency('testee'),
        'generator-donejs': getDependency('generator-donejs'),
        'donejs-cli': getDependency('donejs-cli'),
        'done-serve': getDependency('done-serve')
      }
    }));

    this.fs.copy(this.templatePath('static'), this.destinationPath());
    this.fs.copy(this.templatePath('static/.*'), this.destinationPath());

    this.mainFiles.forEach(function(name) {
      // Handle bug where npm has renamed .gitignore to .npmignore
      // https://github.com/npm/npm/issues/3763
      self.fs.copyTpl(
        self.templatePath(name),
        self.destinationPath((name === "_gitignore") ? ".gitignore" : name),
        self.props
      );
    });

    this.srcFiles.forEach(function(name) {
      self.fs.copyTpl(
        self.templatePath(name),
        self.destinationPath(path.join(self.props.folder, name.replace('plugin', self.props.name))),
        self.props
      );
    });
  },

  end: function () {
    if(!this.options.skipInstall) {
      var done = this.async();
      this.spawnCommand('npm', ['--loglevel', 'error', 'install']).on('close', done);
    }
  }
});
<commit_msg>Adding repository information to generated plugin<commit_after>var generators = require('yeoman-generator');
var path = require('path');
var _ = require('lodash');
var npmVersion = require('../lib/utils').npmVersion;

module.exports = generators.Base.extend({
  initializing: function () {
    this.pkg = this.fs.readJSON(this.destinationPath('package.json'), {});

    // Pre set the default props from the information we have at this point
    this.props = {
      name: this.pkg.name,
      description: this.pkg.description,
      version: this.pkg.version,
      homepage: this.pkg.homepage,
      repository: this.pkg.repository
    };

    this.mainFiles = [
      'documentjs.json',
      'readme.md',
      '_gitignore',
      'test/test.html',
      'test/test.js',
    ];

    this.srcFiles = [
      'plugin_test.js',
      'plugin.js',
      'plugin.md'
    ];
  },

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

    npmVersion(function(err, version){
      if(err) {
        done(err);
        return;
      }

      var prompts = [{
        name: 'name',
        message: 'Project name',
        when: !this.pkg.name,
        default: process.cwd().split(path.sep).pop()
      }, {
        name: 'folder',
        message: 'Project main folder',
        default: 'src'
      }, {
        name: 'description',
        message: 'Description',
        when: !this.pkg.description
      }, {
        name: 'homepage',
        message: 'Project homepage url',
        when: !this.pkg.homepage
      }, {
        name: 'githubAccount',
        message: 'GitHub username or organization',
        when: !this.pkg.repository
      }, {
        name: 'authorName',
        message: 'Author\'s Name',
        when: !this.pkg.author,
        store: true
      }, {
        name: 'authorEmail',
        message: 'Author\'s Email',
        when: !this.pkg.author,
        store: true
      }, {
        name: 'authorUrl',
        message: 'Author\'s Homepage',
        when: !this.pkg.author,
        store: true
      }, {
        name: 'keywords',
        message: 'Application keywords',
        when: !this.pkg.keywords,
        filter: _.words
      }, {
        name: 'npmVersion',
        message: 'NPM version used',
        default: version.major
      }];

      this.prompt(prompts, function (props) {
        this.props = _.extend(this.props, props);
        this.props.name = _.kebabCase(this.props.name);
        done();
      }.bind(this));
    }.bind(this));
  },

  writing: function () {
    var self = this;
    var jshintFolder = this.props.folder && this.props.folder !== '.' ?
      ' ./' + this.props.folder + '/' : '';
    var pkgJsonFields = {
      name: this.props.name,
      version: '0.0.0',
      description: this.props.description,
      homepage: this.props.homepage,
      repository: {
        type: 'git',
        url: 'git://github.com/' +  this.props.githubAccount + '/' + this.props.name + '.git'
      },
      author: {
        name: this.props.authorName,
        email: this.props.authorEmail,
        url: this.props.authorUrl
      },
      "scripts": {
        preversion: "npm test && npm run build",
        version: "git commit -am \"Update dist for release\" && git checkout -b release && git add -f dist/",
        postversion: "git push --tags && git checkout master && git branch -D release && git push",
        testee: "testee test/test.html --browsers firefox",
        test: "npm run jshint && npm run testee",
        jshint: "jshint ./*.js" + jshintFolder + " --config",
        "release:patch": "npm version patch && npm publish",
        "release:minor": "npm version minor && npm publish",
        "release:major": "npm version major && npm publish",
        build: "node build.js",
        document: "documentjs",
        develop: "done-serve --static --develop --port 8080"
      },
      main: "dist/cjs/" + this.props.name,
      browser: {
       transform: [ "cssify" ]
      },
      browserify: {
       transform: [ "cssify" ]
      },
      keywords: this.props.keywords,
      system: {
        main: this.props.name,
        configDependencies: [ 'live-reload' ],
        npmIgnore: [
          'documentjs',
          'testee',
          'generator-donejs',
          'donejs-cli',
          'steal-tools'
        ]
      }
    };

    if(this.props.folder && this.props.folder !== '.') {
      pkgJsonFields.system.directories = { lib: this.props.folder };
    }

    if(this.props.npmVersion >= 3) {
      pkgJsonFields.system.npmAlgorithm = 'flat';
    }

    if(!this.options.packages) {
      throw new Error('No DoneJS dependency package list provided!');
    }

    this.log('Writing package.json v' + this.options.version);

    var getDependency = function(name) {
      return self.options.packages.dependencies[name] ||
        self.options.packages.devDependencies[name];
    };

    this.fs.writeJSON('package.json', _.extend(pkgJsonFields, this.pkg, {
      dependencies: {
        'can': getDependency('can'),
        'jquery': getDependency('jquery')
      },
      devDependencies: {
        'documentjs': getDependency('documentjs'),
        'jshint': '^2.9.1',
        'cssify': '^0.6.0',
        'steal': getDependency('steal'),
        'steal-qunit': getDependency('steal-qunit'),
        'steal-tools': getDependency('steal-tools'),
        'testee': getDependency('testee'),
        'generator-donejs': getDependency('generator-donejs'),
        'donejs-cli': getDependency('donejs-cli'),
        'done-serve': getDependency('done-serve')
      }
    }));

    this.fs.copy(this.templatePath('static'), this.destinationPath());
    this.fs.copy(this.templatePath('static/.*'), this.destinationPath());

    this.mainFiles.forEach(function(name) {
      // Handle bug where npm has renamed .gitignore to .npmignore
      // https://github.com/npm/npm/issues/3763
      self.fs.copyTpl(
        self.templatePath(name),
        self.destinationPath((name === "_gitignore") ? ".gitignore" : name),
        self.props
      );
    });

    this.srcFiles.forEach(function(name) {
      self.fs.copyTpl(
        self.templatePath(name),
        self.destinationPath(path.join(self.props.folder, name.replace('plugin', self.props.name))),
        self.props
      );
    });
  },

  end: function () {
    if(!this.options.skipInstall) {
      var done = this.async();
      this.spawnCommand('npm', ['--loglevel', 'error', 'install']).on('close', done);
    }
  }
});
<|endoftext|>


<commit_before>"use strict";

module.exports = function(Chart) {

	var helpers = Chart.helpers;

	Chart.defaults.line = {
		showLines: true,

		hover: {
			mode: "label"
		},

		scales: {
			xAxes: [{
				type: "category",
				id: 'x-axis-0'
			}],
			yAxes: [{
				type: "linear",
				id: 'y-axis-0'
			}]
		}
	};

	Chart.controllers.line = Chart.DatasetController.extend({

		datasetElementType: Chart.elements.Line,

		dataElementType: Chart.elements.Point,

		addElementAndReset: function(index) {
			var me = this;
			var options = me.chart.options;

			Chart.DatasetController.prototype.addElementAndReset.call(me, index);

			// Make sure bezier control points are updated
			if (options.showLines && options.elements.line.tension !== 0) {
				me.updateBezierControlPoints();
			}
		},

		update: function update(reset) {
			var me = this;
			var meta = me.getMeta();
			var line = meta.dataset;
			var points = meta.data || [];
			var options = me.chart.options;
			var lineElementOptions = options.elements.line;
			var scale = me.getScaleForId(meta.yAxisID);
			var i, ilen, dataset, custom;

			// Update Line
			if (options.showLines) {
				dataset = me.getDataset();
				custom = line.custom || {};

				// Compatibility: If the properties are defined with only the old name, use those values
				if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) {
					dataset.lineTension = dataset.tension;
				}

				// Utility
				line._scale = scale;
				line._datasetIndex = me.index;
				// Data
				line._children = points;
				// Model
				line._model = {
					// Appearance
					tension: custom.tension ? custom.tension : helpers.getValueOrDefault(dataset.lineTension, lineElementOptions.tension),
					backgroundColor: custom.backgroundColor ? custom.backgroundColor : (dataset.backgroundColor || lineElementOptions.backgroundColor),
					borderWidth: custom.borderWidth ? custom.borderWidth : (dataset.borderWidth || lineElementOptions.borderWidth),
					borderColor: custom.borderColor ? custom.borderColor : (dataset.borderColor || lineElementOptions.borderColor),
					borderCapStyle: custom.borderCapStyle ? custom.borderCapStyle : (dataset.borderCapStyle || lineElementOptions.borderCapStyle),
					borderDash: custom.borderDash ? custom.borderDash : (dataset.borderDash || lineElementOptions.borderDash),
					borderDashOffset: custom.borderDashOffset ? custom.borderDashOffset : (dataset.borderDashOffset || lineElementOptions.borderDashOffset),
					borderJoinStyle: custom.borderJoinStyle ? custom.borderJoinStyle : (dataset.borderJoinStyle || lineElementOptions.borderJoinStyle),
					fill: custom.fill ? custom.fill : (dataset.fill !== undefined ? dataset.fill : lineElementOptions.fill),
					// Scale
					scaleTop: scale.top,
					scaleBottom: scale.bottom,
					scaleZero: scale.getBasePixel()
				};

				line.pivot();
			}

			// Update Points
			for (i=0, ilen=points.length; i<ilen; ++i) {
				me.updateElement(points[i], i, reset);
			}

			if (options.showLines && lineElementOptions.tension !== 0) {
				me.updateBezierControlPoints();
			}
		},

		getPointBackgroundColor: function(point, index) {
			var backgroundColor = this.chart.options.elements.point.backgroundColor;
			var dataset = this.getDataset();
			var custom = point.custom || {};

			if (custom.backgroundColor) {
				backgroundColor = custom.backgroundColor;
			} else if (dataset.pointBackgroundColor) {
				backgroundColor = helpers.getValueAtIndexOrDefault(dataset.pointBackgroundColor, index, backgroundColor);
			} else if (dataset.backgroundColor) {
				backgroundColor = dataset.backgroundColor;
			}

			return backgroundColor;
		},

		getPointBorderColor: function(point, index) {
			var borderColor = this.chart.options.elements.point.borderColor;
			var dataset = this.getDataset();
			var custom = point.custom || {};

			if (custom.borderColor) {
				borderColor = custom.borderColor;
			} else if (dataset.pointBorderColor) {
				borderColor = helpers.getValueAtIndexOrDefault(dataset.pointBorderColor, index, borderColor);
			} else if (dataset.borderColor) {
				borderColor = dataset.borderColor;
			}

			return borderColor;
		},

		getPointBorderWidth: function(point, index) {
			var borderWidth = this.chart.options.elements.point.borderWidth;
			var dataset = this.getDataset();
			var custom = point.custom || {};

			if (custom.borderWidth) {
				borderWidth = custom.borderWidth;
			} else if (dataset.pointBorderWidth) {
				borderWidth = helpers.getValueAtIndexOrDefault(dataset.pointBorderWidth, index, borderWidth);
			} else if (dataset.borderWidth) {
				borderWidth = dataset.borderWidth;
			}

			return borderWidth;
		},

		updateElement: function(point, index, reset) {
			var me = this;
			var meta = me.getMeta();
			var custom = point.custom || {};
			var dataset = me.getDataset();
			var datasetIndex = me.index;
			var value = dataset.data[index];
			var yScale = me.getScaleForId(meta.yAxisID);
			var xScale = me.getScaleForId(meta.xAxisID);
			var pointOptions = me.chart.options.elements.point;
			var x, y;

			// Compatibility: If the properties are defined with only the old name, use those values
			if ((dataset.radius !== undefined) && (dataset.pointRadius === undefined)) {
				dataset.pointRadius = dataset.radius;
			}
			if ((dataset.hitRadius !== undefined) && (dataset.pointHitRadius === undefined)) {
				dataset.pointHitRadius = dataset.hitRadius;
			}

			x = xScale.getPixelForValue(value, index, datasetIndex, me.chart.isCombo);
			y = reset ? yScale.getBasePixel() : me.calculatePointY(value, index, datasetIndex, me.chart.isCombo);

			// Utility
			point._xScale = xScale;
			point._yScale = yScale;
			point._datasetIndex = datasetIndex;
			point._index = index;

			// Desired view properties
			point._model = {
				x: x,
				y: y,
				skip: custom.skip || isNaN(x) || isNaN(y),
				// Appearance
				radius: custom.radius || helpers.getValueAtIndexOrDefault(dataset.pointRadius, index, pointOptions.radius),
				pointStyle: custom.pointStyle || helpers.getValueAtIndexOrDefault(dataset.pointStyle, index, pointOptions.pointStyle),
				backgroundColor: me.getPointBackgroundColor(point, index),
				borderColor: me.getPointBorderColor(point, index),
				borderWidth: me.getPointBorderWidth(point, index),
				tension: meta.dataset._model ? meta.dataset._model.tension : 0,
				// Tooltip
				hitRadius: custom.hitRadius || helpers.getValueAtIndexOrDefault(dataset.pointHitRadius, index, pointOptions.hitRadius)
			};
		},

		calculatePointY: function(value, index, datasetIndex, isCombo) {
			var me = this;
			var chart = me.chart;
			var meta = me.getMeta();
			var yScale = me.getScaleForId(meta.yAxisID);
			var sumPos = 0;
			var sumNeg = 0;
			var i, ds, dsMeta;

			if (yScale.options.stacked) {
				for (i = 0; i < datasetIndex; i++) {
					ds = chart.data.datasets[i];
					dsMeta = chart.getDatasetMeta(i);
					if (dsMeta.type === 'line' && chart.isDatasetVisible(i)) {
						if (ds.data[index] < 0) {
							sumNeg += ds.data[index] || 0;
						} else {
							sumPos += ds.data[index] || 0;
						}
					}
				}

				if (value < 0) {
					return yScale.getPixelForValue(sumNeg + value);
				} else {
					return yScale.getPixelForValue(sumPos + value);
				}
			}

			return yScale.getPixelForValue(value);
		},

		updateBezierControlPoints: function() {
			var meta = this.getMeta();
			var area = this.chart.chartArea;
			var points = meta.data || [];
			var i, ilen, point, model, controlPoints;

			for (i=0, ilen=points.length; i<ilen; ++i) {
				point = points[i];
				model = point._model;
				controlPoints = helpers.splineCurve(
					helpers.previousItem(points, i)._model,
					model,
					helpers.nextItem(points, i)._model,
					meta.dataset._model.tension
				);

				// Prevent the bezier going outside of the bounds of the graph
				model.controlPointPreviousX = Math.max(Math.min(controlPoints.previous.x, area.right), area.left);
				model.controlPointPreviousY = Math.max(Math.min(controlPoints.previous.y, area.bottom), area.top);
				model.controlPointNextX = Math.max(Math.min(controlPoints.next.x, area.right), area.left);
				model.controlPointNextY = Math.max(Math.min(controlPoints.next.y, area.bottom), area.top);

				// Now pivot the point for animation
				point.pivot();
			}
		},

		draw: function(ease) {
			var meta = this.getMeta();
			var points = meta.data || [];
			var easingDecimal = ease || 1;
			var i, ilen;

			// Transition Point Locations
			for (i=0, ilen=points.length; i<ilen; ++i) {
				points[i].transition(easingDecimal);
			}

			// Transition and Draw the line
			if (this.chart.options.showLines) {
				meta.dataset.transition(easingDecimal).draw();
			}

			// Draw the points
			for (i=0, ilen=points.length; i<ilen; ++i) {
				points[i].draw();
			}
		},

		setHoverStyle: function(point) {
			// Point
			var dataset = this.chart.data.datasets[point._datasetIndex];
			var index = point._index;
			var custom = point.custom || {};
			var model = point._model;

			model.radius = custom.hoverRadius || helpers.getValueAtIndexOrDefault(dataset.pointHoverRadius, index, this.chart.options.elements.point.hoverRadius);
			model.backgroundColor = custom.hoverBackgroundColor || helpers.getValueAtIndexOrDefault(dataset.pointHoverBackgroundColor, index, helpers.getHoverColor(model.backgroundColor));
			model.borderColor = custom.hoverBorderColor || helpers.getValueAtIndexOrDefault(dataset.pointHoverBorderColor, index, helpers.getHoverColor(model.borderColor));
			model.borderWidth = custom.hoverBorderWidth || helpers.getValueAtIndexOrDefault(dataset.pointHoverBorderWidth, index, model.borderWidth);
		},

		removeHoverStyle: function(point) {
			var me = this;
			var dataset = me.chart.data.datasets[point._datasetIndex];
			var index = point._index;
			var custom = point.custom || {};
			var model = point._model;

			// Compatibility: If the properties are defined with only the old name, use those values
			if ((dataset.radius !== undefined) && (dataset.pointRadius === undefined)) {
				dataset.pointRadius = dataset.radius;
			}

			model.radius = custom.radius || helpers.getValueAtIndexOrDefault(dataset.pointRadius, index, me.chart.options.elements.point.radius);
			model.backgroundColor = me.getPointBackgroundColor(point, index);
			model.borderColor = me.getPointBorderColor(point, index);
			model.borderWidth = me.getPointBorderWidth(point, index);
		}
	});
};
<commit_msg>Line points need always need to pivot after regardless of whether or not bezier points are updated. Bezier points should only be updated if the line tension is not 0.<commit_after>"use strict";

module.exports = function(Chart) {

	var helpers = Chart.helpers;

	Chart.defaults.line = {
		showLines: true,

		hover: {
			mode: "label"
		},

		scales: {
			xAxes: [{
				type: "category",
				id: 'x-axis-0'
			}],
			yAxes: [{
				type: "linear",
				id: 'y-axis-0'
			}]
		}
	};

	Chart.controllers.line = Chart.DatasetController.extend({

		datasetElementType: Chart.elements.Line,

		dataElementType: Chart.elements.Point,

		addElementAndReset: function(index) {
			var me = this;
			var options = me.chart.options;
			var meta = me.getMeta();

			Chart.DatasetController.prototype.addElementAndReset.call(me, index);

			// Make sure bezier control points are updated
			if (options.showLines && meta.dataset._model.tension !== 0) {
				me.updateBezierControlPoints();
			}
		},

		update: function update(reset) {
			var me = this;
			var meta = me.getMeta();
			var line = meta.dataset;
			var points = meta.data || [];
			var options = me.chart.options;
			var lineElementOptions = options.elements.line;
			var scale = me.getScaleForId(meta.yAxisID);
			var i, ilen, dataset, custom;

			// Update Line
			if (options.showLines) {
				dataset = me.getDataset();
				custom = line.custom || {};

				// Compatibility: If the properties are defined with only the old name, use those values
				if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) {
					dataset.lineTension = dataset.tension;
				}

				// Utility
				line._scale = scale;
				line._datasetIndex = me.index;
				// Data
				line._children = points;
				// Model
				line._model = {
					// Appearance
					tension: custom.tension ? custom.tension : helpers.getValueOrDefault(dataset.lineTension, lineElementOptions.tension),
					backgroundColor: custom.backgroundColor ? custom.backgroundColor : (dataset.backgroundColor || lineElementOptions.backgroundColor),
					borderWidth: custom.borderWidth ? custom.borderWidth : (dataset.borderWidth || lineElementOptions.borderWidth),
					borderColor: custom.borderColor ? custom.borderColor : (dataset.borderColor || lineElementOptions.borderColor),
					borderCapStyle: custom.borderCapStyle ? custom.borderCapStyle : (dataset.borderCapStyle || lineElementOptions.borderCapStyle),
					borderDash: custom.borderDash ? custom.borderDash : (dataset.borderDash || lineElementOptions.borderDash),
					borderDashOffset: custom.borderDashOffset ? custom.borderDashOffset : (dataset.borderDashOffset || lineElementOptions.borderDashOffset),
					borderJoinStyle: custom.borderJoinStyle ? custom.borderJoinStyle : (dataset.borderJoinStyle || lineElementOptions.borderJoinStyle),
					fill: custom.fill ? custom.fill : (dataset.fill !== undefined ? dataset.fill : lineElementOptions.fill),
					// Scale
					scaleTop: scale.top,
					scaleBottom: scale.bottom,
					scaleZero: scale.getBasePixel()
				};

				line.pivot();
			}

			// Update Points
			for (i=0, ilen=points.length; i<ilen; ++i) {
				me.updateElement(points[i], i, reset);
			}

			if (options.showLines && line._model.tension !== 0) {
				me.updateBezierControlPoints();
			}

			// Now pivot the point for animation
			for (i=0, ilen=points.length; i<ilen; ++i) {
				points[i].pivot();
			}
		},

		getPointBackgroundColor: function(point, index) {
			var backgroundColor = this.chart.options.elements.point.backgroundColor;
			var dataset = this.getDataset();
			var custom = point.custom || {};

			if (custom.backgroundColor) {
				backgroundColor = custom.backgroundColor;
			} else if (dataset.pointBackgroundColor) {
				backgroundColor = helpers.getValueAtIndexOrDefault(dataset.pointBackgroundColor, index, backgroundColor);
			} else if (dataset.backgroundColor) {
				backgroundColor = dataset.backgroundColor;
			}

			return backgroundColor;
		},

		getPointBorderColor: function(point, index) {
			var borderColor = this.chart.options.elements.point.borderColor;
			var dataset = this.getDataset();
			var custom = point.custom || {};

			if (custom.borderColor) {
				borderColor = custom.borderColor;
			} else if (dataset.pointBorderColor) {
				borderColor = helpers.getValueAtIndexOrDefault(dataset.pointBorderColor, index, borderColor);
			} else if (dataset.borderColor) {
				borderColor = dataset.borderColor;
			}

			return borderColor;
		},

		getPointBorderWidth: function(point, index) {
			var borderWidth = this.chart.options.elements.point.borderWidth;
			var dataset = this.getDataset();
			var custom = point.custom || {};

			if (custom.borderWidth) {
				borderWidth = custom.borderWidth;
			} else if (dataset.pointBorderWidth) {
				borderWidth = helpers.getValueAtIndexOrDefault(dataset.pointBorderWidth, index, borderWidth);
			} else if (dataset.borderWidth) {
				borderWidth = dataset.borderWidth;
			}

			return borderWidth;
		},

		updateElement: function(point, index, reset) {
			var me = this;
			var meta = me.getMeta();
			var custom = point.custom || {};
			var dataset = me.getDataset();
			var datasetIndex = me.index;
			var value = dataset.data[index];
			var yScale = me.getScaleForId(meta.yAxisID);
			var xScale = me.getScaleForId(meta.xAxisID);
			var pointOptions = me.chart.options.elements.point;
			var x, y;

			// Compatibility: If the properties are defined with only the old name, use those values
			if ((dataset.radius !== undefined) && (dataset.pointRadius === undefined)) {
				dataset.pointRadius = dataset.radius;
			}
			if ((dataset.hitRadius !== undefined) && (dataset.pointHitRadius === undefined)) {
				dataset.pointHitRadius = dataset.hitRadius;
			}

			x = xScale.getPixelForValue(value, index, datasetIndex, me.chart.isCombo);
			y = reset ? yScale.getBasePixel() : me.calculatePointY(value, index, datasetIndex, me.chart.isCombo);

			// Utility
			point._xScale = xScale;
			point._yScale = yScale;
			point._datasetIndex = datasetIndex;
			point._index = index;

			// Desired view properties
			point._model = {
				x: x,
				y: y,
				skip: custom.skip || isNaN(x) || isNaN(y),
				// Appearance
				radius: custom.radius || helpers.getValueAtIndexOrDefault(dataset.pointRadius, index, pointOptions.radius),
				pointStyle: custom.pointStyle || helpers.getValueAtIndexOrDefault(dataset.pointStyle, index, pointOptions.pointStyle),
				backgroundColor: me.getPointBackgroundColor(point, index),
				borderColor: me.getPointBorderColor(point, index),
				borderWidth: me.getPointBorderWidth(point, index),
				tension: meta.dataset._model ? meta.dataset._model.tension : 0,
				// Tooltip
				hitRadius: custom.hitRadius || helpers.getValueAtIndexOrDefault(dataset.pointHitRadius, index, pointOptions.hitRadius)
			};
		},

		calculatePointY: function(value, index, datasetIndex, isCombo) {
			var me = this;
			var chart = me.chart;
			var meta = me.getMeta();
			var yScale = me.getScaleForId(meta.yAxisID);
			var sumPos = 0;
			var sumNeg = 0;
			var i, ds, dsMeta;

			if (yScale.options.stacked) {
				for (i = 0; i < datasetIndex; i++) {
					ds = chart.data.datasets[i];
					dsMeta = chart.getDatasetMeta(i);
					if (dsMeta.type === 'line' && chart.isDatasetVisible(i)) {
						if (ds.data[index] < 0) {
							sumNeg += ds.data[index] || 0;
						} else {
							sumPos += ds.data[index] || 0;
						}
					}
				}

				if (value < 0) {
					return yScale.getPixelForValue(sumNeg + value);
				} else {
					return yScale.getPixelForValue(sumPos + value);
				}
			}

			return yScale.getPixelForValue(value);
		},

		updateBezierControlPoints: function() {
			var meta = this.getMeta();
			var area = this.chart.chartArea;
			var points = meta.data || [];
			var i, ilen, point, model, controlPoints;

			for (i=0, ilen=points.length; i<ilen; ++i) {
				point = points[i];
				model = point._model;
				controlPoints = helpers.splineCurve(
					helpers.previousItem(points, i)._model,
					model,
					helpers.nextItem(points, i)._model,
					meta.dataset._model.tension
				);

				// Prevent the bezier going outside of the bounds of the graph
				model.controlPointPreviousX = Math.max(Math.min(controlPoints.previous.x, area.right), area.left);
				model.controlPointPreviousY = Math.max(Math.min(controlPoints.previous.y, area.bottom), area.top);
				model.controlPointNextX = Math.max(Math.min(controlPoints.next.x, area.right), area.left);
				model.controlPointNextY = Math.max(Math.min(controlPoints.next.y, area.bottom), area.top);
			}
		},

		draw: function(ease) {
			var meta = this.getMeta();
			var points = meta.data || [];
			var easingDecimal = ease || 1;
			var i, ilen;

			// Transition Point Locations
			for (i=0, ilen=points.length; i<ilen; ++i) {
				points[i].transition(easingDecimal);
			}

			// Transition and Draw the line
			if (this.chart.options.showLines) {
				meta.dataset.transition(easingDecimal).draw();
			}

			// Draw the points
			for (i=0, ilen=points.length; i<ilen; ++i) {
				points[i].draw();
			}
		},

		setHoverStyle: function(point) {
			// Point
			var dataset = this.chart.data.datasets[point._datasetIndex];
			var index = point._index;
			var custom = point.custom || {};
			var model = point._model;

			model.radius = custom.hoverRadius || helpers.getValueAtIndexOrDefault(dataset.pointHoverRadius, index, this.chart.options.elements.point.hoverRadius);
			model.backgroundColor = custom.hoverBackgroundColor || helpers.getValueAtIndexOrDefault(dataset.pointHoverBackgroundColor, index, helpers.getHoverColor(model.backgroundColor));
			model.borderColor = custom.hoverBorderColor || helpers.getValueAtIndexOrDefault(dataset.pointHoverBorderColor, index, helpers.getHoverColor(model.borderColor));
			model.borderWidth = custom.hoverBorderWidth || helpers.getValueAtIndexOrDefault(dataset.pointHoverBorderWidth, index, model.borderWidth);
		},

		removeHoverStyle: function(point) {
			var me = this;
			var dataset = me.chart.data.datasets[point._datasetIndex];
			var index = point._index;
			var custom = point.custom || {};
			var model = point._model;

			// Compatibility: If the properties are defined with only the old name, use those values
			if ((dataset.radius !== undefined) && (dataset.pointRadius === undefined)) {
				dataset.pointRadius = dataset.radius;
			}

			model.radius = custom.radius || helpers.getValueAtIndexOrDefault(dataset.pointRadius, index, me.chart.options.elements.point.radius);
			model.backgroundColor = me.getPointBackgroundColor(point, index);
			model.borderColor = me.getPointBorderColor(point, index);
			model.borderWidth = me.getPointBorderWidth(point, index);
		}
	});
};
<|endoftext|>


<commit_before>// NOTE: New functions should go in utils.js, old ones should slowly be ported over.
module.exports = {
    init: function init() {
        randcolor = function () {
            var nums = 5;
            var str = '';
            while (nums >= 0) {
                str += sys.rand(0, 16).toString(16);
                nums -= 1;
            }
            return "";
        };

        colormodemessage = function (message) {
            var msg = "";
            var len, i;
            for (i = 0, len = message.length; i < len; i += 1) {
                msg += randcolor() + message[i] + "";
            }

            return msg;
        };

        lolmessage = function (message) {
            var msg = "";
            var len, i;
            for (i = 0, len = message.length; i < len; i += 1) {
                msg += "lol";
            }

            return msg;
        };

        pewpewpewmessage = function (message) {
            var sendStr;
            var ids = sys.playerIds(),
                playerLen = ids.length,
                randPlayer = ids[sys.rand(0, playerLen)];

            while (!sys.loggedIn(randPlayer)) {
                randPlayer = ids[sys.rand(0, playerLen)];
            }

            var name = sys.name(randPlayer),
                auth = sys.auth(randPlayer);

            message = Utils.escapeHtml(message);

            sendStr = "<timestamp/>" + Utils.escapeHtml(name) + ": " + (hasEmotesToggled(randPlayer) ? emoteFormat(message) : Utils.escapeHtml(message));
            if (sys.auth(randPlayer) > 0 && sys.auth(randPlayer) < 4) {
                sendStr = "<timestamp/>+" + Utils.escapeHtml(name) + ": " + (hasEmotesToggled(randPlayer) ? emoteFormat(message) : message);
            }

            if (nightclub) {
                sendStr = Utils.nightclub.rainbowify("(" + Utils.escapeHtml(name) + "): " + message);
            }

            return sendStr;
        };

        // Global var name: reg val name
        var regVals = {
            "MegaUsers": "Megausers",
            "FloodIgnore": "FloodIgnore",
            "Channeltopics": "Channeltopics",
            "Mutes": "Mutes",
            "Rangebans": "Rangebans",
            "Kickmsgs": "Kickmsgs",
            "Banmsgs": "Banmsgs",
            "Welmsgs": "Welmsgs",
            "Emotetoggles": "Emotetoggles",
            "Emoteperms": "Emoteperms",
            "Feedmons": "Feedmon",
            "League": "League"
        };

        for (var i in regVals) {
            Reg.init(regVals[i], {});

            try {
                global[i] = Reg.get(regVals[i]);
            } catch (e) {
                global[i] = {};
            }
        }

        hasEmotePerms = function (name) {
            var id = sys.id(name),
                user = SESSION.users(id),
                hasEmotes,
                ip,
                aliases,
                len,
                i;

            if (id && user && user.originalName) {
                name = user.originalName;
            }

            ip = sys.dbIp(name);
            hasEmotes = sys.maxAuth(ip) > 0 || Emoteperms.hasOwnProperty(name.toLowerCase());

            if (!hasEmotes) {
                aliases = sys.aliases(ip);

                if (!aliases || (len = aliases.length) === 1) {
                    return false;
                }

                for (i = 0; i < len; i += 1) {
                    if (Emoteperms.hasOwnProperty(aliases[i].toLowerCase())) {
                        return true;
                    }
                }
            }

            return hasEmotes;
        };

        hasEmotesToggled = function (src) {
            var name = SESSION.users(src).originalName.toLowerCase();
            return (Utils.mod.hasBasicPermissions(src) || hasEmotePerms(name)) && Emotetoggles.hasOwnProperty(name);
        };

        var globalVars = {
            border: "<timestamp/>«««««««««««««««««««««««««»»»»»»»»»»»»»»»»»»»»»»»»»",
            tourmode: 0,
            spinTypes: [], // can contain: items, emotes, pokemons
            muteall: false,
            supersilence: false,
            rouletteon: false,
            htmlchat: false,
            lolmode: false,
            spacemode: false,
            capsmode: false,
            reversemode: false,
            scramblemode: false,
            colormode: false,
            pewpewpew: false,
            nightclub: false,
            warnings: {},
            teamSpammers: {},
            reconnectTrolls: {},
            uniqueVisitors: {
                ips: {},
                count: 0,
                total: 0
            },
            Poll: {
                active: false,
                subject: '',
                by: '',
                options: [],
                votes: {}
            }
        };

        for (i in globalVars) {
            if (typeof global[i] === "undefined") {
                global[i] = globalVars[i];
            }
        }

        Reg.init('MOTD', '');
        Reg.init('maxPlayersOnline', 0);
        Reg.init('servername', "Meteor Falls");
        Reg.init("Leaguemanager", "HHT");

        if (Reg.get("Champ") === undefined) {
            var LeagueArray = ["Gym1", "Gym2", "Gym3", "Gym4", "Gym5", "Gym6", "Gym7", "Gym8", "Elite1", "Elite2", "Elite3", "Elite4", "Champ"];
            for (x in LeagueArray) {
                Reg.init(LeagueArray[x], "");
            }
        }

        Leaguemanager = Reg.get("Leaguemanager");

        var makeChan = function (cname) {
            sys.createChannel(cname);
            return sys.channelId(cname);
        };

        staffchannel = makeChan("Auth Party");
        testchan = makeChan("Ground Zero");
        watch = makeChan("Watch");

        RegExp.quote = function (str) {
            return str.replace(/([.?*+\^$\[\]\\(){}|\-])/g, "\\$1");
        };

        nthNumber = function (num) {
            var nthNum = {
                0: "th",
                1: "st",
                2: "nd",
                3: "rd"
            };

            return num + (nthNum[num] || "th");
        };

        ChannelLink = function (channel) {
            if (typeof channel === "number") {
                channel = sys.channel(channel);
            }

            return "#" + channel + "";
        };

        addChannelLinks = function (line) {
            var index = line.indexOf('#');
            if (index === -1) {
                return line;
            }

            var str = '', fullChanName, chanName, chr, lastIndex = 0, pos, i;
            var channelNames = Utils.channelNames(true); // lower case names

            while (index !== -1) {
                str += line.substring(lastIndex, index);
                lastIndex = index + 1; // Skip over the '#'

                fullChanName = '';
                chanName = '';

                for (i = 0, pos = lastIndex; i < 20 && (chr = line[pos]); i += 1, pos += 1) {
                    fullChanName += chr;
                    if (channelNames.indexOf(fullChanName.toLowerCase()) !== -1) {
                        chanName = fullChanName;
                    }
                }

                if (chanName) {
                    str += "#" + chanName + "";
                    lastIndex += chanName.length;
                } else {
                    str += '#';
                }

                index = line.indexOf('#', lastIndex);
            }

            if (lastIndex < line.length) {
                str += line.substr(lastIndex);
            }

            return str;
        };

        /*function formatLinks(message) {
            return message.replace(/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?\^=%&:\/~\+#]*[\w\-\@?\^=%&\/~\+#])?/gi, '$1');
        }*/
    }
};

module.reload = function reloadInit() {
    module.exports.init();
    return true;
};
<commit_msg>Remove initiation of old League Reg vars<commit_after>// NOTE: New functions should go in utils.js, old ones should slowly be ported over.
module.exports = {
    init: function init() {
        randcolor = function () {
            var nums = 5;
            var str = '';
            while (nums >= 0) {
                str += sys.rand(0, 16).toString(16);
                nums -= 1;
            }
            return "";
        };

        colormodemessage = function (message) {
            var msg = "";
            var len, i;
            for (i = 0, len = message.length; i < len; i += 1) {
                msg += randcolor() + message[i] + "";
            }

            return msg;
        };

        lolmessage = function (message) {
            var msg = "";
            var len, i;
            for (i = 0, len = message.length; i < len; i += 1) {
                msg += "lol";
            }

            return msg;
        };

        pewpewpewmessage = function (message) {
            var sendStr;
            var ids = sys.playerIds(),
                playerLen = ids.length,
                randPlayer = ids[sys.rand(0, playerLen)];

            while (!sys.loggedIn(randPlayer)) {
                randPlayer = ids[sys.rand(0, playerLen)];
            }

            var name = sys.name(randPlayer),
                auth = sys.auth(randPlayer);

            message = Utils.escapeHtml(message);

            sendStr = "<timestamp/>" + Utils.escapeHtml(name) + ": " + (hasEmotesToggled(randPlayer) ? emoteFormat(message) : Utils.escapeHtml(message));
            if (sys.auth(randPlayer) > 0 && sys.auth(randPlayer) < 4) {
                sendStr = "<timestamp/>+" + Utils.escapeHtml(name) + ": " + (hasEmotesToggled(randPlayer) ? emoteFormat(message) : message);
            }

            if (nightclub) {
                sendStr = Utils.nightclub.rainbowify("(" + Utils.escapeHtml(name) + "): " + message);
            }

            return sendStr;
        };

        // Global var name: reg val name
        var regVals = {
            "MegaUsers": "Megausers",
            "FloodIgnore": "FloodIgnore",
            "Channeltopics": "Channeltopics",
            "Mutes": "Mutes",
            "Rangebans": "Rangebans",
            "Kickmsgs": "Kickmsgs",
            "Banmsgs": "Banmsgs",
            "Welmsgs": "Welmsgs",
            "Emotetoggles": "Emotetoggles",
            "Emoteperms": "Emoteperms",
            "Feedmons": "Feedmon",
            "League": "League"
        };

        for (var i in regVals) {
            Reg.init(regVals[i], {});

            try {
                global[i] = Reg.get(regVals[i]);
            } catch (e) {
                global[i] = {};
            }
        }

        hasEmotePerms = function (name) {
            var id = sys.id(name),
                user = SESSION.users(id),
                hasEmotes,
                ip,
                aliases,
                len,
                i;

            if (id && user && user.originalName) {
                name = user.originalName;
            }

            ip = sys.dbIp(name);
            hasEmotes = sys.maxAuth(ip) > 0 || Emoteperms.hasOwnProperty(name.toLowerCase());

            if (!hasEmotes) {
                aliases = sys.aliases(ip);

                if (!aliases || (len = aliases.length) === 1) {
                    return false;
                }

                for (i = 0; i < len; i += 1) {
                    if (Emoteperms.hasOwnProperty(aliases[i].toLowerCase())) {
                        return true;
                    }
                }
            }

            return hasEmotes;
        };

        hasEmotesToggled = function (src) {
            var name = SESSION.users(src).originalName.toLowerCase();
            return (Utils.mod.hasBasicPermissions(src) || hasEmotePerms(name)) && Emotetoggles.hasOwnProperty(name);
        };

        var globalVars = {
            border: "<timestamp/>«««««««««««««««««««««««««»»»»»»»»»»»»»»»»»»»»»»»»»",
            tourmode: 0,
            spinTypes: [], // can contain: items, emotes, pokemons
            muteall: false,
            supersilence: false,
            rouletteon: false,
            htmlchat: false,
            lolmode: false,
            spacemode: false,
            capsmode: false,
            reversemode: false,
            scramblemode: false,
            colormode: false,
            pewpewpew: false,
            nightclub: false,
            warnings: {},
            teamSpammers: {},
            reconnectTrolls: {},
            uniqueVisitors: {
                ips: {},
                count: 0,
                total: 0
            },
            Poll: {
                active: false,
                subject: '',
                by: '',
                options: [],
                votes: {}
            }
        };

        for (i in globalVars) {
            if (typeof global[i] === "undefined") {
                global[i] = globalVars[i];
            }
        }

        Reg.init('MOTD', '');
        Reg.init('maxPlayersOnline', 0);
        Reg.init('servername', "Meteor Falls");
        Reg.init("Leaguemanager", "HHT");

        Leaguemanager = Reg.get("Leaguemanager");

        var makeChan = function (cname) {
            sys.createChannel(cname);
            return sys.channelId(cname);
        };

        staffchannel = makeChan("Auth Party");
        testchan = makeChan("Ground Zero");
        watch = makeChan("Watch");

        RegExp.quote = function (str) {
            return str.replace(/([.?*+\^$\[\]\\(){}|\-])/g, "\\$1");
        };

        nthNumber = function (num) {
            var nthNum = {
                0: "th",
                1: "st",
                2: "nd",
                3: "rd"
            };

            return num + (nthNum[num] || "th");
        };

        ChannelLink = function (channel) {
            if (typeof channel === "number") {
                channel = sys.channel(channel);
            }

            return "#" + channel + "";
        };

        addChannelLinks = function (line) {
            var index = line.indexOf('#');
            if (index === -1) {
                return line;
            }

            var str = '', fullChanName, chanName, chr, lastIndex = 0, pos, i;
            var channelNames = Utils.channelNames(true); // lower case names

            while (index !== -1) {
                str += line.substring(lastIndex, index);
                lastIndex = index + 1; // Skip over the '#'

                fullChanName = '';
                chanName = '';

                for (i = 0, pos = lastIndex; i < 20 && (chr = line[pos]); i += 1, pos += 1) {
                    fullChanName += chr;
                    if (channelNames.indexOf(fullChanName.toLowerCase()) !== -1) {
                        chanName = fullChanName;
                    }
                }

                if (chanName) {
                    str += "#" + chanName + "";
                    lastIndex += chanName.length;
                } else {
                    str += '#';
                }

                index = line.indexOf('#', lastIndex);
            }

            if (lastIndex < line.length) {
                str += line.substr(lastIndex);
            }

            return str;
        };

        /*function formatLinks(message) {
            return message.replace(/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?\^=%&:\/~\+#]*[\w\-\@?\^=%&\/~\+#])?/gi, '$1');
        }*/
    }
};

module.reload = function reloadInit() {
    module.exports.init();
    return true;
};
<|endoftext|>