<commit_before>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * All rights reserved.
 */

var Document = this.Document = Base.extend({
	beans: true,

	initialize: function(canvas) {
		if (canvas && canvas instanceof HTMLCanvasElement) {
			this.canvas = canvas;
			if (canvas.attributes.resize) {
				// If the canvas has a fullscreen attribute,
				// resize the canvas to fill the window and resize it again
				// whenever the user resizes the window.
				// TODO: set the following styles on the body tag:
				// body {
				//	background: black;
				//	margin: 0;
				//	overflow: hidden;
				// }
				this._size = Element.getScrollBounds().size
						.subtract(Element.getOffset(this.canvas));
				this.canvas.width = this._size.width;
				this.canvas.height = this._size.height;
				var that = this;
				Event.add(window, {
					resize: function(event) {
						that.setSize(Element.getScrollBounds().size
								.subtract(Element.getOffset(that.canvas)));
						that.redraw();
					}
				});
			} else {
				this._size = Size.create(canvas.offsetWidth,
						canvas.offsetHeight);
			}
		} else {
			this._size = Size.read(arguments) || new Size(1024, 768);
			this.canvas = CanvasProvider.getCanvas(this._size);
		}
		// TODO: Currently we don't do anything with Document#bounds.
		// What does it mean to change the bounds of the document? (JP)
		this.bounds = Rectangle.create(0, 0, this._size.width,
				this._size.height);
		this.context = this.canvas.getContext('2d');
		Base.splice(paper.documents, [this]);
		this.activate();
		this.layers = [];
		this.activeLayer = new Layer();
		this.setCurrentStyle(null);
		this.symbols = [];
		this.activeView = new DocumentView(this);
		this.views = [this.activeView];
		this._selectedItems = {};
		this._selectedItemCount = 0;
		// TODO: Test this on IE:
		if (this.canvas.attributes.stats) {
			this.stats = new Stats();
			// Align top-left to the canvas
			var element = this.stats.domElement,
				style = element.style,
				offset = Element.getOffset(this.canvas);
			style.position = 'absolute';
			style.left = offset.x + 'px';
			style.top = offset.y + 'px';
			document.body.appendChild(element);
		}
	},

	getSize: function() {
		return this._size;
	},

	setSize: function(size) {
		size = Size.read(arguments);
		if (this.canvas) {
			this.canvas.width = size.width;
			this.canvas.height = size.height;
		}
		this._size = size;
		this.bounds.setSize(size);
	},

	getCurrentStyle: function() {
		return this._currentStyle;
	},

	setCurrentStyle: function(style) {
		this._currentStyle = PathStyle.create(null, style);
	},

	activate: function() {
		// TODO: Remove indexOf()
		var index = paper.documents.indexOf(this);
		if (index != -1) {
			paper.document = this;
			return true;
		}
		return false;
	},

	getSelectedItems: function() {
		// TODO: return groups if their children are all selected,
		// and filter out their children from the list.
		// TODO: the order of these items should be that of their
		// drawing order.
		var items = [];
		Base.each(this._selectedItems, function(item) {
			items.push(item);
		});
		return items;
	},

	// TODO: implement setSelectedItems?

	_selectItem: function(item, select) {
		if (select) {
			this._selectedItemCount++;
			this._selectedItems[item.getId()] = item;
		} else {
			this._selectedItemCount--;
			delete this._selectedItems[item.getId()];
		}
	},

	/**
	 * Selects all items in the document.
	 */
	selectAll: function() {
		// TODO: is using for var i in good practice?
		// or should we use Base.each? (JP)
		for (var i = 0, l = this.layers.length; i < l; i++)
			this.layers[i].setSelected(true);
	},

	/**
	 * Deselects all selected items in the document.
	 */
	deselectAll: function() {
		// TODO: is using for var i in good practice?
		// or should we use Base.each? (JP)
		for (var i in this._selectedItems)
			this._selectedItems[i].setSelected(false);
	},

	draw: function() {
		if (this.canvas) {
			if (this.stats)
				this.stats.update();
			var ctx = this.context;
			ctx.save();

			// TODO: Remove dirty rectangle test code once it's actually
			// implemented.
			var testDirtyRects = false;
			if (testDirtyRects) {
				var left = this.size.width / 8,
					top = this.size.height / 8;

				function clear(rect) {
					ctx.clearRect(rect.x, rect.y, rect.width, rect.height);

					if (true) {
						ctx.moveTo(rect.x, rect.y);
						ctx.lineTo(rect.x + rect.width, rect.y);
						ctx.lineTo(rect.x + rect.width, rect.y + rect.height);
						ctx.lineTo(rect.x, rect.y + rect.height);
					}
				}

				ctx.beginPath();

				clear(Rectangle.create(left, top, 2 * left, 2 * top));
				clear(Rectangle.create(3 * left, 3 * top, 2 * left, 2 * top));

//				clear(Rectangle.create(left, top, 4 * left, 4 * top));

				ctx.closePath();
				ctx.clip();
			} else {
				// Initial tests conclude that clearing the canvas using clearRect
				// is always faster than setting canvas.width = canvas.width
				// http://jsperf.com/clearrect-vs-setting-width/7
				ctx.clearRect(0, 0, this.size.width + 1, this.size.height + 1);
			}

			var param = { offset: new Point(0, 0) };
			for (var i = 0, l = this.layers.length; i < l; i++)
				Item.draw(this.layers[i], ctx, param);
			ctx.restore();

			// Draw the selection of the selected items in the document:
			if (this._selectedItemCount > 0) {
				ctx.save();
				ctx.strokeWidth = 1;
				// TODO: use Layer#color
				ctx.strokeStyle = ctx.fillStyle = '009dec';
				param = { selection: true };
				Base.each(this._selectedItems, function(item) {
					item.draw(ctx, param);
				});
				ctx.restore();
			}
		}
	},

	redraw: function() {
		this.draw();
	}
});
<commit_msg>Document: fix selection drawing in Firefox.<commit_after>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * All rights reserved.
 */

var Document = this.Document = Base.extend({
	beans: true,

	initialize: function(canvas) {
		if (canvas && canvas instanceof HTMLCanvasElement) {
			this.canvas = canvas;
			if (canvas.attributes.resize) {
				// If the canvas has a fullscreen attribute,
				// resize the canvas to fill the window and resize it again
				// whenever the user resizes the window.
				// TODO: set the following styles on the body tag:
				// body {
				//	background: black;
				//	margin: 0;
				//	overflow: hidden;
				// }
				this._size = Element.getScrollBounds().size
						.subtract(Element.getOffset(this.canvas));
				this.canvas.width = this._size.width;
				this.canvas.height = this._size.height;
				var that = this;
				Event.add(window, {
					resize: function(event) {
						that.setSize(Element.getScrollBounds().size
								.subtract(Element.getOffset(that.canvas)));
						that.redraw();
					}
				});
			} else {
				this._size = Size.create(canvas.offsetWidth,
						canvas.offsetHeight);
			}
		} else {
			this._size = Size.read(arguments) || new Size(1024, 768);
			this.canvas = CanvasProvider.getCanvas(this._size);
		}
		// TODO: Currently we don't do anything with Document#bounds.
		// What does it mean to change the bounds of the document? (JP)
		this.bounds = Rectangle.create(0, 0, this._size.width,
				this._size.height);
		this.context = this.canvas.getContext('2d');
		Base.splice(paper.documents, [this]);
		this.activate();
		this.layers = [];
		this.activeLayer = new Layer();
		this.setCurrentStyle(null);
		this.symbols = [];
		this.activeView = new DocumentView(this);
		this.views = [this.activeView];
		this._selectedItems = {};
		this._selectedItemCount = 0;
		// TODO: Test this on IE:
		if (this.canvas.attributes.stats) {
			this.stats = new Stats();
			// Align top-left to the canvas
			var element = this.stats.domElement,
				style = element.style,
				offset = Element.getOffset(this.canvas);
			style.position = 'absolute';
			style.left = offset.x + 'px';
			style.top = offset.y + 'px';
			document.body.appendChild(element);
		}
	},

	getSize: function() {
		return this._size;
	},

	setSize: function(size) {
		size = Size.read(arguments);
		if (this.canvas) {
			this.canvas.width = size.width;
			this.canvas.height = size.height;
		}
		this._size = size;
		this.bounds.setSize(size);
	},

	getCurrentStyle: function() {
		return this._currentStyle;
	},

	setCurrentStyle: function(style) {
		this._currentStyle = PathStyle.create(null, style);
	},

	activate: function() {
		// TODO: Remove indexOf()
		var index = paper.documents.indexOf(this);
		if (index != -1) {
			paper.document = this;
			return true;
		}
		return false;
	},

	getSelectedItems: function() {
		// TODO: return groups if their children are all selected,
		// and filter out their children from the list.
		// TODO: the order of these items should be that of their
		// drawing order.
		var items = [];
		Base.each(this._selectedItems, function(item) {
			items.push(item);
		});
		return items;
	},

	// TODO: implement setSelectedItems?

	_selectItem: function(item, select) {
		if (select) {
			this._selectedItemCount++;
			this._selectedItems[item.getId()] = item;
		} else {
			this._selectedItemCount--;
			delete this._selectedItems[item.getId()];
		}
	},

	/**
	 * Selects all items in the document.
	 */
	selectAll: function() {
		// TODO: is using for var i in good practice?
		// or should we use Base.each? (JP)
		for (var i = 0, l = this.layers.length; i < l; i++)
			this.layers[i].setSelected(true);
	},

	/**
	 * Deselects all selected items in the document.
	 */
	deselectAll: function() {
		// TODO: is using for var i in good practice?
		// or should we use Base.each? (JP)
		for (var i in this._selectedItems)
			this._selectedItems[i].setSelected(false);
	},

	draw: function() {
		if (this.canvas) {
			if (this.stats)
				this.stats.update();
			var ctx = this.context;
			ctx.save();

			// TODO: Remove dirty rectangle test code once it's actually
			// implemented.
			var testDirtyRects = false;
			if (testDirtyRects) {
				var left = this.size.width / 8,
					top = this.size.height / 8;

				function clear(rect) {
					ctx.clearRect(rect.x, rect.y, rect.width, rect.height);

					if (true) {
						ctx.moveTo(rect.x, rect.y);
						ctx.lineTo(rect.x + rect.width, rect.y);
						ctx.lineTo(rect.x + rect.width, rect.y + rect.height);
						ctx.lineTo(rect.x, rect.y + rect.height);
					}
				}

				ctx.beginPath();

				clear(Rectangle.create(left, top, 2 * left, 2 * top));
				clear(Rectangle.create(3 * left, 3 * top, 2 * left, 2 * top));

//				clear(Rectangle.create(left, top, 4 * left, 4 * top));

				ctx.closePath();
				ctx.clip();
			} else {
				// Initial tests conclude that clearing the canvas using clearRect
				// is always faster than setting canvas.width = canvas.width
				// http://jsperf.com/clearrect-vs-setting-width/7
				ctx.clearRect(0, 0, this.size.width + 1, this.size.height + 1);
			}

			var param = { offset: new Point(0, 0) };
			for (var i = 0, l = this.layers.length; i < l; i++)
				Item.draw(this.layers[i], ctx, param);
			ctx.restore();

			// Draw the selection of the selected items in the document:
			if (this._selectedItemCount > 0) {
				ctx.save();
				ctx.strokeWidth = 1;
				// TODO: use Layer#color
				ctx.strokeStyle = ctx.fillStyle = '#009dec';
				param = { selection: true };
				Base.each(this._selectedItems, function(item) {
					item.draw(ctx, param);
				});
				ctx.restore();
			}
		}
	},

	redraw: function() {
		this.draw();
	}
});
<|endoftext|>


<commit_before>
var dotBox = dotBox || {};
dotBox.ai = dotBox.ai || {};
dotBox.ai.utility = dotBox.ai.utility || {};

