<commit_before>'use strict';

var Pbf = require('../'),
    Benchmark = require('benchmark'),
    fs = require('fs'),
    protobuf = require('protocol-buffers');

var messages = protobuf(fs.readFileSync(__dirname + '/vector_tile.proto')),
    data = fs.readFileSync(__dirname + '/../test/fixtures/12665.vector.pbf'),
    suite = new Benchmark.Suite();

var layers = readLayers(data),
    layersJSON = JSON.stringify(layers);

// var layers2 = messages.Tile.decode(data);

suite
.add('decode vector tile with pbf', function() {
    readLayers(data);
})
.add('decode vector tile with protocol-buffers', function() {
    messages.Tile.decode(data);
})
.add('native JSON.parse of the same data', function() {
    JSON.parse(layersJSON);
})
.add('encode vector tile with pbf', function() {
    encodeLayers(layers);
})
// .add('encode vector tile with protocol-buffers', function() {
//     messages.Tile.encode(layers2);
// })
.add('native JSON.stringify', function() {
    JSON.stringify(layers);
})
.on('cycle', function(event) {
    console.log(String(event.target));
})
.run();

// decoding vector tile

function readLayers(data) {
    return new Pbf(data).readFields(readTile, []);
}
function readTile(tag, layers, pbf) {
    if (tag === 3) layers.push(pbf.readMessage(readLayer, {features: [], keys: [], values: []}));
}
function readLayer(tag, layer, pbf) {
    if (tag === 1) layer.name = pbf.readString();
    else if (tag === 2) layer.features.push(pbf.readMessage(readFeature, {}));
    else if (tag === 3) layer.keys.push(pbf.readString());
    else if (tag === 4) layer.values.push(pbf.readMessage(readValue, {}).value);
    else if (tag === 5) layer.extent = pbf.readVarint();
    else if (tag === 15) layer.version = pbf.readVarint();
}
function readFeature(tag, feature, pbf) {
    if (tag === 1) feature.id = pbf.readVarint();
    else if (tag === 2) feature.tags = pbf.readPackedVarint();
    else if (tag === 3) feature.type = pbf.readVarint();
    else if (tag === 4) feature.geometry = pbf.readPackedVarint();
}
function readValue(tag, value, pbf) {
    if (tag === 1) value.value = pbf.readString();
    else if (tag === 2) value.value = pbf.readFloat();
    else if (tag === 3) value.value = pbf.readDouble();
    else if (tag === 4) value.value = pbf.readVarint();
    else if (tag === 5) value.value = pbf.readVarint();
    else if (tag === 6) value.value = pbf.readSVarint();
    else if (tag === 7) value.value = pbf.readBoolean();
}

// encoding vector tile

function encodeLayers(layers) {
    var pbf = new Pbf();
    for (var i = 0; i < layers.length; i++) {
        pbf.writeMessage(3, encodeLayer, layers[i]);
    }
    return pbf.finish();
}
function encodeLayer(layer, pbf) {
    pbf.writeStringField(1, layer.name);

    for (var i = 0; i < layer.features.length; i++) {
        pbf.writeMessage(2, encodeFeature, layer.features[i]);
    }
    for (i = 0; i < layer.keys.length; i++) {
        pbf.writeStringField(3, layer.keys[i]);
    }
    for (i = 0; i < layer.values.length; i++) {
        pbf.writeMessage(4, encodeValue, layer.values[i]);
    }
    pbf.writeVarintField(5, layer.extent);
    pbf.writeVarintField(15, layer.version);
}
function encodeFeature(feature, pbf) {
    pbf.writeVarintField(1, feature.id);
    pbf.writePackedVarint(2, feature.tags);
    pbf.writeVarintField(3, feature.type);
    pbf.writePackedVarint(4, feature.geometry);
}
function encodeValue(value, pbf) {
    if (typeof value === 'string') pbf.writeStringField(1, value);
    else if (typeof value === 'number') {
        if (value % 1 === 0) { // integer
            if (value >= 0) pbf.writeVarintField(4, value);
            else pbf.writeSVarintField(6, value);
        } else pbf.writeDoubleField(3, value);
    } else if (typeof value === 'boolean') pbf.writeBooleanField(7, value);
}
<commit_msg>cleanup benchmark<commit_after>'use strict';

var Pbf = require('../'),
    Benchmark = require('benchmark'),
    fs = require('fs'),
    protobuf = require('protocol-buffers');

var messages = protobuf(fs.readFileSync(__dirname + '/vector_tile.proto')),
    data = fs.readFileSync(__dirname + '/../test/fixtures/12665.vector.pbf'),
    suite = new Benchmark.Suite();

var layers = read(data),
    layersJSON = JSON.stringify(layers);

var layers2 = messages.Tile.decode(data);

suite
.add('decode vector tile with pbf', function() {
    read(data);
})
.add('decode vector tile with protocol-buffers', function() {
    messages.Tile.decode(data);
})
.add('native JSON.parse of the same data', function() {
    JSON.parse(layersJSON);
})
.add('encode vector tile with pbf', function() {
    write(layers);
})
.add('encode vector tile with protocol-buffers', function() {
    messages.Tile.encode(layers2);
})
.add('native JSON.stringify', function() {
    JSON.stringify(layers);
})
.on('cycle', function(event) {
    console.log(String(event.target));
})
.run();

// decoding vector tile

function read(data) {
    return new Pbf(data).readFields(readTile, []);
}
function readTile(tag, layers, pbf) {
    if (tag === 3) layers.push(pbf.readMessage(readLayer, {features: [], keys: [], values: []}));
}
function readLayer(tag, layer, pbf) {
    if (tag === 1) layer.name = pbf.readString();
    else if (tag === 2) layer.features.push(pbf.readMessage(readFeature, {}));
    else if (tag === 3) layer.keys.push(pbf.readString());
    else if (tag === 4) layer.values.push(pbf.readMessage(readValue, {}).value);
    else if (tag === 5) layer.extent = pbf.readVarint();
    else if (tag === 15) layer.version = pbf.readVarint();
}
function readFeature(tag, feature, pbf) {
    if (tag === 1) feature.id = pbf.readVarint();
    else if (tag === 2) feature.tags = pbf.readPackedVarint();
    else if (tag === 3) feature.type = pbf.readVarint();
    else if (tag === 4) feature.geometry = pbf.readPackedVarint();
}
function readValue(tag, value, pbf) {
    if (tag === 1) value.value = pbf.readString();
    else if (tag === 2) value.value = pbf.readFloat();
    else if (tag === 3) value.value = pbf.readDouble();
    else if (tag === 4 || tag === 5) value.value = pbf.readVarint();
    else if (tag === 6) value.value = pbf.readSVarint();
    else if (tag === 7) value.value = pbf.readBoolean();
}

// encoding vector tile

function write(layers) {
    var pbf = new Pbf();
    for (var i = 0; i < layers.length; i++) pbf.writeMessage(3, writeLayer, layers[i]);
    return pbf.finish();
}
function writeLayer(layer, pbf) {
    pbf.writeStringField(1, layer.name);
    var i;
    for (i = 0; i < layer.features.length; i++) pbf.writeMessage(2, writeFeature, layer.features[i]);
    for (i = 0; i < layer.keys.length; i++) pbf.writeStringField(3, layer.keys[i]);
    for (i = 0; i < layer.values.length; i++) pbf.writeMessage(4, writeValue, layer.values[i]);
    pbf.writeVarintField(5, layer.extent);
    pbf.writeVarintField(15, layer.version);
}
function writeFeature(feature, pbf) {
    pbf.writeVarintField(1, feature.id);
    pbf.writePackedVarint(2, feature.tags);
    pbf.writeVarintField(3, feature.type);
    pbf.writePackedVarint(4, feature.geometry);
}
function writeValue(value, pbf) {
    if (typeof value === 'string') pbf.writeStringField(1, value);
    else if (typeof value === 'boolean') pbf.writeBooleanField(7, value);
    else if (typeof value === 'number') {
        if (value % 1 !== 0) pbf.writeDoubleField(3, value);
        else if (value >= 0) pbf.writeVarintField(4, value);
        else pbf.writeSVarintField(6, value);
    }
}
<|endoftext|>


<commit_before>/* eslint-env browser */

import './lib/displayProjectsGraph';

let projects = document.querySelector('#projects');
let hierarchy = document.querySelector('#hierarchy');
let selectedProject;
let selectedHierarchyItem;
let graph;

// TODO: Hook this up to the log out button on the graph view. It is currently not hooked up to anything,
// but functions properly
document.addEventListener('DOMContentLoaded', () => {
  document.getElementById('logOut').addEventListener('click', () => {
    document.location.href = '/logout';
  });

  // Manage the selection of a project and item hierarchy
  buildProjectAnchors().then(() => {
    getGraph(selectedProject).then(graphJSON => {
      graph = graphJSON;
      console.log(graph);
    });
  });
  buildItemHierarchyAnchors();
  document.getElementById('renderButton').addEventListener('click', event => {
    toggle(hierarchy);
    document.querySelector('svg').style.display = 'block';
  });
});

/**
 * Listens for mouse clicks on the Item hierarchy list and sets the selected
 * variable to that items ID
 */
function buildItemHierarchyAnchors () {
  return new Promise(resolve => {
    querySelectorAll('#hierarchy a').forEach(hierarchyAnchor => {
      hierarchyAnchor.addEventListener('click', event => {
        selectedHierarchyItem = event.target.getAttribute('data-id');
        document.body.style.cursor = 'wait';
        console.log(selectedHierarchyItem);
      });
    });
  });
}

