<commit_before>;(function ( $, window, document, undefined ) {
	function Plugin( element ) {
		this.$element = $( element );
		this.events();
	}

	Plugin.prototype = {
		events: function () {
			var $btnSettings = this.$element.find( ".js-snippet-settings-btn" ),
				$btnCode = this.$element.find( ".js-snippet-code-btn" ),
				$settings = this.$element.find( ".js-snippet-settings" ),
				$code = this.$element.find( ".js-snippet-code" ),
				$preview = this.$element.find( ".js-snippet-preview" ),
				$previewSource = $preview.find( "iframe" ),
				$handleLeft = this.$element.find( ".js-snippet-resize-handle-left" ),
				$handleRight = this.$element.find( ".js-snippet-resize-handle-right" ),
				$sizeIndicator = this.$element.find( ".js-snippet-size" );

			$btnSettings.on( "click", function () {

				$btnCode.removeClass( "active" );
				$btnSettings.toggleClass( "active" );
				$code.hide();
				$settings.add( $preview ).toggle();
			});

			$btnCode.on( "click", function () {

				$btnSettings.removeClass( "active" );
				$btnCode.toggleClass( "active" );
				$settings.hide();
				$preview.show();
				$code.toggle();
			});

			interact( $preview[0] )
				.resizable({
					edges: {
						left: $handleLeft[0],
						right: $handleRight[0],
						bottom: false,
						top: false
					},
					onmove: function (e) {
						var target = e.target;

						if ( e.rect.width > 319 ) {
							target.style.width  = e.rect.width + 'px';
							$sizeIndicator.text( e.rect.width + "px" );
						}
					}
				});
		}
	};

	$.fn.sgSnippet = function () {
		return this.each( function () {
			if (!$.data( this, "sgSnippet" ) ) {
				$.data( this, "sgSnippet", new Plugin( this ) );
			}
		});
	};
})( jQuery, window, document );

$( ".js-snippet" ).sgSnippet();

$( ".js-header-new-snippet" ).on( "click", function () {
	$( ".js-new-snippet-form" ).toggle();
});

$(document).ready(function(){
	var dom = require("ace/lib/dom");
	var commands = require("ace/commands/default_commands").commands;
	commands.push({
		name: "Toggle Fullscreen",
		bindKey: "F11",
		exec: function(editor) {
			dom.toggleCssClass(document.body, "fullScreen");
			dom.toggleCssClass(editor.container, "fullScreen-editor");
			editor.resize();
		}
	});

	// setting up ace editor
    var codeEditor = ace.edit("codeEditor");
    codeEditor.setTheme("ace/theme/chrome");
    codeEditor.getSession().setMode("ace/mode/html");

    var cssEditor = ace.edit("cssEditor");
    cssEditor.setTheme("ace/theme/chrome");
    cssEditor.getSession().setMode("ace/mode/css");

	$('.js-toggle-code-editor-full-screen').on('click', function(e) {
		e.preventDefault();
		codeEditor.keyBinding.$handlers[0].commands['Toggle Fullscreen'].exec(codeEditor);
	});

	$('.js-toggle-css-editor-full-screen').on('click', function(e) {
		e.preventDefault();
		cssEditor.keyBinding.$handlers[0].commands['Toggle Fullscreen'].exec(cssEditor);
	});

	// set categories
	$('#form-new-category').each(function(index, el) {
		var comboBox = $(this);
		$.getJSON('../config.json', function(data) {
			var categories = [];
			$.each(data.categories, function(index, val) {
				categories.push('<option value="'+val.id+'">'+val.name+'</option>');
			});
			comboBox.html(categories.join(''));
		});
	});

	$('.js-submit-form-button').on('click', function(event) {
		event.preventDefault();
		var selector = $(this).data('submit-form');
		$(selector).off('submit.customSubmit');
		$(selector).on('submit.customSubmit', HandleCustomFormSubmit);
		$(selector).submit();
	});

	var colorLiTemplate = $($('.snippet-colors > li').first()[0].cloneNode(true));
	var colorLocation = $('.snippet-colors')[0];
	var fontTemplate = $($('.snippet-fonts > li').first()[0].cloneNode(true));
	var smallFontsTemplate = fontTemplate.find('.snippet-fonts-small')[0];
	$.getJSON('../../db/sassdata.json', function(sassdata){
		$.each(sassdata, function(i, element) {
			colorLocation.innerHTML = '';
			$.each(element.colors, function(index, el) {
				colorLiTemplate.find('i')[0].style.background = index;
				colorLiTemplate.find('i').text(index);
				colorLiTemplate.find('.js-color-text').text(el.join(', '));
				colorLocation.appendChild(colorLiTemplate[0].cloneNode(true));
			});

			var fontsLocation = $('.snippet-fonts')[0];
			fontsLocation.innerHTML = '';
			$.each(element.typography, function(index, el) {
				var smallFontsContainer = fontTemplate.find('.js-small-fonts-container');
				fontTemplate.find('.snippet-fonts-small').remove();
				$.each(el.weights, function(index, fontWeight) {
					smallFontsTemplate.style.fontWeight = fontWeight;
					smallFontsContainer[0].appendChild(smallFontsTemplate.cloneNode(true));
				});
				fontTemplate.find('.snippet-fonts-variable').text(el.variable +': '+ el.value);
				fontTemplate.find('.js-set-font').each(function(index, fontElement) {
					fontElement.style.background = el.value;
				});
				fontsLocation.appendChild(fontTemplate[0].cloneNode(true));
			});
		});
	});

	function HandleCustomFormSubmit(event) {
		event.preventDefault();
		var formToSubmit = $(this);
		formToSubmit.validate();
		var submitFields = $('.js-form-submit-field');
		var invalidFields = submitFields.filter(function(){ return !$(this).valid();});
		if (invalidFields.length == 0 && CodeInputValid()) {
			var data = {};
			submitFields.each(function(index, el) {
				data[$(this).data('js-field-name')] = $(this).val();
			});
			data.code = codeEditor.getValue();
			data.inlineCss = cssEditor.getValue();
			$.ajax({
				type: "POST",
				url: '//'+window.location.hostname+':8080'+formToSubmit.attr('action'),
				data: data,
				success: function(){},
				dataType: 'JSON'
			}).fail(function() {
			    alert( "Failed to post!" );
			});
		}

		function CodeInputValid() {
			if ($('#codeEditor').length == 1 && codeEditor.getValue() == '') {
				$('#form-new-code-error').show();
				return false;
			} else {
				$('#form-new-code-error').hide();
				return true;
			}
		}
	}

    function httpGet(theUrl)
    {
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open( "GET", theUrl, false );
        xmlHttp.send( null );
        return xmlHttp;
    }
});<commit_msg>Added more font seters.<commit_after>;(function ( $, window, document, undefined ) {
	function Plugin( element ) {
		this.$element = $( element );
		this.events();
	}

	Plugin.prototype = {
		events: function () {
			var $btnSettings = this.$element.find( ".js-snippet-settings-btn" ),
				$btnCode = this.$element.find( ".js-snippet-code-btn" ),
				$settings = this.$element.find( ".js-snippet-settings" ),
				$code = this.$element.find( ".js-snippet-code" ),
				$preview = this.$element.find( ".js-snippet-preview" ),
				$previewSource = $preview.find( "iframe" ),
				$handleLeft = this.$element.find( ".js-snippet-resize-handle-left" ),
				$handleRight = this.$element.find( ".js-snippet-resize-handle-right" ),
				$sizeIndicator = this.$element.find( ".js-snippet-size" );

			$btnSettings.on( "click", function () {

				$btnCode.removeClass( "active" );
				$btnSettings.toggleClass( "active" );
				$code.hide();
				$settings.add( $preview ).toggle();
			});

			$btnCode.on( "click", function () {

				$btnSettings.removeClass( "active" );
				$btnCode.toggleClass( "active" );
				$settings.hide();
				$preview.show();
				$code.toggle();
			});

			interact( $preview[0] )
				.resizable({
					edges: {
						left: $handleLeft[0],
						right: $handleRight[0],
						bottom: false,
						top: false
					},
					onmove: function (e) {
						var target = e.target;

						if ( e.rect.width > 319 ) {
							target.style.width  = e.rect.width + 'px';
							$sizeIndicator.text( e.rect.width + "px" );
						}
					}
				});
		}
	};

	$.fn.sgSnippet = function () {
		return this.each( function () {
			if (!$.data( this, "sgSnippet" ) ) {
				$.data( this, "sgSnippet", new Plugin( this ) );
			}
		});
	};
})( jQuery, window, document );

$( ".js-snippet" ).sgSnippet();

$( ".js-header-new-snippet" ).on( "click", function () {
	$( ".js-new-snippet-form" ).toggle();
});

$(document).ready(function(){
	var dom = require("ace/lib/dom");
	var sassdata;
	var commands = require("ace/commands/default_commands").commands;
	commands.push({
		name: "Toggle Fullscreen",
		bindKey: "F11",
		exec: function(editor) {
			dom.toggleCssClass(document.body, "fullScreen");
			dom.toggleCssClass(editor.container, "fullScreen-editor");
			editor.resize();
		}
	});

	// setting up ace editor
    var codeEditor = ace.edit("codeEditor");
    codeEditor.setTheme("ace/theme/chrome");
    codeEditor.getSession().setMode("ace/mode/html");

    var cssEditor = ace.edit("cssEditor");
    cssEditor.setTheme("ace/theme/chrome");
    cssEditor.getSession().setMode("ace/mode/css");

	$('.js-toggle-code-editor-full-screen').on('click', function(e) {
		e.preventDefault();
		codeEditor.keyBinding.$handlers[0].commands['Toggle Fullscreen'].exec(codeEditor);
	});

	$('.js-toggle-css-editor-full-screen').on('click', function(e) {
		e.preventDefault();
		cssEditor.keyBinding.$handlers[0].commands['Toggle Fullscreen'].exec(cssEditor);
	});

	// set categories
	$('#form-new-category').each(function(index, el) {
		var comboBox = $(this);
		$.getJSON('../config.json', function(data) {
			var categories = [];
			$.each(data.categories, function(index, val) {
				categories.push('<option value="'+val.id+'">'+val.name+'</option>');
			});
			comboBox.html(categories.join(''));
		});
	});

	$('.js-submit-form-button').on('click', function(event) {
		event.preventDefault();
		var selector = $(this).data('submit-form');
		$(selector).off('submit.customSubmit');
		$(selector).on('submit.customSubmit', HandleCustomFormSubmit);
		$(selector).submit();
	});

	var colorLiTemplate = $($('.snippet-colors > li').first()[0].cloneNode(true));
	var colorLocation = $('.snippet-colors')[0];
	var fontTemplate = $($('.snippet-fonts > li').first()[0].cloneNode(true));
	var smallFontsTemplate = fontTemplate.find('.snippet-fonts-small')[0];
	$.getJSON('../../db/sassdata.json', function(data){
		sassdata = data;
		HandleSassData(data[0]);
	});

	function HandleSassData(element) {
		var fonts = element.typography.map(function(elem) {
			return elem.value.split('\'')[1];
		}).filter(function(value, index, self) {
		    return self.indexOf(value) === index;
		});
		var fontFamilyPreview = $('.snippet-type-text > .row')[0];
		$('.snippet-type-text > .row').remove();
		$.each(fonts, function(index, val) {
			fontFamilyPreview.style.fontFamily = val;
			$('.snippet-type-text')[0].appendChild(fontFamilyPreview.cloneNode(true));
		});
		colorLocation.innerHTML = '';
		$.each(element.colors, function(index, el) {
			colorLiTemplate.find('i')[0].style.background = index;
			colorLiTemplate.find('i').text(index);
			colorLiTemplate.find('.js-color-text').text(el.join(', '));
			colorLocation.appendChild(colorLiTemplate[0].cloneNode(true));
		});

		var fontsLocation = $('.snippet-fonts')[0];
		fontsLocation.innerHTML = '';
		$.each(element.typography, function(index, el) {
			var smallFontsContainer = fontTemplate.find('.js-small-fonts-container');
			fontTemplate.find('.snippet-fonts-small').remove();
			$.each(el.weights, function(index, fontWeight) {
				smallFontsTemplate.style.fontWeight = fontWeight;
				smallFontsContainer[0].appendChild(smallFontsTemplate.cloneNode(true));
			});
			fontTemplate.find('.snippet-fonts-variable').text(el.variable +': '+ el.value);
			fontTemplate.find('.js-set-font').each(function(index, fontElement) {
				fontElement.style.fontFamily = el.value;
			});
			fontsLocation.appendChild(fontTemplate[0].cloneNode(true));
		});
	}

	function HandleCustomFormSubmit(event) {
		event.preventDefault();
		var formToSubmit = $(this);
		formToSubmit.validate();
		var submitFields = $('.js-form-submit-field');
		var invalidFields = submitFields.filter(function(){ return !$(this).valid();});
		if (invalidFields.length == 0 && CodeInputValid()) {
			var data = {};
			submitFields.each(function(index, el) {
				data[$(this).data('js-field-name')] = $(this).val();
			});
			data.code = codeEditor.getValue();
			data.inlineCss = cssEditor.getValue();
			$.ajax({
				type: "POST",
				url: '//'+window.location.hostname+':5858'+formToSubmit.attr('action'),
				data: data,
				success: function(){},
				dataType: 'JSON'
			}).fail(function() {
			    alert( "Failed to post!" );
			});
		}

		function CodeInputValid() {
			if ($('#codeEditor').length == 1 && codeEditor.getValue() == '') {
				$('#form-new-code-error').show();
				return false;
			} else {
				$('#form-new-code-error').hide();
				return true;
			}
		}
	}

    function httpGet(theUrl)
    {
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open( "GET", theUrl, false );
        xmlHttp.send( null );
        return xmlHttp;
    }
});<|endoftext|>


