<commit_before>var splitor = ',';
var chainMethods = 'select,from,where,orderBy,groupBy,having'.split(splitor);
var onceMethods = 'select,from,orderBy,groupBy,having'.split(splitor);

buildFunctionalSQLPrototype();

var query = createQuery;

// return void(0);

function FunctionalSQL() {
	this.sources = [];
	this.selector = null;
	this.filters = [];
	this.groupBys = [];
	this.result = [];
}

function buildFunctionalSQLPrototype() {
	var proto = FunctionalSQL.prototype;

	proto.select = select;
	proto.doSelect = doSelect;

	proto.from = from;

	proto.where = where;
	proto.doFilter = doFilter;

	proto.orderBy = orderBy;

	proto.groupBy = groupBy;
	proto.doGroup = doGroup;

	proto.having = having;

	proto.execute = execute;

	chainMethods.forEach(function(methodName) {
		chinify(proto, methodName);
	});

	onceMethods.forEach(function(methodName) {
		onceify(proto, methodName);
	});

	return void(0);

	function select(selector) {
		if(isFunction(selector)) {
			this.selector = selector;
		}
	}

	function doSelect() {
		if(this.selector) {
			this.result = this.result.map(this.selector);
		}
	}

	function from() {
		this.result =
			this.sources = argumentsToArray(arguments);
	}

	function where(filter) {
		if(isFunction(filter)) {
			this.filters.push(filter);
		}
	}

	function doFilter() {
		this.filters.forEach(function(filter) {
			this.result = this.result.filter(filter);
		}, this);
	}

	function orderBy() {

	}

	function groupBy(groupBy) {
		if(isFunction(groupBy)) {
			this.groupBys.push(groupBy);
		}
	}

	function doGroup() {
		this.result = group(this.result, this.groupBys);
	}

	function having() {}

	function execute() {
		this.doFilter();
		this.doGroup();
		this.doSelect();

		return this.result;
	}

}

function group(datas, groupBys) {
	if(groupBys.length < 1) {
		return datas;
	}

	var groupObjects = groupToGroupObjects(datas, groupBys);
	return convertToResult(groupObjects);
}

function convertToResult(groupObjects) {
	var container = new ConvertContainer();

	groupObjects.forEach(function(groupObject) {
		let currentContainer = container;

		groupObject.groups.forEach(function(group) {
			let nextContainer = currentContainer[group];
			if(!nextContainer) {
				nextContainer =
					currentContainer[group] = new ConvertContainer();

				currentContainer.result.push([group, nextContainer.result]);
			}
			currentContainer = nextContainer;
		});

		currentContainer.result.push(groupObject.data);
	});

	return container.result;
}

function ConvertContainer() {
	return {
		dic: createEmptyDic(),
		result: [],
	};
}

function groupToGroupObjects(datas, groupBys) {
	return datas.map(function(data) {
		var groupObject = new GroupObject(data);

		groupBys.forEach(function(groupBy) {
			groupObject.groups.push(groupBy(data));
		});

		return groupObject;
	});
}

function GroupObject(data) {
	this.data = data;
	this.groups = [];
}

function isFunction(fun) {
	return Object.prototype.toString.call(fun) === '[object Function]';
}

function createEmptyDic() {
	return Object.create(null);
}

function argumentsToArray(args) {
	return args.length === 1 ?
		args[0] :
		Array.prototype.slice.call(args);
}

function chinify(obj, methodName) {
	wrap.origin = obj[methodName];
	obj[methodName] = wrap;
	return void(0);

	function wrap() {
		wrap.origin.apply(this, arguments);
		return this;
	}
}

function onceify(obj, methodName) {
	wrap.origin = obj[methodName];
	obj[methodName] = wrap;
	return void(0);

	function wrap() {
		var result = wrap.origin.apply(this, arguments);
		this[methodName] = createDuplicateCallErrorHandler(methodName.toUpperCase());
		return result;
	}
}

function createDuplicateCallErrorHandler(key) {
	return function() {
		throw new Error(key);
	}
}

function createQuery() {
	return new FunctionalSQL();
}
<commit_msg>support group by array<commit_after>var splitor = ',';
var chainMethods = 'select,from,where,orderBy,groupBy,having'.split(splitor);
var onceMethods = 'select,from,orderBy,groupBy,having'.split(splitor);

buildFunctionalSQLPrototype();

var query = createQuery;

// return void(0);

function FunctionalSQL() {
	this.sources = [];
	this.selector = null;
	this.filters = [];
	this.groupBys = [];
	this.result = [];
}

function buildFunctionalSQLPrototype() {
	var proto = FunctionalSQL.prototype;

	proto.select = select;
	proto.doSelect = doSelect;

	proto.from = from;

	proto.where = where;
	proto.doFilter = doFilter;

	proto.orderBy = orderBy;

	proto.groupBy = groupBy;
	proto.doGroup = doGroup;

	proto.having = having;

	proto.execute = execute;

	chainMethods.forEach(function(methodName) {
		chinify(proto, methodName);
	});

	onceMethods.forEach(function(methodName) {
		onceify(proto, methodName);
	});

	return void(0);

	function select(selector) {
		if(isFunction(selector)) {
			this.selector = selector;
		}
	}

	function doSelect() {
		if(this.selector) {
			this.result = this.result.map(this.selector);
		}
	}

	function from() {
		var sources = argumentsToArray(arguments);
		this.result =
			this.sources = (
				sources.length === 1 ?
				sources[0] :
				sources
			);
	}

	function where() {
		var filters = getMethodsFromArguments(arguments);

		filters.forEach(function(filter) {
			if(isFunction(filter)) {
				this.filters.push(filter);
			}
		}, this);
	}

	function doFilter() {
		this.filters.forEach(function(filter) {
			this.result = this.result.filter(filter);
		}, this);
	}

	function orderBy() {

	}

	function groupBy(groupBy) {
		var groupBys = getMethodsFromArguments(arguments);

		groupBys.forEach(function(groupBy) {
			if(isFunction(groupBy)) {
				this.groupBys.push(groupBy);
			}
		}, this);
	}

	function doGroup() {
		this.result = group(this.result, this.groupBys);
	}

	function having() {}

	function execute() {
		this.doFilter();
		this.doGroup();
		this.doSelect();

		return this.result;
	}

}

function getMethodsFromArguments(args) {
	return argumentsToArray(args);
}

function group(datas, groupBys) {
	if(groupBys.length < 1) {
		return datas;
	}

	var groupObjects = groupToGroupObjects(datas, groupBys);
	return convertToResult(groupObjects);
}

function convertToResult(groupObjects) {
	var container = new ConvertContainer();

	groupObjects.forEach(function(groupObject) {
		let currentContainer = container;

		groupObject.groups.forEach(function(group) {
			let nextContainer = currentContainer[group];
			if(!nextContainer) {
				nextContainer =
					currentContainer[group] = new ConvertContainer();

				currentContainer.result.push([group, nextContainer.result]);
			}
			currentContainer = nextContainer;
		});

		currentContainer.result.push(groupObject.data);
	});

	return container.result;
}

function ConvertContainer() {
	return {
		dic: createEmptyDic(),
		result: [],
	};
}

function groupToGroupObjects(datas, groupBys) {
	return datas.map(function(data) {
		var groupObject = new GroupObject(data);

		groupBys.forEach(function(groupBy) {
			groupObject.groups.push(groupBy(data));
		});

		return groupObject;
	});
}

function GroupObject(data) {
	this.data = data;
	this.groups = [];
}

function isFunction(fun) {
	return Object.prototype.toString.call(fun) === '[object Function]';
}

function createEmptyDic() {
	return Object.create(null);
}

function argumentsToArray(args) {
	return Array.prototype.slice.call(args);
}

function chinify(obj, methodName) {
	wrap.origin = obj[methodName];
	obj[methodName] = wrap;
	return void(0);

	function wrap() {
		wrap.origin.apply(this, arguments);
		return this;
	}
}

function onceify(obj, methodName) {
	wrap.origin = obj[methodName];
	obj[methodName] = wrap;
	return void(0);

	function wrap() {
		var result = wrap.origin.apply(this, arguments);
		this[methodName] = createDuplicateCallErrorHandler(methodName.toUpperCase());
		return result;
	}
}

function createDuplicateCallErrorHandler(key) {
	return function() {
		throw new Error(key);
	}
}

function createQuery() {
	return new FunctionalSQL();
}
<|endoftext|>


<commit_before>describe("About Functions", function() {

  it("should declare functions", function() {

    function add(a, b) {
      return a + b;
    }

    expect(add(1, 2)).toBe(FILL_ME_IN);
  });

  it("should know internal variables override outer variables", function () {
    var message = "Outer";

    function getMessage() {
      return message;
    }

    function overrideMessage() {
      var message = "Inner";
      return message;
    }

    expect(getMessage()).toBe(FILL_ME_IN);
    expect(overrideMessage()).toBe(FILL_ME_IN);
    expect(message).toBe(FILL_ME_IN);
  });

  it("should have lexical scoping", function () {
    var variable = "top-level";
    function parentfunction() {
        var variable = "local";
      function childfunction() {
          return variable;
      }
      return childfunction();
    }
    expect(parentfunction()).toBe(FILL_ME_IN);
  });

  it("should use lexical scoping to synthesise functions", function () {

    function makeIncreaseByFunction(increaseByAmount) {
      return function (numberToIncrease) {
        return numberToIncrease + increaseByAmount;
      };
    }

    var increaseBy3 = makeIncreaseByFunction(3);
    var increaseBy5 = makeIncreaseByFunction(5);

    expect(increaseBy3(10) + increaseBy5(10)).toBe(FILL_ME_IN);
  });

  it("should allow extra function arguments", function () {

    function returnFirstArg(firstArg) {
      return firstArg;
    }

    expect(returnFirstArg("first", "second", "third")).toBe(FILL_ME_IN);

    function returnSecondArg(firstArg, secondArg) {
      return secondArg;
    }

    expect(returnSecondArg("only give first arg")).toBe(FILL_ME_IN);

    function returnAllArgs() {
      var argsArray = [];
      for (var i = 0; i < arguments.length; i += 1) {
        argsArray.push(arguments[i]);
      }
      return argsArray.join(",");
    }

    expect(returnAllArgs("first", "second", "third")).toBe(FILL_ME_IN);
  });

  it("should pass functions as values", function () {

    var appendRules = function (name) {
      return name + " rules!";
    };

    var appendDoubleRules = function (name) {
      return name + " totally rules!";
    };

    var praiseSinger = { givePraise: appendRules };
    expect(praiseSinger.givePraise("John")).toBe(FILL_ME_IN);

    praiseSinger.givePraise = appendDoubleRules;
    expect(praiseSinger.givePraise("Mary")).toBe(FILL_ME_IN);

  });

  it("should use function body as a string", function () {
    var add = new Function("a", "b", "return a + b;");
    expect(add(1, 2)).toBe(FILL_ME_IN);

    var multiply = function (a, b) {
      //An internal comment
      return a * b;
    };
    expect(multiply.toString()).toBe(FILL_ME_IN);
  });
});
<commit_msg>Finished AboutFunctions.js<commit_after>describe("About Functions", function() {

  it("should declare functions", function() {

    function add(a, b) {
      return a + b;
    }

    expect(add(1, 2)).toBe(3);
  });

  it("should know internal variables override outer variables", function () {
    var message = "Outer";

    function getMessage() {
      return message;
    }

    function overrideMessage() {
      var message = "Inner";
      return message;
    }

    expect(getMessage()).toBe("Outer");
    expect(overrideMessage()).toBe("Inner");
    expect(message).toBe("Outer");
  });

  it("should have lexical scoping", function () {
    var variable = "top-level";
    function parentfunction() {
        var variable = "local";
      function childfunction() {
          return variable;
      }
      return childfunction();
    }
    expect(parentfunction()).toBe("local");
  });

  it("should use lexical scoping to synthesise functions", function () {

    function makeIncreaseByFunction(increaseByAmount) {
      return function (numberToIncrease) {
        return numberToIncrease + increaseByAmount;
      };
    }

    var increaseBy3 = makeIncreaseByFunction(3);
    var increaseBy5 = makeIncreaseByFunction(5);

    expect(increaseBy3(10) + increaseBy5(10)).toBe(28);
  });

  it("should allow extra function arguments", function () {

    function returnFirstArg(firstArg) {
      return firstArg;
    }

    expect(returnFirstArg("first", "second", "third")).toBe("first");

    function returnSecondArg(firstArg, secondArg) {
      return secondArg;
    }

    expect(returnSecondArg("only give first arg")).toBe(undefined);

    function returnAllArgs() {
      var argsArray = [];
      for (var i = 0; i < arguments.length; i += 1) {
        argsArray.push(arguments[i]);
      }
      return argsArray.join(",");
    }

    expect(returnAllArgs("first", "second", "third")).toBe("first,second,third");
  });

  it("should pass functions as values", function () {

    var appendRules = function (name) {
      return name + " rules!";
    };

    var appendDoubleRules = function (name) {
      return name + " totally rules!";
    };

    var praiseSinger = { givePraise: appendRules };
    expect(praiseSinger.givePraise("John")).toBe("John rules!");

    praiseSinger.givePraise = appendDoubleRules;
    expect(praiseSinger.givePraise("Mary")).toBe("Mary totally rules!");

  });

  it("should use function body as a string", function () {
    var add = new Function("a", "b", "return a + b;");
    expect(add(1, 2)).toBe(3);

    var multiply = function (a, b) {
      //An internal comment
      return a * b;
    };
    expect(multiply.toString()).toBe(
      "function (a, b) {\n" +
      "      //An internal comment\n"+
      "      return a * b;\n"+
      "    }");//This is ridiculous.
  });
});
<|endoftext|>


