<commit_before>"use strict";

var _ = require('lodash');
var async = require('async');

/**
 * Create instance of Schema
 *
 * @constructors
 * @this {Schema}
 * @class Schema
 * @return {Schema}
 */
function Schema () {
	if (!(this instanceof Schema)) {
		return new Schema();
	}
}

Schema.prototype = {
	/**
	 * attach schema to this object
	 *
	 * @method
	 * @param {Schema} schema - object for attach.
	 * @param {String} name - field name for attach.
	 * @throws {TypeError} If schema isn't Schema type
	 * @throws {TypeError} If name empty or isn't String type
	 * @return {Schema} @this
	 */
	attach: function (schema, name) {
		if (!(schema instanceof Schema)) {
			throw new TypeError('schema node must be instance of Schema');
		}

		schema.attachTo(this, name);

		schema = null;

		return this;
	},

	/**
	 * attach this object to schema
	 *
	 * @method
	 * @param {Schema} schema - attach destination object.
	 * @param {String} name - field name for attach.
	 * @throws {TypeError} If schema isn't Schema type
	 * @throws {TypeError} If name empty or isn't String type
	 * @throws {Error} If schema already has the same key name
	 * @return {Schema} @this
	 */
	attachTo: function (schema, name) {
		if (!(schema instanceof Schema)) {
			throw new TypeError('schema node must be instance of Schema');
		}

		if (!name || !_.isString(name)) {
			throw new TypeError('invalid scheme field name must be non-empty string, "' + name + '" ' + Object.prototype.toString.call(name) + ' given');
		}

		this.name = name;
		this.path = (schema.path || []).concat(name);

		schema._addField(this, name);

		schema = null;

		return this;
	},

	/**
	 * @private
	 * @param {Schema} schema - attach destination object.
	 * @param {String} name - field name for attach.
	 * @throws {Error} If schema already has the same key name
	 * @return {Schema} @this
	 */
	_addField: function (schema, name) {
		if (!this.keys) {
			this.keys = [];
		} else if (_.contains(this.keys, name)) {
			throw new Error('duplicate key "' + name + '" at "/' + (schema.path && schema.path.join('/')) + '"');
		}

		this.keys.push(name);

		if (!this.fields) {
			this.fields = [];
		}

		this.fields.push(schema);
		schema = null;

		return this;
	},

	/**
	 * @param {Boolean} isRequired - flag.
	 * @return {Schema} @this
	 */
	setRequired: function (isRequired) {
		if (isRequired) {
			this.isRequired = true;
		}

		return this;
	},

	/**
	 * @param {Boolean} nestedTypeIsArray - flag.
	 * @return {Schema} @this
	 */
	typeArray: function (nestedTypeIsArray) {
		if (nestedTypeIsArray) {
			this.isArray = true;
		}

		return this;
	},

	/**
	 * set validate options. can be called several times
	 *
	 * @method
	 * @param {Array|Object|String|Function} validation - validation options.
	 * @return {Schema} @this
	 */
	validate: function (validation) {
		if (validation) {
			if (!this.validations) {
				this.validations = [];
			}

			if (!_.isArray(validation)) {
				this.validations.push(validation);
			} else {
				this.validations = this.validations.concat(validation);
			}
		}

		return this;
	},

	/**
	 * set nested fields builder
	 *
	 * @method
	 * @param {Function} builder - builder function, has two functions in arguments [required, options].
	 * @throws {TypeError} If nested is not a function if specified
	 * @return {Schema} @this
	 */
	build: function (builder) {
		if (builder) {
			if (!_.isFunction(builder)) {
				throw new TypeError('nested builder must be function');
			}

			builder.call(this, this.required.bind(this), this.optional.bind(this));
		}

		return this;
	},

	/**
	 * add new nested schema by construct
	 *
	 * @method
	 * @param {String} name - [required] - field name.
	 * @param {Boolean} isRequired - [optional] - is required flag, default is true
	 * @param {Array|String|Object|Function} validation - [optional] - validation options.
	 * @param {Function|Schema} nested - [optional] - builder function, has two functions in arguments [required, options].
	 * @param {Boolean} nestedTypeIsArray - [optional] - set type Array of current object of Schema.
	 * @return {Schema} @this
	 */
	field: function (name, isRequired, validation, nested, nestedTypeIsArray) {
		if (_.isString(nested)) {
			nested = Schema.get(nested);
		}

		var isSchema = nested instanceof Schema;
		var schema = (isSchema ? nested.clone() : new Schema())
			.attachTo(this, name);

		if (!isSchema) {
			schema.build(nested);
		}

		schema
			.validate(validation)
			.setRequired(isRequired)
			.typeArray(nestedTypeIsArray);

		nested = null;
		return schema;
	},

	/**
	 * clone this schema
	 *
	 * @method
	 * @return {Schema} new object (clone)
	 */
	clone: function () {
		var clone = new Schema();

		_.each(this.fields, function (fieldSchema) {
			fieldSchema.clone().attachTo(clone, fieldSchema.name);
		});

		if (this.validations !== undefined) {
			clone.validations = _.cloneDeep(this.validations);
		}

		if (this.isArray !== undefined) {
			clone.isArray = this.isArray;
		}

		if (this.isRequired !== undefined) {
			clone.isRequired = this.isRequired;
		}

		return clone;
	},

	/**
	 * verify value. compare schema with some object.
	 *
	 * @private
	 * @method
	 * @param {*} value - [required] - value for check.
	 * @param {Object} options - [optional] - validation options, default is plain object.
	 * @param {Function} done - [required] - done-callback.
	 */
	verify: function (value, options, done) {
		if (_.isFunction(options)) {
			done = options;
			options = null;
		}

		options || (options = {});

		if (!_.isFunction(done)) {
			throw new Error('schema verify callback must be function, ' + (typeof done) + ' given');
		}

		var that = this;

		var _done = function (err) {
			if (err instanceof Schema.ValidationError) {
				done(null, false, err);
				return;
			}

			if (err) {
				done(err, false, null);
				return;
			}

			done(null, true, null);
		};

		if (value === undefined) {
			if (this.isRequired) {
				_done(Schema.ValidationError('required', null, this.path, value));
				return;
			}

			_done();
			return;
		}

		var validations = this.validations;
		if (!_.isEmpty(validations)) {
			if (options.validator) {
				validations = options.validator(validations);
			}

			async.reduce(validations, null, function (info, validation, done) {
				validation(value, function (err, isValid, validationError) {
					validationError || (validationError = {});

					if (err) {
						done(err);
						return;
					}

					if (!isValid) {
						done(Schema.ValidationError(validationError.ruleName, validationError.ruleParams, that.path, value));
						return;
					}

					done(null);
				});
			}, function (err) {
				if (err) {
					done(err);
					return;
				}

				that._validationInner(value, options, _done);
			});
			return;
		}

		that._validationInner(value, options, _done);
	},

	/**
	 * verify inner object
	 *
	 * @private
	 * @method
	 * @param {*} value - [required] - value for check
	 * @param {Object} options - [required] - validation options
	 * @param {Function} done - [required] - done-callback
	 */
	_validationInner: function (value, options, done) {
		var that = this;

		if (this.isArray) {
			if (!_.isArray(value)) {
				done(Schema.ValidationError('type', 'array', this.path, value));
				return;
			}

			async.reduce(value, null, function (_1, value, done) {
				that._validateFields(value, options, done);
			}, done);

			return;
		}

		that._validateFields(value, options, done);
	},

	/**
	 * verify inner fields
	 *
	 * @private
	 * @method
	 * @param {*} value - [required] - value for check
	 * @param {Object} options - [required] - validation options
	 * @param {Function} done - [required] - done-callback
	 */
	_validateFields: function (value, options, done) {
		if (!_.isObject(value)) {
			done(Schema.ValidationError('type', 'object', this.path, value));
			return;
		}

		async.reduce(this.fields, null, function (_1, fieldSchema, done) {
			var fieldValue = value[fieldSchema.name];
			fieldSchema.verify(fieldValue, options, function (err, isValid, validationError) {
				done(err || validationError || (isValid ? null : Schema.ValidationError(null, null, fieldSchema.path, fieldValue)));
			});
		}, done);
	},

	/**
	 * add new required nested schema by construct
	 *
	 * @method
	 * @param {String} name - [required] - field name.
	 * @param {Array|String|Object|Function} validation - [optional] - validation options.
	 * @param {Function} nested - [optional] - builder function, has two functions in arguments [required, options].
	 * @param {Boolean} nestedTypeIsArray - [optional] - set type Array of current object of Schema.
	 * @return {Schema}
	 */
	required: function (name, validation, nested, nestedTypeIsArray) {
		return this.field(name, true, validation, nested, nestedTypeIsArray);
	},

	/**
	 * add new optional nested schema by construct
	 *
	 * @method
	 * @param {String} name - [required] - field name.
	 * @param {Array|String|Object|Function} validation - [optional] - validation options.
	 * @param {Function} nested - [optional] - builder function, has two functions in arguments [required, options].
	 * @param {Boolean} nestedTypeIsArray - [optional] - set type Array of current object of Schema.
	 * @return {Schema}
	 */
	optional: function (name, validation, nested, nestedTypeIsArray) {
		return this.field(name, false, validation, nested, nestedTypeIsArray);
	}
};

/**
 * Schema builder. return new Schema instance;
 *
 * @static
 * @param {Array|String|Object|Function} validation - [optional] - validation options.
 * @param {Function|Schema} nested - [optional] - builder function, has two functions in arguments [required, options].
 * @param {Boolean} nestedTypeIsArray - [optional] - set type Array of current object of Schema.
 * @return {Schema}
 */
Schema.build = function (validation, nested, nestedTypeIsArray) {
	return new Schema()
		.build(nested)
		.validate(validation)
		.typeArray(nestedTypeIsArray);
};

/**
 * Schema builder. return new Schema instance; register this schema
 *
 * @static
 * @param {String} name - [required] - name for register.
 * @param {Array|String|Object|Function} validation - [optional] - validation options.
 * @param {Function|Schema} nested - [optional] - builder function, has two functions in arguments [required, options].
 * @param {Boolean} nestedTypeIsArray - [optional] - set type Array of current object of Schema.
 * @return {Schema}
 */
Schema.create = function (name, validation, nested, nestedTypeIsArray) {
	var schema = Schema.build(validation, nested, nestedTypeIsArray);
	return Schema.register(name, schema);
};

var register = {};

/**
 * Schema register
 *
 * @static
 * @param {String} name - [required] - name for register.
 * @param {Schema} schema - [required] - schema for register
 * @throws {TypeError} If invalid name type
 * @throws {TypeError} If schema name type
 * @throws {ReferenceError} If schema was already registered
 * @return {Schema}
 */
Schema.register = function (name, schema) {
	if (!_.isString(name)) {
		throw new TypeError('invalid name type, must be string');
	}

	if (!(schema instanceof Schema)) {
		throw new TypeError('invalid schema type, must be instance of Schema');
	}

	if (register.hasOwnProperty(name)) {
		throw new ReferenceError('schema "' + name + '" was already registered');
	}

	register[name] = schema;
	return schema;
};

/**
 * get registered schema
 *
 * @static
 * @param {String} name - [required] - name for register.
 * @throws {TypeError} If invalid name type
 * @throws {ReferenceError} If schema was not registered before
 * @return {Schema}
 */
Schema.get = function (name) {
	if (!_.isString(name)) {
		throw new TypeError('invalid name type, must be string');
	}

	if (!register.hasOwnProperty(name)) {
		throw new ReferenceError('schema "' + name + '" was not registered');
	}

	return register[name];
};

Schema.errorMessageMap = {};

Schema.ValidationError = function (ruleName, ruleParams, path, value) {
	ruleName || (ruleName = 'unknown');
	path || (path = []);
	value = _.cloneDeep(value);

	var result = new Error();

	Object.defineProperty(result, "type", {
		value: result.type,
		enumerable: true,
		writable: true,
		configurable: true
	});

	result.ruleName = ruleName;
	result.ruleParams = ruleParams;
	result.value = value;
	result.path = path;
	result.message = Schema.errorMessageMap[ruleName] ? Schema.errorMessageMap[ruleName](ruleName, ruleParams, path, value) : 'invalid value ' + ruleName + ' in ' + path;
	result.type = "ValidationError";

	return result;
};

module.exports = Schema;
<commit_msg>add unexpected keys validation<commit_after>"use strict";

var _ = require('lodash');
var async = require('async');

/**
 * Create instance of Schema
 *
 * @constructors
 * @this {Schema}
 * @class Schema
 * @return {Schema}
 */
function Schema () {
	if (!(this instanceof Schema)) {
		return new Schema();
	}
}

