<commit_before>var SoundWave = function(canvas, audioCtx) {
  // Set the Drawing and Audio context for the object
  this.canvas = canvas;
  this.canvas.width = window.innerWidth;
  this.audioCtx = audioCtx

  // Register the function for drawing a sound wave with the oCanvas object
  this.canvas.display.register("soundWave", {
    shapeType: "soundWave",
    isVisible: 1
  }, this.drawSoundwave);

  // Create the sound wave visual object
  this.soundWaveObj = this.canvas.display.soundWave({
    ctrlLines: [],
    stroke: "1px #000",
    isVisible: 1
  });

  // Add it to the canvas
  this.canvas.addChild(this.soundWaveObj);
};

// This method is private and just sets up the first and last control lines
SoundWave.prototype.addFirstAndLastCtrlLines = function(mouseX, mouseY) {
  // create the first and last control lines based on the position of the mouse
    this.soundWaveObj.ctrlLines[this.soundWaveObj.ctrlLines.length] = new LineWithMidpoint(this.canvas);
    this.soundWaveObj.ctrlLines[this.soundWaveObj.ctrlLines.length - 1].createPoint({
      x: -mouseX,
      y: this.canvas.height - mouseY
    });
    this.soundWaveObj.ctrlLines[this.soundWaveObj.ctrlLines.length - 1].createPoint({
      x: mouseX,
      y: mouseY
    });
    this.soundWaveObj.ctrlLines[this.soundWaveObj.ctrlLines.length] = new LineWithMidpoint(this.canvas);
    this.soundWaveObj.ctrlLines[this.soundWaveObj.ctrlLines.length - 1].createPoint({
      x: this.canvas.width - mouseX,
      y: mouseY
    });
    this.soundWaveObj.ctrlLines[this.soundWaveObj.ctrlLines.length - 1].createPoint({
      x: this.canvas.width + mouseX,
      y: this.canvas.height - mouseY
    });
};

SoundWave.prototype.addCtrlLine = function(mouseX, mouseY) {
  // if control line array is empty create the first and last control lines
  if (this.soundWaveObj.ctrlLines.length == 0) {
    this.addFirstAndLastCtrlLines(mouseX, mouseY);
  // if there are at least two control lines and the second last control line (i.e. the user's last control line)
  // is full at the time of the click then move the ending control line forward and put a new control line in its place
  } else if (this.soundWaveObj.ctrlLines[this.soundWaveObj.ctrlLines.length - 2].isFull()) {
    var curCtrlLineLength = this.soundWaveObj.ctrlLines.length - 1;
    this.soundWaveObj.ctrlLines[curCtrlLineLength + 1] = this.soundWaveObj.ctrlLines[curCtrlLineLength];
    this.soundWaveObj.ctrlLines[curCtrlLineLength] = new LineWithMidpoint(this.canvas);
    this.soundWaveObj.ctrlLines[curCtrlLineLength].createPoint({
      x: mouseX,
      y: mouseY
    });
  // if the user's last control line is not full then add a point to it
  } else {
    this.soundWaveObj.ctrlLines[this.soundWaveObj.ctrlLines.length - 2].createPoint({
      x: mouseX,
      y: mouseY
    });
  }
};

SoundWave.prototype.toggleVisibleCtrlPoints = function() {
  if (this.soundWaveObj.isVisible == 0) {
    this.soundWaveObj.isVisible = 1;
    this.canvas.redraw();
  } else {
    this.soundWaveObj.isVisible = 0;
    this.canvas.redraw();
  }

};

SoundWave.prototype.returnSoundCtrlLines = function(frequency) {
  var sndCtrlLineArray = [];

  for (i = 0; i < this.soundWaveObj.ctrlLines.length; i++) {
    sndCtrlLineArray[sndCtrlLineArray.length] = this.soundWaveObj.ctrlLines[i].returnSoundLine(frequency);
  }

  return bezierCurvePath(sndCtrlLineArray, frequency, frequency, 0);

};

SoundWave.prototype.reset = function() {
  this.canvas.children = [];
  this.canvas.clear();
  this.soundWaveObj.ctrlPoints = [];
};

SoundWave.prototype.playSoundwave = function(frequency, duration) {
  var wave = this.returnSoundCtrlLines(frequency);
  var channels = 2; // Make it a stereo sound
  var frameCount = this.audioCtx.sampleRate * duration;
  var myArrayBuffer = this.audioCtx.createBuffer(channels, frameCount, this.audioCtx.sampleRate); // Create an empty duration seconds of stereo buffer at the sample rate of the AudioContext

  for (var channel = 0; channel < channels; channel++) { // Fill the buffer with my invented sound
    var nowBuffering = myArrayBuffer.getChannelData(channel); // This gives us the actual array that contains the data
    for (var j = 0; j < Math.floor(frameCount / wave.length); j++) { // loop over the entire frame count
      for (var i = 0; i < wave.length; i++) {
        nowBuffering[(j * wave.length) + i] = wave[i].y;
      }
    }
  }

  var source = this.audioCtx.createBufferSource(); // Get an AudioBufferSourceNode to play the AudioBuffer
  source.buffer = myArrayBuffer; // set the buffer in the AudioBufferSourceNode
  source.connect(this.audioCtx.destination); // connect the AudioBufferSourceNode to the destination so we can hear the sound
  source.start(); // start the source playing
};

SoundWave.prototype.drawSoundwave = function(canvas) {
  var WHITE = "#FFF";
  var BLACK = "#000";
  var NO = 0;
  var YES = 1;
  this.strokeColor = BLACK;
  canvas.strokeStyle = this.strokeColor; // Set the canvas color
  canvas.lineWidth = this.strokeWidth;

  // first two control lines with all points or more control lines so long as the second last one has all points
  if ((this.ctrlLines.length == 2 && this.ctrlLines[this.ctrlLines.length - 1].isFull()) || (this.ctrlLines.length > 2 && this.ctrlLines[this.ctrlLines.length - 2].isFull())) {

    // check if we're dragging p2 of the first control line or p1 of the last
    if (this.ctrlLines[0].line.p2.dragging == true) {
      this.ctrlLines[this.ctrlLines.length-1].line.p1.x =  this.ctrlLines[0].line.p1.x + canvas.canvas.width;
      this.ctrlLines[this.ctrlLines.length-1].line.p1.y =  this.ctrlLines[0].line.p1.y;
      this.ctrlLines[this.ctrlLines.length-1].line.p2.x = this.ctrlLines[0].line.p2.x + canvas.canvas.width;
      this.ctrlLines[this.ctrlLines.length-1].line.p2.y = this.ctrlLines[0].line.p2.y;
    }

    canvas.beginPath();
    c = bezierCurvePath(this.ctrlLines, $("#points").val(), canvas.canvas.width, canvas.canvas.height);
    canvas.strokeStyle = BLACK;
    for (t = 0; t < c.length; t++) {
      canvas.fillRect(c[t].x, c[t].y, 1, 1); // Fill a pixel
    }

    canvas.moveTo(this.ctrlLines[this.ctrlLines.length-1].line.p1.x, this.ctrlLines[this.ctrlLines.length-1].line.p1.y);
    canvas.lineTo(this.ctrlLines[this.ctrlLines.length-1].line.p2.x, this.ctrlLines[this.ctrlLines.length-1].line.p2.y);
    canvas.stroke();
    canvas.closePath();
  }

  SoundWave.prototype.loadSoundwave = function(filename) {
    context = this.audioCtx;
    bufferLoader = new BufferLoader(context,['../audio/' + filename,],this.processLoadedSound);
    bufferLoader.load();
  }

  SoundWave.prototype.processLoadedSound = function(bufferList) {
    // Create two sources and play them both together.
    var source1 = context.createBufferSource();
    source1.buffer = bufferList[0];
    source1.connect(context.destination);
    source1.start(0);
  }

};
<commit_msg>minor variable name change<commit_after>var SoundWave = function(canvas, audioCtx) {
  // Set the Drawing and Audio context for the object
  this.canvas = canvas;
  this.canvas.width = window.innerWidth;
  this.audioCtx = audioCtx

  // Register the function for drawing a sound wave with the oCanvas object
  this.canvas.display.register("soundWave", {
    shapeType: "soundWave",
    isVisible: 1
  }, this.drawSoundwave);

  // Create the sound wave visual object
  this.soundWaveObj = this.canvas.display.soundWave({
    ctrlLines: [],
    stroke: "1px #000",
    isVisible: 1
  });

  // Add it to the canvas
  this.canvas.addChild(this.soundWaveObj);
};

