<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};

/**
* @name ArrayBuffer
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/buffer}
*/
setReadOnly( ns, 'ArrayBuffer', require( '@stdlib/array/buffer' ) );

/**
* @name Complex64Array
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/complex64}
*/
setReadOnly( ns, 'Complex64Array', require( '@stdlib/array/complex64' ) );

/**
* @name Complex128Array
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/complex128}
*/
setReadOnly( ns, 'Complex128Array', require( '@stdlib/array/complex128' ) );

/**
* @name convertArray
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/convert}
*/
setReadOnly( ns, 'convertArray', require( '@stdlib/array/convert' ) );

/**
* @name convertArraySame
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/convert-same}
*/
setReadOnly( ns, 'convertArraySame', require( '@stdlib/array/convert-same' ) );

/**
* @name arrayCtors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/ctors}
*/
setReadOnly( ns, 'arrayCtors', require( '@stdlib/array/ctors' ) );

/**
* @name DataView
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/dataview}
*/
setReadOnly( ns, 'DataView', require( '@stdlib/array/dataview' ) );

/**
* @name arrayDataType
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/dtype}
*/
setReadOnly( ns, 'arrayDataType', require( '@stdlib/array/dtype' ) );

/**
* @name arrayDataTypes
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/dtypes}
*/
setReadOnly( ns, 'arrayDataTypes', require( '@stdlib/array/dtypes' ) );

/**
* @name filledarray
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/filled}
*/
setReadOnly( ns, 'filledarray', require( '@stdlib/array/filled' ) );

/**
* @name Float32Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/float32}
*/
setReadOnly( ns, 'Float32Array', require( '@stdlib/array/float32' ) );

/**
* @name Float64Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/float64}
*/
setReadOnly( ns, 'Float64Array', require( '@stdlib/array/float64' ) );

/**
* @name iterator2array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/from-iterator}
*/
setReadOnly( ns, 'iterator2array', require( '@stdlib/array/from-iterator' ) );

/**
* @name Int8Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/int8}
*/
setReadOnly( ns, 'Int8Array', require( '@stdlib/array/int8' ) );

/**
* @name Int16Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/int16}
*/
setReadOnly( ns, 'Int16Array', require( '@stdlib/array/int16' ) );

/**
* @name Int32Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/int32}
*/
setReadOnly( ns, 'Int32Array', require( '@stdlib/array/int32' ) );

/**
* @name arrayMinDataType
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/min-dtype}
*/
setReadOnly( ns, 'arrayMinDataType', require( '@stdlib/array/min-dtype' ) );

/**
* @name arrayNextDataType
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/next-dtype}
*/
setReadOnly( ns, 'arrayNextDataType', require( '@stdlib/array/next-dtype' ) );

/**
* @name typedarraypool
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/pool}
*/
setReadOnly( ns, 'typedarraypool', require( '@stdlib/array/pool' ) );

/**
* @name arrayPromotionRules
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/promotion-rules}
*/
setReadOnly( ns, 'arrayPromotionRules', require( '@stdlib/array/promotion-rules' ) );

/**
* @name reviveTypedArray
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/reviver}
*/
setReadOnly( ns, 'reviveTypedArray', require( '@stdlib/array/reviver' ) );

/**
* @name arraySafeCasts
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/safe-casts}
*/
setReadOnly( ns, 'arraySafeCasts', require( '@stdlib/array/safe-casts' ) );

/**
* @name arraySameKindCasts
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/same-kind-casts}
*/
setReadOnly( ns, 'arraySameKindCasts', require( '@stdlib/array/same-kind-casts' ) );

/**
* @name arrayShape
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/shape}
*/
setReadOnly( ns, 'arrayShape', require( '@stdlib/array/shape' ) );

/**
* @name SharedArrayBuffer
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/shared-buffer}
*/
setReadOnly( ns, 'SharedArrayBuffer', require( '@stdlib/array/shared-buffer' ) );

/**
* @name circarray2iterator
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-circular-iterator}
*/
setReadOnly( ns, 'circarray2iterator', require( '@stdlib/array/to-circular-iterator' ) );

/**
* @name array2iterator
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-iterator}
*/
setReadOnly( ns, 'array2iterator', require( '@stdlib/array/to-iterator' ) );

/**
* @name array2iteratorRight
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-iterator-right}
*/
setReadOnly( ns, 'array2iteratorRight', require( '@stdlib/array/to-iterator-right' ) );

/**
* @name typedarray2json
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-json}
*/
setReadOnly( ns, 'typedarray2json', require( '@stdlib/array/to-json' ) );

/**
* @name sparsearray2iterator
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-sparse-iterator}
*/
setReadOnly( ns, 'sparsearray2iterator', require( '@stdlib/array/to-sparse-iterator' ) );

/**
* @name sparsearray2iteratorRight
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-sparse-iterator-right}
*/
setReadOnly( ns, 'sparsearray2iteratorRight', require( '@stdlib/array/to-sparse-iterator-right' ) );

/**
* @name stridedarray2iterator
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-strided-iterator}
*/
setReadOnly( ns, 'stridedarray2iterator', require( '@stdlib/array/to-strided-iterator' ) );

/**
* @name arrayview2iterator
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-view-iterator}
*/
setReadOnly( ns, 'arrayview2iterator', require( '@stdlib/array/to-view-iterator' ) );

/**
* @name arrayview2iteratorRight
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-view-iterator-right}
*/
setReadOnly( ns, 'arrayview2iteratorRight', require( '@stdlib/array/to-view-iterator-right' ) );

/**
* @name typedarray
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed}
*/
setReadOnly( ns, 'typedarray', require( '@stdlib/array/typed' ) );

/**
* @name typedarrayComplexCtors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-complex-ctors}
*/
setReadOnly( ns, 'typedarrayComplexCtors', require( '@stdlib/array/typed-complex-ctors' ) );

/**
* @name typedarrayComplexDataTypes
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-complex-dtypes}
*/
setReadOnly( ns, 'typedarrayComplexDataTypes', require( '@stdlib/array/typed-complex-dtypes' ) );

/**
* @name typedarrayCtors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-ctors}
*/
setReadOnly( ns, 'typedarrayCtors', require( '@stdlib/array/typed-ctors' ) );

/**
* @name typedarrayDataTypes
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-dtypes}
*/
setReadOnly( ns, 'typedarrayDataTypes', require( '@stdlib/array/typed-dtypes' ) );

/**
* @name Uint8Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/uint8}
*/
setReadOnly( ns, 'Uint8Array', require( '@stdlib/array/uint8' ) );

/**
* @name Uint8ClampedArray
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/uint8c}
*/
setReadOnly( ns, 'Uint8ClampedArray', require( '@stdlib/array/uint8c' ) );

/**
* @name Uint16Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/uint16}
*/
setReadOnly( ns, 'Uint16Array', require( '@stdlib/array/uint16' ) );

/**
* @name Uint32Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/uint32}
*/
setReadOnly( ns, 'Uint32Array', require( '@stdlib/array/uint32' ) );

/**
* @name constants
* @memberof ns
* @readonly
* @type {Namespace}
* @see {@link module:@stdlib/constants/array}
*/
setReadOnly( ns, 'constants', require( '@stdlib/constants/array' ) );

// EXPORTS //

module.exports = ns;
<commit_msg>Add *space packages to namespace<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};

/**
* @name ArrayBuffer
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/buffer}
*/
setReadOnly( ns, 'ArrayBuffer', require( '@stdlib/array/buffer' ) );

/**
* @name Complex64Array
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/complex64}
*/
setReadOnly( ns, 'Complex64Array', require( '@stdlib/array/complex64' ) );

/**
* @name Complex128Array
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/complex128}
*/
setReadOnly( ns, 'Complex128Array', require( '@stdlib/array/complex128' ) );

/**
* @name convertArray
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/convert}
*/
setReadOnly( ns, 'convertArray', require( '@stdlib/array/convert' ) );

/**
* @name convertArraySame
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/convert-same}
*/
setReadOnly( ns, 'convertArraySame', require( '@stdlib/array/convert-same' ) );

/**
* @name arrayCtors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/ctors}
*/
setReadOnly( ns, 'arrayCtors', require( '@stdlib/array/ctors' ) );

/**
* @name DataView
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/dataview}
*/
setReadOnly( ns, 'DataView', require( '@stdlib/array/dataview' ) );

/**
* @name arrayDataType
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/dtype}
*/
setReadOnly( ns, 'arrayDataType', require( '@stdlib/array/dtype' ) );

/**
* @name arrayDataTypes
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/dtypes}
*/
setReadOnly( ns, 'arrayDataTypes', require( '@stdlib/array/dtypes' ) );

/**
* @name filledarray
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/filled}
*/
setReadOnly( ns, 'filledarray', require( '@stdlib/array/filled' ) );

/**
* @name Float32Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/float32}
*/
setReadOnly( ns, 'Float32Array', require( '@stdlib/array/float32' ) );

/**
* @name Float64Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/float64}
*/
setReadOnly( ns, 'Float64Array', require( '@stdlib/array/float64' ) );

/**
* @name iterator2array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/from-iterator}
*/
setReadOnly( ns, 'iterator2array', require( '@stdlib/array/from-iterator' ) );

/**
* @name incrspace
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/incrspace}
*/
setReadOnly( ns, 'incrspace', require( '@stdlib/array/incrspace' ) );

/**
* @name Int8Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/int8}
*/
setReadOnly( ns, 'Int8Array', require( '@stdlib/array/int8' ) );

/**
* @name Int16Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/int16}
*/
setReadOnly( ns, 'Int16Array', require( '@stdlib/array/int16' ) );

/**
* @name Int32Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/int32}
*/
setReadOnly( ns, 'Int32Array', require( '@stdlib/array/int32' ) );

/**
* @name linspace
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/linspace}
*/
setReadOnly( ns, 'linspace', require( '@stdlib/array/linspace' ) );

/**
* @name logspace
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/logspace}
*/
setReadOnly( ns, 'logspace', require( '@stdlib/array/logspace' ) );

/**
* @name arrayMinDataType
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/min-dtype}
*/
setReadOnly( ns, 'arrayMinDataType', require( '@stdlib/array/min-dtype' ) );

/**
* @name arrayNextDataType
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/next-dtype}
*/
setReadOnly( ns, 'arrayNextDataType', require( '@stdlib/array/next-dtype' ) );

/**
* @name typedarraypool
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/pool}
*/
setReadOnly( ns, 'typedarraypool', require( '@stdlib/array/pool' ) );

/**
* @name arrayPromotionRules
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/promotion-rules}
*/
setReadOnly( ns, 'arrayPromotionRules', require( '@stdlib/array/promotion-rules' ) );

/**
* @name reviveTypedArray
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/reviver}
*/
setReadOnly( ns, 'reviveTypedArray', require( '@stdlib/array/reviver' ) );

/**
* @name arraySafeCasts
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/safe-casts}
*/
setReadOnly( ns, 'arraySafeCasts', require( '@stdlib/array/safe-casts' ) );

/**
* @name arraySameKindCasts
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/same-kind-casts}
*/
setReadOnly( ns, 'arraySameKindCasts', require( '@stdlib/array/same-kind-casts' ) );

/**
* @name arrayShape
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/shape}
*/
setReadOnly( ns, 'arrayShape', require( '@stdlib/array/shape' ) );

