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

/**
 * Example application. It implements an imageboard with boards & posts.
 * Note that this implementation does not include access control,
 * so it's more like a wiki but without the moderation.
 */
fortune({

  adapter: "mongodb",
  db: 'userAddress'

})

/*!
 * Define resources
 */
.resource("user", {
  title : String,
  firstName : String,
  lastName : String,
  role : String,
  email : String,
  nationality: String,
  languageCode: String,
  addresses: [{ref: "address", inverse: "user"}],
  flights: [{ref: "flight", inverse: "flights"}]
})

.resource("address", {
  type: String,
  addressLine1: String,
  addressLine2: String,
  addressLine3: String,
  addressLine4: String,
  city: String,
  region: String,
  postCode: String,
  country: String,
  dateDeleted: Date,
  user: {ref: "user", inverse: "addresses"}
})

.resource("flight", {
  flightNumber: String,
  users: [{ref: "user", inverse: "users"}]
})

/*!
 * Start the API
 */
.listen(process.argv[2] || 1337);
<commit_msg>Updated DB name<commit_after>var fortune = require('../lib/fortune');

/**
 * Example application. It implements an imageboard with boards & posts.
 * Note that this implementation does not include access control,
 * so it's more like a wiki but without the moderation.
 */
fortune({

  adapter: "mongodb",
  db: 'relationships'

})

/*!
 * Define resources
 */
.resource("user", {
  title : String,
  firstName : String,
  lastName : String,
  role : String,
  email : String,
  nationality: String,
  languageCode: String,
  addresses: [{ref: "address", inverse: "user"}],
  flights: [{ref: "flight", inverse: "flights"}]
})

.resource("address", {
  type: String,
  addressLine1: String,
  addressLine2: String,
  addressLine3: String,
  addressLine4: String,
  city: String,
  region: String,
  postCode: String,
  country: String,
  dateDeleted: Date,
  user: {ref: "user", inverse: "addresses"}
})

.resource("flight", {
  flightNumber: String,
  users: [{ref: "user", inverse: "users"}]
})

/*!
 * Start the API
 */
.listen(process.argv[2] || 1337);
<|endoftext|>


<commit_before>import React from 'react';
import SplitPane from '../src/SplitPane';

var Example = React.createClass({

    render: function() {
        return (
            <SplitPane  defaultSize="900">

                <SplitPane orientation="vertical">

                </SplitPane>
            </SplitPane>
        );
    }

});

React.render(<Example />, document.body);<commit_msg>changes on property names<commit_after>import React from 'react';
import SplitPane from '../src/SplitPane';

var Example = React.createClass({

    render: function() {
        return (
            <SplitPane defaultSize="900">

                <SplitPane orientation="vertical">

                </SplitPane>
            </SplitPane>
        );
    }

});

React.render(<Example />, document.body);<|endoftext|>


<commit_before>const {Command} = require('heroku-cli-command')

class NoCommand extends Command {
  async run () {
    throw new Error(`${this.color.yellow(this.argv[1])} is not a heroku command.
Perhaps you meant ????
Run ${this.color.cmd('heroku help')} for a list of available commands.`)
  }
}

module.exports = NoCommand
<commit_msg>varargs for no_command<commit_after>const {Command} = require('heroku-cli-command')

class NoCommand extends Command {
  async run () {
    throw new Error(`${this.color.yellow(this.argv[1])} is not a heroku command.
Perhaps you meant ????
Run ${this.color.cmd('heroku help')} for a list of available commands.`)
  }
}

NoCommand.variableArgs = true

module.exports = NoCommand
<|endoftext|>


<commit_before>// Copyright 2016 Yahoo Inc.
// Licensed under the terms of the MIT license. Please see LICENSE file in the project root for terms.

/* jshint ignore:start */
/* jscs:disable */
var Promise = require('native-promise-only');
var request = require('superagent');
var except = require('except');
var Backoff = require('backo');
var backoff = new Backoff({ min: 100, max: 10000, jitter: 0, factor: 2 });
var retryErrors = require('./retryerrors.js');
var merge = require('deepmerge');
var validate = require('./validate.js');
var generateURL = require('./generate-url.js');
var headers = require('./headers.js');

// Different crypto for client vs. server
/* istanbul ignore next */
var crypto = process.browser ? require('../shims/crypto-client') : require('../shims/crypto-server');

/**
 * Initiate the Transport function
 *
 * @method FlickrTransport
 * @param {Object} config - Any options that you wish to configure when setting up the API.
 * @returns {Function} - The function to which the other calls can be chained.
 */
var FlickrTransport = function (config, options) {

	if (!config.timeout) {
		config.timeout = 15000; // 15 seconds
	}

	if (!config.retries) {
		config.retries = 3;
	}

	if (!config.onProgress) {
		/* istanbul ignore next */
		config.onProgress = function () { /*noop*/ };
	}

	/* istanbul ignore next */
	if (process.browser && config.apiSecret) {
		throw new Error('Embedding your API secret in the browser could allow a malicious third-party to make API calls using your key.  Making authenticated API calls is disabled in the browser using this SDK at the moment.');
	}

	this.config = config;
	this.retries = 3;
	this.plugins = [];

	this.log = function (message) {
		if (options && options.logger && typeof options.logger.log === 'function') {
			options.logger.log(message);
		}
	};

};

/**
 * Create an oauth 1.0 signature from the request object
 * I would love to use the oauth-signature npm module here
 * but because of the upload API's requirement to *not* include
 * the access token secret in the signing key we can't use it.
 *
 * @method createSignature
 * @param {Object} req - The request object.
 * @param {Object} params - The params being sent through to the call.
 * @returns {string} - The signature required to make the request.
 */
FlickrTransport.prototype.createSignature = function (req, params, signingSecret) {

	var baseString = req.method.toUpperCase() + '&' + encodeURIComponent(req.url) + '&',
	    signingKey = this.config.apiSecret + "&" + (signingSecret || '');

	Object.keys(params).sort().forEach(function(key, i) {
		baseString += (i > 0) ? encodeURIComponent('&') : '';
		baseString += encodeURIComponent(key + '=' + params[key]);
	});

	return crypto.createHmac('sha1', signingKey).update(baseString).digest('base64');

};

/**
 * Create a one-time nonce
 *
 * @method createNonce
 * @returns {string} - The hash required to make the request.
 */
FlickrTransport.prototype.createNonce = function () {
	return crypto.createHash('sha1').update(String(Date.now())).digest('hex');
};

/**
 * Determine if the error/response from the api call means we should try and make the call again.
 *
 * @method shouldRetry
 * @param {Object} error - The error object. This can also be null if there is no error.
 * @param {Object} response - The response object.
 * @returns {Boolean} - Whether or not the call should retry.
 */
FlickrTransport.prototype.shouldRetry = function (error, response) {
	return retryErrors.some(function (check) {
		return check(error, response);
	});
}

/**
 * Superagent plugin for all of the default flickr api v1 params
 *
 * @method createSignature
 * @returns {Object} The default params.
 */
FlickrTransport.prototype.defaults = function (req) {
	return {
		format: 'json',
		nojsoncallback: 1
	};
};

/**
 * Attaching plugins to the request
 *
 * @method usePlugins
 */
FlickrTransport.prototype.usePlugins = function (plugins) {

	return function (req) {
		// If there's plugins use them
		if (plugins.length > 0) {
			plugins.forEach(function (plugin) {
				req.use(plugin);
			});
		}
	}

};

/**
 * Superagent plugin attaching a file if we've got one
 *
 * @method attachFile
 * @param {Object} params - Contains the parameters being passed to the api.
 * @returns {Function} - A callable function that takes the request as a parameter.
 */
FlickrTransport.prototype.attachFile = function (params) {
	return function (req) {
		if (params.photo) {
			req.attach('photo', params.photo);
		}
	};
};

/**
 * Superagent plugin for generating oauth params
 *
 * @method oAuth
 * @param {Object} params - Contains the parameters being passed to the api.
 * @returns {Function} - A callable function that takes the request as a parameter.
 */
FlickrTransport.prototype.oAuth = function (params, auth, isUpload) {

	var flickrTransport = this;

	return function (req) {

		if (isUpload) {

			// Flickr upload params get appended to the POST body
			var oauthParams = {
				oauth_consumer_key:     flickrTransport.config.apiKey,
				oauth_token:            auth.accessToken,
				oauth_version:          '1.0',
				oauth_timestamp:        Math.round(Date.now() / 1000),
				oauth_nonce:            flickrTransport.createNonce(),
				oauth_signature_method: 'HMAC-SHA1'
			};

			oauthParams = merge(oauthParams, flickrTransport.defaults(req));

			Object.keys(oauthParams).forEach(function (oauthParam) {
				if (typeof oauthParams[oauthParam] !== 'undefined') {
					req.field(oauthParam, oauthParams[oauthParam]);
				}
			});

			req.field('oauth_signature', flickrTransport.createSignature(req, merge(params, oauthParams), auth.accessTokenSecret));

		} else {

			var oauthParams = {
				oauth_consumer_key: flickrTransport.config.apiKey,
				oauth_token:        auth.accessToken,
				oauth_version:      '1.0',
				oauth_timestamp:    Math.round(Date.now() / 1000),
				oauth_nonce: flickrTransport.createNonce(),
				oauth_signature_method: 'HMAC-SHA1'
			};

			oauthParams = merge(oauthParams, flickrTransport.defaults(req));

			req.query(oauthParams);

			req.query({
				oauth_signature: flickrTransport.createSignature(req, merge(params, oauthParams), auth.accessTokenSecret)
			});

		}

	}

};

/**
 * Calls the given operation with `params`. The object provided
 * is in the form `{ schema, path, verb }`. Throws if the params
 * do not match the operation's parameters.
 * @private
 * @param {Object} additionalParams Hash of extra params to merge in
 * @param {Object} transportConfig Hash of extra transport configs to merge in
 * @returns {Promise}
 */