<commit_before>var tape = require('../');
var tap = require('tap');
var concat = require('concat-stream');

var stripFullStack = require('./common').stripFullStack;
var testWrapper = require('./anonymous-fn/test-wrapper');

tap.test('inside anonymous functions', function (tt) {
    tt.plan(1);

    var test = tape.createHarness();
    var tc = function (rows) {
        tt.same(stripFullStack(rows.toString('utf8')), [
            'TAP version 13',
            '# wrapped test failure',
            'not ok 1 fail',
            '  ---',
            '    operator: fail',
            '    at: <anonymous> ($TEST/anonymous-fn.js:$LINE:$COL)',
            '    stack: |-',
            '      Error: fail',
            '          [... stack stripped ...]',
            '          at $TEST/anonymous-fn.js:$LINE:$COL',
            '          at Test.<anonymous> ($TEST/anonymous-fn/test-wrapper.js:$LINE:$COL)',
            '          [... stack stripped ...]',
            '  ...',
            '',
            '1..1',
            '# tests 1',
            '# pass  0',
            '# fail  1'
        ].join('\n') + '\n');
    };

    test.createStream().pipe(concat(tc));

    test('wrapped test failure', testWrapper(function (t) {
        t.fail('fail');
        t.end();
    }));
});
<commit_msg>Handle stack variation in Node v0.8<commit_after>var tape = require('../');
var tap = require('tap');
var concat = require('concat-stream');

var stripFullStack = require('./common').stripFullStack;
var testWrapper = require('./anonymous-fn/test-wrapper');

tap.test('inside anonymous functions', function (tt) {
    tt.plan(1);

    var test = tape.createHarness();
    var tc = function (rows) {
        var body = stripFullStack(rows.toString('utf8'));

        // Handle stack trace variation in Node v0.8
        body = body.replace(
            'at Test.module.exports',
            'at Test.<anonymous>'
        );

        tt.same(body, [
            'TAP version 13',
            '# wrapped test failure',
            'not ok 1 fail',
            '  ---',
            '    operator: fail',
            '    at: <anonymous> ($TEST/anonymous-fn.js:$LINE:$COL)',
            '    stack: |-',
            '      Error: fail',
            '          [... stack stripped ...]',
            '          at $TEST/anonymous-fn.js:$LINE:$COL',
            '          at Test.<anonymous> ($TEST/anonymous-fn/test-wrapper.js:$LINE:$COL)',
            '          [... stack stripped ...]',
            '  ...',
            '',
            '1..1',
            '# tests 1',
            '# pass  0',
            '# fail  1'
        ].join('\n') + '\n');
    };

    test.createStream().pipe(concat(tc));

    test('wrapped test failure', testWrapper(function (t) {
        t.fail('fail');
        t.end();
    }));
});
<|endoftext|>


<commit_before>var fs = require('fs')
var crypto = require('crypto')
var async = require('async')
var test = require('tape')

var ncbi = require('../')

var testData = require('./data')
var guillardiaThetaSRAData = require('./guillardia-theta.sra')

test('Download list', function (t) {
  t.plan(2)

  ncbi.urls('assembly', 'Guillardia theta')
  .on('data', function (data) {
    var msg = 'should take a database name (assembly) and search term (Guillardia theta), and list datasets URLs'
    t.deepEqual(data, testData.assembly['guillardia-theta'].urls, msg)
  })

  var results = []
  ncbi.urls('sra', 'Guillardia theta')
  .on('data', function (data) { results.push(data) })
  .on('end', function (data) {
    var msg = 'should take a database name (sra) and search term (Guillardia theta), and list datasets URLs'
    t.deepEqual(results, testData.sra['guillardia-theta'].urls, msg)
  })
})

test('Download', function (t) {
  t.plan(2)

  async.eachSeries(
    [
      'should take a database name and search term, and download datasets',
      'repeat same download to cover already downloaded branch'
    ],
    testDownload
  )

  function testDownload (msg, cb) {
    var path
    ncbi.download('assembly', 'Guillardia theta')
    .on('data', function (data) { path = data.path })
    .on('end', function () {
      var file = fs.ReadStream(path)
      var shasum = crypto.createHash('sha1')
      file.on('data', function (d) { shasum.update(d) })
      file.on('end', function () {
        var sha1 = shasum.digest('hex')
        var hash = 'a2dc7b3b0ae6f40d5205c4394c2fe8bc65d52bc2'
        t.equal(sha1, hash, msg)
        cb()
      })
    })
  }
})

test('Search', function (t) {
  t.plan(3)

  ncbi.search('assembly', 'Guillardia theta')
  .on('data', function (data) {
    var msg = 'should take a database name and search term, and return the data'
    t.deepEqual(data, testData.assembly['guillardia-theta'].search, msg)
  })

  var results1 = []
  ncbi.search('sra', 'Guillardia theta')
  .on('data', function (data) { results1.push(data) })
  .on('end', function () {
    var msg = 'same as previous but searching sra instead of assembly'
    t.deepEqual(results1, guillardiaThetaSRAData, msg)
  })

  var results2 = []
  ncbi.search({ db: 'sra', term: 'Guillardia theta', limit: 1 })
  .on('data', function (data) { results2.push(data) })
  .on('end', function () {
    var msg = 'same as previous but with a limit of 1'
    guillardiaThetaSRAData.forEach(findMatchAndTest)
    function findMatchAndTest (sradata) {
      if (sradata.uid === results2[0].uid) {
        t.deepEqual(results2, [sradata], msg)
      }
    }
  })

  // These tests fail randomly on Travis because of network speed
  // var start1 = Date.now()
  // ncbi.search({ db: 'sra', term: 'human', limit: 500, throughput: 500 })
  // .on('data', function(data) {})
  // .on('end', function() {
  //   var msg = 'get 500 objects fast from sra using throughput of 500 per request'
  //   var seconds = (Date.now() - start1) / 1000
  //   var fast = seconds < 10
  //   t.ok(fast, msg)
  // })
  //
  // var start2 = Date.now()
  // ncbi.search({ db: 'sra', term: 'human', limit: 500, throughput: 5 })
  // .on('data', function(data) {})
  // .on('end', function() {
  //   var msg = 'get 500 objects slowly from sra using throughput of 5 per request'
  //   var seconds = (Date.now() - start2) / 1000
  //   var slow = seconds > 10
  //   t.ok(slow, msg)
  // })
})

test('Link', function (t) {
  t.plan(2)

  var results = []
  ncbi.link('sra', 'bioproject', '35533')
  .on('data', function (data) { results.push(data) })
  .on('end', function () {
    var msg = 'should take names for source database, destination database and a NCBI UID, and return the link'
    t.deepEqual(results, testData.link['sra-bioproject']['35533'], msg)
  })

  ncbi.link('bioproject', 'assembly', '53577')
  .on('data', function (data) {
    var msg = 'same as previous, but doing bioproject->assembly instead of sra->assembly to try get same assembly UID as Search'
    t.deepEqual(data.destUIDs[0], testData.assembly['guillardia-theta'].search.uid, msg)
  })
})
<commit_msg>Make tests less async because of Travis random fail<commit_after>var fs = require('fs')
var crypto = require('crypto')
var async = require('async')
var test = require('tape')

var ncbi = require('../')

var testData = require('./data')
var guillardiaThetaSRAData = require('./guillardia-theta.sra')

test('Download list', function (t) {
  t.plan(2)

  async.eachSeries([
    { db: 'assembly',
      expResult: [testData.assembly['guillardia-theta'].urls],
      msg: 'should take a database name (assembly) and search term (Guillardia theta), and list datasets URLs'},
    { db: 'sra',
      expResult: testData.sra['guillardia-theta'].urls,
      msg: 'should take a database name (sra) and search term (Guillardia theta), and list datasets URLs'}
  ], testSearch)

  function testSearch (obj, cb) {
    var results = []
    ncbi.urls(obj.db, 'Guillardia theta')
    .on('data', function (data) { results.push(data) })
    .on('end', function () {
      t.deepEqual(results, obj.expResult, obj.msg)
      cb()
    })
  }
})

test('Download', function (t) {
  t.plan(2)

  async.eachSeries(
    [
      'should take a database name and search term, and download datasets',
      'repeat same download to cover already downloaded branch'
    ],
    testDownload
  )

  function testDownload (msg, cb) {
    console.warn(msg)
    var path
    var results = []
    var stream = ncbi.download('assembly', 'Guillardia theta')
    stream
    .on('data', function (data) {
      console.warn('got data')
      console.warn(data)
      results.push(data)
      path = data.path
    })
    .on('end', function () {
      console.warn('Hello1')
      if (typeof path !== 'string') {
        console.warn('Hello2')
        console.warn(path)
        console.warn(results)
      }
      var file = fs.createReadStream(path)
      var shasum = crypto.createHash('sha1')
      file.on('data', function (d) { shasum.update(d) })
      file.on('end', function () {
        console.warn('finished reading file')
        var sha1 = shasum.digest('hex')
        var hash = 'a2dc7b3b0ae6f40d5205c4394c2fe8bc65d52bc2'
        t.equal(sha1, hash, msg)
        setTimeout(cb, 2000)
      })
    })
  }
})