function buildProjectAnchors () {
  return new Promise((resolve) => {
    querySelectorAll('#projects a').forEach(projectAnchor => {
      projectAnchor.addEventListener('click', event => {
        selectedProject = event.target.getAttribute('data-id');

        // Wait until loadHierarchy retrieves the new partial view and updates it with the item hierarchy
        // to display the hierarchy selection div and toggle projects view
        document.body.style.cursor = 'wait';
        getHierarchy(selectedProject).then(hierarchyPayload => {
          renderHierarchy(hierarchyPayload);
          toggle(projects);
          toggle(hierarchy);
          document.body.style.cursor = 'default';
          resolve();
        });
      });
    });
  });
}

/**
 * Query the page for a set of elements given a CSS selector.
 *
 * @param selector CSS selector
 * @returns {*} Array of matched elements
 */
function querySelectorAll (selector) {
  return Array.from(document.querySelectorAll(selector));
}

function toggle (element) {
  if (element.classList.contains('hidden')) {
    element.classList.remove('hidden');
  } else {
    element.classList.add('hidden');
  }
}

/**
 * Makes an AJAX request to the provided endpoint for the item hierarchy tree.
 *
 * @param projectId
 * @returns {*}
 */
function getHierarchy (projectId) {
  // TODO: Refactor to use the request module?
  return new Promise((resolve, reject) => {
    let httpRequest = new XMLHttpRequest();
    httpRequest.onreadystatechange = () => {
      if (httpRequest.readyState === XMLHttpRequest.DONE) {
        if (httpRequest.status === 200) {
          resolve(JSON.parse(httpRequest.responseText));
        } else {
          console.log('There was a problem requesting to the hierarchy endpoint.');
          reject({status: httpRequest.status, response: httpRequest.responseText});
        }
      }
    };
    httpRequest.open('GET', '/hierarchy?project=' + projectId);
    httpRequest.send();
  });
}

function renderHierarchy (hierarchyPayload) {
  let itemHierarchyList = document.getElementById('itemHierarchyList');
  if (hierarchyPayload) {
    hierarchyPayload.forEach(item => {
      itemHierarchyList.appendChild(getHierarchyItemWithChildren(item));
    });
  } else {
    itemHierarchyList.appendChild(document.createTextNode('Sorry, this project has no items to display.'));
  }
}

function getHierarchyItemWithChildren (item) {
  let listItem = document.createElement('li');
  let itemAnchor = document.createElement('a');
  itemAnchor.setAttribute('href', '#rootId=' + item.id);
  itemAnchor.appendChild(document.createTextNode(item.name));
  itemAnchor.setAttribute('data-id', item.id);
  listItem.appendChild(itemAnchor);
  if (item.children) {
    let unorderedList = document.createElement('ul');
    item.children.forEach(function (subItem) {
      unorderedList.appendChild(getHierarchyItemWithChildren(subItem));
    });
    listItem.appendChild(unorderedList);
  }
  return listItem;
}

/**
 * Makes an AJAX request to the provided endpoint for the project graph.
 *
 * @param projectId
 * @returns {*}
 */
function getGraph (projectId) {
  // TODO: Refactor to use the request module and promises
  return new Promise((resolve, reject) => {
    let httpRequest = new XMLHttpRequest();
    httpRequest.onreadystatechange = () => {
      if (httpRequest.readyState === XMLHttpRequest.DONE) {
        if (httpRequest.status === 200) {
          resolve(JSON.parse(httpRequest.responseText));
        } else {
          console.log('There was a problem requesting to the graph endpoint.');
          reject({status: httpRequest.status, response: httpRequest.responseText});
        }
      }
    };
    httpRequest.open('GET', 'graph/getGraphData/' + projectId);
    httpRequest.send();
  });
}
<commit_msg>hook up d3 renderGraph<commit_after>/* eslint-env browser */

import renderGraph from './lib/displayProjectsGraph';

let projects = document.querySelector('#projects');
let hierarchy = document.querySelector('#hierarchy');
let graph = document.querySelector('#graphContainer');
let selectedProject;
let selectedHierarchyItem = null;
let graphData;

// TODO: Hook this up to the log out button on the graph view. It is currently not hooked up to anything,
// but functions properly
document.addEventListener('DOMContentLoaded', () => {
  document.getElementById('logOut').addEventListener('click', () => {
    document.location.href = '/logout';
  });

  // Manage the selection of a project and item hierarchy
  buildProjectAnchors().then(() => getGraph(selectedProject)).then(graphJSON => {
    graphData = graphJSON;
    console.log(graphData);
    buildItemHierarchyAnchors();
  });

  document.getElementById('renderButton').addEventListener('click', event => {
    toggle(hierarchy);
    console.log(selectedHierarchyItem);
    renderGraph(graphData, selectedProject, parseInt(selectedHierarchyItem));
  });
});

function buildProjectAnchors () {
  return new Promise((resolve) => {
    querySelectorAll('#projects a').forEach(projectAnchor => {
      projectAnchor.addEventListener('click', event => {
        selectedProject = event.target.getAttribute('data-id');
        // Wait until loadHierarchy retrieves the new partial view and updates it with the item hierarchy
        // to display the hierarchy selection div and toggle projects view
        document.body.style.cursor = 'wait';
        getHierarchy(selectedProject).then(hierarchyPayload => {
          renderHierarchy(hierarchyPayload);
          toggle(projects);
          toggle(hierarchy);
          document.body.style.cursor = 'default';
          resolve(true);
        });
      });
    });
  });
}

/**
 * Listens for mouse clicks on the Item hierarchy list and sets the selected
 * variable to that items ID
 */
function buildItemHierarchyAnchors () {
  return new Promise(resolve => {
    querySelectorAll('#itemHierarchyList a').forEach(hierarchyAnchor => {
      hierarchyAnchor.addEventListener('click', event => {
        selectedHierarchyItem = event.target.getAttribute('data-id');
        resolve(true);
      });
    });
  });
}

/**
 * Query the page for a set of elements given a CSS selector.
 *
 * @param selector CSS selector
 * @returns {*} Array of matched elements
 */
function querySelectorAll (selector) {
  return Array.from(document.querySelectorAll(selector));
}

function toggle (element) {
  if (element.classList.contains('hidden')) {
    element.classList.remove('hidden');
  } else {
    element.classList.add('hidden');
  }
}

/**
 * Makes an AJAX request to the provided endpoint for the item hierarchy tree.
 *
 * @param projectId
 * @returns {*}
 */
function getHierarchy (projectId) {
  // TODO: Refactor to use the request module?
  return new Promise((resolve, reject) => {
    let httpRequest = new XMLHttpRequest();
    httpRequest.onreadystatechange = () => {
      if (httpRequest.readyState === XMLHttpRequest.DONE) {
        if (httpRequest.status === 200) {
          resolve(JSON.parse(httpRequest.responseText));
        } else {
          console.log('There was a problem requesting to the hierarchy endpoint.');
          reject({status: httpRequest.status, response: httpRequest.responseText});
        }
      }
    };
    httpRequest.open('GET', '/hierarchy?project=' + projectId);
    httpRequest.send();
  });
}

function renderHierarchy (hierarchyPayload) {
  let itemHierarchyList = document.getElementById('itemHierarchyList');
  if (hierarchyPayload) {
    hierarchyPayload.forEach(item => {
      itemHierarchyList.appendChild(getHierarchyItemWithChildren(item));
    });
  } else {
    itemHierarchyList.appendChild(document.createTextNode('Sorry, this project has no items to display.'));
  }
}

function getHierarchyItemWithChildren (item) {
  let listItem = document.createElement('li');
  let itemAnchor = document.createElement('a');
  itemAnchor.setAttribute('href', '#rootId=' + item.id);
  itemAnchor.appendChild(document.createTextNode(item.name));
  itemAnchor.setAttribute('data-id', item.id);
  listItem.appendChild(itemAnchor);
  if (item.children) {
    let unorderedList = document.createElement('ul');
    item.children.forEach(function (subItem) {
      unorderedList.appendChild(getHierarchyItemWithChildren(subItem));
    });
    listItem.appendChild(unorderedList);
  }
  return listItem;
}

/**
 * Makes an AJAX request to the provided endpoint for the project graph.
 *
 * @param projectId
 * @returns {*}
 */
function getGraph (projectId) {
  // TODO: Refactor to use the request module and promises
  return new Promise((resolve, reject) => {
    let httpRequest = new XMLHttpRequest();
    httpRequest.onreadystatechange = () => {
      if (httpRequest.readyState === XMLHttpRequest.DONE) {
        if (httpRequest.status === 200) {
          resolve(JSON.parse(httpRequest.responseText));
        } else {
          console.log('There was a problem requesting to the graph endpoint.');
          reject({status: httpRequest.status, response: httpRequest.responseText});
        }
      }
    };
    httpRequest.open('GET', 'graph/getGraphData/' + projectId);
    httpRequest.send();
  });
}
<|endoftext|>


