<commit_before>/*jslint node: true*/
/*global setImmediate: false*/
'use strict';
// Initialize the cache.
var cache = {};
// Initialize the compiler function.
var compiler = require('./../compiler');
// Initialize the fs module.
var fs = require('fs');
// Initialize the production mode status.
var isProduction = process.env.NODE_ENV === 'production';
// Initialize the path module.
var path = require('path');
// Initialize the runtime module.
var runtime = require('./../runtime');

/**
 * Render from a file.
 *
 * @param input The input.
 * @param root The root.
 * @param fragments (Optional) Each fragment.
 * @param callback (Optional) The callback.
 * @param skipLayout (Optional) Indicates if the layout is skipped.
 * @returns The rendered template.
 */
module.exports = function (input, root, fragments, callback, skipLayout) {
	// Initialize the options.
	var options = module.exports.options,
		// Initialize the template.
		template = module.exports.compileFromFile(input),
		// Initialize the output.
		output;
	// Check if the fragments is a function.
	if (typeof fragments === 'function') {
		// Set the callback.
		callback = fragments;
		// Set the fragments.
		fragments = {};
	}
	// Check if the callback is a boolean.
	if (typeof callback === 'boolean') {
		// Set the layout skip state.
		skipLayout = callback;
		// Set the callback.
		callback = null;
	}
	// Set the output ...
	output = !options.layout || skipLayout ?
			// ... use the template or ...
			template(module.exports, root, fragments || {}) :
			// ... use the layout with the template as fragment ...
			module.exports(options.layout, root, {
				// ... with the current template as fragment ...
				content: function (runtime, root) {
					// ... with the current fragments.
					return template(runtime, root, fragments || {});
				}
			}, true);
	// Return the scheduled callback, or the output.
	return callback ? setImmediate(callback, null, output) : output;
};

/**
 * Each alterant.
 */
module.exports.alterant = runtime.alterant;

/**
 * Compile a template from a file.
 *
 * @param input The input.
 * @returns The compiled template.
 */
module.exports.compileFromFile = function (input) {
	// Initialize the absolute path.
	var absolutePath,
		// Initialize the contents.
		contents,
		// Initialize the options.
		options = module.exports.options,
		// Initialize the template.
		template;
	// Check if the template has been cached.
	if (options.enableCache && typeof cache[input] !== 'undefined') {
		// Return the template.
		return cache[input];
	} else {
		// Resolve an input.
		absolutePath = (function () {
			// Initialize the current root.
			var currentRoot = path.dirname(require.main.filename),
				// Initialize the directories.
				directories = module.exports.options.directories,
				// Initialize the directory path.
				directoryPath,
				// Initialize the extensions.
				extensions = module.exports.options.extensions,
				// Initialize the file with extension.
				fileWithExtension,
				// Initialize the file path.
				filePath,
				// Initialize the iterator.
				i,
				// Initialize the iterator.
				j;
			// Iterate through each directory.
			for (i = 0; i < directories.length; i += 1) {
				// Initialize the absolute path.
				directoryPath = path.join(currentRoot, directories[i]);
				// Iterate through each extension.
				for (j = 0; j < extensions.length; j += 1) {
					// Initialize the file name with extension.
					fileWithExtension = input + '.' + extensions[j];
					// Initialize the file path.
					filePath = path.join(directoryPath, fileWithExtension);
					// Check if the file exists.
					if (fs.existsSync(filePath)) {
						// Return the file path.
						return filePath;
					}
				}
			}
			// Return the input, or null.
			return fs.existsSync(input) ? input : null;
		}());
		// Check if the absolute path is valid.
		if (absolutePath) {
			// Read the file contents.
			contents = fs.readFileSync(absolutePath, 'utf8');
			// Compile the template.
			template = compiler(contents, options.enableCompression);
			// Check if the template should be cached.
			if (options.enableCache) {
				// Add the template to the cache.
				cache[input] = template;
			}
			// Return the template.
			return template;
		}
		// Return the placeholder.
		return function () {
			// Return a message.
			return '(UNRESOLVED-TEMPLATE(' + input + '))';
		};
	}
};

/**
 * Compile a template from a string.
 *
 * @param input The input.
 * @returns The compiled template.
 */
module.exports.compileFromString = function (input) {
	// Initialize the options.
	var options = module.exports.options;
	// Initialize the template.
	return compiler(input, options.enableCompression);
};

/**
 * Each option.
 */
module.exports.options = {
	// The template directories.
	directories: ['views', '.'],
	// Indicates if templates are cached.
	enableCache: isProduction,
	// Indicates if templates render compressed output.
	enableCompression: isProduction,
	// The template file extensions.
	extensions: ['gaikan', 'html'],
	// The layout file.
	layout: null
};

/**
 * Each set.
 */
module.exports.set = runtime.set;<commit_msg>Support providing custom root directory<commit_after>/*jslint node: true*/
/*global setImmediate: false*/
'use strict';
// Initialize the cache.
var cache = {};
// Initialize the compiler function.
var compiler = require('./../compiler');
// Initialize the fs module.
var fs = require('fs');
// Initialize the production mode status.
var isProduction = process.env.NODE_ENV === 'production';
// Initialize the path module.
var path = require('path');
// Initialize the runtime module.
var runtime = require('./../runtime');

/**
 * Render from a file.
 *
 * @param input The input.
 * @param root The root.
 * @param fragments (Optional) Each fragment.
 * @param callback (Optional) The callback.
 * @param skipLayout (Optional) Indicates if the layout is skipped.
 * @returns The rendered template.
 */
module.exports = function (input, root, fragments, callback, skipLayout) {
	// Initialize the options.
	var options = module.exports.options,
		// Initialize the template.
		template = module.exports.compileFromFile(input),
		// Initialize the output.
		output;
	// Check if the fragments is a function.
	if (typeof fragments === 'function') {
		// Set the callback.
		callback = fragments;
		// Set the fragments.
		fragments = {};
	}
	// Check if the callback is a boolean.
	if (typeof callback === 'boolean') {
		// Set the layout skip state.
		skipLayout = callback;
		// Set the callback.
		callback = null;
	}
	// Set the output ...
	output = !options.layout || skipLayout ?
			// ... use the template or ...
			template(module.exports, root, fragments || {}) :
			// ... use the layout with the template as fragment ...
			module.exports(options.layout, root, {
				// ... with the current template as fragment ...
				content: function (runtime, root) {
					// ... with the current fragments.
					return template(runtime, root, fragments || {});
				}
			}, true);
	// Return the scheduled callback, or the output.
	return callback ? setImmediate(callback, null, output) : output;
};

/**
 * Each alterant.
 */
module.exports.alterant = runtime.alterant;

/**
 * Compile a template from a file.
 *
 * @param input The input.
 * @returns The compiled template.
 */
module.exports.compileFromFile = function (input) {
	// Initialize the absolute path.
	var absolutePath,
		// Initialize the contents.
		contents,
		// Initialize the options.
		options = module.exports.options,
		// Initialize the template.
		template;
	// Check if the template has been cached.
	if (options.enableCache && typeof cache[input] !== 'undefined') {
		// Return the template.
		return cache[input];
	} else {
		// Resolve an input.
		absolutePath = (function () {
			// Initialize the current root.
			var currentRoot = module.exports.options.rootDir,
				// Initialize the directories.
				directories = module.exports.options.directories,
				// Initialize the directory path.
				directoryPath,
				// Initialize the extensions.
				extensions = module.exports.options.extensions,
				// Initialize the file with extension.
				fileWithExtension,
				// Initialize the file path.
				filePath,
				// Initialize the iterator.
				i,
				// Initialize the iterator.
				j;
			// Iterate through each directory.
			for (i = 0; i < directories.length; i += 1) {
				// Initialize the absolute path.
				directoryPath = path.join(currentRoot, directories[i]);
				// Iterate through each extension.
				for (j = 0; j < extensions.length; j += 1) {
					// Initialize the file name with extension.
					fileWithExtension = input + '.' + extensions[j];
					// Initialize the file path.
					filePath = path.join(directoryPath, fileWithExtension);
					// Check if the file exists.
					if (fs.existsSync(filePath)) {
						// Return the file path.
						return filePath;
					}
				}
			}
			// Return the input, or null.
			return fs.existsSync(input) ? input : null;
		}());
		// Check if the absolute path is valid.
		if (absolutePath) {
			// Read the file contents.
			contents = fs.readFileSync(absolutePath, 'utf8');
			// Compile the template.
			template = compiler(contents, options.enableCompression);
			// Check if the template should be cached.
			if (options.enableCache) {
				// Add the template to the cache.
				cache[input] = template;
			}
			// Return the template.
			return template;
		}
		// Return the placeholder.
		return function () {
			// Return a message.
			return '(UNRESOLVED-TEMPLATE(' + input + '))';
		};
	}
};

/**
 * Compile a template from a string.
 *
 * @param input The input.
 * @returns The compiled template.
 */
module.exports.compileFromString = function (input) {
	// Initialize the options.
	var options = module.exports.options;
	// Initialize the template.
	return compiler(input, options.enableCompression);
};

/**
 * Each option.
 */
module.exports.options = {
	//Root directory where to look for views directory
	rootDir: path.dirname(require.main.filename),
	// The template directories.
	directories: ['views', '.'],
	// Indicates if templates are cached.
	enableCache: isProduction,
	// Indicates if templates render compressed output.
	enableCompression: isProduction,
	// The template file extensions.
	extensions: ['gaikan', 'html'],
	// The layout file.
	layout: null
};

/**
 * Each set.
 */
module.exports.set = runtime.set;
<|endoftext|>