Schema.prototype = {
	/**
	 * attach schema to this object
	 *
	 * @method
	 * @param {Schema} schema - object for attach.
	 * @param {String} name - field name for attach.
	 * @throws {TypeError} If schema isn't Schema type
	 * @throws {TypeError} If name empty or isn't String type
	 * @return {Schema} @this
	 */
	attach: function (schema, name) {
		if (!(schema instanceof Schema)) {
			throw new TypeError('schema node must be instance of Schema');
		}

		schema.attachTo(this, name);

		schema = null;

		return this;
	},

	/**
	 * attach this object to schema
	 *
	 * @method
	 * @param {Schema} schema - attach destination object.
	 * @param {String} name - field name for attach.
	 * @throws {TypeError} If schema isn't Schema type
	 * @throws {TypeError} If name empty or isn't String type
	 * @throws {Error} If schema already has the same key name
	 * @return {Schema} @this
	 */
	attachTo: function (schema, name) {
		if (!(schema instanceof Schema)) {
			throw new TypeError('schema node must be instance of Schema');
		}

		if (!name || !_.isString(name)) {
			throw new TypeError('invalid scheme field name must be non-empty string, "' + name + '" ' + Object.prototype.toString.call(name) + ' given');
		}

		this.name = name;
		this.path = (schema.path || []).concat(name);

		schema._addField(this, name);

		schema = null;

		return this;
	},

	/**
	 * @private
	 * @param {Schema} schema - attach destination object.
	 * @param {String} name - field name for attach.
	 * @throws {Error} If schema already has the same key name
	 * @return {Schema} @this
	 */
	_addField: function (schema, name) {
		if (!this.keys) {
			this.keys = [];
		} else if (_.contains(this.keys, name)) {
			throw new Error('duplicate key "' + name + '" at "/' + (schema.path && schema.path.join('/')) + '"');
		}

		this.keys.push(name);

		if (!this.fields) {
			this.fields = [];
		}

		this.fields.push(schema);
		schema = null;

		return this;
	},

	/**
	 * @param {Boolean} isRequired - flag.
	 * @return {Schema} @this
	 */
	setRequired: function (isRequired) {
		this.isRequired = Boolean(isRequired);

		return this;
	},

	/**
	 * @param {Boolean} nestedTypeIsArray - flag.
	 * @return {Schema} @this
	 */
	typeArray: function (nestedTypeIsArray) {
		if (nestedTypeIsArray) {
			this.isArray = true;
		}

		return this;
	},

	/**
	 * set validate options. can be called several times
	 *
	 * @method
	 * @param {Array|Object|String|Function} validation - validation options.
	 * @return {Schema} @this
	 */
	validate: function (validation) {
		if (validation) {
			if (!this.validations) {
				this.validations = [];
			}

			if (!_.isArray(validation)) {
				this.validations.push(validation);
			} else {
				this.validations = this.validations.concat(validation);
			}
		}

		return this;
	},

	/**
	 * set nested fields builder
	 *
	 * @method
	 * @param {Function} builder - builder function, has two functions in arguments [required, options].
	 * @throws {TypeError} If nested is not a function if specified
	 * @return {Schema} @this
	 */
	build: function (builder) {
		if (builder) {
			if (!_.isFunction(builder)) {
				throw new TypeError('nested builder must be function');
			}

			builder.call(this, this.required.bind(this), this.optional.bind(this));
		}

		return this;
	},

	/**
	 * add new nested schema by construct
	 *
	 * @method
	 * @param {String} name - [required] - field name.
	 * @param {Boolean} isRequired - [optional] - is required flag, default is true
	 * @param {Array|String|Object|Function} validation - [optional] - validation options.
	 * @param {Function|Schema} nested - [optional] - builder function, has two functions in arguments [required, options].
	 * @param {Boolean} nestedTypeIsArray - [optional] - set type Array of current object of Schema.
	 * @return {Schema} @this
	 */
	field: function (name, isRequired, validation, nested, nestedTypeIsArray) {
		if (_.isString(nested)) {
			nested = Schema.get(nested);
		}

		var isSchema = nested instanceof Schema;
		var schema = (isSchema ? nested.clone() : new Schema())
			.attachTo(this, name);

		if (!isSchema) {
			schema.build(nested);
		}

		schema
			.validate(validation)
			.setRequired(isRequired)
			.typeArray(nestedTypeIsArray);

		nested = null;
		return schema;
	},

	/**
	 * clone this schema
	 *
	 * @method
	 * @return {Schema} new object (clone)
	 */
	clone: function () {
		var clone = new Schema();

		_.each(this.fields, function (fieldSchema) {
			fieldSchema.clone().attachTo(clone, fieldSchema.name);
		});

		if (this.validations !== undefined) {
			clone.validations = _.cloneDeep(this.validations);
		}

		if (this.isArray !== undefined) {
			clone.isArray = this.isArray;
		}

		if (this.isRequired !== undefined) {
			clone.isRequired = this.isRequired;
		}

		return clone;
	},

	/**
	 * verify value. compare schema with some object.
	 *
	 * @private
	 * @method
	 * @param {*} value - [required] - value for check.
	 * @param {Object} options - [optional] - validation options, default is plain object.
	 * @param {Function} done - [required] - done-callback.
	 */
	verify: function (value, options, done) {
		if (_.isFunction(options)) {
			done = options;
			options = null;
		}

		options || (options = {});

		if (!_.isFunction(done)) {
			throw new Error('schema verify callback must be function, ' + (typeof done) + ' given');
		}

		var that = this;

		var _done = function (err) {
			if (err instanceof Schema.ValidationError) {
				done(null, false, err);
				return;
			}

			if (err) {
				done(err, false, null);
				return;
			}

			done(null, true, null);
		};

		if (value === undefined) {
			if (this.isRequired) {
				_done(new Schema.ValidationError('required', null, this.path, value));
				return;
			}

			_done();
			return;
		}

		var validations = this.validations;
		if (!_.isEmpty(validations)) {
			if (options.validator) {
				validations = options.validator(validations);
			}

			async.reduce(validations, null, function (info, validation, done) {
				validation(value, function (err, isValid, validationError) {
					validationError || (validationError = {});

					if (err) {
						done(err);
						return;
					}

					if (!isValid) {
						done(new Schema.ValidationError(validationError.ruleName, validationError.ruleParams, that.path, value));
						return;
					}

					done(null);
				});
			}, function (err) {
				if (err) {
					done(err);
					return;
				}

				that._validationInner(value, options, _done);
			});
			return;
		}

		that._validationInner(value, options, _done);
	},

	/**
	 * verify inner object
	 *
	 * @private
	 * @method
	 * @param {*} value - [required] - value for check
	 * @param {Object} options - [required] - validation options
	 * @param {Function} done - [required] - done-callback
	 */
	_validationInner: function (value, options, done) {
		var that = this;

		if (this.isArray) {
			if (!_.isArray(value)) {
				done(new Schema.ValidationError('type', 'array', this.path, value));
				return;
			}

			async.reduce(value, null, function (_1, value, done) {
				that._validateFields(value, options, done);
			}, done);

			return;
		}

		that._validateFields(value, options, done);
	},

	/**
	 * verify inner fields
	 *
	 * @private
	 * @method
	 * @param {*} value - [required] - value for check
	 * @param {Object} options - [required] - validation options
	 * @param {Function} done - [required] - done-callback
	 */
	_validateFields: function (value, options, done) {
		if (_.isEmpty(this.fields)) {
			done();
			return;
		}

		if (!_.isObject(value)) {
			done(new Schema.ValidationError('type', 'object', this.path, value));
			return;
		}

		var diff = _.difference(_.keys(value), this.keys);
		if (diff.length) {
			done(new Schema.ValidationError('unexpected_keys', null, this.path, value));
			return;
		}

		async.reduce(this.fields, null, function (_1, fieldSchema, done) {
			var fieldValue = value[fieldSchema.name];
			fieldSchema.verify(fieldValue, options, function (err, isValid, validationError) {
				err = err || validationError;
				if (err) {
					done(err);
					return;
				}

				if (isValid == null || isValid) {
					done();
					return;
				}

				done(new Schema.ValidationError(null, null, fieldSchema.path, fieldValue));
			});
		}, done);
	},

	/**
	 * add new required nested schema by construct
	 *
	 * @method
	 * @param {String} name - [required] - field name.
	 * @param {Array|String|Object|Function} validation - [optional] - validation options.
	 * @param {Function} nested - [optional] - builder function, has two functions in arguments [required, options].
	 * @param {Boolean} nestedTypeIsArray - [optional] - set type Array of current object of Schema.
	 * @return {Schema}
	 */
	required: function (name, validation, nested, nestedTypeIsArray) {
		return this.field(name, true, validation, nested, nestedTypeIsArray);
	},

	/**
	 * add new optional nested schema by construct
	 *
	 * @method
	 * @param {String} name - [required] - field name.
	 * @param {Array|String|Object|Function} validation - [optional] - validation options.
	 * @param {Function} nested - [optional] - builder function, has two functions in arguments [required, options].
	 * @param {Boolean} nestedTypeIsArray - [optional] - set type Array of current object of Schema.
	 * @return {Schema}
	 */
	optional: function (name, validation, nested, nestedTypeIsArray) {
		return this.field(name, false, validation, nested, nestedTypeIsArray);
	}
};

/**
 * Schema builder. return new Schema instance;
 *
 * @static
 * @param {Array|String|Object|Function} validation - [optional] - validation options.
 * @param {Function|Schema} nested - [optional] - builder function, has two functions in arguments [required, options].
 * @param {Boolean} nestedTypeIsArray - [optional] - set type Array of current object of Schema.
 * @return {Schema}
 */
Schema.build = function (validation, nested, nestedTypeIsArray) {
	return new Schema()
		.build(nested)
		.validate(validation)
		.typeArray(nestedTypeIsArray);
};

/**
 * Schema builder. return new Schema instance; register this schema
 *
 * @static
 * @param {String} name - [required] - name for register.
 * @param {Array|String|Object|Function} validation - [optional] - validation options.
 * @param {Function|Schema} nested - [optional] - builder function, has two functions in arguments [required, options].
 * @param {Boolean} nestedTypeIsArray - [optional] - set type Array of current object of Schema.
 * @return {Schema}
 */
Schema.create = function (name, validation, nested, nestedTypeIsArray) {
	var schema = Schema.build(validation, nested, nestedTypeIsArray);
	return Schema.register(name, schema);
};

var register = {};

/**
 * Schema register
 *
 * @static
 * @param {String} name - [required] - name for register.
 * @param {Schema} schema - [required] - schema for register
 * @throws {TypeError} If invalid name type
 * @throws {TypeError} If schema name type
 * @throws {ReferenceError} If schema was already registered
 * @return {Schema}
 */
Schema.register = function (name, schema) {
	if (!_.isString(name)) {
		throw new TypeError('invalid name type, must be string');
	}

	if (!(schema instanceof Schema)) {
		throw new TypeError('invalid schema type, must be instance of Schema');
	}

	if (register.hasOwnProperty(name)) {
		throw new ReferenceError('schema "' + name + '" was already registered');
	}

	register[name] = schema;
	return schema;
};

/**
 * get registered schema
 *
 * @static
 * @param {String} name - [required] - name for register.
 * @throws {TypeError} If invalid name type
 * @throws {ReferenceError} If schema was not registered before
 * @return {Schema}
 */
Schema.get = function (name) {
	if (!_.isString(name)) {
		throw new TypeError('invalid name type, must be string');
	}

	if (!register.hasOwnProperty(name)) {
		throw new ReferenceError('schema "' + name + '" was not registered');
	}

	return register[name];
};

Schema.errorMessageMap = {};

Schema.ValidationError = function ValidationError (ruleName, ruleParams, path, value) {
	ruleName || (ruleName = 'unknown');
	path || (path = []);
	value = _.cloneDeep(value);

	var map = Schema.errorMessageMap[ruleName];

	var message = map ? map(ruleName, ruleParams, path, value) : 'invalid value ' + ruleName + ' in ' + path;
	Error.call(this, message);
	this.type = this.name = 'ValidationError';
	this.value = value;
	this.path = path;
	this.ruleName = ruleName;
	this.ruleParams = ruleParams;
};

require('util').inherits(Schema.ValidationError, Error);

module.exports = Schema;
<|endoftext|>


<commit_before>/*
 * stopsBuilder
 * returns array with shapes for GTFS, one point per row
 */
var _ = require('lodash');

