<commit_before>var fs = require('fs');
var path = require('path')
var assert = require('assert');
var Lawncipher = require('../');
var Long = require('long');
var faker = require('faker');

var rmdir = require('rmdir');

var sodium = require('libsodium-wrappers');
var to_hex = sodium.to_hex, from_hex = sodium.from_hex;

var deepObjectEquality = Lawncipher.deepObjectEquality;
var randomBuffer = Lawncipher.randomBuffer;

var PearsonBPlusTree = Lawncipher.PearsonBPlusTree;
var PearsonSeedGenerator = Lawncipher.PearsonSeedGenerator;
var PearsonHasher = Lawncipher.PearsonHasher;
var Index = Lawncipher.Index;

var testIndexPath = __dirname;

var testSeed = [
	98,  6, 85, 150, 36, 23, 112, 164, 135, 207, 169,  5, 26, 64, 165, 219,
	61, 20, 68, 89, 130, 63, 52, 102, 24, 229, 132, 245, 80, 216, 195, 115,
	90, 168, 156, 203, 177, 120,  2, 190, 188,  7, 100, 185, 174, 243, 162, 10,
	237, 18, 253, 225, 8, 208, 172, 244, 255, 126, 101, 79, 145, 235, 228, 121,
	123, 251, 67, 250, 161, 0, 107, 97, 241, 111, 181, 82, 249, 33, 69, 55,
	59,153, 29, 9, 213, 167, 84, 93, 30, 46, 94, 75, 151, 114, 73, 222,
	197, 96, 210, 45, 16, 227, 248, 202, 51, 152, 252, 125, 81, 206, 215, 186,
	39, 158, 178, 187, 131, 136,  1, 49, 50, 17, 141, 91, 47, 129, 60, 99,
	154, 35, 86, 171, 105, 34, 38, 200, 147, 58, 77, 118, 173, 246, 76, 254,
	133, 232, 196, 144, 198, 124, 53, 4, 108, 74, 223, 234, 134, 230, 157, 139,
	189, 205, 199, 128, 176, 19, 211, 236, 127, 192, 231, 70, 233, 88, 146, 44,
	183, 201, 22, 83, 13, 214, 116, 109, 159, 32, 95, 226, 140, 220, 57, 12,
	221, 31, 209, 182, 143, 92, 149, 184, 148, 62, 113, 65, 37, 27, 106, 166,
	3, 14, 204, 72, 21, 41, 56, 66, 28, 193, 40, 217, 25, 54,179,117,
	238, 87, 240, 155, 180, 170, 242, 212, 191, 163, 78, 218, 137, 194, 175, 110,
	43, 119, 224, 71, 122, 142, 42, 160, 104, 48, 247, 103, 15, 11, 138, 239
];

function arrayEquality(a1, a2){
	if (!(Array.isArray(a1) && Array.isArray(a2))) return false;
	if (a1.length != a2.length) return false;

	for (var i = 0; i < a1.length; i++){
		if (a1[i] != a2[i]) return false;
	}
	return true;
}

function newRandomUserDoc(){
	return {
		name: faker.name.firstName() + ' ' + faker.name.lastName(),
		email: faker.internet.email(),
		address: faker.address.streetName() + '\n' + faker.address.city() + '\n' + faker.address.country()
	};
}

function basicTests(next){
	var indexKey = randomBuffer(32);

	function saveIndex(_next){
		rmdir(path.join(testIndexPath, 'test_index'), function(err){
			if (err) throw err;

			var testIndex = new Index(testIndexPath, 'test_index', 'index', indexKey, testSeed, function(loadErr){
				if (loadErr) throw loadErr;

				testIndex.add('test', 1, function(e){
					if (e) throw e;

					testIndex.add('hello', 2, function(e){
						if (e) throw e;

						_next();
					});
				});
			});
		});
	}

	function loadIndex(_next){
		var testIndex = new Index(testIndexPath, 'test_index', 'index', indexKey, testSeed, function(loadErr){
			if (loadErr) throw loadErr;

			testIndex.lookup('test', function(err, value){
				if (err) throw err;

				assert(value == 1);

				testIndex.lookup('hello', function(err, value){
					if (err) throw err;

					assert(value == 2);

					_next();
				});
			});
		});
	}

	saveIndex(function(){
		loadIndex(next);
	});
}

console.log('----------------------');
console.log('Basic index testing');
console.log('----------------------');
basicTests(function(){
	console.log('done');
});
<commit_msg>Data load testing on indexes. We are not there yet<commit_after>var fs = require('fs');
var path = require('path')
var assert = require('assert');
var Lawncipher = require('../');
var Long = require('long');
var faker = require('faker');

var rmdir = require('rmdir');

var sodium = require('libsodium-wrappers');
var to_hex = sodium.to_hex, from_hex = sodium.from_hex;

var deepObjectEquality = Lawncipher.deepObjectEquality;
var randomBuffer = Lawncipher.randomBuffer;

var PearsonBPlusTree = Lawncipher.PearsonBPlusTree;
var PearsonSeedGenerator = Lawncipher.PearsonSeedGenerator;
var PearsonHasher = Lawncipher.PearsonHasher;
var Index = Lawncipher.Index;

var testIndexPath = path.join(__dirname, 'test_index');

var testSeed = [
	98,  6, 85, 150, 36, 23, 112, 164, 135, 207, 169,  5, 26, 64, 165, 219,
	61, 20, 68, 89, 130, 63, 52, 102, 24, 229, 132, 245, 80, 216, 195, 115,
	90, 168, 156, 203, 177, 120,  2, 190, 188,  7, 100, 185, 174, 243, 162, 10,
	237, 18, 253, 225, 8, 208, 172, 244, 255, 126, 101, 79, 145, 235, 228, 121,
	123, 251, 67, 250, 161, 0, 107, 97, 241, 111, 181, 82, 249, 33, 69, 55,
	59,153, 29, 9, 213, 167, 84, 93, 30, 46, 94, 75, 151, 114, 73, 222,
	197, 96, 210, 45, 16, 227, 248, 202, 51, 152, 252, 125, 81, 206, 215, 186,
	39, 158, 178, 187, 131, 136,  1, 49, 50, 17, 141, 91, 47, 129, 60, 99,
	154, 35, 86, 171, 105, 34, 38, 200, 147, 58, 77, 118, 173, 246, 76, 254,
	133, 232, 196, 144, 198, 124, 53, 4, 108, 74, 223, 234, 134, 230, 157, 139,
	189, 205, 199, 128, 176, 19, 211, 236, 127, 192, 231, 70, 233, 88, 146, 44,
	183, 201, 22, 83, 13, 214, 116, 109, 159, 32, 95, 226, 140, 220, 57, 12,
	221, 31, 209, 182, 143, 92, 149, 184, 148, 62, 113, 65, 37, 27, 106, 166,
	3, 14, 204, 72, 21, 41, 56, 66, 28, 193, 40, 217, 25, 54,179,117,
	238, 87, 240, 155, 180, 170, 242, 212, 191, 163, 78, 218, 137, 194, 175, 110,
	43, 119, 224, 71, 122, 142, 42, 160, 104, 48, 247, 103, 15, 11, 138, 239
];

function arrayEquality(a1, a2){
	if (!(Array.isArray(a1) && Array.isArray(a2))) return false;
	if (a1.length != a2.length) return false;

	for (var i = 0; i < a1.length; i++){
		if (a1[i] != a2[i]) return false;
	}
	return true;
}

function newRandomUserDoc(){
	return {
		name: faker.name.firstName() + ' ' + faker.name.lastName(),
		email: faker.internet.email(),
		address: faker.address.streetName() + '\n' + faker.address.city() + '\n' + faker.address.country()
	};
}

function basicTests(next){
	var indexKey = randomBuffer(32);

	function saveIndex(_next){
		rmdir(testIndexPath, function(err){
			if (err) throw err;

			var testIndex = new Index(__dirname, 'test_index', 'index', indexKey, testSeed, function(loadErr){
				if (loadErr) throw loadErr;

				testIndex.add('test', 1, function(e){
					if (e) throw e;

					testIndex.add('hello', 2, function(e){
						if (e) throw e;

						_next();
					});
				});
			});
		});
	}

	function loadIndex(_next){
		var testIndex = new Index(__dirname, 'test_index', 'index', indexKey, testSeed, function(loadErr){
			if (loadErr) throw loadErr;

			testIndex.lookup('test', function(err, value){
				if (err) throw err;

				assert(value == 1);

				testIndex.lookup('hello', function(err, value){
					if (err) throw err;

					assert(value == 2);

					_next();
				});
			});
		});
	}

	saveIndex(function(){
		loadIndex(next);
	});
}

//A testing method, designed to test save, loading, lookup and removal of a non-negligeable data set
function loadTests(docCount, cb){
	docCount = docCount || 1000;
	if (typeof cb != 'function') throw new TypeError('cb must be a function');

	var testIndex;
	var indexKey = randomBuffer(32);
	var indexSeed = PearsonSeedGenerator();

	var dataSet = new Array(docCount);

	for (var i = 0; i < docCount; i++){
		dataSet[i] = {k: faker.random.uuid(), v: newRandomUserDoc()};
	}

	function saveIndex(_next){
		rmdir(testIndexPath, function(err){
			if (err) throw err;

			testIndex = new Index(__dirname, 'test_index', 'index', indexKey, indexSeed, function(loadErr){
				if (loadErr) throw loadErr;

				var addIndex = 0;

				function addOne(){
					var currentTuple = dataSet[addIndex];
					testIndex.add(currentTuple.k, currentTuple.v, function(err){
						if (err) throw err;

						nextAdd();
					});
				}

				function nextAdd(){
					addIndex++;
					if (addIndex == docCount){
						_next();
					} else {
						if (addIndex % 100 == 0) setTimeout(addOne, 0);
						else addOne();
					}
				}

				addOne();
			});
		});
	}

	function loadIndex(_next){
		testIndex = new Index(__dirname, 'test_index', 'index', indexKey, indexSeed, function(loadErr){
			if (loadErr) throw loadErr;

			var lookupIndex = 0;

			function lookupOne(){
				var currentTuple = dataSet[lookupIndex];
				testIndex.lookup(currentTuple.k, function(err, value){
					if (err) throw err;

					console.log('lookupIndex: ' + lookupIndex);
					console.log('Found value: ' + JSON.stringify(value));
					console.log('Expected value: ' + JSON.stringify(currentTuple.v));
					assert(deepObjectEquality(currentTuple.v, value));

					nextLookup();
				});
			}

			function nextLookup(){
				lookupIndex++;
				if (lookupIndex == docCount){
					_next();
				} else {
					if (lookupIndex % 100 == 0) setTimeout(lookupOne, 0);
					else lookupOne();
				}
			}

			lookupOne();
		});
	}

	function destroyIndex(_next){
		if (!testIndex) throw new Error('testIndex must be defined');

		var removeIndex = 0;

		function removeOne(){
			var currentTuple = dataSet[lookupIndex];
			testIndex.remove(currentTuple.k, currentTuple.v, function(err){
				if (err) throw err;

				nextRemoval();
			});
		}

		function nextRemoval(){
			removeIndex++;
			if (removeIndex == docCount){
				_next();
			} else {
				if (removeIndex % 100 == 0) setTimeout(removeOne, 0);
				else removeOne();
			}
		}

		removeOne();
	}

	function checkDestruction(_next){
		if (!testIndex) throw new Error('testIndex must be defined');

		var lookupIndex = 0;

		function lookupOne(){
			var currentTuple = dataSet[lookupIndex];
			testIndex.lookup(currentTuple.k, function(err, value){
				if (err) throw err;

				assert(!value);

				nextLookup();
			});
		}

		function nextLookup(){
			lookupIndex++;
			if (lookupIndex == docCount){
				_next();
			} else {
				if (lookupIndex % 100 == 0) setTimeout(lookupOne, 0);
				else lookupOne();
			}
		}

		lookupOne();
	}

	saveIndex(function(){
		loadIndex(function(){
			destroyIndex(checkDestruction);
		});
	});
}

console.log('----------------------');
console.log('Basic index testing');
console.log('----------------------');
basicTests(function(){
	console.log('done');
	console.log('');
	console.log('----------------------');
	console.log('Data load index testing');
	console.log('----------------------');
	loadTests(undefined, function(){
		console.log('done');
	});
});
<|endoftext|>