<commit_before>var socket = io();

angular.module('stacy', ['ui.router', 'uiGmapgoogle-maps'])

.config(function(uiGmapGoogleMapApiProvider) {
  uiGmapGoogleMapApiProvider.configure({
    //    key: 'your api key',
    v: '3.20', //defaults to latest 3.X anyhow
    libraries: 'weather,geometry,visualization'
  });
})

.config(function($stateProvider, $urlRouterProvider) {

  $stateProvider.state('home', {
    url: '/',
    templateUrl: 'templates/home.html',
    controller: 'HomeCtrl'
  }).state('chat', {
    url: '/chat',
    templateUrl: 'templates/chat.html',
    controller: 'ChatCtrl'
  });

  $urlRouterProvider.otherwise('/');

})

.controller('HomeCtrl', function($scope, $location) {

  $scope.go = function() {
    if (!$scope.destination) return;
    $location.path('/chat').search('place=' + $scope.destination);
  };

})

.controller('ChatCtrl', function($scope, $location) {

  $scope.messages = [];
  $scope.rewards=await capitalOne.getRewards();
  $scope.sendMsg = function() {
    if (!$scope.chatMsg) return;
    sendMsg($scope.chatMsg);
    $scope.chatMsg = '';
  };

  socket.on('msg', function(msg){
    if (!Array.isArray(msg.msg)) {
      msg.msg = [msg.msg];
    }
    msg.msg.forEach(function(m) {
      addMsg('to', m);
      processMsg(msg);
    });
    $scope.$apply();
  });

  function processMsg(msg) {
    // todo process msg
    console.log(msg);
    if (msg.session && msg.session.geocode) {
      var geocode = msg.session.geocode;
      $scope.map.center = {
        latitude: geocode.lat,
        longitude: geocode.lng
      };
    }

    if (msg.fare) {
      $scope.flight = {
        in: {
          from: msg.fare.in.origin.airport,
          to: msg.fare.in.destination.airport,
          num: msg.fare.in.flight_number,
          dep: dfmt(msg.fare.in.departs_at),
          arr: dfmt(msg.fare.in.arrives_at),
          cost: msg.fare.in.cost
        },
        out: {
          from: msg.fare.out.origin.airport,
          to: msg.fare.out.destination.airport,
          num: msg.fare.out.flight_number,
          dep: dfmt(msg.fare.out.departs_at),
          arr: dfmt(msg.fare.out.arrives_at),
          cost: msg.fare.out.cost
        }
      };
    }

    if (msg.hotel) {
      $scope.hotel = {
        name: msg.hotel.name,
        price: msg.hotel.price
      };
    }

    updateTotal();
  }

  function sendMsg(msg) {
    addMsg('from', msg);
    socket.emit('msg', msg);
  }

  function addMsg(who, msg) {
    $scope.messages.push({
      who: who,
      msg: msg
    });
    onUpdateMsg();
  }

  function onUpdateMsg() {
    var el = $('#chatMessages')[0];
    setTimeout(() => {
      el.scrollTop = el.scrollHeight;
    }, 0);
  }

  var place = $location.search().place;
  sendMsg('Plan my trip to ' + place + '.');

  $scope.map = {
    center: {
      latitude: 45,
      longitude: -73
    },
    zoom: 13
  };

  var updateTotal = function() {
    var sum = 0.00;
    if ($scope.flight) {
      sum += parseFloat($scope.flight.in.cost.substring(1))
        + parseFloat($scope.flight.out.cost.substring(1));
    }
    if ($scope.hotel) {
      sum += parseFloat($scope.hotel.price.substring(1));
    }
    $scope.total = '$' + sum.toFixed(2);
  };

  updateTotal();
});

function dfmt(d) {
  return moment(d).format('MM-DD HH:mm a')
}
<commit_msg>rm sshit<commit_after>var socket = io();

angular.module('stacy', ['ui.router', 'uiGmapgoogle-maps'])

.config(function(uiGmapGoogleMapApiProvider) {
  uiGmapGoogleMapApiProvider.configure({
    //    key: 'your api key',
    v: '3.20', //defaults to latest 3.X anyhow
    libraries: 'weather,geometry,visualization'
  });
})

.config(function($stateProvider, $urlRouterProvider) {

  $stateProvider.state('home', {
    url: '/',
    templateUrl: 'templates/home.html',
    controller: 'HomeCtrl'
  }).state('chat', {
    url: '/chat',
    templateUrl: 'templates/chat.html',
    controller: 'ChatCtrl'
  });

  $urlRouterProvider.otherwise('/');

})

.controller('HomeCtrl', function($scope, $location) {

  $scope.go = function() {
    if (!$scope.destination) return;
    $location.path('/chat').search('place=' + $scope.destination);
  };

})

.controller('ChatCtrl', function($scope, $location) {

  $scope.messages = [];
  $scope.sendMsg = function() {
    if (!$scope.chatMsg) return;
    sendMsg($scope.chatMsg);
    $scope.chatMsg = '';
  };

  socket.on('msg', function(msg){
    if (!Array.isArray(msg.msg)) {
      msg.msg = [msg.msg];
    }
    msg.msg.forEach(function(m) {
      addMsg('to', m);
      processMsg(msg);
    });
    $scope.$apply();
  });

  function processMsg(msg) {
    // todo process msg
    console.log(msg);
    if (msg.session && msg.session.geocode) {
      var geocode = msg.session.geocode;
      $scope.map.center = {
        latitude: geocode.lat,
        longitude: geocode.lng
      };
    }

    if (msg.fare) {
      $scope.flight = {
        in: {
          from: msg.fare.in.origin.airport,
          to: msg.fare.in.destination.airport,
          num: msg.fare.in.flight_number,
          dep: dfmt(msg.fare.in.departs_at),
          arr: dfmt(msg.fare.in.arrives_at),
          cost: msg.fare.in.cost
        },
        out: {
          from: msg.fare.out.origin.airport,
          to: msg.fare.out.destination.airport,
          num: msg.fare.out.flight_number,
          dep: dfmt(msg.fare.out.departs_at),
          arr: dfmt(msg.fare.out.arrives_at),
          cost: msg.fare.out.cost
        }
      };
    }

    if (msg.hotel) {
      $scope.hotel = {
        name: msg.hotel.name,
        price: msg.hotel.price
      };
    }

    updateTotal();
  }

  function sendMsg(msg) {
    addMsg('from', msg);
    socket.emit('msg', msg);
  }

  function addMsg(who, msg) {
    $scope.messages.push({
      who: who,
      msg: msg
    });
    onUpdateMsg();
  }

  function onUpdateMsg() {
    var el = $('#chatMessages')[0];
    setTimeout(() => {
      el.scrollTop = el.scrollHeight;
    }, 0);
  }

  var place = $location.search().place;
  sendMsg('Plan my trip to ' + place + '.');

  $scope.map = {
    center: {
      latitude: 45,
      longitude: -73
    },
    zoom: 13
  };

  var updateTotal = function() {
    var sum = 0.00;
    if ($scope.flight) {
      sum += parseFloat($scope.flight.in.cost.substring(1))
        + parseFloat($scope.flight.out.cost.substring(1));
    }
    if ($scope.hotel) {
      sum += parseFloat($scope.hotel.price.substring(1));
    }
    $scope.total = '$' + sum.toFixed(2);
  };

  updateTotal();
});

function dfmt(d) {
  return moment(d).format('MM-DD HH:mm a')
}
<|endoftext|>


<commit_before>if (process.fiberLib) {
	module.exports = process.fiberLib;
} else {
	var fs = require('fs'), path = require('path'), detectLibc = require('detect-libc');

	// Seed random numbers [gh-82]
	Math.random();

	// Look for binary for this platform
	var modPath = path.join(__dirname, 'bin', process.platform+ '-'+ process.arch+ '-'+ process.versions.modules+
		((process.platform === 'linux') ? '-'+ detectLibc.family : ''), 'fibers');
	try {
		// Pull in fibers implementation
		process.fiberLib = module.exports = require(modPath).Fiber;
	} catch (ex) {
		// No binary!
		console.error(
			'## There is an issue with `node-fibers` ##\n'+
			'`'+ modPath+ '.node` is missing.\n\n'+
			'Try running this to fix the issue: '+ process.execPath+ ' '+ __dirname.replace(' ', '\\ ')+ '/build'
		);
		console.error(ex.stack || ex.message || ex);
		throw new Error('Missing binary. See message above.');
	}

	setupAsyncHacks(module.exports);
}

