<commit_before>var RiakRecord = function() {
};

RiakRecord.prototype.delete = function(cb) {
	this.bucket.remove(this, function(err) {
		if(err) {
			return cb(err);
		}
		return cb(null);
	});
};

RiakRecord.prototype.load = function(cb) {
	var that = this;
	this.bucket.find(this.key(), function(err, res) {
		if(err) {
			return cb(err);
		}

		that._setVClock(res);
		that._transform(res);
		that._makeIndexes(res);
		cb(null, that);
	});
};

RiakRecord.prototype.updateAttribute = function(attributeName, attributeValue, cb) {
	this[attributeName] = attributeValue;
	if(!this.valid()) {
		return cb(new Error('Invalid element'));
	}
	this.save(function(err, res) {
		if(err) {
			cb(err);
		}
		cb(null, res);
	});
};

RiakRecord.prototype.save = function(cb) {
	if(!this.valid()) {
		return cb(new Error('Invalid element'));
	}
	this.bucket.save(this, cb);
};

RiakRecord.prototype.valid = function() {
	return true;
};

RiakRecord.prototype.key = function() {
	//Per default, a model is valid. Individual models may overwrite this to add model-specific logic
	throw new Error('This is just an interface that has to be implemented in the concrete model');
};

//can be used to make changes to the object after loading it
RiakRecord.prototype._transform = function(res) {
	//Per default, we don't transform the object
};

RiakRecord.prototype._setVClock = function() {
	return this._vclock ? {vclock: this._vclock} : {};
};

RiakRecord.prototype._makeIndexes = function(res) {
	Object.defineProperty(this, '_indexes', {value: res._indexes, writable: true});
};

module.exports = RiakRecord;<commit_msg>Formatted riak_record.js<commit_after>var RiakRecord = function() {
};

RiakRecord.prototype.delete = function(cb) {
  this.bucket.remove(this, function(err) {
    if (err) {
      return cb(err);
    }
    return cb(null);
  });
};

RiakRecord.prototype.load = function(cb) {
  var that = this;
  this.bucket.find(this.key(), function(err, res) {
    if (err) {
      return cb(err);
    }

    that._setVClock(res);
    that._transform(res);
    that._makeIndexes(res);
    cb(null, that);
  });
};

RiakRecord.prototype.updateAttribute = function(attributeName, attributeValue, cb) {
  this[attributeName] = attributeValue;
  if (!this.valid()) {
    return cb(new Error('Invalid element'));
  }
  this.save(function(err, res) {
    if (err) {
      cb(err);
    }
    cb(null, res);
  });
};

RiakRecord.prototype.save = function(cb) {
  if (!this.valid()) {
    return cb(new Error('Invalid element'));
  }
  this.bucket.save(this, cb);
};

RiakRecord.prototype.valid = function() {
  return true;
};

RiakRecord.prototype.key = function() {
  //Per default, a model is valid. Individual models may overwrite this to add model-specific logic
  throw new Error('This is just an interface that has to be implemented in the concrete model');
};

//can be used to make changes to the object after loading it
RiakRecord.prototype._transform = function(res) {
  //Per default, we don't transform the object
};

RiakRecord.prototype._setVClock = function() {
  return this._vclock ? { vclock: this._vclock } : {};
};

RiakRecord.prototype._makeIndexes = function(res) {
  Object.defineProperty(this, '_indexes', { value: res._indexes, writable: true });
};

module.exports = RiakRecord;<|endoftext|>


<commit_before>#!/usr/bin/env node

const formatter = require('../../index');
const path = require('path');
const fs = require('fs');
const readme = fs.readFileSync(path.join(__dirname, '/README.md'), 'utf8');

formatter(readme)
    .then(html => saveFile(path.join(__dirname, '/index.html'), html))
    .catch(err => console.error(err));

function saveFile(dest, html) {
    fs.writeFileSync(dest, html);
}
<commit_msg>refactor(index): promisify system i/o<commit_after>#!/usr/bin/env node

const formatter = require('../../index');
const path = require('path');
const promisifyAll = require('bluebird').promisifyAll;
const fs = promisifyAll(require('fs'));

const srcFilename = path.join(__dirname, '/README.md');
const destFilename = path.join(__dirname, '/index.html');

fs.readFileAsync(srcFilename, 'utf8')
    .then(readme => formatter(readme))
    .then(html => fs.writeFile(destFilename, html))
    .catch(err => console.error(err));<|endoftext|>


<commit_before>const mongojs = require('../app/js/infrastructure/mongojs')
const { db } = mongojs
const async = require('async')
const minilist = require('minimist')

const newTimeout = 240
const oldTimeoutLimits = {$gt: 60, $lt: 240}

const updateUser = function (user, callback) {
  console.log(`Updating user ${user._id}`)
  const update = {
    $set: {
      'features.compileTimeout': newTimeout
    }
  }
  db.users.update({
    _id: user._id,
    'features.compileTimeout': oldTimeoutLimits
  }, update, callback)
}

const updateUsers = (users, callback) =>
  async.eachLimit(users, ASYNC_LIMIT, updateUser, function (error) {
    if (error) {
      callback(error)
      return
    }
    counter += users.length
    console.log(`${counter} users updated`)
    loopForUsers(callback)
  })

var loopForUsers = callback =>
  db.users.find(
    { 'features.compileTimeout': oldTimeoutLimits },
    { 'features.compileTimeout': 1 }
  ).limit(FETCH_LIMIT, function (error, users) {
    if (error) {
      callback(error)
      return
    }
    if (users.length === 0) {
      console.log(`DONE (${counter} users updated)`)
      return callback()
    }
    updateUsers(users, callback)
  })

var counter = 0
var run = () =>
  loopForUsers(function (error) {
    if (error) { throw error }
    process.exit()
  })

let FETCH_LIMIT, ASYNC_LIMIT
var setup = function () {
  let args = minilist(process.argv.slice(2))
  FETCH_LIMIT = (args.fetch) ? args.fetch : 100
  ASYNC_LIMIT = (args.async) ? args.async : 10
}

setup()
run()
<commit_msg>add --all option for increase_compile_timeouts script<commit_after>const mongojs = require('../app/js/infrastructure/mongojs')
const { db } = mongojs
const async = require('async')
const minilist = require('minimist')

const newTimeout = 240
const oldTimeoutLimits = {$gt: 60, $lt: 240}

const updateUser = function (user, callback) {
  console.log(`Updating user ${user._id}`)
  const update = {
    $set: {
      'features.compileTimeout': newTimeout
    }
  }
  db.users.update({
    _id: user._id,
    'features.compileTimeout': oldTimeoutLimits
  }, update, callback)
}

const updateUsers = (users, callback) =>
  async.eachLimit(users, ASYNC_LIMIT, updateUser, function (error) {
    if (error) {
      callback(error)
      return
    }
    counter += users.length
    console.log(`${counter} users updated`);
    if (DO_ALL) {
      return loopForUsers(callback)
    } else {
      console.log('run again to continue updating');
      return callback()
    }
  })

var loopForUsers = callback =>
  db.users.find(
    { 'features.compileTimeout': oldTimeoutLimits },
    { 'features.compileTimeout': 1 }
  ).limit(FETCH_LIMIT, function (error, users) {
    if (error) {
      callback(error)
      return
    }
    if (users.length === 0) {
      console.log(`DONE (${counter} users updated)`)
      return callback()
    }
    updateUsers(users, callback)
  })

var counter = 0
var run = () =>
  loopForUsers(function (error) {
    if (error) { throw error }
    process.exit()
  })

let FETCH_LIMIT, ASYNC_LIMIT, DO_ALL
var setup = function () {
  let args = minilist(process.argv.slice(2))
  // --fetch N  get N users each time
  FETCH_LIMIT = (args.fetch) ? args.fetch : 100
  // --async M  run M updates in parallel
  ASYNC_LIMIT = (args.async) ? args.async : 10
  // --all means run to completion
  DO_ALL = (args.all)
}

setup()
run()
<|endoftext|>


<commit_before>//****************************************************

