<commit_before>'use strict';

/**
 * Load Test a URL, website or websocket.
 * (C) 2013 Alex Fernández.
 */

// requires
const Log = require('log');
const http = require('http');
const https = require('https');
const testing = require('testing');
const httpClient = require('./httpClient.js');
const websocket = require('./websocket.js');
const timing = require('./timing.js');

// globals
const log = new Log('info');

// constants
const SHOW_INTERVAL_MS = 5000;

// init
http.globalAgent.maxSockets = 1000;
https.globalAgent.maxSockets = 1000;

/**
 * Run a load test.
 * Options is an object which may have:
 *	- url: mandatory URL to access.
 *	- concurrency: how many concurrent clients to use.
 *	- maxRequests: how many requests to send
 *	- maxSeconds: how long to run the tests.
 *	- cookies: a string or an array of strings, each with name:value.
 *	- headers: a map with headers: {key1: value1, key2: value2}.
 *	- method: the method to use: POST, PUT. Default: GET, what else.
 *	- body: the contents to send along a POST or PUT request.
 *	- contentType: the MIME type to use for the body, default text/plain.
 *	- requestsPerSecond: how many requests per second to send.
 *	- agentKeepAlive: if true, then use connection keep-alive.
 *	- debug: show debug messages.
 *	- quiet: do not log any messages.
 *	- indexParam: string to replace with a unique index.
 *	- insecure: allow https using self-signed certs.
 * An optional callback will be called if/when the test finishes.
 */
exports.loadTest = function(options, callback) {
	if (!options.url) {
		log.error('Missing URL in options');
		return;
	}
	options.concurrency = options.concurrency || 1;
	if (options.requestsPerSecond) {
		options.requestsPerSecond = options.requestsPerSecond / options.concurrency;
	}
	if (options.debug) {
		log.level = Log.DEBUG;
	}
	if (!options.url.startsWith('http://') && !options.url.startsWith('https://') && !options.url.startsWith('ws://')) {
		log.error('Invalid URL %s, must be http://, https:// or ws://', options.url);
		return;
	}
	if (callback && !('quiet' in options)) {
		options.quiet = true;
	}

	if (options.url.startsWith('ws:')) {
		if (options.requestsPerSecond) {
			log.error('"requestsPerSecond" not supported for WebSockets');
		}
	}

	const operation = new Operation(options, callback);
	operation.start();
	return operation;
};

/**
 * Used to keep track of individual load test Operation runs.
 */
let operationInstanceIndex = 0;

/**
 * A load test operation.
 */
class Operation {
	constructor(options, callback) {
		this.options = options
		this.finalCallback = callback
		this.running = true;
		this.latency = null;
		this.clients = {};
		this.requests = 0;
		this.completedRequests = 0;
		this.showTimer = null;
		this.stopTimeout = null;
		this.instanceIndex = operationInstanceIndex++;
	}

	/**
	 * Start the operation.
	 */
	start() {
		this.latency = new timing.Latency(this.options);
		this.startClients();
		if (this.options.maxSeconds) {
			this.stopTimeout = setTimeout(() => this.stop(), this.options.maxSeconds * 1000).unref();
		}
		this.showTimer = new timing.HighResolutionTimer(SHOW_INTERVAL_MS, () => this.latency.showPartial());
		this.showTimer.unref()
	}

	/**
	 * Call after each operation has finished.
	 */
	callback(error, result, next) {
		this.completedRequests += 1;
		if (this.options.maxRequests) {
			if (this.completedRequests == this.options.maxRequests) {
				this.stop();
			}
			if (this.requests > this.options.maxRequests) {
				log.debug('Should have no more running clients');
			}
		}
		if (this.running && next) {
			next();
		}
		if (this.options.statusCallback) {
			this.options.statusCallback(error, result, this.latency.getResults());
		}
	}

	/**
	 * Start a number of measuring clients.
	 */
	startClients() {
		const url = this.options.url;
		for (let index = 0; index < this.options.concurrency; index++) {
			if (this.options.indexParam) {
				this.options.url = url.replaceAll(this.options.indexParam, index);

				if(this.options.body) {
					let strBody = JSON.stringify(this.options.body);
					strBody = strBody.replaceAll(this.options.indexParam, index);
					this.options.body = JSON.parse(strBody);
				}
			}
			let constructor = httpClient.create;
			// TODO: || this.options.url.startsWith('wss:'))
			if (this.options.url.startsWith('ws:')) {
				constructor = websocket.create;
			}
			const client = constructor(this, this.options);
			this.clients[index] = client;
			if (!this.options.requestsPerSecond) {
				client.start();
			} else {
				// start each client at a random moment in one second
				const offset = Math.floor(Math.random() * 1000);
				setTimeout(() => client.start(), offset);
			}
		}
	}

	/**
	 * Stop clients.
	 */
	stop() {
		if (this.showTimer) {
			this.showTimer.stop();
		}
		if (this.stopTimeout) {
			clearTimeout(this.stopTimeout);
		}
		this.running = false;

		Object.keys(this.clients).forEach(index => {
			this.clients[index].stop();
		});
		if (this.finalCallback) {
			const result = this.latency.getResults();
			result.instanceIndex = this.instanceIndex;
			this.finalCallback(null, result);
		} else {
			this.latency.show();
		}
	}
}

/**
 * A load test with max seconds.
 */
function testMaxSeconds(callback) {
	const options = {
		url: 'http://localhost:7357/',
		maxSeconds: 0.1,
		concurrency: 1,
		quiet: true,
	};
	exports.loadTest(options, callback);
}

/**
 * A load test with max seconds.
 */
function testWSEcho(callback) {
	const options = {
		url: 'ws://localhost:7357/',
		maxSeconds: 0.1,
		concurrency: 1,
		quiet: true,
	};
	exports.loadTest(options, callback);
}

/**
 * Run all tests.
 */
exports.test = function(callback) {
	testing.run([testMaxSeconds, testWSEcho], callback);
};

// run tests if invoked directly
if (__filename == process.argv[1]) {
	exports.test(testing.show);
}