/**
* @name SharedArrayBuffer
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/shared-buffer}
*/
setReadOnly( ns, 'SharedArrayBuffer', require( '@stdlib/array/shared-buffer' ) );

/**
* @name circarray2iterator
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-circular-iterator}
*/
setReadOnly( ns, 'circarray2iterator', require( '@stdlib/array/to-circular-iterator' ) );

/**
* @name array2iterator
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-iterator}
*/
setReadOnly( ns, 'array2iterator', require( '@stdlib/array/to-iterator' ) );

/**
* @name array2iteratorRight
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-iterator-right}
*/
setReadOnly( ns, 'array2iteratorRight', require( '@stdlib/array/to-iterator-right' ) );

/**
* @name typedarray2json
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-json}
*/
setReadOnly( ns, 'typedarray2json', require( '@stdlib/array/to-json' ) );

/**
* @name sparsearray2iterator
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-sparse-iterator}
*/
setReadOnly( ns, 'sparsearray2iterator', require( '@stdlib/array/to-sparse-iterator' ) );

/**
* @name sparsearray2iteratorRight
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-sparse-iterator-right}
*/
setReadOnly( ns, 'sparsearray2iteratorRight', require( '@stdlib/array/to-sparse-iterator-right' ) );

/**
* @name stridedarray2iterator
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-strided-iterator}
*/
setReadOnly( ns, 'stridedarray2iterator', require( '@stdlib/array/to-strided-iterator' ) );

/**
* @name arrayview2iterator
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-view-iterator}
*/
setReadOnly( ns, 'arrayview2iterator', require( '@stdlib/array/to-view-iterator' ) );

/**
* @name arrayview2iteratorRight
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/to-view-iterator-right}
*/
setReadOnly( ns, 'arrayview2iteratorRight', require( '@stdlib/array/to-view-iterator-right' ) );

/**
* @name typedarray
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed}
*/
setReadOnly( ns, 'typedarray', require( '@stdlib/array/typed' ) );

/**
* @name typedarrayComplexCtors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-complex-ctors}
*/
setReadOnly( ns, 'typedarrayComplexCtors', require( '@stdlib/array/typed-complex-ctors' ) );

/**
* @name typedarrayComplexDataTypes
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-complex-dtypes}
*/
setReadOnly( ns, 'typedarrayComplexDataTypes', require( '@stdlib/array/typed-complex-dtypes' ) );

/**
* @name typedarrayCtors
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-ctors}
*/
setReadOnly( ns, 'typedarrayCtors', require( '@stdlib/array/typed-ctors' ) );

/**
* @name typedarrayDataTypes
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/array/typed-dtypes}
*/
setReadOnly( ns, 'typedarrayDataTypes', require( '@stdlib/array/typed-dtypes' ) );

/**
* @name Uint8Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/uint8}
*/
setReadOnly( ns, 'Uint8Array', require( '@stdlib/array/uint8' ) );

/**
* @name Uint8ClampedArray
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/uint8c}
*/
setReadOnly( ns, 'Uint8ClampedArray', require( '@stdlib/array/uint8c' ) );

/**
* @name Uint16Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/uint16}
*/
setReadOnly( ns, 'Uint16Array', require( '@stdlib/array/uint16' ) );

/**
* @name Uint32Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/array/uint32}
*/
setReadOnly( ns, 'Uint32Array', require( '@stdlib/array/uint32' ) );

/**
* @name constants
* @memberof ns
* @readonly
* @type {Namespace}
* @see {@link module:@stdlib/constants/array}
*/
setReadOnly( ns, 'constants', require( '@stdlib/constants/array' ) );

// EXPORTS //

module.exports = ns;
<|endoftext|>


<commit_before>import async from 'async';
import Field from '../Field';
import React from 'react';
import Select from 'react-select';
import xhr from 'xhr';
import { Button, FormInput } from 'elemental';

function compareValues(current, next) {
	if (current.length !== next.length) return false;
	for (let i = 0; i < current.length; i++) {
		if (current[i] !== next[i]) return false;
	}
	return true;
}

module.exports = Field.create({

	displayName: 'RelationshipField',

	getInitialState () {
		return {
			value: null,
		};
	},

	componentDidMount () {
		this._itemsCache = {};
		this.loadValue(this.props.value);
	},

	componentWillReceiveProps (nextProps) {
		if (nextProps.value === this.props.value || nextProps.many && compareValues(this.props.value, nextProps.value)) return;
		this.loadValue(nextProps.value);
	},

	shouldCollapse () {
		if (this.props.many) {
			// many:true relationships have an Array for a value
			return this.props.collapse && !this.props.value.length;
		}
		return this.props.collapse && !this.props.value;
	},

	buildFilters () {
		var filters = {};

		_.each(this.props.filters, function(value, key) {
			if(_.isString(value) && value[0] == ':') {//eslint-disable-line eqeqeq
				var fieldName = value.slice(1);

				var val = this.props.values[fieldName];
				if (val) {
					filters[key] = val;
					return;
				}

				// check if filtering by id and item was already saved
				if (fieldName === ':_id' && Keystone.item) {
					filters[key] = Keystone.item.id;
					return;
				}
			} else {
				filters[key] = value;
			}
		}, this);

		var parts = [];

		_.each(filters, function (val, key) {
			parts.push('filters[' + key + ']=' + encodeURIComponent(val));
		});

		return parts.join('&');
	},

	cacheItem (item) {
		item.href = '/keystone/' + this.props.refList.path + '/' + item.id;
		this._itemsCache[item.id] = item;
	},

	loadValue (values) {
		values = this.props.many ? values : [values];
		let cachedValues = values.map(i => this._itemsCache[i]).filter(i => i);
		if (cachedValues.length === values.length) {
			this.setState({
				loading: false,
				value: this.props.many ? cachedValues : cachedValues[0],
			});
			return;
		}
		this.setState({
			loading: true,
			value: null,
		});
		async.map(values, (value, done) => {
			xhr({
				url: '/keystone/api/' + this.props.refList.path + '/' + value + '?basic',
				responseType: 'json',
			}, (err, resp, data) => {
				if (err || !data) return done(err);
				this.cacheItem(data);
				done(err, data);
			});
		}, (err, expanded) => {
			this.setState({
				loading: false,
				value: this.props.many ? expanded : expanded[0],
			});
		});
	},

	loadOptions (input, callback) {
		// TODO: Implement filters
		xhr({
			url: '/keystone/api/' + this.props.refList.path + '?basic&search=' + input,
			responseType: 'json',
		}, (err, resp, data) => {
			if (err) {
				console.error('Error loading items:', err);
				return callback(null, []);
			}
			data.results.forEach(this.cacheItem);
			callback(null, {
				options: data.results,
				complete: data.results.length === data.count,
			});
		});
	},

	valueChanged (value) {
		this.props.onChange({
			path: this.props.path,
			value: value,
		});
	},

	renderSelect (noedit) {
		return (
			<Select.Async
				multi={this.props.many}
				disabled={noedit}
				loadOptions={this.loadOptions}
				labelKey="name"
				name={this.props.path}
				onChange={this.valueChanged}
				simpleValue
				value={this.state.value}
				valueKey="id"
			/>
		);
	},

	renderValue () {
		return this.renderSelect(true);
	},

	renderField () {
		return this.renderSelect();
	}

});
<commit_msg>Fix for clearing relationship values<commit_after>import async from 'async';
import Field from '../Field';
import React from 'react';
import Select from 'react-select';
import xhr from 'xhr';
import { Button, FormInput } from 'elemental';

function compareValues(current, next) {
	if (current.length !== next.length) return false;
	for (let i = 0; i < current.length; i++) {
		if (current[i] !== next[i]) return false;
	}
	return true;
}

module.exports = Field.create({

	displayName: 'RelationshipField',

	getInitialState () {
		return {
			value: null,
		};
	},

	componentDidMount () {
		this._itemsCache = {};
		this.loadValue(this.props.value);
	},

	componentWillReceiveProps (nextProps) {
		if (nextProps.value === this.props.value || nextProps.many && compareValues(this.props.value, nextProps.value)) return;
		this.loadValue(nextProps.value);
	},

	shouldCollapse () {
		if (this.props.many) {
			// many:true relationships have an Array for a value
			return this.props.collapse && !this.props.value.length;
		}
		return this.props.collapse && !this.props.value;
	},

	buildFilters () {
		var filters = {};

		_.each(this.props.filters, function(value, key) {
			if(_.isString(value) && value[0] == ':') {//eslint-disable-line eqeqeq
				var fieldName = value.slice(1);

				var val = this.props.values[fieldName];
				if (val) {
					filters[key] = val;
					return;
				}

				// check if filtering by id and item was already saved
				if (fieldName === ':_id' && Keystone.item) {
					filters[key] = Keystone.item.id;
					return;
				}
			} else {
				filters[key] = value;
			}
		}, this);

		var parts = [];

		_.each(filters, function (val, key) {
			parts.push('filters[' + key + ']=' + encodeURIComponent(val));
		});

		return parts.join('&');
	},

	cacheItem (item) {
		item.href = '/keystone/' + this.props.refList.path + '/' + item.id;
		this._itemsCache[item.id] = item;
	},

	loadValue (values) {
		if (!values) {
			return this.setState({
				loading: false,
				value: null,
			});
		};
		values = this.props.many ? values : [values];
		let cachedValues = values.map(i => this._itemsCache[i]).filter(i => i);
		if (cachedValues.length === values.length) {
			this.setState({
				loading: false,
				value: this.props.many ? cachedValues : cachedValues[0],
			});
			return;
		}
		this.setState({
			loading: true,
			value: null,
		});
		async.map(values, (value, done) => {
			xhr({
				url: '/keystone/api/' + this.props.refList.path + '/' + value + '?basic',
				responseType: 'json',
			}, (err, resp, data) => {
				if (err || !data) return done(err);
				this.cacheItem(data);
				done(err, data);
			});
		}, (err, expanded) => {
			this.setState({
				loading: false,
				value: this.props.many ? expanded : expanded[0],
			});
		});
	},

	loadOptions (input, callback) {
		// TODO: Implement filters
		xhr({
			url: '/keystone/api/' + this.props.refList.path + '?basic&search=' + input,
			responseType: 'json',
		}, (err, resp, data) => {
			if (err) {
				console.error('Error loading items:', err);
				return callback(null, []);
			}
			data.results.forEach(this.cacheItem);
			callback(null, {
				options: data.results,
				complete: data.results.length === data.count,
			});
		});
	},

	valueChanged (value) {
		this.props.onChange({
			path: this.props.path,
			value: value,
		});
	},

	renderSelect (noedit) {
		return (
			<Select.Async
				multi={this.props.many}
				disabled={noedit}
				loadOptions={this.loadOptions}
				labelKey="name"
				name={this.props.path}
				onChange={this.valueChanged}
				simpleValue
				value={this.state.value}
				valueKey="id"
			/>
		);
	},

	renderValue () {
		return this.renderSelect(true);
	},

	renderField () {
		return this.renderSelect();
	}

});
<|endoftext|>


<commit_before>var s = new Uint32Array(4);

function leftShift(write, readU, readL, amount) {
  var m = 0xFFFFFFFF << (32 - amount);
  write[0] = (readU << amount) | ((readL & m) >>> (32 - amount));
  write[1] = readL << amount;
}