test('Search', function (t) {
  t.plan(3)

  async.series([
    subtest1,
    subtest2,
    subtest3
  ])

  function subtest1 (cb) {
    var results1 = []
    ncbi.search('assembly', 'Guillardia theta')
    .on('data', function (data) { results1.push(data) })
    .on('end', function (data) {
      var msg = 'should take a database name and search term, and return the data'
      t.deepEqual(results1[0], testData.assembly['guillardia-theta'].search, msg)
      cb()
    })
  }

  function subtest2 (cb) {
    var results2 = []
    ncbi.search('sra', 'Guillardia theta')
    .on('data', function (data) { results2.push(data) })
    .on('end', function () {
      var msg = 'same as previous but searching sra instead of assembly'
      t.deepEqual(results2, guillardiaThetaSRAData, msg)
      cb()
    })
  }

  function subtest3 (cb) {
    var results3 = []
    ncbi.search({ db: 'sra', term: 'Guillardia theta', limit: 1 })
    .on('data', function (data) { results3.push(data) })
    .on('end', function () {
      var msg = 'same as previous but with a limit of 1'
      guillardiaThetaSRAData.forEach(findMatchAndTest)
      function findMatchAndTest (sradata) {
        if (sradata.uid === results3[0].uid) {
          t.deepEqual(results3, [sradata], msg)
          cb()
        }
      }
    })
  }

  // These tests fail randomly on Travis because of network speed
  // var start1 = Date.now()
  // ncbi.search({ db: 'sra', term: 'human', limit: 500, throughput: 500 })
  // .on('data', function(data) {})
  // .on('end', function() {
  //   var msg = 'get 500 objects fast from sra using throughput of 500 per request'
  //   var seconds = (Date.now() - start1) / 1000
  //   var fast = seconds < 10
  //   t.ok(fast, msg)
  // })
  //
  // var start2 = Date.now()
  // ncbi.search({ db: 'sra', term: 'human', limit: 500, throughput: 5 })
  // .on('data', function(data) {})
  // .on('end', function() {
  //   var msg = 'get 500 objects slowly from sra using throughput of 5 per request'
  //   var seconds = (Date.now() - start2) / 1000
  //   var slow = seconds > 10
  //   t.ok(slow, msg)
  // })
})

test('Link', function (t) {
  t.plan(2)

  async.series([
    subtest1,
    subtest2
  ])

  function subtest1 (cb) {
    var results = []
    ncbi.link('sra', 'bioproject', '35533')
    .on('data', function (data) { results.push(data) })
    .on('end', function () {
      var msg = 'should take names for source database, destination database and a NCBI UID, and return the link'
      t.deepEqual(results, testData.link['sra-bioproject']['35533'], msg)
      cb()
    })
  }

  function subtest2 (cb) {
    var results = []
    ncbi.link('bioproject', 'assembly', '53577')
    .on('data', function (data) { results.push(data) })
    .on('end', function () {
      var msg = 'same as previous, but doing bioproject->assembly instead of sra->assembly to try get same assembly UID as Search'
      t.deepEqual(results[0].destUIDs[0], testData.assembly['guillardia-theta'].search.uid, msg)
      cb()
    })
  }
})
<|endoftext|>


<commit_before>(function (root, factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        define(['empower', 'espower-source', 'assert'], factory);
    } else if (typeof exports === 'object') {
        factory(require('..'), require('espower-source'), require('assert'));
    } else {
        factory(root.empower, root.espowerSource, root.assert);
    }
}(this, function (
    empower,
    espowerSource,
    baseAssert
) {
    var weave = function (line) {
        return espowerSource(line, '/path/to/some_test.js');
    },
    fakeFormatter = function (context) {
        var events = context.args.reduce(function (accum, arg) {
            return accum.concat(arg.events);
        }, []);
        return [
            context.source.filepath,
            context.source.content,
            JSON.stringify(events)
        ].join('\n');
    };

function testWithOption (option) {
    var assert = empower(baseAssert, fakeFormatter, option);

test('Bug reproduction. should not fail if argument is null Literal. ' + JSON.stringify(option), function () {
    var foo = 'foo';
    try {
        eval(weave('assert.equal(foo, null);'));
        assert.ok(false, 'AssertionError should be thrown');
    } catch (e) {
        baseAssert.equal(e.name, 'AssertionError');
        if (option.modifyMessageOnFail) {
            baseAssert.equal(e.message, [
                '/path/to/some_test.js',
                'assert.equal(foo, null)',
                '[{"value":"foo","espath":"arguments/0"}]'
            ].join('\n'));
        }
        if (option.saveContextOnFail) {
            baseAssert.deepEqual(e.powerAssertContext, {
                "source":{
                    "content":"assert.equal(foo, null)",
                    "filepath":"/path/to/some_test.js",
                    "line": 1
                },
                "args":[
                    {
                        "value":"foo",
                        "events":[{"value":"foo","espath":"arguments/0"}]
                    }
                ]
            });
        }
    }
});

test(JSON.stringify(option) + ' empowered function also acts like an assert function', function () {
    var falsy = 0;
    try {
        eval(weave('assert(falsy);'));
        assert.ok(false, 'AssertionError should be thrown');
    } catch (e) {
        baseAssert.equal(e.name, 'AssertionError');
        if (option.modifyMessageOnFail) {
            baseAssert.equal(e.message, [
                '/path/to/some_test.js',
                'assert(falsy)',
                '[{"value":0,"espath":"arguments/0"}]'
            ].join('\n'));
        }
        if (option.saveContextOnFail) {
            baseAssert.deepEqual(e.powerAssertContext, {
                "source":{
                    "content": "assert(falsy)",
                    "filepath": "/path/to/some_test.js",
                    "line": 1
                },
                "args":[
                    {
                        "value": 0,
                        "events": [
                            {"value":0,"espath":"arguments/0"}
                        ]
                    }
                ]
            });
        }
    }
});

suite(JSON.stringify(option) + ' assertion method with one argument', function () {
    test('Identifier', function () {
        var falsy = 0;
        try {
            eval(weave('assert.ok(falsy);'));
            assert.ok(false, 'AssertionError should be thrown');
        } catch (e) {
            baseAssert.equal(e.name, 'AssertionError');
            if (option.modifyMessageOnFail) {
                baseAssert.equal(e.message, [
                    '/path/to/some_test.js',
                    'assert.ok(falsy)',
                    '[{"value":0,"espath":"arguments/0"}]'
                ].join('\n'));
            }
            if (option.saveContextOnFail) {
                baseAssert.deepEqual(e.powerAssertContext, {
                    "source": {
                        "content":"assert.ok(falsy)",
                        "filepath":"/path/to/some_test.js",
                        "line": 1
                    },
                    "args":[
                        {
                            "value":0,
                            "events":[
                                {"value":0,"espath":"arguments/0"}
                            ]
                        }
                    ]
                });
            }
        }
    });
});

suite(JSON.stringify(option) + ' assertion method with two arguments', function () {
    test('both Identifier', function () {
        var foo = 'foo', bar = 'bar';
        try {
            eval(weave('assert.equal(foo, bar);'));
            assert.ok(false, 'AssertionError should be thrown');
        } catch (e) {
            baseAssert.equal(e.name, 'AssertionError');
            if (option.modifyMessageOnFail) {
                baseAssert.equal(e.message, [
                    '/path/to/some_test.js',
                    'assert.equal(foo, bar)',
                    '[{"value":"foo","espath":"arguments/0"},{"value":"bar","espath":"arguments/1"}]'
                ].join('\n'));
            }
            if (option.saveContextOnFail) {
                baseAssert.deepEqual(e.powerAssertContext, {
                    "source":{
                        "content":"assert.equal(foo, bar)",
                        "filepath":"/path/to/some_test.js",
                        "line": 1
                    },
                    "args":[
                        {
                            "value":"foo",
                            "events":[{"value":"foo","espath":"arguments/0"}]
                        },
                        {
                            "value":"bar",
                            "events":[{"value":"bar","espath":"arguments/1"}]
                        }
                    ]
                });
            }
        }
    });

    test('first argument is Literal', function () {
        var bar = 'bar';
        try {
            eval(weave('assert.equal("foo", bar);'));
            assert.ok(false, 'AssertionError should be thrown');
        } catch (e) {
            baseAssert.equal(e.name, 'AssertionError');
            if (option.modifyMessageOnFail) {
                baseAssert.equal(e.message, [
                    '/path/to/some_test.js',
                    'assert.equal("foo", bar)',
                    '[{"value":"bar","espath":"arguments/1"}]'
                ].join('\n'));
            }
            if (option.saveContextOnFail) {
                baseAssert.deepEqual(e.powerAssertContext, {
                    "source":{
                        "content":"assert.equal(\"foo\", bar)",
                        "filepath":"/path/to/some_test.js",
                        "line": 1
                    },
                    "args": [
                        {
                            "value": "bar",
                            "events": [{"value":"bar","espath":"arguments/1"}]
                        }
                    ]
                });
            }
        }
    });

    test('second argument is Literal', function () {
        var foo = 'foo';
        try {
            eval(weave('assert.equal(foo, "bar");'));
            assert.ok(false, 'AssertionError should be thrown');
        } catch (e) {
            baseAssert.equal(e.name, 'AssertionError');
            if (option.modifyMessageOnFail) {
                baseAssert.equal(e.message, [
                    '/path/to/some_test.js',
                    'assert.equal(foo, "bar")',
                    '[{"value":"foo","espath":"arguments/0"}]'
                ].join('\n'));
            }
            if (option.saveContextOnFail) {
                baseAssert.deepEqual(e.powerAssertContext, {
                    "source":{
                        "content":"assert.equal(foo, \"bar\")",
                        "filepath":"/path/to/some_test.js",
                        "line": 1
                    },
                    "args":[
                        {
                            "value":"foo",
                            "events":[{"value":"foo","espath":"arguments/0"}]
                        }
                    ]
                });
            }
        }
    });
});

}

testWithOption({
    modifyMessageOnFail: false,
    saveContextOnFail: false
});

testWithOption({
    modifyMessageOnFail: true,
    saveContextOnFail: false
});

testWithOption({
    modifyMessageOnFail: false,
    saveContextOnFail: true
});

testWithOption({
    modifyMessageOnFail: true,
    saveContextOnFail: true
});

}));
<commit_msg>test(empower): add test for assertion with optional message argument<commit_after>(function (root, factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        define(['empower', 'espower-source', 'assert'], factory);
    } else if (typeof exports === 'object') {
        factory(require('..'), require('espower-source'), require('assert'));
    } else {
        factory(root.empower, root.espowerSource, root.assert);
    }
}(this, function (
    empower,
    espowerSource,
    baseAssert
) {
    var weave = function (line) {
        return espowerSource(line, '/path/to/some_test.js');
    },
    fakeFormatter = function (context) {
        var events = context.args.reduce(function (accum, arg) {
            return accum.concat(arg.events);
        }, []);
        return [
            context.source.filepath,
            context.source.content,
            JSON.stringify(events)
        ].join('\n');
    };

function testWithOption (option) {
    var assert = empower(baseAssert, fakeFormatter, option);

test('Bug reproduction. should not fail if argument is null Literal. ' + JSON.stringify(option), function () {
    var foo = 'foo';
    try {
        eval(weave('assert.equal(foo, null);'));
        assert.ok(false, 'AssertionError should be thrown');
    } catch (e) {
        baseAssert.equal(e.name, 'AssertionError');
        if (option.modifyMessageOnFail) {
            baseAssert.equal(e.message, [
                '/path/to/some_test.js',
                'assert.equal(foo, null)',
                '[{"value":"foo","espath":"arguments/0"}]'
            ].join('\n'));
        }
        if (option.saveContextOnFail) {
            baseAssert.deepEqual(e.powerAssertContext, {
                "source":{
                    "content":"assert.equal(foo, null)",
                    "filepath":"/path/to/some_test.js",
                    "line": 1
                },
                "args":[
                    {
                        "value":"foo",
                        "events":[{"value":"foo","espath":"arguments/0"}]
                    }
                ]
            });
        }
    }
});

test('assertion with optional message argument. ' + JSON.stringify(option), function () {
    var falsy = 0;
    try {
        eval(weave('assert(falsy, "assertion message");'));
        assert.ok(false, 'AssertionError should be thrown');
    } catch (e) {
        baseAssert.equal(e.name, 'AssertionError');
        if (option.modifyMessageOnFail) {
            baseAssert.equal(e.message, [
                'assertion message /path/to/some_test.js',
                'assert(falsy, "assertion message")',
                '[{"value":0,"espath":"arguments/0"}]'
            ].join('\n'));
        }
        if (option.saveContextOnFail) {
            baseAssert.deepEqual(e.powerAssertContext, {
                "source":{
                    "content": "assert(falsy, \"assertion message\")",
                    "filepath": "/path/to/some_test.js",
                    "line": 1
                },
                "args":[
                    {
                        "value": 0,
                        "events": [
                            {"value":0,"espath":"arguments/0"}
                        ]
                    }
                ]
            });
        }
    }
});

test(JSON.stringify(option) + ' empowered function also acts like an assert function', function () {
    var falsy = 0;
    try {
        eval(weave('assert(falsy);'));
        assert.ok(false, 'AssertionError should be thrown');
    } catch (e) {
        baseAssert.equal(e.name, 'AssertionError');
        if (option.modifyMessageOnFail) {
            baseAssert.equal(e.message, [
                '/path/to/some_test.js',
                'assert(falsy)',
                '[{"value":0,"espath":"arguments/0"}]'
            ].join('\n'));
        }
        if (option.saveContextOnFail) {
            baseAssert.deepEqual(e.powerAssertContext, {
                "source":{
                    "content": "assert(falsy)",
                    "filepath": "/path/to/some_test.js",
                    "line": 1
                },
                "args":[
                    {
                        "value": 0,
                        "events": [
                            {"value":0,"espath":"arguments/0"}
                        ]
                    }
                ]
            });
        }
    }
});

suite(JSON.stringify(option) + ' assertion method with one argument', function () {
    test('Identifier', function () {
        var falsy = 0;
        try {
            eval(weave('assert.ok(falsy);'));
            assert.ok(false, 'AssertionError should be thrown');
        } catch (e) {
            baseAssert.equal(e.name, 'AssertionError');
            if (option.modifyMessageOnFail) {
                baseAssert.equal(e.message, [
                    '/path/to/some_test.js',
                    'assert.ok(falsy)',
                    '[{"value":0,"espath":"arguments/0"}]'
                ].join('\n'));
            }
            if (option.saveContextOnFail) {
                baseAssert.deepEqual(e.powerAssertContext, {
                    "source": {
                        "content":"assert.ok(falsy)",
                        "filepath":"/path/to/some_test.js",
                        "line": 1
                    },
                    "args":[
                        {
                            "value":0,
                            "events":[
                                {"value":0,"espath":"arguments/0"}
                            ]
                        }
                    ]
                });
            }
        }
    });
});

suite(JSON.stringify(option) + ' assertion method with two arguments', function () {
    test('both Identifier', function () {
        var foo = 'foo', bar = 'bar';
        try {
            eval(weave('assert.equal(foo, bar);'));
            assert.ok(false, 'AssertionError should be thrown');
        } catch (e) {
            baseAssert.equal(e.name, 'AssertionError');
            if (option.modifyMessageOnFail) {
                baseAssert.equal(e.message, [
                    '/path/to/some_test.js',
                    'assert.equal(foo, bar)',
                    '[{"value":"foo","espath":"arguments/0"},{"value":"bar","espath":"arguments/1"}]'
                ].join('\n'));
            }
            if (option.saveContextOnFail) {
                baseAssert.deepEqual(e.powerAssertContext, {
                    "source":{
                        "content":"assert.equal(foo, bar)",
                        "filepath":"/path/to/some_test.js",
                        "line": 1
                    },
                    "args":[
                        {
                            "value":"foo",
                            "events":[{"value":"foo","espath":"arguments/0"}]
                        },
                        {
                            "value":"bar",
                            "events":[{"value":"bar","espath":"arguments/1"}]
                        }
                    ]
                });
            }
        }
    });

    test('first argument is Literal', function () {
        var bar = 'bar';
        try {
            eval(weave('assert.equal("foo", bar);'));
            assert.ok(false, 'AssertionError should be thrown');
        } catch (e) {
            baseAssert.equal(e.name, 'AssertionError');
            if (option.modifyMessageOnFail) {
                baseAssert.equal(e.message, [
                    '/path/to/some_test.js',
                    'assert.equal("foo", bar)',
                    '[{"value":"bar","espath":"arguments/1"}]'
                ].join('\n'));
            }
            if (option.saveContextOnFail) {
                baseAssert.deepEqual(e.powerAssertContext, {
                    "source":{
                        "content":"assert.equal(\"foo\", bar)",
                        "filepath":"/path/to/some_test.js",
                        "line": 1
                    },
                    "args": [
                        {
                            "value": "bar",
                            "events": [{"value":"bar","espath":"arguments/1"}]
                        }
                    ]
                });
            }
        }
    });

    test('second argument is Literal', function () {
        var foo = 'foo';
        try {
            eval(weave('assert.equal(foo, "bar");'));
            assert.ok(false, 'AssertionError should be thrown');
        } catch (e) {
            baseAssert.equal(e.name, 'AssertionError');
            if (option.modifyMessageOnFail) {
                baseAssert.equal(e.message, [
                    '/path/to/some_test.js',
                    'assert.equal(foo, "bar")',
                    '[{"value":"foo","espath":"arguments/0"}]'
                ].join('\n'));
            }
            if (option.saveContextOnFail) {
                baseAssert.deepEqual(e.powerAssertContext, {
                    "source":{
                        "content":"assert.equal(foo, \"bar\")",
                        "filepath":"/path/to/some_test.js",
                        "line": 1
                    },
                    "args":[
                        {
                            "value":"foo",
                            "events":[{"value":"foo","espath":"arguments/0"}]
                        }
                    ]
                });
            }
        }
    });
});

}

testWithOption({
    modifyMessageOnFail: false,
    saveContextOnFail: false
});

testWithOption({
    modifyMessageOnFail: true,
    saveContextOnFail: false
});

testWithOption({
    modifyMessageOnFail: false,
    saveContextOnFail: true
});

testWithOption({
    modifyMessageOnFail: true,
    saveContextOnFail: true
});

}));
<|endoftext|>


