<commit_before>"use strict";

// Dependencies
var url = require("url");
var async = require("async");
var fs = require("fs");
var https = require("https");

// App variables
var BASE_URL = "https://en.wikipedia.org/wiki/";

var DOWNLOAD_DIR = "./test/spec/local_pages/";
var airlineFixtures = require("../fixtures/airline_routes.options.json");
var airportFixtures = require("../fixtures/airport_links.json");
var iataLocalList = require("../fixtures/airports_iata.data.json");
var file_url = [
  "Category:Lists_of_airline_destinations"
];

for (var i = 0; i < airlineFixtures.length; i += 1) {
  file_url.push(airlineFixtures[i].name);
}

for (var j = 0; j < airportFixtures.length; j += 1) {
  file_url.push(airportFixtures[j].url);
}

for (var k = 0; k < iataLocalList.length; k += 1) {
  file_url.push(iataLocalList[k]);
}

var download_file_httpsGet = function (file_url, callback) {
  if (file_url.indexOf("https") === -1) {
    file_url = BASE_URL + file_url;
  }

  var file_name = decodeURI(url.parse(file_url).pathname.split("/").pop());

  console.log("filename: " + file_name); //eslint-disable-line no-console
  var file = fs.createWriteStream(DOWNLOAD_DIR + file_name);

  https.get(file_url, function (res) {
    res.on("data", function (chunk) {
      file.write(chunk);
    }).on("error", function (err) {
      throw err;
    }).on("end", function () {
      file.end();
      console.log(file_name + " downloaded to " + DOWNLOAD_DIR);
      callback();
    });
  });

};

async.map(file_url, download_file_httpsGet, function (err) {
  if (err) {
    throw err;
  }
  console.log("\nLocal Pages Updated."); //eslint-disable-line no-console
});
<commit_msg>back to split the url after colon<commit_after>"use strict";

// Dependencies
var url = require("url");
var async = require("async");
var fs = require("fs");
var https = require("https");

// App variables
var BASE_URL = "https://en.wikipedia.org/wiki/";

var DOWNLOAD_DIR = "./test/spec/local_pages/";
var airlineFixtures = require("../fixtures/airline_routes.options.json");
var airportFixtures = require("../fixtures/airport_links.json");
var iataLocalList = require("../fixtures/airports_iata.data.json");
var file_url = [
  "Category:Lists_of_airline_destinations"
];

for (var i = 0; i < airlineFixtures.length; i += 1) {
  file_url.push(airlineFixtures[i].name);
}

for (var j = 0; j < airportFixtures.length; j += 1) {
  file_url.push(airportFixtures[j].url);
}

for (var k = 0; k < iataLocalList.length; k += 1) {
  file_url.push(iataLocalList[k]);
}

var download_file_httpsGet = function (file_url, callback) {
  if (file_url.indexOf("https") === -1) {
    file_url = BASE_URL + file_url;
  }
  var file_name = decodeURI(url.parse(file_url).pathname.split("/").pop());

// bermi if I don't add the following line, I am having issues with the tests
// I should be able to use naming like "Category:Lists_of_airline_destinations"
  file_name = file_name.split(":").pop();
  console.log("filename: " + file_name); //eslint-disable-line no-console
  var file = fs.createWriteStream(DOWNLOAD_DIR + file_name);

  https.get(file_url, function (res) {
    res.on("data", function (chunk) {
      file.write(chunk);
    }).on("error", function (err) {
      throw err;
    }).on("end", function () {
      file.end();
      console.log(file_name + " downloaded to " + DOWNLOAD_DIR);
      callback();
    });
  });

};

async.map(file_url, download_file_httpsGet, function (err) {
  if (err) {
    throw err;
  }
  console.log("\nLocal Pages Updated."); //eslint-disable-line no-console
});
<|endoftext|>


<commit_before>var fs = require("fs");

var tape = require("tape"),
    phylotree = require("../dist/phylotree");

tape("tip length export", function(test) {

	let D = [
			[0,  5,  9,  9, 8],
			[5,  0, 10, 10, 9],
			[9, 10,  0,  8, 7],
			[9, 10,  8,  0, 3],
			[8,  9,  7,  3, 0]
	];

	let nodeList = ["A","B","C","D","E"];
	let nj = phylotree.neighborJoining(D, nodeList.length, nodeList)
  let expectedTree = "((((A:2,B:3)InternalNode0:3,C:4)InternalNode1:2,D:2)InternalNode2:0.5,E:0.5):0;"
  test.equal(nj.getNewick(), expectedTree)
  test.end();

});

<commit_msg>updating neighbor joining documentation<commit_after>const tape = require("tape"),
    phylotree = require("../dist/phylotree");

tape("neighbor joining", function(test) {

	const D = [
			[0,  5,  9,  9, 8],
			[5,  0, 10, 10, 9],
			[9, 10,  0,  8, 7],
			[9, 10,  8,  0, 3],
			[8,  9,  7,  3, 0]
	];

	const nodeList = ["A","B","C","D","E"];
	const nj = phylotree.neighborJoining(D, nodeList.length, nodeList);
  const expectedTree = "((((A:2,B:3)InternalNode0:3,C:4)InternalNode1:2,D:2)InternalNode2:0.5,E:0.5):0;";
  test.equal(nj.getNewick(), expectedTree);
  test.end();

});
<|endoftext|>


<commit_before>/**
 * Talisman parsers/brown tests
 * =============================
 */
import assert from 'assert';
import AveragedPercerptronTagger from '../../src/tag/averaged-perceptron';

const sentences = [
  [['today', 'NN'], ['is', 'PRP'], ['a', 'PRP'], ['beautiful', 'JJ'], ['day', 'NN']]
];

describe('averaged-perceptron', function() {

  describe('training', function() {

    it('should initialize tags & classes correctly.', function() {
      const tagger = new AveragedPercerptronTagger();

      tagger.train(sentences);

      assert.deepEqual(tagger.classes, new Set(['JJ', 'PRP', 'NN']));
    });
  });
});
<commit_msg>Tagger correct init<commit_after>/**
 * Talisman parsers/brown tests
 * =============================
 */
import {assert} from 'chai';
import conll from '../../src/parsers/conll';
import AveragedPercerptronTagger from '../../src/tag/averaged-perceptron';
import {loadResource} from '../helpers';

const excerpt = loadResource('conll2000/excerpt.txt'),
      sentences = conll(excerpt);

const CLASSES = [
  'NN',
  'IN',
  'DT',
  'VBZ',
  'RB',
  'VBN',
  'TO',
  'VB',
  'JJ',
  'NNS',
  'NNP',
  ',',
  'CC',
  'POS',
  '.',
  'VBP',
  'VBG',
  'PRP$',
  'CD',
  '``',
  '\'\'',
  'VBD',
  'EX',
  'MD',
  '#',
  '(',
  '$',
  ')',
  'NNPS',
  'PRP',
  'JJS',
  'WP',
  'RBR',
  'JJR',
  'WDT',
  'WRB',
  'RBS',
  'PDT',
  'RP',
  ':'
];

const TAGS = {
  'in': 'IN',
  'the': 'DT',
  'is': 'VBZ',
  'to': 'TO',
  'for': 'IN',
  ',': ',',
  'a': 'DT',
  'from': 'IN',
  'and': 'CC',
  '.': '.',
  'of': 'IN',
  'by': 'IN',
  'rates': 'NNS',
  '%': 'NN',
  'their': 'PRP$',
  '``': '``',
  'The': 'DT',
  'are': 'VBP',
  'on': 'IN',
  '\'\'': '\'\'',
  'said': 'VBD',
  'at': 'IN',
  'be': 'VB',
  '$': '$',
  'Mr.': 'NNP',
  'was': 'VBD',
  'it': 'PRP',
  'U.S.': 'NNP'
};

describe('averaged-perceptron', function() {

  describe('training', function() {

    it('should initialize tags & classes correctly.', function() {
      const tagger = new AveragedPercerptronTagger();

      tagger.train(sentences);
      assert.sameMembers(Array.from(tagger.classes), CLASSES);
      assert.deepEqual(tagger.tags, TAGS);
    });
  });
});
<|endoftext|>


<commit_before>'use strict';
/* global describe, it */
let assert = require('assert');
let Rx = require('rx');
let CycleDOM = require('../../src');
let {mockDOMSource} = require('../../src/mockDOMSource');

describe('mockDOMSource', function () {
  it('should be in accessible in the API', function () {
    assert.strictEqual(typeof CycleDOM.mockDOMSource, 'function');
  });

  it('should make an Observable for clicks on `.foo`', function (done) {
    const userEvents = mockDOMSource({
      '.foo': {
        'click': Rx.Observable.just(135)
      }
    });
    userEvents.select('.foo').events('click').subscribe(ev => {
      assert.strictEqual(ev, 135);
      done();
    })
  });

  it('should make multiple user event Observables', function (done) {
    const userEvents = mockDOMSource({
      '.foo': {
        'click': Rx.Observable.just(135)
      },
      '.bar': {
        'scroll': Rx.Observable.just(2)
      }
    });
    Rx.Observable.combineLatest(
      userEvents.select('.foo').events('click'),
      userEvents.select('.bar').events('scroll'),
      (a, b) => a * b
    ).subscribe(ev => {
      assert.strictEqual(ev, 270);
      done();
    })
  });

  it('should make multiple user event Observables on the same selector', function (done) {
    const userEvents = mockDOMSource({
      '.foo': {
        'click': Rx.Observable.just(135),
        'scroll': Rx.Observable.just(3)
      }
    });
    Rx.Observable.combineLatest(
      userEvents.select('.foo').events('click'),
      userEvents.select('.foo').events('scroll'),
      (a, b) => a * b
    ).subscribe(ev => {
      assert.strictEqual(ev, 405);
      done();
    })
  });

  it('should return an empty Observable if query does not match', function (done) {
    const userEvents = mockDOMSource({
      '.foo': {
        'click': Rx.Observable.just(135)
      }
    });
    let subscribeExecuted = false;
    userEvents.select('.impossible').events('scroll')
      .subscribe(assert.fail, assert.fail, done);
  });

  it('should return empty Observable for select().observable', function (done) {
    const userEvents = mockDOMSource({
      '.foo': {
        'click': Rx.Observable.just(135)
      }
    });
    let subscribeExecuted = false;
    userEvents.select('.foo').observable
      .subscribe(assert.fail, assert.fail, done);
  });
});
<commit_msg>test(mockDOMSource): add test for chaining .select()<commit_after>'use strict';
/* global describe, it */
let assert = require('assert');
let Rx = require('rx');
let CycleDOM = require('../../src');
let {mockDOMSource} = require('../../src/mockDOMSource');

