<commit_before>/*
 * dialog unit tests
 */

//
// Dialog Test Helper Functions
//
var el, offsetBefore, offsetAfter, dragged;

var dlg = function() {
	return el.data("dialog").element.parents(".ui-dialog:first");
}

var isOpen = function(why) {
	ok(dlg().is(":visible"), why);
}

var isNotOpen = function(why) {
	ok(!dlg().is(":visible"), why);
}

var drag = function(handle, dx, dy) {
	var element = el.data("dialog").element;
	offsetBefore = el.offset();
	$(handle).simulate("drag", {
		dx: dx || 0,
		dy: dy || 0
	});
	dragged = { dx: dx, dy: dy };
	offsetAfter = el.offset();
}

var moved = function (dx, dy, msg) {
	msg = msg ? msg + "." : "";
	var actual = { left: offsetAfter.left, top: offsetAfter.top };
	var expected = { left: offsetBefore.left + dx, top: offsetAfter.top };
	compare2(actual, expected, 'dragged[' + dragged.dx + ', ' + dragged.dy + '] ' + msg);
}

function shouldmove(why) {
	var handle = $(".ui-dialog-titlebar", dlg());
	drag(handle, 50, 50);
	moved(50, 50, why);
}

function shouldnotmove(why) {
	var handle = $(".ui-dialog-titlebar", dlg());
	drag(handle, 50, 50);
	moved(0, 0, why);
}

var border = function(el, side) { return parseInt(el.css('border-' + side + '-width')); }

var margin = function(el, side) { return parseInt(el.css('margin-' + side)); }

// Dialog Tests
module("dialog");