<commit_before>// (function(module) {

  var teacherView = {};
  var ref = new Firebase('https://queue-you.firebaseio.com/');
  var ref2 = new Firebase('https://queue-you.firebaseio.com/users');
  var profileList = [];

  teacherView.showList = function() {
    $('#teacher-button').on('click', function() {
      $('#teacher').show().siblings().hide();
      teacherView.post();
    });
  };

  /////////////////////////////////////

  teacherView.test = function() {
    $('#teacher-test').on('click', function() {
      // e.preventDefault();
      $('#form').show().siblings().hide();
    });
  };

  /////////////////////////////////////

  teacherView.storagePull = function(){
    ref2.on('child_added', function(snapshot, prevChildKey){
      var newPost = snapshot.val();
      console.log(newPost);
      profileList.push(snapshot.val());
    });
  };

  teacherView.post = function(){
    for (var i = 0; i < profileList.length; i++) {
      $('ol').append('
Name: ' + profileList[i].name + '
' +
      profileList[i].issue + '
' +
      profileList[i].desc +'
' + '
' + '</li');
    }
  };
  //   profileList.forEach(function(name, issue, desc) {
  //     $('ol').append('
' + this.name + this.issue + this.desc + '
').toHtml();
  //   });
  // };

  teacherView.showList();
  teacherView.storagePull();
  teacherView.test();
//   module.teacherView = teacherView;
// })(window);
<commit_msg>added method to remove list items on click in teacherview<commit_after>// (function(module) {

  var teacherView = {};
  var ref = new Firebase('https://queue-you.firebaseio.com/');
  var ref2 = new Firebase('https://queue-you.firebaseio.com/users');
  var profileList = [];

  teacherView.showList = function() {
    $('#teacher-button').on('click', function() {
      $('#teacher').show().siblings().hide();
      teacherView.post();
    });
  };

  /////////////////////////////////////

  teacherView.test = function() {
    $('#teacher-test').on('click', function() {
      // e.preventDefault();
      $('#form').show().siblings().hide();
    });
  };

  /////////////////////////////////////

  teacherView.storagePull = function(){
    ref2.on('child_added', function(snapshot, prevChildKey){
      var newPost = snapshot.val();
      console.log(newPost);
      profileList.push(snapshot.val());
    });
  };

  teacherView.post = function(){
    for (var i = 0; i < profileList.length; i++) {
      $('ol').append('
Name: ' + profileList[i].name + '
' +
      profileList[i].issue + '
' +
      profileList[i].desc +'
' + '
' + '
');
      teacherView.remove();
    }
  };
  //   profileList.forEach(function(name, issue, desc) {
  //     $('ol').append('
' + this.name + this.issue + this.desc + '
').toHtml();
  //   });
  // };
  teacherView.remove = function() {
    $('li').click(function() {
      $( this ).remove();
    });
  };

  teacherView.showList();
  teacherView.storagePull();
  teacherView.test();
//   module.teacherView = teacherView;
// })(window);
<|endoftext|>


<commit_before>import helpers from './helpers/helpers'
const { flatten, sampleArray, roundDown } = helpers
import { scaleOrdinal, schemeCategory10, scaleLinear } from 'd3-scale'
import { forceSimulation, forceLink, forceManyBody, forceCenter, forceX, forceY } from 'd3-force'
import { select, selectAll, event } from 'd3-selection'
import { drag as d3drag } from 'd3-drag'
import { range } from 'd3-array'
import { timer } from 'd3-timer'
import messageState from './messageState'
import { getData } from './api'
import "../main.scss"
import { Nodes, initializeNodes } from './nodes'

let renderer = new THREE.WebGLRenderer({ alpha: true }),
  width = window.innerWidth, height = window.innerHeight,
  scene = new THREE.Scene(),
  camera = new THREE.OrthographicCamera(width / -2, width / 2, height / 2, height / -2, 1, 10000),
  nodePositions, nodeSizes,
  edgeGeometry = new THREE.BufferGeometry(),
  nodeGeometry = new THREE.BufferGeometry(),
  edgeVertices, lastOccupiedEdgeVertexIndex,
  nodePositionBuffer, edgeVerticesBuffer,
  force = forceSimulation(),
  emptyNode = new THREE.Vector2(),
  links,
  nodeData, edgeData,
  cycleSID = null, cycleDur = 5000,
  updateLinksSID = null, updateLinksNodeIndex = 0,
  nodeSizeScale = scaleLinear().range([1, 10]).clamp(true)

scene.add(camera)
camera.position.z = 1000

const nodeMaterial = new THREE.ShaderMaterial({
  uniforms: {
    color: {
      type: 'c',
      value: new THREE.Color(0x3498db)
    },
    alpha: { type: 'f', value: 0.7 },
    pointSize: { type: 'f', value: 10 }
  },
  vertexShader: document.getElementById("node-vertexshader").textContent,
  fragmentShader: document.getElementById("node-fragmentshader").textContent,
  transparent: true
})

const edgeMaterial = new THREE.ShaderMaterial({
  uniforms: {
    color: {
      type: 'c',
      value: new THREE.Color(0x3498db)
    }
  },
  vertexShader: document.getElementById("edge-vertexshader").textContent,
  fragmentShader: document.getElementById("edge-fragmentshader").textContent,
  transparent: true
})

renderer.setSize(width, height)
renderer.setPixelRatio(window.devicePixelRatio)

document.body.appendChild(renderer.domElement)

const updateLinks = () => {
  Nodes[updateLinksNodeIndex].adjustFollowing()

  links = []

  for(let i=0; i<Nodes.length; i++) {
    let n = Nodes[i]
    if(n.following.length) {
      for(let j=0; j<n.following.length; j++) {
        let target
        for(let k=0; k<Nodes.length; k++) {
          if(Nodes[k].id === n.following[j]) {
            target = Nodes[k]
            break
          }
        }
        links.push({ source: n, target })
      }
    }
  }

  force.force("link").links(links)

  force.alphaTarget(0.3).restart()

  updateLinksNodeIndex = (updateLinksNodeIndex + 1) % Nodes.length
}

const initialize = () => {
  nodePositions = new Float32Array(Nodes.length * 2)
  nodeSizes = new Float32Array(Nodes.length)
  edgeVertices = new Float32Array(edgeData.length * 6)

  nodePositionBuffer = new THREE.BufferAttribute(nodePositions, 2)
  nodeGeometry.addAttribute("position", nodePositionBuffer)
  nodeGeometry.addAttribute("size", new THREE.BufferAttribute(nodeSizes, 1))

  edgeVerticesBuffer = new THREE.BufferAttribute(edgeVertices, 3)

  edgeGeometry.addAttribute("position", edgeVerticesBuffer)

  scene.add(new THREE.Points(nodeGeometry, nodeMaterial))
  scene.add(new THREE.LineSegments(edgeGeometry, edgeMaterial))

  force.nodes(Nodes)
    .force("link", forceLink().id(d => d.id))
    .force("charge", forceManyBody().strength(-10).distanceMax(300))
    .force("center", forceCenter(width / 2, height / 2))
    .force("vertical", forceY().strength(0.1))
    .force("horizontal", forceX().strength(0.1))

  timer(d => {
    for(let i=0; i < Nodes.length; i++) {
      let node = Nodes[i]
      nodePositions[i * 2] = node.x - width / 2
      nodePositions[i * 2 + 1] = -(node.y - height / 2)
      nodeSizes[i] = nodeSizeScale(node.following.length)
    }

    for(let i=0; i < Math.max(lastOccupiedEdgeVertexIndex, links.length); i++) {
      const link = links[i]

      let source, target
      if(link) {
        source = link.source
        target = link.target
      } else {
        source = emptyNode
        target = emptyNode
      }

      edgeVertices[(i * 2) * 3] = source.x - width / 2
      edgeVertices[(i * 2) * 3 + 1] = -(source.y - height / 2)
      edgeVertices[(i * 2) * 3 + 3] = target.x - width / 2
      edgeVertices[(i * 2) * 3 + 4] = -(target.y - height / 2)
    }

    lastOccupiedEdgeVertexIndex = links.length

    edgeVerticesBuffer.needsUpdate = true
    nodePositionBuffer.needsUpdate = true
    renderer.render(scene, camera)
  })

  links = edgeData

  links.forEach(l => {
    const source = Nodes.find(n => n.id === +l.source)
    const target = Nodes.find(n => n.id === +l.target)
    source.following = source.following.concat(target.id)
  })

  Nodes.forEach(n => n.init())

  messageState.init()

  messageState.cycle()

  cycleSID = setInterval(messageState.cycle, cycleDur)

  updateLinks()

  updateLinksSID = setInterval(updateLinks, cycleDur / Nodes.length)
}

Promise.all(['nodes', 'edges'].map(getData))
  .then(data => {
    nodeData = data[0].filter((d, i) => i < 600)

    nodeData.splice(roundDown(nodeData.length, 3)) // nodes length must be multiple of 3

    edgeData = data[1].filter(d =>
      [+d.source, +d.target].every(id => nodeData.find(n => n.node_id === id)))

    edgeData.splice(roundDown(edgeData.length, 3))

    initializeNodes(nodeData)
    initialize()
  })

<commit_msg>use random size<commit_after>import helpers from './helpers/helpers'
const { flatten, sampleArray, roundDown } = helpers
import { scaleOrdinal, schemeCategory10, scaleLinear } from 'd3-scale'
import { forceSimulation, forceLink, forceManyBody, forceCenter, forceX, forceY } from 'd3-force'
import { select, selectAll, event } from 'd3-selection'
import { drag as d3drag } from 'd3-drag'
import { range } from 'd3-array'
import { timer } from 'd3-timer'
import messageState from './messageState'
import { getData } from './api'
import "../main.scss"
import { Nodes, initializeNodes } from './nodes'

let renderer = new THREE.WebGLRenderer({ alpha: true }),
  width = window.innerWidth, height = window.innerHeight,
  scene = new THREE.Scene(),
  camera = new THREE.OrthographicCamera(width / -2, width / 2, height / 2, height / -2, 1, 10000),
  nodePositions, nodeSizes,
  edgeGeometry = new THREE.BufferGeometry(),
  nodeGeometry = new THREE.BufferGeometry(),
  edgeVertices, lastOccupiedEdgeVertexIndex,
  nodePositionBuffer, edgeVerticesBuffer,
  force = forceSimulation(),
  emptyNode = new THREE.Vector2(),
  links,
  nodeData, edgeData,
  cycleSID = null, cycleDur = 5000,
  updateLinksSID = null, updateLinksNodeIndex = 0,
  nodeSizeScale = scaleLinear().range([1, 10]).clamp(true)

scene.add(camera)
camera.position.z = 1000

const nodeMaterial = new THREE.ShaderMaterial({
  uniforms: {
    color: {
      type: 'c',
      value: new THREE.Color(0x3498db)
    },
    alpha: { type: 'f', value: 0.7 },
    pointSize: { type: 'f', value: 10 }
  },
  vertexShader: document.getElementById("node-vertexshader").textContent,
  fragmentShader: document.getElementById("node-fragmentshader").textContent,
  transparent: true
})

const edgeMaterial = new THREE.ShaderMaterial({
  uniforms: {
    color: {
      type: 'c',
      value: new THREE.Color(0x3498db)
    }
  },
  vertexShader: document.getElementById("edge-vertexshader").textContent,
  fragmentShader: document.getElementById("edge-fragmentshader").textContent,
  transparent: true
})

renderer.setSize(width, height)
renderer.setPixelRatio(window.devicePixelRatio)

document.body.appendChild(renderer.domElement)

const updateLinks = () => {
  Nodes[updateLinksNodeIndex].adjustFollowing()

  links = []

  for(let i=0; i<Nodes.length; i++) {
    let n = Nodes[i]
    if(n.following.length) {
      for(let j=0; j<n.following.length; j++) {
        let target
        for(let k=0; k<Nodes.length; k++) {
          if(Nodes[k].id === n.following[j]) {
            target = Nodes[k]
            break
          }
        }
        links.push({ source: n, target })
      }
    }
  }

  force.force("link").links(links)

  force.alphaTarget(0.3).restart()

  updateLinksNodeIndex = (updateLinksNodeIndex + 1) % Nodes.length
}

const initialize = () => {
  nodePositions = new Float32Array(Nodes.length * 2)
  nodeSizes = new Float32Array(Nodes.length)
  edgeVertices = new Float32Array(edgeData.length * 6)

  nodePositionBuffer = new THREE.BufferAttribute(nodePositions, 2)
  nodeGeometry.addAttribute("position", nodePositionBuffer)
  nodeGeometry.addAttribute("size", new THREE.BufferAttribute(nodeSizes, 1))

  edgeVerticesBuffer = new THREE.BufferAttribute(edgeVertices, 3)

  edgeGeometry.addAttribute("position", edgeVerticesBuffer)

  scene.add(new THREE.Points(nodeGeometry, nodeMaterial))
  scene.add(new THREE.LineSegments(edgeGeometry, edgeMaterial))

  force.nodes(Nodes)
    .force("link", forceLink().id(d => d.id))
    .force("charge", forceManyBody().strength(-10).distanceMax(300))
    .force("center", forceCenter(width / 2, height / 2))
    .force("vertical", forceY().strength(0.1))
    .force("horizontal", forceX().strength(0.1))

  timer(d => {
    for(let i=0; i < Nodes.length; i++) {
      let node = Nodes[i]
      nodePositions[i * 2] = node.x - width / 2
      nodePositions[i * 2 + 1] = -(node.y - height / 2)
      nodeSizes[i] = nodeSizeScale(0.5)
    }

    for(let i=0; i < Math.max(lastOccupiedEdgeVertexIndex, links.length); i++) {
      const link = links[i]

      let source, target
      if(link) {
        source = link.source
        target = link.target
      } else {
        source = emptyNode
        target = emptyNode
      }

      edgeVertices[(i * 2) * 3] = source.x - width / 2
      edgeVertices[(i * 2) * 3 + 1] = -(source.y - height / 2)
      edgeVertices[(i * 2) * 3 + 3] = target.x - width / 2
      edgeVertices[(i * 2) * 3 + 4] = -(target.y - height / 2)
    }

    lastOccupiedEdgeVertexIndex = links.length

    edgeVerticesBuffer.needsUpdate = true
    nodePositionBuffer.needsUpdate = true
    renderer.render(scene, camera)
  })

  links = edgeData

  links.forEach(l => {
    const source = Nodes.find(n => n.id === +l.source)
    const target = Nodes.find(n => n.id === +l.target)
    source.following = source.following.concat(target.id)
  })

  Nodes.forEach(n => n.init())

  messageState.init()

  messageState.cycle()

  cycleSID = setInterval(messageState.cycle, cycleDur)

  updateLinks()

  updateLinksSID = setInterval(updateLinks, cycleDur / Nodes.length)
}

Promise.all(['nodes', 'edges'].map(getData))
  .then(data => {
    nodeData = data[0].filter((d, i) => i < 600)

    nodeData.splice(roundDown(nodeData.length, 3)) // nodes length must be multiple of 3

    edgeData = data[1].filter(d =>
      [+d.source, +d.target].every(id => nodeData.find(n => n.node_id === id)))

    edgeData.splice(roundDown(edgeData.length, 3))

    initializeNodes(nodeData)
    initialize()
  })

<|endoftext|>


<commit_before>describe("About Functions", function() {

  it("should declare functions", function() {

    function add(a, b) {
      return a + b;
    }

    expect(add(1, 2)).toBe(3);
  });

  it("should know internal variables override outer variables", function () {
    var message = "Outer";

    function getMessage() {
      return message;
    }

    function overrideMessage() {
      var message = "Inner";
      return message;
    }

    expect(getMessage()).toBe("Outer");
    expect(overrideMessage()).toBe("Inner");
    expect(message).toBe("Outer");
  });

  it("should have lexical scoping", function () {
    var variable = "top-level";
    function parentfunction() {
      var variable = "local";
      function childfunction() {
          return variable;
      }
      return childfunction();
    }
    expect(parentfunction()).toBe("local");
  });

  it("should use lexical scoping to synthesise functions", function () {

    function makeIncreaseByFunction(increaseByAmount) {
      return function (numberToIncrease) {
        return numberToIncrease + increaseByAmount;
      };
    }

    var increaseBy3 = makeIncreaseByFunction(3);
    var increaseBy5 = makeIncreaseByFunction(5);

    expect(increaseBy3(10) + increaseBy5(10)).toBe(FILL_ME_IN);
  });

  it("should allow extra function arguments", function () {

    function returnFirstArg(firstArg) {
      return firstArg;
    }

    expect(returnFirstArg("first", "second", "third")).toBe(FILL_ME_IN);

    function returnSecondArg(firstArg, secondArg) {
      return secondArg;
    }

    expect(returnSecondArg("only give first arg")).toBe(FILL_ME_IN);

    function returnAllArgs() {
      var argsArray = [];
      for (var i = 0; i < arguments.length; i += 1) {
        argsArray.push(arguments[i]);
      }
      return argsArray.join(",");
    }

    expect(returnAllArgs("first", "second", "third")).toBe(FILL_ME_IN);
  });

  it("should pass functions as values", function () {

    var appendRules = function (name) {
      return name + " rules!";
    };

    var appendDoubleRules = function (name) {
      return name + " totally rules!";
    };

    var praiseSinger = { givePraise: appendRules };
    expect(praiseSinger.givePraise("John")).toBe(FILL_ME_IN);

    praiseSinger.givePraise = appendDoubleRules;
    expect(praiseSinger.givePraise("Mary")).toBe(FILL_ME_IN);

  });

  it("should use function body as a string", function () {
    var add = new Function("a", "b", "return a + b;");
    expect(add(1, 2)).toBe(FILL_ME_IN);

    var multiply = function (a, b) {
      //An internal comment
      return a * b;
    };
    expect(multiply.toString()).toBe(FILL_ME_IN);
  });
});
<commit_msg>It uses lexical scoping to synthesize functions<commit_after>describe("About Functions", function() {

  it("should declare functions", function() {

    function add(a, b) {
      return a + b;
    }

    expect(add(1, 2)).toBe(3);
  });

  it("should know internal variables override outer variables", function () {
    var message = "Outer";

    function getMessage() {
      return message;
    }

    function overrideMessage() {
      var message = "Inner";
      return message;
    }

    expect(getMessage()).toBe("Outer");
    expect(overrideMessage()).toBe("Inner");
    expect(message).toBe("Outer");
  });

  it("should have lexical scoping", function () {
    var variable = "top-level";
    function parentfunction() {
      var variable = "local";
      function childfunction() {
          return variable;
      }
      return childfunction();
    }
    expect(parentfunction()).toBe("local");
  });

  it("should use lexical scoping to synthesise functions", function () {

    function makeIncreaseByFunction(increaseByAmount) {
      return function (numberToIncrease) {
        return numberToIncrease + increaseByAmount;
      };
    }

    var increaseBy3 = makeIncreaseByFunction(3);
    var increaseBy5 = makeIncreaseByFunction(5);

    expect(increaseBy3(10) + increaseBy5(10)).toBe(28);
  });

  it("should allow extra function arguments", function () {

    function returnFirstArg(firstArg) {
      return firstArg;
    }

    expect(returnFirstArg("first", "second", "third")).toBe(FILL_ME_IN);

    function returnSecondArg(firstArg, secondArg) {
      return secondArg;
    }

    expect(returnSecondArg("only give first arg")).toBe(FILL_ME_IN);

    function returnAllArgs() {
      var argsArray = [];
      for (var i = 0; i < arguments.length; i += 1) {
        argsArray.push(arguments[i]);
      }
      return argsArray.join(",");
    }

    expect(returnAllArgs("first", "second", "third")).toBe(FILL_ME_IN);
  });

  it("should pass functions as values", function () {

    var appendRules = function (name) {
      return name + " rules!";
    };

    var appendDoubleRules = function (name) {
      return name + " totally rules!";
    };

    var praiseSinger = { givePraise: appendRules };
    expect(praiseSinger.givePraise("John")).toBe(FILL_ME_IN);

    praiseSinger.givePraise = appendDoubleRules;
    expect(praiseSinger.givePraise("Mary")).toBe(FILL_ME_IN);

  });

  it("should use function body as a string", function () {
    var add = new Function("a", "b", "return a + b;");
    expect(add(1, 2)).toBe(FILL_ME_IN);

    var multiply = function (a, b) {
      //An internal comment
      return a * b;
    };
    expect(multiply.toString()).toBe(FILL_ME_IN);
  });
});
<|endoftext|>


<commit_before>import ASTWalker from './ASTWalker.js';

/**
 * Default walker instance.
 * @type {ASTWalker}
 */
const walker = new ASTWalker();

/**
 * Provides a default ASTWalker instance.
 */
export default walker;

/**
 * Wires up walker on the plugin eventbus.
 *
 * @param {PluginEvent} ev - The plugin event.
 *
 * @see https://www.npmjs.com/package/typhonjs-plugin-manager
 * @ignore
 */
export function onPluginLoad(ev)
{
   const eventbus = ev.eventbus;

   let eventPrepend = '';

   const options = ev.pluginOptions;

   // Apply any plugin options.
   if (typeof options === 'object')
   {
      // If `eventPrepend` is defined then it is prepended before all event bindings.
      if (typeof options.eventPrepend === 'string') { eventPrepend = `${options.eventPrepend}:`; }
   }

   eventbus.on(`${eventPrepend}ast:walker:traverse`, walker.traverse, walker);
}
<commit_msg>updated event binding<commit_after>import ASTWalker from './ASTWalker.js';

/**
 * Default walker instance.
 * @type {ASTWalker}
 */
const walker = new ASTWalker();

/**
 * Provides a default ASTWalker instance.
 */
export default walker;

/**
 * Wires up walker on the plugin eventbus.
 *
 * @param {PluginEvent} ev - The plugin event.
 *
 * @see https://www.npmjs.com/package/typhonjs-plugin-manager
 * @ignore
 */
export function onPluginLoad(ev)
{
   const eventbus = ev.eventbus;

   let eventPrepend = 'typhonjs';

   const options = ev.pluginOptions;

   // Apply any plugin options.
   if (typeof options === 'object')
   {
      // If `eventPrepend` is defined then it is prepended before all event bindings.
      if (typeof options.eventPrepend === 'string') { eventPrepend = `${options.eventPrepend}:`; }
   }

   eventbus.on(`${eventPrepend}:ast:walker:traverse`, walker.traverse, walker);
}
<|endoftext|>


<commit_before>export * from './schemas';
export * from './fields';

export routerStore from 'stores/routerStore';
export authStore from 'stores/authStore';
export DataStore from 'stores/DataStore';

export Admin from 'containers/Admin';
export Toolbar from 'components/Toolbar';
export ConfirmButton from 'components/ConfirmButton';
export ContextButton from 'components/ContextButton';
export CreateButton from 'components/CreateButton';
export UpdateButton from 'components/UpdateButton';
export RemoveButton from 'components/RemoveButton';
export RefButton from 'components/RefButton';
export TableQuerySwitch from 'components/TableQuerySwitch';

export TableQuery from 'components/TableQuery';

export Form from 'components/Nested/Form';
export Submit from 'components/Nested/Submit';
export Reset from 'components/Nested/Reset';

export withField from 'utils/withField';
export withActions from 'utils/withActions';

export joinKeys from 'utils/joinKeys';
<commit_msg>expose ModalConsumer<commit_after>export * from './schemas';
export * from './fields';

export routerStore from 'stores/routerStore';
export authStore from 'stores/authStore';
export DataStore from 'stores/DataStore';

export Admin from 'containers/Admin';
export ModalConsumer from 'components/ModalConsumer';
export Toolbar from 'components/Toolbar';
export ConfirmButton from 'components/ConfirmButton';
export ContextButton from 'components/ContextButton';
export CreateButton from 'components/CreateButton';
export UpdateButton from 'components/UpdateButton';
export RemoveButton from 'components/RemoveButton';
export RefButton from 'components/RefButton';
export TableQuerySwitch from 'components/TableQuerySwitch';

export TableQuery from 'components/TableQuery';

export Form from 'components/Nested/Form';
export Submit from 'components/Nested/Submit';
export Reset from 'components/Nested/Reset';

export withField from 'utils/withField';
export withActions from 'utils/withActions';

export joinKeys from 'utils/joinKeys';
<|endoftext|>


<commit_before>import * as THREE from 'three';

const aspectRatio = window.innerWidth / window.innerHeight;

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, aspectRatio, 0.1, 1000 );

const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

const cuboid = new THREE.BoxGeometry( 0.25, 2, 0.25 );
const shortCuboid = new THREE.BoxGeometry( 0.25, 0.5, 0.25 );
const flatCuboid = new THREE.BoxGeometry( 1, 0.1, 1 );
const green = new THREE.MeshBasicMaterial( { color: 0x00ff00,
                                             wireframe: true } );
const cylinder = new THREE.CylinderGeometry( 0.3, 0.3, 0.4, 16 );
cylinder.rotateX( Math.PI / 2 );
const blue = new THREE.MeshBasicMaterial( { color: 0x0000ff,
                                            wireframe: true} );

const base = new THREE.Mesh( flatCuboid, green );
const stand = new THREE.Mesh( shortCuboid, green );
const upperArm = new THREE.Mesh( cuboid, green );
const lowerArm = new THREE.Mesh( cuboid, green );

const shoulder = new THREE.Mesh( cylinder, blue );
const elbow = new THREE.Mesh( cylinder, blue );

base.add( stand );
stand.add( shoulder );
shoulder.add( upperArm );
upperArm.add( elbow );
elbow.add( lowerArm );

scene.add( base );

camera.position.y = 1.2;
camera.position.z = 5;

stand.position.y = 0.25;
shoulder.position.y = 0.25;
upperArm.position.y = 1;
elbow.position.y = 1;
lowerArm.position.y = 1;

const keyPressed = { up: false, down: false,
                     w: false, s: false,
                     a: false, d: false };

function handleKeyup(event) {
    event.preventDefault();
    const keycode = event.which;

    switch ( keycode ) {
    case 38: keyPressed.up = false; break;
    case 40: keyPressed.down = false; break;
    case 87: keyPressed.w = false; break;
    case 83: keyPressed.s = false; break;
    case 65: keyPressed.a = false; break;
    case 68: keyPressed.d = false; break;
    }
}
document.addEventListener("keyup", handleKeyup, false);

function handleKeydown(event) {
    event.preventDefault();
    const keycode = event.which;

    switch ( keycode ) {
    case 38: keyPressed.up = true; break;
    case 40: keyPressed.down = true; break;
    case 87: keyPressed.w = true; break;
    case 83: keyPressed.s = true; break;
    case 65: keyPressed.a = true; break;
    case 68: keyPressed.d = true; break;
    }
}
document.addEventListener("keydown", handleKeydown, false);

const delta = 0.05;

const animate = () => {
    requestAnimationFrame( animate );

    if ( keyPressed.up ) {
        elbow.rotation.z -= delta;
    }
    if ( keyPressed.down ) {
        elbow.rotation.z += delta;
    }
    if ( keyPressed.w ) {
        shoulder.rotation.z -= delta;
    }
    if ( keyPressed.s ) {
        shoulder.rotation.z += delta;
    }
    if ( keyPressed.d ) {
        base.rotation.y -= delta;
    }
    if ( keyPressed.a ) {
        base.rotation.y += delta;
    }

    renderer.render(scene, camera);
};

animate();
<commit_msg>Minor refactor<commit_after>import * as THREE from 'three';

const aspectRatio = window.innerWidth / window.innerHeight;

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, aspectRatio, 0.1, 1000 );