FlickrTransport.prototype.call = function (definition, params, auth, additionalParams, transportConfig) {

	var flickrTransport = this;
	var schema = definition.schema;
	var path = definition.path;
	var verb = definition.verb;
	var config = schema.paths[path][verb];
	var operationId = config.operationId;
	var startTime = new Date().getTime();
	var defaultParamExceptions = [ 'photo', 'url', 'arguments', 'headers' ];
	var nonQueryParams = [];
	var responseHeaders = {};
	var responseBody;

	auth = auth || {};

	var apiParams = merge(params, additionalParams || {});

	// Remove any null params
	Object.keys(apiParams).forEach(function (paramKey) {
		if (apiParams[paramKey] === null) {
			delete apiParams[paramKey];
		}
	});

	return new Promise(function (resolve, reject) {

		var validationErrors = validate(apiParams, config.parameters);

		if (validationErrors.length > 0) {
			reject(validationErrors);
			return;
		}

		// Get a URL with params substituted in where appropriate
		var uri = generateURL(definition, apiParams, merge(flickrTransport.config, transportConfig || {}));

		// Filter out non-query params
		config.parameters.forEach(function (configParam) {
			if (configParam.in !== 'query') {
				nonQueryParams.push(configParam.name);
			}
		});

		// Not all params get passed to oauth
		var oauthParams = except(apiParams, defaultParamExceptions.concat(nonQueryParams));

		// Start log
		flickrTransport.log("Starting " + verb + " API call to " + uri);

		function makeRequest() {

			request(verb, uri)
			.use(function (request) {
				/* istanbul ignore else */
				if (!process.browser) {
					// Cookies are implicit on the client
					request.set("Cookie", flickrTransport.config.cookie || "");
				}
				return request;
			})
			.use(function (request) {
				request.query(oauthParams);

				if (verb === "post") { request.send(apiParams); }

				return request;
			})
			.use(flickrTransport.attachFile(apiParams))
			.use(function (request) {
				// if we don't have an access token, don't attach auth
				// to the request
				if (operationId !== 'getRequestToken' && operationId !== 'getAccessToken') {
					return flickrTransport.oAuth(oauthParams, auth, apiParams.photo)(request);
				}
				return request;
			})
			.use(flickrTransport.usePlugins(flickrTransport.plugins))
			.end(handleRequest);

			// Reset the plugins as they are definied per request
			flickrTransport.plugins = [];
		}

		function handleRequest(err, res) {

			// End log
			flickrTransport.log("Finished " + verb + " API call to " + uri + " in " + (new Date().getTime() - startTime) + "ms");

			// Decrement retries
			flickrTransport.retries--;

			if (err) {
				// HTTP error
				if (flickrTransport.retries > 0 && flickrTransport.shouldRetry(err, res)) {
					// Try again
					setTimeout(makeRequest, backoff.duration());
				} else {
					flickrTransport.resetRetries();
					reject(err);
					return;
				}
			} else {

				if (res.body && Object.keys(res.body).length === 0 && res.text.match(/xml/)) {
					// Deal with the XML response as if it's a string. The response
					// is always simple so there's no need to convert it wholesale to
					// JSON which would introduce a heavy dependency.
					/* istanbul ignore next */
					if (res.text.match(/stat="fail"/)) {
						// Good ol' Flickr 200 but with error
						flickrTransport.resetRetries();
						reject({
							code: res.text.match(/code="([0-9]+)"/)[1],
							message: res.text.match(/msg="([A-Za-z0-9\-\s]+)"/)[1]
						});
						return;
					} else {
						flickrTransport.resetRetries();
						responseBody = {
							photoID: res.text.match(/<photoid>([0-9]+)<\/photoid>/)[1]
						};
					}
				} else {
					// Regular response in the body
					if (res.body && res.body.stat === 'fail') {
						// Good ol' Flickr 200 but with error
						flickrTransport.resetRetries();
						reject(res.body);
						return;
					} else {
						flickrTransport.resetRetries();
						responseBody = res.body;
					}
				}

				// Check if there are response headers we want to return
				// in our own response
				Object.keys(res.headers).forEach(function (headerKey) {
					if (headers[headerKey]) {
						responseHeaders[headers[headerKey]] = res.headers[headerKey];
					}
				});

				responseBody = responseBody || {};

				// When we're requesting a token, it returns text that we need to parse
				/* istanbul ignore next */
				if (res.type === 'text/plain' && (operationId === "getRequestToken" || operationId === "getAccessToken")) {
					var values = (res.text || '').split('&');
					values.forEach(function (keyPair) {
						var keyVal = keyPair.split('=');
						if (keyVal.length > 1) {
							responseBody[keyVal[0]] = keyVal[1];
						}
					})
				}

				// Return the whole lot
				resolve({
					headers: responseHeaders,
					body: responseBody
				});

			}

		}

		// Make the initial call
		makeRequest();

	});

};

/**
 * Resets the backoff and retries remaining counter
 * @private
 */
FlickrTransport.prototype.resetRetries = function () {
	backoff.reset();
	this.retries = 3;
};

module.exports = FlickrTransport;
<commit_msg>The transport is used by other things too, but calls are allowed in the client there because it supports oauth2, so this needs to be changed.<commit_after>// Copyright 2016 Yahoo Inc.
// Licensed under the terms of the MIT license. Please see LICENSE file in the project root for terms.

/* jshint ignore:start */
/* jscs:disable */
var Promise = require('native-promise-only');
var request = require('superagent');
var except = require('except');
var Backoff = require('backo');
var backoff = new Backoff({ min: 100, max: 10000, jitter: 0, factor: 2 });
var retryErrors = require('./retryerrors.js');
var merge = require('deepmerge');
var validate = require('./validate.js');
var generateURL = require('./generate-url.js');
var headers = require('./headers.js');

// Different crypto for client vs. server
/* istanbul ignore next */
var crypto = process.browser ? require('../shims/crypto-client') : require('../shims/crypto-server');

/**
 * Initiate the Transport function
 *
 * @method FlickrTransport
 * @param {Object} config - Any options that you wish to configure when setting up the API.
 * @returns {Function} - The function to which the other calls can be chained.
 */
var FlickrTransport = function (config, options) {

	if (!config.timeout) {
		config.timeout = 15000; // 15 seconds
	}

	if (!config.retries) {
		config.retries = 3;
	}

	if (!config.onProgress) {
		/* istanbul ignore next */
		config.onProgress = function () { /*noop*/ };
	}

	this.config = config;
	this.retries = 3;
	this.plugins = [];

	this.log = function (message) {
		if (options && options.logger && typeof options.logger.log === 'function') {
			options.logger.log(message);
		}
	};

};

/**
 * Create an oauth 1.0 signature from the request object
 * I would love to use the oauth-signature npm module here
 * but because of the upload API's requirement to *not* include
 * the access token secret in the signing key we can't use it.
 *
 * @method createSignature
 * @param {Object} req - The request object.
 * @param {Object} params - The params being sent through to the call.
 * @returns {string} - The signature required to make the request.
 */
FlickrTransport.prototype.createSignature = function (req, params, signingSecret) {

	var baseString = req.method.toUpperCase() + '&' + encodeURIComponent(req.url) + '&',
	    signingKey = this.config.apiSecret + "&" + (signingSecret || '');

	Object.keys(params).sort().forEach(function(key, i) {
		baseString += (i > 0) ? encodeURIComponent('&') : '';
		baseString += encodeURIComponent(key + '=' + params[key]);
	});

	return crypto.createHmac('sha1', signingKey).update(baseString).digest('base64');

};

/**
 * Create a one-time nonce
 *
 * @method createNonce
 * @returns {string} - The hash required to make the request.
 */
FlickrTransport.prototype.createNonce = function () {
	return crypto.createHash('sha1').update(String(Date.now())).digest('hex');
};

/**
 * Determine if the error/response from the api call means we should try and make the call again.
 *
 * @method shouldRetry
 * @param {Object} error - The error object. This can also be null if there is no error.
 * @param {Object} response - The response object.
 * @returns {Boolean} - Whether or not the call should retry.
 */
FlickrTransport.prototype.shouldRetry = function (error, response) {
	return retryErrors.some(function (check) {
		return check(error, response);
	});
}

/**
 * Superagent plugin for all of the default flickr api v1 params
 *
 * @method createSignature
 * @returns {Object} The default params.
 */
FlickrTransport.prototype.defaults = function (req) {
	return {
		format: 'json',
		nojsoncallback: 1
	};
};

/**
 * Attaching plugins to the request
 *
 * @method usePlugins
 */
FlickrTransport.prototype.usePlugins = function (plugins) {

	return function (req) {
		// If there's plugins use them
		if (plugins.length > 0) {
			plugins.forEach(function (plugin) {
				req.use(plugin);
			});
		}
	}

};

/**
 * Superagent plugin attaching a file if we've got one
 *
 * @method attachFile
 * @param {Object} params - Contains the parameters being passed to the api.
 * @returns {Function} - A callable function that takes the request as a parameter.
 */
FlickrTransport.prototype.attachFile = function (params) {
	return function (req) {
		if (params.photo) {
			req.attach('photo', params.photo);
		}
	};
};

/**
 * Superagent plugin for generating oauth params
 *
 * @method oAuth
 * @param {Object} params - Contains the parameters being passed to the api.
 * @returns {Function} - A callable function that takes the request as a parameter.
 */
FlickrTransport.prototype.oAuth = function (params, auth, isUpload) {

	var flickrTransport = this;

	return function (req) {

		if (isUpload) {

			// Flickr upload params get appended to the POST body
			var oauthParams = {
				oauth_consumer_key:     flickrTransport.config.apiKey,
				oauth_token:            auth.accessToken,
				oauth_version:          '1.0',
				oauth_timestamp:        Math.round(Date.now() / 1000),
				oauth_nonce:            flickrTransport.createNonce(),
				oauth_signature_method: 'HMAC-SHA1'
			};

			oauthParams = merge(oauthParams, flickrTransport.defaults(req));

			Object.keys(oauthParams).forEach(function (oauthParam) {
				if (typeof oauthParams[oauthParam] !== 'undefined') {
					req.field(oauthParam, oauthParams[oauthParam]);
				}
			});

			req.field('oauth_signature', flickrTransport.createSignature(req, merge(params, oauthParams), auth.accessTokenSecret));

		} else {

			var oauthParams = {
				oauth_consumer_key: flickrTransport.config.apiKey,
				oauth_token:        auth.accessToken,
				oauth_version:      '1.0',
				oauth_timestamp:    Math.round(Date.now() / 1000),
				oauth_nonce: flickrTransport.createNonce(),
				oauth_signature_method: 'HMAC-SHA1'
			};

			oauthParams = merge(oauthParams, flickrTransport.defaults(req));

			req.query(oauthParams);

			req.query({
				oauth_signature: flickrTransport.createSignature(req, merge(params, oauthParams), auth.accessTokenSecret)
			});

		}

	}

};

/**
 * Calls the given operation with `params`. The object provided
 * is in the form `{ schema, path, verb }`. Throws if the params
 * do not match the operation's parameters.
 * @private
 * @param {Object} additionalParams Hash of extra params to merge in
 * @param {Object} transportConfig Hash of extra transport configs to merge in
 * @returns {Promise}
 */