function setupAsyncHacks(Fiber) {
	// Older (or newer?) versions of node may not support this API
	try {
		var aw = process.binding('async_wrap');
		var getAsyncIdStackSize;

		if (aw.asyncIdStackSize instanceof Function) {
			getAsyncIdStackSize = aw.asyncIdStackSize;
		} else if (aw.constants.kStackLength !== undefined) {
			getAsyncIdStackSize = function(kStackLength) {
				return function() {
					return aw.async_hook_fields[kStackLength];
				};
			}(aw.constants.kStackLength);
		} else {
			throw new Error('Couldn\'t figure out how to get async stack size');
		}

		var popAsyncContext = aw.popAsyncContext || aw.popAsyncIds;
		var pushAsyncContext = aw.pushAsyncContext || aw.pushAsyncIds;
		if (!popAsyncContext || !pushAsyncContext) {
			throw new Error('Push/pop do not exist');
		}

		var kExecutionAsyncId;
		if (aw.constants.kExecutionAsyncId === undefined) {
			kExecutionAsyncId = aw.constants.kCurrentAsyncId;
		} else {
			kExecutionAsyncId = aw.constants.kExecutionAsyncId;
		}
		var kTriggerAsyncId;
		if (aw.constants.kTriggerAsyncId === undefined) {
			kTriggerAsyncId = aw.constants.kCurrentTriggerId;
		} else {
			kTriggerAsyncId = aw.constants.kTriggerAsyncId;
		}

		var asyncIds = aw.async_id_fields || aw.async_uid_fields;

		function getAndClearStack() {
			var ii = getAsyncIdStackSize();
			var stack = new Array(ii);
			for (; ii > 0; --ii) {
				var asyncId = asyncIds[kExecutionAsyncId];
				stack[ii - 1] = {
					asyncId: asyncId,
					triggerId: asyncIds[kTriggerAsyncId],
				};
				popAsyncContext(asyncId);
			}
			return stack;
		}

		function restoreStack(stack) {
			for (var ii = 0; ii < stack.length; ++ii) {
				pushAsyncContext(stack[ii].asyncId, stack[ii].triggerId);
			}
		}

		function logUsingFibers(fibersMethod) {
			const logUseFibersLevel = +(process.env.ENABLE_LOG_USE_FIBERS || 0);

			if (!logUseFibersLevel) return;

			if (logUseFibersLevel === 1) {
				console.warn(`[FIBERS_LOG] Using ${fibersMethod}.`);
				return;
			}

			const { LOG_USE_FIBERS_INCLUDE_IN_PATH } = process.env;
			const stackFromError = new Error("[FIBERS_LOG]").stack;

			if (
				!LOG_USE_FIBERS_INCLUDE_IN_PATH ||
				stackFromError.includes(LOG_USE_FIBERS_INCLUDE_IN_PATH)
			) {
				console.warn(stackFromError);
			}
		}

		function wrapFunction(fn, fibersMethod) {
			return function () {
				logUsingFibers(fibersMethod);
				var stack = getAndClearStack();
				try {
					return fn.apply(this, arguments);
				} finally {
					restoreStack(stack);
				}
			};
		}

		// Monkey patch methods which may long jump
		Fiber.yield = wrapFunction(Fiber.yield, "Fiber.yield");
		Fiber.prototype.run = wrapFunction(Fiber.prototype.run, "Fiber.run");
		Fiber.prototype.throwInto = wrapFunction(
			Fiber.prototype.throwInto,
			"Fiber.throwInto"
		);

	} catch (err) {
		return;
	}
}
<commit_msg>Enable log stack when includes string it<commit_after>if (process.fiberLib) {
	module.exports = process.fiberLib;
} else {
	var fs = require('fs'), path = require('path'), detectLibc = require('detect-libc');

	// Seed random numbers [gh-82]
	Math.random();

	// Look for binary for this platform
	var modPath = path.join(__dirname, 'bin', process.platform+ '-'+ process.arch+ '-'+ process.versions.modules+
		((process.platform === 'linux') ? '-'+ detectLibc.family : ''), 'fibers');
	try {
		// Pull in fibers implementation
		process.fiberLib = module.exports = require(modPath).Fiber;
	} catch (ex) {
		// No binary!
		console.error(
			'## There is an issue with `node-fibers` ##\n'+
			'`'+ modPath+ '.node` is missing.\n\n'+
			'Try running this to fix the issue: '+ process.execPath+ ' '+ __dirname.replace(' ', '\\ ')+ '/build'
		);
		console.error(ex.stack || ex.message || ex);
		throw new Error('Missing binary. See message above.');
	}

	setupAsyncHacks(module.exports);
}

function setupAsyncHacks(Fiber) {
	// Older (or newer?) versions of node may not support this API
	try {
		var aw = process.binding('async_wrap');
		var getAsyncIdStackSize;

		if (aw.asyncIdStackSize instanceof Function) {
			getAsyncIdStackSize = aw.asyncIdStackSize;
		} else if (aw.constants.kStackLength !== undefined) {
			getAsyncIdStackSize = function(kStackLength) {
				return function() {
					return aw.async_hook_fields[kStackLength];
				};
			}(aw.constants.kStackLength);
		} else {
			throw new Error('Couldn\'t figure out how to get async stack size');
		}

		var popAsyncContext = aw.popAsyncContext || aw.popAsyncIds;
		var pushAsyncContext = aw.pushAsyncContext || aw.pushAsyncIds;
		if (!popAsyncContext || !pushAsyncContext) {
			throw new Error('Push/pop do not exist');
		}

		var kExecutionAsyncId;
		if (aw.constants.kExecutionAsyncId === undefined) {
			kExecutionAsyncId = aw.constants.kCurrentAsyncId;
		} else {
			kExecutionAsyncId = aw.constants.kExecutionAsyncId;
		}
		var kTriggerAsyncId;
		if (aw.constants.kTriggerAsyncId === undefined) {
			kTriggerAsyncId = aw.constants.kCurrentTriggerId;
		} else {
			kTriggerAsyncId = aw.constants.kTriggerAsyncId;
		}

		var asyncIds = aw.async_id_fields || aw.async_uid_fields;

		function getAndClearStack() {
			var ii = getAsyncIdStackSize();
			var stack = new Array(ii);
			for (; ii > 0; --ii) {
				var asyncId = asyncIds[kExecutionAsyncId];
				stack[ii - 1] = {
					asyncId: asyncId,
					triggerId: asyncIds[kTriggerAsyncId],
				};
				popAsyncContext(asyncId);
			}
			return stack;
		}

		function restoreStack(stack) {
			for (var ii = 0; ii < stack.length; ++ii) {
				pushAsyncContext(stack[ii].asyncId, stack[ii].triggerId);
			}
		}

		function logUsingFibers(fibersMethod) {
			const logUseFibersLevel = +(process.env.ENABLE_LOG_USE_FIBERS || 0);

			if (!logUseFibersLevel) return;

			if (logUseFibersLevel === 1) {
				console.warn(`[FIBERS_LOG] Using ${fibersMethod}.`);
				return;
			}

			const { LOG_USE_FIBERS_INCLUDE_IN_PATH } = process.env;
			const stackFromError = new Error(`[FIBERS_LOG] Using ${fibersMethod}.`).stack;

			if (
				!LOG_USE_FIBERS_INCLUDE_IN_PATH ||
				stackFromError.includes(LOG_USE_FIBERS_INCLUDE_IN_PATH)
			) {
				console.warn(stackFromError);
			}
		}

		function wrapFunction(fn, fibersMethod) {
			return function () {
				logUsingFibers(fibersMethod);
				var stack = getAndClearStack();
				try {
					return fn.apply(this, arguments);
				} finally {
					restoreStack(stack);
				}
			};
		}

		// Monkey patch methods which may long jump
		Fiber.yield = wrapFunction(Fiber.yield, "Fiber.yield");
		Fiber.prototype.run = wrapFunction(Fiber.prototype.run, "Fiber.run");
		Fiber.prototype.throwInto = wrapFunction(
			Fiber.prototype.throwInto,
			"Fiber.throwInto"
		);

	} catch (err) {
		return;
	}
}
<|endoftext|>


<commit_before>module.exports = function (userId, message, attachment, callback) {
  return this.execute('messages.send', {
    [ typeof userId === 'number' ? 'user_id' : 'user_ids' ]: typeof userId === 'number' ? userId : userId.join(','),
    message: message,
    attachment: attachment
  }, this.settings.token, callback)
}
<commit_msg>refactor reply<commit_after>module.exports = function (userId, message, attachment, callback) {
  const { token: access_token } = this.settings

  return this.execute('messages.send', {
    user_ids: typeof userId === 'number' ? userId : userId.join(','),
    message,
    attachment,
    access_token
  }, callback)
}
<|endoftext|>


<commit_before>import http from 'http'
import validate from './middleware/validate'
import asynchronous from './middleware/asynchronous'

const methods = [...http.METHODS, 'ALL']

export default (router, route) => {
  if (!route.method) {
    throw new Error('Route: `method` not provided')
  }

  if (!methods.includes(route.method)) {
    throw new Error('Route: Invalid `method` provided')
  }

  if (!route.url) {
    throw new Error('Route: `url` not provided')
  }

  if (!route.handler) {
    throw new Error('Route: `handler` not provided')
  }

  route.handler = !Array.isArray(route.handler)
    ? [route.handler]
    : route.handler

  if (route.validate) {
    route.handler.splice(-1, 0, validate(route.validate))
  }

  route.handler = route.handler.map(asynchronous)

  router[route.method.toLowerCase()](route.url, ...route.handler)
}
<commit_msg>Added aliases for route options<commit_after>import http from 'http'
import validate from './middleware/validate'
import asynchronous from './middleware/asynchronous'

const methods = [...http.METHODS, 'ALL']

export default (router, route) => {
  if (!route.method) {
    throw new Error('Route: `method` not provided')
  }

  if (!methods.includes(route.method)) {
    throw new Error('Route: Invalid `method` provided')
  }

  if (!route.url && !route.path) {
    throw new Error('Route: `url` or `path` not provided')
  }

  if (!route.handler) {
    throw new Error('Route: `handler` not provided')
  }

  route.handler = !Array.isArray(route.handler)
    ? [route.handler]
    : route.handler

  if (route.validate || route.validation) {
    route.handler.splice(-1, 0, validate(route.validate || route.validation))
  }

  route.handler = route.handler.map(asynchronous)

  router[route.method.toLowerCase()](route.url || route.path, ...route.handler)
}
<|endoftext|>


<commit_before>// nodeunit

if(typeof $object=='undefined') $object = require('../src/clone.js');