describe('mockDOMSource', function () {
  it('should be in accessible in the API', function () {
    assert.strictEqual(typeof CycleDOM.mockDOMSource, 'function');
  });

  it('should make an Observable for clicks on `.foo`', function (done) {
    const userEvents = mockDOMSource({
      '.foo': {
        'click': Rx.Observable.just(135)
      }
    });
    userEvents.select('.foo').events('click').subscribe(ev => {
      assert.strictEqual(ev, 135);
      done();
    })
  });

  it('should make multiple user event Observables', function (done) {
    const userEvents = mockDOMSource({
      '.foo': {
        'click': Rx.Observable.just(135)
      },
      '.bar': {
        'scroll': Rx.Observable.just(2)
      }
    });
    Rx.Observable.combineLatest(
      userEvents.select('.foo').events('click'),
      userEvents.select('.bar').events('scroll'),
      (a, b) => a * b
    ).subscribe(ev => {
      assert.strictEqual(ev, 270);
      done();
    })
  });

  it('should make multiple user event Observables on the same selector', function (done) {
    const userEvents = mockDOMSource({
      '.foo': {
        'click': Rx.Observable.just(135),
        'scroll': Rx.Observable.just(3)
      }
    });
    Rx.Observable.combineLatest(
      userEvents.select('.foo').events('click'),
      userEvents.select('.foo').events('scroll'),
      (a, b) => a * b
    ).subscribe(ev => {
      assert.strictEqual(ev, 405);
      done();
    })
  });

  it('should return an empty Observable if query does not match', function (done) {
    const userEvents = mockDOMSource({
      '.foo': {
        'click': Rx.Observable.just(135)
      }
    });
    let subscribeExecuted = false;
    userEvents.select('.impossible').events('scroll')
      .subscribe(assert.fail, assert.fail, done);
  });

  it('should return empty Observable for select().observable', function (done) {
    const userEvents = mockDOMSource({
      '.foo': {
        'click': Rx.Observable.just(135)
      }
    });
    let subscribeExecuted = false;
    userEvents.select('.foo').observable
      .subscribe(assert.fail, assert.fail, done);
  });

  it('should return defined Observable when chaining .select()',
    function (done) {
    const mockedDOMSource = mockDOMSource({
      '.bar': {
        '.foo': {
          '.baz': {
            observable: Rx.Observable.just(135)
          }
        }
      }
    });
    mockedDOMSource.select('.bar').select('.foo').select('.baz').observable
      .subscribe(e => {
        assert.strictEqual(e, 135);
        done();
      });
  });
});
<|endoftext|>


<commit_before>"use strict";

var base = require("xbase"),
	fs = require("fs"),
	path = require("path"),
	util = require("util"),
	uuid = require("node-uuid"),
	tiptoe = require("tiptoe");

exports.searchReplace = searchReplace;
function searchReplace(file, match, replace, cb)
{
	tiptoe(
		function loadFile()
		{
			fs.readFile(file, "utf8", this);
		},
		function replaceAndSave(data)
		{
			fs.writeFile(file, data.replace(new RegExp(match, "g"), replace), "utf8", this);
		},
		function handleErrors(err) { setImmediate(function() { cb(err); }); }
	);
}

exports.concat = concat;
function concat(files, dest, options, cb)
{
	if(!cb && typeof(options)==="function")
	{
		cb = options;
		options = {};
	}

	var writeSeperator = 1;

	files = files.slice();

	base.info("Combining to [%s] files: %s", dest, files.join(" "));

	var output = fs.createWriteStream(dest);

	var first = true;
	function concatNext()
	{
		if(first && options.prefix)
			output.write(options.prefix);

		if(options.filePrefixes && files.length)
			output.write(options.filePrefixes[writeSeperator-1]);

		first = false;

		if(options.seperator && (writeSeperator%2)===0)
			output.write(options.seperator);

		writeSeperator++;

		if(!files.length)
		{
			if(options.suffix)
				output.write(options.suffix);

			output.end();
			return cb();
		}

		var input = fs.createReadStream(files.shift());
		input.pipe(output, { end : false });
		input.on("end", concatNext);
	}

	concatNext();
}

exports.copy = copy;
function copy(src, dest, cb)
{
	var cbCalled = false;

	var rd = fs.createReadStream(src);
	rd.on("error", function(err) { done(err); });

	var wr = fs.createWriteStream(dest);
	wr.on("error", function(err) { done(err); });

	wr.on("close", function(ex) { done(); });
	rd.pipe(wr);

	function done(err)
	{
		if(!cbCalled)
		{
			cb(err);
			cbCalled = true;
		}
	}
}

exports.move = move;
function move(src, dest, cb)
{
	tiptoe(
		function checkExisting()
		{
			exports.exists(dest, this);
		},
		function removeExisting(exists)
		{
			if(exists)
				fs.unlink(dest, this);
			else
				this();
		},
		function copyFile()
		{
			copy(src, dest, this);
		},
		function removeFile()
		{
			fs.unlink(src, this);
		},
		function handleErrors(err) { setImmediate(function() { cb(err); }); }
	);
}

exports.generateTempFilePath = generateTempFilePath;
function generateTempFilePath(prefix)
{
	var tempFilePath;
	var existsSync = fs.existsSync ? fs.existsSync : path.existsSync;
	prefix = prefix || "/tmp";

	do
	{
		tempFilePath = path.join(prefix, uuid.v4() + ".tmp");
	} while(existsSync(tempFilePath));

	return tempFilePath;
}

exports.exists = exists;
function exists(target, cb)
{
	fs.exists(target, function(exists) { cb(null, exists); });
}

exports.unlink = unlink;
function unlink(target, cb)
{
	fs.exists(target, function(exists) { if(exists) { fs.unlink(target, cb); } else { return setImmediate(cb); }});
}
<commit_msg>Added suffix support to tmp file<commit_after>"use strict";

var base = require("xbase"),
	fs = require("fs"),
	path = require("path"),
	util = require("util"),
	uuid = require("node-uuid"),
	tiptoe = require("tiptoe");

exports.searchReplace = searchReplace;
function searchReplace(file, match, replace, cb)
{
	tiptoe(
		function loadFile()
		{
			fs.readFile(file, {encoding:"utf8"}, this);
		},
		function replaceAndSave(data)
		{
			fs.writeFile(file, data.replace(new RegExp(match, "g"), replace), {encoding:"utf8"}, this);
		},
		function handleErrors(err) { setImmediate(function() { cb(err); }); }
	);
}

exports.concat = concat;
function concat(files, dest, options, cb)
{
	if(!cb && typeof(options)==="function")
	{
		cb = options;
		options = {};
	}

	var writeSeperator = 1;

	files = files.slice();

	base.info("Combining to [%s] files: %s", dest, files.join(" "));

	var output = fs.createWriteStream(dest);

	var first = true;
	function concatNext()
	{
		if(first && options.prefix)
			output.write(options.prefix);

		if(options.filePrefixes && files.length)
			output.write(options.filePrefixes[writeSeperator-1]);

		first = false;

		if(options.seperator && (writeSeperator%2)===0)
			output.write(options.seperator);

		writeSeperator++;

		if(!files.length)
		{
			if(options.suffix)
				output.write(options.suffix);

			output.end();
			return cb();
		}

		var input = fs.createReadStream(files.shift());
		input.pipe(output, { end : false });
		input.on("end", concatNext);
	}

	concatNext();
}

exports.copy = copy;
function copy(src, dest, cb)
{
	var cbCalled = false;

	var rd = fs.createReadStream(src);
	rd.on("error", function(err) { done(err); });

	var wr = fs.createWriteStream(dest);
	wr.on("error", function(err) { done(err); });

	wr.on("close", function(ex) { done(); });
	rd.pipe(wr);

	function done(err)
	{
		if(!cbCalled)
		{
			cb(err);
			cbCalled = true;
		}
	}
}

exports.move = move;
function move(src, dest, cb)
{
	tiptoe(
		function checkExisting()
		{
			exports.exists(dest, this);
		},
		function removeExisting(exists)
		{
			if(exists)
				fs.unlink(dest, this);
			else
				this();
		},
		function copyFile()
		{
			copy(src, dest, this);
		},
		function removeFile()
		{
			fs.unlink(src, this);
		},
		function handleErrors(err) { setImmediate(function() { cb(err); }); }
	);
}

exports.generateTempFilePath = generateTempFilePath;
function generateTempFilePath(prefix, suffix)
{
	var tempFilePath;
	var existsSync = fs.existsSync ? fs.existsSync : path.existsSync;
	prefix = prefix || "/tmp";

	do
	{
		tempFilePath = path.join(prefix, uuid.v4() + (typeof suffix==="undefined" ? ".tmp" : suffix));
	} while(existsSync(tempFilePath));

	return tempFilePath;
}

exports.exists = exists;
function exists(target, cb)
{
	fs.exists(target, function(exists) { cb(null, exists); });
}

exports.unlink = unlink;
function unlink(target, cb)
{
	fs.exists(target, function(exists) { if(exists) { fs.unlink(target, cb); } else { return setImmediate(cb); }});
}
<|endoftext|>