function xor(write, read1U, read1L, read2U, read2L) {
  write[0] = read1U ^ read2U;
  write[1] = read1L ^ read2L;
}

function rightShift(write, readU, readL, amount) {
  var m = 0xFFFFFFFF >>> (32 - amount);
  write[0] = readU >>> amount;
  write[1] = (readL >>> amount) | ((readU & m) << (32 - amount));
}

function add(write, read1U, read1L, read2U, read2L) {
   var sumL = read1L + read2L;

   write[0] = read1U + read2U + (sumL / 2 >>> 31);
   write[1] = sumL & 0xFFFFFFFF;
}

s[1] = 1;
s[3] = 2;

var t1 = new Uint32Array(2);
var t2 = new Uint32Array(2);

function xorshift() {
  // Lint64_t s1 = s[ 0 ];
  var s1U = s[0], s1L = s[1];
  // const Lint64_t s0 = s[ 1 ];
  var s0U = s[2], s0L = s[3];

  // s[ 0 ] = s0;
  s[0] = s0U;
  s[1] = s0L;

  // k1 ^= s1 << 23;
  leftShift(t1, s1U, s1L, 23);
  xor      (t2, s1U, s1L, t1[0], t1[1]);

  // s1 = k1
  s1U = t2[0];
  s1L = t2[1];

  // k2 = ( s1 ^ s0 ^ ( s1 >> 17 ) ^ ( s0 >> 26 ) )
  xor       (t1, s1U, s1L, s0U, s0L);

  rightShift(t2, s1U, s1L, 17);
  xor       (t1, t1[0], t1[1], t2[0], t2[1]);

  rightShift(t2, s0U, s0L, 26);
  xor       (t1, t1[0], t1[1], t2[0], t2[1]);

  // s[1] = k2
  s[2] = t1[0];
  s[3] = t1[1];

  // retLrn k2 + s0
  add(t2, t1[0], t1[1], s0U, s0L);

  return t2;
}

module.exports = xorshift;
<commit_msg>[optim] swtich typedarrays to std arrays<commit_after>var s = [0, 0, 0, 0];

function leftShift(write, readU, readL, amount) {
  var m = 0xFFFFFFFF << (32 - amount);
  write[0] = (readU << amount) | ((readL & m) >>> (32 - amount));
  write[1] = readL << amount;
}

function xor(write, read1U, read1L, read2U, read2L) {
  write[0] = read1U ^ read2U;
  write[1] = read1L ^ read2L;
}

function rightShift(write, readU, readL, amount) {
  var m = 0xFFFFFFFF >>> (32 - amount);
  write[0] = readU >>> amount;
  write[1] = (readL >>> amount) | ((readU & m) << (32 - amount));
}

function add(write, read1U, read1L, read2U, read2L) {
   var sumL = (read1L >>> 0) + (read2L >>> 0);

   write[0] = (read1U + read2U + (sumL / 2 >>> 31)) >>> 0;
   write[1] = sumL >>> 0;
}

s[1] = 1;
s[3] = 2;

var t1 = [0, 0];
var t2 = [0, 0];

function xorshift() {
  // Lint64_t s1 = s[ 0 ];
  var s1U = s[0], s1L = s[1];
  // const Lint64_t s0 = s[ 1 ];
  var s0U = s[2], s0L = s[3];

  // s[ 0 ] = s0;
  s[0] = s0U;
  s[1] = s0L;

  // k1 ^= s1 << 23;
  leftShift(t1, s1U, s1L, 23);
  xor      (t2, s1U, s1L, t1[0], t1[1]);

  // s1 = k1
  s1U = t2[0];
  s1L = t2[1];

  // k2 = ( s1 ^ s0 ^ ( s1 >> 17 ) ^ ( s0 >> 26 ) )
  xor       (t1, s1U, s1L, s0U, s0L);

  rightShift(t2, s1U, s1L, 17);
  xor       (t1, t1[0], t1[1], t2[0], t2[1]);

  rightShift(t2, s0U, s0L, 26);
  xor       (t1, t1[0], t1[1], t2[0], t2[1]);

  // s[1] = k2
  s[2] = t1[0];
  s[3] = t1[1];

  // retLrn k2 + s0
  add(t2, t1[0], t1[1], s0U, s0L);

  return t2;
}

module.exports = xorshift;
<|endoftext|>


<commit_before>'use strict';

const dateTimeRegex = /^(\d{4}):(\d{2}):(\d{2}) (\d{2}):(\d{2}):(\d{2})$/;

class IFD {
    constructor() {
        this.fields = new Map();
    }

    // Custom fields
    get size() {
        return this.width * this.height;
    }
    get width() {
        return this.imageWidth;
    }
    get height() {
        return this.imageLength;
    }
    get components() {
        return this.samplesPerPixel;
    }
    get date() {
        var date = new Date();
        var result = dateTimeRegex.exec(this.dateTime);
        date.setFullYear(result[1], result[2] - 1, result[3]);
        date.setHours(result[4], result[5], result[6]);
        return date;
    }

    // IFD fields
    get newSubfileType() {
        return this.fields.get(254)
    }
    get imageWidth() {
        return this.fields.get(256);
    }
    get imageLength() {
        return this.fields.get(257);
    }
    get bitsPerSample() {
        return this.fields.get(258);
    }
    get compression() {
        return this.fields.get(259);
    }
    get type() {
        return this.fields.get(262);
    }
    get fillOrder() {
        return this.fields.get(266) || 1;
    }
    get documentName() {
        return this.fields.get(269);
    }
    get imageDescription() {
        return this.fields.get(270);
    }
    get stripOffsets() {
        return alwaysArray(this.fields.get(273));
    }
    get orientation() {
        return this.fields.get(274);
    }
    get samplesPerPixel() {
        return this.fields.get(277);
    }
    get rowsPerStrip() {
        return this.fields.get(278);
    }
    get stripByteCounts() {
        return alwaysArray(this.fields.get(279));
    }
    get minSampleValue() {
        return this.fields.get(280) || 0;
    }
    get maxSampleValue() {
        return this.fields.get(281) || Math.pow(2, this.bitsPerSample) - 1;
    }
    get xResolution() {
        return this.fields.get(282);
    }
    get yResolution() {
        return this.fields.get(283);
    }
    get planarConfiguration() {
        return this.fields.get(284) || 1;
    }
    get resolutionUnit() {
        return this.fields.get(296) || 2;
    }
    get dateTime() {
        return this.fields.get(306);
    }
    get predictor() {
        return this.fields.get(317) || 1;
    }
    get sampleFormat() {
        return this.fields.get(339) || 1;
    }
    get sMinSampleValue() {
        return this.fields.get(340) || this.minSampleValue;
    }
    get sMaxSampleValue() {
        return this.fields.get(341) || this.maxSampleValue;
    }
}

module.exports = IFD;

function alwaysArray(value) {
    if (typeof value === 'number') return [value];
    return value;
}<commit_msg>fix: default value for compression field is 1<commit_after>'use strict';

const dateTimeRegex = /^(\d{4}):(\d{2}):(\d{2}) (\d{2}):(\d{2}):(\d{2})$/;

class IFD {
    constructor() {
        this.fields = new Map();
    }

    // Custom fields
    get size() {
        return this.width * this.height;
    }
    get width() {
        return this.imageWidth;
    }
    get height() {
        return this.imageLength;
    }
    get components() {
        return this.samplesPerPixel;
    }
    get date() {
        var date = new Date();
        var result = dateTimeRegex.exec(this.dateTime);
        date.setFullYear(result[1], result[2] - 1, result[3]);
        date.setHours(result[4], result[5], result[6]);
        return date;
    }

    // IFD fields
    get newSubfileType() {
        return this.fields.get(254)
    }
    get imageWidth() {
        return this.fields.get(256);
    }
    get imageLength() {
        return this.fields.get(257);
    }
    get bitsPerSample() {
        return this.fields.get(258);
    }
    get compression() {
        return this.fields.get(259) || 1;
    }
    get type() {
        return this.fields.get(262);
    }
    get fillOrder() {
        return this.fields.get(266) || 1;
    }
    get documentName() {
        return this.fields.get(269);
    }
    get imageDescription() {
        return this.fields.get(270);
    }
    get stripOffsets() {
        return alwaysArray(this.fields.get(273));
    }
    get orientation() {
        return this.fields.get(274);
    }
    get samplesPerPixel() {
        return this.fields.get(277);
    }
    get rowsPerStrip() {
        return this.fields.get(278);
    }
    get stripByteCounts() {
        return alwaysArray(this.fields.get(279));
    }
    get minSampleValue() {
        return this.fields.get(280) || 0;
    }
    get maxSampleValue() {
        return this.fields.get(281) || Math.pow(2, this.bitsPerSample) - 1;
    }
    get xResolution() {
        return this.fields.get(282);
    }
    get yResolution() {
        return this.fields.get(283);
    }
    get planarConfiguration() {
        return this.fields.get(284) || 1;
    }
    get resolutionUnit() {
        return this.fields.get(296) || 2;
    }
    get dateTime() {
        return this.fields.get(306);
    }
    get predictor() {
        return this.fields.get(317) || 1;
    }
    get sampleFormat() {
        return this.fields.get(339) || 1;
    }
    get sMinSampleValue() {
        return this.fields.get(340) || this.minSampleValue;
    }
    get sMaxSampleValue() {
        return this.fields.get(341) || this.maxSampleValue;
    }
}

module.exports = IFD;

function alwaysArray(value) {
    if (typeof value === 'number') return [value];
    return value;
}<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

/**
 * Module dependencies
 */

// Node.js core.
const cp = require('child_process');
const path = require('path');

// Public dependencies
const _ = require('lodash');
const forever = require('forever-monitor');

// Local Strapi dependencies.
const isLocalStrapiValid = require('../lib/private/isLocalStrapiValid');

// Logger.
const logger = require('strapi-utils').logger;

/**
 * `$ strapi start`
 *
 * Expose method which starts the appropriate instance of Strapi
 * (fire up the application in our working directory).
 */

module.exports = function() {
  try {
    // Set NODE_ENV
    if (_.isEmpty(process.env.NODE_ENV)) {
      process.env.NODE_ENV = 'development';
    }

    // Require server configurations
    const server = require(path.resolve(
      process.cwd(),
      'config',
      'environments',
      'development',
      'server.json'
    ));

    // if (process.env.NODE_ENV === 'development' && server.reload === true) {
    //   const options = _.assign(
    //     {},
    //     {
    //       silent: false,
    //       watch: true,
    //       watchDirectory: process.cwd(),
    //       watchIgnoreDotFiles: true, // Whether to ignore file starting with a '.'
    //       watchIgnorePatterns: [
    //         'node_modules/**/*',
    //         'public/**/*',
    //         '.git/**/*',
    //         '.idea'
    //       ], // Ignore patterns to use when watching files.
    //       killTree: true, // Kills the entire child process tree on `exit`,
    //       spinSleepTime: 0,
    //       command: 'node --harmony-async-await'
    //     }
    //   );
    //
    //   const child = new forever.Monitor('server.js', options);
    //
    //   // Run listeners
    //   child.on('watch:restart', info => {
    //     logger.verbose(
    //       'Restarting due to ' +
    //         info.file +
    //         '... (' +
    //         info.stat.replace(child.cwd, '.') +
    //         ')'
    //     );
    //     console.log();
    //   });
    //
    //   child.on('exit:code', function(code) {
    //     if (code) {
    //       process.exit(code);
    //     }
    //   });
    //
    //   // Start child process
    //   return child.start();
    // }

    // Otherwise, if no workable local `strapi` module exists,
    // run the application using the currently running version
    // of `strapi`. This is probably always the global install.
    return require('strapi');
  } catch (e) {
    logger.error(e);
    process.exit(0);
  }
};

