<commit_before>/*
http://github.com/isaacs/npm/issues/issue/7

npm update [pkg]

Does the following:

1. check for a new version of pkg
2. if not found, then quit
3. install new version of pkg
4. For each other version of pkg, for each dependent in
  other version's dependents folder, if the new version
  would satisfy the dependency as well, update other
  version's dependent's dependency links to point at the
  new version
5. If no dependents are left, then remove old version

If no packages are specified, then run for all installed
packages.

Depending on config value, update-dependents, run steps 4-5
after installation

* always - Run an update after every install, so as to
  minimize the different number of versions of things.
* true - Default, run if newly installed version is
  the highest version number (that is, don't downgrade
  by default)
* false - Don't run "update" automatically after
  installation.

*/

module.exports = update

var readInstalled = require("./utils/read-installed")
  , chain = require("./utils/chain")
  , log = require("./utils/log")
  , registry = require("./utils/registry")
  , npm = require("../npm")
  , semver = require("./utils/semver")
  , lifecycle = require("./utils/lifecycle")

function update (args, cb) {
  findUpdates(args, function (er, updates) {
    if (er) return log.er(cb, "failed to find updates")(er)
    if (!updates || Object.keys(updates).length === 0) return log(
      "Nothing to update", "update", cb)
    installUpdates(updates, cb)
  })
}
function installUpdates (updates, cb) {
  npm.config.set("update-dependents", true)
  var installList = []
    , updateList = []
    , preChain = []
    , postChain = []
    , fullList = []
  Object.keys(updates).forEach(function (i) {
    var u = updates[i]
    if (u.have.indexOf(u.latest) === -1) {
      installList.push(i+"@"+u.latest)
    } else {
      updateList.push(i+"@"+u.latest)
    }
    fullList.push(i+"@"+u.latest)
    preChain.push([lifecycle, u.pkg, "preupdate"])
    postChain.push( [lifecycle, u.pkg, "update"]
                  , [lifecycle, u.pkg, "postupdate"]
                  )
  })
  cb = (function (cb) { return function (er) {
    log(fullList.join(" "), er ? "failed to update" : "updated")
    cb(er)
  }})(cb)
  log(fullList.join(" "), "updates")
  chain(preChain.concat(function (er) {
    if (er) return cb(er)
    if (installList.length > 0) {
      return npm.commands.install(installList, function (er) {
        if (er) return log.er(cb, "install failed "+installList)(er)
        updateAndActivate(updateList, fullList, postChain, cb)
      })
    }
    updateAndActivate(updateList, fullList, postChain, cb)
  }))
}
function updateAndActivate (updateList, fullList, postChain, cb) {
  npm.commands["update-dependents"](updateList, function (er) {
    if (er) return log.er(cb, "update failed "+updateList)(er)
    npm.commands.activate(fullList, function (er) {
      if (er) return cb(er)
      chain(postChain.concat(cb))
    })
  })
}

function findUpdates (args, cb) {
  readInstalled(args, function (er, inst) {
    if (er) return log.er(cb, "Couldn't read installed packages")(er)
    var pkgs = Object.keys(inst)
      , p = pkgs.length
      , updates = {}
      , tag = npm.config.get("tag")
    function found () { if (--p === 0) cb(null, updates) }
    pkgs.forEach(function (pkg) {
      registry.get(pkg, function (er, data) {
        if (er) return log(pkg, "not in registry", found)
        var latest = data["dist-tags"] && data["dist-tags"][tag]
          , have = Object.keys(inst[pkg]).sort(semver.sort)
          , minHave = have[0]
        if (!latest || !semver.gt(latest, minHave)) return found()
        // we have something that's out of date.
        updates[pkg] = {latest:latest,have:have,pkg:data.versions[latest]}
        found()
      })
    })
  })
}

<commit_msg>Asynchronize<commit_after>/*
http://github.com/isaacs/npm/issues/issue/7

npm update [pkg]

Does the following:

1. check for a new version of pkg
2. if not found, then quit
3. install new version of pkg
4. For each other version of pkg, for each dependent in
  other version's dependents folder, if the new version
  would satisfy the dependency as well, update other
  version's dependent's dependency links to point at the
  new version
5. If no dependents are left, then remove old version

If no packages are specified, then run for all installed
packages.

Depending on config value, update-dependents, run steps 4-5
after installation

* always - Run an update after every install, so as to
  minimize the different number of versions of things.
* true - Default, run if newly installed version is
  the highest version number (that is, don't downgrade
  by default)
* false - Don't run "update" automatically after
  installation.

*/

module.exports = update

var readInstalled = require("./utils/read-installed")
  , chain = require("./utils/chain")
  , log = require("./utils/log")
  , registry = require("./utils/registry")
  , npm = require("../npm")
  , semver = require("./utils/semver")
  , lifecycle = require("./utils/lifecycle")
  , asyncMap = require("./utils/async-map")

function update (args, cb) {
  findUpdates(args, function (er, updates) {
    if (er) return log.er(cb, "failed to find updates")(er)
    if (!updates || Object.keys(updates).length === 0) return log(
      "Nothing to update", "update", cb)
    installUpdates(updates, cb)
  })
}
function installUpdates (updates, cb) {
  npm.config.set("update-dependents", true)
  var installList = []
    , updateList = []
    , preChain = []
    , postChain = []
    , fullList = []
  updates.forEach(function (u) {
    if (u.have.indexOf(u.latest) === -1) {
      installList.push(u.name+"@"+u.latest)
    } else {
      updateList.push(u.name+"@"+u.latest)
    }
    fullList.push(u.name+"@"+u.latest)
    preChain.push([lifecycle, u.pkg, "preupdate"])
    postChain.push( [lifecycle, u.pkg, "update"]
                  , [lifecycle, u.pkg, "postupdate"]
                  )
  })
  cb = (function (cb) { return function (er) {
    log(fullList.join(" "), er ? "failed to update" : "updated")
    cb(er)
  }})(cb)
  log(fullList.join(" "), "updates")
  chain(preChain.concat(function (er) {
    if (er) return cb(er)
    if (installList.length > 0) {
      return npm.commands.install(installList, function (er) {
        if (er) return log.er(cb, "install failed "+installList)(er)
        updateAndActivate(updateList, fullList, postChain, cb)
      })
    }
    updateAndActivate(updateList, fullList, postChain, cb)
  }))
}
function updateAndActivate (updateList, fullList, postChain, cb) {
  npm.commands["update-dependents"](updateList, function (er) {
    if (er) return log.er(cb, "update failed "+updateList)(er)
    npm.commands.activate(fullList, function (er) {
      if (er) return cb(er)
      chain(postChain.concat(cb))
    })
  })
}

function findUpdates (args, cb) {
  readInstalled(args, function (er, inst) {
    if (er) return log.er(cb, "Couldn't read installed packages")(er)
    var tag = npm.config.get("tag")
    asyncMap(Object.keys(inst), function (pkg, cb) {
      log.verbose(pkg, "find updates")
      registry.get(pkg, function (er, data) {
        if (er) return log.verbose(pkg, "not in registry", cb)
        var latest = data["dist-tags"] && data["dist-tags"][tag]
          , have = Object.keys(inst[pkg]).sort(semver.sort)
          , minHave = have[0]
        log.verbose(latest, pkg+"@latest")
        log.verbose(minHave, pkg+" min installed")
        log.verbose(semver.gt(latest, minHave), pkg+" latest > minHave")
        if (!latest || !semver.gt(latest, minHave)) return cb()
        // we have something that's out of date.
        cb(null, { latest : latest
                 , have : have
                 , pkg : data.versions[latest]
                 , name : data.name
                 })
      })
    }, cb)
  })
}

<|endoftext|>


<commit_before>'use strict';

var async = require('async');
var request = require('supertest');

module.exports = function updateAccount(serviceData, cursor, queues, cb) {

  var url = '/v1/people/~/connections?oauth2_access_token=' + serviceData.access_token + '&format=json';
  cursor = null;
  if(cursor !== null) {
    url += '&modified=new&modified-since=' + cursor;
  }
  cursor = new Date().getTime();

  async.waterfall([
   function getConnections(cb) {
    request('https://api.linkedin.com')
    .get(url)
    .expect(200)
    .end(cb);
  },
  function parseConnections(res, cb) {
    if(res.body.values && res.body.values.length > 0) {
      res.body.values.forEach(function(contact) {
        if(contact.id !== 'private') {
          queues.addition.push(contact);
        }
      });
    }
    cb(null, cursor, serviceData.accessToken);
  },
  ], cb);
};
<commit_msg>Woops<commit_after>'use strict';

var async = require('async');
var request = require('supertest');

module.exports = function updateAccount(serviceData, cursor, queues, cb) {

  var url = '/v1/people/~/connections?oauth2_access_token=' + serviceData.access_token + '&format=json';

  if(cursor !== null) {
    url += '&modified=new&modified-since=' + cursor;
  }
  cursor = new Date().getTime();

  async.waterfall([
   function getConnections(cb) {
    request('https://api.linkedin.com')
    .get(url)
    .expect(200)
    .end(cb);
  },
  function parseConnections(res, cb) {
    if(res.body.values && res.body.values.length > 0) {
      res.body.values.forEach(function(contact) {
        if(contact.id !== 'private') {
          queues.addition.push(contact);
        }
      });
    }
    cb(null, cursor, serviceData.accessToken);
  },
  ], cb);
};
<|endoftext|>


<commit_before>/**
 * In Node environment for default parameter for function are "In Progress".
 * Command to run the program:
 * node --harmony_default_parameters index.js
 */
'use strict';

/* NOTES: Don't uncomment, its for understanding purpose.

// Both age and work are optional as they are given a default value if the parameter are not provided.
// The || operator will return second operand when first is false. The names parameter that are not
// explicitly provided are set to `undefined`.
function Person(name, age, work) {
  age = age || 18;
  work = work || "Engineer";
}

Tips:
- There is problem with above approach, when the age is set actually to 0, it will get replaced with 18
because 0 is false/undefined

// Below is a safe alternative.
function Person(name, age, work) {
  age = (typeof age !== "undefined") ? age || 18;
  work = (typeof work !== "undefined") ? work || "Engineer";
}

Tips:
- Above code needs lot of extra code to just perform basic operation
- Below is the default parameter in ES6
*/

// Assign the default parameter in the arguments.
function Person(name, age = 18, work = "Engineer") {
  console.log("My name is " + name + " and its my " + age + " birthday!");
  console.log("Currently, I work as " + work);
}

/**
 * name = "Ashwin Hegde", age is not passed so it default to 18, work is not passed so it default to Engineer
 */
Person("Ashwin Hegde");

/**
 * name = "Ashwin Hegde", age = 25 (Overrite the default), work is not passed so it default to Engineer
 */
Person("Ashwin Hegde", 25);

/**
 * name = "Ashwin Hegde", age = 25 (Overrite the default), work = Full Stack Engineer (Overrite the default)
 */
Person("Ashwin Hegde", 27, "Full Stack Engineer");

/**
 * name = "Ashwin Hegde", age is passed as undefined so it default to 18, work = Sr Engineer (Overrite the default)
 */
Person("Ashwin Hegde", undefined, "Sr Engineer");

/**
 * name = "Ashwin Hegde", age = null (Overrite the default), work = Sr Engineer (Overrite the default)
 */