<commit_msg>stop latency in Operation.stop (#175)<commit_after>'use strict';

/**
 * Load Test a URL, website or websocket.
 * (C) 2013 Alex Fernández.
 */

// requires
const Log = require('log');
const http = require('http');
const https = require('https');
const testing = require('testing');
const httpClient = require('./httpClient.js');
const websocket = require('./websocket.js');
const timing = require('./timing.js');

// globals
const log = new Log('info');

// constants
const SHOW_INTERVAL_MS = 5000;

// init
http.globalAgent.maxSockets = 1000;
https.globalAgent.maxSockets = 1000;

/**
 * Run a load test.
 * Options is an object which may have:
 *	- url: mandatory URL to access.
 *	- concurrency: how many concurrent clients to use.
 *	- maxRequests: how many requests to send
 *	- maxSeconds: how long to run the tests.
 *	- cookies: a string or an array of strings, each with name:value.
 *	- headers: a map with headers: {key1: value1, key2: value2}.
 *	- method: the method to use: POST, PUT. Default: GET, what else.
 *	- body: the contents to send along a POST or PUT request.
 *	- contentType: the MIME type to use for the body, default text/plain.
 *	- requestsPerSecond: how many requests per second to send.
 *	- agentKeepAlive: if true, then use connection keep-alive.
 *	- debug: show debug messages.
 *	- quiet: do not log any messages.
 *	- indexParam: string to replace with a unique index.
 *	- insecure: allow https using self-signed certs.
 * An optional callback will be called if/when the test finishes.
 */
exports.loadTest = function(options, callback) {
	if (!options.url) {
		log.error('Missing URL in options');
		return;
	}
	options.concurrency = options.concurrency || 1;
	if (options.requestsPerSecond) {
		options.requestsPerSecond = options.requestsPerSecond / options.concurrency;
	}
	if (options.debug) {
		log.level = Log.DEBUG;
	}
	if (!options.url.startsWith('http://') && !options.url.startsWith('https://') && !options.url.startsWith('ws://')) {
		log.error('Invalid URL %s, must be http://, https:// or ws://', options.url);
		return;
	}
	if (callback && !('quiet' in options)) {
		options.quiet = true;
	}

	if (options.url.startsWith('ws:')) {
		if (options.requestsPerSecond) {
			log.error('"requestsPerSecond" not supported for WebSockets');
		}
	}

	const operation = new Operation(options, callback);
	operation.start();
	return operation;
};

/**
 * Used to keep track of individual load test Operation runs.
 */
let operationInstanceIndex = 0;

/**
 * A load test operation.
 */
class Operation {
	constructor(options, callback) {
		this.options = options
		this.finalCallback = callback
		this.running = true;
		this.latency = null;
		this.clients = {};
		this.requests = 0;
		this.completedRequests = 0;
		this.showTimer = null;
		this.stopTimeout = null;
		this.instanceIndex = operationInstanceIndex++;
	}

	/**
	 * Start the operation.
	 */
	start() {
		this.latency = new timing.Latency(this.options);
		this.startClients();
		if (this.options.maxSeconds) {
			this.stopTimeout = setTimeout(() => this.stop(), this.options.maxSeconds * 1000).unref();
		}
		this.showTimer = new timing.HighResolutionTimer(SHOW_INTERVAL_MS, () => this.latency.showPartial());
		this.showTimer.unref()
	}

	/**
	 * Call after each operation has finished.
	 */
	callback(error, result, next) {
		this.completedRequests += 1;
		if (this.options.maxRequests) {
			if (this.completedRequests == this.options.maxRequests) {
				this.stop();
			}
			if (this.requests > this.options.maxRequests) {
				log.debug('Should have no more running clients');
			}
		}
		if (this.running && next) {
			next();
		}
		if (this.options.statusCallback) {
			this.options.statusCallback(error, result, this.latency.getResults());
		}
	}

	/**
	 * Start a number of measuring clients.
	 */
	startClients() {
		const url = this.options.url;
		for (let index = 0; index < this.options.concurrency; index++) {
			if (this.options.indexParam) {
				this.options.url = url.replaceAll(this.options.indexParam, index);

				if(this.options.body) {
					let strBody = JSON.stringify(this.options.body);
					strBody = strBody.replaceAll(this.options.indexParam, index);
					this.options.body = JSON.parse(strBody);
				}
			}
			let constructor = httpClient.create;
			// TODO: || this.options.url.startsWith('wss:'))
			if (this.options.url.startsWith('ws:')) {
				constructor = websocket.create;
			}
			const client = constructor(this, this.options);
			this.clients[index] = client;
			if (!this.options.requestsPerSecond) {
				client.start();
			} else {
				// start each client at a random moment in one second
				const offset = Math.floor(Math.random() * 1000);
				setTimeout(() => client.start(), offset);
			}
		}
	}

	/**
	 * Stop clients.
	 */
	stop() {
		if (this.showTimer) {
			this.showTimer.stop();
		}
		if (this.stopTimeout) {
			clearTimeout(this.stopTimeout);
		}
		this.running = false;
		this.latency.running = false;

		Object.keys(this.clients).forEach(index => {
			this.clients[index].stop();
		});
		if (this.finalCallback) {
			const result = this.latency.getResults();
			result.instanceIndex = this.instanceIndex;
			this.finalCallback(null, result);
		} else {
			this.latency.show();
		}
	}
}

/**
 * A load test with max seconds.
 */
function testMaxSeconds(callback) {
	const options = {
		url: 'http://localhost:7357/',
		maxSeconds: 0.1,
		concurrency: 1,
		quiet: true,
	};
	exports.loadTest(options, callback);
}

/**
 * A load test with max seconds.
 */
function testWSEcho(callback) {
	const options = {
		url: 'ws://localhost:7357/',
		maxSeconds: 0.1,
		concurrency: 1,
		quiet: true,
	};
	exports.loadTest(options, callback);
}

/**
 * Run all tests.
 */
exports.test = function(callback) {
	testing.run([testMaxSeconds, testWSEcho], callback);
};

// run tests if invoked directly
if (__filename == process.argv[1]) {
	exports.test(testing.show);
}

<|endoftext|>


<commit_before>(function () {
    'use strict';

    function WavesTransactionLoadingService($q, apiService) {
        var self = this;

        // returns promise that loads and merges unconfirmed and confirmed transactions
        this.loadTransactions = function (address) {
            var unconfirmed;
            return apiService.transactions.unconfirmed()
                .then(function (response) {
                    unconfirmed = response;

                    return apiService.transactions.list(address);
                })
                .then(function (response) {
                    var confirmed = response[0];

                    return self.mergeTransactions(address, unconfirmed, confirmed);
                });
        };

        this.refreshAssetCache = function (cache, transactions) {
            var sequence = $q.resolve();
            _.forEach(transactions, function (tx) {
                var assetId;
                if (tx.assetId)
                    assetId = tx.assetId;
                else if (tx.order1 && tx.order1.assetPair.amountAsset)
                    assetId = tx.order1.assetPair.amountAsset;

                var cached = cache[assetId];
                if (!cached) {
                    sequence = sequence
                        .then(function () {
                            return apiService.transactions.info(assetId);
                        })
                        .then(function (response) {
                            cache.put(response);
                        });
                }
            });

            return sequence;
        };

        this.mergeTransactions = function (address, unconfirmed, confirmed) {
            var rawAddress = address;
            unconfirmed = _.filter(unconfirmed, function (transaction) {
                return (transaction.sender === rawAddress || transaction.recipient === rawAddress);
            });
            var unconfirmedSignatures = _.map(unconfirmed, function (transaction) {
                return transaction.signature;
            });
            confirmed = _.filter(confirmed, function (transaction) {
                return unconfirmedSignatures.indexOf(transaction.signature) === -1;
            });
            unconfirmed = _.map(unconfirmed, function (transaction) {
                transaction.unconfirmed = true;

                return transaction;
            });

            return _.union(unconfirmed, confirmed);
        };
    }

    WavesTransactionLoadingService.$inject = ['$q', 'apiService'];

    angular
        .module('app.shared')
        .service('transactionLoadingService', WavesTransactionLoadingService);
})();
<commit_msg>Fixed asset cache refresh<commit_after>(function () {
    'use strict';

    function WavesTransactionLoadingService($q, apiService) {
        var self = this;

        // returns promise that loads and merges unconfirmed and confirmed transactions
        this.loadTransactions = function (address) {
            var unconfirmed;
            return apiService.transactions.unconfirmed()
                .then(function (response) {
                    unconfirmed = response;

                    return apiService.transactions.list(address);
                })
                .then(function (response) {
                    var confirmed = response[0];

                    return self.mergeTransactions(address, unconfirmed, confirmed);
                });
        };

        this.refreshAssetCache = function (cache, transactions) {
            var sequence = $q.resolve();
            _.forEach(transactions, function (tx) {
                var assetId;
                if (tx.assetId)
                    assetId = tx.assetId;
                else if (tx.order1 && tx.order1.assetPair.amountAsset)
                    assetId = tx.order1.assetPair.amountAsset;

                if (assetId) {
                    var cached = cache[assetId];
                    if (!cached) {
                        sequence = sequence
                            .then(function () {
                                return apiService.transactions.info(assetId);
                            })
                            .then(function (response) {
                                cache.put(response);
                            });
                    }
                }
            });

            return sequence;
        };

        this.mergeTransactions = function (address, unconfirmed, confirmed) {
            var rawAddress = address;
            unconfirmed = _.filter(unconfirmed, function (transaction) {
                return (transaction.sender === rawAddress || transaction.recipient === rawAddress);
            });
            var unconfirmedSignatures = _.map(unconfirmed, function (transaction) {
                return transaction.signature;
            });
            confirmed = _.filter(confirmed, function (transaction) {
                return unconfirmedSignatures.indexOf(transaction.signature) === -1;
            });
            unconfirmed = _.map(unconfirmed, function (transaction) {
                transaction.unconfirmed = true;

                return transaction;
            });

            return _.union(unconfirmed, confirmed);
        };
    }

    WavesTransactionLoadingService.$inject = ['$q', 'apiService'];

    angular
        .module('app.shared')
        .service('transactionLoadingService', WavesTransactionLoadingService);
})();
<|endoftext|>


<commit_before>var db = require('./models');

db.Game.find({}, function(err, games) {
  console.log(games);
  db.Game.remove({}, function (err, games) {
    if(err) { return console.log("ERROR: ", err);}
    console.log("Delete all games!!");
  });
});

db.Draw.find({}, function(err, draws) {
  console.log(draws);
  db.Draw.remove({}, function (err, draws) {
    if(err) { return console.log("ERROR: ", err);}
    console.log("Delete all draws!!");
  });
});

process.exit();
<commit_msg>fix seed.js not exit<commit_after>var db = require('./models');

db.Game.find({}, function(err, games) {
  console.log(games);
  db.Game.remove({}, function (err, games) {
    if(err) { return console.log("ERROR: ", err);}
    console.log("Delete all games!!");
  });
});

db.Draw.find({}, function(err, draws) {
  console.log(draws);
  db.Draw.remove({}, function (err, draws) {
    if(err) { return console.log("ERROR: ", err);}
    console.log("Delete all draws!!");
    process.exit();
  });
});
<|endoftext|>


<commit_before>/**
 * @module sign
 */

'use strict'

const path = require('path')

const Promise = require('bluebird')
const compareVersion = require('compare-version')

const pkg = require('./package.json')
const util = require('./util')
const debuglog = util.debuglog
const debugwarn = util.debugwarn
const getAppContentsPath = util.getAppContentsPath
const execFileAsync = util.execFileAsync
const validateOptsAppAsync = util.validateOptsAppAsync
const validateOptsPlatformAsync = util.validateOptsPlatformAsync
const walkAsync = util.walkAsync
const Identity = require('./util-identities').Identity
const findIdentitiesAsync = require('./util-identities').findIdentitiesAsync
const ProvisioningProfile = require('./util-provisioning-profiles').ProvisioningProfile
const preEmbedProvisioningProfile = require('./util-provisioning-profiles').preEmbedProvisioningProfile
const preAutoEntitlements = require('./util-entitlements').preAutoEntitlements

/**
 * This function returns a promise validating opts.binaries, the additional binaries to be signed along with the discovered enclosed components.
 * @function
 * @param {Object} opts - Options.
 * @returns {Promise} Promise.
 */
function validateOptsBinariesAsync (opts) {
  return new Promise(function (resolve, reject) {
    if (opts.binaries) {
      if (!Array.isArray(opts.binaries)) {
        reject(new Error('Additional binaries should be an Array.'))
        return
      }
      // TODO: Presence check for binary files, reject if any does not exist
    }
    resolve()
  })
}

/**
 * This function returns a promise validating all options passed in opts.
 * @function
 * @param {Object} opts - Options.
 * @returns {Promise} Promise.
 */
function validateSignOptsAsync (opts) {
  if (opts.ignore && !(opts.ignore instanceof Array)) {
    opts.ignore = [opts.ignore]
  }

  if (opts['provisioning-profile']) {
    if (typeof opts['provisioning-profile'] !== 'string' && !(opts['provisioning-profile'] instanceof ProvisioningProfile)) return Promise.reject(new Error('Path to provisioning profile should be a string or a ProvisioningProfile object.'))
  }

  if (opts['type']) {
    if (opts['type'] !== 'development' && opts['type'] !== 'distribution') return Promise.reject(new Error('Type must be either `development` or `distribution`.'))
  } else {
    opts['type'] = 'distribution'
  }

  return Promise.map([
    validateOptsAppAsync,
    validateOptsPlatformAsync,
    validateOptsBinariesAsync
  ], function (validate) {
    return validate(opts)
  })
}

/**
 * This function returns a promise verifying the code sign of application bundle.
 * @function
 * @param {Object} opts - Options.
 * @returns {Promise} Promise resolving output.
 */
function verifySignApplicationAsync (opts) {
  // Verify with codesign
  var compareVersion = require('compare-version')
  var osRelease = require('os').release()
  debuglog('Verifying application bundle with codesign...')

  var promise = execFileAsync('codesign', [
    '--verify',
    '--deep',
  ]
    .concat(
      opts['strict-verify'] !== false &&
      compareVersion(osRelease, '15.0.0') >= 0 // Only pass strict flag in El Capitan and later
        ? ['--strict' +
            (opts['strict-verify']
             ? '=' + opts['strict-verify'] // Array should be converted to a comma separated string
             : '')]
        : [],
      ['--verbose=2', opts.app]))

  // Additionally test Gatekeeper acceptance for darwin platform
  if (opts.platform === 'darwin' && opts['gatekeeper-assess'] !== false) {
    promise = promise
      .then(function () {
        debuglog('Verifying Gatekeeper acceptance for darwin platform...')
        return execFileAsync('spctl', [
          '--assess',
          '--type', 'execute',
          '--verbose',
          '--ignore-cache',
          '--no-cache',
          opts.app
        ])
      })
  }

  return promise
    .thenReturn()
}

/**
 * This function returns a promise codesigning only.
 * @function
 * @param {Object} opts - Options.
 * @returns {Promise} Promise.
 */
function signApplicationAsync (opts) {
  return walkAsync(getAppContentsPath(opts))
    .then(function (childPaths) {
      function ignoreFilePath (opts, filePath) {
        if (opts.ignore) {
          return opts.ignore.some(function (ignore) {
            if (typeof ignore === 'function') {
              return ignore(filePath)
            }
            return filePath.match(ignore)
          })
        }
        return false
      }

      if (opts.binaries) childPaths = childPaths.concat(opts.binaries)

      var args = [
        '--sign', opts.identity.hash || opts.identity.name,
        '--force'
      ]
      if (opts.keychain) {
        args.push('--keychain', opts.keychain)
      }
      if (opts.requirements) {
        args.push('--requirements', opts.requirements)
      }
      if (opts.timestamp) {
        args.push('--timestamp', opts.timestamp)
      }

      var promise
      if (opts.entitlements) {
        // Sign with entitlements
        promise = Promise.mapSeries(childPaths, function (filePath) {
          if (ignoreFilePath(opts, filePath)) {
            debuglog('Skipped... ' + filePath)
            return
          }
          debuglog('Signing... ' + filePath)
          return execFileAsync('codesign', args.concat('--entitlements', opts['entitlements-inherit'], filePath))
        })
          .then(function () {
            debuglog('Signing... ' + opts.app)
            return execFileAsync('codesign', args.concat('--entitlements', opts.entitlements, opts.app))
          })
      } else {
        // Otherwise normally
        promise = Promise.mapSeries(childPaths, function (filePath) {
          if (ignoreFilePath(opts, filePath)) {
            debuglog('Skipped... ' + filePath)
            return
          }
          debuglog('Signing... ' + filePath)
          return execFileAsync('codesign', args.concat(filePath))
        })
          .then(function () {
            debuglog('Signing... ' + opts.app)
            return execFileAsync('codesign', args.concat(opts.app))
          })
      }

      return promise
        .then(function () {
          // Verify code sign
          debuglog('Verifying...')
          var promise = verifySignApplicationAsync(opts)
            .then(function (result) {
              debuglog('Verified.')
            })

          // Check entitlements if applicable
          if (opts.entitlements) {
            promise = promise
              .then(function () {
                debuglog('Displaying entitlements...')
                return execFileAsync('codesign', [
                  '--display',
                  '--entitlements', ':-', // Write to standard output and strip off the blob header
                  opts.app
                ])
              })
              .then(function (result) {
                debuglog('Entitlements:', '\n',
                  result)
              })
          }

          return promise
        })
    })
}

/**
 * This function returns a promise signing the application.
 * @function
 * @param {mixed} opts - Options.
 * @returns {Promise} Promise.
 */
var signAsync = module.exports.signAsync = function (opts) {
  debuglog('electron-osx-sign@%s', pkg.version)
  return validateSignOptsAsync(opts)
    .then(function () {
      // Determine identity for signing
      var promise
      if (opts.identity) {
        debuglog('`identity` passed in arguments.')
        if (opts['identity-validation'] === false) {
          if (!(opts.identity instanceof Identity)) {
            opts.identity = new Identity(opts.identity)
          }
          return Promise.resolve()
        }
        promise = findIdentitiesAsync(opts, opts.identity)
      } else {
        debugwarn('No `identity` passed in arguments...')
        if (opts.platform === 'mas') {
          if (opts.type === 'distribution') {
            debuglog('Finding `3rd Party Mac Developer Application` certificate for signing app distribution in the Mac App Store...')
            promise = findIdentitiesAsync(opts, '3rd Party Mac Developer Application:')
          } else {
            debuglog('Finding `Mac Developer` certificate for signing app in development for the Mac App Store signing...')
            promise = findIdentitiesAsync(opts, 'Mac Developer:')
          }
        } else {
          debuglog('Finding `Developer ID Application` certificate for distribution outside the Mac App Store...')
          promise = findIdentitiesAsync(opts, 'Developer ID Application:')
        }
      }
      return promise
        .then(function (identities) {
          if (identities.length > 0) {
            // Identity(/ies) found
            if (identities.length > 1) {
              debugwarn('Multiple identities found, will use the first discovered.')
            } else {
              debuglog('Found 1 identity.')
            }
            opts.identity = identities[0]
          } else {
            // No identity found
            return Promise.reject(new Error('No identity found for signing.'))
          }
        })
    })
    .then(function () {
      // Determine entitlements for code signing
      var filePath
      if (opts.platform === 'mas') {
        // To sign apps for Mac App Store, an entitlements file is required, especially for app sandboxing (as well some other services).
        // Fallback entitlements for sandboxing by default: Note this may cause troubles while running an signed app due to missing keys special to the project.
        // Further reading: https://developer.apple.com/library/mac/documentation/Miscellaneous/Reference/EntitlementKeyReference/Chapters/EnablingAppSandbox.html
        if (!opts.entitlements) {
          filePath = path.join(__dirname, 'default.entitlements.mas.plist')
          debugwarn('No `entitlements` passed in arguments:', '\n',
            '* Sandbox entitlements are required for Mac App Store distribution, your codesign entitlements file is default to:', filePath)
          opts.entitlements = filePath
        }
        if (!opts['entitlements-inherit']) {
          filePath = path.join(__dirname, 'default.entitlements.mas.inherit.plist')
          debugwarn('No `entitlements-inherit` passed in arguments:', '\n',
            '* Sandbox entitlements file for enclosing app files is default to:', filePath)
          opts['entitlements-inherit'] = filePath
        }
      } else {
        // Not necessary to have entitlements for non Mac App Store distribution
        if (!opts.entitlements) {
          debugwarn('No `entitlements` passed in arguments:', '\n',
            '* Provide `entitlements` to specify entitlements file for codesign.')
        } else {
          // If entitlements is provided as a flag, fallback to default
          if (opts.entitlements === true) {
            filePath = path.join(__dirname, 'default.entitlements.darwin.plist')
            debugwarn('`entitlements` not specified in arguments:', '\n',
              '* Provide `entitlements` to specify entitlements file for codesign.', '\n',
              '* Sandbox entitlements file for enclosing app files is default to:', filePath)
            opts.entitlements = filePath
          }
          if (!opts['entitlements-inherit']) {
            filePath = path.join(__dirname, 'default.entitlements.darwin.inherit.plist')
            debugwarn('No `entitlements-inherit` passed in arguments:', '\n',
              '* Sandbox entitlements file for enclosing app files is default to:', filePath)
            opts['entitlements-inherit'] = filePath
          }
        }
      }
    })
    .then(function () {
      // Pre-sign operations
      var preSignOperations = []

      if (opts['pre-embed-provisioning-profile'] === false) {
        debugwarn('Pre-sign operation disabled for provisioning profile embedding:', '\n',
          '* Enable by setting `pre-embed-provisioning-profile` to `true`.')
      } else {
        debuglog('Pre-sign operation enabled for provisioning profile:', '\n',
          '* Disable by setting `pre-embed-previsioning-profile` to `false`.')
        preSignOperations.push(preEmbedProvisioningProfile)
      }

      if (opts['pre-auto-entitlements'] === false) {
        debugwarn('Pre-sign operation disabled for entitlements automation.')
      } else {
        debuglog('Pre-sign operation enabled for entitlements automation with versions >= `1.1.1`:', '\n',
          '* Disable by setting `pre-auto-entitlements` to `false`.')
        if (opts.entitlements && (!opts.version || compareVersion(opts.version, '1.1.1') >= 0)) {
          // Enable Mac App Store sandboxing without using temporary-exception, introduced in Electron v1.1.1. Relates to electron#5601
          preSignOperations.push(preAutoEntitlements)
        }
      }

      return Promise.mapSeries(preSignOperations, function (preSignOperation) {
        return preSignOperation(opts)
      })
    })
    .then(function () {
      debuglog('Signing application...', '\n',
        '> Application:', opts.app, '\n',
        '> Platform:', opts.platform, '\n',
        '> Entitlements:', opts.entitlements, '\n',
        '> Child entitlements:', opts['entitlements-inherit'], '\n',
        '> Additional binaries:', opts.binaries, '\n',
        '> Identity:', opts.identity)
      return signApplicationAsync(opts)
    })
    .then(function () {
      // Post-sign operations
      debuglog('Application signed.')
    })
}

/**
 * This function is a normal callback implementation.
 * @function
 * @param {Object} opts - Options.
 * @param {RequestCallback} cb - Callback.
 */
module.exports.sign = function (opts, cb) {
  signAsync(opts)
    .then(function () {
      debuglog('Application signed: ' + opts.app)
      if (cb) cb()
    })
    .catch(function (err) {
      debuglog('Sign failed:')
      if (err.message) debuglog(err.message)
      else if (err.stack) debuglog(err.stack)
      else debuglog(err)
      if (cb) cb(err)
    })
}
<commit_msg>Fix style<commit_after>/**
 * @module sign
 */

'use strict'

const path = require('path')

const Promise = require('bluebird')
const compareVersion = require('compare-version')

const pkg = require('./package.json')
const util = require('./util')
const debuglog = util.debuglog
const debugwarn = util.debugwarn
const getAppContentsPath = util.getAppContentsPath
const execFileAsync = util.execFileAsync
const validateOptsAppAsync = util.validateOptsAppAsync
const validateOptsPlatformAsync = util.validateOptsPlatformAsync
const walkAsync = util.walkAsync
const Identity = require('./util-identities').Identity
const findIdentitiesAsync = require('./util-identities').findIdentitiesAsync
const ProvisioningProfile = require('./util-provisioning-profiles').ProvisioningProfile
const preEmbedProvisioningProfile = require('./util-provisioning-profiles').preEmbedProvisioningProfile
const preAutoEntitlements = require('./util-entitlements').preAutoEntitlements

/**
 * This function returns a promise validating opts.binaries, the additional binaries to be signed along with the discovered enclosed components.
 * @function
 * @param {Object} opts - Options.
 * @returns {Promise} Promise.
 */
function validateOptsBinariesAsync (opts) {
  return new Promise(function (resolve, reject) {
    if (opts.binaries) {
      if (!Array.isArray(opts.binaries)) {
        reject(new Error('Additional binaries should be an Array.'))
        return
      }
      // TODO: Presence check for binary files, reject if any does not exist
    }
    resolve()
  })
}

/**
 * This function returns a promise validating all options passed in opts.
 * @function
 * @param {Object} opts - Options.
 * @returns {Promise} Promise.
 */
function validateSignOptsAsync (opts) {
  if (opts.ignore && !(opts.ignore instanceof Array)) {
    opts.ignore = [opts.ignore]
  }

  if (opts['provisioning-profile']) {
    if (typeof opts['provisioning-profile'] !== 'string' && !(opts['provisioning-profile'] instanceof ProvisioningProfile)) return Promise.reject(new Error('Path to provisioning profile should be a string or a ProvisioningProfile object.'))
  }

  if (opts['type']) {
    if (opts['type'] !== 'development' && opts['type'] !== 'distribution') return Promise.reject(new Error('Type must be either `development` or `distribution`.'))
  } else {
    opts['type'] = 'distribution'
  }

  return Promise.map([
    validateOptsAppAsync,
    validateOptsPlatformAsync,
    validateOptsBinariesAsync
  ], function (validate) {
    return validate(opts)
  })
}

/**
 * This function returns a promise verifying the code sign of application bundle.
 * @function
 * @param {Object} opts - Options.
 * @returns {Promise} Promise resolving output.
 */
function verifySignApplicationAsync (opts) {
  // Verify with codesign
  var compareVersion = require('compare-version')
  var osRelease = require('os').release()
  debuglog('Verifying application bundle with codesign...')

  var promise = execFileAsync('codesign', [
    '--verify',
    '--deep'
  ]
    .concat(
      opts['strict-verify'] !== false &&
      compareVersion(osRelease, '15.0.0') >= 0 // Only pass strict flag in El Capitan and later
        ? ['--strict' +
            (opts['strict-verify']
             ? '=' + opts['strict-verify'] // Array should be converted to a comma separated string
             : '')]
        : [],
      ['--verbose=2', opts.app]))

  // Additionally test Gatekeeper acceptance for darwin platform
  if (opts.platform === 'darwin' && opts['gatekeeper-assess'] !== false) {
    promise = promise
      .then(function () {
        debuglog('Verifying Gatekeeper acceptance for darwin platform...')
        return execFileAsync('spctl', [
          '--assess',
          '--type', 'execute',
          '--verbose',
          '--ignore-cache',
          '--no-cache',
          opts.app
        ])
      })
  }

  return promise
    .thenReturn()
}

/**
 * This function returns a promise codesigning only.
 * @function
 * @param {Object} opts - Options.
 * @returns {Promise} Promise.
 */
function signApplicationAsync (opts) {
  return walkAsync(getAppContentsPath(opts))
    .then(function (childPaths) {
      function ignoreFilePath (opts, filePath) {
        if (opts.ignore) {
          return opts.ignore.some(function (ignore) {
            if (typeof ignore === 'function') {
              return ignore(filePath)
            }
            return filePath.match(ignore)
          })
        }
        return false
      }

      if (opts.binaries) childPaths = childPaths.concat(opts.binaries)

      var args = [
        '--sign', opts.identity.hash || opts.identity.name,
        '--force'
      ]
      if (opts.keychain) {
        args.push('--keychain', opts.keychain)
      }
      if (opts.requirements) {
        args.push('--requirements', opts.requirements)
      }
      if (opts.timestamp) {
        args.push('--timestamp', opts.timestamp)
      }

      var promise
      if (opts.entitlements) {
        // Sign with entitlements
        promise = Promise.mapSeries(childPaths, function (filePath) {
          if (ignoreFilePath(opts, filePath)) {
            debuglog('Skipped... ' + filePath)
            return
          }
          debuglog('Signing... ' + filePath)
          return execFileAsync('codesign', args.concat('--entitlements', opts['entitlements-inherit'], filePath))
        })
          .then(function () {
            debuglog('Signing... ' + opts.app)
            return execFileAsync('codesign', args.concat('--entitlements', opts.entitlements, opts.app))
          })
      } else {
        // Otherwise normally
        promise = Promise.mapSeries(childPaths, function (filePath) {
          if (ignoreFilePath(opts, filePath)) {
            debuglog('Skipped... ' + filePath)
            return
          }
          debuglog('Signing... ' + filePath)
          return execFileAsync('codesign', args.concat(filePath))
        })
          .then(function () {
            debuglog('Signing... ' + opts.app)
            return execFileAsync('codesign', args.concat(opts.app))
          })
      }

      return promise
        .then(function () {
          // Verify code sign
          debuglog('Verifying...')
          var promise = verifySignApplicationAsync(opts)
            .then(function (result) {
              debuglog('Verified.')
            })

          // Check entitlements if applicable
          if (opts.entitlements) {
            promise = promise
              .then(function () {
                debuglog('Displaying entitlements...')
                return execFileAsync('codesign', [
                  '--display',
                  '--entitlements', ':-', // Write to standard output and strip off the blob header
                  opts.app
                ])
              })
              .then(function (result) {
                debuglog('Entitlements:', '\n',
                  result)
              })
          }

          return promise
        })
    })
}

/**
 * This function returns a promise signing the application.
 * @function
 * @param {mixed} opts - Options.
 * @returns {Promise} Promise.
 */
var signAsync = module.exports.signAsync = function (opts) {
  debuglog('electron-osx-sign@%s', pkg.version)
  return validateSignOptsAsync(opts)
    .then(function () {
      // Determine identity for signing
      var promise
      if (opts.identity) {
        debuglog('`identity` passed in arguments.')
        if (opts['identity-validation'] === false) {
          if (!(opts.identity instanceof Identity)) {
            opts.identity = new Identity(opts.identity)
          }
          return Promise.resolve()
        }
        promise = findIdentitiesAsync(opts, opts.identity)
      } else {
        debugwarn('No `identity` passed in arguments...')
        if (opts.platform === 'mas') {
          if (opts.type === 'distribution') {
            debuglog('Finding `3rd Party Mac Developer Application` certificate for signing app distribution in the Mac App Store...')
            promise = findIdentitiesAsync(opts, '3rd Party Mac Developer Application:')
          } else {
            debuglog('Finding `Mac Developer` certificate for signing app in development for the Mac App Store signing...')
            promise = findIdentitiesAsync(opts, 'Mac Developer:')
          }
        } else {
          debuglog('Finding `Developer ID Application` certificate for distribution outside the Mac App Store...')
          promise = findIdentitiesAsync(opts, 'Developer ID Application:')
        }
      }
      return promise
        .then(function (identities) {
          if (identities.length > 0) {
            // Identity(/ies) found
            if (identities.length > 1) {
              debugwarn('Multiple identities found, will use the first discovered.')
            } else {
              debuglog('Found 1 identity.')
            }
            opts.identity = identities[0]
          } else {
            // No identity found
            return Promise.reject(new Error('No identity found for signing.'))
          }
        })
    })
    .then(function () {
      // Determine entitlements for code signing
      var filePath
      if (opts.platform === 'mas') {
        // To sign apps for Mac App Store, an entitlements file is required, especially for app sandboxing (as well some other services).
        // Fallback entitlements for sandboxing by default: Note this may cause troubles while running an signed app due to missing keys special to the project.
        // Further reading: https://developer.apple.com/library/mac/documentation/Miscellaneous/Reference/EntitlementKeyReference/Chapters/EnablingAppSandbox.html
        if (!opts.entitlements) {
          filePath = path.join(__dirname, 'default.entitlements.mas.plist')
          debugwarn('No `entitlements` passed in arguments:', '\n',
            '* Sandbox entitlements are required for Mac App Store distribution, your codesign entitlements file is default to:', filePath)
          opts.entitlements = filePath
        }
        if (!opts['entitlements-inherit']) {
          filePath = path.join(__dirname, 'default.entitlements.mas.inherit.plist')
          debugwarn('No `entitlements-inherit` passed in arguments:', '\n',
            '* Sandbox entitlements file for enclosing app files is default to:', filePath)
          opts['entitlements-inherit'] = filePath
        }
      } else {
        // Not necessary to have entitlements for non Mac App Store distribution
        if (!opts.entitlements) {
          debugwarn('No `entitlements` passed in arguments:', '\n',
            '* Provide `entitlements` to specify entitlements file for codesign.')
        } else {
          // If entitlements is provided as a flag, fallback to default
          if (opts.entitlements === true) {
            filePath = path.join(__dirname, 'default.entitlements.darwin.plist')
            debugwarn('`entitlements` not specified in arguments:', '\n',
              '* Provide `entitlements` to specify entitlements file for codesign.', '\n',
              '* Sandbox entitlements file for enclosing app files is default to:', filePath)
            opts.entitlements = filePath
          }
          if (!opts['entitlements-inherit']) {
            filePath = path.join(__dirname, 'default.entitlements.darwin.inherit.plist')
            debugwarn('No `entitlements-inherit` passed in arguments:', '\n',
              '* Sandbox entitlements file for enclosing app files is default to:', filePath)
            opts['entitlements-inherit'] = filePath
          }
        }
      }
    })
    .then(function () {
      // Pre-sign operations
      var preSignOperations = []

      if (opts['pre-embed-provisioning-profile'] === false) {
        debugwarn('Pre-sign operation disabled for provisioning profile embedding:', '\n',
          '* Enable by setting `pre-embed-provisioning-profile` to `true`.')
      } else {
        debuglog('Pre-sign operation enabled for provisioning profile:', '\n',
          '* Disable by setting `pre-embed-previsioning-profile` to `false`.')
        preSignOperations.push(preEmbedProvisioningProfile)
      }

      if (opts['pre-auto-entitlements'] === false) {
        debugwarn('Pre-sign operation disabled for entitlements automation.')
      } else {
        debuglog('Pre-sign operation enabled for entitlements automation with versions >= `1.1.1`:', '\n',
          '* Disable by setting `pre-auto-entitlements` to `false`.')
        if (opts.entitlements && (!opts.version || compareVersion(opts.version, '1.1.1') >= 0)) {
          // Enable Mac App Store sandboxing without using temporary-exception, introduced in Electron v1.1.1. Relates to electron#5601
          preSignOperations.push(preAutoEntitlements)
        }
      }

      return Promise.mapSeries(preSignOperations, function (preSignOperation) {
        return preSignOperation(opts)
      })
    })
    .then(function () {
      debuglog('Signing application...', '\n',
        '> Application:', opts.app, '\n',
        '> Platform:', opts.platform, '\n',
        '> Entitlements:', opts.entitlements, '\n',
        '> Child entitlements:', opts['entitlements-inherit'], '\n',
        '> Additional binaries:', opts.binaries, '\n',
        '> Identity:', opts.identity)
      return signApplicationAsync(opts)
    })
    .then(function () {
      // Post-sign operations
      debuglog('Application signed.')
    })
}

/**
 * This function is a normal callback implementation.
 * @function
 * @param {Object} opts - Options.
 * @param {RequestCallback} cb - Callback.
 */
module.exports.sign = function (opts, cb) {
  signAsync(opts)
    .then(function () {
      debuglog('Application signed: ' + opts.app)
      if (cb) cb()
    })
    .catch(function (err) {
      debuglog('Sign failed:')
      if (err.message) debuglog(err.message)
      else if (err.stack) debuglog(err.stack)
      else debuglog(err)
      if (cb) cb(err)
    })
}
<|endoftext|>


<commit_before>var fs = require('fs');
var signature = require('./lib/signature');

var cert = fs.readFileSync('cert.p12');
var data = fs.readFileSync('data.bin');
var sig = fs.readFileSync('signature.bin');

signature.p12toPEM(cert, '', function(err, pem) {
    if (err) throw err;

    var sig = signature.sign(data, pem)
    console.warn(sig.toString('base64'));
    console.warn(signature.verify(data, sig, pem));
});
<commit_msg>remove sign test program<commit_after><|endoftext|>


<commit_before>'use strict'
var insp = require('./inspect')
var colors = require('ansicolors')

// only recurse into arrays if they contain actual specs or objects
function needRecurseArray(arr) {
  for (var i = 0; i < arr.length; i++) {
    var el = arr[i]
    if (typeof el !== 'number' && typeof el !== 'string' && el != null) return true
  }
  return false
}

function needRecurse(spec) {
  if (Array.isArray(spec)) return needRecurseArray(spec)
  var keys = Object.keys(spec)
  if (keys.length === 0) return false

  // if no spok functions are part of the spec, we could use deepEqual, but
  // we get a more fine grained output if we recurse even if the spec values
  // are constants
  return true
}

/**
 * Checks the given specifications against the object.
 *
 * When the tests are run the **actual** values are printed to verify visually while
 * each provided specification is validated and a test failure caused if one of them fails.
 *
 * @name spok
 * @function
 * @param {Object} t which has assertion functions `equal` and `deepEqual` (to compare objects) - use
 * **tap**, **tape**, **assert** or any other library that has those and thus is compatible
 * @param {Object} obj the object to verify the specifications against
 * @param {Object} specifications the specifications to verify
 */
module.exports = function spok(t, obj, specifications, prefix) {
  prefix = typeof prefix === 'string' ? prefix : ''

  function check(k) {
    if (k === '$topic') return

    var spec = specifications[k]
    var val = obj[k]

    var msg = prefix + k + ' = ' + insp(val, spok.color)
    if (spec != null) {
      if (spec.$spec == null && spec.name != null && spec.name.length > 0) {
        spec.$spec = spec.name
      }
      var ps = !!spok.printSpec && spec.$spec != null
      var pd = !!spok.printDescription && spec.$description != null
      if (ps) msg += '  ' + colors.brightBlack('satisfies: ' + spec.$spec)
      if (pd) msg += '  ' + colors.brightBlack(spec.$description)
    }

    switch (typeof spec) {
      case 'function': return t.equal(!!spec(val), true, msg)
      case 'boolean':
      case 'number':
      case 'string':
        return t.equal(val, spec, msg)
      case 'object':
        if (spec == null) return t.equal(val, spec, msg)
        if (!needRecurse(spec)) return t.deepEqual(val, spec, msg)

        if (spec.$topic == null) {
          var rootTopic = specifications.$topic != null ? specifications.$topic + '.' : ''
          spec.$topic = rootTopic + k
        }
        return spok(t, val, spec, prefix)
      default:
        throw new Error('Type ' + typeof spec + ' not yet handled. Please submit a PR')
    }
  }

  if (specifications.$topic) {
    // print indicator that a specific spec started being evaluated
    t.equal(1, 1, prefix + 'spok: ' + specifications.$topic)
    prefix = prefix + '·· '
  }

  // check all specs
  Object.keys(specifications).forEach(check)

  // provide confirmation that spec is done
  if (spok.sound) require('child_process').execSync('say spokie dokie -v Vicki -r 600')
}

var spok = module.exports

spok.printSpec = true
spok.printDescription = false
spok.sound = false
spok.color = true

/**
 * Specififies that the given number is within the given range, i.e. `min<= x <=max`.
 *
 * ```js
 * var spec = {
 *  x: spok.range(1, 2)   // specifies that x should be >=1 and <=2
 * }
 * ```
 *
 * @name spok.range
 * @function
 * @param {Number} min minimum
 * @param {Number} max maximum
 */
spok.range = function range(min, max) {
  function checkRange(x) {
    return spok.number(x) && min <= x && x <= max
  }
  checkRange.$spec = 'spok.range(' + min + ', ' + max + ')'
  checkRange.$description = min + ' <= value <= ' + max
  return checkRange
}

/**
 * Specififies that a number is greater than the given criteria.
 *
 * ```js
 * var spec = {
 *  x: spok.gt(1)  // specifies that x should be >1
 * }
 * ```
 *
 * @name spok.gt
 * @function
 * @param {Number} n criteria
 */
spok.gt = function gt(n) {
  function checkgt(x) {
    return spok.number(x) && x > n
  }
  checkgt.$spec = 'spok.gt(' + n + ')'
  checkgt.$description = 'value > ' + n
  return checkgt
}

/**
 * Specififies that a number is greater or equal the given criteria.
 *
 * ```js
 * var spec = {
 *  x: spok.ge(1)  // specifies that x should be >=1
 * }
 * ```
 *
 * @name spok.ge
 * @function
 * @param {Number} n criteria
 */
spok.ge = function ge(n) {
  function checkge(x) {
    return spok.number(x) && x >= n
  }
  checkge.$spec = 'spok.ge(' + n + ')'
  checkge.$description = 'value >= ' + n
  return checkge
}

/**
 * Specififies that a number is less than the given criteria.
 *
 * ```js
 * var spec = {
 *  x: spok.lt(1)  // specifies that x should be < 1
 * }
 * ```
 *
 * @name spok.lt
 * @function
 * @param {Number} n criteria
 */
spok.lt = function lt(n) {
  function checklt(x) {
    return spok.number(x) && x < n
  }
  checklt.$spec = 'spok.lt(' + n + ')'
  checklt.$description = 'value < ' + n
  return checklt
}

/**
 * Specififies that a number is less or equal the given criteria.
 *
 * ```js
 * var spec = {
 *  x: spok.le(1)  // specifies that x should be <=1
 * }
 * ```
 *
 * @name spok.le
 * @function
 * @param {Number} n criteria
 */
spok.le = function le(n) {
  function checkle(x) {
    return spok.number(x) && x <= n
  }
  checkle.$spec = 'spok.le(' + n + ')'
  checkle.$description = 'value <= ' + n
  return checkle
}

/**
 * Specifies that the value is not equal another.
 *
 * ```js
 * var spec = {
 *  x: spok.ne(undefined)  // specifies that x should be defined
 * }
 * ```
 *
 * @name spok.ne
 * @function
 * @param {Any} value criteria
 */
spok.ne = function ne(value) {
  function checkne(x) {
    return value !== x
  }
  checkne.$spec = 'spok.ne(' + value + ')'
  checkne.$description = 'value !== ' + value
  return checkne
}

/**
 * Specifies that the value is greater than zero
 *
 * ```js
 * var spec = {
 *   x: spok.gtz
 * }
 * ```
 * @name spok.gtz
 * @function
 */
spok.gtz = spok.gt(0)
spok.gtz.$spec = 'spok.gtz'
spok.gtz.$description = 'value > 0'

/**
 * Specifies that the value is greater or equal zero
 *
 * ```js
 * var spec = {
 *   x: spok.gez
 * }
 * ```
 * @name spok.gez
 * @function
 */
spok.gez = spok.ge(0)
spok.gez.$spec = 'spok.gez'
spok.gez.$description = 'value >= 0'

/**
 * Specifies that the value is less than zero
 *
 * ```js
 * var spec = {
 *   x: spok.ltz
 * }
 * ```
 * @name spok.ltz
 * @function
 */
spok.ltz = spok.lt(0)
spok.ltz.$spec = 'spok.ltz'
spok.ltz.$description = 'value < 0'

/**
 * Specifies that the value is less or equal zero
 *
 * ```js
 * var spec = {
 *   x: spok.lez
 * }
 * ```
 * @name spok.lez
 * @function
 */
spok.lez = spok.le(0)
spok.lez.$spec = 'spok.lez'
spok.lez.$description = 'value <= 0'

/**
 * Specifies that the input is of a given type.
 *
 * ```js
 * var spec = {
 *  x: spok.type('number')  // specifies that x should be a Number
 * }
 * ```
 *
 * @name spok.type
 * @function
 * @param {String} t expected type
 */
spok.type = function type(t) {
  function checkType(x) {
    return typeof x === t
  }
  checkType.$spec = 'spok.type(' + t + ')'
  checkType.$description = 'value is of type ' + t
  return checkType
}

/**
 * Specifies that the input is an array.
 *
 * ```js
 * var spec = {
 *  x: spok.array  // specifies that x should be an Array
 * }
 * ```
 *
 * @name spok.array
 * @function
 */
spok.array = function array(x) {
  return Array.isArray(x)
}
spok.array.$spec = 'spok.array'
spok.array.$description = 'values ia an Array'

/**
 * Specifies that the input is an array with a specific number of elements
 *
 * var spec = {
 *  x: spok.arrayElements(2)  // specifies that x should be an Array witn 2 elements
 * }
 *
 * @name spok.arrayElements
 * @function
 * @param {Number} n number of elements
 */
spok.arrayElements = function arrayElements(n) {
  function checkCount(array) {
    if (array == null) {
      return console.error('Expected %d, but found array to be null.', n)
    }
    var pass = spok.array(array) && array.length === n
    if (!pass) console.error('Expected %d, but found %d elements.', n, array.length)
    return pass
  }
  checkCount.$spec = 'spok.arrayElements(' + n + ')'
  checkCount.$description = 'array has ' + n + ' element(s)'
  return checkCount
}

/**
 * Specifies that the input of type number and `isNaN(x)` returns `false`.
 *
 * ```js
 * var spec = {
 *  x: spok.number  // specifies that x should be a Number
 * }
 * ```
 *
 * @name spok.number
 * @function
 */
spok.number = function number(x) {
  return typeof x === 'number' && !isNaN(x)
}
spok.number.$spec = 'spok.number'
spok.number.$description = 'value is a number'

/**
 * Specifies that the input is a string.
 *
 * ```
 * var spec = {
 *   x: spok.string  // specifies that x should be a String
 * }
 * ```
 *
 * @name spok.string
 * @function
 */
spok.string = spok.type('string')
spok.string.$spec = 'spok.string'
spok.string.$description = 'value is a string'

/**
 * Specifies that the input is a function.
 *
 * ```
 * var spec = {
 *   x: spok.function  // specifies that x should be a function
 * }
 * ```
 *
 * @name spok.function
 * @function
 */
spok.function = spok.type('function')
spok.function.$spec = 'spok.function'
spok.function.$description = 'value is a function'

/**
 * Specifies that the input is an object and it is not `null`.
 *
 * ```js
 * var spec = {
 *  x: spok.definedObject  // specifies that x is a non-null object
 * }
 * ```
 *
 * @name spok.definedObject
 * @function
 */
spok.definedObject = function definedObject(x) {
  return x !== null && typeof x === 'object'
}
spok.definedObject.$spec = 'spok.definedObject'
spok.definedObject.$description = 'value is defined and of type object'

/**
 * Specifies that the string starts with the specified substring.
 *
 * **NOTE**: only available with node.js which has an ES6 `startsWith` function
 *
 * ```js
 * var spec = {
 *  x: spok.startsWith('hello')  // specifies that x should start with 'hello'
 * }
 * ```
 *
 * @name spok.startsWith
 * @function
 * @param {String} what substring the given string should start with
 */
spok.startsWith = function startsWith(what) {
  function checkStartsWith(x) {
    var res = x && typeof x.startsWith === 'function' && x.startsWith(what)
    if (!res) console.error('"%s" does not start with "%s"', x, what)
    return res
  }
  checkStartsWith.$spec = 'spok.startsWith(' + what + ')'
  checkStartsWith.$description = 'string starts with ' + what
  return checkStartsWith
}

/**
 * Specifies that the string ends with the specified substring.
 *
 * **NOTE**: only available with node.js which has an ES6 `endsWith` function
 *
 * ```js
 * var spec = {
 *  x: spok.endsWith('hello')  // specifies that x should start with 'hello'
 * }
 * ```
 *
 * @name spok.endsWith
 * @function
 * @param {String} what substring the given string should start with
 */
spok.endsWith = function endsWith(what) {
  function checkEndsWith(x) {
    var res = x && typeof x.endsWith === 'function' && x.endsWith(what)
    if (!res) console.error('"%s" does not start with "%s"', x, what)
    return res
  }
  checkEndsWith.$spec = 'spok.endsWith(' + what + ')'
  checkEndsWith.$description = 'string ends with ' + what
  return checkEndsWith
}

/**
 * Specifies that the string needs to match the given regular expression.
 *
 * ```js
 * var spec = {
 *   x: spok.test(/hello$/) // specifies that x should match /hello$/
 * }
 * ```
 *
 * @name spok.test
 * @function
 * @param {RegExp} regex regular expression against which the string is checked via `test`
 */
spok.test = function test(regex) {
  function checkTest(x) {
    var res = regex.test(x)
    if (!res) console.error('"%s" does not match \n%s', x, regex.toString())
    return res
  }
  var s = regex.toString()
  checkTest.$spec = 'spok.test(' + s + ')'
  checkTest.$description = 'value matches ' + s + ' regex'
  return checkTest
}

/**
 * Specifies that a value is defined, i.e. it is neither `null` nor `undefined`.
 *
 * ```js
 * var spec = {
 *   x: spok.defined
 * }
 * ```
 *
 * @name spok.defined
 * @function
 */
spok.defined = function defined(x) {
  return x != null
}
spok.defined.$spec = 'spok.defined'
spok.defined.$description = 'value is neither null nor undefined'

/**
 * Specifies that a value is notDefined, i.e. it is either `null` or `notDefined`.
 *
 * ```js
 * var spec = {
 *   x: spok.notDefined
 * }
 * ```
 *
 * @name spok.notDefined
 * @function
 */
spok.notDefined = function notDefined(x) {
  return x == null
}
spok.notDefined.$spec = 'spok.notDefined'
spok.notDefined.$description = 'value is either null or undefined'
<commit_msg>fix: ignoring $spec and $description during check<commit_after>'use strict'
var insp = require('./inspect')
var colors = require('ansicolors')

// only recurse into arrays if they contain actual specs or objects
function needRecurseArray(arr) {
  for (var i = 0; i < arr.length; i++) {
    var el = arr[i]
    if (typeof el !== 'number' && typeof el !== 'string' && el != null) return true
  }
  return false
}

function needRecurse(spec) {
  if (Array.isArray(spec)) return needRecurseArray(spec)
  var keys = Object.keys(spec)
  if (keys.length === 0) return false

  // if no spok functions are part of the spec, we could use deepEqual, but
  // we get a more fine grained output if we recurse even if the spec values
  // are constants
  return true
}

/**
 * Checks the given specifications against the object.
 *
 * When the tests are run the **actual** values are printed to verify visually while
 * each provided specification is validated and a test failure caused if one of them fails.
 *
 * @name spok
 * @function
 * @param {Object} t which has assertion functions `equal` and `deepEqual` (to compare objects) - use
 * **tap**, **tape**, **assert** or any other library that has those and thus is compatible
 * @param {Object} obj the object to verify the specifications against
 * @param {Object} specifications the specifications to verify
 */
module.exports = function spok(t, obj, specifications, prefix) {
  prefix = typeof prefix === 'string' ? prefix : ''

  function check(k) {
    if (k === '$topic' || k === '$spec' || k === '$description') return

    var spec = specifications[k]
    var val = obj[k]

    var msg = prefix + k + ' = ' + insp(val, spok.color)
    if (spec != null) {
      if (spec.$spec == null && spec.name != null && spec.name.length > 0) {
        spec.$spec = spec.name
      }
      var ps = !!spok.printSpec && spec.$spec != null
      var pd = !!spok.printDescription && spec.$description != null
      if (ps) msg += '  ' + colors.brightBlack('satisfies: ' + spec.$spec)
      if (pd) msg += '  ' + colors.brightBlack(spec.$description)
    }

    switch (typeof spec) {
      case 'function': return t.equal(!!spec(val), true, msg)
      case 'boolean':
      case 'number':
      case 'string':
        return t.equal(val, spec, msg)
      case 'object':
        if (spec == null) return t.equal(val, spec, msg)
        if (!needRecurse(spec)) return t.deepEqual(val, spec, msg)

        if (spec.$topic == null) {
          var rootTopic = specifications.$topic != null ? specifications.$topic + '.' : ''
          spec.$topic = rootTopic + k
        }
        return spok(t, val, spec, prefix)
      default:
        throw new Error('Type ' + typeof spec + ' not yet handled. Please submit a PR')
    }
  }

  if (specifications.$topic) {
    // print indicator that a specific spec started being evaluated
    t.equal(1, 1, prefix + 'spok: ' + specifications.$topic)
    prefix = prefix + '·· '
  }

  // check all specs
  Object.keys(specifications).forEach(check)

  // provide confirmation that spec is done
  if (spok.sound) require('child_process').execSync('say spokie dokie -v Vicki -r 600')
}

var spok = module.exports

spok.printSpec = true
spok.printDescription = false
spok.sound = false
spok.color = true

/**
 * Specififies that the given number is within the given range, i.e. `min<= x <=max`.
 *
 * ```js
 * var spec = {
 *  x: spok.range(1, 2)   // specifies that x should be >=1 and <=2
 * }
 * ```
 *
 * @name spok.range
 * @function
 * @param {Number} min minimum
 * @param {Number} max maximum
 */
spok.range = function range(min, max) {
  function checkRange(x) {
    return spok.number(x) && min <= x && x <= max
  }
  checkRange.$spec = 'spok.range(' + min + ', ' + max + ')'
  checkRange.$description = min + ' <= value <= ' + max
  return checkRange
}

/**
 * Specififies that a number is greater than the given criteria.
 *
 * ```js
 * var spec = {
 *  x: spok.gt(1)  // specifies that x should be >1
 * }
 * ```
 *
 * @name spok.gt
 * @function
 * @param {Number} n criteria
 */
spok.gt = function gt(n) {
  function checkgt(x) {
    return spok.number(x) && x > n
  }
  checkgt.$spec = 'spok.gt(' + n + ')'
  checkgt.$description = 'value > ' + n
  return checkgt
}

/**
 * Specififies that a number is greater or equal the given criteria.
 *
 * ```js
 * var spec = {
 *  x: spok.ge(1)  // specifies that x should be >=1
 * }
 * ```
 *
 * @name spok.ge
 * @function
 * @param {Number} n criteria
 */
spok.ge = function ge(n) {
  function checkge(x) {
    return spok.number(x) && x >= n
  }
  checkge.$spec = 'spok.ge(' + n + ')'
  checkge.$description = 'value >= ' + n
  return checkge
}

/**
 * Specififies that a number is less than the given criteria.
 *
 * ```js
 * var spec = {
 *  x: spok.lt(1)  // specifies that x should be < 1
 * }
 * ```
 *
 * @name spok.lt
 * @function
 * @param {Number} n criteria
 */
spok.lt = function lt(n) {
  function checklt(x) {
    return spok.number(x) && x < n
  }
  checklt.$spec = 'spok.lt(' + n + ')'
  checklt.$description = 'value < ' + n
  return checklt
}

/**
 * Specififies that a number is less or equal the given criteria.
 *
 * ```js
 * var spec = {
 *  x: spok.le(1)  // specifies that x should be <=1
 * }
 * ```
 *
 * @name spok.le
 * @function
 * @param {Number} n criteria
 */
spok.le = function le(n) {
  function checkle(x) {
    return spok.number(x) && x <= n
  }
  checkle.$spec = 'spok.le(' + n + ')'
  checkle.$description = 'value <= ' + n
  return checkle
}

/**
 * Specifies that the value is not equal another.
 *
 * ```js
 * var spec = {
 *  x: spok.ne(undefined)  // specifies that x should be defined
 * }
 * ```
 *
 * @name spok.ne
 * @function
 * @param {Any} value criteria
 */
spok.ne = function ne(value) {
  function checkne(x) {
    return value !== x
  }
  checkne.$spec = 'spok.ne(' + value + ')'
  checkne.$description = 'value !== ' + value
  return checkne
}

/**
 * Specifies that the value is greater than zero
 *
 * ```js
 * var spec = {
 *   x: spok.gtz
 * }
 * ```
 * @name spok.gtz
 * @function
 */
spok.gtz = spok.gt(0)
spok.gtz.$spec = 'spok.gtz'
spok.gtz.$description = 'value > 0'

/**
 * Specifies that the value is greater or equal zero
 *
 * ```js
 * var spec = {
 *   x: spok.gez
 * }
 * ```
 * @name spok.gez
 * @function
 */
spok.gez = spok.ge(0)
spok.gez.$spec = 'spok.gez'
spok.gez.$description = 'value >= 0'

/**
 * Specifies that the value is less than zero
 *
 * ```js
 * var spec = {
 *   x: spok.ltz
 * }
 * ```
 * @name spok.ltz
 * @function
 */
spok.ltz = spok.lt(0)
spok.ltz.$spec = 'spok.ltz'
spok.ltz.$description = 'value < 0'

/**
 * Specifies that the value is less or equal zero
 *
 * ```js
 * var spec = {
 *   x: spok.lez
 * }
 * ```
 * @name spok.lez
 * @function
 */
spok.lez = spok.le(0)
spok.lez.$spec = 'spok.lez'
spok.lez.$description = 'value <= 0'

/**
 * Specifies that the input is of a given type.
 *
 * ```js
 * var spec = {
 *  x: spok.type('number')  // specifies that x should be a Number
 * }
 * ```
 *
 * @name spok.type
 * @function
 * @param {String} t expected type
 */
spok.type = function type(t) {
  function checkType(x) {
    return typeof x === t
  }
  checkType.$spec = 'spok.type(' + t + ')'
  checkType.$description = 'value is of type ' + t
  return checkType
}

/**
 * Specifies that the input is an array.
 *
 * ```js
 * var spec = {
 *  x: spok.array  // specifies that x should be an Array
 * }
 * ```
 *
 * @name spok.array
 * @function
 */
spok.array = function array(x) {
  return Array.isArray(x)
}
spok.array.$spec = 'spok.array'
spok.array.$description = 'values ia an Array'

/**
 * Specifies that the input is an array with a specific number of elements
 *
 * var spec = {
 *  x: spok.arrayElements(2)  // specifies that x should be an Array witn 2 elements
 * }
 *
 * @name spok.arrayElements
 * @function
 * @param {Number} n number of elements
 */
spok.arrayElements = function arrayElements(n) {
  function checkCount(array) {
    if (array == null) {
      return console.error('Expected %d, but found array to be null.', n)
    }
    var pass = spok.array(array) && array.length === n
    if (!pass) console.error('Expected %d, but found %d elements.', n, array.length)
    return pass
  }
  checkCount.$spec = 'spok.arrayElements(' + n + ')'
  checkCount.$description = 'array has ' + n + ' element(s)'
  return checkCount
}

/**
 * Specifies that the input of type number and `isNaN(x)` returns `false`.
 *
 * ```js
 * var spec = {
 *  x: spok.number  // specifies that x should be a Number
 * }
 * ```
 *
 * @name spok.number
 * @function
 */
spok.number = function number(x) {
  return typeof x === 'number' && !isNaN(x)
}
spok.number.$spec = 'spok.number'
spok.number.$description = 'value is a number'

/**
 * Specifies that the input is a string.
 *
 * ```
 * var spec = {
 *   x: spok.string  // specifies that x should be a String
 * }
 * ```
 *
 * @name spok.string
 * @function
 */
spok.string = spok.type('string')
spok.string.$spec = 'spok.string'
spok.string.$description = 'value is a string'

/**
 * Specifies that the input is a function.
 *
 * ```
 * var spec = {
 *   x: spok.function  // specifies that x should be a function
 * }
 * ```
 *
 * @name spok.function
 * @function
 */
spok.function = spok.type('function')
spok.function.$spec = 'spok.function'
spok.function.$description = 'value is a function'

/**
 * Specifies that the input is an object and it is not `null`.
 *
 * ```js
 * var spec = {
 *  x: spok.definedObject  // specifies that x is a non-null object
 * }
 * ```
 *
 * @name spok.definedObject
 * @function
 */
spok.definedObject = function definedObject(x) {
  return x !== null && typeof x === 'object'
}
spok.definedObject.$spec = 'spok.definedObject'
spok.definedObject.$description = 'value is defined and of type object'

/**
 * Specifies that the string starts with the specified substring.
 *
 * **NOTE**: only available with node.js which has an ES6 `startsWith` function
 *
 * ```js
 * var spec = {
 *  x: spok.startsWith('hello')  // specifies that x should start with 'hello'
 * }
 * ```
 *
 * @name spok.startsWith
 * @function
 * @param {String} what substring the given string should start with
 */
spok.startsWith = function startsWith(what) {
  function checkStartsWith(x) {
    var res = x && typeof x.startsWith === 'function' && x.startsWith(what)
    if (!res) console.error('"%s" does not start with "%s"', x, what)
    return res
  }
  checkStartsWith.$spec = 'spok.startsWith(' + what + ')'
  checkStartsWith.$description = 'string starts with ' + what
  return checkStartsWith
}

/**
 * Specifies that the string ends with the specified substring.
 *
 * **NOTE**: only available with node.js which has an ES6 `endsWith` function
 *
 * ```js
 * var spec = {
 *  x: spok.endsWith('hello')  // specifies that x should start with 'hello'
 * }
 * ```
 *
 * @name spok.endsWith
 * @function
 * @param {String} what substring the given string should start with
 */
spok.endsWith = function endsWith(what) {
  function checkEndsWith(x) {
    var res = x && typeof x.endsWith === 'function' && x.endsWith(what)
    if (!res) console.error('"%s" does not start with "%s"', x, what)
    return res
  }
  checkEndsWith.$spec = 'spok.endsWith(' + what + ')'
  checkEndsWith.$description = 'string ends with ' + what
  return checkEndsWith
}

/**
 * Specifies that the string needs to match the given regular expression.
 *
 * ```js
 * var spec = {
 *   x: spok.test(/hello$/) // specifies that x should match /hello$/
 * }
 * ```
 *
 * @name spok.test
 * @function
 * @param {RegExp} regex regular expression against which the string is checked via `test`
 */
spok.test = function test(regex) {
  function checkTest(x) {
    var res = regex.test(x)
    if (!res) console.error('"%s" does not match \n%s', x, regex.toString())
    return res
  }
  var s = regex.toString()
  checkTest.$spec = 'spok.test(' + s + ')'
  checkTest.$description = 'value matches ' + s + ' regex'
  return checkTest
}

/**
 * Specifies that a value is defined, i.e. it is neither `null` nor `undefined`.
 *
 * ```js
 * var spec = {
 *   x: spok.defined
 * }
 * ```
 *
 * @name spok.defined
 * @function
 */
spok.defined = function defined(x) {
  return x != null
}
spok.defined.$spec = 'spok.defined'
spok.defined.$description = 'value is neither null nor undefined'

/**
 * Specifies that a value is notDefined, i.e. it is either `null` or `notDefined`.
 *
 * ```js
 * var spec = {
 *   x: spok.notDefined
 * }
 * ```
 *
 * @name spok.notDefined
 * @function
 */
spok.notDefined = function notDefined(x) {
  return x == null
}
spok.notDefined.$spec = 'spok.notDefined'
spok.notDefined.$description = 'value is either null or undefined'
<|endoftext|>


<commit_before>'use strict';

const Srtr = function() {};

/**
 * Fallback sort predicate. Perform ternary comparsion of numbers.
 *
 * TODO: Explain all this.
 * TODO: Document spaceship (<=>) operator.
 *
 * @example
 *
 *      2 <=> 3 // -1
 *      3 <=> 3 //  0
 *      3 <=> 2 //  1
 *
 * @example
 *
 *      10 - 7  //  3
 *      10 - 10 //  0
 *      10 - 13 // -3
 *
 * @private
 * @see https://en.wikipedia.org/wiki/Three-way_comparison
 * @param {number} value - Current value in collection.
 * @param {number} comparison - Comparison value in collection.
 * @return {number} - Next value subtracted from current.
 */

function spaceship(value, comparison) {
    return value < comparison ? -1 : value === comparison ? 0 : 1;
}

/**
 * Use recursive quicksort to reorder a collection.
 *
 * TODO: Document this for newbies.
 *
 * @public
 * @see https://en.wikipedia.org/wiki/Quicksort
 * @param {array} collection - Unsorted collecton.
 * @return {array} collection - Sorted collecton.
 */

Srtr.prototype.quicksort = function(collection, predicate = spaceship) {
    /* eslint no-magic-numbers: "off" */
    if (collection.length < 2) {
        return collection;
    }

    const pivot = collection[collection.length >> 1];

    return [
        ...this.quicksort(collection.filter(element => predicate(element, pivot) < 0), predicate),
        ...collection.filter(element => predicate(element, pivot) === 0),
        ...this.quicksort(collection.filter(element => predicate(element, pivot) > 0), predicate)
    ];
};

/**
 * Use iterative bubble sort to reorder a collection.
 *
 * TODO: Document this for newbies.
 *
 * @public
 * @see https://en.wikipedia.org/wiki/Bubble_sort
 * @param {array} collection - Unsorted collection
 * @param {function} predicate - Predicate function to test values.
 * @return {array} collection - Sorted collection.
 */

Srtr.prototype.bubblesort = function(collection, predicate = spaceship) {
    collection = collection.slice();

    for (let index = 0; index < collection.length - 1; index++) {
        if (parseInt(predicate(collection[index], collection[index + 1])) > 0) {
            [collection[index], collection[index + 1]] = [collection[index + 1], collection[index]];
            index = 0;
        }
    }

    return collection;
};

module.exports = Object.create(Srtr.prototype);
<commit_msg>Added check for collection size.<commit_after>'use strict';

const Srtr = function() {};

/**
 * Fallback sort predicate. Perform ternary comparsion of numbers.
 *
 * TODO: Explain all this.
 * TODO: Document spaceship (<=>) operator.
 *
 * @example
 *
 *      2 <=> 3 // -1
 *      3 <=> 3 //  0
 *      3 <=> 2 //  1
 *
 * @example
 *
 *      10 - 7  //  3
 *      10 - 10 //  0
 *      10 - 13 // -3
 *
 * @private
 * @see https://en.wikipedia.org/wiki/Three-way_comparison
 * @see https://en.wikipedia.org/wiki/%3F:
 * @param {number} value - Current value in collection.
 * @param {number} comparison - Comparison value in collection.
 * @return {number} - Next value subtracted from current.
 */

function spaceship(value, comparison) {
    return value < comparison ? -1 : value === comparison ? 0 : 1;
}

/**
 * Use recursive quicksort to reorder a collection.
 *
 * TODO: Document this for newbies.
 *
 * @public
 * @see https://en.wikipedia.org/wiki/Quicksort
 * @param {array} collection - Unsorted collecton.
 * @return {array} collection - Sorted collecton.
 */

Srtr.prototype.quicksort = function(collection, predicate = spaceship) {
    /* eslint no-magic-numbers: "off" */
    if (collection.length < 2) {
        return collection;
    }

    const pivot = collection[collection.length >> 1];

    return [
        ...this.quicksort(collection.filter(element => predicate(element, pivot) < 0), predicate),
        ...collection.filter(element => predicate(element, pivot) === 0),
        ...this.quicksort(collection.filter(element => predicate(element, pivot) > 0), predicate)
    ];
};

/**
 * Use iterative bubble sort to reorder a collection.
 *
 * TODO: Document this for newbies.
 *
 * @public
 * @see https://en.wikipedia.org/wiki/Bubble_sort
 * @param {array} collection - Unsorted collection
 * @param {function} predicate - Predicate function to test values.
 * @return {array} collection - Sorted collection.
 */

Srtr.prototype.bubblesort = function(collection, predicate = spaceship) {
    if (collection.length < 2) {
        return collection;
    }

    collection = collection.slice();

    for (let index = 0; index < collection.length - 1; index++) {
        if (parseInt(predicate(collection[index], collection[index + 1])) > 0) {
            [collection[index], collection[index + 1]] = [collection[index + 1], collection[index]];
            index = 0;
        }
    }

    return collection;
};

module.exports = Object.create(Srtr.prototype);
<|endoftext|>


<commit_before>define(
  'ephox.darwin.keyboard.Retries',

  [
    'ephox.darwin.keyboard.Rectangles',
    'ephox.fussy.api.Point',
    'ephox.perhaps.Option',
    'global!Math'
  ],

  function (Rectangles, Point, Option, Math) {
    var JUMP_SIZE = 5;
    /*
     * This isn't right ... but let's just hook it up first.
     */

    var mogel = function (win, guess, guessBox, caret) {
      // We haven't dropped vertically, so we need to look down and try again.
      if (guessBox.bottom === caret.bottom) return webkitAgain(win, { left: caret.left, bottom: caret.bottom + JUMP_SIZE });
      // The returned guessBox based on the guess actually doesn't include the initial caret. So we search again
      // where we adjust the caret so that it is inside the returned guessBox. This means that the offset calculation
      // will be more accurate.
      else if (guessBox.top > caret.bottom) return Point.find(win, caret.left, guessBox.top + 1).orThunk(function () { return Option.some(guess); });
      // We couldn't find any better way to improve our guess.
      else return Option.some(guess);
    };

     // In Firefox, it isn't giving you the next element ... it's giving you the current element. So if the box of where it gives you has the same y value
    // minus some error, try again with a bigger jump.
    var firefoxAgain = function (win, caret, _adjustedCaret) {
      var adjustedCaret = _adjustedCaret !== undefined ? _adjustedCaret : caret;
      return Point.find(win, adjustedCaret.left, adjustedCaret.bottom + JUMP_SIZE).bind(function (pt) {
        return pt.start().fold(Option.none, function (e, eo) {
          console.log('e: ', e.dom());
          return Rectangles.getBox(win, e, eo).bind(function (box) {
            if (Math.abs(box.top - caret.top) < (2 * JUMP_SIZE)) {
              return firefoxAgain(win, caret, { left: adjustedCaret.left, bottom: adjustedCaret.bottom + JUMP_SIZE, top: adjustedCaret.top + JUMP_SIZE }).orThunk(function () {
                return Option.some(pt);
              });
            }

            return mogel(win, pt, box, caret);
          });
        }, Option.none);
      });
    };

    // The process is that you incrementally go down ... if you find the next element, but your top is not at that element's bounding rect.
    // then try again with the same x but the box's y
    var webkitAgain = function (win, caret) {
      return Point.find(win, caret.left, caret.bottom + JUMP_SIZE).bind(function (guess) {
        return guess.start().fold(Option.none, function (e, eo) {
          return Rectangles.getBox(win, e, eo).bind(function (guessBox) {
            return mogel(win, guess, guessBox, caret);
          });
        }, Option.none);
      });
    };

    var ieAgain = function (win, caret) {
      return Point.find(win, caret.left, caret.bottom + 5);
    };

    return {
      webkitAgain: webkitAgain,
      firefoxAgain: firefoxAgain,
      ieAgain: ieAgain
    };
  }
);<commit_msg>TBIO-2087: more cleanup<commit_after>define(
  'ephox.darwin.keyboard.Retries',

  [
    'ephox.darwin.keyboard.Rectangles',
    'ephox.fussy.api.Point',
    'ephox.perhaps.Option',
    'global!Math'
  ],

  function (Rectangles, Point, Option, Math) {
    var JUMP_SIZE = 5;
    /*
     * This isn't right ... but let's just hook it up first.
     */

    var mogel = function (win, guess, guessBox, caret) {
      // We haven't dropped vertically, so we need to look down and try again.
      if (guessBox.bottom === caret.bottom) return webkitAgain(win, { left: caret.left, bottom: caret.bottom + JUMP_SIZE });
      // The returned guessBox based on the guess actually doesn't include the initial caret. So we search again
      // where we adjust the caret so that it is inside the returned guessBox. This means that the offset calculation
      // will be more accurate.
      else if (guessBox.top > caret.bottom) return Point.find(win, caret.left, guessBox.top + 1).orThunk(function () { return Option.some(guess); });
      // We couldn't find any better way to improve our guess.
      else return Option.some(guess);
    };

     // In Firefox, it isn't giving you the next element ... it's giving you the current element. So if the box of where it gives you has the same y value
    // minus some error, try again with a bigger jump.
    var firefoxAgain = function (win, caret, _adjustedCaret) {
      var adjustedCaret = _adjustedCaret !== undefined ? _adjustedCaret : caret;
      return Point.find(win, adjustedCaret.left, adjustedCaret.bottom + JUMP_SIZE).bind(function (guess) {
        return guess.start().fold(Option.none, function (e, eo) {
          console.log('e: ', e.dom());
          return Rectangles.getBox(win, e, eo).bind(function (guessBox) {
            if (guessBox.bottom === caret.bottom) {
              return firefoxAgain(win, caret, { left: adjustedCaret.left, bottom: adjustedCaret.bottom + JUMP_SIZE, top: adjustedCaret.top + JUMP_SIZE }).orThunk(function () {
                return Option.some(guess);
              });
            }

            return mogel(win, guess, guessBox, caret);
          });
        }, Option.none);
      });
    };

    // The process is that you incrementally go down ... if you find the next element, but your top is not at that element's bounding rect.
    // then try again with the same x but the box's y
    var webkitAgain = function (win, caret) {
      return Point.find(win, caret.left, caret.bottom + JUMP_SIZE).bind(function (guess) {
        return guess.start().fold(Option.none, function (e, eo) {
          return Rectangles.getBox(win, e, eo).bind(function (guessBox) {
            return mogel(win, guess, guessBox, caret);
          });
        }, Option.none);
      });
    };

    var ieAgain = function (win, caret) {
      return Point.find(win, caret.left, caret.bottom + 5);
    };

    return {
      webkitAgain: webkitAgain,
      firefoxAgain: firefoxAgain,
      ieAgain: ieAgain
    };
  }
);<|endoftext|>


<commit_before>const request = require("supertest");
const app = require("./app.js");

describe("Get Login", () => {
    it("Should Get the login Page   ", async () => {
        const res = await request(app)
            .get("/login")
            .end()
        expect(res.statusCode).toEqual(200);
    });
});
<commit_msg>Will it like this better?<commit_after>const request = require("supertest");
const app = require("./app.js");

describe("Get Login", () => {
    it("Should Get the login Page   ", async () => {
        const res = await request(app)
            .get("/login")
        expect(res.statusCode).toEqual(200);
    });
});
<|endoftext|>


<commit_before>import path from 'node:path';
import test from 'ava';
import {fileURLToPath} from 'node:url';
import {pkgUp, pkgUpSync} from './index.js';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

const cwd = path.join(__dirname, 'fixture');
const pkgPath = path.join(__dirname, 'package.json');

test('async', async t => {
	t.is(await pkgUp({cwd}), pkgPath);
	t.is(path.dirname(await pkgUp()), __dirname);
});

test('sync', t => {
	t.is(pkgUpSync({cwd}), pkgPath);
	t.is(path.dirname(pkgUpSync()), __dirname);
});
<commit_msg>Fix CI<commit_after>import path from 'node:path';
import {fileURLToPath} from 'node:url';
import test from 'ava';
import {pkgUp, pkgUpSync} from './index.js';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

const cwd = path.join(__dirname, 'fixture');
const pkgPath = path.join(__dirname, 'package.json');

test('async', async t => {
	t.is(await pkgUp({cwd}), pkgPath);
	t.is(path.dirname(await pkgUp()), __dirname);
});

test('sync', t => {
	t.is(pkgUpSync({cwd}), pkgPath);
	t.is(path.dirname(pkgUpSync()), __dirname);
});
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-7-20 09:58:55<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>'use strict';
<commit_msg>Add base unit test<commit_after>'use strict';

var test = require('tap').test;
var app = require('loopback');

// https://github.com/strongloop/loopback-boot/blob/master/lib/executor.js#L57-L71
// the loopback-boot module patches in the loopback attribute so we can assume the same
app.loopback = require('loopback');

var dataSource = app.createDataSource({
  connector: app.Memory
});

// import our IPs mixin
require('./')(app);

test('Loopback Datasource IPs', function(tap) {
  tap.test('createdByIp', function(t) {

    var Book = dataSource.createModel('Book',
      {name: String, type: String},
      {mixins: {IPs: true}}
    );

    t.test('Should exist on create', function(tt) {
      Book.destroyAll(function() {
        Book.create({name: 'book 1', type: 'fiction'}, function(error, createdBook) {
          tt.error(error);
          tt.ok(createdBook.updatedByIp);
          // TODO: Fix unit test :(
          // tt.type(createdBook.updatedByIp, String);
          tt.end();
        });
      });
    });

    t.test('Should not change on save', function(tt) {
      Book.destroyAll(function() {
        Book.create({name: 'book 1', type: 'fiction'}, function(error, createdBook) {
          tt.error(error);
          tt.ok(createdBook.createdByIp);

          createdBook.name = 'book inf';
          createdBook.save(function(error, savedBook) {
            tt.error(error);
            tt.equal(createdBook.createdByIp, savedBook.createdByIp);
            tt.end();
          });
        });
      });
    });

    t.test('Should not change on update', function(tt) {
      Book.destroyAll(function() {
        Book.create({name: 'book 1', type: 'fiction'}, function(error, createdBook) {
          tt.error(error);
          tt.ok(createdBook.createdByIp);

          createdBook.updateAttributes({name: 'book inf'}, function(err, updatedBook) {
            tt.error(err);
            tt.equal(createdBook.createdByIp, updatedBook.createdByIp);
            tt.end();
          });
        });
      });
    });

    t.test('Should not change with bulk updates', function(tt) {
      Book.destroyAll(function() {
        Book.create({name: 'book 1', type: 'fiction'}, function(error, createdBook) {
          tt.error(error);
          tt.ok(createdBook.createdByIp);

          Book.updateAll({type: 'fiction'}, {type: 'non-fiction'}, function(error) {
            tt.error(error);

            Book.findById(createdBook.id, function(err, bookFound) {
              tt.error(err);
              tt.equal(createdBook.createdByIp, bookFound.createdByIp);
              tt.end();
            });
          });
        });
      });
    });

  });

  tap.test('updatedByIp', function(t) {

    var Book = dataSource.createModel('Book',
      {name: String, type: String},
      {mixins: {IPs: true}}
    );

    t.test('Should exist on create', function(tt) {
      Book.destroyAll(function() {
        Book.create({name: 'book 1', type: 'fiction'}, function(error, createdBook) {
          tt.error(error);
          tt.ok(createdBook.updatedByIp);
          tt.type(createdBook.updatedByIp, String);
          tt.end();
        });
      });
    });

    t.test('Should be updated via updateAttributes', function(tt) {
      Book.destroyAll(function() {
        Book.create({name: 'book 1', type: 'fiction'}, function(error, createdBook) {
          tt.error(error);
          tt.ok(createdBook.updatedByIp);

          //TODO: Add mock request to change updatedByIp attribute!
          createdBook.updateAttributes({type: 'historical-fiction'}, function(error, updatedBook) {
            tt.error(error);
            tt.ok(updatedBook.updatedByIp);
            tt.end();
          });
        });
      });
    });

    t.test('Should update bulk model updates at once', function(tt) {
      var createdByIp1,
          createdByIp2,
          updatedByIp1,
          updatedByIp2;

      Book.destroyAll(function() {
        Book.create({name: 'book 1', type: 'fiction'}, function(error, book1) {
          tt.error(error);
          tt.ok(book1.createdByIp);
          tt.ok(book1.updatedByIp);

          createdByIp1 = book1.createdByIp;
          updatedByIp1 = book1.updatedByIp;
          Book.create({name: 'book 2', type: 'fiction'}, function(error, book2) {
            tt.error(error);
            tt.ok(book2.createdByIp);
            tt.ok(book2.updatedByIp);

            createdByIp2 = book2.createdByIp;
            updatedByIp2 = book2.updatedByIp;
            Book.updateAll({type: 'fiction'}, {type: 'romance'}, function(error) {
              tt.error(error);
              tt.equal(createdByIp1, book1.createdByIp);
              tt.equal(createdByIp2, book2.createdByIp);

              //TODO: Add mock request to change updatedByIp attribute on bulk model updates!
              Book.find({type: 'romance'}, function(err, books) {
                tt.error(err);
                tt.equal(books.length, 2);

                books.forEach(function(book) {
                  tt.ok(book.updatedByIp);
                });
                tt.end();
              });
            });
          });
        });
      });
    });

  });

  tap.test('Boot options', function(t) {

    t.test('Should use createdIp and lastUpdatedIp instead', function(tt) {
      var Book = dataSource.createModel('Book',
        {name: String, type: String},
        {mixins: {IPs: {createdByIp: 'createdIp', updatedByIp: 'lastUpdatedIp'}}}
      );

      Book.destroyAll(function() {
        Book.create({name: 'book 1', type: 'fiction'}, function(error, createdBook) {
          tt.error(error);

          tt.type(createdBook.createdByIp, 'undefined');
          tt.type(createdBook.updatedByIp, 'undefined');

          tt.ok(createdBook.createdIp);
          tt.type(createdBook.createdIp, String);

          tt.ok(createdBook.lastUpdatedIp);
          tt.type(createdBook.lastUpdatedIp, String);

          tt.end();
        });
      });
    });

    t.test('Should default required on createdByIp and updatedByIp ', function(tt) {
      var Book = dataSource.createModel('Book',
        {name: String, type: String},
        {mixins: {IPs: true}}
      );

      tt.equal(Book.definition.properties.createdByIp.required, true);
      tt.equal(Book.definition.properties.updatedByIp.required, true);
      tt.end();
    });

    t.test('Should have optional createdByIp and updatedByIp', function(tt) {
      var Book = dataSource.createModel('Book',
        {name: String, type: String},
        {mixins: {IPs: {required: false}}}
      );

      tt.equal(Book.definition.properties.createdByIp.required, false);
      tt.equal(Book.definition.properties.updatedByIp.required, false);
      tt.end();
    });

  });

  tap.test('Operation hook options', function(t) {

    var Book = dataSource.createModel('Book',
      {name: String, type: String},
      {mixins: {IPs: true}}
    );

    t.test('Should skip changing updatedByIp when option passed', function(tt) {
      var updated,
          book;

      Book.destroyAll(function() {
        Book.create({name: 'book 1', type: 'fiction'}, function(error, createdBook) {
          tt.error(error);
          tt.ok(createdBook.updatedByIp);

          updated = createdBook.updatedByIp;
          book = createdBook.toObject();
          book.name = 'book 2';

          Book.updateOrCreate(book, {skipUpdatedByIp: true}, function(err, book2) {
            tt.error(err);
            tt.ok(book2.updatedByIp);
            tt.equal(updated, book2.updatedByIp);
            tt.end();
          });

        });
      });
    });

  });

});
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-6-13 20:39:38<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>var ri = setInterval(function(){console.log('hello')},1000);

console.log(ri);

setTimeout(function(){clearInterval(ri)},5000)
<commit_msg>clean<commit_after><|endoftext|>


<commit_before>var fs = require('fs');
var ioctl = require('ioctl');

var TTY = '/dev/tty1';

var KDSETMODE = 0x4B3A;
var KD_GRAPHICS = 0x01;
var KD_TEXT = 0x00;

fs.open(TTY, 'r+', function(err, fd) {
    if (err) {
        throw err;
    }

    var ret = ioctl(fd, KDSETMODE, KD_TEXT);
    console.log('KDSETMODE ret: ' + ret);
    fs.close(fd);
});<commit_msg>Delete test.js<commit_after><|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-7-24 01:35:21<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>