<commit_before>define(
[
  'underscore',
  'jQuery'
],
function(_, $) { 'use strict';

/*
* Application controller.
*/
var MainController = function($scope, $filter, $modal, bookmarksStorage, appSettings, booleanSearchEngine) {

  // Constant: default value of how many items we want to display on main page.
  var defaultTotalDisplayed = 20;

  $scope.searchText = ''; // Search text
  $scope.bookmarks = []; // All bookmarks
  $scope.filteredBookmarks = [];
  $scope.tags = []; // All tags
  $scope.orders = [ // Different sorting orders
                    {title:'Date', value: '-date'},
                    {title:'Title', value: 'title'},
                    {title:'URL', value: 'url'}
                  ];
  $scope.currentOrder = $scope.orders[0]; // date is default sorting order

  // Maximum number of items currently displayed
  $scope.totalDisplayed = defaultTotalDisplayed;

  $scope.selectedIndex = 0;

  $scope.hideTopLevelFolders = false;
  $scope.showThumbnails = true;

  // Auto add showing bookmarks when user scroll to page down
  var loadMorePlaceholder = $('#loadMorePlaceholder').get(0);
  $(window).scroll(function () {
    if ($scope.filteredBookmarks.length > $scope.totalDisplayed) {
      if (loadMorePlaceholder.getBoundingClientRect().top <= window.innerHeight) {
        $scope.totalDisplayed += defaultTotalDisplayed;
        $scope.$apply();
      }
    }
  });

  $(window).resize(function(){
    countItemsPerRow();
  });

  var getAllPanels = function() {
    return $('#list-bookmarks div.panel');
  };

  var countItemsPerRow = function() {
    var bookmarksList = angular.element('#list-bookmarks'),
    boxSize = bookmarksList.find('li:first-child').width(),
    bookmarksListW = bookmarksList.width(),
    perRow = Math.floor( bookmarksListW / boxSize);

    $scope.itemsPerRow = perRow;
  };

  var isElementInViewport = function(el) {
    var rect = el.getBoundingClientRect();
    return rect.top >= 0 && rect.left >= 0 && rect.bottom <= $(window).height() && rect.right <= $(window).width();
  };

  // Key down events handlers
  $('#mainContent').keydown(function(e) {
    if (e.isDefaultPrevented()) {
      return;
    }

    var updated = false;
    if (e.which === 13) { // Enter press on page - go to the selected bookmark
      _gaq.push(['_trackEvent', 'Navigation', 'keydown', 'Navigation via enter']);

      // If first pattern is not our filter let's assume that user wants to search on this domain
      var match = /^(\w+)(\.\w+)?:(.+)/i.exec($scope.searchText);
      if (match && !_(['tag', 'url', 'title']).contains(match[1])) {
        window.location = 'https://' + match[1] + (match[2] || '.com') + '/?q=' + encodeURIComponent(match[3].trim());
      } else {
        var result = $scope.filteredBookmarks;
        if (result.length > $scope.selectedIndex) {
          window.location.href = result[$scope.selectedIndex].url;
        }
      }
    } else if (e.which === 37) { // left arrow key
      if ($scope.selectedIndex > 0) {
        $scope.selectedIndex--;
        updated = true;
      }
    } else if (e.which === 39) { // right arrow key
      if (getAllPanels().length > $scope.selectedIndex + 1) {
        $scope.selectedIndex++;
        updated = true;
      }

    } else if (e.which === 9 && e.shiftKey) { // shift+tab key
      if ($scope.selectedIndex > 0) {
        $scope.selectedIndex--;
        updated = true;
      }

    } else if (e.which === 9) { // tab key
      if (getAllPanels().length > $scope.selectedIndex + 1) {
        $scope.selectedIndex++;
        updated = true;
      }
    } else if (e.which === 40) { // down key
      if (getAllPanels().length > $scope.selectedIndex + $scope.itemsPerRow) {
        $scope.selectedIndex += $scope.itemsPerRow;
        updated = true;
      }
    } else if (e.which === 38) { // up key
      if ($scope.selectedIndex - $scope.itemsPerRow >= 0) {
        $scope.selectedIndex -= $scope.itemsPerRow;
        updated = true;
      }
    }
    if (updated) { // right arrow, left arrow, down arrow, up arrow, tab, and shift+tab key pressed - select next element
      $scope.$apply();
      var panels = getAllPanels();
      var selectedElement = panels.get($scope.selectedIndex);
      if (selectedElement) {
        var rect = selectedElement.getBoundingClientRect(); // If element is not visible - scroll to it
        if (!(rect.top >= 0 && rect.left >= 0 && rect.bottom <= $(window).height() && rect.right <= $(window).width())) {
          $("body").stop().animate({
            scrollTop: ($(panels.get($scope.selectedIndex)).offset().top - $(panels.get(0)).offset().top)
          }, 500);
        }
      }
      return false;
    }
  });

  var loadBookmarks = function() {
    bookmarksStorage.getAll(function(bookmarks, setttings) {
      $scope.hideTopLevelFolders = appSettings.hideTopLevelFolders = setttings.hideTopLevelFolders;
      $scope.showThumbnails = appSettings.showThumbnails = setttings.showThumbnails;
      $scope.bookmarks = bookmarks;
      $scope.filteredBookmarks = bookmarks;

      $scope.tags = _.chain(bookmarks)
                      .map(function (item) { return item.tag; })
                      .flatten()
                      .groupBy(function(t){ return t.text; })
                      .map(function(tagsArray, text) {
                          return {tagText: text,  numberOfTags: tagsArray.length };
                      })
                      .value();

      $scope.$apply();
      countItemsPerRow();
    }.bind(this));
  }.bind(this);
  loadBookmarks();

  // Set maximum total displayed items to default and scroll to top of the page
  var resetView = function() {
    $scope.totalDisplayed = defaultTotalDisplayed;
    $scope.selectedIndex = 0;
    setTimeout(function() {
      window.scroll(0, 0);
    }, 10);
  };

  var updateTagsInfo = function(updatedTags, originalTags){
    var newTags = _.difference(updatedTags, originalTags);
    var deletedTags = _.difference(originalTags, updatedTags);

    _.each(newTags, function(item){
        var existingTag = _.find($scope.tags, function(t){return t.tagText == item; });
        if(_.isUndefined(existingTag)){
            $scope.tags.push({tagText: item, numberOfTags: 1, custom: true});
        }
        else{
            existingTag.numberOfTags++;
        }
    });

    _.each(deletedTags, function(item){
        var existingTag = _.find($scope.tags, function(t){return t.tagText == item; });
        if(!_.isUndefined(existingTag)){
          if(existingTag.numberOfTags > 1) {
              existingTag.numberOfTags--;
          }
          else{
              $scope.tags.splice(_.indexOf($scope.tags, existingTag), 1);
          }
        }
    });
  };

  // When user change search string we scroll to top of the page and set total displayed items to default
  $scope.$watch('searchText', function() {
    $scope.filteredBookmarks =
      _.filter(
        $scope.bookmarks,
        function(bookmark){
          return booleanSearchEngine.filterBookmark(bookmark, $scope.searchText);
        }
      );
    resetView();
  });

  // On tag click we set search text
  $scope.selectTag = function(tag) {
    _gaq.push(['_trackEvent', 'Navigation', 'selectTag']);
    $scope.searchText = 'tag:' + tag;
  };

  // Change sorting order
  $scope.changeOrder = function(order) {
    _gaq.push(['_trackEvent', 'Navigation', 'changeOrder',  'Change order to ' + order]);
    $scope.currentOrder = order;
    resetView();
  };

  // Show modal dialog for adding tags
  $scope.editBookmark = function(bookmark) {
    _gaq.push(['_trackEvent', 'Navigation', 'editBookmark']);

    var originalBookmark = _.clone(bookmark);

    var modalInstance = $modal.open({
      scope: $scope.$new(true /* isolate */),
      templateUrl: 'partials/editBookmark.tpl.html',
      controller: 'editBookmarkController',
      resolve: {
        bookmark: function() {
          return bookmark;
        }
      },
      keyboard: true,
      backdrop: false
    });

    modalInstance.result.then(function (updatedBookmark) {
      var updatedTags = [];
      if(!_.isNull(updatedBookmark)){
        updatedTags = _.map(updatedBookmark.tag, function(item) { return item.text; });
      }
      var originalTags = _.map(originalBookmark.tag, function(item) { return item.text; });
      updateTagsInfo(updatedTags, originalTags);

      if (!updatedBookmark) {
        // Bookmark was deleted
        $scope.bookmarks.splice(_.indexOf($scope.bookmarks, bookmark), 1);
      }
    });

    return false;
  };

  $scope.selectBookmark = function(index) {
    $scope.selectedIndex = index;
  };

  $scope.setHideTopLevelFolders = function() {
    _gaq.push(['_trackEvent', 'ChangeSettings', 'HideTopLevelFolders changed to ' + !$scope.hideTopLevelFolders]);
    bookmarksStorage.setHideTopLevelFolders(!$scope.hideTopLevelFolders, loadBookmarks);
  };

  $scope.setShowThumbnails = function() {
    _gaq.push(['_trackEvent', 'ChangeSettings', 'ShowThumbnails changed to ' + !$scope.showThumbnails]);
    bookmarksStorage.setShowThumbnails(!$scope.showThumbnails, loadBookmarks);
  };

  $scope.getTypeheadSuggestions = function($viewValue) {
    var pattern = 'NONE';
    var searchText = $viewValue;
    var definedSearch = $viewValue;

    var expressionTree = booleanSearchEngine.generateExpressionTree($viewValue);
    if (expressionTree && expressionTree.length > 0) {
      var node = _.last(expressionTree);
      if (node) {
        var lastLiteral = _.last(node.literals);
        pattern = node.pattern;

        searchText = (lastLiteral && lastLiteral.expression === 'NONE' ? lastLiteral.text : '');

        definedSearch = $viewValue.replace(/\s+$/, '');
        definedSearch = definedSearch.substr(0, $viewValue.length - searchText.length);
        if (definedSearch.length > 0) {
          definedSearch += ' ';
        }
      }
    }

    if (pattern === 'NONE') {
      pattern = 'TITLE:';
    }

    var chain;

    if (pattern === 'TITLE:') {
      chain = _.chain(this.bookmarks)
        .map(function(b) {
          return b.title;
        });
    } else if (pattern === 'TAG:') {
       chain = _.chain(this.tags)
        .map(function(t) {
          return t.tagText;
        });
    } else if (pattern === 'URL:') {
      chain = _.chain(this.bookmarks)
        .map(function(b) {
          return b.url;
        });
    }

    if (!chain) {
      return [];
    }

    return chain
      .filter(function(t) {
        return t.toUpperCase().indexOf(searchText.toUpperCase()) >= 0;
      })
      .sortBy(function(t) {
        return t;
      })
      .first(10)
      .map(function(t) {
        return definedSearch + t;
      }).value();
  };
};

return [
  '$scope',
  '$filter',
  '$modal',
  'bookmarksStorage',
  'appSettings',
  'booleanSearchEngine',
  MainController
];

});