Person("Ashwin Hegde", null, "Sr Engineer");
<commit_msg>Fixes typo<commit_after>/**
 * In Node environment for default parameter for function are "In Progress".
 * Command to run the program:
 * node --harmony_default_parameters eg1_function.js
 */
'use strict';

/* NOTES: Don't uncomment, its for understanding purpose.

// Both age and work are optional as they are given a default value if the parameter are not provided.
// The || operator will return second operand when first is false. The names parameter that are not
// explicitly provided are set to `undefined`.
function Person(name, age, work) {
  age = age || 18;
  work = work || "Engineer";
}

Tips:
- There is problem with above approach, when the age is set actually to 0, it will get replaced with 18
because 0 is false/undefined

// Below is a safe alternative.
function Person(name, age, work) {
  age = (typeof age !== "undefined") ? age || 18;
  work = (typeof work !== "undefined") ? work || "Engineer";
}

Tips:
- Above code needs lot of extra code to just perform basic operation
- Below is the default parameter in ES6
*/

// Assign the default parameter in the arguments.
function Person(name, age = 18, work = "Engineer") {
  console.log("My name is " + name + " and its my " + age + " birthday!");
  console.log("Currently, I work as " + work);
}

/**
 * name = "Ashwin Hegde", age is not passed so it default to 18, work is not passed so it default to Engineer
 */
Person("Ashwin Hegde");

/**
 * name = "Ashwin Hegde", age = 25 (Overrite the default), work is not passed so it default to Engineer
 */
Person("Ashwin Hegde", 25);

/**
 * name = "Ashwin Hegde", age = 25 (Overrite the default), work = Full Stack Engineer (Overrite the default)
 */
Person("Ashwin Hegde", 27, "Full Stack Engineer");

/**
 * name = "Ashwin Hegde", age is passed as undefined so it default to 18, work = Sr Engineer (Overrite the default)
 */
Person("Ashwin Hegde", undefined, "Sr Engineer");

/**
 * name = "Ashwin Hegde", age = null (Overrite the default), work = Sr Engineer (Overrite the default)
 */
Person("Ashwin Hegde", null, "Sr Engineer");
<|endoftext|>


<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import BaseChartComponent from 'yarn-ui/components/base-chart-component';

export default BaseChartComponent.extend({
  CELL_WIDTH: 250,
  SAMPLE_CELL_WIDTH: 100,
  SAMPLE_HEIGHT: 30,
  CELL_HEIGHT: 30,
  CELL_MARGIN: 2,
  RACK_MARGIN: 20,
  filter: "",
  selectedCategory: 0,
  memoryLabel: "Memory",
  cpuLabel: "VCores",
  containersLabel: "Containers",
  totalContainers: 0,

  bindTP: function(element, cell) {
    var currentToolTip = this.tooltip;
    element.on("mouseover", function() {
      currentToolTip
        .style("left", (d3.event.pageX) + "px")
        .style("top", (d3.event.pageY - 28) + "px");
      cell.style("opacity", 1.0);
    }.bind(this))
      .on("mousemove", function() {
        // Handle pie chart case
        var text = cell.attr("tooltiptext");
        currentToolTip
            .style("background", "black")
            .style("opacity", 0.7);
        currentToolTip
            .html(text)
            .style('font-size', '12px')
            .style('color', 'white')
            .style('font-weight', '400');
        currentToolTip
            .style("left", (d3.event.pageX) + "px")
            .style("top", (d3.event.pageY - 28) + "px");
  }.bind(this))
      .on("mouseout", function() {
        currentToolTip.style("opacity", 0);
        cell.style("opacity", 0.8);
      }.bind(this));
  },

  bindSelectCategory: function(element, i) {
    element.on("click", function() {
      if (this.selectedCategory === i) {
        // Remove selection for second click
        this.selectedCategory = 0;
      } else {
        this.selectedCategory = i;
      }
      this.didInsertElement();
    }.bind(this));
  },

  isNodeSelected: function(node) {
    if (this.filter) {
      var rack = node.get("rack");
      var host = node.get("nodeHostName");
      if (!rack.includes(this.filter) && !host.includes(this.filter)) {
        return false;
      }
    }

    if (this.selectedCategory === 0) {
      return true;
    }

    var usage = this.calcUsage(node);
    var lowerLimit = (this.selectedCategory - 1) * 0.2;
    var upperLimit = this.selectedCategory * 0.2;
    if (lowerLimit <= usage && usage <= upperLimit) {
      return true;
    }
    return false;
  },

  // data:
  //    [{label=label1, value=value1}, ...]
  //    ...
  renderCells: function (model, title) {
    var selectedOption = d3.select("select").property("value");
    var data = [];
    model.forEach(function (o) {
      data.push(o);
    });

    this.chart.g.remove();
    this.chart.g = this.chart.svg.append("g");
    var g = this.chart.g;
    var layout = this.getLayout();
    layout.margin = 50;

    let racks = new Set();
    for (var i = 0; i < data.length; i++) {
      racks.add(data[i].get("rack"));
    }

    let racksArray = [];
    racks.forEach(v => racksArray.push(v));

    var xOffset = layout.margin;
    var yOffset = layout.margin * 3;

    var gradientStartColor = "#60cea5";
    var gradientEndColor = "#ffbc0b";

    var colorFunc = d3.interpolateRgb(d3.rgb(gradientStartColor), d3.rgb(gradientEndColor));

    var sampleXOffset = (layout.x2 - layout.x1) / 2 - 2.5 * this.SAMPLE_CELL_WIDTH -
      2 * this.CELL_MARGIN;
    var sampleYOffset = layout.margin * 2;
    var text;

    for (i = 1; i <= 5; i++) {
      var ratio = i * 0.2 - 0.1;

      var rect = g.append("rect")
        .attr("x", sampleXOffset)
        .attr("y", sampleYOffset)
        .attr("fill", this.selectedCategory === i ? "#26bbf0" : colorFunc(ratio))
        .attr("width", this.SAMPLE_CELL_WIDTH)
        .attr("height", this.SAMPLE_HEIGHT)
        .attr("class", "hyperlink");
      this.bindSelectCategory(rect, i);
      text = g.append("text")
        .text("" + (ratio * 100).toFixed(1) + "% Used")
        .attr("y", sampleYOffset + this.SAMPLE_HEIGHT / 2 + 5)
        .attr("x", sampleXOffset + this.SAMPLE_CELL_WIDTH / 2)
        .attr("class", "heatmap-cell hyperlink");
      this.bindSelectCategory(text, i);
      sampleXOffset += this.CELL_MARGIN + this.SAMPLE_CELL_WIDTH;
    }

    if (this.selectedCategory !== 0) {
      text = g.append("text")
        .text("Clear")
        .attr("y", sampleYOffset + this.SAMPLE_HEIGHT / 2 + 5)
        .attr("x", sampleXOffset + 20)
        .attr("class", "heatmap-clear hyperlink");
      this.bindSelectCategory(text, 0);
    }

    var chartXOffset = -1;

    this.totalContainers = 0;
    for (i = 0; i < racksArray.length; i++) {
      text = g.append("text")
        .text(racksArray[i])
        .attr("y", yOffset + this.CELL_HEIGHT / 2 + 5)
        .attr("x", layout.margin)
        .attr("class", "heatmap-rack");

      if (-1 === chartXOffset) {
        chartXOffset = layout.margin + text.node().getComputedTextLength() + 30;
      }

      xOffset = chartXOffset;

      for (var j = 0; j < data.length; j++) {
        var rack = data[j].get("rack");

        if (rack === racksArray[i]) {
          this.totalContainers += data[j].get("numContainers");
          this.addNode(g, xOffset, yOffset, colorFunc, data[j]);
          xOffset += this.CELL_MARGIN + this.CELL_WIDTH;
          if (xOffset + this.CELL_MARGIN + this.CELL_WIDTH >= layout.x2 -
            layout.margin) {
            xOffset = chartXOffset;
            yOffset = yOffset + this.CELL_MARGIN + this.CELL_HEIGHT;
          }

        }
      }

      while (xOffset > chartXOffset && xOffset + this.CELL_MARGIN +
        this.CELL_WIDTH < layout.x2 - layout.margin) {
        this.addPlaceholderNode(g, xOffset, yOffset);
        xOffset += this.CELL_MARGIN + this.CELL_WIDTH;
      }

      if (xOffset !== chartXOffset) {
        xOffset = chartXOffset;
        yOffset += this.CELL_MARGIN + this.CELL_HEIGHT;
      }
      yOffset += this.RACK_MARGIN;
    }

    layout.y2 = yOffset + layout.margin;
    this.adjustMaxHeight(layout.y2);
    this.renderTitleAndBG(g, title + selectedOption + ")" , layout, false);
  },

  addNode: function (g, xOffset, yOffset, colorFunc, data) {
    var rect = g.append("rect")
      .attr("y", yOffset)
      .attr("x", xOffset)
      .attr("height", this.CELL_HEIGHT)
      .attr("fill", colorFunc(this.calcUsage(data)))
      .attr("width", this.CELL_WIDTH)
      .attr("tooltiptext", data.get("toolTipText") + this.getToolTipText(data));

    if (this.isNodeSelected(data)) {
      rect.style("opacity", 0.8);
      this.bindTP(rect, rect);
    } else {
      rect.style("opacity", 0.8);
      rect.attr("fill", "DimGray");
    }
    var node_id = data.get("id"),
        node_addr = data.get("nodeHTTPAddress"),
        href = `#/yarn-node/${node_id}/${node_addr}`;
    var a = g.append("a")
      .attr("href", href);
    a.append("text")
      .text(data.get("nodeHostName"))
      .attr("y", yOffset + this.CELL_HEIGHT / 2 + 5)
      .attr("x", xOffset + this.CELL_WIDTH / 2)
      .attr("class", this.isNodeSelected(data) ? "heatmap-cell" : "heatmap-cell-notselected");
    if (this.isNodeSelected(data)) {
      this.bindTP(a, rect);
    }
  },

  addPlaceholderNode: function(g, xOffset, yOffset) {
    g.append("rect")
      .attr("y", yOffset)
      .attr("x", xOffset)
      .attr("height", this.CELL_HEIGHT)
      .attr("fill", "grey")
      .attr("width", this.CELL_WIDTH)
      .style("opacity", 0.20);
  },

  draw: function() {
    this.initChart(true);
    this.renderCells(this.get("model"), this.get("title"), this.get("textWidth"));
  },

  didInsertElement: function () {
    var self = this;
    var optionsData = [this.memoryLabel, this.cpuLabel, this.containersLabel];
    d3.select("#heatmap-select")
      .on('change', function() {
        self.renderCells(self.get("model"), self.get("title"), self.get("textWidth"));
      })
      .selectAll('option')
      .data(optionsData).enter()
      .append('option')
      .text(function (d) { return d; });

    this.draw();
  },

  actions: {
    applyFilter: function(event) {
      this.filter = event.srcElement.value;
      this.selectedCategory = 0;
      this.didInsertElement();
    }
  },

  calcUsage: function(data) {
    var selectedOption = d3.select('select').property("value");
    if (selectedOption === this.memoryLabel) {
      return data.get("usedMemoryMB") /
        (data.get("usedMemoryMB") + data.get("availMemoryMB"));
    }
    else if (selectedOption === this.cpuLabel) {
      return data.get("usedVirtualCores") /
        (data.get("usedVirtualCores") + data.get("availableVirtualCores"));
    }
    else if (selectedOption === this.containersLabel) {
      var totalContainers = this.totalContainers;
      if (totalContainers === 0) { return 0; }
      return data.get("numContainers") / totalContainers;
    }
  },

  getToolTipText: function(data) {
    var selectedOption = d3.select('select').property("value");
    if (selectedOption === this.memoryLabel) {
      return "
Used Memory: " + Math.round(data.get("usedMemoryMB")) + " MB
" +
        "
Available Memory: " + Math.round(data.get("availMemoryMB")) + " MB
";
    }
    else if (selectedOption === this.cpuLabel) {
      return "
Used VCores: " + Math.round(data.get("usedVirtualCores")) + " VCores
" +
        "
Available VCores: " + Math.round(data.get("availableVirtualCores")) + " VCores
";
    }
    else if (selectedOption === this.containersLabel) {
        return "
Containers: " + Math.round(data.get("numContainers")) + " Containers
" +
          "
Total Containers: " + this.totalContainers + " Containers
";
    }
  }
});
<commit_msg>YARN-8182. [UI2] Proxy- Clicking on nodes under Nodes HeatMap gives 401 error. Contributed by Sunil G.<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import BaseChartComponent from 'yarn-ui/components/base-chart-component';