<commit_before>var commonSpec = function(Opal, Asciidoctor) {

  describe('When loaded', function() {
    it('Opal should not be null', function() {
      expect(Opal).not.toBe(null);
    });

    it('Asciidoctor should not be null', function() {
      expect(Asciidoctor).not.toBe(null);
    });
  });

  describe('Loading', function() {
    it('should load document with inline attributes @', function() {
      var options = Opal.hash({'attributes': 'icons=font@'});
      var doc = Asciidoctor.$load('== Test', options);
      expect(doc.attributes.smap['icons']).toBe('font');
    });

    it('should load document with inline attributes !', function() {
      var options = Opal.hash({'attributes': 'icons=font@ data-uri!'});
      var doc = Asciidoctor.$load('== Test', options);
      expect(doc.attributes.smap['icons']).toBe('font');
    });

    it('should load document attributes', function() {
      var options = Opal.hash({'attributes': 'icons=font@ data-uri!'});
      var doc = Asciidoctor.$load('= Document Title\n:attribute-key: attribute-value\n\ncontent', options);
      expect(doc.$attr('attribute-key')).toBe('attribute-value');
    });

    it('should load document with array attributes !', function() {
      var options = Opal.hash({'attributes': ['icons=font@', 'data-uri!']});
      var doc = Asciidoctor.$load('== Test', options);
      expect(doc.attributes.smap['icons']).toBe('font');
      expect(doc.attributes.smap['data-uri']).toBeUndefined();
    });

    it('should load document with boolean attributes', function() {
      var options = Opal.hash({'attributes': ['sectnums=true']});
      var doc = Asciidoctor.$load('== Test', options);
      expect(doc.attributes.smap['sectnums']).toBe('true');
    });

    it('should load document authors', function() {
      var doc = Asciidoctor.$load('= Authors\nGuillaume Grossetie;Anders Nawroth\n');
      expect(doc.attributes.smap['author']).toBe('Guillaume Grossetie');
      expect(doc.attributes.smap['author_1']).toBe('Guillaume Grossetie');
      expect(doc.attributes.smap['author_2']).toBe('Anders Nawroth');
      expect(doc.attributes.smap['authorcount']).toBe(2);
      expect(doc.attributes.smap['authorinitials']).toBe('GG');
      expect(doc.attributes.smap['authorinitials_1']).toBe('GG');
      expect(doc.attributes.smap['authorinitials_2']).toBe('AN');
      expect(doc.attributes.smap['authors']).toBe('Guillaume Grossetie, Anders Nawroth');
    });
  });

  describe('Modifying', function() {
    it('should allow document-level attributes to be modified', function() {
      var doc = Asciidoctor.$load('= Document Title\n:lang: fr\n\ncontent is in {lang}');
      expect(doc.$attr('lang')).toBe('fr');
      doc.$set_attribute('lang', 'us');
      expect(doc.$attr('lang')).toBe('us');
      var html = doc.$convert();
      expect(html).toContain('content is in us');
    });
  });

  describe('Parsing', function() {
    it('== Test should contains
Test
', function() {
      var html = Asciidoctor.$convert('== Test', null);
      expect(html).toContain('
Test
');
    });

    it('=== Test should contains
Test
', function() {
      var html = Asciidoctor.$convert('=== Test', null);
      expect(html).toContain('
Test
');
    });

   it('=== Test should embed assets', function() {
     var options = Opal.hash({doctype: 'article', safe: 'unsafe', header_footer: true, attributes: ['showtitle', 'stylesheet=asciidoctor.css', 'stylesdir=../../build']});
     var html = Asciidoctor.$convert('=== Test', options);
     expect(html).toContain('Asciidoctor default stylesheet');
    });

    it('backend=docbook45 should produce a docbook45 document', function() {
      var options = Opal.hash({'attributes': ['backend=docbook45', 'doctype=book'],'header_footer':true});
      var html = Asciidoctor.$convert(':doctitle: DocTitle\n:docdate: 2014-01-01\n== Test', options);
      expect(html).toContain('<?xml version="1.0" encoding="UTF-8"?>\n\
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">\n\
<?asciidoc-toc?>\n\
<?asciidoc-numbered?>\n\
<book lang="en">\n\
<bookinfo>\n\
<title>DocTitle</title>\n\
<date>2014-01-01</date>\n\
</bookinfo>\n\
<chapter id="_test">\n\
<title>Test</title>\n\
\n\
</chapter>\n\
</book>');
    });

    it('backend=docbook5 should produce a docbook5 document', function() {
      var options = Opal.hash({'attributes': ['backend=docbook5', 'doctype=book'],'header_footer':true});
      var html = Asciidoctor.$convert(':doctitle: DocTitle\n:docdate: 2014-01-01\n== Test', options);
      expect(html).toContain('<?xml version="1.0" encoding="UTF-8"?>\n\
<?asciidoc-toc?>\n\
<?asciidoc-numbered?>\n\
<book xmlns="http://docbook.org/ns/docbook" xmlns:xl="http://www.w3.org/1999/xlink" version="5.0" xml:lang="en">\n\
<info>\n\
<title>DocTitle</title>\n\
<date>2014-01-01</date>\n\
</info>\n\
<chapter xml:id="_test">\n\
<title>Test</title>\n\
\n\
</chapter>\n\
</book>');
    });

    it('should produce a html5 document with font icons', function() {
      var options = Opal.hash({'attributes': 'icons=font@'});
      var html = Asciidoctor.$convert('= Document\n\nThis is a simple document.\n\n== Section\n\nCAUTION: This is important!', options);
      expect(html).toContain('');
    });

  });

  describe('Include', function() {
    it('Should includes file', function() {
      var opts = Opal.hash({'safe': 'safe'});
      var html = Asciidoctor.$convert('include::spec/share/include.adoc[]', opts);
      expect(html).toContain('include content');
    });
  });

}

// Export commonSpec for node test
if (typeof module !== 'undefined' && module.exports) {
  module.exports = commonSpec;
}
<commit_msg>Improve test by fetching attribute entry with Hash methods<commit_after>var commonSpec = function(Opal, Asciidoctor) {

  describe('When loaded', function() {
    it('Opal should not be null', function() {
      expect(Opal).not.toBe(null);
    });

    it('Asciidoctor should not be null', function() {
      expect(Asciidoctor).not.toBe(null);
    });
  });

  describe('Loading', function() {
    it('should load document with inline attributes @', function() {
      var options = Opal.hash({'attributes': 'icons=font@'});
      var doc = Asciidoctor.$load('== Test', options);
      expect(doc.attributes.smap['icons']).toBe('font');
      expect(doc.attributes['$[]']('icons')).toBe('font');
      expect(doc.attributes.$fetch('icons')).toBe('font');
    });

    it('should load document with inline attributes !', function() {
      var options = Opal.hash({'attributes': 'icons=font@ data-uri!'});
      var doc = Asciidoctor.$load('== Test', options);
      expect(doc.attributes.smap['icons']).toBe('font');
    });

    it('should load document attributes', function() {
      var options = Opal.hash({'attributes': 'icons=font@ data-uri!'});
      var doc = Asciidoctor.$load('= Document Title\n:attribute-key: attribute-value\n\ncontent', options);
      expect(doc.$attr('attribute-key')).toBe('attribute-value');
    });

    it('should load document with array attributes !', function() {
      var options = Opal.hash({'attributes': ['icons=font@', 'data-uri!']});
      var doc = Asciidoctor.$load('== Test', options);
      expect(doc.attributes.smap['icons']).toBe('font');
      expect(doc.attributes.smap['data-uri']).toBeUndefined();
    });

    it('should load document with boolean attributes', function() {
      var options = Opal.hash({'attributes': ['sectnums=true']});
      var doc = Asciidoctor.$load('== Test', options);
      expect(doc.attributes.smap['sectnums']).toBe('true');
    });

    it('should load document authors', function() {
      var doc = Asciidoctor.$load('= Authors\nGuillaume Grossetie;Anders Nawroth\n');
      expect(doc.attributes.smap['author']).toBe('Guillaume Grossetie');
      expect(doc.attributes.smap['author_1']).toBe('Guillaume Grossetie');
      expect(doc.attributes.smap['author_2']).toBe('Anders Nawroth');
      expect(doc.attributes.smap['authorcount']).toBe(2);
      expect(doc.attributes.smap['authorinitials']).toBe('GG');
      expect(doc.attributes.smap['authorinitials_1']).toBe('GG');
      expect(doc.attributes.smap['authorinitials_2']).toBe('AN');
      expect(doc.attributes.smap['authors']).toBe('Guillaume Grossetie, Anders Nawroth');
    });
  });

  describe('Modifying', function() {
    it('should allow document-level attributes to be modified', function() {
      var doc = Asciidoctor.$load('= Document Title\n:lang: fr\n\ncontent is in {lang}');
      expect(doc.$attr('lang')).toBe('fr');
      doc.$set_attribute('lang', 'us');
      expect(doc.$attr('lang')).toBe('us');
      var html = doc.$convert();
      expect(html).toContain('content is in us');
    });
  });

  describe('Parsing', function() {
    it('== Test should contains
Test
', function() {
      var html = Asciidoctor.$convert('== Test', null);
      expect(html).toContain('
Test
');
    });

    it('=== Test should contains
Test
', function() {
      var html = Asciidoctor.$convert('=== Test', null);
      expect(html).toContain('
Test
');
    });

   it('=== Test should embed assets', function() {
     var options = Opal.hash({doctype: 'article', safe: 'unsafe', header_footer: true, attributes: ['showtitle', 'stylesheet=asciidoctor.css', 'stylesdir=../../build']});
     var html = Asciidoctor.$convert('=== Test', options);
     expect(html).toContain('Asciidoctor default stylesheet');
    });

    it('backend=docbook45 should produce a docbook45 document', function() {
      var options = Opal.hash({'attributes': ['backend=docbook45', 'doctype=book'],'header_footer':true});
      var html = Asciidoctor.$convert(':doctitle: DocTitle\n:docdate: 2014-01-01\n== Test', options);
      expect(html).toContain('<?xml version="1.0" encoding="UTF-8"?>\n\
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">\n\
<?asciidoc-toc?>\n\
<?asciidoc-numbered?>\n\
<book lang="en">\n\
<bookinfo>\n\
<title>DocTitle</title>\n\
<date>2014-01-01</date>\n\
</bookinfo>\n\
<chapter id="_test">\n\
<title>Test</title>\n\
\n\
</chapter>\n\
</book>');
    });

    it('backend=docbook5 should produce a docbook5 document', function() {
      var options = Opal.hash({'attributes': ['backend=docbook5', 'doctype=book'],'header_footer':true});
      var html = Asciidoctor.$convert(':doctitle: DocTitle\n:docdate: 2014-01-01\n== Test', options);
      expect(html).toContain('<?xml version="1.0" encoding="UTF-8"?>\n\
<?asciidoc-toc?>\n\
<?asciidoc-numbered?>\n\
<book xmlns="http://docbook.org/ns/docbook" xmlns:xl="http://www.w3.org/1999/xlink" version="5.0" xml:lang="en">\n\
<info>\n\
<title>DocTitle</title>\n\
<date>2014-01-01</date>\n\
</info>\n\
<chapter xml:id="_test">\n\
<title>Test</title>\n\
\n\
</chapter>\n\
</book>');
    });

    it('should produce a html5 document with font icons', function() {
      var options = Opal.hash({'attributes': 'icons=font@'});
      var html = Asciidoctor.$convert('= Document\n\nThis is a simple document.\n\n== Section\n\nCAUTION: This is important!', options);
      expect(html).toContain('');
    });

  });

  describe('Include', function() {
    it('Should includes file', function() {
      var opts = Opal.hash({'safe': 'safe'});
      var html = Asciidoctor.$convert('include::spec/share/include.adoc[]', opts);
      expect(html).toContain('include content');
    });
  });

}

// Export commonSpec for node test
if (typeof module !== 'undefined' && module.exports) {
  module.exports = commonSpec;
}
<|endoftext|>


<commit_before>'use strict';

// setup the headerless localStorage
if (global.window === undefined) {
    require('mock-local-storage');
    global.window = {
        localStorage: global.localStorage
    }
}