this['clone.js'] = {

    clone: function(test){
        var clone = $object.clone({a:1});
            test.ok( clone.hasOwnProperty('a') );
            test.equal( Object.getPrototypeOf(clone), $object);
            test.strictEqual( Object.getOwnPropertyNames(clone).length, 1);

        clone = $object.clone({a:1}, {});
            test.ok( clone.hasOwnProperty('a') );
            test.equal( Object.getPrototypeOf(clone), $object);
            test.strictEqual( Object.getOwnPropertyNames(clone).length, 1);

        clone = $object.clone();
            test.strictEqual( Object.getOwnPropertyNames(clone).length, 0);
            test.equal( Object.getPrototypeOf(clone), $object);

        test.done();
    },

    'clone.call': function(test){
        var $proto = {a: 1};

            var clone = $object.clone.call($proto);
                test.equal( Object.getPrototypeOf(clone), $proto,
                    'check prototype');

            clone = $object.clone.call($proto, {b:2});
                test.ok( clone.hasOwnProperty('b') );

            clone = $object.clone.call($proto, {b:2}, {});
                test.ok( clone.hasOwnProperty('b') );

        test.done();
    },

    'clone.constructor': function(test){
        var constructor = $object.clone({constructor: ''}).constructor;
        var c = $object.clone({constructor: ''});
            test.ok(constructor !== c.constructor);
            test.ok(constructor !== $object.clone().constructor);
            test.equal(typeof constructor, 'function');

        test.done();
    },

    create: function(test){
        var customConstructorCalled = false;
        var $myType = $object.clone({
            constructor: function(){
                customConstructorCalled = true;
            }
        });
        var instance = $myType.create({ignored: true});
            test.ok(customConstructorCalled);
            test.ok(typeof instance.ignored == 'undefined');
            test.ok(!Object.isSealed(instance));//default constructor does not called

        instance = $object.create();
            test.ok( Object.isSealed(instance), 'the created object should be sealed by default');

        test.done();
    },

    describe: function(test){

        //test.expect(2);

        test.deepEqual(
            $object.describe({
                         _p: undefined,
      '(const) _unwritable': 231,
                     method: Function,
                constructor: Function
            }),{
                         _p: {value: undefined, enumerable:false},
                _unwritable: {value: 231, enumerable:false, writable: false},
                     method: {value: Function, enumerable:false},
                constructor: {value: Function, enumerable:false}
            },
            'private properties, functions, constructor should be not enumerable'
        );

        //todo

        test.done();
    },

    'can, cant': function(test){

        var $myObj = $object.clone({
            fly: function(){},
            swim: function(a,b,c){}
        });
        var myObj = $myObj.create();
            test.ok(!!   myObj.can('swim').as($myObj) );
            test.ok(!! $object.can.call(myObj, 'fly').like($myObj) );

            test.ok(!    myObj.cant('swim').as($myObj) );
            test.ok(!  $object.cant.call(myObj, 'fly').like($myObj) );

        test.done();
    },

    copy: function(test){
        var myArray = $object.copy(Array);
        myArray[0] = 11;
        myArray[1] = 22;
            test.deepEqual(myArray, [11 ,22]);

            myArray.defineProperties({test: 'T'});
                test.strictEqual(myArray.test, 'T');

        var $collection = $object.clone({items: []});
        var $users = $collection.clone({name: ''});

            // $users full prototype chain:
            //$users -> $collection -> $object -> Object.prototype -> null

            // see prototype chains produced by copy:

            var userCopy = $users.copy();
            //~$users -> $object
                test.equal(Object.getPrototypeOf(userCopy), $object);
                test.ok(userCopy.hasOwnProperty('name'));
                test.ok(userCopy.items === undefined);

            userCopy = $users.copy(Array);
            //~$users -> Array.prototype
                test.equal(Object.getPrototypeOf(userCopy), Array.prototype);
                test.ok(userCopy.hasOwnProperty('name'));
                test.ok(userCopy.items === undefined);
                test.ok(userCopy.clone === undefined);

            userCopy = $users.copy(Array, Infinity);
            //~$users -> ~$collection -> ~$object -> Array.prototype
                test.ok(userCopy.hasOwnProperty('name'));
                test.ok(userCopy.getPrototype().hasOwnProperty('items'));
                test.ok(userCopy.getPrototype().getPrototype().hasOwnProperty('clone'));
                test.ok(userCopy.getPrototype().getPrototype().getPrototype() === Array.prototype);

            userCopy = $users.copy(Array, Infinity, true);
            //~($users + $collection + $object) -> Array.prototype
                test.equal(Object.getPrototypeOf(userCopy), Array.prototype);
                test.ok(userCopy.hasOwnProperty('name'));
                test.ok(userCopy.hasOwnProperty('items'));
                test.ok(userCopy.hasOwnProperty('clone'));

        //TODO: add tests for deepCopy/deepClone

        test.done();
    },

    deepCopy: function(test){
        var obj = $object.clone({l1: {l2: {l3: null}}});
        var deepCopy = obj.deepCopy();
        test.strictEqual(deepCopy.l1.l2.l3, null);

            obj.l1.l2.l3 = 11;
                test.strictEqual(deepCopy.l1.l2.l3, null);

            deepCopy.l1.l2.l3 = 22;
                test.strictEqual(obj.l1.l2.l3, 11);

        test.done();
    },

    deepClone: function(test){
        var obj = $object.clone({l1: {l2: {l3: null}}});
        var deepClone = obj.deepClone();
            test.strictEqual(deepClone.l1.l2.l3, null);

            obj.l1.l2.l3 = 11;
                test.strictEqual(deepClone.l1.l2.l3, 11);

            deepClone.l1.l2.l3 = 22;
                test.strictEqual(obj.l1.l2.l3, 11);

        test.done();
    },

    'callSuper, applySuper': function(test){
        var calls = [];
        var $parent = $object.clone({
            constructor: function(arg){
                calls.push('collection');
                this.callSuper('constructor', arg);
            }
        });
        var $child = $parent.clone({
            constructor: function(arg){
                calls.push('users');
                this.callSuper('constructor', arg);
            }
        });

        var child = $child.create({setBy$objectConstructor: 11});
            test.deepEqual(calls, ['users','collection']);
            test.equal(child.setBy$objectConstructor, 11, '$object.constructor called');

        test.done();
    },

    createSuperSafeCallback: function(test){

        test.expect(2);

        var $parent = $object.clone({
            constructor: function(){},
            asyncMethod: function(){
                var args = arguments;
                var callback = function(){
                    this.applySuper(args);
                    test.equal(this.__super__, $object);
                }
                setTimeout( this.createSuperSafeCallback(callback, this) );
            }
        });
        var $child = $parent.clone({
            constructor: function(){
                this.applySuper('asyncMethod', [{a:11}]);
                test.equal(this.__super__, $parent);
            }
        });

        var child = $child.create();

        setTimeout(function(){
//            console.log(child.a);
//            test.equal(11, child.a);
            test.done();
        });
    },

    apply: function(test){
        //methodName, args, withObj, asObj
        var asObj = {defineProperties: function(){
            this.called = true;
            return this;
        }};
        var obj = $object.apply(Array(22,33), 'defineProperties',[{a:11}], asObj);
            test.equal(obj.a, undefined);
            test.ok(obj.called);
            test.equal(obj[0], 22);
            test.equal(Object.getPrototypeOf(obj), Array.prototype);

        //methodName, args, withObj
        obj = $object.apply(Array(22,33), 'defineProperties',[{a:11}]);
            test.equal(obj.a,  11);
            test.equal(obj[0], 22);
            test.equal(Object.getPrototypeOf(obj), Array.prototype);

        //methodName, withObj
        obj = $object.apply(Array(22,33), 'defineProperties');
            test.equal(obj[0], 22);
            test.equal(Object.getPrototypeOf(obj), Array.prototype);

        test.done();
    }

};
<commit_msg>add concat() test<commit_after>// nodeunit

if(typeof $object=='undefined') $object = require('../src/clone.js');