function afterwards(err, strapi) {
  if (err) {
    logger.error(err.stack ? err.stack : err);

    strapi ? strapi.stop() : process.exit(1);
  }
}
<commit_msg>Fix start CLI<commit_after>#!/usr/bin/env node

'use strict';

/**
 * Module dependencies
 */

// Node.js core.
const cp = require('child_process');
const path = require('path');

// Public dependencies
const _ = require('lodash');
const forever = require('forever-monitor');

// Logger.
const logger = require('strapi-utils').logger;

/**
 * `$ strapi start`
 *
 * Expose method which starts the appropriate instance of Strapi
 * (fire up the application in our working directory).
 */

module.exports = function() {
  try {
    // Set NODE_ENV
    if (_.isEmpty(process.env.NODE_ENV)) {
      process.env.NODE_ENV = 'development';
    }

    // Require server configurations
    const server = require(path.resolve(
      process.cwd(),
      'config',
      'environments',
      'development',
      'server.json'
    ));

    if (process.env.NODE_ENV === 'development' && server.reload === true) {
      const options = _.assign(
        {},
        {
          silent: false,
          watch: true,
          watchDirectory: process.cwd(),
          watchIgnoreDotFiles: true, // Whether to ignore file starting with a '.'
          watchIgnorePatterns: [
            'node_modules/**/*',
            'public/**/*',
            '.git/**/*',
            '.idea'
          ], // Ignore patterns to use when watching files.
          killTree: true, // Kills the entire child process tree on `exit`,
          spinSleepTime: 0,
          command: 'node'
        }
      );

      const child = new forever.Monitor('server.js', options);

      // Run listeners
      child.on('watch:restart', info => {
        logger.verbose(
          'Restarting due to ' +
            info.file +
            '... (' +
            info.stat.replace(child.cwd, '.') +
            ')'
        );
        console.log();
      });

      child.on('exit:code', function(code) {
        if (code) {
          process.exit(code);
        }
      });

      // Start child process
      return child.start();
    }

    // Otherwise, if no workable local `strapi` module exists,
    // run the application using the currently running version
    // of `strapi`. This is probably always the global install.
    const strapi = function () {
      try {
        return require(path.resolve(process.cwd(), 'node_modules', 'strapi'));
      } catch (e) {
        return require('strapi');
      }
    }();

    strapi.start();

  } catch (e) {
    logger.error(e);
    process.exit(0);
  }
};

function afterwards(err, strapi) {
  if (err) {
    logger.error(err.stack ? err.stack : err);

    strapi ? strapi.stop() : process.exit(1);
  }
}
<|endoftext|>


<commit_before>
// MODULES //

var // Expectation library:
	chai = require( 'chai' ),

	// Test utilities:
	utils = require( './utils' ),

	// Module to be tested:
	mStream = require( './../lib/stats/mmean' );

// VARIABLES //

var expect = chai.expect,
	assert = chai.assert;

// TESTS //

describe( 'stats/mean', function tests() {
	'use strict';

	it( 'should export a factory function', function test() {
		expect( mStream ).to.be.a( 'function' );
	});

	it( 'should provide a method to get the window size', function test() {
		var tStream = mStream();
		assert.strictEqual( tStream.window(), 5 );
	});

	it( 'should provide a method to set the window size', function test() {
		var tStream = mStream();
		tStream.window( 25 );
		assert.strictEqual( tStream.window(), 25 );
	});

	it( 'should not allow a non-numeric window size', function test() {
		var tStream = mStream();

		expect( badValue( '5' ) ).to.throw( Error );
		expect( badValue( [] ) ).to.throw( Error );
		expect( badValue( {} ) ).to.throw( Error );
		expect( badValue( null ) ).to.throw( Error );
		expect( badValue( undefined ) ).to.throw( Error );
		expect( badValue( NaN ) ).to.throw( Error );

		function badValue( value ) {
			return function() {
				tStream.window( value );
			};
		}
	});

	it( 'should calculate the mean of piped data', function test( done ) {
		var data, expected, tStream, WINDOW = 5;

		// Simulate some data...
		data = [ 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5 ];

		// Expected values is the rolling average:
		expected = [ 2.4, 2.6, 3, 3.4, 3.6, 4, 4.4, 4.6 ];

		// Create a new mean stream:
		tStream = mStream()
			.window( WINDOW )
			.stream();

		// Mock reading from the stream:
		utils.readStream( tStream, onRead );

		// Mock piping a data to the stream:
		utils.writeStream( data, tStream );

		return;

		/**
		* FUNCTION: onRead( error, actual )
		*	Read event handler. Checks for errors and compares streamed data to expected data.
		*/
		function onRead( error, actual ) {
			expect( error ).to.not.exist;

			assert.lengthOf( actual, data.length-WINDOW+1 );

			assert.closeTo( actual[ 0 ], expected[ 0 ], 0.001 );
			assert.closeTo( actual[ 1 ], expected[ 1 ], 0.001 );
			assert.closeTo( actual[ 2 ], expected[ 2 ], 0.001 );
			assert.closeTo( actual[ 3 ], expected[ 3 ], 0.001 );
			assert.closeTo( actual[ 4 ], expected[ 4 ], 0.001 );
			assert.closeTo( actual[ 5 ], expected[ 5 ], 0.001 );
			assert.closeTo( actual[ 6 ], expected[ 6 ], 0.001 );
			assert.closeTo( actual[ 7 ], expected[ 7 ], 0.001 );

			done();
		} // end FUNCTION onRead()
	});

	it( 'should calculate the mean of piped data using an arbitrary window size', function test( done ) {
		var data, expected, tStream, WINDOW = 3;

		// Simulate some data...
		data = [ 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5 ];

		// Expected values is the rolling average:
		expected = [ 2, 2.33333, 2.666666, 3, 3.33333333, 3.6666666, 4, 4.33333333, 4.66666666, 5 ];

		// Create a new mean stream:
		tStream = mStream()
			.window( WINDOW )
			.stream();

		// Mock reading from the stream:
		utils.readStream( tStream, onRead );

		// Mock piping a data to the stream:
		utils.writeStream( data, tStream );

		return;

		/**
		* FUNCTION: onRead( error, actual )
		*	Read event handler. Checks for errors and compares streamed data to expected data.
		*/
		function onRead( error, actual ) {
			expect( error ).to.not.exist;

			assert.lengthOf( actual, data.length-WINDOW+1 );

			assert.closeTo( actual[ 0 ], expected[ 0 ], 0.001 );
			assert.closeTo( actual[ 1 ], expected[ 1 ], 0.001 );
			assert.closeTo( actual[ 2 ], expected[ 2 ], 0.001 );
			assert.closeTo( actual[ 3 ], expected[ 3 ], 0.001 );
			assert.closeTo( actual[ 4 ], expected[ 4 ], 0.001 );
			assert.closeTo( actual[ 5 ], expected[ 5 ], 0.001 );
			assert.closeTo( actual[ 6 ], expected[ 6 ], 0.001 );
			assert.closeTo( actual[ 7 ], expected[ 7 ], 0.001 );
			assert.closeTo( actual[ 8 ], expected[ 8 ], 0.001 );
			assert.closeTo( actual[ 9 ], expected[ 9 ], 0.001 );

			done();
		} // end FUNCTION onRead()
	});

});<commit_msg>[UPDATE] do not assume default initial value.<commit_after>
// MODULES //

var // Expectation library:
	chai = require( 'chai' ),

	// Test utilities:
	utils = require( './utils' ),

	// Module to be tested:
	mStream = require( './../lib/stats/mmean' );

// VARIABLES //

var expect = chai.expect,
	assert = chai.assert;

// TESTS //

describe( 'stats/mean', function tests() {
	'use strict';

	it( 'should export a factory function', function test() {
		expect( mStream ).to.be.a( 'function' );
	});

	it( 'should provide a method to get the window size', function test() {
		var tStream = mStream();
		expect( tStream.window() ).to.be.a( 'number' );
	});

	it( 'should provide a method to set the window size', function test() {
		var tStream = mStream();
		tStream.window( 25 );
		assert.strictEqual( tStream.window(), 25 );
	});

	it( 'should not allow a non-numeric window size', function test() {
		var tStream = mStream();

		expect( badValue( '5' ) ).to.throw( Error );
		expect( badValue( [] ) ).to.throw( Error );
		expect( badValue( {} ) ).to.throw( Error );
		expect( badValue( null ) ).to.throw( Error );
		expect( badValue( undefined ) ).to.throw( Error );
		expect( badValue( NaN ) ).to.throw( Error );

		function badValue( value ) {
			return function() {
				tStream.window( value );
			};
		}
	});

	it( 'should calculate the mean of piped data', function test( done ) {
		var data, expected, tStream, WINDOW = 5;

		// Simulate some data...
		data = [ 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5 ];

		// Expected values is the rolling average:
		expected = [ 2.4, 2.6, 3, 3.4, 3.6, 4, 4.4, 4.6 ];

		// Create a new mean stream:
		tStream = mStream()
			.window( WINDOW )
			.stream();

		// Mock reading from the stream:
		utils.readStream( tStream, onRead );

		// Mock piping a data to the stream:
		utils.writeStream( data, tStream );

		return;

		/**
		* FUNCTION: onRead( error, actual )
		*	Read event handler. Checks for errors and compares streamed data to expected data.
		*/
		function onRead( error, actual ) {
			expect( error ).to.not.exist;

			assert.lengthOf( actual, data.length-WINDOW+1 );

			assert.closeTo( actual[ 0 ], expected[ 0 ], 0.001 );
			assert.closeTo( actual[ 1 ], expected[ 1 ], 0.001 );
			assert.closeTo( actual[ 2 ], expected[ 2 ], 0.001 );
			assert.closeTo( actual[ 3 ], expected[ 3 ], 0.001 );
			assert.closeTo( actual[ 4 ], expected[ 4 ], 0.001 );
			assert.closeTo( actual[ 5 ], expected[ 5 ], 0.001 );
			assert.closeTo( actual[ 6 ], expected[ 6 ], 0.001 );
			assert.closeTo( actual[ 7 ], expected[ 7 ], 0.001 );

			done();
		} // end FUNCTION onRead()
	});

	it( 'should calculate the mean of piped data using an arbitrary window size', function test( done ) {
		var data, expected, tStream, WINDOW = 3;

		// Simulate some data...
		data = [ 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5 ];

		// Expected values is the rolling average:
		expected = [ 2, 2.33333, 2.666666, 3, 3.33333333, 3.6666666, 4, 4.33333333, 4.66666666, 5 ];

		// Create a new mean stream:
		tStream = mStream()
			.window( WINDOW )
			.stream();

		// Mock reading from the stream:
		utils.readStream( tStream, onRead );

		// Mock piping a data to the stream:
		utils.writeStream( data, tStream );

		return;

		/**
		* FUNCTION: onRead( error, actual )
		*	Read event handler. Checks for errors and compares streamed data to expected data.
		*/
		function onRead( error, actual ) {
			expect( error ).to.not.exist;

			assert.lengthOf( actual, data.length-WINDOW+1 );

			assert.closeTo( actual[ 0 ], expected[ 0 ], 0.001 );
			assert.closeTo( actual[ 1 ], expected[ 1 ], 0.001 );
			assert.closeTo( actual[ 2 ], expected[ 2 ], 0.001 );
			assert.closeTo( actual[ 3 ], expected[ 3 ], 0.001 );
			assert.closeTo( actual[ 4 ], expected[ 4 ], 0.001 );
			assert.closeTo( actual[ 5 ], expected[ 5 ], 0.001 );
			assert.closeTo( actual[ 6 ], expected[ 6 ], 0.001 );
			assert.closeTo( actual[ 7 ], expected[ 7 ], 0.001 );
			assert.closeTo( actual[ 8 ], expected[ 8 ], 0.001 );
			assert.closeTo( actual[ 9 ], expected[ 9 ], 0.001 );

			done();
		} // end FUNCTION onRead()
	});

});<|endoftext|>