// setup the dependencies
const Store = require('../src/store.js');
const test  = require('tape');

// define test variables
var name = 'John Doe';
var age  = 33;
var wife = {
    name: 'Jane Doe',
    age: 31
}

var timeout = 2000;
localStorage.clear();

// test the store initialization
test('new Store', assert => {
    assert.plan(1);
    var expected = 'object';

    try {
        var sessionStore = new Store('session');
        var actual = typeof(sessionStore);
        assert.equal(actual, expected, 'Store instance should be created');
    } catch(error) {
        assert.fail(error.message);
    }
});

// test the set method
test('Store.set', assert => {
    var userStore = new Store('userStore');

    assert.plan(3);
    assert.true(userStore.set('name', name));
    assert.true(userStore.set('age', age));
    assert.true(userStore.set('wife', wife));
});

// test the get method
test('Store.get', assert => {
    var userStore = new Store('userStore');

    assert.plan(4);
    assert.equal(userStore.get('name'), name);
    assert.equal(userStore.get('age'), age);
    assert.deepEqual(userStore.get('wife'), wife);
    assert.deepEqual(userStore.get(), {
        name: name,
        age: age,
        wife: wife
    });
});

// test the isset method
test('Store.isset', assert => {
    var userStore = new Store('userStore');

    assert.plan(4);
    assert.true(userStore.get('name'));
    assert.true(userStore.get('age'));
    assert.true(userStore.get('wife'));
    assert.false(userStore.get('randomError'));
});

// test the remove method
test('Store.remove', assert => {
    var userStore = new Store('userStore');

    var expected = 1;

    assert.plan(1);

    userStore.remove('name');
    userStore.remove('age');

    assert.equal(localStorage.length, expected);
});

// test the flush method
test('Store.flush', assert => {
    var otherStore = new Store('otherStore');
    otherStore.set('1', 1);
    otherStore.set('2', 1);
    otherStore.set('3', 1);

    var userStore = new Store('userStore');

    var expected = 3;

    assert.plan(1);

    userStore.flush();

    assert.equal(localStorage.length, expected);
});

// test the static flushExpired method
test('<static> Store.flushExpired', assert => {
    var flushStore = new Store('flushStatic');
    var otherStore = new Store('otherFlushStore');

    flushStore.set('1', 1, Date.now() + timeout - 2000);
    flushStore.set('2', 1, Date.now() + timeout - 100);
    flushStore.set('3', 1, Date.now() + timeout - 1000);
    flushStore.set('4', 1, Date.now() + timeout + 6000);

    otherStore.set('1', 1, Date.now() + timeout - 200);
    otherStore.set('2', 1, Date.now() + timeout - 50);
    otherStore.set('3', 1, Date.now() + timeout + 1000);
    otherStore.set('4', 1, Date.now() + timeout + 10000);

    setTimeout(function() {
        assert.plan(2);

        Store.flushExpired();

        assert.equal(Object.keys(flushStore.get()).length, 1);
        assert.equal(Object.keys(otherStore.get()).length, 2);
    }, timeout);
});

// test the static flush method
test('<static> Store.flush', assert => {
    var expected = 0;

    assert.plan(1);

    Store.flush();

    assert.equal(localStorage.length, expected);
});

// the the auto flush method on Store initialization
test('new Store ; auto flush expired values', assert => {
    var flushStore = new Store('flush');
    var expected   = 2;

    flushStore.set('1', 1, Date.now() + timeout - 1000);
    flushStore.set('2', 2, Date.now() + timeout - 100);
    flushStore.set('3', 3, Date.now() + timeout - 50);
    flushStore.set('4', 4, Date.now() + timeout + 1000);
    flushStore.set('5', 5, Date.now() + timeout + 5000);

    setTimeout(function() {
        assert.plan(1);

        var flushStore = new Store('flush');

        assert.equal(Object.keys(flushStore.get()).length, expected);
    }, timeout);
});

// the the auto flush method on Store initialization
test('new Store ; suppress auto flush expired values', assert => {
    var flushStore = new Store('suppressFlush');
    var expected   = 5;

    flushStore.set('1', 1, Date.now() + timeout - 1000);
    flushStore.set('2', 2, Date.now() + timeout - 100);
    flushStore.set('3', 3, Date.now() + timeout - 50);
    flushStore.set('4', 4, Date.now() + timeout + 1000);
    flushStore.set('5', 5, Date.now() + timeout + 5000);

    setTimeout(function() {
        assert.plan(1);

        var flushStore = new Store('suppressFlush', false);

        assert.equal(Object.keys(flushStore.get()).length, expected);
    }, timeout);
});
<commit_msg>fixed the isset test<commit_after>'use strict';

// setup the headerless localStorage
if (global.window === undefined) {
    require('mock-local-storage');
    global.window = {
        localStorage: global.localStorage
    }
}

// setup the dependencies
const Store = require('../src/store.js');
const test  = require('tape');

// define test variables
var name = 'John Doe';
var age  = 33;
var wife = {
    name: 'Jane Doe',
    age: 31
}

var timeout = 2000;
localStorage.clear();

// test the store initialization
test('new Store', assert => {
    assert.plan(1);
    var expected = 'object';

    try {
        var sessionStore = new Store('session');
        var actual = typeof(sessionStore);
        assert.equal(actual, expected, 'Store instance should be created');
    } catch(error) {
        assert.fail(error.message);
    }
});

// test the set method
test('Store.set', assert => {
    var userStore = new Store('userStore');

    assert.plan(3);
    assert.true(userStore.set('name', name));
    assert.true(userStore.set('age', age));
    assert.true(userStore.set('wife', wife));
});

// test the get method
test('Store.get', assert => {
    var userStore = new Store('userStore');

    assert.plan(4);
    assert.equal(userStore.get('name'), name);
    assert.equal(userStore.get('age'), age);
    assert.deepEqual(userStore.get('wife'), wife);
    assert.deepEqual(userStore.get(), {
        name: name,
        age: age,
        wife: wife
    });
});

// test the isset method
test('Store.isset', assert => {
    var userStore = new Store('userStore');

    assert.plan(4);
    assert.true(userStore.isset('name'));
    assert.true(userStore.isset('age'));
    assert.true(userStore.isset('wife'));
    assert.false(userStore.isset('randomError'));
});

// test the remove method
test('Store.remove', assert => {
    var userStore = new Store('userStore');

    var expected = 1;

    assert.plan(1);

    userStore.remove('name');
    userStore.remove('age');

    assert.equal(localStorage.length, expected);
});

// test the flush method
test('Store.flush', assert => {
    var otherStore = new Store('otherStore');
    otherStore.set('1', 1);
    otherStore.set('2', 1);
    otherStore.set('3', 1);

    var userStore = new Store('userStore');

    var expected = 3;

    assert.plan(1);

    userStore.flush();

    assert.equal(localStorage.length, expected);
});

// test the static flushExpired method
test('<static> Store.flushExpired', assert => {
    var flushStore = new Store('flushStatic');
    var otherStore = new Store('otherFlushStore');

    flushStore.set('1', 1, Date.now() + timeout - 2000);
    flushStore.set('2', 1, Date.now() + timeout - 100);
    flushStore.set('3', 1, Date.now() + timeout - 1000);
    flushStore.set('4', 1, Date.now() + timeout + 6000);

    otherStore.set('1', 1, Date.now() + timeout - 200);
    otherStore.set('2', 1, Date.now() + timeout - 50);
    otherStore.set('3', 1, Date.now() + timeout + 1000);
    otherStore.set('4', 1, Date.now() + timeout + 10000);

    setTimeout(function() {
        assert.plan(2);

        Store.flushExpired();

        assert.equal(Object.keys(flushStore.get()).length, 1);
        assert.equal(Object.keys(otherStore.get()).length, 2);
    }, timeout);
});

// test the static flush method
test('<static> Store.flush', assert => {
    var expected = 0;

    assert.plan(1);

    Store.flush();

    assert.equal(localStorage.length, expected);
});

// the the auto flush method on Store initialization
test('new Store ; auto flush expired values', assert => {
    var flushStore = new Store('flush');
    var expected   = 2;

    flushStore.set('1', 1, Date.now() + timeout - 1000);
    flushStore.set('2', 2, Date.now() + timeout - 100);
    flushStore.set('3', 3, Date.now() + timeout - 50);
    flushStore.set('4', 4, Date.now() + timeout + 1000);
    flushStore.set('5', 5, Date.now() + timeout + 5000);

    setTimeout(function() {
        assert.plan(1);

        var flushStore = new Store('flush');

        assert.equal(Object.keys(flushStore.get()).length, expected);
    }, timeout);
});

// the the auto flush method on Store initialization
test('new Store ; suppress auto flush expired values', assert => {
    var flushStore = new Store('suppressFlush');
    var expected   = 5;

    flushStore.set('1', 1, Date.now() + timeout - 1000);
    flushStore.set('2', 2, Date.now() + timeout - 100);
    flushStore.set('3', 3, Date.now() + timeout - 50);
    flushStore.set('4', 4, Date.now() + timeout + 1000);
    flushStore.set('5', 5, Date.now() + timeout + 5000);

    setTimeout(function() {
        assert.plan(1);

        var flushStore = new Store('suppressFlush', false);

        assert.equal(Object.keys(flushStore.get()).length, expected);
    }, timeout);
});
<|endoftext|>


<commit_before>var alt = require("../alt-instance");
var SettingsActions = require("../actions/SettingsActions");

var Immutable = require("immutable");
const STORAGE_KEY = "__openlegder__";
const CORE_ASSET = "BTS";

var ls = typeof localStorage === "undefined" ? null : localStorage;

class SettingsStore {
    constructor() {
        this.exportPublicMethods({getSetting: this.getSetting.bind(this)});

        this.settings = Immutable.Map({
            locale: "en",
            connection: "wss://bitshares.openledger.info/ws"
        });

        this.defaultMarkets = Immutable.Map([
            ["BTC_CORE", {"quote":"BTC","base":CORE_ASSET}],
            ["CNY_CORE", {"quote":"CNY","base":CORE_ASSET}],
            ["EUR_CORE", {"quote":"EUR","base":CORE_ASSET}],
            ["GOLD_CORE", {"quote":"GOLD","base":CORE_ASSET}],
            ["SILVER_CORE", {"quote":"SILVER","base":CORE_ASSET}],
            ["USD_CORE", {"quote":"USD","base":CORE_ASSET}],
            ["BTC_USD", {"quote":"BTC","base":"USD"}],
            ["BTC_CNY", {"quote":"BTC","base":"CNY"}]
        ]);

        // If you want a default value to be translated, add the translation to settings in locale-xx.js
        // and use an object {translate: key} in the defaults array
        this.defaults = {
            locale: [
                "en",
                "cn",
                "fr",
                "ko",
                "de",
                "es",
                "tr"
            ],
            connection: [
                "wss://bitshares.openledger.info/ws",
                "ws://127.0.0.1:8091"
            ]
            // confirmMarketOrder: [
            //     {translate: "confirm_yes"},
            //     {translate: "confirm_no"}
            // ]
        };

        this.bindListeners({
            onChangeSetting: SettingsActions.changeSetting,
            onAddMarket: SettingsActions.addMarket,
            onRemoveMarket: SettingsActions.removeMarket,
            onAddWS: SettingsActions.addWS,
            onRemoveWS: SettingsActions.removeWS
        });

        if (this._lsGet("settings_v1")) {
            this.settings = Immutable.Map(JSON.parse(this._lsGet("settings_v1")));
        }

        if (this._lsGet("defaultMarkets")) {
            this.defaultMarkets = Immutable.Map(JSON.parse(this._lsGet("defaultMarkets")));
        }

        if (this._lsGet("defaults")) {
            this.defaults = JSON.parse(this._lsGet("defaults"));
        }
    }

    getSetting(setting) {
        return this.settings.get(setting);
    }

    onChangeSetting(payload) {
        this.settings = this.settings.set(
            payload.setting,
            payload.value
        );

        this._lsSet("settings_v1", this.settings.toJS());
    }

    _lsGet(key) {
        if (ls) {
            return ls.getItem(STORAGE_KEY + key);
        }
    }

    _lsSet(key, object) {
        if (ls) {
            ls.setItem(STORAGE_KEY + key, JSON.stringify(object));
        }

    }