export default BaseChartComponent.extend({
  CELL_WIDTH: 250,
  SAMPLE_CELL_WIDTH: 100,
  SAMPLE_HEIGHT: 30,
  CELL_HEIGHT: 30,
  CELL_MARGIN: 2,
  RACK_MARGIN: 20,
  filter: "",
  selectedCategory: 0,
  memoryLabel: "Memory",
  cpuLabel: "VCores",
  containersLabel: "Containers",
  totalContainers: 0,

  bindTP: function(element, cell) {
    var currentToolTip = this.tooltip;
    element.on("mouseover", function() {
      currentToolTip
        .style("left", (d3.event.pageX) + "px")
        .style("top", (d3.event.pageY - 28) + "px");
      cell.style("opacity", 1.0);
    }.bind(this))
      .on("mousemove", function() {
        // Handle pie chart case
        var text = cell.attr("tooltiptext");
        currentToolTip
            .style("background", "black")
            .style("opacity", 0.7);
        currentToolTip
            .html(text)
            .style('font-size', '12px')
            .style('color', 'white')
            .style('font-weight', '400');
        currentToolTip
            .style("left", (d3.event.pageX) + "px")
            .style("top", (d3.event.pageY - 28) + "px");
  }.bind(this))
      .on("mouseout", function() {
        currentToolTip.style("opacity", 0);
        cell.style("opacity", 0.8);
      }.bind(this));
  },

  bindSelectCategory: function(element, i) {
    element.on("click", function() {
      if (this.selectedCategory === i) {
        // Remove selection for second click
        this.selectedCategory = 0;
      } else {
        this.selectedCategory = i;
      }
      this.didInsertElement();
    }.bind(this));
  },

  isNodeSelected: function(node) {
    if (this.filter) {
      var rack = node.get("rack");
      var host = node.get("nodeHostName");
      if (!rack.includes(this.filter) && !host.includes(this.filter)) {
        return false;
      }
    }

    if (this.selectedCategory === 0) {
      return true;
    }

    var usage = this.calcUsage(node);
    var lowerLimit = (this.selectedCategory - 1) * 0.2;
    var upperLimit = this.selectedCategory * 0.2;
    if (lowerLimit <= usage && usage <= upperLimit) {
      return true;
    }
    return false;
  },

  // data:
  //    [{label=label1, value=value1}, ...]
  //    ...
  renderCells: function (model, title) {
    var selectedOption = d3.select("select").property("value");
    var data = [];
    model.forEach(function (o) {
      data.push(o);
    });

    this.chart.g.remove();
    this.chart.g = this.chart.svg.append("g");
    var g = this.chart.g;
    var layout = this.getLayout();
    layout.margin = 50;

    let racks = new Set();
    for (var i = 0; i < data.length; i++) {
      racks.add(data[i].get("rack"));
    }

    let racksArray = [];
    racks.forEach(v => racksArray.push(v));

    var xOffset = layout.margin;
    var yOffset = layout.margin * 3;

    var gradientStartColor = "#60cea5";
    var gradientEndColor = "#ffbc0b";

    var colorFunc = d3.interpolateRgb(d3.rgb(gradientStartColor), d3.rgb(gradientEndColor));

    var sampleXOffset = (layout.x2 - layout.x1) / 2 - 2.5 * this.SAMPLE_CELL_WIDTH -
      2 * this.CELL_MARGIN;
    var sampleYOffset = layout.margin * 2;
    var text;

    for (i = 1; i <= 5; i++) {
      var ratio = i * 0.2 - 0.1;

      var rect = g.append("rect")
        .attr("x", sampleXOffset)
        .attr("y", sampleYOffset)
        .attr("fill", this.selectedCategory === i ? "#26bbf0" : colorFunc(ratio))
        .attr("width", this.SAMPLE_CELL_WIDTH)
        .attr("height", this.SAMPLE_HEIGHT)
        .attr("class", "hyperlink");
      this.bindSelectCategory(rect, i);
      text = g.append("text")
        .text("" + (ratio * 100).toFixed(1) + "% Used")
        .attr("y", sampleYOffset + this.SAMPLE_HEIGHT / 2 + 5)
        .attr("x", sampleXOffset + this.SAMPLE_CELL_WIDTH / 2)
        .attr("class", "heatmap-cell hyperlink");
      this.bindSelectCategory(text, i);
      sampleXOffset += this.CELL_MARGIN + this.SAMPLE_CELL_WIDTH;
    }

    if (this.selectedCategory !== 0) {
      text = g.append("text")
        .text("Clear")
        .attr("y", sampleYOffset + this.SAMPLE_HEIGHT / 2 + 5)
        .attr("x", sampleXOffset + 20)
        .attr("class", "heatmap-clear hyperlink");
      this.bindSelectCategory(text, 0);
    }

    var chartXOffset = -1;

    this.totalContainers = 0;
    for (i = 0; i < racksArray.length; i++) {
      text = g.append("text")
        .text(racksArray[i])
        .attr("y", yOffset + this.CELL_HEIGHT / 2 + 5)
        .attr("x", layout.margin)
        .attr("class", "heatmap-rack");

      if (-1 === chartXOffset) {
        chartXOffset = layout.margin + text.node().getComputedTextLength() + 30;
      }

      xOffset = chartXOffset;

      for (var j = 0; j < data.length; j++) {
        var rack = data[j].get("rack");

        if (rack === racksArray[i]) {
          this.totalContainers += data[j].get("numContainers");
          this.addNode(g, xOffset, yOffset, colorFunc, data[j]);
          xOffset += this.CELL_MARGIN + this.CELL_WIDTH;
          if (xOffset + this.CELL_MARGIN + this.CELL_WIDTH >= layout.x2 -
            layout.margin) {
            xOffset = chartXOffset;
            yOffset = yOffset + this.CELL_MARGIN + this.CELL_HEIGHT;
          }

        }
      }

      while (xOffset > chartXOffset && xOffset + this.CELL_MARGIN +
        this.CELL_WIDTH < layout.x2 - layout.margin) {
        this.addPlaceholderNode(g, xOffset, yOffset);
        xOffset += this.CELL_MARGIN + this.CELL_WIDTH;
      }

      if (xOffset !== chartXOffset) {
        xOffset = chartXOffset;
        yOffset += this.CELL_MARGIN + this.CELL_HEIGHT;
      }
      yOffset += this.RACK_MARGIN;
    }

    layout.y2 = yOffset + layout.margin;
    this.adjustMaxHeight(layout.y2);
    this.renderTitleAndBG(g, title + selectedOption + ")" , layout, false);
  },

  addNode: function (g, xOffset, yOffset, colorFunc, data) {
    var rect = g.append("rect")
      .attr("y", yOffset)
      .attr("x", xOffset)
      .attr("height", this.CELL_HEIGHT)
      .attr("fill", colorFunc(this.calcUsage(data)))
      .attr("width", this.CELL_WIDTH)
      .attr("tooltiptext", data.get("toolTipText") + this.getToolTipText(data));

    if (this.isNodeSelected(data)) {
      rect.style("opacity", 0.8);
      this.bindTP(rect, rect);
    } else {
      rect.style("opacity", 0.8);
      rect.attr("fill", "DimGray");
    }
    var node_id = data.get("id"),
        node_addr = encodeURIComponent(data.get("nodeHTTPAddress")),
        href = `#/yarn-node/${node_id}/${node_addr}/info`;
    var a = g.append("a")
      .attr("href", href);
    a.append("text")
      .text(data.get("nodeHostName"))
      .attr("y", yOffset + this.CELL_HEIGHT / 2 + 5)
      .attr("x", xOffset + this.CELL_WIDTH / 2)
      .attr("class", this.isNodeSelected(data) ? "heatmap-cell" : "heatmap-cell-notselected");
    if (this.isNodeSelected(data)) {
      this.bindTP(a, rect);
    }
  },

  addPlaceholderNode: function(g, xOffset, yOffset) {
    g.append("rect")
      .attr("y", yOffset)
      .attr("x", xOffset)
      .attr("height", this.CELL_HEIGHT)
      .attr("fill", "grey")
      .attr("width", this.CELL_WIDTH)
      .style("opacity", 0.20);
  },

  draw: function() {
    this.initChart(true);
    this.renderCells(this.get("model"), this.get("title"), this.get("textWidth"));
  },

  didInsertElement: function () {
    var self = this;
    var optionsData = [this.memoryLabel, this.cpuLabel, this.containersLabel];
    d3.select("#heatmap-select")
      .on('change', function() {
        self.renderCells(self.get("model"), self.get("title"), self.get("textWidth"));
      })
      .selectAll('option')
      .data(optionsData).enter()
      .append('option')
      .text(function (d) { return d; });

    this.draw();
  },

  actions: {
    applyFilter: function(event) {
      this.filter = event.srcElement.value;
      this.selectedCategory = 0;
      this.didInsertElement();
    }
  },

  calcUsage: function(data) {
    var selectedOption = d3.select('select').property("value");
    if (selectedOption === this.memoryLabel) {
      return data.get("usedMemoryMB") /
        (data.get("usedMemoryMB") + data.get("availMemoryMB"));
    }
    else if (selectedOption === this.cpuLabel) {
      return data.get("usedVirtualCores") /
        (data.get("usedVirtualCores") + data.get("availableVirtualCores"));
    }
    else if (selectedOption === this.containersLabel) {
      var totalContainers = this.totalContainers;
      if (totalContainers === 0) { return 0; }
      return data.get("numContainers") / totalContainers;
    }
  },

  getToolTipText: function(data) {
    var selectedOption = d3.select('select').property("value");
    if (selectedOption === this.memoryLabel) {
      return "
Used Memory: " + Math.round(data.get("usedMemoryMB")) + " MB
" +
        "
Available Memory: " + Math.round(data.get("availMemoryMB")) + " MB
";
    }
    else if (selectedOption === this.cpuLabel) {
      return "
Used VCores: " + Math.round(data.get("usedVirtualCores")) + " VCores
" +
        "
Available VCores: " + Math.round(data.get("availableVirtualCores")) + " VCores
";
    }
    else if (selectedOption === this.containersLabel) {
        return "
Containers: " + Math.round(data.get("numContainers")) + " Containers
" +
          "
Total Containers: " + this.totalContainers + " Containers
";
    }
  }
});
<|endoftext|>