<commit_before>var test = require('tape')
var makeOsm = require('./create_db')

var versions = {}
var ways = []
var osm

test('setup db', function (t) {
  t.plan(9)
  osm = makeOsm()
  var batch = [
    { type: 'put', key: 'A', value: { type: 'node', lat: 64.5, lon: -147.3 } },
    { type: 'put', key: 'B', value: { type: 'node', lat: 1.0, lon: 2.0 } },
    { type: 'put', key: 'C', value: { type: 'node', lat: 3.0, lon: 4.0 } },
    { type: 'put', key: 'D', value: { type: 'node', lat: 64.123, lon: -147.56 } },
    { type: 'put', key: 'F', value: { type: 'way', refs: [ 'A', 'B' ] } }
  ]
  osm.batch(batch, function (err, nodes) {
    t.error(err)
    nodes.forEach(function (node) {
      versions[node.value.k] = node.key
    })
    ways[0] = versions.F
    console.log('way0 version:', ways[0])
    osm.ready(ready)
  })
  // We start with 4 nodes, with 'A' and 'B' referenced by way 'F'
  function ready () {
    osm.refs.list('A', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [ways[0]], 'A referenced by original way')
    })
    osm.refs.list('B', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [ways[0]], 'B referenced by original way')
    })
    osm.refs.list('C', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [], 'No ways should reference C')
    })
    osm.refs.list('D', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [], 'No ways should reference D')
    })
  }
})

test('modify way', function (t) {
  t.plan(9)
  // modify original way
  var way1 = { type: 'way', refs: [ 'A', 'C' ] }
  osm.put('F', way1, {links: [versions.F]}, function (err, doc) {
    t.error(err)
    ways[1] = doc.key
    console.log('way1 version:', ways[1])
    osm.ready(ready)
  })
  /**
   *
   * way0 <---- way1
   *
   */
  // After modifying way 'F' to point to 'A' and 'C' there is a single head
  // (no forks), so the join on node 'B' should not refer to any way.
  function ready () {
    osm.refs.list('A', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [ways[1]], 'A referenced by way1')
    })
    osm.refs.list('B', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [], 'B no longer referenced')
    })
    osm.refs.list('C', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [ways[1]], 'C referenced by way1')
    })
    osm.refs.list('D', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [], 'No ways should reference D')
    })
  }
})

test('fork way', function (t) {
  t.plan(9)
  // create fork of original way
  var way2 = { type: 'way', refs: [ 'A', 'D' ] }
  osm.put('F', way2, {links: [versions.F]}, function (err, doc) {
    ways[2] = doc.key
    console.log('way2 version:', ways[2])
    t.error(err)
    osm.ready(ready)
  })
  /**
   *          /---- way1
   * way0 <---
   *          \---- way2
   *
   */
  // Now the way is forked, 'A' should be referenced by both forks, 'C' by the
  // first fork, 'D' by the second fork, and 'B' should not be referenced by either
  function ready () {
    osm.refs.list('A', function (err, refs) {
      t.error(err)
      t.deepEqual([ways[1], ways[2]].sort(), refs.map(mapKeys).sort(), 'A referenced by way1 and way2')
    })
    osm.refs.list('B', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [], 'B no longer referenced')
    })
    osm.refs.list('C', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [ways[1]], 'C referenced by way1')
    })
    osm.refs.list('D', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [ways[2]], 'D referenced by way2')
    })
  }
})

test('delete a fork', function (t) {
  t.plan(9)
  // Delete first fork
  osm.del('F', {links: [ways[1]]}, function (err, doc) {
    ways[3] = doc.key
    t.error(err)
    osm.ready(ready)
  })
  /**
   *          /---- way1 <--- way3(deleted)
   * way0 <---
   *          \---- way2
   *
   */
  // The way is still forked, but one of the forks is deleted. 'A' should probably
  // still reference both forks? 'B' should not be referenced by anything.
  // 'C' was only referenced by the now deleted fork.
  function ready () {
    osm.refs.list('A', function (err, refs) {
      t.error(err)
      // TODO: change this if we change deleted fork join behaviour
      t.deepEqual(refs.map(mapKeys), [ways[2]], 'A referenced by way2')
    })
    osm.refs.list('B', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [], 'B no longer referenced')
    })
    osm.refs.list('C', function (err, refs) {
      t.error(err)
      // TODO: change this if we change deleted join behaviour
      t.deepEqual(refs.map(mapKeys), [], 'C no longer referenced')
    })
    osm.refs.list('D', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [ways[2]], 'D referenced by way2')
    })
  }
})