<commit_msg>Bug fix #94 - Hitting Enter on Selected Bookmark Launches Wrong Link<commit_after>define(
[
  'underscore',
  'jQuery'
],
function(_, $) { 'use strict';

/*
* Application controller.
*/
var MainController = function($scope, $filter, $modal, bookmarksStorage, appSettings, booleanSearchEngine) {

  // Constant: default value of how many items we want to display on main page.
  var defaultTotalDisplayed = 20;

  $scope.searchText = ''; // Search text
  $scope.bookmarks = []; // All bookmarks
  $scope.filteredBookmarks = [];
  $scope.tags = []; // All tags
  $scope.orders = [ // Different sorting orders
                    {title:'Date', value: '-date'},
                    {title:'Title', value: 'title'},
                    {title:'URL', value: 'url'}
                  ];
  $scope.currentOrder = $scope.orders[0]; // date is default sorting order

  // Maximum number of items currently displayed
  $scope.totalDisplayed = defaultTotalDisplayed;

  $scope.selectedIndex = 0;

  $scope.hideTopLevelFolders = false;
  $scope.showThumbnails = true;

  // Auto add showing bookmarks when user scroll to page down
  var loadMorePlaceholder = $('#loadMorePlaceholder').get(0);
  $(window).scroll(function () {
    if ($scope.filteredBookmarks.length > $scope.totalDisplayed) {
      if (loadMorePlaceholder.getBoundingClientRect().top <= window.innerHeight) {
        $scope.totalDisplayed += defaultTotalDisplayed;
        $scope.$apply();
      }
    }
  });

  $(window).resize(function(){
    countItemsPerRow();
  });

  var getAllPanels = function() {
    return $('#list-bookmarks div.panel');
  };

  var countItemsPerRow = function() {
    var bookmarksList = angular.element('#list-bookmarks'),
    boxSize = bookmarksList.find('li:first-child').width(),
    bookmarksListW = bookmarksList.width(),
    perRow = Math.floor( bookmarksListW / boxSize);

    $scope.itemsPerRow = perRow;
  };

  var isElementInViewport = function(el) {
    var rect = el.getBoundingClientRect();
    return rect.top >= 0 && rect.left >= 0 && rect.bottom <= $(window).height() && rect.right <= $(window).width();
  };

  // Key down events handlers
  $('#mainContent').keydown(function(e) {
    if (e.isDefaultPrevented()) {
      return;
    }

    var updated = false;
    if (e.which === 13) { // Enter press on page - go to the selected bookmark
      _gaq.push(['_trackEvent', 'Navigation', 'keydown', 'Navigation via enter']);

      // If first pattern is not our filter let's assume that user wants to search on this domain
      var match = /^(\w+)(\.\w+)?:(.+)/i.exec($scope.searchText);
      if (match && !_(['tag', 'url', 'title']).contains(match[1])) {
        window.location = 'https://' + match[1] + (match[2] || '.com') + '/?q=' + encodeURIComponent(match[3].trim());
      } else {
        var result = $scope.filteredBookmarks;
        if (result.length > $scope.selectedIndex) {
          window.location.href = $filter('orderBy')(result, $scope.currentOrder.value)[$scope.selectedIndex].url;
        }
      }
    } else if (e.which === 37) { // left arrow key
      if ($scope.selectedIndex > 0) {
        $scope.selectedIndex--;
        updated = true;
      }
    } else if (e.which === 39) { // right arrow key
      if (getAllPanels().length > $scope.selectedIndex + 1) {
        $scope.selectedIndex++;
        updated = true;
      }

    } else if (e.which === 9 && e.shiftKey) { // shift+tab key
      if ($scope.selectedIndex > 0) {
        $scope.selectedIndex--;
        updated = true;
      }

    } else if (e.which === 9) { // tab key
      if (getAllPanels().length > $scope.selectedIndex + 1) {
        $scope.selectedIndex++;
        updated = true;
      }
    } else if (e.which === 40) { // down key
      if (getAllPanels().length > $scope.selectedIndex + $scope.itemsPerRow) {
        $scope.selectedIndex += $scope.itemsPerRow;
        updated = true;
      }
    } else if (e.which === 38) { // up key
      if ($scope.selectedIndex - $scope.itemsPerRow >= 0) {
        $scope.selectedIndex -= $scope.itemsPerRow;
        updated = true;
      }
    }
    if (updated) { // right arrow, left arrow, down arrow, up arrow, tab, and shift+tab key pressed - select next element
      $scope.$apply();
      var panels = getAllPanels();
      var selectedElement = panels.get($scope.selectedIndex);
      if (selectedElement) {
        var rect = selectedElement.getBoundingClientRect(); // If element is not visible - scroll to it
        if (!(rect.top >= 0 && rect.left >= 0 && rect.bottom <= $(window).height() && rect.right <= $(window).width())) {
          $("body").stop().animate({
            scrollTop: ($(panels.get($scope.selectedIndex)).offset().top - $(panels.get(0)).offset().top)
          }, 500);
        }
      }
      return false;
    }
  });

  var loadBookmarks = function() {
    bookmarksStorage.getAll(function(bookmarks, setttings) {
      $scope.hideTopLevelFolders = appSettings.hideTopLevelFolders = setttings.hideTopLevelFolders;
      $scope.showThumbnails = appSettings.showThumbnails = setttings.showThumbnails;
      $scope.bookmarks = bookmarks;
      $scope.filteredBookmarks = bookmarks;

      $scope.tags = _.chain(bookmarks)
                      .map(function (item) { return item.tag; })
                      .flatten()
                      .groupBy(function(t){ return t.text; })
                      .map(function(tagsArray, text) {
                          return {tagText: text,  numberOfTags: tagsArray.length };
                      })
                      .value();

      $scope.$apply();
      countItemsPerRow();
    }.bind(this));
  }.bind(this);
  loadBookmarks();

  // Set maximum total displayed items to default and scroll to top of the page
  var resetView = function() {
    $scope.totalDisplayed = defaultTotalDisplayed;
    $scope.selectedIndex = 0;
    setTimeout(function() {
      window.scroll(0, 0);
    }, 10);
  };

  var updateTagsInfo = function(updatedTags, originalTags){
    var newTags = _.difference(updatedTags, originalTags);
    var deletedTags = _.difference(originalTags, updatedTags);

    _.each(newTags, function(item){
        var existingTag = _.find($scope.tags, function(t){return t.tagText == item; });
        if(_.isUndefined(existingTag)){
            $scope.tags.push({tagText: item, numberOfTags: 1, custom: true});
        }
        else{
            existingTag.numberOfTags++;
        }
    });

    _.each(deletedTags, function(item){
        var existingTag = _.find($scope.tags, function(t){return t.tagText == item; });
        if(!_.isUndefined(existingTag)){
          if(existingTag.numberOfTags > 1) {
              existingTag.numberOfTags--;
          }
          else{
              $scope.tags.splice(_.indexOf($scope.tags, existingTag), 1);
          }
        }
    });
  };

  // When user change search string we scroll to top of the page and set total displayed items to default
  $scope.$watch('searchText', function() {
    $scope.filteredBookmarks =
      _.filter(
        $scope.bookmarks,
        function(bookmark){
          return booleanSearchEngine.filterBookmark(bookmark, $scope.searchText);
        }
      );
    resetView();
  });

  // On tag click we set search text
  $scope.selectTag = function(tag) {
    _gaq.push(['_trackEvent', 'Navigation', 'selectTag']);
    $scope.searchText = 'tag:' + tag;
  };

  // Change sorting order
  $scope.changeOrder = function(order) {
    _gaq.push(['_trackEvent', 'Navigation', 'changeOrder',  'Change order to ' + order]);
    $scope.currentOrder = order;
    resetView();
  };

  // Show modal dialog for adding tags
  $scope.editBookmark = function(bookmark) {
    _gaq.push(['_trackEvent', 'Navigation', 'editBookmark']);

    var originalBookmark = _.clone(bookmark);

    var modalInstance = $modal.open({
      scope: $scope.$new(true /* isolate */),
      templateUrl: 'partials/editBookmark.tpl.html',
      controller: 'editBookmarkController',
      resolve: {
        bookmark: function() {
          return bookmark;
        }
      },
      keyboard: true,
      backdrop: false
    });

    modalInstance.result.then(function (updatedBookmark) {
      var updatedTags = [];
      if(!_.isNull(updatedBookmark)){
        updatedTags = _.map(updatedBookmark.tag, function(item) { return item.text; });
      }
      var originalTags = _.map(originalBookmark.tag, function(item) { return item.text; });
      updateTagsInfo(updatedTags, originalTags);

      if (!updatedBookmark) {
        // Bookmark was deleted
        $scope.bookmarks.splice(_.indexOf($scope.bookmarks, bookmark), 1);
      }
    });

    return false;
  };

  $scope.selectBookmark = function(index) {
    $scope.selectedIndex = index;
  };

  $scope.setHideTopLevelFolders = function() {
    _gaq.push(['_trackEvent', 'ChangeSettings', 'HideTopLevelFolders changed to ' + !$scope.hideTopLevelFolders]);
    bookmarksStorage.setHideTopLevelFolders(!$scope.hideTopLevelFolders, loadBookmarks);
  };

  $scope.setShowThumbnails = function() {
    _gaq.push(['_trackEvent', 'ChangeSettings', 'ShowThumbnails changed to ' + !$scope.showThumbnails]);
    bookmarksStorage.setShowThumbnails(!$scope.showThumbnails, loadBookmarks);
  };

  $scope.getTypeheadSuggestions = function($viewValue) {
    var pattern = 'NONE';
    var searchText = $viewValue;
    var definedSearch = $viewValue;

    var expressionTree = booleanSearchEngine.generateExpressionTree($viewValue);
    if (expressionTree && expressionTree.length > 0) {
      var node = _.last(expressionTree);
      if (node) {
        var lastLiteral = _.last(node.literals);
        pattern = node.pattern;

        searchText = (lastLiteral && lastLiteral.expression === 'NONE' ? lastLiteral.text : '');

        definedSearch = $viewValue.replace(/\s+$/, '');
        definedSearch = definedSearch.substr(0, $viewValue.length - searchText.length);
        if (definedSearch.length > 0) {
          definedSearch += ' ';
        }
      }
    }

    if (pattern === 'NONE') {
      pattern = 'TITLE:';
    }

    var chain;

    if (pattern === 'TITLE:') {
      chain = _.chain(this.bookmarks)
        .map(function(b) {
          return b.title;
        });
    } else if (pattern === 'TAG:') {
       chain = _.chain(this.tags)
        .map(function(t) {
          return t.tagText;
        });
    } else if (pattern === 'URL:') {
      chain = _.chain(this.bookmarks)
        .map(function(b) {
          return b.url;
        });
    }

    if (!chain) {
      return [];
    }

    return chain
      .filter(function(t) {
        return t.toUpperCase().indexOf(searchText.toUpperCase()) >= 0;
      })
      .sortBy(function(t) {
        return t;
      })
      .first(10)
      .map(function(t) {
        return definedSearch + t;
      }).value();
  };
};

return [
  '$scope',
  '$filter',
  '$modal',
  'bookmarksStorage',
  'appSettings',
  'booleanSearchEngine',
  MainController
];

});

<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 *
 * 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 applicable 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.
 */

/**
 * Manual standalone test script for stress testing foam.dao.SyncDAO. To tweak
 * test operation, jump to comment "Test configuration".
 */

require('../../src/foam.js');

var Item;
var BaseDAO;
var ProxyDAO;
var QuickSink;
var SyncDAO;
var SyncRecord;
var VersionNoDAO;

foam.CLASS({
  package: 'foam.dao.test',
  name: 'Item',

  properties: [ 'id', [ 'version', -1 ], 'data' ]
});

foam.CLASS({
  package: 'foam.dao.test',
  name: 'BaseDAO',
  extends: 'foam.dao.ProxyDAO',

  documentation: `Clone before put()/remove() to delegate (default: MDAO). Also,
      delay up to "maxDelay" milliseconds before passing put()/remove() to
      delegate, and before returning delegate's response.`,

  requires: [ 'foam.dao.MDAO' ],

  properties: [
    {
      name: 'delegate',
      factory: function() {
        return this.MDAO.create({ of: this.of });
      }
    },
    {
      name: 'maxDelay',
      documentation: `Maximum number of milliseconds to delay passing to
          delegate and/or returning value from delegate.`,
      value: 20
    }
  ],

  methods: [
    function put_(x, o) {
      return this.delay_('put_', [ x, o.clone() ]);
    },
    function remove_(x, o) {
      return this.delay_('remove_', [ x, o.clone() ]);
    },
    function delay_(op, args) {
      var self = this;
      return new Promise(function(resolve, reject) {
        // Log to ensure ordering (i.e., no logs such as these should appear
        // after verification step).
        console.log('Base DAO', op);
        setTimeout(function() {
          console.log('Base DAO', op, 'send to delegate');
          return self.delegate[op].apply(self.delegate, args).then(function(o) {
            setTimeout(function() {
              console.log('Base DAO', op, 'resolve');
              resolve(o);
            }, Math.floor(Math.random() * self.maxDelay));
          }, function(e) {
            setTimeout(function() {
              console.log('Base DAO', op, 'reject');
              reject(e);
            }, Math.floor(Math.random() * self.maxDelay));
          });
        }, Math.floor(Math.random() * self.maxDelay));
      });
    }
  ]
});

Item = foam.lookup('foam.dao.test.Item');
BaseDAO = foam.lookup('foam.dao.test.BaseDAO');
ProxyDAO = foam.lookup('foam.dao.ProxyDAO');
QuickSink = foam.lookup('foam.dao.QuickSink');
SyncDAO = foam.lookup('foam.dao.SyncDAO');
SyncRecord = foam.lookup('foam.dao.sync.SyncRecord');
VersionNoDAO = foam.lookup('foam.dao.VersionNoDAO');

function getData(name) {
  return name + ':' + Math.ceil(Math.random() * 1000);
}