// This method is private and just sets up the first and last control lines
SoundWave.prototype.addFirstAndLastCtrlLines = function(mouseX, mouseY) {
  // create the first and last control lines based on the position of the mouse
    this.soundWaveObj.ctrlLines[this.soundWaveObj.ctrlLines.length] = new LineWithMidpoint(this.canvas);
    this.soundWaveObj.ctrlLines[this.soundWaveObj.ctrlLines.length - 1].createPoint({
      x: -mouseX,
      y: this.canvas.height - mouseY
    });
    this.soundWaveObj.ctrlLines[this.soundWaveObj.ctrlLines.length - 1].createPoint({
      x: mouseX,
      y: mouseY
    });
    this.soundWaveObj.ctrlLines[this.soundWaveObj.ctrlLines.length] = new LineWithMidpoint(this.canvas);
    this.soundWaveObj.ctrlLines[this.soundWaveObj.ctrlLines.length - 1].createPoint({
      x: this.canvas.width - mouseX,
      y: mouseY
    });
    this.soundWaveObj.ctrlLines[this.soundWaveObj.ctrlLines.length - 1].createPoint({
      x: this.canvas.width + mouseX,
      y: this.canvas.height - mouseY
    });
};

SoundWave.prototype.addCtrlLine = function(mouseX, mouseY) {
  // if control line array is empty create the first and last control lines
  if (this.soundWaveObj.ctrlLines.length == 0) {
    this.addFirstAndLastCtrlLines(mouseX, mouseY);
  // if there are at least two control lines and the second last control line (i.e. the user's last control line)
  // is full at the time of the click then move the ending control line forward and put a new control line in its place
  } else if (this.soundWaveObj.ctrlLines[this.soundWaveObj.ctrlLines.length - 2].isFull()) {
    var curCtrlLineLength = this.soundWaveObj.ctrlLines.length - 1;
    this.soundWaveObj.ctrlLines[curCtrlLineLength + 1] = this.soundWaveObj.ctrlLines[curCtrlLineLength];
    this.soundWaveObj.ctrlLines[curCtrlLineLength] = new LineWithMidpoint(this.canvas);
    this.soundWaveObj.ctrlLines[curCtrlLineLength].createPoint({
      x: mouseX,
      y: mouseY
    });
  // if the user's last control line is not full then add a point to it
  } else {
    this.soundWaveObj.ctrlLines[this.soundWaveObj.ctrlLines.length - 2].createPoint({
      x: mouseX,
      y: mouseY
    });
  }
};

SoundWave.prototype.toggleVisibleCtrlPoints = function() {
  if (this.soundWaveObj.isVisible == 0) {
    this.soundWaveObj.isVisible = 1;
    this.canvas.redraw();
  } else {
    this.soundWaveObj.isVisible = 0;
    this.canvas.redraw();
  }

};

SoundWave.prototype.returnSoundCtrlLines = function(frequency) {
  var sndCtrlLineArray = [];

  for (i = 0; i < this.soundWaveObj.ctrlLines.length; i++) {
    sndCtrlLineArray[sndCtrlLineArray.length] = this.soundWaveObj.ctrlLines[i].returnSoundLine(frequency);
  }

  return bezierCurvePath(sndCtrlLineArray, frequency, frequency, 0);

};

SoundWave.prototype.reset = function() {
  this.canvas.children = [];
  this.canvas.clear();
  this.soundWaveObj.ctrlPoints = [];
};

SoundWave.prototype.playSoundwave = function(frequency, duration) {
  var wave = this.returnSoundCtrlLines(frequency);
  var channels = 2; // Make it a stereo sound
  var frameCount = this.audioCtx.sampleRate * duration;
  var myArrayBuffer = this.audioCtx.createBuffer(channels, frameCount, this.audioCtx.sampleRate); // Create an empty duration seconds of stereo buffer at the sample rate of the AudioContext

  for (var channel = 0; channel < channels; channel++) { // Fill the buffer with my invented sound
    var nowBuffering = myArrayBuffer.getChannelData(channel); // This gives us the actual array that contains the data
    for (var j = 0; j < Math.floor(frameCount / wave.length); j++) { // loop over the entire frame count
      for (var i = 0; i < wave.length; i++) {
        nowBuffering[(j * wave.length) + i] = wave[i].y;
      }
    }
  }

  var source = this.audioCtx.createBufferSource(); // Get an AudioBufferSourceNode to play the AudioBuffer
  source.buffer = myArrayBuffer; // set the buffer in the AudioBufferSourceNode
  source.connect(this.audioCtx.destination); // connect the AudioBufferSourceNode to the destination so we can hear the sound
  source.start(); // start the source playing
};

SoundWave.prototype.drawSoundwave = function(canvas) {
  var WHITE = "#FFF";
  var BLACK = "#000";
  var NO = 0;
  var YES = 1;
  this.strokeColor = BLACK;
  canvas.strokeStyle = this.strokeColor; // Set the canvas color
  canvas.lineWidth = this.strokeWidth;

  // first two control lines with all points or more control lines so long as the second last one has all points
  if ((this.ctrlLines.length == 2 && this.ctrlLines[this.ctrlLines.length - 1].isFull()) || (this.ctrlLines.length > 2 && this.ctrlLines[this.ctrlLines.length - 2].isFull())) {

    // check if we're dragging p2 of the first control line or p1 of the last
    if (this.ctrlLines[0].line.p2.dragging == true) {
      this.ctrlLines[this.ctrlLines.length-1].line.p1.x =  this.ctrlLines[0].line.p1.x + canvas.canvas.width;
      this.ctrlLines[this.ctrlLines.length-1].line.p1.y =  this.ctrlLines[0].line.p1.y;
      this.ctrlLines[this.ctrlLines.length-1].line.p2.x = this.ctrlLines[0].line.p2.x + canvas.canvas.width;
      this.ctrlLines[this.ctrlLines.length-1].line.p2.y = this.ctrlLines[0].line.p2.y;
    }

    canvas.beginPath();
    c = bezierCurvePath(this.ctrlLines, $("#points").val(), canvas.canvas.width, canvas.canvas.height);
    canvas.strokeStyle = BLACK;
    for (t = 0; t < c.length; t++) {
      canvas.fillRect(c[t].x, c[t].y, 1, 1); // Fill a pixel
    }

    canvas.moveTo(this.ctrlLines[this.ctrlLines.length-1].line.p1.x, this.ctrlLines[this.ctrlLines.length-1].line.p1.y);
    canvas.lineTo(this.ctrlLines[this.ctrlLines.length-1].line.p2.x, this.ctrlLines[this.ctrlLines.length-1].line.p2.y);
    canvas.stroke();
    canvas.closePath();
  }

  SoundWave.prototype.loadSoundwave = function(filename) {
    context = this.audioCtx;
    bufferLoader = new BufferLoader(context,['../audio/' + filename,],this.processLoadedSound);
    bufferLoader.load();
  }

  SoundWave.prototype.processLoadedSound = function(bufferList) {
    // Create two sources and play them both together.
    var source = this.audioCtx.createBufferSource();
    source.buffer = bufferList[0];
    source.connect(context.destination);
    source.start(0);
  }

};
<|endoftext|>


<commit_before>var pomParser = require("../lib");
var expect = require('chai').expect;
var assert = require('assert');

var POM_PATH = __dirname + "/fixture/pom.xml";