/*
  node = {
    nodeType: type,
    nodeValue: value,
    leftChild: node,
    rightChild: node
  };
*/

var TreeNode = function (element) {
  this.element = element;
  this.leftChild = null;
  this.rightChild = null;
};

TreeNode.prototype = {
  //constructor: TreeNode,
  makeEmpty: function () {},

  setLeftChild: function (treeNode) {
    this.leftChild = treeNode;
  },

  setRightChild: function (treeNode) {
    this.rightChild = treeNode;
  }
};

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

var Stack = function () {
  this.size = 0;
  this.top = null;
};

Stack._Element = function (element, next) {
  this.element = element;
  this.next = next;
};

Stack.prototype = {

  makeEmpty: function () {},

  push: function (element) {
    var temp = this.top;
    this.top = new Stack._Element(element, temp);
    this.size++;
  },

  pop: function () {
    if (this.size == 0) {
      return null;
    }
    var temp = this.top;
    this.top = temp.next;
    this.size--;
    return temp.element;
  },

  display: function () {
    if (this.size == 0)
      return "Empty Stack!"
    var temp = this.top;
    var output = " ";
    for (var i = 0; i < this.size; i++) {
      output = '
' + temp.element + '
' + output;
      console.log(temp.element);
      temp = temp.next;
    }
    return output;
  }
};

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

var Queue = function () {
  this.size = 0;
  this.front = null;
  this.rear = null;
};

Queue._Element = function (element, next) {
  this.element = element;
  this.next = next;
};

Queue.prototype = {

  makeEmpty: function() {},

  enqueue: function(element) {
    if (this.size == 0) {
      this.front = new Queue._Element(element, null);
      this.rear = this.front;
      this.size++;
    } else {
      var temp = this.rear;
      this.rear = new Queue._Element(element, null);
      temp.next = this.rear;
      this.size++;
    }
  },

  dequeue: function() {
    if (this.size == 0) {
      return null;
    } else if (this.size == 1) {
      var temp = this.front;
      this.front = null;
      this.rear = null;
      this.size--;
      return temp.element;
    } else {
      var temp = this.front;
      this.front = temp.next;
      this.size--;
      return temp.element;
    }
  },

  display: function() {
    if (this.size == 0)
      return "Empty Queue!"
    var temp = this.front;
    var output = " ";
    for (var i = 0; i < this.size; i++) {
      output = output + '
' + temp.element + '
';
      console.log(temp.element);
      temp = temp.next;
    }
    return output;
  }

};

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

var ExpQueue = function() {
  Queue.call(this);
  this.index = null;
}

ExpQueue.prototype = new Queue();

ExpQueue.prototype.reset = function() {
  this.index = this.front;
  console.log('ExpQueue: Reset.');
};

ExpQueue.prototype.exec = function() {
  var temp = this.index;
  if (temp == null) {
    this.reset();
    return null;
  } else {
    this.index = temp.next;
    //console.log(temp.element);
    return temp.element;
  }
};

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

var ExpObject = function(input) {
  this.input = input;
  this.originExp = null;
  this.postfixExp = null;
  this.expTree = null;
  this.value = null;

  this.status = {
    isCalculated: false,
    initialized: false,
  };

  this._init();
};

ExpObject._ExpNodeElement = function(type, value) {
  this.nodeType = type;
  this.nodeValue = value;
}

ExpObject._ExpNodeElement.prototype.toString = function() {
  return this.nodeValue;
}

ExpObject.RE = {
  validate: /^(?:\s*((?:\d+(?:\.\d*)?)|(?:[\+\-\*\/\(\)])))*\s*$/g,
  pattern: /(?=\s*)((\d+(\.\d*)?)|([\+\-\*\/\(\)]))(?=\s*)/g,
  number: /\d+(?:\.\d*)?/g
};

ExpObject.prototype = {

  _init: function() {
    this._createOriginExp();
    this._createPostfixExp();
    this._createExpTree();
    this.value = this.calculate();
  },

  _reader: function(chars) {
    var type;
    if (ExpObject.RE.number.test(chars) == true) {
      type = 'number';
      chars = Number(chars);
    } else if (chars == '+' || chars == '-') {
      type = 'plus';
    } else if (chars == '*' || chars == '/') {
      type = 'mult';
    } else if (chars == '(') {
      type = 'leftBracket';
    } else if (chars == ')') {
      type = 'rightBracket';
    } else {
      type = chars;     // this one leads to error;
    }
    ExpObject.RE.number.lastIndex = 0;
    return new ExpObject._ExpNodeElement(type, chars);
  },

  _dispExp: function(exp, div) {
    div.innerHTML = exp.display();
  },

  _createOriginExp: function() {
    this.originExp = new ExpQueue();
    var validate = ExpObject.RE.validate.test(this.input);
    ExpObject.RE.validate.lastIndex = 0;

    if (validate == false) {
      throw new Error('ExpObject: Invalid input.');
    }

    while ((scan = ExpObject.RE.pattern.exec(this.input)) != null) {
      var expNode = this._reader(scan[0]);
      this.originExp.enqueue(expNode);
    }

    if (this.originExp.size == 0) {
      console.log("ExpObject: Empty input.");
    } else {
      console.log("ExpObject: OriginExp parsed.");
    }

    this.originExp.reset();
  },

  _createPostfixExp: function() {
    this.postfixExp = new ExpQueue();
    var tempStack = new Stack();
    var temp;

    while ((temp = this.originExp.exec()) != null) {
      switch (temp.nodeType) {
        case "number":
          this.postfixExp.enqueue(temp);
          break;
        case "plus":
          if (tempStack.top == null) {
            tempStack.push(temp);
          } else if (tempStack.top.element.nodeType == "leftBracket") {
            tempStack.push(temp);
          } else if (tempStack.top.element.nodeType == "plus" || tempStack.top.element.nodeType == "mult") {
            do {
              var popped = tempStack.pop();
              this.postfixExp.enqueue(popped);
            } while (tempStack.top != null && (tempStack.top.element.nodeType == "plus" || tempStack.top.element.nodeType == "mult"));
            tempStack.push(temp);
          }
          break;
        case "mult":
          if (tempStack.top == null) {
            tempStack.push(temp);
          } else if (tempStack.top.element.nodeType == "leftBracket") {
            tempStack.push(temp);
          } else if (tempStack.top.element.nodeType == "plus") {
            tempStack.push(temp);
          } else if (tempStack.top.element.nodeType == "mult") {
            do {
              var popped = tempStack.pop();
              this.postfixExp.enqueue(popped);
            } while (tempStack.top != null && tempStack.top.element.nodeType == "mult");
            tempStack.push(temp);
          }
          break;
        case "leftBracket":
          tempStack.push(temp);
          break;
        case "rightBracket":
          while (tempStack.top != null && tempStack.top.element.nodeType != "leftBracket") {
            var popped = tempStack.pop();
            this.postfixExp.enqueue(popped);
          }
          if (tempStack.top == null) {
            throw new Error('ExpObject: Illegal right bracket.');
          }
          if (tempStack.top.element.nodeType == "leftBracket") {
            tempStack.pop();
          }
          break;
        default:
          throw new Error('ExpObject: Unknown Error!');
      }
    }

    while (tempStack.top != null) {
      if (tempStack.top.element.nodeType == "leftBracket") {
        throw new Error('ExpObject: Bracket not correctly closed!');
      }
      var popped = tempStack.pop();
      this.postfixExp.enqueue(popped);
    }

    console.log("ExpObject: postfixExp parsed.");
    this.postfixExp.reset();
  },

  _createExpTree: function() {
    this.expTree = null;
    var tempStack = new Stack();
    var temp;

    while ((temp = this.postfixExp.exec()) != null) {
      var tempNode = new TreeNode(temp);
      if (temp.nodeType == "number") {
        tempStack.push(tempNode);
      } else {
        if (tempStack.size < 2) {
          throw new Error('Invalid Exp cannot be parsed.');
        }
        tempNode.setRightChild(tempStack.pop());
        tempNode.setLeftChild(tempStack.pop());
        tempStack.push(tempNode);
      }
    }
    if (tempStack.size != 1) {
      throw new Error('Invalid Exp cannot be parsed.');
    }
    this.expTree = tempStack.pop();
    console.log('ExpObject: ExpTree parsed successfully.');
  },

  calculate: function() {

    traversal = function(treeNode) {
      if (treeNode.element.nodeType == "number") {
        return treeNode.element.nodeValue;
      } else if (treeNode.element.nodeValue == "+") {
        return ((traversal(treeNode.leftChild)) + (traversal(treeNode.rightChild)));
      } else if (treeNode.element.nodeValue == "-") {
        return (traversal(treeNode.leftChild) - traversal(treeNode.rightChild));
      } else if (treeNode.element.nodeValue == "*") {
        return (traversal(treeNode.leftChild) * traversal(treeNode.rightChild));
      } else if (treeNode.element.nodeValue == "/") {
        return (traversal(treeNode.leftChild) / traversal(treeNode.rightChild));
      } else {
        throw new Error('ExpObject: Invalid ExpTree.');
      }
    };

    return traversal(this.expTree);
  },

  /**
     * Draw the expression tree on a canvas
     * w: width of the canvas; h: height per level;
     * fs: font size; r: radius of a node circle;
     *
     * @method draw
     * @param {Number} w
     * @param {Number} h
     * @param {Number} fz
     * @param {Number} r
     * @return {Canvas Element}
     */
  draw: function(w, h, fs, r) {

    var canvas = document.createElement('canvas');
    canvas.width = w;
    canvas.height = w;

    var c = canvas.getContext('2d');

    //style config
    c.fillStyle = '#333';
    c.strokeStyle = 'bold #333';
    c.lineWidth = 1;
    c.font = "bold " + fs + "pt Helvetica";
    c.textAlign = "center";
    //

    var currentQueue = new Queue();
    var nextQueue;
    var n = 0;
    if (this.expTree != null) {
      currentQueue.enqueue(this.expTree);
      n++;
    }
    var alpha = Math.PI / 18;
    var k = h / Math.tan(alpha);
    var x0 = w / 2;
    var x = x0;
    var y = r;
    var p;
    var l = 0;

    while (currentQueue.size != 0 && n > 0) {
      nextQueue = new Queue();
      n = 0;
      p = 1;
      while (currentQueue.size != 0) {
        var tempNode = currentQueue.dequeue();
        if (tempNode != null) {
          if (tempNode.leftChild != null) n++;
          nextQueue.enqueue(tempNode.leftChild);
          if (tempNode.rightChild != null) n++;
          nextQueue.enqueue(tempNode.rightChild);

          var word = tempNode.element.toString();
          c.fillText(word, x, y + r / 3);
          c.beginPath();
          c.arc(x, y, r, 0, 2 * Math.PI, true);
          if (l) {
            c.moveTo(x + p * r * Math.cos(alpha), y - r * Math.sin(alpha));
            c.lineTo(x + p * (k - r * Math.cos(alpha)), y - h + r * Math.sin(alpha));
          }
          c.stroke();
        } else {
          nextQueue.enqueue(null);
          nextQueue.enqueue(null);
        }
        x += (2 * k);
        p *= (-1);
      }
      currentQueue = nextQueue;
      k /= 2;
      x0 -= k;
      x = x0;
      y += h;
      l++;
      alpha = Math.atan(2 * Math.tan(alpha));
    }

    return canvas;
  }

};
<commit_msg>8/15 little change color<commit_after>//****************************************************