module.exports = function(data){
  var stops = [];
  _.each(data[0].elements, function(element){
    if (element.type == 'node' ){
      if (element.tags.public_transport && element.tags.public_transport == 'platform'){
        stops.push({
          stop_id:element.id,
          stop_code:element.tags.ref || element.tags.rel,
          stop_name:element.tags.name || element.tags['addr:street'],
          stop_desc:element.tags.desc,
          stop_lat:element.lat,
          stop_lon:element.lon
        });
      }
    }
  });
  return stops;
};
<commit_msg>use pole number for stop names when address is missing<commit_after>/*
 * stopsBuilder
 * returns array with shapes for GTFS, one point per row
 */
var _ = require('lodash');

module.exports = function(data){
  var stops = [];
  _.each(data[0].elements, function(element){
    if (element.type == 'node' ){
      if (element.tags.public_transport && element.tags.public_transport == 'platform'){
        stops.push({
          stop_id:element.id,
          stop_code:element.tags.ref || element.tags.rel,
          stop_name:element.tags.name || element.tags['addr:street'] || element.tags.ref || element.tags.rel,
          stop_desc:element.tags.desc,
          stop_lat:element.lat,
          stop_lon:element.lon
        });
      }
    }
  });
  return stops;
};
<|endoftext|>


<commit_before>var glob = require('glob');
var fs = require('fs');
var _ = require('underscore');
var natcompare = require('./natcompare.js');

var RSS = require('rss');
var feed = new RSS({
    title:        'cdnjs.com - library updates',
    description:  'Track when libraries are added and updated! Managed by Ryan Kirkman and Thomas Davis. Sponsored and hosted by Cloudflare',
    site_url:         'http://cdnjs.com/',
    feed_url:         'http://cdnjs.com/rss.xml',
    image_url:        'http://cdnjs.com/img/poweredbycloudflare.png',
    copyright:    'Copyright © 2013 Cdnjs. All rights reserved',

    author: 'cdnjs team'
});
var exec=require('child_process').exec;
exec('git ls-tree -r --name-only HEAD | grep **/package.json | while read filename; do   echo "$(git log -1 --since="2 weeks ago" --name-status --format="%ad" -- $filename) blahcrap"; done',function(err,stdout,stderr){
    var recentLibraries = stdout.split('blahcrap');
    recentLibraries = _.filter(recentLibraries, function(lib){
      if(lib.length > 4) {
        return true;
      };
      return false;
    })
    recentLibraries = _.map(recentLibraries, function(lib){
      lib = lib.replace('\n\n', '\n');
      lib = lib.replace('\t', '\n');
      lib = lib.substr(1);
      lib = lib.split('\n');
      lib[0] = new Date(lib[0]);
      lib = {
        date: lib[0],
        change: lib[1],
        path: lib[2].replace(/(^\s+|\s+$)/g, '')
      }
      return lib;
    })
    recentLibraries = _.sortBy(recentLibraries, function(arrayElement) {
    //element will be each array, so we just return a date from first element in it
    return arrayElement.date.getTime();
    });
    recentLibraries = recentLibraries.reverse();
    _.each(recentLibraries, function (lib) {
      var package = JSON.parse(fs.readFileSync(lib.path, 'utf8'));
      var title = '';
      if(lib.change === 'M') {
        title = package.name + ' updated to version ' + package.version
      }
      if(lib.change === 'A') {
        title = package.name + '('+package.version+') was added'
      }
      var fileurl = '//cdnjs.cloudflare.com/ajax/libs/'+ package.name + '/' + package.version + '/' + package.filename;
      feed.item({
          title:          title,
          url:            package.homepage,
          guid:           package.name+package.version,
          description:    package.description + '

' + 'View file',
          date:           lib.date
      });
    })
    fs.writeFileSync('rss', feed.xml(true), 'utf8');

})

var packages = Array();

glob("ajax/libs/**/package.json", function (error, matches) {
  matches.forEach(function(element){
    var package = JSON.parse(fs.readFileSync(element, 'utf8'));
    package.assets = Array();
    var versions = glob.sync("ajax/libs/"+package.name+"/!(package.json)");
    versions.forEach(function(version) {
      var temp = Object();
      temp.version = version.replace(/^.+\//, "");
      temp.files = glob.sync(version + "/**/*.*");
      for (var i = 0; i < temp.files.length; i++){
        temp.files[i] = temp.files[i].replace(version + "/", "");
      }
      package.assets.push(temp);
    });
    package.assets.sort(function(a, b){
      return natcompare.compare(a.version, b.version);
    })
    package.assets.reverse();
    packages.push(package);
  });
  // Initialize the feed object
  fs.writeFileSync('packages.json', JSON.stringify({"packages":packages}, null, 4), 'utf8');
});
<commit_msg>updated rss<commit_after>var glob = require('glob');
var fs = require('fs');
var _ = require('underscore');
var natcompare = require('./natcompare.js');

var RSS = require('rss');
var feed = new RSS({
    title:        'cdnjs.com - library updates',
    description:  'Track when libraries are added and updated! Managed by Ryan Kirkman and Thomas Davis. Sponsored and hosted by Cloudflare',
    site_url:         'http://cdnjs.com/',
    feed_url:         'http://cdnjs.com/rss.xml',
    image_url:        'http://cdnjs.com/img/poweredbycloudflare.png',
    copyright:    'Copyright © 2013 Cdnjs. All rights reserved',

    author: 'cdnjs team'
});
var exec=require('child_process').exec;
exec('git ls-tree -r --name-only HEAD | grep **/package.json | while read filename; do   echo "$(git log -1 --since="2 weeks ago" --name-status --format="%ad" -- $filename) blahcrap"; done',function(err,stdout,stderr){
    var recentLibraries = stdout.split('blahcrap');
    recentLibraries = _.filter(recentLibraries, function(lib){
      if(lib.length > 4) {
        return true;
      };
      return false;
    })
    recentLibraries = _.map(recentLibraries, function(lib){
      lib = lib.replace('\n\n', '\n');
      lib = lib.replace('\t', '\n');
      lib = lib.substr(1);
      lib = lib.split('\n');
      lib[0] = new Date(lib[0]);
      lib = {
        date: lib[0],
        change: lib[1],
        path: lib[2].replace(/(^\s+|\s+$)/g, '')
      }
      return lib;
    })
    recentLibraries = _.sortBy(recentLibraries, function(arrayElement) {
    //element will be each array, so we just return a date from first element in it
    return arrayElement.date.getTime();
    });
    recentLibraries = recentLibraries.reverse();
    _.each(recentLibraries, function (lib) {
      var package = JSON.parse(fs.readFileSync(lib.path, 'utf8'));
      var title = '';
      if(lib.change === 'M') {
        title = package.name + ' updated to version ' + package.version
      }
      if(lib.change === 'A') {
        title = package.name + '('+package.version+') was added'
      }
      var fileurl = '//cdnjs.cloudflare.com/ajax/libs/'+ package.name + '/' + package.version + '/' + package.filename;
      feed.item({
          title:          title,
          url:            package.homepage,
          guid:           package.name+package.version,
          description:    package.description + '

' + ''+fileurl+'',
          date:           lib.date
      });
    })
    fs.writeFileSync('rss', feed.xml(true), 'utf8');

})

var packages = Array();

glob("ajax/libs/**/package.json", function (error, matches) {
  matches.forEach(function(element){
    var package = JSON.parse(fs.readFileSync(element, 'utf8'));
    package.assets = Array();
    var versions = glob.sync("ajax/libs/"+package.name+"/!(package.json)");
    versions.forEach(function(version) {
      var temp = Object();
      temp.version = version.replace(/^.+\//, "");
      temp.files = glob.sync(version + "/**/*.*");
      for (var i = 0; i < temp.files.length; i++){
        temp.files[i] = temp.files[i].replace(version + "/", "");
      }
      package.assets.push(temp);
    });
    package.assets.sort(function(a, b){
      return natcompare.compare(a.version, b.version);
    })
    package.assets.reverse();
    packages.push(package);
  });
  // Initialize the feed object
  fs.writeFileSync('packages.json', JSON.stringify({"packages":packages}, null, 4), 'utf8');
});
<|endoftext|>


<commit_before>$(document).ready(function () {
	$("#where-section").fadeTo(0, 0);
	$("#talk-section").fadeTo(0, 0);
	$("#activities-section").fadeTo(0, 0);
	$("#price-section").fadeTo(0, 0);

	function showSection($el) {
		var show = $( $el ).data("show");
		console.log(show);
		var $show = $( show );
		$show.fadeTo(1200, 1);
	}

	var offset = 220;

	var options = [
		{
			selector: '#where',
			offset: offset,
			callback: showSection
		},
		{
			selector: '#talk',
			offset: offset,
			callback: showSection
		},
		{
			selector: '#activities',
			offset: offset,
			callback: showSection
		},
		{
			selector: '#price',
			offset: offset,
			callback: showSection
		}
	];
	Materialize.scrollFire(options);
} );
<commit_msg>Minor offset in scrollfire<commit_after>$(document).ready(function () {
	$("#where-section").fadeTo(0, 0);
	$("#talk-section").fadeTo(0, 0);
	$("#activities-section").fadeTo(0, 0);
	$("#price-section").fadeTo(0, 0);

	function showSection($el) {
		var show = $( $el ).data("show");
		console.log(show);
		var $show = $( show );
		$show.fadeTo(1200, 1);
	}

	var offset = 150;

	var options = [
		{
			selector: '#where',
			offset: offset,
			callback: showSection
		},
		{
			selector: '#talk',
			offset: offset,
			callback: showSection
		},
		{
			selector: '#activities',
			offset: offset,
			callback: showSection
		},
		{
			selector: '#price',
			offset: offset,
			callback: showSection
		}
	];
	Materialize.scrollFire(options);
} );
<|endoftext|>


<commit_before>"use strict";

import React from "react";

import classNames from "classnames";

import Icon from "./Icon.js";
import TimeFormatter from "./TimeFormatter.js";
import GroupAttributes from "./GroupAttributes.js";
import ArtworkImage from "./ArtworkImage.js";

import CollectionStore from "../stores/CollectionStore.js";
import CollectionActions from "../actions/CollectionActions.js";

import PlaylistActions from "../actions/PlaylistActions.js";

import NowPlayingStore from "../stores/NowPlayingStore.js";

export class RootCollection extends React.Component {
  render() {
    var path = ["Root"];
    if (this.props.path) {
      path = this.props.path;
    }
    return <GroupContent path={path} depth={0} />;
  }
}

export class Group extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      expanded: (this.props.depth !== 1),
      favourite: false,
      checklist: false,
      common: {},
    };

    this.setCommon = this.setCommon.bind(this);
    this.setFavourite = this.setFavourite.bind(this);
    this.setChecklist = this.setChecklist.bind(this);

    this._onClick = this._onClick.bind(this);
    this._onClickHeader = this._onClickHeader.bind(this);
    this._onClickImage = this._onClickImage.bind(this);
    this._onPlayNow = this._onPlayNow.bind(this);
    this._onQueue = this._onQueue.bind(this);
    this._toggleFavourite = this._toggleFavourite.bind(this);
    this._toggleChecklist = this._toggleChecklist.bind(this);
  }

  setCommon(c) {
    this.setState({common: c});
  }

  setFavourite(v) {
    this.setState({favourite: v});
  }

  setChecklist(v) {
    this.setState({checklist: v});
  }

  render() {
    var content = null;
    var play = null;
    var attributes = null;
    var headerDiv = null;
    var image = null;

    if (this.state.expanded) {
      content = [
        <GroupContent path={this.props.path} depth={this.props.depth} setCommon={this.setCommon} setFavourite={this.setFavourite} setChecklist={this.setChecklist} key="GroupContent0" />,
      ];

      if (this.props.depth === 1) {
        content.push(

        );
      }

      var common = this.state.common;
      var duration = null;
      if (this.state.common.totalTime) {
        duration = (

            <Icon icon="schedule" extraClasses={{duration: true}}/>
            <TimeFormatter className="time" time={parseInt(common.TotalTime / 1000)} />

        );
      }

      var attributeArr = [];
      var fields = ["albumArtist", "artist", "composer", "year"];
      fields.forEach(function(f) {
        if (common[f]) {
          attributeArr.push(common[f]);
        }
      });

      if (attributeArr.length > 0) {
        attributes = <GroupAttributes list={attributeArr} />;
      }

      var favouriteIcon = this.state.favourite ? "favorite" : "favorite_border";
      var checklistIcon = this.state.checklist ? "check_circle" : "check";
      var checklistTitle = this.state.checklist ? "Remove from Checklist" : "Add to Checklist";

      play = (

          {duration}
          <Icon icon="play_arrow"title="Play Now" onClick={this._onPlayNow} />
          <Icon icon="playlist_add"title="Queue" onClick={this._onQueue} />
          <Icon icon={favouriteIcon} title="Favourite" extraClasses={{enabled: this.state.favourite}} onClick={this._toggleFavourite} />
          <Icon icon={checklistIcon} title={checklistTitle} extraClasses={{enabled: this.state.checklist}} onClick={this._toggleChecklist} />

      );

      if (this.state.common.id && this.props.depth === 1) {
        image = <ArtworkImage path={`/artwork/${common.id}`} onClick={this._onClickImage}/>;
      }
    }

    // FIXME: this is to get around the "everything else" group which has no name
    // (and can"t be closed)
    var itemName = this.props.item.name;
    if (this.props.depth === 1 && itemName === "") {
      itemName = "Misc";
    }

    var albumArtist = null;
    if (this.props.depth === 1 && (this.props.item.albumArtist || this.props.item.artist)) {
      var artist = this.props.item.albumArtist || this.props.item.artist;
      albumArtist = {artist.join(", ")};
    }

    if (itemName !== "") {
      headerDiv = (

          {image}
          {itemName}{albumArtist}
          {play}
          {attributes}

      );
    }

    var groupClasses = {
      "group": true,
      "expanded": this.state.expanded,
    };

    return (

        {headerDiv}
        {content}

    );
  }

  _onClick(e) {
    if (!this.state.expanded) {
      this._onClickHeader(e);
    }
  }

  _onClickHeader(e) {
    e.stopPropagation();
    this.setState({expanded: !this.state.expanded});
  }

  _onClickImage(e) {
    e.stopPropagation();
  }

  _onPlayNow(e) {
    PlaylistActions.addItemPlayNow(this.props.path);
    e.stopPropagation();
  }

  _onQueue(e) {
    PlaylistActions.addItem(this.props.path);
    e.stopPropagation();
  }

  _toggleFavourite(e) {
    CollectionActions.setFavourite(this.props.path, !this.state.favourite);
    e.stopPropagation();
    this.setState({favourite: !this.state.favourite});
  }

  _toggleChecklist(e) {
    CollectionActions.setChecklist(this.props.path, !this.state.checklist);
    e.stopPropagation();
    this.setState({checklist: !this.state.checklist});
  }

}