(function (namespace) {

    var util = dotBox.utility;
//        itUtil = dotBox.utility.iterators;

    function findCloseableBoxes(gameEngine) {

        var results = [],
            boxIndex,
            boxCount = gameEngine.getBoxCount(),
            lineStates;

        for (boxIndex = 0; boxIndex < boxCount; boxIndex++) {

            if (!gameEngine.isBoxScored(boxIndex)) {

                lineStates = gameEngine.getLineStatesForBox(boxIndex);

                if (lineStates.open.length === 1) {

                    results.push({
                        boxIndex: boxIndex,
                        openLine: lineStates.open[0]
                    });

                }

            }

        }

        return results;

    }

    function boxHasThreeOrMoreOpen(boxIndex, gameEngine) {

        var lineStates;

        lineStates = gameEngine.getLineStatesForBox(boxIndex);

        return lineStates.open.length >= 3;

    }

    function getAllOpenLines(gameEngine) {

        var allOpen = [],
            iterator,
            itAndAddIfOpen;

        itAndAddIfOpen = function (it) {
            var line;

            //noinspection JSHint,JSLint
            while (line = it.next()) {

                if (!gameEngine.isLineConnected(line)) {
                    allOpen.push(line);
                }
            }

        };

        iterator = itUtil.hLineIterator(gameEngine.getDotCountLength(), gameEngine.getDotCountWidth());
        itAndAddIfOpen(iterator);

        iterator = itUtil.vLineIterator(gameEngine.getDotCountLength(), gameEngine.getDotCountWidth());
        itAndAddIfOpen(iterator);

        return allOpen;
    }

    function findNonThirdSideLines(gameEngine) {

        var i,
            allOpen,
            adjacentBoxes,
            line,
            dotL = gameEngine.getDotCountLength(),
            dotW = gameEngine.getDotCountWidth(),
            resultLines = [],
            boxIsWideOpen;

        allOpen = getAllOpenLines(gameEngine);

        boxIsWideOpen = function (bIndex) {
            return boxHasThreeOrMoreOpen(bIndex, gameEngine);
        };

        for (i = 0; i < allOpen.length; i++) {
            line = allOpen[i];
            adjacentBoxes = util.line.getBoxesFromLine(line, dotL, dotW);

            if (adjacentBoxes.every(boxIsWideOpen)) {
                resultLines.push(line);
            }
        }

        return resultLines;

    }

    namespace.findCloseableBoxes = findCloseableBoxes;
    namespace.boxHasThreeOrMoreOpen = boxHasThreeOrMoreOpen;
    namespace.getAllOpenLines = getAllOpenLines;
    namespace.findNonThirdSideLines = findNonThirdSideLines;

}(dotBox.ai.utility));

<commit_msg>Fixed a minor bug.<commit_after>
var dotBox = dotBox || {};
dotBox.ai = dotBox.ai || {};
dotBox.ai.utility = dotBox.ai.utility || {};

(function (namespace) {

    var util = dotBox.utility,
        itUtil = dotBox.utility.iterators;

    function findCloseableBoxes(gameEngine) {

        var results = [],
            boxIndex,
            boxCount = gameEngine.getBoxCount(),
            lineStates;

        for (boxIndex = 0; boxIndex < boxCount; boxIndex++) {

            if (!gameEngine.isBoxScored(boxIndex)) {

                lineStates = gameEngine.getLineStatesForBox(boxIndex);

                if (lineStates.open.length === 1) {

                    results.push({
                        boxIndex: boxIndex,
                        openLine: lineStates.open[0]
                    });

                }

            }

        }

        return results;

    }

    function boxHasThreeOrMoreOpen(boxIndex, gameEngine) {

        var lineStates;

        lineStates = gameEngine.getLineStatesForBox(boxIndex);

        return lineStates.open.length >= 3;

    }

    function getAllOpenLines(gameEngine) {

        var allOpen = [],
            iterator,
            itAndAddIfOpen;

        itAndAddIfOpen = function (it) {
            var line;

            //noinspection JSHint,JSLint
            while (line = it.next()) {

                if (!gameEngine.isLineConnected(line)) {
                    allOpen.push(line);
                }
            }

        };

        iterator = itUtil.hLineIterator(gameEngine.getDotCountLength(), gameEngine.getDotCountWidth());
        itAndAddIfOpen(iterator);

        iterator = itUtil.vLineIterator(gameEngine.getDotCountLength(), gameEngine.getDotCountWidth());
        itAndAddIfOpen(iterator);

        return allOpen;
    }

    function findNonThirdSideLines(gameEngine) {

        var i,
            allOpen,
            adjacentBoxes,
            line,
            dotL = gameEngine.getDotCountLength(),
            dotW = gameEngine.getDotCountWidth(),
            resultLines = [],
            boxIsWideOpen;

        allOpen = getAllOpenLines(gameEngine);

        boxIsWideOpen = function (bIndex) {
            return boxHasThreeOrMoreOpen(bIndex, gameEngine);
        };

        for (i = 0; i < allOpen.length; i++) {
            line = allOpen[i];
            adjacentBoxes = util.line.getBoxesFromLine(line, dotL, dotW);

            if (adjacentBoxes.every(boxIsWideOpen)) {
                resultLines.push(line);
            }
        }

        return resultLines;

    }

    namespace.findCloseableBoxes = findCloseableBoxes;
    namespace.boxHasThreeOrMoreOpen = boxHasThreeOrMoreOpen;
    namespace.getAllOpenLines = getAllOpenLines;
    namespace.findNonThirdSideLines = findNonThirdSideLines;

}(dotBox.ai.utility));

<|endoftext|>


<commit_before>import React from 'react';
import { props, t, skinnable } from '../utils';
import Select from 'react-select';
import find from 'lodash/find';
import cx from 'classnames';
import { warn } from '../utils/log';

const PropTypes = {
  value: t.maybe(t.union([t.Number, t.String, t.Object])),
  valueLink: t.maybe(t.struct({
    value: t.maybe(t.String),
    requestChange: t.Function
  })),
  onChange: t.maybe(t.Function),
  options: t.Array,
  id: t.maybe(t.String),
  className: t.maybe(t.String),
  style: t.maybe(t.Object)
};

@skinnable()
@props(PropTypes, { strict: false })
export default class Dropdown extends React.Component {

  componentDidMount() {
    this.logWarnings();
  }

  logWarnings = () => {
    if (this.props.children) {
      warn('You\'re passing children. Not expected behaviour');
    }
  };

  getValue = () => (
    this.props.valueLink ? this.props.valueLink.value : this.props.value
  );

  valueToOption = (value, options) => {
    if (t.String.is(value) || t.Number.is(value)) {
      return find(options, { value });
    }
    return value;
  };

  getOnChange = () => this.props.valueLink ? this.props.valueLink.requestChange : this.props.onChange;

  _onBlur = () => this.forceUpdate();

  getLocals() {
    const {
      className,
      options,
      valueLink,
      ...props
    } = this.props;

    return {
      ...props,
      options,
      className: cx('dropdown', className),
      value: this.valueToOption(this.getValue(), options),
      onChange: this.getOnChange(),
      onBlur: this._onBlur
    };
  }

  template(locals) {
    return <Select {...locals} />;
  }
}
<commit_msg>now value and valueLink are compliant<commit_after>import React from 'react';
import { props, t, skinnable } from '../utils';
import Select from 'react-select';
import find from 'lodash/find';
import cx from 'classnames';
import { warn } from '../utils/log';

const PropTypes = {
  value: t.maybe(t.union([t.Number, t.String, t.Object])),
  valueLink: t.maybe(t.struct({
    value: t.maybe(t.union([t.Number, t.String, t.Object])),
    requestChange: t.Function
  })),
  onChange: t.maybe(t.Function),
  options: t.Array,
  id: t.maybe(t.String),
  className: t.maybe(t.String),
  style: t.maybe(t.Object)
};

@skinnable()
@props(PropTypes, { strict: false })
export default class Dropdown extends React.Component {

  componentDidMount() {
    this.logWarnings();
  }

  logWarnings = () => {
    if (this.props.children) {
      warn('You\'re passing children. Not expected behaviour');
    }
  };

  getValue = () => (
    this.props.valueLink ? this.props.valueLink.value : this.props.value
  );

  valueToOption = (value, options) => {
    if (t.String.is(value) || t.Number.is(value)) {
      return find(options, { value });
    }
    return value;
  };

  getOnChange = () => this.props.valueLink ? this.props.valueLink.requestChange : this.props.onChange;

  _onBlur = () => this.forceUpdate();

  getLocals() {
    const {
      className,
      options,
      valueLink,
      ...props
    } = this.props;

    return {
      ...props,
      options,
      className: cx('dropdown', className),
      value: this.valueToOption(this.getValue(), options),
      onChange: this.getOnChange(),
      onBlur: this._onBlur
    };
  }

  template(locals) {
    return <Select {...locals} />;
  }
}
<|endoftext|>


<commit_before>import {E, M} from './constants';
import {tableOf, tableLenOf, heightOf, length, lengthsOf, isLeaf} from './accessors';
import {parentise, siblise, nodeCopy, firstSlot, lastSlot} from './internal';
import {Node} from './Node';

/**
 * append/concat to lists together
 *
 * this is an attempt to optimize only one use case
 * not compatible with current code base
 *
 *
 * still need to verify this is worth the perf benefits
 *
 *
 *
 *
 *
 */

/**
 * join to lists together(concat)
 *
 * @param {Node} a
 * @param {Node} b
 * @return {Node}
 */
export function append(a, b) {
	var aTable = a['@@rrb/table'];
	var bTable = b['@@rrb/table'];
	var aTableLen = aTable.length;
	var bTableLen = bTable.length;
	if (aTableLen === 0) return b;
	if (bTableLen === 0) return a;

	var [a2, b2] = __append(a, b);
	var a2Table = a2['@@rrb/table'];
	var b2Table = b2['@@rrb/table'];
	var a2TableLen = a2Table.length;
	var b2TableLen = b2Table.length;

	// Check if both nodes can be crunshed together.
	if (a2TableLen + b2TableLen <= M) {
		if (a2Table.length === 0) return b2;
		if (b2Table.length === 0) return a2;

		// Adjust .table and .lengths
		a2['@@rrb/table'] = a2Table.concat(b2Table);
		if (a2['@@rrb/height'] > 0) {
			var len = length(a2);
			var lengths = lengthsOf(b2);
			for (var i = 0, l = lengths.length; i < l; i++) {
				lengths[i] += len;
			}
			a2['@@rrb/lengths'] = a2['@@rrb/lengths'].concat(lengths);
		}

		return a2;
	}

	if (a2['@@rrb/height'] > 0) {
		var toRemove = calcToRemove(a, b);
		if (toRemove > E) {
			[a2, b2] = shuffle(a2, b2, toRemove);
		}
	}

	return siblise(a2, b2);
}

/**
 * Returns an array of two nodes; right and left. One node _may_ be empty.
 * @param {Node} a
 * @param {Node} b
 * @return {Array<Node>}
 * @private
 */
function __append(a, b) {
	var aHeight = a['@@rrb/height'];
	var bHeight = b['@@rrb/height'];

	if (aHeight == 0 && bHeight == 0) {
		return [a, b];
	}

	if (aHeight !== 1 || bHeight !== 1) {
		if (aHeight === bHeight) {
			a = nodeCopy(a);
			b = nodeCopy(b);
			var _  = __append(lastSlot(a), firstSlot(b));
			var a0 = _[0];
			var b0 = _[1];

				insertRight(a, b0);
			insertLeft(b, a0);

		} else if (aHeight > bHeight) {
			a = nodeCopy(a);
			var _ = __append(lastSlot(a), b);
			var a0 = _[0];
			var b0 = _[1];

			insertRight(a, a0);
			b = parentise(b0, b0['@@rrb/height'] + 1);
		} else {
			b = nodeCopy(b);
			var _ = __append(a, firstSlot(b));

			var left = tableLenOf(_[0]) === 0 ? 0 : 1;
			var right = left === 0 ? 1 : 0;
			insertLeft(b, _[left]);
			a = parentise(_[right], _[right]['@@rrb/height'] + 1);
		}
	}

	// Check if balancing is needed and return based on that.
	if (tableLenOf(a) === 0 || tableLenOf(b) === 0) {
		return [a, b];
	}

	var toRemove = calcToRemove(a, b);
	if (toRemove <= E) {
		return [a, b];
	}
	return shuffle(a, b, toRemove);
}