/*
  node = {
    nodeType: type,
    nodeValue: value,
    leftChild: node,
    rightChild: node
  };
*/

var TreeNode = function (element) {
  this.element = element;
  this.leftChild = null;
  this.rightChild = null;
};

TreeNode.prototype = {
  //constructor: TreeNode,
  makeEmpty: function () {},

  setLeftChild: function (treeNode) {
    this.leftChild = treeNode;
  },

  setRightChild: function (treeNode) {
    this.rightChild = treeNode;
  }
};

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

var Stack = function () {
  this.size = 0;
  this.top = null;
};

Stack._Element = function (element, next) {
  this.element = element;
  this.next = next;
};

Stack.prototype = {

  makeEmpty: function () {},

  push: function (element) {
    var temp = this.top;
    this.top = new Stack._Element(element, temp);
    this.size++;
  },

  pop: function () {
    if (this.size == 0) {
      return null;
    }
    var temp = this.top;
    this.top = temp.next;
    this.size--;
    return temp.element;
  },

  display: function () {
    if (this.size == 0)
      return "Empty Stack!"
    var temp = this.top;
    var output = " ";
    for (var i = 0; i < this.size; i++) {
      output = '
' + temp.element + '
' + output;
      console.log(temp.element);
      temp = temp.next;
    }
    return output;
  }
};

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

var Queue = function () {
  this.size = 0;
  this.front = null;
  this.rear = null;
};

Queue._Element = function (element, next) {
  this.element = element;
  this.next = next;
};

Queue.prototype = {

  makeEmpty: function() {},

  enqueue: function(element) {
    if (this.size == 0) {
      this.front = new Queue._Element(element, null);
      this.rear = this.front;
      this.size++;
    } else {
      var temp = this.rear;
      this.rear = new Queue._Element(element, null);
      temp.next = this.rear;
      this.size++;
    }
  },

  dequeue: function() {
    if (this.size == 0) {
      return null;
    } else if (this.size == 1) {
      var temp = this.front;
      this.front = null;
      this.rear = null;
      this.size--;
      return temp.element;
    } else {
      var temp = this.front;
      this.front = temp.next;
      this.size--;
      return temp.element;
    }
  },

  display: function() {
    if (this.size == 0)
      return "Empty Queue!"
    var temp = this.front;
    var output = " ";
    for (var i = 0; i < this.size; i++) {
      output = output + '
' + temp.element + '
';
      console.log(temp.element);
      temp = temp.next;
    }
    return output;
  }

};

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

var ExpQueue = function() {
  Queue.call(this);
  this.index = null;
}

ExpQueue.prototype = new Queue();

ExpQueue.prototype.reset = function() {
  this.index = this.front;
  console.log('ExpQueue: Reset.');
};

ExpQueue.prototype.exec = function() {
  var temp = this.index;
  if (temp == null) {
    this.reset();
    return null;
  } else {
    this.index = temp.next;
    //console.log(temp.element);
    return temp.element;
  }
};

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

var ExpObject = function(input) {
  this.input = input;
  this.originExp = null;
  this.postfixExp = null;
  this.expTree = null;
  this.value = null;

  this.status = {
    isCalculated: false,
    initialized: false,
  };

  this._init();
};

ExpObject._ExpNodeElement = function(type, value) {
  this.nodeType = type;
  this.nodeValue = value;
}

ExpObject._ExpNodeElement.prototype.toString = function() {
  return this.nodeValue;
}

ExpObject.RE = {
  validate: /^(?:\s*((?:\d+(?:\.\d*)?)|(?:[\+\-\*\/\(\)])))*\s*$/g,
  pattern: /(?=\s*)((\d+(\.\d*)?)|([\+\-\*\/\(\)]))(?=\s*)/g,
  number: /\d+(?:\.\d*)?/g
};