const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

const cuboid = new THREE.BoxGeometry( 0.25, 2, 0.25 );
const shortCuboid = new THREE.BoxGeometry( 0.25, 0.5, 0.25 );
const flatCuboid = new THREE.BoxGeometry( 1, 0.1, 1 );
const green = new THREE.MeshBasicMaterial( { color: 0x00ff00,
                                             wireframe: true } );
const cylinder = new THREE.CylinderGeometry( 0.3, 0.3, 0.4, 16 );
cylinder.rotateX( Math.PI / 2 );
const blue = new THREE.MeshBasicMaterial( { color: 0x0000ff,
                                            wireframe: true} );

const base = new THREE.Mesh( flatCuboid, green );
const stand = new THREE.Mesh( shortCuboid, green );
const upperArm = new THREE.Mesh( cuboid, green );
const lowerArm = new THREE.Mesh( cuboid, green );

const shoulder = new THREE.Mesh( cylinder, blue );
const elbow = new THREE.Mesh( cylinder, blue );

base.add( stand );
stand.add( shoulder );
shoulder.add( upperArm );
upperArm.add( elbow );
elbow.add( lowerArm );

scene.add( base );

camera.position.y = 1.2;
camera.position.z = 5;

stand.position.y = 0.25;
shoulder.position.y = 0.25;
upperArm.position.y = 1;
elbow.position.y = 1;
lowerArm.position.y = 1;