// Helperfunctions for __append. Replaces a child node at the side of the parent.
function insertRight(parent, node) {
	var index = tableLenOf(parent) - 1;
	tableOf(parent)[index] = node;
	lengthsOf(parent)[index] = length(node) + (index > 0 ? lengthsOf(parent)[index - 1] : 0);
}

function insertLeft(parent, node) {
	var lengths = lengthsOf(parent);
	var table = tableOf(parent);

	if (tableLenOf(node) > 0) {
		table[0] = node;
		lengths[0] = length(node);

		var len = length(table[0]);
		for (var i = 1, l = lengths.length; l > i; i++) {
			lengths[i] = len = (len += length(table[i]));
		}

	} else {
		table.shift();
		for (var i = 1, l = lengths.length; l > i; i++) {
			lengths[i] = lengths[i] - lengths[0];
		}
		lengths.shift();
	}
}

/**
 * Returns an array of two balanced nodes.
 * @param {Node} a
 * @param {Node} b
 * @param {number} toRemove
 * @return {Array<Node>}
 */
function shuffle(a, b, toRemove) {
	var newA = preSizedNodeOf(heightOf(a), Math.min(M, tableLenOf(a) + tableLenOf(b) - toRemove));
	var newB = preSizedNodeOf(heightOf(a), tableLenOf(newA) - (tableLenOf(a) + tableLenOf(b) - toRemove));

	// Skip the slots with size M. More precise: copy the slot references
	// to the new node
	var read = 0;
	while (tableOf(getEither(tableOf(a), tableOf(a), read)).length % M === 0) {
		setEither(tableOf(newA), tableOf(newB), read, getEither(tableOf(a), tableOf(b), read));
		setEither(lengthsOf(newA), lengthsOf(newB), read, getEither(lengthsOf(a), lengthsOf(b), read));
		read++;
	}

	// Pulling items from left to right, caching in a slot before writing
	// it into the new nodes.
	var write = read;
	var slot = preSizedNodeOf(heightOf(a) - 1, 0);
	var from = 0;

	// If the current slot is still containing data, then there will be at
	// least one more write, so we do not break this loop yet.
	while (read - write - (tableLenOf(slot) > 0 ? 1 : 0) < toRemove) {
		// Find out the max possible items for copying.
		var source = getEither(tableOf(a), tableOf(b), read);
		var to = Math.min(M - tableLenOf(slot), tableLenOf(source));

		// Copy and adjust size table.
		slot['@@rrb/table'] = tableOf(slot).concat(tableOf(source).slice(from, to));
		if (slot['@@rrb/height'] > 0) {
			var lengths = lengthsOf(slot);
			var len = lengths.length;
			for (var i = len; i < len + to - from; i++) {
				lengths[i] = length(tableOf(slot)[i]);
				lengths[i] += (i > 0 ? lengthsOf(slot)[i - 1] : 0);
			}
		}

		from += to;

		// Only proceed to next slots[i] if the current one was
		// fully copied.
		if (tableLenOf(source) <= to) {
			read++;
			from = 0;
		}

		// Only create a new slot if the current one is filled up.
		if (tableLenOf(slot) === M) {
			saveSlot(newA, newB, write, slot);
			slot = preSizedNodeOf(heightOf(a) - 1, 0);
			write++;
		}
	}

	// Cleanup after the loop. Copy the last slot into the new nodes.
	if (tableLenOf(slot) > 0) {
		saveSlot(newA, newB, write, slot);
		write++;
	}

	// Shift the untouched slots to the left
	while (read < tableLenOf(a) + tableLenOf(b)) {
		saveSlot(newA, newB, write, getEither(tableOf(a), tableOf(b), read));
		read++;
		write++;
	}

	return [newA, newB];
}

// Creates a node or leaf with a given length at their arrays for performance.
// Is only used by shuffle.
function preSizedNodeOf(height, length) {
	if (height > 0)
		return new Node(length, new Array(length), new Array(length));

	return new Node(0, new Array(length), void 0);
}

/**
 * helper for setting picking a slot between to nodes
 * @param {Node} aList - a non-leaf node
 * @param {Node} bList - a non-leaf node
 * @param {number} index
 * @param {Node} slot
 */
function saveSlot(aList, bList, index, slot) {
	setEither(tableOf(aList), tableOf(bList), index, slot);

	var isInFirst = (index === 0 || index === lengthsOf(aList).length);
	var len = isInFirst ? 0 : getEither(lengthsOf(aList), lengthsOf(aList), index - 1);

	setEither(lengthsOf(aList), lengthsOf(bList), index, len + length(slot));
}

// getEither, setEither and saveSlot are helpers for accessing elements over two arrays.
function getEither(a, b, i) {
	return i < a.length ? a[i] : b[i - a.length];
}

function setEither(a, b, i, value) {
	if (i < a.length) {
		a[i] = value;
	} else {
		b[i - a.length] = value;
	}
}

/**
 * Returns the extra search steps for E. Refer to the paper.
 *
 * @param {Node} a - a non leaf node
 * @param {Node} b - a non leaf node
 * @return {number}
 */
function calcToRemove(a, b) {
	var aTable = a['@@rrb/table'];
	var bTable = b['@@rrb/table'];
	var subLengths = sumOfLengths(aTable) + sumOfLengths(bTable);

	return (aTable.length + bTable.length) - (Math.floor((subLengths - 1) / M) + 1);
}

function sumOfLengths(table) {
	var sum = 0;
	var len = table.length;
	for (var i = 0; len > i; i++)
		sum += table[i]['@@rrb/table'].length;

	return sum;
}<commit_msg>code refactoring<commit_after>import {E, M} from './constants';
import {tableOf, tableLenOf, heightOf, length, lengthsOf, isLeaf} from './accessors';
import {parentise, siblise, nodeCopy, firstSlot, lastSlot} from './internal';
import {Node} from './Node';

/**
 * append/concat to lists together
 *
 * this is an attempt to optimize only one use case
 * not compatible with current code base
 *
 *
 * still need to verify this is worth the perf benefits
 *
 *
 *
 *
 *
 */

/**
 * join to lists together(concat)
 *
 * @param {Node} a
 * @param {Node} b
 * @return {Node}
 */
export function append(a, b) {
	var aTable = a['@@rrb/table'];
	var bTable = b['@@rrb/table'];
	var aTableLen = aTable.length;
	var bTableLen = bTable.length;

	if (aTableLen === 0) return b;
	if (bTableLen === 0) return a;

	var [a2, b2] = __append(a, b);
	var a2Table = a2['@@rrb/table'];
	var b2Table = b2['@@rrb/table'];
	var a2TableLen = a2Table.length;
	var b2TableLen = b2Table.length;

	// Check if both nodes can be crunshed together.
	if (a2TableLen + b2TableLen <= M) {
		if (a2Table.length === 0) return b2;
		if (b2Table.length === 0) return a2;

		// Adjust .table and .lengths
		a2['@@rrb/table'] = a2Table.concat(b2Table);
		if (a2['@@rrb/height'] > 0) {
			var len = length(a2);
			var lengths = lengthsOf(b2);
			for (var i = 0, l = lengths.length; i < l; i++) {
				lengths[i] += len;
			}
			a2['@@rrb/lengths'] = a2['@@rrb/lengths'].concat(lengths);
		}

		return a2;
	}

	if (a2['@@rrb/height'] > 0) {
		var toRemove = calcToRemove(a, b);
		if (toRemove > E) {
			[a2, b2] = shuffle(a2, b2, toRemove);
		}
	}

	return siblise(a2, b2);
}

/**
 * Returns an array of two nodes; right and left. One node _may_ be empty.
 * @param {Node} a
 * @param {Node} b
 * @return {Array<Node>}
 * @private
 */
function __append(a, b) {
	var aHeight = a['@@rrb/height'];
	var bHeight = b['@@rrb/height'];

	if (aHeight == 0 && bHeight == 0) {
		return [a, b];
	}

	if (aHeight !== 1 || bHeight !== 1) {
		if (aHeight === bHeight) {
			a = nodeCopy(a);
			b = nodeCopy(b);
			var tuple  = __append(lastSlot(a), firstSlot(b));
			var a0 = tuple[0];
			var b0 = tuple[1];

				insertRight(a, b0);
			insertLeft(b, a0);

		} else if (aHeight > bHeight) {
			a = nodeCopy(a);
			var tuple = __append(lastSlot(a), b);
			var a0 = tuple[0];
			var b0 = tuple[1];

			insertRight(a, a0);
			b = parentise(b0, b0['@@rrb/height'] + 1);
		} else {
			b = nodeCopy(b);
			var tuple = __append(a, firstSlot(b));

			var left = tableLenOf(tuple[0]) === 0 ? 0 : 1;
			var right = left === 0 ? 1 : 0;
			insertLeft(b, tuple[left]);
			a = parentise(tuple[right], tuple[right]['@@rrb/height'] + 1);
		}
	}

	// Check if balancing is needed and return based on that.
	if (tableLenOf(a) === 0 || tableLenOf(b) === 0) {
		return [a, b];
	}

	var toRemove = calcToRemove(a, b);
	if (toRemove <= E) {
		return [a, b];
	}
	return shuffle(a, b, toRemove);
}

// Helperfunctions for __append. Replaces a child node at the side of the parent.
function insertRight(parent, node) {
	var index = tableLenOf(parent) - 1;
	tableOf(parent)[index] = node;
	lengthsOf(parent)[index] = length(node) + (index > 0 ? lengthsOf(parent)[index - 1] : 0);
}

function insertLeft(parent, node) {
	var lengths = lengthsOf(parent);
	var table = tableOf(parent);

	if (tableLenOf(node) > 0) {
		table[0] = node;
		lengths[0] = length(node);

		var len = length(table[0]);
		for (var i = 1, l = lengths.length; l > i; i++) {
			lengths[i] = len = (len += length(table[i]));
		}

	} else {
		table.shift();
		for (var i = 1, l = lengths.length; l > i; i++) {
			lengths[i] = lengths[i] - lengths[0];
		}
		lengths.shift();
	}
}

/**
 * Returns an array of two balanced nodes.
 * @param {Node} a
 * @param {Node} b
 * @param {number} toRemove
 * @return {Array<Node>}
 */
function shuffle(a, b, toRemove) {
	var newA = preSizedNodeOf(heightOf(a), Math.min(M, tableLenOf(a) + tableLenOf(b) - toRemove));
	var newB = preSizedNodeOf(heightOf(a), tableLenOf(newA) - (tableLenOf(a) + tableLenOf(b) - toRemove));

	// Skip the slots with size M. More precise: copy the slot references
	// to the new node
	var read = 0;
	while (tableOf(getEither(tableOf(a), tableOf(a), read)).length % M === 0) {
		setEither(tableOf(newA), tableOf(newB), read, getEither(tableOf(a), tableOf(b), read));
		setEither(lengthsOf(newA), lengthsOf(newB), read, getEither(lengthsOf(a), lengthsOf(b), read));
		read++;
	}

	// Pulling items from left to right, caching in a slot before writing
	// it into the new nodes.
	var write = read;
	var slot = preSizedNodeOf(heightOf(a) - 1, 0);
	var from = 0;

	// If the current slot is still containing data, then there will be at
	// least one more write, so we do not break this loop yet.
	while (read - write - (tableLenOf(slot) > 0 ? 1 : 0) < toRemove) {
		// Find out the max possible items for copying.
		var source = getEither(tableOf(a), tableOf(b), read);
		var to = Math.min(M - tableLenOf(slot), tableLenOf(source));

		// Copy and adjust size table.
		slot['@@rrb/table'] = tableOf(slot).concat(tableOf(source).slice(from, to));
		if (slot['@@rrb/height'] > 0) {
			var lengths = lengthsOf(slot);
			var len = lengths.length;
			for (var i = len; i < len + to - from; i++) {
				lengths[i] = length(tableOf(slot)[i]);
				lengths[i] += (i > 0 ? lengthsOf(slot)[i - 1] : 0);
			}
		}

		from += to;

		// Only proceed to next slots[i] if the current one was
		// fully copied.
		if (tableLenOf(source) <= to) {
			read++;
			from = 0;
		}

		// Only create a new slot if the current one is filled up.
		if (tableLenOf(slot) === M) {
			saveSlot(newA, newB, write, slot);
			slot = preSizedNodeOf(heightOf(a) - 1, 0);
			write++;
		}
	}

	// Cleanup after the loop. Copy the last slot into the new nodes.
	if (tableLenOf(slot) > 0) {
		saveSlot(newA, newB, write, slot);
		write++;
	}

	// Shift the untouched slots to the left
	while (read < tableLenOf(a) + tableLenOf(b)) {
		saveSlot(newA, newB, write, getEither(tableOf(a), tableOf(b), read));
		read++;
		write++;
	}

	return [newA, newB];
}