Group.propTypes = {
  path: React.PropTypes.array.isRequired,
  item: React.PropTypes.object.isRequired,
  depth: React.PropTypes.number.isRequired,
};

class GroupContent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {item: null};
    this._onChange = this._onChange.bind(this);
  }

  componentDidMount() {
    CollectionStore.addChangeListener(this._onChange);
    CollectionActions.fetch(this.props.path);
  }

  componentWillUnmount() {
    CollectionStore.removeChangeListener(this._onChange);
  }

  render() {
    var item = this.state.item;
    if (item === null) {
      return null;
    }

    if (item.groups) {
      return <GroupList path={this.props.path} depth={this.props.depth} list={item.groups} />;
    }
    return <TrackList path={this.props.path} list={item.tracks} listStyle={item.listStyle} />;
  }

  _onChange(keyPath) {
    if (CollectionStore.pathToKey(this.props.path) === keyPath) {
      var item = CollectionStore.getCollection(this.props.path);

      var common = {};
      var fields = ["totalTime", "albumArtist", "artist", "id", "composer", "year"];
      fields.forEach(function(f) {
        if (item[f]) {
          common[f] = item[f];
        }
      });

      if (Object.keys(common).length > 0 && this.props.setCommon) {
        this.props.setCommon(common);
      }
      if (this.props.setFavourite) {
        this.props.setFavourite(item.favourite);
      }
      if (this.props.setChecklist) {
        this.props.setChecklist(item.checklist);
      }
      this.setState({item: item});
    }
  }
}

GroupContent.propTypes = {
  path: React.PropTypes.array.isRequired,
  depth: React.PropTypes.number.isRequired,
};

export class GroupList extends React.Component {
  render() {
    var list = this.props.list.map(function(item) {
      return <Group path={this.props.path.concat([item.key])} depth={this.props.depth + 1} item={item} key={item.key} />;
    }.bind(this));

    return (

        {list}

    );
  }
}

GroupList.propTypes = {
  path: React.PropTypes.array.isRequired,
  depth: React.PropTypes.number.isRequired,
  list: React.PropTypes.array.isRequired,
};

class TrackList extends React.Component {
  render() {
    var discs = {};
    var discIndices = [];
    var trackNumber = 0;
    this.props.list.forEach(function(track) {
      var discNumber = track.discNumber;
      if (!discs[discNumber]) {
        discs[discNumber] = [];
        discIndices.push(discNumber);
      }
      track.key = String(trackNumber++);
      discs[discNumber].push(track);
    });

    var ols = [];
    var buildTrack = function(track) {
      return <Track key={track.id} data={track} path={this.props.path.concat([track.key])} />;
    }.bind(this);

    for (var i = 0; i < discIndices.length; i++) {
      var disc = discs[discIndices[i]];
      ols.push(
        <ol key={`disc${discIndices[i]}`} className={this.props.listStyle}>
          {disc.map(buildTrack)}

      );
    }

    return (

        {ols}

    );
  }
}

TrackList.propTypes = {
  path: React.PropTypes.array.isRequired,
  list: React.PropTypes.array.isRequired,
  listStyle: React.PropTypes.string.isRequired,
};

function isCurrent(id) {
  var t = NowPlayingStore.getTrack();
  if (t) {
    return t.id === id;
  }
  return false;
}

class Track extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      current: isCurrent(this.props.data.id),
      playing: NowPlayingStore.getPlaying(),
      expanded: false,
    };
    this._onChange = this._onChange.bind(this);
    this._onClick = this._onClick.bind(this);
    this._onPlayNow = this._onPlayNow.bind(this);
    this._onMore = this._onMore.bind(this);
    this._onQueue = this._onQueue.bind(this);
  }

  componentDidMount() {
    NowPlayingStore.addChangeListener(this._onChange);
  }

  componentWillUnmount() {
    NowPlayingStore.removeChangeListener(this._onChange);
  }

  render() {
    var durationSecs = parseInt(this.props.data.totalTime / 1000);
    var liClasses = {
      "current": this.state.current,
      "playing": this.state.current && this.state.playing,
    };

    var expanded = null;
    if (this.state.expanded) {
      var data = this.props.data;
      var attributeArr = [];
      var fields = ["albumArtist", "artist", "composer", "year"];
      fields.forEach(function(f) {
        if (data[f]) {
          attributeArr.push(data[f]);
        }
      });

      var attributes = null;
      if (attributeArr.length > 0) {
        attributes = <GroupAttributes list={attributeArr} />;
      }
      expanded = {attributes};
    }

    return (

        <span id={`track_${this.props.data.id}`} className="name">{this.props.data.name}
        <TimeFormatter className="duration" time={durationSecs} />

          <Icon icon="more_vert"title="More" onClick={this._onMore} />
          <Icon icon="play_arrow"title="Play Now" onClick={this._onPlayNow} />
          <Icon icon="playlist_add"title="Queue" onClick={this._onQueue} />

        {expanded}

    );
  }

  _onChange() {
    this.setState({
      current: isCurrent(this.props.data.id),
      playing: NowPlayingStore.getPlaying(),
    });
  }

  _onClick(e) {
    e.stopPropagation();
    CollectionActions.setCurrentTrack(this.props.data);
  }

  _onPlayNow(e) {
    e.stopPropagation();
    PlaylistActions.addItemPlayNow(this.props.path);
  }

  _onQueue(e) {
    e.stopPropagation();
    PlaylistActions.addItem(this.props.path);
  }

  _onMore(e) {
    e.stopPropagation();
    this.setState({
      expanded: !this.state.expanded,
    });
  }
}

Track.propTypes = {path: React.PropTypes.array.isRequired};
<commit_msg>Fix group timing display.<commit_after>"use strict";

import React from "react";

import classNames from "classnames";

import Icon from "./Icon.js";
import TimeFormatter from "./TimeFormatter.js";
import GroupAttributes from "./GroupAttributes.js";
import ArtworkImage from "./ArtworkImage.js";

import CollectionStore from "../stores/CollectionStore.js";
import CollectionActions from "../actions/CollectionActions.js";

import PlaylistActions from "../actions/PlaylistActions.js";

import NowPlayingStore from "../stores/NowPlayingStore.js";

export class RootCollection extends React.Component {
  render() {
    var path = ["Root"];
    if (this.props.path) {
      path = this.props.path;
    }
    return <GroupContent path={path} depth={0} />;
  }
}

export class Group extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      expanded: (this.props.depth !== 1),
      favourite: false,
      checklist: false,
      common: {},
    };

    this.setCommon = this.setCommon.bind(this);
    this.setFavourite = this.setFavourite.bind(this);
    this.setChecklist = this.setChecklist.bind(this);

    this._onClick = this._onClick.bind(this);
    this._onClickHeader = this._onClickHeader.bind(this);
    this._onClickImage = this._onClickImage.bind(this);
    this._onPlayNow = this._onPlayNow.bind(this);
    this._onQueue = this._onQueue.bind(this);
    this._toggleFavourite = this._toggleFavourite.bind(this);
    this._toggleChecklist = this._toggleChecklist.bind(this);
  }

  setCommon(c) {
    this.setState({common: c});
  }

  setFavourite(v) {
    this.setState({favourite: v});
  }

  setChecklist(v) {
    this.setState({checklist: v});
  }

  render() {
    var content = null;
    var play = null;
    var attributes = null;
    var headerDiv = null;
    var image = null;

    if (this.state.expanded) {
      content = [
        <GroupContent path={this.props.path} depth={this.props.depth} setCommon={this.setCommon} setFavourite={this.setFavourite} setChecklist={this.setChecklist} key="GroupContent0" />,
      ];

      if (this.props.depth === 1) {
        content.push(

        );
      }

      var common = this.state.common;
      var duration = null;
      if (this.state.common.totalTime) {
        duration = (

            <Icon icon="schedule" extraClasses={{duration: true}}/>
            <TimeFormatter className="time" time={parseInt(common.totalTime / 1000)} />

        );
      }

      var attributeArr = [];
      var fields = ["albumArtist", "artist", "composer", "year"];
      fields.forEach(function(f) {
        if (common[f]) {
          attributeArr.push(common[f]);
        }
      });

      if (attributeArr.length > 0) {
        attributes = <GroupAttributes list={attributeArr} />;
      }

      var favouriteIcon = this.state.favourite ? "favorite" : "favorite_border";
      var checklistIcon = this.state.checklist ? "check_circle" : "check";
      var checklistTitle = this.state.checklist ? "Remove from Checklist" : "Add to Checklist";

      play = (

          {duration}
          <Icon icon="play_arrow"title="Play Now" onClick={this._onPlayNow} />
          <Icon icon="playlist_add"title="Queue" onClick={this._onQueue} />
          <Icon icon={favouriteIcon} title="Favourite" extraClasses={{enabled: this.state.favourite}} onClick={this._toggleFavourite} />
          <Icon icon={checklistIcon} title={checklistTitle} extraClasses={{enabled: this.state.checklist}} onClick={this._toggleChecklist} />

      );

      if (this.state.common.id && this.props.depth === 1) {
        image = <ArtworkImage path={`/artwork/${common.id}`} onClick={this._onClickImage}/>;
      }
    }

    // FIXME: this is to get around the "everything else" group which has no name
    // (and can"t be closed)
    var itemName = this.props.item.name;
    if (this.props.depth === 1 && itemName === "") {
      itemName = "Misc";
    }

    var albumArtist = null;
    if (this.props.depth === 1 && (this.props.item.albumArtist || this.props.item.artist)) {
      var artist = this.props.item.albumArtist || this.props.item.artist;
      albumArtist = {artist.join(", ")};
    }

    if (itemName !== "") {
      headerDiv = (

          {image}
          {itemName}{albumArtist}
          {play}
          {attributes}

      );
    }

    var groupClasses = {
      "group": true,
      "expanded": this.state.expanded,
    };

    return (

        {headerDiv}
        {content}

    );
  }

  _onClick(e) {
    if (!this.state.expanded) {
      this._onClickHeader(e);
    }
  }

  _onClickHeader(e) {
    e.stopPropagation();
    this.setState({expanded: !this.state.expanded});
  }

  _onClickImage(e) {
    e.stopPropagation();
  }

  _onPlayNow(e) {
    PlaylistActions.addItemPlayNow(this.props.path);
    e.stopPropagation();
  }

  _onQueue(e) {
    PlaylistActions.addItem(this.props.path);
    e.stopPropagation();
  }

  _toggleFavourite(e) {
    CollectionActions.setFavourite(this.props.path, !this.state.favourite);
    e.stopPropagation();
    this.setState({favourite: !this.state.favourite});
  }

  _toggleChecklist(e) {
    CollectionActions.setChecklist(this.props.path, !this.state.checklist);
    e.stopPropagation();
    this.setState({checklist: !this.state.checklist});
  }

}