/**
 * Test configuration
 */

// Data in remote before VersionNoDAO is added.
var initialData = [
  Item.create({ id: 0, data: getData('initial') }),
  Item.create({ id: 10, data: getData('initial') }),
  Item.create({ id: 20, data: getData('initial') }),
  Item.create({ id: 30, data: getData('initial') }),
  Item.create({ id: 40, data: getData('initial') })
];

// Number of independent SyncDAOs communicating with remote.
var numActiveAgents = 10;
// Number of non-sync agents just put()/remove()ing to remote.
var numPassiveAgents = 10;

// Record ids span integers: [0, numRecords - 1].
var numRecords = 50;
// Number of times ("rounds") to synchronously put()/remove() records.
var numRounds = 50;
// Number of put()/remove()s per synchronous "round".
var opsPerRound = 20;
// Wait time between rounds.
var waitBetweenRounds = 1000;
// Wait time for sync DAOs to finish synchronizing before verifying results.
// NOTE: If this value is too low, then spurious errors will be reported.
var waitToSettle = 10000;

/**
 * DAO setup
 */

// Underlying DAO on remote.
var remoteDelegate = BaseDAO.create({ of: Item });
initialData.forEach(function(data) { remoteDelegate.put(data); });
// DAO that agents hit when talking to remote.
var remoteDAO = VersionNoDAO.create({
  property: Item.VERSION,
  delegate: remoteDelegate
});

// Agents using SyncDAOs.
var activeAgents = new Array(numActiveAgents);
for ( var i = 0; i < numActiveAgents; i++ ) {
  // TODO(markdittmer): Add initial unsynced data to agents.
  activeAgents[i] = SyncDAO.create({
    of: Item,
    remoteDAO: remoteDAO,
    delegate: BaseDAO.create({ of: Item }),
    syncProperty: Item.VERSION,
    syncRecordDAO: BaseDAO.create({ of: SyncRecord })
  });
}

// Agents talking directly to remote.
var passiveAgents = new Array(numPassiveAgents);
for ( var i = 0; i < numPassiveAgents; i++ ) {
  passiveAgents[i] = ProxyDAO.create({ delegate: remoteDAO });
}

// All the agents.
var agents = activeAgents.concat(passiveAgents);

/**
 * Test run(s)
 */

// Setup timers for each round.
for ( var i = 0; i < numRounds; i++ ) {
  setTimeout(function() {
    for ( var j = 0; j < opsPerRound; j++ ) {
      var agentNo = Math.floor(Math.random() * agents.length);
      var agent = agents[agentNo];
      var op = Math.floor(Math.random() * 2) === 0 ? 'put' : 'remove';
      agent[op](Item.create({
        id: Math.floor(Math.random() * numRecords),
        data: getData('agent' + agentNo)
      }));
    }
  }, i * waitBetweenRounds);
}

/**
 * Test result verification.
 */

// Setup timer for verification.
setTimeout(function() {
  var reference;

  // Add log marker after which no DAO activity should be logged.
  // If DAO activity is logged after this line, results should not be trusted;
  // increase timeouts to let SyncDAOs settle.
  console.log('DONE! (There should be no BaseDAO logs below this line)');

  var p = remoteDAO.select().then(function(sink) {
    reference = sink.array;
  });
  for ( var i = 0; i < activeAgents.length; i++ ) {
    // Wait for previous round (or "reference" accumulation) before reporting on
    // next active agent.
    p = p.then(function(i) {
      return activeAgents[i].select().then(function(sink) {
        var array = sink.array;
        if ( array.length !== reference.length )
          console.error('Agent', i, 'has too many/few records');
        for ( var j = 0; j < array.length; j++ ) {
          if ( ! foam.util.equals(array[j], reference[j]) )
            console.error('Agent', i, 'does not match reference at', j);
        }
      });
    }.bind(this, i));
  }
}, numRounds * waitBetweenRounds + waitToSettle);
<commit_msg>Update syncDAOStress test to use setup consistent with Sync/VersionNo/StoreAndForward changes<commit_after>/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 *
 * 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 applicable 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.
 */

/**
 * Manual standalone test script for stress testing foam.dao.SyncDAO. To tweak
 * test operation, jump to comment "Test configuration".
 */

require('../../src/foam.js');

var BaseDAO;
var Item;
var ProxyDAO;
var QuickSink;
var StoreAndForwardDAO;
var SyncDAO;
var SyncRecord;
var VersionNoDAO;

foam.CLASS({
  package: 'foam.dao.test',
  name: 'Item',

  properties: [ 'id', [ 'version', -1 ], [ 'deleted', false ], 'data' ]
});

foam.CLASS({
  package: 'foam.dao.test',
  name: 'BaseDAO',
  extends: 'foam.dao.ProxyDAO',

  documentation: `Clone before put()/remove() to delegate (default: MDAO). Also,
      delay up to "maxDelay" milliseconds before passing put()/remove() to
      delegate, and before returning delegate's response.`,

  requires: [ 'foam.dao.MDAO' ],

  properties: [
    {
      name: 'delegate',
      factory: function() {
        return this.MDAO.create({ of: this.of });
      }
    },
    {
      name: 'maxDelay',
      documentation: `Maximum number of milliseconds to delay passing to
          delegate and/or returning value from delegate.`,
      value: 20
    }
  ],

  methods: [
    function put_(x, o) {
      return this.delay_('put_', [ x, o.clone() ]);
    },
    function remove_(x, o) {
      return this.delay_('remove_', [ x, o.clone() ]);
    },
    function delay_(op, args) {
      var self = this;
      return new Promise(function(resolve, reject) {
        // Log to ensure ordering (i.e., no logs such as these should appear
        // after verification step).
        setTimeout(function() {
          return self.delegate[op].apply(self.delegate, args).then(function(o) {
            setTimeout(function() {
              resolve(o);
            }, Math.floor(Math.random() * self.maxDelay));
          }, function(e) {
            setTimeout(function() {
              reject(e);
            }, Math.floor(Math.random() * self.maxDelay));
          });
        }, Math.floor(Math.random() * self.maxDelay));
      });
    }
  ]
});

Item = foam.lookup('foam.dao.test.Item');
BaseDAO = foam.lookup('foam.dao.test.BaseDAO');
ProxyDAO = foam.lookup('foam.dao.ProxyDAO');
QuickSink = foam.lookup('foam.dao.QuickSink');
StoreAndForwardDAO = foam.lookup('foam.dao.StoreAndForwardDAO');
SyncDAO = foam.lookup('foam.dao.SyncDAO');
SyncRecord = foam.lookup('foam.dao.sync.SyncRecord');
VersionNoDAO = foam.lookup('foam.dao.VersionNoDAO');

function getData(name) {
  return name + ':' + Math.ceil(Math.random() * 1000);
}

/**
 * Test configuration
 */

// Data in remote before VersionNoDAO is added.
var initialData = [
  Item.create({ id: 0, data: getData('initial') }),
  Item.create({ id: 10, data: getData('initial') }),
  Item.create({ id: 20, data: getData('initial') }),
  Item.create({ id: 30, data: getData('initial') }),
  Item.create({ id: 40, data: getData('initial') })
];

// Number of independent SyncDAOs communicating with remote.
var numActiveAgents = 10;
// Number of non-sync agents just put()/remove()ing to remote.
var numPassiveAgents = 10;

// Record ids span integers: [0, numRecords - 1].
var numRecords = 50;
// Number of times ("rounds") to synchronously put()/remove() records.
var numRounds = 50;
// Number of put()/remove()s per synchronous "round".
var opsPerRound = 20;
// Wait time between rounds.
var waitBetweenRounds = 3000;
// Polling frequency for polling SyncDAOs; should be appreciably less than
// waitBetweenRounds.
var pollingFrequency = 2000;
// Wait time for sync DAOs to finish synchronizing before verifying results.
// NOTE: If this value is too low, then spurious errors will be reported.
var waitToSettle = 10000;

/**
 * DAO setup
 */

// Underlying DAO on remote.
var remoteDelegate = BaseDAO.create({ of: Item });
initialData.forEach(function(data) { remoteDelegate.put(data); });
// DAO that agents hit when talking to remote.
var remoteDAO = StoreAndForwardDAO.create({
  delegate: VersionNoDAO.create({
    versionProperty: Item.VERSION,
    deletedProperty: Item.DELETED,
    delegate: remoteDelegate
  })
});

// Agents using SyncDAOs.
var activeAgents = new Array(numActiveAgents);
for ( var i = 0; i < numActiveAgents; i++ ) {
  // TODO(markdittmer): Add initial unsynced data to agents.
  activeAgents[i] = SyncDAO.create({
    of: Item,
    remoteDAO: remoteDAO,
    delegate: BaseDAO.create({ of: Item }),
    versionProperty: Item.VERSION,
    deletedProperty: Item.DELETED,
    syncRecordDAO: BaseDAO.create({ of: SyncRecord }),
    polling: Math.floor(Math.random() * 2) === 0,
    pollingFrequency: pollingFrequency
  });
}

// Agents talking directly to remote.
var passiveAgents = new Array(numPassiveAgents);
for ( var i = 0; i < numPassiveAgents; i++ ) {
  passiveAgents[i] = ProxyDAO.create({ delegate: remoteDAO });
}

// All the agents.
var agents = activeAgents.concat(passiveAgents);

/**
 * Test run(s)
 */

// Setup timers for each round.
for ( var i = 0; i < numRounds; i++ ) {
  setTimeout(function() {
    for ( var j = 0; j < opsPerRound; j++ ) {
      var agentNo = Math.floor(Math.random() * agents.length);
      var agent = agents[agentNo];
      var op = Math.floor(Math.random() * 2) === 0 ? 'put' : 'remove';
      agent[op](Item.create({
        id: Math.floor(Math.random() * numRecords),
        data: getData('agent' + agentNo)
      }));
    }
  }, i * waitBetweenRounds);
}

/**
 * Test result verification.
 */

// Setup timer for verification.
setTimeout(function() {
  var E = foam.lookup('foam.mlang.ExpressionsSingleton').create();
  var errorCount = 0;
  var reference;

  // Add log marker after which no DAO activity should be logged.
  // If DAO activity is logged after this line, results should not be trusted;
  // increase timeouts to let SyncDAOs settle.
  console.log('DONE! (There should be no non-polling BaseDAO logs below)');

  // Exclude deleted records from reference.
  var p = remoteDAO.where(E.EQ(Item.DELETED, false)).select().
      then(function(sink) { reference = sink.array; });

  for ( var i = 0; i < activeAgents.length; i++ ) {
    // Wait for previous round (or "reference" accumulation) before reporting on
    // next active agent.
    p = p.then(function(i) {
      return activeAgents[i].select().then(function(sink) {
        var array = sink.array;
        if ( array.length !== reference.length ) {
          errorCount++;
          console.error('Agent', i, 'has too many/few records');
        }
        for ( var j = 0; j < array.length; j++ ) {
          if ( ! foam.util.equals(array[j], reference[j]) ) {
            errorCount++;
            console.error('Agent', i, 'does not match reference at', j);
          }
        }
      });
    }.bind(this, i));
  }
  p.then(function() {
    setTimeout(function() {
      console.log('Exiting (found', errorCount, 'errors)');
      require('process').exit(errorCount === 0 ? 0 : 1);
    }, pollingFrequency + 100);
  });
}, numRounds * waitBetweenRounds + waitToSettle);
<|endoftext|>