// Creates a node or leaf with a given length at their arrays for performance.
// Is only used by shuffle.
function preSizedNodeOf(height, length) {
	if (height > 0)
		return new Node(length, new Array(length), new Array(length));

	return new Node(0, new Array(length), void 0);
}

/**
 * helper for setting picking a slot between to nodes
 * @param {Node} aList - a non-leaf node
 * @param {Node} bList - a non-leaf node
 * @param {number} index
 * @param {Node} slot
 */
function saveSlot(aList, bList, index, slot) {
	setEither(tableOf(aList), tableOf(bList), index, slot);

	var isInFirst = (index === 0 || index === lengthsOf(aList).length);
	var len = isInFirst ? 0 : getEither(lengthsOf(aList), lengthsOf(aList), index - 1);

	setEither(lengthsOf(aList), lengthsOf(bList), index, len + length(slot));
}

// getEither, setEither and saveSlot are helpers for accessing elements over two arrays.
function getEither(a, b, i) {
	return i < a.length ? a[i] : b[i - a.length];
}

function setEither(a, b, i, value) {
	if (i < a.length) {
		a[i] = value;
	} else {
		b[i - a.length] = value;
	}
}

/**
 * Returns the extra search steps for E. Refer to the paper.
 *
 * @param {Node} a - a non leaf node
 * @param {Node} b - a non leaf node
 * @return {number}
 */
function calcToRemove(a, b) {
	var aTable = a['@@rrb/table'];
	var bTable = b['@@rrb/table'];
	var subLengths = sumOfLengths(aTable) + sumOfLengths(bTable);

	return (aTable.length + bTable.length) - (Math.floor((subLengths - 1) / M) + 1);
}

function sumOfLengths(table) {
	var sum = 0;
	var len = table.length;
	for (var i = 0; len > i; i++)
		sum += table[i]['@@rrb/table'].length;

	return sum;
}<|endoftext|>


<commit_before>/*! handshake - v0.1.0 - 2012-07-11
* https://github.com/stephenbinns/handshake
* Copyright (c) 2012 Stephen Binns; Licensed MIT */

(function(exports, undefined) {
	'use strict';

	// ASSERTIONS
	function isNull(value) {
		return value === null;
	}

	function isUndefined(value) {
		return ofType(typeof(undefined), value);
	}

	function isNotNull(value){
		return !isNull(value);
	}

	function isNotUndefined(value){
		return !isUndefined(value);
	}

	function isNotNullOrUndefined(value){
		return isNotNull(value) && isNotUndefined(value);
	}

	function isEmpty(value){
		return value.hasOwnProperty('length') && value.length === 0;
	}

	function ofType(typeName, value){
		return typeof (value) === typeName;
	}

	// EXCEPTION HELPER
	function expect(operation, message){
		if (operation === false){
			throw new Error(message);
		}
	}

	exports.preconditions = function(value, paramName){
		paramName = paramName  || 'unnamed';

		var api = {
			isNotNullOrUndefined : function(message){
				message = message || 'Argument: ' + paramName + ' may not be null or undefined';
				expect(isNotNullOrUndefined(value), message);
				return api;
			},
			isNotNull : function(message){
				message = message || 'Argument: ' + paramName + ' may not be null';
				expect(isNotNull(value), message);
				return api;
			},
			isNotUndefined : function(message){
				message = message || 'Argument: ' + paramName + ' may not be undefined';
				expect(isNotUndefined(value), message);
				return api;
			},
			isNotEmpty : function(message) {
				message = message || 'Argument: ' + paramName + ' may not be empty';
				expect(isEmpty(value) === false, message);
				return api;
			},
			isString : function(message) {
				message = message || 'Argument: ' + paramName + ' must be a string';
				var string = 'string';
				expect(ofType(typeof(string), value));
				return api;
			},
			isInt : function(message) {
				message = message || 'Argument: ' + paramName + ' must be an int';
				var interger = 1;
				expect(ofType(typeof(interger),value));
				return api;
			},
			isBoolean : function(message) {
				message = message || 'Argument: ' + paramName + ' must be a bool';
				var bool = true;
				expect(ofType(typeof(bool), value));
				return api;
			},
			isArray : function(message) {
				message = message || 'Argument: ' + paramName + ' must be an array';
				var array = [];
				expect(ofType(typeof(array), value) && isNotNull(value)) ;
				return api;
			},
			isTrue : function(message){
				message = message || 'Argument: ' + paramName + ' must be true';
				expect(value === true);
				return api;
			},
			isFalse : function(message){
				message = message || 'Argument: ' + paramName + ' must be false';
				expect(value === false);
				return api;
			}
		};

		return api;
	};

}(typeof exports === 'object' && exports || this));
<commit_msg>updated dist<commit_after>/*! handshake - v0.1.0 - 2012-07-11
* https://github.com/stephenbinns/handshake
* Copyright (c) 2012 Stephen Binns; Licensed MIT */

(function(exports, undefined) {
  'use strict';

  // ASSERTIONS
  function isNull(value) {
    return value === null;
  }

  function isUndefined(value) {
    return ofType(typeof(undefined), value);
  }

  function isNotNull(value){
    return !isNull(value);
  }

  function isNotUndefined(value){
    return !isUndefined(value);
  }

  function isNotNullOrUndefined(value){
    return isNotNull(value) && isNotUndefined(value);
  }

  function isEmpty(value){
    return value.hasOwnProperty('length') && value.length === 0;
  }

  function ofType(typeName, value){
    return typeof (value) === typeName;
  }

  // EXCEPTION HELPER
  function expect(operation, message){
    if (operation === false){
      throw new Error(message);
    }
  }

  exports.preconditions = function(value, paramName){
    paramName = paramName  || 'unnamed';

    var api = {
      isNotNullOrUndefined : function(message){
        message = message || 'Argument: ' + paramName + ' may not be null or undefined';
        expect(isNotNullOrUndefined(value), message);
        return api;
      },
      isNotNull : function(message){
        message = message || 'Argument: ' + paramName + ' may not be null';
        expect(isNotNull(value), message);
        return api;
      },
      isNotUndefined : function(message){
        message = message || 'Argument: ' + paramName + ' may not be undefined';
        expect(isNotUndefined(value), message);
        return api;
      },
      isNotEmpty : function(message) {
        message = message || 'Argument: ' + paramName + ' may not be empty';
        expect(isEmpty(value) === false, message);
        return api;
      },
      isString : function(message) {
        message = message || 'Argument: ' + paramName + ' must be a string';
        var string = 'string';
        expect(ofType(typeof(string), value));
        return api;
      },
      isInt : function(message) {
        message = message || 'Argument: ' + paramName + ' must be an int';
        var interger = 1;
        expect(ofType(typeof(interger),value));
        return api;
      },
      isBoolean : function(message) {
        message = message || 'Argument: ' + paramName + ' must be a bool';
        var bool = true;
        expect(ofType(typeof(bool), value));
        return api;
      },
      isArray : function(message) {
        message = message || 'Argument: ' + paramName + ' must be an array';
        var array = [];
        expect(ofType(typeof(array), value) && isNotNull(value)) ;
        return api;
      },
      isTrue : function(message){
        message = message || 'Argument: ' + paramName + ' must be true';
        expect(value === true);
        return api;
      },
      isFalse : function(message){
        message = message || 'Argument: ' + paramName + ' must be false';
        expect(value === false);
        return api;
      }
    };

    return api;
  };

}(typeof exports === 'object' && exports || this));
<|endoftext|>


<commit_before>
/**
 * @file Require preload configuration option
 */
/*#ifndef(UMD)*/
"use strict";
/*global _gpfRequireConfigureAddOption*/
/*#endif*/

function _gpfRequireConfigurePreload (context, value) {
  _gpfArrayForEach(Object.keys(value), function (name) {
      context.preload[name] = value[name];
  }, this);
}

_gpfRequireConfigureAddOption("preload", _gpfRequireConfigurePreload);
<commit_msg>preload option (#306)<commit_after>
/**
 * @file Require preload configuration option
 * @since 0.2.9
 */
/*#ifndef(UMD)*/
"use strict";
/*global _gpfArrayForEach*/ // Almost like [].forEach (undefined are also enumerated)
/*global _gpfRequireConfigureAddOption*/ // Declare a configuration option
/*#endif*/

function _gpfRequireConfigureCheckPreload (value) {
    if (typeof value !== "object") {
        gpf.Error.invalidRequireConfigureOptionValue();
    }
}

function _gpfRequireConfigurePreload (context, value) {
    _gpfRequireConfigureCheckPreload(value);
    _gpfArrayForEach(Object.keys(value), function (name) {
        context.preload[name] = value[name];
    });
}

_gpfRequireConfigureAddOption("preload", _gpfRequireConfigurePreload);
<|endoftext|>


<commit_before>// window._ = require('lodash');
window.Popper = require('popper.js').default;

/**
 * jQuery and the Bootstrap jQuery plugin
 */
try {
    window.$ = window.jQuery = require('jquery');
    require('bootstrap');
} catch (e) {}

/**
 * Axios HTTP library
 */
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

/**
 * CSRF Token
 */
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}

/**
 * Dropzone
 */
window.Dropzone = require('dropzone');

/**
 * Vue
 */
import Vue from 'vue';
window.Vue = Vue;

/**
 * i18n
 */
import VueI18n from 'vue-i18n';
import fr from '../../lang/fr.json';
const messages = { fr };
const i18n = new VueI18n({ locale: 'fr', messages });

/**
 * Date Filter
 */
import date from './filters/Date.js';
Vue.filter('date', date);

import ItemListStatusButton from './components/ItemListStatusButton.vue';
import ItemListCheckbox from './components/ItemListCheckbox.vue';

/**
 * Lists
 */
import ItemListColumnHeader from './components/ItemListColumnHeader.vue';
import ItemList from './components/ItemList.vue';
import ItemListTree from './components/ItemListTree.vue';
new Vue({
    i18n,
    components: {
        ItemListColumnHeader,
        ItemList,
        ItemListTree,
        ItemListStatusButton,
        ItemListCheckbox,
    },
}).$mount('#app');

/**
 * Alertify
 */
window.alertify = require('alertify.js');

/**
 * Selectize
 */
require('selectize');

/**
 * All files in /reources/assets/js/admin
 */
var req = require.context('../../../resources/assets/js/admin', true, /^(.*\.(js$))[^.]*$/im);
req.keys().forEach(function(key) {
    req(key);
});
<commit_msg>Filepicker import<commit_after>// window._ = require('lodash');
window.Popper = require('popper.js').default;

/**
 * jQuery and the Bootstrap jQuery plugin
 */
try {
    window.$ = window.jQuery = require('jquery');
    require('bootstrap');
} catch (e) {}

/**
 * Axios HTTP library
 */
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

/**
 * CSRF Token
 */
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}

/**
 * Vue
 */
import Vue from 'vue';
window.Vue = Vue;

/**
 * i18n
 */
import VueI18n from 'vue-i18n';
import fr from '../../lang/fr.json';
const messages = { fr };
const i18n = new VueI18n({ locale: 'fr', messages });

/**
 * Date Filter
 */
import date from './filters/Date.js';
Vue.filter('date', date);

import ItemListStatusButton from './components/ItemListStatusButton.vue';
import ItemListCheckbox from './components/ItemListCheckbox.vue';

/**
 * Lists
 */
import ItemListColumnHeader from './components/ItemListColumnHeader.vue';
import ItemList from './components/ItemList.vue';
import ItemListTree from './components/ItemListTree.vue';

/**
 * Filepicker
 */
import Filepicker from './components/Filepicker.vue';

new Vue({
    i18n,
    components: {
        ItemListColumnHeader,
        ItemList,
        ItemListTree,
        ItemListStatusButton,
        ItemListCheckbox,
        Filepicker,
    },
}).$mount('#app');