const keyPressed = { up: false, down: false,
                     w: false, s: false,
                     a: false, d: false };

function handleKeyup(event) {
    event.preventDefault();
    const keycode = event.which;

    switch ( keycode ) {
    case 38: keyPressed.up = false; break;
    case 40: keyPressed.down = false; break;
    case 87: keyPressed.w = false; break;
    case 83: keyPressed.s = false; break;
    case 65: keyPressed.a = false; break;
    case 68: keyPressed.d = false; break;
    }
}
document.addEventListener("keyup", handleKeyup, false);

function handleKeydown(event) {
    event.preventDefault();
    const keycode = event.which;

    switch ( keycode ) {
    case 38: keyPressed.up = true; break;
    case 40: keyPressed.down = true; break;
    case 87: keyPressed.w = true; break;
    case 83: keyPressed.s = true; break;
    case 65: keyPressed.a = true; break;
    case 68: keyPressed.d = true; break;
    }
}
document.addEventListener("keydown", handleKeydown, false);

const delta = 0.05;

const animate = () => {
    requestAnimationFrame( animate );

    if ( keyPressed.up ) { elbow.rotation.z -= delta; }
    if ( keyPressed.down ) { elbow.rotation.z += delta; }
    if ( keyPressed.w ) { shoulder.rotation.z -= delta; }
    if ( keyPressed.s ) { shoulder.rotation.z += delta; }
    if ( keyPressed.d ) { base.rotation.y -= delta; }
    if ( keyPressed.a ) { base.rotation.y += delta; }

    renderer.render(scene, camera);
};

animate();
<|endoftext|>


<commit_before>import React from "react";
import ReactDOM from "react-dom";

// Sails lib
var socketIOClient = require('socket.io-client');
var sailsIOClient = require('sails.io.js');
window.io = sailsIOClient(socketIOClient);
io.sails.autoConnect = false;

// TapEvent
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();

// material ui
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import themeConfiguration from './config/theme';
const muiTheme = getMuiTheme(themeConfiguration);

// Router
import router from './router';
import { RouterProvider } from 'react-router5';

// Pages
import App from "./components/App.jsx";

// constants
import * as constants from './config/constants';

import jwtDecode from 'jwt-decode';

// actions and services
import WebSocketService from './services/WebSocketService';

// Connect to websocket server
WebSocketService.connect();

// Render the app using router
ReactDOM.render(
    <MuiThemeProvider muiTheme={muiTheme}>
        <RouterProvider router={ router }>
            <App />
        </RouterProvider>
    </MuiThemeProvider>,
    document.getElementById('app')
);