test("init", function() {
	expect(6);

	el = $("#dialog1").dialog();
	ok(true, '.dialog() called on element');

	$([]).dialog();
	ok(true, '.dialog() called on empty collection');

	$("
").dialog();
	ok(true, '.dialog() called on disconnected DOMElement');

	$("
").dialog().dialog("foo");
	ok(true, 'arbitrary method called after init');

	$("
").dialog().data("foo.dialog");
	ok(true, 'arbitrary option getter after init');

	$("
").dialog().data("foo.dialog", "bar");
	ok(true, 'arbitrary option setter after init');

});

test("destroy", function() {
	expect(6);

	$("#dialog1").dialog().dialog("destroy");
	ok(true, '.dialog("destroy") called on element');

	$([]).dialog().dialog("destroy");
	ok(true, '.dialog("destroy") called on empty collection');

	$("
").dialog().dialog("destroy");
	ok(true, '.dialog("destroy") called on disconnected DOMElement');

	$("
").dialog().dialog("destroy").dialog("foo");
	ok(true, 'arbitrary method called after destroy');

	$("
").dialog().dialog("destroy").data("foo.dialog");
	ok(true, 'arbitrary option getter after destroy');

	$("
").dialog().dialog("destroy").data("foo.dialog", "bar");
	ok(true, 'arbitrary option setter after destroy');
});

/*
//This one takes a while to run

test("element types", function() {
	var typeNames = ('p,h1,h2,h3,h4,h5,h6,blockquote,ol,ul,dl,div,form'
		+ ',table,fieldset,address,ins,del,em,strong,q,cite,dfn,abbr'
		+ ',acronym,code,samp,kbd,var,img,object,hr'
		+ ',input,button,label,select,iframe').split(',');

	$.each(typeNames, function(i) {
		var typeName = typeNames[i];
		el = $(document.createElement(typeName)).appendTo('body');
		(typeName == 'table' && el.append("
content
"));
		el.dialog();
		ok(true, '$("<' + typeName + '/&gt").dialog()');
		el.dialog("destroy");
		el.remove();
	});
});

*/

test("defaults", function() {
	el = $('
').dialog();
	var defaults = {
		autoOpen: true,
		buttons: {},
		disabled: false,
		draggable: true,
		height: 200,
		maxHeight: null,
		maxWidth: null,
		minHeight: 100,
		minWidth: 150,
		modal: false,
		overlay: {},
		position: 'center',
		resizable: true,
		stack: true,
		title: null,
		width: 300
	};
	$.each(defaults, function(key, val) {
		var actual = el.data(key + ".dialog"), expected = val,
			method = (expected && expected.constructor == Object) ?
				compare2 : equals;
		method(actual, expected, key);
	});
	el.remove();
});

module("dialog: Options");

test("autoOpen", function() {
	expect(2);

	el = $("
").dialog({ autoOpen: false });
	isNotOpen('.dialog({ autoOpen: false })');
	el.remove();

	el = $("
").dialog({ autoOpen: true });
	isOpen('.dialog({ autoOpen: true })');
	el.remove();
});

test("buttons", function() {
	expect(10);
	var buttons = {
		"Ok": function(ev, ui) {
			ok(true, "button click fires callback");
			equals(this, el[0], "context of callback");
			equals(ev.target, btn[0], "event target");
		},
		"Cancel": function(ev, ui) {
			ok(true, "button click fires callback");
			equals(this, el[0], "context of callback");
			equals(ev.target, btn[1], "event target");
		}
	}
	el = $("
").dialog({ buttons: buttons });
	var btn = $("button", dlg());
	equals(btn.length, 2, "number of buttons");
	var i = 0;
	$.each(buttons, function(key, val) {
		equals(btn.eq(i).text(), key, "text of button " + (i+1));
		i += 1;
	});
	equals(btn.parent().attr('className'), 'ui-dialog-buttonpane', "buttons in container");
	btn.trigger("click");
});

test("draggable", function() {
	el = $("
").dialog({ draggable: false });
	shouldnotmove();
	el.remove();
	el = $("
").dialog({ draggable: true });
	shouldmove();
});

module("dialog: Methods");

module("dialog: Callbacks");

module("dialog: Tickets");

test("#XXXX title", function() {

});

module("dialog: Cleanup");

test("cleanup", function() {

	$(".ui-dialog").remove();

});
<commit_msg>tests dialog - added some option and callback tests<commit_after>/*
 * dialog unit tests
 */

//
// Dialog Test Helper Functions
//
var el,
	offsetBefore, offsetAfter,
	heightBefore, heightAfter,
	widthBefore, widthAfter,
	dragged;

var dlg = function() {
	return el.data("dialog").element.parents(".ui-dialog:first");
}

var isOpen = function(why) {
	ok(dlg().is(":visible"), why);
}

var isNotOpen = function(why) {
	ok(!dlg().is(":visible"), why);
}

var drag = function(handle, dx, dy) {
	var d = dlg();
	offsetBefore = d.offset();
	heightBefore = d.height();
	widthBefore = d.width();
	$(handle, d).simulate("drag", {
		dx: dx || 0,
		dy: dy || 0
	});
	dragged = { dx: dx, dy: dy };
	offsetAfter = d.offset();
	heightAfter = d.height();
	widthAfter = d.width();
}

var moved = function (dx, dy, msg) {
	msg = msg ? msg + "." : "";
	var actual = { left: offsetAfter.left, top: offsetAfter.top };
	var expected = { left: offsetBefore.left + dx, top: offsetAfter.top };
	compare2(actual, expected, 'dragged[' + dragged.dx + ', ' + dragged.dy + '] ' + msg);
}

function shouldmove(why) {
	var handle = $(".ui-dialog-titlebar", dlg());
	drag(handle, 50, 50);
	moved(50, 50, why);
}

function shouldnotmove(why) {
	var handle = $(".ui-dialog-titlebar", dlg());
	drag(handle, 50, 50);
	moved(0, 0, why);
}

var border = function(el, side) { return parseInt(el.css('border-' + side + '-width')); }

var margin = function(el, side) { return parseInt(el.css('margin-' + side)); }

// Dialog Tests
module("dialog");

test("init", function() {
	expect(6);

	$("#dialog1").dialog().remove();
	ok(true, '.dialog() called on element');

	$([]).dialog().remove();
	ok(true, '.dialog() called on empty collection');

	$("
").dialog().remove();
	ok(true, '.dialog() called on disconnected DOMElement');

	$("
").dialog().dialog("foo").remove();
	ok(true, 'arbitrary method called after init');

	el = $("
").dialog()
	var foo = el.data("foo.dialog");
	el.remove();
	ok(true, 'arbitrary option getter after init');

	$("
").dialog().data("foo.dialog", "bar").remove();
	ok(true, 'arbitrary option setter after init');
});

test("destroy", function() {
	expect(6);

	$("#dialog1").dialog().dialog("destroy").remove();
	ok(true, '.dialog("destroy") called on element');

	$([]).dialog().dialog("destroy").remove();
	ok(true, '.dialog("destroy") called on empty collection');

	$("
").dialog().dialog("destroy").remove();
	ok(true, '.dialog("destroy") called on disconnected DOMElement');

	$("
").dialog().dialog("destroy").dialog("foo").remove();
	ok(true, 'arbitrary method called after destroy');

	el = $("
").dialog();
	var foo = el.dialog("destroy").data("foo.dialog");
	el.remove();
	ok(true, 'arbitrary option getter after destroy');

	$("
").dialog().dialog("destroy").data("foo.dialog", "bar").remove();
	ok(true, 'arbitrary option setter after destroy');
});

/*
//This one takes a while to run

test("element types", function() {
	var typeNames = ('p,h1,h2,h3,h4,h5,h6,blockquote,ol,ul,dl,div,form'
		+ ',table,fieldset,address,ins,del,em,strong,q,cite,dfn,abbr'
		+ ',acronym,code,samp,kbd,var,img,object,hr'
		+ ',input,button,label,select,iframe').split(',');

	$.each(typeNames, function(i) {
		var typeName = typeNames[i];
		el = $(document.createElement(typeName)).appendTo('body');
		(typeName == 'table' && el.append("
content
"));
		el.dialog();
		ok(true, '$("<' + typeName + '/&gt").dialog()');
		el.dialog("destroy");
		el.remove();
	});
});

*/

test("defaults", function() {
	el = $('
').dialog();
	var defaults = {
		autoOpen: true,
		buttons: {},
		disabled: false,
		draggable: true,
		height: 200,
		maxHeight: null,
		maxWidth: null,
		minHeight: 100,
		minWidth: 150,
		modal: false,
		overlay: {},
		position: 'center',
		resizable: true,
		stack: true,
		title: null,
		width: 300
	};
	$.each(defaults, function(key, val) {
		var actual = el.data(key + ".dialog"), expected = val,
			method = (expected && expected.constructor == Object) ?
				compare2 : equals;
		method(actual, expected, key);
	});
	el.remove();
});

module("dialog: Options");

test("autoOpen", function() {
	expect(2);

	el = $("
").dialog({ autoOpen: false });
	isNotOpen('.dialog({ autoOpen: false })');
	el.remove();

	el = $("
").dialog({ autoOpen: true });
	isOpen('.dialog({ autoOpen: true })');
	el.remove();
});

test("buttons", function() {
	expect(10);
	var buttons = {
		"Ok": function(ev, ui) {
			ok(true, "button click fires callback");
			equals(this, el[0], "context of callback");
			equals(ev.target, btn[0], "event target");
		},
		"Cancel": function(ev, ui) {
			ok(true, "button click fires callback");
			equals(this, el[0], "context of callback");
			equals(ev.target, btn[1], "event target");
		}
	}
	el = $("
").dialog({ buttons: buttons });
	var btn = $("button", dlg());
	equals(btn.length, 2, "number of buttons");
	var i = 0;
	$.each(buttons, function(key, val) {
		equals(btn.eq(i).text(), key, "text of button " + (i+1));
		i += 1;
	});
	equals(btn.parent().attr('className'), 'ui-dialog-buttonpane', "buttons in container");
	btn.trigger("click");
	el.remove();
});

test("draggable", function() {
	el = $("
").dialog({ draggable: false });
	shouldnotmove();
	el.remove();
	el = $("
").dialog({ draggable: true });
	shouldmove();
	el.remove();
});

test("height", function() {
	el = $("
").dialog();
	equals(dlg().height(), 200, "default height");
	el.remove();
	el = $("
").dialog({ height: 437 });
	equals(dlg().height(), 437, "default height");
	el.remove();
});

test("maxHeight", function() {
	el = $("
").dialog({ maxHeight: 400 });
	drag('.ui-resizable-s', 1000, 1000);
	equals(heightAfter, 400, "maxHeight");
	el.remove();
	el = $("
").dialog({ maxHeight: 400 });
	drag('.ui-resizable-n', -1000, -1000);
	equals(heightAfter, 400, "maxHeight");
	el.remove();
});

test("maxWidth", function() {
	el = $("
").dialog({ maxWidth: 400 });
	drag('.ui-resizable-e', 1000, 1000);
	equals(widthAfter, 400, "maxWidth");
	el.remove();
	el = $("
").dialog({ maxWidth: 400 });
	drag('.ui-resizable-w', -1000, -1000);
	equals(widthAfter, 400, "maxWidth");
	el.remove();
});

test("minHeight", function() {
	el = $("
").dialog({ minHeight: 10 });
	drag('.ui-resizable-s', -1000, -1000);
	equals(heightAfter, 10, "minHeight");
	el.remove();
	el = $("
").dialog({ minHeight: 10 });
	drag('.ui-resizable-n', 1000, 1000);
	equals(heightAfter, 10, "minHeight");
	el.remove();
});

test("minWidth", function() {
	el = $("
").dialog({ minWidth: 10 });
	drag('.ui-resizable-e', -1000, -1000);
	equals(widthAfter, 10, "minWidth");
	el.remove();
	el = $("
").dialog({ minWidth: 10 });
	drag('.ui-resizable-w', 1000, 1000);
	equals(widthAfter, 10, "minWidth");
	el.remove();
});

module("dialog: Methods");

module("dialog: Callbacks");

test("open", function() {
	expect(4);
	el = $("");
	var content = el[0];
	el.dialog({
		open: function(ev, ui) {
			ok(true, 'autoOpen: true fires open callback');
			equals(this, content, "context of callback");
		}
	});
	el.remove();
	el = $("");
	var content = el[0];
	el.dialog({
		autoOpen: false,
		open: function(ev, ui) {
			ok(true, '.dialog("open") fires open callback');
			equals(this, el[0], "context of callback");
		}
	});
	el.dialog("open");
	el.remove();
});

test("close", function() {
	expect(2);
	el = $("
").dialog({
		close: function(ev, ui) {
			ok(true, '.dialog("close") fires close callback');
			equals(this, el[0], "context of callback");
		}
	});
	el.dialog("close");
	el.remove();
});

module("dialog: Tickets");
<|endoftext|>


<commit_before>var objects = require('ubelt/objects')
  , it = require('it-is')

exports ['merge'] = function (){
  it(objects.merge({a: 1}, {b: 2})).deepEqual({a: 1, b: 2})
}
exports ['merge N'] = function (){
  it(objects.merge({a: 1}, {b: 2}, {c: 3})).deepEqual({a: 1, b: 2, c: 3})
}
exports ['merge override from left'] = function (){
  it(objects.merge({a: 1}, {a: 2, b: 2})).deepEqual({a: 2, b: 2})
}
exports ['merge override from left N'] = function (){
  it(objects.merge({a: 1}, {a: 2, b: 2}, {b: 0, c: 3})).deepEqual({a: 2, b: 0, c: 3})
}
exports ['merge single arg'] = function (){
  it(objects.merge({a: 2, b: 2})).deepEqual({a: 2, b: 2})
}
exports ['merge null'] = function (){
  it(objects.merge()).equal(null)
  it(objects.merge(null)).equal(null)
  it(objects.merge(null, null, null)).equal(null)
}

exports ['merge with null'] = function (){
  it(objects.merge({x: 1}, null)).deepEqual({x: 1})
  it(objects.merge(null, {x: 1})).deepEqual({x: 1})
}

exports ['deep merge'] = function () {

 it(objects.deepMerge({a: {x: 1} }, {a: {y: 2} })).deepEqual({a: {x: 1, y: 2}})

}

exports ['non overlapping'] = function () {
//oh oops. deep merge takes only 2 args, not N. alse it copies. when merge mutates.
//immutable is better because it's easier to reason about.
 it(objects.deepMerge({a: 2}, {b: 'x' })).deepEqual({a: 2, b: 'x'})

}

exports ['each'] = function (){
  var on = {a: 1,b: 2, c: 3}, count = 0
  objects.each(on, function(v,k){
    it(v).equal(on[k])
    count ++
  })
  it(count).equal(3)
}
exports ['map'] = function (){

  var on = {a: 1,b: 2, c: 3}, count = 0
  var off =
    objects.map(on, function(v,k){
      it(v).equal(on[k])
      count ++
      return v * 2
    })
  it(count).equal(3)
  it(off).deepEqual({
    a: 2, b: 4,c: 6
  })
}

exports ['map -- {}'] = function (){

  var on = {}, count = 0
  var off =
    objects.map(on, function(v,k){
      count ++
    })
  it(count).equal(0)
  it(off).deepEqual({})
}

exports ['map -- {}'] = function (){

  var on = {}, count = 0
  var off =
    objects.map(on, function(v,k){
      count ++
    })
  it(count).equal(0)
  it(off).deepEqual({})
}

exports ['map on numbers -- start at 1'] = function () {

  var seven = objects.map(7, function (n) {
      return n
  })

  it(seven).deepEqual([1,2,3,4,5,6,7])

}

exports ['map on numbers: 0 - 8'] = function () {

  var seven = objects.map(0, 8, function (n) {
      return n
  })

  it(seven).deepEqual([0,1,2,3,4,5,6,7,8])

}

exports ['map even numbers: 2,4...12'] = function () {

  var seven = objects.map(2, 4, 12, function (n) {
      return n
  })

  it(seven).deepEqual([2,4,6,8,10,12])
}

exports ['map even numbers: 12, 10...2 in reverse'] = function () {

  var seven = objects.map(12, 10, 2, function (n) {
      return n
  })

  it(seven).deepEqual([2,4,6,8,10,12].reverse())

}

exports ['filter'] = function (){

  var on = {a: 1,b: 2, c: 3, d:4, e:5, f:6, g:7}, count = 0

  it(objects.filter(on, function (x){
    return !(x % 2)
  })).deepEqual({b: 2, d:4, f:6})
}

exports ['filter with regexp'] = function (){

  var on = [ '.git',
    'test',
    'objects.js',
    'index.js',
    'package.json',
    'types.js',
    'readme.markdown',
    '.gitignore',
    'arrays.js' ], count = 0

  it(objects.filter(on, /^.*\.js$/))
  .deepEqual([
    'objects.js',
    'index.js',
    'types.js',
    'arrays.js' ])
}

exports ['mapKeys -- create a object from a list of keys and a function'] = function (){

  var keys = ['foo','bar','xux']

  it(objects.mapKeys(keys, function (k){
      return k.toUpperCase()
  })).deepEqual({foo: 'FOO', bar: 'BAR', xux: 'XUX'})

}

exports ['mapToArray'] = function (){

  var on = {a: 1,b: 2, c: 3, d:4, e:5, f:6, g:7}, count = 0

  it(objects.mapToArray(on,function (v){
    return v
  })).deepEqual([1,2,3,4,5,6,7])

}

exports ['find'] = function () {

  //
  // sometime need to stop before the end, find is like that
  //

  var numbers = [3, 5, 3, 7, 77, 21, 4]

  it(objects.find(numbers, function (e) { return !(e % 2)})).equal(4)
  it(objects.findKey(numbers, function (e) { return !(e % 2)})).equal(6)
  it(objects.findReturn(numbers, function (e) { return !(e % 2)})).equal(true)

  it(objects.find([], function () {})).equal(null)
  it(objects.find(null, function () {})).equal(null)

}

exports ['path'] = function () {

  var a1 = {A: 1}

  it(objects.path(a1, ['A'])).equal(1)
  it(objects.path({A: {B: 4}}, ['A', 'B'])).equal(4)
  it(objects.path({A: {B: 4}}, ['A', 'C'])).strictEqual(undefined)
  it(objects.path(null, ['A', 'C'])).strictEqual(undefined)
  it(objects.path({Z: [0, 1, 2]}, ['Z', 2])).strictEqual(2)
  it(objects.path({Z: [0, 1, 2]}, ['Z', 0])).strictEqual(0)
  it(objects.path({Z: [0, 1, 2]}, ['Z', 0, 'T'])).strictEqual(undefined)
  it(objects.path({Z: null}, ['Z', 0, 'T'])).strictEqual(undefined)
  it(objects.path({Z: null}, ['Z'])).strictEqual(null)

}

exports ['has'] = function () {
  var x = {A: 1, B: 2}

  it(objects.has(x, {A: 1})).equal(true)
  it(objects.has(x, {B: 2})).equal(true)
  it(objects.has(x, {})).equal(true)
  it(objects.has(x, {C: 3})).equal(false)

  var y = {A: 1, B: 2, D: {C: 3}}
  it(objects.has(y, {A: 1})).equal(true)
  it(objects.has(y, {B: 2})).equal(true)
  it(objects.has(y, {D: {}})).equal(true)
  it(objects.has(y, {D: {C: 3}})).equal(true)
  it(objects.has(y, {D: {C: 3, E: false}})).equal(false)

}

exports ['setPath'] = function () {

  var x = {}
    , c = Math.random()
    , z = Math.random()
  objects.setPath(x, ['a','b','c'], c)
  it.equal(x.a.b.c, c)
  objects.setPath(x, ['z'], z)
  it.equal(x.z, z)
}<commit_msg>add test for enqueue<commit_after>var objects = require('ubelt/objects')
  , it = require('it-is')

exports ['merge'] = function (){
  it(objects.merge({a: 1}, {b: 2})).deepEqual({a: 1, b: 2})
}
exports ['merge N'] = function (){
  it(objects.merge({a: 1}, {b: 2}, {c: 3})).deepEqual({a: 1, b: 2, c: 3})
}
exports ['merge override from left'] = function (){
  it(objects.merge({a: 1}, {a: 2, b: 2})).deepEqual({a: 2, b: 2})
}
exports ['merge override from left N'] = function (){
  it(objects.merge({a: 1}, {a: 2, b: 2}, {b: 0, c: 3})).deepEqual({a: 2, b: 0, c: 3})
}
exports ['merge single arg'] = function (){
  it(objects.merge({a: 2, b: 2})).deepEqual({a: 2, b: 2})
}
exports ['merge null'] = function (){
  it(objects.merge()).equal(null)
  it(objects.merge(null)).equal(null)
  it(objects.merge(null, null, null)).equal(null)
}

exports ['merge with null'] = function (){
  it(objects.merge({x: 1}, null)).deepEqual({x: 1})
  it(objects.merge(null, {x: 1})).deepEqual({x: 1})
}

exports ['deep merge'] = function () {

 it(objects.deepMerge({a: {x: 1} }, {a: {y: 2} })).deepEqual({a: {x: 1, y: 2}})

}

exports ['non overlapping'] = function () {
//oh oops. deep merge takes only 2 args, not N. alse it copies. when merge mutates.
//immutable is better because it's easier to reason about.
 it(objects.deepMerge({a: 2}, {b: 'x' })).deepEqual({a: 2, b: 'x'})

}

exports ['each'] = function (){
  var on = {a: 1,b: 2, c: 3}, count = 0
  objects.each(on, function(v,k){
    it(v).equal(on[k])
    count ++
  })
  it(count).equal(3)
}
exports ['map'] = function (){

  var on = {a: 1,b: 2, c: 3}, count = 0
  var off =
    objects.map(on, function(v,k){
      it(v).equal(on[k])
      count ++
      return v * 2
    })
  it(count).equal(3)
  it(off).deepEqual({
    a: 2, b: 4,c: 6
  })
}

exports ['map -- {}'] = function (){

  var on = {}, count = 0
  var off =
    objects.map(on, function(v,k){
      count ++
    })
  it(count).equal(0)
  it(off).deepEqual({})
}

exports ['map -- {}'] = function (){

  var on = {}, count = 0
  var off =
    objects.map(on, function(v,k){
      count ++
    })
  it(count).equal(0)
  it(off).deepEqual({})
}

exports ['map on numbers -- start at 1'] = function () {

  var seven = objects.map(7, function (n) {
      return n
  })

  it(seven).deepEqual([1,2,3,4,5,6,7])

}

exports ['map on numbers: 0 - 8'] = function () {

  var seven = objects.map(0, 8, function (n) {
      return n
  })

  it(seven).deepEqual([0,1,2,3,4,5,6,7,8])

}

exports ['map even numbers: 2,4...12'] = function () {

  var seven = objects.map(2, 4, 12, function (n) {
      return n
  })

  it(seven).deepEqual([2,4,6,8,10,12])
}

exports ['map even numbers: 12, 10...2 in reverse'] = function () {

  var seven = objects.map(12, 10, 2, function (n) {
      return n
  })

  it(seven).deepEqual([2,4,6,8,10,12].reverse())

}

exports ['filter'] = function (){

  var on = {a: 1,b: 2, c: 3, d:4, e:5, f:6, g:7}, count = 0

  it(objects.filter(on, function (x){
    return !(x % 2)
  })).deepEqual({b: 2, d:4, f:6})
}

exports ['filter with regexp'] = function (){

  var on = [ '.git',
    'test',
    'objects.js',
    'index.js',
    'package.json',
    'types.js',
    'readme.markdown',
    '.gitignore',
    'arrays.js' ], count = 0

  it(objects.filter(on, /^.*\.js$/))
  .deepEqual([
    'objects.js',
    'index.js',
    'types.js',
    'arrays.js' ])
}

exports ['mapKeys -- create a object from a list of keys and a function'] = function (){

  var keys = ['foo','bar','xux']

  it(objects.mapKeys(keys, function (k){
      return k.toUpperCase()
  })).deepEqual({foo: 'FOO', bar: 'BAR', xux: 'XUX'})

}

exports ['mapToArray'] = function (){

  var on = {a: 1,b: 2, c: 3, d:4, e:5, f:6, g:7}, count = 0

  it(objects.mapToArray(on,function (v){
    return v
  })).deepEqual([1,2,3,4,5,6,7])

}

exports ['find'] = function () {

  //
  // sometime need to stop before the end, find is like that
  //

  var numbers = [3, 5, 3, 7, 77, 21, 4]

  it(objects.find(numbers, function (e) { return !(e % 2)})).equal(4)
  it(objects.findKey(numbers, function (e) { return !(e % 2)})).equal(6)
  it(objects.findReturn(numbers, function (e) { return !(e % 2)})).equal(true)

  it(objects.find([], function () {})).equal(null)
  it(objects.find(null, function () {})).equal(null)

}

exports ['path'] = function () {

  var a1 = {A: 1}

  it(objects.path(a1, ['A'])).equal(1)
  it(objects.path({A: {B: 4}}, ['A', 'B'])).equal(4)
  it(objects.path({A: {B: 4}}, ['A', 'C'])).strictEqual(undefined)
  it(objects.path(null, ['A', 'C'])).strictEqual(undefined)
  it(objects.path({Z: [0, 1, 2]}, ['Z', 2])).strictEqual(2)
  it(objects.path({Z: [0, 1, 2]}, ['Z', 0])).strictEqual(0)
  it(objects.path({Z: [0, 1, 2]}, ['Z', 0, 'T'])).strictEqual(undefined)
  it(objects.path({Z: null}, ['Z', 0, 'T'])).strictEqual(undefined)
  it(objects.path({Z: null}, ['Z'])).strictEqual(null)

}

exports ['has'] = function () {
  var x = {A: 1, B: 2}

  it(objects.has(x, {A: 1})).equal(true)
  it(objects.has(x, {B: 2})).equal(true)
  it(objects.has(x, {})).equal(true)
  it(objects.has(x, {C: 3})).equal(false)

  var y = {A: 1, B: 2, D: {C: 3}}
  it(objects.has(y, {A: 1})).equal(true)
  it(objects.has(y, {B: 2})).equal(true)
  it(objects.has(y, {D: {}})).equal(true)
  it(objects.has(y, {D: {C: 3}})).equal(true)
  it(objects.has(y, {D: {C: 3, E: false}})).equal(false)

}

exports ['setPath'] = function () {

  var x = {}
    , c = Math.random()
    , z = Math.random()
  objects.setPath(x, ['a','b','c'], c)
  it.equal(x.a.b.c, c)
  objects.setPath(x, ['z'], z)
  it.equal(x.z, z)
}

exports ['enqueue'] = function () {

  //add an item to the end of an array if it is not already in the array.

  var queue = []

  objects.enqueue(queue, 1)
  it.deepEqual(queue, [1])

  objects.enqueue(queue, 2)
  objects.enqueue(queue, 3)
  it.deepEqual(queue, [1, 2, 3])

  objects.enqueue(queue, 2)
  it.deepEqual(queue, [1, 2, 3])

  queue.shift()
  it.deepEqual(queue, [2, 3])

  objects.enqueue(queue, 1)
  it.deepEqual(queue, [2, 3, 1])

}<|endoftext|>


<commit_before>// run grunt --help for help on how to run
// Learn more about configuring this file at <https://github.com/theintern/intern/wiki/Configuring-Intern>.
// These default settings work OK for most people. The options that *must* be changed below are the
// packages, suites, excludeInstrumentation, and (if you want functional tests) functionalSuites.
define({
	// The port on which the instrumenting proxy will listen
	proxyPort: 9000,

	serverUrl: "http://127.0.0.1:9000/",

	// Browsers to run integration testing against. Note that version numbers must be strings if used with Sauce
	// OnDemand. Options that will be permutated are browserName, version, platform, and platformVersion; any other
	// capabilities options specified for an environment will be copied as-is
	environments: [
		// It seems that specifying version="" or leaving version unspecified
		// does not default to the latest version of the browser.

		// Desktop.
		// Not running on IE9 since Widget-attr test depends on domClass methods only available in IE10_
		{ browserName: "internet explorer", version: "11", platform: "Windows 8.1", requireWindowFocus: "true" },
		{ browserName: "internet explorer", version: "10", platform: "Windows 8", requireWindowFocus: "true" },
		// { browserName: "internet explorer", version: "9", platform: "Windows 7" },
		{ browserName: "firefox", version: "25", platform: [ /*"OS X 10.6", "Linux", */ "Windows 7" ] },
		{ browserName: "chrome", version: "32", platform: [ /*"OS X 10.6", "Linux", */ "Windows 7" ] },
		{ browserName: "safari", version: "6", platform: [ "OS X 10.8" ] },

		// Mobile
		{ browserName: "android", platform: "Linux", version: "4.1" },
		{ browserName: "android", platform: "Linux", "device-type": "tablet", version: "4.1" },
		{ browserName: "android", platform: "Linux", version: "4.1" },
		{ browserName: "android", platform: "Linux", "device-type": "tablet", version: "4.0" },
		{ browserName: "android", platform: "Linux", version: "4.0" },
		{ browserName: "iphone", platform: "OS X 10.9", version: "7"},
		{ browserName: "ipad", platform: "OS X 10.9", version: "7"},
		{ browserName: "iphone", platform: "OS X 10.8", version: "6.1"},
		{ browserName: "ipad", platform: "OS X 10.8", version: "6.1"},
		{ browserName: "iphone", platform: "OS X 10.8", version: "6.0"},
		{ browserName: "ipad", platform: "OS X 10.8", version: "6.0"}
	],

	// Maximum number of simultaneous integration tests that should be executed on the remote WebDriver service
	maxConcurrency: 3,

	// Whether or not to start Sauce Connect before running tests
	useSauceConnect: true,

	// Connection information for the remote WebDriver service. If using Sauce Labs, keep your username and password
	// in the SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables unless you are sure you will NEVER be
	// publishing this configuration file somewhere
	webdriver: {
		host: "localhost",
		port: 4444
	},
	loader: {
		baseUrl: ".."
	},

	// Non-functional test suite(s) to run in each browser
	suites: [ "deliteful/tests/unit/all" ],

	// Functional test suite(s) to run in each browser once non-functional tests are completed
	functionalSuites: [ "deliteful/tests/functional/all" ],

	// A regular expression matching URLs to files that should not be included in code coverage analysis
	excludeInstrumentation: /^(requirejs|dcl|dojo|dpointer|delite\/|deliteful\/tests|.*themes|.*transitions)/
});
<commit_msg>fix intern parameter name<commit_after>// run grunt --help for help on how to run
// Learn more about configuring this file at <https://github.com/theintern/intern/wiki/Configuring-Intern>.
// These default settings work OK for most people. The options that *must* be changed below are the
// packages, suites, excludeInstrumentation, and (if you want functional tests) functionalSuites.
define({
	// The port on which the instrumenting proxy will listen
	proxyPort: 9000,

	proxyUrl: "http://127.0.0.1:9000/",

	// Browsers to run integration testing against. Note that version numbers must be strings if used with Sauce
	// OnDemand. Options that will be permutated are browserName, version, platform, and platformVersion; any other
	// capabilities options specified for an environment will be copied as-is
	environments: [
		// It seems that specifying version="" or leaving version unspecified
		// does not default to the latest version of the browser.

		// Desktop.
		// Not running on IE9 since Widget-attr test depends on domClass methods only available in IE10_
		{ browserName: "internet explorer", version: "11", platform: "Windows 8.1", requireWindowFocus: "true" },
		{ browserName: "internet explorer", version: "10", platform: "Windows 8", requireWindowFocus: "true" },
		// { browserName: "internet explorer", version: "9", platform: "Windows 7" },
		{ browserName: "firefox", version: "25", platform: [ /*"OS X 10.6", "Linux", */ "Windows 7" ] },
		{ browserName: "chrome", version: "32", platform: [ /*"OS X 10.6", "Linux", */ "Windows 7" ] },
		{ browserName: "safari", version: "6", platform: [ "OS X 10.8" ] },

		// Mobile
		{ browserName: "android", platform: "Linux", version: "4.1" },
		{ browserName: "android", platform: "Linux", "device-type": "tablet", version: "4.1" },
		{ browserName: "android", platform: "Linux", version: "4.1" },
		{ browserName: "android", platform: "Linux", "device-type": "tablet", version: "4.0" },
		{ browserName: "android", platform: "Linux", version: "4.0" },
		{ browserName: "iphone", platform: "OS X 10.9", version: "7"},
		{ browserName: "ipad", platform: "OS X 10.9", version: "7"},
		{ browserName: "iphone", platform: "OS X 10.8", version: "6.1"},
		{ browserName: "ipad", platform: "OS X 10.8", version: "6.1"},
		{ browserName: "iphone", platform: "OS X 10.8", version: "6.0"},
		{ browserName: "ipad", platform: "OS X 10.8", version: "6.0"}
	],

	// Maximum number of simultaneous integration tests that should be executed on the remote WebDriver service
	maxConcurrency: 3,

	// Whether or not to start Sauce Connect before running tests
	useSauceConnect: true,

	// Connection information for the remote WebDriver service. If using Sauce Labs, keep your username and password
	// in the SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables unless you are sure you will NEVER be
	// publishing this configuration file somewhere
	webdriver: {
		host: "localhost",
		port: 4444
	},
	loader: {
		baseUrl: ".."
	},

	// Non-functional test suite(s) to run in each browser
	suites: [ "deliteful/tests/unit/all" ],

	// Functional test suite(s) to run in each browser once non-functional tests are completed
	functionalSuites: [ "deliteful/tests/functional/all" ],

	// A regular expression matching URLs to files that should not be included in code coverage analysis
	excludeInstrumentation: /^(requirejs|dcl|dojo|dpointer|delite\/|deliteful\/tests|.*themes|.*transitions)/
});
<|endoftext|>


<commit_before>var path = require('path'),
		glob = require('glob'),
    common = require('./common');

function parseElement(el){
	el.fill = el.fill || " ";
	el.adjust = el.adjust || "left";
	if(!el.length){
		throw new Error("required: length");
	}
	if(!(el.adjust === "left" || el.adjust === "right")){
		throw new Error("unsupported direction: " + el.direction)
	}
	if(!el.property){
		el.value = el.value || "";
	}
}

function loadSpec(file){
	var spec = require(path.resolve(process.cwd(),file))
	if(!spec || !Array.isArray(spec)){
		throw new Error('Invalid spec file');
	}
	spec.forEach(function(element){
		parseElement(element);
	});
	return spec;
};

module.exports.load = function(specPath){
	var ret = {},
			specs = glob.sync(specPath + "/**/*.tpl.js");

	specs.forEach(function (file) {
	  var name  = common.toCamelCase(path.basename(file).replace('.tpl.js',''));

	  console.log(file);

	  if (~file.indexOf('-')) {
	    name = file
	    .split('-').map(function (part) {
	      return capitalize(part);
	    }).join('');
	  }

	  ret[name] = loadSpec(file);
  });
	return ret;
};<commit_msg>console.log should not be there.<commit_after>var path = require('path'),
		glob = require('glob'),
    common = require('./common');

function parseElement(el){
	el.fill = el.fill || " ";
	el.adjust = el.adjust || "left";
	if(!el.length){
		throw new Error("required: length");
	}
	if(!(el.adjust === "left" || el.adjust === "right")){
		throw new Error("unsupported direction: " + el.direction)
	}
	if(!el.property){
		el.value = el.value || "";
	}
}

function loadSpec(file){
	var spec = require(path.resolve(process.cwd(),file))
	if(!spec || !Array.isArray(spec)){
		throw new Error('Invalid spec file');
	}
	spec.forEach(function(element){
		parseElement(element);
	});
	return spec;
};

module.exports.load = function(specPath){
	var ret = {},
			specs = glob.sync(specPath + "/**/*.tpl.js");

	specs.forEach(function (file) {
	  var name  = common.toCamelCase(path.basename(file).replace('.tpl.js',''));

	  if (~file.indexOf('-')) {
	    name = file
	    .split('-').map(function (part) {
	      return capitalize(part);
	    }).join('');
	  }

	  ret[name] = loadSpec(file);
  });
	return ret;
};<|endoftext|>


<commit_before>// run grunt --help for help on how to run
// Learn more about configuring this file at <https://github.com/theintern/intern/wiki/Configuring-Intern>.
// These default settings work OK for most people. The options that *must* be changed below are the
// packages, suites, excludeInstrumentation, and (if you want functional tests) functionalSuites.
define({
	// The port on which the instrumenting proxy will listen
	proxyPort: 9000,

	proxyUrl: "http://127.0.0.1:9000/",

	// Browsers to run integration testing against. Note that version numbers must be strings if used with Sauce
	// OnDemand. Options that will be permutated are browserName, version, platform, and platformVersion; any other
	// capabilities options specified for an environment will be copied as-is
	environments: [
		// It seems that specifying version="" or leaving version unspecified
		// does not default to the latest version of the browser.

		// Desktop.
		// Not running on IE9 since Widget-attr test depends on domClass methods only available in IE10_
		{ browserName: "internet explorer", version: "11", platform: "Windows 8.1", requireWindowFocus: "true",
			name : "deliteful"},
		{ browserName: "internet explorer", version: "10", platform: "Windows 8", requireWindowFocus: "true",
			name : "deliteful"},
		// { browserName: "internet explorer", version: "9", platform: "Windows 7" },
		{ browserName: "firefox", version: "25", platform: [ /*"OS X 10.6", "Linux", */ "Windows 7" ],
			name : "deliteful"},
		{ browserName: "chrome", version: "32", platform: [ /*"OS X 10.6", "Linux", */ "Windows 7" ],
			name : "deliteful"},
		{ browserName: "safari", version: "7", platform: [ "OS X 10.9" ], name : "deliteful"},

		// Mobile
		{ browserName: "iphone 7.1 simulator", platform: "OS X 10.9", version: "7.1", deviceName: "iPhone",
			app: "safari", device: "iPhone Simulator", name: "deliteful" },
		{ browserName: "ipad 7.1 simulator", platform: "OS X 10.9", version: "7.1", deviceName: "iPad",
			app: "safari", device: "iPad Simulator", name: "deliteful" },
		{ browserName: "iphone 7.0 simulator", platform: "OS X 10.9", version: "7.0", deviceName: "iPhone",
			app: "safari", device: "iPhone Simulator", name: "deliteful" },
		{ browserName: "ipad 7.0 simulator", platform: "OS X 10.9", version: "7.0", deviceName: "iPad",
			app: "safari", device: "iPad Simulator", name: "deliteful" }
//		{ browserName: "", platform: "OS X 10.8", version: "6", deviceName: "iPhone",
//			app: "safari", device: "iPhone Simulator", name: "deliteful" },
//		{ browserName: "", platform: "OS X 10.8", version: "6", deviceName: "iPad",
//			app: "safari", device: "iPad Simulator", name: "deliteful" },
//		{ browserName: "android", platform: "Linux", version: "4.1", name : "deliteful"},
//		{ browserName: "android", platform: "Linux", "device-type": "tablet", version: "4.1", name : "deliteful"},
//		{ browserName: "android", platform: "Linux", version: "4.1", name : "deliteful"},
//		{ browserName: "android", platform: "Linux", "device-type": "tablet", version: "4.0", name : "deliteful"},
//		{ browserName: "android", platform: "Linux", version: "4.0", name : "deliteful"},
	],

	// Maximum number of simultaneous integration tests that should be executed on the remote WebDriver service
	maxConcurrency: 3,

	// Whether or not to start Sauce Connect before running tests
	useSauceConnect: true,

	// Connection information for the remote WebDriver service. If using Sauce Labs, keep your username and password
	// in the SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables unless you are sure you will NEVER be
	// publishing this configuration file somewhere
	webdriver: {
		host: "localhost",
		port: 4444
	},

	loader: {
		baseUrl: typeof window !== "undefined" ? "../../.." : "..",
		config: {
			"ecma402/locales": "en-US"
		}
	},

	useLoader: {
		"host-node": "requirejs",
		"host-browser": "../../../requirejs/require.js"
	},

	// Non-functional test suite(s) to run in each browser
	suites: [ "deliteful/tests/unit/all" ],

	// Functional test suite(s) to run in each browser once non-functional tests are completed
	functionalSuites: [ "deliteful/tests/functional/all" ],

	// A regular expression matching URLs to files that should not be included in code coverage analysis
	excludeInstrumentation:
		/^(requirejs.*|dcl|dojo|dstore|dpointer|decor|delite\/|deliteful\/tests|.*themes|.*transitions)/
});
<commit_msg>intern config now includes only one ios platform (to avoid webdriver/sauce issues)<commit_after>// run grunt --help for help on how to run
// Learn more about configuring this file at <https://github.com/theintern/intern/wiki/Configuring-Intern>.
// These default settings work OK for most people. The options that *must* be changed below are the
// packages, suites, excludeInstrumentation, and (if you want functional tests) functionalSuites.
define({
	// The port on which the instrumenting proxy will listen
	proxyPort: 9000,

	proxyUrl: "http://127.0.0.1:9000/",

	// Browsers to run integration testing against. Note that version numbers must be strings if used with Sauce
	// OnDemand. Options that will be permutated are browserName, version, platform, and platformVersion; any other
	// capabilities options specified for an environment will be copied as-is
	environments: [
		// It seems that specifying version="" or leaving version unspecified
		// does not default to the latest version of the browser.

		// Desktop.
		// Not running on IE9 since Widget-attr test depends on domClass methods only available in IE10_
		{ browserName: "internet explorer", version: "11", platform: "Windows 8.1", requireWindowFocus: "true",
			name : "deliteful"},
		{ browserName: "internet explorer", version: "10", platform: "Windows 8", requireWindowFocus: "true",
			name : "deliteful"},
		// { browserName: "internet explorer", version: "9", platform: "Windows 7" },
		{ browserName: "firefox", version: "25", platform: [ /*"OS X 10.6", "Linux", */ "Windows 7" ],
			name : "deliteful"},
		{ browserName: "chrome", version: "32", platform: [ /*"OS X 10.6", "Linux", */ "Windows 7" ],
			name : "deliteful"},
		{ browserName: "safari", version: "7", platform: [ "OS X 10.9" ], name : "deliteful"},

		// Mobile
		{ browserName: "iphone 7.1 simulator", platform: "OS X 10.9", version: "7.1", deviceName: "iPhone",
			app: "safari", device: "iPhone Simulator", name: "deliteful" }

		/* For now disabled to avoid webdriver/sauce issues
		{ browserName: "ipad 7.1 simulator", platform: "OS X 10.9", version: "7.1", deviceName: "iPad",
			app: "safari", device: "iPad Simulator", name: "deliteful" },
		{ browserName: "iphone 7.0 simulator", platform: "OS X 10.9", version: "7.0", deviceName: "iPhone",
			app: "safari", device: "iPhone Simulator", name: "deliteful" },
		{ browserName: "ipad 7.0 simulator", platform: "OS X 10.9", version: "7.0", deviceName: "iPad",
			app: "safari", device: "iPad Simulator", name: "deliteful" }
		*/
//		{ browserName: "", platform: "OS X 10.8", version: "6", deviceName: "iPhone",
//			app: "safari", device: "iPhone Simulator", name: "deliteful" },
//		{ browserName: "", platform: "OS X 10.8", version: "6", deviceName: "iPad",
//			app: "safari", device: "iPad Simulator", name: "deliteful" },
//		{ browserName: "android", platform: "Linux", version: "4.1", name : "deliteful"},
//		{ browserName: "android", platform: "Linux", "device-type": "tablet", version: "4.1", name : "deliteful"},
//		{ browserName: "android", platform: "Linux", version: "4.1", name : "deliteful"},
//		{ browserName: "android", platform: "Linux", "device-type": "tablet", version: "4.0", name : "deliteful"},
//		{ browserName: "android", platform: "Linux", version: "4.0", name : "deliteful"},
	],

	// Maximum number of simultaneous integration tests that should be executed on the remote WebDriver service
	maxConcurrency: 3,

	// Whether or not to start Sauce Connect before running tests
	useSauceConnect: true,

	// Connection information for the remote WebDriver service. If using Sauce Labs, keep your username and password
	// in the SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables unless you are sure you will NEVER be
	// publishing this configuration file somewhere
	webdriver: {
		host: "localhost",
		port: 4444
	},

	loader: {
		baseUrl: typeof window !== "undefined" ? "../../.." : "..",
		config: {
			"ecma402/locales": "en-US"
		}
	},

	useLoader: {
		"host-node": "requirejs",
		"host-browser": "../../../requirejs/require.js"
	},

	// Non-functional test suite(s) to run in each browser
	suites: [ "deliteful/tests/unit/all" ],

	// Functional test suite(s) to run in each browser once non-functional tests are completed
	functionalSuites: [ "deliteful/tests/functional/all" ],

	// A regular expression matching URLs to files that should not be included in code coverage analysis
	excludeInstrumentation:
		/^(requirejs.*|dcl|dojo|dstore|dpointer|decor|delite\/|deliteful\/tests|.*themes|.*transitions)/
});
<|endoftext|>


<commit_before>'use strict';

const rp = require('minimal-request-promise');
const REQUEST_THROTTLE = 1000/30;
const RETRIABLE_ERRORS = ['ECONNRESET', 'ENOTFOUND', 'ESOCKETTIMEDOUT', 'ETIMEDOUT', 'ECONNREFUSED', 'EHOSTUNREACH', 'EPIPE', 'EAI_AGAIN'];
const NUMBER_OF_RETRIES = 20;

module.exports = function tlReply(messageObject, message, tlAccessToken) {

  var sendHttpRequest = function sendApiRequest(tlAccessToken, method, options, numberOfRetries) {
      return rp.post(`https://api.telegram.org/bot${tlAccessToken}/${method}`, options)
        .catch(e => {
          let httpCode = parseInt(e.statusCode, 10);
          if (numberOfRetries-- > 0 && (RETRIABLE_ERRORS.indexOf(e.statusMessage) >= 0 || httpCode == 429 || httpCode == 420 || httpCode >= 500 && httpCode < 600)) {
            return sendHttpRequest(tlAccessToken, method, options, numberOfRetries);
          }
          throw e;
        });
    },
    sendSingle = function sendSingle (message) {
      var method, body;

      if (typeof message !== 'string') {
        method = message.method ? message.method : messageObject.originalRequest.inline_query ?
          'inline_query' : 'sendMessage';
        body = message.body ? message.body : message;
        if (!body.chat_id)
          body.chat_id = messageObject.sender;
      } else if (messageObject.originalRequest.inline_query && typeof message === 'string') {
        method = 'answerInlineQuery';
        body = {
          inline_query_id: messageObject.sender,
          results: message
        };
      } else {
        method = 'sendMessage';
        body = {
          chat_id: messageObject.sender,
          text: message
        };
      }

      let numberOfRetries = NUMBER_OF_RETRIES;

      const options = {
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(body)
      };

      return sendHttpRequest(tlAccessToken, method, options, numberOfRetries);
    },

    sendAll = function () {
      if (!messages.length) {
        return Promise.resolve();
      } else {
        return sendSingle(messages.shift())
        .then(() => {
          return new Promise((resolve) => {
            if (!messages.length)
              resolve();
            else
              setTimeout(() => {
                resolve();
              }, REQUEST_THROTTLE);
          });
        })
        .then(sendAll);
      }
    },

    messages = Array.isArray(message) ? message : [message];

  return sendAll();
};
<commit_msg>Minor refactor<commit_after>'use strict';

const rp = require('minimal-request-promise');
const REQUEST_THROTTLE = 1000/30;
const RETRIABLE_ERRORS = ['ECONNRESET', 'ENOTFOUND', 'ESOCKETTIMEDOUT', 'ETIMEDOUT', 'ECONNREFUSED', 'EHOSTUNREACH', 'EPIPE', 'EAI_AGAIN'];
const NUMBER_OF_RETRIES = 20;

module.exports = function tlReply(messageObject, message, tlAccessToken) {

  var sendHttpRequest = function sendApiRequest(tlAccessToken, method, options, numberOfRetries) {
      return rp.post(`https://api.telegram.org/bot${tlAccessToken}/${method}`, options)
        .catch(e => {
          let httpCode = parseInt(e.statusCode, 10);
          if (numberOfRetries-- > 0 && (RETRIABLE_ERRORS.indexOf(e.statusMessage) >= 0 || httpCode == 429 || httpCode == 420 || httpCode >= 500 && httpCode < 600)) {
            return sendHttpRequest(tlAccessToken, method, options, numberOfRetries);
          }
          throw e;
        });
    },
    sendSingle = function sendSingle (message) {
      var method, body;

      if (typeof message !== 'string') {
        method = message.method ? message.method : messageObject.originalRequest.inline_query ?
          'inline_query' : 'sendMessage';
        body = message.body ? message.body : message;
        if (!body.chat_id)
          body.chat_id = messageObject.sender;
      } else if (messageObject.originalRequest.inline_query && typeof message === 'string') {
        method = 'answerInlineQuery';
        body = {
          inline_query_id: messageObject.sender,
          results: message
        };
      } else {
        method = 'sendMessage';
        body = {
          chat_id: messageObject.sender,
          text: message
        };
      }

      let numberOfRetries = NUMBER_OF_RETRIES;

      const options = {
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(body)
      };

      return sendHttpRequest(tlAccessToken, method, options, numberOfRetries);
    },

    sendAll = function () {
      if (!messages.length) {
        return Promise.resolve();
      } else {
        return sendSingle(messages.shift())
        .then(() => {
          return new Promise((resolve) => {
            if (!messages.length)
              resolve();
            else
              setTimeout(resolve, REQUEST_THROTTLE);
          });
        })
        .then(sendAll);
      }
    },

    messages = Array.isArray(message) ? message : [message];

  return sendAll();
};
<|endoftext|>


<commit_before>//injectable

var trackingEmitter = require('./emitter')

//globa tracking emitter

//something for defaults

// exports.$define = {
//   $trackSettings: {
//     value: {
//
//     }
//   }
// }

exports.$flags = {
  $track: function( val, event ) {

    /*
      val:true
      val:String
      val: Function
      val:Array (welke dingen je wil doen)
      val: {
        EMITTERKEY: {  do something special }
      }
    */

    console.error(val, event) //set event
    if( val === true ) {
      console.error('TRUE TRACKIN\'-----')

      //now also for all emitters that are allready there
      //this.$on --- each

      if(this.$on) {
        this.$on.each( function( emitter, key ) {
          console.log('%cshall i add a tracking listener on this emitter? --->', 'background:#333;color:white;', '\n', key )

          if(key === '$error') {
            //do spesh!
            //default -- dit moet ook uit een object komen
          }

          emitter.on('track', function( event ) {
            trackingEmitter.emit( event, false, false, key, this  )
          })

        }, function( property, key ) {
          return key !== '$value'
        })
      }

      this.on('$value', function( event, previousValue ) {
        trackingEmitter.emit( event, false, false, '$value', this, previousValue  )
      }, 'track')

    }

  }
}

/*
 - start met error handelere -- emit uitleggen error meegven infos knallen
 - dan tracking
*/
<commit_msg>added tracking<commit_after>"use strict";
//injectable
var trackingEmitter = require('./emitter')
var Emitter = require('../emitter')

function defaultTracking(id, event) {
  if (this.$on) {
    for (var i in this.$on) {
      if (i[0] !== '_' && this.$on[i] instanceof Emitter && i !== '$change') {
        loopdingetje(this.$on[i], i)
      }
    }
    function loopdingetje(emitter, key) {
      emitter.on( function( event, meta ) {
        trackingEmitter.emit(event, false, false, key, this, meta, id)
      }, 'track')
    }
  }
  this.on('$change', function(event, removed) {
    trackingEmitter.emit(event, false, false, '$change', this, removed, id)
  }, 'track')
}

exports.$flags = {
  $track: function( val, event ) {
    if (typeof val === "function") {
      //handle as function
      console.error('THIS\'-----', this)
    }
    if (typeof val === "string") {
      // defaultTracking.call( this, 'hahah', event)
      defaultTracking.call( this, val, event)
    }
    if (val.constructor === Array) {
      //handle as array
      console.error('THIS\'-----', this)
    }
    //object is elke key een specialevent
    if (val === true) {
      defaultTracking.call( this, this.$path.join(' > ') , event)
      //defaultTracking.call( this, this.$path.join(' > '), event)
      //default behaviour
      //console.error('THIS\'-----', this)
      //now also for all emitters that are allready there
      //this.$on --- each
    }
  }
}
<|endoftext|>


<commit_before>const isNumber = require(`isNumber`)

const unitlessNumberProperties = {
  animationIterationCount: true,
  boxFlex: true,
  boxFlexGroup: true,
  boxOrdinalGroup: true,
  columnCount: true,
  fillOpacity: true,
  flex: true,
  flexGrow: true,
  flexPositive: true,
  flexShrink: true,
  flexNegative: true,
  flexOrder: true,
  fontWeight: true,
  lineClamp: true,
  lineHeight: true,
  opacity: true,
  order: true,
  orphans: true,
  stopOpacity: true,
  strokeDashoffset: true,
  strokeOpacity: true,
  strokeWidth: true,
  tabSize: true,
  widows: true,
  zIndex: true,
  zoom: true
}

function transform (key, value) {
  const isUnitlessNumber = unitlessNumberProperties[key] || false

  if (!isUnitlessNumber && isNumber(value)) {
    value = `${value}px`
  }

  return {key, value}
}

module.exports = function transformStyle (style) {
  if (!style) return

  const keys = Object.keys(style)
  const length = keys.length
  let newStyle = {}

  for (let i = 0; i < length; i++) {
    let attr = keys[i]
    let {key, value} = transform(attr, style[attr])
    newStyle[key] = value
  }

  return newStyle
}
<commit_msg>Inline function in while loop in trasformStyle<commit_after>const isNumber = require(`isNumber`)

const unitlessNumberProperties = {
  animationIterationCount: true,
  boxFlex: true,
  boxFlexGroup: true,
  boxOrdinalGroup: true,
  columnCount: true,
  fillOpacity: true,
  flex: true,
  flexGrow: true,
  flexPositive: true,
  flexShrink: true,
  flexNegative: true,
  flexOrder: true,
  fontWeight: true,
  lineClamp: true,
  lineHeight: true,
  opacity: true,
  order: true,
  orphans: true,
  stopOpacity: true,
  strokeDashoffset: true,
  strokeOpacity: true,
  strokeWidth: true,
  tabSize: true,
  widows: true,
  zIndex: true,
  zoom: true
}

module.exports = function transformStyle (style) {
  if (!style) return

  const keys = Object.keys(style)
  const length = keys.length
  let newStyle = {}

  for (let i = 0; i < length; i++) {
    const key = keys[i]
    const isUnitlessNumber = unitlessNumberProperties[key] || false
    let value = style[key]

    if (!isUnitlessNumber && isNumber(value)) {
      value = `${value}px`
    }

    newStyle[key] = value
  }

  return newStyle
}
<|endoftext|>


<commit_before>'use strict';

let util = require('util');
let path = require('path');
let url = require('url');
let grpc = require('grpc');
let co = require('co');

/**
 * Name of the transport
 * @const
 */
const NAME = 'grpc';

/**
 * call wraps the method of conn into an endpoint.
 * @param  {Object} conn   A gRPC Client.
 * @param  {string} method The endpoint method name of the service.
 * @return {function*}        The endpoint.
 */
function call(conn, method) {
  if (!conn[method]) {
    throw new Error(util.format('conn has no method %s', method));
  }
  return function*(request, context) {
    let options = {};
    if (context && context.timeout) {
      options.deadline = Date.now() + context.timeout;
    }

    function call() {
      return function(callback) {
        try {
          conn[method](request, options, callback);
        } catch (err) {
          // TODO Decide on how to handle endpoint connection disruptions
          if(err.message === 'Call cannot be created from a closed channel') {
            err.code = grpc.status.UNAVAILABLE;
          }
          callback(err);
        }
      };
    }
    try {
      let result = yield call();
      let response = {
        error: null,
        data: result,
      };
      return response;
    } catch (err) {
      let resp;
      switch (err.code) {
        case grpc.status.OK:
        case grpc.status.CANCELLED:
          resp = {
            error: new Error('operation was cancelled'),
          };
          break;
        case grpc.status.INVALID_ARGUMENT:
          resp = {
            error: new Error('invalid argument'),
          };
          break;
        case grpc.status.NOT_FOUND:
          resp = {
            error: new Error('not found'),
          };
          break;
        case grpc.status.ALREADY_EXISTS:
          resp = {
            error: new Error('already exists'),
          };
          break;
        case grpc.status.PERMISSION_DENIED:
          resp = {
            error: new Error('permission denied'),
          };
          break;
        case grpc.status.UNAUTHENTICATED:
          resp = {
            error: new Error('unauthenticated'),
          };
          break;
        case grpc.status.FAILED_PRECONDITION:
          resp = {
            error: new Error('failed precondition'),
          };
          break;
        case grpc.status.ABORTED:
          resp = {
            error: new Error('aborted'),
          };
          break;
        case grpc.status.OUT_OF_RANGE:
          resp = {
            error: new Error('out of range'),
          };
          break;
        case grpc.status.UNIMPLEMENTED:
          resp = {
            error: new Error('unimplemented'),
          };
          break;
        case grpc.status.RESOURCE_EXHAUSTED:
          resp = {
            error: new Error('resource exhausted'),
          };
          break;
        case grpc.status.DEADLINE_EXCEEDED:
          resp = {
            error: new Error('deadline exceeded'),
          };
          break;
        case grpc.status.UNKNOWN:
          resp = {
            error: new Error('unknown'),
          };
          break;
        case grpc.status.INTERNAL:
          resp = {
            error: new Error('internal'),
          };
          break;
        case grpc.status.UNAVAILABLE:
          resp = {
            error: new Error('unavailable'),
          };
          break;
        case grpc.status.DATA_LOSS:
          resp = {
            error: new Error('data loss'),
          };
          break;
        default:
          throw err;
      }
      if (resp.error.message !== err.message) {
        resp.error.details = err.message;
      }
      return resp;
    }
  }
}

/**
 * serve wraps the endpoint to provide a gRPC service method.
 * @param  {function*} endpoint Endpoint which will be served as a gRPC service method.
 * @return {[function]}          The function can be used as a gRPC service method.
 */
function serve(endpoint, logger) {
  return function(call, callback) {
    let req = call.request;
    if (!endpoint) {
      callback({
        code: grpc.status.NOT_IMPLEMENTED
      });
    }
    co(function*() {
      let result = yield endpoint(req);
      return {error: null, result: result};
    }).catch(function(err) {
      let code;
      // match message to grpc code
      // only service errors
      switch (err.message) {
        case 'operation was cancelled':
          code = grpc.status.CANCELLED;
          break;
        case 'invalid argument':
          code = grpc.status.INVALID_ARGUMENT;
          break;
        case 'not found':
          code = grpc.status.NOT_FOUND;
          break;
        case 'already exists':
          code = grpc.status.ALREADY_EXISTS;
          break;
        case 'permission denied':
          code = grpc.status.PERMISSION_DENIED;
          break;
        case 'unauthenticated':
          code = grpc.status.UNAUTHENTICATED;
          break;
        case 'failed precondition':
          code = grpc.status.FAILED_PRECONDITION;
          break;
        case 'aborted':
          code = grpc.status.ABORTED;
          break;
        case 'out of range':
          code = grpc.status.OUT_OF_RANGE;
          break;
        case 'unimplemented':
          code = grpc.status.UNIMPLEMENTED;
          break;
      }
      if (!code) {
        code = grpc.status.INTERNAL;
      }
      let details = err.message;
      if (err.details) {
        details = err.details;
      }
      return {error:{
        code: code,
        details: details,
      }, result: null };
    }).then(function(resp){
      callback(resp.error, resp.result);
    }).catch(function(err){
      logger.log('ERROR', 'grpc transport error', err, err.stack);
    });
  };
}

function getDescendantProp(obj, desc) {
    var arr = desc.split(".");
    while(arr.length && (obj = obj[arr.shift()]));
    return obj;
}

/**
 * Server is a gRPC transport provider for serving.
 * @param {Object} config Configuration object.
 * Requires properties:addr,package,proto,service
 * Optional properties: credentials.ssl.certs
 */
function Server(config, logger) {
  this._server = new grpc.Server();
  this._config = config;
  let protoFileName = path.join(process.cwd(), config.proto);
  logger.log('VERBOSE', util.format('loading protobuf file %s', protoFileName));
  this._proto = grpc.load(protoFileName);
  let pkg = getDescendantProp(this._proto, this._config.package);
  this._service = pkg[this._config.service].service;
  this._logger = logger;
  this.name = NAME;
}

/**
 * bind maps the service to gRPC methods and binds the address.
 * @param  {Object} service Business logic
 */
Server.prototype.bind = function*(service) {
  // wrap all service methods
  let logger = this._logger;
  let binding = {};
  Object.getOwnPropertyNames(service).forEach(function(name) {
    binding[name] = serve(service[name], logger);
  });

  this._server.addProtoService(this._service, binding);

  let credentials = grpc.ServerCredentials.createInsecure();
  if (this._config.credentials) {
    if (this._config.credentials.ssl) {
      credentials = grpc.credentials.createSsl(this._config.credentials.ssl.certs);
    }
  }
  this._server.bind(this._config.addr, credentials);
}

/**
 * start launches the gRPC server and provides the service endpoints.
 */
Server.prototype.start = function*() {
  this._server.start();
}

/**
 * end stops the gRPC server and no longer provides the service endpoints.
 */
Server.prototype.end = function*() {
  var self = this;
  var shutdown = function() {
    return function(cb) {
      self._server.tryShutdown(cb);
    };
  }
  yield shutdown();
}

/**
 * Client is a gRPC transport provider for calling endpoints.
 * @param {Object} config Configuration object.
 * Requires properties: package,proto,service
 * Optional properties: timeout
 */
function Client(config, logger) {
  this.name = NAME;
  this._config = config;
  let protoFileName = path.join(process.cwd(), config.proto);
  logger.log('VERBOSE', util.format('loading protobuf file %s', protoFileName));
  this._proto = grpc.load(protoFileName);
  logger.log('VERBOSE', util.format('creating protobuf pkg %s', this._config.package));
  let pkg = getDescendantProp(this._proto, this._config.package);
  this._service = pkg[this._config.service];
}

Client.prototype.makeEndpoint = function*(method, instance) {
  let u = url.parse(instance, true, true);
  if (u.protocol !== 'grpc:') {
    throw new Error('not a grpc instance URL');
  }
  let host = u.host;
  let credentials = grpc.credentials.createInsecure();
  if (this._config.credentials) {
    if (this._config.credentials.ssl) {
      let certs = this._config.credentials.ssl.certs;
      let key = this._config.credentials.ssl.key;
      let chain = this._config.credentials.ssl.chain;
      credentials = grpc.credentials.createSsl(certs, key, chain);
    }
  }
  let self = this;
  let conn = new this._service(host, credentials);
  if (this._config.timeout) {
    let deadline = Date.now() + this._config.timeout;
    var wait = function() {
      return function(callback) {
        grpc.waitForClientReady(conn, deadline, function(err) {
          if (err) {
            let chan = grpc.getClientChannel(conn);
            chan.close();
          }
          callback(err);
        });
      }
    }
    yield wait();
  }
  return call(conn, method);
}

module.exports.Name = NAME;
module.exports.Client = Client;
module.exports.Server = Server;
module.exports.serve = serve;
module.exports.call = call;
<commit_msg>Add microservice.Client.end function<commit_after>'use strict';

let util = require('util');
let path = require('path');
let url = require('url');
let grpc = require('grpc');
let co = require('co');

/**
 * Name of the transport
 * @const
 */
const NAME = 'grpc';

/**
 * call wraps the method of conn into an endpoint.
 * @param  {Object} conn   A gRPC Client.
 * @param  {string} method The endpoint method name of the service.
 * @return {function*}        The endpoint.
 */
function call(conn, method) {
  if (!conn[method]) {
    throw new Error(util.format('conn has no method %s', method));
  }
  return function*(request, context) {
    let options = {};
    if (context && context.timeout) {
      options.deadline = Date.now() + context.timeout;
    }

    function call() {
      return function(callback) {
        try {
          conn[method](request, options, callback);
        } catch (err) {
          // TODO Decide on how to handle endpoint connection disruptions
          if(err.message === 'Call cannot be created from a closed channel') {
            err.code = grpc.status.UNAVAILABLE;
          }
          callback(err);
        }
      };
    }
    try {
      let result = yield call();
      let response = {
        error: null,
        data: result,
      };
      return response;
    } catch (err) {
      let resp;
      switch (err.code) {
        case grpc.status.OK:
        case grpc.status.CANCELLED:
          resp = {
            error: new Error('operation was cancelled'),
          };
          break;
        case grpc.status.INVALID_ARGUMENT:
          resp = {
            error: new Error('invalid argument'),
          };
          break;
        case grpc.status.NOT_FOUND:
          resp = {
            error: new Error('not found'),
          };
          break;
        case grpc.status.ALREADY_EXISTS:
          resp = {
            error: new Error('already exists'),
          };
          break;
        case grpc.status.PERMISSION_DENIED:
          resp = {
            error: new Error('permission denied'),
          };
          break;
        case grpc.status.UNAUTHENTICATED:
          resp = {
            error: new Error('unauthenticated'),
          };
          break;
        case grpc.status.FAILED_PRECONDITION:
          resp = {
            error: new Error('failed precondition'),
          };
          break;
        case grpc.status.ABORTED:
          resp = {
            error: new Error('aborted'),
          };
          break;
        case grpc.status.OUT_OF_RANGE:
          resp = {
            error: new Error('out of range'),
          };
          break;
        case grpc.status.UNIMPLEMENTED:
          resp = {
            error: new Error('unimplemented'),
          };
          break;
        case grpc.status.RESOURCE_EXHAUSTED:
          resp = {
            error: new Error('resource exhausted'),
          };
          break;
        case grpc.status.DEADLINE_EXCEEDED:
          resp = {
            error: new Error('deadline exceeded'),
          };
          break;
        case grpc.status.UNKNOWN:
          resp = {
            error: new Error('unknown'),
          };
          break;
        case grpc.status.INTERNAL:
          resp = {
            error: new Error('internal'),
          };
          break;
        case grpc.status.UNAVAILABLE:
          resp = {
            error: new Error('unavailable'),
          };
          break;
        case grpc.status.DATA_LOSS:
          resp = {
            error: new Error('data loss'),
          };
          break;
        default:
          throw err;
      }
      if (resp.error.message !== err.message) {
        resp.error.details = err.message;
      }
      return resp;
    }
  }
}

/**
 * serve wraps the endpoint to provide a gRPC service method.
 * @param  {function*} endpoint Endpoint which will be served as a gRPC service method.
 * @return {[function]}          The function can be used as a gRPC service method.
 */
function serve(endpoint, logger) {
  return function(call, callback) {
    let req = call.request;
    if (!endpoint) {
      callback({
        code: grpc.status.NOT_IMPLEMENTED
      });
    }
    co(function*() {
      let result = yield endpoint(req);
      return {error: null, result: result};
    }).catch(function(err) {
      let code;
      // match message to grpc code
      // only service errors
      switch (err.message) {
        case 'operation was cancelled':
          code = grpc.status.CANCELLED;
          break;
        case 'invalid argument':
          code = grpc.status.INVALID_ARGUMENT;
          break;
        case 'not found':
          code = grpc.status.NOT_FOUND;
          break;
        case 'already exists':
          code = grpc.status.ALREADY_EXISTS;
          break;
        case 'permission denied':
          code = grpc.status.PERMISSION_DENIED;
          break;
        case 'unauthenticated':
          code = grpc.status.UNAUTHENTICATED;
          break;
        case 'failed precondition':
          code = grpc.status.FAILED_PRECONDITION;
          break;
        case 'aborted':
          code = grpc.status.ABORTED;
          break;
        case 'out of range':
          code = grpc.status.OUT_OF_RANGE;
          break;
        case 'unimplemented':
          code = grpc.status.UNIMPLEMENTED;
          break;
      }
      if (!code) {
        code = grpc.status.INTERNAL;
      }
      let details = err.message;
      if (err.details) {
        details = err.details;
      }
      return {error:{
        code: code,
        details: details,
      }, result: null };
    }).then(function(resp){
      callback(resp.error, resp.result);
    }).catch(function(err){
      logger.log('ERROR', 'grpc transport error', err, err.stack);
    });
  };
}

function getDescendantProp(obj, desc) {
    var arr = desc.split(".");
    while(arr.length && (obj = obj[arr.shift()]));
    return obj;
}

/**
 * Server is a gRPC transport provider for serving.
 * @param {Object} config Configuration object.
 * Requires properties:addr,package,proto,service
 * Optional properties: credentials.ssl.certs
 */
function Server(config, logger) {
  this._server = new grpc.Server();
  this._config = config;
  let protoFileName = path.join(process.cwd(), config.proto);
  logger.log('VERBOSE', util.format('loading protobuf file %s', protoFileName));
  this._proto = grpc.load(protoFileName);
  let pkg = getDescendantProp(this._proto, this._config.package);
  this._service = pkg[this._config.service].service;
  this._logger = logger;
  this.name = NAME;
}

/**
 * bind maps the service to gRPC methods and binds the address.
 * @param  {Object} service Business logic
 */
Server.prototype.bind = function*(service) {
  // wrap all service methods
  let logger = this._logger;
  let binding = {};
  Object.getOwnPropertyNames(service).forEach(function(name) {
    binding[name] = serve(service[name], logger);
  });

  this._server.addProtoService(this._service, binding);

  let credentials = grpc.ServerCredentials.createInsecure();
  if (this._config.credentials) {
    if (this._config.credentials.ssl) {
      credentials = grpc.credentials.createSsl(this._config.credentials.ssl.certs);
    }
  }
  this._server.bind(this._config.addr, credentials);
}

/**
 * start launches the gRPC server and provides the service endpoints.
 */
Server.prototype.start = function*() {
  this._server.start();
}

/**
 * end stops the gRPC server and no longer provides the service endpoints.
 */
Server.prototype.end = function*() {
  var self = this;
  var shutdown = function() {
    return function(cb) {
      self._server.tryShutdown(cb);
    };
  }
  yield shutdown();
}

/**
 * Client is a gRPC transport provider for calling endpoints.
 * @param {Object} config Configuration object.
 * Requires properties: package,proto,service
 * Optional properties: timeout
 */
function Client(config, logger) {
  this.name = NAME;
  this._config = config;
  let protoFileName = path.join(process.cwd(), config.proto);
  logger.log('VERBOSE', util.format('loading protobuf file %s', protoFileName));
  this._proto = grpc.load(protoFileName);
  logger.log('VERBOSE', util.format('creating protobuf pkg %s', this._config.package));
  let pkg = getDescendantProp(this._proto, this._config.package);
  this._service = pkg[this._config.service];
}

Client.prototype.makeEndpoint = function*(method, instance) {
  let u = url.parse(instance, true, true);
  if (u.protocol !== 'grpc:') {
    throw new Error('not a grpc instance URL');
  }
  let host = u.host;
  let credentials = grpc.credentials.createInsecure();
  if (this._config.credentials) {
    if (this._config.credentials.ssl) {
      let certs = this._config.credentials.ssl.certs;
      let key = this._config.credentials.ssl.key;
      let chain = this._config.credentials.ssl.chain;
      credentials = grpc.credentials.createSsl(certs, key, chain);
    }
  }
  let self = this;
  let conn = new this._service(host, credentials);
  if (this._config.timeout) {
    let deadline = Date.now() + this._config.timeout;
    var wait = function() {
      return function(callback) {
        grpc.waitForClientReady(conn, deadline, function(err) {
          if (err) {
            let chan = grpc.getClientChannel(conn);
            chan.close();
          }
          callback(err);
        });
      }
    }
    yield wait();
  }
  let e = call(conn, method);

  if (!this.endpoint) {
    this.endpoint = {};
  }
  if (!this.endpoint[method]) {
    this.endpoint[method] = {
      instances: [],
    };
  }
  this.endpoint[method].instances.push({
    instance: instance,
    conn: conn,
    endpoint: e,
  });
  return e;
}

Client.prototype.end = function*(){
  let endpoints = Object.keys(this.endpoint);
  for(let i = 0; i < endpoints.length; i++) {
    let endpoint = this.endpoint[endpoints[i]];
    for(let j = 0; j < endpoint.instances; j++) {
      let conn = endpoint.instances[j].conn;
      let chan = grpc.getClientChannel(conn);
      chan.close();
    }
  }
}

module.exports.Name = NAME;
module.exports.Client = Client;
module.exports.Server = Server;
module.exports.serve = serve;
module.exports.call = call;
<|endoftext|>


<commit_before>var React = require('react'),
    render = require('../src/render.js').render;

describe('Render', function() {
  var domContainer;

  class Component extends React.Component {
    render() {
      return React.DOM.span();
    }
  }

  beforeEach(function() {
    sinon.spy(React, 'createElement');
    sinon.stub(React, 'render');

    domContainer = document.createElement('div');
  });

  afterEach(function() {
    React.createElement.restore();
    React.render.restore();
  });

  it('should create element for component', function() {
    render({
      component: Component,
      snapshot: {foo: 'bar'},
      container: domContainer
    });

    var args = React.createElement.lastCall.args;
    expect(args[0]).to.equal(Component);
  });

  it('should create element with props', function() {
    render({
      component: Component,
      snapshot: {foo: 'bar'},
      container: domContainer
    });

    var args = React.createElement.lastCall.args;
    expect(args[1].foo).to.equal('bar');
  });

  it('should render created element', function() {
    render({
      component: Component,
      snapshot: {foo: 'bar'},
      container: domContainer
    });

    var args = React.render.lastCall.args;
    expect(args[0]).to.equal(React.createElement.returnValues[0]);
  });

  it('should render in given container', function() {
    render({
      component: Component,
      snapshot: {foo: 'bar'},
      container: domContainer
    });

    var args = React.render.lastCall.args;
    expect(args[1]).to.equal(domContainer);
  });
});
<commit_msg>Can't believe I copy pasted so hard just 2 months ago #7<commit_after>var React = require('react'),
    render = require('../src/render.js').render;

describe('Render', function() {
  var domContainer;

  class Component extends React.Component {
    render() {
      return React.DOM.span();
    }
  }

  beforeEach(function() {
    sinon.spy(React, 'createElement');
    sinon.stub(React, 'render');

    domContainer = document.createElement('div');

    render({
      component: Component,
      snapshot: {foo: 'bar'},
      container: domContainer
    });
  });

  afterEach(function() {
    React.createElement.restore();
    React.render.restore();
  });

  it('should create element for component', function() {
    var args = React.createElement.lastCall.args;
    expect(args[0]).to.equal(Component);
  });

  it('should create element with props', function() {
    var args = React.createElement.lastCall.args;
    expect(args[1].foo).to.equal('bar');
  });

  it('should render created element', function() {
    var args = React.render.lastCall.args;
    expect(args[0]).to.equal(React.createElement.returnValues[0]);
  });

  it('should render in given container', function() {
    var args = React.render.lastCall.args;
    expect(args[1]).to.equal(domContainer);
  });
});
<|endoftext|>


<commit_before>// Stuff that is to be accessible from other modules (folders)

// The properties of a page that should be indexed for full-text search.
export const searchableTextFields = [
    'content.fullText',
    'content.title',
    'content.author',
    'content.description',
    'content.keywords',
]

// Revise and augment a page doc, used for two possible reasons:
//   1: Rename old fields to the current scheme, without needing data migration.
//   2: Choose the best fields from the available data (doing this at retrieval
//      rather than at storage time gives flexibility).
export const revisePageFields = doc => ({
    ...doc,
    // Choose a name to display; use the extracted title if available.
    title: (doc.content && doc.content.title) || '',
})
<commit_msg>Also make url searchable.<commit_after>// Stuff that is to be accessible from other modules (folders)

// The properties of a page that should be indexed for full-text search.
export const searchableTextFields = [
    'content.fullText',
    'content.title',
    'content.author',
    'content.description',
    'content.keywords',
    'url',
]

// Revise and augment a page doc, used for two possible reasons:
//   1: Rename old fields to the current scheme, without needing data migration.
//   2: Choose the best fields from the available data (doing this at retrieval
//      rather than at storage time gives flexibility).
export const revisePageFields = doc => ({
    ...doc,
    // Choose a name to display; use the extracted title if available.
    title: (doc.content && doc.content.title) || '',
})
<|endoftext|>


<commit_before>'use strict';
const moment = require('moment');
require('moment-timezone');

module.exports = function TwitchMessages(client) {
  const modChannel = client.channels.get('252275732628242432') || client.channels.get('373924698075037706');
  if (!modChannel) {
    client.utils.ownerError('twitchMessages', client, 'Unable to find Mod Channel');
    return;
  }
  const streamInfoSocket = require('socket.io-client')('wss://info.dbkynd.com');
  streamInfoSocket.on('connect', () => {
    client.logger.info('connected to streamInfo websocket');
  });
  streamInfoSocket.on('disconnect', () => {
    client.logger.warn('disconnected from streamInfo websocket');
  });
  streamInfoSocket.on('discord_ban_event', async data => {
    client.logger.debug(data);
    if (!data) return;
    if (typeof data !== 'object') return;
    if (Array.isArray(data)) return;
    if (!modChannel) return;
    client.logger.debug('discord_ban_event received');
    const messages = data.messages
      .sort(x => -parseInt(x.userstate['tmi-sent-ts']))
      .map(x => {
        const time = moment(parseInt(x.userstate['tmi-sent-ts']));
        return `\`\`[${time.tz('America/Los_Angeles').format('MM/DD/YY HH:mm:ss')}]\`\` ${x.message}`;
      });
    const embed = new client.Discord.MessageEmbed()
      .setAuthor(data.banee, await client.twitch.getUserLogo(data.banee_id),
        `https://www.twitch.tv/${data.banee.toLowerCase()}`)
      .setColor('DARK_ORANGE')
      .setDescription(messages.join('\n'))
      .setFooter(`Banned by ${data.banear}`)
      .setTimestamp(new Date(data.time));
    if (data.reason) embed.addField('Ban Reason:', data.reason);
    if (!['SEND_MESSAGES', 'EMBED_LINKS'].every(perm => modChannel.permissionsFor(client.user).has(perm))) {
      client.utils.ownerError('twitchMessages', client, 'Missing Channel Permissions');
      return;
    }
    modChannel.send({ embed })
      .catch(err => {
        client.utils.ownerError('twitchMessages', client, err);
      });
  });

  streamInfoSocket.on('discord_unban_event', async data => {
    client.logger.debug(data);
    if (!data) return;
    if (typeof data !== 'object') return;
    if (Array.isArray(data)) return;
    if (!modChannel) return;
    client.logger.debug('discord_unban_event received');
    const embed = new client.Discord.MessageEmbed()
      .setAuthor(data.banee, await client.twitch.getUserLogo(data.banee_id),
        `https://www.twitch.tv/${data.banee.toLowerCase()}`)
      .setColor('DARK_BLUE')
      .setFooter(`Unbanned by ${data.banear}`)
      .setTimestamp(new Date(data.time));
    if (!['SEND_MESSAGES', 'EMBED_LINKS'].every(perm => modChannel.permissionsFor(client.user).has(perm))) {
      client.utils.ownerError('twitchMessages', client, 'Missing Channel Permissions');
      return;
    }
    modChannel.send({ embed })
      .catch(err => {
        client.utils.ownerError('twitchMessages', client, err);
      });
  });
};
<commit_msg>streamInfo moved urls<commit_after>'use strict';
const moment = require('moment');
require('moment-timezone');

module.exports = function TwitchMessages(client) {
  const modChannel = client.channels.get('252275732628242432') || client.channels.get('373924698075037706');
  if (!modChannel) {
    client.utils.ownerError('twitchMessages', client, 'Unable to find Mod Channel');
    return;
  }
  const streamInfoSocket = require('socket.io-client')('wss://info.annemunition.tv');
  streamInfoSocket.on('connect', () => {
    client.logger.info('connected to streamInfo websocket');
  });
  streamInfoSocket.on('disconnect', () => {
    client.logger.warn('disconnected from streamInfo websocket');
  });
  streamInfoSocket.on('discord_ban_event', async data => {
    client.logger.debug(data);
    if (!data) return;
    if (typeof data !== 'object') return;
    if (Array.isArray(data)) return;
    if (!modChannel) return;
    client.logger.debug('discord_ban_event received');
    const messages = data.messages
      .sort(x => -parseInt(x.userstate['tmi-sent-ts']))
      .map(x => {
        const time = moment(parseInt(x.userstate['tmi-sent-ts']));
        return `\`\`[${time.tz('America/Los_Angeles').format('MM/DD/YY HH:mm:ss')}]\`\` ${x.message}`;
      });
    const embed = new client.Discord.MessageEmbed()
      .setAuthor(data.banee, await client.twitch.getUserLogo(data.banee_id),
        `https://www.twitch.tv/${data.banee.toLowerCase()}`)
      .setColor('DARK_ORANGE')
      .setDescription(messages.join('\n'))
      .setFooter(`Banned by ${data.banear}`)
      .setTimestamp(new Date(data.time));
    if (data.reason) embed.addField('Ban Reason:', data.reason);
    if (!['SEND_MESSAGES', 'EMBED_LINKS'].every(perm => modChannel.permissionsFor(client.user).has(perm))) {
      client.utils.ownerError('twitchMessages', client, 'Missing Channel Permissions');
      return;
    }
    modChannel.send({ embed })
      .catch(err => {
        client.utils.ownerError('twitchMessages', client, err);
      });
  });

  streamInfoSocket.on('discord_unban_event', async data => {
    client.logger.debug(data);
    if (!data) return;
    if (typeof data !== 'object') return;
    if (Array.isArray(data)) return;
    if (!modChannel) return;
    client.logger.debug('discord_unban_event received');
    const embed = new client.Discord.MessageEmbed()
      .setAuthor(data.banee, await client.twitch.getUserLogo(data.banee_id),
        `https://www.twitch.tv/${data.banee.toLowerCase()}`)
      .setColor('DARK_BLUE')
      .setFooter(`Unbanned by ${data.banear}`)
      .setTimestamp(new Date(data.time));
    if (!['SEND_MESSAGES', 'EMBED_LINKS'].every(perm => modChannel.permissionsFor(client.user).has(perm))) {
      client.utils.ownerError('twitchMessages', client, 'Missing Channel Permissions');
      return;
    }
    modChannel.send({ embed })
      .catch(err => {
        client.utils.ownerError('twitchMessages', client, err);
      });
  });
};
<|endoftext|>


<commit_before>import React, {Component} from 'react'
import Cards from '../../components/Cards/Cards'
import {push} from '../../helpers/dbcalls'
import {base} from '../../config/constants'
import Deleteandroutebutton from '../../components/Deleteandroutebutton/Deleteandroutebutton'
import Writeandroutebutton from '../../components/Writeandroutebutton/Writeandroutebutton'
import Counterlabel from '../../components/Counterlabel/Counterlabel'
import Styles from './Create.css.js'

class create extends Component {

  constructor(props) {
    super(props)
    this.state = {
      lobbyId: "",
      lobbyKey: "",
      loading: true
    };
  }
  componentDidMount() {
    var self = this;
    const userId = base
      .app()
      .INTERNAL
      .getUid()
    //functions to call
    let createLobby = () => {
      const inviteCode = Math.floor(Math.random() * 900000) + 100000
      let promise = new Promise((resolve, reject) => {
        let collection = 'activegame'
        let data = {
          code: inviteCode,
          host: userId,
          state: 'draft'
        }
        push(resolve, reject, data, collection);
      })
      promise.then((data) => {
        self.setState({lobbyId: inviteCode, lobbyKey: data.key, loading: false});
      }).catch(function (error) {
        console.log(error);
      });
    }

    //functions to execute at start
    let hostExists = new Promise((resolve, reject) => {
      base
        .fetch('activegame/', {
        context: this,
        asArray: true,
        queries: {
          orderByChild: 'host',
          equalTo: userId
        }
      })
        .then(data => {
          resolve(data);
        })
        .catch(error => {
          //handle error
        })
    })
    hostExists.then((data) => {
      if (data.length > 0) {
        console.log(data[0])
        if(data[0].state === "ready"){
          this.props.history.push("gameadmin")
        }else{
          this.setState({lobbyId: data[0].code, lobbyKey: data[0].key, loading: false});
        }
      } else {
        createLobby();
      }
    })
  }

  render() {
    return (

        {this.state.loading === true
          ?

              LOADING...

          :

              Available Cards

            <Cards dbReference={'/cards'}/>

Lobby ID: {this.state.lobbyId}

              <Counterlabel
                labelText={"Joined People: "}
                dbReference={'activegame/' + this.state.lobbyKey + '/memberarray/'}
                state={'count'}/>
              <Writeandroutebutton
                route={"/main"}
                labelText={"Start"}
                dbReference={'activegame/' + this.state.lobbyKey}
                dialog={this.refs}
                />
              <Deleteandroutebutton
                route={"/main"}
                labelText={"Cancel"}
                dbReference={'activegame/' + this.state.lobbyKey}
                removeState={'count'}/>

}

    )
  }
}

export default create<commit_msg>added writeandroutebutton to create.js<commit_after>import React, {Component} from 'react'
import Cards from '../../components/Cards/Cards'
import {withRouter} from 'react-router-dom'
import {push, post, update} from '../../helpers/dbcalls'
import {base} from '../../config/constants'
import Deleteandroutebutton from '../../components/Deleteandroutebutton/Deleteandroutebutton'
import Writeandroutebutton from '../../components/Writeandroutebutton/Writeandroutebutton'
import Counterlabel from '../../components/Counterlabel/Counterlabel'
import Styles from './Create.css.js'
import RaisedButton from 'material-ui/RaisedButton'
import SimpleState from 'react-simple-state'
import Warningwindow from '../../components/Warningwindow/Warningwindow'
import shuffle from '../../helpers/shuffle'
const simpleState = new SimpleState()

class create extends Component {

  constructor(props) {
    super(props)
    this.state = {
      lobbyId: "",
      lobbyKey: "",
      loading: true,
      alertMsg: ""
    };
  }
  componentDidMount() {
    var self = this;
    const userId = base
      .app()
      .INTERNAL
      .getUid()
    //functions to call
    let createLobby = () => {
      const inviteCode = Math.floor(Math.random() * 900000) + 100000
      let promise = new Promise((resolve, reject) => {
        let collection = 'activegame'
        let data = {
          code: inviteCode,
          host: userId,
          state: 'draft'
        }
        push(resolve, reject, data, collection);
      })
      promise.then((data) => {
        self.setState({lobbyId: inviteCode, lobbyKey: data.key, loading: false});
      }).catch(function (error) {
        console.log(error);
      });
    }

    //functions to execute at start
    let hostExists = new Promise((resolve, reject) => {
      base
        .fetch('activegame/', {
        context: this,
        asArray: true,
        queries: {
          orderByChild: 'host',
          equalTo: userId
        }
      })
        .then(data => {
          resolve(data);
        })
        .catch(error => {
          //handle error
        })
    })
    hostExists.then((data) => {
      if (data.length > 0) {
        console.log(data[0])
        if(data[0].state === "ready"){
          this.props.history.push("gameadmin")
        }else{
          this.setState({lobbyId: data[0].code, lobbyKey: data[0].key, loading: false});
        }
      } else {
        createLobby();
      }
    })
  }

  startGame() {
    const usersObj = simpleState.getState('count')
    const cardsObj = simpleState.getState('cards')
    console.log(cardsObj)
    const cardsCount = cardsObj
      .list
      .map(function (a) {
        return a.count;
      })
      .reduce((a, b) => a + b, 0);
    const userCount = usersObj.count.length
    console.log(cardsCount)
    if ((cardsCount === userCount)&& userCount > 0) {
      console.log("start")
      let cards = []
      for (let i = 0; i < cardsObj.list.length; i++) {
          console.log(cardsObj.list[i].count)
        for (let p = 0; p < cardsObj.list[i].count; p++) {
          console.log(cardsObj.list[i].count)
          cards.push(cardsObj.list[i].key)
        }
      }
      shuffle(cards)
      let memberarray = [];
      for (let i = 0; i < usersObj.count.length; i++) {
        const key = usersObj.count[i].key
        memberarray[key] =  {
            "card" : cards[i]
          }
      }
      let updateMembers = new Promise((resolve, reject) => {
          const collection = 'activegame/' + this.state.lobbyKey + "/memberarray/"
          post(resolve, reject, memberarray, collection);
      })
      updateMembers.then((data) => {
        let setGameReady = new Promise((resolve, reject) => {
            const collection = this.props.dbReference
            const object = {state: "ready"}
            update(resolve, reject, object, collection);
        })
        setGameReady.then((data) => {
          console.log("to route")
          this.props.history.push("gameadmin")
        }).catch( function (error) {
            alert("Error: " + error);
            this.setState({
              alertMsg: "Error: "+ error
            })
            this.dialog.handleOpen()
        });
      }).catch(function (error) {
        this.setState({
          alertMsg: "Error: "+ error
        })
        this.dialog.handleOpen()
      });
    } else {
      console.log("stop")
      this.setState({
        alertMsg: "You need as many players as selected cards. Please delete or add some cards or players. "
      })
      this.dialog.handleOpen()
    }
  }

  render() {
    return (

        {this.state.loading === true
          ?

              LOADING...

          :

              Available Cards

            <Cards dbReference={'/cards'}/>

Lobby ID: {this.state.lobbyId}

              <Counterlabel
                labelText={"Joined People: "}
                dbReference={'activegame/' + this.state.lobbyKey + '/memberarray/'}
                state={'count'}/>
              <Warningwindow message={this.state.alertMsg}
                ref={(dialog) => {this.dialog = dialog}}/>
              <RaisedButton
                primary={true}
                onClick={this
                .startGame
                .bind(this)}
                label={"Start"}/>
              <Deleteandroutebutton
                route={"/main"}
                labelText={"Cancel"}
                dbReference={'activegame/' + this.state.lobbyKey}
                removeState={'count'}/>

}

    )
  }
}

export default create<|endoftext|>


<commit_before>import { describe, it } from "mocha";
import { expect } from "chai";

import Schema from "../src/schema";
import Key from "../src/key";

describe("Schema", () => {

  describe("#getAll", () => {

    it("should return array", () => {
      expect(Schema.getAll()).to.be.an.instanceof(Array);
    });

    it("should return array which contains schemata", () => {
      const schema = Schema.getById("org.gtk.Demo");
      expect(Schema.getAll()).to.contain(schema);
    });

  });

  describe("#exists", () => {

    it("should throw TypeError if id is not a string", () => {
      expect(() => { Schema.exists(123); }).to.throw(TypeError);
    });

    it("should return false if there is no schema with the id", () => {
      expect(Schema.exists("unavailable")).to.be.false;
    });

    it("should return true if there is a schema with the id", () => {
      expect(Schema.exists("org.gtk.Demo")).to.be.true;
    });

  });

  describe("#getById", () => {

    it("should return null if there is no schema with the id", () => {
      expect(Schema.getById("unavailable")).to.be.null;
    });

    it("should return schema object it there is a schema with the id", () => {
      expect(Schema.getById("org.gtk.Demo"))
        .to.be.an.instanceof(Schema);
    });

  });

  describe("#getId", () => {

    it("should return schema id", () => {
      const id = "org.gtk.Demo";
      const schema = Schema.getById(id);
      expect(schema.getId()).to.be.equal(id);
    });

  });

  describe("#getAllKeys", () => {

    it("should return array", () => {
      const schema = Schema.getById("org.gtk.Demo");
      expect(schema.getAllKeys()).to.be.an.instanceof(Array);
    });

    it("should return array which contains keys", () => {

      const schema = Schema.getById("org.gtk.Demo");

      const expectedKeys = [
        new Key(schema, "color"),
        new Key(schema, "fullscreen"),
        new Key(schema, "maximized"),
        new Key(schema, "window-size")
      ];

      const keys = schema.getAllKeys();

      expect(keys.length).to.equal(expectedKeys.length);

      expectedKeys.forEach((key) => {
        expect(keys).to.contain(key);
      });

    });

  });

});
<commit_msg>Changed schema test sequence.<commit_after>import { describe, it } from "mocha";
import { expect } from "chai";

import Schema from "../src/schema";
import Key from "../src/key";

describe("Schema", () => {

  describe("#getAll", () => {

    it("should return array", () => {
      expect(Schema.getAll()).to.be.an.instanceof(Array);
    });

    it("should return array which contains schemata", () => {
      const schema = Schema.getById("org.gtk.Demo");
      expect(Schema.getAll()).to.contain(schema);
    });

  });

  describe("#exists", () => {

    it("should throw TypeError if id is not a string", () => {
      expect(() => { Schema.exists(123); }).to.throw(TypeError);
    });

    it("should return false if there is no schema with the id", () => {
      expect(Schema.exists("unavailable")).to.be.false;
    });

    it("should return true if there is a schema with the id", () => {
      expect(Schema.exists("org.gtk.Demo")).to.be.true;
    });

  });

  describe("#getById", () => {

    it("should return null if there is no schema with the id", () => {
      expect(Schema.getById("unavailable")).to.be.null;
    });

    it("should return schema object it there is a schema with the id", () => {
      expect(Schema.getById("org.gtk.Demo"))
        .to.be.an.instanceof(Schema);
    });

  });

  describe("#getId", () => {

    it("should return schema id", () => {
      const id = "org.gtk.Demo";
      const schema = Schema.getById(id);
      expect(schema.getId()).to.be.equal(id);
    });

  });

  describe("#getAllKeys", () => {

    it("should return array", () => {
      const schema = Schema.getById("org.gtk.Demo");
      expect(schema.getAllKeys()).to.be.an.instanceof(Array);
    });

    it("should return array which contains keys", () => {

      const schema = Schema.getById("org.gtk.Demo");

      const expectedKeys = [
        new Key(schema, "color"),
        new Key(schema, "fullscreen"),
        new Key(schema, "maximized"),
        new Key(schema, "window-size")
      ];

      const keys = schema.getAllKeys();

      expectedKeys.forEach((key) => {
        expect(keys).to.contain(key);
      });

      expect(keys.length).to.equal(expectedKeys.length);

    });

  });

});
<|endoftext|>