FlickrTransport.prototype.call = function (definition, params, auth, additionalParams, transportConfig) {

	/* istanbul ignore next */
	if (process.browser && flickrTransport.config && flickrTransport.config.apiSecret) {
		throw new Error('Embedding your API secret in the browser could allow a malicious third-party to make API calls using your key.  Making authenticated API calls is disabled in the browser using this SDK at the moment.');
	}

	var flickrTransport = this;
	var schema = definition.schema;
	var path = definition.path;
	var verb = definition.verb;
	var config = schema.paths[path][verb];
	var operationId = config.operationId;
	var startTime = new Date().getTime();
	var defaultParamExceptions = [ 'photo', 'url', 'arguments', 'headers' ];
	var nonQueryParams = [];
	var responseHeaders = {};
	var responseBody;

	auth = auth || {};

	var apiParams = merge(params, additionalParams || {});

	// Remove any null params
	Object.keys(apiParams).forEach(function (paramKey) {
		if (apiParams[paramKey] === null) {
			delete apiParams[paramKey];
		}
	});

	return new Promise(function (resolve, reject) {

		var validationErrors = validate(apiParams, config.parameters);

		if (validationErrors.length > 0) {
			reject(validationErrors);
			return;
		}

		// Get a URL with params substituted in where appropriate
		var uri = generateURL(definition, apiParams, merge(flickrTransport.config, transportConfig || {}));

		// Filter out non-query params
		config.parameters.forEach(function (configParam) {
			if (configParam.in !== 'query') {
				nonQueryParams.push(configParam.name);
			}
		});

		// Not all params get passed to oauth
		var oauthParams = except(apiParams, defaultParamExceptions.concat(nonQueryParams));

		// Start log
		flickrTransport.log("Starting " + verb + " API call to " + uri);

		function makeRequest() {

			request(verb, uri)
			.use(function (request) {
				/* istanbul ignore else */
				if (!process.browser) {
					// Cookies are implicit on the client
					request.set("Cookie", flickrTransport.config.cookie || "");
				}
				return request;
			})
			.use(function (request) {
				request.query(oauthParams);

				if (verb === "post") { request.send(apiParams); }

				return request;
			})
			.use(flickrTransport.attachFile(apiParams))
			.use(function (request) {
				// if we don't have an access token, don't attach auth
				// to the request
				if (operationId !== 'getRequestToken' && operationId !== 'getAccessToken') {
					return flickrTransport.oAuth(oauthParams, auth, apiParams.photo)(request);
				}
				return request;
			})
			.use(flickrTransport.usePlugins(flickrTransport.plugins))
			.end(handleRequest);

			// Reset the plugins as they are definied per request
			flickrTransport.plugins = [];
		}

		function handleRequest(err, res) {

			// End log
			flickrTransport.log("Finished " + verb + " API call to " + uri + " in " + (new Date().getTime() - startTime) + "ms");

			// Decrement retries
			flickrTransport.retries--;

			if (err) {
				// HTTP error
				if (flickrTransport.retries > 0 && flickrTransport.shouldRetry(err, res)) {
					// Try again
					setTimeout(makeRequest, backoff.duration());
				} else {
					flickrTransport.resetRetries();
					reject(err);
					return;
				}
			} else {

				if (res.body && Object.keys(res.body).length === 0 && res.text.match(/xml/)) {
					// Deal with the XML response as if it's a string. The response
					// is always simple so there's no need to convert it wholesale to
					// JSON which would introduce a heavy dependency.
					/* istanbul ignore next */
					if (res.text.match(/stat="fail"/)) {
						// Good ol' Flickr 200 but with error
						flickrTransport.resetRetries();
						reject({
							code: res.text.match(/code="([0-9]+)"/)[1],
							message: res.text.match(/msg="([A-Za-z0-9\-\s]+)"/)[1]
						});
						return;
					} else {
						flickrTransport.resetRetries();
						responseBody = {
							photoID: res.text.match(/<photoid>([0-9]+)<\/photoid>/)[1]
						};
					}
				} else {
					// Regular response in the body
					if (res.body && res.body.stat === 'fail') {
						// Good ol' Flickr 200 but with error
						flickrTransport.resetRetries();
						reject(res.body);
						return;
					} else {
						flickrTransport.resetRetries();
						responseBody = res.body;
					}
				}

				// Check if there are response headers we want to return
				// in our own response
				Object.keys(res.headers).forEach(function (headerKey) {
					if (headers[headerKey]) {
						responseHeaders[headers[headerKey]] = res.headers[headerKey];
					}
				});

				responseBody = responseBody || {};

				// When we're requesting a token, it returns text that we need to parse
				/* istanbul ignore next */
				if (res.type === 'text/plain' && (operationId === "getRequestToken" || operationId === "getAccessToken")) {
					var values = (res.text || '').split('&');
					values.forEach(function (keyPair) {
						var keyVal = keyPair.split('=');
						if (keyVal.length > 1) {
							responseBody[keyVal[0]] = keyVal[1];
						}
					})
				}

				// Return the whole lot
				resolve({
					headers: responseHeaders,
					body: responseBody
				});

			}

		}

		// Make the initial call
		makeRequest();

	});

};

/**
 * Resets the backoff and retries remaining counter
 * @private
 */
FlickrTransport.prototype.resetRetries = function () {
	backoff.reset();
	this.retries = 3;
};

module.exports = FlickrTransport;
<|endoftext|>


<commit_before>const moment = require("moment");

exports.run = function(client, message, [args]){
  const config = require("../../settings.json");

  args = message.content.split(" ").slice(1).join(" ");
  if(args.length < 1) {
    args = null;
    console.log(`[${moment().format("YYYY-MM-DD HH:mm")}] Game status wiped.`);
    return client.user.setPresence({ game: { name: args, type: 0 } });
  }

  console.log(`[${moment().format("YYYY-MM-DD HH:mm")}] Game status changed to ${args}.`);
  client.user.setPresence({ game: { name: args, type: 0 } });
};

exports.conf = {
    enabled: true,
    runIn: ["text", "dm", "group"],
    aliases: [],
    permLevel: 10,
    botPerms: [],
    requiredFuncs: [],
};

  exports.help = {
    name: "game",
    description: "Set the game status of Margarine",
    usage: "[args:args]",
    usageDelim: "",
};<commit_msg>Delete game.js<commit_after><|endoftext|>


<commit_before>var q = require('q');
var promise = require('selenium-webdriver').promise;

/**
 * Execute the Runner's test cases through Mocha.
 *
 * @param {Runner} runner The current Protractor Runner.
 * @param {Array} specs Array of Directory Path Strings.
 * @return {q.Promise} Promise resolved with the test results
 */
exports.run = function(runner, specs) {
  var Mocha = require('mocha'),
      mocha = new Mocha(runner.getConfig().mochaOpts);

  // Add hooks for afterEach
  require('./setupAfterEach').setup(runner, specs);

  var deferred = q.defer();

  // Mocha doesn't set up the ui until the pre-require event, so
  // wait until then to load mocha-webdriver adapters as well.
  mocha.suite.on('pre-require', function() {
    try {
      global.after = wrapped(global.after);
      global.afterEach = wrapped(global.afterEach);
      global.before = wrapped(global.before);
      global.beforeEach = wrapped(global.beforeEach);

      global.it = wrapped(global.it);
      global.it.only = wrapped(global.iit);
      global.it.skip = wrapped(global.xit);
    } catch (err) {
      deferred.reject(err);
    }
  });

  mocha.loadFiles();

  runner.runTestPreparer().then(function() {
    specs.forEach(function(file) {
      mocha.addFile(file);
    });

    var testResult = [];

    var mochaRunner = mocha.run(function(failures) {
      try {
        var completed = q();
        if (runner.getConfig().onComplete) {
          completed = q(runner.getConfig().onComplete());
        }
        completed.then(function() {
          deferred.resolve({
            failedCount: failures,
            specResults: testResult
          });
        });
      } catch (err) {
        deferred.reject(err);
      }
    });

    mochaRunner.on('pass', function(test) {
      var testInfo = {
        name: test.title,
        category: test.fullTitle().slice(0, -test.title.length).trim()
      };
      runner.emit('testPass', testInfo);
      testResult.push({
        description: test.title,
        assertions: [{
          passed: true
        }],
        duration: test.duration
      });
    });

    mochaRunner.on('fail', function(test) {
      var testInfo = {
        name: test.title,
        category: test.fullTitle().slice(0, -test.title.length).trim()
      };
      runner.emit('testFail', testInfo);
      testResult.push({
        description: test.title,
        assertions: [{
          passed: false,
          errorMsg: test.err.message,
          stackTrace: test.err.stack
        }],
        duration: test.duration
      });
    });
  }).catch (function(reason) {
      deferred.reject(reason);
  });

  return deferred.promise;
};

var flow = (function() {
  var initial = process.env['SELENIUM_PROMISE_MANAGER'];
  try {
    process.env['SELENIUM_PROMISE_MANAGER'] = '1';
    return promise.controlFlow();
  } finally {
    if (initial === undefined) {
      delete process.env['SELENIUM_PROMISE_MANAGER'];
    } else {
      process.env['SELENIUM_PROMISE_MANAGER'] = initial;
    }
  }
})();

/**
 * Wraps a function on Mocha's BDD interface so it runs inside a
 * webdriver.promise.ControlFlow and waits for the flow to complete before
 * continuing.
 * @param {!Function} globalFn The function to wrap.
 * @return {!Function} The new function.
 */
function wrapped(globalFn) {
  return function() {
    if (arguments.length === 1) {
      return globalFn(makeAsyncTestFn(arguments[0]));

    } else if (arguments.length === 2) {
      return globalFn(arguments[0], makeAsyncTestFn(arguments[1]));

    } else {
      throw Error('Invalid # arguments: ' + arguments.length);
    }
  };
}

/**
 * Wraps a function so that all passed arguments are ignored.
 * @param {!Function} fn The function to wrap.
 * @return {!Function} The wrapped function.
 */
function seal(fn) {
  return function() {
    fn();
  };
}

/**
 * Make a wrapper to invoke caller's test function, fn.  Run the test function
 * within a ControlFlow.
 *
 * Should preserve the semantics of Mocha's Runnable.prototype.run (See
 * https://github.com/mochajs/mocha/blob/master/lib/runnable.js#L192)
 *
 * @param {!Function} fn
 * @return {!Function}
 */
function makeAsyncTestFn(fn) {
  var isAsync = fn.length > 0;
  var isGenerator = promise.isGenerator(fn);
  if (isAsync && isGenerator) {
    throw new TypeError(
        'generator-based tests must not take a callback; for async testing,'
            + ' return a promise (or yield on a promise)');
  }

  var ret = /** @type {function(this: mocha.Context)}*/ function(done) {
    var self = this;
    var runTest = function(resolve, reject) {
      try {
        if (self.isAsync) {
          fn.call(self, function(err) { err ? reject(err) : resolve(); });
        } else if (self.isGenerator) {
          resolve(promise.consume(fn, self));
        } else {
          resolve(fn.call(self));
        }
      } catch (ex) {
        reject(ex);
      }
    };

    if (!promise.USE_PROMISE_MANAGER) {
      new promise.Promise(runTest).then(seal(done), done);
      return;
    }

    var runnable = this.runnable();
    var mochaCallback = runnable.callback;
    runnable.callback = function() {
      flow.reset();
      return mochaCallback.apply(this, arguments);
    };

    flow.execute(function controlFlowExecute() {
      return new promise.Promise(function(fulfill, reject) {
        return runTest(fulfill, reject);
      }, flow);
    }, runnable.fullTitle()).then(seal(done), done);
  };

  ret.toString = function() {
    return fn.toString();
  };

  return ret;
}
<commit_msg>chore(mocha): refactor to use `selenium-webdriver`'s mocha adapters (#4013)<commit_after>var q = require('q');

/**
 * Execute the Runner's test cases through Mocha.
 *
 * @param {Runner} runner The current Protractor Runner.
 * @param {Array} specs Array of Directory Path Strings.
 * @return {q.Promise} Promise resolved with the test results
 */