<commit_before>module.exports = (form, ...restArgs) => {
  const args = [...restArgs] || null;
  if (!form) {
    throw new Error('rfGetter - Form element must be passed as an argument');
  }
  if (args.length > 0) {
    throw new Error('rfGetter - Must pass in a single FORM element as an argument');
  }
  if (form.tagName !== 'FORM') {
    throw new Error('rfGetter - Must pass in a FORM element to the function');
  }
  if (form.children.length < 1) return {};

  // Write the react form getter function here
  const results = {};

    // User should pass in a ref to a form element.

  const validTags = new Set(['INPUT', 'SELECT']);
  const invalidInputTypes = new Set(['button', 'submit', 'reset']);

  const addNodeToResults = (name, value, type) => {
    if (name) {
      results[name] = value;
    } else {
      console.warn(`Input with the value: ${value} and type: ${type}
      has no name property and could not be added to form data`);
    }
  };

  const queue = [...form.children];

  while (queue.length) {
    const currNode = queue.shift();
    const type = currNode.getAttribute('type');
    if (currNode.children.length > 0) {
      queue.push(...currNode.children);
    }
    if (validTags.has(currNode.tagName) && !invalidInputTypes.has(type)) {
      const name = currNode.getAttribute('name');
      const value = currNode.value;

      if (type === 'radio' || type === 'checkbox') {
        if (currNode.checked) addNodeToResults(name, value, type);
      } else {
        addNodeToResults(name, value, type);
      }
    }
  }
  return results;
};
<commit_msg>removed unnecesarry comments from index.js<commit_after>module.exports = (form, ...restArgs) => {
  const args = [...restArgs] || null;
  if (!form) {
    throw new Error('rfGetter - Form element must be passed as an argument');
  }
  if (args.length > 0) {
    throw new Error('rfGetter - Must pass in a single FORM element as an argument');
  }
  if (form.tagName !== 'FORM') {
    throw new Error('rfGetter - Must pass in a FORM element to the function');
  }
  if (form.children.length < 1) return {};

  /* Start function */
  const results = {};

  const validTags = new Set(['INPUT', 'SELECT']);
  const invalidInputTypes = new Set(['button', 'submit', 'reset']);

  const addNodeToResults = (name, value, type) => {
    if (name) {
      results[name] = value;
    } else {
      console.warn(`Input with the value: ${value} and type: ${type}
      has no name property and could not be added to form data`);
    }
  };

  const queue = [...form.children];

  while (queue.length) {
    const currNode = queue.shift();
    const type = currNode.getAttribute('type');
    if (currNode.children.length > 0) {
      queue.push(...currNode.children);
    }
    if (validTags.has(currNode.tagName) && !invalidInputTypes.has(type)) {
      const name = currNode.getAttribute('name');
      const value = currNode.value;

      if (type === 'radio' || type === 'checkbox') {
        if (currNode.checked) addNodeToResults(name, value, type);
      } else {
        addNodeToResults(name, value, type);
      }
    }
  }
  return results;
};
<|endoftext|>


<commit_before>var UID = "_U_";
var MULTI_TYPE = "_multi";

var STATUS = {
  UNKNOWN : 'UNKNOWN',
  PENDING : 'PENDING',
  RUNNING : 'RUNNING',
  DONE : 'DONE',
  FAILED : 'FAILED'
};

// *** Node *******************************************************************
function Node(id, name, type, status) {
  if (typeof (name) === 'undefined') {
    name = id;
  }
  if (typeof (type) === 'undefined') {
    type = 'analysis';
  }
  if (typeof (status) === 'undefined') {
    status = STATUS.UNKNOWN;
  }
  if (typeof STATUS[status] === 'undefined') {
    throw Error("Unknown status '" + status + "' for node " + name + "(id="
        + id + ")");
  }
  this.id = id;
  this.name = name;
  this.isMulti = (type.search(/_multi$/) >= 0);
  this.type = this.isMulti ? type.substr(0, type.length - MULTI_TYPE.length)
      : type;
  this.status = status;
}

Node.prototype.isMdo = function() {
  return this.type === "mdo";
};

Node.prototype.getScenarioId = function() {
  if (this.isMdo()) {
    var idxscn = this.name.indexOf("_scn-");
    if (idxscn === -1) {
      console.log("Warning: MDO Scenario not found. "
          + "Bad type or name for node: " + JSON.stringify(this));
      return null;
    }
    return this.name.substr(idxscn + 1);
  }
  return null;
};

// *** Edge *******************************************************************
function Edge(from, to, nameOrVars, row, col, isMulti) {
  this.id = "link_" + from + "_" + to;
  if (typeof (nameOrVars) === "string") {
    this.name = nameOrVars;
    this.vars = {};
    let vars = this.name.split(',');
    vars.forEach((n, i) => this.vars[i] = n.trim());
  } else { // vars = {id: name, ...}
    this.vars = nameOrVars;
    let names = [];
    for (let k in this.vars) {
      names.push(this.vars[k]);
    }
    this.name = names.join(", ")
  }
  this.row = row;
  this.col = col;
  this.iotype = row < col ? "in" : "out";
  this.io = {
    fromU : (from === UID),
    toU : (to === UID),
  };
  this.isMulti = isMulti;
}

Edge.prototype.isIO = function() {
  return this.io.fromU || this.io.toU;
};

Edge.prototype.addVar = function(nameOrVar) {
  if (typeof(nameOrVar) === "string") {
    if (this.name==="") {
      this.name=nameOrVar;
    } else {
      this.name+=", "+nameOrVar;
    }
    this.vars[this.vars.length] = nameOrVar;
  } else {
    for (let k in nameOrVar) {
      this.vars[k] = nameOrVar[k];
      let names = [];
      for (let k in this.vars) {
        names.push(this.vars[k]);
      }
      this.name = names.join(", ")
    }
  }
}

Edge.prototype.removeVar = function(nameOrId) {
  let found = false;
  for (k in this.nameOrVars) {
    if (k === nameOrId) {
      this.nameOrVars.delete(k);
      found = true;
    }
  }
  if (!found) {
    for (k in this.nameOrVars) {
      if (this.nameOrVars[k] === nameOrId) {
        this.nameOrVars.delete(k);
        found = true;
      }
    }
  }
  if (found) {
    let names = [];
    for (let k in this.vars) {
      names.push(this.vars[k]);
    }
    this.name = names.join(", ");
  }
}

// *** Graph ******************************************************************
function Graph(mdo, refname) {
  this.nodes = [ new Node(UID, UID, "user") ];
  this.edges = [];
  this.chains = [];
  this.refname = refname || "";
  this._newNodeCount = 0;

  var numbering = Graph.number(mdo.workflow);
  var numPrefixes = numbering.toNum;
  this.nodesByStep = numbering.toNode;

  mdo.nodes.forEach(function(item) {
    var num = numPrefixes[item.id];
    this.nodes.push(new Node(item.id, num ? num + ":" + item.name : item.name,
        item.type, item.status));
  }, this);

  if (mdo.edges) {
    mdo.edges.forEach(function(item) {
      this.addEdge(item.from, item.to, item.vars?item.vars:item.name);
    }, this);
  }

  if (mdo.workflow) {
    this._makeChaining(mdo.workflow);
  }
}

Graph.NODE_STATUS = STATUS;

Graph.prototype._makeChaining = function(workflow) {
  var echain = Graph.expand(workflow);
  echain.forEach(function(leafChain) {
    if (leafChain.length < 2) {
      throw new Error("Bad process chain (" + leafChain.length + "elt)");
    } else {
      this.chains.push([]);
      var ids = this.nodes.map(function(elt) {
        return elt.id;
      });
      leafChain.forEach(function(item, j) {
        if (j !== 0) {
          var idA = ids.indexOf(leafChain[j - 1]);
          if (idA < 0) {
            throw new Error("Process chain element (" + leafChain[j - 1]
                + ") not found");
          }
          var idB = ids.indexOf(leafChain[j]);
          if (idB < 0) {
            throw new Error("Process chain element (" + leafChain[j]
                + ") not found");
          }
          if (idA !== idB) {
            this.chains[this.chains.length - 1].push([ idA, idB ]);
          }
        }
      }, this);
    }
  }, this);
};

Graph.prototype.idxOf = function(nodeId) {
  let idx = this.nodes.map(function(elt) {
    return elt.id;
  }).indexOf(nodeId);
  if (idx<0) {
    throw new Error("Graph.idxOf: "+nodeId+" not found in "+JSON.stringify(this.nodes));
  }
  return idx;
};

Graph.prototype.getNode = function(nodeId) {
  var theNode;
  this.nodes.forEach(function(node) {
    if (node.id === nodeId) {
      theNode = node;
    }
  }, this);
  return theNode;
};

Graph.prototype.getNodeFromIndex = function(idx) {
  var node;
  if (idx >= 0 && idx < this.nodes.length) {
    node = this.nodes[idx];
  } else {
    throw new Error("Index out of range : " + idx + " not in [0, "
        + (this.nodes.length - 1) + "]");
  }
  return node;
}

Graph.prototype.addNode = function(nodeName) {
  this._newNodeCount += 1;
  this.nodes
      .push(new Node("NewNode" + this._newNodeCount, nodeName, "analysis"));
};

Graph.prototype.removeNode = function(index) {
  var self = this;
  // Update edges
  var edges = this.findEdgesOf(index);
  edges.toRemove.forEach(function(edge) {
    var idx = self.edges.indexOf(edge);
    if (idx > -1) {
      self.edges.splice(idx, 1);
    }
  }, this);
  edges.toShift.forEach(function(edge) {
    if (edge.row > 1) {
      edge.row -= 1;
    }
    if (edge.col > 1) {
      edge.col -= 1;
    }
  }, this);

  // Update nodes
  this.nodes.splice(index, 1);
};

Graph.prototype.moveLeft = function(index) {
  if (index>1) {
    let tmp = this.nodes[index-1];
    this.nodes[index-1] = this.nodes[index];
    this.nodes[index] = tmp;
  }
};

Graph.prototype.moveRight = function(index) {
  if (index<this.nodes.length-1) {
    let tmp = this.nodes[index+1];
    this.nodes[index+1] = this.nodes[index];
    this.nodes[index] = tmp;
  }
};

Graph.prototype.addEdge = function(nodeIdFrom, nodeIdTo, nameOrVar) {
  var idA = this.idxOf(nodeIdFrom);
  var idB = this.idxOf(nodeIdTo);
  var isMulti = this.nodes[idA].isMulti || this.nodes[idB].isMulti;
  this.edges
      .push(new Edge(nodeIdFrom, nodeIdTo, nameOrVar, idA, idB, isMulti));
}