test('delete way completely', function (t) {
  t.plan(9)
  osm.del('F', function (err, doc) {
    t.error(err)
    osm.ready(ready)
  })
  /**
   *          /--- way1 <--- way3(deleted) <---\
   * way0 <---                                  ---- way4(deleted)
   *          \--- way2 <----------------------/
   */
  function ready () {
    osm.refs.list('A', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [], 'A no longer referenced')
    })
    osm.refs.list('B', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [], 'B no longer referenced')
    })
    osm.refs.list('C', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [], 'C no longer referenced')
    })
    osm.refs.list('D', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [], 'D no longer referenced')
    })
  }
})

function mapKeys (ref) {
  return ref.key
}

<commit_msg>test: expect deleted way tombstones in refs results<commit_after>var test = require('tape')
var makeOsm = require('./create_db')

var versions = {}
var ways = []
var osm

test('setup db', function (t) {
  t.plan(9)
  osm = makeOsm()
  var batch = [
    { type: 'put', key: 'A', value: { type: 'node', lat: 64.5, lon: -147.3 } },
    { type: 'put', key: 'B', value: { type: 'node', lat: 1.0, lon: 2.0 } },
    { type: 'put', key: 'C', value: { type: 'node', lat: 3.0, lon: 4.0 } },
    { type: 'put', key: 'D', value: { type: 'node', lat: 64.123, lon: -147.56 } },
    { type: 'put', key: 'F', value: { type: 'way', refs: [ 'A', 'B' ] } }
  ]
  osm.batch(batch, function (err, nodes) {
    t.error(err)
    nodes.forEach(function (node) {
      versions[node.value.k] = node.key
    })
    ways[0] = versions.F
    console.log('way0 version:', ways[0])
    osm.ready(ready)
  })
  // We start with 4 nodes, with 'A' and 'B' referenced by way 'F'
  function ready () {
    osm.refs.list('A', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [ways[0]], 'A referenced by original way')
    })
    osm.refs.list('B', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [ways[0]], 'B referenced by original way')
    })
    osm.refs.list('C', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [], 'No ways should reference C')
    })
    osm.refs.list('D', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [], 'No ways should reference D')
    })
  }
})

test('modify way', function (t) {
  t.plan(9)
  // modify original way
  var way1 = { type: 'way', refs: [ 'A', 'C' ] }
  osm.put('F', way1, {links: [versions.F]}, function (err, doc) {
    t.error(err)
    ways[1] = doc.key
    console.log('way1 version:', ways[1])
    osm.ready(ready)
  })
  /**
   *
   * way0 <---- way1
   *
   */
  // After modifying way 'F' to point to 'A' and 'C' there is a single head
  // (no forks), so the join on node 'B' should not refer to any way.
  function ready () {
    osm.refs.list('A', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [ways[1]], 'A referenced by way1')
    })
    osm.refs.list('B', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [], 'B no longer referenced')
    })
    osm.refs.list('C', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [ways[1]], 'C referenced by way1')
    })
    osm.refs.list('D', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [], 'No ways should reference D')
    })
  }
})

test('fork way', function (t) {
  t.plan(9)
  // create fork of original way
  var way2 = { type: 'way', refs: [ 'A', 'D' ] }
  osm.put('F', way2, {links: [versions.F]}, function (err, doc) {
    ways[2] = doc.key
    console.log('way2 version:', ways[2])
    t.error(err)
    osm.ready(ready)
  })
  /**
   *          /---- way1
   * way0 <---
   *          \---- way2
   *
   */
  // Now the way is forked, 'A' should be referenced by both forks, 'C' by the
  // first fork, 'D' by the second fork, and 'B' should not be referenced by either
  function ready () {
    osm.refs.list('A', function (err, refs) {
      t.error(err)
      t.deepEqual([ways[1], ways[2]].sort(), refs.map(mapKeys).sort(), 'A referenced by way1 and way2')
    })
    osm.refs.list('B', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [], 'B no longer referenced')
    })
    osm.refs.list('C', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [ways[1]], 'C referenced by way1')
    })
    osm.refs.list('D', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [ways[2]], 'D referenced by way2')
    })
  }
})

test('delete a fork', function (t) {
  t.plan(9)
  // Delete first fork
  osm.del('F', {links: [ways[1]]}, function (err, doc) {
    ways[3] = doc.key
    t.error(err)
    osm.ready(ready)
  })
  /**
   *          /---- way1 <--- way3(deleted)
   * way0 <---
   *          \---- way2
   *
   */
  // The way is still forked, but one of the forks is deleted. 'A' should probably
  // still reference both forks? 'B' should not be referenced by anything.
  // 'C' was only referenced by the now deleted fork.
  function ready () {
    osm.refs.list('A', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys).sort(), [ways[3], ways[2]].sort(), 'A referenced by way2')
    })
    osm.refs.list('B', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [], 'B no longer referenced')
    })
    osm.refs.list('C', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [ways[3]], 'C no longer referenced')
    })
    osm.refs.list('D', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [ways[2]], 'D referenced by way2')
    })
  }
})

test('delete way completely', function (t) {
  t.plan(9)
  osm.del('F', function (err, doc) {
    t.error(err)
    ways[4] = doc.key
    osm.ready(ready)
  })
  /**
   *          /--- way1 <--- way3(deleted) <---\
   * way0 <---                                  ---- way4(deleted)
   *          \--- way2 <----------------------/
   */
  function ready () {
    osm.refs.list('A', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [ways[4]], 'A no longer referenced')
    })
    osm.refs.list('B', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [], 'B no longer referenced')
    })
    osm.refs.list('C', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [ways[4]], 'C no longer referenced')
    })
    osm.refs.list('D', function (err, refs) {
      t.error(err)
      t.deepEqual(refs.map(mapKeys), [ways[4]], 'D no longer referenced')
    })
  }
})

function mapKeys (ref) {
  return ref.key
}

<|endoftext|>


<commit_before>// /*eslint-env node*/
// var webpackConfig = require("../webpack.config.js");
// var _ = require("lodash");

// function base() {
//   return {
//     frameworks: ["mocha"],
//     files: ["tests.webpack.js"],
//     preprocessors: {
//       "tests.webpack.js": [ "webpack", "sourcemap" ]
//     },
//     webpack: webpackConfig,
//     webpackServer: {
//       noInfo: true
//     }
//   };
// }

// function local() {
//   return _.extend(base(), {
//     browsers: ["Chrome"],
//     reporters: ["mocha"]
//   });
// }

// function sauceLabs() {
//   var customLaunchers = {
//     sl_chrome: {
//       base: "SauceLabs",
//       browserName: "chrome"
//     },
//     sl_firefox: {
//       base: "SauceLabs",
//       browserName: "firefox"
//     },
//     sl_safari: {
//       base: "SauceLabs",
//       browserName: "safari",
//       platform: "OS X 10.10"
//     },
//     sl_iphone_ios_8: {
//       base: "SauceLabs",
//       browserName: "iphone",
//       version: "8.4",
//       deviceName: "iPhone 6 Plus",
//       deviceOrientation: "portrait"
//     },
//     sl_ie_11: {
//       base: "SauceLabs",
//       browserName: "internet explorer",
//       platform: "Windows 8.1",
//       version: "11"
//     }
//   };

//   return _.extend(base(), {
//     sauceLabs: {
//       testName: "Konbini Tests"
//     },
//     browserDisconnectTimeout: 10000,
//     browserDisconnectTolerance: 1,
//     browserNoActivityTimeout: 4 * 60 * 1000,
//     captureTimeout: 4 * 60 * 1000,
//     customLaunchers: customLaunchers,
//     browsers: Object.keys(customLaunchers),
//     reporters: ["dots", "saucelabs"],
//     singleRun: true
//   });
// }

module.exports = function (config) {
  console.log(config == config); //lol
  // if (process.env.CONTINUOUS_INTEGRATION) {
  //   // We are on travis
  //   config.set(sauceLabs());
  // } else {
  //   config.set(local());
  // }
};
<commit_msg>asdfasdfoaefoiasdfasdf<commit_after>// /*eslint-env node*/
// var webpackConfig = require("../webpack.config.js");
// var _ = require("lodash");

function base() {
  return {
    frameworks: ["mocha"],
    files: ["tests.webpack.js"],
    preprocessors: {
      "tests.webpack.js": [ "webpack", "sourcemap" ]
    },
    webpack: webpackConfig,
    webpackServer: {
      noInfo: true
    }
  };
}

function local() {
  return _.extend(base(), {
    browsers: [], //Chrome
    reporters: ["mocha"]
  });
}

// function sauceLabs() {
//   var customLaunchers = {
//     sl_chrome: {
//       base: "SauceLabs",
//       browserName: "chrome"
//     },
//     sl_firefox: {
//       base: "SauceLabs",
//       browserName: "firefox"
//     },
//     sl_safari: {
//       base: "SauceLabs",
//       browserName: "safari",
//       platform: "OS X 10.10"
//     },
//     sl_iphone_ios_8: {
//       base: "SauceLabs",
//       browserName: "iphone",
//       version: "8.4",
//       deviceName: "iPhone 6 Plus",
//       deviceOrientation: "portrait"
//     },
//     sl_ie_11: {
//       base: "SauceLabs",
//       browserName: "internet explorer",
//       platform: "Windows 8.1",
//       version: "11"
//     }
//   };

//   return _.extend(base(), {
//     sauceLabs: {
//       testName: "Konbini Tests"
//     },
//     browserDisconnectTimeout: 10000,
//     browserDisconnectTolerance: 1,
//     browserNoActivityTimeout: 4 * 60 * 1000,
//     captureTimeout: 4 * 60 * 1000,
//     customLaunchers: customLaunchers,
//     browsers: Object.keys(customLaunchers),
//     reporters: ["dots", "saucelabs"],
//     singleRun: true
//   });
// }

module.exports = function (config) {
  // if (process.env.CONTINUOUS_INTEGRATION) {
  //   // We are on travis
  //   config.set(sauceLabs());
  // } else {
  //   config.set(local());
  // }
  config.set(local());
};
<|endoftext|>


<commit_before>"use strict";
const q = require("q");
import expect from 'expect';

/**
 * Construct a mock HTTP backend, heavily inspired by Angular.js.
 * @constructor
 */