/**
 * Check if the user is authenticated
 * used to protect some routes
 *
 * Parameters are from react-router (onEnter prop)
 *
 * @param nextState
 * @param replace
 * @param callback
 * @returns callback
 */
function requireAuth (nextState, replace, callback) {
    // if there is a valid JWT in the localStorage, continue
    let jwt = localStorage.getItem(constants.jwtName);
    if(jwt) {
        try {
            jwtDecode(jwt);
            return callback();
        } catch (e) {
            console.log('JWT Decode error:', e);
            localStorage.removeItem(constants.jwtName);
            replace('/');
            return callback();
        }
    }
    else {
        replace('/');
    }
}
<commit_msg>Disable soundmanager debug in console<commit_after>import React from "react";
import ReactDOM from "react-dom";

// Sails lib
var socketIOClient = require('socket.io-client');
var sailsIOClient = require('sails.io.js');
window.io = sailsIOClient(socketIOClient);
io.sails.autoConnect = false;

// TapEvent
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();

// material ui
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import themeConfiguration from './config/theme';
const muiTheme = getMuiTheme(themeConfiguration);

// Configure sound manager
soundManager.setup({debugMode: false});

// Router
import router from './router';
import { RouterProvider } from 'react-router5';

// Pages
import App from "./components/App.jsx";

// constants
import * as constants from './config/constants';

import jwtDecode from 'jwt-decode';

// actions and services
import WebSocketService from './services/WebSocketService';

// Connect to websocket server
WebSocketService.connect();

// Render the app using router
ReactDOM.render(
    <MuiThemeProvider muiTheme={muiTheme}>
        <RouterProvider router={ router }>
            <App />
        </RouterProvider>
    </MuiThemeProvider>,
    document.getElementById('app')
);

/**
 * Check if the user is authenticated
 * used to protect some routes
 *
 * Parameters are from react-router (onEnter prop)
 *
 * @param nextState
 * @param replace
 * @param callback
 * @returns callback
 */
function requireAuth (nextState, replace, callback) {
    // if there is a valid JWT in the localStorage, continue
    let jwt = localStorage.getItem(constants.jwtName);
    if(jwt) {
        try {
            jwtDecode(jwt);
            return callback();
        } catch (e) {
            console.log('JWT Decode error:', e);
            localStorage.removeItem(constants.jwtName);
            replace('/');
            return callback();
        }
    }
    else {
        replace('/');
    }
}
<|endoftext|>


<commit_before>import utils from './utils';

class CreditCardSpace {
  constructor(element) {
    if (!(element instanceof Element)) {
      throw new Error('CreditCardSpace can be attached to an Element only');
    }
    this.element = element;
    attachEvents(element);
  }

  value() {
    return utils.clearFormattedCardNumber(this.element.value);
  }

  destroy() {
    this.element.removeEventListener(inputHandler);
    this.element.removeEventListener(keyDownHandler);
  }
}

function attachEvents(element) {
  element.addEventListener('input', inputHandler);
  element.addEventListener('keydown', keyDownHandler);
}

function inputHandler(event) {
  utils.formatInputValue(event.target);
}

function keyDownHandler(event) {
  let position = utils.getCursorPosition(event.target);
  if (event.keyCode === 46 && event.target.value.charAt(position) === ' ') { // delete
    position += 1;
    utils.setCursorPosition(event.target, position);
  } else if (event.keyCode === 8 && event.target.value.charAt(position - 1) === ' ') { // backspace
    position -= 1;
    utils.setCursorPosition(event.target, position);
  } else if (event.keyCode === 90 && (event.ctrlKey || event.metaKey)) { // ctrl/cmd Z
    event.preventDefault();
    event.stopPropagation();
  }
}

export default CreditCardSpace;
<commit_msg>fix(input): fix cursor position on android<commit_after>import utils from './utils';

class CreditCardSpace {
  constructor(element) {
    if (!(element instanceof Element)) {
      throw new Error('CreditCardSpace can be attached to an Element only');
    }
    this.element = element;
    attachEvents(element);
  }

  value() {
    return utils.clearFormattedCardNumber(this.element.value);
  }

  destroy() {
    this.element.removeEventListener(inputHandler);
    this.element.removeEventListener(keyDownHandler);
  }
}

function attachEvents(element) {
  element.addEventListener('input', (event) => {
    setTimeout(
      () => inputHandler(event)
    );
  });
  element.addEventListener('keydown', keyDownHandler);
}

function inputHandler(event) {
  utils.formatInputValue(event.target);
}

function keyDownHandler(event) {
  let position = utils.getCursorPosition(event.target);
  if (event.keyCode === 46 && event.target.value.charAt(position) === ' ') { // delete
    position += 1;
    utils.setCursorPosition(event.target, position);
  } else if (event.keyCode === 8 && event.target.value.charAt(position - 1) === ' ') { // backspace
    position -= 1;
    utils.setCursorPosition(event.target, position);
  } else if (event.keyCode === 90 && (event.ctrlKey || event.metaKey)) { // ctrl/cmd Z
    event.preventDefault();
    event.stopPropagation();
  }
}

export default CreditCardSpace;
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import App from './containers/App';
import './index.css';

const spreadsheetId = window.location.hash.substring(1) || '1akhbqFlElr0iKnKmK0ZTQeNTBgvNgZVghEpDR9_MDvY';
ReactDOM.render(
  <App
    refreshInterval={ 60 * 60 * 1000 }
    spreadsheetId={ spreadsheetId }
  />,
  document.getElementById('root')
);
<commit_msg>Replace current url if spreadsheet ID is missing<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import App from './containers/App';
import './index.css';

let spreadsheetId = window.location.hash.substring(1);
if (!spreadsheetId) {
  spreadsheetId = '1akhbqFlElr0iKnKmK0ZTQeNTBgvNgZVghEpDR9_MDvY';
  window.location.replace(`./#${spreadsheetId}`);
}

ReactDOM.render(
  <App
    refreshInterval={ 60 * 60 * 1000 }
    spreadsheetId={ spreadsheetId }
  />,
  document.getElementById('root')
);
<|endoftext|>


<commit_before>import path from 'path';
import os from 'os';
import mkdirp from 'mkdirp';
import md5 from 'md5';
import randomPort from 'random-port';
import { EasyZip } from 'easy-zip';
import rimraf from 'rimraf';
import magic from './whiten';

export default function whiten(modules, registry, cb) {
    if (!registry || typeof registry !== 'string') {
        cb = typeof registry === 'function' ? registry : undefined;
        registry = "npm";
    }
    let tempDir = path.join(os.tmpdir(), "whiten-" + md5(new Date().toString()));
    console.log("Downloading to " + tempDir);
    let storageDir = path.join(tempDir, "storage");
    mkdirp.sync(storageDir);
    mkdirp.sync(path.join(tempDir, "temp"));
    randomPort(port => {
        magic(registry, modules, tempDir, port, (err, stdout, stderr) => {
            if (err) {
                console.err(err);
            } else {
                rimraf.sync(path.join(storageDir, '.sinopia-db.json'));
                let zip = new EasyZip();
                zip.zipFolder(storageDir, () => {
                    cb(zip);
                    rimraf(tempDir, (error) => {
                        if (error) {
                            console.error(error);
                        }
                    });
                });
            }
        });
    });
}
<commit_msg>create a directory for atom packages<commit_after>import path from 'path';
import os from 'os';
import mkdirp from 'mkdirp';
import md5 from 'md5';
import randomPort from 'random-port';
import { EasyZip } from 'easy-zip';
import rimraf from 'rimraf';
import magic from './whiten';

export default function whiten(modules, registry, cb) {
    if (!registry || typeof registry !== 'string') {
        cb = typeof registry === 'function' ? registry : undefined;
        registry = "npm";
    }
    let tempDir = path.join(os.tmpdir(), "whiten-" + md5(new Date().toString()));
    console.log("Downloading to " + tempDir);
    let storageDir = path.join(tempDir, "storage");
    mkdirp.sync(storageDir);
    mkdirp.sync(path.join(tempDir, "temp"));
    if (registry === "apm") {
        mkdirp.sync(path.join(tempDir, "atom"));
    }
    randomPort(port => {
        magic(registry, modules, tempDir, port, (err, stdout, stderr) => {
            if (err) {
                console.err(err);
            } else {
                rimraf.sync(path.join(storageDir, '.sinopia-db.json'));
                let zip = new EasyZip();
                zip.zipFolder(storageDir, () => {
                    cb(zip);
                    rimraf(tempDir, (error) => {
                        if (error) {
                            console.error(error);
                        }
                    });
                });
            }
        });
    });
}
<|endoftext|>


<commit_before>// import polyfills first
import './polyfill';

// Mixin the deprecations
import './deprecation';

// export lib
import * as accessibility from './accessibility';
import * as extract from './extract';
import * as extras from './extras';
import * as filters from './filters';
import * as interaction from './interaction';
import * as loaders from './loaders';
import * as mesh from './mesh';
import * as particles from './particles';
import * as prepare from './prepare';

export * from './core';
export {
    accessibility,
    extract,
    extras,
    filters,
    interaction,
    loaders,
    mesh,
    particles,
    prepare,
};

/**
 * A premade instance of the loader that can be used to loader resources.
 *
 * @name loader
 * @memberof PIXI
 * @property {PIXI.loaders.Loader}
 */
const loader = new loaders.Loader();

export { loader };

// Always export pixi globally.
global.PIXI = exports; // eslint-disable-line
<commit_msg>use `export *` syntax for deprecation so it runs first<commit_after>// import polyfills
import './polyfill';

// export core
export * from './deprecation';
export * from './core';

// export libs
import * as accessibility from './accessibility';
import * as extract from './extract';
import * as extras from './extras';
import * as filters from './filters';
import * as interaction from './interaction';
import * as loaders from './loaders';
import * as mesh from './mesh';
import * as particles from './particles';
import * as prepare from './prepare';

export {
    accessibility,
    extract,
    extras,
    filters,
    interaction,
    loaders,
    mesh,
    particles,
    prepare,
};

/**
 * A premade instance of the loader that can be used to loader resources.
 *
 * @name loader
 * @memberof PIXI
 * @property {PIXI.loaders.Loader}
 */
const loader = new loaders.Loader();

export { loader };

// Always export pixi globally.
global.PIXI = exports; // eslint-disable-line
<|endoftext|>


<commit_before>/* jshint node:true */
'use strict';

var fs = require('fs');
var path = require('path');
var cheerio = require('cheerio');
var glob = require('glob');
var gutil = require('gulp-util');
var through = require('through2');
var extend = require('lodash.assign');
var PluginError = gutil.PluginError;