Graph.prototype.removeEdge = function(nodeIdFrom, nodeIdTo) {
  let edge = this.findEdge(nodeIdFrom, nodeIdTo);
  this.edges.splice(edge.index, 1);
}

Graph.prototype.addEdgeVar = function(nodeIdFrom, nodeIdTo, nameOrVar) {
  let edge = this.findEdge(nodeIdFrom, nodeIdTo).element;
  if (edge) {
    edge.addVar(nameOrVar);
  } else {
    this.addEdge(nodeIdFrom, nodeIdTo, nameOrVar)
  }
}

Graph.prototype.findEdgesOf = function(nodeIdx) {
  var toRemove = [];
  var toShift = [];
  this.edges.forEach(function(edge) {
    if ((edge.row === nodeIdx) || (edge.col === nodeIdx)) {
      toRemove.push(edge);
    } else if ((edge.row > nodeIdx) || (edge.col > nodeIdx)) {
      toShift.push(edge);
    }
  }, this);
  return {
    toRemove : toRemove,
    toShift : toShift
  };
};

Graph.prototype.findEdge = function(nodeIdFrom, nodeIdTo) {
  let element, index;
  let idxFrom = this.idxOf(nodeIdFrom);
  let idxTo = this.idxOf(nodeIdTo);
  this.edges.some(function(edge, i) {
    if ((edge.row === idxFrom) && (edge.col === idxTo)) {
      if (element) {
        throw Error('edge have be uniq between two nodes, but got: '+
            JSON.stringify(element)+ ' and '+JSON.stringify(edge))
      }
      element = edge;
      index = i;
      return true;
    }
  }, this);
  return {element, index};
}

function _expand(workflow) {
  var ret = [];
  var prev;
  workflow.forEach(function(item) {
    if (item instanceof Array) {
      if (item[0].hasOwnProperty('parallel')) {
        if (prev) {
          ret = ret.slice(0, ret.length - 1).concat(
              item[0].parallel.map(function(elt) {
                return [ prev ].concat(_expand([ elt ]), prev);
              }));
        } else {
          throw new Error("Bad workflow structure : "
              + "cannot parallel loop without previous starting point.");
        }
      } else if (prev) {
        ret = ret.concat(_expand(item), prev);
      } else {
        ret = ret.concat(_expand(item));
      }
      prev = ret[ret.length - 1];
    } else if (item.hasOwnProperty('parallel')) {
      if (prev) {
        ret = ret.slice(0, ret.length - 1).concat(
            item.parallel.map(function(elt) {
              return [ prev ].concat(_expand([ elt ]));
            }));
      } else {
        ret = ret.concat(item.parallel.map(function(elt) {
          return _expand([ elt ]);
        }));
      }
      prev = undefined;
    } else {
      var i = ret.length - 1;
      var flagParallel = false;
      while (i >= 0 && (ret[i] instanceof Array)) {
        ret[i] = ret[i].concat(item);
        i -= 1;
        flagParallel = true;
      }
      if (!flagParallel) {
        ret.push(item);
      }
      prev = item;
    }
  });
  return ret;
}

Graph._isPatchNeeded = function(toBePatched) {
  var lastElts = toBePatched.map(function(arr) {
    return arr[arr.length - 1];
  });
  var lastElt = lastElts[0];
  for (var i = 0; i < lastElts.length; i++) {
    if (lastElts[i] !== lastElt) {
      return true;
    }
  }
  return false;
};

Graph._patchParallel = function(expanded) {
  var toBePatched = [];
  expanded.forEach(function(elt) {
    if (elt instanceof Array) {
      toBePatched.push(elt);
    } else if (Graph._isPatchNeeded(toBePatched)) {
      toBePatched.forEach(function(arr) {
        arr.push(elt);
      }, this);
    }
  }, this);
};

Graph.expand = function(item) {
  var expanded = _expand(item);
  var result = [];
  var current = [];
  // first pass to add missing 'end link' in case of parallel branches at the
  // end of a loop
  // [a, [b, d], [b, c], a] -> [a, [b, d, a], [b, c, a], a]
  Graph._patchParallel(expanded);
  // [a, aa, [b, c], d] -> [[a, aa, b], [b,c], [c, d]]
  expanded.forEach(function(elt) {
    if (elt instanceof Array) {
      if (current.length > 0) {
        current.push(elt[0]);
        result.push(current);
        current = [];
      }
      result.push(elt);
    } else {
      if (result.length > 0 && current.length === 0) {
        var lastChain = result[result.length - 1];
        var lastElt = lastChain[lastChain.length - 1];
        current.push(lastElt);
      }
      current.push(elt);
    }
  }, this);
  if (current.length > 0) {
    result.push(current);
  }
  return result;
};

Graph.number = function(workflow, num) {
  num = (typeof num === 'undefined') ? 0 : num;
  var toNum = {};
  var toNode = [];

  function setStep(step, nodeId) {
    if (step in toNode) {
      toNode[step].push(nodeId);
    } else {
      toNode[step] = [ nodeId ];
    }
  }

  function setNum(nodeId, beg, end) {
    if (end === undefined) {
      num = String(beg);
      setStep(beg, nodeId);
    } else {
      num = end + "-" + beg;
      setStep(end, nodeId);
    }
    if (nodeId in toNum) {
      toNum[nodeId] += "," + num;
    } else {
      toNum[nodeId] = num;
    }
  }

  function _number(wks, num) {
    var ret = 0;
    if (wks instanceof Array) {
      if (wks.length === 0) {
        ret = num;
      } else if (wks.length === 1) {
        ret = _number(wks[0], num);
      } else {
        var head = wks[0];
        var tail = wks.slice(1);
        var beg = _number(head, num);
        if (tail[0] instanceof Array) {
          var end = _number(tail[0], beg);
          setNum(head, beg, end);
          beg = end + 1;
          tail.shift();
        }
        ret = _number(tail, beg);
      }
    } else if ((wks instanceof Object) && 'parallel' in wks) {
      var nums = wks.parallel.map(function(branch) {
        return _number(branch, num);
      });
      ret = Math.max.apply(null, nums);
    } else {
      setNum(wks, num);
      ret = num + 1;
    }
    return ret;
  }

  _number(workflow, num);
  // console.log('toNodes=', JSON.stringify(toNode));
  // console.log('toNum=',JSON.stringify(toNum));
  return {
    toNum : toNum,
    toNode : toNode
  };
};

module.exports = Graph;
<commit_msg>fix addNode<commit_after>var UID = "_U_";
var MULTI_TYPE = "_multi";

var STATUS = {
  UNKNOWN : 'UNKNOWN',
  PENDING : 'PENDING',
  RUNNING : 'RUNNING',
  DONE : 'DONE',
  FAILED : 'FAILED'
};

// *** Node *******************************************************************
function Node(id, name, type, status) {
  if (typeof (name) === 'undefined') {
    name = id;
  }
  if (typeof (type) === 'undefined') {
    type = 'analysis';
  }
  if (typeof (status) === 'undefined') {
    status = STATUS.UNKNOWN;
  }
  if (typeof STATUS[status] === 'undefined') {
    throw Error("Unknown status '" + status + "' for node " + name + "(id="
        + id + ")");
  }
  this.id = id;
  this.name = name;
  this.isMulti = (type.search(/_multi$/) >= 0);
  this.type = this.isMulti ? type.substr(0, type.length - MULTI_TYPE.length)
      : type;
  this.status = status;
}

Node.prototype.isMdo = function() {
  return this.type === "mdo";
};

Node.prototype.getScenarioId = function() {
  if (this.isMdo()) {
    var idxscn = this.name.indexOf("_scn-");
    if (idxscn === -1) {
      console.log("Warning: MDO Scenario not found. "
          + "Bad type or name for node: " + JSON.stringify(this));
      return null;
    }
    return this.name.substr(idxscn + 1);
  }
  return null;
};

// *** Edge *******************************************************************
function Edge(from, to, nameOrVars, row, col, isMulti) {
  this.id = "link_" + from + "_" + to;
  if (typeof (nameOrVars) === "string") {
    this.name = nameOrVars;
    this.vars = {};
    let vars = this.name.split(',');
    vars.forEach((n, i) => this.vars[i] = n.trim());
  } else { // vars = {id: name, ...}
    this.vars = nameOrVars;
    let names = [];
    for (let k in this.vars) {
      names.push(this.vars[k]);
    }
    this.name = names.join(", ")
  }
  this.row = row;
  this.col = col;
  this.iotype = row < col ? "in" : "out";
  this.io = {
    fromU : (from === UID),
    toU : (to === UID),
  };
  this.isMulti = isMulti;
}

Edge.prototype.isIO = function() {
  return this.io.fromU || this.io.toU;
};

Edge.prototype.addVar = function(nameOrVar) {
  if (typeof(nameOrVar) === "string") {
    if (this.name==="") {
      this.name=nameOrVar;
    } else {
      this.name+=", "+nameOrVar;
    }
    this.vars[this.vars.length] = nameOrVar;
  } else {
    for (let k in nameOrVar) {
      this.vars[k] = nameOrVar[k];
      let names = [];
      for (let k in this.vars) {
        names.push(this.vars[k]);
      }
      this.name = names.join(", ")
    }
  }
}

Edge.prototype.removeVar = function(nameOrId) {
  let found = false;
  for (k in this.nameOrVars) {
    if (k === nameOrId) {
      this.nameOrVars.delete(k);
      found = true;
    }
  }
  if (!found) {
    for (k in this.nameOrVars) {
      if (this.nameOrVars[k] === nameOrId) {
        this.nameOrVars.delete(k);
        found = true;
      }
    }
  }
  if (found) {
    let names = [];
    for (let k in this.vars) {
      names.push(this.vars[k]);
    }
    this.name = names.join(", ");
  }
}