/**
 * Alertify
 */
window.alertify = require('alertify.js');

/**
 * Selectize
 */
require('selectize');

/**
 * All files in /reources/assets/js/admin
 */
var req = require.context('../../../resources/assets/js/admin', true, /^(.*\.(js$))[^.]*$/im);
req.keys().forEach(function(key) {
    req(key);
});
<|endoftext|>


<commit_before>/*global $, jQuery, alert*/

function highlightAddress(markerId) {
    'use strict';
    // console.log('marker : '+markerId);
    var item = $('#item-' + markerId);
    if (item.length && !item.hasClass('active')) {
        $('.places-list .active').removeClass('active');
        item.addClass('active');
    }
}

var onMarkerClick = function () {
    'use strict';
    highlightAddress(this.id);
    infoWindow.setContent(this.html);
    infoWindow.open(map, this);
};

// Gmaps
if ($('#map').length) {
    var infoWindow = new google.maps.InfoWindow(),
        jsonData = [],
        markers = [],
        markersPoints = [],
        markersPos = [],
        noms = [],
        iterator = 0,
        mapOptions = {
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            center: new google.maps.LatLng(50.85, 4.36),
            mapTypeControl: false,
            streetViewControl: false,
            zoom: 12
        },
        map = new google.maps.Map(document.getElementById('map'), mapOptions);

    google.maps.event.addListener(map, 'click', function () {
        'use strict';
        infoWindow.close();
    });

    var locale = $('html').attr('lang'),
        apiUrl = $('#map').data('url');

    jQuery.getJSON(apiUrl + location.search, function (data) {
        'use strict';
        var i = 0,
            coords = [];
        if (!jQuery.isArray(data)) {
            jsonData = [data];
        } else {
            jsonData = data;
        }
        for (i = 0; i < jsonData.length; i += 1) {
            if (jsonData[i].latitude > 0 && jsonData[i].longitude > 0) {
                markersPos[i] = new google.maps.LatLng(jsonData[i].latitude, jsonData[i].longitude);
                markers[i] = {};
                coords = [];
                markers[i].id = jsonData[i].id;
                markers[i].shape = jsonData[i].shape;
                markers[i].html = '
' + jsonData[i].title[locale] + '
';
                markers[i].html += '
';
                if (jsonData[i].address) { coords.push(jsonData[i].address); }
                if (jsonData[i].phone) { coords.push('T ' + jsonData[i].phone); }
                if (jsonData[i].fax) { coords.push('F ' + jsonData[i].fax); }
                if (jsonData[i].email) { coords.push('' + jsonData[i].email + ''); }
                if (jsonData[i].website) { coords.push('' + data[i].website + ''); }
                markers[i].html += coords.join('
');
                markers[i].html += '
';
            }
        }
        // console.log(markers);
        if (markers.length > 0) {
            drop();
            AutoCenter();
        }
    });

    // Search Postcode
    $('#search-nearest button').click(function () {
        'use strict';

        var address = $('#search-nearest input').val(),
            geocoder;

        if (!address.length) {
            return false;
        }

        geocoder = new google.maps.Geocoder();
        geocoder.geocode(
            {
                address: address
            },
            function (results) {
                if (status == google.maps.GeocoderStatus.OK) {
                    var p = results[0].geometry.location,
                        lat = p.lat(),
                        lng = p.lng();
                    setDistancesForMarkers(lat, lng);
                }
                console.log(status);
            }
        );

        return false;
    });

    // Click on a marker in the list to open the info window on the map.
    $('.places-item-btn-map').on('click', function(){
        var id = $(this).closest('li').attr('id').replace(/item-/gi,'');
        for (var i = markers.length - 1; i >= 0; i--){
            if (markers[i].id == id) {
                var latLng = new google.maps.LatLng(markersPos[i].lat(),markersPos[i].lng());
                map.panTo( latLng );
                map.setZoom(18);
                google.maps.event.trigger(markersPoints[i], 'click');
            };
        };
        return false;
    })

    // Compute distance between two points
    var rad = function (x) {
        'use strict';
        return x * Math.PI / 180;
    };

    function getDistance(p1_lat, p1_lng, p2_lat, p2_lng) {
        'use strict';
        var R = 6378137, // Earth’s mean radius in meter
            dLat = rad(p2_lat - p1_lat),
            dLong = rad(p2_lng - p1_lng),
            a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                Math.cos(rad(p1_lat)) * Math.cos(rad(p2_lat)) *
                Math.sin(dLong / 2) * Math.sin(dLong / 2),
            c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)),
            d = R * c;
        return d; // returns the distance in meter
    }

    // Get the distance between a given point and the markers
    function setDistancesForMarkers(lat, lng) {
        'use strict';
        var i = 0;
        for (i = 0; i < jsonData.length; i += 1) {
            if (jsonData[i].latitude > 0 && jsonData[i].longitude > 0) {
                jsonData[i].distance = getDistance(lat, lng, jsonData[i].latitude, jsonData[i].longitude);
                jsonData.sort(function (a, b) {
                    return parseFloat(a.distance) - parseFloat(b.distance);
                });
            }
        }
        openMarkerId(jsonData[0].id);
    }

}

function addMarker(animation) {
    'use strict';

    // decaler un marker s'il y a déjà un point à la même position
    var dedans = 0,
        i = 0,
        latLng;
    for (i = markers.length - 1; i >= 0; i -= 1) {
        // console.log(markers[iterator].lat());
        if (markersPos[iterator].lat() === markersPos[i].lat() && markersPos[iterator].lng() === markersPos[i].lng()) {
            // markers[i]['html'] += markers[iterator]['html'];
            dedans += 1;
        }
    }
    if (dedans >= 2) {
        // console.log(dedans+' '+iterator);
        // Il y a au moins deux points ayant la même position, alors on décale un des deux
        latLng = new google.maps.LatLng(markersPos[iterator].lat(), markersPos[iterator].lng() + Math.random() / 4000 + 0.00001);
    } else {
        latLng = markersPos[iterator];
    }

    markersPoints[iterator] = new google.maps.Marker({
        // icon: {
        //     url: '/img/marker.png',
        //     size: new google.maps.Size(36, 52),
        //     origin: new google.maps.Point(0, 0),
        //     anchor: new google.maps.Point(18, 48),
        //     scaledSize: new google.maps.Size(36, 52)
        // },
        position: latLng,
        map: map,
        draggable: false,
        animation: animation
    });
    // console.log(markers[iterator]);
    markersPoints[iterator].html = markers[iterator].html;
    markersPoints[iterator].id = markers[iterator].id;
    google.maps.event.addListener(markersPoints[iterator], 'click', onMarkerClick);
    if (markers.length === 1) {
        google.maps.event.trigger(markersPoints[iterator], 'click');
    }
    iterator += 1;
}

function drop() {
    'use strict';
    var i = 0;
    if (markers.length <= 3) {
        for (i = 0; i < markers.length; i += 1) {
            setTimeout(function () {
                addMarker(google.maps.Animation.DROP);
            }, i * 200);
        }
    } else {
        for (i = 0; i < markers.length; i += 1) {
            addMarker(false);
        }
    }
}

function AutoCenter() {
    'use strict';
    var bounds = new google.maps.LatLngBounds(),
        listener;
    $.each(markers, function (index) {
        bounds.extend(markersPos[index]);
    });
    map.fitBounds(bounds);
    listener = google.maps.event.addListener(map, 'idle', function () {
        if (map.getZoom() > 17) {
            map.setZoom(17);
        }
        google.maps.event.removeListener(listener);
    });
}

function openMarkerId(id) {
    'use strict';
    var i = 0,
        latLng;
    // console.log('click : '+id );
    for (i = markers.length - 1; i >= 0; i -= 1) {
        // console.log(markers[i].id );
        if (markers[i].id === id) {
            latLng = new google.maps.LatLng(markersPos[i].lat(), markersPos[i].lng());
            map.panTo(latLng);
            map.setZoom(13);
            google.maps.event.trigger(markersPoints[i], 'click');
        }
    }
    return false;
}
<commit_msg>console log removed<commit_after>/*global $, jQuery, alert*/

function highlightAddress(markerId) {
    'use strict';
    // console.log('marker : '+markerId);
    var item = $('#item-' + markerId);
    if (item.length && !item.hasClass('active')) {
        $('.places-list .active').removeClass('active');
        item.addClass('active');
    }
}

var onMarkerClick = function () {
    'use strict';
    highlightAddress(this.id);
    infoWindow.setContent(this.html);
    infoWindow.open(map, this);
};

// Gmaps
if ($('#map').length) {
    var infoWindow = new google.maps.InfoWindow(),
        jsonData = [],
        markers = [],
        markersPoints = [],
        markersPos = [],
        noms = [],
        iterator = 0,
        mapOptions = {
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            center: new google.maps.LatLng(50.85, 4.36),
            mapTypeControl: false,
            streetViewControl: false,
            zoom: 12
        },
        map = new google.maps.Map(document.getElementById('map'), mapOptions);

    google.maps.event.addListener(map, 'click', function () {
        'use strict';
        infoWindow.close();
    });

    var locale = $('html').attr('lang'),
        apiUrl = $('#map').data('url');

    jQuery.getJSON(apiUrl + location.search, function (data) {
        'use strict';
        var i = 0,
            coords = [];
        if (!jQuery.isArray(data)) {
            jsonData = [data];
        } else {
            jsonData = data;
        }
        for (i = 0; i < jsonData.length; i += 1) {
            if (jsonData[i].latitude > 0 && jsonData[i].longitude > 0) {
                markersPos[i] = new google.maps.LatLng(jsonData[i].latitude, jsonData[i].longitude);
                markers[i] = {};
                coords = [];
                markers[i].id = jsonData[i].id;
                markers[i].shape = jsonData[i].shape;
                markers[i].html = '
' + jsonData[i].title[locale] + '
';
                markers[i].html += '
';
                if (jsonData[i].address) { coords.push(jsonData[i].address); }
                if (jsonData[i].phone) { coords.push('T ' + jsonData[i].phone); }
                if (jsonData[i].fax) { coords.push('F ' + jsonData[i].fax); }
                if (jsonData[i].email) { coords.push('' + jsonData[i].email + ''); }
                if (jsonData[i].website) { coords.push('' + data[i].website + ''); }
                markers[i].html += coords.join('
');
                markers[i].html += '
';
            }
        }
        // console.log(markers);
        if (markers.length > 0) {
            drop();
            AutoCenter();
        }
    });

    // Search Postcode
    $('#search-nearest button').click(function () {
        'use strict';

        var address = $('#search-nearest input').val(),
            geocoder;

        if (!address.length) {
            return false;
        }

        geocoder = new google.maps.Geocoder();
        geocoder.geocode(
            {
                address: address
            },
            function (results) {
                if (status == google.maps.GeocoderStatus.OK) {
                    var p = results[0].geometry.location,
                        lat = p.lat(),
                        lng = p.lng();
                    setDistancesForMarkers(lat, lng);
                }
            }
        );

        return false;
    });

    // Click on a marker in the list to open the info window on the map.
    $('.places-item-btn-map').on('click', function(){
        var id = $(this).closest('li').attr('id').replace(/item-/gi,'');
        for (var i = markers.length - 1; i >= 0; i--){
            if (markers[i].id == id) {
                var latLng = new google.maps.LatLng(markersPos[i].lat(),markersPos[i].lng());
                map.panTo( latLng );
                map.setZoom(18);
                google.maps.event.trigger(markersPoints[i], 'click');
            };
        };
        return false;
    })

    // Compute distance between two points
    var rad = function (x) {
        'use strict';
        return x * Math.PI / 180;
    };

    function getDistance(p1_lat, p1_lng, p2_lat, p2_lng) {
        'use strict';
        var R = 6378137, // Earth’s mean radius in meter
            dLat = rad(p2_lat - p1_lat),
            dLong = rad(p2_lng - p1_lng),
            a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                Math.cos(rad(p1_lat)) * Math.cos(rad(p2_lat)) *
                Math.sin(dLong / 2) * Math.sin(dLong / 2),
            c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)),
            d = R * c;
        return d; // returns the distance in meter
    }

    // Get the distance between a given point and the markers
    function setDistancesForMarkers(lat, lng) {
        'use strict';
        var i = 0;
        for (i = 0; i < jsonData.length; i += 1) {
            if (jsonData[i].latitude > 0 && jsonData[i].longitude > 0) {
                jsonData[i].distance = getDistance(lat, lng, jsonData[i].latitude, jsonData[i].longitude);
                jsonData.sort(function (a, b) {
                    return parseFloat(a.distance) - parseFloat(b.distance);
                });
            }
        }
        openMarkerId(jsonData[0].id);
    }

}