describe('require("pom-parser")', function () {

  describe('loading from files', function() {
    var pomResponse = null;
    var pom = null;
    var xml = null;

    // Setup the tests using mocha's promise.
    // https://lostechies.com/derickbailey/2012/08/17/asynchronous-unit-tests-with-mocha-promises-and-winjs/
    before(function(done) {
      pomParser.parse({filePath: POM_PATH}, function(err, response) {
        expect(err).to.be.null;
        expect(response).to.be.an("object");

	      pomResponse = response;
	      pom = pomResponse.pomObject;
	      xml = pomResponse.pomXml;
	      done();
      });
    });

    // Tear down the tests by printing the loaded xml and the parsed object.
    after(function(done) {
      console.log("\n\nThe XML loaded");
      console.log(xml);
      console.log("\n\nThe parsed XML");
      console.log(JSON.stringify(pom, null, 2));
      done();
    });

    it('can load any pom.xml properly', function(done) {
      expect(pomResponse.pomXml).to.be.an("string");
      expect(pomResponse.pomObject).to.be.an("object");
      done();
    });

    it('parses xml attributes as properties', function(done) {
      expect(pom.project.xmlns).to.equal("http://maven.apache.org/POM/4.0.0");
      expect(pom.project["xmlns:xsi"]).to.equal("http://www.w3.org/2001/XMLSchema-instance");
      done();
    });

    it('parses xml elements as properties', function(done) {
      expect(pom.project.parent).to.be.an("object");
      expect(pom.project.parent.artifactid).to.equal("tynamo-parent");
      done();
    });

  });

  describe('when opts is null', function(){
    it('parser should throw an error', function() {
      assert.throws(function(){
        pomParser.parse(null, function(err, response){}, Error);
      });
    });
  });

  describe('when opts is empty', function(){
    it('parser should throw an error', function(){
      assert.throws(function(){
        pomParser.parse({}, function(err, response){}, Error);
      });
    });
  });

  describe('error scenarios', function() {
    it('should return error if file does not exist', function(done) {
      pomParser.parse({ filePath: __dirname + 'incorrect-file-path' }, function(err, response) {
        expect(response).to.be.null;
        expect(err).to.not.be.null;
        done();
      });
    });

    it('should return error if invalid xml file', function(done) {
      pomParser.parse({ filePath: __dirname + '/fixture/pom2.xml' }, function(err, response) {
        expect(response).to.be.null;
        expect(err).to.not.be.null;
        done();
      });
    });

    it('should return error if invalid xml content', function(done) {
      const invalidXml = '<parent>this is invalid</PARENT>';
      pomParser.parse({ xmlContent: invalidXml }, function(err) {
        expect(err).to.not.be.null;
        done();
      });
    });
  });
});
<commit_msg>chore: lint<commit_after>var pomParser = require("../lib");
var expect = require('chai').expect;
var assert = require('assert');

var POM_PATH = __dirname + "/fixture/pom.xml";

describe('require("pom-parser")', function () {

  describe('loading from files', function() {
    var pomResponse = null;
    var pom = null;
    var xml = null;

    // Setup the tests using mocha's promise.
    // https://lostechies.com/derickbailey/2012/08/17/asynchronous-unit-tests-with-mocha-promises-and-winjs/
    before(function(done) {
      pomParser.parse({filePath: POM_PATH}, function(err, response) {
        expect(err).to.be.null;
        expect(response).to.be.an("object");

        pomResponse = response;
        pom = pomResponse.pomObject;
        xml = pomResponse.pomXml;
        done();
      });
    });

    // Tear down the tests by printing the loaded xml and the parsed object.
    after(function(done) {
      console.log("\n\nThe XML loaded");
      console.log(xml);
      console.log("\n\nThe parsed XML");
      console.log(JSON.stringify(pom, null, 2));
      done();
    });

    it('can load any pom.xml properly', function(done) {
      expect(pomResponse.pomXml).to.be.an("string");
      expect(pomResponse.pomObject).to.be.an("object");
      done();
    });

    it('parses xml attributes as properties', function(done) {
      expect(pom.project.xmlns).to.equal("http://maven.apache.org/POM/4.0.0");
      expect(pom.project["xmlns:xsi"]).to.equal("http://www.w3.org/2001/XMLSchema-instance");
      done();
    });

    it('parses xml elements as properties', function(done) {
      expect(pom.project.parent).to.be.an("object");
      expect(pom.project.parent.artifactid).to.equal("tynamo-parent");
      done();
    });

  });

  describe('when opts is null', function(){
    it('parser should throw an error', function() {
      assert.throws(function(){
        pomParser.parse(null, function(err, response){}, Error);
      });
    });
  });

  describe('when opts is empty', function(){
    it('parser should throw an error', function(){
      assert.throws(function(){
        pomParser.parse({}, function(err, response){}, Error);
      });
    });
  });

  describe('error scenarios', function() {
    it('should return error if file does not exist', function(done) {
      pomParser.parse({ filePath: __dirname + 'incorrect-file-path' }, function(err, response) {
        expect(response).to.be.null;
        expect(err).to.not.be.null;
        done();
      });
    });

    it('should return error if invalid xml file', function(done) {
      pomParser.parse({ filePath: __dirname + '/fixture/pom2.xml' }, function(err, response) {
        expect(response).to.be.null;
        expect(err).to.not.be.null;
        done();
      });
    });

    it('should return error if invalid xml content', function(done) {
      const invalidXml = '<parent>this is invalid</PARENT>';
      pomParser.parse({ xmlContent: invalidXml }, function(err) {
        expect(err).to.not.be.null;
        done();
      });
    });
  });
});
<|endoftext|>


<commit_before>/*
 * 0xtrades.info
 * https://github.com/vsergeev/0xtrades.info
 *
 * Copyright (c) 2017 Ivan (Vanya) A. Sergeev
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/******************************************************************************/
/* Constants */
/******************************************************************************/

var ERRORS = {
  GET_NETWORK_ID:       1,
  GET_BLOCK_HEIGHT:     2,
  UNSUPPORTED_NETWORK:  3,
};

var ZEROEX_GENESIS_BLOCK = {
  1: 4145578,
  42: 4145578,
};

var ZEROEX_RELAY_ADDRESSES = {
  1: {
    "0xa258b39954cef5cb142fd567a46cddb31a670124": "Radar Relay",
    "0xeb71bad396acaa128aeadbc7dbd59ca32263de01": "Kin Alpha",
    "0xc22d5b2951db72b44cfb8089bb8cd374a3c354ea": "OpenRelay",
  },
  42: {
    "0xa258b39954cef5cb142fd567a46cddb31a670124": "Radar Relay",
  },
};

/* Populated by model */
var ZEROEX_TOKEN_INFOS = {
    /* Pre-load some newer token infos */
    "0x8f8221afbb33998d8584a2b05749ba73c37a938a": {
      name: "Request",
      symbol: "REQ",
      decimals: 18,
    },
    "0xd4fa1460f537bb9085d22c7bccb5dd450ef28e3a": {
      name: "Populous Platform",
      symbol: "PPT",
      decimals: 8,
    },
    "0xab16e0d25c06cb376259cc18c1de4aca57605589": {
      name: "FinallyUsableCryptoKarma",
      symbol: "FUCK",
      decimals: 4,
    },
    "0x0e0989b1f9b8a38983c2ba8053269ca62ec9b195": {
      name: "Po.et",
      symbol: "POE",
      decimals: 8,
    },
    "0x8ae4bf2c33a8e667de34b54938b0ccd03eb8cc06": {
      name: "Patientory",
      symbol: "PTOY",
      decimals: 8,
    },
};

/* Populated by model */
var ZEROEX_EXCHANGE_ADDRESS = null;

/* Populated by model */
var ZEROEX_TOKEN_ADDRESS = null;

var NETWORK_NAME = {
  1: "Mainnet",
  3: "Ropsten",
  4: "Rinkeby",
  42: "Kovan",
};

var NETWORK_BLOCK_EXPLORER = {
  1: "https://etherscan.io",
  3: "https://ropsten.etherscan.io",
  4: "https://rinkeby.etherscan.io",
  42: "https://kovan.etherscan.io",
};

var PRICE_API_URL = function (symbols, base) {
  return "https://min-api.cryptocompare.com/data/pricemulti?fsyms=" + symbols.join(',') + "&tsyms=" + base;
};

var INFURA_API_URL = "https://mainnet.infura.io/rdkuEWbeKAjSR9jZ6P1h";

var ZEROEX_PORTAL_URL = "https://0xproject.com/portal";

var STATISTICS_TIME_WINDOW = 86400; /* 24 hours */

var BLOCK_FETCH_COUNT = Math.ceil(STATISTICS_TIME_WINDOW/17);

var BLOCK_INFO_RETRY_TIMEOUT = 15*1000;

var PRICE_UPDATE_TIMEOUT = 5*60*1000;

var PRICE_CHART_DEFAULT_PAIR = "ZRX/WETH";

var CHART_DEFAULT_COLORS = ['#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a',
                            '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94',
                            '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d',
                            '#17becf', '#9edae5'];

var CHART_DEFAULT_TOOLTIP_CALLBACK = function (item, data) {
  var label = data.labels[item.index];
  var value = data.datasets[item.datasetIndex].tooltips[item.index] || data.datasets[item.datasetIndex].data[item.index];
  return label + ": " + value;
};