this['clone.js'] = {

    clone: function(test){
        var clone = $object.clone({a:1});
            test.ok( clone.hasOwnProperty('a') );
            test.equal( Object.getPrototypeOf(clone), $object);
            test.strictEqual( Object.getOwnPropertyNames(clone).length, 1);

        clone = $object.clone({a:1}, {});
            test.ok( clone.hasOwnProperty('a') );
            test.equal( Object.getPrototypeOf(clone), $object);
            test.strictEqual( Object.getOwnPropertyNames(clone).length, 1);

        clone = $object.clone();
            test.strictEqual( Object.getOwnPropertyNames(clone).length, 0);
            test.equal( Object.getPrototypeOf(clone), $object);

        test.done();
    },

    'clone.call': function(test){
        var $proto = {a: 1};

            var clone = $object.clone.call($proto);
                test.equal( Object.getPrototypeOf(clone), $proto,
                    'check prototype');

            clone = $object.clone.call($proto, {b:2});
                test.ok( clone.hasOwnProperty('b') );

            clone = $object.clone.call($proto, {b:2}, {});
                test.ok( clone.hasOwnProperty('b') );

        test.done();
    },

    'clone.constructor': function(test){
        var constructor = $object.clone({constructor: ''}).constructor;
        var c = $object.clone({constructor: ''});
            test.ok(constructor !== c.constructor);
            test.ok(constructor !== $object.clone().constructor);
            test.equal(typeof constructor, 'function');

        test.done();
    },

    create: function(test){
        var customConstructorCalled = false;
        var $myType = $object.clone({
            constructor: function(){
                customConstructorCalled = true;
            }
        });
        var instance = $myType.create({ignored: true});
            test.ok(customConstructorCalled);
            test.ok(typeof instance.ignored == 'undefined');
            test.ok(!Object.isSealed(instance));//default constructor does not called

        instance = $object.create();
            test.ok( Object.isSealed(instance), 'the created object should be sealed by default');

        test.done();
    },

    describe: function(test){

        //test.expect(2);

        test.deepEqual(
            $object.describe({
                         _p: undefined,
      '(const) _unwritable': 231,
                     method: Function,
                constructor: Function
            }),{
                         _p: {value: undefined, enumerable:false},
                _unwritable: {value: 231, enumerable:false, writable: false},
                     method: {value: Function, enumerable:false},
                constructor: {value: Function, enumerable:false}
            },
            'private properties, functions, constructor should be not enumerable'
        );

        //todo

        test.done();
    },

    'can, cant': function(test){

        var $myObj = $object.clone({
            fly: function(){},
            swim: function(a,b,c){}
        });
        var myObj = $myObj.create();
            test.ok(!!   myObj.can('swim').as($myObj) );
            test.ok(!! $object.can.call(myObj, 'fly').like($myObj) );

            test.ok(!    myObj.cant('swim').as($myObj) );
            test.ok(!  $object.cant.call(myObj, 'fly').like($myObj) );

        test.done();
    },

    copy: function(test){
        var myArray = $object.copy(Array);
        myArray[0] = 11;
        myArray[1] = 22;
            test.deepEqual(myArray, [11 ,22]);

            myArray.defineProperties({test: 'T'});
                test.strictEqual(myArray.test, 'T');

        var $collection = $object.clone({items: []});
        var $users = $collection.clone({name: ''});

            // $users full prototype chain:
            //$users -> $collection -> $object -> Object.prototype -> null

            // see prototype chains produced by copy:

            var userCopy = $users.copy();
            //~$users -> $object
                test.equal(Object.getPrototypeOf(userCopy), $object);
                test.ok(userCopy.hasOwnProperty('name'));
                test.ok(userCopy.items === undefined);

            userCopy = $users.copy(Array);
            //~$users -> Array.prototype
                test.equal(Object.getPrototypeOf(userCopy), Array.prototype);
                test.ok(userCopy.hasOwnProperty('name'));
                test.ok(userCopy.items === undefined);
                test.ok(userCopy.clone === undefined);

            userCopy = $users.copy(Array, Infinity);
            //~$users -> ~$collection -> ~$object -> Array.prototype
                test.ok(userCopy.hasOwnProperty('name'));
                test.ok(userCopy.getPrototype().hasOwnProperty('items'));
                test.ok(userCopy.getPrototype().getPrototype().hasOwnProperty('clone'));
                test.ok(userCopy.getPrototype().getPrototype().getPrototype() === Array.prototype);

            userCopy = $users.copy(Array, Infinity, true);
            //~($users + $collection + $object) -> Array.prototype
                test.equal(Object.getPrototypeOf(userCopy), Array.prototype);
                test.ok(userCopy.hasOwnProperty('name'));
                test.ok(userCopy.hasOwnProperty('items'));
                test.ok(userCopy.hasOwnProperty('clone'));

        //TODO: add tests for deepCopy/deepClone

        test.done();
    },

    deepCopy: function(test){
        var obj = $object.clone({l1: {l2: {l3: null}}});
        var deepCopy = obj.deepCopy();
        test.strictEqual(deepCopy.l1.l2.l3, null);

            obj.l1.l2.l3 = 11;
                test.strictEqual(deepCopy.l1.l2.l3, null);

            deepCopy.l1.l2.l3 = 22;
                test.strictEqual(obj.l1.l2.l3, 11);

        test.done();
    },

    deepClone: function(test){
        var obj = $object.clone({l1: {l2: {l3: null}}});
        var deepClone = obj.deepClone();
            test.strictEqual(deepClone.l1.l2.l3, null);

            obj.l1.l2.l3 = 11;
                test.strictEqual(deepClone.l1.l2.l3, 11);

            deepClone.l1.l2.l3 = 22;
                test.strictEqual(obj.l1.l2.l3, 11);

        test.done();
    },

    'callSuper, applySuper': function(test){
        var calls = [];
        var $parent = $object.clone({
            constructor: function(arg){
                calls.push('collection');
                this.callSuper('constructor', arg);
            }
        });
        var $child = $parent.clone({
            constructor: function(arg){
                calls.push('users');
                this.callSuper('constructor', arg);
            }
        });

        var child = $child.create({setBy$objectConstructor: 11});
            test.deepEqual(calls, ['users','collection']);
            test.equal(child.setBy$objectConstructor, 11, '$object.constructor called');

        test.done();
    },

    createSuperSafeCallback: function(test){

        test.expect(2);

        var $parent = $object.clone({
            constructor: function(){},
            asyncMethod: function(){
                var args = arguments;
                var callback = function(){
                    this.applySuper(args);
                    test.equal(this.__super__, $object);
                }
                setTimeout( this.createSuperSafeCallback(callback, this) );
            }
        });
        var $child = $parent.clone({
            constructor: function(){
                this.applySuper('asyncMethod', [{a:11}]);
                test.equal(this.__super__, $parent);
            }
        });

        var child = $child.create();

        setTimeout(function(){
//            console.log(child.a);
//            test.equal(11, child.a);
            test.done();
        });
    },

    apply: function(test){
        //methodName, args, withObj, asObj
        var asObj = {defineProperties: function(){
            this.called = true;
            return this;
        }};
        var obj = $object.apply(Array(22,33), 'defineProperties',[{a:11}], asObj);
            test.equal(obj.a, undefined);
            test.ok(obj.called);
            test.equal(obj[0], 22);
            test.equal(Object.getPrototypeOf(obj), Array.prototype);

        //methodName, args, withObj
        obj = $object.apply(Array(22,33), 'defineProperties',[{a:11}]);
            test.equal(obj.a,  11);
            test.equal(obj[0], 22);
            test.equal(Object.getPrototypeOf(obj), Array.prototype);

        //methodName, withObj
        obj = $object.apply(Array(22,33), 'defineProperties');
            test.equal(obj[0], 22);
            test.equal(Object.getPrototypeOf(obj), Array.prototype);

        test.done();
    },

    concat: function(test){
        var $parent = $object.clone({a: 1});
        var $child  = $parent.clone({b: 2});
        var toMerge = $child .clone({c: 3, _c: 33});

            var obj = $object.clone().concat(toMerge);
                test.strictEqual(obj._c, 33);
                test.strictEqual(obj.c,  3);
                test.strictEqual(obj.b,  undefined);
                test.strictEqual(obj.a,  undefined);

            obj = $object.clone().concat(toMerge, ['a','_c']);
                test.strictEqual(obj._c, 33);
                test.strictEqual(obj.c,  undefined);
                test.strictEqual(obj.b,  undefined);
                test.strictEqual(obj.a,  1);

            obj = $object.clone().concat(toMerge, true);
                test.strictEqual(obj._c, 33);
                test.strictEqual(obj.c,  3);
                test.strictEqual(obj.b,  2);
                test.strictEqual(obj.a,  1);

        test.done();
    }

};
<|endoftext|>


<commit_before>if (!roms) {
    var roms = {};
};

if(!roms.volunteer){
    roms.volunteer = {};
}

/**
 * Match the entered name of the volunteer with an existing person/volunteer
 * @param forename entered forename
 * @param surname entered surname
 * @param $personId jquery reference to the hidden field containing the person id
 */
roms.volunteer.matchVolunteerPerson = function(forename, surname, $personId) {

    if(!forename || !surname) {
        return;
    }

    var existingPersonName = $personId.data("full-name");
    if (existingPersonName == forename + " " + surname) {
        // no change in value
        return;
    }
    this.findVolunteerPerson(forename, surname, $personId, existingPersonName);

    $personId.data("full-name", forename + " " + surname);
}

/**
 * Look up the person matching the name and show a popover
 * to allow the user the select the match, if any
 */
roms.volunteer.findVolunteerPerson = function(forename, surname, $personId, existingPersonName)  {
    var _parent = this;
    var existingPersonId = $personId.val();
    $.ajax({
        url: '../persons/search',
        contentType: "application/json",
        dataType: 'json',
        data:  {
            forename: forename,
            surname: surname,
            checkVolunteer: true
        },
        success: function(data) {
            // no match, and no person linked. We don't show anything
            if (!data.results && !existingPersonId) {
                return;
            }

            // enrich the results, splitting out the volunters from the persons.
            // if we are matching an existing volunteer we don't want to create a new one
            var volunteers = new Array();
            var persons = new Array();
            if (data.results) {
                for (var i = 0; i < data.results.length; i++) {
                    var result = data.results[i];

                    if (result.personId != existingPersonId) {
                        if (result.volunteer) {
                            volunteers.push(result);
                        } else {
                            persons.push(result);
                        }
                    }
                }
            }

            data.existingPersonId = existingPersonId;
            data.existingPersonName = existingPersonName;
            if (volunteers.length > 0) {
                data.matchedVolunteers = true;
                data.volunteers = volunteers;
            }

            if (persons.length > 0) {
                data.matchedPersons = true;
                data.persons = persons;
            }

            var template = $("#volunteer-person-search-form").html();
            var html = Mustache.to_html(template, data);

            $("#volunteer-person-modal .modal-body").html(html)
            var modalElement = $("#volunteer-person-modal")

            modalElement.modal('show')

            // if they select the person id, set it to the hidden volunteer person id field
            $("a.matched-person").on("click", function(event){
                _parent.populateVolunteerFromPerson($(this).data("person-id"), $personId);
                modalElement.modal('hide')
            });
        }
    });
}