exports.run = function(runner, specs) {
  var Mocha = require('mocha'),
      mocha = new Mocha(runner.getConfig().mochaOpts);

  // Add hooks for afterEach
  require('./setupAfterEach').setup(runner, specs);

  var deferred = q.defer();

  // Mocha doesn't set up the ui until the pre-require event, so
  // wait until then to load mocha-webdriver adapters as well.
  mocha.suite.on('pre-require', function() {
    try {
      // We need to re-wrap all of the global functions, which `selenium-webdriver/testing` only
      // does when it is required. So first we must remove it from the cache.
      delete require.cache[require.resolve('selenium-webdriver/testing')];
      var seleniumAdapter = require('selenium-webdriver/testing');

      // Save unwrapped version
      var unwrappedFns = {};
      ['after', 'afterEach', 'before', 'beforeEach', 'it', 'xit', 'iit'].forEach(function(fnName) {
        unwrappedFns[fnName] = global[fnName] || Mocha[fnName];
      });

      var wrapFn = function(seleniumWrappedFn, opt_fnName) {
        // This does not work on functions that can be nested (e.g. `describe`)
        return function() {
          // Set globals to unwrapped version to avoid circular reference
          var wrappedFns = {};
          for (var fnName in unwrappedFns) {
            wrappedFns[fnName] = global[fnName];
            global[fnName] = unwrappedFns[fnName];
          }

          var args = arguments;
          // Allow before/after hooks to use names
          if (opt_fnName && (arguments.length > 1) && (seleniumWrappedFn.length < 2)) {
            global[opt_fnName] = global[opt_fnName].bind(this, args[0]);
            args = Array.prototype.slice.call(arguments, 1);
          }

          try {
            seleniumWrappedFn.apply(this, args);
          } finally {
            // Restore wrapped version
            for (fnName in wrappedFns) {
              global[fnName] = wrappedFns[fnName];
            }
          }
        };
      };

      // Wrap functions
      global.after = wrapFn(seleniumAdapter.after, 'after');
      global.afterEach = wrapFn(seleniumAdapter.afterEach, 'afterEach');
      global.before = wrapFn(seleniumAdapter.before, 'before');
      global.beforeEach = wrapFn(seleniumAdapter.beforeEach, 'beforeEach');

      global.it = wrapFn(seleniumAdapter.it);
      global.iit = wrapFn(seleniumAdapter.it.only);
      global.xit = wrapFn(seleniumAdapter.xit);
      global.it.only = wrapFn(seleniumAdapter.it.only);
      global.it.skip = wrapFn(seleniumAdapter.it.skip);
    } catch (err) {
      deferred.reject(err);
    }
  });

  mocha.loadFiles();

  runner.runTestPreparer().then(function() {
    specs.forEach(function(file) {
      mocha.addFile(file);
    });

    var testResult = [];

    var mochaRunner = mocha.run(function(failures) {
      try {
        var completed = q();
        if (runner.getConfig().onComplete) {
          completed = q(runner.getConfig().onComplete());
        }
        completed.then(function() {
          deferred.resolve({
            failedCount: failures,
            specResults: testResult
          });
        });
      } catch (err) {
        deferred.reject(err);
      }
    });

    mochaRunner.on('pass', function(test) {
      var testInfo = {
        name: test.title,
        category: test.fullTitle().slice(0, -test.title.length).trim()
      };
      runner.emit('testPass', testInfo);
      testResult.push({
        description: test.title,
        assertions: [{
          passed: true
        }],
        duration: test.duration
      });
    });

    mochaRunner.on('fail', function(test) {
      var testInfo = {
        name: test.title,
        category: test.fullTitle().slice(0, -test.title.length).trim()
      };
      runner.emit('testFail', testInfo);
      testResult.push({
        description: test.title,
        assertions: [{
          passed: false,
          errorMsg: test.err.message,
          stackTrace: test.err.stack
        }],
        duration: test.duration
      });
    });
  }).catch (function(reason) {
      deferred.reject(reason);
  });

  return deferred.promise;
};
<|endoftext|>


<commit_before>var node = {}
var lifeline = [new Node(0,1,1,1,10), new Node(2,0,1,1,12)]

function Node(pid, tid, pidSource, tidSource, time) {
  if (!(this instanceof Node)) {
    return new Node();
  }

  this.srcProcessId = pidSource;
  this.srcThreadId = tidSource;
  this.processId = pid;
  this.threadId = tid;
  this.time = time;
}
<commit_msg>added strict js<commit_after>(function() {
  'use strict'

  var node = {}
  var lifeline = [new Node(0,1,1,1,10), new Node(2,0,1,1,12)]

  function Node(pid, tid, pidSource, tidSource, time) {
    if (!(this instanceof Node)) {
      return new Node();
    }
    this.srcProcessId = pidSource;
    this.srcThreadId = tidSource;
    this.processId = pid;
    this.threadId = tid;
    this.time = time;
  }

})();

<|endoftext|>


<commit_before>/* AlloyTouch
 * By AlloyTeam http://www.alloyteam.com/
 * Github: https://github.com/AlloyTeam/AlloyTouch
 * MIT Licensed.
 */
; (function () {
    (function () {
        var lastTime = 0;
        var vendors = ['webkit', 'moz'];
        for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
            window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
            window.cancelAnimationFrame =
              window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'];
        }

        if (!window.requestAnimationFrame)
            window.requestAnimationFrame = function (callback, element) {
                var currTime = new Date().getTime();
                var timeToCall = Math.max(0, 16 - (currTime - lastTime));
                var id = window.setTimeout(function () { callback(currTime + timeToCall); },
                  timeToCall);
                lastTime = currTime + timeToCall;
                return id;
            };

        if (!window.cancelAnimationFrame)
            window.cancelAnimationFrame = function (id) {
                clearTimeout(id);
            };
    }());

    function bind(element, type, callback) {
        element.addEventListener(type, callback, false);
    }

    function iosEase(x) {
        return Math.sqrt(1 - Math.pow(x - 1, 2));
    }

    function preventDefaultTest (el, exceptions) {
        for (var i in exceptions) {
            if (exceptions[i].test(el[i])) {
                return true;
            }
        }
        return false;
    }

    var AlloyTouch = function (option) {
        this.scroller = option.target;
        this.element = typeof option.touch === "string" ? document.querySelector(option.touch) : option.touch;
        this.vertical = option.vertical;
        this.vertical === undefined && (this.vertical = true);
        this.property = option.property;
        this.tickID = 0;
        this.preX;
        this.preY;
        this.sensitivity = option.sensitivity === undefined ? 1 : option.sensitivity;
        this.factor = option.factor === undefined ? 1 : option.factor;
        this.sMf = this.sensitivity * this.factor;
        //拖动时候的摩擦因子
        this.factor1 = 1;
        this.min = option.min;
        this.max = option.max;
        this.startTime;
        this.start;
        this.recording = false;
        this.deceleration = 0.0006;
        this.change = option.change || function () { };
        this.touchEnd = option.touchEnd || function () { };
        this.touchStart = option.touchStart || function () { };
        this.touchMove = option.touchMove || function () { };
        this.reboundEnd = option.reboundEnd || function () { };
        this.preventDefaultException = { tagName: /^(INPUT|TEXTAREA|BUTTON|SELECT)$/ };
        this.hasMin = !(this.min === undefined);
        this.hasMax = !(this.max === undefined);
        this.isTouchStart = false;
        this.step = option.step;
        this.spring = option.spring;
        this.spring === undefined && (this.spring = true);
        this.inertia = option.inertia;
        this.inertia === undefined && (this.inertia = true);
        this.correctionEnd = option.correctionEnd || function () { };
        this.intelligentCorrection = option.intelligentCorrection;
        if (this.hasMax && this.hasMin) {
            this.currentPage = Math.round((this.max - this.scroller[this.property]) / this.step);
        }
        bind(this.element, "touchstart", this._start.bind(this));
        bind(window, "touchmove", this._move.bind(this));
        bind(window, "touchend", this._end.bind(this));
    }

    AlloyTouch.prototype = {
        _start: function (evt) {
            this.isTouchStart = true;
            this._firstTouchMove = true;
            this._preventMoveDefault = true;
            this.touchStart(this.scroller[this.property]);
            cancelAnimationFrame(this.tickID);
            this.correctionEnd(this.scroller[this.property]);
            if (this.hasMax && this.hasMin) {
                this.currentPage = Math.round((this.max - this.scroller[this.property]) / this.step);
            }
            this.startTime = new Date().getTime();
            this._startX = this.preX = evt.touches[0].pageX;
            this._startY = this.preY = evt.touches[0].pageY;
            this.start = this.vertical ? this.preY : this.preX;
        },
        _move: function (evt) {
            if (this.isTouchStart) {
                if (this._firstTouchMove) {
                    var dDis=Math.abs(evt.touches[0].pageX - this._startX) - Math.abs(evt.touches[0].pageY - this._startY);
                    if (dDis > 0 && this.vertical) {
                        this._preventMoveDefault = false;
                    } else if (dDis < 0 && !this.vertical) {
                        this._preventMoveDefault = false;
                    }
                    this._firstTouchMove = false;
                }
                if (this._preventMoveDefault) {
                    var d = (this.vertical ? evt.touches[0].pageY - this.preY : evt.touches[0].pageX - this.preX) * this.sMf;
                    if (this.hasMax && this.scroller[this.property] > this.max && d > 0) {
                        this.factor1 = 0.3;
                    } else if (this.hasMin && this.scroller[this.property] < this.min && d < 0) {
                        this.factor1 = 0.3;
                    } else {
                        this.factor1 = 1;
                    }
                    d *= this.factor1;
                    this.preX = evt.touches[0].pageX;
                    this.preY = evt.touches[0].pageY;
                    this.scroller[this.property] += d;
                    this.change(this.scroller[this.property]);
                    var timestamp = new Date().getTime();
                    if (timestamp - this.startTime > 300) {
                        this.startTime = timestamp;
                        this.start = this.vertical ? this.preY : this.preX;
                    }
                    this.touchMove(this.scroller[this.property]);

                    evt.preventDefault();
                }
            }
        },
        _end: function (evt) {
            if (this.isTouchStart && this._preventMoveDefault) {
                var self = this;
                this.touchEnd(this.scroller[this.property]);
                if (this.hasMax && this.scroller[this.property] > this.max) {
                    this.to(this.scroller, this.property, this.max, 200, iosEase, this.change, this.reboundEnd);
                } else if (this.hasMin && this.scroller[this.property] < this.min) {
                    this.to(this.scroller, this.property, this.min, 200, iosEase, this.change, this.reboundEnd);
                } else if (this.inertia) {
                    //var y = evt.changedTouches[0].pageY;
                    var duration = new Date().getTime() - this.startTime;
                    if (duration < 300) {
                        var distance = ((this.vertical ? evt.changedTouches[0].pageY : evt.changedTouches[0].pageX) - this.start) * this.sensitivity,
                            speed = Math.abs(distance) / duration,
                            speed2 = this.factor * speed,
                            destination = this.scroller[this.property] + (speed2 * speed2) / (2 * this.deceleration) * (distance < 0 ? -1 : 1);

                        self.to(this.scroller, this.property, Math.round(destination), Math.round(speed / self.deceleration), iosEase, function (value) {

                            if (self.spring) {
                                if (self.hasMax && self.scroller[self.property] > self.max) {
                                    setTimeout(function () {
                                        cancelAnimationFrame(self.tickID);
                                        self.to(self.scroller, self.property, self.max, 200, iosEase, self.change);
                                    }, 50);
                                } else if (self.hasMin && self.scroller[self.property] < self.min) {
                                    setTimeout(function () {
                                        cancelAnimationFrame(self.tickID);
                                        self.to(self.scroller, self.property, self.min, 200, iosEase, self.change);
                                    }, 50);
                                }
                            } else {

                                if (self.hasMax && self.scroller[self.property] > self.max) {
                                    cancelAnimationFrame(self.tickID);
                                    self.scroller[self.property] = self.max;

                                } else if (self.hasMin && self.scroller[self.property] < self.min) {
                                    cancelAnimationFrame(self.tickID);
                                    self.scroller[self.property] = self.min;

                                }
                            }
                            self.change(self.scroller[self.property]);
                        }, function () {
                            if (self.step) {
                                self.correction(self.scroller, self.property);
                            }
                        });
                    } else {
                        if (self.step) {
                            self.correction(self.scroller, self.property);
                        }
                    }
                } else {
                    if (self.step) {
                        self.correction(self.scroller, self.property);
                    }
                }
                if (!preventDefaultTest(evt.target, this.preventDefaultException)) {
                    evt.preventDefault();
                }
                this.isTouchStart = false;
            }
        },
        to: function (el, property, value, time, ease, onChange, onEnd) {
            var current = el[property];
            var dv = value - current;
            var beginTime = new Date();
            var self = this;
            var toTick = function () {

                var dt = new Date() - beginTime;
                if (dt >= time) {
                    el[property] = value;
                    onChange && onChange(value);
                    onEnd && onEnd(value);
                    return;
                }
                el[property] = Math.round(dv * ease(dt / time) + current);
                self.tickID = requestAnimationFrame(toTick);
                //cancelAnimationFrame必须在 tickID = requestAnimationFrame(toTick);的后面
                onChange && onChange(el[property]);
            }
            toTick();
        },
        correction: function (el, property) {
            var value = el[property];
            if (this.intelligentCorrection&&this.hasMax && this.hasMin) {
                var prevPage = this.currentPage;
                var d = this.scroller[this.property] - (this.max - prevPage * this.step);
                if (Math.abs(d) > this.step / 20) {
                    if (d > 0) {
                        this.to(el, property, (value < 0 ? -1 : 1) * (prevPage - 1) * this.step, 400, iosEase, this.change, function (value) {
                            this.correctionEnd(value);
                            this.currentPage = prevPage - 1;
                        }.bind(this));

                    } else {
                        this.to(el, property, (value < 0 ? -1 : 1) * (prevPage + 1) * this.step, 400, iosEase, this.change, function (value) {
                            this.correctionEnd(value);
                            this.currentPage = prevPage + 1;
                        }.bind(this));
                    }

                } else {
                    this.to(el, property, (value < 0 ? -1 : 1) * prevPage * this.step, 400, iosEase, this.change, this.correctionEnd);
                }
            } else {
                var rpt = Math.floor(Math.abs(value / this.step));
                var dy = value % this.step;
                if (Math.abs(dy) > this.step / 2) {
                    this.to(el, property, (value < 0 ? -1 : 1) * (rpt + 1) * this.step, 400, iosEase, this.change, this.correctionEnd);
                } else {
                    this.to(el, property, (value < 0 ? -1 : 1) * rpt * this.step, 400, iosEase, this.change, this.correctionEnd);
                }
            }
        }
    }

    window.AlloyTouch = AlloyTouch;

})();
<commit_msg>移除无用属性<commit_after>/* AlloyTouch
 * By AlloyTeam http://www.alloyteam.com/
 * Github: https://github.com/AlloyTeam/AlloyTouch
 * MIT Licensed.
 */