/* From http://www.localeplanet.com/api/auto/currencymap.json */
var FIAT_CURRENCY_MAP = {
  "USD": {
    "symbol": "$",
    "symbol_native": "$",
    "decimal_digits": 2,
    "rounding": 0,
    "code": "USD"
  },
  "EUR": {
    "symbol": "€",
    "symbol_native": "€",
    "decimal_digits": 2,
    "rounding": 0,
    "code": "EUR"
  },
  "GBP": {
    "symbol": "£",
    "symbol_native": "£",
    "decimal_digits": 2,
    "rounding": 0,
    "code": "GBP"
  },
  "JPY": {
    "symbol": "¥",
    "symbol_native": "￥",
    "decimal_digits": 0,
    "rounding": 0,
    "code": "JPY"
  },
  "KRW": {
    "symbol": "₩",
    "symbol_native": "₩",
    "decimal_digits": 0,
    "rounding": 0,
    "code": "KRW"
  },
};

var FIAT_CURRENCY_DEFAULT = "USD";
<commit_msg>constants: add MANA token to token infos<commit_after>/*
 * 0xtrades.info
 * https://github.com/vsergeev/0xtrades.info
 *
 * Copyright (c) 2017 Ivan (Vanya) A. Sergeev
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/******************************************************************************/
/* Constants */
/******************************************************************************/

var ERRORS = {
  GET_NETWORK_ID:       1,
  GET_BLOCK_HEIGHT:     2,
  UNSUPPORTED_NETWORK:  3,
};

var ZEROEX_GENESIS_BLOCK = {
  1: 4145578,
  42: 4145578,
};

var ZEROEX_RELAY_ADDRESSES = {
  1: {
    "0xa258b39954cef5cb142fd567a46cddb31a670124": "Radar Relay",
    "0xeb71bad396acaa128aeadbc7dbd59ca32263de01": "Kin Alpha",
    "0xc22d5b2951db72b44cfb8089bb8cd374a3c354ea": "OpenRelay",
  },
  42: {
    "0xa258b39954cef5cb142fd567a46cddb31a670124": "Radar Relay",
  },
};

/* Populated by model */
var ZEROEX_TOKEN_INFOS = {
    /* Pre-load some newer token infos */
    "0x8f8221afbb33998d8584a2b05749ba73c37a938a": {
      name: "Request",
      symbol: "REQ",
      decimals: 18,
    },
    "0xd4fa1460f537bb9085d22c7bccb5dd450ef28e3a": {
      name: "Populous Platform",
      symbol: "PPT",
      decimals: 8,
    },
    "0xab16e0d25c06cb376259cc18c1de4aca57605589": {
      name: "FinallyUsableCryptoKarma",
      symbol: "FUCK",
      decimals: 4,
    },
    "0x0e0989b1f9b8a38983c2ba8053269ca62ec9b195": {
      name: "Po.et",
      symbol: "POE",
      decimals: 8,
    },
    "0x8ae4bf2c33a8e667de34b54938b0ccd03eb8cc06": {
      name: "Patientory",
      symbol: "PTOY",
      decimals: 8,
    },
    "0x0f5d2fb29fb7d3cfee444a200298f468908cc942": {
      name: "Decentraland MANA",
      symbol: "MANA",
      decimals: 18,
    },
};

/* Populated by model */
var ZEROEX_EXCHANGE_ADDRESS = null;

/* Populated by model */
var ZEROEX_TOKEN_ADDRESS = null;

var NETWORK_NAME = {
  1: "Mainnet",
  3: "Ropsten",
  4: "Rinkeby",
  42: "Kovan",
};

var NETWORK_BLOCK_EXPLORER = {
  1: "https://etherscan.io",
  3: "https://ropsten.etherscan.io",
  4: "https://rinkeby.etherscan.io",
  42: "https://kovan.etherscan.io",
};

var PRICE_API_URL = function (symbols, base) {
  return "https://min-api.cryptocompare.com/data/pricemulti?fsyms=" + symbols.join(',') + "&tsyms=" + base;
};

var INFURA_API_URL = "https://mainnet.infura.io/rdkuEWbeKAjSR9jZ6P1h";

var ZEROEX_PORTAL_URL = "https://0xproject.com/portal";

var STATISTICS_TIME_WINDOW = 86400; /* 24 hours */

var BLOCK_FETCH_COUNT = Math.ceil(STATISTICS_TIME_WINDOW/17);

var BLOCK_INFO_RETRY_TIMEOUT = 15*1000;

var PRICE_UPDATE_TIMEOUT = 5*60*1000;

var PRICE_CHART_DEFAULT_PAIR = "ZRX/WETH";

var CHART_DEFAULT_COLORS = ['#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a',
                            '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94',
                            '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d',
                            '#17becf', '#9edae5'];

var CHART_DEFAULT_TOOLTIP_CALLBACK = function (item, data) {
  var label = data.labels[item.index];
  var value = data.datasets[item.datasetIndex].tooltips[item.index] || data.datasets[item.datasetIndex].data[item.index];
  return label + ": " + value;
};

/* From http://www.localeplanet.com/api/auto/currencymap.json */
var FIAT_CURRENCY_MAP = {
  "USD": {
    "symbol": "$",
    "symbol_native": "$",
    "decimal_digits": 2,
    "rounding": 0,
    "code": "USD"
  },
  "EUR": {
    "symbol": "€",
    "symbol_native": "€",
    "decimal_digits": 2,
    "rounding": 0,
    "code": "EUR"
  },
  "GBP": {
    "symbol": "£",
    "symbol_native": "£",
    "decimal_digits": 2,
    "rounding": 0,
    "code": "GBP"
  },
  "JPY": {
    "symbol": "¥",
    "symbol_native": "￥",
    "decimal_digits": 0,
    "rounding": 0,
    "code": "JPY"
  },
  "KRW": {
    "symbol": "₩",
    "symbol_native": "₩",
    "decimal_digits": 0,
    "rounding": 0,
    "code": "KRW"
  },
};

var FIAT_CURRENCY_DEFAULT = "USD";
<|endoftext|>


<commit_before>/*
 * instances.js: Instance methods for working with database instances from Openstack Trove
 *
 * (C) 2014 Hewlett-Packard Development Company, L.P.
 *
 */

var pkgcloud = require('../../../../../lib/pkgcloud'),
    Flavor   = pkgcloud.providers.rackspace.database.Flavor,
    Instance = pkgcloud.providers.rackspace.database.Instance,
    errs     = require('errs'),
    qs       = require('querystring');

// Create Database Instance
// Need a flavor
// ### @options {Object} Set of options can be
// #### options['name'] {string} Name of instance (required)
// #### options['flavor'] {string | Object} Should be the HREF for the flavor or a instance of Flavor class (required)
// #### options['size'] {number} The Volume size in Gigabytes, must be between 1 and 8
// #### options['databases'] {array} Array of strings with database names to create when the instance is ready.
// ### @callback {Function} Function to continue the call is cb(error, Instance)
exports.createInstance = function createInstance(options, callback) {
  var self = this,
      flavorRef,
      size;

  // Check for options
  if (!options || typeof options === 'function') {
    return errs.handle(errs.create({
      message: 'Options required for create an instance.'
    }), options);
  }

  if (!options['name']) {
    return errs.handle(errs.create({
      message: 'options. name is a required argument'
    }), callback);
  }

  if (!options['flavor']) {
    return errs.handle(errs.create({
      message: 'options. flavor is a required argument'
    }), callback);
  }

  // If the 'databases' are specified we create a template for each database name.
  if (options && options['databases'] &&
      Array.isArray(options['databases']) &&
      options['databases'].length > 0) {
    options['databases'].forEach(function (item, idx) {
      if (typeof item === 'string') {
        // This template is according to the defaults of rackspace.
        options['databases'][idx] = {
          name: item,
          character_set: 'utf8',
          collate: 'utf8_general_ci'
        };
      }
    });
  }

  // Check for the correct value of 'size', should be between 1 and 8 otherwise will be 1
  if (options && options['size']) {
    // Ensure size is an Integer
    if (typeof options['size'] !== 'number') {
      return errs.handle(errs.create({
        message: 'options. Volume size should be a Number, not a String'
      }), callback);
    }
    size = (options['size'] > 0 && options['size'] < 9) ? options['size'] : 1;
  }

  // Extract the href value of the Flavor instance
  // Should be always true because above we return an error if not exists
  if (options && options['flavor']) {
    flavorRef = options['flavor'] instanceof Flavor ? options['flavor'].href : options['flavor'];
  }

  var createOptions = {
    method: 'POST',
    path: 'instances',
    body: {
      instance: {
        name: options['name'],
        flavorRef: flavorRef,
        databases: options['databases'] || [],
        volume: { size: size || 1 },
        nics: options['networks'],
        datastore: options['datastore'],
        users: options['users'] || []
      }
    }
  };

  this._request(createOptions, function (err, body) {
    return err
      ? callback(err)
      : callback(null, new Instance(self, body.instance));
  });
};