<commit_before>/*global describe, it*/
var expect = require('../unexpected-with-plugins'),
    _ = require('lodash'),
    AssetGraph = require('../../lib/AssetGraph');

describe('relations/HtmlPictureSource test', function () {
    it('should handle a test case with an existing <picture><source src="..."></picture> construct', function (done) {
        new AssetGraph({root: __dirname + '/../../testdata/relations/HtmlPictureSource/'})
            .loadAssets('index.html')
            .populate({
                followRelations: function () {return false;}
            })
            .queue(function (assetGraph) {
                expect(assetGraph, 'to contain relations including unresolved', 'HtmlPictureSource', 2);
                assetGraph.findAssets({type: 'Html'})[0].url = 'http://example.com/foo/bar.html';
                assetGraph.findRelations({}, true).forEach(function (relation) {
                    relation.hrefType = 'relative';
                });
                expect(_.map(assetGraph.findRelations({}, true), 'href'), 'to equal', [
                    '../image.png',
                    '../otherImage.jpg'
                ]);
            })
            .run(done);
    });
});
<commit_msg>Fix HtmlPictureSource test, 25 failing [ci skip]<commit_after>/*global describe, it*/
const expect = require('../unexpected-with-plugins');
const _ = require('lodash');
const AssetGraph = require('../../lib/AssetGraph');

describe('relations/HtmlPictureSource test', function () {
    it('should handle a test case with an existing <picture><source src="..."></picture> construct', async function () {
        const assetGraph = await new AssetGraph({root: __dirname + '/../../testdata/relations/HtmlPictureSource/'})
            .loadAssets('index.html')
            .populate({
                startAssets: { isInitial: true },
                followRelations: () => false
            });

        expect(assetGraph, 'to contain relations including unresolved', 'HtmlPictureSource', 2);
        assetGraph.findAssets({type: 'Html'})[0].url = 'http://example.com/foo/bar.html';
        assetGraph.findRelations({}, true).forEach(function (relation) {
            relation.hrefType = 'relative';
        });
        expect(_.map(assetGraph.findRelations({}, true), 'href'), 'to equal', [
            '../image.png',
            '../otherImage.jpg'
        ]);
    });
});
<|endoftext|>


<commit_before>import test from 'ava';
import Cache from '../lib/Cache';

test.cb('infinite ranges should not be queried unnecessarily', t => {
	const cache = new Cache();

	cache.put({
		knowledge: { 'asdf:xyz!(:)': [ [ 12345, Infinity ] ] },
		indexes: { 'asdf:xyz!(:)': [] }
	});

	cache.onChange((changes) => {
		if (changes.queries && changes.queries['asdf:xyz!(:)']) {
			t.deepEqual(
				changes.queries['asdf:xyz!(:)'].arr,
				[ [ 12345, 20, 0 ] ]
			);
			t.end();
		}
	});

	cache.query('asdf:xyz!(:)', [ 12345, 20, 0 ], () => {});
});

test('should avoid duplicates', t => {
	const cache = new Cache();

	cache.put({
		knowledge: { 'asdf:xyz!(:)': [ [ 10, Infinity ] ] },
		indexes: { 'asdf:xyz!(:)': [
			{ id: 1, type: 'asdf', xyz: 10 },
			{ id: 2, type: 'asdf', xyz: 12 }
		] }
	});

	cache.put({
		knowledge: { 'asdf:xyz!(:)': [ [ 5, 10 ] ] },
		indexes: { 'asdf:xyz!(:)': [
			{ id: 5, type: 'asdf', xyz: 5 },
			{ id: 4, type: 'asdf', xyz: 7 },
			{ id: 1, type: 'asdf', xyz: 10 }
		] }
	});

	console.log(cache.indexes.arr);
	t.deepEqual(cache.indexes['asdf:xyz!(:)'].arr, [
		{ id: 5, type: 'asdf', xyz: 5 },
		{ id: 4, type: 'asdf', xyz: 7 },
		{ id: 1, type: 'asdf', xyz: 10 },
		{ id: 2, type: 'asdf', xyz: 12 }
	]);
});
<commit_msg>Update infibug.test.js<commit_after>import test from 'ava';
import Cache from '../lib/Cache';

test.cb('infinite ranges should not be queried unnecessarily', t => {
	const cache = new Cache();

	cache.put({
		knowledge: { 'asdf:xyz!(:)': [ [ 12345, Infinity ] ] },
		indexes: { 'asdf:xyz!(:)': [] }
	});

	cache.onChange((changes) => {
		if (changes.queries && changes.queries['asdf:xyz!(:)']) {
			t.deepEqual(
				changes.queries['asdf:xyz!(:)'].arr,
				[ [ 12345, 20, 0 ] ]
			);
			t.end();
		}
	});

	cache.query('asdf:xyz!(:)', [ 12345, 20, 0 ], () => {});
});

test('should avoid duplicates', t => {
	const cache = new Cache();

	cache.put({
		knowledge: { 'asdf:xyz!(:)': [ [ 10, Infinity ] ] },
		indexes: { 'asdf:xyz!(:)': [
			{ id: 1, type: 'asdf', xyz: 10 },
			{ id: 2, type: 'asdf', xyz: 12 }
		] }
	});

	cache.put({
		knowledge: { 'asdf:xyz!(:)': [ [ 5, 10 ] ] },
		indexes: { 'asdf:xyz!(:)': [
			{ id: 5, type: 'asdf', xyz: 5 },
			{ id: 4, type: 'asdf', xyz: 7 },
			{ id: 1, type: 'asdf', xyz: 10 }
		] }
	});

	t.deepEqual(cache.indexes['asdf:xyz!(:)'].arr, [
		{ id: 5, type: 'asdf', xyz: 5 },
		{ id: 4, type: 'asdf', xyz: 7 },
		{ id: 1, type: 'asdf', xyz: 10 },
		{ id: 2, type: 'asdf', xyz: 12 }
	]);
});
<|endoftext|>


<commit_before>dojo.provide("dijit.util.place");

// ported from dojo.html.util

dijit.util.getViewport = function(){
	//	summary
	//	Returns the dimensions of the viewable area of a browser window
	var _window = dojo.global;
	var _document = dojo.doc;
	var w = 0;
	var h = 0;

	if(dojo.isMozilla){
		// mozilla
		w = _document.documentElement.clientWidth;
		h = _window.innerHeight;
	}else if(!dojo.isOpera && _window.innerWidth){
		//in opera9, dojo.body().clientWidth should be used, instead
		//of window.innerWidth/document.documentElement.clientWidth
		//so we have to check whether it is opera
		w = _window.innerWidth;
		h = _window.innerHeight;
	}else if(dojo.body().clientWidth){
		// IE, Opera
		w = dojo.body().clientWidth;
		h = dojo.body().clientHeight;
	}
	return { w: w, h: h };	//	object
};

dijit.util.getScroll = function(){
	//	summary
	//	Returns the scroll position of the document
	var _window = dojo.global;
	var _document = dojo.doc;
	var top = _window.pageYOffset || _document.documentElement.scrollTop || dojo.body().scrollTop || 0;
	var left = _window.pageXOffset || _document.documentElement.scrollLeft || dojo.body().scrollLeft || 0;
	return {
		top: top,
		left: left,
		offset:{ x: left, y: top }	//	note the change, NOT an Array with added properties.
	};	//	object
};

dijit.util.placeOnScreen = function(
	/* HTMLElement */	node,
	/* integer */		desiredX,
	/* integer */		desiredY,
	/* integer */		padding,
	/* boolean? */		hasScroll,
	/* string? */		corners,
	/* boolean? */		tryOnly){
	//	summary:
	//		Keeps 'node' in the visible area of the screen while trying to
	//		place closest to desiredX, desiredY. The input coordinates are
	//		expected to be the desired screen position, not accounting for
	//		scrolling. If you already accounted for scrolling, set 'hasScroll'
	//		to true. Set padding to either a number or array for [paddingX, paddingY]
	//		to put some buffer around the element you want to position.
	//		Set which corner(s) you want to bind to, such as
	//
	//			placeOnScreen(node, desiredX, desiredY, padding, hasScroll, "TR")
	//			placeOnScreen(node, [desiredX, desiredY], padding, hasScroll, ["TR", "BL"])
	//
	//		The desiredX/desiredY will be treated as the topleft(TL)/topright(TR) or
	//		BottomLeft(BL)/BottomRight(BR) corner of the node. Each corner is tested
	//		and if a perfect match is found, it will be used. Otherwise, it goes through
	//		all of the specified corners, and choose the most appropriate one.
	//		By default, corner = ['TL'].
	//		If tryOnly is set to true, the node will not be moved to the place.
	//
	//		NOTE: node is assumed to be absolutely or relatively positioned.
	//
	//	Alternate call sig:
	//		 placeOnScreen(node, [x, y], padding, hasScroll)
	//
	//	Examples:
	//		 placeOnScreen(node, 100, 200)
	//		 placeOnScreen("myId", [800, 623], 5)
	//		 placeOnScreen(node, 234, 3284, [2, 5], true)

	// TODO: make this function have variable call sigs
	//	kes(node, ptArray, cornerArray, padding, hasScroll)
	//	kes(node, ptX, ptY, cornerA, cornerB, cornerC, paddingArray, hasScroll)
	if(dojo.isArray(desiredX)){
		tryOnly = corners;
		corners = hasScroll;
		hasScroll = padding;
		padding = desiredY;
		desiredY = desiredX[1];
		desiredX = desiredX[0];
	}

	if(dojo.isString(corners)){
		corners = corners.split(",");
	}

	if(!isNaN(padding)){
		padding = [Number(padding), Number(padding)];
	}else if(!dojo.isArray(padding)){
		padding = [0, 0];
	}

	var scroll = dijit.util.getScroll().offset;
	var view = dijit.util.getViewport();

	node = dojo.byId(node);
	var oldDisplay = node.style.display;
	var oldVis = node.style.visibility;
	node.style.visibility = "hidden";
	node.style.display = "";
//	var bb = dojo.html.getBorderBox(node);
	var bb = dojo.marginBox(node); //PORT okay?
	var w = bb.w;
	var h = bb.h;
	node.style.display = oldDisplay;
	node.style.visibility = oldVis;

	if(!dojo.isArray(corners)){
		corners = ['TL'];
	}

	var bestx, besty, bestDistance = Infinity, bestCorner;

	for(var cidex=0; cidex<corners.length; ++cidex){
		var corner = corners[cidex];
		var match = true;
		var tryX = desiredX - (corner.charAt(1)=='L' ? 0 : w) + padding[0]*(corner.charAt(1)=='L' ? 1 : -1);
		var tryY = desiredY - (corner.charAt(0)=='T' ? 0 : h) + padding[1]*(corner.charAt(0)=='T' ? 1 : -1);
		if(hasScroll){
			tryX -= scroll.x;
			tryY -= scroll.y;
		}

		if(tryX < 0){
			tryX = 0;
			match = false;
		}

		if(tryY < 0){
			tryY = 0;
			match = false;
		}

		var x = tryX + w;
		if(x > view.w){
			x = view.w - w;
			match = false;
		}else{
			x = tryX;
		}
		x = Math.max(padding[0], x) + scroll.x;

		var y = tryY + h;
		if(y > view.h){
			y = view.h - h;
			match = false;
		}else{
			y = tryY;
		}
		y = Math.max(padding[1], y) + scroll.y;

		if(match){ //perfect match, return now
			bestx = x;
			besty = y;
			bestDistance = 0;
			bestCorner = corner;
			break;
		}else{
			//not perfect, find out whether it is better than the saved one
			var dist = Math.pow(x-tryX-scroll.x,2)+Math.pow(y-tryY-scroll.y,2);
			if(bestDistance > dist){
				bestDistance = dist;
				bestx = x;
				besty = y;
				bestCorner = corner;
			}
		}
	}

	if(!tryOnly){
		node.style.left = bestx + "px";
		node.style.top = besty + "px";
	}

	return {left: bestx, top: besty, x: bestx, y: besty, dist: bestDistance, corner:  bestCorner};	//	object
}