// *** Graph ******************************************************************
function Graph(mdo, refname) {
  this.nodes = [ new Node(UID, UID, "user") ];
  this.edges = [];
  this.chains = [];
  this.refname = refname || "";
  this._newNodeCount = 0;

  var numbering = Graph.number(mdo.workflow);
  var numPrefixes = numbering.toNum;
  this.nodesByStep = numbering.toNode;

  mdo.nodes.forEach(function(item) {
    var num = numPrefixes[item.id];
    this.nodes.push(new Node(item.id, num ? num + ":" + item.name : item.name,
        item.type, item.status));
  }, this);

  if (mdo.edges) {
    mdo.edges.forEach(function(item) {
      this.addEdge(item.from, item.to, item.vars?item.vars:item.name);
    }, this);
  }

  if (mdo.workflow) {
    this._makeChaining(mdo.workflow);
  }
}

Graph.NODE_STATUS = STATUS;

Graph.prototype._makeChaining = function(workflow) {
  var echain = Graph.expand(workflow);
  echain.forEach(function(leafChain) {
    if (leafChain.length < 2) {
      throw new Error("Bad process chain (" + leafChain.length + "elt)");
    } else {
      this.chains.push([]);
      var ids = this.nodes.map(function(elt) {
        return elt.id;
      });
      leafChain.forEach(function(item, j) {
        if (j !== 0) {
          var idA = ids.indexOf(leafChain[j - 1]);
          if (idA < 0) {
            throw new Error("Process chain element (" + leafChain[j - 1]
                + ") not found");
          }
          var idB = ids.indexOf(leafChain[j]);
          if (idB < 0) {
            throw new Error("Process chain element (" + leafChain[j]
                + ") not found");
          }
          if (idA !== idB) {
            this.chains[this.chains.length - 1].push([ idA, idB ]);
          }
        }
      }, this);
    }
  }, this);
};

Graph.prototype.idxOf = function(nodeId) {
  let idx = this.nodes.map(function(elt) {
    return elt.id;
  }).indexOf(nodeId);
  if (idx<0) {
    throw new Error("Graph.idxOf: "+nodeId+" not found in "+JSON.stringify(this.nodes));
  }
  return idx;
};

Graph.prototype.getNode = function(nodeId) {
  var theNode;
  this.nodes.forEach(function(node) {
    if (node.id === nodeId) {
      theNode = node;
    }
  }, this);
  return theNode;
};

Graph.prototype.getNodeFromIndex = function(idx) {
  var node;
  if (idx >= 0 && idx < this.nodes.length) {
    node = this.nodes[idx];
  } else {
    throw new Error("Index out of range : " + idx + " not in [0, "
        + (this.nodes.length - 1) + "]");
  }
  return node;
}

Graph.prototype.addNode = function(node) {
  this._newNodeCount += 1;
  this.nodes.push(new Node(node.id, node.name, node.kind));
};

Graph.prototype.removeNode = function(index) {
  var self = this;
  // Update edges
  var edges = this.findEdgesOf(index);
  edges.toRemove.forEach(function(edge) {
    var idx = self.edges.indexOf(edge);
    if (idx > -1) {
      self.edges.splice(idx, 1);
    }
  }, this);
  edges.toShift.forEach(function(edge) {
    if (edge.row > 1) {
      edge.row -= 1;
    }
    if (edge.col > 1) {
      edge.col -= 1;
    }
  }, this);

  // Update nodes
  this.nodes.splice(index, 1);
};

Graph.prototype.moveLeft = function(index) {
  if (index>1) {
    let tmp = this.nodes[index-1];
    this.nodes[index-1] = this.nodes[index];
    this.nodes[index] = tmp;
  }
};

Graph.prototype.moveRight = function(index) {
  if (index<this.nodes.length-1) {
    let tmp = this.nodes[index+1];
    this.nodes[index+1] = this.nodes[index];
    this.nodes[index] = tmp;
  }
};

Graph.prototype.addEdge = function(nodeIdFrom, nodeIdTo, nameOrVar) {
  var idA = this.idxOf(nodeIdFrom);
  var idB = this.idxOf(nodeIdTo);
  var isMulti = this.nodes[idA].isMulti || this.nodes[idB].isMulti;
  this.edges
      .push(new Edge(nodeIdFrom, nodeIdTo, nameOrVar, idA, idB, isMulti));
}

Graph.prototype.removeEdge = function(nodeIdFrom, nodeIdTo) {
  let edge = this.findEdge(nodeIdFrom, nodeIdTo);
  this.edges.splice(edge.index, 1);
}

Graph.prototype.addEdgeVar = function(nodeIdFrom, nodeIdTo, nameOrVar) {
  let edge = this.findEdge(nodeIdFrom, nodeIdTo).element;
  if (edge) {
    edge.addVar(nameOrVar);
  } else {
    this.addEdge(nodeIdFrom, nodeIdTo, nameOrVar)
  }
}

Graph.prototype.findEdgesOf = function(nodeIdx) {
  var toRemove = [];
  var toShift = [];
  this.edges.forEach(function(edge) {
    if ((edge.row === nodeIdx) || (edge.col === nodeIdx)) {
      toRemove.push(edge);
    } else if ((edge.row > nodeIdx) || (edge.col > nodeIdx)) {
      toShift.push(edge);
    }
  }, this);
  return {
    toRemove : toRemove,
    toShift : toShift
  };
};

Graph.prototype.findEdge = function(nodeIdFrom, nodeIdTo) {
  let element, index;
  let idxFrom = this.idxOf(nodeIdFrom);
  let idxTo = this.idxOf(nodeIdTo);
  this.edges.some(function(edge, i) {
    if ((edge.row === idxFrom) && (edge.col === idxTo)) {
      if (element) {
        throw Error('edge have be uniq between two nodes, but got: '+
            JSON.stringify(element)+ ' and '+JSON.stringify(edge))
      }
      element = edge;
      index = i;
      return true;
    }
  }, this);
  return {element, index};
}

function _expand(workflow) {
  var ret = [];
  var prev;
  workflow.forEach(function(item) {
    if (item instanceof Array) {
      if (item[0].hasOwnProperty('parallel')) {
        if (prev) {
          ret = ret.slice(0, ret.length - 1).concat(
              item[0].parallel.map(function(elt) {
                return [ prev ].concat(_expand([ elt ]), prev);
              }));
        } else {
          throw new Error("Bad workflow structure : "
              + "cannot parallel loop without previous starting point.");
        }
      } else if (prev) {
        ret = ret.concat(_expand(item), prev);
      } else {
        ret = ret.concat(_expand(item));
      }
      prev = ret[ret.length - 1];
    } else if (item.hasOwnProperty('parallel')) {
      if (prev) {
        ret = ret.slice(0, ret.length - 1).concat(
            item.parallel.map(function(elt) {
              return [ prev ].concat(_expand([ elt ]));
            }));
      } else {
        ret = ret.concat(item.parallel.map(function(elt) {
          return _expand([ elt ]);
        }));
      }
      prev = undefined;
    } else {
      var i = ret.length - 1;
      var flagParallel = false;
      while (i >= 0 && (ret[i] instanceof Array)) {
        ret[i] = ret[i].concat(item);
        i -= 1;
        flagParallel = true;
      }
      if (!flagParallel) {
        ret.push(item);
      }
      prev = item;
    }
  });
  return ret;
}

Graph._isPatchNeeded = function(toBePatched) {
  var lastElts = toBePatched.map(function(arr) {
    return arr[arr.length - 1];
  });
  var lastElt = lastElts[0];
  for (var i = 0; i < lastElts.length; i++) {
    if (lastElts[i] !== lastElt) {
      return true;
    }
  }
  return false;
};

Graph._patchParallel = function(expanded) {
  var toBePatched = [];
  expanded.forEach(function(elt) {
    if (elt instanceof Array) {
      toBePatched.push(elt);
    } else if (Graph._isPatchNeeded(toBePatched)) {
      toBePatched.forEach(function(arr) {
        arr.push(elt);
      }, this);
    }
  }, this);
};

Graph.expand = function(item) {
  var expanded = _expand(item);
  var result = [];
  var current = [];
  // first pass to add missing 'end link' in case of parallel branches at the
  // end of a loop
  // [a, [b, d], [b, c], a] -> [a, [b, d, a], [b, c, a], a]
  Graph._patchParallel(expanded);
  // [a, aa, [b, c], d] -> [[a, aa, b], [b,c], [c, d]]
  expanded.forEach(function(elt) {
    if (elt instanceof Array) {
      if (current.length > 0) {
        current.push(elt[0]);
        result.push(current);
        current = [];
      }
      result.push(elt);
    } else {
      if (result.length > 0 && current.length === 0) {
        var lastChain = result[result.length - 1];
        var lastElt = lastChain[lastChain.length - 1];
        current.push(lastElt);
      }
      current.push(elt);
    }
  }, this);
  if (current.length > 0) {
    result.push(current);
  }
  return result;
};