<commit_before>import express from 'express';
import path from 'path';
import logger from 'morgan';
import bodyParser from 'body-parser';
import routes from './routes';

const app = express();
app.disable('x-powered-by');

// View engine setup
app.set('views', path.join(__dirname, '../views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

app.use(logger('dev', {
  skip: () => app.get('env') === 'test'
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, '../public')));

// Routes
app.use('/', routes);

// Catch 404 and forward to error handler
app.use((req, res, next) => {
  const err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// Error handler
app.use((err, req, res, next) => { // eslint-disable-line no-unused-vars
  res
    .status(err.status || 500)
    .render('error', {
      message: err.message
    });
});

export default app;
<commit_msg>Ejs view engine<commit_after>import express from 'express';
import path from 'path';
import logger from 'morgan';
import bodyParser from 'body-parser';
import routes from './routes';

const app = express();
app.disable('x-powered-by');

// View engine setup
app.set('views', path.join(__dirname, '../views'));
app.set('view engine', 'ejs');

app.use(logger('dev', {
  skip: () => app.get('env') === 'test'
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, '../public')));

// Routes
app.use('/', routes);

// Catch 404 and forward to error handler
app.use((req, res, next) => {
  const err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// Error handler
app.use((err, req, res, next) => { // eslint-disable-line no-unused-vars
  res
    .status(err.status || 500)
    .render('error', {
      message: err.message
    });
});

export default app;
<|endoftext|>


<commit_before>module.exports = {
  extends: ['@commitlint/config-conventional'],
  rules: { 'header-max-length': [2, 'always', 100] },
};
<commit_msg>ci(commitlint): dynamically estimate max header length for pull request title on squash and merge (#387)<commit_after>// NOTICE: When a github "squash and merge" is performed, github add the PR link in the commit
//         message using the format ` (#<PR_ID>)`. Travis provide the target branch of the build,
//         so authorizing 4+5 = 9 characters more on master for the max header length should work
//         until we reach PR #99999.

let maxHeaderLength = 100;

const prExtrasChars = 9;

const isCommitOnMaster = process.env.TRAVIS_BRANCH && process.env.TRAVIS_BRANCH === 'master';

if (isCommitOnMaster) {
  maxHeaderLength += prExtrasChars;
}

module.exports = {
  extends: ['@commitlint/config-conventional'],
  rules: { 'header-max-length': [2, 'always', maxHeaderLength] },
};
<|endoftext|>


<commit_before>/*
* Description:  Session stored in redis for websvr
* Author:       Kris Zhang
* Licenses:     MIT
* Project url:  https://github.com/newghost/websvr-redis
*/

var redis = require('redis');

var RedisStore = module.exports = (function() {

  var client;

  var del = function(sid) {
    client.del(sid);
  };

  var set = function(sid, session) {
    client.set(sid, JSON.stringify(session), function(err) {
      err && console.error(err);
    });
  };

  var get = function(sid, cb) {
    var session = {};

    client.get(sid, function(err, data) {
      if (err) {
        console.error(err);
      } else {
        try {
          session = JSON.parse(data);
        } catch(e) {
          del(sid);
        }
      }

      cb && cb(session);
    });
  };

  /*
  Clear the sessions, you should do it manually somewhere, etc:
  setInterval(websvr.SessionStore.clear, 200 * 60 * 1000)
  */
  var clear = function() {
    client.keys('*', function (err, keys) {
      if (err) return console.log(err);

      //Delete these sessions that created very very long ago
      var expire = +new Date() - Settings.sessionTimeout * 24;

      for (var i = 0; i < keys.length; i++) {
        var key  = keys[i]
          , idx  = key.indexOf('-')
          , flag = true
          ;

        if (key.length == 25 && idx > 0) {
          var stamp = parseInt(key.substr(0, idx), 32);
          //expired?
          stamp && stamp > expire && (flag = false);
        }

        flag && del(key);
      }
    });
  };

  var start = function(options) {
    options = options || {};

    var host = options.host   || '127.0.0.1'
      , port = parseInt(options.host) || 6379
      , opts = options.opts   || {}
      , auth = options.auth
      , idx  = options.select || 0
      ;

    client = redis.createClient(port, host, opts);

    auth && client.auth(auth);

    client.select(idx);

    client.on('error', function (err) {
      console.error('Error ' + err);
    });
  };

  return {
      get   : get
    , set   : set
    , del   : del
    , clear : clear
    , start : start
  }

})();<commit_msg>update<commit_after>/*
* Description:  Session stored in redis for websvr
* Author:       Kris Zhang
* Licenses:     MIT
* Project url:  https://github.com/newghost/websvr-redis
*/

var redis = require('redis');

var RedisStore = module.exports = (function() {

  var client;

  var del = function(sid) {
    client.del(sid);
  };

  var set = function(sid, session) {
    client.set(sid, JSON.stringify(session), function(err) {
      err && console.error(err);
    });
  };

  var get = function(sid, cb) {
    var session = {};

    client.get(sid, function(err, data) {
      if (err) {
        console.error(err);
      } else {
        try {
          session = JSON.parse(data);
        } catch(e) {
          del(sid);
        }
      }

      cb && cb(session);
    });
  };

  //Delete these sessions that created long long ago (1 day)
  var expire = 24 * 3600 * 1000;
  /*
  Clear the sessions, you should do it manually somewhere, etc:
  setInterval(websvr.SessionStore.clear, 200 * 60 * 1000)
  */
  var clear = function() {
    client.keys('*', function (err, keys) {
      if (err) return console.log(err);

      for (var i = 0; i < keys.length; i++) {
        var key  = keys[i]
          , idx  = key.indexOf('-')
          , flag = true
          ;

        if (key.length == 25 && idx > 0) {
          var stamp = parseInt(key.substr(0, idx), 32);
          //expired?
          stamp && stamp > expire && (flag = false);
        }

        flag && del(key);
      }
    });
  };

  var start = function(options) {
    options = options || {};

    var host = options.host   || '127.0.0.1'
      , port = parseInt(options.host) || 6379
      , opts = options.opts   || {}
      , auth = options.auth
      , idx  = options.select || 0
      ;

    client = redis.createClient(port, host, opts);

    auth && client.auth(auth);

    client.select(idx);

    client.on('error', function (err) {
      console.error('Error ' + err);
    });
  };

  return {
      get   : get
    , set   : set
    , del   : del
    , clear : clear
    , start : start
  }

})();<|endoftext|>


<commit_before>// Initialization --------------------------------------------------------------
$.getJSON("../config.json", function(data) {
  console.log("initialized");
  SC.initialize({
    client_id: data["soundcloud_client_id"]
  });
});

chrome.storage.sync.clear();
var stream = null;
var currentTracks = null;
var currentSongIdx = -1;
// -----------------------------------------------------------------------------
chrome.runtime.onConnect.addListener(function(port) {
  clearPagination();
  displayCurrentSong(port);
  displayPreviousSearch(port);
  port.onMessage.addListener(messageHandler(port));
});

function messageHandler(port) {
  var listener = function(msg) {
    var content = msg.content;
    var message = msg.message;

    switch (message) {
      case "play-song":
        playSong(port, content.index);
        displayCurrentExtensionTrack(port);
        break;
      case "search":
        var searchInfo = {
          q: content,
          limit: 10,
          linked_partitioning: 1
        };

        SC.get("/tracks", searchInfo).then(function(res) {
          chrome.storage.sync.set({
            previousSearch: searchInfo
          });
          displayTracks(port, res);
        });
        break;
      case "toggle":
        if (!!stream) {
          stream.toggle();
        }
        break;
      case "next-tracks":
        var currentTrackHref = content;
        $.getJSON(currentTrackHref, function(res) {
          displayTracks(port, res);
          chrome.storage.sync.set({
            prevTracks: getPrevHref(currentTrackHref)
          });
        });
        break;
      case "prev-tracks":
        chrome.storage.sync.get("prevTracks", function(obj) {
          if (chrome.runtime.lastError == null && !$.isEmptyObject(obj)) {
            var currentTrackHref = obj.prevTracks;
            $.getJSON(obj.prevTracks, function(res) {
              displayTracks(port, res);
              chrome.storage.sync.set({
                prevTracks: getPrevHref(currentTrackHref)
              });
            });
          }
        });
        break;
      default:
        break;
    }
  };
  // displayCurrentSong(port); // might not need
  return listener;
}

// BUG: you can't replay the same song over. probably because the stream
// doesn't close/is cached? Have to look into this.
function playSong(port, index) {
  var track = currentTracks[index];
  chrome.storage.sync.set({
    currentTrack: track
  });
  SC.stream("/tracks/" + track.id).then(function(player) {
    player.on("finish", function() {
      chrome.storage.sync.set({
        currentTrack: {}
      });
      // TODO: out-of-bounds handling that would require pagination
      playSong(port, index + 1);
    });

    player.play();

    currentSongIdx = index;
    stream = player;
  });

  // BUG: auto-play won't display the new current track
  displayCurrentExtensionTrack(port);
}

function displayTracks(port, tracksResp) {
  currentTracks = tracksResp.collection;
  port.postMessage({
    message: "display-tracks",
    content: tracksResp
  });
}

function displayPreviousSearch(port) {
  chrome.storage.sync.get(["previousSearch"], function(obj) {
    if (chrome.runtime.lastError == null && "previousSearch" in obj) {
      SC.get("/tracks", obj.previousSearch).then(function(res) {
        displayTracks(port, res);
      });
    }
  });
}

function displayCurrentSong(port) {
  chrome.tabs.query(
    {
      url: "*://soundcloud.com/*"
    },
    function(soundcloudTabs) {
      if (soundcloudTabs.length > 0) {
        var currentlyPlaying = null;
        // TODO: try to not have to look thru all the tabs every time. Caching?
        var audibleTabs = soundcloudTabs.filter(function(t) {
          return t.audible == true;
        });
        if (audibleTabs.length == 0) {
          return;
        }
        currentlyPlaying = audibleTabs[0];
        port.postMessage({
          message: "display-current-track",
          content: currentlyPlaying
        });
      } else {
        displayCurrentExtensionTrack(port);
      }
    }
  );
}

function displayCurrentExtensionTrack(port) {
  chrome.storage.sync.get(["currentTrack"], function(obj) {
    if (
      chrome.runtime.lastError == null &&
      "currentTrack" in obj &&
      !$.isEmptyObject(obj.currentTrack)
    ) {
      port.postMessage({
        message: "display-current-track",
        content: {
          track: obj.currentTrack,
          isPlaying: !!stream && stream.controller.getState() === "playing"
        }
      });
    }
  });
}

function clearPagination() {
  chrome.storage.sync.remove(["prevTracks", "nextTracks"]);
}

// Assumes valid API url from soundcloud
function getPrevHref(url) {
  var oldUrl = url.split("?");
  var params = $.parseParams(oldUrl[1]);
  if (params.offset > 0) {
    params.offset =
      Number.parseInt(params.offset) - Number.parseInt(params.limit);
  }
  return oldUrl[0] + "?" + $.param(params);
}

function getNextHref(url) {
  var oldUrl = url.split("?");
  var params = $.parseParams(oldUrl[1]);
  params.offset =
    Number.parseInt(params.offset) + Number.parseInt(params.limit);
  return oldUrl[0] + "?" + $.param(params);
}

// https://gist.github.com/kares/956897
(function($) {
  var re = /([^&=]+)=?([^&]*)/g;
  var decodeRE = /\+/g; // Regex for replacing addition symbol with a space
  var decode = function(str) {
    return decodeURIComponent(str.replace(decodeRE, " "));
  };
  $.parseParams = function(query) {
    var params = {},
      e;
    while ((e = re.exec(query))) {
      var k = decode(e[1]),
        v = decode(e[2]);
      if (k.substring(k.length - 2) === "[]") {
        k = k.substring(0, k.length - 2);
        (params[k] || (params[k] = [])).push(v);
      } else params[k] = v;
    }
    return params;
  };
})(jQuery);

// --------- KEYBOARD SHORTCUT LISTENERS -------------------------------------
function switchToTabInWindow(tabId, windowId) {
  var windowUpdateInfo = { focused: true };
  chrome.windows.update(windowId, windowUpdateInfo);

  var tabUpdateInfo = { active: true };
  chrome.tabs.update(tabId, tabUpdateInfo);
}

function setPrevPageInfo(tabId, windowId) {
  var newPrevInfo = {
    prevTabId: tabId,
    prevWindowId: windowId
  };
  chrome.storage.sync.set(newPrevInfo);
}

chrome.commands.onCommand.addListener(function(command) {
  switch (command) {
    case "open-soundcloud":
      var activeTabInfo = {
        lastFocusedWindow: true,
        active: true
      };
      chrome.tabs.query(activeTabInfo, function(tabs) {
        if (tabs.length > 0) {
          // only set previous info if the page you are looking at is a
          // "tabbable" window. For example, a develepor tools window. TODO: look more into this.
          setPrevPageInfo(tabs[0].id, tabs[0].windowId);
        }
      });
      var query = {
        url: "*://soundcloud.com/*"
      };
      chrome.tabs.query(query, function(soundcloudTabs) {
        if (soundcloudTabs.length == 0) {
          chrome.tabs.create({
            url: "https://soundcloud.com"
          });
        } else {
          var tabToSwitchTo = null;
          // TODO: try to not have to look thru all the tabs every time. Caching?
          var audibleTabs = soundcloudTabs.filter(function(t) {
            return t.audible == true;
          });
          if (audibleTabs.length > 0) {
            tabToSwitchTo = audibleTabs[0];
          } else {
            tabToSwitchTo = soundcloudTabs[0];
          }
          // TODO: only update if not on tabToSwitchTo
          switchToTabInWindow(tabToSwitchTo.id, tabToSwitchTo.windowId);
        }
      });
      break;
    case "previous-location":
      var prevInfo = ["prevTabId", "prevWindowId"];
      chrome.storage.sync.get(prevInfo, function(prevInfo) {
        if (chrome.runtime.lastError == null) {
          switchToTabInWindow(prevInfo.prevTabId, prevInfo.prevWindowId);
        }
      });
    default:
      break;
  }
});
<commit_msg>move display current track outside of play function<commit_after>// Initialization --------------------------------------------------------------
$.getJSON("../config.json", function(data) {
  console.log("initialized");
  SC.initialize({
    client_id: data["soundcloud_client_id"]
  });
});

chrome.storage.sync.clear();
var stream = null;
var currentTracks = null;
var currentSongIdx = -1;
// -----------------------------------------------------------------------------
chrome.runtime.onConnect.addListener(function(port) {
  clearPagination();
  displayCurrentSong(port);
  displayPreviousSearch(port);
  port.onMessage.addListener(messageHandler(port));
});

function messageHandler(port) {
  var listener = function(msg) {
    var content = msg.content;
    var message = msg.message;

    switch (message) {
      case "play-song":
        playSong(content.index);
        displayCurrentExtensionTrack(port);
        break;
      case "search":
        var searchInfo = {
          q: content,
          limit: 10,
          linked_partitioning: 1
        };

        SC.get("/tracks", searchInfo).then(function(res) {
          chrome.storage.sync.set({
            previousSearch: searchInfo
          });
          displayTracks(port, res);
        });
        break;
      case "toggle":
        if (!!stream) {
          stream.toggle();
        }
        break;
      case "next-tracks":
        var currentTrackHref = content;
        $.getJSON(currentTrackHref, function(res) {
          displayTracks(port, res);
          chrome.storage.sync.set({
            prevTracks: getPrevHref(currentTrackHref)
          });
        });
        break;
      case "prev-tracks":
        chrome.storage.sync.get("prevTracks", function(obj) {
          if (chrome.runtime.lastError == null && !$.isEmptyObject(obj)) {
            var currentTrackHref = obj.prevTracks;
            $.getJSON(obj.prevTracks, function(res) {
              displayTracks(port, res);
              chrome.storage.sync.set({
                prevTracks: getPrevHref(currentTrackHref)
              });
            });
          }
        });
        break;
      default:
        break;
    }
  };
  // displayCurrentSong(port); // might not need
  return listener;
}

// BUG: you can't replay the same song over. probably because the stream
// doesn't close/is cached? Have to look into this.
function playSong(index) {
  var track = currentTracks[index];
  chrome.storage.sync.set({
    currentTrack: track
  });
  SC.stream("/tracks/" + track.id).then(function(player) {
    player.on("finish", function() {
      chrome.storage.sync.set({
        currentTrack: {}
      });
      console.log(player.controller.getState());
      // TODO: out-of-bounds handling that would require pagination
      playSong(index + 1);
    });

    player.play();

    currentSongIdx = index;
    stream = player;
  });
}

function displayTracks(port, tracksResp) {
  currentTracks = tracksResp.collection;
  port.postMessage({
    message: "display-tracks",
    content: tracksResp
  });
}

function displayPreviousSearch(port) {
  chrome.storage.sync.get(["previousSearch"], function(obj) {
    if (chrome.runtime.lastError == null && "previousSearch" in obj) {
      SC.get("/tracks", obj.previousSearch).then(function(res) {
        displayTracks(port, res);
      });
    }
  });
}

function displayCurrentSong(port) {
  chrome.tabs.query(
    {
      url: "*://soundcloud.com/*"
    },
    function(soundcloudTabs) {
      if (soundcloudTabs.length > 0) {
        var currentlyPlaying = null;
        // TODO: try to not have to look thru all the tabs every time. Caching?
        var audibleTabs = soundcloudTabs.filter(function(t) {
          return t.audible == true;
        });
        if (audibleTabs.length == 0) {
          displayCurrentExtensionTrack(port);
          return;
        }
        currentlyPlaying = audibleTabs[0];
        port.postMessage({
          message: "display-current-track",
          content: currentlyPlaying
        });
      } else {
        displayCurrentExtensionTrack(port);
      }
    }
  );
}

function displayCurrentExtensionTrack(port) {
  chrome.storage.sync.get(["currentTrack"], function(obj) {
    if (
      chrome.runtime.lastError == null &&
      "currentTrack" in obj &&
      !$.isEmptyObject(obj.currentTrack)
    ) {
      port.postMessage({
        message: "display-current-track",
        content: {
          track: obj.currentTrack,
          isPlaying: !!stream && stream.controller.getState() === "playing"
        }
      });
    }
  });
}

function clearPagination() {
  chrome.storage.sync.remove(["prevTracks", "nextTracks"]);
}

// Assumes valid API url from soundcloud
function getPrevHref(url) {
  var oldUrl = url.split("?");
  var params = $.parseParams(oldUrl[1]);
  if (params.offset > 0) {
    params.offset =
      Number.parseInt(params.offset) - Number.parseInt(params.limit);
  }
  return oldUrl[0] + "?" + $.param(params);
}

function getNextHref(url) {
  var oldUrl = url.split("?");
  var params = $.parseParams(oldUrl[1]);
  params.offset =
    Number.parseInt(params.offset) + Number.parseInt(params.limit);
  return oldUrl[0] + "?" + $.param(params);
}

// https://gist.github.com/kares/956897
(function($) {
  var re = /([^&=]+)=?([^&]*)/g;
  var decodeRE = /\+/g; // Regex for replacing addition symbol with a space
  var decode = function(str) {
    return decodeURIComponent(str.replace(decodeRE, " "));
  };
  $.parseParams = function(query) {
    var params = {},
      e;
    while ((e = re.exec(query))) {
      var k = decode(e[1]),
        v = decode(e[2]);
      if (k.substring(k.length - 2) === "[]") {
        k = k.substring(0, k.length - 2);
        (params[k] || (params[k] = [])).push(v);
      } else params[k] = v;
    }
    return params;
  };
})(jQuery);

// --------- KEYBOARD SHORTCUT LISTENERS -------------------------------------
function switchToTabInWindow(tabId, windowId) {
  var windowUpdateInfo = { focused: true };
  chrome.windows.update(windowId, windowUpdateInfo);

  var tabUpdateInfo = { active: true };
  chrome.tabs.update(tabId, tabUpdateInfo);
}

function setPrevPageInfo(tabId, windowId) {
  var newPrevInfo = {
    prevTabId: tabId,
    prevWindowId: windowId
  };
  chrome.storage.sync.set(newPrevInfo);
}

chrome.commands.onCommand.addListener(function(command) {
  switch (command) {
    case "open-soundcloud":
      var activeTabInfo = {
        lastFocusedWindow: true,
        active: true
      };
      chrome.tabs.query(activeTabInfo, function(tabs) {
        if (tabs.length > 0) {
          // only set previous info if the page you are looking at is a
          // "tabbable" window. For example, a develepor tools window. TODO: look more into this.
          setPrevPageInfo(tabs[0].id, tabs[0].windowId);
        }
      });
      var query = {
        url: "*://soundcloud.com/*"
      };
      chrome.tabs.query(query, function(soundcloudTabs) {
        if (soundcloudTabs.length == 0) {
          chrome.tabs.create({
            url: "https://soundcloud.com"
          });
        } else {
          var tabToSwitchTo = null;
          // TODO: try to not have to look thru all the tabs every time. Caching?
          var audibleTabs = soundcloudTabs.filter(function(t) {
            return t.audible == true;
          });
          if (audibleTabs.length > 0) {
            tabToSwitchTo = audibleTabs[0];
          } else {
            tabToSwitchTo = soundcloudTabs[0];
          }
          // TODO: only update if not on tabToSwitchTo
          switchToTabInWindow(tabToSwitchTo.id, tabToSwitchTo.windowId);
        }
      });
      break;
    case "previous-location":
      var prevInfo = ["prevTabId", "prevWindowId"];
      chrome.storage.sync.get(prevInfo, function(prevInfo) {
        if (chrome.runtime.lastError == null) {
          switchToTabInWindow(prevInfo.prevTabId, prevInfo.prevWindowId);
        }
      });
    default:
      break;
  }
});
<|endoftext|>


<commit_before>module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    concat: {
      options: {
        separator: ';',
      },
      dist: {
        src: ['js/actions.js', 'js/main.js', 'js/vendor/fuse.min.js'],
        dest: 'js/dist/built.js',
      },
    },
    watch: {
      js: {
        files: [
          'js/*.js'

        ],
        tasks: [
          'default',
        ]
      }
    }
  });
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.registerTask('default', ['concat']);
}<commit_msg>Add css to grunt watch.<commit_after>module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    concat: {
      options: {
        separator: ';',
      },
      dist: {
        src: ['js/actions.js', 'js/main.js', 'js/vendor/fuse.min.js'],
        dest: 'js/dist/built.js',
      },
    },
    watch: {
      js: {
        files: [
          'js/*.js',
          'css/*.css'
        ],
        tasks: [
          'default',
        ]
      }
    }
  });
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.registerTask('default', ['concat']);
}<|endoftext|>


<commit_before>/*
 * slurp-esri
 * github.com/steveoh/slurp-esri
 *
 * Copyright (c) 2014 steveoh
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {
  // load all npm grunt tasks
  require('load-grunt-tasks')(grunt);

  // Project configuration.
  grunt.initConfig({
    jshint: {
      all: [
        'Gruntfile.js',
        'tasks/*.js',
        '<%= nodeunit.tests %>'
      ],
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      }
    },

    // Before generating any new files, remove any previously-created files.
    clean: {
      tests: ['tmp', 'src']
    },
    esri_slurp: {
      options: {
        version: '3.8'
      }
    },
    // Unit tests.
    nodeunit: {
      tests: ['test/*_test.js']
    },
    bump: {
      options: {
        pushTo: 'origin'
      }
    }
  });

  // Actually load this plugin's task(s).
  grunt.loadTasks('tasks');
  grunt.loadNpmTasks('grunt-bump');

  // Whenever the "test" task is run, first clean the "tmp" dir, then run this
  // plugin's task(s), then test the result.
  grunt.registerTask('test', ['clean', 'nodeunit']);

  // By default, lint and run all tests.
  grunt.registerTask('default', ['jshint', 'esri_slurp']);

  grunt.registerTask('travis', ['jshint', 'esri_slurp', 'nodeunit']);
};<commit_msg>no more grunt bumping without the commits!<commit_after>/*
 * slurp-esri
 * github.com/steveoh/slurp-esri
 *
 * Copyright (c) 2014 steveoh
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {
  // load all npm grunt tasks
  require('load-grunt-tasks')(grunt);

  // Project configuration.
  grunt.initConfig({
    jshint: {
      all: [
        'Gruntfile.js',
        'tasks/*.js',
        '<%= nodeunit.tests %>'
      ],
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      }
    },

    // Before generating any new files, remove any previously-created files.
    clean: {
      tests: ['tmp', 'src']
    },
    esri_slurp: {
      options: {
        version: '3.8'
      }
    },
    // Unit tests.
    nodeunit: {
      tests: ['test/*_test.js']
    },
    bump: {
      options: {
        pushTo: 'origin',
        commit: true
      }
    }
  });

  // Actually load this plugin's task(s).
  grunt.loadTasks('tasks');
  grunt.loadNpmTasks('grunt-bump');

  // Whenever the "test" task is run, first clean the "tmp" dir, then run this
  // plugin's task(s), then test the result.
  grunt.registerTask('test', ['clean', 'nodeunit']);

  // By default, lint and run all tests.
  grunt.registerTask('default', ['jshint', 'esri_slurp']);

  grunt.registerTask('travis', ['jshint', 'esri_slurp', 'nodeunit']);
};<|endoftext|>


<commit_before>//    Copyright 2016 underdolphin(masato sueda)
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.

/// <reference path="typings/index.d.ts" />

const Electron = require('electron-connect').server;
const gulp = require('gulp');
const cleancss = require('gulp-clean-css');
const htmlmin = require('gulp-htmlmin');
const plumber = require('gulp-plumber');
const stylus = require('gulp-stylus');
const prettydiff = require('gulp-prettydiff');
const typescript = require('gulp-typescript');

const process = require('child_process');

gulp.task('html', () => {
    gulp.src('src/**/*.html')
        .pipe(plumber())
        .pipe(htmlmin({
            collapseWhitespace: true
        }))
        .pipe(gulp.dest('./build/'));
});