module.exports = function(options) {
  options = extend({trim: true}, options);

  function transform(file, encoding, next) {

    if (file.isNull()) {
      return next(null, file); // pass along
    }

    var $ = cheerio.load(file.contents.toString('utf8'), {decodeEntities: false});

    // This function receives an ng-include src and tries to read it from the filesystem
    function readSource(src) {
      var cwd = path.dirname(file.path);
      if (options.assetsDirs && options.assetsDirs.length) {
        var basename = path.basename(cwd);
        if (options.assetsDirs.indexOf(basename) === -1) {
          options.assetsDirs.unshift(path.basename(cwd));
        }
        src = path.join(options.assetsDirs.length > 1 ? '{' + options.assetsDirs.join(',') + '}' : options.assetsDirs[0], src);
        cwd = path.dirname(cwd);
      }
      var match = glob.sync(src, {cwd: cwd});
      if (!match.length) return next(new PluginError('gulp-nginclude', 'File "' + src + '" not found'));
      return fs.readFileSync(path.join(cwd, match[0])).toString();
    }

    function processTag(i, ng) {
      var $ng = $(ng);
      var src = $ng.attr('src') || $ng.attr('ng-include');
      if (!src.match(/^'[^']+'$/g)) {
        return false;
      }

      // Remove old ng-include attributes so Angular doesn't read them
      $ng.removeAttr('src').removeAttr('ng-include');

      var before = '\n<!-- ngInclude: ' + src + ' -->\n';
      var after = '\n<!--/ngInclude: ' + src + ' -->\n';
      var include = readSource(src.substr(1, src.length - 2));
      if (options.trim && include) {
        include = include.trim();
      }
      $ng.html(before + include + after);
      return true;
    }

    // Use while to make the task recursive
    while (true) {
      var tags = $('ng-include, [ng-include]');

      // If we don't find any more ng-include tags, we're done
      if (tags.length === 0) {
        file.contents = new Buffer($.html());
        return next(null, file);
      }

      // For each tag, grab the associated source file and sub it in
      var results = [];
      /* jshint validthis:true*/
      tags.each(function() {
        results.push(processTag.apply(null, arguments));
      });

      // If we don't find any more suitable ng-include tags
      if (results.filter(Boolean).length === 0) {
        file.contents = new Buffer($.html());
        return next(null, file);
      }

    }

  }

  return through.obj(transform);

};
<commit_msg>fix(match): check for src before testing regex match<commit_after>/* jshint node:true */
'use strict';

var fs = require('fs');
var path = require('path');
var cheerio = require('cheerio');
var glob = require('glob');
var gutil = require('gulp-util');
var through = require('through2');
var extend = require('lodash.assign');
var PluginError = gutil.PluginError;

module.exports = function(options) {
  options = extend({trim: true}, options);

  function transform(file, encoding, next) {

    if (file.isNull()) {
      return next(null, file); // pass along
    }

    var $ = cheerio.load(file.contents.toString('utf8'), {decodeEntities: false});

    // This function receives an ng-include src and tries to read it from the filesystem
    function readSource(src) {
      var cwd = path.dirname(file.path);
      if (options.assetsDirs && options.assetsDirs.length) {
        var basename = path.basename(cwd);
        if (options.assetsDirs.indexOf(basename) === -1) {
          options.assetsDirs.unshift(path.basename(cwd));
        }
        src = path.join(options.assetsDirs.length > 1 ? '{' + options.assetsDirs.join(',') + '}' : options.assetsDirs[0], src);
        cwd = path.dirname(cwd);
      }
      var match = glob.sync(src, {cwd: cwd});
      if (!match.length) return next(new PluginError('gulp-nginclude', 'File "' + src + '" not found'));
      return fs.readFileSync(path.join(cwd, match[0])).toString();
    }

    function processTag(i, ng) {
      var $ng = $(ng);
      var src = $ng.attr('src') || $ng.attr('ng-include');
      if (!src || !src.match(/^'[^']+'$/g)) {
        return false;
      }

      // Remove old ng-include attributes so Angular doesn't read them
      $ng.removeAttr('src').removeAttr('ng-include');

      var before = '\n<!-- ngInclude: ' + src + ' -->\n';
      var after = '\n<!--/ngInclude: ' + src + ' -->\n';
      var include = readSource(src.substr(1, src.length - 2));
      if (options.trim && include) {
        include = include.trim();
      }
      $ng.html(before + include + after);
      return true;
    }

    // Use while to make the task recursive
    while (true) {
      var tags = $('ng-include, [ng-include]');

      // If we don't find any more ng-include tags, we're done
      if (tags.length === 0) {
        file.contents = new Buffer($.html());
        return next(null, file);
      }

      // For each tag, grab the associated source file and sub it in
      var results = [];
      /* jshint validthis:true*/
      tags.each(function() {
        results.push(processTag.apply(null, arguments));
      });

      // If we don't find any more suitable ng-include tags
      if (results.filter(Boolean).length === 0) {
        file.contents = new Buffer($.html());
        return next(null, file);
      }

    }

  }

  return through.obj(transform);

};
<|endoftext|>


<commit_before>import 'core-js/shim';
import yosay from 'yosay';
import mkdirp from 'mkdirp';

import { Base } from 'yeoman-generator';

export default class CraftsmanGenerator extends Base {
  constructor(...args) {
    super(...args);

    this.pkg = require('../package.json');

    this.sourceRoot(`${__dirname}/../templates`);

    // Configure Lodash templating so it ignores interpolation markers in
    // ES6 template strings.
    this._.templateSettings.interpolate = /<%=([\s\S]+?)%>/g;

    const done = this.async();

    this.log(yosay('You\'re using the fantastic Craft generator.'));
  }

  get prompting() {
    return {
      slug() {
        let done = this.async();

        let prompt = [
          {
            type: 'input',
            name: 'slug',
            messag: 'Enter example unique slug for this project',
          },
        ];

        this.prompt(prompt, ( { slug } ) => {
          this.slug = slug;
          done();
        });
      },

      remoteDev() {
        let done = this.async();

        let prompt = [
          {
            type: 'input',
            name: 'dev',
            message: 'Enter the hostname of the dokku development server',
            default: 'dev.example.com',
          },
        ];

        this.prompt(prompt, ( { dev } ) => {
          this.remoteDev = dev;
          done();
        });
      },

      remoteStaging() {
        let done = this.async();

        let prompt = [
          {
            type: 'input',
            name: 'staging',
            message: 'Enter the hostname of the dokku staging server',
            default: 'staging.example.com',
          },
        ];

        this.prompt(prompt, ( { staging } ) => {
          this.remoteStaging = staging;
          done();
        });
      },

      remoteProduction() {
        let done = this.async();

        let prompt = [
          {
            type: 'input',
            name: 'production',
            message: ' the hostname of the dokku production server',
            defaults: 'craft.mydokkuhost.com',
          },
        ];

        this.prompt(prompt, ( { production } ) => {
          this.remoteProduction = production;
          done();
        });
      },

      features() {
        let done = this.async();

        let prompt = [
          {
            type: 'checkbox',
            name: 'features',
            message: 'What else would you like?',

            choices: [
              {
                name: 'inuit.css',
                value: 'includeInuit',
                checked: true,
              }, {
                name: 'jQuery',
                value: 'includejQuery',
                checked: true,
              },
            ]
          },
        ];

        this.prompt(prompt, ( { features } ) => {
          function hasFeature(feature) {
            return features.indexOf(feature) !== -1;
          }

          this.includeInuit = hasFeature('includeInuit');
          this.includejQuery = hasFeature('includejQuery');

          done();
        });
      },
    };
  }

  app() {
    mkdirp('app');
    mkdirp('app/images');
    this.write('app/images/.gitkeep', '');
  }

  styles() {
    if (!this.includeInuit) {
      mkdirp('app/styles');
      this.copy('main.scss', 'app/styles/main.scss');
    } else {
      this.directory('styles', 'app/styles');
    }
  }

  scripts() {
    mkdirp('app/scripts');
    this.write('app/scripts/main.js', 'console.log(\'\\\'Allo \\\'Allo!\');');
  }

  bower() {
    this.copy('bowerrc', '.bowerrc');
    this.copy('_bower.json', 'bower.json');
  }

  gulp() {
    this.copy('gulpfile.babel.js', 'gulpfile.babel.js');
  }

  git() {
    this.copy('gitignore', '.gitignore');
    this.copy('gitattributes', '.gitattributes');
  }

  package() {
    this.copy('_package.json', 'package.json');
  }

  composer() {
    this.copy('_composer.json', 'composer.json');
    this.copy('_composer.lock', 'composer.lock');
  }

  extras() {
    this.copy('favicon.ico', 'app/favicon.ico');
    this.copy('robots.txt', 'app/robots.txt');

    this.copy('editorconfig', '.editorconfig');
    this.copy('eslintrc', '.eslintrc');
    this.copy('env', '.env');
    this.copy('CHECKS', 'CHECKS');
    this.copy('_env.json', 'env.json');
    this.copy('Procfile', 'Procfile');
  }

  vagrant() {
    this.copy('Vagrantfile', 'Vagrantfile');
  }

  puppet() {
    this.directory('puppet', 'puppet');
  }

  craft() {
    mkdirp('public');
    mkdirp('public/assets');
    this.write('public/assets/.gitkeep', '');

    this.copy('index.php', 'public/index.php');
    this.copy('htaccess', 'public/.htaccess');

    mkdirp('craft');
    this.directory('craft', 'craft');
  }

  templates() {
    this.directory('templates', 'app/templates');
  }

  install() {
    this.installDependencies();
  }
}<commit_msg>fix: typo in message param<commit_after>import 'core-js/shim';
import yosay from 'yosay';
import mkdirp from 'mkdirp';

import { Base } from 'yeoman-generator';

export default class CraftsmanGenerator extends Base {
  constructor(...args) {
    super(...args);

    this.pkg = require('../package.json');

    this.sourceRoot(`${__dirname}/../templates`);

    // Configure Lodash templating so it ignores interpolation markers in
    // ES6 template strings.
    this._.templateSettings.interpolate = /<%=([\s\S]+?)%>/g;

    const done = this.async();

    this.log(yosay('You\'re using the fantastic Craft generator.'));
  }

  get prompting() {
    return {
      slug() {
        let done = this.async();

        let prompt = [
          {
            type: 'input',
            name: 'slug',
            message: 'Enter example unique slug for this project',
          },
        ];

        this.prompt(prompt, ( { slug } ) => {
          this.slug = slug;
          done();
        });
      },

      remoteDev() {
        let done = this.async();

        let prompt = [
          {
            type: 'input',
            name: 'dev',
            message: 'Enter the hostname of the dokku development server',
            default: 'dev.example.com',
          },
        ];

        this.prompt(prompt, ( { dev } ) => {
          this.remoteDev = dev;
          done();
        });
      },

      remoteStaging() {
        let done = this.async();

        let prompt = [
          {
            type: 'input',
            name: 'staging',
            message: 'Enter the hostname of the dokku staging server',
            default: 'staging.example.com',
          },
        ];

        this.prompt(prompt, ( { staging } ) => {
          this.remoteStaging = staging;
          done();
        });
      },

      remoteProduction() {
        let done = this.async();

        let prompt = [
          {
            type: 'input',
            name: 'production',
            message: ' the hostname of the dokku production server',
            defaults: 'craft.mydokkuhost.com',
          },
        ];

        this.prompt(prompt, ( { production } ) => {
          this.remoteProduction = production;
          done();
        });
      },

      features() {
        let done = this.async();

        let prompt = [
          {
            type: 'checkbox',
            name: 'features',
            message: 'What else would you like?',

            choices: [
              {
                name: 'inuit.css',
                value: 'includeInuit',
                checked: true,
              }, {
                name: 'jQuery',
                value: 'includejQuery',
                checked: true,
              },
            ]
          },
        ];

        this.prompt(prompt, ( { features } ) => {
          function hasFeature(feature) {
            return features.indexOf(feature) !== -1;
          }

          this.includeInuit = hasFeature('includeInuit');
          this.includejQuery = hasFeature('includejQuery');

          done();
        });
      },
    };
  }

  app() {
    mkdirp('app');
    mkdirp('app/images');
    this.write('app/images/.gitkeep', '');
  }