; (function () {
    (function () {
        var lastTime = 0;
        var vendors = ['webkit', 'moz'];
        for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
            window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
            window.cancelAnimationFrame =
              window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'];
        }

        if (!window.requestAnimationFrame)
            window.requestAnimationFrame = function (callback, element) {
                var currTime = new Date().getTime();
                var timeToCall = Math.max(0, 16 - (currTime - lastTime));
                var id = window.setTimeout(function () { callback(currTime + timeToCall); },
                  timeToCall);
                lastTime = currTime + timeToCall;
                return id;
            };

        if (!window.cancelAnimationFrame)
            window.cancelAnimationFrame = function (id) {
                clearTimeout(id);
            };
    }());

    function bind(element, type, callback) {
        element.addEventListener(type, callback, false);
    }

    function iosEase(x) {
        return Math.sqrt(1 - Math.pow(x - 1, 2));
    }

    function preventDefaultTest (el, exceptions) {
        for (var i in exceptions) {
            if (exceptions[i].test(el[i])) {
                return true;
            }
        }
        return false;
    }

    var AlloyTouch = function (option) {
        this.scroller = option.target;
        this.element = typeof option.touch === "string" ? document.querySelector(option.touch) : option.touch;
        this.vertical = option.vertical;
        this.vertical === undefined && (this.vertical = true);
        this.property = option.property;
        this.tickID = 0;
        this.preX;
        this.preY;
        this.sensitivity = option.sensitivity === undefined ? 1 : option.sensitivity;
        this.factor = option.factor === undefined ? 1 : option.factor;
        this.sMf = this.sensitivity * this.factor;
        //拖动时候的摩擦因子
        this.factor1 = 1;
        this.min = option.min;
        this.max = option.max;
        this.startTime;
        this.start;
        this.deceleration = 0.0006;
        this.change = option.change || function () { };
        this.touchEnd = option.touchEnd || function () { };
        this.touchStart = option.touchStart || function () { };
        this.touchMove = option.touchMove || function () { };
        this.reboundEnd = option.reboundEnd || function () { };
        this.preventDefaultException = { tagName: /^(INPUT|TEXTAREA|BUTTON|SELECT)$/ };
        this.hasMin = !(this.min === undefined);
        this.hasMax = !(this.max === undefined);
        this.isTouchStart = false;
        this.step = option.step;
        this.spring = option.spring;
        this.spring === undefined && (this.spring = true);
        this.inertia = option.inertia;
        this.inertia === undefined && (this.inertia = true);
        this.correctionEnd = option.correctionEnd || function () { };
        this.intelligentCorrection = option.intelligentCorrection;
        if (this.hasMax && this.hasMin) {
            this.currentPage = Math.round((this.max - this.scroller[this.property]) / this.step);
        }
        bind(this.element, "touchstart", this._start.bind(this));
        bind(window, "touchmove", this._move.bind(this));
        bind(window, "touchend", this._end.bind(this));
    }

    AlloyTouch.prototype = {
        _start: function (evt) {
            this.isTouchStart = true;
            this._firstTouchMove = true;
            this._preventMoveDefault = true;
            this.touchStart(this.scroller[this.property]);
            cancelAnimationFrame(this.tickID);
            this.correctionEnd(this.scroller[this.property]);
            if (this.hasMax && this.hasMin) {
                this.currentPage = Math.round((this.max - this.scroller[this.property]) / this.step);
            }
            this.startTime = new Date().getTime();
            this._startX = this.preX = evt.touches[0].pageX;
            this._startY = this.preY = evt.touches[0].pageY;
            this.start = this.vertical ? this.preY : this.preX;
        },
        _move: function (evt) {
            if (this.isTouchStart) {
                if (this._firstTouchMove) {
                    var dDis=Math.abs(evt.touches[0].pageX - this._startX) - Math.abs(evt.touches[0].pageY - this._startY);
                    if (dDis > 0 && this.vertical) {
                        this._preventMoveDefault = false;
                    } else if (dDis < 0 && !this.vertical) {
                        this._preventMoveDefault = false;
                    }
                    this._firstTouchMove = false;
                }
                if (this._preventMoveDefault) {
                    var d = (this.vertical ? evt.touches[0].pageY - this.preY : evt.touches[0].pageX - this.preX) * this.sMf;
                    if (this.hasMax && this.scroller[this.property] > this.max && d > 0) {
                        this.factor1 = 0.3;
                    } else if (this.hasMin && this.scroller[this.property] < this.min && d < 0) {
                        this.factor1 = 0.3;
                    } else {
                        this.factor1 = 1;
                    }
                    d *= this.factor1;
                    this.preX = evt.touches[0].pageX;
                    this.preY = evt.touches[0].pageY;
                    this.scroller[this.property] += d;
                    this.change(this.scroller[this.property]);
                    var timestamp = new Date().getTime();
                    if (timestamp - this.startTime > 300) {
                        this.startTime = timestamp;
                        this.start = this.vertical ? this.preY : this.preX;
                    }
                    this.touchMove(this.scroller[this.property]);

                    evt.preventDefault();
                }
            }
        },
        _end: function (evt) {
            if (this.isTouchStart && this._preventMoveDefault) {
                var self = this;
                this.touchEnd(this.scroller[this.property]);
                if (this.hasMax && this.scroller[this.property] > this.max) {
                    this.to(this.scroller, this.property, this.max, 200, iosEase, this.change, this.reboundEnd);
                } else if (this.hasMin && this.scroller[this.property] < this.min) {
                    this.to(this.scroller, this.property, this.min, 200, iosEase, this.change, this.reboundEnd);
                } else if (this.inertia) {
                    //var y = evt.changedTouches[0].pageY;
                    var duration = new Date().getTime() - this.startTime;
                    if (duration < 300) {
                        var distance = ((this.vertical ? evt.changedTouches[0].pageY : evt.changedTouches[0].pageX) - this.start) * this.sensitivity,
                            speed = Math.abs(distance) / duration,
                            speed2 = this.factor * speed,
                            destination = this.scroller[this.property] + (speed2 * speed2) / (2 * this.deceleration) * (distance < 0 ? -1 : 1);

                        self.to(this.scroller, this.property, Math.round(destination), Math.round(speed / self.deceleration), iosEase, function (value) {

                            if (self.spring) {
                                if (self.hasMax && self.scroller[self.property] > self.max) {
                                    setTimeout(function () {
                                        cancelAnimationFrame(self.tickID);
                                        self.to(self.scroller, self.property, self.max, 200, iosEase, self.change);
                                    }, 50);
                                } else if (self.hasMin && self.scroller[self.property] < self.min) {
                                    setTimeout(function () {
                                        cancelAnimationFrame(self.tickID);
                                        self.to(self.scroller, self.property, self.min, 200, iosEase, self.change);
                                    }, 50);
                                }
                            } else {

                                if (self.hasMax && self.scroller[self.property] > self.max) {
                                    cancelAnimationFrame(self.tickID);
                                    self.scroller[self.property] = self.max;

                                } else if (self.hasMin && self.scroller[self.property] < self.min) {
                                    cancelAnimationFrame(self.tickID);
                                    self.scroller[self.property] = self.min;

                                }
                            }
                            self.change(self.scroller[self.property]);
                        }, function () {
                            if (self.step) {
                                self.correction(self.scroller, self.property);
                            }
                        });
                    } else {
                        if (self.step) {
                            self.correction(self.scroller, self.property);
                        }
                    }
                } else {
                    if (self.step) {
                        self.correction(self.scroller, self.property);
                    }
                }
                if (!preventDefaultTest(evt.target, this.preventDefaultException)) {
                    evt.preventDefault();
                }
                this.isTouchStart = false;
            }
        },
        to: function (el, property, value, time, ease, onChange, onEnd) {
            var current = el[property];
            var dv = value - current;
            var beginTime = new Date();
            var self = this;
            var toTick = function () {

                var dt = new Date() - beginTime;
                if (dt >= time) {
                    el[property] = value;
                    onChange && onChange(value);
                    onEnd && onEnd(value);
                    return;
                }
                el[property] = Math.round(dv * ease(dt / time) + current);
                self.tickID = requestAnimationFrame(toTick);
                //cancelAnimationFrame必须在 tickID = requestAnimationFrame(toTick);的后面
                onChange && onChange(el[property]);
            }
            toTick();
        },
        correction: function (el, property) {
            var value = el[property];
            if (this.intelligentCorrection&&this.hasMax && this.hasMin) {
                var prevPage = this.currentPage;
                var d = this.scroller[this.property] - (this.max - prevPage * this.step);
                if (Math.abs(d) > this.step / 20) {
                    if (d > 0) {
                        this.to(el, property, (value < 0 ? -1 : 1) * (prevPage - 1) * this.step, 400, iosEase, this.change, function (value) {
                            this.correctionEnd(value);
                            this.currentPage = prevPage - 1;
                        }.bind(this));

                    } else {
                        this.to(el, property, (value < 0 ? -1 : 1) * (prevPage + 1) * this.step, 400, iosEase, this.change, function (value) {
                            this.correctionEnd(value);
                            this.currentPage = prevPage + 1;
                        }.bind(this));
                    }

                } else {
                    this.to(el, property, (value < 0 ? -1 : 1) * prevPage * this.step, 400, iosEase, this.change, this.correctionEnd);
                }
            } else {
                var rpt = Math.floor(Math.abs(value / this.step));
                var dy = value % this.step;
                if (Math.abs(dy) > this.step / 2) {
                    this.to(el, property, (value < 0 ? -1 : 1) * (rpt + 1) * this.step, 400, iosEase, this.change, this.correctionEnd);
                } else {
                    this.to(el, property, (value < 0 ? -1 : 1) * rpt * this.step, 400, iosEase, this.change, this.correctionEnd);
                }
            }
        }
    }

    window.AlloyTouch = AlloyTouch;

})();
<|endoftext|>