// Gets all instances info
// ### @options {Object} Set of options can be
// #### options['limit'] {Integer} Number of results you want
// #### options['offset'] {Integer} Offset mark for result list
// ### @callback {Function} Function to continue the call is cb(error, instances, offset)
exports.getInstances = function getInstances(options, callback) {
  var self = this,
      completeUrl = {},
      requestOptions = {};

  if (typeof options === 'function') {
    callback = options;
    options = {};
  }

  // The limit parameter for truncate results
  if (options && options.limit) {
    completeUrl.limit = options.limit;
  }

  // The offset
  if (options && options.offset) {
    completeUrl.marker = options.offset;
  }

  requestOptions.qs = completeUrl;
  requestOptions.path = 'instances';

  this._request(requestOptions, function (err, body) {
    if (err) {
      return callback(err);
    }

    var marker = null;
    if (body.links && body.links.length > 0) {
      marker = qs.parse(body.links[0].href.split('?').pop()).marker;
    }

    callback(null, body.instances.map(function (result) {
      return new Instance(self, result);
    }), marker);
  });
};

// Destroying the database instance
// ### @instance {string | Object} The ID of the istance of a instance of Instance class (required)
// ### @callback {Function} Function to continue the call is cb(error, res)
exports.destroyInstance = function destroyInstance(instance, callback) {
  // Check for instance
  if (typeof instance === 'function') {
    return errs.handle(errs.create({
      message: 'An instance is required.'
    }), instance);
  }

  var instanceId = instance instanceof Instance ? instance.id : instance;
  this._request({
    method: 'DELETE',
    path: 'instances/' + instanceId
  }, function (err, body, response) {
    return err
      ? callback(err)
      : callback(null, response);
  });
};

// Details of specific instance
// ### @instance {string | Object} The ID of the istance of a instance of Instance class (required)
// ### @callback {Function} Function to continue the call is cb(error, instances, offset)
exports.getInstance = function getInstance(instance, callback) {
  // Check for instance
  if (typeof instance === 'function') {
    return errs.handle(errs.create({
      message: 'An instance is required.'
    }), instance);
  }

  var self = this;
  var instanceId = instance instanceof Instance ? instance.id : instance;
  this._request({
    path: 'instances/' + instanceId
  }, function (err, body) {
    return err
      ? callback(err)
      : callback(null, new Instance(self, body.instance));
  });
};

// Restart the Instance
// Call this function cause a restart in the instance specified
// ### @instance {string | Object} The ID of the istance of a instance of Instance class (required)
// ### @callback {Function} Function to continue the call is cb(error)
exports.restartInstance = function restartInstance(instance, callback) {
  // Check for instance
  if (typeof instance === 'function' || typeof instance === 'undefined') {
    return errs.handle(errs.create({
      message: 'An instance is required.'
    }), Array.prototype.slice.call(arguments).pop());
  }

  var instanceId = instance instanceof Instance ? instance.id : instance;

  var restartOptions = {
    method: 'POST',
    path: 'instances/' + instanceId + '/action',
    body: { restart: {} }
  };

  this._request(restartOptions, function (err, body, response) {
    if (err) {
      return callback(err);
    }

    if (response.statusCode === 202) {
      return callback(null);
    }

    errs.handle(errs.create({
      message: 'Bad response from restart action.'
    }), callback);
  });
};

// Resize the memory of the database instance.
// You can use this to change the flavor of the database instance, need a new flavor.
// ### @instance {string | Object} The ID of the istance of a instance of Instance class (required)
// ### @flavor {Flavor class} The flavor to resize the instance, should be different (required)
// ### @callback {Function} Function to continue, no params are passed.
exports.setFlavor = function setFlavor(instance, flavor, callback) {
  // Check for the flavor
  if (typeof flavor === 'function' || typeof flavor === 'undefined') {
    return errs.handle(errs.create({
      message: 'A flavor is required.'
    }), Array.prototype.slice.call(arguments).pop());
  }
  // Check for instance
  if (typeof instance === 'function' || typeof instance === 'undefined') {
    return errs.handle(errs.create({
      message: 'An instance is required.'
    }), Array.prototype.slice.call(arguments).pop());
  }

  if (!(flavor instanceof Flavor)) {
    return errs.handle(errs.create({
      message: 'A valid flavor is required.'
    }), Array.prototype.slice.call(arguments).pop());
  }
  //@todo: Check if the new flavor are different from the old.

  var instanceId = instance instanceof Instance ? instance.id : instance;

  var resizeOptions = {
    method: 'POST',
    path: 'instances/' + instanceId + '/action',
    body: {
      resize: {
        flavorRef: flavor.href
      }
    }
  };

  this._request(resizeOptions, function (err, body, response) {
    if (err) {
      return callback(err);
    }

    if (response.statusCode === 202) {
      return callback(null);
    }
    return errs.handle(errs.create({
      message: 'Bad response from resize action.'
    }), callback);
  });
};

// Resize the volume size of the database instance.
// You can use this to change the size of the volume for a database instance.
// ### @instance {string | Object} The ID of the istance of a instance of Instance class (required)
// ### @newSize  {Number} The new size for the volume (require)
// ### @callback {Function} Function to continue, no params are passed.
exports.setVolumeSize = function setVolumeSize(instance, newSize, callback) {
  // Check for instance
  if (typeof instance === 'function' || typeof instance === 'undefined') {
    return errs.handle(errs.create({
      message: 'An instance is required.'
    }), Array.prototype.slice.call(arguments).pop());
  }
  // Check for the volume size
  if (typeof newSize === 'function' || typeof newSize === 'undefined') {
    return errs.handle(errs.create({
      message: 'An correct volume size is required.'
    }), Array.prototype.slice.call(arguments).pop());
  }
  if (newSize > 10 || newSize < 1) {
    return errs.handle(errs.create({
      message: 'An correct volume size is required.'
    }), Array.prototype.slice.call(arguments).pop());
  }

  var instanceId = instance instanceof Instance ? instance.id : instance;

  var resizeOptions = {
    method: 'POST',
    path: 'instances/' + instanceId + '/action',
    body: {
      resize: {
        volume: { size: newSize }
      }
    }
  };

  this._request(resizeOptions, function (err, body, response) {
    if (err) {
      return callback(err);
    }

    if (response.statusCode === 202) {
      return callback(null);
    }
    return errs.handle(errs.create({
      message: 'Bad response from resize action.'
    }), callback);
  });
};

// Enable the root user for the given database instance.
// ### @instance {string | Object} The ID of the instance or a instance or Instance class (required)
// ### @callback {Function} Function to continue, the call is cb(error, res)
exports.enableRootUser = function enableRootUser(instance, callback) {
  // Check for instance
  if (typeof instance === 'function' || typeof instance === 'undefined') {
    return errs.handle(errs.create({
      message: 'An instance is required.'
    }), Array.prototype.slice.call(arguments).pop());
  }

  var instanceId = instance instanceof Instance ? instance.id : instance;

  var options = {
    method: 'POST',
    path: 'instances/' + instanceId + '/root'
  };

  this._request(options, function (err, body, response) {
    if (err) {
      return callback(err);
    }

    if (response.statusCode === 200) {
      return callback(null, body);
    }

    return errs.handle(errs.create({
      message: 'Bad response from enabling root user'
    }), callback);
  });
};

// List the root status for the database instance.
// `res` will be an object like `{ rootEnabled: true }`
// ### @instance {string | Object} The ID of the instance or a instance or Instance class (required)
// ### @callback {Function} Function to continue, the call is cb(error, res)
exports.listRootStatus = function listRootStatus(instance, callback) {
  // Check for instance
  if (typeof instance === 'function' || typeof instance === 'undefined') {
    return errs.handle(errs.create({
      message: 'An instance is required.'
    }), Array.prototype.slice.call(arguments).pop());
  }

  var instanceId = instance instanceof Instance ? instance.id : instance;

  var options = {
    method: 'GET',
    path: 'instances/' + instanceId + '/root'
  };

  this._request(options, function (err, body, response) {
    if (err) {
      return callback(err);
    }

    if (response.statusCode === 200) {
      return callback(null, body);
    }

    return errs.handle(errs.create({
      message: 'Bad response from listing root-enabled status'
    }), callback);
  });
};
<commit_msg>[openstack][database] support volume type; increase volume size limit to 4096<commit_after>/*
 * instances.js: Instance methods for working with database instances from Openstack Trove
 *
 * (C) 2014 Hewlett-Packard Development Company, L.P.
 *
 */