  styles() {
    if (!this.includeInuit) {
      mkdirp('app/styles');
      this.copy('main.scss', 'app/styles/main.scss');
    } else {
      this.directory('styles', 'app/styles');
    }
  }

  scripts() {
    mkdirp('app/scripts');
    this.write('app/scripts/main.js', 'console.log(\'\\\'Allo \\\'Allo!\');');
  }

  bower() {
    this.copy('bowerrc', '.bowerrc');
    this.copy('_bower.json', 'bower.json');
  }

  gulp() {
    this.copy('gulpfile.babel.js', 'gulpfile.babel.js');
  }

  git() {
    this.copy('gitignore', '.gitignore');
    this.copy('gitattributes', '.gitattributes');
  }

  package() {
    this.copy('_package.json', 'package.json');
  }

  composer() {
    this.copy('_composer.json', 'composer.json');
    this.copy('_composer.lock', 'composer.lock');
  }

  extras() {
    this.copy('favicon.ico', 'app/favicon.ico');
    this.copy('robots.txt', 'app/robots.txt');

    this.copy('editorconfig', '.editorconfig');
    this.copy('eslintrc', '.eslintrc');
    this.copy('env', '.env');
    this.copy('CHECKS', 'CHECKS');
    this.copy('_env.json', 'env.json');
    this.copy('Procfile', 'Procfile');
  }

  vagrant() {
    this.copy('Vagrantfile', 'Vagrantfile');
  }

  puppet() {
    this.directory('puppet', 'puppet');
  }

  craft() {
    mkdirp('public');
    mkdirp('public/assets');
    this.write('public/assets/.gitkeep', '');

    this.copy('index.php', 'public/index.php');
    this.copy('htaccess', 'public/.htaccess');

    mkdirp('craft');
    this.directory('craft', 'craft');
  }

  templates() {
    this.directory('templates', 'app/templates');
  }

  install() {
    this.installDependencies();
  }
}
<|endoftext|>


<commit_before>import axios from 'axios';
import uniqueRandomArray from 'unique-random-array';

var githubInfo = axios.get('https://api.github.com/users').then(function(res) {
  return res.data;
  // this.datas = res.data;
  // this.datas.map(function (val, key) {
  //   names.push(val.login);
  // });
  // this.names = names;
}).catch(function (e) {
  console.log('Error!');
});

module.exports = {
  datas: null,
  names: null,
  getDatas: function () {
    return githubInfo.then(function (datas) {
      return datas;
    });
  },
  getNames: function () {
    return githubInfo.then(function (datas) {
      var names = [];
      datas.map(function (val, key) {
        names.push(val.login);
      });
      return names;
    });
  },
  getRandomAnythings: function (datas) {
    return uniqueRandomArray(datas)();
  }
};
<commit_msg>change axios timeout length<commit_after>import axios from 'axios';
import uniqueRandomArray from 'unique-random-array';

var githubInfo = axios({
  method: 'get',
  url: 'https://api.github.com/users',
  timeout: 5000,
}).then(function(res) {
  return res.data;
  // this.datas = res.data;
  // this.datas.map(function (val, key) {
  //   names.push(val.login);
  // });
  // this.names = names;
}).catch(function (e) {
  console.log('Error!');
});

module.exports = {
  datas: null,
  names: null,
  getDatas: function () {
    return githubInfo.then(function (datas) {
      return datas;
    });
  },
  getNames: function () {
    return githubInfo.then(function (datas) {
      var names = [];
      datas.map(function (val, key) {
        names.push(val.login);
      });
      return names;
    });
  },
  getRandomAnythings: function (datas) {
    return uniqueRandomArray(datas)();
  }
};
<|endoftext|>


<commit_before>import qs from 'querystring'
import _ from 'lodash'
import _fetch from 'isomorphic-fetch'

import _package from '../package.json'

const test = process.env.NODE_ENV === 'test'

const defaultConfig = {
  apiUrl: process.env.BALANC_API || 'https://eddyy.com/v1',
  _ver: _package.version,

  domain: typeof window !== 'undefined' ? window.location.hostname : undefined,
  // domainEmail: String // default from or to
  // domainKey: '', // 'signed key from server',
}
const ctxFields = Object.keys(defaultConfig)

export class Balanc {
  constructor(config) {
    this.conf = defaultConfig
    this.config(config)
  }

  // Exchange Level
  createDeal(body) {
    return this.fetch({method: 'POST', url: 'deal', body})
  }
  markArrive(dealKey, itemKeys) {
    return this.fetch({method: 'POST', url: `deal/${dealKey}/markArrive`, body: {itemKeys}})
  }

  receiptUrl({_key}) {
    const {apiUrl, domain, domainKey} = this.conf
    const filename = `${encodeURIComponent(domain)}/${encodeURIComponent(_key)}.pdf`
    return `${apiUrl}/receipt/${filename}?${qs.stringify(_.pickBy({domainKey, test}))}`
  }

  // Payment Reminder
  getReceivables({from, to}) {
    return this.fetch({url: 'receivable', body: {from, to}})
  }

  billUrl({from, to}) {
    const {apiUrl, domain, domainKey} = this.conf
    const filename = `${encodeURIComponent(domain)}/${encodeURIComponent(from)}/${encodeURIComponent(to)}`
    return `${apiUrl}/bill/${filename}.pdf?${qs.stringify(_.pickBy({domainKey, test}))}`
  }

  // Account Level
  getDeals({from, to}) {
    return this.fetch({url: 'deal', body: {from, to}})
  }

  getAccount({user, account, field}) {
    return this.fetch({url: 'account', body: {user, account, field}})
  }

  accountExcelUrl({user, account, field}) {
    const {apiUrl, domain, domainKey} = this.conf
    let filename = `${encodeURIComponent(domain)}/${encodeURIComponent(user)}/${encodeURIComponent(account)}`
    if (field) {
      filename += `/${encodeURIComponent(field)}`
    }
    return `${apiUrl}/bill/${filename}.xlsx?${qs.stringify(_.pickBy({domainKey, test}))}`
  }

  // util
  config(conf) {
    if (!conf) return this.conf
    _.assign(this.conf, _.pick(conf, ctxFields))
    return this
  }

  mixinConfig(ctx) {
    const method = ctx.method = ctx.method ? ctx.method.toUpperCase() : 'GET'
    const {apiUrl, ...conf} = this.conf
    const body = {
      ...conf,
      ...ctx.body,
    }
    if (method === 'GET') {
      ctx.url = `${apiUrl}/${ctx.url}?${qs.stringify(body)}`
    } else {
      ctx.url = `${apiUrl}/${ctx.url}`
      ctx.body = body
    }
    return ctx
  }

  fetch(ctx) {
    this.mixinConfig(ctx)

    if (ctx.method === 'GET') {
      // delete body
      delete ctx.body
    } else {
      // headers
      ctx.headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'x-ver': ctx.body._ver,
        ...ctx.headers,
      }
      if (test) {
        ctx.headers['x-test'] = test
      }
      delete ctx.body._ver

      // body
      ctx.body = JSON.stringify(ctx.body)
    }

    return _fetch(ctx.url, ctx)
    .then(response => {
      if (response.status >= 200 && response.status < 400) {
        const contentType = response.headers.get('Content-Type')
        return _.startsWith(contentType, 'application/json') ? response.json() : response
      } else {
        var error = new Error(response.statusText)
        error.response = response
        throw error
      }
    })
  }
}

export default new Balanc()
<commit_msg>also post with domainEmail<commit_after>import qs from 'querystring'
import _ from 'lodash'
import _fetch from 'isomorphic-fetch'

import _package from '../package.json'

const test = process.env.NODE_ENV === 'test'

const defaultConfig = {
  apiUrl: process.env.BALANC_API || 'https://eddyy.com/v1',
  _ver: _package.version,

  domain: typeof window !== 'undefined' ? window.location.hostname : undefined,
  domainEmail: '', // default from or to
  // domainKey: '', // 'signed key from server',
}
const ctxFields = Object.keys(defaultConfig)

export class Balanc {
  constructor(config) {
    this.conf = defaultConfig
    this.config(config)
  }

  // Exchange Level
  createDeal(body) {
    return this.fetch({method: 'POST', url: 'deal', body})
  }
  markArrive(dealKey, itemKeys) {
    return this.fetch({method: 'POST', url: `deal/${dealKey}/markArrive`, body: {itemKeys}})
  }

  receiptUrl({_key}) {
    const {apiUrl, domain, domainKey} = this.conf
    const filename = `${encodeURIComponent(domain)}/${encodeURIComponent(_key)}.pdf`
    return `${apiUrl}/receipt/${filename}?${qs.stringify(_.pickBy({domainKey, test}))}`
  }

  // Payment Reminder
  getReceivables({from, to}) {
    return this.fetch({url: 'receivable', body: {from, to}})
  }

  billUrl({from, to}) {
    const {apiUrl, domain, domainKey} = this.conf
    const filename = `${encodeURIComponent(domain)}/${encodeURIComponent(from)}/${encodeURIComponent(to)}`
    return `${apiUrl}/bill/${filename}.pdf?${qs.stringify(_.pickBy({domainKey, test}))}`
  }

  // Account Level
  getDeals({from, to}) {
    return this.fetch({url: 'deal', body: {from, to}})
  }

  getAccount({user, account, field}) {
    return this.fetch({url: 'account', body: {user, account, field}})
  }

  accountExcelUrl({user, account, field}) {
    const {apiUrl, domain, domainKey} = this.conf
    let filename = `${encodeURIComponent(domain)}/${encodeURIComponent(user)}/${encodeURIComponent(account)}`
    if (field) {
      filename += `/${encodeURIComponent(field)}`
    }
    return `${apiUrl}/bill/${filename}.xlsx?${qs.stringify(_.pickBy({domainKey, test}))}`
  }

  // util
  config(conf) {
    if (!conf) return this.conf
    _.assign(this.conf, _.pick(conf, ctxFields))
    return this
  }

  mixinConfig(ctx) {
    const method = ctx.method = ctx.method ? ctx.method.toUpperCase() : 'GET'
    const {apiUrl, ...conf} = this.conf
    const body = {
      ...conf,
      ...ctx.body,
    }
    if (method === 'GET') {
      ctx.url = `${apiUrl}/${ctx.url}?${qs.stringify(body)}`
    } else {
      ctx.url = `${apiUrl}/${ctx.url}`
      ctx.body = body
    }
    return ctx
  }

  fetch(ctx) {
    this.mixinConfig(ctx)

    if (ctx.method === 'GET') {
      // delete body
      delete ctx.body
    } else {
      // headers
      ctx.headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'x-ver': ctx.body._ver,
        ...ctx.headers,
      }
      if (test) {
        ctx.headers['x-test'] = test
      }
      delete ctx.body._ver

      // body
      ctx.body = JSON.stringify(ctx.body)
    }

    return _fetch(ctx.url, ctx)
    .then(response => {
      if (response.status >= 200 && response.status < 400) {
        const contentType = response.headers.get('Content-Type')
        return _.startsWith(contentType, 'application/json') ? response.json() : response
      } else {
        var error = new Error(response.statusText)
        error.response = response
        throw error
      }
    })
  }
}

export default new Balanc()
<|endoftext|>


<commit_before>/* eslint-disable filenames/match-exported */
import path from "path"
import fs from "fs-extra"
import postcss from "postcss"
import postcssImport from "postcss-import"
import postcssSass from "postcss-sass"
import postcssScss from "postcss-scss"
import postcssSmartAsset from "postcss-smart-asset"
import postcssSugarSS from "sugarss"