ExpObject.prototype = {

  _init: function() {
    this._createOriginExp();
    this._createPostfixExp();
    this._createExpTree();
    this.value = this.calculate();
  },

  _reader: function(chars) {
    var type;
    if (ExpObject.RE.number.test(chars) == true) {
      type = 'number';
      chars = Number(chars);
    } else if (chars == '+' || chars == '-') {
      type = 'plus';
    } else if (chars == '*' || chars == '/') {
      type = 'mult';
    } else if (chars == '(') {
      type = 'leftBracket';
    } else if (chars == ')') {
      type = 'rightBracket';
    } else {
      type = chars;     // this one leads to error;
    }
    ExpObject.RE.number.lastIndex = 0;
    return new ExpObject._ExpNodeElement(type, chars);
  },

  _dispExp: function(exp, div) {
    div.innerHTML = exp.display();
  },

  _createOriginExp: function() {
    this.originExp = new ExpQueue();
    var validate = ExpObject.RE.validate.test(this.input);
    ExpObject.RE.validate.lastIndex = 0;

    if (validate == false) {
      throw new Error('ExpObject: Invalid input.');
    }

    while ((scan = ExpObject.RE.pattern.exec(this.input)) != null) {
      var expNode = this._reader(scan[0]);
      this.originExp.enqueue(expNode);
    }

    if (this.originExp.size == 0) {
      console.log("ExpObject: Empty input.");
    } else {
      console.log("ExpObject: OriginExp parsed.");
    }

    this.originExp.reset();
  },

  _createPostfixExp: function() {
    this.postfixExp = new ExpQueue();
    var tempStack = new Stack();
    var temp;

    while ((temp = this.originExp.exec()) != null) {
      switch (temp.nodeType) {
        case "number":
          this.postfixExp.enqueue(temp);
          break;
        case "plus":
          if (tempStack.top == null) {
            tempStack.push(temp);
          } else if (tempStack.top.element.nodeType == "leftBracket") {
            tempStack.push(temp);
          } else if (tempStack.top.element.nodeType == "plus" || tempStack.top.element.nodeType == "mult") {
            do {
              var popped = tempStack.pop();
              this.postfixExp.enqueue(popped);
            } while (tempStack.top != null && (tempStack.top.element.nodeType == "plus" || tempStack.top.element.nodeType == "mult"));
            tempStack.push(temp);
          }
          break;
        case "mult":
          if (tempStack.top == null) {
            tempStack.push(temp);
          } else if (tempStack.top.element.nodeType == "leftBracket") {
            tempStack.push(temp);
          } else if (tempStack.top.element.nodeType == "plus") {
            tempStack.push(temp);
          } else if (tempStack.top.element.nodeType == "mult") {
            do {
              var popped = tempStack.pop();
              this.postfixExp.enqueue(popped);
            } while (tempStack.top != null && tempStack.top.element.nodeType == "mult");
            tempStack.push(temp);
          }
          break;
        case "leftBracket":
          tempStack.push(temp);
          break;
        case "rightBracket":
          while (tempStack.top != null && tempStack.top.element.nodeType != "leftBracket") {
            var popped = tempStack.pop();
            this.postfixExp.enqueue(popped);
          }
          if (tempStack.top == null) {
            throw new Error('ExpObject: Illegal right bracket.');
          }
          if (tempStack.top.element.nodeType == "leftBracket") {
            tempStack.pop();
          }
          break;
        default:
          throw new Error('ExpObject: Unknown Error!');
      }
    }

    while (tempStack.top != null) {
      if (tempStack.top.element.nodeType == "leftBracket") {
        throw new Error('ExpObject: Bracket not correctly closed!');
      }
      var popped = tempStack.pop();
      this.postfixExp.enqueue(popped);
    }

    console.log("ExpObject: postfixExp parsed.");
    this.postfixExp.reset();
  },

  _createExpTree: function() {
    this.expTree = null;
    var tempStack = new Stack();
    var temp;

    while ((temp = this.postfixExp.exec()) != null) {
      var tempNode = new TreeNode(temp);
      if (temp.nodeType == "number") {
        tempStack.push(tempNode);
      } else {
        if (tempStack.size < 2) {
          throw new Error('Invalid Exp cannot be parsed.');
        }
        tempNode.setRightChild(tempStack.pop());
        tempNode.setLeftChild(tempStack.pop());
        tempStack.push(tempNode);
      }
    }
    if (tempStack.size != 1) {
      throw new Error('Invalid Exp cannot be parsed.');
    }
    this.expTree = tempStack.pop();
    console.log('ExpObject: ExpTree parsed successfully.');
  },

  calculate: function() {

    traversal = function(treeNode) {
      if (treeNode.element.nodeType == "number") {
        return treeNode.element.nodeValue;
      } else if (treeNode.element.nodeValue == "+") {
        return ((traversal(treeNode.leftChild)) + (traversal(treeNode.rightChild)));
      } else if (treeNode.element.nodeValue == "-") {
        return (traversal(treeNode.leftChild) - traversal(treeNode.rightChild));
      } else if (treeNode.element.nodeValue == "*") {
        return (traversal(treeNode.leftChild) * traversal(treeNode.rightChild));
      } else if (treeNode.element.nodeValue == "/") {
        return (traversal(treeNode.leftChild) / traversal(treeNode.rightChild));
      } else {
        throw new Error('ExpObject: Invalid ExpTree.');
      }
    };

    return traversal(this.expTree);
  },

  /**
     * Draw the expression tree on a canvas
     * w: width of the canvas; h: height per level;
     * fs: font size; r: radius of a node circle;
     *
     * @method draw
     * @param {Number} w
     * @param {Number} h
     * @param {Number} fz
     * @param {Number} r
     * @return {Canvas Element}
     */
  draw: function(w, h, fs, r) {

    var canvas = document.createElement('canvas');
    canvas.width = w;
    canvas.height = w;

    var c = canvas.getContext('2d');

    c.font = "bold " + fs + "pt Helvetica";
    c.textAlign = "center";

    var currentQueue = new Queue();
    var nextQueue;
    var n = 0;
    if (this.expTree != null) {
      currentQueue.enqueue(this.expTree);
      n++;
    }
    var alpha = Math.PI / 18;
    var k = h / Math.tan(alpha);
    var x0 = w / 2;
    var x = x0;
    var y = r + 5;
    var p;
    var l = 0;

    while (currentQueue.size != 0 && n > 0) {
      nextQueue = new Queue();
      n = 0;
      p = 1;
      while (currentQueue.size != 0) {
        var tempNode = currentQueue.dequeue();
        if (tempNode != null) {
          if (tempNode.leftChild != null) n++;
          nextQueue.enqueue(tempNode.leftChild);
          if (tempNode.rightChild != null) n++;
          nextQueue.enqueue(tempNode.rightChild);

          c.beginPath();
          c.strokeStyle = '#353';
          c.fillStyle = '#353';
          c.lineWidth = 3;
          c.arc(x, y, r, 0, 2 * Math.PI, true);
          if (tempNode.element.nodeType == 'number') {
            c.stroke();
          } else {
            c.fill();
          }
          c.beginPath();
          if (tempNode.element.nodeType == 'number') {
            c.fillStyle = '#333';
          } else {
            c.fillStyle = '#FFF';
          }
          var word = tempNode.element.toString();
          c.fillText(word, x, y + r / 3);
          if (l) {
            c.beginPath();
            c.strokeStyle = '#333';
            c.lineWidth = 2;
            c.moveTo(x + p * r * Math.cos(alpha), y - r * Math.sin(alpha));
            c.lineTo(x + p * (k - r * Math.cos(alpha)), y - h + r * Math.sin(alpha));
            c.stroke();
          }
        } else {
          nextQueue.enqueue(null);
          nextQueue.enqueue(null);
        }
        x += (2 * k);
        p *= (-1);
      }
      currentQueue = nextQueue;
      k /= 2;
      x0 -= k;
      x = x0;
      y += h;
      l++;
      alpha = Math.atan(2 * Math.tan(alpha));
    }

    return canvas;
  }

};
<|endoftext|>


<commit_before>var util = require('util');
var Insidetransfer = require('./insidetransfer.js');

var private = {}, self = null,
	library = null, modules = null;

function MyAsset(cb, _library) {
	self = this;
	library = _library;

	cb(null, self);
}

MyAsset.prototype.create = function (data, trs) {
	trs = MyAsset.super_.prototype.create.call(self, data, trs);

	return trs;
}

MyAsset.prototype.getBytes = function (trs) {
	try {
		var buf = new Buffer(trs.asset.myasset.text, 'utf8');
	} catch (e) {
		throw Error(e.toString());
	}

	return buf;
}