function HttpBackend() {
    this.requests = [];
    this.expectedRequests = [];
    const self = this;
    // the request function dependency that the SDK needs.
    this.requestFn = function(opts, callback) {
        const req = new Request(opts, callback);
        console.log("HTTP backend received request: " + req);
        self.requests.push(req);

        const abort = function() {
            const idx = self.requests.indexOf(req);
            if (idx >= 0) {
                console.log("Aborting HTTP request: %s %s", opts.method,
                            opts.uri);
                self.requests.splice(idx, 1);
                req.callback("aborted");
            }
        };

        return {
            abort: abort,
        };
    };
}
HttpBackend.prototype = {
    /**
     * Respond to all of the requests (flush the queue).
     * @param {string} path The path to flush (optional) default: all.
     * @param {integer} numToFlush The number of things to flush (optional), default: all.
     * @param {integer=} waitTime  The time (in ms) to wait for a request to happen.
     *    default: 5
     *
     * @return {Promise} resolves when there is nothing left to flush, with the
     *    number of requests flushed
     */
    flush: function(path, numToFlush, waitTime) {
        const defer = q.defer();
        const self = this;
        let flushed = 0;
        let triedWaiting = false;
        if (waitTime === undefined) {
            waitTime = 5;
        }
        console.log(
            "HTTP backend flushing... (path=" + path
            + " numToFlush=" + numToFlush
            + " waitTime=" + waitTime
            + ")",
        );
        const tryFlush = function() {
            // if there's more real requests and more expected requests, flush 'em.
            console.log(
                "  trying to flush queue => reqs=[" + self.requests
                + "] expected=[" + self.expectedRequests
                + "]",
            );
            if (self._takeFromQueue(path)) {
                // try again on the next tick.
                flushed += 1;
                if (numToFlush && flushed === numToFlush) {
                    console.log("  Flushed assigned amount:", numToFlush);
                    defer.resolve(flushed);
                } else {
                    console.log("  flushed. Trying for more.");
                    setTimeout(tryFlush, 0);
                }
            } else if (flushed === 0 && !triedWaiting) {
                // we may not have made the request yet, wait a generous amount of
                // time before giving up.
                console.log(
                    "  nothing to flush yet; waiting " + waitTime +
                    "ms for requests.")
                setTimeout(tryFlush, waitTime);
                triedWaiting = true;
            } else {
                if (flushed === 0) {
                    console.log("  nothing to flush; giving up");
                } else {
                    console.log(
                        "  no more flushes after flushing", flushed,
                        "requests",
                    );
                }
                defer.resolve(flushed);
            }
        };

        setTimeout(tryFlush, 0);

        return defer.promise;
    },

    /**
     * Attempts to resolve requests/expected requests.
     * @param {string} path The path to flush (optional) default: all.
     * @return {boolean} true if something was resolved.
     */
    _takeFromQueue: function(path) {
        let req = null;
        let i;
        let j;
        let matchingReq = null;
        let expectedReq = null;
        let testResponse = null;
        for (i = 0; i < this.requests.length; i++) {
            req = this.requests[i];
            for (j = 0; j < this.expectedRequests.length; j++) {
                expectedReq = this.expectedRequests[j];
                if (path && path !== expectedReq.path) {
                    continue;
                }
                if (expectedReq.method === req.method &&
                        req.path.indexOf(expectedReq.path) !== -1) {
                    if (!expectedReq.data || (JSON.stringify(expectedReq.data) ===
                            JSON.stringify(req.data))) {
                        matchingReq = expectedReq;
                        this.expectedRequests.splice(j, 1);
                        break;
                    }
                }
            }

            if (matchingReq) {
                // remove from request queue
                this.requests.splice(i, 1);
                i--;

                for (j = 0; j < matchingReq.checks.length; j++) {
                    matchingReq.checks[j](req);
                }
                testResponse = matchingReq.response;
                console.log("    responding to %s", matchingReq.path);
                let body = testResponse.body;
                if (Object.prototype.toString.call(body) == "[object Function]") {
                    body = body(req.path, req.data);
                }
                req.callback(
                    testResponse.err, testResponse.response, body,
                );
                matchingReq = null;
            }
        }
        if (testResponse) {  // flushed something
            return true;
        }
        return false;
    },

    /**
     * Makes sure that the SDK hasn't sent any more requests to the backend.
     */
    verifyNoOutstandingRequests: function() {
        const firstOutstandingReq = this.requests[0] || {};
        expect(this.requests.length).toEqual(0,
            "Expected no more HTTP requests but received request to " +
            firstOutstandingReq.path,
        );
    },

    /**
     * Makes sure that the test doesn't have any unresolved requests.
     */
    verifyNoOutstandingExpectation: function() {
        const firstOutstandingExpectation = this.expectedRequests[0] || {};
        expect(this.expectedRequests.length).toEqual(0,
            "Expected to see HTTP request for " + firstOutstandingExpectation.path,
        );
    },

    /**
     * Create an expected request.
     * @param {string} method The HTTP method
     * @param {string} path The path (which can be partial)
     * @param {Object} data The expected data.
     * @return {Request} An expected request.
     */
    when: function(method, path, data) {
        const pendingReq = new ExpectedRequest(method, path, data);
        this.expectedRequests.push(pendingReq);
        return pendingReq;
    },
};

/**
 * Represents the expectation of a request.
 *
 *
Includes the conditions to be matched against, the checks to be made,
 * and the response to be returned.
 *
 * @constructor
 * @param {string} method
 * @param {string} path
 * @param {object?} data
 */
function ExpectedRequest(method, path, data) {
    this.method = method;
    this.path = path;
    this.data = data;
    this.response = null;
    this.checks = [];
}

ExpectedRequest.prototype = {
    toString: function() {
        return this.method + " " + this.path
    },

    /**
     * Execute a check when this request has been satisfied.
     * @param {Function} fn The function to execute.
     * @return {Request} for chaining calls.
     */
    check: function(fn) {
        this.checks.push(fn);
        return this;
    },

    /**
     * Respond with the given data when this request is satisfied.
     * @param {Number} code The HTTP status code.
     * @param {Object|Function} data The HTTP JSON body. If this is a function,
     * it will be invoked when the JSON body is required (which should be returned).
     */
    respond: function(code, data) {
        this.response = {
            response: {
                statusCode: code,
                headers: {},
            },
            body: data,
            err: null,
        };
    },

    /**
     * Fail with an Error when this request is satisfied.
     * @param {Number} code The HTTP status code.
     * @param {Error} err The error to throw (e.g. Network Error)
     */
    fail: function(code, err) {
        this.response = {
            response: {
                statusCode: code,
                headers: {},
            },
            body: null,
            err: err,
        };
    },
};

/**
 * Represents a request made by the app.
 *
 * @constructor
 * @param {object} opts opts passed to request()
 * @param {function} callback
 */
function Request(opts, callback) {
    this.opts = opts;
    this.callback = callback;

    Object.defineProperty(this, 'method', {
        get: function() {
            return opts.method;
        },
    });

    Object.defineProperty(this, 'path', {
        get: function() {
            return opts.uri;
        },
    });

    Object.defineProperty(this, 'data', {
        get: function() {
            return opts.body;
        },
    });

    Object.defineProperty(this, 'queryParams', {
        get: function() {
            return opts.qs;
        },
    });

    Object.defineProperty(this, 'headers', {
        get: function() {
            return opts.headers || {};
        },
    });
}

Request.prototype = {
    toString: function() {
        return this.method + " " + this.path;
    },
};

/**
 * The HttpBackend class.
 */
module.exports = HttpBackend;
<commit_msg>Improve logging in mock-request<commit_after>"use strict";
const q = require("q");
import expect from 'expect';

/**
 * Construct a mock HTTP backend, heavily inspired by Angular.js.
 * @constructor
 */
function HttpBackend() {
    this.requests = [];
    this.expectedRequests = [];
    const self = this;
    // the request function dependency that the SDK needs.
    this.requestFn = function(opts, callback) {
        const req = new Request(opts, callback);
        console.log(`${Date.now()} HTTP backend received request: ${req}`);
        self.requests.push(req);

        const abort = function() {
            const idx = self.requests.indexOf(req);
            if (idx >= 0) {
                console.log("Aborting HTTP request: %s %s", opts.method,
                            opts.uri);
                self.requests.splice(idx, 1);
                req.callback("aborted");
            }
        };

        return {
            abort: abort,
        };
    };
}
HttpBackend.prototype = {
    /**
     * Respond to all of the requests (flush the queue).
     * @param {string} path The path to flush (optional) default: all.
     * @param {integer} numToFlush The number of things to flush (optional), default: all.
     * @param {integer=} waitTime  The time (in ms) to wait for a request to happen.
     *    default: 5
     *
     * @return {Promise} resolves when there is nothing left to flush, with the
     *    number of requests flushed
     */
    flush: function(path, numToFlush, waitTime) {
        const defer = q.defer();
        const self = this;
        let flushed = 0;
        let triedWaiting = false;
        if (waitTime === undefined) {
            waitTime = 5;
        }

        function log(msg) {
            console.log(`${Date.now()} flush[${path || ''}]: ${msg}`);
        }

        log("HTTP backend flushing... (path=" + path
            + " numToFlush=" + numToFlush
            + " waitTime=" + waitTime
            + ")",
        );
        const tryFlush = function() {
            // if there's more real requests and more expected requests, flush 'em.
            log(`  trying to flush => reqs=[${self.requests}] ` +
                `expected=[${self.expectedRequests}]`,
            );
            if (self._takeFromQueue(path)) {
                // try again on the next tick.
                flushed += 1;
                if (numToFlush && flushed === numToFlush) {
                    log(`Flushed assigned amount: ${numToFlush}`);
                    defer.resolve(flushed);
                } else {
                    log(`  flushed. Trying for more.`);
                    setTimeout(tryFlush, 0);
                }
            } else if (flushed === 0 && !triedWaiting) {
                // we may not have made the request yet, wait a generous amount of
                // time before giving up.
                log(`  nothing to flush yet; waiting for requests.`);
                setTimeout(tryFlush, waitTime);
                triedWaiting = true;
            } else {
                if (flushed === 0) {
                    log("nothing to flush; giving up");
                } else {
                    log(`no more flushes after flushing ${flushed} requests`);
                }
                defer.resolve(flushed);
            }
        };

        setTimeout(tryFlush, 0);

        return defer.promise;
    },

    /**
     * Attempts to resolve requests/expected requests.
     * @param {string} path The path to flush (optional) default: all.
     * @return {boolean} true if something was resolved.
     */
    _takeFromQueue: function(path) {
        let req = null;
        let i;
        let j;
        let matchingReq = null;
        let expectedReq = null;
        let testResponse = null;
        for (i = 0; i < this.requests.length; i++) {
            req = this.requests[i];
            for (j = 0; j < this.expectedRequests.length; j++) {
                expectedReq = this.expectedRequests[j];
                if (path && path !== expectedReq.path) {
                    continue;
                }
                if (expectedReq.method === req.method &&
                        req.path.indexOf(expectedReq.path) !== -1) {
                    if (!expectedReq.data || (JSON.stringify(expectedReq.data) ===
                            JSON.stringify(req.data))) {
                        matchingReq = expectedReq;
                        this.expectedRequests.splice(j, 1);
                        break;
                    }
                }
            }

            if (matchingReq) {
                // remove from request queue
                this.requests.splice(i, 1);
                i--;

                for (j = 0; j < matchingReq.checks.length; j++) {
                    matchingReq.checks[j](req);
                }
                testResponse = matchingReq.response;
                console.log(`${Date.now()}    responding to ${matchingReq.path}`);
                let body = testResponse.body;
                if (Object.prototype.toString.call(body) == "[object Function]") {
                    body = body(req.path, req.data);
                }
                req.callback(
                    testResponse.err, testResponse.response, body,
                );
                matchingReq = null;
            }
        }
        if (testResponse) {  // flushed something
            return true;
        }
        return false;
    },

    /**
     * Makes sure that the SDK hasn't sent any more requests to the backend.
     */
    verifyNoOutstandingRequests: function() {
        const firstOutstandingReq = this.requests[0] || {};
        expect(this.requests.length).toEqual(0,
            "Expected no more HTTP requests but received request to " +
            firstOutstandingReq.path,
        );
    },

    /**
     * Makes sure that the test doesn't have any unresolved requests.
     */
    verifyNoOutstandingExpectation: function() {
        const firstOutstandingExpectation = this.expectedRequests[0] || {};
        expect(this.expectedRequests.length).toEqual(0,
            "Expected to see HTTP request for " + firstOutstandingExpectation.path,
        );
    },

    /**
     * Create an expected request.
     * @param {string} method The HTTP method
     * @param {string} path The path (which can be partial)
     * @param {Object} data The expected data.
     * @return {Request} An expected request.
     */
    when: function(method, path, data) {
        const pendingReq = new ExpectedRequest(method, path, data);
        this.expectedRequests.push(pendingReq);
        return pendingReq;
    },
};