Group.propTypes = {
  path: React.PropTypes.array.isRequired,
  item: React.PropTypes.object.isRequired,
  depth: React.PropTypes.number.isRequired,
};

class GroupContent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {item: null};
    this._onChange = this._onChange.bind(this);
  }

  componentDidMount() {
    CollectionStore.addChangeListener(this._onChange);
    CollectionActions.fetch(this.props.path);
  }

  componentWillUnmount() {
    CollectionStore.removeChangeListener(this._onChange);
  }

  render() {
    var item = this.state.item;
    if (item === null) {
      return null;
    }

    if (item.groups) {
      return <GroupList path={this.props.path} depth={this.props.depth} list={item.groups} />;
    }
    return <TrackList path={this.props.path} list={item.tracks} listStyle={item.listStyle} />;
  }

  _onChange(keyPath) {
    if (CollectionStore.pathToKey(this.props.path) === keyPath) {
      var item = CollectionStore.getCollection(this.props.path);

      var common = {};
      var fields = ["totalTime", "albumArtist", "artist", "id", "composer", "year"];
      fields.forEach(function(f) {
        if (item[f]) {
          common[f] = item[f];
        }
      });

      if (Object.keys(common).length > 0 && this.props.setCommon) {
        this.props.setCommon(common);
      }
      if (this.props.setFavourite) {
        this.props.setFavourite(item.favourite);
      }
      if (this.props.setChecklist) {
        this.props.setChecklist(item.checklist);
      }
      this.setState({item: item});
    }
  }
}

GroupContent.propTypes = {
  path: React.PropTypes.array.isRequired,
  depth: React.PropTypes.number.isRequired,
};

export class GroupList extends React.Component {
  render() {
    var list = this.props.list.map(function(item) {
      return <Group path={this.props.path.concat([item.key])} depth={this.props.depth + 1} item={item} key={item.key} />;
    }.bind(this));

    return (

        {list}

    );
  }
}

GroupList.propTypes = {
  path: React.PropTypes.array.isRequired,
  depth: React.PropTypes.number.isRequired,
  list: React.PropTypes.array.isRequired,
};

class TrackList extends React.Component {
  render() {
    var discs = {};
    var discIndices = [];
    var trackNumber = 0;
    this.props.list.forEach(function(track) {
      var discNumber = track.discNumber;
      if (!discs[discNumber]) {
        discs[discNumber] = [];
        discIndices.push(discNumber);
      }
      track.key = String(trackNumber++);
      discs[discNumber].push(track);
    });

    var ols = [];
    var buildTrack = function(track) {
      return <Track key={track.id} data={track} path={this.props.path.concat([track.key])} />;
    }.bind(this);

    for (var i = 0; i < discIndices.length; i++) {
      var disc = discs[discIndices[i]];
      ols.push(
        <ol key={`disc${discIndices[i]}`} className={this.props.listStyle}>
          {disc.map(buildTrack)}

      );
    }

    return (

        {ols}

    );
  }
}

TrackList.propTypes = {
  path: React.PropTypes.array.isRequired,
  list: React.PropTypes.array.isRequired,
  listStyle: React.PropTypes.string.isRequired,
};

function isCurrent(id) {
  var t = NowPlayingStore.getTrack();
  if (t) {
    return t.id === id;
  }
  return false;
}

class Track extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      current: isCurrent(this.props.data.id),
      playing: NowPlayingStore.getPlaying(),
      expanded: false,
    };
    this._onChange = this._onChange.bind(this);
    this._onClick = this._onClick.bind(this);
    this._onPlayNow = this._onPlayNow.bind(this);
    this._onMore = this._onMore.bind(this);
    this._onQueue = this._onQueue.bind(this);
  }

  componentDidMount() {
    NowPlayingStore.addChangeListener(this._onChange);
  }

  componentWillUnmount() {
    NowPlayingStore.removeChangeListener(this._onChange);
  }

  render() {
    var durationSecs = parseInt(this.props.data.totalTime / 1000);
    var liClasses = {
      "current": this.state.current,
      "playing": this.state.current && this.state.playing,
    };

    var expanded = null;
    if (this.state.expanded) {
      var data = this.props.data;
      var attributeArr = [];
      var fields = ["albumArtist", "artist", "composer", "year"];
      fields.forEach(function(f) {
        if (data[f]) {
          attributeArr.push(data[f]);
        }
      });

      var attributes = null;
      if (attributeArr.length > 0) {
        attributes = <GroupAttributes list={attributeArr} />;
      }
      expanded = {attributes};
    }

    return (

        <span id={`track_${this.props.data.id}`} className="name">{this.props.data.name}
        <TimeFormatter className="duration" time={durationSecs} />

          <Icon icon="more_vert"title="More" onClick={this._onMore} />
          <Icon icon="play_arrow"title="Play Now" onClick={this._onPlayNow} />
          <Icon icon="playlist_add"title="Queue" onClick={this._onQueue} />

        {expanded}

    );
  }

  _onChange() {
    this.setState({
      current: isCurrent(this.props.data.id),
      playing: NowPlayingStore.getPlaying(),
    });
  }

  _onClick(e) {
    e.stopPropagation();
    CollectionActions.setCurrentTrack(this.props.data);
  }

  _onPlayNow(e) {
    e.stopPropagation();
    PlaylistActions.addItemPlayNow(this.props.path);
  }

  _onQueue(e) {
    e.stopPropagation();
    PlaylistActions.addItem(this.props.path);
  }

  _onMore(e) {
    e.stopPropagation();
    this.setState({
      expanded: !this.state.expanded,
    });
  }
}

Track.propTypes = {path: React.PropTypes.array.isRequired};
<|endoftext|>


<commit_before>/**
 * @file Defines the provider settings.
 *
 * Will set the path to Mongo, and applications id
 * Most of the configuration can be done using system environment variables.
 */

// Load environment variables from .env file
var dotenv = require('dotenv');
dotenv.load();

// node_env can either be "development" or "production"
var node_env = process.env.NODE_ENV || "development";

// Port to run the app on. 8000 for development
// (Vagrant syncs this port)
// 80 for production
var default_port = 8000;
if(node_env === "production") {
  default_port = 80;
}

var defaultEvernoteRoot = (node_env === 'development' || node_env === 'test') ? 'https://sandbox.evernote.com' : 'https://www.evernote.com';

var config = {
  env: node_env,
  port: process.env.PORT || default_port,
  workers: process.env.WORKERS || 1, // Number of workers for upload tasks

  evernoteKey: process.env.EVERNOTE_API_ID,
  evernoteSecret: process.env.EVERNOTE_API_SECRET,
  evernoteRoot: process.env.EVERNOTE_DOMAINROOT || defaultEvernoteRoot,

  usersConcurrency: process.env.USERS_CONCURRENCY || 1,
  concurrency: process.env.CONCURRENCY || 1,

  appId: process.env.ANYFETCH_API_ID,
  appSecret: process.env.ANYFETCH_API_SECRET,

  appName: process.env.APP_NAME,
  providerUrl: process.env.PROVIDER_URL,

  testToken: process.env.EVERNOTE_TEST_TOKEN || (process.env.EVERNOTE_TEST_TOKEN_PART1 + process.env.EVERNOTE_TEST_TOKEN_PART2),

  retry: 2,
  retryDelay: 4 * 1000,

  opbeat: {
    organizationId: process.env.OPBEAT_ORGANIZATION_ID,
    appId: process.env.OPBEAT_APP_ID,
    secretToken: process.env.OPBEAT_SECRET_TOKEN
  }
};

config.clientConfig = {
  consumerKey: config.evernoteKey,
  consumerSecret: config.evernoteSecret,
  sandbox: (config.env === "development" || config.env === "test")
};

// Exports configuration for use by app.js
module.exports = config;
<commit_msg>Try better config of client<commit_after>/**
 * @file Defines the provider settings.
 *
 * Will set the path to Mongo, and applications id
 * Most of the configuration can be done using system environment variables.
 */

// Load environment variables from .env file
var dotenv = require('dotenv');
dotenv.load();

// node_env can either be "development" or "production"
var node_env = process.env.NODE_ENV || "development";

// Port to run the app on. 8000 for development
// (Vagrant syncs this port)
// 80 for production
var default_port = 8000;
if(node_env === "production") {
  default_port = 80;
}

var defaultEvernoteRoot = (node_env === 'development' || node_env === 'test') ? 'https://sandbox.evernote.com' : 'https://www.evernote.com';

var config = {
  env: node_env,
  port: process.env.PORT || default_port,
  workers: process.env.WORKERS || 1, // Number of workers for upload tasks

  evernoteKey: process.env.EVERNOTE_API_ID,
  evernoteSecret: process.env.EVERNOTE_API_SECRET,
  evernoteRoot: process.env.EVERNOTE_DOMAINROOT || defaultEvernoteRoot,

  usersConcurrency: process.env.USERS_CONCURRENCY || 1,
  concurrency: process.env.CONCURRENCY || 1,

  appId: process.env.ANYFETCH_API_ID,
  appSecret: process.env.ANYFETCH_API_SECRET,

  appName: process.env.APP_NAME,
  providerUrl: process.env.PROVIDER_URL,

  testToken: process.env.EVERNOTE_TEST_TOKEN || (process.env.EVERNOTE_TEST_TOKEN_PART1 + process.env.EVERNOTE_TEST_TOKEN_PART2),

  retry: 2,
  retryDelay: 4 * 1000,

  opbeat: {
    organizationId: process.env.OPBEAT_ORGANIZATION_ID,
    appId: process.env.OPBEAT_APP_ID,
    secretToken: process.env.OPBEAT_SECRET_TOKEN
  }
};

config.clientConfig = {
  consumerKey: config.evernoteKey,
  consumerSecret: config.evernoteSecret,
  callbackUrl: config.providerUrl + '/init/callback',
  signatureMethod: "HMAC-SHA1",
  sandbox: (config.env === "development" || config.env === "test")
};

// Exports configuration for use by app.js
module.exports = config;
<|endoftext|>


<commit_before>var gulp = require('gulp');
var runSequence = require('run-sequence');
var conventionalGithubReleaser = require('conventional-github-releaser');
var git = require('gulp-git');
var fs = require('fs');

gulp.task('git-commit-changes', function () {
    return gulp.src('.')
        .pipe(git.add())
        .pipe(git.commit('[Prerelease] Bumped version number', {args: '--no-verify'}));
});

gulp.task('git-push-changes', function (cb) {
    git.push('origin', 'master', cb);
});

gulp.task('git-create-new-tag', function (cb) {
    var version = getPackageJsonVersion();
    git.tag(version, 'Created Tag for version: ' + version, function (error) {
        if (error) {
            return cb(error);
        }
        git.push('origin', 'master', { args: '--tags' }, cb);
    });

    function getPackageJsonVersion() {
        return JSON.parse(fs.readFileSync('./package.json', 'utf8')).version;
    };
});

gulp.task('conventional-release', function (done) {
    conventionalGithubReleaser({ type: 'oauth', token: process.env.CONVENTIONAL_GITHUB_RELEASER_TOKEN }, { preset: 'angular' }, done);
});

gulp.task('release', function (callback) {
    runSequence(
        'git-commit-changes',
        'git-push-changes',
        'git-create-new-tag',
        function (error) {
            if (error) {
                console.log(error.message);
            } else {
                console.log('RELEASE FINISHED SUCCESSFULLY');
            }
            callback(error);
        });
});<commit_msg>chore(build): return conventional release task<commit_after>var gulp = require('gulp');
var runSequence = require('run-sequence');
var conventionalGithubReleaser = require('conventional-github-releaser');
var git = require('gulp-git');
var fs = require('fs');

gulp.task('git-commit-changes', function () {
    return gulp.src('.')
        .pipe(git.add())
        .pipe(git.commit('[Prerelease] Bumped version number', {args: '--no-verify'}));
});

gulp.task('git-push-changes', function (cb) {
    git.push('origin', 'master', cb);
});

gulp.task('git-create-new-tag', function (cb) {
    var version = getPackageJsonVersion();
    git.tag(version, 'Created Tag for version: ' + version, function (error) {
        if (error) {
            return cb(error);
        }
        git.push('origin', 'master', { args: '--tags' }, cb);
    });

    function getPackageJsonVersion() {
        return JSON.parse(fs.readFileSync('./package.json', 'utf8')).version;
    };
});

gulp.task('conventional-release', function (done) {
    conventionalGithubReleaser({ type: 'oauth', token: process.env.CONVENTIONAL_GITHUB_RELEASER_TOKEN }, { preset: 'angular' }, done);
});