dijit.util.placeOnScreenAroundElement = function(
	/* HTMLElement */node,
	/* HTMLElement */aroundNode,
	/* integer */padding,
	/* string? */aroundCorners,
	/* boolean? */tryOnly){
	//	summary
	//	Like placeOnScreen, except it accepts aroundNode instead of x,y
	//	and attempts to place node around it.  Uses margin box dimensions.
	//
	//	aroundCorners
	//		specify Which corner of aroundNode should be
	//		used to place the node => which corner(s) of node to use (see the
	//		corners parameter in dijit.util.placeOnScreen)
	//		e.g. {'TL': 'BL', 'BL': 'TL'}

	var best, bestDistance=Infinity;
	aroundNode = dojo.byId(aroundNode);
	var oldDisplay = aroundNode.style.display;
	aroundNode.style.display="";
	var mb = dojo.marginBox(aroundNode);
	var aroundNodeW = mb.w;
	var aroundNodeH = mb.h;
	var aroundNodePos = dojo.coords(aroundNode, true);
	aroundNode.style.display=oldDisplay;

	for(var nodeCorner in aroundCorners){
		var pos, desiredX, desiredY;
		var corners = aroundCorners[nodeCorner];

		desiredX = aroundNodePos.x + (nodeCorner.charAt(1)=='L' ? 0 : aroundNodeW);
		desiredY = aroundNodePos.y + (nodeCorner.charAt(0)=='T' ? 0 : aroundNodeH);

		pos = dijit.util.placeOnScreen(node, desiredX, desiredY, padding, true, corners, true);
		if(pos.dist == 0){
			best = pos;
			break;
		}else{
			//not perfect, find out whether it is better than the saved one
			if(bestDistance > pos.dist){
				bestDistance = pos.dist;
				best = pos;
			}
		}
	}

	if(!tryOnly){
		node.style.left = best.left + "px";
		node.style.top = best.top + "px";
	}
	return best;	//	object
}
<commit_msg>For placeOnScreen(), attach the node to document.body(). Otherwise, the positioning will be off, and it also might get cutoff (if it's inside a div with overflow: hidden). Not sure if this is the best solution but leaving this way for now. Fixes #3149.<commit_after>dojo.provide("dijit.util.place");

// ported from dojo.html.util

dijit.util.getViewport = function(){
	//	summary
	//	Returns the dimensions of the viewable area of a browser window
	var _window = dojo.global;
	var _document = dojo.doc;
	var w = 0;
	var h = 0;

	if(dojo.isMozilla){
		// mozilla
		w = _document.documentElement.clientWidth;
		h = _window.innerHeight;
	}else if(!dojo.isOpera && _window.innerWidth){
		//in opera9, dojo.body().clientWidth should be used, instead
		//of window.innerWidth/document.documentElement.clientWidth
		//so we have to check whether it is opera
		w = _window.innerWidth;
		h = _window.innerHeight;
	}else if(dojo.body().clientWidth){
		// IE, Opera
		w = dojo.body().clientWidth;
		h = dojo.body().clientHeight;
	}
	return { w: w, h: h };	//	object
};

dijit.util.getScroll = function(){
	//	summary
	//	Returns the scroll position of the document
	var _window = dojo.global;
	var _document = dojo.doc;
	var top = _window.pageYOffset || _document.documentElement.scrollTop || dojo.body().scrollTop || 0;
	var left = _window.pageXOffset || _document.documentElement.scrollLeft || dojo.body().scrollLeft || 0;
	return {
		top: top,
		left: left,
		offset:{ x: left, y: top }	//	note the change, NOT an Array with added properties.
	};	//	object
};

dijit.util.placeOnScreen = function(
	/* HTMLElement */	node,
	/* integer */		desiredX,
	/* integer */		desiredY,
	/* integer */		padding,
	/* boolean? */		hasScroll,
	/* string? */		corners,
	/* boolean? */		tryOnly){
	//	summary:
	//		Keeps 'node' in the visible area of the screen while trying to
	//		place closest to desiredX, desiredY. The input coordinates are
	//		expected to be the desired screen position, not accounting for
	//		scrolling. If you already accounted for scrolling, set 'hasScroll'
	//		to true. Set padding to either a number or array for [paddingX, paddingY]
	//		to put some buffer around the element you want to position.
	//		Set which corner(s) you want to bind to, such as
	//
	//			placeOnScreen(node, desiredX, desiredY, padding, hasScroll, "TR")
	//			placeOnScreen(node, [desiredX, desiredY], padding, hasScroll, ["TR", "BL"])
	//
	//		The desiredX/desiredY will be treated as the topleft(TL)/topright(TR) or
	//		BottomLeft(BL)/BottomRight(BR) corner of the node. Each corner is tested
	//		and if a perfect match is found, it will be used. Otherwise, it goes through
	//		all of the specified corners, and choose the most appropriate one.
	//		By default, corner = ['TL'].
	//		If tryOnly is set to true, the node will not be moved to the place.
	//
	//		NOTE: node is assumed to be absolutely or relatively positioned.
	//
	//	Alternate call sig:
	//		 placeOnScreen(node, [x, y], padding, hasScroll)
	//
	//	Examples:
	//		 placeOnScreen(node, 100, 200)
	//		 placeOnScreen("myId", [800, 623], 5)
	//		 placeOnScreen(node, 234, 3284, [2, 5], true)

	// TODO: make this function have variable call sigs
	//	kes(node, ptArray, cornerArray, padding, hasScroll)
	//	kes(node, ptX, ptY, cornerA, cornerB, cornerC, paddingArray, hasScroll)
	if(dojo.isArray(desiredX)){
		tryOnly = corners;
		corners = hasScroll;
		hasScroll = padding;
		padding = desiredY;
		desiredY = desiredX[1];
		desiredX = desiredX[0];
	}

	if(dojo.isString(corners)){
		corners = corners.split(",");
	}

	if(!isNaN(padding)){
		padding = [Number(padding), Number(padding)];
	}else if(!dojo.isArray(padding)){
		padding = [0, 0];
	}

	var scroll = dijit.util.getScroll().offset;
	var view = dijit.util.getViewport();

	node = dojo.byId(node);
	var oldDisplay = node.style.display;
	var oldVis = node.style.visibility;
	node.style.visibility = "hidden";
	node.style.display = "";
//	var bb = dojo.html.getBorderBox(node);
	var bb = dojo.marginBox(node); //PORT okay?
	var w = bb.w;
	var h = bb.h;
	node.style.display = oldDisplay;
	node.style.visibility = oldVis;

	if(!dojo.isArray(corners)){
		corners = ['TL'];
	}

	var bestx, besty, bestDistance = Infinity, bestCorner;

	for(var cidex=0; cidex<corners.length; ++cidex){
		var corner = corners[cidex];
		var match = true;
		var tryX = desiredX - (corner.charAt(1)=='L' ? 0 : w) + padding[0]*(corner.charAt(1)=='L' ? 1 : -1);
		var tryY = desiredY - (corner.charAt(0)=='T' ? 0 : h) + padding[1]*(corner.charAt(0)=='T' ? 1 : -1);
		if(hasScroll){
			tryX -= scroll.x;
			tryY -= scroll.y;
		}

		if(tryX < 0){
			tryX = 0;
			match = false;
		}

		if(tryY < 0){
			tryY = 0;
			match = false;
		}

		var x = tryX + w;
		if(x > view.w){
			x = view.w - w;
			match = false;
		}else{
			x = tryX;
		}
		x = Math.max(padding[0], x) + scroll.x;

		var y = tryY + h;
		if(y > view.h){
			y = view.h - h;
			match = false;
		}else{
			y = tryY;
		}
		y = Math.max(padding[1], y) + scroll.y;

		if(match){ //perfect match, return now
			bestx = x;
			besty = y;
			bestDistance = 0;
			bestCorner = corner;
			break;
		}else{
			//not perfect, find out whether it is better than the saved one
			var dist = Math.pow(x-tryX-scroll.x,2)+Math.pow(y-tryY-scroll.y,2);
			if(bestDistance > dist){
				bestDistance = dist;
				bestx = x;
				besty = y;
				bestCorner = corner;
			}
		}
	}

	if(!tryOnly){
		node.style.left = bestx + "px";
		node.style.top = besty + "px";
	}

	return {left: bestx, top: besty, x: bestx, y: besty, dist: bestDistance, corner:  bestCorner};	//	object
}

dijit.util.placeOnScreenAroundElement = function(
	/* HTMLElement */node,
	/* HTMLElement */aroundNode,
	/* integer */padding,
	/* string? */aroundCorners,
	/* boolean? */tryOnly){
	//	summary
	//	Like placeOnScreen, except it accepts aroundNode instead of x,y
	//	and attempts to place node around it.  Uses margin box dimensions.
	//
	//	aroundCorners
	//		specify Which corner of aroundNode should be
	//		used to place the node => which corner(s) of node to use (see the
	//		corners parameter in dijit.util.placeOnScreen)
	//		e.g. {'TL': 'BL', 'BL': 'TL'}

	// This won't work if the node is inside a <div style="position: relative>,
	// so reattach it to document.body.   (Otherwise, the positioning will be wrong
	// and also it might get cutoff)
	if(!node.parentNode || String(node.parentNode.tagName).toLowerCase() != "body"){
		dojo.body().appendChild(node);
	}

	var best, bestDistance=Infinity;
	aroundNode = dojo.byId(aroundNode);
	var oldDisplay = aroundNode.style.display;
	aroundNode.style.display="";
	var mb = dojo.marginBox(aroundNode);
	var aroundNodeW = mb.w;
	var aroundNodeH = mb.h;
	var aroundNodePos = dojo.coords(aroundNode, true);
	aroundNode.style.display=oldDisplay;

	for(var nodeCorner in aroundCorners){
		var pos, desiredX, desiredY;
		var corners = aroundCorners[nodeCorner];

		desiredX = aroundNodePos.x + (nodeCorner.charAt(1)=='L' ? 0 : aroundNodeW);
		desiredY = aroundNodePos.y + (nodeCorner.charAt(0)=='T' ? 0 : aroundNodeH);

		pos = dijit.util.placeOnScreen(node, desiredX, desiredY, padding, true, corners, true);
		if(pos.dist == 0){
			best = pos;
			break;
		}else{
			//not perfect, find out whether it is better than the saved one
			if(bestDistance > pos.dist){
				bestDistance = pos.dist;
				best = pos;
			}
		}
	}

	if(!tryOnly){
		node.style.left = best.left + "px";
		node.style.top = best.top + "px";
	}
	return best;	//	object
}
<|endoftext|>


<commit_before>'use strict';

var rlp = require('rlp');

var Contract = require('./contract.js');
var providers = require('./providers.js');
var SigningKey = require('./signing-key.js');

var utils = require('./utils.js');

// This ensures we inject a setImmediate into the global space, which
// dramatically improves the performance of the scrypt PBKDF.
require('setimmediate');

var transactionFields = [
    {name: 'nonce',    maxLength: 32, },
    {name: 'gasPrice', maxLength: 32, },
    {name: 'gasLimit', maxLength: 32, },
    {name: 'to',          length: 20, },
    {name: 'value',    maxLength: 32, },
    {name: 'data'},
];

function Wallet(privateKey, provider) {
    if (!(this instanceof Wallet)) { throw new Error('missing new'); }

    // Make sure we have a valid signing key
    var signingKey = privateKey;
    if (!(privateKey instanceof SigningKey)) {
        signingKey = new SigningKey(privateKey);
    }
    utils.defineProperty(this, 'privateKey', signingKey.privateKey);

    Object.defineProperty(this, 'provider', {
        enumerable: true,
        get: function() { return provider; },
        set: function(value) {
            if (value !== null && !providers.isProvider(value)) {
                throw new Error('invalid provider');
            }
            provider = value;
        }
    });

    Object.defineProperty(this, '_provider', {
        enumerable: true,
        get: function() {
            if (!provider) { throw new Error('missing provider'); }
            return provider;
        },
    });

    if (provider !== null) {

        // If no provider was provided, check for metamask or ilk
        if (provider === undefined) {
            if (global.web3 && global.web3.currentProvider && global.web3.currentProvider.sendAsync) {
                this.provider = new providers.Web3Provider(global.web3.currentProvider);
            }

        // An Ethereum RPC node
        } else if (typeof(provider) === 'string' && provider.match(/^https?:\/\//)) {
            this.provider = new providers.HttpProvider(provider);

        } else {
            this.provider = provider;
        }
    }

    utils.defineProperty(this, 'address', signingKey.address);

    utils.defineProperty(this, 'sign', function(transaction) {
        var raw = [];
        transactionFields.forEach(function(fieldInfo) {
            var value = transaction[fieldInfo.name] || (new Buffer(0));
            value = utils.hexOrBuffer(utils.hexlify(value), fieldInfo.name);

            // Fixed-width field
            if (fieldInfo.length && value.length !== fieldInfo.length) {
                var error = new Error('invalid ' + fieldInfo.name);
                error.reason = 'wrong length';
                error.value = value;
                throw error;
            }

            // Variable-width (with a maximum)
            if (fieldInfo.maxLength) {
                value = utils.stripZeros(value);
                if (value.length > fieldInfo.maxLength) {
                    var error = new Error('invalid ' + fieldInfo.name);
                    error.reason = 'too long';
                    error.value = value;
                    throw error;
                }
            }

            raw.push(value);
        });

        var digest = utils.sha3(rlp.encode(raw));

        var signature = signingKey.signDigest(digest);
        var s = signature.s;
        var v = signature.recoveryParam;

        raw.push(new Buffer([27 + v]));
        raw.push(utils.bnToBuffer(signature.r));
        raw.push(utils.bnToBuffer(s));

        return ('0x' + rlp.encode(raw).toString('hex'));
    });
}

utils.defineProperty(Wallet.prototype, 'getBalance', function(blockNumber) {
    var provider = this._provider;

    var self = this;
    return new Promise(function(resolve, reject) {
        provider.getBalance(self.address, blockNumber).then(function(balance) {
            resolve(balance);
        }, function(error) {
            reject(error);
        });
    });
});

utils.defineProperty(Wallet.prototype, 'getTransactionCount', function(blockNumber) {
    var provider = this._provider;

    var self = this;
    return new Promise(function(resolve, reject) {
        provider.getTransactionCount(self.address, blockNumber).then(function(transactionCount) {
            resolve(transactionCount);
        }, function(error) {
            reject(error);
        });
    });
});

utils.defineProperty(Wallet.prototype, 'estimateGas', function(transaction) {
    var provider = this._provider;

    transaction = utils.cloneObject(transaction);
    if (transaction.from == null) { transaction.from = this.address; }

    return new Promise(function(resolve, reject) {
        provider.estimateGas(transaction).then(function(gasEstimate) {
            resolve(gasEstimate);
        }, function(error) {
            reject(error);
        });
    });
});

utils.defineProperty(Wallet.prototype, 'sendTransaction', function(transaction) {
    var gasLimit = transaction.gasLimit;
    if (gasLimit == null) { gasLimit = 3000000; }

    var self = this;

    var provider = this._provider;

    var gasPrice = new Promise(function(resolve, reject) {
        if (transaction.gasPrice) {
            return resolve(transaction.gasPrice);
        }
        provider.getGasPrice().then(function(gasPrice) {
            resolve(gasPrice);
        }, function(error) {
            reject(error);
        });
    });

    var nonce = new Promise(function(resolve, reject) {
        if (transaction.nonce) {
            return resolve(transaction.nonce);
        }
        provider.getTransactionCount(self.address, 'pending').then(function(transactionCount) {
            resolve(transactionCount);
        }, function(error) {
            reject(error);
        });
    });

    return new Promise(function(resolve, reject) {
        Promise.all([gasPrice, nonce]).then(function(results) {
            var signedTransaction = self.sign({
                to: transaction.to,
                gasLimit: gasLimit,
                gasPrice: results[0],
                nonce: results[1],
                value: transaction.value
            });

            provider.sendTransaction(signedTransaction).then(function(txid) {
                resolve(txid);
            }, function(error) {
                reject(error);
            });

        }, function(error) {
            reject(error);
        });
    });
});

utils.defineProperty(Wallet.prototype, 'send', function(address, amountWei, options) {
    address = SigningKey.getAddress(address);
    if (utils.BN.isBN(amountWei)) {
        amountWei = '0x' + utils.bnToBuffer(amountWei).toString('hex');
    }
    if (!utils.isHexString(amountWei)) { throw new Error('invalid amountWei'); }

    if (!options) { options = {}; }

    return this.sendTransaction({
        to: address,
        gasLimit: options.gasLimit,
        gasPrice: options.gasPrice,
        nonce: options.nonce,
        value: amountWei,
    });
});

utils.defineProperty(Wallet.prototype, 'getContract', function(address, abi) {
    return new Contract(this, address, new Contract.Interface(abi));
});

utils.defineProperty(Wallet, 'getAddress', SigningKey.getAddress);
utils.defineProperty(Wallet, 'getIcapAddress', SigningKey.getIcapAddress);

utils.defineProperty(Wallet, '_Contract', Contract);

var zero = new utils.BN(0);
var negative1 = new utils.BN(-1);
var tenPower18 = new utils.BN('1000000000000000000');
utils.defineProperty(Wallet, 'formatEther', function(wei, options) {
    if (typeof(wei) === 'number') {
        // @TODO: Warn if truncation will occur?
        wei = new utils.BN(wei);
    } else if (utils.isHexString(wei)) {
        wei = new utils.BN(wei.substring(2));
    }
    if (!options) { options = {}; }

    if (!(wei instanceof utils.BN)) { throw new Error('invalid wei'); }

    var negative = wei.lt(zero);
    if (negative) { wei = wei.mul(negative1); }

    var fraction = wei.mod(tenPower18).toString(10);
    while (fraction.length < 18) { fraction = '0' + fraction; }

    if (!options.pad) {
        fraction = fraction.match(/^([0-9]*[1-9]|0)(0*)/)[1];
    }

    var whole = wei.div(tenPower18).toString(10);

    if (options.commify) {
        whole = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
    }

    var value = whole + '.' + fraction;

    if (negative) { value = '-' + value; }

    return value;
});

utils.defineProperty(Wallet, 'parseEther', function(ether) {
    if (typeof(ether) !== 'string' || !ether.match(/^-?[0-9.]+$/)) {
        throw new Error('invalid value');
    }

    // Is it negative?
    var negative = (ether.substring(0, 1) === '-');
    if (negative) { ether = ether.substring(1); }

    if (ether === '.') { throw new Error('invalid value'); }

    // Split it into a whole and fractional part
    var comps = ether.split('.');
    if (comps.length > 2) { throw new Error('too many decimal points'); }

    var whole = comps[0], fraction = comps[1];
    if (!whole) { whole = '0'; }
    if (!fraction) { fraction = '0'; }
    if (fraction.length > 18) { throw new Error('too many decimal places'); }

    while (fraction.length < 18) { fraction += '0'; }

    whole = new utils.BN(whole);
    fraction = new utils.BN(fraction);

    var wei = (whole.mul(tenPower18)).add(fraction);

    if (negative) { wei = wei.mul(negative1); }

    return wei;
});

module.exports = Wallet;
<commit_msg>Fixed bug when passing in hex string to formatEther.<commit_after>'use strict';

var rlp = require('rlp');

var Contract = require('./contract.js');
var providers = require('./providers.js');
var SigningKey = require('./signing-key.js');

var utils = require('./utils.js');

// This ensures we inject a setImmediate into the global space, which
// dramatically improves the performance of the scrypt PBKDF.
require('setimmediate');

var transactionFields = [
    {name: 'nonce',    maxLength: 32, },
    {name: 'gasPrice', maxLength: 32, },
    {name: 'gasLimit', maxLength: 32, },
    {name: 'to',          length: 20, },
    {name: 'value',    maxLength: 32, },
    {name: 'data'},
];

function Wallet(privateKey, provider) {
    if (!(this instanceof Wallet)) { throw new Error('missing new'); }

    // Make sure we have a valid signing key
    var signingKey = privateKey;
    if (!(privateKey instanceof SigningKey)) {
        signingKey = new SigningKey(privateKey);
    }
    utils.defineProperty(this, 'privateKey', signingKey.privateKey);

    Object.defineProperty(this, 'provider', {
        enumerable: true,
        get: function() { return provider; },
        set: function(value) {
            if (value !== null && !providers.isProvider(value)) {
                throw new Error('invalid provider');
            }
            provider = value;
        }
    });

    Object.defineProperty(this, '_provider', {
        enumerable: true,
        get: function() {
            if (!provider) { throw new Error('missing provider'); }
            return provider;
        },
    });

    if (provider !== null) {

        // If no provider was provided, check for metamask or ilk
        if (provider === undefined) {
            if (global.web3 && global.web3.currentProvider && global.web3.currentProvider.sendAsync) {
                this.provider = new providers.Web3Provider(global.web3.currentProvider);
            }

        // An Ethereum RPC node
        } else if (typeof(provider) === 'string' && provider.match(/^https?:\/\//)) {
            this.provider = new providers.HttpProvider(provider);

        } else {
            this.provider = provider;
        }
    }

    utils.defineProperty(this, 'address', signingKey.address);

    utils.defineProperty(this, 'sign', function(transaction) {
        var raw = [];
        transactionFields.forEach(function(fieldInfo) {
            var value = transaction[fieldInfo.name] || (new Buffer(0));
            value = utils.hexOrBuffer(utils.hexlify(value), fieldInfo.name);

            // Fixed-width field
            if (fieldInfo.length && value.length !== fieldInfo.length) {
                var error = new Error('invalid ' + fieldInfo.name);
                error.reason = 'wrong length';
                error.value = value;
                throw error;
            }

            // Variable-width (with a maximum)
            if (fieldInfo.maxLength) {
                value = utils.stripZeros(value);
                if (value.length > fieldInfo.maxLength) {
                    var error = new Error('invalid ' + fieldInfo.name);
                    error.reason = 'too long';
                    error.value = value;
                    throw error;
                }
            }

            raw.push(value);
        });

        var digest = utils.sha3(rlp.encode(raw));

        var signature = signingKey.signDigest(digest);
        var s = signature.s;
        var v = signature.recoveryParam;

        raw.push(new Buffer([27 + v]));
        raw.push(utils.bnToBuffer(signature.r));
        raw.push(utils.bnToBuffer(s));

        return ('0x' + rlp.encode(raw).toString('hex'));
    });
}

utils.defineProperty(Wallet.prototype, 'getBalance', function(blockNumber) {
    var provider = this._provider;

    var self = this;
    return new Promise(function(resolve, reject) {
        provider.getBalance(self.address, blockNumber).then(function(balance) {
            resolve(balance);
        }, function(error) {
            reject(error);
        });
    });
});

utils.defineProperty(Wallet.prototype, 'getTransactionCount', function(blockNumber) {
    var provider = this._provider;

    var self = this;
    return new Promise(function(resolve, reject) {
        provider.getTransactionCount(self.address, blockNumber).then(function(transactionCount) {
            resolve(transactionCount);
        }, function(error) {
            reject(error);
        });
    });
});

utils.defineProperty(Wallet.prototype, 'estimateGas', function(transaction) {
    var provider = this._provider;

    transaction = utils.cloneObject(transaction);
    if (transaction.from == null) { transaction.from = this.address; }

    return new Promise(function(resolve, reject) {
        provider.estimateGas(transaction).then(function(gasEstimate) {
            resolve(gasEstimate);
        }, function(error) {
            reject(error);
        });
    });
});

utils.defineProperty(Wallet.prototype, 'sendTransaction', function(transaction) {
    var gasLimit = transaction.gasLimit;
    if (gasLimit == null) { gasLimit = 3000000; }

    var self = this;

    var provider = this._provider;

    var gasPrice = new Promise(function(resolve, reject) {
        if (transaction.gasPrice) {
            return resolve(transaction.gasPrice);
        }
        provider.getGasPrice().then(function(gasPrice) {
            resolve(gasPrice);
        }, function(error) {
            reject(error);
        });
    });

    var nonce = new Promise(function(resolve, reject) {
        if (transaction.nonce) {
            return resolve(transaction.nonce);
        }
        provider.getTransactionCount(self.address, 'pending').then(function(transactionCount) {
            resolve(transactionCount);
        }, function(error) {
            reject(error);
        });
    });

    return new Promise(function(resolve, reject) {
        Promise.all([gasPrice, nonce]).then(function(results) {
            var signedTransaction = self.sign({
                to: transaction.to,
                gasLimit: gasLimit,
                gasPrice: results[0],
                nonce: results[1],
                value: transaction.value
            });

            provider.sendTransaction(signedTransaction).then(function(txid) {
                resolve(txid);
            }, function(error) {
                reject(error);
            });

        }, function(error) {
            reject(error);
        });
    });
});

utils.defineProperty(Wallet.prototype, 'send', function(address, amountWei, options) {
    address = SigningKey.getAddress(address);
    if (utils.BN.isBN(amountWei)) {
        amountWei = '0x' + utils.bnToBuffer(amountWei).toString('hex');
    }
    if (!utils.isHexString(amountWei)) { throw new Error('invalid amountWei'); }

    if (!options) { options = {}; }

    return this.sendTransaction({
        to: address,
        gasLimit: options.gasLimit,
        gasPrice: options.gasPrice,
        nonce: options.nonce,
        value: amountWei,
    });
});

utils.defineProperty(Wallet.prototype, 'getContract', function(address, abi) {
    return new Contract(this, address, new Contract.Interface(abi));
});

utils.defineProperty(Wallet, 'getAddress', SigningKey.getAddress);
utils.defineProperty(Wallet, 'getIcapAddress', SigningKey.getIcapAddress);

utils.defineProperty(Wallet, '_Contract', Contract);

var zero = new utils.BN(0);
var negative1 = new utils.BN(-1);
var tenPower18 = new utils.BN('1000000000000000000');
utils.defineProperty(Wallet, 'formatEther', function(wei, options) {

    if (typeof(wei) === 'number') {
        // @TODO: Warn if truncation will occur?
        wei = new utils.BN(wei);
    } else if (utils.isHexString(wei)) {
        wei = new utils.BN(wei.substring(2), 16);
    }

    if (!options) { options = {}; }

    if (!(wei instanceof utils.BN)) { throw new Error('invalid wei'); }

    var negative = wei.lt(zero);
    if (negative) { wei = wei.mul(negative1); }

    var fraction = wei.mod(tenPower18).toString(10);
    while (fraction.length < 18) { fraction = '0' + fraction; }

    if (!options.pad) {
        fraction = fraction.match(/^([0-9]*[1-9]|0)(0*)/)[1];
    }

    var whole = wei.div(tenPower18).toString(10);

    if (options.commify) {
        whole = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
    }

    var value = whole + '.' + fraction;

    if (negative) { value = '-' + value; }

    return value;
});

utils.defineProperty(Wallet, 'parseEther', function(ether) {
    if (typeof(ether) !== 'string' || !ether.match(/^-?[0-9.]+$/)) {
        throw new Error('invalid value');
    }

    // Is it negative?
    var negative = (ether.substring(0, 1) === '-');
    if (negative) { ether = ether.substring(1); }

    if (ether === '.') { throw new Error('invalid value'); }

    // Split it into a whole and fractional part
    var comps = ether.split('.');
    if (comps.length > 2) { throw new Error('too many decimal points'); }

    var whole = comps[0], fraction = comps[1];
    if (!whole) { whole = '0'; }
    if (!fraction) { fraction = '0'; }
    if (fraction.length > 18) { throw new Error('too many decimal places'); }

    while (fraction.length < 18) { fraction += '0'; }

    whole = new utils.BN(whole);
    fraction = new utils.BN(fraction);

    var wei = (whole.mul(tenPower18)).add(fraction);

    if (negative) { wei = wei.mul(negative1); }

    return wei;
});

module.exports = Wallet;
<|endoftext|>


<commit_before>/**
* ownCloud
*
* @author Vincent Petry
* @copyright 2014 Vincent Petry <pvince81@owncloud.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library.  If not, see <http://www.gnu.org/licenses/>.
*
*/

/**
 * This node module is run by the karma executable to specify its configuration.
 *
 * The list of files from all needed JavaScript files including the ones from the
 * apps to test, and the test specs will be passed as configuration object.
 *
 * Note that it is possible to test a single app by setting the KARMA_TESTSUITE
 * environment variable to the apps name, for example "core" or "files_encryption".
 * Multiple apps can be specified by separating them with space.
 *
 * Setting the environment variable NOCOVERAGE to 1 will disable the coverage
 * preprocessor, which is needed to be able to debug tests properly in a browser.
 */

/* jshint node: true */
module.exports = function(config) {

	function findApps() {
		/*
		var fs = require('fs');
		var apps = fs.readdirSync('apps');
		return apps;
		*/
		// other apps tests don't run yet... needs further research / clean up
		return [
			'files',
			'files_trashbin',
			{
				name: 'files_sharing',
				srcFiles: [
					// only test these files, others are not ready and mess
					// up with the global namespace/classes/state
					'apps/files_sharing/js/app.js',
					'apps/files_sharing/js/sharedfilelist.js',
					'apps/files_sharing/js/share.js',
					'apps/files_sharing/js/external.js',
					'apps/files_sharing/js/public.js',
					'apps/files_sharing/js/sharetabview.js'
				],
				testFiles: ['apps/files_sharing/tests/js/*.js']
			},
			{
				name: 'files_external',
				srcFiles: [
					// only test these files, others are not ready and mess
					// up with the global namespace/classes/state
					'apps/files_external/js/app.js',
					'apps/files_external/js/mountsfilelist.js',
					'apps/files_external/js/settings.js',
					'apps/files_external/js/statusmanager.js'
				],
				testFiles: ['apps/files_external/tests/js/*.js']
			},
			{
				name: 'files_versions',
				srcFiles: [
					// need to enforce loading order...
					'apps/files_versions/js/versionmodel.js',
					'apps/files_versions/js/versioncollection.js',
					'apps/files_versions/js/versionstabview.js'
				],
				testFiles: ['apps/files_versions/tests/js/**/*.js']
			},
			{
				name: 'comments',
				srcFiles: [
					// need to enforce loading order...
					'apps/comments/js/app.js',
					'apps/comments/js/commentmodel.js',
					'apps/comments/js/commentcollection.js',
					'apps/comments/js/commentsummarymodel.js',
					'apps/comments/js/commentstabview.js',
					'apps/comments/js/filesplugin.js'
				],
				testFiles: ['apps/comments/tests/js/**/*.js']
			},
			{
				name: 'systemtags',
				srcFiles: [
					// need to enforce loading order...
					'apps/systemtags/js/app.js',
					'apps/systemtags/js/systemtagsinfoview.js',
					'apps/systemtags/js/systemtagsfilelist.js',
					'apps/systemtags/js/filesplugin.js'
				],
				testFiles: ['apps/systemtags/tests/js/**/*.js']
			},
			{
				name: 'settings',
				srcFiles: [
					'settings/js/users/deleteHandler.js'
				],
				testFiles: [
					'settings/tests/js/users/deleteHandlerSpec.js'
				]
			}
		];
	}

	// respect NOCOVERAGE env variable
	// it is useful to disable coverage for debugging
	// because the coverage preprocessor will wrap the JS files somehow
	var enableCoverage = !parseInt(process.env.NOCOVERAGE, 10);
	console.log('Coverage preprocessor: ', enableCoverage?'enabled':'disabled');

	// default apps to test when none is specified (TODO: read from filesystem ?)
	var appsToTest = process.env.KARMA_TESTSUITE;
    if (appsToTest) {
		appsToTest = appsToTest.split(' ');
	}
	else {
		appsToTest = ['core'].concat(findApps());
	}

	console.log('Apps to test: ', appsToTest);

	// read core files from core.json,
	// these are required by all apps so always need to be loaded
	// note that the loading order is important that's why they
	// are specified in a separate file
	var corePath = 'core/js/';
	var vendorPath = 'core/vendor/';
	var coreModule = require('../' + corePath + 'core.json');
	var testCore = false;
	var files = [];
	var index;
	var preprocessors = {};

	// find out what apps to test from appsToTest
	index = appsToTest.indexOf('core');
	if (index > -1) {
		appsToTest.splice(index, 1);
		testCore = true;
	}

	// core mocks
	files.push(corePath + 'tests/specHelper.js');

	var srcFile, i;
	// add vendor library files
	for ( i = 0; i < coreModule.vendor.length; i++ ) {
		srcFile = vendorPath + coreModule.vendor[i];
		files.push(srcFile);
	}

	// add core library files
	for ( i = 0; i < coreModule.libraries.length; i++ ) {
		srcFile = corePath + coreModule.libraries[i];
		files.push(srcFile);
	}

	// add core modules files
	for ( i = 0; i < coreModule.modules.length; i++ ) {
		srcFile = corePath + coreModule.modules[i];
		files.push(srcFile);
		if (enableCoverage) {
			preprocessors[srcFile] = 'coverage';
		}
	}

	// TODO: settings pages

	// need to test the core app as well ?
	if (testCore) {
		// core tests
		files.push(corePath + 'tests/specs/**/*.js');
	}

	function addApp(app) {
		// if only a string was specified, expand to structure
		if (typeof(app) === 'string') {
			app = {
				srcFiles: 'apps/' + app + '/js/**/*.js',
				testFiles: 'apps/' + app + '/tests/js/**/*.js'
			};
		}

		// add source files/patterns
		files = files.concat(app.srcFiles || []);
		// add test files/patterns
		files = files.concat(app.testFiles || []);
		if (enableCoverage) {
			// add coverage entry for each file/pattern
			for (var i = 0; i < app.srcFiles.length; i++) {
				preprocessors[app.srcFiles[i]] = 'coverage';
			}
		}
	}

	// add source files for apps to test
	for ( i = 0; i < appsToTest.length; i++ ) {
		addApp(appsToTest[i]);
	}

	// serve images to avoid warnings
	files.push({pattern: 'core/img/**/*', watched: false, included: false, served: true});

	// include core CSS
	files.push({pattern: 'core/css/*.css', watched: true, included: true, served: true});

	config.set({

		// base path, that will be used to resolve files and exclude
		basePath: '..',

		// frameworks to use
		frameworks: ['jasmine', 'jasmine-sinon'],

		// list of files / patterns to load in the browser
		files: files,

		// list of files to exclude
		exclude: [

		],

		proxies: {
			// prevent warnings for images
			'/context.html//core/img/': 'http://localhost:9876/base/core/img/',
			'/context.html//core/css/': 'http://localhost:9876/base/core/css/',
			'/context.html//core/fonts/': 'http://localhost:9876/base/core/fonts/'
		},

		// test results reporter to use
		// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
		reporters: ['dots', 'junit', 'coverage'],

		junitReporter: {
			outputDir: 'tests',
			outputFile: 'autotest-results-js.xml',
			useBrowserName: false
		},

		// web server port
		port: 9876,

		preprocessors: preprocessors,

		coverageReporter: {
			dir:'tests/karma-coverage',
			reporters: [
				{ type: 'html' },
				{ type: 'cobertura' }
			]
		},

		// enable / disable colors in the output (reporters and logs)
		colors: true,

		// level of logging
		// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
		logLevel: config.LOG_INFO,

		// enable / disable watching file and executing tests whenever any file changes
		autoWatch: true,

		// Start these browsers, currently available:
		// - Chrome
		// - ChromeCanary
		// - Firefox
		// - Opera (has to be installed with `npm install karma-opera-launcher`)
		// - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
		// - PhantomJS
		// - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
		browsers: ['PhantomJS'],

		// If browser does not capture in given timeout [ms], kill it
		captureTimeout: 60000,

		// Continuous Integration mode
		// if true, it capture browsers, run tests and exit
		singleRun: false
  });
};
<commit_msg>Increase phantomjs timeout<commit_after>/**
* ownCloud
*
* @author Vincent Petry
* @copyright 2014 Vincent Petry <pvince81@owncloud.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library.  If not, see <http://www.gnu.org/licenses/>.
*
*/

/**
 * This node module is run by the karma executable to specify its configuration.
 *
 * The list of files from all needed JavaScript files including the ones from the
 * apps to test, and the test specs will be passed as configuration object.
 *
 * Note that it is possible to test a single app by setting the KARMA_TESTSUITE
 * environment variable to the apps name, for example "core" or "files_encryption".
 * Multiple apps can be specified by separating them with space.
 *
 * Setting the environment variable NOCOVERAGE to 1 will disable the coverage
 * preprocessor, which is needed to be able to debug tests properly in a browser.
 */

/* jshint node: true */
module.exports = function(config) {

	function findApps() {
		/*
		var fs = require('fs');
		var apps = fs.readdirSync('apps');
		return apps;
		*/
		// other apps tests don't run yet... needs further research / clean up
		return [
			'files',
			'files_trashbin',
			{
				name: 'files_sharing',
				srcFiles: [
					// only test these files, others are not ready and mess
					// up with the global namespace/classes/state
					'apps/files_sharing/js/app.js',
					'apps/files_sharing/js/sharedfilelist.js',
					'apps/files_sharing/js/share.js',
					'apps/files_sharing/js/external.js',
					'apps/files_sharing/js/public.js',
					'apps/files_sharing/js/sharetabview.js'
				],
				testFiles: ['apps/files_sharing/tests/js/*.js']
			},
			{
				name: 'files_external',
				srcFiles: [
					// only test these files, others are not ready and mess
					// up with the global namespace/classes/state
					'apps/files_external/js/app.js',
					'apps/files_external/js/mountsfilelist.js',
					'apps/files_external/js/settings.js',
					'apps/files_external/js/statusmanager.js'
				],
				testFiles: ['apps/files_external/tests/js/*.js']
			},
			{
				name: 'files_versions',
				srcFiles: [
					// need to enforce loading order...
					'apps/files_versions/js/versionmodel.js',
					'apps/files_versions/js/versioncollection.js',
					'apps/files_versions/js/versionstabview.js'
				],
				testFiles: ['apps/files_versions/tests/js/**/*.js']
			},
			{
				name: 'comments',
				srcFiles: [
					// need to enforce loading order...
					'apps/comments/js/app.js',
					'apps/comments/js/commentmodel.js',
					'apps/comments/js/commentcollection.js',
					'apps/comments/js/commentsummarymodel.js',
					'apps/comments/js/commentstabview.js',
					'apps/comments/js/filesplugin.js'
				],
				testFiles: ['apps/comments/tests/js/**/*.js']
			},
			{
				name: 'systemtags',
				srcFiles: [
					// need to enforce loading order...
					'apps/systemtags/js/app.js',
					'apps/systemtags/js/systemtagsinfoview.js',
					'apps/systemtags/js/systemtagsfilelist.js',
					'apps/systemtags/js/filesplugin.js'
				],
				testFiles: ['apps/systemtags/tests/js/**/*.js']
			},
			{
				name: 'settings',
				srcFiles: [
					'settings/js/users/deleteHandler.js'
				],
				testFiles: [
					'settings/tests/js/users/deleteHandlerSpec.js'
				]
			}
		];
	}

	// respect NOCOVERAGE env variable
	// it is useful to disable coverage for debugging
	// because the coverage preprocessor will wrap the JS files somehow
	var enableCoverage = !parseInt(process.env.NOCOVERAGE, 10);
	console.log('Coverage preprocessor: ', enableCoverage?'enabled':'disabled');

	// default apps to test when none is specified (TODO: read from filesystem ?)
	var appsToTest = process.env.KARMA_TESTSUITE;
    if (appsToTest) {
		appsToTest = appsToTest.split(' ');
	}
	else {
		appsToTest = ['core'].concat(findApps());
	}

	console.log('Apps to test: ', appsToTest);

	// read core files from core.json,
	// these are required by all apps so always need to be loaded
	// note that the loading order is important that's why they
	// are specified in a separate file
	var corePath = 'core/js/';
	var vendorPath = 'core/vendor/';
	var coreModule = require('../' + corePath + 'core.json');
	var testCore = false;
	var files = [];
	var index;
	var preprocessors = {};

	// find out what apps to test from appsToTest
	index = appsToTest.indexOf('core');
	if (index > -1) {
		appsToTest.splice(index, 1);
		testCore = true;
	}

	// core mocks
	files.push(corePath + 'tests/specHelper.js');

	var srcFile, i;
	// add vendor library files
	for ( i = 0; i < coreModule.vendor.length; i++ ) {
		srcFile = vendorPath + coreModule.vendor[i];
		files.push(srcFile);
	}

	// add core library files
	for ( i = 0; i < coreModule.libraries.length; i++ ) {
		srcFile = corePath + coreModule.libraries[i];
		files.push(srcFile);
	}

	// add core modules files
	for ( i = 0; i < coreModule.modules.length; i++ ) {
		srcFile = corePath + coreModule.modules[i];
		files.push(srcFile);
		if (enableCoverage) {
			preprocessors[srcFile] = 'coverage';
		}
	}

	// TODO: settings pages

	// need to test the core app as well ?
	if (testCore) {
		// core tests
		files.push(corePath + 'tests/specs/**/*.js');
	}

	function addApp(app) {
		// if only a string was specified, expand to structure
		if (typeof(app) === 'string') {
			app = {
				srcFiles: 'apps/' + app + '/js/**/*.js',
				testFiles: 'apps/' + app + '/tests/js/**/*.js'
			};
		}

		// add source files/patterns
		files = files.concat(app.srcFiles || []);
		// add test files/patterns
		files = files.concat(app.testFiles || []);
		if (enableCoverage) {
			// add coverage entry for each file/pattern
			for (var i = 0; i < app.srcFiles.length; i++) {
				preprocessors[app.srcFiles[i]] = 'coverage';
			}
		}
	}

	// add source files for apps to test
	for ( i = 0; i < appsToTest.length; i++ ) {
		addApp(appsToTest[i]);
	}

	// serve images to avoid warnings
	files.push({pattern: 'core/img/**/*', watched: false, included: false, served: true});

	// include core CSS
	files.push({pattern: 'core/css/*.css', watched: true, included: true, served: true});

	config.set({

		// base path, that will be used to resolve files and exclude
		basePath: '..',

		// frameworks to use
		frameworks: ['jasmine', 'jasmine-sinon'],

		// list of files / patterns to load in the browser
		files: files,

		// list of files to exclude
		exclude: [

		],

		proxies: {
			// prevent warnings for images
			'/context.html//core/img/': 'http://localhost:9876/base/core/img/',
			'/context.html//core/css/': 'http://localhost:9876/base/core/css/',
			'/context.html//core/fonts/': 'http://localhost:9876/base/core/fonts/'
		},

		// test results reporter to use
		// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
		reporters: ['dots', 'junit', 'coverage'],

		junitReporter: {
			outputDir: 'tests',
			outputFile: 'autotest-results-js.xml',
			useBrowserName: false
		},

		// web server port
		port: 9876,

		preprocessors: preprocessors,

		coverageReporter: {
			dir:'tests/karma-coverage',
			reporters: [
				{ type: 'html' },
				{ type: 'cobertura' }
			]
		},

		// enable / disable colors in the output (reporters and logs)
		colors: true,

		// level of logging
		// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
		logLevel: config.LOG_INFO,

		// enable / disable watching file and executing tests whenever any file changes
		autoWatch: true,

		// Start these browsers, currently available:
		// - Chrome
		// - ChromeCanary
		// - Firefox
		// - Opera (has to be installed with `npm install karma-opera-launcher`)
		// - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
		// - PhantomJS
		// - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
		browsers: ['PhantomJS'],

		// If browser does not capture in given timeout [ms], kill it
		captureTimeout: 60000,
		browserNoActivityTimeout: 60000,
		browserDisconnectTimeout: 30000,
		captureTimeout: 60000,

		// Continuous Integration mode
		// if true, it capture browsers, run tests and exit
		singleRun: false
  });
};
<|endoftext|>