/**
 * Populate the volunteer form from the existing person
 */
roms.volunteer.populateVolunteerFromPerson = function(selectedPersonId, $personId) {
    // chosen nobody. Clear the existing value
    if (!selectedPersonId) {
        $personId.val(selectedPersonId);
        return;
    }
    var existingPersonId = $personId.val();

    if (existingPersonId == selectedPersonId) {
        return;
    }

    // new person - pull the person data and populate the form.
    $.ajax({
        url: '../persons/' + selectedPersonId  + "/reference",
        contentType: "application/json",
        dataType: 'json',
        success: function(data) {
            $("input[name='birthDate']").val(data.birthDate);
            $("input[name='middleName']").val(data.middleName);
            $("input[name='telephone']").val(data.telephone);
            $("input[name='mobile']").val(data.mobile);
            $("input[name='workPhone']").val(data.workPhone);
            $("input[name='email']").val(data.email);
            if(data.congregation) {
                $("input[name='congregationId']").val(data.congregation.congregationId);
            }
            if (data.address) {
                $("input[name='street']").val(data.address.street);
                $("input[name='town']").val(data.address.town);
                $("input[name='county']").val(data.address.county);
                $("input[name='postcode']").val(data.address.postcode);
            }
        }
    });
    $personId.val(selectedPersonId);
}

roms.volunteer.matchEmergencyContactPerson = function(forename, surname, $personId) {

    if(!forename || !surname) {
        return;
    }

    var existingPersonName = $personId.data("full-name");
    if (existingPersonName == forename + " " + surname) {
        // no change in value
        return;
    }
    var existingPersonId = $personId.val();

    $.ajax({
        url: '../persons/search',
        contentType: "application/json",
        dataType: 'json',
        data:  {
            forename: forename,
            surname: surname,
            checkVolunteer: false
        },
        success: function(data) {
            // no match, and no person linked. We don't show anything
            if (!data.results && !existingPersonId) {
                return;
            }

            alert(data);

        }
    });

    $personId.data("full-name", forename + " " + surname);
}

$(document).ready(function() {
    $("#surname").blur(function() {
        roms.volunteer.matchVolunteerPerson($("#forename").val(), $("#surname").val(), $("#personId"));
    });

    $("#emergencyContactSurname").blur(function() {
        roms.volunteer.matchEmergencyContactPerson(
            $("#emergencyContactForename").val(),
            $("#emergencyContactSurname").val(),
            $("#emergencyContactPersonId")
        );
    });

    $(".datepicker").datepicker({
        dateFormat: "dd/mm/yy",
        changeYear: true
    });

    $("#congregationName").typeahead({
        source: roms.common.congregationTypeAheadSource,
        minLength: 2
    });

    $("#volunteer").validate({
        rules: {
            forename: {
                minlength: 2,
                required: true
            },
            surname: {
                minlength: 2,
                required: true
            },
            gender: {
                required: true
            },
            birthDate: {
                required: true
            },
            baptismDate: {
                required: true
            },
            street: {
                minlength: 2,
                required: true
            },
            town: {
                minlength: 2,
                required: true
            },
            postcode: {
                minlength: 2,
                required: true
            },
            email: {
                required: true,
                email: true
            },
            maritalStatusId: {
                required: true
            },
            emergencyContactForename: {
                minlength: 2,
                required: true
            },
            emergencyContactSurname: {
                minlength: 2,
                required: true
            },
            emergencyContactStreet: {
                minlength: 2,
                required: true
            },
            emergencyContactTown: {
                minlength: 2,
                required: true
            },
            emergencyRelationshipId: {
                required: true
            },
            congregationName: {
                required: true,
                remote: {
                    // check for an exact match. Populate the congregation id
                    url: "../congregations/search",
                    contentType: "application/json",
                    dataType: "json",
                    data: {
                        name: function() {
                            return $("#congregationName").val();
                        }
                    },
                    dataFilter: function(rawData) {
                        var data = JSON.parse(rawData)
                        if (data.results && data.results[0].name == $("#congregationName").val()) {
                            $("#congregationId").val(data.results[0].id);
                            return true;

                        }
                        return false;
                    }
                }
            },
            congregationId: {
                required: true
            },
            formDate: {
                required: true
            }
        },
        highlight: froms.common.validatorHighlight,
        success: roms.common.validatorSuccess,
        errorPlacement: roms.common.validatorErrorPlacement
    });

});
<commit_msg>[#45006035] correct typo in validator form refactor<commit_after>if (!roms) {
    var roms = {};
};

if(!roms.volunteer){
    roms.volunteer = {};
}

/**
 * Match the entered name of the volunteer with an existing person/volunteer
 * @param forename entered forename
 * @param surname entered surname
 * @param $personId jquery reference to the hidden field containing the person id
 */
roms.volunteer.matchVolunteerPerson = function(forename, surname, $personId) {

    if(!forename || !surname) {
        return;
    }

    var existingPersonName = $personId.data("full-name");
    if (existingPersonName == forename + " " + surname) {
        // no change in value
        return;
    }
    this.findVolunteerPerson(forename, surname, $personId, existingPersonName);

    $personId.data("full-name", forename + " " + surname);
}

/**
 * Look up the person matching the name and show a popover
 * to allow the user the select the match, if any
 */
roms.volunteer.findVolunteerPerson = function(forename, surname, $personId, existingPersonName)  {
    var _parent = this;
    var existingPersonId = $personId.val();
    $.ajax({
        url: '../persons/search',
        contentType: "application/json",
        dataType: 'json',
        data:  {
            forename: forename,
            surname: surname,
            checkVolunteer: true
        },
        success: function(data) {
            // no match, and no person linked. We don't show anything
            if (!data.results && !existingPersonId) {
                return;
            }

            // enrich the results, splitting out the volunters from the persons.
            // if we are matching an existing volunteer we don't want to create a new one
            var volunteers = new Array();
            var persons = new Array();
            if (data.results) {
                for (var i = 0; i < data.results.length; i++) {
                    var result = data.results[i];

                    if (result.personId != existingPersonId) {
                        if (result.volunteer) {
                            volunteers.push(result);
                        } else {
                            persons.push(result);
                        }
                    }
                }
            }

            data.existingPersonId = existingPersonId;
            data.existingPersonName = existingPersonName;
            if (volunteers.length > 0) {
                data.matchedVolunteers = true;
                data.volunteers = volunteers;
            }

            if (persons.length > 0) {
                data.matchedPersons = true;
                data.persons = persons;
            }

            var template = $("#volunteer-person-search-form").html();
            var html = Mustache.to_html(template, data);

            $("#volunteer-person-modal .modal-body").html(html)
            var modalElement = $("#volunteer-person-modal")

            modalElement.modal('show')

            // if they select the person id, set it to the hidden volunteer person id field
            $("a.matched-person").on("click", function(event){
                _parent.populateVolunteerFromPerson($(this).data("person-id"), $personId);
                modalElement.modal('hide')
            });
        }
    });
}

/**
 * Populate the volunteer form from the existing person
 */
roms.volunteer.populateVolunteerFromPerson = function(selectedPersonId, $personId) {
    // chosen nobody. Clear the existing value
    if (!selectedPersonId) {
        $personId.val(selectedPersonId);
        return;
    }
    var existingPersonId = $personId.val();

    if (existingPersonId == selectedPersonId) {
        return;
    }

    // new person - pull the person data and populate the form.
    $.ajax({
        url: '../persons/' + selectedPersonId  + "/reference",
        contentType: "application/json",
        dataType: 'json',
        success: function(data) {
            $("input[name='birthDate']").val(data.birthDate);
            $("input[name='middleName']").val(data.middleName);
            $("input[name='telephone']").val(data.telephone);
            $("input[name='mobile']").val(data.mobile);
            $("input[name='workPhone']").val(data.workPhone);
            $("input[name='email']").val(data.email);
            if(data.congregation) {
                $("input[name='congregationId']").val(data.congregation.congregationId);
            }
            if (data.address) {
                $("input[name='street']").val(data.address.street);
                $("input[name='town']").val(data.address.town);
                $("input[name='county']").val(data.address.county);
                $("input[name='postcode']").val(data.address.postcode);
            }
        }
    });
    $personId.val(selectedPersonId);
}

roms.volunteer.matchEmergencyContactPerson = function(forename, surname, $personId) {

    if(!forename || !surname) {
        return;
    }

    var existingPersonName = $personId.data("full-name");
    if (existingPersonName == forename + " " + surname) {
        // no change in value
        return;
    }
    var existingPersonId = $personId.val();

    $.ajax({
        url: '../persons/search',
        contentType: "application/json",
        dataType: 'json',
        data:  {
            forename: forename,
            surname: surname,
            checkVolunteer: false
        },
        success: function(data) {
            // no match, and no person linked. We don't show anything
            if (!data.results && !existingPersonId) {
                return;
            }

            alert(data);

        }
    });

    $personId.data("full-name", forename + " " + surname);
}