    onAddMarket(market) {
        let marketID = market.quote + "_" + market.base;

        if (!this.defaultMarkets.has(marketID)) {
            this.defaultMarkets = this.defaultMarkets.set(marketID, {quote: market.quote, base: market.base});

            this._lsSet("defaultMarkets", this.defaultMarkets.toJS());
        } else {
            return false;
        }
    }

    onRemoveMarket(market) {
        let marketID = market.quote + "_" + market.base;

        this.defaultMarkets = this.defaultMarkets.delete(marketID);

        this._lsSet("defaultMarkets", this.defaultMarkets.toJS());
    }

    onAddWS(ws) {
        this.defaults.connection.push(ws);
        this._lsSet("defaults", this.defaults);
    }

    onRemoveWS(index) {
        this.defaults.connection.splice(index, 1);
        this._lsSet("defaults", this.defaults);
    }
}

module.exports = alt.createStore(SettingsStore, "SettingsStore");
<commit_msg>improve navigation for new users<commit_after>var alt = require("../alt-instance");
var SettingsActions = require("../actions/SettingsActions");

var Immutable = require("immutable");
const STORAGE_KEY = "__openlegder__";
const CORE_ASSET = "BTS";

var ls = typeof localStorage === "undefined" ? null : localStorage;

class SettingsStore {
    constructor() {
        this.exportPublicMethods({getSetting: this.getSetting.bind(this)});

        this.settings = Immutable.Map({
            locale: "en",
            connection: "wss://bitshares.openledger.info/ws"
        });

        this.defaultMarkets = Immutable.Map([
            ["BTC_CORE", {"quote":"BTC","base":CORE_ASSET}],
            ["CNY_CORE", {"quote":"CNY","base":CORE_ASSET}],
            ["EUR_CORE", {"quote":"EUR","base":CORE_ASSET}],
            ["GOLD_CORE", {"quote":"GOLD","base":CORE_ASSET}],
            ["SILVER_CORE", {"quote":"SILVER","base":CORE_ASSET}],
            ["USD_CORE", {"quote":"USD","base":CORE_ASSET}],
            ["BTC_USD", {"quote":"BTC","base":"USD"}],
            ["BTC_CNY", {"quote":"BTC","base":"CNY"}]
        ]);

        // If you want a default value to be translated, add the translation to settings in locale-xx.js
        // and use an object {translate: key} in the defaults array
        this.defaults = {
            locale: [
                "en",
                "cn",
                "fr",
                "ko",
                "de",
                "es",
                "tr"
            ],
            connection: [
                "wss://bitshares.openledger.info/ws",
                "ws://127.0.0.1:8090"
            ]
            // confirmMarketOrder: [
            //     {translate: "confirm_yes"},
            //     {translate: "confirm_no"}
            // ]
        };

        this.bindListeners({
            onChangeSetting: SettingsActions.changeSetting,
            onAddMarket: SettingsActions.addMarket,
            onRemoveMarket: SettingsActions.removeMarket,
            onAddWS: SettingsActions.addWS,
            onRemoveWS: SettingsActions.removeWS
        });

        if (this._lsGet("settings_v1")) {
            this.settings = Immutable.Map(JSON.parse(this._lsGet("settings_v1")));
        }

        if (this._lsGet("defaultMarkets")) {
            this.defaultMarkets = Immutable.Map(JSON.parse(this._lsGet("defaultMarkets")));
        }

        if (this._lsGet("defaults")) {
            this.defaults = JSON.parse(this._lsGet("defaults"));
        }
    }

    getSetting(setting) {
        return this.settings.get(setting);
    }

    onChangeSetting(payload) {
        this.settings = this.settings.set(
            payload.setting,
            payload.value
        );

        this._lsSet("settings_v1", this.settings.toJS());
    }

    _lsGet(key) {
        if (ls) {
            return ls.getItem(STORAGE_KEY + key);
        }
    }

    _lsSet(key, object) {
        if (ls) {
            ls.setItem(STORAGE_KEY + key, JSON.stringify(object));
        }

    }

    onAddMarket(market) {
        let marketID = market.quote + "_" + market.base;

        if (!this.defaultMarkets.has(marketID)) {
            this.defaultMarkets = this.defaultMarkets.set(marketID, {quote: market.quote, base: market.base});

            this._lsSet("defaultMarkets", this.defaultMarkets.toJS());
        } else {
            return false;
        }
    }

    onRemoveMarket(market) {
        let marketID = market.quote + "_" + market.base;

        this.defaultMarkets = this.defaultMarkets.delete(marketID);

        this._lsSet("defaultMarkets", this.defaultMarkets.toJS());
    }

    onAddWS(ws) {
        this.defaults.connection.push(ws);
        this._lsSet("defaults", this.defaults);
    }

    onRemoveWS(index) {
        this.defaults.connection.splice(index, 1);
        this._lsSet("defaults", this.defaults);
    }
}

module.exports = alt.createStore(SettingsStore, "SettingsStore");
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.View.extend({
  classNames: [ 'pusher' ]
});
<commit_msg>Changed the application view to a Component instead of a view<commit_after>import Ember from 'ember';

export default Ember.Component.extend({
  classNames: [ 'pusher' ]
});
<|endoftext|>


<commit_before>'use strict';

var util = require('util');
var common = require('../modules/common-functions');
var ABOUT_YOU_QUESTIONS = require('../modules/constants').ABOUT_YOU_QUESTIONS;

var OUTCOMES = [
  {
    question: 'on_benefits',
    url: '/benefits'
  },
  {
    question: 'own_property',
    url: '/property'
  },
  {
    question: 'have_savings',
    url: '/savings'
  }
];
var FIELDS_WITH_SUBFIELDS = [
  {
    field_name: 'have_children',
    subfield_name: 'num_children',
    errorText: 'Please specify the number of children you have'
  },
  {
    field_name: 'have_dependants',
    subfield_name: 'num_dependants',
    errorText: 'Please specify the number of dependants you have'
  }
];

module.exports = {
  'Start page': function(client) {
    common.startPage(client);
  },

  'Categories of law (Your problem)': function(client) {
    common.selectDebtCategory(client);
  },

  'About you': function(client) {
    client
      .assert.urlContains('/about')
      .assert.containsText('h1', 'About you')
    ;

    // test validation
    common.submitAndCheckForError(client, 'This form has errors.\nPlease correct them and try again');
    ABOUT_YOU_QUESTIONS.forEach(function(item) {
      common.submitAndCheckForFieldError(client, item, 'Not a valid choice');
    });
    FIELDS_WITH_SUBFIELDS.forEach(function(item) {
      common.aboutYouSetAllToNo(client);
      client
        .verify.hidden(util.format('input[name="%s"]', item.subfield_name))
        .click(util.format('input[name="%s"][value="%s"]', item.field_name, 1))
        .verify.visible(util.format('input[name="%s"]', item.subfield_name))
        .submitForm('form')
      ;
      common.submitAndCheckForFieldError(client, item.field_name, item.errorText);
    });

    // test outcomes
    common.aboutYouSetAllToNo(client);
    client
      .submitForm('form')
      .verify.urlContains('/income', 'Goes to /income when all answers are No')
      .url(client.launch_url + '/about')
    ;
    OUTCOMES.forEach(function(item) {
      common.aboutYouSetAllToNo(client);
      client
        .click(util.format('input[name="%s"][value="%s"]', item.question, 1))
        .submitForm('form')
        .verify.urlContains(item.url, util.format('Goes to %s when %s is Yes', item.url, item.question))
        .back()
      ;
    });

    client.end();
  }
};
<commit_msg>redundant line<commit_after>'use strict';

var util = require('util');
var common = require('../modules/common-functions');
var ABOUT_YOU_QUESTIONS = require('../modules/constants').ABOUT_YOU_QUESTIONS;

var OUTCOMES = [
  {
    question: 'on_benefits',
    url: '/benefits'
  },
  {
    question: 'own_property',
    url: '/property'
  },
  {
    question: 'have_savings',
    url: '/savings'
  }
];
var FIELDS_WITH_SUBFIELDS = [
  {
    field_name: 'have_children',
    subfield_name: 'num_children',
    errorText: 'Please specify the number of children you have'
  },
  {
    field_name: 'have_dependants',
    subfield_name: 'num_dependants',
    errorText: 'Please specify the number of dependants you have'
  }
];

module.exports = {
  'Start page': function(client) {
    common.startPage(client);
  },

  'Categories of law (Your problem)': function(client) {
    common.selectDebtCategory(client);
  },

  'About you': function(client) {
    client
      .assert.urlContains('/about')
      .assert.containsText('h1', 'About you')
    ;

    // test validation
    common.submitAndCheckForError(client, 'This form has errors.\nPlease correct them and try again');
    ABOUT_YOU_QUESTIONS.forEach(function(item) {
      common.submitAndCheckForFieldError(client, item, 'Not a valid choice');
    });
    FIELDS_WITH_SUBFIELDS.forEach(function(item) {
      common.aboutYouSetAllToNo(client);
      client
        .verify.hidden(util.format('input[name="%s"]', item.subfield_name))
        .click(util.format('input[name="%s"][value="%s"]', item.field_name, 1))
        .verify.visible(util.format('input[name="%s"]', item.subfield_name))
      ;
      common.submitAndCheckForFieldError(client, item.field_name, item.errorText);
    });

    // test outcomes
    common.aboutYouSetAllToNo(client);
    client
      .submitForm('form')
      .verify.urlContains('/income', 'Goes to /income when all answers are No')
      .url(client.launch_url + '/about')
    ;
    OUTCOMES.forEach(function(item) {
      common.aboutYouSetAllToNo(client);
      client
        .click(util.format('input[name="%s"][value="%s"]', item.question, 1))
        .submitForm('form')
        .verify.urlContains(item.url, util.format('Goes to %s when %s is Yes', item.url, item.question))
        .back()
      ;
    });

    client.end();
  }
};
<|endoftext|>


<commit_before>import { VASTClient } from '../src/vast_client';
import { VASTTracker } from '../src/vast_tracker';
import { inlineTrackersParsed } from '../spec/samples/inline_trackers';

const vastClient = new VASTClient();