var pkgcloud = require('../../../../../lib/pkgcloud'),
    Flavor   = pkgcloud.providers.rackspace.database.Flavor,
    Instance = pkgcloud.providers.rackspace.database.Instance,
    errs     = require('errs'),
    qs       = require('querystring');

// Create Database Instance
// Need a flavor
// ### @options {Object} Set of options can be
// #### options['name'] {string} Name of instance (required)
// #### options['flavor'] {string | Object} Should be the HREF for the flavor or a instance of Flavor class (required)
// #### options['size'] {number} The Volume size in Gigabytes, must be between 1 and 8
// #### options['databases'] {array} Array of strings with database names to create when the instance is ready.
// ### @callback {Function} Function to continue the call is cb(error, Instance)
exports.createInstance = function createInstance(options, callback) {
  var self = this,
      flavorRef,
      size;

  // Check for options
  if (!options || typeof options === 'function') {
    return errs.handle(errs.create({
      message: 'Options required for create an instance.'
    }), options);
  }

  if (!options['name']) {
    return errs.handle(errs.create({
      message: 'options. name is a required argument'
    }), callback);
  }

  if (!options['flavor']) {
    return errs.handle(errs.create({
      message: 'options. flavor is a required argument'
    }), callback);
  }

  // If the 'databases' are specified we create a template for each database name.
  if (options && options['databases'] &&
      Array.isArray(options['databases']) &&
      options['databases'].length > 0) {
    options['databases'].forEach(function (item, idx) {
      if (typeof item === 'string') {
        // This template is according to the defaults of rackspace.
        options['databases'][idx] = {
          name: item,
          character_set: 'utf8',
          collate: 'utf8_general_ci'
        };
      }
    });
  }

  // Check for the correct value of 'size', should be between 1 and 8 otherwise will be 1
  if (options && options['size']) {
    // Ensure size is an Integer
    if (typeof options['size'] !== 'number') {
      return errs.handle(errs.create({
        message: 'options. Volume size should be a Number, not a String'
      }), callback);
    }
    size = (options['size'] > 0 && options['size'] <= 4096) ? options['size'] : 1;
  }

  // Extract the href value of the Flavor instance
  // Should be always true because above we return an error if not exists
  if (options && options['flavor']) {
    flavorRef = options['flavor'] instanceof Flavor ? options['flavor'].href : options['flavor'];
  }

  var createOptions = {
    method: 'POST',
    path: 'instances',
    body: {
      instance: {
        name: options['name'],
        flavorRef: flavorRef,
        databases: options['databases'] || [],
        volume: {
          size: size || 1,
          type: options['volumeType'] || 'ssd',
        },
        nics: options['networks'],
        datastore: options['datastore'],
        users: options['users'] || [],
      }
    }
  };

  this._request(createOptions, function (err, body) {
    return err
      ? callback(err)
      : callback(null, new Instance(self, body.instance));
  });
};

// Gets all instances info
// ### @options {Object} Set of options can be
// #### options['limit'] {Integer} Number of results you want
// #### options['offset'] {Integer} Offset mark for result list
// ### @callback {Function} Function to continue the call is cb(error, instances, offset)
exports.getInstances = function getInstances(options, callback) {
  var self = this,
      completeUrl = {},
      requestOptions = {};

  if (typeof options === 'function') {
    callback = options;
    options = {};
  }

  // The limit parameter for truncate results
  if (options && options.limit) {
    completeUrl.limit = options.limit;
  }

  // The offset
  if (options && options.offset) {
    completeUrl.marker = options.offset;
  }

  requestOptions.qs = completeUrl;
  requestOptions.path = 'instances';

  this._request(requestOptions, function (err, body) {
    if (err) {
      return callback(err);
    }

    var marker = null;
    if (body.links && body.links.length > 0) {
      marker = qs.parse(body.links[0].href.split('?').pop()).marker;
    }

    callback(null, body.instances.map(function (result) {
      return new Instance(self, result);
    }), marker);
  });
};

// Destroying the database instance
// ### @instance {string | Object} The ID of the istance of a instance of Instance class (required)
// ### @callback {Function} Function to continue the call is cb(error, res)
exports.destroyInstance = function destroyInstance(instance, callback) {
  // Check for instance
  if (typeof instance === 'function') {
    return errs.handle(errs.create({
      message: 'An instance is required.'
    }), instance);
  }

  var instanceId = instance instanceof Instance ? instance.id : instance;
  this._request({
    method: 'DELETE',
    path: 'instances/' + instanceId
  }, function (err, body, response) {
    return err
      ? callback(err)
      : callback(null, response);
  });
};

// Details of specific instance
// ### @instance {string | Object} The ID of the istance of a instance of Instance class (required)
// ### @callback {Function} Function to continue the call is cb(error, instances, offset)
exports.getInstance = function getInstance(instance, callback) {
  // Check for instance
  if (typeof instance === 'function') {
    return errs.handle(errs.create({
      message: 'An instance is required.'
    }), instance);
  }

  var self = this;
  var instanceId = instance instanceof Instance ? instance.id : instance;
  this._request({
    path: 'instances/' + instanceId
  }, function (err, body) {
    return err
      ? callback(err)
      : callback(null, new Instance(self, body.instance));
  });
};

// Restart the Instance
// Call this function cause a restart in the instance specified
// ### @instance {string | Object} The ID of the istance of a instance of Instance class (required)
// ### @callback {Function} Function to continue the call is cb(error)
exports.restartInstance = function restartInstance(instance, callback) {
  // Check for instance
  if (typeof instance === 'function' || typeof instance === 'undefined') {
    return errs.handle(errs.create({
      message: 'An instance is required.'
    }), Array.prototype.slice.call(arguments).pop());
  }

  var instanceId = instance instanceof Instance ? instance.id : instance;

  var restartOptions = {
    method: 'POST',
    path: 'instances/' + instanceId + '/action',
    body: { restart: {} }
  };

  this._request(restartOptions, function (err, body, response) {
    if (err) {
      return callback(err);
    }

    if (response.statusCode === 202) {
      return callback(null);
    }

    errs.handle(errs.create({
      message: 'Bad response from restart action.'
    }), callback);
  });
};

// Resize the memory of the database instance.
// You can use this to change the flavor of the database instance, need a new flavor.
// ### @instance {string | Object} The ID of the istance of a instance of Instance class (required)
// ### @flavor {Flavor class} The flavor to resize the instance, should be different (required)
// ### @callback {Function} Function to continue, no params are passed.
exports.setFlavor = function setFlavor(instance, flavor, callback) {
  // Check for the flavor
  if (typeof flavor === 'function' || typeof flavor === 'undefined') {
    return errs.handle(errs.create({
      message: 'A flavor is required.'
    }), Array.prototype.slice.call(arguments).pop());
  }
  // Check for instance
  if (typeof instance === 'function' || typeof instance === 'undefined') {
    return errs.handle(errs.create({
      message: 'An instance is required.'
    }), Array.prototype.slice.call(arguments).pop());
  }

  if (!(flavor instanceof Flavor)) {
    return errs.handle(errs.create({
      message: 'A valid flavor is required.'
    }), Array.prototype.slice.call(arguments).pop());
  }
  //@todo: Check if the new flavor are different from the old.

  var instanceId = instance instanceof Instance ? instance.id : instance;

  var resizeOptions = {
    method: 'POST',
    path: 'instances/' + instanceId + '/action',
    body: {
      resize: {
        flavorRef: flavor.href
      }
    }
  };

  this._request(resizeOptions, function (err, body, response) {
    if (err) {
      return callback(err);
    }

    if (response.statusCode === 202) {
      return callback(null);
    }
    return errs.handle(errs.create({
      message: 'Bad response from resize action.'
    }), callback);
  });
};

// Resize the volume size of the database instance.
// You can use this to change the size of the volume for a database instance.
// ### @instance {string | Object} The ID of the istance of a instance of Instance class (required)
// ### @newSize  {Number} The new size for the volume (require)
// ### @callback {Function} Function to continue, no params are passed.
exports.setVolumeSize = function setVolumeSize(instance, newSize, callback) {
  // Check for instance
  if (typeof instance === 'function' || typeof instance === 'undefined') {
    return errs.handle(errs.create({
      message: 'An instance is required.'
    }), Array.prototype.slice.call(arguments).pop());
  }
  // Check for the volume size
  if (typeof newSize === 'function' || typeof newSize === 'undefined') {
    return errs.handle(errs.create({
      message: 'An correct volume size is required.'
    }), Array.prototype.slice.call(arguments).pop());
  }
  if (newSize > 10 || newSize < 1) {
    return errs.handle(errs.create({
      message: 'An correct volume size is required.'
    }), Array.prototype.slice.call(arguments).pop());
  }

  var instanceId = instance instanceof Instance ? instance.id : instance;

  var resizeOptions = {
    method: 'POST',
    path: 'instances/' + instanceId + '/action',
    body: {
      resize: {
        volume: { size: newSize }
      }
    }
  };

  this._request(resizeOptions, function (err, body, response) {
    if (err) {
      return callback(err);
    }

    if (response.statusCode === 202) {
      return callback(null);
    }
    return errs.handle(errs.create({
      message: 'Bad response from resize action.'
    }), callback);
  });
};