MyAsset.prototype.verify = function (trs, sender, cb, scope) {
	MyAsset.super_.prototype.verify.call(self, trs, sender, function (err, trs) {
		if (err) {
			return cb(err);
		}
		if (!trs.asset.myasset.text) {
			return cb("TRANSACTIONS.EMPTY_TEXT");
		}
		cb(null, trs)
	}, scope);
}

MyAsset.prototype.save = function (trs, cb) {
	modules.api.sql.insert({
		table: "asset_myasset",
		values: {
			text: trs.asset.myasset.text,
			transactionId: trs.id
		}
	}, cb);
}

MyAsset.prototype.normalize = function (asset, cb) {
	return setImmediate(cb);
}

MyAsset.prototype.dbRead = function (row) {
	if (!row.t_ma_transactionId) {
		return null;
	}
	return {
		myasset: {
			text: row.t_ma_text
		}
	};
}

MyAsset.prototype.onBind = function (_modules) {
	modules = _modules;

	modules.logic.transaction.attachAssetType(3, self);
}

util.inherits(MyAsset, Insidetransfer);

module.exports = MyAsset;<commit_msg>Beautifying code / logs.<commit_after>var util = require("util");
var Insidetransfer = require("./insidetransfer.js");

var private = {}, self = null,
	library = null, modules = null;

function MyAsset(cb, _library) {
	self = this;
	library = _library;

	cb(null, self);
}

MyAsset.prototype.create = function (data, trs) {
	trs = MyAsset.super_.prototype.create.call(self, data, trs);

	return trs;
}

MyAsset.prototype.getBytes = function (trs) {
	try {
		var buf = new Buffer(trs.asset.myasset.text, "utf8");
	} catch (e) {
		throw Error(e.toString());
	}

	return buf;
}

MyAsset.prototype.verify = function (trs, sender, cb, scope) {
	MyAsset.super_.prototype.verify.call(self, trs, sender, function (err, trs) {
		if (err) {
			return cb(err);
		}
		if (!trs.asset.myasset.text) {
			return cb("Invalid transaction asset");
		}
		cb(null, trs)
	}, scope);
}

MyAsset.prototype.save = function (trs, cb) {
	modules.api.sql.insert({
		table: "asset_myasset",
		values: {
			text: trs.asset.myasset.text,
			transactionId: trs.id
		}
	}, cb);
}

MyAsset.prototype.normalize = function (asset, cb) {
	return setImmediate(cb);
}

MyAsset.prototype.dbRead = function (row) {
	if (!row.t_ma_transactionId) {
		return null;
	}
	return {
		myasset: {
			text: row.t_ma_text
		}
	};
}

MyAsset.prototype.onBind = function (_modules) {
	modules = _modules;

	modules.logic.transaction.attachAssetType(3, self);
}

util.inherits(MyAsset, Insidetransfer);

module.exports = MyAsset;
<|endoftext|>


<commit_before>'use strict'

const _ = require('lodash')
const Graph = require('graph.js/dist/graph.full.js')

// Setup server

const http = require('http')
const fs = require('fs')
const path = require('path')

// define path to index.html, otherwise it will be relative to dir where
// scripts is run
let scr = path.join(__dirname, '../../viz/index.html')

// Loading the index file . html displayed to the client

const server = http.createServer(function(req, res) {
  fs.readFile(scr, 'utf-8', function(err, content) {
    res.writeHead(200, {"Content-Type": "text/html"})
    res.end(content)
  })
})

// Loading socket.io

const io = require('socket.io').listen(server)

// sets MaxListeners without limit, important if several instances of
// socket.io are expected (e.g. if we have several junctions, forks, and
// even tasks)
io.sockets.setMaxListeners(0)

// When a client connects, we note it in the console
io.sockets.on('connection', function (socket) {
  console.log('A client is connected!')
})
server.listen(8084)

// Actions
const ADD_OUTPUT = 'collection/add-output'
const ADD_JUNCTION_VERTEX = 'collection/add-junction-vertex'

const defaultState = new Graph()

const reducer = (state = defaultState, action) => {
  switch (action.type) {
    case ADD_OUTPUT:
      return addOutputHandler(state, action)
      break
    case ADD_JUNCTION_VERTEX:
      return addJunctionVertexHandler(state, action)
      break
    default:
      return state
  }
}

const jsonifyGraph = (graph, obj = {}) => {
  const graphsonObj = {
    graph: {
      mode: "NORMAL",
      vertices: [],
      edges: []
    }
  }

  // iterate through vertices
  // in ECMAScript 6, you can use a for..of loop
  for (let [key, value] of graph.vertices()) {
    // iterates over all vertices of the graph
    graphsonObj.graph.vertices.push({
      _id: key,
      _type: "vertex",
      values: value
    })
  }
  // iterate through edges
  // in ECMAScript 6, you can use a for..of loop
  for (let [from, to, value] of graph.edges()) {
    // iterates over all vertices of the graph
    graphsonObj.graph.edges.push({
      source: from,
      target: to,
      _type: "edge"
    })
  }

  const assignVal = (obj, key, val) => {
    if (val === undefined) {
      obj[key] = { _value: '' }
    } else {
      obj[key] = { _value: val }
    }
  }
  for (const [key, val] of graph.sources()) {
    assignVal(obj, key, val)
  }

  const travelNode = (node) => {
    const obj = {}
    for (const [key, val] of graph.verticesFrom(node)) {
      assignVal(obj, key, val)
      Object.assign(obj[key], travelNode(key))
    }
    return obj
  }

  // writes each graphson to file
  fs.writeFileSync('graphson.json', JSON.stringify(graphsonObj, null, 2))

  // Output to visualization server
  io.sockets.on('connection', function (socket) {
    socket.emit('message', graphsonObj)
  })

  Object.keys(obj).forEach(key => Object.assign(obj[key], travelNode(key)))

  return obj
}

function addOutputHandler (state, action) {
  // TODO remove duplicate code b/w this, and creating the next trajection in join
  const { type, uid, output, input, params, context, name } = action
  const { trajectory } = context
  // console.log(`trajectory for ${uid}: `, trajectory)
  // console.log(`output for ${uid}: `, output)
  // console.log(`params for ${uid}: `, params)

  if (!_.isArray(trajectory)) {
    console.log('Trajectory is not an array!')
    return state
  }

  // Clone graph to maintain immutable state
  const graph = state.clone()

  // Add a node for current task
  // only adds to graph if uid has in fact a name (from tasks)
  if (name) {
    // here needed to had taskName to better comprehend what is being
    // created by junction, joins forks and tasks.
    graph.addNewVertex(uid, {
      type: type,
      taskName: name,
      input: input,
      output: output,
      params: params}
    ) //addNewVertex(key, [value])
  }

  // Add edge from last trajectory node to current output if no params,
  // otherwise to params (which points to current output)
  if (trajectory.length > 0) {
      graph.addNewEdge(trajectory[trajectory.length - 1], uid)
  }

  return graph
}

function addJunctionVertexHandler(state, action) {
  const { uid, results } = action

  // Clone graph to maintain immutable state
  const graph = state.clone()

  const values = []
  const lastUids = []
  for (const result of results) {
    if (result.tasks) {
      // Dealing with a join/fork/junction
      // Since param nodes never have values, can use these
      result.tasks.forEach((taskUid, i) => {
        values.push(graph.vertexValue(taskUid))
        if (i === result.tasks.length - 1) lastUids.push(taskUid)
      })
    } else {
      // Dealing with a single task
      const taskUid = result.uid
      values.push(graph.vertexValue(taskUid))
      lastUids.push(taskUid)
    }
  }

  // TODO flatten values?
  // I think each vertex value is already an array only
  graph.addNewVertex(uid, _.flatten(values))

  // Edge from last task of each to new junction node
  lastUids.forEach(lastUid => graph.addNewEdge(lastUid, uid))

  return graph
}

reducer.ADD_OUTPUT = ADD_OUTPUT
reducer.addOutput = (uid, taskState) => ({
  type: ADD_OUTPUT,
  uid,
  name: taskState.name,
  output: taskState.resolvedOutput,
  //input: taskState.input,     // ideally we should pass resolvedInput
  context: taskState.context,
  params: taskState.params
})