/**
 * Represents the expectation of a request.
 *
 *
Includes the conditions to be matched against, the checks to be made,
 * and the response to be returned.
 *
 * @constructor
 * @param {string} method
 * @param {string} path
 * @param {object?} data
 */
function ExpectedRequest(method, path, data) {
    this.method = method;
    this.path = path;
    this.data = data;
    this.response = null;
    this.checks = [];
}

ExpectedRequest.prototype = {
    toString: function() {
        return this.method + " " + this.path
    },

    /**
     * Execute a check when this request has been satisfied.
     * @param {Function} fn The function to execute.
     * @return {Request} for chaining calls.
     */
    check: function(fn) {
        this.checks.push(fn);
        return this;
    },

    /**
     * Respond with the given data when this request is satisfied.
     * @param {Number} code The HTTP status code.
     * @param {Object|Function} data The HTTP JSON body. If this is a function,
     * it will be invoked when the JSON body is required (which should be returned).
     */
    respond: function(code, data) {
        this.response = {
            response: {
                statusCode: code,
                headers: {},
            },
            body: data,
            err: null,
        };
    },

    /**
     * Fail with an Error when this request is satisfied.
     * @param {Number} code The HTTP status code.
     * @param {Error} err The error to throw (e.g. Network Error)
     */
    fail: function(code, err) {
        this.response = {
            response: {
                statusCode: code,
                headers: {},
            },
            body: null,
            err: err,
        };
    },
};

/**
 * Represents a request made by the app.
 *
 * @constructor
 * @param {object} opts opts passed to request()
 * @param {function} callback
 */
function Request(opts, callback) {
    this.opts = opts;
    this.callback = callback;

    Object.defineProperty(this, 'method', {
        get: function() {
            return opts.method;
        },
    });

    Object.defineProperty(this, 'path', {
        get: function() {
            return opts.uri;
        },
    });

    Object.defineProperty(this, 'data', {
        get: function() {
            return opts.body;
        },
    });

    Object.defineProperty(this, 'queryParams', {
        get: function() {
            return opts.qs;
        },
    });

    Object.defineProperty(this, 'headers', {
        get: function() {
            return opts.headers || {};
        },
    });
}

Request.prototype = {
    toString: function() {
        return this.method + " " + this.path;
    },
};

/**
 * The HttpBackend class.
 */
module.exports = HttpBackend;
<|endoftext|>


<commit_before>// Run through node with following flags: --trace-deopt --trace-opt --allow-natives-syntax
const nuonces = require('../index.js');
const once = nuonces.stripped;

const reportFiles = process.execArgv.reduce((result, value) => {
	var m = value.match(/^--(?:trace_hydrogen_file|redirect-code-traces-to)=([\w\W]+)$/);
	if (m && m[1]) {
		result.push(m[1]);
	}
	return result;
}, []).join(' and ');

console.log('nuonce properties are treated as ' + (%HasFastProperties(nuonces) ? 'fast' : 'slow'));

function printStatus(fn) {
	var status = %GetOptimizationStatus(fn);
	switch(status) {
		case 1: console.log('Function ' + fn.name + ' is optimized'); break;
		case 2: console.log('Function ' + fn.name + ' is not optimized'); break;
		case 3: console.log('Function ' + fn.name + ' is always optimized'); break;
		case 4: console.log('Function ' + fn.name + ' is never optimized'); break;
		case 6: console.log('Function ' + fn.name + ' is maybe deoptimized'); break;
		case 7: console.log('Function ' + fn.name + ' is optimized by TurboFan'); break;
		default: console.log('Unknown ' + fn.name + ' optimization status: ' + status); break;
	}
}

function createFn (argc) {
	let opts = new Array(argc);
	for (let x = argc; x > 0; x--) {
		opts.push('a' + x);
	}
	opts.push('return ' + (opts.join(' + ') || '0') + ' + Math.random();');
	return new Function(...opts);
}

// Optimize our fn creator so we do not have to check irrelevant deoptimizations
createFn(3);
createFn(2);
%OptimizeFunctionOnNextCall(createFn);
createFn(1);

var fn;
for (let i = 0; i < 3000; ++i) {
	fn = once(createFn(Math.floor(Math.random(4))));
	for (let j = 0; j < 30; j++) {
		fn(j);
	}
}

printStatus(once);
printStatus(fn);

if (reportFiles) {
	console.log('You can now visit http://mrale.ph/irhydra/2/.');
	console.log('Upload ' + reportFiles + ' there for further investigation.');
}
<commit_msg>Fixed test function in optimization test.<commit_after>// Run through node with following flags: --trace-deopt --trace-opt --allow-natives-syntax
const nuonces = require('../index.js');
const once = nuonces.stripped;

const reportFiles = process.execArgv.reduce((result, value) => {
	var m = value.match(/^--(?:trace_hydrogen_file|redirect-code-traces-to)=([\w\W]+)$/);
	if (m && m[1]) {
		result.push(m[1]);
	}
	return result;
}, []).join(' and ');

console.log('nuonce properties are treated as ' + (%HasFastProperties(nuonces) ? 'fast' : 'slow'));

function printStatus(fn) {
	var status = %GetOptimizationStatus(fn);
	switch(status) {
		case 1: console.log('Function ' + fn.name + ' is optimized'); break;
		case 2: console.log('Function ' + fn.name + ' is not optimized'); break;
		case 3: console.log('Function ' + fn.name + ' is always optimized'); break;
		case 4: console.log('Function ' + fn.name + ' is never optimized'); break;
		case 6: console.log('Function ' + fn.name + ' is maybe deoptimized'); break;
		case 7: console.log('Function ' + fn.name + ' is optimized by TurboFan'); break;
		default: console.log('Unknown ' + fn.name + ' optimization status: ' + status); break;
	}
}

function createFn (argc) {
	let opts = new Array(argc);
	for (let x = argc; x >= 0; x--) {
		opts[x] = 'a' + x;
	}
	opts.push('return ' + (opts.join(' + ') || '0') + ' + ' + Math.random() + ';');
	return new Function(...opts);
}

// Optimize our fn creator so we do not have to check irrelevant deoptimizations
createFn(3);
createFn(2);
%OptimizeFunctionOnNextCall(createFn);
createFn(1);

var fn;
for (let i = 0; i < 3000; ++i) {
	fn = once(createFn(Math.floor(Math.random()*5)));
	for (let j = 0; j < 30; j++) {
		fn(j);
	}
}

printStatus(once);
printStatus(fn);

if (reportFiles) {
	console.log('You can now visit http://mrale.ph/irhydra/2/.');
	console.log('Upload ' + reportFiles + ' there for further investigation.');
}
<|endoftext|>