// Enable the root user for the given database instance.
// ### @instance {string | Object} The ID of the instance or a instance or Instance class (required)
// ### @callback {Function} Function to continue, the call is cb(error, res)
exports.enableRootUser = function enableRootUser(instance, callback) {
  // Check for instance
  if (typeof instance === 'function' || typeof instance === 'undefined') {
    return errs.handle(errs.create({
      message: 'An instance is required.'
    }), Array.prototype.slice.call(arguments).pop());
  }

  var instanceId = instance instanceof Instance ? instance.id : instance;

  var options = {
    method: 'POST',
    path: 'instances/' + instanceId + '/root'
  };

  this._request(options, function (err, body, response) {
    if (err) {
      return callback(err);
    }

    if (response.statusCode === 200) {
      return callback(null, body);
    }

    return errs.handle(errs.create({
      message: 'Bad response from enabling root user'
    }), callback);
  });
};

// List the root status for the database instance.
// `res` will be an object like `{ rootEnabled: true }`
// ### @instance {string | Object} The ID of the instance or a instance or Instance class (required)
// ### @callback {Function} Function to continue, the call is cb(error, res)
exports.listRootStatus = function listRootStatus(instance, callback) {
  // Check for instance
  if (typeof instance === 'function' || typeof instance === 'undefined') {
    return errs.handle(errs.create({
      message: 'An instance is required.'
    }), Array.prototype.slice.call(arguments).pop());
  }

  var instanceId = instance instanceof Instance ? instance.id : instance;

  var options = {
    method: 'GET',
    path: 'instances/' + instanceId + '/root'
  };

  this._request(options, function (err, body, response) {
    if (err) {
      return callback(err);
    }

    if (response.statusCode === 200) {
      return callback(null, body);
    }

    return errs.handle(errs.create({
      message: 'Bad response from listing root-enabled status'
    }), callback);
  });
};
<|endoftext|>


<commit_before>'use strict()';

process.env.NODE_ENV = 'test';

var assert = require('assert'),
		expect = require('chai').expect,
		autostart = require('../lib/index.js');

describe('Arguments', function() {
	it('should not accept too few arguments', function() {
		expect(autostart.enableAutostart('someString', 'anotherString', 'stillAString')).to.equal(1);
		expect(autostart.disableAutostart('someString')).to.equal(1);
		expect(autostart.isAutostartEnabled('someString')).to.equal(1);
	});

	it('should not accept arguments with wrong types', function() {
		expect(autostart.enableAutostart(1, 2, 3, 4)).to.equal(1);
		expect(autostart.enableAutostart('string', 2, 3, 4)).to.equal(1);
		expect(autostart.enableAutostart('string', 'string', 3, 4)).to.equal(1);
		expect(autostart.enableAutostart('string', 'string', 'string', 4)).to.equal(1);
		expect(autostart.disableAutostart(1, 2)).to.equal(1);
		expect(autostart.disableAutostart('string', 2)).to.equal(1);
		expect(autostart.isAutostartEnabled(1, 2)).to.equal(1);
		expect(autostart.isAutostartEnabled('string', 2)).to.equal(1);
	});
});

describe('Checks', function() {
	it('should respond with isEnabled=false and not throw for fake service', function() {
		autostart.isAutostartEnabled('test', function(isEnabled, error) {
			expect(isEnabled).to.equal(false);
			if(os.platform() === 'linux') {
				expect(error).to.equal('Your platform currently is not supported');
			}
			else if(os.platform() === 'darwin') {
				expect(error).to.equal(null);
			}
			else if(os.platform() === 'win32') {
				expect(error).to.equal('Your platform currently is not supported');
			}
			else {
				expect(error).to.equal('Your platform currently is not supported');
			}
		});
	});
});
<commit_msg>Updated test.js<commit_after>'use strict()';

process.env.NODE_ENV = 'test';

var assert = require('assert'),
		expect = require('chai').expect,
		os = require('os'),
		autostart = require('../lib/index.js');

describe('Arguments', function() {
	it('should not accept too few arguments', function() {
		expect(autostart.enableAutostart('someString', 'anotherString', 'stillAString')).to.equal(1);
		expect(autostart.disableAutostart('someString')).to.equal(1);
		expect(autostart.isAutostartEnabled('someString')).to.equal(1);
	});

	it('should not accept arguments with wrong types', function() {
		expect(autostart.enableAutostart(1, 2, 3, 4)).to.equal(1);
		expect(autostart.enableAutostart('string', 2, 3, 4)).to.equal(1);
		expect(autostart.enableAutostart('string', 'string', 3, 4)).to.equal(1);
		expect(autostart.enableAutostart('string', 'string', 'string', 4)).to.equal(1);
		expect(autostart.disableAutostart(1, 2)).to.equal(1);
		expect(autostart.disableAutostart('string', 2)).to.equal(1);
		expect(autostart.isAutostartEnabled(1, 2)).to.equal(1);
		expect(autostart.isAutostartEnabled('string', 2)).to.equal(1);
	});
});

describe('Checks', function() {
	it('should respond with isEnabled=false and not throw for fake service', function() {
		autostart.isAutostartEnabled('test', function(isEnabled, error) {
			expect(isEnabled).to.equal(false);
			if(os.platform() === 'linux') {
				expect(error).to.equal('Your platform currently is not supported');
			}
			else if(os.platform() === 'darwin') {
				expect(error).to.equal(null);
			}
			else if(os.platform() === 'win32') {
				expect(error).to.equal('Your platform currently is not supported');
			}
			else {
				expect(error).to.equal('Your platform currently is not supported');
			}
		});
	});
});
<|endoftext|>


<commit_before>//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: For creating grouped collapsible content areas.
//>>label: Collapsible Sets (Accordions)
//>>group: Widgets
//>>css.structure: ../css/structure/jquery.mobile.collapsible.css
//>>css.theme: ../css/themes/default/jquery.mobile.theme.css

define( [ "jquery", "../jquery.mobile.widget", "./collapsible", "./addFirstLastClasses", "../jquery.mobile.registry" ], function( jQuery ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, undefined ) {

$.widget( "mobile.collapsibleset", $.mobile.widget, $.extend( {
	_create: function() {
		var $el = this.element.addClass( "ui-collapsible-set" ),
			o = this.options;

		// Inherit the theme from collapsible-set
		if ( !o.theme ) {
			o.theme = $.mobile.getInheritedTheme( $el, "c" );
		}
		// Inherit the content-theme from collapsible-set
		if ( !o.contentTheme ) {
			o.contentTheme = $el.jqmData( "content-theme" );
		}
		// Inherit the corner styling from collapsible-set
		if ( !o.corners ) {
			o.corners = $el.jqmData( "corners" );
		}

		if ( $el.jqmData( "inset" ) !== undefined ) {
			o.inset = $el.jqmData( "inset" );
		}
		o.inset = o.inset !== undefined ? o.inset : true;
		o.corners = o.corners !== undefined ? o.corners : true;

		if ( !!o.corners && !!o.inset ) {
			$el.addClass( "ui-corner-all" );
		}

		// Initialize the collapsible set if it's not already initialized
		if ( !$el.jqmData( "collapsiblebound" ) ) {
			$el
				.jqmData( "collapsiblebound", true )
				.bind( "expand", function( event ) {
					var closestCollapsible = $( event.target )
						.closest( ".ui-collapsible" );
					if ( closestCollapsible.parent().is( ":mobile-collapsibleset, :jqmData(role='collapsible-set')" ) ) {
						closestCollapsible
							.siblings( ".ui-collapsible" )
							.trigger( "collapse" );
					}
				});
		}
	},

	_init: function() {
		var $el = this.element,
			collapsiblesInSet = $el.children( ":mobile-collapsible, :jqmData(role='collapsible')" ),
			expanded = collapsiblesInSet.filter( ":jqmData(collapsed='false')" );
		this._refresh( "true" );

		// Because the corners are handled by the collapsible itself and the default state is collapsed
		// That was causing https://github.com/jquery/jquery-mobile/issues/4116
		expanded.trigger( "expand" );
	},

	_refresh: function( create ) {
		var collapsiblesInSet = this.element.children( ":mobile-collapsible, :jqmData(role='collapsible')" );

		$.mobile.collapsible.prototype.enhance( collapsiblesInSet.not( ".ui-collapsible" ) );

		this._addFirstLastClasses( collapsiblesInSet, this._getVisibles( collapsiblesInSet, create ), create );
	},

	refresh: function() {
		this._refresh( false );
	}
}, $.mobile.behaviors.addFirstLastClasses ) );

$.mobile.collapsibleset.initSelector = ":jqmData(role='collapsible-set')";

//auto self-init widgets
$.mobile._enhancer.add( "mobile.collapsibleset" );

})( jQuery );
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");
<commit_msg>Collapsible: Do not collapse already-collapsed collapsibles. Fixes #5911. Thanks @DzenisevichK.<commit_after>//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: For creating grouped collapsible content areas.
//>>label: Collapsible Sets (Accordions)
//>>group: Widgets
//>>css.structure: ../css/structure/jquery.mobile.collapsible.css
//>>css.theme: ../css/themes/default/jquery.mobile.theme.css