gulp.task('css', () => {
    gulp.src('src/**/*.styl')
        .pipe(plumber())
        .pipe(stylus())
        .pipe(cleancss())
        .pipe(gulp.dest('./build/'));
})

gulp.task('js', () => {
    const project = typescript('tsconfig.json', {
        typescript: require('typescript')
    });

    gulp.src('src/**/*.ts')
        .pipe(plumber())
        .pipe(typescript(project))
        .pipe(prettydiff({
            lang: 'js',
            mode: 'minify',
        }))
        .pipe(gulp.dest('./build/'));
});

gulp.task('serve', () => {
    const electron = Electron.create();
    electron.start();
    gulp.watch('build/main/**/**.js',electron.restart)
    gulp.watch(['build/**/**.html','build/**/**.css','build/renderer/**/**.js'],electron.reload)
})

gulp.task('watch', () => {

    gulp.watch('src/**/*.html', ['html']);
    gulp.watch('src/**/*.styl', ['css']);
    gulp.watch('src/**/*.ts', ['js']);
});

gulp.task("default",['html','css','js','serve','watch']);<commit_msg>Change gulpfile.js<commit_after>//    Copyright 2016 underdolphin(masato sueda)
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.

/// <reference path="typings/index.d.ts" />

const electron = require('electron-connect').server.create();
const gulp = require('gulp');
const cleancss = require('gulp-clean-css');
const htmlmin = require('gulp-htmlmin');
const plumber = require('gulp-plumber');
const stylus = require('gulp-stylus');
const prettydiff = require('gulp-prettydiff');
const typescript = require('gulp-typescript');