describe('VASTTracker', function() {
  let vastTracker = null;

  describe('#linear', () => {
    let spyEmitter;
    let spyTrackUrl;
    let adTrackingUrls;
    let ad;
    const expectedMacros = {
      ASSETURI: 'http%3A%2F%2Fexample.com%2Flinear-asset.mp4',
      UNIVERSALADID: 'sample-registry%20000123',
      PODSEQUENCE: '1',
      ADSERVINGID: 'z292x16y-3d7f-6440-bd29-2ec0f153fc89',
      ADTYPE: 'video',
      ADCATEGORIES: 'Category-A%2CCategory-B%2CCategory-C'
    };
    beforeEach(() => {
      ad = inlineTrackersParsed.ads[0];
      adTrackingUrls = ad.creatives[0].trackingEvents;
      vastTracker = new VASTTracker(vastClient, ad, ad.creatives[0]);
      spyEmitter = jest.spyOn(vastTracker, 'emit');
      spyTrackUrl = jest.spyOn(vastTracker, 'trackURLs');
    });

    describe('#click', () => {
      beforeEach(() => {
        vastTracker.setProgress(60 * 75 + 5.25);
        vastTracker.click();
      });
      it('should have emitted click event and called trackUrl', () => {
        expect(spyEmitter).toHaveBeenCalledWith(
          'clickthrough',
          'http://example.com/linear-clickthrough_adplayhead:01%3A15%3A05.250'
        );

        expect(spyTrackUrl).toHaveBeenCalledWith(
          ad.creatives[0].videoClickTrackingURLTemplates,
          expect.objectContaining({
            ...expectedMacros,
            ADPLAYHEAD: '01%3A15%3A05.250'
          })
        );
      });
    });

    describe('#minimize', () => {
      beforeEach(() => {
        vastTracker.minimize();
      });
      it('should be defined', () => {
        expect(adTrackingUrls.minimize).toBeDefined();
      });
      it('should have emitted minimize event and called trackUrl', () => {
        expect(spyEmitter).toHaveBeenCalledWith('minimize', {
          trackingURLTemplates: adTrackingUrls.minimize
        });

        expect(spyTrackUrl).toHaveBeenCalledWith(
          adTrackingUrls.minimize,
          expect.objectContaining(expectedMacros)
        );
      });
    });

    describe('#verificationNotExecuted', () => {
      let verificationUrl;
      let reasonMacro = { REASON: 3 };
      const vendor = 'company.com-omid';
      beforeEach(() => {
        verificationUrl =
          ad.adVerifications[0].trackingEvents.verificationNotExecuted;
        vastTracker.verificationNotExecuted(vendor, reasonMacro);
      });
      it('should be defined', () => {
        expect(verificationUrl).toBeDefined();
      });
      it('should have emitted verificationNotExecuted event and called trackUrl', () => {
        expect(spyTrackUrl).toHaveBeenCalledWith(
          verificationUrl,
          expect.objectContaining(reasonMacro)
        );
        expect(spyEmitter).toHaveBeenCalledWith('verificationNotExecuted', {
          trackingURLTemplates: verificationUrl
        });
      });
      it('should throw missing AdVerification vendor error', () => {
        const vendor = ad.adVerifications[0].vendor;
        ad.adVerifications[0].vendor = null;
        expect(() => {
          vastTracker.verificationNotExecuted(vendor, reasonMacro);
        }).toThrowError(
          'No associated verification element found for vendor: company.com-omid'
        );
        ad.adVerifications[0].vendor = vendor;
      });
      it('should throw missing AdVerification error', () => {
        ad.adVerifications.length = 0;
        expect(() => {
          vastTracker.verificationNotExecuted(vendor, reasonMacro);
        }).toThrowError('No adVerifications provided');
      });
    });

    describe('#otherAdInteraction', () => {
      beforeEach(() => {
        vastTracker.otherAdInteraction();
      });
      it('should be defined', () => {
        expect(adTrackingUrls.otherAdInteraction).toBeDefined();
      });
      it('should have emitted otherAdInteraction event and called trackUrl', () => {
        expect(spyEmitter).toHaveBeenCalledWith('otherAdInteraction', {
          trackingURLTemplates: adTrackingUrls.otherAdInteraction
        });
        expect(spyTrackUrl).toHaveBeenCalledWith(
          adTrackingUrls.otherAdInteraction,
          expect.objectContaining(expectedMacros)
        );
      });
    });

    describe('#acceptInvitation', () => {
      beforeEach(() => {
        vastTracker.acceptInvitation();
      });
      it('should be defined', () => {
        expect(adTrackingUrls.acceptInvitation).toBeDefined();
      });
      it('should have emitted acceptInvitation event and called trackUrl', () => {
        expect(spyEmitter).toHaveBeenCalledWith('acceptInvitation', {
          trackingURLTemplates: adTrackingUrls.acceptInvitation
        });
        expect(spyTrackUrl).toHaveBeenCalledWith(
          adTrackingUrls.acceptInvitation,
          expect.objectContaining(expectedMacros)
        );
      });
    });

    describe('#adExpand', () => {
      beforeEach(() => {
        vastTracker.adExpand();
      });
      it('should be defined', () => {
        expect(adTrackingUrls.adExpand).toBeDefined();
      });
      it('should have emitted adExpand event and called trackUrl', () => {
        expect(spyEmitter).toHaveBeenCalledWith('adExpand', {
          trackingURLTemplates: adTrackingUrls.adExpand
        });
        expect(spyTrackUrl).toHaveBeenCalledWith(
          adTrackingUrls.adExpand,
          expect.objectContaining(expectedMacros)
        );
      });
    });

    describe('#adCollapse', () => {
      beforeEach(() => {
        vastTracker.adCollapse();
      });
      it('should be defined', () => {
        expect(adTrackingUrls.adCollapse).toBeDefined();
      });
      it('should have emitted adCollapse event and called trackUrl', () => {
        expect(spyEmitter).toHaveBeenCalledWith('adCollapse', {
          trackingURLTemplates: adTrackingUrls.adCollapse
        });
        expect(spyTrackUrl).toHaveBeenCalledWith(
          adTrackingUrls.adCollapse,
          expect.objectContaining(expectedMacros)
        );
      });
    });

    describe('#overlayViewDuration', () => {
      beforeEach(() => {
        vastTracker.overlayViewDuration('00:00:30', {
          CONTENTPLAYHEAD: '00:00:40',
          MEDIAPLAYHEAD: '00:00:40'
        });
      });
      it('should be defined', () => {
        expect(adTrackingUrls.overlayViewDuration).toBeDefined();
      });
      it('should have emitted adExpand event and called trackUrl', () => {
        expect(spyEmitter).toHaveBeenCalledWith('overlayViewDuration', {
          trackingURLTemplates: adTrackingUrls.overlayViewDuration
        });
        expect(spyTrackUrl).toHaveBeenCalledWith(
          adTrackingUrls.overlayViewDuration,
          expect.objectContaining({
            ...expectedMacros,
            ADPLAYHEAD: '00%3A00%3A30',
            CONTENTPLAYHEAD: '00%3A00%3A40',
            MEDIAPLAYHEAD: '00%3A00%3A40'
          })
        );
      });
    });

    describe('#notUsed', () => {
      it('should be defined', () => {
        expect(adTrackingUrls.notUsed).toBeDefined();
      });
      it('should have emitted adExpand event, called trackUrl and not emitted any other event', () => {
        vastTracker.notUsed();
        vastTracker.adCollapse();

        expect(spyEmitter).toHaveBeenCalledWith('notUsed', {
          trackingURLTemplates: adTrackingUrls.notUsed
        });
        expect(spyTrackUrl).toHaveBeenCalledWith(
          adTrackingUrls.notUsed,
          expect.objectContaining(expectedMacros)
        );
        expect(spyEmitter).toHaveBeenCalledTimes(1);
      });
    });

    describe('setProgress', () => {
      let spyTrack;
      let lastMock;
      beforeEach(() => {
        spyTrack = jest.spyOn(vastTracker, 'track');
        vastTracker.assetDuration = 10;
        //  vastTracker.lastDuration = 40;
        vastTracker.setProgress(5);
      });
      it('call track with progress-5', () => {
        expect(spyTrack).toHaveBeenCalledWith('progress-5', expect.anything());
      });

      it('call track with progress-50%', () => {
        expect(spyTrack).toHaveBeenCalledWith(
          'progress-50%',
          expect.anything()
        );
      });
      it('should have a lastPercentage variable', () => {
        expect(vastTracker.lastPercentage).toBeDefined();
      });
    });
  });
});
<commit_msg>added some tests, deleted dead code<commit_after>import { VASTClient } from '../src/vast_client';
import { VASTTracker } from '../src/vast_tracker';
import { inlineTrackersParsed } from '../spec/samples/inline_trackers';

const vastClient = new VASTClient();

describe('VASTTracker', function() {
  let vastTracker = null;

  describe('#linear', () => {
    let spyEmitter;
    let spyTrackUrl;
    let adTrackingUrls;
    let ad;
    const expectedMacros = {
      ASSETURI: 'http%3A%2F%2Fexample.com%2Flinear-asset.mp4',
      UNIVERSALADID: 'sample-registry%20000123',
      PODSEQUENCE: '1',
      ADSERVINGID: 'z292x16y-3d7f-6440-bd29-2ec0f153fc89',
      ADTYPE: 'video',
      ADCATEGORIES: 'Category-A%2CCategory-B%2CCategory-C'
    };
    beforeEach(() => {
      ad = inlineTrackersParsed.ads[0];
      adTrackingUrls = ad.creatives[0].trackingEvents;
      vastTracker = new VASTTracker(vastClient, ad, ad.creatives[0]);
      spyEmitter = jest.spyOn(vastTracker, 'emit');
      spyTrackUrl = jest.spyOn(vastTracker, 'trackURLs');
    });

    describe('#click', () => {
      beforeEach(() => {
        vastTracker.setProgress(60 * 75 + 5.25);
        vastTracker.click();
      });
      it('should have emitted click event and called trackUrl', () => {
        expect(spyEmitter).toHaveBeenCalledWith(
          'clickthrough',
          'http://example.com/linear-clickthrough_adplayhead:01%3A15%3A05.250'
        );

        expect(spyTrackUrl).toHaveBeenCalledWith(
          ad.creatives[0].videoClickTrackingURLTemplates,
          expect.objectContaining({
            ...expectedMacros,
            ADPLAYHEAD: '01%3A15%3A05.250'
          })
        );
      });
    });

    describe('#minimize', () => {
      beforeEach(() => {
        vastTracker.minimize();
      });
      it('should be defined', () => {
        expect(adTrackingUrls.minimize).toBeDefined();
      });
      it('should have emitted minimize event and called trackUrl', () => {
        expect(spyEmitter).toHaveBeenCalledWith('minimize', {
          trackingURLTemplates: adTrackingUrls.minimize
        });

        expect(spyTrackUrl).toHaveBeenCalledWith(
          adTrackingUrls.minimize,
          expect.objectContaining(expectedMacros)
        );
      });
    });

    describe('#verificationNotExecuted', () => {
      let verificationUrl;
      let reasonMacro = { REASON: 3 };
      const vendor = 'company.com-omid';
      beforeEach(() => {
        verificationUrl =
          ad.adVerifications[0].trackingEvents.verificationNotExecuted;
        vastTracker.verificationNotExecuted(vendor, reasonMacro);
      });
      it('should be defined', () => {
        expect(verificationUrl).toBeDefined();
      });
      it('should have emitted verificationNotExecuted event and called trackUrl', () => {
        expect(spyTrackUrl).toHaveBeenCalledWith(
          verificationUrl,
          expect.objectContaining(reasonMacro)
        );
        expect(spyEmitter).toHaveBeenCalledWith('verificationNotExecuted', {
          trackingURLTemplates: verificationUrl
        });
      });
      it('should throw missing AdVerification vendor error', () => {
        const vendor = ad.adVerifications[0].vendor;
        ad.adVerifications[0].vendor = null;
        expect(() => {
          vastTracker.verificationNotExecuted(vendor, reasonMacro);
        }).toThrowError(
          'No associated verification element found for vendor: company.com-omid'
        );
        ad.adVerifications[0].vendor = vendor;
      });
      it('should throw missing AdVerification error', () => {
        ad.adVerifications.length = 0;
        expect(() => {
          vastTracker.verificationNotExecuted(vendor, reasonMacro);
        }).toThrowError('No adVerifications provided');
      });
    });

    describe('#otherAdInteraction', () => {
      beforeEach(() => {
        vastTracker.otherAdInteraction();
      });
      it('should be defined', () => {
        expect(adTrackingUrls.otherAdInteraction).toBeDefined();
      });
      it('should have emitted otherAdInteraction event and called trackUrl', () => {
        expect(spyEmitter).toHaveBeenCalledWith('otherAdInteraction', {
          trackingURLTemplates: adTrackingUrls.otherAdInteraction
        });
        expect(spyTrackUrl).toHaveBeenCalledWith(
          adTrackingUrls.otherAdInteraction,
          expect.objectContaining(expectedMacros)
        );
      });
    });

    describe('#acceptInvitation', () => {
      beforeEach(() => {
        vastTracker.acceptInvitation();
      });
      it('should be defined', () => {
        expect(adTrackingUrls.acceptInvitation).toBeDefined();
      });
      it('should have emitted acceptInvitation event and called trackUrl', () => {
        expect(spyEmitter).toHaveBeenCalledWith('acceptInvitation', {
          trackingURLTemplates: adTrackingUrls.acceptInvitation
        });
        expect(spyTrackUrl).toHaveBeenCalledWith(
          adTrackingUrls.acceptInvitation,
          expect.objectContaining(expectedMacros)
        );
      });
    });

    describe('#adExpand', () => {
      beforeEach(() => {
        vastTracker.adExpand();
      });
      it('should be defined', () => {
        expect(adTrackingUrls.adExpand).toBeDefined();
      });
      it('should have emitted adExpand event and called trackUrl', () => {
        expect(spyEmitter).toHaveBeenCalledWith('adExpand', {
          trackingURLTemplates: adTrackingUrls.adExpand
        });
        expect(spyTrackUrl).toHaveBeenCalledWith(
          adTrackingUrls.adExpand,
          expect.objectContaining(expectedMacros)
        );
      });
    });

    describe('#adCollapse', () => {
      beforeEach(() => {
        vastTracker.adCollapse();
      });
      it('should be defined', () => {
        expect(adTrackingUrls.adCollapse).toBeDefined();
      });
      it('should have emitted adCollapse event and called trackUrl', () => {
        expect(spyEmitter).toHaveBeenCalledWith('adCollapse', {
          trackingURLTemplates: adTrackingUrls.adCollapse
        });
        expect(spyTrackUrl).toHaveBeenCalledWith(
          adTrackingUrls.adCollapse,
          expect.objectContaining(expectedMacros)
        );
      });
    });

    describe('#overlayViewDuration', () => {
      beforeEach(() => {
        vastTracker.overlayViewDuration('00:00:30', {
          CONTENTPLAYHEAD: '00:00:40',
          MEDIAPLAYHEAD: '00:00:40'
        });
      });
      it('should be defined', () => {
        expect(adTrackingUrls.overlayViewDuration).toBeDefined();
      });
      it('should have emitted adExpand event and called trackUrl', () => {
        expect(spyEmitter).toHaveBeenCalledWith('overlayViewDuration', {
          trackingURLTemplates: adTrackingUrls.overlayViewDuration
        });
        expect(spyTrackUrl).toHaveBeenCalledWith(
          adTrackingUrls.overlayViewDuration,
          expect.objectContaining({
            ...expectedMacros,
            ADPLAYHEAD: '00%3A00%3A30',
            CONTENTPLAYHEAD: '00%3A00%3A40',
            MEDIAPLAYHEAD: '00%3A00%3A40'
          })
        );
      });
    });

    describe('#notUsed', () => {
      it('should be defined', () => {
        expect(adTrackingUrls.notUsed).toBeDefined();
      });
      it('should have emitted adExpand event, called trackUrl and not emitted any other event', () => {
        vastTracker.notUsed();
        vastTracker.adCollapse();

        expect(spyEmitter).toHaveBeenCalledWith('notUsed', {
          trackingURLTemplates: adTrackingUrls.notUsed
        });
        expect(spyTrackUrl).toHaveBeenCalledWith(
          adTrackingUrls.notUsed,
          expect.objectContaining(expectedMacros)
        );
        expect(spyEmitter).toHaveBeenCalledTimes(1);
      });
    });

    describe('setProgress', () => {
      let spyTrack;
      let lastMock;
      beforeEach(() => {
        spyTrack = jest.spyOn(vastTracker, 'track');
        vastTracker.assetDuration = 10;
        vastTracker.setProgress(5);
      });
      it('should be defined', () => {
        expect(vastTracker.setProgress).toBeDefined();
      });
      it('call track with progress-5', () => {
        expect(spyTrack).toHaveBeenCalledWith('progress-5', expect.anything());
      });

      it('call track with progress-50%', () => {
        expect(spyTrack).toHaveBeenCalledWith(
          'progress-50%',
          expect.anything()
        );
      });
      it('should have a lastPercentage variable', () => {
        expect(vastTracker.lastPercentage).toBeDefined();
      });
      it('should make the lastPercentage variable at the value -1', () => {
        vastTracker.lastPercentage = 1;
        expect(spyTrack).toHaveBeenCalledWith('progress-4%', expect.anything());
      });
    });
  });
});
<|endoftext|>