$(document).ready(function() {
    $("#surname").blur(function() {
        roms.volunteer.matchVolunteerPerson($("#forename").val(), $("#surname").val(), $("#personId"));
    });

    $("#emergencyContactSurname").blur(function() {
        roms.volunteer.matchEmergencyContactPerson(
            $("#emergencyContactForename").val(),
            $("#emergencyContactSurname").val(),
            $("#emergencyContactPersonId")
        );
    });

    $(".datepicker").datepicker({
        dateFormat: "dd/mm/yy",
        changeYear: true
    });

    $("#congregationName").typeahead({
        source: roms.common.congregationTypeAheadSource,
        minLength: 2
    });

    $("#volunteer").validate({
        rules: {
            forename: {
                minlength: 2,
                required: true
            },
            surname: {
                minlength: 2,
                required: true
            },
            gender: {
                required: true
            },
            birthDate: {
                required: true
            },
            baptismDate: {
                required: true
            },
            street: {
                minlength: 2,
                required: true
            },
            town: {
                minlength: 2,
                required: true
            },
            postcode: {
                minlength: 2,
                required: true
            },
            email: {
                required: true,
                email: true
            },
            maritalStatusId: {
                required: true
            },
            emergencyContactForename: {
                minlength: 2,
                required: true
            },
            emergencyContactSurname: {
                minlength: 2,
                required: true
            },
            emergencyContactStreet: {
                minlength: 2,
                required: true
            },
            emergencyContactTown: {
                minlength: 2,
                required: true
            },
            emergencyRelationshipId: {
                required: true
            },
            congregationName: {
                required: true,
                remote: {
                    // check for an exact match. Populate the congregation id
                    url: "../congregations/search",
                    contentType: "application/json",
                    dataType: "json",
                    data: {
                        name: function() {
                            return $("#congregationName").val();
                        }
                    },
                    dataFilter: function(rawData) {
                        var data = JSON.parse(rawData)
                        if (data.results && data.results[0].name == $("#congregationName").val()) {
                            $("#congregationId").val(data.results[0].id);
                            return true;

                        }
                        return false;
                    }
                }
            },
            congregationId: {
                required: true
            },
            formDate: {
                required: true
            }
        },
        highlight: roms.common.validatorHighlight,
        success: roms.common.validatorSuccess,
        errorPlacement: roms.common.validatorErrorPlacement
    });

});
<|endoftext|>


<commit_before>(function () {
    'use strict';
    quickiesApp.controller('CountersController', ['$scope', '$rootScope', '$q', 'Quickies',
        function ($scope, $rootScope, $q, Quickies) {
            $scope.counters = Quickies.counters();

            $rootScope.$on('$routeChangeSuccess', function() {
                var counters = Quickies.counters({}, function() {
                    $scope.counters = counters;
                });
            });
        }
    ]);
})();<commit_msg>removed useless $q from CountersController<commit_after>(function () {
    'use strict';
    quickiesApp.controller('CountersController', ['$scope', '$rootScope', 'Quickies',
        function ($scope, $rootScope, Quickies) {
            $scope.counters = Quickies.counters();

            $rootScope.$on('$routeChangeSuccess', function() {
                var counters = Quickies.counters({}, function() {
                    $scope.counters = counters;
                });
            });
        }
    ]);
})();<|endoftext|>


<commit_before>import test from 'ava';
import Dictionary from './../src/dictionary';

test('it does not merge if a non object is provided', t => {
    const dict = new Dictionary('a string');

    t.false(dict.hasLocale('en'));
});

test('it can check for locale existance', t => {
    const dict = new Dictionary({
        en: { }
    });

    t.true(dict.hasLocale('en'));
    t.false(dict.hasLocale('ar'));
});

test('it can check for message existance', t => {
    const dict = new Dictionary({
        en: {
            messages: {
                winter: 'Winter is coming'
            }
        }
    });

    t.true(dict.hasMessage('en', 'winter'));
});

test('it can fetch a message', t => {
    const dict = new Dictionary({
        en: {
            messages: {
                winter: 'Winter is coming'
            }
        }
    });

    t.is(dict.getMessage('en', 'winter'), 'Winter is coming');
});

test('it should use the polyfill if object.assign does not exist', t => {
    const assign = Object.assign;
    Object.assign = undefined;

    const dict = new Dictionary({
        en: {
            messages: {
                winter: 'Winter is coming'
            }
        }
    });

    t.is(dict.getMessage('en', 'winter'), 'Winter is coming');

    Object.assign = assign;
});

test('it can check for attribute existance', t => {
    const dict = new Dictionary({
        en: {
            attributes: {
                email: 'Email Address'
            }
        }
    });

    t.true(dict.hasAttribute('en', 'email'));
});

test('it can fetch an attribute', t => {
    const dict = new Dictionary({
        en: {
            attributes: {
                email: 'Email Address'
            }
        }
    });

    t.is(dict.getAttribute('en', 'email'), 'Email Address');
});

test('it can default to a fallback if message or attribute does not exist', t => {
    const dict = new Dictionary();
    t.is(
        dict.getMessage('en', 'winter', 'Winter is still coming'),
        'Winter is still coming'
    );
    t.is(
        dict.getAttribute('en', 'john', 'Knows nothing'),
        'Knows nothing'
    );
});

test('it can set messages', t => {
    const dict = new Dictionary();
    dict.setMessage('en', 'winter', 'Winter is coming');

    t.is(dict.getMessage('en', 'winter'), 'Winter is coming');
});

test('it can set attributes', t => {
    const dict = new Dictionary();
    dict.setAttribute('en', 'email', 'Email Address');

    t.is(dict.getAttribute('en', 'email'), 'Email Address');
});
<commit_msg>remove object.assign polyfill test<commit_after>import test from 'ava';
import Dictionary from './../src/dictionary';

test('it does not merge if a non object is provided', t => {
    const dict = new Dictionary('a string');

    t.false(dict.hasLocale('en'));
});

test('it can check for locale existance', t => {
    const dict = new Dictionary({
        en: { }
    });

    t.true(dict.hasLocale('en'));
    t.false(dict.hasLocale('ar'));
});

test('it can check for message existance', t => {
    const dict = new Dictionary({
        en: {
            messages: {
                winter: 'Winter is coming'
            }
        }
    });

    t.true(dict.hasMessage('en', 'winter'));
});

test('it can fetch a message', t => {
    const dict = new Dictionary({
        en: {
            messages: {
                winter: 'Winter is coming'
            }
        }
    });

    t.is(dict.getMessage('en', 'winter'), 'Winter is coming');
});

test('it can check for attribute existance', t => {
    const dict = new Dictionary({
        en: {
            attributes: {
                email: 'Email Address'
            }
        }
    });

    t.true(dict.hasAttribute('en', 'email'));
});

test('it can fetch an attribute', t => {
    const dict = new Dictionary({
        en: {
            attributes: {
                email: 'Email Address'
            }
        }
    });

    t.is(dict.getAttribute('en', 'email'), 'Email Address');
});

test('it can default to a fallback if message or attribute does not exist', t => {
    const dict = new Dictionary();
    t.is(
        dict.getMessage('en', 'winter', 'Winter is still coming'),
        'Winter is still coming'
    );
    t.is(
        dict.getAttribute('en', 'john', 'Knows nothing'),
        'Knows nothing'
    );
});

test('it can set messages', t => {
    const dict = new Dictionary();
    dict.setMessage('en', 'winter', 'Winter is coming');

    t.is(dict.getMessage('en', 'winter'), 'Winter is coming');
});

test('it can set attributes', t => {
    const dict = new Dictionary();
    dict.setAttribute('en', 'email', 'Email Address');

    t.is(dict.getAttribute('en', 'email'), 'Email Address');
});
<|endoftext|>


<commit_before>require('proof')(22, require('cadence')(prove))