function addMarker(animation) {
    'use strict';

    // decaler un marker s'il y a déjà un point à la même position
    var dedans = 0,
        i = 0,
        latLng;
    for (i = markers.length - 1; i >= 0; i -= 1) {
        // console.log(markers[iterator].lat());
        if (markersPos[iterator].lat() === markersPos[i].lat() && markersPos[iterator].lng() === markersPos[i].lng()) {
            // markers[i]['html'] += markers[iterator]['html'];
            dedans += 1;
        }
    }
    if (dedans >= 2) {
        // console.log(dedans+' '+iterator);
        // Il y a au moins deux points ayant la même position, alors on décale un des deux
        latLng = new google.maps.LatLng(markersPos[iterator].lat(), markersPos[iterator].lng() + Math.random() / 4000 + 0.00001);
    } else {
        latLng = markersPos[iterator];
    }

    markersPoints[iterator] = new google.maps.Marker({
        // icon: {
        //     url: '/img/marker.png',
        //     size: new google.maps.Size(36, 52),
        //     origin: new google.maps.Point(0, 0),
        //     anchor: new google.maps.Point(18, 48),
        //     scaledSize: new google.maps.Size(36, 52)
        // },
        position: latLng,
        map: map,
        draggable: false,
        animation: animation
    });
    // console.log(markers[iterator]);
    markersPoints[iterator].html = markers[iterator].html;
    markersPoints[iterator].id = markers[iterator].id;
    google.maps.event.addListener(markersPoints[iterator], 'click', onMarkerClick);
    if (markers.length === 1) {
        google.maps.event.trigger(markersPoints[iterator], 'click');
    }
    iterator += 1;
}

function drop() {
    'use strict';
    var i = 0;
    if (markers.length <= 3) {
        for (i = 0; i < markers.length; i += 1) {
            setTimeout(function () {
                addMarker(google.maps.Animation.DROP);
            }, i * 200);
        }
    } else {
        for (i = 0; i < markers.length; i += 1) {
            addMarker(false);
        }
    }
}

function AutoCenter() {
    'use strict';
    var bounds = new google.maps.LatLngBounds(),
        listener;
    $.each(markers, function (index) {
        bounds.extend(markersPos[index]);
    });
    map.fitBounds(bounds);
    listener = google.maps.event.addListener(map, 'idle', function () {
        if (map.getZoom() > 17) {
            map.setZoom(17);
        }
        google.maps.event.removeListener(listener);
    });
}

function openMarkerId(id) {
    'use strict';
    var i = 0,
        latLng;
    for (i = markers.length - 1; i >= 0; i -= 1) {
        if (markers[i].id === id) {
            latLng = new google.maps.LatLng(markersPos[i].lat(), markersPos[i].lng());
            map.panTo(latLng);
            map.setZoom(13);
            google.maps.event.trigger(markersPoints[i], 'click');
        }
    }
    return false;
}
<|endoftext|>


<commit_before>var geoip = require('geoip-lite');
var crawler = require('../src/crawler.js')
var normalizeIpp = crawler.normalizeIpp
var normalizePubKey = crawler.normalizePubKey
var _ = require('lodash');

module.exports = {

  /*
  * @param {Object} raw crawl
  * @return {Object} { public_key: {ipp: ipp, version: version} }
  * Takes raw crawl and returns a dictionary of unique rippleds keyed by public
  * key and with the properties ipp and version.
  */
  getRippleds: function(nodes) {
    var rippleds = {};
    _.each(nodes, function(node) {

      // node properties
      var n_ipp = Object.keys(node)[0];
      var n_peers = node[n_ipp].overlay.active;

      _.each(n_peers, function(peer) {

        // peer properties
        var p_v = peer.version;
        var p_pk = normalizePubKey(peer.public_key);
        try {
          var p_ipp = normalizeIpp(peer.ip, peer.port);
        } catch (error) {
          var p_ipp = undefined;
        }

        // Fill in rippled
        var rippled = rippleds[p_pk]
        if (rippled) {
          if(!rippled.ipp)
            rippled.ipp = p_ipp;
          if(!rippled.version)
            rippled.version = p_v;
        } else {
          rippleds[p_pk] = { ipp: p_ipp, version: p_v };
        }

      });
    });
    return rippleds;
  },

  /*
  * @param {Object} raw crawl
  * @return {Object} { public_key: {ipp: ipp, version: version, in: count, out: count} }
  * Takes raw crawl and returns a dictionary of unique rippleds keyed by public
  * key and with the properties ipp, version, in count and out count.
  */
  getRippledsC: function(nodes) {
    var rippleds = this.getRippleds(nodes);
    var degrees = this.getDegrees(nodes);
    _.each(Object.keys(degrees), function(pk) {
      if (rippleds[pk]) {
        rippleds[pk].in = degrees[pk].in;
        rippleds[pk].out = degrees[pk].out;
      }
    });
    return rippleds;
  },

  /*
  * @param {Object} raw crawl
  * @return {Object} { publickey1,publickey2: 1 }
  * Takes raw crawl and returns an object of unique edges
  * edges have in the format "publickey1,publickey2" : 1.
  */
  getLinks: function(nodes) {
    var rippleds = this.getRippleds(nodes);
    // Create ippToPk using rippleds
    var ippToPk = {};
    _.each(Object.keys(rippleds), function(pk) {
      var ipp = rippleds[pk].ipp
      if (ipp)
        ippToPk[ipp] = pk;
    });

    var links = {};
    _.each(nodes, function(node) {

      // node properties
      var n_ipp = Object.keys(node)[0];
      var n_peers = node[n_ipp].overlay.active;

      _.each(n_peers, function(peer) {

        // peer properties
        var p_pk = normalizePubKey(peer.public_key);
        var p_type = peer.type;
        try {
          var p_ipp = normalizeIpp(peer.ip, peer.port);
        } catch (error) {
          var p_ipp = undefined;
        }

        // Make link
        if (p_type) {
          // Get link
          if (p_type == "in") {
            a = ippToPk[n_ipp];
            b = p_pk;
          }
          else if (p_type == "out") {
            a = p_pk;
            b = ippToPk[n_ipp];
          }
          else if (p_type == "peer") {
            if (peer.ip) {
              if (peer.ip.split(":").length == 2) {
                a = ippToPk[n_ipp];
                b = p_pk;
              } else {
                a = p_pk;
                b = ippToPk[n_ipp];
              }
            }
          } else {
            // If type is not in/out/peer
            throw new Error("Peer has unexpected type")
          }

          if (a !== undefined && b !== undefined) {
            if (links[[a,b]] === undefined) {
              links[[a,b]] = 0;
            }
            links[[a,b]] += 1;
          }
        }

      });
    });

    return links;
  },

  /*
  * @param {Object} raw crawl
  * @return {Object} { version: count }
  * Takes a raw crawl and returns a dictionary of versions with their counts.
  */
  getVersions: function(nodes) {
    var rippleds = this.getRippleds(nodes);
    var versions = {};

    _.each(rippleds, function(rippled) {
      if (versions[rippled.version]) {
        versions[rippled.version] += 1;
      } else {
        versions[rippled.version] = 1;
      }
    });
    return versions;
  },

  /*
  * @param {Object} raw crawl
  * @return {Object} { location: count }
  * Takes a raw crawl and returns a dictionary of locations with their counts.
  * Locations are in the format COUNTRY_CITY (note that city might be missing).
  */
  getLocations: function(nodes) {
    var rippleds = this.getRippleds(nodes);
    var locations = {};

    _.each(rippleds, function(rippled) {
      var ipp = rippled.ipp;
      if (ipp) {
        geoloc = geoip.lookup(ipp.split(':')[0]);
        location = geoloc.country + '_' + geoloc.city;
      } else {
        location = undefined;
      }

      if (locations[location])
        locations[location] += 1;
      else
        locations[location] = 1;
    });
    return locations;
  },

  /*
  * @param {Object} raw crawl
  * @return {Object} {public_key: {in: count, out: count}}
  * Takes a raw crawl and returns the
  * in and out degree of each rippled instance.
  */
  getDegrees: function(nodes) {
    var links = this.getLinks(nodes);
    var connections = {};

    _.each(Object.keys(links), function(link) {
      var from = link.split(',')[0];
      var to = link.split(',')[1];

      if (!connections[from]) {
        connections[from] = {in: 0, out: 0};
      }
      connections[from].out += 1;

      if (!connections[to]) {
        connections[to] = {in: 0, out: 0};
      }
      connections[to].in += 1;

    });

    return connections;
  }

}
<commit_msg>fixed link count issuse caused by global a and b variables<commit_after>var geoip = require('geoip-lite');
var crawler = require('../src/crawler.js')
var normalizeIpp = crawler.normalizeIpp
var normalizePubKey = crawler.normalizePubKey
var _ = require('lodash');

module.exports = {

  /*
  * @param {Object} raw crawl
  * @return {Object} { public_key: {ipp: ipp, version: version} }
  * Takes raw crawl and returns a dictionary of unique rippleds keyed by public
  * key and with the properties ipp and version.
  */
  getRippleds: function(nodes) {
    var rippleds = {};
    _.each(nodes, function(node) {

      // node properties
      var n_ipp = Object.keys(node)[0];
      var n_peers = node[n_ipp].overlay.active;

      _.each(n_peers, function(peer) {

        // peer properties
        var p_v = peer.version;
        var p_pk = normalizePubKey(peer.public_key);
        try {
          var p_ipp = normalizeIpp(peer.ip, peer.port);
        } catch (error) {
          var p_ipp = undefined;
        }

        // Fill in rippled
        var rippled = rippleds[p_pk]
        if (rippled) {
          if(!rippled.ipp)
            rippled.ipp = p_ipp;
          if(!rippled.version)
            rippled.version = p_v;
        } else {
          rippleds[p_pk] = { ipp: p_ipp, version: p_v };
        }

      });
    });
    return rippleds;
  },

  /*
  * @param {Object} raw crawl
  * @return {Object} { public_key: {ipp: ipp, version: version, in: count, out: count} }
  * Takes raw crawl and returns a dictionary of unique rippleds keyed by public
  * key and with the properties ipp, version, in count and out count.
  */
  getRippledsC: function(nodes) {
    var rippleds = this.getRippleds(nodes);
    var degrees = this.getDegrees(nodes);
    _.each(Object.keys(degrees), function(pk) {
      if (rippleds[pk]) {
        rippleds[pk].in = degrees[pk].in;
        rippleds[pk].out = degrees[pk].out;
      }
    });
    return rippleds;
  },

  /*
  * @param {Object} raw crawl
  * @return {Object} { publickey1,publickey2: 1 }
  * Takes raw crawl and returns an object of unique edges
  * edges have in the format "publickey1,publickey2" : 1.
  */
  getLinks: function(nodes) {
    var rippleds = this.getRippleds(nodes);
    // Create ippToPk using rippleds
    var ippToPk = {};
    _.each(Object.keys(rippleds), function(pk) {
      var ipp = rippleds[pk].ipp
      if (ipp)
        ippToPk[ipp] = pk;
    });

    var links = {};
    _.each(nodes, function(node) {

      // node properties
      var n_ipp = Object.keys(node)[0];
      var n_peers = node[n_ipp].overlay.active;

      _.each(n_peers, function(peer) {

        // peer properties
        var p_pk = normalizePubKey(peer.public_key);
        var p_type = peer.type;
        try {
          var p_ipp = normalizeIpp(peer.ip, peer.port);
        } catch (error) {
          var p_ipp = undefined;
        }

        var a,b;
        // Make link
        if (p_type) {
          // Get link
          if (p_type == "in") {
            a = ippToPk[n_ipp];
            b = p_pk;
          }
          else if (p_type == "out") {
            a = p_pk;
            b = ippToPk[n_ipp];
          }
          else if (p_type == "peer") {
            if (peer.ip) {
              if (peer.ip.split(":").length == 2) {
                a = ippToPk[n_ipp];
                b = p_pk;
              } else {
                a = p_pk;
                b = ippToPk[n_ipp];
              }
            }
          } else {
            // If type is not in/out/peer
            throw new Error("Peer has unexpected type")
          }

          if (a !== undefined && b !== undefined) {
            if (links[[a,b]] === undefined) {
              links[[a,b]] = 0;
            }
            links[[a,b]] += 1;
          }
        }

      });
    });

    return links;
  },

  /*
  * @param {Object} raw crawl
  * @return {Object} { version: count }
  * Takes a raw crawl and returns a dictionary of versions with their counts.
  */
  getVersions: function(nodes) {
    var rippleds = this.getRippleds(nodes);
    var versions = {};

    _.each(rippleds, function(rippled) {
      if (versions[rippled.version]) {
        versions[rippled.version] += 1;
      } else {
        versions[rippled.version] = 1;
      }
    });
    return versions;
  },

  /*
  * @param {Object} raw crawl
  * @return {Object} { location: count }
  * Takes a raw crawl and returns a dictionary of locations with their counts.
  * Locations are in the format COUNTRY_CITY (note that city might be missing).
  */
  getLocations: function(nodes) {
    var rippleds = this.getRippleds(nodes);
    var locations = {};

    _.each(rippleds, function(rippled) {
      var ipp = rippled.ipp;
      if (ipp) {
        geoloc = geoip.lookup(ipp.split(':')[0]);
        location = geoloc.country + '_' + geoloc.city;
      } else {
        location = undefined;
      }

      if (locations[location])
        locations[location] += 1;
      else
        locations[location] = 1;
    });
    return locations;
  },

  /*
  * @param {Object} raw crawl
  * @return {Object} {public_key: {in: count, out: count}}
  * Takes a raw crawl and returns the
  * in and out degree of each rippled instance.
  */
  getDegrees: function(nodes) {
    var links = this.getLinks(nodes);
    var connections = {};

    _.each(Object.keys(links), function(link) {
      var from = link.split(',')[0];
      var to = link.split(',')[1];

      if (!connections[from]) {
        connections[from] = {in: 0, out: 0};
      }
      connections[from].out += 1;

      if (!connections[to]) {
        connections[to] = {in: 0, out: 0};
      }
      connections[to].in += 1;

    });

    return connections;
  }

}
<|endoftext|>