gulp.task('html', () => {
    gulp.src('src/**/*.html')
        .pipe(plumber())
        .pipe(htmlmin({
            collapseWhitespace: true
        }))
        .pipe(gulp.dest('./build/'));
});

gulp.task('css', () => {
    gulp.src('src/**/*.styl')
        .pipe(plumber())
        .pipe(stylus())
        .pipe(cleancss())
        .pipe(gulp.dest('./build/'));
})

gulp.task('js', () => {
    const project = typescript('tsconfig.json', {
        typescript: require('typescript')
    });

    gulp.src('src/**/*.ts')
        .pipe(plumber())
        .pipe(typescript(project))
        .pipe(prettydiff({
            lang: 'js',
            mode: 'minify',
        }))
        .pipe(gulp.dest('./build/'));
});

gulp.task('serve', () => {
    electron.start();
    gulp.watch('build/main/**/**.js', ['restart:electron']);
    gulp.watch(['build/**/**.html', 'build/**/**.css', 'build/renderer/**/**.js'], ['reload:renderer'])
})

gulp.task('watch', () => {
    gulp.watch('src/**/*.html', ['html']);
    gulp.watch('src/**/*.styl', ['css']);
    gulp.watch('src/**/*.ts', ['js']);
});

gulp.task('restart:electron', (done) => {
    electron.restart();
    done();
});

gulp.task('reload:renderer', (done) => {
    electron.reload();
    done();
});

gulp.task("default", ['watch','serve']);<|endoftext|>


<commit_before>// @flow

import {getTermInfo} from '../../../../lib/storage'
import {parseTerm} from '../../../../lib/course-search/parse-term'
import type {FilterType} from '../../../components/filter'
import {loadAllCourseFilterOptions} from '../../../../lib/course-search'

export async function buildFilters(): Promise<FilterType[]> {
	const terms = await getTermInfo()
	const allTerms = terms
		.map(term => ({
			title: term.term,
			label: parseTerm(term.term.toString()),
		}))
		.reverse()

	const {ges, departments} = await loadAllCourseFilterOptions()

	const allGEs = ges.map(ge => ({title: ge}))
	const allDepartments = departments.map(dep => ({title: dep}))

	return [
		{
			type: 'toggle',
			key: 'spaceAvailable',
			enabled: false,
			spec: {
				label: 'Space Available',
				title: 'Enrollment',
				caption: 'When activated, shows only courses with space available.',
			},
			apply: {
				key: 'spaceAvailable',
			},
		},
		{
			type: 'list',
			key: 'term',
			enabled: false,
			spec: {
				title: 'Terms',
				options: allTerms,
				mode: 'OR',
				selected: allTerms,
				displayTitle: false,
			},
			apply: {
				key: 'term',
			},
		},
		{
			type: 'list',
			key: 'gereqs',
			enabled: false,
			spec: {
				title: 'GEs',
				showImages: false,
				options: allGEs,
				mode: 'AND',
				selected: [],
				displayTitle: true,
			},
			apply: {
				key: 'gereqs',
			},
		},
		{
			type: 'list',
			key: 'departments',
			enabled: false,
			spec: {
				title: 'Departments',
				showImages: false,
				options: allDepartments,
				mode: 'OR',
				selected: allDepartments,
				displayTitle: true,
			},
			apply: {
				key: 'departments',
			},
		},
		{
			type: 'toggle',
			key: 'status',
			enabled: false,
			spec: {
				label: 'Open Courses',
				title: 'Status',
				caption:
					'Allows you to either see only courses that are open, or all courses.',
			},
			apply: {
				key: 'status',
				trueEquivalent: 'O',
			},
		},
		{
			type: 'toggle',
			key: 'type',
			enabled: false,
			spec: {
				label: 'Lab Only',
				title: 'Lab',
				caption: 'Allows you to only see labs.',
			},
			apply: {
				key: 'type',
				trueEquivalent: 'Lab',
			},
		},
	]
}
<commit_msg>add course level filter<commit_after>// @flow

import {getTermInfo} from '../../../../lib/storage'
import {parseTerm} from '../../../../lib/course-search/parse-term'
import type {FilterType} from '../../../components/filter'
import {loadAllCourseFilterOptions} from '../../../../lib/course-search'