<commit_before>/* @flow */

import type { Decoder, Decode } from "./Decoder"
import { Error, TypeError, ThrownError } from "./Error"
import { FieldError } from "./Field"
import * as Variant from "./Decoder"

export type Record = Decoder<$ObjMap<a, (Decoder) => b>>
export type Fields = $ObjMap<a, (b) => Decoder> & {
  [string]: Decoder<*>
}

export interface RecordDecoder {
  type: "Record";
  fields: Fields;
}

export default class RecordReader implements RecordDecoder {
  type: "Record" = "Record"
  fields: Fields
  constructor(fields: Fields) {
    this.fields = fields
  }
  static decode(fields: Fields, input: mixed): Decode {
    if (typeof input === "object" && input !== null) {
      const result: Object = {}
      for (let key of Object.keys(fields)) {
        try {
          const value = Variant.decode(fields[key], input[key])
          if (value instanceof Error) {
            return new FieldError(key, value)
          } else {
            result[key] = value
          }
        } catch (error) {
          return new FieldError(key, new ThrownError(error))
        }
      }
      return result
    } else {
      return new TypeError("object", input)
    }
  }
}
<commit_msg>Workaround facebook/flow#5301<commit_after>/* @flow */

import type { Decoder, Decode } from "./Decoder"
import { Error, TypeError, ThrownError } from "./Error"
import { FieldError } from "./Field"
import * as Variant from "./Decoder"

export type Record = Decoder<$Exact<$ObjMap<a, (Decoder) => b>>>
export type Fields = $ObjMap<a, (b) => Decoder> & {
  [string]: Decoder<*>
}

export interface RecordDecoder {
  type: "Record";
  fields: Fields;
}