Graph.number = function(workflow, num) {
  num = (typeof num === 'undefined') ? 0 : num;
  var toNum = {};
  var toNode = [];

  function setStep(step, nodeId) {
    if (step in toNode) {
      toNode[step].push(nodeId);
    } else {
      toNode[step] = [ nodeId ];
    }
  }

  function setNum(nodeId, beg, end) {
    if (end === undefined) {
      num = String(beg);
      setStep(beg, nodeId);
    } else {
      num = end + "-" + beg;
      setStep(end, nodeId);
    }
    if (nodeId in toNum) {
      toNum[nodeId] += "," + num;
    } else {
      toNum[nodeId] = num;
    }
  }

  function _number(wks, num) {
    var ret = 0;
    if (wks instanceof Array) {
      if (wks.length === 0) {
        ret = num;
      } else if (wks.length === 1) {
        ret = _number(wks[0], num);
      } else {
        var head = wks[0];
        var tail = wks.slice(1);
        var beg = _number(head, num);
        if (tail[0] instanceof Array) {
          var end = _number(tail[0], beg);
          setNum(head, beg, end);
          beg = end + 1;
          tail.shift();
        }
        ret = _number(tail, beg);
      }
    } else if ((wks instanceof Object) && 'parallel' in wks) {
      var nums = wks.parallel.map(function(branch) {
        return _number(branch, num);
      });
      ret = Math.max.apply(null, nums);
    } else {
      setNum(wks, num);
      ret = num + 1;
    }
    return ret;
  }

  _number(workflow, num);
  // console.log('toNodes=', JSON.stringify(toNode));
  // console.log('toNum=',JSON.stringify(toNum));
  return {
    toNum : toNum,
    toNode : toNode
  };
};

module.exports = Graph;
<|endoftext|>


<commit_before>/* global __DEV__ */
import React from 'react'
import { render } from 'react-dom'

import ROOT from 'containers/Root'

if (__DEV__) {
  const RedBox = require('redbox-react')
  try {
    render(ROOT, document.getElementById('root'))
  } catch (e) {
    render(<RedBox error={ e } />, document.getElementById('root'))
  }
} else {
  React.render(ROOT, document.getElementById('root'))
}
<commit_msg>Destroy Deprecated code.<commit_after>/* global __DEV__ */
import React from 'react'
import { render } from 'react-dom'

import ROOT from 'containers/Root'

if (__DEV__) {
  const RedBox = require('redbox-react')
  try {
    render(ROOT, document.getElementById('root'))
  } catch (e) {
    render(<RedBox error={ e } />, document.getElementById('root'))
  }
} else {
  render(ROOT, document.getElementById('root'))
}
<|endoftext|>


<commit_before>/* eslint-env browser */

import './lib/displayProjectsGraph';

// TODO: Hook this up to the log out button on the graph view. It is currently not hooked up to anything,
// but functions properly
document.addEventListener('DOMContentLoaded', () => {
  document.getElementById('logOut').addEventListener('click', () => {
    document.location.href = '/logout';
  });
});

/**
 * Query the page for a set of elements given a CSS selector.
 *
 * @param selector CSS selector
 * @returns {*} Array of matched elements
 */
function querySelectorAll (selector) {
  return Array.prototype.slice.call(document.querySelectorAll(selector));
}

document.addEventListener('DOMContentLoaded', () => {
  querySelectorAll('#projects a').forEach(projectAnchor => {
    projectAnchor.addEventListener('click', event => {
      let selectedProject = event.target.getAttribute('data-id');
      let hierarchy = getHierarchyRequest('/hierarchy', selectedProject);
      let graph = getGraphRequest('/graph', selectedProject);
      // Temporary statement for linter
      console.log(graph + hierarchy);
      // TODO: change query parameter (dependent on hierarchy endpoint story)
    });
  });
});

/**
 * Makes an AJAX request to the provided endpoint for the item hierarchy tree.
 *
 * @param url
 * @param projectId
 * @returns {*}
 */
function getHierarchyRequest (url, projectId) {
  let hierarchy = {};
  // TODO: Refactor to use the request module
  let httpRequest = new XMLHttpRequest();
  httpRequest.onreadystatechange = () => {
    if (httpRequest.readyState === XMLHttpRequest.DONE) {
      if (httpRequest.status === 200) {
        hierarchy = JSON.parse(httpRequest.responseText);
        console.log(httpRequest.responseText);
      } else {
        console.log('There was a problem requesting to the hierarchy endpoint.');
      }
    }
  };
  httpRequest.open('GET', url);
  httpRequest.send('project=' + projectId);
  return hierarchy;
}

/**
 * Makes an AJAX request to the provided endpoint for the project graph.
 *
 * @param url
 * @param projectId
 * @returns {*}
 */
function getGraphRequest (url, projectId) {
  let graph = {};
  // TODO: Refactor to use the request module
  let httpRequest = new XMLHttpRequest();
  httpRequest.onreadystatechange = () => {
    if (httpRequest.readyState === XMLHttpRequest.DONE) {
      if (httpRequest.status === 200) {
        graph = JSON.parse(httpRequest.responseText);
        console.log(httpRequest.responseText);
      } else {
        console.log('There was a problem requesting to the graph endpoint.');
      }
    }
  };
  httpRequest.open('GET', url);
  httpRequest.send('project=' + projectId);
  return graph;
}
<commit_msg>Try to prepare for graph request<commit_after>/* eslint-env browser */

import './lib/displayProjectsGraph';

// TODO: Hook this up to the log out button on the graph view. It is currently not hooked up to anything,
// but functions properly
document.addEventListener('DOMContentLoaded', () => {
  document.getElementById('logOut').addEventListener('click', () => {
    document.location.href = '/logout';
  });
});

/**
 * Query the page for a set of elements given a CSS selector.
 *
 * @param selector CSS selector
 * @returns {*} Array of matched elements
 */
function querySelectorAll (selector) {
  return Array.prototype.slice.call(document.querySelectorAll(selector));
}

document.addEventListener('DOMContentLoaded', () => {
  querySelectorAll('#projects a').forEach(projectAnchor => {
    projectAnchor.addEventListener('click', event => {
      let selectedProject = event.target.getAttribute('data-id');
      getHierarchyRequest('/hierarchy', selectedProject);
      getGraphRequest('/graph', selectedProject, (graph) => {
        console.log(graph);
      });
      // TODO: change query parameter (dependent on hierarchy endpoint story)
    });
  });
});

/**
 * Makes an AJAX request to the provided endpoint for the item hierarchy tree.
 *
 * @param url
 * @param projectId
 * @returns {*}
 */
function getHierarchyRequest (url, projectId) {
  let hierarchy = {};
  // TODO: Refactor to use the request module
  let httpRequest = new XMLHttpRequest();
  httpRequest.onreadystatechange = () => {
    if (httpRequest.readyState === XMLHttpRequest.DONE) {
      if (httpRequest.status === 200) {
        hierarchy = JSON.parse(httpRequest.responseText);
        console.log(httpRequest.responseText);
      } else {
        console.log('There was a problem requesting to the hierarchy endpoint.');
      }
    }
  };
  httpRequest.open('GET', url);
  httpRequest.send('project=' + projectId);
  return hierarchy;
}

/**
 * Makes an AJAX request to the provided endpoint for the project graph.
 *
 * @param url
 * @param projectId
 * @param callback
 * @returns {*}
 */
function getGraphRequest (url, projectId, callback) {
  // TODO: Refactor to use the request module and promises
  let httpRequest = new XMLHttpRequest();
  httpRequest.onreadystatechange = () => {
    if (httpRequest.readyState === XMLHttpRequest.DONE) {
      if (httpRequest.status === 200) {
        callback(JSON.parse(httpRequest.responseText));
        console.log(httpRequest.responseText);
      } else {
        console.log('There was a problem requesting to the graph endpoint.');
      }
    }
  };
  httpRequest.open('GET', url + '?project=' + projectId);
  httpRequest.send();
}
<|endoftext|>


<commit_before>const fsExtra = require('fs-extra');
const path = require('path');
const argv = require('minimist')(process.argv.slice(2), { string: 'version' });

const version = argv.version;

if (!version) {
    console.error(`missing argument 'version'`);
    process.exit(1);
    return;
}

const packageJSONPath = path.resolve(__dirname, '../package.json');

const packageJSON = fsExtra.readJSONSync(packageJSONPath);

packageJSON.version = version;
packageJSON.private = false;
packageJSON.dependencies = {};

fsExtra.writeJSONSync(packageJSONPath, packageJSON, { spaces: 2 })
<commit_msg>fix: missing dependencies in deployed package<commit_after>const fsExtra = require('fs-extra');
const path = require('path');
const argv = require('minimist')(process.argv.slice(2), { string: 'version' });

const version = argv.version;

if (!version) {
    console.error(`missing argument 'version'`);
    process.exit(1);
    return;
}

const packageJSONPath = path.resolve(__dirname, '../package.json');

const packageJSON = fsExtra.readJSONSync(packageJSONPath);

packageJSON.version = version;
packageJSON.private = false;

fsExtra.writeJSONSync(packageJSONPath, packageJSON, { spaces: 2 })
<|endoftext|>


<commit_before>import React, { Suspense } from 'react'
import { act, create } from 'react-test-renderer'

function TestHook({ callback, hookProps, onError, children }) {
  try {
    children(callback(hookProps))
  } catch (err) {
    onError(err)
  }
  return null
}

function Fallback() {
  return null
}

function resultContainer() {
  let value = null
  let error = null
  const resolvers = []

  const result = {
    get current() {
      if (error) {
        throw error
      }
      return value
    },
    get error() {
      return error
    }
  }

  const updateResult = (val, err) => {
    value = val
    error = err
    resolvers.splice(0, resolvers.length).forEach((resolve) => resolve())
  }

  return {
    result,
    addResolver: (resolver) => {
      resolvers.push(resolver)
    },
    setValue: (val) => updateResult(val),
    setError: (err) => updateResult(undefined, err)
  }
}