gulp.task('release', function (callback) {
    runSequence(
        'git-commit-changes',
        'git-push-changes',
        'git-create-new-tag',
        'conventional-release',
        function (error) {
            if (error) {
                console.log(error.message);
            } else {
                console.log('RELEASE FINISHED SUCCESSFULLY');
            }
            callback(error);
        });
});<|endoftext|>


<commit_before>const normalizerPlugin = function(schema, opt) {

  function listConnectedAccounts(schema, norm) {
    let curr = schema.login_method;
    let connected = [];

    opt.loginMethods.forEach((method) => {
      if(method !== curr) {
        switch(method) {
          case "local":
            if(schema.get("local.email")) {
              connected.push(method);
            }
            break;

          default:
            if(schema.get(method + ".id")) {
              connected.push(method);
            }
        }
      }
    });

    norm.connected_accounts = connected;
  }

  function normalize(schema) {
    let norm = {
      id: schema._id.toString(16),
      login_method: schema.login_method
    };

    norm.username = schema[schema.login_method].username;
    if(schema.login_method === "local") {
      norm.email = schema.local.email;
    }

    listConnectedAccounts(schema, norm);

    return norm;
  }

  schema.methods.normalize = function() {
    return normalize(this);
  };
};

module.exports = normalizerPlugin;
<commit_msg>extend normalizer to return newly added user fields<commit_after>const normalizerPlugin = function(schema, opt) {

  function listConnectedAccounts(schema, norm) {
    let curr = schema.login_method;
    let connected = [];

    opt.loginMethods.forEach((method) => {
      if(method !== curr) {
        switch(method) {
          case "local":
            if(schema.get("local.email")) {
              connected.push(method);
            }
            break;

          default:
            if(schema.get(method + ".id")) {
              connected.push(method);
            }
        }
      }
    });

    norm.connected_accounts = connected;
  }

  function normalize(schema) {

    // TODO map through the pins and liked pins to return (_id --> id)

    let norm = {
      id: schema._id.toString(16),
      login_method: schema.login_method,
      pins: schema.pins,
      liked_pins: schema.liked_pins
    };

    norm.username = schema[schema.login_method].username;
    if(schema.login_method === "local") {
      norm.email = schema.local.email;
    }

    listConnectedAccounts(schema, norm);

    return norm;
  }

  schema.methods.normalize = function() {
    return normalize(this);
  };
};

module.exports = normalizerPlugin;
<|endoftext|>


<commit_before>module.exports = function( config ) {
	config.set( {
		failOnEmptyTestSuite: false,

		// base path that will be used to resolve all patterns (eg. files, exclude)
		basePath: '../../',

		// frameworks to use
		// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
		frameworks: [
			'mocha',
			'sinon-chai',
			'fixture'
		],

		// list of files / patterns to load in the browser
		files: [
			'tests/**/*.js',
			'tests/support/fixtures/**/*'
		],

		// list of files to exclude
		exclude: [
			'tests/support/**/*.js'
		],

		// preprocess matching files before serving them to the browser
		// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
		preprocessors: {
			'tests/**/*.js': [ 'rollup' ],
			'tests/support/fixtures/**/*.html': [ 'html2js' ],
			'tests/support/fixtures/**/*.json': [ 'json_fixtures' ]
		},

		// test results reporter to use
		// possible values: 'dots', 'progress'
		// available reporters: https://npmjs.org/browse/keyword/karma-reporter
		reporters: [
			'progress',
			'coverage'
		],

		// web server port
		port: 9876,

		// enable / disable colors in the output (reporters and logs)
		colors: true,

		// level of logging
		// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
		logLevel: config.LOG_INFO,

		// enable / disable watching file and executing tests whenever any file changes
		autoWatch: false,

		// start these browsers
		// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
		browsers: [
			'Chrome',
			'Firefox'
		],

		// Continuous Integration mode
		// if true, Karma captures browsers, runs the tests and exits
		singleRun: true,

		// Concurrency level
		// how many browser should be started simultaneous
		concurrency: 1,

		rollupPreprocessor: {
			rollup: {
				plugins: [
					require( 'rollup-plugin-istanbul' )( {
						exclude: [ 'tests/**/*.js' ]
				    } ),
					require( 'rollup-plugin-mockr' )( require( '../mockr/default' ) ),
					require( 'rollup-plugin-commonjs' )(),
					require( 'rollup-plugin-node-resolve' )( {
						jsnext: true,
						main: false
					} )
				]
			},
			bundle: {
				format: 'iife'
			}
		},

		jsonFixturesPreprocessor: {
			variableName: '__json__'
		},

		coverageReporter: {
			reporters: [
				{ type: 'text-summary' },
				{ type: 'lcovonly' }
			]
		}
	} );
};
<commit_msg>build(karma): fix configuration for rollup preprocessor<commit_after>module.exports = function( config ) {
	config.set( {
		failOnEmptyTestSuite: false,

		// base path that will be used to resolve all patterns (eg. files, exclude)
		basePath: '../../',

		// frameworks to use
		// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
		frameworks: [
			'mocha',
			'sinon-chai',
			'fixture'
		],

		// list of files / patterns to load in the browser
		files: [
			'tests/**/*.js',
			'tests/support/fixtures/**/*'
		],

		// list of files to exclude
		exclude: [
			'tests/support/**/*.js'
		],

		// preprocess matching files before serving them to the browser
		// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
		preprocessors: {
			'tests/**/*.js': [ 'rollup' ],
			'tests/support/fixtures/**/*.html': [ 'html2js' ],
			'tests/support/fixtures/**/*.json': [ 'json_fixtures' ]
		},

		// test results reporter to use
		// possible values: 'dots', 'progress'
		// available reporters: https://npmjs.org/browse/keyword/karma-reporter
		reporters: [
			'progress',
			'coverage'
		],

		// web server port
		port: 9876,

		// enable / disable colors in the output (reporters and logs)
		colors: true,

		// level of logging
		// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
		logLevel: config.LOG_INFO,

		// enable / disable watching file and executing tests whenever any file changes
		autoWatch: false,

		// start these browsers
		// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
		browsers: [
			'Chrome',
			'Firefox'
		],

		// Continuous Integration mode
		// if true, Karma captures browsers, runs the tests and exits
		singleRun: true,

		// Concurrency level
		// how many browser should be started simultaneous
		concurrency: 1,

		rollupPreprocessor: {
			plugins: [
				require( 'rollup-plugin-istanbul' )( {
					exclude: [ 'tests/**/*.js' ]
				} ),
				require( 'rollup-plugin-mockr' )( require( '../mockr/default' ) ),
				require( 'rollup-plugin-commonjs' )(),
				require( 'rollup-plugin-node-resolve' )( {
					jsnext: true,
					main: false
				} )
			],
			format: 'iife'
		},

		jsonFixturesPreprocessor: {
			variableName: '__json__'
		},

		coverageReporter: {
			reporters: [
				{ type: 'text-summary' },
				{ type: 'lcovonly' }
			]
		}
	} );
};
<|endoftext|>


<commit_before>'use strict';

var create            = require('es5-ext/object/create')
  , d                 = require('d')
  , notifyReverse     = require('../notify/reverse-all')
  , onValueTurn       = require('../notify/on-value-turn')
  , emitDescDescValue = require('../utils/emit-desc-desc-value')
  , turn              = require('./turn-prototype')

  , hasOwnProperty = Object.hasOwnProperty, keys = Object.keys
  , getPrototypeOf = Object.getPrototypeOf, defineProperty = Object.defineProperty
  , isObjectId = RegExp.prototype.test.bind(/^[0-9a-z][A-Za-z0-9]*$/)

  , snapshotObservableObj, snapshotObservableObjKey, switchReverse
  , notifyObservableObj, notifyObservableObjKey, notifyReverses
  , emitDescs, emitMultiples, emitItems, emitDescDescs;

snapshotObservableObj = function (obj, map) {
	var descs, sKey, value, objMap;
	if (obj.hasOwnProperty('__isObservable__')) {
		descs = obj.__descriptors__;
		for (sKey in descs) {
			value = obj._get_(sKey);
			if (value === undefined) continue;
			if (!objMap) {
				if (!map) map = create(null);
				objMap = map[obj.__id__] = create(null);
			}
			objMap[sKey] = value;
		}
	}
	if (!obj.hasOwnProperty('__descendants__')) return map;
	obj.__descendants__._plainForEach_(function (obj) {
		map = snapshotObservableObj(obj, map);
	});
	return map;
};

snapshotObservableObjKey = function (obj, sKey, map) {
	var value;
	if (obj.hasOwnProperty('__isObservable__')) {
		value = obj._get_(sKey);
		if (value !== undefined) {
			if (!map) map = create(null);
			map[obj.__id__] = value;
		}
	}
	if (!obj.hasOwnProperty('__descendants__')) return map;
	obj.__descendants__._plainForEach_(function (obj) {
		map = snapshotObservableObjKey(obj, sKey, map);
	});
	return map;
};

notifyObservableObj = function (obj, map, dbEvent, postponed) {
	var descs, sKey, nu, old, objMap, marked = false;
	if (obj.hasOwnProperty('__isObservable__')) {
		descs = obj.__descriptors__;
		objMap = map && map[obj.__id__];
		for (sKey in descs) {
			nu = obj._get_(sKey);
			old = objMap && objMap[sKey];
			if (old !== undefined) delete objMap[sKey];
			if (nu === old) continue;
			if (!marked) {
				marked = true;
				obj._postponed_ += 1;
				if (!postponed) postponed = [obj];
				else postponed.push(obj);
			}
			if (nu === undefined) obj._emitDelete_(obj._keys_[sKey], old, dbEvent);
			else obj._emitSet_(obj._keys_[sKey], nu, old, dbEvent);
		}
		if (objMap) {
			for (sKey in objMap) {
				if (!marked) {
					marked = true;
					obj._postponed_ += 1;
					if (!postponed) postponed = [obj];
					else postponed.push(obj);
				}
				obj._emitDelete_(obj._keys_[sKey], objMap[sKey], dbEvent);
			}
		}
	}
	if (!obj.hasOwnProperty('__descendants__')) return postponed;
	obj.__descendants__._plainForEach_(function (obj) {
		postponed = notifyObservableObj(obj, map, dbEvent, postponed);
	});
	return postponed;
};

notifyObservableObjKey = function (obj, sKey, map, dbEvent, postponed) {
	var nu, old;
	if (obj.hasOwnProperty('__isObservable__')) {
		nu = obj._get_(sKey);
		old = map[obj.__id__];
		if (nu !== old) {
			obj._postponed_ += 1;
			if (!postponed) postponed = [obj];
			else postponed.push(obj);
			if (nu === undefined) obj._emitDelete_(obj._keys_[sKey], old, dbEvent);
			else obj._emitSet_(obj._keys_[sKey], nu, old, dbEvent);
		}
	}
	if (!obj.hasOwnProperty('__descendants__')) return postponed;
	obj.__descendants__._plainForEach_(function (obj) {
		postponed = notifyObservableObjKey(obj, sKey, map, dbEvent, postponed);
	});
	return postponed;
};

notifyReverses = function (obj, nu, postponed) {
	var isObjectType;
	if (obj.constructor.prototype !== obj) return postponed;
	if (obj.hasOwnProperty('__reverseMaps__')) {
		isObjectType = obj.database.isObjectType;
		keys(obj.__reverseMaps__).forEach(function (sKey) {
			var map = this[sKey], desc = obj.__descriptors__[sKey];
			if (desc.reverse === undefined) return;
			if (!isObjectType(desc.type)) return;
			postponed = notifyReverse(desc.type.prototype,
				obj._serialize_(desc.reverse), nu, map, desc.unique, postponed);
		}, obj.__reverseMaps__);
	}
	if (!obj.hasOwnProperty('__descendants__')) return postponed;
	obj.__descendants__._plainForEach_(function (obj) {
		postponed = notifyReverses(obj, nu, postponed);
	});
	return postponed;
};

switchReverse = function (obj, nu, old, postponed) {
	var maps, objProto, nuOt, oldOt, processMap;

	// Own and descendants reverse maps
	objProto = nu.database.Object.prototype;
	if (nu === objProto) nuOt = true;
	else if (objProto.isPrototypeOf(nu)) nuOt = true;
	if (old === objProto) oldOt = true;
	else if (objProto.isPrototypeOf(old)) oldOt = true;

	if (nuOt !== oldOt) postponed = notifyReverses(obj, nuOt, postponed);

	if (old.__reverseMaps__ === nu.__reverseMaps__) return postponed;

	// Old proto reverse maps
	maps = old.__reverseMaps__;
	if (maps) {
		processMap = function (sKey) {
			postponed = maps[sKey]._excludeObjBranch_(obj, sKey, postponed);
		};
		while (maps) {
			keys(maps).forEach(processMap);
			maps = getPrototypeOf(maps);
		}
	}

	// New proto reverse maps
	maps = nu.__reverseMaps__;
	if (maps) {
		processMap = function (sKey) {
			postponed = maps[sKey]._includeObjBranch_(obj, sKey, postponed);
		};
		while (maps) {
			keys(maps).forEach(processMap);
			maps = getPrototypeOf(maps);
		}
	}
	return postponed;
};