function prove (async, okay) {
    var send = require('./fixtures/send')
    var optional = require('./fixtures/optional')
    var args = require('./fixtures/arguments')
    var main = require('./fixtures/main')
    var stream = require('stream')
    var events = require('events')
    var stdout
    var chunks
    var ee
    async(function () {
        var events = require('events')
        var identified = require('./fixtures/identified')
        async(function () {
            identified({}, async())
        }, function (identifier) {
            okay(identifier, [ 1 ], 'set identifier')
        })
    }, function () {
        var events = require('events')
        var errored = require('./fixtures/errored')
        async([function () {
            errored({}, async())
        }, function (error) {
            okay(/^destructible#error$/m.test(error.message), 'error from constructor')
        }])
    }, function () {
        var stream = require('stream')
        var echo = require('./fixtures/echo')
        async(function () {
            echo([ 'a', 'b' ], {
                $stdout: new stream.PassThrough
            }, async())
        }, function (child) {
            async(function () {
                child.exit(async())
            }, function () {
                okay(child.options.$stdout.read().toString(), 'a b\n', 'echo')
            })
        })
    }, function () {
        var messaged = require('./fixtures/messaged')
        var Messenger = require('../messenger')
        var stream = require('stream')
        async(function () {
            messaged({}, { $stdout: new stream.PassThrough, messenger: new Messenger }, async())
        }, function (child) {
            child.options.messenger.emit('message', { method: 'shutdown' })
            async(function () {
                child.exit(async())
            }, function () {
                okay(child.options.$stdout.read().toString(), 'shutdown\n', 'send')
            })
        })
    }, function () {
        var language = require('./fixtures/language')
        var LANG = process.env.LANG
        async(function () {
            process.env.LANG = 'fr_FR'
            console.log(process.env.LANG)
            language({}, {}, async())
        }, function (lang, child) {
            if (LANG != null) {
                process.env.LANG = LANG
            } else {
                delete process.env.LANG
            }
            okay(lang, 'fr_FR', 'language from environment')
            child.exit(async())
        })
    }, function () {
        var optional = require('./fixtures/optional')
        async(function () {
            optional({}, async())
        }, function (pid, child) {
            okay(pid, process.pid, 'default property return')
            async(function () {
                child.exit(async())
                child.destroy()
            }, function (exitCode, pid) {
                okay({
                    exitCode: exitCode,
                    pid: pid
                }, {
                    exitCode: 0,
                    pid: process.pid
                },  'default property exit')
            })
        })
    }, function () {
        var optional = require('./fixtures/optional')
        async(function () {
            optional({}, { pid: 2 },  async())
        }, function (pid, child) {
            okay(pid, 2, 'override default property return')
            async(function () {
                child.exit(async())
                child.destroy()
            }, function (exitCode, pid) {
                okay({
                    exitCode: exitCode,
                    pid: pid
                }, {
                    exitCode: 0,
                    pid: 2
                },  'override default pid exit')
            })
        })
    }, function () {
        var events = require('events')
        var signaled = require('./fixtures/signaled')
        async(function () {
            signaled({}, {
                $signals: new events.EventEmitter
            }, async())
        }, function (destructed, child) {
            child.options.$signals.once('SIGINT', function () {
                okay('SIGINT swallowed')
            })
            okay(!destructed[0], 'SIGINT did not destroy')
            child.options.$signals.emit('SIGHUP') // Should do nothing.
            okay(!destructed[0], 'SIGHUP did not destroy')
            async(function () {
                child.exit(async())
                child.options.$signals.emit('SIGTERM')
            }, function (exitCode) {
                okay({
                    exitCode: exitCode,
                    destructed: destructed[0]
                }, {
                    exitCode: 0,
                    destructed: true
                },  'SIGTERM did destroy')
            })
        })
    }, function () {
        var events = require('events')
        var signaled = require('./fixtures/signaled')
        async(function () {
            signaled({}, {
                $signals: new events.EventEmitter,
                $trap: false
            }, async())
        }, function (destructed, child) {
            okay(child.options.$signals.listenerCount('SIGINT'), 0, 'no traps')
            child.options.$signals.emit('SIGINT')
            okay(!destructed[0], 'SIGINT did not destroy')
            child.destroy()
            child.exit(async())
        })
    }, function () {
        var events = require('events')
        var signaled = require('./fixtures/signaled')
        async(function () {
            signaled({}, {
                $signals: new events.EventEmitter,
                $trap: true
            }, async())
        }, function (destructed, child) {
            okay(child.options.$signals.listenerCount('SIGINT'), 1, 'has a SIGINT trap')
            child.options.$signals.emit('SIGINT')
            okay(destructed[0], 'SIGINT destroyed')
            child.destroy()
            child.exit(async())
        })
    }, function () {
        // Also tests untrap as false.
        var main = require('./fixtures/main')
        var events = require('events')
        async(function () {
            main({}, {
                $signals: new events.EventEmitter,
                $isMainModule: true
            }, async())
        }, function (isMainModule, child) {
            okay(isMainModule, 'is main module')
            okay(child.options.$signals.listenerCount('SIGINT'), 1, 'main module still trapped')
            child.exit(async())
        })
    }, function () {
        // Also tests untrap as false.
        var main = require('./fixtures/main')
        var events = require('events')
        async(function () {
            main({}, {
                $signals: new events.EventEmitter,
                $isMainModule: true,
                $untrap: true
            }, async())
        }, function (isMainModule, child) {
            okay(isMainModule, 'is still main module')
            okay(child.options.$signals.listenerCount('SIGINT'), 0, 'main module untrapped')
            child.exit(async())
        })
    }, function () {
        // Also tests untrap as false.
        var abend = require('./fixtures/abend')
        var events = require('events')
        async([function () {
            abend({}, async())
        }, function (error) {
            okay(error.exitCode, 1, 'abend exit code')
            return [ async.return ]
        }], function () {
            throw new Error('abend expected')
        })
    }, function () {
        var args = require('./fixtures/arguments')
        async(function () {
            args([{ name: 'value' }], {}, async())
        }, function (name, child) {
            okay(name, 'value', 'disconected')
            child.exit(async())
        })
    })
}
<commit_msg>Remove unused imports and variables.<commit_after>require('proof')(22, require('cadence')(prove))

function prove (async, okay) {
    async(function () {
        var identified = require('./fixtures/identified')
        async(function () {
            identified({}, async())
        }, function (identifier) {
            okay(identifier, [ 1 ], 'set identifier')
        })
    }, function () {
        var errored = require('./fixtures/errored')
        async([function () {
            errored({}, async())
        }, function (error) {
            okay(/^destructible#error$/m.test(error.message), 'error from constructor')
        }])
    }, function () {
        var stream = require('stream')
        var echo = require('./fixtures/echo')
        async(function () {
            echo([ 'a', 'b' ], {
                $stdout: new stream.PassThrough
            }, async())
        }, function (child) {
            async(function () {
                child.exit(async())
            }, function () {
                okay(child.options.$stdout.read().toString(), 'a b\n', 'echo')
            })
        })
    }, function () {
        var messaged = require('./fixtures/messaged')
        var Messenger = require('../messenger')
        var stream = require('stream')
        async(function () {
            messaged({}, { $stdout: new stream.PassThrough, messenger: new Messenger }, async())
        }, function (child) {
            child.options.messenger.emit('message', { method: 'shutdown' })
            async(function () {
                child.exit(async())
            }, function () {
                okay(child.options.$stdout.read().toString(), 'shutdown\n', 'send')
            })
        })
    }, function () {
        var language = require('./fixtures/language')
        var LANG = process.env.LANG
        async(function () {
            process.env.LANG = 'fr_FR'
            console.log(process.env.LANG)
            language({}, {}, async())
        }, function (lang, child) {
            if (LANG != null) {
                process.env.LANG = LANG
            } else {
                delete process.env.LANG
            }
            okay(lang, 'fr_FR', 'language from environment')
            child.exit(async())
        })
    }, function () {
        var optional = require('./fixtures/optional')
        async(function () {
            optional({}, async())
        }, function (pid, child) {
            okay(pid, process.pid, 'default property return')
            async(function () {
                child.exit(async())
                child.destroy()
            }, function (exitCode, pid) {
                okay({
                    exitCode: exitCode,
                    pid: pid
                }, {
                    exitCode: 0,
                    pid: process.pid
                },  'default property exit')
            })
        })
    }, function () {
        var optional = require('./fixtures/optional')
        async(function () {
            optional({}, { pid: 2 },  async())
        }, function (pid, child) {
            okay(pid, 2, 'override default property return')
            async(function () {
                child.exit(async())
                child.destroy()
            }, function (exitCode, pid) {
                okay({
                    exitCode: exitCode,
                    pid: pid
                }, {
                    exitCode: 0,
                    pid: 2
                },  'override default pid exit')
            })
        })
    }, function () {
        var events = require('events')
        var signaled = require('./fixtures/signaled')
        async(function () {
            signaled({}, {
                $signals: new events.EventEmitter
            }, async())
        }, function (destructed, child) {
            child.options.$signals.once('SIGINT', function () {
                okay('SIGINT swallowed')
            })
            okay(!destructed[0], 'SIGINT did not destroy')
            child.options.$signals.emit('SIGHUP') // Should do nothing.
            okay(!destructed[0], 'SIGHUP did not destroy')
            async(function () {
                child.exit(async())
                child.options.$signals.emit('SIGTERM')
            }, function (exitCode) {
                okay({
                    exitCode: exitCode,
                    destructed: destructed[0]
                }, {
                    exitCode: 0,
                    destructed: true
                },  'SIGTERM did destroy')
            })
        })
    }, function () {
        var events = require('events')
        var signaled = require('./fixtures/signaled')
        async(function () {
            signaled({}, {
                $signals: new events.EventEmitter,
                $trap: false
            }, async())
        }, function (destructed, child) {
            okay(child.options.$signals.listenerCount('SIGINT'), 0, 'no traps')
            child.options.$signals.emit('SIGINT')
            okay(!destructed[0], 'SIGINT did not destroy')
            child.destroy()
            child.exit(async())
        })
    }, function () {
        var events = require('events')
        var signaled = require('./fixtures/signaled')
        async(function () {
            signaled({}, {
                $signals: new events.EventEmitter,
                $trap: true
            }, async())
        }, function (destructed, child) {
            okay(child.options.$signals.listenerCount('SIGINT'), 1, 'has a SIGINT trap')
            child.options.$signals.emit('SIGINT')
            okay(destructed[0], 'SIGINT destroyed')
            child.destroy()
            child.exit(async())
        })
    }, function () {
        // Also tests untrap as false.
        var main = require('./fixtures/main')
        var events = require('events')
        async(function () {
            main({}, {
                $signals: new events.EventEmitter,
                $isMainModule: true
            }, async())
        }, function (isMainModule, child) {
            okay(isMainModule, 'is main module')
            okay(child.options.$signals.listenerCount('SIGINT'), 1, 'main module still trapped')
            child.exit(async())
        })
    }, function () {
        // Also tests untrap as false.
        var main = require('./fixtures/main')
        var events = require('events')
        async(function () {
            main({}, {
                $signals: new events.EventEmitter,
                $isMainModule: true,
                $untrap: true
            }, async())
        }, function (isMainModule, child) {
            okay(isMainModule, 'is still main module')
            okay(child.options.$signals.listenerCount('SIGINT'), 0, 'main module untrapped')
            child.exit(async())
        })
    }, function () {
        // Also tests untrap as false.
        var abend = require('./fixtures/abend')
        async([function () {
            abend({}, async())
        }, function (error) {
            okay(error.exitCode, 1, 'abend exit code')
            return [ async.return ]
        }], function () {
            throw new Error('abend expected')
        })
    }, function () {
        var args = require('./fixtures/arguments')
        async(function () {
            args([{ name: 'value' }], {}, async())
        }, function (name, child) {
            okay(name, 'value', 'disconected')
            child.exit(async())
        })
    })
}
<|endoftext|>