<commit_before>// View model for the courses page
function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("CoursesTitle");}, gvm);
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CoursesHeader");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.availableLocations = ko.observableArray([]);
    gvm.availableTrainings = ko.observableArray([]);
    gvm.availableCourses = ko.observableArray([]);

    /*
     * Update the location dropdown list
     */
    gvm.updateLocations = function() {
        $.getJSON('/api/locations', function(data) {
            gvm.availableLocations.removeAll();
            $.each(data, function(i, item) {
                /* Put item in list */
                gvm.availableLocations.push(item);

                /* Add listener to listitem */
                $("#locbtn-" + item.id).click(function(){
                    gvm.updateTrainings(item.id);
                    $(".btn-location span:first").text($(this).text());
                });
            });
        });

    }

    /*
     * Update the training data
     */
    gvm.updateTrainings = function(id) {
        $.getJSON('/api/trainings/' + id, function(data) {
            gvm.availableTrainings.removeAll();
            $.each(data, function(i, item) {
                gvm.availableTrainings.push(item);

                /* Add listener to listitem */
                $("#trainingbtn-" + item.id).click(function(){
                    gvm.updateCourses(item.id);
                    $(".btn-training span:first").text($(this).text());
                });
            });
        });
    }

    /*
     * Update available courses
     */
    gvm.updateCourses = function(id) {
        $.getJSON('/api/courses/' + id, function(data) {
            gvm.availableCourses.removeAll();
            $.each(data, function(i, item) {
                gvm.availableCourses.push(item);

                /* Add listener to listitem */
                $("#coursebtn-" + item.id).click(function(){
                    alert("You selected course: " + item.name);
                    $(".btn-course span:first").text($(this).text());
                });
            });
        });
    }
}

function initPage() {
    viewModel.updateLocations();
}<commit_msg>courses page dropdown menu<commit_after>// View model for the courses page
function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("CoursesTitle");}, gvm);
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CoursesHeader");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.availableLocations = ko.observableArray([]);
    gvm.availableTrainings = ko.observableArray([]);
    gvm.availableCourses = ko.observableArray([]);

    /*
     * Update the location dropdown list
     */
    gvm.updateLocations = function() {
        $.getJSON('/api/locations', function(data) {
            gvm.availableLocations.removeAll();
            $.each(data, function(i, item) {
                /* Put item in list */
                gvm.availableLocations.push(item);

                /* Add listener to listitem */
                $("#locbtn-" + item.id).click(function(){
                    gvm.updateTrainings(item.id);
                    $(".btn-location span:first").text($(this).text());
                });
            });
        });

    }

    /*
     * Update the training data
     */
    gvm.updateTrainings = function(id) {
        $.getJSON('/api/trainings/' + id, function(data) {
            gvm.availableTrainings.removeAll();
            $.each(data, function(i, item) {
                gvm.availableTrainings.push(item);

                /* Add listener to listitem */
                $("#trainingbtn-" + item.id).click(function(){
                    gvm.updateCourses(item.id);
                    $(".btn-training span:first").text($(this).text());
                });
            });
        });
    }

    /*
     * Update available courses
     */
    gvm.updateCourses = function(id) {
        $.getJSON('/api/courses/' + id, function(data) {
            gvm.availableCourses.removeAll();
            $.each(data, function(i, item) {
                gvm.availableCourses.push(item);

                /* Add listener to listitem */
                $("#coursebtn-" + item.id).click(function(){
                    $(".btn-course span:first").text($(this).text());
                });
            });
        });
    }
}

function initPage() {
    viewModel.updateLocations();
}<|endoftext|>


<commit_before>// View model for the courses page
function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("CoursesTitle");}, gvm);
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CoursesHeader");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.availableLocations = ko.observableArray([]);
    gvm.availableTrainings = ko.observableArray([]);
    gvm.availableCourses = ko.observableArray([]);

    gvm.addAvailableLocations = function(id, name) {
        var selectObject = {id: id, locationName: name};
        gvm.availableLocations.push(selectObject);
    }
    gvm.addAvailableTrainings = function(id, name) {
        var selectObject = {id: id, trainingName: name};
        gvm.availableTrainings.push(selectObject);
    }

    gvm.addAvailableCourses = function(id, name) {
        var selectObject = {id: id, courseName: name};
        gvm.availableCourses.push(selectObject);
    }

    gvm.clearAll = function() {
        gvm.availableLocations.removeAll();
        gvm.availableTrainings.removeAll();
        gvm.availableCourses.removeAll();
    }
}

function loadAllSelects($locationid, $trainingid)
{
    viewModel.clearAll();
    $.getJSON('/api/locations', function(data){
        // Load table data
        $.each(data, function(i, item) {
            viewModel.addAvailableLocations(item.id, item.name);
        });
    });
    $.getJSON('/api/trainings/' + $locationid, function(data){
        // Load table data
        $.each(data, function(i, item) {
            viewModel.addAvailableTrainings(item.id, item.name);
        });
    });
    $.getJSON('/api/courses/' + $trainingid, function(data) {
        $.each(data, function(i, item) {
            viewModel.addAvailableCourses(item.id, item.name);
        });
    });
}

function initPage() {
    $("#location").change(function() {
        loadAllSelects($("#location").val(), $("#training").val());
    });
}<commit_msg>change event<commit_after>// View model for the courses page
function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("CoursesTitle");}, gvm);
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CoursesHeader");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.availableLocations = ko.observableArray([]);
    gvm.availableTrainings = ko.observableArray([]);
    gvm.availableCourses = ko.observableArray([]);

    gvm.addAvailableLocations = function(id, name) {
        var selectObject = {id: id, locationName: name};
        gvm.availableLocations.push(selectObject);
    }
    gvm.addAvailableTrainings = function(id, name) {
        var selectObject = {id: id, trainingName: name};
        gvm.availableTrainings.push(selectObject);
    }

    gvm.addAvailableCourses = function(id, name) {
        var selectObject = {id: id, courseName: name};
        gvm.availableCourses.push(selectObject);
    }

    gvm.clearAll = function() {
        gvm.availableLocations.removeAll();
        gvm.availableTrainings.removeAll();
        gvm.availableCourses.removeAll();
    }
}

function loadAllSelects($locationid, $trainingid)
{
    viewModel.clearAll();
    $.getJSON('/api/locations', function(data){
        // Load table data
        $.each(data, function(i, item) {
            viewModel.addAvailableLocations(item.id, item.name);
        });
    });
    $.getJSON('/api/trainings/' + $locationid, function(data){
        // Load table data
        $.each(data, function(i, item) {
            viewModel.addAvailableTrainings(item.id, item.name);
        });
    });
    $.getJSON('/api/courses/' + $trainingid, function(data) {
        $.each(data, function(i, item) {
            viewModel.addAvailableCourses(item.id, item.name);
        });
    });
}

function initPage() {
    loadAllSelects(1, 1);
    $("#location").change(function() {
        loadAllSelects($("#location").val(), $("#training").val());
    });
}<|endoftext|>