emitMultiples = function (obj, nuProto, oldProto, dbEvent, postponed) {
	var nuItems = nuProto.__multiples__, oldItems = oldProto.__multiples__
	  , sKey, nuSet, done, oldSet;
	if (nuItems === oldItems) return postponed;
	done = create(null);
	for (sKey in nuItems) {
		nuSet = nuItems[sKey];
		done[sKey] = true;
		oldSet = oldItems[sKey];
		if (nuSet === oldSet) continue;
		postponed = emitItems(obj, sKey, nuSet, oldSet, dbEvent, postponed);
	}
	for (sKey in oldItems) {
		if (done[sKey]) continue;
		oldSet = oldItems[sKey];
		postponed = emitItems(obj, sKey, null, oldSet, dbEvent, postponed);
	}
	return postponed;
};

emitItems = function (obj, sKey, nuSet, oldSet, dbEvent, postponed) {
	var done, iKey, item, ownSet, nu, old;
	if (obj.hasOwnProperty('__multiples__') &&
			hasOwnProperty.call(obj.__multiples__, sKey)) {
		ownSet = obj.__multiples__[sKey];
	}
	if (nuSet) {
		done = create(null);
		for (iKey in nuSet) {
			done[iKey] = true;
			if (ownSet && hasOwnProperty.call(ownSet, iKey) &&
					ownSet[iKey].hasOwnProperty('_value_')) {
				continue;
			}
			item = nuSet[iKey];
			nu = Boolean(item._value_);
			old = Boolean(oldSet && oldSet[iKey] && oldSet[iKey]._value_);
			if (nu === old) continue;
			postponed = item._emitValue_(obj, nu, old, dbEvent, postponed);
		}
		if (!oldSet) return postponed;
	}
	for (iKey in oldSet) {
		if (done && done[iKey]) continue;
		if (ownSet && hasOwnProperty.call(ownSet, iKey) &&
				ownSet[iKey].hasOwnProperty('_value_')) {
			continue;
		}
		item = oldSet[iKey];
		if (!item._value_) continue;
		postponed = item._emitValue_(obj, false, true, dbEvent, postponed);
	}
	return postponed;
};

emitDescDescs = function (obj, pSKey, nuDesc, oldDesc, dbEvent, postponed) {
	var descProto = obj.database.Base.prototype.__descriptorPrototype__
	  , nuDescDesc, done, nu, old, oldDescDesc, key, ownDesc;

	if (pSKey) {
		if (obj.hasOwnProperty('__descriptors__') &&
				hasOwnProperty.call(obj.__descriptors__, pSKey)) {
			ownDesc = obj.__descriptors__[pSKey];
		}
	} else if (obj.hasOwnProperty('__descriptorPrototype__')) {
		ownDesc = obj.__descriptorPrototype__;
	}
	if (nuDesc) {
		done = create(null);
		for (key in nuDesc) {
			if (key === 'reverse') continue;
			done[key] = true;
			if (ownDesc && ownDesc.hasOwnProperty(key)) continue;
			nu = nuDesc[key];
			old = oldDesc ? oldDesc[key] : descProto[key];
			if (nu === old) continue;
			nuDescDesc = nuDesc.__descriptors__[key];
			postponed = emitDescDescValue(obj, nu, old, pSKey, key,
				nuDescDesc && nuDescDesc._sideNotify_,
				nuDescDesc && nuDescDesc._postNotify_, dbEvent, postponed);
		}
	}

	if (oldDesc) {
		for (key in oldDesc) {
			if (key === 'reverse') continue;
			if (done && done[key]) continue;
			if (ownDesc && ownDesc.hasOwnProperty(key)) continue;
			old = oldDesc[key];
			if (old === descProto[key]) continue;
			oldDescDesc = oldDesc.__descriptors__[key];
			postponed = emitDescDescValue(obj, undefined, old, pSKey, key,
				oldDescDesc && oldDescDesc._sideNotify_,
				oldDescDesc && oldDescDesc._postNotify_, dbEvent, postponed);
		}
	}
	return postponed;
};

emitDescs = function (obj, nuProto, oldProto, dbEvent, postponed) {
	var nuDescs = nuProto.__descriptors__, oldDescs = oldProto.__descriptors__
	  , sKey, ownDescs, nuDesc, done, nu, old, oldDesc;
	if (nuDescs === oldDescs) return postponed;
	ownDescs = obj.hasOwnProperty('__descriptors__') ? obj.__descriptors__ : null;
	done = create(null);
	for (sKey in nuDescs) {
		done[sKey] = true;
		nuDesc = nuDescs[sKey];
		oldDesc = oldDescs[sKey] || oldProto.__descriptorPrototype__;
		postponed = emitDescDescs(obj, sKey, nuDesc, oldDesc, dbEvent, postponed);
		if (ownDescs && hasOwnProperty.call(ownDescs, sKey)) {
			if (ownDescs[sKey].hasOwnProperty('_value_')) continue;
			nu = nuDesc._resolveInner_();
			old = oldDesc ? oldDesc._resolveInner_() : undefined;
		} else {
			nu = nuDesc._resolveValueValue_();
			old = oldDesc ? oldDesc._resolveValueValue_() : undefined;
		}
		if (nu === old) continue;
		postponed = nuDesc._emitValue_(obj, nu, old, dbEvent, postponed);
	}
	for (sKey in oldDescs) {
		if (done[sKey]) continue;
		oldDesc = oldDescs[sKey];
		postponed = emitDescDescs(obj, sKey, nuProto.__descriptorPrototype__,
			oldDesc, dbEvent, postponed);
		if (ownDescs && hasOwnProperty.call(ownDescs, sKey)) {
			if (ownDescs[sKey].hasOwnProperty('_value_')) continue;
			old = oldDesc._resolveInner_();
		} else {
			old = oldDesc._resolveValueValue_();
		}
		if (old === undefined) continue;
		postponed = oldDesc._emitValue_(obj, undefined, old, dbEvent, postponed);
	}
	return postponed;
};

exports.object = function (obj, nu, dbEvent, postponed) {
	var old = getPrototypeOf(obj)
	  , objSnapshot = snapshotObservableObj(obj);

	defineProperty(obj, '__prototypeTurnInProgress__', d(true));
	postponed = switchReverse(obj, nu, old, postponed);
	postponed = turn.object(obj, nu, postponed);
	postponed = notifyObservableObj(obj, objSnapshot, dbEvent, postponed);
	if (old.__descriptorPrototype__ !== nu.__descriptorPrototpe__) {
		postponed = emitDescDescs(obj, '', nu.__descriptorPrototpe__,
			old.__descriptorPrototype__, dbEvent, postponed);
	}
	postponed = emitDescs(obj, nu, old, dbEvent, postponed);
	postponed = emitMultiples(obj, nu, old, dbEvent, postponed);

	delete obj.__prototypeTurnInProgress__;
	if (!isObjectId(obj.__id__)) return postponed;
	return onValueTurn(obj, nu.constructor, old.constructor, dbEvent, postponed);
};

exports.descriptor = function (desc, nuProto, dbEvent, postponed) {
	var oldProto = getPrototypeOf(desc), nu, old
	  , objSnapshot = snapshotObservableObjKey(desc.object, desc._sKey_);

	postponed = turn.descriptor(desc, nuProto, postponed);
	postponed = notifyObservableObjKey(desc.object, desc._sKey_, objSnapshot,
		dbEvent, postponed);
	postponed = emitDescDescs(desc.object, desc._sKey_, nuProto, oldProto,
		dbEvent, postponed);
	if (desc.hasOwnProperty('_value_')) return postponed;
	nu = nuProto._resolveInner_();
	old = oldProto._resolveInner_();
	if (nu === old) return postponed;
	return desc._emitValue_(desc.object, nu, old, dbEvent, postponed);
};
<commit_msg>Better variable names<commit_after>'use strict';

var create            = require('es5-ext/object/create')
  , d                 = require('d')
  , notifyReverse     = require('../notify/reverse-all')
  , onValueTurn       = require('../notify/on-value-turn')
  , emitDescDescValue = require('../utils/emit-desc-desc-value')
  , turn              = require('./turn-prototype')

  , hasOwnProperty = Object.hasOwnProperty, keys = Object.keys
  , getPrototypeOf = Object.getPrototypeOf, defineProperty = Object.defineProperty
  , isObjectId = RegExp.prototype.test.bind(/^[0-9a-z][A-Za-z0-9]*$/)

  , snapshotObservableObj, snapshotObservableObjKey, switchReverse
  , notifyObservableObj, notifyObservableObjKey, notifyReverses
  , emitDescs, emitMultiples, emitItems, emitDescDescs;

snapshotObservableObj = function (obj, map) {
	var descs, sKey, value, objMap;
	if (obj.hasOwnProperty('__isObservable__')) {
		descs = obj.__descriptors__;
		for (sKey in descs) {
			value = obj._get_(sKey);
			if (value === undefined) continue;
			if (!objMap) {
				if (!map) map = create(null);
				objMap = map[obj.__id__] = create(null);
			}
			objMap[sKey] = value;
		}
	}
	if (!obj.hasOwnProperty('__descendants__')) return map;
	obj.__descendants__._plainForEach_(function (obj) {
		map = snapshotObservableObj(obj, map);
	});
	return map;
};

snapshotObservableObjKey = function (obj, sKey, map) {
	var value;
	if (obj.hasOwnProperty('__isObservable__')) {
		value = obj._get_(sKey);
		if (value !== undefined) {
			if (!map) map = create(null);
			map[obj.__id__] = value;
		}
	}
	if (!obj.hasOwnProperty('__descendants__')) return map;
	obj.__descendants__._plainForEach_(function (obj) {
		map = snapshotObservableObjKey(obj, sKey, map);
	});
	return map;
};

notifyObservableObj = function (obj, map, dbEvent, postponed) {
	var descs, sKey, nu, old, objMap, marked = false;
	if (obj.hasOwnProperty('__isObservable__')) {
		descs = obj.__descriptors__;
		objMap = map && map[obj.__id__];
		for (sKey in descs) {
			nu = obj._get_(sKey);
			old = objMap && objMap[sKey];
			if (old !== undefined) delete objMap[sKey];
			if (nu === old) continue;
			if (!marked) {
				marked = true;
				obj._postponed_ += 1;
				if (!postponed) postponed = [obj];
				else postponed.push(obj);
			}
			if (nu === undefined) obj._emitDelete_(obj._keys_[sKey], old, dbEvent);
			else obj._emitSet_(obj._keys_[sKey], nu, old, dbEvent);
		}
		if (objMap) {
			for (sKey in objMap) {
				if (!marked) {
					marked = true;
					obj._postponed_ += 1;
					if (!postponed) postponed = [obj];
					else postponed.push(obj);
				}
				obj._emitDelete_(obj._keys_[sKey], objMap[sKey], dbEvent);
			}
		}
	}
	if (!obj.hasOwnProperty('__descendants__')) return postponed;
	obj.__descendants__._plainForEach_(function (obj) {
		postponed = notifyObservableObj(obj, map, dbEvent, postponed);
	});
	return postponed;
};

notifyObservableObjKey = function (obj, sKey, map, dbEvent, postponed) {
	var nu, old;
	if (obj.hasOwnProperty('__isObservable__')) {
		nu = obj._get_(sKey);
		old = map[obj.__id__];
		if (nu !== old) {
			obj._postponed_ += 1;
			if (!postponed) postponed = [obj];
			else postponed.push(obj);
			if (nu === undefined) obj._emitDelete_(obj._keys_[sKey], old, dbEvent);
			else obj._emitSet_(obj._keys_[sKey], nu, old, dbEvent);
		}
	}
	if (!obj.hasOwnProperty('__descendants__')) return postponed;
	obj.__descendants__._plainForEach_(function (obj) {
		postponed = notifyObservableObjKey(obj, sKey, map, dbEvent, postponed);
	});
	return postponed;
};

