<commit_before>describe("iD.presets.Category", function() {
    var category, residential;

    beforeEach(function() {
        category = {
            "geometry": "line",
            "icon": "highway",
            "name": "roads",
            "members": [
                "highway/residential"
            ]
        };
        residential = iD.presets.Preset('highway/residential', {
            tags: {
                highway: 'residential'
            },
            geometry: ['line']
        });
    });

    it("maps members names to preset instances", function() {
        var c = iD.presets.Category(category, iD.presets.Collection([residential]));
        expect(c.members.collection[0]).to.eql(residential);
    });

    describe("#matchGeometry", function() {
        it("matches the type of an entity", function() {
            var c = iD.presets.Category(category, iD.presets.Collection([residential])),
                w = iD.Way(),
                n = iD.Node(),
                g = iD.Graph().replace(w);
            expect(c.matchGeometry(w, g)).to.eql(true);
            expect(c.matchGeometry(n, g)).to.eql(false);
        });
    });
});
<commit_msg>Fix tests<commit_after>describe("iD.presets.Category", function() {
    var category, residential;

    beforeEach(function() {
        category = {
            "geometry": "line",
            "icon": "highway",
            "name": "roads",
            "members": [
                "highway/residential"
            ]
        };
        residential = iD.presets.Preset('highway/residential', {
            tags: {
                highway: 'residential'
            },
            geometry: ['line']
        });
    });

    it("maps members names to preset instances", function() {
        var c = iD.presets.Category('road', category, iD.presets.Collection([residential]));
        expect(c.members.collection[0]).to.eql(residential);
    });

    describe("#matchGeometry", function() {
        it("matches the type of an entity", function() {
            var c = iD.presets.Category('road', category, iD.presets.Collection([residential])),
                w = iD.Way(),
                n = iD.Node(),
                g = iD.Graph().replace(w);
            expect(c.matchGeometry(w, g)).to.eql(true);
            expect(c.matchGeometry(n, g)).to.eql(false);
        });
    });
});
<|endoftext|>


<commit_before>/* global describe, it, before, expect */
/* jshint expr: true */

var GitHubStrategy = require('../lib/strategy');

describe('Strategy#userProfile', function() {

  describe('fetched from default endpoint', function() {
    var strategy =  new GitHubStrategy({
      clientID: 'ABC123',
      clientSecret: 'secret'
    }, function() {});

    strategy._oauth2.get = function(url, accessToken, callback) {
      if (url != 'https://api.github.com/user') { return callback(new Error('wrong url argument')); }
      if (accessToken != 'token') { return callback(new Error('wrong token argument')); }

      var body = '{ "login": "octocat", "id": 1, "name": "monalisa octocat", "email": "octocat@github.com", "html_url": "https://github.com/octocat" }';
      callback(null, body, undefined);
    };

    var profile;

    before(function(done) {
      strategy.userProfile('token', function(err, p) {
        if (err) { return done(err); }
        profile = p;
        done();
      });
    });

    it('should parse profile', function() {
      expect(profile.provider).to.equal('github');

      expect(profile.id).to.equal('1');
      expect(profile.username).to.equal('octocat');
      expect(profile.displayName).to.equal('monalisa octocat');
      expect(profile.profileUrl).to.equal('https://github.com/octocat');
      expect(profile.emails).to.have.length(1);
      expect(profile.emails[0].value).to.equal('octocat@github.com');
    });

    it('should set raw property', function() {
      expect(profile._raw).to.be.a('string');
    });

    it('should set json property', function() {
      expect(profile._json).to.be.an('object');
    });
  }); // fetched from default endpoint

  describe('fetched from default endpoint and then fetching emails, where user has a publicly visible email address', function() {
    var strategy =  new GitHubStrategy({
      clientID: 'ABC123',
      clientSecret: 'secret',
      scope: [ 'user:email' ]
    }, function() {});

    strategy._oauth2._request = function(method, url, headers, body, accessToken, callback) {
      var body;
      switch (url) {
      case 'https://api.github.com/user':
        body = '{ "login": "octocat", "id": 1, "name": "monalisa octocat", "email": "octocat@github.com", "html_url": "https://github.com/octocat" }';
        break;
      case 'https://api.github.com/user/emails':
        body = '[{"email":"octocat@github.com","primary":true,"verified":true}]';
        break;
      default:
        return callback(new Error('wrong url argument'));
      }
      callback(null, body, undefined);
    };

    var profile;

    before(function(done) {
      strategy.userProfile('token', function(err, p) {
        if (err) { return done(err); }
        profile = p;
        done();
      });
    });

    it('should parse profile', function() {
      expect(profile.provider).to.equal('github');

      expect(profile.id).to.equal('1');
      expect(profile.username).to.equal('octocat');
      expect(profile.displayName).to.equal('monalisa octocat');
      expect(profile.profileUrl).to.equal('https://github.com/octocat');
      expect(profile.emails).to.have.length(1);
      expect(profile.emails[0].value).to.equal('octocat@github.com');
      expect(profile.emails[0].primary).to.equal(true);
      expect(profile.emails[0].verified).to.equal(true);
    });

    it('should set raw property', function() {
      expect(profile._raw).to.be.a('string');
    });

    it('should set json property', function() {
      expect(profile._json).to.be.an('object');
    });
  }); // fetched from default endpoint and then fetching emails, where user has a publicly visible email address

  describe('error caused by invalid token', function() {
    var strategy =  new GitHubStrategy({
        clientID: 'ABC123',
        clientSecret: 'secret'
      }, function() {});

    strategy._oauth2.get = function(url, accessToken, callback) {
      var body = '{"message":"Bad credentials","documentation_url":"https://developer.github.com/v3"}';
      callback({ statusCode: 400, data: body });
    };

    var err, profile;
    before(function(done) {
      strategy.userProfile('token', function(e, p) {
        err = e;
        profile = p;
        done();
      });
    });

    it('should error', function() {
      expect(err).to.be.an.instanceOf(Error);
      expect(err.constructor.name).to.equal('APIError');
      expect(err.message).to.equal('Bad credentials');
    });
  }); // error caused by invalid token

  describe('internal error', function() {
    var strategy =  new GitHubStrategy({
      clientID: 'ABC123',
      clientSecret: 'secret'
    }, function() {});

    strategy._oauth2.get = function(url, accessToken, callback) {
      return callback(new Error('something went wrong'));
    }

    var err, profile;

    before(function(done) {
      strategy.userProfile('wrong-token', function(e, p) {
        err = e;
        profile = p;
        done();
      });
    });

    it('should error', function() {
      expect(err).to.be.an.instanceOf(Error);
      expect(err.constructor.name).to.equal('InternalOAuthError');
      expect(err.message).to.equal('Failed to fetch user profile');
      expect(err.oauthError).to.be.an.instanceOf(Error);
      expect(err.oauthError.message).to.equal('something went wrong');
    });

    it('should not load profile', function() {
      expect(profile).to.be.undefined;
    });
  }); // internal error

});
<commit_msg>More test cases.<commit_after>/* global describe, it, before, expect */
/* jshint expr: true */

var GitHubStrategy = require('../lib/strategy');

describe('Strategy#userProfile', function() {

  describe('fetched from default endpoint', function() {
    var strategy =  new GitHubStrategy({
      clientID: 'ABC123',
      clientSecret: 'secret'
    }, function() {});

    strategy._oauth2.get = function(url, accessToken, callback) {
      if (url != 'https://api.github.com/user') { return callback(new Error('wrong url argument')); }
      if (accessToken != 'token') { return callback(new Error('wrong token argument')); }

      var body = '{ "login": "octocat", "id": 1, "name": "monalisa octocat", "email": "octocat@github.com", "html_url": "https://github.com/octocat" }';
      callback(null, body, undefined);
    };

    var profile;

    before(function(done) {
      strategy.userProfile('token', function(err, p) {
        if (err) { return done(err); }
        profile = p;
        done();
      });
    });

    it('should parse profile', function() {
      expect(profile.provider).to.equal('github');

      expect(profile.id).to.equal('1');
      expect(profile.username).to.equal('octocat');
      expect(profile.displayName).to.equal('monalisa octocat');
      expect(profile.profileUrl).to.equal('https://github.com/octocat');
      expect(profile.emails).to.have.length(1);
      expect(profile.emails[0].value).to.equal('octocat@github.com');
    });

    it('should set raw property', function() {
      expect(profile._raw).to.be.a('string');
    });

    it('should set json property', function() {
      expect(profile._json).to.be.an('object');
    });
  }); // fetched from default endpoint

  describe('fetched from default endpoint and then fetching emails, where user has a publicly visible email address', function() {
    var strategy =  new GitHubStrategy({
      clientID: 'ABC123',
      clientSecret: 'secret',
      scope: [ 'user:email' ]
    }, function() {});

    strategy._oauth2._request = function(method, url, headers, body, accessToken, callback) {
      var body;
      switch (url) {
      case 'https://api.github.com/user':
        body = '{ "login": "octocat", "id": 1, "name": "monalisa octocat", "email": "octocat@github.com", "html_url": "https://github.com/octocat" }';
        break;
      case 'https://api.github.com/user/emails':
        body = '[{"email":"octocat@github.com","primary":true,"verified":true}]';
        break;
      default:
        return callback(new Error('wrong url argument'));
      }
      callback(null, body, undefined);
    };

    var profile;

    before(function(done) {
      strategy.userProfile('token', function(err, p) {
        if (err) { return done(err); }
        profile = p;
        done();
      });
    });

    it('should parse profile', function() {
      expect(profile.provider).to.equal('github');

      expect(profile.id).to.equal('1');
      expect(profile.username).to.equal('octocat');
      expect(profile.displayName).to.equal('monalisa octocat');
      expect(profile.profileUrl).to.equal('https://github.com/octocat');
      expect(profile.emails).to.have.length(1);
      expect(profile.emails[0].value).to.equal('octocat@github.com');
      expect(profile.emails[0].primary).to.equal(true);
      expect(profile.emails[0].verified).to.equal(true);
    });

    it('should set raw property', function() {
      expect(profile._raw).to.be.a('string');
    });

    it('should set json property', function() {
      expect(profile._json).to.be.an('object');
    });
  }); // fetched from default endpoint and then fetching emails, where user has a publicly visible email address

  describe('error caused by invalid token', function() {
    var strategy =  new GitHubStrategy({
        clientID: 'ABC123',
        clientSecret: 'secret'
      }, function() {});

    strategy._oauth2.get = function(url, accessToken, callback) {
      var body = '{"message":"Bad credentials","documentation_url":"https://developer.github.com/v3"}';
      callback({ statusCode: 400, data: body });
    };

    var err, profile;
    before(function(done) {
      strategy.userProfile('token', function(e, p) {
        err = e;
        profile = p;
        done();
      });
    });

    it('should error', function() {
      expect(err).to.be.an.instanceOf(Error);
      expect(err.constructor.name).to.equal('APIError');
      expect(err.message).to.equal('Bad credentials');
    });
  }); // error caused by invalid token

  describe('error caused by malformed response', function() {
    var strategy =  new GitHubStrategy({
        clientID: 'ABC123',
        clientSecret: 'secret'
      }, function() {});

    strategy._oauth2.get = function(url, accessToken, callback) {
      var body = 'Hello, world.';
      callback(null, body, undefined);
    };

    var err, profile;
    before(function(done) {
      strategy.userProfile('token', function(e, p) {
        err = e;
        profile = p;
        done();
      });
    });

    it('should error', function() {
      expect(err).to.be.an.instanceOf(Error);
      expect(err.message).to.equal('Failed to parse user profile');
    });
  }); // error caused by malformed response

  describe('internal error', function() {
    var strategy =  new GitHubStrategy({
      clientID: 'ABC123',
      clientSecret: 'secret'
    }, function() {});

    strategy._oauth2.get = function(url, accessToken, callback) {
      return callback(new Error('something went wrong'));
    }

    var err, profile;

    before(function(done) {
      strategy.userProfile('wrong-token', function(e, p) {
        err = e;
        profile = p;
        done();
      });
    });

    it('should error', function() {
      expect(err).to.be.an.instanceOf(Error);
      expect(err.constructor.name).to.equal('InternalOAuthError');
      expect(err.message).to.equal('Failed to fetch user profile');
      expect(err.oauthError).to.be.an.instanceOf(Error);
      expect(err.oauthError.message).to.equal('something went wrong');
    });

    it('should not load profile', function() {
      expect(profile).to.be.undefined;
    });
  }); // internal error

});
<|endoftext|>