function renderHook(callback, { initialProps, wrapper } = {}) {
  const { result, setValue, setError, addResolver } = resultContainer()
  const hookProps = { current: initialProps }

  const wrapUiIfNeeded = (innerElement) =>
    wrapper ? React.createElement(wrapper, null, innerElement) : innerElement

  const toRender = () =>
    wrapUiIfNeeded(
      <Suspense fallback={<Fallback />}>
        <TestHook callback={callback} hookProps={hookProps.current} onError={setError}>
          {setValue}
        </TestHook>
      </Suspense>
    )

  let testRenderer
  act(() => {
    testRenderer = create(toRender())
  })
  const { unmount, update } = testRenderer

  return {
    result,
    waitForNextUpdate: () => new Promise((resolve) => addResolver(resolve)),
    rerender: (newProps = hookProps.current) => {
      hookProps.current = newProps
      act(() => {
        update(toRender())
      })
    },
    unmount: () => {
      act(() => {
        unmount()
      })
    }
  }
}

function testHook(...args) {
  console.warn(
    '`testHook` has been deprecated and will be removed in a future release.  Please use `renderHook` instead.'
  )
  return renderHook(...args)
}

export { renderHook, act, testHook }
<commit_msg>Don't catch promises so enable suspense to work<commit_after>import React, { Suspense } from 'react'
import { act, create } from 'react-test-renderer'

function TestHook({ callback, hookProps, onError, children }) {
  try {
    children(callback(hookProps))
  } catch (err) {
    if (err.then) {
      throw err
    } else {
      onError(err)
    }
  }
  return null
}

function Fallback() {
  return null
}

function resultContainer() {
  let value = null
  let error = null
  const resolvers = []

  const result = {
    get current() {
      if (error) {
        throw error
      }
      return value
    },
    get error() {
      return error
    }
  }

  const updateResult = (val, err) => {
    value = val
    error = err
    resolvers.splice(0, resolvers.length).forEach((resolve) => resolve())
  }

  return {
    result,
    addResolver: (resolver) => {
      resolvers.push(resolver)
    },
    setValue: (val) => updateResult(val),
    setError: (err) => updateResult(undefined, err)
  }
}

function renderHook(callback, { initialProps, wrapper } = {}) {
  const { result, setValue, setError, addResolver } = resultContainer()
  const hookProps = { current: initialProps }

  const wrapUiIfNeeded = (innerElement) =>
    wrapper ? React.createElement(wrapper, null, innerElement) : innerElement

  const toRender = () =>
    wrapUiIfNeeded(
      <Suspense fallback={<Fallback />}>
        <TestHook callback={callback} hookProps={hookProps.current} onError={setError}>
          {setValue}
        </TestHook>
      </Suspense>
    )

  let testRenderer
  act(() => {
    testRenderer = create(toRender())
  })
  const { unmount, update } = testRenderer

  return {
    result,
    waitForNextUpdate: () => new Promise((resolve) => addResolver(resolve)),
    rerender: (newProps = hookProps.current) => {
      hookProps.current = newProps
      act(() => {
        update(toRender())
      })
    },
    unmount: () => {
      act(() => {
        unmount()
      })
    }
  }
}

function testHook(...args) {
  console.warn(
    '`testHook` has been deprecated and will be removed in a future release.  Please use `renderHook` instead.'
  )
  return renderHook(...args)
}

export { renderHook, act, testHook }
<|endoftext|>


<commit_before>var React = require('react-native');

var StyleSheetRegistry = require('react-native/Libraries/ReactNative/ReactNativePropRegistry');

module.exports = function(incomingProps, defaultProps) {

    // External props has a higher precedence
    var computedProps = {};

    incomingProps = _.clone(incomingProps);
    delete incomingProps.children;

    // console.log(defaultProps, incomingProps);

    if(incomingProps)
        _.merge(computedProps, defaultProps, incomingProps);
    else
        computedProps = defaultProps;

    // Pass the merged Style Object instead
    if(incomingProps.style) {

        if(typeof incomingProps.style == 'number') {
            var incomingPropsStyle = StyleSheetRegistry.getStyleByID(incomingProps.style);
            computedProps.style = {};
        } else {
            var incomingPropsStyle = incomingProps.style;
        }

        _.merge(computedProps.style, defaultProps.style, incomingPropsStyle);

    }

    // console.log("computedProps ", computedProps);

    return computedProps;

}<commit_msg>remove unused import React from computeProps<commit_after>var StyleSheetRegistry = require('react-native/Libraries/ReactNative/ReactNativePropRegistry');

module.exports = function(incomingProps, defaultProps) {

    // External props has a higher precedence
    var computedProps = {};

    incomingProps = _.clone(incomingProps);
    delete incomingProps.children;

    // console.log(defaultProps, incomingProps);

    if(incomingProps)
        _.merge(computedProps, defaultProps, incomingProps);
    else
        computedProps = defaultProps;

    // Pass the merged Style Object instead
    if(incomingProps.style) {

        if(typeof incomingProps.style == 'number') {
            var incomingPropsStyle = StyleSheetRegistry.getStyleByID(incomingProps.style);
            computedProps.style = {};
        } else {
            var incomingPropsStyle = incomingProps.style;
        }

        _.merge(computedProps.style, defaultProps.style, incomingPropsStyle);

    }

    // console.log("computedProps ", computedProps);

    return computedProps;

}<|endoftext|>


<commit_before>
// Require index.html so it gets copied to dist
require('./index.html');
require('./index.scss');
require('../favicon.ico');

require("c3/c3.css");

var d3 = require("d3");
var c3 = require("c3");

var Elm = require('./Main.elm');

var mountNode = document.querySelector('main');

// .embed() can take an optional second argument. This would be an object describing the data we need to start a program, i.e. a userID or some token
var app = Elm.Main.embed(mountNode);

var charts = {};

function generateChart(object) {
  var element = document.getElementById(object.domId);
  console.log("chart element is: ", element);
  var chart = c3.generate({
    bindto: "#" + object.domId,
    type: 'line',
    data: {
      x: 'x',
      columns: [],
    },
    axis: {
      y: {
        label: {
          text: "Nettonåverdi",
          position: 'outer-middle'
        },
        tick: {
          //format: $scope.tickFormat
        }
      },
      x: {
        tick: {
          //format: $scope.tickFormat
        }
      }
    },
    grid: {
      y: {
        lines: [
          {value: 0, text: "Grense for lønnsomhet"}
        ]
      }
    }
  });

  charts[object.domId] = chart;
  updateChart(chart, object.data, object.variableTitle);
  app.ports.charts.send(Object.keys(charts));

}

app.ports.generateC3.subscribe(function (object) {
  console.log("generateC3", object.domId);
  requestAnimationFrame(
    function() {
      generateChart(object);
    },
    1);
});

function updateChart(chart, realData, variableTitle) {
  var dataRows = [].concat([['x', 'Nettonåverdi']], realData);
  chart.axis.labels({x: variableTitle});
  chart.load(
    {
      rows: dataRows,
    });

}

app.ports.updateC3.subscribe(function (object) {
  console.log('update', object);
  var chart = charts[object.domId];
  updateChart(chart, object.data, object.variableTitle);
});

app.ports.destroyC3.subscribe(function (domId) {
  console.log("destroyC3", domId);
  charts[domId].destroy();
  delete charts[domId];
  app.ports.charts.send(Object.keys(charts));
});

app.ports.setTitle.subscribe(function (title) {
  document.title = title;
});
<commit_msg>Make javascript code robust. Fixes #43<commit_after>
// Require index.html so it gets copied to dist
require('./index.html');
require('./index.scss');
require('../favicon.ico');

require("c3/c3.css");

var d3 = require("d3");
var c3 = require("c3");

var Elm = require('./Main.elm');

var mountNode = document.querySelector('main');

// .embed() can take an optional second argument. This would be an object describing the data we need to start a program, i.e. a userID or some token
var app = Elm.Main.embed(mountNode);

var charts = {};

function generateChart(object) {
  var element = document.getElementById(object.domId);
  console.log("chart element is: ", element);
  var chart = c3.generate({
    bindto: "#" + object.domId,
    type: 'line',
    data: {
      x: 'x',
      columns: [],
    },
    axis: {
      y: {
        label: {
          text: "Nettonåverdi",
          position: 'outer-middle'
        },
        tick: {
          //format: $scope.tickFormat
        }
      },
      x: {
        tick: {
          //format: $scope.tickFormat
        }
      }
    },
    grid: {
      y: {
        lines: [
          {value: 0, text: "Grense for lønnsomhet"}
        ]
      }
    }
  });

  charts[object.domId] = chart;
  updateChart(chart, object.data, object.variableTitle);
  app.ports.charts.send(Object.keys(charts));

}

app.ports.generateC3.subscribe(function (object) {
  console.log("generateC3", object.domId);
  requestAnimationFrame(
    function() {
      generateChart(object);
    },
    1);
});

function updateChart(chart, realData, variableTitle) {
  var dataRows = [].concat([['x', 'Nettonåverdi']], realData);
  chart.axis.labels({x: variableTitle});
  chart.load(
    {
      rows: dataRows,
    });

}

app.ports.updateC3.subscribe(function (object) {
  console.log('update', object);
  var chart = charts[object.domId];
  if (!chart) {
    console.log('the chart', object.domId, 'is gone');
    return;
  }
  updateChart(chart, object.data, object.variableTitle);
});

app.ports.destroyC3.subscribe(function (domId) {
  console.log("destroyC3", domId);
  charts[domId].destroy();
  delete charts[domId];
  app.ports.charts.send(Object.keys(charts));
});

app.ports.setTitle.subscribe(function (title) {
  document.title = title;
});
<|endoftext|>


<commit_before>import 'lie/polyfill'

import 'babel-core/polyfill'
import 'whatwg-fetch'

import React from 'react'
React.initializeTouchEvents(true)

import {Parse} from 'parse'
window.Parse = Parse
Parse.initialize('3YmZ7OaEPjPzP7yg19Wts1VGYmVr2qCw36nZIDYD', 'lWmcTJJ7ADHlHh5pTWudTiimBODHy3lEUYz5vlnG')
Parse.Analytics.track('load', {browser: navigator.userAgent})