<commit_before>// Importing libraries
var express = require('express');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

// Big security hole, but makes all files availiable from the outside.
// Quickfix for us.
// We will fix this hole later. But it works for the first demo.
app.use('/', express.static(__dirname + '/'));

var teacherid;
var connectedstudents = [];

// Now we will connect the users to socket.io.
// Socket io is a library that maintains and keeps track of connected users.
// We added things to student.html and student.js to make it work.

// This creates a connection to the
io.on('connection',function(socket){

  // Creates events for the existing connection

  socket.on('usertype',function(type){
    // Checks if the type of person connected is using the javascript from the
    // student page or the teacher page, and decides further actions based on
    // this.
    if (type == 'student'){
      console.log('Student has logged on');
      io.to(teacherid).emit('update',feedbackcalculator());
      socket.slower = false;
      socket.faster = false;
      connectedstudents.push(socket);
      // Creates a listener for a signal with a name that MAY contain data.
      // Basically an eventlistener across pages.
      socket.on('slower',function(){
        console.log('Student pressed slower button');
        // send message to teacher:
        socket.slower = true;
        socket.faster = false;
        io.to(teacherid).emit('update',feedbackcalculator());
      });
      socket.on('faster',function(){
        console.log('Student pressed faster button');
        socket.faster = true;
        socket.slower = false;
        io.to(teacherid).emit('update',feedbackcalculator());
      });
      socket.on('disconnect',function(){
          for (var i = 0; i<connectedstudents.length;i++){
            if ( connectedstudents[i].id == socket.id){
              connectedstudents.splice(i,1);
            }
          };
          io.to(teacherid).emit('update',feedbackcalculator());
      });
    }
    else{
      console.log('Teacher has logged on');
      // detects the socket id from the teacher connection and sets it.
      teacherid = socket.id;
    }
  });
});

function feedbackcalculator(){
  var slower = 0;
  var faster = 0;
  for (var i = 0; i<connectedstudents.length;i++){
    var student = connectedstudents[i];
    if (student.slower == true){
      slower += 1;
    };
    if (student.faster == true){
      faster += 1;
    };
  };

  return {
    slower:slower,
    faster:faster,
    students:connectedstudents.length,
  }
};

// Starts the server on port 3000.
http.listen(3000, function(){
  console.log('listening on *:3000');
});
<commit_msg>deleted app folder in node folder. Old folder structure and server file<commit_after><|endoftext|>


<commit_before><commit_msg>Factor out distance threshold as a constant, and reduce it a little.<commit_after><|endoftext|>


<commit_before><commit_msg>typo fixes in auth plugin<commit_after><|endoftext|>


<commit_before><commit_msg>show new timeline elements a bit earlier<commit_after><|endoftext|>


<commit_before>//a thin wrapper around tiny-lr module
var log = require('bole')('budo')
var xtend = require('xtend')
var tinylr = require('tiny-lr')

module.exports = function(glob, opt) {
  opt = xtend(opt)
  opt.host = opt.host || 'localhost'
  if (typeof opt.port !== 'number')
    opt.port = 35729

  var server = tinylr()
  var closed = false

  server.listen(opt.port, opt.host, function(a) {
    if (closed)
      return
    log.info('livereload running on ' + opt.port)
  })

  var serverImpl = server.server
  serverImpl.removeAllListeners('error')
  serverImpl.on('error', function(err) {
    if (err.code === 'EADDRINUSE') {
      process.stderr.write('ERROR: livereload not started, port ' + opt.port + ' is in use\n')
      server.close()
      closed = true
    }
  })

  return {
    close: function close() {
      if (closed)
        return
      server.close()
      closed = true
    },

    reload: function reload(path) {
      try {
        server.changed({
          body: {
            files: [path]
          }
        })
      } catch (e) {
        throw e
      }
    }
  }
}<commit_msg>fixed tinylr params<commit_after>//a thin wrapper around tiny-lr module
var log = require('bole')('budo')
var xtend = require('xtend')
var tinylr = require('tiny-lr')

module.exports = function(opt) {
  opt = xtend(opt)
  opt.host = opt.host || 'localhost'
  if (typeof opt.port !== 'number')
    opt.port = 35729

  var server = tinylr()
  var closed = false

  server.listen(opt.port, opt.host, function(a) {
    if (closed)
      return
    log.info('livereload running on ' + opt.port)
  })

  var serverImpl = server.server
  serverImpl.removeAllListeners('error')
  serverImpl.on('error', function(err) {
    if (err.code === 'EADDRINUSE') {
      process.stderr.write('ERROR: livereload not started, port ' + opt.port + ' is in use\n')
      server.close()
      closed = true
    }
  })

  return {
    close: function close() {
      if (closed)
        return
      server.close()
      closed = true
    },

    reload: function reload(path) {
      try {
        server.changed({
          body: {
            files: [path]
          }
        })
      } catch (e) {
        throw e
      }
    }
  }
}<|endoftext|>


<commit_before>var current_page;
var responses_expected = 0;
var response_counter = 0;
var total_submission_list = [];

self.port.on("show", function onShow(url) {
	reset();
	current_page = url;
	getAllSubmissions(url);
});

self.port.on("hide", function onHide() {
	var e_links = document.getElementById("links");
	while (e_links.firstChild) {
		e_links.removeChild(e_links.firstChild);
	}
});

function reset(){
	current_page = "";
	responses_expected = 0;
	response_counter = 0;
	total_submission_list = [];
	document.getElementById("loading").style.display = "block";
}

function getAllSubmissions(url){
	var reddit_urls = getAllURLVersions(url);
	responses_expected = reddit_urls.length;

	for(var i=0; reddit_url = reddit_urls[i]; i++) {
		getJSON(reddit_url, handleResponse);
	}
}

function getAllURLVersions(url){
	var without_http = "";
	var result = ['http://www.reddit.com/api/info.json?url=' + encodeURIComponent(url)];
	if (url.indexOf('https') === 0) {
		without_http = url.substring(5);
		result.push('http://www.reddit.com/api/info.json?url=' + encodeURIComponent(without_http));
		result.push('http://www.reddit.com/api/info.json?url=' + encodeURIComponent("http://" + without_http));
	}
	else{
		if (url.indexOf('http') === 0) {
			without_http = url.substring(4);
			result.push('http://www.reddit.com/api/info.json?url=' + encodeURIComponent(without_http));
			result.push('http://www.reddit.com/api/info.json?url=' + encodeURIComponent("https://" + without_http));
		}
		else{
			result.push('http://www.reddit.com/api/info.json?url=' + encodeURIComponent("http://" + without_http));
			result.push('http://www.reddit.com/api/info.json?url=' + encodeURIComponent("https://" + without_http));
		}
	}
	return result;
}

function handleResponse(jsonData){
	var now = new Date();
	var now_timestamp = now.getTime();// = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
	var submissions = [];
	for(var i=0; entry = jsonData.data.children[i]; i++) {
		submission_timestamp = entry.data.created_utc*1000;
		submissions[i] = {
			link: "http://reddit.com" + entry.data.permalink,
			title: entry.data.title,
			score: entry.data.score+"",
			age: (now_timestamp - submission_timestamp),
			comments: entry.data.num_comments+"",
			subreddit: entry.data.subreddit,
		};
	}
	total_submission_list.push.apply(total_submission_list, submissions);

	response_counter++;
	if(response_counter === responses_expected){
		document.getElementById("loading").style.display = "none";
		putSubmissionsIntoUI(total_submission_list);
	}
}

function putSubmissionsIntoUI(submissions){
	if(submissions.length === 0){
		var t_nonefound = document.createTextNode("This page hasn't been submitted to reddit, yet.");
		var t_submit = document.createTextNode("Create submission");

		var e_nonefound = document.createElement("div");
		e_nonefound.setAttribute("align", "center");
		e_nonefound.setAttribute("style", "font-size: 140% !important");
		e_nonefound.appendChild(t_nonefound);

		var e_submit = document.createElement("div");
		e_submit.setAttribute("class", "submitbutton");
		e_submit.appendChild(t_submit);

		e_submit.onclick = function() {
			openLinkInNewTab("http://www.reddit.com/submit?url=" + encodeURIComponent(current_page));
		};

		document.getElementById("links").appendChild(e_nonefound);
		document.getElementById("links").appendChild(e_submit);
	}
	else{
		for(var i=0; submission = submissions[i]; i++) {
			var t_score = document.createTextNode(submission.score);
			var t_title = document.createTextNode(submission.title);
			var t_subreddit = document.createTextNode("/r/" + submission.subreddit);
			var t_comments = document.createTextNode(submission.comments + " comments");
			var t_time = document.createTextNode(formatAge(submission.age));

			var e_submission = document.createElement("div");
			e_submission.setAttribute("class", "submission");

			var e_score = document.createElement("div");
			e_score.setAttribute("class", "score");
			e_score.setAttribute("align", "center");
			e_score.appendChild(t_score);

			var e_title = document.createElement("div");
			e_title.setAttribute("class", "title");
			e_title.appendChild(t_title);

			var e_infocontainer = document.createElement("div");

			var e_subreddit = document.createElement("div");
			e_subreddit.setAttribute("class", "subreddit");
			e_subreddit.appendChild(t_subreddit);

			var e_comments = document.createElement("div");
			e_comments.setAttribute("class", "comment");
			e_comments.appendChild(t_comments);

			var e_time = document.createElement("div");
			e_time.setAttribute("class", "time");
			e_time.appendChild(t_time);

			e_infocontainer.appendChild(e_subreddit);
			e_infocontainer.appendChild(e_comments);
			e_infocontainer.appendChild(e_time);

			e_submission.appendChild(e_score);
			e_submission.appendChild(e_title);
			e_submission.appendChild(e_infocontainer);

			var s = submission
			e_submission.onclick = function() {
				openLinkInNewTab(s.link);
			};

			document.getElementById("links").appendChild(e_submission);
		}
	}
}