export default class RecordReader implements RecordDecoder {
  type: "Record" = "Record"
  fields: Fields
  constructor(fields: Fields) {
    this.fields = fields
  }
  static decode(fields: Fields, input: mixed): Decode {
    if (typeof input === "object" && input !== null) {
      const result: Object = {}
      for (let key of Object.keys(fields)) {
        try {
          const value = Variant.decode(fields[key], input[key])
          if (value instanceof Error) {
            return new FieldError(key, value)
          } else {
            result[key] = value
          }
        } catch (error) {
          return new FieldError(key, new ThrownError(error))
        }
      }
      return result
    } else {
      return new TypeError("object", input)
    }
  }
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * The examples provided by Facebook are for non-commercial testing and
 * evaluation purposes only.
 *
 * Facebook reserves all rights not expressly granted.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
 * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * @flow
 * @providesModule ARTExample
 */
'use strict';

var React = require('react');
var ReactNative = require('react-native');
var {
  ART,
  Platform,
  View,
} = ReactNative;

const {
  Surface,
  Path,
  Group,
  Transform,
  Shape,
} = ART;

var scale = Platform.isTVOS ? 4 : 1;

class ARTExample extends React.Component{
    render(){
        const pathRect = new Path()
            .moveTo(scale * 0,scale * 0)
            .lineTo(scale * 0,scale * 110)
            .lineTo(scale * 110,scale * 110)
            .lineTo(scale * 110,scale * 0)
            .close();

        const pathCircle0 = new Path()
            .moveTo(scale * 30,scale * 5)
            .arc(scale * 0,scale * 50,scale * 25)
            .arc(scale * 0,-scale * 50,scale * 25)
            .close();

        const pathCircle1 = new Path()
            .moveTo(scale * 30,scale * 55)
            .arc(scale * 0,scale * 50,scale * 25)
            .arc(scale * 0,-scale * 50,scale * 25)
            .close();

        const pathCircle2 = new Path()
            .moveTo(scale * 55,scale * 30)
            .arc(scale * 50,scale * 0,scale * 25)
            .arc(-scale * 50,scale * 0,scale * 25)
            .close();

        const pathCircle3 = new Path()
            .moveTo(scale * 55,scale * 80)
            .arc(scale * 50,scale * 0,scale * 25)
            .arc(-scale * 50,scale * 0,scale * 25)
            .close();

        return (
            <View>
                <Surface width={scale * 200} height={scale * 200}>
                    <Group>
                        <Shape d={pathRect} stroke="#000080" fill="#000080" strokeWidth={scale}/>
                        <Shape d={pathCircle0} stroke="#FF0000" fill="#FF0000" strokeWidth={scale}/>
                        <Shape d={pathCircle1} stroke="#00FF00" fill="#00FF00" strokeWidth={scale}/>
                        <Shape d={pathCircle2} stroke="#00FFFF" fill="#00FFFF" strokeWidth={scale}/>
                        <Shape d={pathCircle3} stroke="#FFFFFF" fill="#FFFFFF" strokeWidth={scale}/>
                    </Group>
                </Surface>
            </View>
        );
    }
}

exports.title = '<ART>';
exports.displayName = 'ARTExample';
exports.description = 'ART input for numeric values';
exports.examples = [
  {
    title: 'ART Example',
    render(): React.Element<any> {
      return <ARTExample />;
    }
  },
];
<commit_msg>Fix header on RNTester file<commit_after>/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @flow
 * @providesModule ARTExample
 */
'use strict';

var React = require('react');
var ReactNative = require('react-native');
var {
  ART,
  Platform,
  View,
} = ReactNative;

const {
  Surface,
  Path,
  Group,
  Transform,
  Shape,
} = ART;

var scale = Platform.isTVOS ? 4 : 1;

class ARTExample extends React.Component{
    render(){
        const pathRect = new Path()
            .moveTo(scale * 0,scale * 0)
            .lineTo(scale * 0,scale * 110)
            .lineTo(scale * 110,scale * 110)
            .lineTo(scale * 110,scale * 0)
            .close();

        const pathCircle0 = new Path()
            .moveTo(scale * 30,scale * 5)
            .arc(scale * 0,scale * 50,scale * 25)
            .arc(scale * 0,-scale * 50,scale * 25)
            .close();

        const pathCircle1 = new Path()
            .moveTo(scale * 30,scale * 55)
            .arc(scale * 0,scale * 50,scale * 25)
            .arc(scale * 0,-scale * 50,scale * 25)
            .close();

        const pathCircle2 = new Path()
            .moveTo(scale * 55,scale * 30)
            .arc(scale * 50,scale * 0,scale * 25)
            .arc(-scale * 50,scale * 0,scale * 25)
            .close();

        const pathCircle3 = new Path()
            .moveTo(scale * 55,scale * 80)
            .arc(scale * 50,scale * 0,scale * 25)
            .arc(-scale * 50,scale * 0,scale * 25)
            .close();

        return (
            <View>
                <Surface width={scale * 200} height={scale * 200}>
                    <Group>
                        <Shape d={pathRect} stroke="#000080" fill="#000080" strokeWidth={scale}/>
                        <Shape d={pathCircle0} stroke="#FF0000" fill="#FF0000" strokeWidth={scale}/>
                        <Shape d={pathCircle1} stroke="#00FF00" fill="#00FF00" strokeWidth={scale}/>
                        <Shape d={pathCircle2} stroke="#00FFFF" fill="#00FFFF" strokeWidth={scale}/>
                        <Shape d={pathCircle3} stroke="#FFFFFF" fill="#FFFFFF" strokeWidth={scale}/>
                    </Group>
                </Surface>
            </View>
        );
    }
}

exports.title = '<ART>';
exports.displayName = 'ARTExample';
exports.description = 'ART input for numeric values';
exports.examples = [
  {
    title: 'ART Example',
    render(): React.Element<any> {
      return <ARTExample />;
    }
  },
];
<|endoftext|>


<commit_before>//TODO event channel
var eventbus = null;

$(document).ready(function () {
    new Button().usage();

    new Textbox().usage();

    new ButtonGroup().usage();

    new Carousel().usage();

    new DataViewer().usage();

    new Selection().usage();

    pubsub();
});

function pubsub() {
    // TODO  : publish in contsructor
    eventbus = new Eventbus();

    // Single Publishing
    eventbus.publish('event_4', {
        state: 'foo bar tar'
    });

    // Single Subscribing
    var subscribe = eventbus.subscribe('event_4', function (state) {
        console.log(state);
    });

    // Multiple Publishing
    eventbus.publish([
        {
            event: 'event_1',
            state: {
                foo1: 'bar1 tar1'
            }
        },
        {
            event: 'event_2',
            state: {
                foo2: 'bar2 tar2'
            }
        },
        {
            event: 'event_3',
            state: {
                foo3: 'bar3 tar3'
            }
        }
    ]);

    // Multiple Subscribing
    var subscribers = eventbus.subscribe([
        {
            event: 'event_1',
            listener: function (state) {
                console.log(state);
            }
        },
        {
            event: 'event_2',
            listener: function (state) {
                console.log(state);
            }
        },
        {
            event: 'event_3',
            listener: function (state) {
                console.log(state);
            }
        }
    ]);

    //Fire a specific event
    eventbus.fire('event_1');

    //Fire all events
    eventbus.fire();

    //Listen event bus
    eventbus.listen();
    //Callbacks removed
    eventbus.mute();

    eventbus.listen();
    //New Eventbus insctance
    eventbus.clean();
    eventbus.listen();
}
<commit_msg>eventbus test methods<commit_after>//TODO event channel
var eventbus = null;
var publisher_1 = null;
var publisher_2 = null;
var publisher_3 = null;
var subscriber_1 = null;
var subscriber_2 = null;
var subscriber_3 = null;

$(document).ready(function () {
    new Button().usage();

    new Textbox().usage();

    new ButtonGroup().usage();

    new Carousel().usage();

    new DataViewer().usage();

    new Selection().usage();

    pubsub();
});

function pubsub() {
    // TODO  : publish in contsructor
    eventbus = new Eventbus();

    publisher_1 = new Publisher('event_1', {
        foo: 'bar'
    });

    publisher_2 = new Publisher('event_2', {
        zar: 'tar'
    });

    publisher_3 = new Publisher('event_3', {
        car: 'tır'
    });

    var publisherArr = [publisher_1, publisher_2, publisher_3];
    publisherArr.forEach(function (value) {
        eventbus.publisher.register(value);
    });

    subscriber_1 = new Subscriber('event_1', function (state) {
        console.log(state);
    });

    subscriber_2 = new Subscriber('event_2', function (state) {
        console.log(state);
    });

    subscriber_3 = new Subscriber('event_3', function (state) {
        console.log(state);
    });

    var subscriberArr = [subscriber_1, subscriber_2, subscriber_3];

    subscriberArr.forEach(function (subscriber) {
        eventbus.subscriber.register(subscriber);
    });

    //Trigger spesific publisher
    eventbus.publisher.fire(publisher_1);

    // subscriber = new Subscriber('event_1', function (state) {
    //     console.log(state);
    // });

    // eventbus.publisher.register([
    //     publisher_1,
    //     publisher_2
    // ]);
    // eventbus.publisher.register(publisher_1);

    // // Single Publishing
    // eventbus.publish('event_4', {
    //     state: 'foo bar tar'
    // });
    //
    // // Single Subscribing
    // var subscribe = eventbus.subscribe('event_4', function (state) {
    //     console.log(state);
    // });

    // Multiple Publishing
    // eventbus.publisher.register([
    //     {
    //         event: 'event_1',
    //         state: {
    //             foo1: 'bar1 tar1'
    //         }
    //     },
    //     {
    //         event: 'event_2',
    //         state: {
    //             foo2: 'bar2 tar2'
    //         }
    //     },
    //     {
    //         event: 'event_3',
    //         state: {
    //             foo3: 'bar3 tar3'
    //         }
    //     }
    // ]);
    //
    // // Multiple Subscribing
    // var subscribers = eventbus.subscribe([
    //     {
    //         event: 'event_1',
    //         listener: function (state) {
    //             // console.log(state);
    //         }
    //     },
    //     {
    //         event: 'event_2',
    //         listener: function (state) {
    //             // console.log(state);
    //         }
    //     },
    //     {
    //         event: 'event_3',
    //         listener: function (state) {
    //             // console.log(state);
    //         }
    //     }
    // ]);
    //
    // console.log(eventbus.listen());

    // //Fire a specific event
    // eventbus.fire('event_1');
    //
    // //Fire all events
    // eventbus.fire();
    //
    // //Listen event bus
    // eventbus.listen();
    // //Callbacks removed
    // eventbus.mute();
    //
    // eventbus.listen();
    // //New Eventbus insctance
    // eventbus.clean();
    // eventbus.listen();
}
<|endoftext|>


<commit_before>import './js/shim/shim-jquery';
import './js/shim/shim-lightbox';
import './js/shim/shim-semantic-ui';

import 'semantic-ui-css/semantic.css';
import 'lightbox2/dist/css/lightbox.min.css';
import 'slick-carousel/slick/slick.css';

import 'sylius/ui-resources/js/app';
import './js/app';

import 'sylius/ui-resources/sass/main.scss';
import './scss/style.scss';

import 'sylius/ui-resources/img/logo.png';
import 'sylius/ui-resources/img/avatar.png';
<commit_msg>Add missing images in entry.js<commit_after>import './js/shim/shim-jquery';
import './js/shim/shim-lightbox';
import './js/shim/shim-semantic-ui';

import 'semantic-ui-css/semantic.css';
import 'lightbox2/dist/css/lightbox.min.css';
import 'slick-carousel/slick/slick.css';

import 'sylius/ui-resources/js/app';
import './js/app';

import 'sylius/ui-resources/sass/main.scss';
import './scss/style.scss';

import 'sylius/ui-resources/img/logo.png';
import 'sylius/ui-resources/img/avatar.png';

import './img/homepage-banner.jpg';
import './img/sylius-plus-banner.png';
<|endoftext|>


<commit_before>$(function(){

    const inputField = document.getElementById('q');
    const samplePopup = document.getElementById('samples');
    const productionBox = document.getElementById('production-box');
    const answerBox = document.getElementById('answer-box');
    const errorBox = document.getElementById('error-box');
    const popup = document.getElementById('popup');
    const popupCloseButton = document.getElementById('close');
    const sampleButton = document.getElementById('show-samples');
    const form = document.getElementById('f');
    const optionsBox = document.getElementById('options-box');
    const optionsHeader = document.getElementById('options-header');
    const logBox = document.getElementById("log");
    const monitor = document.getElementById("monitor");

    function setup()
    {
        popupCloseButton.onclick = function() {
            popup.style.display = "none";
        };

        sampleButton.onclick = function (event) {
            event.preventDefault();
            samplePopup.style.display = "block";
        };

        form.onsubmit = function(){
            postQuestion(inputField.value);
            return false;
        };

        let samples = document.querySelectorAll('#samples li');
        for (let i = 0; i < samples.length; i++) {
            samples[i].onclick = function (element) {
                let li = element.currentTarget;
                inputField.value = li.innerHTML;
                samplePopup.style.display = "none";
            }
        }

        updateMonitor()
    }

    function showError(error) {
        let html = "";

        for (let i = 0; i < error.length; i++) {
            html += error[i] + "
";
        }

        errorBox.innerHTML = html;
    }

    function showAnswer(answer) {
        answerBox.innerHTML = answer;
    }

    function clearInput() {
        inputField.value = "";
    }

    function showProductions(productions) {

        let html = '';

        for (let key in productions) {
            let production = productions[key];

            let matches = production.match(/([^:]+)/);
            let name = matches[1];
            let value = production.substr(name.length + 1)
                .replace(/&/g, "&")
                .replace(/</g, "<")
                .replace(/>/g, ">")
                .replace(/"/g, """)
                .replace(/'/g, "'")
                .replace("\n", "
");

            html += "
" + name + "
";
            html += "
" + value + "
";
        }

        productionBox.innerHTML = html;
    }

    function postQuestion(question) {
        $.ajax({
            url: 'ajax-answer.php',
            data: { format: "json", query: question, app: "blocks" },
            dataType: 'json',
            type: 'GET',
            success: function (data) {

                if (data.OptionKeys.length === 0) {
                    showAnswer(data.Answer);
                    clearInput();
                    log(question, data.Answer)
                    updateMonitor()
                } else {
                    showAnswer("");
                }
                showError(data.ErrorLines);
                showProductions(data.Productions);
                showOptions(data.Answer, data.OptionKeys, data.OptionValues);
            },
            error: function (request, status, error) {
                showError(error)
            }
        });
    }

    function showOptions(answer, optionKeys, optionValues) {
        let html = "
";
        let showOptions = optionKeys.length > 0;

        for (let i = 0; i < optionKeys.length; i++) {
            html += "
" + optionValues[i] + "
";
        }

        html += "
"

        optionsHeader.innerHTML = answer;
        optionsBox.innerHTML = html;

        popup.style.display = showOptions ? "block" : "none";

        let aTags = optionsBox.querySelectorAll('a');
        for (let i = 0; i < aTags.length; i++) {
            aTags[i].onclick = function (event) {
                event.preventDefault();
                postQuestion(event.currentTarget.getAttribute('href'));
            };
        }
    }

    function log(question, answer) {
        let html = "";

        html += "

" + question + "

";
        html += "
" + answer + "
";

        logBox.innerHTML = html + logBox.innerHTML;
    }

    function updateMonitor()
    {
        $.ajax({
            url: 'scene.php',
            data: { format: "json" },
            dataType: 'json',
            type: 'GET',
            success: function (data) {
                buildScene(data)
            },
            error: function (request, status, error) {
                showError(error)
            }
        });
    }

    function buildScene(data)
    {
        const scene = new THREE.Scene();
        const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

        for (let i = 0; i < data.length; i++) {
            let datum = data[i];
            let object = createObject(datum);
            scene.add(object);
        }

        const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
        scene.add( directionalLight );

        camera.position.set(5, 5, 7);
        const renderer = new THREE.WebGLRenderer();
        renderer.setSize( 600, 300 );

        monitor.innerHTML = "";
        monitor.appendChild( renderer.domElement );

        renderer.render( scene, camera );
    }

    function createObject(datum)
    {
        if (datum.Type === "pyramid") {
            return createPyramid(datum)
        } else {
            return createBlock(datum)
        }
    }

    function createPyramid(datum)
    {
        var geometry = new THREE.Geometry();

        let s = 100;
        let x = (datum.X / s);
        let y = (datum.Y / s);
        let z = -(datum.Z / s);
        let w = (datum.Width / s);
        let l = -(datum.Length / s);
        let h = (datum.Height / s);

        geometry.vertices = [
            new THREE.Vector3( x + 0, y + 0, z + 0 ),
            new THREE.Vector3( x + w, y + 0, z + 0 ),
            new THREE.Vector3( x + w, y + 0, z + l ),
            new THREE.Vector3( x + 0, y + 0, z + l ),
            new THREE.Vector3( x + 0.5 * w, y + h, z + 0.5 * l )
        ];

        geometry.faces = [
            new THREE.Face3( 0, 1, 2 ),
            new THREE.Face3( 0, 2, 3 ),
            new THREE.Face3( 1, 0, 4 ),
            new THREE.Face3( 2, 1, 4 ),
            new THREE.Face3( 3, 2, 4 ),
            new THREE.Face3( 0, 3, 4 )
        ];

        let colors = {
            red: 0xff0000,
            green: 0x00ff00,
            blue: 0x0000ff,
            white: 0xffffff,
            black: 0x808080
        }

        var material = new THREE.MeshBasicMaterial( {color: colors[datum.Color] , wireframe:false, transparent: true, opacity: 0.5} );
        return new THREE.Mesh( geometry, material );
    }

    function createBlock(datum)
    {
        var geometry = new THREE.Geometry();

        let s = 100;
        let x = (datum.X / s);
        let y = (datum.Y / s);
        let z = -(datum.Z / s);
        let w = (datum.Width / s);
        let l = -(datum.Length / s);
        let h = ((datum.Height ? datum.Height : 0.01) / s);

        geometry.vertices = [
            new THREE.Vector3( x + 0, y + 0, z + 0 ),
            new THREE.Vector3( x + w, y + 0, z + 0 ),
            new THREE.Vector3( x + w, y + 0, z + l ),
            new THREE.Vector3( x + 0, y + 0, z + l ),

            new THREE.Vector3( x + 0, y + h, z + 0 ),
            new THREE.Vector3( x + w, y + h, z + 0 ),
            new THREE.Vector3( x + w, y + h, z + l ),
            new THREE.Vector3( x + 0, y + h, z + l ),
        ];

        geometry.faces = [
            new THREE.Face3(0 ,1,  2),
            new THREE.Face3(2, 3,  0),

            new THREE.Face3( 0, 1,  5),
            new THREE.Face3( 5, 4,  0),

            new THREE.Face3( 0, 3,  7),
            new THREE.Face3( 7, 4,  0),

            new THREE.Face3( 6, 2,  1),
            new THREE.Face3( 1, 5,  6),

            new THREE.Face3( 3, 2,  6),
            new THREE.Face3( 6, 7,  3),

            new THREE.Face3( 6, 5,  4),
            new THREE.Face3( 4, 7,  6),
        ];

        let colors = {
            red: 0xff0000,
            green: 0x00ff00,
            blue: 0x0000ff,
            white: 0xffffff,
            black: 0x808080
        }

        var material = new THREE.MeshBasicMaterial( {color: colors[datum.Color] , wireframe:false, transparent: true, opacity: 0.5} );
        return new THREE.Mesh( geometry, material );
    }

    setup();
});
<commit_msg>skew!<commit_after>$(function(){

    const inputField = document.getElementById('q');
    const samplePopup = document.getElementById('samples');
    const productionBox = document.getElementById('production-box');
    const answerBox = document.getElementById('answer-box');
    const errorBox = document.getElementById('error-box');
    const popup = document.getElementById('popup');
    const popupCloseButton = document.getElementById('close');
    const sampleButton = document.getElementById('show-samples');
    const form = document.getElementById('f');
    const optionsBox = document.getElementById('options-box');
    const optionsHeader = document.getElementById('options-header');
    const logBox = document.getElementById("log");
    const monitor = document.getElementById("monitor");

    const colors = {
        red: 0xc00000,
        green: 0x008000,
        blue: 0x0000c0,
        white: 0xc0c0c0,
        black: 0x654321
    }

    const opacity = 0.9;

    function setup()
    {
        popupCloseButton.onclick = function() {
            popup.style.display = "none";
        };

        sampleButton.onclick = function (event) {
            event.preventDefault();
            samplePopup.style.display = "block";
        };

        form.onsubmit = function(){
            postQuestion(inputField.value);
            return false;
        };

        let samples = document.querySelectorAll('#samples li');
        for (let i = 0; i < samples.length; i++) {
            samples[i].onclick = function (element) {
                let li = element.currentTarget;
                inputField.value = li.innerHTML;
                samplePopup.style.display = "none";
            }
        }

        updateMonitor()
    }

    function showError(error) {
        let html = "";

        for (let i = 0; i < error.length; i++) {
            html += error[i] + "
";
        }

        errorBox.innerHTML = html;
    }

    function showAnswer(answer) {
        answerBox.innerHTML = answer;
    }

    function clearInput() {
        inputField.value = "";
    }

    function showProductions(productions) {

        let html = '';

        for (let key in productions) {
            let production = productions[key];

            let matches = production.match(/([^:]+)/);
            let name = matches[1];
            let value = production.substr(name.length + 1)
                .replace(/&/g, "&")
                .replace(/</g, "<")
                .replace(/>/g, ">")
                .replace(/"/g, """)
                .replace(/'/g, "'")
                .replace("\n", "
");

            html += "
" + name + "
";
            html += "
" + value + "
";
        }

        productionBox.innerHTML = html;
    }

    function postQuestion(question) {
        $.ajax({
            url: 'ajax-answer.php',
            data: { format: "json", query: question, app: "blocks" },
            dataType: 'json',
            type: 'GET',
            success: function (data) {

                if (data.OptionKeys.length === 0) {
                    showAnswer(data.Answer);
                    clearInput();
                    log(question, data.Answer)
                    updateMonitor()
                } else {
                    showAnswer("");
                }
                showError(data.ErrorLines);
                showProductions(data.Productions);
                showOptions(data.Answer, data.OptionKeys, data.OptionValues);
            },
            error: function (request, status, error) {
                showError(error)
            }
        });
    }

    function showOptions(answer, optionKeys, optionValues) {
        let html = "
";
        let showOptions = optionKeys.length > 0;

        for (let i = 0; i < optionKeys.length; i++) {
            html += "
" + optionValues[i] + "
";
        }

        html += "
"

        optionsHeader.innerHTML = answer;
        optionsBox.innerHTML = html;

        popup.style.display = showOptions ? "block" : "none";

        let aTags = optionsBox.querySelectorAll('a');
        for (let i = 0; i < aTags.length; i++) {
            aTags[i].onclick = function (event) {
                event.preventDefault();
                postQuestion(event.currentTarget.getAttribute('href'));
            };
        }
    }

    function log(question, answer) {
        let html = "";

        html += "

" + question + "

";
        html += "
" + answer + "
";

        logBox.innerHTML = html + logBox.innerHTML;
    }

    function updateMonitor()
    {
        $.ajax({
            url: 'scene.php',
            data: { format: "json" },
            dataType: 'json',
            type: 'GET',
            success: function (data) {
                buildScene(data)
            },
            error: function (request, status, error) {
                showError(error)
            }
        });
    }

    function buildScene(data)
    {
        const scene = new THREE.Scene();
        var camera = new THREE.OrthographicCamera( -7, 7, 7, -7, 0, 1000 );

        const group = new THREE.Group();

        for (let i = 0; i < data.length; i++) {
            let datum = data[i];
            let object = createObject(datum);
            skew(object)
            group.add(createEdges(object))
            group.add(object);
        }

        scene.add( group );

        const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
        scene.add( directionalLight );

        camera.position.set(6.75, 5, 0);
        const renderer = new THREE.WebGLRenderer({ antialias: true });
        renderer.setSize( 600, 300 );

        monitor.innerHTML = "";
        monitor.appendChild( renderer.domElement );

        renderer.render( scene, camera );
    }

    // https://stackoverflow.com/questions/36472653/drawing-edges-of-a-mesh-in-three-js
    function createEdges(mesh)
    {
        var geometry = new THREE.EdgesGeometry( mesh.geometry );
        var material = new THREE.LineBasicMaterial( { color: 0xf0f0f0 } );

        return new THREE.LineSegments( geometry, material );
    }

    // https://stackoverflow.com/questions/26021618/how-can-i-create-an-axonometric-oblique-cavalier-cabinet-with-threejs
    function skew(mesh)
    {
        var alpha = Math.PI / 4;

        var Syx = 0,
            Szx = - 0.5 * Math.cos( alpha ),
            Sxy = 0,
            Szy = - 0.5 * Math.sin( alpha ),
            Sxz = 0,
            Syz = 0;

        var matrix = new THREE.Matrix4();

        matrix.set(   1,   Syx,  Szx,  0,
            Sxy,     1,  Szy,  0,
            Sxz,   Syz,   1,   0,
            0,     0,   0,   1  );

        mesh.geometry.applyMatrix4(matrix);
    }

    function createObject(datum)
    {
        if (datum.Type === "pyramid") {
            return createPyramid(datum)
        } else {
            return createBlock(datum)
        }
    }

    function createPyramid(datum)
    {
        var geometry = new THREE.Geometry();

        let s = 100;
        let x = (datum.X / s);
        let y = (datum.Y / s);
        let z = -(datum.Z / s);
        let w = (datum.Width / s);
        let l = -(datum.Length / s);
        let h = (datum.Height / s);

        geometry.vertices = [
            new THREE.Vector3( x + 0, y + 0, z + 0 ),
            new THREE.Vector3( x + w, y + 0, z + 0 ),
            new THREE.Vector3( x + w, y + 0, z + l ),
            new THREE.Vector3( x + 0, y + 0, z + l ),
            new THREE.Vector3( x + 0.5 * w, y + h, z + 0.5 * l )
        ];

        geometry.faces = [
            new THREE.Face3( 0, 1, 2 ),
            new THREE.Face3( 0, 2, 3 ),
            new THREE.Face3( 1, 0, 4 ),
            new THREE.Face3( 2, 1, 4 ),
            new THREE.Face3( 3, 2, 4 ),
            new THREE.Face3( 0, 3, 4 )
        ];

        var material = new THREE.MeshBasicMaterial( {color: colors[datum.Color] , wireframe:false, transparent: true, opacity: opacity} );
        return new THREE.Mesh( geometry, material );
    }

    function createBlock(datum)
    {
        var geometry = new THREE.Geometry();

        let s = 100;
        let x = (datum.X / s);
        let y = (datum.Y / s);
        let z = -(datum.Z / s);
        let w = (datum.Width / s);
        let l = -(datum.Length / s);
        let h = ((datum.Height ? datum.Height : 0.01) / s);

        geometry.vertices = [
            new THREE.Vector3( x + 0, y + 0, z + 0 ),
            new THREE.Vector3( x + w, y + 0, z + 0 ),
            new THREE.Vector3( x + w, y + 0, z + l ),
            new THREE.Vector3( x + 0, y + 0, z + l ),

            new THREE.Vector3( x + 0, y + h, z + 0 ),
            new THREE.Vector3( x + w, y + h, z + 0 ),
            new THREE.Vector3( x + w, y + h, z + l ),
            new THREE.Vector3( x + 0, y + h, z + l ),
        ];

        geometry.faces = [
            new THREE.Face3(0 ,1,  2),
            new THREE.Face3(2, 3,  0),

            new THREE.Face3( 0, 1,  5),
            new THREE.Face3( 5, 4,  0),

            new THREE.Face3( 0, 3,  7),
            new THREE.Face3( 7, 4,  0),

            new THREE.Face3( 1, 2,  6),
            new THREE.Face3( 6, 5,  1),

            new THREE.Face3( 3, 2,  6),
            new THREE.Face3( 6, 7,  3),

            new THREE.Face3( 6, 5,  4),
            new THREE.Face3( 4, 7,  6),
        ];

        var material = new THREE.MeshBasicMaterial( {color: colors[datum.Color] , wireframe:false, transparent: true, opacity: opacity} );
        return new THREE.Mesh( geometry, material );
    }

    setup();
});
<|endoftext|>