<commit_before>var fs = require('fs'),
    path = require('path'),
    async = require('async'),
    assert = require('assert'),
    utils = require('../utils'),
    ScratchFile = utils.ScratchFile,
    gm = require('gm'),
    exporters = {},
    engine = {};

function Canvas() {
  var canvas = gm(1, 1, 'transparent');

  // Override the -size options (won't work otherwise)
  canvas._in = ['-background', 'transparent'];

  // Save the canvas
  this.canvas = canvas;
}
Canvas.prototype = {
  'addImage': function addImage (img, x, y, cb) {
    // Add the image
    var canvas = this.canvas;

    // TODO: Pull request this in to gm
    canvas.out('-page');
    canvas.out('+' + x + '+' + y);
    canvas.out(img.file);
  },
  'export': function exportFn (options, cb) {
    // Grab the exporter
    var canvas = this.canvas,
        format = options.format || 'png',
        exporter = exporters[format];

    // Assert it exists
    assert(exporter, 'Exporter ' + format + ' does not exist for spritesmith\'s gm engine');

    // Flatten the image (with transparency)
    canvas.mosaic();

    // Render the item
    exporter.call(this, options, cb);
  }
};

// Expose Canvas to engine
engine.Canvas = Canvas;

// Create paths for the scratch directory and transparent pixel
function createCanvas(width, height, cb) {
  // Generate a scratch file
  var scratchFile = new ScratchFile('png'),
      filepath = scratchFile.filepath;
  async.waterfall([
    function generateCanvas (cb) {
      // Generate a transparent canvas
      var base = gm(width, height, 'transparent');

      // Write out the base file
      base.write(filepath, cb);
    },
    function destroyScratchFile (x, y, z, cb) {
      // Ignore destory errors
      scratchFile.destroy(function () {
        cb(null);
      });
    },
    function loadBackCanvas (cb) {
      // Create a canvas
      var canvas = new Canvas();

      // Callback with it
      cb(null, canvas);
    }
  ], cb);
}

// Expose createCanvas to engine
engine.createCanvas = createCanvas;

// Write out Image as a static property of Canvas
/**
 * @param {String} file File path to load in
 * @param {Function} callback Error first callback to retrun the image from
 * @prop {Number} image.width
 * @prop {Number} image.height
 * @note Must be guaranteed to integrate into own library via .addImage
 */
function createImage(file, cb) {
  // Create the image
  var img = gm(file);

  // In series...
  async.waterfall([
    // Grab the size
    function getImgSize (cb) {
      img.size(cb);
    },
    function saveImgSize (size, cb) {
      // Create a structure for preserving the height and width of the image
      var imgFile = {
        'height': size.height,
        'width': size.width,
        'file': file
      };

      // Callback with the imgFile
      cb(null, imgFile);
    }
  ], cb);
}
engine.createImage = createImage;

// Function to add new exporters
function addExporter(name, exporter) {
  exporters[name] = exporter;
}

// Expose the exporters
engine.exporters = exporters;
engine.addExporter = addExporter;

// Helper to create gm exporters (could be a class for better abstraction)
function getGmExporter(ext) {
  /**
   * Generic gm exporter
   * @param {Object} options Options to export with
   * @param {Number} [options.quality] Quality of the exported item
   * @param {Function} cb Error-first callback to return binary image string to
   */
  return function gmExporterFn (options, cb) {
    var canvas = this.canvas,
        file = new ScratchFile(ext),
        filepath = file.filepath;

    // Update the quality of the canvas (if specified)
    var quality = options.quality;
    if (quality !== undefined) {
      canvas.quality(quality);
    }

    async.waterfall([
      // Write to file
      function writeOutCanvas (cb) {
        canvas.write(filepath, cb);
      },
      // Read the file back in (in binary)
      function readInCanvas (x, y, z, cb) {
       fs.readFile(filepath, 'binary', cb);
      },
      // Destroy the file
      function destroyFile (retVal, cb) {
        file.destroy(function () {
          cb(null, retVal);
        });
      }
    ], cb);
  }
}

// Generate the png exporter
var gmPngExporter = getGmExporter('png');
addExporter('png', gmPngExporter);
addExporter('image/png', gmPngExporter);

// Generate the jpeg exporter
var gmJpegExporter = getGmExporter('jpeg');
addExporter('jpg', gmJpegExporter);
addExporter('jpeg', gmJpegExporter);
addExporter('image/jpg', gmJpegExporter);
addExporter('image/jpeg', gmJpegExporter);

// This does not seem to be working at the moment
// // Generate the tiff exporter
// var gmTiffExporter = getGmExporter('tiff');
// addExporter('tiff', gmTiffExporter);
// addExporter('image/tiff', gmTiffExporter);

// Export the canvas
module.exports = engine;<commit_msg>Fixed a missing semicolon<commit_after>var fs = require('fs'),
    path = require('path'),
    async = require('async'),
    assert = require('assert'),
    utils = require('../utils'),
    ScratchFile = utils.ScratchFile,
    gm = require('gm'),
    exporters = {},
    engine = {};

function Canvas() {
  var canvas = gm(1, 1, 'transparent');

  // Override the -size options (won't work otherwise)
  canvas._in = ['-background', 'transparent'];

  // Save the canvas
  this.canvas = canvas;
}
Canvas.prototype = {
  'addImage': function addImage (img, x, y, cb) {
    // Add the image
    var canvas = this.canvas;

    // TODO: Pull request this in to gm
    canvas.out('-page');
    canvas.out('+' + x + '+' + y);
    canvas.out(img.file);
  },
  'export': function exportFn (options, cb) {
    // Grab the exporter
    var canvas = this.canvas,
        format = options.format || 'png',
        exporter = exporters[format];

    // Assert it exists
    assert(exporter, 'Exporter ' + format + ' does not exist for spritesmith\'s gm engine');

    // Flatten the image (with transparency)
    canvas.mosaic();

    // Render the item
    exporter.call(this, options, cb);
  }
};

// Expose Canvas to engine
engine.Canvas = Canvas;

// Create paths for the scratch directory and transparent pixel
function createCanvas(width, height, cb) {
  // Generate a scratch file
  var scratchFile = new ScratchFile('png'),
      filepath = scratchFile.filepath;
  async.waterfall([
    function generateCanvas (cb) {
      // Generate a transparent canvas
      var base = gm(width, height, 'transparent');

      // Write out the base file
      base.write(filepath, cb);
    },
    function destroyScratchFile (x, y, z, cb) {
      // Ignore destory errors
      scratchFile.destroy(function () {
        cb(null);
      });
    },
    function loadBackCanvas (cb) {
      // Create a canvas
      var canvas = new Canvas();

      // Callback with it
      cb(null, canvas);
    }
  ], cb);
}

// Expose createCanvas to engine
engine.createCanvas = createCanvas;

// Write out Image as a static property of Canvas
/**
 * @param {String} file File path to load in
 * @param {Function} callback Error first callback to retrun the image from
 * @prop {Number} image.width
 * @prop {Number} image.height
 * @note Must be guaranteed to integrate into own library via .addImage
 */
function createImage(file, cb) {
  // Create the image
  var img = gm(file);

  // In series...
  async.waterfall([
    // Grab the size
    function getImgSize (cb) {
      img.size(cb);
    },
    function saveImgSize (size, cb) {
      // Create a structure for preserving the height and width of the image
      var imgFile = {
        'height': size.height,
        'width': size.width,
        'file': file
      };

      // Callback with the imgFile
      cb(null, imgFile);
    }
  ], cb);
}
engine.createImage = createImage;

// Function to add new exporters
function addExporter(name, exporter) {
  exporters[name] = exporter;
}

// Expose the exporters
engine.exporters = exporters;
engine.addExporter = addExporter;

// Helper to create gm exporters (could be a class for better abstraction)
function getGmExporter(ext) {
  /**
   * Generic gm exporter
   * @param {Object} options Options to export with
   * @param {Number} [options.quality] Quality of the exported item
   * @param {Function} cb Error-first callback to return binary image string to
   */
  return function gmExporterFn (options, cb) {
    var canvas = this.canvas,
        file = new ScratchFile(ext),
        filepath = file.filepath;

    // Update the quality of the canvas (if specified)
    var quality = options.quality;
    if (quality !== undefined) {
      canvas.quality(quality);
    }

    async.waterfall([
      // Write to file
      function writeOutCanvas (cb) {
        canvas.write(filepath, cb);
      },
      // Read the file back in (in binary)
      function readInCanvas (x, y, z, cb) {
       fs.readFile(filepath, 'binary', cb);
      },
      // Destroy the file
      function destroyFile (retVal, cb) {
        file.destroy(function () {
          cb(null, retVal);
        });
      }
    ], cb);
  };
}

// Generate the png exporter
var gmPngExporter = getGmExporter('png');
addExporter('png', gmPngExporter);
addExporter('image/png', gmPngExporter);

// Generate the jpeg exporter
var gmJpegExporter = getGmExporter('jpeg');
addExporter('jpg', gmJpegExporter);
addExporter('jpeg', gmJpegExporter);
addExporter('image/jpg', gmJpegExporter);
addExporter('image/jpeg', gmJpegExporter);

// This does not seem to be working at the moment
// // Generate the tiff exporter
// var gmTiffExporter = getGmExporter('tiff');
// addExporter('tiff', gmTiffExporter);
// addExporter('image/tiff', gmTiffExporter);

// Export the canvas
module.exports = engine;<|endoftext|>


<commit_before>'use strict';

/**
 * Controller for the BreakOut-Member-Page.
 */

const co = require('co');
const _ = require('lodash');
const fs = require('fs');

const api = requireLocal('services/api-proxy');

let team = {};