define( [ "jquery", "../jquery.mobile.widget", "./collapsible", "./addFirstLastClasses", "../jquery.mobile.registry" ], function( jQuery ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, undefined ) {

$.widget( "mobile.collapsibleset", $.mobile.widget, $.extend( {
	_create: function() {
		var $el = this.element.addClass( "ui-collapsible-set" ),
			o = this.options;

		// Inherit the theme from collapsible-set
		if ( !o.theme ) {
			o.theme = $.mobile.getInheritedTheme( $el, "c" );
		}
		// Inherit the content-theme from collapsible-set
		if ( !o.contentTheme ) {
			o.contentTheme = $el.jqmData( "content-theme" );
		}
		// Inherit the corner styling from collapsible-set
		if ( !o.corners ) {
			o.corners = $el.jqmData( "corners" );
		}

		if ( $el.jqmData( "inset" ) !== undefined ) {
			o.inset = $el.jqmData( "inset" );
		}
		o.inset = o.inset !== undefined ? o.inset : true;
		o.corners = o.corners !== undefined ? o.corners : true;

		if ( !!o.corners && !!o.inset ) {
			$el.addClass( "ui-corner-all" );
		}

		// Initialize the collapsible set if it's not already initialized
		if ( !$el.jqmData( "collapsiblebound" ) ) {
			$el
				.jqmData( "collapsiblebound", true )
				.bind( "expand", function( event ) {
					var closestCollapsible = $( event.target )
						.closest( ".ui-collapsible" );
					if ( closestCollapsible.parent().is( ":mobile-collapsibleset, :jqmData(role='collapsible-set')" ) ) {
						closestCollapsible
							.siblings( ".ui-collapsible:not(.ui-collapsible-collapsed)" )
							.trigger( "collapse" );
					}
				});
		}
	},

	_init: function() {
		var $el = this.element,
			collapsiblesInSet = $el.children( ":mobile-collapsible, :jqmData(role='collapsible')" ),
			expanded = collapsiblesInSet.filter( ":jqmData(collapsed='false')" );
		this._refresh( "true" );

		// Because the corners are handled by the collapsible itself and the default state is collapsed
		// That was causing https://github.com/jquery/jquery-mobile/issues/4116
		expanded.trigger( "expand" );
	},

	_refresh: function( create ) {
		var collapsiblesInSet = this.element.children( ":mobile-collapsible, :jqmData(role='collapsible')" );

		$.mobile.collapsible.prototype.enhance( collapsiblesInSet.not( ".ui-collapsible" ) );

		this._addFirstLastClasses( collapsiblesInSet, this._getVisibles( collapsiblesInSet, create ), create );
	},

	refresh: function() {
		this._refresh( false );
	}
}, $.mobile.behaviors.addFirstLastClasses ) );

$.mobile.collapsibleset.initSelector = ":jqmData(role='collapsible-set')";

//auto self-init widgets
$.mobile._enhancer.add( "mobile.collapsibleset" );

})( jQuery );
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");
<|endoftext|>


<commit_before>/*global describe, it*/
var File = require('vinyl');
var assert = require('assert');
var cwd = process.cwd() + '/test/fixtures';
var fs = require('fs');
var templates = require('../');
var vfs = require('vinyl-fs');

describe('gulp-ng-template-strings', function() {
    it('should inline template contents into js file', function(done) {
        vfs.src('has-template-urls.js', {cwd:cwd})
            .pipe(templates())
            .on('data', function(file) {
                assert.equal(
                    file.contents.toString('utf8'),
                    fs.readFileSync(cwd + '/expected/has-template-urls.js', 'utf8'));
                done();
            });
    });

    it('should pass js without template urls through unchanged', function(done) {
        var path = 'no-template-urls.js';
        vfs.src(path, {cwd:cwd})
            .pipe(templates())
            .on('data', function(file) {
                assert.equal(
                    file.contents.toString('utf8'),
                    fs.readFileSync(cwd + '/' + path, 'utf8'));
                done();
            });
    });

    it('should emit an error when input is streaming', function(done) {
        templates()
            .on('error', function(err) {
                assert(err);
                done();
            })
            .write(new File({
                contents: fs.createReadStream(cwd + '/has-template-urls.js')
            }));
    });
});
<commit_msg>add use strict<commit_after>/*global describe, it*/
'use strict';
var File = require('vinyl');
var assert = require('assert');
var cwd = process.cwd() + '/test/fixtures';
var fs = require('fs');
var templates = require('../');
var vfs = require('vinyl-fs');

describe('gulp-ng-template-strings', function() {
    it('should inline template contents into js file', function(done) {
        vfs.src('has-template-urls.js', {cwd:cwd})
            .pipe(templates())
            .on('data', function(file) {
                assert.equal(
                    file.contents.toString('utf8'),
                    fs.readFileSync(cwd + '/expected/has-template-urls.js', 'utf8'));
                done();
            });
    });

    it('should pass js without template urls through unchanged', function(done) {
        var path = 'no-template-urls.js';
        vfs.src(path, {cwd:cwd})
            .pipe(templates())
            .on('data', function(file) {
                assert.equal(
                    file.contents.toString('utf8'),
                    fs.readFileSync(cwd + '/' + path, 'utf8'));
                done();
            });
    });

    it('should emit an error when input is streaming', function(done) {
        templates()
            .on('error', function(err) {
                assert(err);
                done();
            })
            .write(new File({
                contents: fs.createReadStream(cwd + '/has-template-urls.js')
            }));
    });
});
<|endoftext|>


<commit_before>import _ from 'lodash'
import stringify from 'fast-stable-stringify'

import { memorize } from '.'

export const buildIndex = (docs, fields, isUnique) => {
  fields = Array.isArray(fields) ? fields : [fields]
  const field = fields[0]
  if (fields.length === 1) {
    return isUnique ? _.keyBy(docs, field) : _.groupBy(docs, field)
  }
  const restSteps = fields.slice(1)
  const groups = _.groupBy(docs, field)
  return _.mapValues(groups, groupDocs => buildIndex(groupDocs, restSteps, isUnique))
}

export const recall = (coll, fnName, ...args) => {
  return memorize(coll, `${fnName}-${stringify(args)}`, state => coll[fnName](state.byId, ...args))
}
<commit_msg>fix: recall with 'buildIndex' even not yet define buildIndex function in collection<commit_after>import _ from 'lodash'
import stringify from 'fast-stable-stringify'

import { memorize } from '.'

export const buildIndex = (docs, fields, isUnique) => {
  fields = Array.isArray(fields) ? fields : [fields]
  const field = fields[0]
  if (fields.length === 1) {
    return isUnique ? _.keyBy(docs, field) : _.groupBy(docs, field)
  }
  const restSteps = fields.slice(1)
  const groups = _.groupBy(docs, field)
  return _.mapValues(groups, groupDocs => buildIndex(groupDocs, restSteps, isUnique))
}

export const recall = (coll, fnName, ...args) => {
  const func = coll[fnName] || (fnName === 'buildIndex' ? buildIndex : null)
  if (process.env.NODE_ENV !== 'production' && typeof func !== 'function') {
    console.error(`recall cannot find "${fnName}" in collection "${coll && coll.name}"`)
  }
  return memorize(coll, `${fnName}-${stringify(args)}`, state => func.apply(coll, [state.byId, ...args]))
}
<|endoftext|>