<commit_before>var std = require('std'),
	tokenizer = require('../../src/tokenizer'),
	parser = require('../../src/parser'),
	resolver = require('../../src/resolver'),
	compiler = require('../../src/compiler'),
	a = require('../ast-mocks'),
	http = require('http'),
	zombie = require('zombie'),
	compilerServerPort = 9797,
	slice = require('std/slice'),
	bind = require('std/bind'),
	each = require('std/each')

var currentTestCode, compilerServer

startCompilerServer()

test('a number and a string').code(
	'
"Hello " 1
')
	.textIs('#output', 'Hello 1')

test('a variable in a div').code(
	'var foo = "foo"',
	'
foo
')
	.textIs('#output', 'foo')

test('clicking a button updates the UI').code(
	'var foo = "bar"',
	'
foo
',
	'<button id="button"></button onClick=handler() {',
	'	foo.set("cat")',
	'}>')
	.textIs('#output', 'bar')
	.click('#button')
	.textIs('#output', 'cat')

test('object literals').code(
	'var foo = { nested: { bar:1 } }',
	'
foo foo.nested foo.nested.bar
'
	)
	.textIs('#output', '{ nested:{ bar:1 } }{ bar:1 }1')

test('divs follow mouse').code(
	'import Mouse',
	'
',
	'
'
	)
	.moveMouse(100, 100)
	.positionIs('#output1', 100, 100)
	.positionIs('#output2', 150, 150)

test('script tag variable passing').code(
	'var foo = "foo"',
	'',
	'
foo
')
	.textIs('#output', 'bar')

test('variable declaration inside div').code(
	'
',
	'	var cat = "cat"',
	'
cat
',
	'
')
	.textIs('#output', 'cat')

test('changing object literals').code(
	'var foo = { a:1 }',
	'
',
	'	{ foo: { a:foo.a } }',
	'	{ a:foo.a }',
	'	foo',
	'
'
	)
	.textIs('#output', '{ foo:{ a:1 } }{ a:1 }{ a:1 }')
	.click('#output')
	.textIs('#output', '{ foo:{ a:2 } }{ a:2 }{ a:2 }')

test('null values').code(
	'var foo=null',
	'
"null:"foo " null:"null
'
	)
	.textIs('#output', 'null: null:')

// test('value changes type')
// 	.compile(
// 		'let foo = "bar"',
// 		'
foo
',
// 		'
foo.Type
',
// 		'<button id="button"></button onClick=handler() { foo.set(1) }>'
// 	)
// 	.textIs('#value', 'bar')
// 	.textIs('#Type', 'Text')
// 	.click('#button')
// 	.textIs('#value', 1)
// 	.textIs('#Type', 'Number')

// test('handler with logic')
// 	.code(
// 		'let cat = "hi1"',
// 		'let foo = handler() {',
// 		'	if (cat == "hi1") { cat.set("hi2") }',
// 		'	else { cat.set("hi3") }',
// 		'}',
// 		'<button id="button" onclick=foo/>',
// 		'
cat
'
// 	)
// 	.textIs('#output', 'hi1')
// 	.click('#button')
// 	.textIs('#output', 'hi2')
// 	.click('#button')
// 	.textIs('#output', 'hi3')

/* Util
 ******/
var isFirstTest = true
function test(name) {
	var actionHandlers = createActionHandlers()
	var testObj = {
		code: function() {
			var code = std.slice(arguments).join('\n'),
				actions = this._actions = []

			module.exports['compile\t"'+name+'"'] = function(assert) {
				currentTestCode = code

				try {
					var tokens = tokenizer.tokenize(currentTestCode),
						parsedAST = parser.parse(tokens),
						resolvedAST = resolver.resolve(parsedAST),
						result = compiler._printHTML(compiler.compile(resolvedAST))
				} catch(e) {
					console.log(e.stack)
					process.exit()
				}

				if (isFirstTest) { console.log('loading headless browser - hang tight!'); isFirstTest = false }
				zombie.visit('http://localhost:'+compilerServerPort, { debug:false }, function(err, browser) {
					if (err || browser.statusCode != 200) {
						throw new Error("Error: " + err + " " + browser.statusCode + " " + browser.errors)
					}
					(function nextAction() {
						if (!actions.length) {
							assert.done()
							scheduleCompilerServerShutdown()
							return
						}
						var action = actions.shift()
						try {
							actionHandlers[action.name].apply(this, [assert, browser, nextAction].concat(action.args))
						} catch(e) {
							console.log('compiler threw -', e.stack, '\n\nThe test code that caused the error:\n', currentTestCode)
						}
					})()
				})
			}
			return this
		}
	}

	each(actionHandlers, function(handler, name) {
		testObj[name] = function chainableAction() {
			this._actions.push({ name:name, args:slice(arguments) })
			return this
		}
	})

	return testObj
}

function createActionHandlers() {
	return {
		// Events
		click: function(assert, browser, next, selector) {
			var target = browser.querySelector(selector)
			browser.fire('click', target, next)
		},
		moveMouse: function(assert, browser, next, clientX, clientY) {
			browser.fire('mousemove', browser.document, { attributes: {clientX:clientX, clientY:clientY} }, next)
		},
		// Asserts
		htmlIs: function(assert, browser, next, selector, expectedHTML) {
			assert.deepEqual(expectedHTML, browser.html(selector))
			next()
		},
		textIs: function(assert, browser, next, selector, expectedHTML) {
			assert.deepEqual(expectedHTML, browser.text(selector))
			next()
		},
		positionIs: function(assert, browser, next, selector, x, y) {
			var style = browser.querySelector(selector).style
			assert.deepEqual(style.left, x+'px')
			assert.deepEqual(style.top, y+'px')
			next()
		}
	}
}

function startCompilerServer() {
	compilerServer = http.createServer(function(res, res) {
		try {
			var tokens = tokenizer.tokenize(currentTestCode),
				parsedAST = parser.parse(tokens),
				resolvedAST = resolver.resolve(parsedAST),
				result = compiler._printHTML(compiler.compile(resolvedAST))
		} catch(e) {
			var error = e
		}

		if (error) {
			console.log("compiler server error", error.stack)
			res.writeHead(500)
			res.end(error.stack)
		} else {
			res.writeHead(200, { 'Content-Length':result.length })
			res.end(result)
		}
	})
	compilerServer.listen(compilerServerPort)
}

function scheduleCompilerServerShutdown() {
	clearTimeout(scheduleCompilerServerShutdown.timeout)
	scheduleCompilerServerShutdown.timeout = setTimeout(function() {
		console.log("Tests done, shutting down compiler server")
		compilerServer.close()
	}, 200)
}
<commit_msg>Dump all browser state on error<commit_after>var std = require('std'),
	tokenizer = require('../../src/tokenizer'),
	parser = require('../../src/parser'),
	resolver = require('../../src/resolver'),
	compiler = require('../../src/compiler'),
	a = require('../ast-mocks'),
	http = require('http'),
	zombie = require('zombie'),
	compilerServerPort = 9797,
	slice = require('std/slice'),
	bind = require('std/bind'),
	each = require('std/each')

var currentTestCode, compilerServer

startCompilerServer()

test('a number and a string').code(
	'
"Hello " 1
')
	.textIs('#output', 'Hello 1')

test('a variable in a div').code(
	'var foo = "foo"',
	'
foo
')
	.textIs('#output', 'foo')

test('clicking a button updates the UI').code(
	'var foo = "bar"',
	'
foo
',
	'<button id="button"></button onClick=handler() {',
	'	foo.set("cat")',
	'}>')
	.textIs('#output', 'bar')
	.click('#button')
	.textIs('#output', 'cat')

test('object literals').code(
	'var foo = { nested: { bar:1 } }',
	'
foo foo.nested foo.nested.bar
'
	)
	.textIs('#output', '{ nested:{ bar:1 } }{ bar:1 }1')

test('divs follow mouse').code(
	'import Mouse',
	'
',
	'
'
	)
	.moveMouse(100, 100)
	.positionIs('#output1', 100, 100)
	.positionIs('#output2', 150, 150)

test('script tag variable passing').code(
	'var foo = "foo"',
	'',
	'
foo
')
	.textIs('#output', 'bar')

test('variable declaration inside div').code(
	'
',
	'	var cat = "cat"',
	'
cat
',
	'
')
	.textIs('#output', 'cat')

test('changing object literals').code(
	'var foo = { a:1 }',
	'
',
	'	{ foo: { a:foo.a } }',
	'	{ a:foo.a }',
	'	foo',
	'
'
	)
	.textIs('#output', '{ foo:{ a:1 } }{ a:1 }{ a:1 }')
	.click('#output')
	.textIs('#output', '{ foo:{ a:2 } }{ a:2 }{ a:2 }')

test('null values').code(
	'var foo=null',
	'
"null:"foo " null:"null
'
	)
	.textIs('#output', 'null: null:')

// test('value changes type')
// 	.compile(
// 		'let foo = "bar"',
// 		'
foo
',
// 		'
foo.Type
',
// 		'<button id="button"></button onClick=handler() { foo.set(1) }>'
// 	)
// 	.textIs('#value', 'bar')
// 	.textIs('#Type', 'Text')
// 	.click('#button')
// 	.textIs('#value', 1)
// 	.textIs('#Type', 'Number')

// test('handler with logic')
// 	.code(
// 		'let cat = "hi1"',
// 		'let foo = handler() {',
// 		'	if (cat == "hi1") { cat.set("hi2") }',
// 		'	else { cat.set("hi3") }',
// 		'}',
// 		'<button id="button" onclick=foo/>',
// 		'
cat
'
// 	)
// 	.textIs('#output', 'hi1')
// 	.click('#button')
// 	.textIs('#output', 'hi2')
// 	.click('#button')
// 	.textIs('#output', 'hi3')

/* Util
 ******/
var isFirstTest = true
function test(name) {
	var actionHandlers = createActionHandlers()
	var testObj = {
		code: function() {
			var code = std.slice(arguments).join('\n'),
				actions = this._actions = []

			module.exports['compile\t"'+name+'"'] = function(assert) {
				currentTestCode = code

				try {
					var tokens = tokenizer.tokenize(currentTestCode),
						parsedAST = parser.parse(tokens),
						resolvedAST = resolver.resolve(parsedAST),
						result = compiler._printHTML(compiler.compile(resolvedAST))
				} catch(e) {
					console.log(e.stack)
					process.exit()
				}

				if (isFirstTest) { console.log('loading headless browser - hang tight!'); isFirstTest = false }
				zombie.visit('http://localhost:'+compilerServerPort, { debug:false }, function(err, browser) {
					if (err || browser.statusCode != 200) {
						throw new Error("Error: " + err + " " + browser.statusCode + " " + browser.errors + " " + browser.dump())
					}
					(function nextAction() {
						if (!actions.length) {
							assert.done()
							scheduleCompilerServerShutdown()
							return
						}
						var action = actions.shift()
						try {
							actionHandlers[action.name].apply(this, [assert, browser, nextAction].concat(action.args))
						} catch(e) {
							console.log('compiler threw -', e.stack, '\n\nThe test code that caused the error:\n', currentTestCode)
						}
					})()
				})
			}
			return this
		}
	}

	each(actionHandlers, function(handler, name) {
		testObj[name] = function chainableAction() {
			this._actions.push({ name:name, args:slice(arguments) })
			return this
		}
	})

	return testObj
}

function createActionHandlers() {
	return {
		// Events
		click: function(assert, browser, next, selector) {
			var target = browser.querySelector(selector)
			browser.fire('click', target, next)
		},
		moveMouse: function(assert, browser, next, clientX, clientY) {
			browser.fire('mousemove', browser.document, { attributes: {clientX:clientX, clientY:clientY} }, next)
		},
		// Asserts
		htmlIs: function(assert, browser, next, selector, expectedHTML) {
			assert.deepEqual(expectedHTML, browser.html(selector))
			next()
		},
		textIs: function(assert, browser, next, selector, expectedHTML) {
			assert.deepEqual(expectedHTML, browser.text(selector))
			next()
		},
		positionIs: function(assert, browser, next, selector, x, y) {
			var style = browser.querySelector(selector).style
			assert.deepEqual(style.left, x+'px')
			assert.deepEqual(style.top, y+'px')
			next()
		}
	}
}

function startCompilerServer() {
	compilerServer = http.createServer(function(res, res) {
		try {
			var tokens = tokenizer.tokenize(currentTestCode),
				parsedAST = parser.parse(tokens),
				resolvedAST = resolver.resolve(parsedAST),
				result = compiler._printHTML(compiler.compile(resolvedAST))
		} catch(e) {
			var error = e
		}

		if (error) {
			console.log("compiler server error", error.stack)
			res.writeHead(500)
			res.end(error.stack)
		} else {
			res.writeHead(200, { 'Content-Length':result.length })
			res.end(result)
		}
	})
	compilerServer.listen(compilerServerPort)
}

function scheduleCompilerServerShutdown() {
	clearTimeout(scheduleCompilerServerShutdown.timeout)
	scheduleCompilerServerShutdown.timeout = setTimeout(function() {
		console.log("Tests done, shutting down compiler server")
		compilerServer.close()
	}, 200)
}
<|endoftext|>


<commit_before>import { compileToFunctions } from 'vue-template-compiler';
import mount from '../../../src/mount';
import ClickComponent from '../../resources/components/event-components/ClickComponent.vue';
import SlotChild from '../../resources/components/slots/SlotChild.vue';

describe.only('mount', () => {
  it('returns new VueWrapper with mounted Vue instance if no options are passed', () => {
    if (navigator.userAgent.includes && navigator.userAgent.includes('node.js')) {
      return;
    }
    const compiled = compileToFunctions('
<input />
');
    const wrapper = mount(compiled);
    expect(wrapper.element.querySelector('input')).to.be.instanceOf(HTMLElement);
    expect(wrapper.vm).to.be.an('object');
  });

  it('returns new VueWrapper with mounted Vue instance with props, if passed as propsData', () => {
    if (navigator.userAgent.includes && navigator.userAgent.includes('node.js')) {
      return;
    }
    const childClickHandler = () => {};
    const wrapper = mount(ClickComponent, { propsData: { childClickHandler } });
    expect(wrapper.element.querySelector('button')).to.be.instanceOf(HTMLElement);
    expect(wrapper.vm).to.be.an('object');
    expect(wrapper.vm.$props.childClickHandler).to.equal(childClickHandler);
  });

  it('mounts component to DOM before returning VueWrapper when passed attachToDocument in options', () => {
    if (navigator.userAgent.includes && navigator.userAgent.includes('node.js')) {
      return;
    }
    const compiled = compileToFunctions('
<input />
');
    const wrapper = mount(compiled, { attachToDocument: true });
    expect(wrapper.element.querySelector('input')).to.be.instanceOf(HTMLElement);
    expect(wrapper.vm).to.be.an('object');
    expect(document.querySelectorAll('input').length).to.equal(1);
  });

  it.only('mounts component with default slot if passed component in slot object', () => {
    const wrapper = mount(SlotChild, { slots: { default: ClickComponent } });
    expect(wrapper.contains(ClickComponent)).to.equal(true);
  });

  it.only('mounts component with default slot if passed object with template prop in slot object', () => {
    const compiled = compileToFunctions('
');
    const wrapper = mount(SlotChild, { slots: { default: compiled } });
    expect(wrapper.contains('#div')).to.equal(true);
  });

  it.only('mounts component with named slot if passed component in slot object', () => {
    const wrapper = mount(SlotChild, { slots: { header: ClickComponent, footer: ClickComponent } });
    expect(wrapper.find(ClickComponent).length).to.equal(2);
  });

  it('returns VueWrapper with mountedToDom set to true when passed attachToDocument in options', () => {
    const compiled = compileToFunctions('
<input />
');
    const wrapper = mount(compiled, { attachToDocument: true });
    expect(wrapper.mountedToDom).to.equal(true);
  });
});
<commit_msg>[Tests] Remove .only from mount.spec<commit_after>import { compileToFunctions } from 'vue-template-compiler';
import mount from '../../../src/mount';
import ClickComponent from '../../resources/components/event-components/ClickComponent.vue';
import SlotChild from '../../resources/components/slots/SlotChild.vue';

describe.only('mount', () => {
  it('returns new VueWrapper with mounted Vue instance if no options are passed', () => {
    if (navigator.userAgent.includes && navigator.userAgent.includes('node.js')) {
      return;
    }
    const compiled = compileToFunctions('
<input />
');
    const wrapper = mount(compiled);
    expect(wrapper.element.querySelector('input')).to.be.instanceOf(HTMLElement);
    expect(wrapper.vm).to.be.an('object');
  });

  it('returns new VueWrapper with mounted Vue instance with props, if passed as propsData', () => {
    if (navigator.userAgent.includes && navigator.userAgent.includes('node.js')) {
      return;
    }
    const childClickHandler = () => {};
    const wrapper = mount(ClickComponent, { propsData: { childClickHandler } });
    expect(wrapper.element.querySelector('button')).to.be.instanceOf(HTMLElement);
    expect(wrapper.vm).to.be.an('object');
    expect(wrapper.vm.$props.childClickHandler).to.equal(childClickHandler);
  });

  it('mounts component to DOM before returning VueWrapper when passed attachToDocument in options', () => {
    if (navigator.userAgent.includes && navigator.userAgent.includes('node.js')) {
      return;
    }
    const compiled = compileToFunctions('
<input />
');
    const wrapper = mount(compiled, { attachToDocument: true });
    expect(wrapper.element.querySelector('input')).to.be.instanceOf(HTMLElement);
    expect(wrapper.vm).to.be.an('object');
    expect(document.querySelectorAll('input').length).to.equal(1);
  });

  it('mounts component with default slot if passed component in slot object', () => {
    const wrapper = mount(SlotChild, { slots: { default: ClickComponent } });
    expect(wrapper.contains(ClickComponent)).to.equal(true);
  });

  it('mounts component with default slot if passed object with template prop in slot object', () => {
    const compiled = compileToFunctions('
');
    const wrapper = mount(SlotChild, { slots: { default: compiled } });
    expect(wrapper.contains('#div')).to.equal(true);
  });

  it('mounts component with named slot if passed component in slot object', () => {
    const wrapper = mount(SlotChild, { slots: { header: ClickComponent, footer: ClickComponent } });
    expect(wrapper.find(ClickComponent).length).to.equal(2);
  });

  it('returns VueWrapper with mountedToDom set to true when passed attachToDocument in options', () => {
    const compiled = compileToFunctions('
<input />
');
    const wrapper = mount(compiled, { attachToDocument: true });
    expect(wrapper.mountedToDom).to.equal(true);
  });
});
<|endoftext|>


<commit_before>'use strict';

describe('time', function() {
	beforeEach(module('ADE'));

	var timeFilter;

	beforeEach(inject(function($filter) {
		timeFilter = $filter('time');
	}));

	it('should print a date', function() {
		expect(timeFilter(1355517820)).toBe('2:43 pm');
	});

	it('should print a empty string for non-dates', function() {
		expect(timeFilter(undefined)).toBe('');
		expect(timeFilter(null)).toBe('');
		expect(timeFilter(0)).toBe('');
		expect(timeFilter('')).toBe('');
	});
});
<commit_msg>Fix time spec<commit_after>'use strict';

describe('time', function() {
	beforeEach(module('ADE'));

	var timeFilter;

	beforeEach(inject(function($filter) {
		timeFilter = $filter('time');
	}));

	it('should print a date', function() {
		expect(timeFilter(1355517820)).toBe('12:43 pm');
	});

	it('should print a empty string for non-dates', function() {
		expect(timeFilter(undefined)).toBe('');
		expect(timeFilter(null)).toBe('');
		expect(timeFilter(0)).toBe('');
		expect(timeFilter('')).toBe('');
	});
});
<|endoftext|>


<commit_before>define(['backbone',
        'underscore',
        'models/chat-message',
        'models/chat-user',
        'collections/chat-messages',
        'views/chat-message',
        'views/chat-users',
		'connectors/stomp-connector',
        'utils/template',
        'utils/events'], function(Backbone, _, ChatMessage, ChatUser, ChatMessageList, ChatMessageView, ChatUsersView, StompConnector, template, events){

	var ChatRoomView = Backbone.View.extend({

		initialize: function(){
			this.collection = new ChatMessageList();
			this.collection.on('add', this.saveMessage, this);
			this.subscribe(this.model);

			this.usersView = new ChatUsersView({roomCode: this.model.get('code')});
		},

		events: {
			'keyup .txt-message': 'checkMessage',
			submit: 'sendMessage'
		},

		checkMessage: function(event){
			event.preventDefault();

			var message = this.$('.txt-message').val().trim();
			if (message) {
				this.ableButtonSendMessage();
				if (event.keyCode===13) {
					this.sendMessage(event);
					this.$('.txt-message').val('');
				}

			} else {
				this.disableButtonSendMessage();

			}

		},

		isButtonSendMessageEnabled: function(){
			return !this.$('.btn-send-message').attr('disabled');
		},

		ableButtonSendMessage: function(){
			this.$('.btn-send-message').removeAttr('disabled');
		},

		disableButtonSendMessage: function(){
			this.$('.btn-send-message').attr('disabled', 'disabled');
		},

		sendMessage: function(e){
			e.preventDefault();
			var roomCode = this.model.get('code');
			var $textMessage = this.$('.txt-message');
			var content = $textMessage.val();

			if ( content ) {
				var chatMessage = new ChatMessage({content:content, roomCode: roomCode});
				this.collection.add( chatMessage );
				$textMessage.val('');
				this.disableButtonSendMessage();
			}
		},

		saveMessage: function(chatMessage){
			chatMessage.save();
		},

		showMessage: function(chatMessage){
			var chatMessageView = new ChatMessageView({model:chatMessage});
			var $messages = this.$('.chat[data-code="'+this.model.get('code')+'"] .chat-content');
			$messages.append( chatMessageView.render().el );
			this.focusLastMessages();
		},

		focusLastMessages: function(){
			var txtMessage = this.$('.txt-message');
			txtMessage.attr('disabled', 'disabled');

			this.$(".chat-content").animate({
				scrollTop: this.$('.chat-content').height() + 500

			}, 1000, function(){
				txtMessage.removeAttr('disabled');
				txtMessage.focus();

			});
		},

		subscribe: function(room){
			var view = this;
			var roomCode = room.get('code');

			this.messagesSubscription = StompConnector.getConnection().subscribe('/topic/rooms-'+roomCode, function(request){
				var chatMessage = new ChatMessage(JSON.parse(request.body));
				view.showMessage(chatMessage);
				if(chatMessage.has('user')){
					view.usersView.addUser(new ChatUser(chatMessage.get('user')));
				}

			}, {roomCode: roomCode});
		},

		hide: function(){
			this.$el.hide();
		},

		show: function(){
			this.$el.show();
		},

		destroy: function(){
			if (this.messagesSubscription) this.messagesSubscription.unsubscribe(null, {code:this.model.get('code')});
			this.usersView.destroy();
			this.remove();
		},

		render: function(){
			var view = this;
			$.get('templates/_chat_room.html').success(function(html){
				var template = _.template(html);
				view.$el.html(template(view.model.attributes));

				view.$('.chat-users').html( view.usersView.render().el );
				view.usersView.refreshUsers();
			});
			return this;
		}

	});

	return ChatRoomView;

});<commit_msg>Fixing scroll to last message<commit_after>define(['backbone',
        'underscore',
        'models/chat-message',
        'models/chat-user',
        'collections/chat-messages',
        'views/chat-message',
        'views/chat-users',
		'connectors/stomp-connector',
        'utils/template',
        'utils/events'], function(Backbone, _, ChatMessage, ChatUser, ChatMessageList, ChatMessageView, ChatUsersView, StompConnector, template, events){

	var ChatRoomView = Backbone.View.extend({

		initialize: function(){
			this.collection = new ChatMessageList();
			this.collection.on('add', this.saveMessage, this);
			this.subscribe(this.model);

			this.usersView = new ChatUsersView({roomCode: this.model.get('code')});
		},

		events: {
			'keyup .txt-message': 'checkMessage',
			submit: 'sendMessage'
		},

		checkMessage: function(event){
			event.preventDefault();

			var message = this.$('.txt-message').val().trim();
			if (message) {
				this.ableButtonSendMessage();
				if (event.keyCode===13) {
					this.sendMessage(event);
					this.$('.txt-message').val('');
				}

			} else {
				this.disableButtonSendMessage();

			}

		},

		isButtonSendMessageEnabled: function(){
			return !this.$('.btn-send-message').attr('disabled');
		},

		ableButtonSendMessage: function(){
			this.$('.btn-send-message').removeAttr('disabled');
		},

		disableButtonSendMessage: function(){
			this.$('.btn-send-message').attr('disabled', 'disabled');
		},

		sendMessage: function(e){
			e.preventDefault();
			var roomCode = this.model.get('code');
			var $textMessage = this.$('.txt-message');
			var content = $textMessage.val();

			if ( content ) {
				var chatMessage = new ChatMessage({content:content, roomCode: roomCode});
				this.collection.add( chatMessage );
				$textMessage.val('');
				this.disableButtonSendMessage();
			}
		},

		saveMessage: function(chatMessage){
			chatMessage.save();
		},

		showMessage: function(chatMessage){
			var chatMessageView = new ChatMessageView({model:chatMessage});
			var $messages = this.$('.chat[data-code="'+this.model.get('code')+'"] .chat-content');
			$messages.append( chatMessageView.render().el );
			this.focusLastMessages();
		},

		focusLastMessages: function(){
			var txtMessage = this.$('.txt-message');
			txtMessage.attr('disabled', 'disabled');

			var chatContent = this.$(".chat-content");
			chatContent.animate({
				scrollTop: chatContent.height() * chatContent.height()

			}, 1000, function(){
				txtMessage.removeAttr('disabled');
				txtMessage.focus();

			});
		},

		subscribe: function(room){
			var view = this;
			var roomCode = room.get('code');

			this.messagesSubscription = StompConnector.getConnection().subscribe('/topic/rooms-'+roomCode, function(request){
				var chatMessage = new ChatMessage(JSON.parse(request.body));
				view.showMessage(chatMessage);
				if(chatMessage.has('user')){
					view.usersView.addUser(new ChatUser(chatMessage.get('user')));
				}

			}, {roomCode: roomCode});
		},

		hide: function(){
			this.$el.hide();
		},

		show: function(){
			this.$el.show();
		},

		destroy: function(){
			if (this.messagesSubscription) this.messagesSubscription.unsubscribe(null, {code:this.model.get('code')});
			this.usersView.destroy();
			this.remove();
		},

		render: function(){
			var view = this;
			$.get('templates/_chat_room.html').success(function(html){
				var template = _.template(html);
				view.$el.html(template(view.model.attributes));

				view.$('.chat-users').html( view.usersView.render().el );
				view.usersView.refreshUsers();
			});
			return this;
		}

	});

	return ChatRoomView;

});<|endoftext|>


<commit_before>process.env.NODE_ENV = 'test';

var chai = require('chai'),
    expect = chai.expect,
    net = require('net'),
    tls = require('tls'),
    fs = require('fs'),
    winston = require('winston'),
    timekeeper = require('timekeeper'),
    freezed_time = new Date(1330688329321);

chai.Assertion.includeStack = true;

require('../lib/winston-logstash');

describe('winston-logstash transport', function() {
  var test_server, port = 28777;

  function createTestServer(port, on_data) {
    var server = net.createServer(port, function (socket) {
      socket.on('end', function () { });
      socket.on('data', on_data);
    });
    server.listen(port, function() {});

    return server;
  }

  function createTestSecureServer(port, options, on_data) {
    var serverOptions = {
      key: (options.serverKey) ? fs.readFileSync(options.serverKey) : fs.readFileSync(__dirname + '/server.key'),
      cert: (options.serverCert) ? fs.readFileSync(options.serverCert) : fs.readFileSync(__dirname + '/server.cert'),
      handshakeTimeout: 2000,
      requestCert: options.verify ? options.verify : false,
      ca: options.verify ? [ fs.readFileSync(__dirname + '/client.pub') ] : []
    };
    var server = tls.createServer(serverOptions, function(socket) {
      socket.on('end', function () { });
      socket.on('data', on_data);
    });
    server.listen(port, function() {});

    return server
  }

  function createLogger(port, secure, caFilePath) {
    return new (winston.Logger)({
      transports: [
        new (winston.transports.Logstash)({
          port: port,
          node_name: 'test',
          localhost: 'localhost',
          pid: 12345 ,
          ssl_enable: secure ? true : false,
          ca: (secure && caFilePath) ? [__dirname + '/server.cert'] : undefined
        })
      ]
    });
  }

  describe('with logstash server', function () {
    var test_server, port = 28777;

    beforeEach(function(done) {
      timekeeper.freeze(freezed_time);
      done();
    });

    it('send logs over TCP as valid json', function(done) {
      var response;
      var logger = createLogger(port);
      var expected = {"stream":"sample","level":"info","message":"hello world"};

      test_server = createTestServer(port, function (data) {
        response = data.toString();
        expect(JSON.parse(response)).to.be.eql(expected);
        done();
      });

      logger.log('info', 'hello world', {stream: 'sample'});
    });

    it('send each log with a new line character', function(done) {
      var response;
      var logger = createLogger(port);

      test_server = createTestServer(port, function (data) {
        response = data.toString();
        expect(response).to.be.equal('{"stream":"sample","level":"info","message":"hello world"}\n');
        done();
      });

      logger.log('info', 'hello world', {stream: 'sample'});
    });

    // Teardown
    afterEach(function () {
      if (test_server) {
        test_server.close(function () {});
      }
      timekeeper.reset();
      test_server = null;
    });

  });

  describe('with secured logstash server', function() {
    var test_server, port = 28777;

    beforeEach(function(done) {
      timekeeper.freeze(freezed_time);
      done();
    });

    it('send logs over SSL secured TCP as valid json', function(done) {
      var response;
      var logger = createLogger(port, true, __dirname + '/server.cert');
      var expected = {"stream":"sample","level":"info","message":"hello world"};

      test_server = createTestSecureServer(port, {}, function (data) {
        response = data.toString();
        expect(JSON.parse(response)).to.be.eql(expected);
        done();
      });

      logger.log('info', 'hello world', {stream: 'sample'});
    });

    it('send logs over SSL secured TCP as valid json with SSL verification', function(done) {
      var response;
      var logger = createLogger(port, true, __dirname + '/server.cert');
      var expected = {"stream":"sample","level":"info","message":"hello world"};

      test_server = createTestSecureServer(port, { verify: true }, function (data) {
        response = data.toString();
        expect(JSON.parse(response)).to.be.eql(expected);
        done();
      });

      logger.log('info', 'hello world', {stream: 'sample'});
    });

    it('logstash transport receive an error when there is a connection error different from ECONNREFUSED', function(done) {
      var response,
          logger = createLogger(port, true, __dirname + '/server-fail.cert'),
          expected = {"stream":"sample","level":"info","message":"hello world"},
          silence = true;

      test_server = createTestSecureServer(port, {
        serverKey: __dirname + '/server-fail.key',
        serverCert: __dirname + '/server-fail.cert',
        verify: true
      }, function (data) {
        response = data.toString();
        expect(JSON.parse(response)).to.be.eql(expected);
        done();
      });

      logger.transports.logstash.on('error', function (err) {
        expect(err).to.be.an.instanceof(Error);
        if (silence) {
          done();
          silence = false;
        }
      });

      logger.log('info', 'hello world', {stream: 'sample'});
    });

    // Teardown
    afterEach(function () {
      if (test_server) {
        test_server.close(function () {});
      }
      timekeeper.reset();
      test_server = null;
      logger = null;
    });
  });

  describe('without logstash server', function () {
    var logger, interval;

    var checkSocketStatus = function (retries, logger, done) {
      interval = setInterval(function() {
        if (logger.transports.logstash.retries == retries) {
          clearInterval(interval);
          done();
        }
      }, 500);
    };

    it('fallback to silent mode if logstash server is down', function(done) {
      var response;
      var logger = createLogger(28747);

      checkSocketStatus (4, logger, function() {
        expect(logger.transports.logstash.silent).to.be.true;
        done();
      });

      logger.log('info', 'hello world', {stream: 'sample'});
    });

    it('emit an error message when it fallback to silent mode', function(done) {
      var logger = createLogger(28747),
          called = true;

      logger.transports.logstash.on('error', function (err) {
        if (/OFFLINE$/.test(err.message)) {
          expect(logger.transports.logstash.retries).to.be.equal(4);
          expect(logger.transports.logstash.silent).to.be.true;

          if (called) {
            done();
          };

          called = false;
        }
      });
      // Wait for timeout for logger before sending first message
      var interval = setInterval(function() {
        logger.log('info', 'hello world', {stream: 'sample'});
        clearInterval(interval);
      }, 400);

    });
  });
});

<commit_msg>Add spec for logging with different log level<commit_after>process.env.NODE_ENV = 'test';

var chai = require('chai'),
    expect = chai.expect,
    net = require('net'),
    tls = require('tls'),
    fs = require('fs'),
    winston = require('winston'),
    timekeeper = require('timekeeper'),
    freezed_time = new Date(1330688329321);

chai.Assertion.includeStack = true;

require('../lib/winston-logstash');

describe('winston-logstash transport', function() {
  var test_server, port = 28777;

  function createTestServer(port, on_data) {
    var server = net.createServer(port, function (socket) {
      socket.on('end', function () { });
      socket.on('data', on_data);
    });
    server.listen(port, function() {});

    return server;
  }

  function createTestSecureServer(port, options, on_data) {
    var serverOptions = {
      key: (options.serverKey) ? fs.readFileSync(options.serverKey) : fs.readFileSync(__dirname + '/server.key'),
      cert: (options.serverCert) ? fs.readFileSync(options.serverCert) : fs.readFileSync(__dirname + '/server.cert'),
      handshakeTimeout: 2000,
      requestCert: options.verify ? options.verify : false,
      ca: options.verify ? [ fs.readFileSync(__dirname + '/client.pub') ] : []
    };
    var server = tls.createServer(serverOptions, function(socket) {
      socket.on('end', function () { });
      socket.on('data', on_data);
    });
    server.listen(port, function() {});

    return server
  }

  function createLogger(port, secure, caFilePath) {
    return new (winston.Logger)({
      transports: [
        new (winston.transports.Logstash)({
          port: port,
          node_name: 'test',
          localhost: 'localhost',
          pid: 12345 ,
          ssl_enable: secure ? true : false,
          ca: (secure && caFilePath) ? [__dirname + '/server.cert'] : undefined
        })
      ]
    });
  }

  describe('with logstash server', function () {
    var test_server, port = 28777;

    beforeEach(function(done) {
      timekeeper.freeze(freezed_time);
      done();
    });

    it('send logs over TCP as valid json', function(done) {
      var response;
      var logger = createLogger(port);
      var expected = {"stream":"sample","level":"info","message":"hello world"};

      test_server = createTestServer(port, function (data) {
        response = data.toString();
        expect(JSON.parse(response)).to.be.eql(expected);
        done();
      });

      logger.log('info', 'hello world', {stream: 'sample'});
    });

    it('send each log with a new line character', function(done) {
      var response;
      var logger = createLogger(port);

      test_server = createTestServer(port, function (data) {
        response = data.toString();
        expect(response).to.be.equal('{"stream":"sample","level":"info","message":"hello world"}\n');
        done();
      });

      logger.log('info', 'hello world', {stream: 'sample'});
    });

    it('send with different log levels', function(done) {

      var response;
      var logger = createLogger(port);

      test_server = createTestServer(port, function (data) {
        response = data.toString();
        expect(response).to.be.equal('{"stream":"sample","level":"info","message":"hello world"}\n{"stream":"sample","level":"error","message":"hello world"}\n');
        done();
      });

      logger.log('info', 'hello world', {stream: 'sample'});
      logger.log('error', 'hello world', {stream: 'sample'});

    });

    // Teardown
    afterEach(function () {
      if (test_server) {
        test_server.close(function () {});
      }
      timekeeper.reset();
      test_server = null;
    });

  });

  describe('with secured logstash server', function() {
    var test_server, port = 28777;

    beforeEach(function(done) {
      timekeeper.freeze(freezed_time);
      done();
    });

    it('send logs over SSL secured TCP as valid json', function(done) {
      var response;
      var logger = createLogger(port, true, __dirname + '/server.cert');
      var expected = {"stream":"sample","level":"info","message":"hello world"};

      test_server = createTestSecureServer(port, {}, function (data) {
        response = data.toString();
        expect(JSON.parse(response)).to.be.eql(expected);
        done();
      });

      logger.log('info', 'hello world', {stream: 'sample'});
    });

    it('send logs over SSL secured TCP as valid json with SSL verification', function(done) {
      var response;
      var logger = createLogger(port, true, __dirname + '/server.cert');
      var expected = {"stream":"sample","level":"info","message":"hello world"};

      test_server = createTestSecureServer(port, { verify: true }, function (data) {
        response = data.toString();
        expect(JSON.parse(response)).to.be.eql(expected);
        done();
      });

      logger.log('info', 'hello world', {stream: 'sample'});
    });

    it('logstash transport receive an error when there is a connection error different from ECONNREFUSED', function(done) {
      var response,
          logger = createLogger(port, true, __dirname + '/server-fail.cert'),
          expected = {"stream":"sample","level":"info","message":"hello world"},
          silence = true;

      test_server = createTestSecureServer(port, {
        serverKey: __dirname + '/server-fail.key',
        serverCert: __dirname + '/server-fail.cert',
        verify: true
      }, function (data) {
        response = data.toString();
        expect(JSON.parse(response)).to.be.eql(expected);
        done();
      });

      logger.transports.logstash.on('error', function (err) {
        expect(err).to.be.an.instanceof(Error);
        if (silence) {
          done();
          silence = false;
        }
      });

      logger.log('info', 'hello world', {stream: 'sample'});
    });

    // Teardown
    afterEach(function () {
      if (test_server) {
        test_server.close(function () {});
      }
      timekeeper.reset();
      test_server = null;
      logger = null;
    });
  });

  describe('without logstash server', function () {
    var logger, interval;

    var checkSocketStatus = function (retries, logger, done) {
      interval = setInterval(function() {
        if (logger.transports.logstash.retries == retries) {
          clearInterval(interval);
          done();
        }
      }, 500);
    };

    it('fallback to silent mode if logstash server is down', function(done) {
      var response;
      var logger = createLogger(28747);

      checkSocketStatus (4, logger, function() {
        expect(logger.transports.logstash.silent).to.be.true;
        done();
      });

      logger.log('info', 'hello world', {stream: 'sample'});
    });

    it('emit an error message when it fallback to silent mode', function(done) {
      var logger = createLogger(28747),
          called = true;

      logger.transports.logstash.on('error', function (err) {
        if (/OFFLINE$/.test(err.message)) {
          expect(logger.transports.logstash.retries).to.be.equal(4);
          expect(logger.transports.logstash.silent).to.be.true;

          if (called) {
            done();
          };

          called = false;
        }
      });
      // Wait for timeout for logger before sending first message
      var interval = setInterval(function() {
        logger.log('info', 'hello world', {stream: 'sample'});
        clearInterval(interval);
      }, 400);

    });
  });
});

<|endoftext|>


<commit_before>/*
 * Store the incoming data (if it's not already found) in the specified object
 * using the specified key, then pass it along unchanged.
 *
 * This is a "do-nothing" data transform to allow caching of intermediate results
 * from within a Vega pipeline (a series of transforms). The intent is to
 * support a much faster pipeline for frequently modified visualizations, as
 * used in the Tree Illustrator project:
 *   https://github.com/OpenTreeOfLife/tree-illustrator
 *
 * Note that this transform doesn't concern itself with the details of the caching
 * mechanism; it's assumed to be an existing Javascript object (associative
 * array) that functions as a simple key/value store. Similarly, the host
 * application is responsible for defining idempotent keys for cached data.
 *
 * Also, note that this doesn't *retrieve* cached data or speed things up on
 * its own! Instead, by feeding a cache it enables the host application to
 * construct a simpler pipeline by providing cached data instead of URLs,
 * omitting unneeded transforms, etc.
 */
var vg  = require('vega'),
    log  = require('vega-logging'),
    dl = require('datalib'),
    Transform = require('vega/src/transforms/Transform');

function Stash(graph) {
  Transform.prototype.init.call(this, graph);
  Transform.addParameters(this, {
      cachePath: {type: 'value'},
      key: {type: 'value'},
      flush: {type: 'value', default: false}
  });

  return this;
  // TODO: add calls to mutates(), router()?
}

var prototype = (Stash.prototype = Object.create(Transform.prototype));
prototype.constructor = Stash;

prototype.transform = function(input) {
  log.debug(input, ['stashing']);
/*
  console.log("INCOMING data to stash transform:");
  console.log(input);

  console.log("  cachePath:");
  console.log(this.param('cachePath'));
  console.log(this.param('cachePath').field);

  console.log("  key:");
  console.log(this.param('key'));

  console.log("  flush:");
  console.log(this.param('flush'));
*/

  var g = this._graph,
      cachePath = this.param('cachePath'),
      cache = eval(cachePath),
      key = this.param('key'),
      flush = this.param('flush');

  if (!cache || (typeof cache !== 'object')) {
    // if an invalid cache path is submitted, treat this as a no-op
    console.warn('stash transform: no cache found in eval('+ cachePath +')! skipping this data');
    return input;
  }

  /* Stash the complete, current data. Note that we actually store a *copy* of
   * the data, since Vega always clones data in a spec (see comment above).
   */
  if (flush || !(key in cache)) {
    // be sure to cache the "raw" data as returned from source
    // NOTE that g.dataValues() is a hash with n ids!
    // for now, let's stash the whole thing
    cache[ key ] = dl.duplicate(g.dataValues());
    // N.B. dl.duplicate cleans up any weird methods and circular references
/*
    for (var valueName in g.dataValues()) {
      var valueData = g.dataValues()[valueName];
          cache[ key ] = dl.duplicate(valueData);
      //if ('_data' in valueData) {
      //    cache[ key ] = dl.duplicate(valueData._data);
      //} else {
      //}
    }
*/
  }

/* OR should we stash data piecemeal, based on state??
  // move new (and possibly changed) data to the cache
  function set(x) {
    //move one datum (tuple?) into the cache
    console.log("setting '"+ x +"'...");
    //Tuple.set(x, field, expr(x, null, signals));
  }
  input.add.forEach(set);
  if (this.reevaluate(input)) {
    input.mod.forEach(set);
  }
*/
  return input;
};

module.exports = Stash;

Stash.schema = {
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "Stash transform",
  "description": "Stores the incoming data (if it's not already found) in the" +
    " specified object using the specified key, then passes it along unchanged.",
  "type": "object",
  "properties": {
    "type": {"enum": ["stash"]},
    "cachePath": {
      "description": "A field pointing to the cache object",
      "oneOf": [{"type": "string"}, {"$ref": "#/refs/signal"}]  // TODO: signal?
    },
    "key": {
      "description": "A unique key for this data in the stash",
      "oneOf": [{"type": "string"}, {"$ref": "#/refs/signal"}]
    },
    "flush": {
      "description": "If true, will replace any existing stashed data.",
      "oneOf": [{"type": "boolean"}, {"$ref": "#/refs/signal"}],
      "default": false
    }
  },
  "additionalProperties": false,  // TODO: confirm this
  "required": ["type", "key", "cachePath"]
};
<commit_msg>Fix stash "transform" to support a single datum.<commit_after>/*
 * Store the incoming data (if it's not already found) in the specified object
 * using the specified key, then pass it along unchanged.
 *
 * This is a "do-nothing" data transform to allow caching of intermediate results
 * from within a Vega pipeline (a series of transforms). The intent is to
 * support a much faster pipeline for frequently modified visualizations, as
 * used in the Tree Illustrator project:
 *   https://github.com/OpenTreeOfLife/tree-illustrator
 *
 * Note that this transform doesn't concern itself with the details of the caching
 * mechanism; it's assumed to be an existing Javascript object (associative
 * array) that functions as a simple key/value store. Similarly, the host
 * application is responsible for defining idempotent keys for cached data.
 *
 * Also, note that this doesn't *retrieve* cached data or speed things up on
 * its own! Instead, by feeding a cache it enables the host application to
 * construct a simpler pipeline by providing cached data instead of URLs,
 * omitting unneeded transforms, etc.
 */
var vg  = require('vega'),
    log  = require('vega-logging'),
    assert = require('assert'),
    dl = require('datalib'),
    Transform = require('vega/src/transforms/Transform');

function Stash(graph) {
  Transform.prototype.init.call(this, graph);
  Transform.addParameters(this, {
      cachePath: {type: 'value'},
      key: {type: 'value'},
      flush: {type: 'value', default: false}
  });

  return this;
  // TODO: add calls to mutates(), router()?
}

var prototype = (Stash.prototype = Object.create(Transform.prototype));
prototype.constructor = Stash;

prototype.transform = function(input) {
  log.debug(input, ['stashing']);
/*
  console.log("INCOMING data to stash transform:");
  console.log(input);

  console.log("  cachePath:");
  console.log(this.param('cachePath'));
  console.log(this.param('cachePath').field);

  console.log("  key:");
  console.log(this.param('key'));

  console.log("  flush:");
  console.log(this.param('flush'));
*/

  var cachePath = this.param('cachePath'),
      cache = eval(cachePath),
      key = this.param('key'),
      flush = this.param('flush');

  if (!cache || (typeof cache !== 'object')) {
    // if an invalid cache path is submitted, treat this as a no-op
    console.warn('stash transform: no cache found in eval('+ cachePath +')! skipping this data');
    return input;
  }

  // For now, this transform ASSUMES just one incoming tuple, which will be
  // completely replaced by the plucked values.
  assert((input.add.length < 2 &&
          input.mod.length === 0 &&
          input.rem.length === 0),
         "The stash transform only stores a single added datum.");

  /* Stash a single incoming datum. Note that we actually store a *copy* of
   * the data, since Vega always clones data in a spec (see comment above).
   */
  if (flush || !(key in cache)) {
    // be sure to cache the "raw" data as returned from source
    cache[ key ] = dl.duplicate(input.add[0]);
    // N.B. dl.duplicate cleans up any weird methods and circular references
  }

/* OR should we stash all data piecemeal, based on state??
  // move new (and possibly changed) data to the cache
  function set(x) {
    //move one datum (tuple?) into the cache
    console.log("setting '"+ x +"'...");
    //Tuple.set(x, field, expr(x, null, signals));
  }
  input.add.forEach(set);
  if (this.reevaluate(input)) {
    input.mod.forEach(set);
  }
*/
  return input;
};

module.exports = Stash;

Stash.schema = {
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "Stash transform",
  "description": "Stores the incoming data (if it's not already found) in the" +
    " specified object using the specified key, then passes it along unchanged.",
  "type": "object",
  "properties": {
    "type": {"enum": ["stash"]},
    "cachePath": {
      "description": "A field pointing to the cache object",
      "oneOf": [{"type": "string"}, {"$ref": "#/refs/signal"}]  // TODO: signal?
    },
    "key": {
      "description": "A unique key for this data in the stash",
      "oneOf": [{"type": "string"}, {"$ref": "#/refs/signal"}]
    },
    "flush": {
      "description": "If true, will replace any existing stashed data.",
      "oneOf": [{"type": "boolean"}, {"$ref": "#/refs/signal"}],
      "default": false
    }
  },
  "additionalProperties": false,  // TODO: confirm this
  "required": ["type", "key", "cachePath"]
};
<|endoftext|>


<commit_before>function qmiEditor(collectionId, data) {

  var newSections = [], newFiles = [];
  var setActiveTab, getActiveTab;

  $(".edit-accordion").on('accordionactivate', function(event, ui) {
    setActiveTab = $(".edit-accordion").accordion("option", "active");
    if(setActiveTab !== false) {
      Florence.globalVars.activeTab = setActiveTab;
    }
  });

  getActiveTab = Florence.globalVars.activeTab;
  accordion(getActiveTab);
  getLastPosition ();

  $("#metadata-s").remove();
  $("#metadata-f").remove();
  $("#metadata-ad").remove();
  $("#summary-p").remove();
  $(".release-date").remove();
  $("#reference-p").remove();

  // Metadata edition and saving
  $("#title").on('input', function () {
    $(this).textareaAutoSize();
    data.description.title = $(this).val();
  });
  if (!data.description.contact) {
    data.description.contact = {};
  }
  $("#contactName").on('input', function () {
    $(this).textareaAutoSize();
    data.description.contact.name = $(this).val();
  });
  $("#contactEmail").on('input', function () {
    $(this).textareaAutoSize();
    data.description.contact.email = $(this).val();
  });
  $("#contactTelephone").on('input', function () {
    $(this).textareaAutoSize();
    data.description.contact.telephone = $(this).val();
  });
  $("#survey").on('input', function () {
    $(this).textareaAutoSize();
    data.description.surveyName = $(this).val();
  });
  $("#frequency").on('input', function () {
    $(this).textareaAutoSize();
    data.description.frequency = $(this).val();
  });
  $("#compilation").on('input', function () {
    $(this).textareaAutoSize();
    data.description.compilation = $(this).val();
  });
  $("#geoCoverage").on('input', function () {
    $(this).textareaAutoSize();
    data.description.geographicCoverage = $(this).val();
  });
  $("#sampleSize").on('input', function () {
    $(this).textareaAutoSize();
    data.description.sampleSize = $(this).val();
  });
  if (!data.description.lastRevised){
    $('#lastRevised').datepicker({dateFormat: 'dd MM yy'}).on('change', function () {
      data.description.lastRevised = new Date($(this).datepicker({dateFormat: 'dd MM yy'})[0].value).toISOString();
    });
  } else {
    dateTmp = data.description.lastRevised;
    var dateTmpFormatted = $.datepicker.formatDate('dd MM yy', new Date(dateTmp));
    $('#lastRevised').val(dateTmpFormatted).datepicker({dateFormat: 'dd MM yy'}).on('change', function () {
      data.description.lastRevised = new Date($('#lastRevised').datepicker('getDate')).toISOString();
    });
  }
  $("#keywordsTag").tagit({availableTags: data.description.keywords,
                        singleField: true,
                        allowSpaces: true,
                        singleFieldNode: $('#keywords')
  });
  $('#keywords').on('change', function () {
    data.description.keywords = $('#keywords').val().split(', ');
  });
  $("#metaDescription").on('input', function () {
    $(this).textareaAutoSize();
    data.description.metaDescription = $(this).val();
  });

  /* The checked attribute is a boolean attribute, which means the corresponding property is true if the attribute
   is present at all—even if, for example, the attribute has no value or is set to empty string value or even "false" */
  var checkBoxStatus = function () {
    if (data.description.nationalStatistic === "false" || data.description.nationalStatistic === false) {
      return false;
    }
    return true;
  };

  $("#metadata-list input[type='checkbox']").prop('checked', checkBoxStatus).click(function () {
    data.description.nationalStatistic = $("#metadata-list input[type='checkbox']").prop('checked') ? true : false;
  });

  // Save
  var editNav = $('.edit-nav');
  editNav.off(); // remove any existing event handlers.

  editNav.on('click', '.btn-edit-save', function () {
    save();
    updateContent(collectionId, data.uri, JSON.stringify(data));
  });

  // completed to review
  editNav.on('click', '.btn-edit-save-and-submit-for-review', function () {
    //pageData = $('.fl-editor__headline').val();
    save();
    saveAndCompleteContent(collectionId, data.uri, JSON.stringify(data));
  });

  // reviewed to approve
  editNav.on('click', '.btn-edit-save-and-submit-for-approval', function () {
    save();
    saveAndReviewContent(collectionId, data.uri, JSON.stringify(data));
  });

  function save() {
   // Sections
      var orderSection = $("#sortable-content").sortable('toArray');
      $(orderSection).each(function (indexS, nameS) {
        var markdown = $('#content-markdown_' + nameS).val();
      newSections[indexS] = markdown;
      });
      data.markdown = newSections;
    // Files are uploaded. Save metadata
    var orderFile = $("#sortable-file").sortable('toArray');
    $(orderFile).each(function(indexF, nameF){
      var title = $('#file-title_'+nameF).val();
      var file = data.downloads[parseInt(nameF)].file;
      newFiles[indexF] = {title: title, file: file};
    });
    data.downloads = newFiles;
  }
}
<commit_msg>Allow only numbers in sample size<commit_after>function qmiEditor(collectionId, data) {

  var newSections = [], newFiles = [];
  var setActiveTab, getActiveTab;

  $(".edit-accordion").on('accordionactivate', function(event, ui) {
    setActiveTab = $(".edit-accordion").accordion("option", "active");
    if(setActiveTab !== false) {
      Florence.globalVars.activeTab = setActiveTab;
    }
  });

  getActiveTab = Florence.globalVars.activeTab;
  accordion(getActiveTab);
  getLastPosition ();

  $("#metadata-s").remove();
  $("#metadata-f").remove();
  $("#metadata-ad").remove();
  $("#summary-p").remove();
  $(".release-date").remove();
  $("#reference-p").remove();

  // Metadata edition and saving
  $("#title").on('input', function () {
    $(this).textareaAutoSize();
    data.description.title = $(this).val();
  });
  if (!data.description.contact) {
    data.description.contact = {};
  }
  $("#contactName").on('input', function () {
    $(this).textareaAutoSize();
    data.description.contact.name = $(this).val();
  });
  $("#contactEmail").on('input', function () {
    $(this).textareaAutoSize();
    data.description.contact.email = $(this).val();
  });
  $("#contactTelephone").on('input', function () {
    $(this).textareaAutoSize();
    data.description.contact.telephone = $(this).val();
  });
  $("#survey").on('input', function () {
    $(this).textareaAutoSize();
    data.description.surveyName = $(this).val();
  });
  $("#frequency").on('input', function () {
    $(this).textareaAutoSize();
    data.description.frequency = $(this).val();
  });
  $("#compilation").on('input', function () {
    $(this).textareaAutoSize();
    data.description.compilation = $(this).val();
  });
  $("#geoCoverage").on('input', function () {
    $(this).textareaAutoSize();
    data.description.geographicCoverage = $(this).val();
  });
  $("#sampleSize").on('input', function () {
    $(this).textareaAutoSize();
    if (isNumber.match(/^\d+$/)) {
      data.description.sampleSize = isNumber;
    } else {
      alert('This needs to be a number');
    }
  });
  if (!data.description.lastRevised){
    $('#lastRevised').datepicker({dateFormat: 'dd MM yy'}).on('change', function () {
      data.description.lastRevised = new Date($(this).datepicker({dateFormat: 'dd MM yy'})[0].value).toISOString();
    });
  } else {
    dateTmp = data.description.lastRevised;
    var dateTmpFormatted = $.datepicker.formatDate('dd MM yy', new Date(dateTmp));
    $('#lastRevised').val(dateTmpFormatted).datepicker({dateFormat: 'dd MM yy'}).on('change', function () {
      data.description.lastRevised = new Date($('#lastRevised').datepicker('getDate')).toISOString();
    });
  }
  $("#keywordsTag").tagit({availableTags: data.description.keywords,
                        singleField: true,
                        allowSpaces: true,
                        singleFieldNode: $('#keywords')
  });
  $('#keywords').on('change', function () {
    data.description.keywords = $('#keywords').val().split(', ');
  });
  $("#metaDescription").on('input', function () {
    $(this).textareaAutoSize();
    data.description.metaDescription = $(this).val();
  });

  /* The checked attribute is a boolean attribute, which means the corresponding property is true if the attribute
   is present at all—even if, for example, the attribute has no value or is set to empty string value or even "false" */
  var checkBoxStatus = function () {
    if (data.description.nationalStatistic === "false" || data.description.nationalStatistic === false) {
      return false;
    }
    return true;
  };

  $("#metadata-list input[type='checkbox']").prop('checked', checkBoxStatus).click(function () {
    data.description.nationalStatistic = $("#metadata-list input[type='checkbox']").prop('checked') ? true : false;
  });

  // Save
  var editNav = $('.edit-nav');
  editNav.off(); // remove any existing event handlers.

  editNav.on('click', '.btn-edit-save', function () {
    save();
    updateContent(collectionId, data.uri, JSON.stringify(data));
  });

  // completed to review
  editNav.on('click', '.btn-edit-save-and-submit-for-review', function () {
    //pageData = $('.fl-editor__headline').val();
    save();
    saveAndCompleteContent(collectionId, data.uri, JSON.stringify(data));
  });

  // reviewed to approve
  editNav.on('click', '.btn-edit-save-and-submit-for-approval', function () {
    save();
    saveAndReviewContent(collectionId, data.uri, JSON.stringify(data));
  });

  function save() {
   // Sections
      var orderSection = $("#sortable-content").sortable('toArray');
      $(orderSection).each(function (indexS, nameS) {
        var markdown = $('#content-markdown_' + nameS).val();
      newSections[indexS] = markdown;
      });
      data.markdown = newSections;
    // Files are uploaded. Save metadata
    var orderFile = $("#sortable-file").sortable('toArray');
    $(orderFile).each(function(indexF, nameF){
      var title = $('#file-title_'+nameF).val();
      var file = data.downloads[parseInt(nameF)].file;
      newFiles[indexF] = {title: title, file: file};
    });
    data.downloads = newFiles;
  }
}
<|endoftext|>


<commit_before>function qmiEditor(collectionId, data) {

  var newSections = [], newFiles = [];
  var setActiveTab, getActiveTab;

  $(".edit-accordion").on('accordionactivate', function(event, ui) {
    setActiveTab = $(".edit-accordion").accordion("option", "active");
    if(setActiveTab !== false) {
      Florence.globalVars.activeTab = setActiveTab;
    }
  });

  getActiveTab = Florence.globalVars.activeTab;
  accordion(getActiveTab);
  getLastPosition ();

  $("#metadata-s").remove();
  $("#metadata-f").remove();
  $("#metadata-ad").remove();
  $("#summary-p").remove();
  $(".release-date").remove();
  $("#reference-p").remove();

  // Metadata edition and saving
  $("#title").on('input', function () {
    $(this).textareaAutoSize();
    data.description.title = $(this).val();
  });
  if (!data.description.contact) {
    data.description.contact = {};
  }
  $("#contactName").on('input', function () {
    $(this).textareaAutoSize();
    data.description.contact.name = $(this).val();
  });
  $("#contactEmail").on('input', function () {
    $(this).textareaAutoSize();
    data.description.contact.email = $(this).val();
  });
  $("#contactTelephone").on('input', function () {
    $(this).textareaAutoSize();
    data.description.contact.telephone = $(this).val();
  });
  $("#survey").on('input', function () {
    $(this).textareaAutoSize();
    data.description.surveyName = $(this).val();
  });
  $("#frequency").on('input', function () {
    $(this).textareaAutoSize();
    data.description.frequency = $(this).val();
  });
  $("#compilation").on('input', function () {
    $(this).textareaAutoSize();
    data.description.compilation = $(this).val();
  });
  $("#geoCoverage").on('input', function () {
    $(this).textareaAutoSize();
    data.description.geographicCoverage = $(this).val();
  });
  $("#sampleSize").on('input', function () {
    $(this).textareaAutoSize();
    data.description.sampleSize = isNumber;
  });
  if (!data.description.lastRevised){
    $('#lastRevised').datepicker({dateFormat: 'dd MM yy'}).on('change', function () {
      data.description.lastRevised = new Date($(this).datepicker({dateFormat: 'dd MM yy'})[0].value).toISOString();
    });
  } else {
    dateTmp = data.description.lastRevised;
    var dateTmpFormatted = $.datepicker.formatDate('dd MM yy', new Date(dateTmp));
    $('#lastRevised').val(dateTmpFormatted).datepicker({dateFormat: 'dd MM yy'}).on('change', function () {
      data.description.lastRevised = new Date($('#lastRevised').datepicker('getDate')).toISOString();
    });
  }
  $("#keywordsTag").tagit({availableTags: data.description.keywords,
                        singleField: true,
                        allowSpaces: true,
                        singleFieldNode: $('#keywords')
  });
  $('#keywords').on('change', function () {
    data.description.keywords = $('#keywords').val().split(', ');
  });
  $("#metaDescription").on('input', function () {
    $(this).textareaAutoSize();
    data.description.metaDescription = $(this).val();
  });

  /* The checked attribute is a boolean attribute, which means the corresponding property is true if the attribute
   is present at all—even if, for example, the attribute has no value or is set to empty string value or even "false" */
  var checkBoxStatus = function () {
    if (data.description.nationalStatistic === "false" || data.description.nationalStatistic === false) {
      return false;
    }
    return true;
  };

  $("#metadata-list input[type='checkbox']").prop('checked', checkBoxStatus).click(function () {
    data.description.nationalStatistic = $("#metadata-list input[type='checkbox']").prop('checked') ? true : false;
  });

  // Save
  var editNav = $('.edit-nav');
  editNav.off(); // remove any existing event handlers.

  editNav.on('click', '.btn-edit-save', function () {
    save();
    updateContent(collectionId, data.uri, JSON.stringify(data));
  });

  // completed to review
  editNav.on('click', '.btn-edit-save-and-submit-for-review', function () {
    //pageData = $('.fl-editor__headline').val();
    save();
    saveAndCompleteContent(collectionId, data.uri, JSON.stringify(data));
  });

  // reviewed to approve
  editNav.on('click', '.btn-edit-save-and-submit-for-approval', function () {
    save();
    saveAndReviewContent(collectionId, data.uri, JSON.stringify(data));
  });

  function save() {
   // Sections
      var orderSection = $("#sortable-content").sortable('toArray');
      $(orderSection).each(function (indexS, nameS) {
        var markdown = $('#content-markdown_' + nameS).val();
      newSections[indexS] = markdown;
      });
      data.markdown = newSections;
    // Files are uploaded. Save metadata
    var orderFile = $("#sortable-file").sortable('toArray');
    $(orderFile).each(function(indexF, nameF){
      var title = $('#file-title_'+nameF).val();
      var file = data.downloads[parseInt(nameF)].file;
      newFiles[indexF] = {title: title, file: file};
    });
    data.downloads = newFiles;
  }
}
<commit_msg>Change var name<commit_after>function qmiEditor(collectionId, data) {

  var newSections = [], newFiles = [];
  var setActiveTab, getActiveTab;

  $(".edit-accordion").on('accordionactivate', function(event, ui) {
    setActiveTab = $(".edit-accordion").accordion("option", "active");
    if(setActiveTab !== false) {
      Florence.globalVars.activeTab = setActiveTab;
    }
  });

  getActiveTab = Florence.globalVars.activeTab;
  accordion(getActiveTab);
  getLastPosition ();

  $("#metadata-s").remove();
  $("#metadata-f").remove();
  $("#metadata-ad").remove();
  $("#summary-p").remove();
  $(".release-date").remove();
  $("#reference-p").remove();

  // Metadata edition and saving
  $("#title").on('input', function () {
    $(this).textareaAutoSize();
    data.description.title = $(this).val();
  });
  if (!data.description.contact) {
    data.description.contact = {};
  }
  $("#contactName").on('input', function () {
    $(this).textareaAutoSize();
    data.description.contact.name = $(this).val();
  });
  $("#contactEmail").on('input', function () {
    $(this).textareaAutoSize();
    data.description.contact.email = $(this).val();
  });
  $("#contactTelephone").on('input', function () {
    $(this).textareaAutoSize();
    data.description.contact.telephone = $(this).val();
  });
  $("#survey").on('input', function () {
    $(this).textareaAutoSize();
    data.description.surveyName = $(this).val();
  });
  $("#frequency").on('input', function () {
    $(this).textareaAutoSize();
    data.description.frequency = $(this).val();
  });
  $("#compilation").on('input', function () {
    $(this).textareaAutoSize();
    data.description.compilation = $(this).val();
  });
  $("#geoCoverage").on('input', function () {
    $(this).textareaAutoSize();
    data.description.geographicCoverage = $(this).val();
  });
  $("#sampleSize").on('input', function () {
    $(this).textareaAutoSize();
    data.description.sampleSize = $(this).val();
  });
  if (!data.description.lastRevised){
    $('#lastRevised').datepicker({dateFormat: 'dd MM yy'}).on('change', function () {
      data.description.lastRevised = new Date($(this).datepicker({dateFormat: 'dd MM yy'})[0].value).toISOString();
    });
  } else {
    dateTmp = data.description.lastRevised;
    var dateTmpFormatted = $.datepicker.formatDate('dd MM yy', new Date(dateTmp));
    $('#lastRevised').val(dateTmpFormatted).datepicker({dateFormat: 'dd MM yy'}).on('change', function () {
      data.description.lastRevised = new Date($('#lastRevised').datepicker('getDate')).toISOString();
    });
  }
  $("#keywordsTag").tagit({availableTags: data.description.keywords,
                        singleField: true,
                        allowSpaces: true,
                        singleFieldNode: $('#keywords')
  });
  $('#keywords').on('change', function () {
    data.description.keywords = $('#keywords').val().split(', ');
  });
  $("#metaDescription").on('input', function () {
    $(this).textareaAutoSize();
    data.description.metaDescription = $(this).val();
  });

  /* The checked attribute is a boolean attribute, which means the corresponding property is true if the attribute
   is present at all—even if, for example, the attribute has no value or is set to empty string value or even "false" */
  var checkBoxStatus = function () {
    if (data.description.nationalStatistic === "false" || data.description.nationalStatistic === false) {
      return false;
    }
    return true;
  };

  $("#metadata-list input[type='checkbox']").prop('checked', checkBoxStatus).click(function () {
    data.description.nationalStatistic = $("#metadata-list input[type='checkbox']").prop('checked') ? true : false;
  });

  // Save
  var editNav = $('.edit-nav');
  editNav.off(); // remove any existing event handlers.

  editNav.on('click', '.btn-edit-save', function () {
    save();
    updateContent(collectionId, data.uri, JSON.stringify(data));
  });

  // completed to review
  editNav.on('click', '.btn-edit-save-and-submit-for-review', function () {
    //pageData = $('.fl-editor__headline').val();
    save();
    saveAndCompleteContent(collectionId, data.uri, JSON.stringify(data));
  });

  // reviewed to approve
  editNav.on('click', '.btn-edit-save-and-submit-for-approval', function () {
    save();
    saveAndReviewContent(collectionId, data.uri, JSON.stringify(data));
  });

  function save() {
   // Sections
      var orderSection = $("#sortable-content").sortable('toArray');
      $(orderSection).each(function (indexS, nameS) {
        var markdown = $('#content-markdown_' + nameS).val();
      newSections[indexS] = markdown;
      });
      data.markdown = newSections;
    // Files are uploaded. Save metadata
    var orderFile = $("#sortable-file").sortable('toArray');
    $(orderFile).each(function(indexF, nameF){
      var title = $('#file-title_'+nameF).val();
      var file = data.downloads[parseInt(nameF)].file;
      newFiles[indexF] = {title: title, file: file};
    });
    data.downloads = newFiles;
  }
}
<|endoftext|>