function formatAge(age){
	var MINUTE = 60 * 1000;
	var HOUR = MINUTE * 60;
	var DAY = HOUR * 24;
	var WEEK = DAY * 7;
	var YEAR = WEEK * 52;
	var MONTH = YEAR / 12;
	if (age < MINUTE) {
		return age + " seconds ago";
	} else if(age < HOUR) {
		return Math.floor(age / MINUTE) + " minutes ago";
	} else if(age < DAY) {
		return Math.floor(age / HOUR) + " hours ago";
	} else if(age < WEEK) {
		return Math.floor(age / DAY) + " days ago";
	} else if(age < MONTH) {
		return Math.floor(age / WEEK) + " weeks ago";
	} else if(age < YEAR) {
		return Math.floor(age / MONTH) + " months ago";
	} else {
		return Math.floor(age / YEAR) + " years ago";
	}
}

function openLinkInNewTab(url){
	self.port.emit("open-link", url);
}

function getJSON(path, success)
{
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function()
    {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
                if (success)
                    success(JSON.parse(xhr.responseText));
            }
        }
    };
    xhr.open("GET", path, true);
    xhr.send();
}

<commit_msg>fix getAllURLVersions<commit_after>var current_page;
var responses_expected = 0;
var response_counter = 0;
var total_submission_list = [];

self.port.on("show", function onShow(url) {
	reset();
	current_page = url;
	getAllSubmissions(url);
});

self.port.on("hide", function onHide() {
	var e_links = document.getElementById("links");
	while (e_links.firstChild) {
		e_links.removeChild(e_links.firstChild);
	}
});

function reset(){
	current_page = "";
	responses_expected = 0;
	response_counter = 0;
	total_submission_list = [];
	document.getElementById("loading").style.display = "block";
}

function getAllSubmissions(url){
	var reddit_urls = getAllURLVersions(url);
	responses_expected = reddit_urls.length;

	for(var i=0; reddit_url = reddit_urls[i]; i++) {
		getJSON(reddit_url, handleResponse);
	}
}

function getAllURLVersions(url){
	var without_http = "";
	var result = ['http://www.reddit.com/api/info.json?url=' + encodeURIComponent(url)];
	if (url.indexOf('https') === 0) {
		without_http = url.substring(5);
		result.push('http://www.reddit.com/api/info.json?url=' + encodeURIComponent(without_http));
		result.push('http://www.reddit.com/api/info.json?url=' + encodeURIComponent("http" + without_http));
	}
	else{
		if (url.indexOf('http') === 0) {
			without_http = url.substring(4);
			result.push('http://www.reddit.com/api/info.json?url=' + encodeURIComponent(without_http));
			result.push('http://www.reddit.com/api/info.json?url=' + encodeURIComponent("https" + without_http));
		}
		else{
			result.push('http://www.reddit.com/api/info.json?url=' + encodeURIComponent("http" + without_http));
			result.push('http://www.reddit.com/api/info.json?url=' + encodeURIComponent("https" + without_http));
		}
	}
	return result;
}

function handleResponse(jsonData){
	var now = new Date();
	var now_timestamp = now.getTime();// = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
	var submissions = [];
	for(var i=0; entry = jsonData.data.children[i]; i++) {
		submission_timestamp = entry.data.created_utc*1000;
		submissions[i] = {
			link: "http://reddit.com" + entry.data.permalink,
			title: entry.data.title,
			score: entry.data.score+"",
			age: (now_timestamp - submission_timestamp),
			comments: entry.data.num_comments+"",
			subreddit: entry.data.subreddit,
		};
	}
	total_submission_list.push.apply(total_submission_list, submissions);

	response_counter++;
	if(response_counter === responses_expected){
		document.getElementById("loading").style.display = "none";
		putSubmissionsIntoUI(total_submission_list);
	}
}

function putSubmissionsIntoUI(submissions){
	if(submissions.length === 0){
		var t_nonefound = document.createTextNode("This page hasn't been submitted to reddit, yet.");
		var t_submit = document.createTextNode("Create submission");

		var e_nonefound = document.createElement("div");
		e_nonefound.setAttribute("align", "center");
		e_nonefound.setAttribute("style", "font-size: 140% !important");
		e_nonefound.appendChild(t_nonefound);

		var e_submit = document.createElement("div");
		e_submit.setAttribute("class", "submitbutton");
		e_submit.appendChild(t_submit);

		e_submit.onclick = function() {
			openLinkInNewTab("http://www.reddit.com/submit?url=" + encodeURIComponent(current_page));
		};

		document.getElementById("links").appendChild(e_nonefound);
		document.getElementById("links").appendChild(e_submit);
	}
	else{
		for(var i=0; submission = submissions[i]; i++) {
			var t_score = document.createTextNode(submission.score);
			var t_title = document.createTextNode(submission.title);
			var t_subreddit = document.createTextNode("/r/" + submission.subreddit);
			var t_comments = document.createTextNode(submission.comments + " comments");
			var t_time = document.createTextNode(formatAge(submission.age));

			var e_submission = document.createElement("div");
			e_submission.setAttribute("class", "submission");

			var e_score = document.createElement("div");
			e_score.setAttribute("class", "score");
			e_score.setAttribute("align", "center");
			e_score.appendChild(t_score);

			var e_title = document.createElement("div");
			e_title.setAttribute("class", "title");
			e_title.appendChild(t_title);

			var e_infocontainer = document.createElement("div");

			var e_subreddit = document.createElement("div");
			e_subreddit.setAttribute("class", "subreddit");
			e_subreddit.appendChild(t_subreddit);

			var e_comments = document.createElement("div");
			e_comments.setAttribute("class", "comment");
			e_comments.appendChild(t_comments);

			var e_time = document.createElement("div");
			e_time.setAttribute("class", "time");
			e_time.appendChild(t_time);

			e_infocontainer.appendChild(e_subreddit);
			e_infocontainer.appendChild(e_comments);
			e_infocontainer.appendChild(e_time);

			e_submission.appendChild(e_score);
			e_submission.appendChild(e_title);
			e_submission.appendChild(e_infocontainer);

			var s = submission
			e_submission.onclick = function() {
				openLinkInNewTab(s.link);
			};

			document.getElementById("links").appendChild(e_submission);
		}
	}
}

function formatAge(age){
	var MINUTE = 60 * 1000;
	var HOUR = MINUTE * 60;
	var DAY = HOUR * 24;
	var WEEK = DAY * 7;
	var YEAR = WEEK * 52;
	var MONTH = YEAR / 12;
	if (age < MINUTE) {
		return age + " seconds ago";
	} else if(age < HOUR) {
		return Math.floor(age / MINUTE) + " minutes ago";
	} else if(age < DAY) {
		return Math.floor(age / HOUR) + " hours ago";
	} else if(age < WEEK) {
		return Math.floor(age / DAY) + " days ago";
	} else if(age < MONTH) {
		return Math.floor(age / WEEK) + " weeks ago";
	} else if(age < YEAR) {
		return Math.floor(age / MONTH) + " months ago";
	} else {
		return Math.floor(age / YEAR) + " years ago";
	}
}

function openLinkInNewTab(url){
	self.port.emit("open-link", url);
}

function getJSON(path, success)
{
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function()
    {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
                if (success)
                    success(JSON.parse(xhr.responseText));
            }
        }
    };
    xhr.open("GET", path, true);
    xhr.send();
}

<|endoftext|>


<commit_before>// Disable links prefetch
user_pref("network.prefetch-next", false);

// Disable onload popups
pref("dom.disable_open_during_load", true);

// Disable usless security warnings
pref("security.warn_entering_secure", false);
pref("security.warn_entering_secure.show_once", true);
pref("security.warn_leaving_secure", false);
pref("security.warn_leaving_secure.show_once", false);
pref("security.warn_submit_insecure", false);
pref("security.warn_submit_insecure.show_once", false);
pref("security.warn_viewing_mixed", true);
pref("security.warn_viewing_mixed.show_once", false);
pref("security.warn_entering_weak", true);
pref("security.warn_entering_weak.show_once", false);

// Set some style properties to not follow our dark gtk theme
pref("ui.-moz-field", "#FFFFFF");
pref("ui.-moz-fieldtext", "#000000");
pref("ui.buttonface", "#D3D3DD");
pref("ui.buttontext", "#000000");

// Fonts
pref("font.size.unit", "pt");

pref("font.default.ar", "sans-serif");
pref("font.size.variable.ar", 12);
pref("font.size.fixed.ar", 9);

pref("font.default.el", "serif");
pref("font.size.variable.el", 12);
pref("font.size.fixed.el", 9);

pref("font.default.he", "sans-serif");
pref("font.size.variable.he", 12);
pref("font.size.fixed.he", 9);

pref("font.default.ja", "sans-serif");
pref("font.size.variable.ja", 12);
pref("font.size.fixed.ja", 12);

pref("font.default.ko", "sans-serif");
pref("font.size.variable.ko", 12);
pref("font.size.fixed.ko", 12);

pref("font.default.th", "serif");
pref("font.size.variable.th", 12);
pref("font.size.fixed.th", 9);

pref("font.default.tr", "serif");
pref("font.size.variable.tr", 12);
pref("font.size.fixed.tr", 9);

pref("font.default.x-baltic", "serif");
pref("font.size.variable.x-baltic", 12);
pref("font.size.fixed.x-baltic", 9);

pref("font.default.x-central-euro", "serif");
pref("font.size.variable.x-central-euro", 12);
pref("font.size.fixed.x-central-euro", 9);

pref("font.default.x-cyrillic", "serif");
pref("font.size.variable.x-cyrillic", 12);
pref("font.size.fixed.x-cyrillic", 9);

pref("font.default.x-unicode", "serif");
pref("font.size.variable.x-unicode", 12);
pref("font.size.fixed.x-unicode", 9);

pref("font.default.x-western", "serif");
pref("font.size.variable.x-western", 12);
pref("font.size.fixed.x-western", 9);

pref("font.default.zh-CN", "sans-serif");
pref("font.size.variable.zh-CN", 12);
pref("font.size.fixed.zh-CN", 12);

pref("font.default.zh-TW", "sans-serif");
pref("font.size.variable.zh-TW", 12);
pref("font.size.fixed.zh-TW", 12);

pref("font.default.zh-HK", "sans-serif");
pref("font.size.variable.zh-HK", 12);
pref("font.size.fixed.zh-HK", 12);

// Enable error pages (xulrunner is missing this pref)
pref("browser.xul.error_pages.enabled", true);
<commit_msg>Set dialog color to panel grey<commit_after>// Disable links prefetch
user_pref("network.prefetch-next", false);

// Disable onload popups
pref("dom.disable_open_during_load", true);

// Disable usless security warnings
pref("security.warn_entering_secure", false);
pref("security.warn_entering_secure.show_once", true);
pref("security.warn_leaving_secure", false);
pref("security.warn_leaving_secure.show_once", false);
pref("security.warn_submit_insecure", false);
pref("security.warn_submit_insecure.show_once", false);
pref("security.warn_viewing_mixed", true);
pref("security.warn_viewing_mixed.show_once", false);
pref("security.warn_entering_weak", true);
pref("security.warn_entering_weak.show_once", false);

// Set some style properties to not follow our dark gtk theme
pref("ui.-moz-field", "#FFFFFF");
pref("ui.-moz-fieldtext", "#000000");
pref("ui.-moz-dialog", "#C0C0C0");
pref("ui.buttonface", "#D3D3DD");
pref("ui.buttontext", "#000000");