reducer.ADD_JUNCTION_VERTEX = ADD_JUNCTION_VERTEX
reducer.addJunctionVertex = (uid, results) => ({
  type: ADD_JUNCTION_VERTEX,
  uid,
  results
})

reducer.jsonifyGraph = jsonifyGraph

module.exports = reducer
<commit_msg>for now input pattern was added<commit_after>'use strict'

const _ = require('lodash')
const Graph = require('graph.js/dist/graph.full.js')

// Setup server

const http = require('http')
const fs = require('fs')
const path = require('path')

// define path to index.html, otherwise it will be relative to dir where
// scripts is run
let scr = path.join(__dirname, '../../viz/index.html')

// Loading the index file . html displayed to the client

const server = http.createServer(function(req, res) {
  fs.readFile(scr, 'utf-8', function(err, content) {
    res.writeHead(200, {"Content-Type": "text/html"})
    res.end(content)
  })
})

// Loading socket.io

const io = require('socket.io').listen(server)

// sets MaxListeners without limit, important if several instances of
// socket.io are expected (e.g. if we have several junctions, forks, and
// even tasks)
io.sockets.setMaxListeners(0)

// When a client connects, we note it in the console
io.sockets.on('connection', function (socket) {
  console.log('A client is connected!')
})
server.listen(8084)

// Actions
const ADD_OUTPUT = 'collection/add-output'
const ADD_JUNCTION_VERTEX = 'collection/add-junction-vertex'

const defaultState = new Graph()

const reducer = (state = defaultState, action) => {
  switch (action.type) {
    case ADD_OUTPUT:
      return addOutputHandler(state, action)
      break
    case ADD_JUNCTION_VERTEX:
      return addJunctionVertexHandler(state, action)
      break
    default:
      return state
  }
}

const jsonifyGraph = (graph, obj = {}) => {
  const graphsonObj = {
    graph: {
      mode: "NORMAL",
      vertices: [],
      edges: []
    }
  }

  // iterate through vertices
  // in ECMAScript 6, you can use a for..of loop
  for (let [key, value] of graph.vertices()) {
    // iterates over all vertices of the graph
    graphsonObj.graph.vertices.push({
      _id: key,
      _type: "vertex",
      values: value
    })
  }
  // iterate through edges
  // in ECMAScript 6, you can use a for..of loop
  for (let [from, to, value] of graph.edges()) {
    // iterates over all vertices of the graph
    graphsonObj.graph.edges.push({
      source: from,
      target: to,
      _type: "edge"
    })
  }

  const assignVal = (obj, key, val) => {
    if (val === undefined) {
      obj[key] = { _value: '' }
    } else {
      obj[key] = { _value: val }
    }
  }
  for (const [key, val] of graph.sources()) {
    assignVal(obj, key, val)
  }

  const travelNode = (node) => {
    const obj = {}
    for (const [key, val] of graph.verticesFrom(node)) {
      assignVal(obj, key, val)
      Object.assign(obj[key], travelNode(key))
    }
    return obj
  }

  // writes each graphson to file
  fs.writeFileSync('graphson.json', JSON.stringify(graphsonObj, null, 2))

  // Output to visualization server
  io.sockets.on('connection', function (socket) {
    socket.emit('message', graphsonObj)
  })

  Object.keys(obj).forEach(key => Object.assign(obj[key], travelNode(key)))

  return obj
}

function addOutputHandler (state, action) {
  // TODO remove duplicate code b/w this, and creating the next trajection in join
  const { type, uid, output, input, params, context, name } = action
  const { trajectory } = context
  // console.log(`trajectory for ${uid}: `, trajectory)
  // console.log(`output for ${uid}: `, output)
  // console.log(`params for ${uid}: `, params)

  if (!_.isArray(trajectory)) {
    console.log('Trajectory is not an array!')
    return state
  }

  // Clone graph to maintain immutable state
  const graph = state.clone()

  // Add a node for current task
  // only adds to graph if uid has in fact a name (from tasks)
  if (name) {
    // here needed to had taskName to better comprehend what is being
    // created by junction, joins forks and tasks.
    graph.addNewVertex(uid, {
      type: type,
      taskName: name,
      input: input,
      output: output,
      params: params}
    ) //addNewVertex(key, [value])
  }

  // Add edge from last trajectory node to current output if no params,
  // otherwise to params (which points to current output)
  if (trajectory.length > 0) {
      graph.addNewEdge(trajectory[trajectory.length - 1], uid)
  }

  return graph
}

function addJunctionVertexHandler(state, action) {
  const { uid, results } = action

  // Clone graph to maintain immutable state
  const graph = state.clone()

  const values = []
  const lastUids = []
  for (const result of results) {
    if (result.tasks) {
      // Dealing with a join/fork/junction
      // Since param nodes never have values, can use these
      result.tasks.forEach((taskUid, i) => {
        values.push(graph.vertexValue(taskUid))
        if (i === result.tasks.length - 1) lastUids.push(taskUid)
      })
    } else {
      // Dealing with a single task
      const taskUid = result.uid
      values.push(graph.vertexValue(taskUid))
      lastUids.push(taskUid)
    }
  }

  // TODO flatten values?
  // I think each vertex value is already an array only
  graph.addNewVertex(uid, _.flatten(values))

  // Edge from last task of each to new junction node
  lastUids.forEach(lastUid => graph.addNewEdge(lastUid, uid))

  return graph
}

reducer.ADD_OUTPUT = ADD_OUTPUT
reducer.addOutput = (uid, taskState) => ({
  type: ADD_OUTPUT,
  uid,
  name: taskState.name,
  output: taskState.resolvedOutput,
  input: taskState.input,     // ideally we should pass resolvedInput
  context: taskState.context,
  params: taskState.params
})

reducer.ADD_JUNCTION_VERTEX = ADD_JUNCTION_VERTEX
reducer.addJunctionVertex = (uid, results) => ({
  type: ADD_JUNCTION_VERTEX,
  uid,
  results
})

reducer.jsonifyGraph = jsonifyGraph

module.exports = reducer
<|endoftext|>


<commit_before>
let sinon from 'sinon/pkg/sinon.js');
var _ from 'lodash');
import React from 'react';
var ReactDOM from 'react-dom');
var TestUtils from 'react-addons-test-utils');
var ReactSelect from '../../../../lib/js/app/components/common/react_select.js');
var TestHelpers from '../../../support/TestHelpers');