<commit_before>var duree = "longue";
var duration_longue = true;
var duration_courte = false;

  $(document).ready(function(){
  //on initialise les variables avec les valeurs par défaut
    var duree = "longue";
    var pub = "adu";
    var nbDePersonnes = 16;
    var sce = 1;
  //on appuie les boutons en conséquence
    $("#dur_lon").addClass("active");
    $("#pub_adu").addClass("active");
    $("#sce_1").addClass("active");
    //$("#car").load('carousel_long.html');

    //On remplit le champ du bouton +/- avec la valeur par défaut
    $("#inputnb").val(nbDePersonnes);

    //var carousel_c = $.get("carousel_court.html");
    //var carousel_l = $.get("carousel_long.html");
  //On change la valeur des variables en fonction des actions utilisateurs
  //Pour la durée :
    $("#dur_cou").click(function(e){
      duree = "courte";
      duration_courte = true;
      duration_longue = false;
      $("#dur_lon").removeClass("active");
      $("#dur_cou").addClass("active");
      //var code = load("carousel_court.html");
      //$("#myCarousel").replaceWith("
 This text is strong
  This text is italic
");
      //alert(carousel_c);
      //$("#car").empty();
      $("#car").load('carousel_court.html');
      $("#p1").show();
      alert("Chargement terminé \n Guide pour atelier court !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();});
    });
    $("#dur_lon").click(function(e){
      duree = "longue";
      duration_longue = true;
      duration_courte =false;
      $("#dur_cou").removeClass("active");
      $("#dur_lon").addClass("active");
      //$("#myCarousel").replaceWith(carousel_l);
      //$("#car").empty();
      $("#car").load('carousel_long.html');
      $("#p1").show();
      alert("Chargement terminé \n Guide pour atelier long !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();})
    });
  //Pour le public :
    $("#pub_enf").click(function(e){
      pub = "enf";
      $("#pub_adu").removeClass("active");
      $("#pub_enf").addClass("active");
    });
    $("#pub_adu").click(function(e){
      pub = "adu";
      $("#pub_enf").removeClass("active");
      $("#pub_adu").addClass("active");
    });
  //Pour le scénario :
    $("#sce_2").click(function(e){
      sce = 2;
      $("#sce_1").removeClass("active");
      $("#sce_2").addClass("active");
    });
    $("#sce_1").click(function(e){
      sce = 1;
      $("#sce_2").removeClass("active");
      $("#sce_1").addClass("active");
    });

    $("#pointLien").click(function(e){
      if(pub == "enf"){
        $("#pointLien").attr('href','graphiques_enfants.html');
      }else{
        $("#pointLien").attr('href','graphiques_adultes.html');
      }
    });

  });

function demoFromHTML() {

alert("hola");

     var pdf = new jsPDF('p', 'pt', 'a4', false);
     //var pdf = new jsPDF();
  /*var logo = new Image();
         pdf.text("hello", 30,30);
       logo.src = "1.png";
       pdf.addImage(logo, 'PNG', 2, 2, 590,850);*/

          if(duration_longue){
            var logo = new Image();
            logo.src = "https://vizkit.github.io/donnees/.jpeg";
            pdf.addImage(logo, 'JPEG', 2, 2, 590,850);
            pdf.addPage();
     //       var logo = new Image();
      //      logo.src = "/pdf_images/1.png";
       //     pdf.addImage(logo, 'PNG', 2, 2, 590,850);

          }/*else if(duration_courte) {
            logo.src = "/pdf_images/1.png";
            pdf.addImage(logo, 'PNG', 2, 2, 590,850);
            pdf.addPage();
            logo.src = "/pdf_images/1.png";
            pdf.addImage(logo, 'PNG', 2, 2, 590,850);

          }*/

           var uno= 1;

       /*   var paso;
        for (paso = 4; paso < 6; paso++) {
            pdf.addPage();
            var logo = new Image();
            logo.src = paso+".png";
            pdf.addImage(logo, 'PNG', 2, 2, 590,850);
          // Se ejecuta 5 veces, con valores desde paso desde 0 hasta 4.

          };*/

     pdf.output("dataurlnewwindow");

        }
<commit_msg>Update dynamic_carousel.js<commit_after>var duree = "longue";
var duration_longue = true;
var duration_courte = false;

  $(document).ready(function(){
  //on initialise les variables avec les valeurs par défaut
    var duree = "longue";
    var pub = "adu";
    var nbDePersonnes = 16;
    var sce = 1;
  //on appuie les boutons en conséquence
    $("#dur_lon").addClass("active");
    $("#pub_adu").addClass("active");
    $("#sce_1").addClass("active");
    //$("#car").load('carousel_long.html');

    //On remplit le champ du bouton +/- avec la valeur par défaut
    $("#inputnb").val(nbDePersonnes);

    //var carousel_c = $.get("carousel_court.html");
    //var carousel_l = $.get("carousel_long.html");
  //On change la valeur des variables en fonction des actions utilisateurs
  //Pour la durée :
    $("#dur_cou").click(function(e){
      duree = "courte";
      duration_courte = true;
      duration_longue = false;
      $("#dur_lon").removeClass("active");
      $("#dur_cou").addClass("active");
      //var code = load("carousel_court.html");
      //$("#myCarousel").replaceWith("
 This text is strong
  This text is italic
");
      //alert(carousel_c);
      //$("#car").empty();
      $("#car").load('carousel_court.html');
      $("#p1").show();
      alert("Chargement terminé \n Guide pour atelier court !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();});
    });
    $("#dur_lon").click(function(e){
      duree = "longue";
      duration_longue = true;
      duration_courte =false;
      $("#dur_cou").removeClass("active");
      $("#dur_lon").addClass("active");
      //$("#myCarousel").replaceWith(carousel_l);
      //$("#car").empty();
      $("#car").load('carousel_long.html');
      $("#p1").show();
      alert("Chargement terminé \n Guide pour atelier long !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();})
    });
  //Pour le public :
    $("#pub_enf").click(function(e){
      pub = "enf";
      $("#pub_adu").removeClass("active");
      $("#pub_enf").addClass("active");
    });
    $("#pub_adu").click(function(e){
      pub = "adu";
      $("#pub_enf").removeClass("active");
      $("#pub_adu").addClass("active");
    });
  //Pour le scénario :
    $("#sce_2").click(function(e){
      sce = 2;
      $("#sce_1").removeClass("active");
      $("#sce_2").addClass("active");
    });
    $("#sce_1").click(function(e){
      sce = 1;
      $("#sce_2").removeClass("active");
      $("#sce_1").addClass("active");
    });

    $("#pointLien").click(function(e){
      if(pub == "enf"){
        $("#pointLien").attr('href','graphiques_enfants.html');
      }else{
        $("#pointLien").attr('href','graphiques_adultes.html');
      }
    });

  });

function demoFromHTML() {

alert("hola");

     var pdf = new jsPDF('p', 'pt', 'a4', false);
     //var pdf = new jsPDF();
  /*var logo = new Image();
         pdf.text("hello", 30,30);
       logo.src = "1.png";
       pdf.addImage(logo, 'PNG', 2, 2, 590,850);*/

          if(duration_longue){
            var logo = new Image();
            logo.src = "https://vizkit.github.io/donnees/4jpeg";
            pdf.addImage(logo, 'JPEG', 2, 2, 590,850);
            pdf.addPage();
     //       var logo = new Image();
      //      logo.src = "/pdf_images/1.png";
       //     pdf.addImage(logo, 'PNG', 2, 2, 590,850);

          }/*else if(duration_courte) {
            logo.src = "/pdf_images/1.png";
            pdf.addImage(logo, 'PNG', 2, 2, 590,850);
            pdf.addPage();
            logo.src = "/pdf_images/1.png";
            pdf.addImage(logo, 'PNG', 2, 2, 590,850);

          }*/

           var uno= 1;

       /*   var paso;
        for (paso = 4; paso < 6; paso++) {
            pdf.addPage();
            var logo = new Image();
            logo.src = paso+".png";
            pdf.addImage(logo, 'PNG', 2, 2, 590,850);
          // Se ejecuta 5 veces, con valores desde paso desde 0 hasta 4.

          };*/

     pdf.output("dataurlnewwindow");

        }
<|endoftext|>


<commit_before>/*

function demoFromHTML() {

     var pdf = new jsPDF('p', 'pt', 'a4', false);

  alert(duration_longue);

          if(duration_longue){

            if(adult){
              alert("adult_long");
              var logo = new Image();
              logo.src = "https://vizkit.github.io/pdf_images/long/Long_adults/long_adults_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();
            }else{
                 alert("enfant_LONGUE");
              logo.src = "https://vizkit.github.io/pdf_images/long/Long_enfants/long_enfants_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();
            }

          }else{
            if(enfant){
                 alert("enfant_Court");
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_1.PNG";
                pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                pdf.addPage();

            }else {
              alert("adult_court");
              logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();

            }

           var uno= 1;
          }

       /*   var paso;
        for (paso = 4; paso < 6; paso++) {
            pdf.addPage();
            var logo = new Image();
            logo.src = paso+".png";
            pdf.addImage(logo, 'PNG', 2, 2, 590,850);
          // Se ejecuta 5 veces, con valores desde paso desde 0 hasta 4.

          };

     pdf.output("dataurlnewwindow");

        }*/

  $(document).ready(function(){
  //on initialise les variables avec les valeurs par défaut

    var duree = "longue";
    var pub = "adu";
    var nbDePersonnes = 16;
    var sce = 1;
    duration_longue = true;
    duration_courte = false;
    enfant = false;
    adult = true;

  //on appuie les boutons en conséquence
    $("#dur_lon").addClass("active");
    $("#pub_adu").addClass("active");
    $("#sce_1").addClass("active");
    //$("#car").load('carousel_long.html');

    //On remplit le champ du bouton +/- avec la valeur par défaut
    $("#inputnb").val(nbDePersonnes);

    //var carousel_c = $.get("carousel_court.html");
    //var carousel_l = $.get("carousel_long.html");
  //On change la valeur des variables en fonction des actions utilisateurs
  //Pour la durée :
    $("#dur_cou").click(function(e){
      duree = "courte";
      duration_courte = true;
      duration_longue = false;
      $("#dur_lon").removeClass("active");
      $("#dur_cou").addClass("active");
      //var code = load("carousel_court.html");
      //$("#myCarousel").replaceWith("
 This text is strong
  This text is italic
");
      //alert(carousel_c);
      //$("#car").empty();
      $("#car").load('carousel_court.html');
      $("#p1").show();
            alert(duration_longue);
            alert(duration_courte);
      alert("Chargement terminé \n Guide pour atelier court !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();});
    });
    $("#dur_lon").click(function(e){
      duree = "longue";
      duration_longue = true;
      duration_courte = false;
      $("#dur_cou").removeClass("active");
      $("#dur_lon").addClass("active");
      //$("#myCarousel").replaceWith(carousel_l);
      //$("#car").empty();
      $("#car").load('carousel_long.html');
      $("#p1").show();
      alert("Chargement terminé \n Guide pour atelier long !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();})
    });
  //Pour le public :
    $("#pub_enf").click(function(e){
      pub = "enf";
      adult = false;
      enfant = true;
      $("#pub_adu").removeClass("active");
      $("#pub_enf").addClass("active");
    });
    $("#pub_adu").click(function(e){
      pub = "adu";
      adult = true;
      enfant = false;
      $("#pub_enf").removeClass("active");
      $("#pub_adu").addClass("active");
    });
  //Pour le scénario :
    $("#sce_2").click(function(e){
      sce = 2;
      $("#sce_1").removeClass("active");
      $("#sce_2").addClass("active");
    });
    $("#sce_1").click(function(e){
      sce = 1;
      $("#sce_2").removeClass("active");
      $("#sce_1").addClass("active");
    });

    $("#pointLien").click(function(e){
      if(pub == "enf"){
        $("#pointLien").attr('href','graphiques_enfants.html');
      }else{
        $("#pointLien").attr('href','graphiques_adultes.html');
      }
    });

   $("#buttonemail").click(function(e){

     var pdf = new jsPDF('p', 'pt', 'a4', false);

  alert("longue");
  alert(duration_longue);
alert(duration_longue);

          if(duration_longue){

            if(adult){
              alert("adult_long");
              var logo = new Image();
              logo.src = "https://vizkit.github.io/pdf_images/long/Long_adults/long_adults_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();
            }else{
                 alert("enfant_LONGUE");
              logo.src = "https://vizkit.github.io/pdf_images/long/Long_enfants/long_enfants_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();
            }

          }else{
            if(enfant){
                 alert("enfant_Court");
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_1.PNG";
                pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                pdf.addPage();

            }else {
              alert("adult_court");
              logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();

            }

           var uno= 1;
          }

       /*   var paso;
        for (paso = 4; paso < 6; paso++) {
            pdf.addPage();
            var logo = new Image();
            logo.src = paso+".png";
            pdf.addImage(logo, 'PNG', 2, 2, 590,850);
          // Se ejecuta 5 veces, con valores desde paso desde 0 hasta 4.

          };*/

     pdf.output("dataurlnewwindow");

      });

  });

<commit_msg>Update dynamic_carousel.js<commit_after>/*

function demoFromHTML() {

     var pdf = new jsPDF('p', 'pt', 'a4', false);

  alert(duration_longue);

          if(duration_longue){

            if(adult){
              alert("adult_long");
              var logo = new Image();
              logo.src = "https://vizkit.github.io/pdf_images/long/Long_adults/long_adults_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();
            }else{
                 alert("enfant_LONGUE");
              logo.src = "https://vizkit.github.io/pdf_images/long/Long_enfants/long_enfants_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();
            }

          }else{
            if(enfant){
                 alert("enfant_Court");
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_1.PNG";
                pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                pdf.addPage();

            }else {
              alert("adult_court");
              logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();

            }

           var uno= 1;
          }

       /*   var paso;
        for (paso = 4; paso < 6; paso++) {
            pdf.addPage();
            var logo = new Image();
            logo.src = paso+".png";
            pdf.addImage(logo, 'PNG', 2, 2, 590,850);
          // Se ejecuta 5 veces, con valores desde paso desde 0 hasta 4.

          };

     pdf.output("dataurlnewwindow");

        }*/

  $(document).ready(function(){
  //on initialise les variables avec les valeurs par défaut

    var duree = "longue";
    var pub = "adu";
    var nbDePersonnes = 16;
    var sce = 1;
    duration_longue = true;
    duration_courte = false;
    enfant = false;
    adult = true;

  //on appuie les boutons en conséquence
    $("#dur_lon").addClass("active");
    $("#pub_adu").addClass("active");
    $("#sce_1").addClass("active");
    //$("#car").load('carousel_long.html');

    //On remplit le champ du bouton +/- avec la valeur par défaut
    $("#inputnb").val(nbDePersonnes);

    //var carousel_c = $.get("carousel_court.html");
    //var carousel_l = $.get("carousel_long.html");
  //On change la valeur des variables en fonction des actions utilisateurs
  //Pour la durée :
    $("#dur_cou").click(function(e){
      duree = "courte";
      duration_courte = true;
      duration_longue = false;
      $("#dur_lon").removeClass("active");
      $("#dur_cou").addClass("active");
      //var code = load("carousel_court.html");
      //$("#myCarousel").replaceWith("
 This text is strong
  This text is italic
");
      //alert(carousel_c);
      //$("#car").empty();
      $("#car").load('carousel_court.html');
      $("#p1").show();
      alert("Chargement terminé \n Guide pour atelier court !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();});
    });
    $("#dur_lon").click(function(e){
      duree = "longue";
      duration_longue = true;
      duration_courte = false;
      $("#dur_cou").removeClass("active");
      $("#dur_lon").addClass("active");
      //$("#myCarousel").replaceWith(carousel_l);
      //$("#car").empty();
      $("#car").load('carousel_long.html');
      $("#p1").show();
      alert("Chargement terminé \n Guide pour atelier long !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();})
    });
  //Pour le public :
    $("#pub_enf").click(function(e){
      pub = "enf";
      adult = false;
      enfant = true;
      $("#pub_adu").removeClass("active");
      $("#pub_enf").addClass("active");
    });
    $("#pub_adu").click(function(e){
      pub = "adu";
      adult = true;
      enfant = false;
      $("#pub_enf").removeClass("active");
      $("#pub_adu").addClass("active");
    });
  //Pour le scénario :
    $("#sce_2").click(function(e){
      sce = 2;
      $("#sce_1").removeClass("active");
      $("#sce_2").addClass("active");
    });
    $("#sce_1").click(function(e){
      sce = 1;
      $("#sce_2").removeClass("active");
      $("#sce_1").addClass("active");
    });

    $("#pointLien").click(function(e){
      if(pub == "enf"){
        $("#pointLien").attr('href','graphiques_enfants.html');
      }else{
        $("#pointLien").attr('href','graphiques_adultes.html');
      }
    });

   $("#buttonemail").click(function(e){

     var pdf = new jsPDF('p', 'pt', 'a4', false);

  alert(duration_longue);
alert(duration_courte);

          if(duration_longue){

            if(adult){
              alert("adult_long");
              var logo = new Image();
              logo.src = "https://vizkit.github.io/pdf_images/long/Long_adults/long_adults_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();
            }else{
                 alert("enfant_LONGUE");
              logo.src = "https://vizkit.github.io/pdf_images/long/Long_enfants/long_enfants_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();
            }

          }else{
            if(enfant){
                 alert("enfant_Court");
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_1.PNG";
                pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                pdf.addPage();

            }else {
              alert("adult_court");
              logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();

            }

           var uno= 1;
          }

       /*   var paso;
        for (paso = 4; paso < 6; paso++) {
            pdf.addPage();
            var logo = new Image();
            logo.src = paso+".png";
            pdf.addImage(logo, 'PNG', 2, 2, 590,850);
          // Se ejecuta 5 veces, con valores desde paso desde 0 hasta 4.

          };*/

     pdf.output("dataurlnewwindow");

      });

  });

<|endoftext|>


<commit_before>/**
 * @fileoverview Promise Interface tests
 */
const { assert } = require('chai');
const Promise = require('bluebird');

const midd = require('../');

/**
 * Apply test suites with various parameters.
 *
 * @param {number} num The number of the test to use.
 * @param {string} middMethod The middlewarify method to be used.
 * @param {Object=} middOpts Options to create the middleware with.
 */
function applyTests(num, middMethod, middOpts) {
  let middleware;
  setup(function() {
    if (middMethod !== 'use') {
      middOpts = { beforeAfter: true };
    }
    middleware = Object.create(null);
    midd.make(
      middleware,
      'create',
      function() {
        return Promise.resolve();
      },
      middOpts,
    );
  });

  test(`7.${num}.1 accepts a promise`, function(done) {
    middleware.create[middMethod](function() {
      return new Promise(function(resolve) {
        resolve();
      });
    });
    middleware.create().then(done, done);
  });
  test(`7.${num}.2 propagates error`, function(done) {
    middleware.create[middMethod](function() {
      return new Promise(function(resolve, reject) {
        setTimeout(function() {
          reject(new Error('poop'));
        });
      });
    });
    middleware.create().catch(function() {
      done();
    });
  });
  test(`7.${num}.3 propagates error message`, function(done) {
    middleware.create[middMethod](function() {
      return new Promise(function(resolve, reject) {
        setTimeout(function() {
          reject(new Error('Error'));
        });
      });
    });
    middleware
      .create()
      .catch(function(err) {
        assert.equal(err.message, 'Error');
      })
      .then(done, done);
  });
  test(`7.${num}.4 arguments propagate`, function(done) {
    middleware.create[middMethod](function(arg1) {
      return new Promise(function(resolve) {
        assert.equal(arg1, 1);
        resolve();
      });
    });
    middleware.create[middMethod](function(arg1) {
      return new Promise(function(resolve) {
        assert.equal(arg1, 1);
        resolve();
      });
    });

    middleware.create(1).then(done, done);
  });

  test(`7.${num}.5 async resolution`, function(done) {
    let invoked = false;
    middleware.create[middMethod](function() {
      return new Promise(function(resolve) {
        setTimeout(function() {
          invoked = true;
          resolve();
        });
      });
    });
    middleware
      .create()
      .then(function() {
        assert.ok(invoked);
      })
      .then(done, done);
  });
  test(`7.${num}.6 async rejection`, function(done) {
    let invoked = false;
    middleware.create[middMethod](function() {
      return new Promise(function(resolve, reject) {
        setTimeout(function() {
          invoked = true;
          reject();
        });
      });
    });
    middleware
      .create()
      .then(null, function() {
        assert.ok(invoked);
      })
      .then(done, done);
  });

  test(`7.${num}.7 async resolution for final callback`, function(done) {
    let invoked = false;
    middleware = Object.create(null);
    midd.make(
      middleware,
      'create',
      function() {
        return new Promise(function(resolve) {
          setTimeout(function() {
            invoked = true;
            resolve();
          });
        });
      },
      middOpts,
    );
    middleware
      .create()
      .then(function() {
        assert.ok(invoked);
      })
      .then(done, done);
  });
}

/**
 * Actual Testing Starts
 *
 *
 *
 *
 *
 *
 */

suite('7. Promise Interface', function() {
  suite('7.1 Middleware with use()', function() {
    applyTests(1, 'use');
  });
  suite('7.2 Middleware with before()', function() {
    applyTests(2, 'before', { beforeAfter: true });
  });
  suite('7.3 Middleware with after()', function() {
    applyTests(3, 'after', { beforeAfter: true });
  });
  suite('7.8 Middleware with use() check', function() {
    const newMidd = Object.create(null);
    midd.make(newMidd, 'create', function() {
      return Promise.resolve();
    });

    test('7.8.3 propagates error message', function(done) {
      newMidd.create.use(function() {
        return new Promise(function(resolve, reject) {
          setTimeout(function() {
            reject(new Error('Error'));
          });
        });
      });
      newMidd
        .create()
        .then(null, function(err) {
          assert.equal(err.message, 'Error');
          done();
        })
        .then(null, done);
    });
  });
});
<commit_msg>adjust promise interface tests<commit_after>/**
 * @fileoverview Promise Interface tests
 */
const { assert } = require('chai');
const Promise = require('bluebird');

const midd = require('../');

/**
 * Apply test suites with various parameters.
 *
 * @param {number} num The number of the test to use.
 * @param {string} middMethod The middlewarify method to be used.
 * @param {Object=} middOpts Options to create the middleware with.
 */
function applyTests(num, middMethod, middOpts) {
  let middleware;
  setup(function() {
    middleware = Object.create(null);
    midd.make(
      middleware,
      'create',
      function() {
        return Promise.resolve();
      },
      middOpts,
    );
  });

  test(`7.${num}.1 accepts a promise`, function(done) {
    middleware.create[middMethod](function() {
      return new Promise(function(resolve) {
        resolve();
      });
    });
    const retVal = middleware.create();
    retVal.then(done, done);
  });
  test(`7.${num}.2 propagates error`, function(done) {
    middleware.create[middMethod](function() {
      return new Promise(function(resolve, reject) {
        setTimeout(function() {
          reject(new Error('poop'));
        });
      });
    });
    middleware.create().catch(function() {
      done();
    });
  });
  test(`7.${num}.3 propagates error message`, function(done) {
    middleware.create[middMethod](function() {
      return new Promise(function(resolve, reject) {
        setTimeout(function() {
          reject(new Error('Error'));
        });
      });
    });
    middleware
      .create()
      .catch(function(err) {
        assert.equal(err.message, 'Error');
      })
      .then(done, done);
  });
  test(`7.${num}.4 arguments propagate`, function(done) {
    middleware.create[middMethod](function(arg1) {
      return new Promise(function(resolve) {
        assert.equal(arg1, 1);
        resolve();
      });
    });
    middleware.create[middMethod](function(arg1) {
      return new Promise(function(resolve) {
        assert.equal(arg1, 1);
        resolve();
      });
    });

    middleware.create(1).then(done, done);
  });

  test(`7.${num}.5 async resolution`, function(done) {
    let invoked = false;
    middleware.create[middMethod](function() {
      return new Promise(function(resolve) {
        setTimeout(function() {
          invoked = true;
          resolve();
        });
      });
    });
    middleware
      .create()
      .then(function() {
        assert.ok(invoked);
      })
      .then(done, done);
  });
  test(`7.${num}.6 async rejection`, function(done) {
    let invoked = false;
    middleware.create[middMethod](function() {
      return new Promise(function(resolve, reject) {
        setTimeout(function() {
          invoked = true;
          reject();
        });
      });
    });
    middleware
      .create()
      .then(null, function() {
        assert.ok(invoked);
      })
      .then(done, done);
  });

  test(`7.${num}.7 async resolution for final callback`, function(done) {
    let invoked = false;
    middleware = Object.create(null);
    midd.make(
      middleware,
      'create',
      function() {
        return new Promise(function(resolve) {
          setTimeout(function() {
            invoked = true;
            resolve();
          });
        });
      },
      middOpts,
    );
    middleware
      .create()
      .then(function() {
        assert.ok(invoked);
      })
      .then(done, done);
  });
}

/**
 * Actual Testing Starts
 *
 *
 *
 *
 *
 *
 */

suite('7. Promise Interface', function() {
  suite('7.1 Middleware with use()', function() {
    applyTests(1, 'use', { async: true });
  });
  suite('7.2 Middleware with before()', function() {
    applyTests(2, 'before', { beforeAfter: true, async: true });
  });
  suite('7.3 Middleware with after()', function() {
    applyTests(3, 'after', { beforeAfter: true, async: true });
  });
  suite('7.8 Middleware with use() check', function() {
    const newMidd = Object.create(null);
    midd.make(
      newMidd,
      'create',
      function() {
        return Promise.resolve();
      },
      { async: true },
    );

    test('7.8.3 propagates error message', function(done) {
      newMidd.create.use(function() {
        return new Promise(function(resolve, reject) {
          setTimeout(function() {
            reject(new Error('Error'));
          });
        });
      });
      newMidd
        .create()
        .then(null, function(err) {
          assert.equal(err.message, 'Error');
          done();
        })
        .then(null, done);
    });
  });
});
<|endoftext|>