export async function buildFilters(): Promise<FilterType[]> {
	const terms = await getTermInfo()
	const allTerms = terms
		.map(term => ({
			title: term.term,
			label: parseTerm(term.term.toString()),
		}))
		.reverse()

	const {ges, departments} = await loadAllCourseFilterOptions()

	const allGEs = ges.map(ge => ({title: ge}))
	const allDepartments = departments.map(dep => ({title: dep}))
	const courseLevelOptions = [{title: 100}, {title: 200}, {title: 300}]

	return [
		{
			type: 'toggle',
			key: 'spaceAvailable',
			enabled: false,
			spec: {
				label: 'Space Available',
				title: 'Enrollment',
				caption: 'When activated, shows only courses with space available.',
			},
			apply: {
				key: 'spaceAvailable',
			},
		},
		{
			type: 'list',
			key: 'term',
			enabled: false,
			spec: {
				title: 'Terms',
				options: allTerms,
				mode: 'OR',
				selected: allTerms,
				displayTitle: false,
			},
			apply: {
				key: 'term',
			},
		},
		{
			type: 'list',
			key: 'gereqs',
			enabled: false,
			spec: {
				title: 'GEs',
				showImages: false,
				options: allGEs,
				mode: 'AND',
				selected: [],
				displayTitle: true,
			},
			apply: {
				key: 'gereqs',
			},
		},
		{
			type: 'list',
			key: 'departments',
			enabled: false,
			spec: {
				title: 'Departments',
				showImages: false,
				options: allDepartments,
				mode: 'OR',
				selected: allDepartments,
				displayTitle: true,
			},
			apply: {
				key: 'departments',
			},
		},
		{
			type: 'list',
			key: 'level',
			enabled: false,
			spec: {
				title: 'Level',
				showImages: false,
				options: courseLevelOptions,
				mode: 'OR',
				selected: courseLevelOptions,
				displayTitle: true,
			},
			apply: {
				key: 'level',
			},
		},
		{
			type: 'toggle',
			key: 'status',
			enabled: false,
			spec: {
				label: 'Open Courses',
				title: 'Status',
				caption:
					'Allows you to either see only courses that are open, or all courses.',
			},
			apply: {
				key: 'status',
				trueEquivalent: 'O',
			},
		},
		{
			type: 'toggle',
			key: 'type',
			enabled: false,
			spec: {
				label: 'Lab Only',
				title: 'Lab',
				caption: 'Allows you to only see labs.',
			},
			apply: {
				key: 'type',
				trueEquivalent: 'Lab',
			},
		},
	]
}
<|endoftext|>


<commit_before>/**
 * Copyright 2015 Kitware Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * This file contains options that apply to ALL target build configurations. Because we use
 * the DllPlugin for dynamic loading, each individual bundle has its own config options
 * that can extend these.
 */
var path = require('path');
var webpack = require('webpack');

var ExtractTextPlugin = require('extract-text-webpack-plugin');

var paths = require('./webpack.paths.js');
var es2015Preset = require.resolve('babel-preset-es2015');

function fileLoader() {
    return {
        loader: 'file-loader',
        query: {
            name: 'assets/[name]-[hash:8].[ext]'
        }
    };
}

function urlLoader(options) {
    options = options || {};
    var loader = {
        loader: 'url-loader',
        query: {
            limit: 4096
        }
    };
    if (options.mimetype) {
        loader.query.mimetype = options.mimetype;
    }
    return loader;
}

function _coverageConfig() {
    try {
        var istanbulPlugin = require.resolve('babel-plugin-istanbul');
        return {
            plugins: [[
                istanbulPlugin, {
                    exclude: ['**/*.pug', '**/*.jade', 'node_modules/**/*']
                }
            ]]
        };
    } catch (e) {
        // We won't have the istanbul plugin installed in a prod env.
        return {};
    }
}

var loaderPaths = [path.resolve('clients', 'web', 'src')];
var loaderPathsNodeModules = loaderPaths.concat([path.resolve('node_modules')]);

module.exports = {
    output: {
        path: paths.web_built,
        filename: '[name].min.js'
    },
    plugins: [
        // Automatically detect jQuery and $ as free var in modules
        // and inject the jquery library. This is required by many jquery plugins
        new webpack.ProvidePlugin({
            jQuery: 'jquery',
            $: 'jquery',
            'window.jQuery': 'jquery'
        })
    ],
    module: {
        loaders: [
            // ES2015
            {
                test: /\.js$/,
                include: loaderPaths,
                loader: 'babel-loader',
                exclude: /node_modules/,
                query: {
                    presets: [es2015Preset],
                    env: {
                        cover: _coverageConfig()
                    }
                }
            },
            // JSON files
            {
                test: /\.json$/,
                include: loaderPaths.concat(loaderPathsNodeModules),
                loader: 'json-loader'
            },
            // Stylus
            {
                test: /\.styl$/,
                include: loaderPaths,
                loader: ExtractTextPlugin.extract({
                    fallbackLoader: 'style-loader',
                    loader: ['css-loader', {
                        loader: 'stylus-loader',
                        query: {
                            'resolve url': true
                        }
                    }]
                })
            },
            // CSS
            {
                test: /\.css$/,
                include: loaderPathsNodeModules,
                loader: ExtractTextPlugin.extract({
                    fallbackLoader: 'style-loader',
                    loader: ['css-loader']})
            },
            // Pug
            {
                test: /\.(pug|jade)$/,
                include: loaderPaths,
                loaders: [
                    {
                        loader: 'babel-loader',
                        query: {
                            presets: [es2015Preset]
                        }
                    },
                    'pug-loader'
                ]
            },
            // PNG, JPEG
            {
                test: /\.(png|jpg)$/,
                include: loaderPathsNodeModules,
                loaders: [
                    fileLoader()
                ]
            },
            // WOFF
            {
                test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
                include: loaderPathsNodeModules,
                loaders: [
                    urlLoader({ mimetype: 'application/font-woff' }),
                    fileLoader()
                ]
            },
            // WOFF2
            {
                test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
                include: loaderPathsNodeModules,
                loaders: [
                    urlLoader({ mimetype: 'application/font-woff2' }),
                    fileLoader()
                ]
            },
            // TTF
            {
                test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
                include: loaderPathsNodeModules,
                loaders: [
                    urlLoader({ mimetype: 'application/octet-stream' }),
                    fileLoader()
                ]
            },
            // EOT
            {
                test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
                include: loaderPathsNodeModules,
                loaders: [
                    fileLoader()
                ]
            },
            // SVG
            {
                test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
                include: loaderPathsNodeModules,
                loaders: [
                    urlLoader({ mimetype: 'image/svg+xml' }),
                    fileLoader()
                ]
            }
        ],
        noParse: [
            // Avoid warning:
            //   This seems to be a pre-built javascript file. Though this is
            //   possible, it's not recommended. Try to require the original source
            //   to get better results.
            // This needs fixing later, as Webpack works better when provided with source.
            // /node_modules\/pug/,
            // /node_modules\/remarkable/
        ]
    },
    resolve: {
        alias: {
            'girder': paths.web_src
        },
        modules: [
            paths.clients_web,
            paths.plugins,
            paths.node_modules
        ]
    },
    node: {
        canvas: 'empty',
        file: 'empty',
        fs: 'empty',
        jsdom: 'empty',
        system: 'empty',
        xmldom: 'empty'
    }
};
<commit_msg>Explicitly list webpack resolve.extensions<commit_after>/**
 * Copyright 2015 Kitware Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * This file contains options that apply to ALL target build configurations. Because we use
 * the DllPlugin for dynamic loading, each individual bundle has its own config options
 * that can extend these.
 */
var path = require('path');
var webpack = require('webpack');

var ExtractTextPlugin = require('extract-text-webpack-plugin');

var paths = require('./webpack.paths.js');
var es2015Preset = require.resolve('babel-preset-es2015');

function fileLoader() {
    return {
        loader: 'file-loader',
        query: {
            name: 'assets/[name]-[hash:8].[ext]'
        }
    };
}

function urlLoader(options) {
    options = options || {};
    var loader = {
        loader: 'url-loader',
        query: {
            limit: 4096
        }
    };
    if (options.mimetype) {
        loader.query.mimetype = options.mimetype;
    }
    return loader;
}

function _coverageConfig() {
    try {
        var istanbulPlugin = require.resolve('babel-plugin-istanbul');
        return {
            plugins: [[
                istanbulPlugin, {
                    exclude: ['**/*.pug', '**/*.jade', 'node_modules/**/*']
                }
            ]]
        };
    } catch (e) {
        // We won't have the istanbul plugin installed in a prod env.
        return {};
    }
}

var loaderPaths = [path.resolve('clients', 'web', 'src')];
var loaderPathsNodeModules = loaderPaths.concat([path.resolve('node_modules')]);

module.exports = {
    output: {
        path: paths.web_built,
        filename: '[name].min.js'
    },
    plugins: [
        // Automatically detect jQuery and $ as free var in modules
        // and inject the jquery library. This is required by many jquery plugins
        new webpack.ProvidePlugin({
            jQuery: 'jquery',
            $: 'jquery',
            'window.jQuery': 'jquery'
        })
    ],
    module: {
        loaders: [
            // ES2015
            {
                test: /\.js$/,
                include: loaderPaths,
                loader: 'babel-loader',
                exclude: /node_modules/,
                query: {
                    presets: [es2015Preset],
                    env: {
                        cover: _coverageConfig()
                    }
                }
            },
            // JSON files
            {
                test: /\.json$/,
                include: loaderPaths.concat(loaderPathsNodeModules),
                loader: 'json-loader'
            },
            // Stylus
            {
                test: /\.styl$/,
                include: loaderPaths,
                loader: ExtractTextPlugin.extract({
                    fallbackLoader: 'style-loader',
                    loader: ['css-loader', {
                        loader: 'stylus-loader',
                        query: {
                            'resolve url': true
                        }
                    }]
                })
            },
            // CSS
            {
                test: /\.css$/,
                include: loaderPathsNodeModules,
                loader: ExtractTextPlugin.extract({
                    fallbackLoader: 'style-loader',
                    loader: ['css-loader']})
            },
            // Pug
            {
                test: /\.(pug|jade)$/,
                include: loaderPaths,
                loaders: [
                    {
                        loader: 'babel-loader',
                        query: {
                            presets: [es2015Preset]
                        }
                    },
                    'pug-loader'
                ]
            },
            // PNG, JPEG
            {
                test: /\.(png|jpg)$/,
                include: loaderPathsNodeModules,
                loaders: [
                    fileLoader()
                ]
            },
            // WOFF
            {
                test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
                include: loaderPathsNodeModules,
                loaders: [
                    urlLoader({ mimetype: 'application/font-woff' }),
                    fileLoader()
                ]
            },
            // WOFF2
            {
                test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
                include: loaderPathsNodeModules,
                loaders: [
                    urlLoader({ mimetype: 'application/font-woff2' }),
                    fileLoader()
                ]
            },
            // TTF
            {
                test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
                include: loaderPathsNodeModules,
                loaders: [
                    urlLoader({ mimetype: 'application/octet-stream' }),
                    fileLoader()
                ]
            },
            // EOT
            {
                test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
                include: loaderPathsNodeModules,
                loaders: [
                    fileLoader()
                ]
            },
            // SVG
            {
                test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
                include: loaderPathsNodeModules,
                loaders: [
                    urlLoader({ mimetype: 'image/svg+xml' }),
                    fileLoader()
                ]
            }
        ],
        noParse: [
            // Avoid warning:
            //   This seems to be a pre-built javascript file. Though this is
            //   possible, it's not recommended. Try to require the original source
            //   to get better results.
            // This needs fixing later, as Webpack works better when provided with source.
            // /node_modules\/pug/,
            // /node_modules\/remarkable/
        ]
    },
    resolve: {
        alias: {
            'girder': paths.web_src
        },
        extensions: ['.js'],
        modules: [
            paths.clients_web,
            paths.plugins,
            paths.node_modules
        ]
    },
    node: {
        canvas: 'empty',
        file: 'empty',
        fs: 'empty',
        jsdom: 'empty',
        system: 'empty',
        xmldom: 'empty'
    }
};
<|endoftext|>