// Fonts
pref("font.size.unit", "pt");

pref("font.default.ar", "sans-serif");
pref("font.size.variable.ar", 12);
pref("font.size.fixed.ar", 9);

pref("font.default.el", "serif");
pref("font.size.variable.el", 12);
pref("font.size.fixed.el", 9);

pref("font.default.he", "sans-serif");
pref("font.size.variable.he", 12);
pref("font.size.fixed.he", 9);

pref("font.default.ja", "sans-serif");
pref("font.size.variable.ja", 12);
pref("font.size.fixed.ja", 12);

pref("font.default.ko", "sans-serif");
pref("font.size.variable.ko", 12);
pref("font.size.fixed.ko", 12);

pref("font.default.th", "serif");
pref("font.size.variable.th", 12);
pref("font.size.fixed.th", 9);

pref("font.default.tr", "serif");
pref("font.size.variable.tr", 12);
pref("font.size.fixed.tr", 9);

pref("font.default.x-baltic", "serif");
pref("font.size.variable.x-baltic", 12);
pref("font.size.fixed.x-baltic", 9);

pref("font.default.x-central-euro", "serif");
pref("font.size.variable.x-central-euro", 12);
pref("font.size.fixed.x-central-euro", 9);

pref("font.default.x-cyrillic", "serif");
pref("font.size.variable.x-cyrillic", 12);
pref("font.size.fixed.x-cyrillic", 9);

pref("font.default.x-unicode", "serif");
pref("font.size.variable.x-unicode", 12);
pref("font.size.fixed.x-unicode", 9);

pref("font.default.x-western", "serif");
pref("font.size.variable.x-western", 12);
pref("font.size.fixed.x-western", 9);

pref("font.default.zh-CN", "sans-serif");
pref("font.size.variable.zh-CN", 12);
pref("font.size.fixed.zh-CN", 12);

pref("font.default.zh-TW", "sans-serif");
pref("font.size.variable.zh-TW", 12);
pref("font.size.fixed.zh-TW", 12);

pref("font.default.zh-HK", "sans-serif");
pref("font.size.variable.zh-HK", 12);
pref("font.size.fixed.zh-HK", 12);

// Enable error pages (xulrunner is missing this pref)
pref("browser.xul.error_pages.enabled", true);
<|endoftext|>


<commit_before>const url = require('url');
const _ = require('lodash');

function words(string) {
    return _.words(string, /([a-z][a-z0-9]*|[A-Z][a-z0-9]+|[A-Z]+)/g);
}

function toCamelCase(string) {
    return words(string).map((word, index) => (index ? _.upperFirst : _.lowerFirst)(word.toLowerCase())).join('');
}
exports.toCamelCase = toCamelCase;

function toPascalCase(string) {
    return words(string).map(word => _.upperFirst(word.toLowerCase())).join('');
}
exports.toPascalCase = toPascalCase;

function resolveType(pointer = '', base = '', typeReference = {}) {
    return _.get(typeReference, url.resolve(base, pointer), { fromTuple: _.identity });
}

function handleCasting(handlers, value, contextSchema, typeReference) {
    const { responsible, executor } = _.head(handlers) || { responsible: _.constant(true), executor: _.identity };
    return (responsible(contextSchema.schema) ? executor : _.partial(handleCasting, _.tail(handlers)))(value, contextSchema, typeReference);
}

function castTupleConvertibleType(value, contextSchema, typeReference) {
    return handleCasting(castingHandlers, value, contextSchema, typeReference);
}
exports.castTupleConvertibleType = castTupleConvertibleType;

const castingHandlers = [
    {
        responsible: (schema) => '$ref' in schema,
        executor: (value, { base, schema }, typeReference) => resolveType(schema['$ref'], base, typeReference).fromTuple(value)
    },
    {
        responsible: (schema) => schema.type === 'array',
        executor: (values, { base, schema: { items } }, typeReference) => {
            const next = Array.isArray(items) ? _.nth : _.identity;
            return _.map(values, (value, index) => castTupleConvertibleType(value, { base, schema: next(items, index) }, typeReference));
        }
    },
    {
        responsible: (schema) => (schema.type || 'object') === 'object',
        executor: (object, { base, schema }, typeReference) => {
            const properties = _.toPairs(schema.properties);
            const patternProperties = _.toPairs(schema.patternProperties);
            return _.mapValues(object, (value, key) => {
                const schemas = properties.filter(([propertyName]) => propertyName === key)
                    .concat(patternProperties.filter(([pattern]) => (new RegExp(pattern)).test(key)))
                    .map(_.last);
                return schemas.reduce((value, schema) => castTupleConvertibleType(value, { base, schema }, typeReference), value);
            });
        }
    }
];

function toTuple(value) {
    const hasToTuple = value && typeof value['toTuple'] === 'function';
    return hasToTuple ? value.toTuple() : Array.isArray(value) ? _.map(value, toTuple) : value;
}
exports.toTuple = toTuple;

function createTupleConvertibleType(typeName, schema) {
    const { items } = schema;
    const args = items.map(item => _.at(item, 'title', 'default'))
        .map(([name, value]) => _.compact([toCamelCase(name), JSON.stringify(value)]).join('=')).join(',');
    const keys = items.map(item => toCamelCase(_.at(item, 'title')));
    const properties = keys.map(key => `${key}: { enumerable: true, value: ${key} }`)
        .concat(`[Symbol.toStringTag]: { value: '${typeName}' }`).join(',');
    const functionBody = `Object.defineProperties(this, {${properties}})`;
    const constructor = new Function(args, functionBody);
    Object.defineProperties(constructor, {
        name: { configurable: true, value: typeName }
    });
    constructor.prototype.toTuple = function () {
        return _.at(this, keys).map(toTuple);
    };
    return constructor;
}

function createTupleConvertibleTypes(schema, commonTypeReference) {
    const { id = '', definitions } = schema;
    const base = url.resolve(id, '#/definitions/');
    const typeReference = _.fromPairs(_.toPairs(definitions)
        .map(([key, schema]) => ([base + key, createTupleConvertibleType(toPascalCase(_.get(schema, 'title', key)), schema)])));
    const types = _.mapKeys(typeReference, value => value.name);
    Object.assign(typeReference, commonTypeReference);
    return [defineFromTupleFunction(types, schema, typeReference), typeReference];
}
exports.createTupleConvertibleTypes = createTupleConvertibleTypes;

function createFromTupleFunction(constructor, { base, schema }, typeReference) {
    const types = schema.items.map(item => resolveType(item['$ref'], base, typeReference));
    return function fromTuple(tuple) {
        const args = _.zip(types, tuple).map(([type, value]) => type.fromTuple(value));
        return new (Function.prototype.bind.apply(constructor, [null].concat(args)));
    };
}

function defineFromTupleFunction(types, { id = '', definitions }, typeReference) {
    return _.mapValues(types, (constructor, typeName) => {
        const typeReferenceKey = _.findKey(typeReference, { name: typeName });
        const path = url.parse(typeReferenceKey).hash.replace(/^#\/definitions\/(.*)$/g, '$1');
        const schema = _.get(definitions, path);
        constructor.fromTuple = createFromTupleFunction(constructor, { base: id, schema }, typeReference);
        return constructor;
    });
}<commit_msg>Refactor typing.js<commit_after>const url = require('url');
const _ = require('lodash');

function words(string) {
    return _.words(string, /([a-z][a-z0-9]*|[A-Z][a-z0-9]+|[A-Z]+)/g);
}

function toCamelCase(string) {
    return words(string).map((word, index) => (index ? _.upperFirst : _.lowerFirst)(word.toLowerCase())).join('');
}
exports.toCamelCase = toCamelCase;

function toPascalCase(string) {
    return words(string).map(word => _.upperFirst(word.toLowerCase())).join('');
}
exports.toPascalCase = toPascalCase;

function resolveType(pointer = '', base = '', typeReference = {}) {
    return _.get(typeReference, url.resolve(base, pointer), { fromTuple: _.identity });
}

function handleCasting(handlers, value, contextSchema, typeReference) {
    const { responsible, executor } = _.head(handlers) || { responsible: _.constant(true), executor: _.identity };
    return (responsible(contextSchema.schema) ? executor : _.partial(handleCasting, _.tail(handlers)))(value, contextSchema, typeReference);
}

function castTupleConvertibleType(value, contextSchema, typeReference) {
    return handleCasting(castingHandlers, value, contextSchema, typeReference);
}
exports.castTupleConvertibleType = castTupleConvertibleType;

const castingHandlers = [
    {
        responsible: (schema) => '$ref' in schema,
        executor: (value, { base, schema }, typeReference) => resolveType(schema['$ref'], base, typeReference).fromTuple(value)
    },
    {
        responsible: (schema) => schema.type === 'array',
        executor: (values, { base, schema: { items } }, typeReference) => {
            const next = Array.isArray(items) ? _.nth : _.identity;
            return _.map(values, (value, index) => castTupleConvertibleType(value, { base, schema: next(items, index) }, typeReference));
        }
    },
    {
        responsible: (schema) => (schema.type || 'object') === 'object',
        executor: (object, { base, schema }, typeReference) => {
            const properties = _.toPairs(schema.properties);
            const patternProperties = _.toPairs(schema.patternProperties);
            return _.mapValues(object, (value, key) => {
                const schemas = properties.filter(([propertyName]) => propertyName === key)
                    .concat(patternProperties.filter(([pattern]) => (new RegExp(pattern)).test(key)))
                    .map(_.last);
                return schemas.reduce((value, schema) => castTupleConvertibleType(value, { base, schema }, typeReference), value);
            });
        }
    }
];

function toTuple(value) {
    const hasToTuple = value && typeof value['toTuple'] === 'function';
    return hasToTuple ? value.toTuple() : Array.isArray(value) ? _.map(value, toTuple) : value;
}
exports.toTuple = toTuple;

function createTupleConvertibleType(typeName, schema) {
    const { items: itemObject = [] } = schema;
    const items = [].concat(itemObject);
    const args = items.map(item => _.at(item, 'title', 'default'))
        .map(([name, value]) => _.compact([toCamelCase(name), JSON.stringify(value)]).join('=')).join(',');
    const keys = items.map(item => toCamelCase(_.get(item, 'title')));
    const properties = keys.map(key => `${key}: { enumerable: true, value: ${key} }`)
        .concat(`[Symbol.toStringTag]: { value: '${typeName}' }`).join(',');
    const functionBody = `Object.defineProperties(this, {${properties}})`;
    const constructor = new Function(args, functionBody);
    Object.defineProperties(constructor, {
        name: { configurable: true, value: typeName }
    });
    constructor.prototype.toTuple = function () {
        return _.at(this, keys).map(toTuple);
    };
    return constructor;
}

function createTupleConvertibleTypes(schema, commonTypeReference) {
    const { id = '', definitions } = schema;
    const base = url.resolve(id, '#/definitions/');
    const typeReference = _.fromPairs(_.toPairs(definitions)
        .map(([key, schema]) => ([base + key, createTupleConvertibleType(toPascalCase(_.get(schema, 'title', key)), schema)])));
    const types = _.mapKeys(typeReference, value => value.name);
    Object.assign(typeReference, commonTypeReference);
    return [defineFromTupleFunction(types, schema, typeReference), typeReference];
}
exports.createTupleConvertibleTypes = createTupleConvertibleTypes;

function createFromTupleFunction(constructor, { base, schema }, typeReference) {
    const types = schema.items.map(item => resolveType(item['$ref'], base, typeReference));
    return function fromTuple(tuple) {
        const args = _.zip(types, tuple).map(([type, value]) => type.fromTuple(value));
        return new (Function.prototype.bind.apply(constructor, [null].concat(args)));
    };
}

function defineFromTupleFunction(types, { id = '', definitions }, typeReference) {
    return _.mapValues(types, (constructor, typeName) => {
        const typeReferenceKey = _.findKey(typeReference, { name: typeName });
        const path = url.parse(typeReferenceKey).hash.replace(/^#\/definitions\/(.*)$/g, '$1');
        const schema = _.get(definitions, path);
        constructor.fromTuple = createFromTupleFunction(constructor, { base: id, schema }, typeReference);
        return constructor;
    });
}<|endoftext|>