import { createFilter } from "rollup-pluginutils"
import { getHash } from "asset-hash"

const scriptExtensions = /^\.(json|mjs|js|jsx|es|esx|ts|tsx)$/

const styleParser = {
  ".pcss": null,
  ".css": null,
  ".sss": postcssSugarSS,
  ".scss": postcssScss,
  ".sass": postcssSass
}

function getPostCssPlugins(keepName) {
  return [
    postcssImport(),
    postcssSmartAsset({
      url: "copy",
      useHash: true,
      keepName
    })
  ]
}

/* eslint-disable max-params */
async function processStyle(id, fileDest, keepName) {
  const content = await fs.readFile(id)
  const parser = styleParser[path.extname(id)]
  const processor = postcss(getPostCssPlugins(keepName))
  const text = content.toString()

  const result = await processor.process(text, {
    from: id,
    to: fileDest,
    extensions: Object.keys(styleParser),
    map: { inline: false },

    // Always uses parser... even for scss as we like to offer "normal" CSS in deployed files.
    parser
  })

  await Promise.all([
    fs.outputFile(fileDest, result.css),
    fs.outputFile(`${fileDest}.map`, result.map)
  ])
}

export default function rebase(options = {}) {
  const {
    include,
    exclude,
    verbose = false,
    keepName = false,
    assetFolder = ""
  } = options

  const filter = createFilter(include, exclude)
  const wrappers = {}
  const assets = {}
  const files = {}

  let root = null

  function rootRelative(file) {
    // Last sequence is for Windows support
    return path.relative(root, file).replace("\\", "/")
  }

  return {
    name: "rollup-plugin-rebase",

    /* eslint-disable complexity, max-statements */
    async resolveId(importee, importer) {
      if (!filter(importee)) {
        return null
      }

      // Ignore root files which are typically script files. Delegate to other
      // plugins or default behavior.
      if (!importer) {
        root = path.dirname(path.resolve(importee))
        return null
      }

      // If we process an import request of an already processed asset
      // we deal with it to exclude it from any further bundling through Rollup.
      if (assets[importee] != null) {
        return false
      }

      // We do not process files which do not have a file extensions,
      // cause all assets typically have one. By returning `null` we delegate
      // the resolver to other plugins.
      let fileExt = path.extname(importee)
      if (fileExt === "" || scriptExtensions.test(fileExt)) {
        return null
      }

      // Handle style extension rename - outputting SugarSS is not possible.
      if (fileExt === ".sss") {
        fileExt = ".pcss"
      }

      const fileSource = path.resolve(path.dirname(importer), importee)
      const fileName = path.basename(importee, fileExt)
      const fileHash = await getHash(fileSource)
      const fileTarget = keepName ?
        `${fileName}~${fileHash}${fileExt}` :
        `${fileHash}${fileExt}`

      // Registering for our copying job when the bundle is created (kind of a job queue)
      // and respect any sub folder given by the configuration options.
      files[fileSource] = path.join(assetFolder, fileTarget)

      // Replacing slashes for Windows, as we need to use POSIX style to be compat
      // to Rollup imports / NodeJS resolve implementation.
      const assetId = path
        .join(root, assetFolder, fileTarget)
        .replace(/\\/g, "/")

      // console.log("Importer:", importer)
      // console.log("Asset-ID:", assetId)
      // console.log("Root-Dir:", root)
      const resolvedId = `${assetId}.js`

      // Register asset for exclusion handling in this function.
      // We need the additonal wrapping to be able to not just exclude the file
      // but to combine it with tweaking the import location. This indirection
      // makes this possible as we benefit from having a two-phase resolve.
      assets[assetId] = true

      // Store data for our dynamic wrapper generator in `load()`. This uses the
      // `assetId` to refer to our asset in its virtual new location which is
      // relative to the importer. This is enough to tweak the import statements
      // and make them flat and relative as desired in our output scenario.
      wrappers[resolvedId] = assetId

      return resolvedId
    },

    load(id) {
      if (wrappers[id] != null) {
        // It's not really any loader but kind of a dynamic code generator
        // which is just referring back to the asset we are interested in.
        // This is the magic behind the two-step-resolver and makes it possible
        // to have both: tweaked import references and externals together.
        const importee = wrappers[id]
        // console.log("Load:", importee)
        return `export { default } from "${importee}";`
      }

      return null
    },

    async generateBundle({ file, dir }) {
      const outputFolder = dir || path.dirname(file)

      try {
        // Copy all assets in parallel and waiting for it to complete.
        await Promise.all(
          Object.keys(files).map(async (fileSource) => {
            const fileDest = path.join(outputFolder, files[fileSource])
            const fileExt = path.extname(fileSource)

            // Style related files are processed, not just copied, so that
            // we can handle internal references in CSS as well.
            if (fileExt in styleParser) {
              if (verbose) {
                console.log(`Processing ${rootRelative(fileSource)} => ${rootRelative(fileDest)}...`)
              }

              await processStyle(fileSource, fileDest, keepName)
            } else {
              if (verbose) {
                console.log(`Copying ${rootRelative(fileSource)} => ${rootRelative(fileDest)}...`)
              }

              await fs.copy(fileSource, fileDest)
            }
          })
        )
      } catch (error) {
        throw new Error(`Error while copying files: ${error}`)
      }
    }
  }
}
<commit_msg>Added three new methods to have access to internal data structures.<commit_after>/* eslint-disable filenames/match-exported */
import path from "path"
import fs from "fs-extra"
import postcss from "postcss"
import postcssImport from "postcss-import"
import postcssSass from "postcss-sass"
import postcssScss from "postcss-scss"
import postcssSmartAsset from "postcss-smart-asset"
import postcssSugarSS from "sugarss"

import { createFilter } from "rollup-pluginutils"
import { getHash } from "asset-hash"

const scriptExtensions = /^\.(json|mjs|js|jsx|es|esx|ts|tsx)$/

const styleParser = {
  ".pcss": null,
  ".css": null,
  ".sss": postcssSugarSS,
  ".scss": postcssScss,
  ".sass": postcssSass
}

function getPostCssPlugins(keepName) {
  return [
    postcssImport(),
    postcssSmartAsset({
      url: "copy",
      useHash: true,
      keepName
    })
  ]
}

/* eslint-disable max-params */
async function processStyle(id, fileDest, keepName) {
  const content = await fs.readFile(id)
  const parser = styleParser[path.extname(id)]
  const processor = postcss(getPostCssPlugins(keepName))
  const text = content.toString()

  const result = await processor.process(text, {
    from: id,
    to: fileDest,
    extensions: Object.keys(styleParser),
    map: { inline: false },

    // Always uses parser... even for scss as we like to offer "normal" CSS in deployed files.
    parser
  })

  await Promise.all([
    fs.outputFile(fileDest, result.css),
    fs.outputFile(`${fileDest}.map`, result.map)
  ])
}

export default function rebase(options = {}) {
  const {
    include,
    exclude,
    verbose = false,
    keepName = false,
    assetFolder = ""
  } = options

  const filter = createFilter(include, exclude)
  const wrappers = {}
  const assets = {}
  const files = {}

  let root = null

  function rootRelative(file) {
    // Last sequence is for Windows support
    return path.relative(root, file).replace("\\", "/")
  }

  return {
    name: "rollup-plugin-rebase",

    /** Whether the given ID is a wrapper file generated by this plugin. */
    isRebaseWrapper(wrapperId) {
      return Boolean(wrappers[wrapperId])
    },

    /** Whether the given assetId is an registered asset file */
    isRebaseAsset(assetId) {
      return Boolean(assets[assetId])
    },

    /** Whether the given source is was resolved by this plugin. */
    isRebaseSource(fileSource) {
      return Boolean(files[fileSource])
    },

    /* eslint-disable complexity, max-statements */
    async resolveId(importee, importer) {
      if (!filter(importee)) {
        return null
      }

      // Ignore root files which are typically script files. Delegate to other
      // plugins or default behavior.
      if (!importer) {
        root = path.dirname(path.resolve(importee))
        return null
      }

      // If we process an import request of an already processed asset
      // we deal with it to exclude it from any further bundling through Rollup.
      if (assets[importee] != null) {
        return false
      }

      // We do not process files which do not have a file extensions,
      // cause all assets typically have one. By returning `null` we delegate
      // the resolver to other plugins.
      let fileExt = path.extname(importee)
      if (fileExt === "" || scriptExtensions.test(fileExt)) {
        return null
      }

      // Handle style extension rename - outputting SugarSS is not possible.
      if (fileExt === ".sss") {
        fileExt = ".pcss"
      }

      const fileSource = path.resolve(path.dirname(importer), importee)
      const fileName = path.basename(importee, fileExt)
      const fileHash = await getHash(fileSource)
      const fileTarget = keepName ?
        `${fileName}~${fileHash}${fileExt}` :
        `${fileHash}${fileExt}`

      // Registering for our copying job when the bundle is created (kind of a job queue)
      // and respect any sub folder given by the configuration options.
      files[fileSource] = path.join(assetFolder, fileTarget)

      // Replacing slashes for Windows, as we need to use POSIX style to be compat
      // to Rollup imports / NodeJS resolve implementation.
      const assetId = path
        .join(root, assetFolder, fileTarget)
        .replace(/\\/g, "/")

      // console.log("Importer:", importer)
      // console.log("Asset-ID:", assetId)
      // console.log("Root-Dir:", root)
      const resolvedId = `${assetId}.js`

      // Register asset for exclusion handling in this function.
      // We need the additonal wrapping to be able to not just exclude the file
      // but to combine it with tweaking the import location. This indirection
      // makes this possible as we benefit from having a two-phase resolve.
      assets[assetId] = true

      // Store data for our dynamic wrapper generator in `load()`. This uses the
      // `assetId` to refer to our asset in its virtual new location which is
      // relative to the importer. This is enough to tweak the import statements
      // and make them flat and relative as desired in our output scenario.
      wrappers[resolvedId] = assetId

      return resolvedId
    },

    load(id) {
      if (wrappers[id] != null) {
        // It's not really any loader but kind of a dynamic code generator
        // which is just referring back to the asset we are interested in.
        // This is the magic behind the two-step-resolver and makes it possible
        // to have both: tweaked import references and externals together.
        const importee = wrappers[id]
        // console.log("Load:", importee)
        return `export { default } from "${importee}";`
      }

      return null
    },

    async generateBundle({ file, dir }) {
      const outputFolder = dir || path.dirname(file)

      try {
        // Copy all assets in parallel and waiting for it to complete.
        await Promise.all(
          Object.keys(files).map(async (fileSource) => {
            const fileDest = path.join(outputFolder, files[fileSource])
            const fileExt = path.extname(fileSource)

            // Style related files are processed, not just copied, so that
            // we can handle internal references in CSS as well.
            if (fileExt in styleParser) {
              if (verbose) {
                console.log(`Processing ${rootRelative(fileSource)} => ${rootRelative(fileDest)}...`)
              }

              await processStyle(fileSource, fileDest, keepName)
            } else {
              if (verbose) {
                console.log(`Copying ${rootRelative(fileSource)} => ${rootRelative(fileDest)}...`)
              }

              await fs.copy(fileSource, fileDest)
            }
          })
        )
      } catch (error) {
        throw new Error(`Error while copying files: ${error}`)
      }
    }
  }
}
<|endoftext|>