describe('components/common/react_select', () => {
  before(() => {
    this.handleBlurStub = sinon.stub();
    this.handleChangeStub = sinon.stub();
    this.handleSelectionStub = sinon.stub();

    var props = {
      items: [],
      wrapClasses: '',
      inputClasses: '',
      placeholder: '',
      handleBlur: this.handleBlurStub,
      handleChange: this.handleChangeStub,
      handleSelection: this.handleSelectionStub
    };
    this.component = TestUtils.renderIntoDocument(<ReactSelect {...props} />);
  });

  describe('setup', () => {
    it('is of the right type', () => {
      assert.isTrue(TestUtils.isCompositeComponentWithType(this.component, ReactSelect));
    });
    it('has one input', () => {
      assert.lengthOf(TestUtils.scryRenderedDOMComponentsWithTag(this.component, 'input'), 1);
    });
  });

  describe('search', () => {
    before(() => {
      this.searchTest = function(selectOptions, searchValue, expectedListItems) {
        var propsStep1 = _.assign({}, this.component.props, { items: selectOptions, value: searchValue });
        this.component = TestHelpers.renderComponent(ReactSelect, propsStep1);
        this.component.setState({ initialFocus: false });

        TestUtils.Simulate.focus(this.component.refs.input);
        TestUtils.Simulate.change(this.component.refs.input);

        var listItems = _.map(ReactDOM.findDOMNode(this.component.refs.list).childNodes, function(item) {
          return item.textContent;
        }.bind(this));
        assert.sameMembers(listItems, expectedListItems);
      };
    });

    it('searches for items case insensitive', () => {
      var propsStep1 = _.assign({}, this.component.props, { items: ['ONE', 'TWO', 'THREE'], value: 'one' });
      this.component = TestHelpers.renderComponent(ReactSelect, propsStep1);
      this.component.setState({ initialFocus: false });

      TestUtils.Simulate.focus(this.component.refs.input);
      TestUtils.Simulate.change(this.component.refs.input);

      var listItems = _.map(ReactDOM.findDOMNode(this.component.refs.list).childNodes, function(item) {
        return item.textContent;
      });
      assert.sameMembers(listItems, ['ONE']);
    });

    it('should display items with opening square bracket (RegExp reserved char)', () => {
      var selectOptions = ['ONE', 'TWO[2]', 'THREE'];
      var searchValue = 'two[';
      var expectedListItems = ['TWO[2]'];

      this.searchTest(selectOptions, searchValue, expectedListItems);
    });

    it('should display items with opening curly brace (RegExp reserved char)', () => {
      var selectOptions = ['ONE', 'TWO', 'THREE{tres}'];
      var searchValue = 'three{';
      var expectedListItems = ['THREE{tres}'];

      this.searchTest(selectOptions, searchValue, expectedListItems);
    });

    it('should display items with opening parenthesis (RegExp reserved char)', () => {
      var selectOptions = ['ONE', 'TWO', 'THREE(3)'];
      var searchValue = 'three(';
      var expectedListItems = ['THREE(3)'];

      this.searchTest(selectOptions, searchValue, expectedListItems);
    });

    it('should display items with closing square bracket (RegExp reserved char)', () => {
      var selectOptions = ['ONE', 'TWO]xxx[', 'THREE'];
      var searchValue = 'two]';
      var expectedListItems = ['TWO]xxx['];

      this.searchTest(selectOptions, searchValue, expectedListItems);
    });

    it('should display items with closing curly brace (RegExp reserved char)', () => {
      var selectOptions = ['ONE', 'TWO', 'THREE}tres'];
      var searchValue = 'three}';
      var expectedListItems = ['THREE}tres'];

      this.searchTest(selectOptions, searchValue, expectedListItems);
    });

    it('should display items with closing parenthesis (RegExp reserved char)', () => {
      var selectOptions = ['ONE', 'TWO', 'THREE)yyy'];
      var searchValue = 'three)';
      var expectedListItems = ['THREE)yyy'];

      this.searchTest(selectOptions, searchValue, expectedListItems);
    });

    it('should display items with both square brackets (RegExp reserved char)', () => {
      var selectOptions = ['ONE', 'TWO[2]', 'THREE'];
      var searchValue = 'two[2]';
      var expectedListItems = ['TWO[2]'];

      this.searchTest(selectOptions, searchValue, expectedListItems);
    });

    it('should display items with both curly braces (RegExp reserved char)', () => {
      var selectOptions = ['ONE', 'TWO', 'THREE{tres}'];
      var searchValue = 'three{tres}';
      var expectedListItems = ['THREE{tres}'];

      this.searchTest(selectOptions, searchValue, expectedListItems);
    });

    it('should display items with both parentheses (RegExp reserved char)', () => {
      var selectOptions = ['ONE', 'TWO', 'THREE(yyy)'];
      var searchValue = 'three(yyy)';
      var expectedListItems = ['THREE(yyy)'];

      this.searchTest(selectOptions, searchValue, expectedListItems);
    });
  });
});
<commit_msg>fix test react select<commit_after>
import _ from 'lodash';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import ReactSelect from '../../../../lib/js/app/components/common/react_select.js';
import TestHelpers from '../../../support/TestHelpers';

describe('components/common/react_select', () => {
  let handleBlurStub;
  let handleChangeStub;
  let handleSelectionStub;
  let component;
  beforeAll(() => {
    handleBlurStub = jest.fn();
    handleChangeStub = jest.fn();
    handleSelectionStub = jest.fn();

    const props = {
      items: [],
      wrapClasses: '',
      inputClasses: '',
      placeholder: '',
      handleBlur: handleBlurStub,
      handleChange: handleChangeStub,
      handleSelection: handleSelectionStub
    };
    component = TestUtils.renderIntoDocument(<ReactSelect {...props} />);
  });

  describe('setup', () => {
    it('is of the right type', () => {
      expect(TestUtils.isCompositeComponentWithType(component, ReactSelect)).toBe(true);
    });
    it('has one input', () => {
      expect(TestUtils.scryRenderedDOMComponentsWithTag(component, 'input')).toHaveLength(1);
    });
  });

  describe('search', () => {
    let searchTest;
    beforeAll(() => {
      searchTest = function(selectOptions, searchValue, expectedListItems) {
        const propsStep1 = _.assign({}, component.props, { items: selectOptions, value: searchValue });
        component = TestHelpers.renderComponent(ReactSelect, propsStep1);
        component.setState({ initialFocus: false });

        TestUtils.Simulate.focus(component.refs.input);
        TestUtils.Simulate.change(component.refs.input);

        const listItems = _.map(ReactDOM.findDOMNode(component.refs.list).childNodes, function(item) {
          return item.textContent;
        }.bind(this));
        expect(listItems).toEqual(expect.arrayContaining(expectedListItems));
      };
    });

    it('searches for items case insensitive', () => {
      const propsStep1 = _.assign({}, component.props, { items: ['ONE', 'TWO', 'THREE'], value: 'one' });
      component = TestHelpers.renderComponent(ReactSelect, propsStep1);
      component.setState({ initialFocus: false });

      TestUtils.Simulate.focus(component.refs.input);
      TestUtils.Simulate.change(component.refs.input);

      const listItems = _.map(ReactDOM.findDOMNode(component.refs.list).childNodes, function(item) {
        return item.textContent;
      });
      expect(listItems).toEqual(expect.arrayContaining(['ONE']));
    });

    it('should display items with opening square bracket (RegExp reserved char)', () => {
      const selectOptions = ['ONE', 'TWO[2]', 'THREE'];
      const searchValue = 'two[';
      const expectedListItems = ['TWO[2]'];

      searchTest(selectOptions, searchValue, expectedListItems);
    });

    it('should display items with opening curly brace (RegExp reserved char)', () => {
      const selectOptions = ['ONE', 'TWO', 'THREE{tres}'];
      const searchValue = 'three{';
      const expectedListItems = ['THREE{tres}'];

      searchTest(selectOptions, searchValue, expectedListItems);
    });

    it('should display items with opening parenthesis (RegExp reserved char)', () => {
      const selectOptions = ['ONE', 'TWO', 'THREE(3)'];
      const searchValue = 'three(';
      const expectedListItems = ['THREE(3)'];

      searchTest(selectOptions, searchValue, expectedListItems);
    });

    it('should display items with closing square bracket (RegExp reserved char)', () => {
      const selectOptions = ['ONE', 'TWO]xxx[', 'THREE'];
      const searchValue = 'two]';
      const expectedListItems = ['TWO]xxx['];

      searchTest(selectOptions, searchValue, expectedListItems);
    });

    it('should display items with closing curly brace (RegExp reserved char)', () => {
      const selectOptions = ['ONE', 'TWO', 'THREE}tres'];
      const searchValue = 'three}';
      const expectedListItems = ['THREE}tres'];

      searchTest(selectOptions, searchValue, expectedListItems);
    });

    it('should display items with closing parenthesis (RegExp reserved char)', () => {
      const selectOptions = ['ONE', 'TWO', 'THREE)yyy'];
      const searchValue = 'three)';
      const expectedListItems = ['THREE)yyy'];

      searchTest(selectOptions, searchValue, expectedListItems);
    });

    it('should display items with both square brackets (RegExp reserved char)', () => {
      const selectOptions = ['ONE', 'TWO[2]', 'THREE'];
      const searchValue = 'two[2]';
      const expectedListItems = ['TWO[2]'];

      searchTest(selectOptions, searchValue, expectedListItems);
    });

    it('should display items with both curly braces (RegExp reserved char)', () => {
      const selectOptions = ['ONE', 'TWO', 'THREE{tres}'];
      const searchValue = 'three{tres}';
      const expectedListItems = ['THREE{tres}'];

      searchTest(selectOptions, searchValue, expectedListItems);
    });

    it('should display items with both parentheses (RegExp reserved char)', () => {
      const selectOptions = ['ONE', 'TWO', 'THREE(yyy)'];
      const searchValue = 'three(yyy)';
      const expectedListItems = ['THREE(yyy)'];

      searchTest(selectOptions, searchValue, expectedListItems);
    });
  });
});
<|endoftext|>