/**
 * Sends the occurred error back to the client, and logs it to the bunyan global logger.
 * @param res
 * @param errMsg
 * @param err
 * @returns {*}
 */
const sendErr = (res, errMsg, err) => {

  if (err) logger.error(errMsg, err);
  else logger.error(errMsg);

  res.status(500).send({error: errMsg});
};

team.getTeamByUrl = (teamId, token) => co(function*() {
  let tempTeam = yield api.team.get(teamId);

  //ONLY VIEW FULLY PAID TEAMS
  if(!tempTeam.hasFullyPaid) return tempTeam;

  let events = yield api.event.all();
  tempTeam.event = events.filter((event) => event.id === tempTeam.event).pop();

  let allSponsors = yield api.sponsoring.getByTeam(tempTeam.event.id, tempTeam.id);
  allSponsors = allSponsors.filter(s => s.status === 'ACCEPTED' && !s.sponsorIsHidden);
  tempTeam.sponsors = yield allSponsors.map(sponsor => {
    if (sponsor.userId) return api.user.get(sponsor.userId);
    return sponsor.unregisteredSponsor;
  });

  let allChallenges = yield api.challenge.getByTeam(tempTeam.event.id, tempTeam.id);
  tempTeam.challenges = allChallenges.filter(s => s.status === 'ACCEPTED');

  let postingIds = yield api.team.getPostingIds(teamId);
  let allPostings = yield api.posting.getPostingsByIds(postingIds, token);
  tempTeam.postings = allPostings.reverse();

  let locations = yield api.location.getByTeam(teamId);
  locations = locations.filter(l => l.duringEvent);

  tempTeam.max = {};
  tempTeam.max.distance = yield api.team.getDistance(teamId);
  tempTeam.max.donations = yield api.team.getDonations(teamId);

  tempTeam.mapData = [{
    id: teamId,
    name: tempTeam.name,
    event: tempTeam.event,
    locations: locations,
    members: []
  }];

  tempTeam.members.forEach((m,i) => {
    tempTeam.mapData[0].members[i] = {
      firstname: m.firstname
    }
  });

  return tempTeam;
}).catch((ex) => {
  throw ex;
});

team.getAll = (sort) => co(function*() {

  if(!sort) sort = 'name';

  const events = yield api.event.all();

  let teamsByEvent = yield events.map((e) => api.team.getAllByEvent(e.id));

  let allTeams = teamsByEvent.map((teams, index) => {
    return teams.map(team => {
      team.city = events[index].city;
      team.event = events[index].id;
      return team;
    });
  });

  allTeams = _.flatten(allTeams);
  allTeams = allTeams.filter(t => t.hasFullyPaid && t.id !== 1);

  return _.sortBy(allTeams, t => t[sort]);

}).catch((ex) => {
  throw ex;
});

team.createPost = (req, res, next) => co(function*() {

  let mediaType = req.body.mediaType === '' ? null : [req.body.mediaType];

  let post = yield api.posting.createPosting(
    req.user,
    req.body.postText,
    mediaType,
    req.body.latitude,
    req.body.longitude);

  if (req.body.mediaType !== '' && req.file) {
    yield post.media.map(m => api.uploadPicture(req.file, m));
  }

  res.sendStatus(200);

}).catch((ex) => {
  sendErr(res, ex.message, ex);
});

team.createLike = (req, res, next) => co(function*() {

  yield api.posting.createLike(req.user, req.body.postingId);
  res.sendStatus(200);

}).catch((ex) => {
  sendErr(res, ex.message, ex);
});

team.createComment = (req, res, next) => co(function*() {
  if(req.body.text && req.body.text !== '') {
    yield api.posting.createComment(req.user, req.body.id, req.body.text);
    return res.sendStatus(200);
  }
  return res.sendStatus(500);

}).catch((ex) => {
  sendErr(res, ex.message, ex);
});

team.isAuth = (req, res) => {
  if(req.isAuthenticated()) return res.sendStatus(200);
  return res.sendStatus(401);
};

module.exports = team;<commit_msg>shuffels team if no sorting is required<commit_after>'use strict';

/**
 * Controller for the BreakOut-Member-Page.
 */

const co = require('co');
const _ = require('lodash');
const fs = require('fs');

const api = requireLocal('services/api-proxy');

let team = {};

/**
 * Sends the occurred error back to the client, and logs it to the bunyan global logger.
 * @param res
 * @param errMsg
 * @param err
 * @returns {*}
 */
const sendErr = (res, errMsg, err) => {

  if (err) logger.error(errMsg, err);
  else logger.error(errMsg);

  res.status(500).send({error: errMsg});
};

team.getTeamByUrl = (teamId, token) => co(function*() {
  let tempTeam = yield api.team.get(teamId);

  //ONLY VIEW FULLY PAID TEAMS
  if(!tempTeam.hasFullyPaid) return tempTeam;

  let events = yield api.event.all();
  tempTeam.event = events.filter((event) => event.id === tempTeam.event).pop();

  let allSponsors = yield api.sponsoring.getByTeam(tempTeam.event.id, tempTeam.id);
  allSponsors = allSponsors.filter(s => s.status === 'ACCEPTED' && !s.sponsorIsHidden);
  tempTeam.sponsors = yield allSponsors.map(sponsor => {
    if (sponsor.userId) return api.user.get(sponsor.userId);
    return sponsor.unregisteredSponsor;
  });

  let allChallenges = yield api.challenge.getByTeam(tempTeam.event.id, tempTeam.id);
  tempTeam.challenges = allChallenges.filter(s => s.status === 'ACCEPTED');

  let postingIds = yield api.team.getPostingIds(teamId);
  let allPostings = yield api.posting.getPostingsByIds(postingIds, token);
  tempTeam.postings = allPostings.reverse();

  let locations = yield api.location.getByTeam(teamId);
  locations = locations.filter(l => l.duringEvent);

  tempTeam.max = {};
  tempTeam.max.distance = yield api.team.getDistance(teamId);
  tempTeam.max.donations = yield api.team.getDonations(teamId);

  tempTeam.mapData = [{
    id: teamId,
    name: tempTeam.name,
    event: tempTeam.event,
    locations: locations,
    members: []
  }];

  tempTeam.members.forEach((m,i) => {
    tempTeam.mapData[0].members[i] = {
      firstname: m.firstname
    }
  });

  return tempTeam;
}).catch((ex) => {
  throw ex;
});

team.getAll = (sort) => co(function*() {

  const events = yield api.event.all();

  let teamsByEvent = yield events.map((e) => api.team.getAllByEvent(e.id));

  let allTeams = teamsByEvent.map((teams, index) => {
    return teams.map(team => {
      team.city = events[index].city;
      team.event = events[index].id;
      return team;
    });
  });

  allTeams = _.flatten(allTeams);
  allTeams = allTeams.filter(t => t.hasFullyPaid && t.id !== 1);
  if(sort) {
    allTeams = _.sortBy(allTeams, t => t[sort]);
  } else {
    allTeams = _.shuffle(allTeams);
  }

  return allTeams;

}).catch((ex) => {
  throw ex;
});

team.createPost = (req, res, next) => co(function*() {

  let mediaType = req.body.mediaType === '' ? null : [req.body.mediaType];

  let post = yield api.posting.createPosting(
    req.user,
    req.body.postText,
    mediaType,
    req.body.latitude,
    req.body.longitude);

  if (req.body.mediaType !== '' && req.file) {
    yield post.media.map(m => api.uploadPicture(req.file, m));
  }

  res.sendStatus(200);

}).catch((ex) => {
  sendErr(res, ex.message, ex);
});

team.createLike = (req, res, next) => co(function*() {

  yield api.posting.createLike(req.user, req.body.postingId);
  res.sendStatus(200);

}).catch((ex) => {
  sendErr(res, ex.message, ex);
});

team.createComment = (req, res, next) => co(function*() {
  if(req.body.text && req.body.text !== '') {
    yield api.posting.createComment(req.user, req.body.id, req.body.text);
    return res.sendStatus(200);
  }
  return res.sendStatus(500);

}).catch((ex) => {
  sendErr(res, ex.message, ex);
});

team.isAuth = (req, res) => {
  if(req.isAuthenticated()) return res.sendStatus(200);
  return res.sendStatus(401);
};

module.exports = team;<|endoftext|>


<commit_before>import Base64 from "../base64/Base64";
import SubEntity from "./SubEntity";

class Annotation extends SubEntity {
    static get logicalName() {
        return "annotation";
    }

    static async parseFile(annotation) {
        const {documentbody, mimetype} = annotation,
            blob = Base64.blob(documentbody, mimetype);
        blob.name = annotation.filename;
        return blob;
    }

    async parseFile(annotation) {
        return this.getClass().parseFile(annotation);
    }

    static async parseAnnotation(file, accountid) {
        if (!accountid) {
            throw new Error("No accountid specified!");
        }
        const base64 = await Base64.decodeBlob(file);
        const {name, type} = file;
        const annotation = new this({
            filename: name,
            mimetype: type,
            documentbody: base64
        });
        const strippedAccountid = accountid.startsWith("{") && accountid.endsWith("}") ? accountid.substr(1, accountid.length - 2) : accountid;
        try {
            await annotation.bind("objectid", strippedAccountid, "account");
            return annotation;
        } catch(e) {
            throw e;
        }
    }

    async parseAnnotation(file) {
        return this.getClass().parseAnnotation(file);
    }
}
export default Annotation;
<commit_msg>Regarding support for parseAnnotation by specifying logicalName<commit_after>import Base64 from "../base64/Base64";
import SubEntity from "./SubEntity";

class Annotation extends SubEntity {
    static get logicalName() {
        return "annotation";
    }

    static async parseFile(annotation) {
        const {documentbody, mimetype} = annotation,
            blob = Base64.blob(documentbody, mimetype);
        blob.name = annotation.filename;
        return blob;
    }

    async parseFile(annotation) {
        return this.getClass().parseFile(annotation);
    }

    static async parseAnnotation(file, id, logicalName) {
        if (!id) {
            throw new Error("No id specified!");
        }
        if (!logicalName) {
            throw new Error("No logicalName specified");
        }
        const base64 = await Base64.decodeBlob(file);
        const {name, type} = file;
        const annotation = new this({
            filename: name,
            mimetype: type,
            documentbody: base64
        });
        const strippedId = id.startsWith("{") && id.endsWith("}") ? id.substr(1, id.length - 2) : id;
        try {
            await annotation.bind("objectid", strippedId, logicalName);
            return annotation;
        } catch(e) {
            throw e;
        }
    }

    async parseAnnotation(file) {
        return this.getClass().parseAnnotation(file);
    }
}
export default Annotation;
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var request = require('request');
var config = require('config.json');

router.get('/', function (req, res) {
    res.render('register');
});

router.post('/', function (req, res) {
    // register using api to maintain clean separation between layers
    request.post({
        url: config.apiUrl + 'users/register',
        form: req.body,
        json: true
    }, function (error, response, body) {
        if (error) {
            console.log(error);
            return res.render('register', { error: 'An error occurred' + error});
        }

        if (response.statusCode !== 200) {
            return res.render('register', {
                error: response.body,
                firstName: req.body.firstName,
                lastName: req.body.lastName,
                username: req.body.username
            });
        }

        // return to login page with success message
        req.session.success = 'Registration successful';
        return res.redirect('/login');
    });
});

module.exports = router;<commit_msg>Now Finally fixed Heroku issue for real<commit_after>var express = require('express');
var router = express.Router();
var request = require('request');
var config = require('config.json');

router.get('/', function (req, res) {
    res.render('register');
});

router.post('/', function (req, res) {
    // register using api to maintain clean separation between layers
    request.post({
        url: 'http://127.0.0.1:' + process.env.PORT + 'users/register',
        form: req.body,
        json: true
    }, function (error, response, body) {
        if (error) {
            console.log(error);
            return res.render('register', { error: 'An error occurred' + error});
        }

        if (response.statusCode !== 200) {
            return res.render('register', {
                error: response.body,
                firstName: req.body.firstName,
                lastName: req.body.lastName,
                username: req.body.username
            });
        }

        // return to login page with success message
        req.session.success = 'Registration successful';
        return res.redirect('/login');
    });
});

module.exports = router;<|endoftext|>