notifyReverses = function (obj, nu, postponed) {
	var isObjectType;
	if (obj.constructor.prototype !== obj) return postponed;
	if (obj.hasOwnProperty('__reverseMaps__')) {
		isObjectType = obj.database.isObjectType;
		keys(obj.__reverseMaps__).forEach(function (sKey) {
			var map = this[sKey], desc = obj.__descriptors__[sKey];
			if (desc.reverse === undefined) return;
			if (!isObjectType(desc.type)) return;
			postponed = notifyReverse(desc.type.prototype,
				obj._serialize_(desc.reverse), nu, map, desc.unique, postponed);
		}, obj.__reverseMaps__);
	}
	if (!obj.hasOwnProperty('__descendants__')) return postponed;
	obj.__descendants__._plainForEach_(function (obj) {
		postponed = notifyReverses(obj, nu, postponed);
	});
	return postponed;
};

switchReverse = function (obj, nu, old, postponed) {
	var maps, objProto, nuTurn, oldTurn, processMap;

	// Own and descendants reverse maps
	objProto = nu.database.Object.prototype;
	if (nu === objProto) nuTurn = true;
	else if (objProto.isPrototypeOf(nu)) nuTurn = true;
	if (old === objProto) oldTurn = true;
	else if (objProto.isPrototypeOf(old)) oldTurn = true;

	if (nuTurn !== oldTurn) postponed = notifyReverses(obj, nuTurn, postponed);

	if (old.__reverseMaps__ === nu.__reverseMaps__) return postponed;

	// Old proto reverse maps
	maps = old.__reverseMaps__;
	if (maps) {
		processMap = function (sKey) {
			postponed = maps[sKey]._excludeObjBranch_(obj, sKey, postponed);
		};
		while (maps) {
			keys(maps).forEach(processMap);
			maps = getPrototypeOf(maps);
		}
	}

	// New proto reverse maps
	maps = nu.__reverseMaps__;
	if (maps) {
		processMap = function (sKey) {
			postponed = maps[sKey]._includeObjBranch_(obj, sKey, postponed);
		};
		while (maps) {
			keys(maps).forEach(processMap);
			maps = getPrototypeOf(maps);
		}
	}
	return postponed;
};

emitMultiples = function (obj, nuProto, oldProto, dbEvent, postponed) {
	var nuItems = nuProto.__multiples__, oldItems = oldProto.__multiples__
	  , sKey, nuSet, done, oldSet;
	if (nuItems === oldItems) return postponed;
	done = create(null);
	for (sKey in nuItems) {
		nuSet = nuItems[sKey];
		done[sKey] = true;
		oldSet = oldItems[sKey];
		if (nuSet === oldSet) continue;
		postponed = emitItems(obj, sKey, nuSet, oldSet, dbEvent, postponed);
	}
	for (sKey in oldItems) {
		if (done[sKey]) continue;
		oldSet = oldItems[sKey];
		postponed = emitItems(obj, sKey, null, oldSet, dbEvent, postponed);
	}
	return postponed;
};

emitItems = function (obj, sKey, nuSet, oldSet, dbEvent, postponed) {
	var done, iKey, item, ownSet, nu, old;
	if (obj.hasOwnProperty('__multiples__') &&
			hasOwnProperty.call(obj.__multiples__, sKey)) {
		ownSet = obj.__multiples__[sKey];
	}
	if (nuSet) {
		done = create(null);
		for (iKey in nuSet) {
			done[iKey] = true;
			if (ownSet && hasOwnProperty.call(ownSet, iKey) &&
					ownSet[iKey].hasOwnProperty('_value_')) {
				continue;
			}
			item = nuSet[iKey];
			nu = Boolean(item._value_);
			old = Boolean(oldSet && oldSet[iKey] && oldSet[iKey]._value_);
			if (nu === old) continue;
			postponed = item._emitValue_(obj, nu, old, dbEvent, postponed);
		}
		if (!oldSet) return postponed;
	}
	for (iKey in oldSet) {
		if (done && done[iKey]) continue;
		if (ownSet && hasOwnProperty.call(ownSet, iKey) &&
				ownSet[iKey].hasOwnProperty('_value_')) {
			continue;
		}
		item = oldSet[iKey];
		if (!item._value_) continue;
		postponed = item._emitValue_(obj, false, true, dbEvent, postponed);
	}
	return postponed;
};

emitDescDescs = function (obj, pSKey, nuDesc, oldDesc, dbEvent, postponed) {
	var descProto = obj.database.Base.prototype.__descriptorPrototype__
	  , nuDescDesc, done, nu, old, oldDescDesc, key, ownDesc;

	if (pSKey) {
		if (obj.hasOwnProperty('__descriptors__') &&
				hasOwnProperty.call(obj.__descriptors__, pSKey)) {
			ownDesc = obj.__descriptors__[pSKey];
		}
	} else if (obj.hasOwnProperty('__descriptorPrototype__')) {
		ownDesc = obj.__descriptorPrototype__;
	}
	if (nuDesc) {
		done = create(null);
		for (key in nuDesc) {
			if (key === 'reverse') continue;
			done[key] = true;
			if (ownDesc && ownDesc.hasOwnProperty(key)) continue;
			nu = nuDesc[key];
			old = oldDesc ? oldDesc[key] : descProto[key];
			if (nu === old) continue;
			nuDescDesc = nuDesc.__descriptors__[key];
			postponed = emitDescDescValue(obj, nu, old, pSKey, key,
				nuDescDesc && nuDescDesc._sideNotify_,
				nuDescDesc && nuDescDesc._postNotify_, dbEvent, postponed);
		}
	}

	if (oldDesc) {
		for (key in oldDesc) {
			if (key === 'reverse') continue;
			if (done && done[key]) continue;
			if (ownDesc && ownDesc.hasOwnProperty(key)) continue;
			old = oldDesc[key];
			if (old === descProto[key]) continue;
			oldDescDesc = oldDesc.__descriptors__[key];
			postponed = emitDescDescValue(obj, undefined, old, pSKey, key,
				oldDescDesc && oldDescDesc._sideNotify_,
				oldDescDesc && oldDescDesc._postNotify_, dbEvent, postponed);
		}
	}
	return postponed;
};

emitDescs = function (obj, nuProto, oldProto, dbEvent, postponed) {
	var nuDescs = nuProto.__descriptors__, oldDescs = oldProto.__descriptors__
	  , sKey, ownDescs, nuDesc, done, nu, old, oldDesc;
	if (nuDescs === oldDescs) return postponed;
	ownDescs = obj.hasOwnProperty('__descriptors__') ? obj.__descriptors__ : null;
	done = create(null);
	for (sKey in nuDescs) {
		done[sKey] = true;
		nuDesc = nuDescs[sKey];
		oldDesc = oldDescs[sKey] || oldProto.__descriptorPrototype__;
		postponed = emitDescDescs(obj, sKey, nuDesc, oldDesc, dbEvent, postponed);
		if (ownDescs && hasOwnProperty.call(ownDescs, sKey)) {
			if (ownDescs[sKey].hasOwnProperty('_value_')) continue;
			nu = nuDesc._resolveInner_();
			old = oldDesc ? oldDesc._resolveInner_() : undefined;
		} else {
			nu = nuDesc._resolveValueValue_();
			old = oldDesc ? oldDesc._resolveValueValue_() : undefined;
		}
		if (nu === old) continue;
		postponed = nuDesc._emitValue_(obj, nu, old, dbEvent, postponed);
	}
	for (sKey in oldDescs) {
		if (done[sKey]) continue;
		oldDesc = oldDescs[sKey];
		postponed = emitDescDescs(obj, sKey, nuProto.__descriptorPrototype__,
			oldDesc, dbEvent, postponed);
		if (ownDescs && hasOwnProperty.call(ownDescs, sKey)) {
			if (ownDescs[sKey].hasOwnProperty('_value_')) continue;
			old = oldDesc._resolveInner_();
		} else {
			old = oldDesc._resolveValueValue_();
		}
		if (old === undefined) continue;
		postponed = oldDesc._emitValue_(obj, undefined, old, dbEvent, postponed);
	}
	return postponed;
};

exports.object = function (obj, nu, dbEvent, postponed) {
	var old = getPrototypeOf(obj)
	  , objSnapshot = snapshotObservableObj(obj);

	defineProperty(obj, '__prototypeTurnInProgress__', d(true));
	postponed = switchReverse(obj, nu, old, postponed);
	postponed = turn.object(obj, nu, postponed);
	postponed = notifyObservableObj(obj, objSnapshot, dbEvent, postponed);
	if (old.__descriptorPrototype__ !== nu.__descriptorPrototpe__) {
		postponed = emitDescDescs(obj, '', nu.__descriptorPrototpe__,
			old.__descriptorPrototype__, dbEvent, postponed);
	}
	postponed = emitDescs(obj, nu, old, dbEvent, postponed);
	postponed = emitMultiples(obj, nu, old, dbEvent, postponed);

	delete obj.__prototypeTurnInProgress__;
	if (!isObjectId(obj.__id__)) return postponed;
	return onValueTurn(obj, nu.constructor, old.constructor, dbEvent, postponed);
};

exports.descriptor = function (desc, nuProto, dbEvent, postponed) {
	var oldProto = getPrototypeOf(desc), nu, old
	  , objSnapshot = snapshotObservableObjKey(desc.object, desc._sKey_);

	postponed = turn.descriptor(desc, nuProto, postponed);
	postponed = notifyObservableObjKey(desc.object, desc._sKey_, objSnapshot,
		dbEvent, postponed);
	postponed = emitDescDescs(desc.object, desc._sKey_, nuProto, oldProto,
		dbEvent, postponed);
	if (desc.hasOwnProperty('_value_')) return postponed;
	nu = nuProto._resolveInner_();
	old = oldProto._resolveInner_();
	if (nu === old) return postponed;
	return desc._emitValue_(desc.object, nu, old, dbEvent, postponed);
};
<|endoftext|>


<commit_before>import $ from 'jquery';
import cookie from 'cookie';

// To enable running behind applications that require specific headers
// to be set during HTTP requests (e.g., CSRF tokens), we support parsing
// a set of cookies with a key prefix of "mlflow-request-header-$HeaderName",
// which will be added as an HTTP header to all AJAX requests.
export const setupAjaxHeaders = () => {
  const requestHeaders = getRequestHeaders(document.cookie);
  $(document).ajaxSend((event, jqXHR) => {
    if (requestHeaders) {
      for (const [headerKey, headerValue] of Object.entries(requestHeaders)) {
        jqXHR.setRequestHeader(headerKey, headerValue);
      }
    }
  });
};

export const getRequestHeaders = (documentCookie) => {
  const headerCookiePrefix = "mlflow-request-header-";
  const parsedCookie = cookie.parse(documentCookie);
  console.log(parsedCookie);
  const headers = {};
  for (const cookieName in parsedCookie) {
    if (cookieName.startsWith(headerCookiePrefix)) {
      headers[cookieName.substring(headerCookiePrefix.length)] = parsedCookie[cookieName];
    }
  }
  return headers;
};
<commit_msg>Remove unnecessary console.log (#2328)<commit_after>import $ from 'jquery';
import cookie from 'cookie';

// To enable running behind applications that require specific headers
// to be set during HTTP requests (e.g., CSRF tokens), we support parsing
// a set of cookies with a key prefix of "mlflow-request-header-$HeaderName",
// which will be added as an HTTP header to all AJAX requests.
export const setupAjaxHeaders = () => {
  const requestHeaders = getRequestHeaders(document.cookie);
  $(document).ajaxSend((event, jqXHR) => {
    if (requestHeaders) {
      for (const [headerKey, headerValue] of Object.entries(requestHeaders)) {
        jqXHR.setRequestHeader(headerKey, headerValue);
      }
    }
  });
};

export const getRequestHeaders = (documentCookie) => {
  const headerCookiePrefix = "mlflow-request-header-";
  const parsedCookie = cookie.parse(documentCookie);
  const headers = {};
  for (const cookieName in parsedCookie) {
    if (cookieName.startsWith(headerCookiePrefix)) {
      headers[cookieName.substring(headerCookiePrefix.length)] = parsedCookie[cookieName];
    }
  }
  return headers;
};
<|endoftext|>


<commit_before>var KEY_CODES = {
  POWER: 378130479,
  MINUS: 378134559,
  PLUS: 378132519,
  RED: 378077439,
  GREEN: 378126399,
  BLUE: 378110079,
  CROSS: 378114159,
  SQUARE: 378118239,
  TRIANGLE: 378093759,
  TOP_LEFT: 378097839,
  TOP: 378101919,
  TOP_RIGHT: 378099879,
  LEFT: 378081519,
  PLAY: 378091719,
  RIGHT: 378116199,
  BOTTOM_LEFT: 378083559,
  BOTTOM: 378124359,
  BOTTOM_RIGHT: 378085599,
  X: 378089679,
  Y: 378122319,
  Z: 378105999
};

exports = KEY_CODES;
<commit_msg>Delete ir-remote-controller.js<commit_after><|endoftext|>