<commit_before>/*!
 * Copyright 2013 Apereo Foundation (AF) Licensed under the
 * Educational Community 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://opensource.org/licenses/ECL-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.
 */

/**
 * Utility plugin that handles the responsive left hand navigation interactions. This plugin will support the
 * opening and closing of the left hand navigation using the `.oae-lhnavigation-toggle` element using an animation.
 * When a page link is clicked on a mobile device, the navigation will automatically close. The navigation will
 * remain visible when an action button is clicked, as this doesn't render a new page.
 */

define(['jquery', 'oae.api.util'], function (jQuery, oaeUtil) {
    (function($) {

        var LHNAVIGATION_WIDTH = 210;
        var LHNAVIGATION_PADDING = 25;

        /**
         * Open the left hand navigation
         */
        var openLhNav = function() {
            // First set the opacity and width to 0 before animating it
            $('.oae-lhnavigation').css({
                'opacity': 0,
                'width': 0
            });
            // Remove the bootstrap responsive hidden classes to show the left hand
            // navigation when animating on smaller screens
            $('.oae-lhnavigation > ul').removeClass('hidden-xs hidden-sm');
            // Animate the opacity and width
            $('.oae-lhnavigation').animate({
                'opacity': 1,
                'width': LHNAVIGATION_WIDTH  + 'px'
            }, 250);
            // Animate the padding of the page to 200px (width of the left hand nav) + 20 pixels (margin)
            $('.oae-page').animate({
                'padding-left': (LHNAVIGATION_WIDTH + 10) + 'px'
            }, 250, function() {
                $('.oae-lhnavigation').addClass('oae-lhnav-expanded');
            });

            // If the user focuses in on anything within the main page, we be cool and slide the nav
            // shut for them
            $('.oae-page').on('focusin.oae-lhnav-toggle', function(event) {
                closeLhNav();
            });
        };

        /**
         * Close the left hand navigation
         */
        var closeLhNav = function() {
            // Animate the width and opacity to 0
            $('.oae-lhnavigation').animate({
                'opacity': 0,
                'width': 0
            }, 250);
            // Animate the padding of the page to 25 pixels
            $('.oae-page').animate({
                'padding-left': LHNAVIGATION_PADDING + 'px'
            }, 250, function() {
                // Add the bootstrap and OAE helper classes
                $('.oae-lhnavigation > ul').addClass('hidden-xs hidden-sm');
                $('.oae-lhnavigation').removeClass('oae-lhnav-expanded');
            });

            // When the menu is closed, remove the page-focus auto-close listener
            $('.oae-page').off('focusin.oae-lhnav-toggle');
        };

        /**
         * Close the left hand navigation when clicking a navigation link, but not an action link (e.g., Share)
         * as that opens a widget that intends to overlay the left hand menu.
         */
        $(document).on('click', '.oae-lhnavigation > ul > li:not(.oae-lhnavigation-action)', closeLhNav);

        /**
         * Toggle the left hand navigation with animation. The left hand navigation can only
         * be toggled in small and extra small viewports.
         */
        $(document).on('click', '.oae-lhnavigation-toggle', function(ev) {
            // If the left hand navigation is open, close it
            if ($('.oae-lhnavigation').hasClass('oae-lhnav-expanded')) {
                closeLhNav();
            // If the left hand navigation is closed, open it
            } else {
                openLhNav();
            }
        });

        /**
         * Dismiss the keyboard on a mobile device when a search form is submitted. This won't be
         * noticable on desktop browsers.
         *
         * @see https://github.com/oaeproject/3akai-ux/issues/3401
         */
        $(document).on('submit', 'form[role="search"]', function() {
            $(this).find('.search-query').blur().focus();
        });

    })(jQuery);
});
<commit_msg>(Issue 3399) Remove unneeded event parameter<commit_after>/*!
 * Copyright 2013 Apereo Foundation (AF) Licensed under the
 * Educational Community 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://opensource.org/licenses/ECL-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.
 */

/**
 * Utility plugin that handles the responsive left hand navigation interactions. This plugin will support the
 * opening and closing of the left hand navigation using the `.oae-lhnavigation-toggle` element using an animation.
 * When a page link is clicked on a mobile device, the navigation will automatically close. The navigation will
 * remain visible when an action button is clicked, as this doesn't render a new page.
 */

define(['jquery', 'oae.api.util'], function (jQuery, oaeUtil) {
    (function($) {

        var LHNAVIGATION_WIDTH = 210;
        var LHNAVIGATION_PADDING = 25;

        /**
         * Open the left hand navigation
         */
        var openLhNav = function() {
            // First set the opacity and width to 0 before animating it
            $('.oae-lhnavigation').css({
                'opacity': 0,
                'width': 0
            });
            // Remove the bootstrap responsive hidden classes to show the left hand
            // navigation when animating on smaller screens
            $('.oae-lhnavigation > ul').removeClass('hidden-xs hidden-sm');
            // Animate the opacity and width
            $('.oae-lhnavigation').animate({
                'opacity': 1,
                'width': LHNAVIGATION_WIDTH  + 'px'
            }, 250);
            // Animate the padding of the page to 200px (width of the left hand nav) + 20 pixels (margin)
            $('.oae-page').animate({
                'padding-left': (LHNAVIGATION_WIDTH + 10) + 'px'
            }, 250, function() {
                $('.oae-lhnavigation').addClass('oae-lhnav-expanded');
            });

            // If the user focuses in on anything within the main page, we be cool and slide the nav
            // shut for them
            $('.oae-page').on('focusin.oae-lhnav-toggle', function() {
                closeLhNav();
            });
        };

        /**
         * Close the left hand navigation
         */
        var closeLhNav = function() {
            // Animate the width and opacity to 0
            $('.oae-lhnavigation').animate({
                'opacity': 0,
                'width': 0
            }, 250);
            // Animate the padding of the page to 25 pixels
            $('.oae-page').animate({
                'padding-left': LHNAVIGATION_PADDING + 'px'
            }, 250, function() {
                // Add the bootstrap and OAE helper classes
                $('.oae-lhnavigation > ul').addClass('hidden-xs hidden-sm');
                $('.oae-lhnavigation').removeClass('oae-lhnav-expanded');
            });

            // When the menu is closed, remove the page-focus auto-close listener
            $('.oae-page').off('focusin.oae-lhnav-toggle');
        };

        /**
         * Close the left hand navigation when clicking a navigation link, but not an action link (e.g., Share)
         * as that opens a widget that intends to overlay the left hand menu.
         */
        $(document).on('click', '.oae-lhnavigation > ul > li:not(.oae-lhnavigation-action)', closeLhNav);

        /**
         * Toggle the left hand navigation with animation. The left hand navigation can only
         * be toggled in small and extra small viewports.
         */
        $(document).on('click', '.oae-lhnavigation-toggle', function(ev) {
            // If the left hand navigation is open, close it
            if ($('.oae-lhnavigation').hasClass('oae-lhnav-expanded')) {
                closeLhNav();
            // If the left hand navigation is closed, open it
            } else {
                openLhNav();
            }
        });

        /**
         * Dismiss the keyboard on a mobile device when a search form is submitted. This won't be
         * noticable on desktop browsers.
         *
         * @see https://github.com/oaeproject/3akai-ux/issues/3401
         */
        $(document).on('submit', 'form[role="search"]', function() {
            $(this).find('.search-query').blur().focus();
        });

    })(jQuery);
});
<|endoftext|>