<commit_before>/* Copyright 2015 Christine S. MacNeill

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by appli cable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

var Receiver = require ('../model/Receiver.js');
var test = require('tape');
var Formats = require('../model/Formats.js');
var Transports = require('../model/Transports.js');

var methods = Receiver.prototype;

var bbcReceiverJSON = `{
    "description": "ap-z800-4 quad rtp receiver 4",
    "tags": {
        "Location": [
            "MCUK"
        ]
    },
    "format": "urn:x-ipstudio:format:video",
    "caps": {},
    "device_id": "0d0cb97e-b96a-4a39-887f-d491492d9081",
    "version": "1441895693:480000000",
    "label": "MCUK Gallery QuadView Right 4",
    "id": "3350d113-1593-4271-a7f5-f4974415bb8e",
    "transport": "urn:x-ipstudio:transport:rtp",
    "subscription": {
        "sender_id": "55311762-8003-48fa-a645-0a0c7621ce45"
    }
}`;

var bbcReceiver = new Receiver(
  '3350d113-1593-4271-a7f5-f4974415bb8e',
  '1441895693:480000000',
  'MCUK Gallery QuadView Right 4',
  'ap-z800-4 quad rtp receiver 4',
  'urn:x-ipstudio:format:video',
  {}, // caps
  { Location : [ 'MCUK' ]},
  '0d0cb97e-b96a-4a39-887f-d491492d9081',
  'urn:x-ipstudio:transport:rtp',
  { sender_id : 'urn:x-ipstudio:transport:rtp' }
);
<commit_msg>Interim work on receiver spec.<commit_after>/* Copyright 2015 Christine S. MacNeill

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by appli cable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

var Receiver = require ('../model/Receiver.js');
var test = require('tape');
var Formats = require('../model/Formats.js');
var Transports = require('../model/Transports.js');

var methods = Receiver.prototype;

var bbcReceiverJSON = `{
    "description": "ap-z800-4 quad rtp receiver 4",
    "tags": {
        "Location": [
            "MCUK"
        ]
    },
    "format": "urn:x-ipstudio:format:video",
    "caps": {},
    "device_id": "0d0cb97e-b96a-4a39-887f-d491492d9081",
    "version": "1441895693:480000000",
    "label": "MCUK Gallery QuadView Right 4",
    "id": "3350d113-1593-4271-a7f5-f4974415bb8e",
    "transport": "urn:x-ipstudio:transport:rtp",
    "subscription": {
        "sender_id": "55311762-8003-48fa-a645-0a0c7621ce45"
    }
}`;

var bbcReceiver = new Receiver(
  '3350d113-1593-4271-a7f5-f4974415bb8e',
  '1441895693:480000000',
  'MCUK Gallery QuadView Right 4',
  'ap-z800-4 quad rtp receiver 4',
  'urn:x-ipstudio:format:video',
  {}, // caps
  { Location : [ 'MCUK' ] },
  '0d0cb97e-b96a-4a39-887f-d491492d9081',
  'urn:x-ipstudio:transport:rtp',
  { sender_id : 'urn:x-ipstudio:transport:rtp' }
);
<|endoftext|>


<commit_before>var moment = require('moment-timezone')
var sherlock = require('./other_modules/sherlock/sherlock')

function createDateFromText (inputText) {
  var convertedToUTC = moment.tz(inputText, 'America/Chicago').tz('UTC')
  var utcDate = new Date(convertedToUTC.format())
  console.log('Converted to ' + utcDate)
  return utcDate
}

function processDateAndTitleFromText (inputText, callback) {
  var sherlocked = sherlock.parse(inputText)
  if (sherlocked.startDate == null) {
    callback("Couldn't work out that time sorry. 😕", null, null)
  }
  callback(null, sherlocked.startDate, sherlocked.eventTitle)
}

module.exports = {
  createDateFromText,
  processDateAndTitleFromText
}
<commit_msg>scheduler<commit_after>var moment = require('moment-timezone')
var sherlock = require('./other_modules/sherlock/sherlock')

function createDateFromText (inputText) {
  var convertedToUTC = moment.tz(inputText, 'America/Chicago').tz('UTC')
  var utcDate = new Date(convertedToUTC.format())
  console.log('Converted to ' + utcDate)
  return utcDate
}

function processDateAndTitleFromText (inputText, callback) {
  var sherlocked = sherlock.parse(inputText)
  let now = new Date()
  console.log('NOW:' + now)
  if (sherlocked.startDate == null) {
    callback("Couldn't work out that time sorry. 😕", null, null)
  }
  callback(null, sherlocked.startDate, sherlocked.eventTitle)
}

module.exports = {
  createDateFromText,
  processDateAndTitleFromText
}
<|endoftext|>


<commit_before>/*    Copyright 2016 Firewalla LLC
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
'use strict';

let log = require('./logger.js')(__filename);

let redis = require('redis');
let rclient = redis.createClient();

let Promise = require('bluebird');
Promise.promisifyAll(redis.RedisClient.prototype);
Promise.promisifyAll(redis.Multi.prototype);

let async = require('asyncawait/async');
let await = require('asyncawait/await');

let util = require('util');

let instance = null;
class AppTool {
  constructor() {
    if(!instance) {
      instance = this;
    }
    return instance;
  }

  getAppInfo(msg) {
    return msg.appInfo;
  }

  isAppReadyForNewDeviceHandler(appInfo) {
    if(appInfo)
      return true
    else
      return false;
  }

  // when app supports providing app info, it means legacy flow info can be discarded
  isAppReadyToDiscardLegacyFlowInfo(appInfo) {
    if(appInfo)
      return true
    else
      return false;
  }

  isAppReadyToDiscardLegacyAlarm(appInfo) {
    if(appInfo)
      return true
    else
      return false;
  }
}

module.exports = function () {
  return new AppTool();
}
<commit_msg>add app version limitation on device handler and flow info<commit_after>/*    Copyright 2016 Firewalla LLC
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
'use strict';

let log = require('./logger.js')(__filename);

let redis = require('redis');
let rclient = redis.createClient();

let Promise = require('bluebird');
Promise.promisifyAll(redis.RedisClient.prototype);
Promise.promisifyAll(redis.Multi.prototype);

let async = require('asyncawait/async');
let await = require('asyncawait/await');

let util = require('util');

let instance = null;
class AppTool {
  constructor() {
    if(!instance) {
      instance = this;
    }
    return instance;
  }

  getAppInfo(msg) {
    return msg.appInfo;
  }

  isAppReadyForNewDeviceHandler(appInfo) {
    if(appInfo && appInfo.version && appInfo.version >= "1.18")
      return true
    else
      return false;
  }

  // when app supports providing app info, it means legacy flow info can be discarded
  isAppReadyToDiscardLegacyFlowInfo(appInfo) {
    if(appInfo && appInfo.version && appInfo.version >= "1.18")
      return true
    else
      return false;
  }

  isAppReadyToDiscardLegacyAlarm(appInfo) {
    if(appInfo)
      return true
    else
      return false;
  }
}

module.exports = function () {
  return new AppTool();
}
<|endoftext|>


<commit_before>onload = function() {

	var harness = new pdf_test_harness();

	var body = document.getElementsByTagName('body')[0];
	body.style.display = 'flex';

	var div = document.createElement('div');
	div.setAttribute('style', 'position:fixed;height:20px;width:100%;background:lightblue');
	body.appendChild(div);

	var div2 = document.createElement('div');
	div2.setAttribute('style', 'position:fixed;display:flex;top:20px; bottom:0;width:100%');
	body.appendChild(div2);

	var btn1 = document.createElement('input');
	btn1.setAttribute('type', 'radio');
	btn1.setAttribute('name', 'view');
	div.appendChild(btn1);
	btn1.checked = true;

	var lbl1 = document.createElement('label');
	lbl1.setAttribute('for', 'btn1');
	lbl1.innerHTML = 'PDF'
	div.appendChild(lbl1);

	var btn2 = document.createElement('input');
	btn2.setAttribute('type', 'radio');
	btn2.setAttribute('name', 'view');
	div.appendChild(btn2);

	var lbl2 = document.createElement('label');
	lbl2.setAttribute('for', 'btn2');
	lbl2.innerHTML = 'Source'
	div.appendChild(lbl2);

	var btn3 = document.createElement('input');
	btn3.setAttribute('type', 'radio');
	btn3.setAttribute('name', 'view');
	div.appendChild(btn3);

	var lbl3 = document.createElement('label');
	lbl3.setAttribute('for', 'btn3');
	lbl3.innerHTML = 'Both'
	div.appendChild(lbl3);

	harness.source = document.createElement('pre');
	harness.source.setAttribute('style', 'margin-top:0;width:100%;height:100%;position:absolute;top:0px;bottom:0px;overflow:auto');
	div2.appendChild(harness.source);

	harness.iframe = document.createElement('iframe');
	harness.iframe.setAttribute('style', 'width:100%;height:100%;position:absolute;overflow:auto;top:0px;bottom:0px');
	div2.appendChild(harness.iframe);

	if (pdf_test_harness.onload) {
		harness.pdf = pdf_test_harness.onload(harness);
		if (harness.message){
			var popup = document.createElement('div');
			popup.setAttribute('style', 'position:fixed;margin:auto;top:50px;background-color:beige;padding:1em;border:1px solid black');
			popup.innerHTML = harness.message;
			body.appendChild(popup);
			popup.onclick = function(){
				popup.parentNode.removeChild(popup);
			}

		}
	}

	harness.render('pdf');

	btn1.onclick = function() {
		harness.render('pdf');
	}
	btn2.onclick = function() {
		harness.render('source');
	}
	btn3.onclick = function() {
		harness.render('both');
	}
}

pdf_test_harness = function(pdf) {
	this.pdf = pdf;
	this.onload = undefined;
	this.iframe = undefined;

	this.entityMap = {
		"&" : "&",
		"<" : "<",
		">" : ">",
		'"' : '"',
		"'" : ''',
		"/" : '/'
	};

	this.escapeHtml = function(string) {
		return String(string).replace(/[&<>"'\/]/g, function(s) {
			return this.entityMap[s];
		}.bind(this));
	};

	this.getParameterByName = function(name) {
		name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
		var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), results = regex.exec(location.search);
		return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
	};

	this.setPdf = function(pdf) {
		this.pdf = pdf;
		this.rendered = undefined;
		this.render(this.view);
	};

	// generate the pdf, the source code, or both
	this.render = function(view) {
		this.view = view;
		//Current code only lets us render one time.
		if (!this.rendered) {
			this.rendered = this.pdf.output('datauristring');
			this.iframe.src = this.rendered;
			var raw = this.pdf.output();
			raw = this.escapeHtml(raw);
			this.source.innerHTML = raw;
		}
		if ('pdf' === view) {
			this.source.style.display = 'none';
			this.iframe.style.display = 'block';
			this.iframe.style.width = '100%';
		} else if ('source' === view) {
			this.iframe.style.display = 'none';
			this.source.style.display = 'block';
			this.source.style.width = '100%';
		}

		if ('both' === view) {
			raw = this.escapeHtml(raw);
			this.iframe.style.width = '50%';
			this.iframe.style.position = 'relative';
			this.iframe.style.display = 'inline-block';
			this.source.style.width = '50%';
			this.source.style.position = 'relative';
			this.source.style.display = 'inline-block';
		}
	}
}<commit_msg>added header and body to test harness<commit_after>onload = function() {

	var harness = new pdf_test_harness();

	var body = document.getElementsByTagName('body')[0];
	body.style.display = 'flex';

	var div = document.createElement('div');
	div.setAttribute('style', 'position:fixed;height:20px;width:100%;background:lightblue');
	body.appendChild(div);
	harness.header = div;

	var div2 = document.createElement('div');
	div2.setAttribute('style', 'position:fixed;display:flex;top:20px; bottom:0;width:100%');
	body.appendChild(div2);
	harness.body = div2;

	var btn1 = document.createElement('input');
	btn1.setAttribute('type', 'radio');
	btn1.setAttribute('name', 'view');
	div.appendChild(btn1);
	btn1.checked = true;

	var lbl1 = document.createElement('label');
	lbl1.setAttribute('for', 'btn1');
	lbl1.innerHTML = 'PDF'
	div.appendChild(lbl1);

	var btn2 = document.createElement('input');
	btn2.setAttribute('type', 'radio');
	btn2.setAttribute('name', 'view');
	div.appendChild(btn2);

	var lbl2 = document.createElement('label');
	lbl2.setAttribute('for', 'btn2');
	lbl2.innerHTML = 'Source'
	div.appendChild(lbl2);

	var btn3 = document.createElement('input');
	btn3.setAttribute('type', 'radio');
	btn3.setAttribute('name', 'view');
	div.appendChild(btn3);

	var lbl3 = document.createElement('label');
	lbl3.setAttribute('for', 'btn3');
	lbl3.innerHTML = 'Both'
	div.appendChild(lbl3);

	harness.source = document.createElement('pre');
	harness.source.setAttribute('style', 'margin-top:0;width:100%;height:100%;position:absolute;top:0px;bottom:0px;overflow:auto');
	div2.appendChild(harness.source);

	harness.iframe = document.createElement('iframe');
	harness.iframe.setAttribute('style', 'width:100%;height:100%;position:absolute;overflow:auto;top:0px;bottom:0px');
	div2.appendChild(harness.iframe);

	if (pdf_test_harness.onload) {
		harness.pdf = pdf_test_harness.onload(harness);
		if (harness.message){
			var popup = document.createElement('div');
			popup.setAttribute('style', 'position:fixed;margin:auto;top:50px;background-color:beige;padding:1em;border:1px solid black');
			popup.innerHTML = harness.message;
			body.appendChild(popup);
			popup.onclick = function(){
				popup.parentNode.removeChild(popup);
			}

		}
	}

	harness.render('pdf');

	btn1.onclick = function() {
		harness.render('pdf');
	}
	btn2.onclick = function() {
		harness.render('source');
	}
	btn3.onclick = function() {
		harness.render('both');
	}
}

pdf_test_harness = function(pdf) {
	this.pdf = pdf;
	this.onload = undefined;
	this.iframe = undefined;

	this.entityMap = {
		"&" : "&",
		"<" : "<",
		">" : ">",
		'"' : '"',
		"'" : ''',
		"/" : '/'
	};

	this.escapeHtml = function(string) {
		return String(string).replace(/[&<>"'\/]/g, function(s) {
			return this.entityMap[s];
		}.bind(this));
	};

	this.getParameterByName = function(name) {
		name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
		var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), results = regex.exec(location.search);
		return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
	};

	this.setPdf = function(pdf) {
		this.pdf = pdf;
		this.rendered = undefined;
		this.render(this.view);
	};

	// generate the pdf, the source code, or both
	this.render = function(view) {
		this.view = view;
		//Current code only lets us render one time.
		if (!this.rendered) {
			this.rendered = this.pdf.output('datauristring');
			this.iframe.src = this.rendered;
			var raw = this.pdf.output();
			raw = this.escapeHtml(raw);
			this.source.innerHTML = raw;
		}
		if ('pdf' === view) {
			this.source.style.display = 'none';
			this.iframe.style.display = 'block';
			this.iframe.style.width = '100%';
		} else if ('source' === view) {
			this.iframe.style.display = 'none';
			this.source.style.display = 'block';
			this.source.style.width = '100%';
		}

		if ('both' === view) {
			raw = this.escapeHtml(raw);
			this.iframe.style.width = '50%';
			this.iframe.style.position = 'relative';
			this.iframe.style.display = 'inline-block';
			this.source.style.width = '50%';
			this.source.style.position = 'relative';
			this.source.style.display = 'inline-block';
		}
	}
}<|endoftext|>