import './index.scss'

import './start-things/bind-keys'
import './start-things/start-notifications'
import './start-things/start-global-pollution'
import './start-things/start-data-loading'
import './start-things/start-router'
<commit_msg>only submit to analytics if NODE_ENV=production<commit_after>import 'lie/polyfill'

import 'babel-core/polyfill'
import 'whatwg-fetch'

import React from 'react'
React.initializeTouchEvents(true)

import {Parse} from 'parse'
if (process.env.NODE_ENV === 'production') {
	window.Parse = Parse
	Parse.initialize('3YmZ7OaEPjPzP7yg19Wts1VGYmVr2qCw36nZIDYD', 'lWmcTJJ7ADHlHh5pTWudTiimBODHy3lEUYz5vlnG')
	Parse.Analytics.track('load', {browser: navigator.userAgent})
}

import './index.scss'

import './start-things/bind-keys'
import './start-things/start-notifications'
import './start-things/start-global-pollution'
import './start-things/start-data-loading'
import './start-things/start-router'
<|endoftext|>


<commit_before>import React, { useMemo } from 'react'
import Svg, {
  Defs,
  G,
  Path,
  Rect,
  Image,
  ClipPath,
  LinearGradient,
  Stop
} from 'react-native-svg'
import genMatrix from './genMatrix'
import transformMatrixIntoPath from './transformMatrixIntoPath'

const renderLogo = ({
  size,
  logo,
  logoSize,
  logoBackgroundColor,
  logoMargin,
  logoBorderRadius
}) => {
  const logoPosition = (size - logoSize - logoMargin * 2) / 2
  const logoBackgroundSize = logoSize + logoMargin * 2
  const logoBackgroundBorderRadius =
    logoBorderRadius + (logoMargin / logoSize) * logoBorderRadius

  return (
    <G x={logoPosition} y={logoPosition}>
      <Defs>
        <ClipPath id='clip-logo-background'>
          <Rect
            width={logoBackgroundSize}
            height={logoBackgroundSize}
            rx={logoBackgroundBorderRadius}
            ry={logoBackgroundBorderRadius}
          />
        </ClipPath>
        <ClipPath id='clip-logo'>
          <Rect
            width={logoSize}
            height={logoSize}
            rx={logoBorderRadius}
            ry={logoBorderRadius}
          />
        </ClipPath>
      </Defs>
      <G>
        <Rect
          width={logoBackgroundSize}
          height={logoBackgroundSize}
          fill={logoBackgroundColor}
          clipPath='url(#clip-logo-background)'
        />
      </G>
      <G x={logoMargin} y={logoMargin}>
        <Image
          width={logoSize}
          height={logoSize}
          preserveAspectRatio='xMidYMid slice'
          href={logo}
          clipPath='url(#clip-logo)'
        />
      </G>
    </G>
  )
}

const QRCode = ({
  value = 'this is a QR code',
  size = 100,
  color = 'black',
  backgroundColor = 'white',
  logo,
  logoSize = 100 * 0.2,
  logoBackgroundColor = 'transparent',
  logoMargin = 2,
  logoBorderRadius = 0,
  quietZone = 0,
  enableLinearGradient = false,
  gradientDirection = ['0%', '0%', '100%', '100%'],
  linearGradient = ['rgb(255,0,0)', 'rgb(0,255,255)'],
  ecl = 'M',
  getRef,
  onError
}) => {
  const result = useMemo(() => {
    try {
      return transformMatrixIntoPath(genMatrix(value, ecl), size)
    } catch (error) {
      if (onError && typeof onError === 'function') {
        onError(error)
      } else {
        // Pass the error when no handler presented
        throw error
      }
    }
  }, [value, size, ecl])

  if (!result) {
    return null
  }

  const { path, cellSize } = result

  return (
    <Svg
      ref={getRef}
      viewBox={[
        -quietZone,
        -quietZone,
        size + quietZone * 2,
        size + quietZone * 2
      ].join(' ')}
      width={size}
      height={size}
    >
      <Defs>
        <LinearGradient
          id='grad'
          x1={gradientDirection[0]}
          y1={gradientDirection[1]}
          x2={gradientDirection[2]}
          y2={gradientDirection[3]}
        >
          <Stop offset='0' stopColor={linearGradient[0]} stopOpacity='1' />
          <Stop offset='1' stopColor={linearGradient[1]} stopOpacity='1' />
        </LinearGradient>
      </Defs>
      <G>
        <Rect width={size} height={size} fill={backgroundColor} />
      </G>
      <G>
        <Path
          d={path}
          stroke={enableLinearGradient ? 'url(#grad)' : color}
          strokeWidth={cellSize}
        />
      </G>
      {logo &&
        renderLogo({
          size,
          logo,
          logoSize,
          logoBackgroundColor,
          logoMargin,
          logoBorderRadius
        })}
    </Svg>
  )
}

export default QRCode
<commit_msg>Fix default logoSize<commit_after>import React, { useMemo } from 'react'
import Svg, {
  Defs,
  G,
  Path,
  Rect,
  Image,
  ClipPath,
  LinearGradient,
  Stop
} from 'react-native-svg'
import genMatrix from './genMatrix'
import transformMatrixIntoPath from './transformMatrixIntoPath'

const renderLogo = ({
  size,
  logo,
  logoSize,
  logoBackgroundColor,
  logoMargin,
  logoBorderRadius
}) => {
  const logoPosition = (size - logoSize - logoMargin * 2) / 2
  const logoBackgroundSize = logoSize + logoMargin * 2
  const logoBackgroundBorderRadius =
    logoBorderRadius + (logoMargin / logoSize) * logoBorderRadius

  return (
    <G x={logoPosition} y={logoPosition}>
      <Defs>
        <ClipPath id='clip-logo-background'>
          <Rect
            width={logoBackgroundSize}
            height={logoBackgroundSize}
            rx={logoBackgroundBorderRadius}
            ry={logoBackgroundBorderRadius}
          />
        </ClipPath>
        <ClipPath id='clip-logo'>
          <Rect
            width={logoSize}
            height={logoSize}
            rx={logoBorderRadius}
            ry={logoBorderRadius}
          />
        </ClipPath>
      </Defs>
      <G>
        <Rect
          width={logoBackgroundSize}
          height={logoBackgroundSize}
          fill={logoBackgroundColor}
          clipPath='url(#clip-logo-background)'
        />
      </G>
      <G x={logoMargin} y={logoMargin}>
        <Image
          width={logoSize}
          height={logoSize}
          preserveAspectRatio='xMidYMid slice'
          href={logo}
          clipPath='url(#clip-logo)'
        />
      </G>
    </G>
  )
}

const QRCode = ({
  value = 'this is a QR code',
  size = 100,
  color = 'black',
  backgroundColor = 'white',
  logo,
  logoSize = size * 0.2,
  logoBackgroundColor = 'transparent',
  logoMargin = 2,
  logoBorderRadius = 0,
  quietZone = 0,
  enableLinearGradient = false,
  gradientDirection = ['0%', '0%', '100%', '100%'],
  linearGradient = ['rgb(255,0,0)', 'rgb(0,255,255)'],
  ecl = 'M',
  getRef,
  onError
}) => {
  const result = useMemo(() => {
    try {
      return transformMatrixIntoPath(genMatrix(value, ecl), size)
    } catch (error) {
      if (onError && typeof onError === 'function') {
        onError(error)
      } else {
        // Pass the error when no handler presented
        throw error
      }
    }
  }, [value, size, ecl])

  if (!result) {
    return null
  }

  const { path, cellSize } = result

  return (
    <Svg
      ref={getRef}
      viewBox={[
        -quietZone,
        -quietZone,
        size + quietZone * 2,
        size + quietZone * 2
      ].join(' ')}
      width={size}
      height={size}
    >
      <Defs>
        <LinearGradient
          id='grad'
          x1={gradientDirection[0]}
          y1={gradientDirection[1]}
          x2={gradientDirection[2]}
          y2={gradientDirection[3]}
        >
          <Stop offset='0' stopColor={linearGradient[0]} stopOpacity='1' />
          <Stop offset='1' stopColor={linearGradient[1]} stopOpacity='1' />
        </LinearGradient>
      </Defs>
      <G>
        <Rect width={size} height={size} fill={backgroundColor} />
      </G>
      <G>
        <Path
          d={path}
          stroke={enableLinearGradient ? 'url(#grad)' : color}
          strokeWidth={cellSize}
        />
      </G>
      {logo &&
        renderLogo({
          size,
          logo,
          logoSize,
          logoBackgroundColor,
          logoMargin,
          logoBorderRadius
        })}
    </Svg>
  )
}

export default QRCode
<|endoftext|>


<commit_before>'use strict';

var angular = require('angular');

module.exports = angular.module('pacApp', [])

.directive('pacBookDetails', require('./BookDetails.3.directive'))
.directive('pacBookOverview', require('./BookOverview.directive'))

.factory('httpBook', require('./HttpBook.4.factory'))

// warmup
//.run(function(httpBook) { httpBook.get(); })

// simulate illegal op
//.run(function(httpBook) { httpBook.get(function(book) { book.countPages(); }); })

.name;
<commit_msg>step4f<commit_after>'use strict';

var angular = require('angular');

module.exports = angular.module('pacApp', [])

.directive('pacBookDetails', require('./BookDetails.directive'))
.directive('pacBookOverview', require('./BookOverview.directive'))

.factory('httpBook', require('./HttpBook.4.factory'))

// warmup
//.run(function(httpBook) { httpBook.get(); })

// simulate illegal op
//.run(function(httpBook) { httpBook.get(function(book) { book.countPages(); }); })

.name;
<|endoftext|>