<commit_before>/** @license MIT License (c) copyright B Cavalier & J Hann */

/**
 * wire/cola plugin
 *
 * wire is part of the cujo.js family of libraries (http://cujojs.com/)
 *
 * Licensed under the MIT License at:
 * http://www.opensource.org/licenses/mit-license.php
 */

(function(define) {
define(['when', 'cola/AdapterResolver',
	'cola/ArrayAdapter', 'cola/dom/NodeListAdapter',
	'cola/ResultSetAdapter', 'cola/QueryAdapter', 'cola/mediator/syncCollections',
	'cola/ObjectAdapter', 'cola/dom/NodeAdapter',
	'cola/ResultAdapter', 'cola/mediator/syncProperties',
	'cola/addPropertyTransforms', 'cola/transformCollection', 'cola/transform/compose'],
function(when, adapterResolver,
	ArrayAdapter, NodeListAdapter, ResultSetAdapter, QueryAdapter, syncCollections,
	ObjectAdapter, NodeAdapter,
	ResultAdapter, syncProperties,
	addPropertyTransforms, transformCollection, compose
) {

	var cachedBindings, isArray, undef, slice;

	// TODO: move most of this stuff, including adapter registration to cola.js
	// TODO: implement wire$build that auto-adds these deps to build
	adapterResolver.register(ArrayAdapter, 'collection');
	adapterResolver.register(NodeListAdapter, 'collection');
//	adapterResolver.register(ResultSetAdapter, 'collection');
	adapterResolver.register(QueryAdapter, 'collection');
	adapterResolver.register(NodeAdapter, 'object');
	adapterResolver.register(ObjectAdapter, 'object');
//	adapterResolver.register(ResultAdapter, 'object');

	function querySelector (selector, node) {
		return node.querySelector(selector);
	}

	isArray = Array.isArray || function(it) {
		return Object.prototype.toString.call(it) == '[object Array]';
	};

	slice = Array.prototype.slice;

	/**
	 * "globally" cached bindings.  Cache bindings here so that a bind can find,
	 * process, and remove them later
	 * @private
 	 */
	cachedBindings = [];

	/**
	 * @private
	 * @param target anything - target component for which to find cached bindings
	 * @param found {Function} function to call with existing cached bindings
	 * @param [notFound] {Function} function to call if no cached bindings found
	 */
	function findCachedBindings(target, found, notFound) {
		for(var i = 0, len = cachedBindings.length; i < len; i++) {
			if(cachedBindings[i].target === target) {
				return found(cachedBindings, i, cachedBindings[i]);
			}
		}

		return notFound(cachedBindings);
	}

	function mixin(dst, src) {
		for(var p in src) {
			if(src.hasOwnProperty(p)) {
				dst[p] = src[p];
			}
		}
		return dst;
	}

	function mergeBindings(bindingDef, bindings) {
		mixin(bindingDef.bindings, bindings);
	}

	function createPropertyTransform(transforms, wire) {

		// Could optimize the single function/string case here
		// by avoiding the when.reduce.  If wire spec parsing perf
		// ever becomes a problem, we can optimize a bit here.

		if(!isArray(transforms)) {
			transforms = [transforms];
		}

		return when.reduce(transforms,
			function(txList, txSpec) {
				var name;

				if(typeof txSpec == 'function') {
					return txSpec;
				}

				// Determine the name of the transform and try
				// to resolve it as a component in the current
				// wire spec
				if(typeof txSpec == 'string') {
					name = txSpec;
				} else {
					for(name in txSpec) {
						if(name != 'inverse') break;
					}
				}

				return when(wire.resolveRef(name),
					function(transform) {
						txList.push(function() {
							var args = slice.call(arguments);
							return transform.apply(undef, args.concat(txSpec[name]));
						});
						return txList;
					}
				);
			}, [])
		.then(
			function(txList) {
				return txList.length > 1 ? compose(txList) : txList[0];
			}
		);
	}

	function setupBinding(bindingSpecs, name, wire) {
		var bindingSpec, binding;

		bindingSpec = mixin({}, bindingSpecs[name]);
		binding = {
			name: name,
			spec: bindingSpec
		};

		return bindingSpec.transform
			? when(createPropertyTransform(bindingSpec.transform, wire),
				function(propertyTransform) {
					binding.spec.transform = propertyTransform;
					return binding;
				})
			: binding;
	}

	function setupBindings(bindingSpecs, wire) {
		var promises = [];

		for(var name in bindingSpecs) {
			if(bindingSpecs.hasOwnProperty(name)) {
				promises.push(setupBinding(bindingSpecs, name, wire));
			}
		}

		return when.reduce(promises, function(bindings, bindingSpec) {
			bindings[bindingSpec.name] = bindingSpec.spec;
			return bindings;
		}, {});
	}

	function cacheBindings(resolver, proxy, wire, pluginOptions) {
		// wire the bindings immediately, in the same context as they
		// are declared.  Since bindings/bind may be in different
		// contexts, deferring the wiring until bind could cause
		// lots of confusion, since they'd be wired in that context,
		// not in the one where they are declared.
		when(wire(proxy.options),
			function(bindings) {

				return when(setupBindings(bindings, wire),
					function(bindings) {
						findCachedBindings(proxy.target,
							function(cachedBindings, i, bindingDef) {
								// Merge any existing bindings
								mergeBindings(bindingDef, bindings);
							},
							function(cachedBindings) {
								// Cache new bindings if none exist for
								// the current target
								var newBindings = {
									target: proxy.target,
									bindings: bindings,
									pluginOptions: pluginOptions
								};
								cachedBindings.push(newBindings);
							}
						);
					}
				);
			}
		).then(resolver.resolve, resolver.reject);
	}

	function removeCachedBindings(resolver, proxy /*, wire */) {
		// If there were any bindings that were never used (via "bind"), we
		// can remove them now since the component is being destroyed.
		findCachedBindings(proxy.target, function(cachedBindings, i) {
			cachedBindings.splice(i, 1);
		});

		resolver.resolve();
	}

	function collectPropertyTransforms(bindings) {
		var name, propertyTransforms, transform;

		propertyTransforms = {};
		for(name in bindings) {
			transform = bindings[name].transform;
			if(transform) {
				propertyTransforms[name] = transform;
			}
		}

		return propertyTransforms;
	}

	function createAdapter(obj, type, options) {
		// FIXME: This is just for initial testing
		var Adapter, adapter;
		Adapter = adapterResolver(obj, type);
		// if (!Adapter) throw new Error('wire/cola: could not find Adapter constructor for ' + type);
		adapter = Adapter ? new Adapter(obj, options) : obj;

		if (options.bindings && type == 'object') {
			adapter = addPropertyTransforms(adapter, collectPropertyTransforms(options.bindings));
		}

		return adapter;
	}

	function doBind(target, datasource, bindings, options, wire) {
		// TODO: create comparator from options (e.g. sortBy: ['prop1', 'prop2'])
		// TODO: create symbolizer from options (e.g. key: ['name', 'version'])
		var adapter1, adapter2, collectionTransform;

		options = mixin({
			querySelector: querySelector
		}, options || {});

		// TODO: ensure these are in the right order so transforms are always in the right order
		adapter1 = createAdapter(datasource, 'collection', options);

		collectionTransform = options.transform;
		if (collectionTransform) {
			if (typeof collectionTransform != 'function') {
				collectionTransform = compose(collectionTransform);
			}
			adapter1 = transformCollection(adapter1, collectionTransform);
		}

		options = mixin({ bindings: bindings }, options);
		adapter2 = createAdapter(target, 'collection', options);

		// FIXME: throw if we can't create an adapter?
		if (!(adapter1 && adapter2)) return;

		return syncCollections(adapter1, adapter2, createAdapter);
	}

	return {
		wire$plugin: function(ready, destroyed, pluginOptions) {

			var unmediators = [];

			// TODO: allow querySelector to be specified in pluginOptions?

			function bindFacet(resolver, proxy, wire) {
				// Find any cached bindings for this component, and if found
				// setup cola data binding.
				findCachedBindings(proxy.target,
					function(cachedBindings, i, bindingDef) {
						// Remove cached bindings
						cachedBindings.splice(i, 1);

						// Wire pluginOptions, then bind to the datasource
						when(wire(proxy.options), function(options) {
							var datasource;

							if(proxy.options.to) {
								datasource = options.to;
							} else {
								datasource = options;
								options = {};
							}

							// TODO: mixin proxy.options onto pluginOptions?
							options = mixin(options, bindingDef.pluginOptions);

							// Use cached bindings to setup cola data binding for
							// the current target component
							var unmediate = doBind(bindingDef.target, datasource, bindingDef.bindings, options);

							unmediators.push(unmediate);

							// TODO: Store cola info in wire$plugin so we can tear the bindings down
							// the component is destroyed?

						}).then(resolver.resolve, resolver.reject);

					},
					function() {
						// No bindings found: "bind" was used without "bindings"
						resolver.reject('bind: no bindings declared for component: ' + proxy.id);

					}
				);
			}

			function destroyMediators() {
				var unmediate, i;
				i = unmediators.length;
				while(unmediate = unmediators[--i]) unmediate();
			}

			function cacheBindingsAndOptions (resolver, proxy, wire) {
				return cacheBindings(resolver, proxy, wire, pluginOptions);
			}

			destroyed.then(destroyMediators);

			return {
				facets: {
					bindings: {
						configure: cacheBindingsAndOptions,
						destroy: removeCachedBindings
					},
					bind: {
						connect: bindFacet
					}
				}
			};
		}
	};
});

})(typeof define == 'function'
	// use define for AMD if available
	? define
	: function(deps, factory) {
		module.exports = factory.apply(this, deps.map(function(x) {
			return require(x);
		}));
	}
);
<commit_msg>Changing cola bind facet to happen in the ready lifecycle step<commit_after>/** @license MIT License (c) copyright B Cavalier & J Hann */

/**
 * wire/cola plugin
 *
 * wire is part of the cujo.js family of libraries (http://cujojs.com/)
 *
 * Licensed under the MIT License at:
 * http://www.opensource.org/licenses/mit-license.php
 */

(function(define) {
define(['when', 'cola/AdapterResolver',
	'cola/ArrayAdapter', 'cola/dom/NodeListAdapter',
	'cola/ResultSetAdapter', 'cola/QueryAdapter', 'cola/mediator/syncCollections',
	'cola/ObjectAdapter', 'cola/dom/NodeAdapter',
	'cola/ResultAdapter', 'cola/mediator/syncProperties',
	'cola/addPropertyTransforms', 'cola/transformCollection', 'cola/transform/compose'],
function(when, adapterResolver,
	ArrayAdapter, NodeListAdapter, ResultSetAdapter, QueryAdapter, syncCollections,
	ObjectAdapter, NodeAdapter,
	ResultAdapter, syncProperties,
	addPropertyTransforms, transformCollection, compose
) {

	var cachedBindings, isArray, undef, slice;

	// TODO: move most of this stuff, including adapter registration to cola.js
	// TODO: implement wire$build that auto-adds these deps to build
	adapterResolver.register(ArrayAdapter, 'collection');
	adapterResolver.register(NodeListAdapter, 'collection');
//	adapterResolver.register(ResultSetAdapter, 'collection');
	adapterResolver.register(QueryAdapter, 'collection');
	adapterResolver.register(NodeAdapter, 'object');
	adapterResolver.register(ObjectAdapter, 'object');
//	adapterResolver.register(ResultAdapter, 'object');

	function querySelector (selector, node) {
		return node.querySelector(selector);
	}

	isArray = Array.isArray || function(it) {
		return Object.prototype.toString.call(it) == '[object Array]';
	};

	slice = Array.prototype.slice;

	/**
	 * "globally" cached bindings.  Cache bindings here so that a bind can find,
	 * process, and remove them later
	 * @private
 	 */
	cachedBindings = [];

	/**
	 * @private
	 * @param target anything - target component for which to find cached bindings
	 * @param found {Function} function to call with existing cached bindings
	 * @param [notFound] {Function} function to call if no cached bindings found
	 */
	function findCachedBindings(target, found, notFound) {
		for(var i = 0, len = cachedBindings.length; i < len; i++) {
			if(cachedBindings[i].target === target) {
				return found(cachedBindings, i, cachedBindings[i]);
			}
		}

		return notFound(cachedBindings);
	}

	function mixin(dst, src) {
		for(var p in src) {
			if(src.hasOwnProperty(p)) {
				dst[p] = src[p];
			}
		}
		return dst;
	}

	function mergeBindings(bindingDef, bindings) {
		mixin(bindingDef.bindings, bindings);
	}

	function createPropertyTransform(transforms, wire) {

		// Could optimize the single function/string case here
		// by avoiding the when.reduce.  If wire spec parsing perf
		// ever becomes a problem, we can optimize a bit here.

		if(!isArray(transforms)) {
			transforms = [transforms];
		}

		return when.reduce(transforms,
			function(txList, txSpec) {
				var name;

				if(typeof txSpec == 'function') {
					return txSpec;
				}

				// Determine the name of the transform and try
				// to resolve it as a component in the current
				// wire spec
				if(typeof txSpec == 'string') {
					name = txSpec;
				} else {
					for(name in txSpec) {
						if(name != 'inverse') break;
					}
				}

				return when(wire.resolveRef(name),
					function(transform) {
						txList.push(function() {
							var args = slice.call(arguments);
							return transform.apply(undef, args.concat(txSpec[name]));
						});
						return txList;
					}
				);
			}, [])
		.then(
			function(txList) {
				return txList.length > 1 ? compose(txList) : txList[0];
			}
		);
	}

	function setupBinding(bindingSpecs, name, wire) {
		var bindingSpec, binding;

		bindingSpec = mixin({}, bindingSpecs[name]);
		binding = {
			name: name,
			spec: bindingSpec
		};

		return bindingSpec.transform
			? when(createPropertyTransform(bindingSpec.transform, wire),
				function(propertyTransform) {
					binding.spec.transform = propertyTransform;
					return binding;
				})
			: binding;
	}

	function setupBindings(bindingSpecs, wire) {
		var promises = [];

		for(var name in bindingSpecs) {
			if(bindingSpecs.hasOwnProperty(name)) {
				promises.push(setupBinding(bindingSpecs, name, wire));
			}
		}

		return when.reduce(promises, function(bindings, bindingSpec) {
			bindings[bindingSpec.name] = bindingSpec.spec;
			return bindings;
		}, {});
	}

	function cacheBindings(resolver, proxy, wire, pluginOptions) {
		// wire the bindings immediately, in the same context as they
		// are declared.  Since bindings/bind may be in different
		// contexts, deferring the wiring until bind could cause
		// lots of confusion, since they'd be wired in that context,
		// not in the one where they are declared.
		when(wire(proxy.options),
			function(bindings) {

				return when(setupBindings(bindings, wire),
					function(bindings) {
						findCachedBindings(proxy.target,
							function(cachedBindings, i, bindingDef) {
								// Merge any existing bindings
								mergeBindings(bindingDef, bindings);
							},
							function(cachedBindings) {
								// Cache new bindings if none exist for
								// the current target
								var newBindings = {
									target: proxy.target,
									bindings: bindings,
									pluginOptions: pluginOptions
								};
								cachedBindings.push(newBindings);
							}
						);
					}
				);
			}
		).then(resolver.resolve, resolver.reject);
	}

	function removeCachedBindings(resolver, proxy /*, wire */) {
		// If there were any bindings that were never used (via "bind"), we
		// can remove them now since the component is being destroyed.
		findCachedBindings(proxy.target, function(cachedBindings, i) {
			cachedBindings.splice(i, 1);
		});

		resolver.resolve();
	}

	function collectPropertyTransforms(bindings) {
		var name, propertyTransforms, transform;

		propertyTransforms = {};
		for(name in bindings) {
			transform = bindings[name].transform;
			if(transform) {
				propertyTransforms[name] = transform;
			}
		}

		return propertyTransforms;
	}

	function createAdapter(obj, type, options) {
		// FIXME: This is just for initial testing
		var Adapter, adapter;
		Adapter = adapterResolver(obj, type);
		// if (!Adapter) throw new Error('wire/cola: could not find Adapter constructor for ' + type);
		adapter = Adapter ? new Adapter(obj, options) : obj;

		if (options.bindings && type == 'object') {
			adapter = addPropertyTransforms(adapter, collectPropertyTransforms(options.bindings));
		}

		return adapter;
	}

	function doBind(target, datasource, bindings, options, wire) {
		// TODO: create comparator from options (e.g. sortBy: ['prop1', 'prop2'])
		// TODO: create symbolizer from options (e.g. key: ['name', 'version'])
		var adapter1, adapter2, collectionTransform;

		options = mixin({
			querySelector: querySelector
		}, options || {});

		// TODO: ensure these are in the right order so transforms are always in the right order
		adapter1 = createAdapter(datasource, 'collection', options);

		collectionTransform = options.transform;
		if (collectionTransform) {
			if (typeof collectionTransform != 'function') {
				collectionTransform = compose(collectionTransform);
			}
			adapter1 = transformCollection(adapter1, collectionTransform);
		}

		options = mixin({ bindings: bindings }, options);
		adapter2 = createAdapter(target, 'collection', options);

		// FIXME: throw if we can't create an adapter?
		if (!(adapter1 && adapter2)) return;

		return syncCollections(adapter1, adapter2, createAdapter);
	}

	return {
		wire$plugin: function(ready, destroyed, pluginOptions) {

			var unmediators = [];

			// TODO: allow querySelector to be specified in pluginOptions?

			function bindFacet(resolver, proxy, wire) {
				// Find any cached bindings for this component, and if found
				// setup cola data binding.
				findCachedBindings(proxy.target,
					function(cachedBindings, i, bindingDef) {
						// Remove cached bindings
						cachedBindings.splice(i, 1);

						// Wire pluginOptions, then bind to the datasource
						when(wire(proxy.options), function(options) {
							var datasource;

							if(proxy.options.to) {
								datasource = options.to;
							} else {
								datasource = options;
								options = {};
							}

							// TODO: mixin proxy.options onto pluginOptions?
							options = mixin(options, bindingDef.pluginOptions);

							// Use cached bindings to setup cola data binding for
							// the current target component
							var unmediate = doBind(bindingDef.target, datasource, bindingDef.bindings, options);

							unmediators.push(unmediate);

							// TODO: Store cola info in wire$plugin so we can tear the bindings down
							// the component is destroyed?

						}).then(resolver.resolve, resolver.reject);

					},
					function() {
						// No bindings found: "bind" was used without "bindings"
						resolver.reject('bind: no bindings declared for component: ' + proxy.id);

					}
				);
			}

			function destroyMediators() {
				var unmediate, i;
				i = unmediators.length;
				while(unmediate = unmediators[--i]) unmediate();
			}

			function cacheBindingsAndOptions (resolver, proxy, wire) {
				return cacheBindings(resolver, proxy, wire, pluginOptions);
			}

			destroyed.then(destroyMediators);

			return {
				facets: {
					bindings: {
						configure: cacheBindingsAndOptions,
						destroy: removeCachedBindings
					},
					bind: {
						ready: bindFacet
					}
				}
			};
		}
	};
});

})(typeof define == 'function'
	// use define for AMD if available
	? define
	: function(deps, factory) {
		module.exports = factory.apply(this, deps.map(function(x) {
			return require(x);
		}));
	}
);
<|endoftext|>


<commit_before>module.exports = {
    iterations: 1,
    learningRate: 0.1,
    loggingStep: 1,
    excludedChars: ["9", "h", "i", "j", "1", "l", "0", "q", "k", "o", "r", "s", "t", "u", "v", "z"],
    paths: {
        database: "./db/db.json",
        generateTo: "./gen/"
    }
}<commit_msg>Improved load/save<commit_after>module.exports = {
    iterations: 5,
    learningRate: 0.1,
    loggingStep: 1,
    excludedChars: ["9", "h", "i", "j", "1", "l", "0", "q", "k", "o", "r", "s", "t", "u", "v", "z"],
    paths: {
        database: "./db/db.json",
        generateTo: "./gen/"
    }
}<|endoftext|>


<commit_before>'use strict';

module.exports = {
  http: {
    routes: {
      public: {
        'get /video/*': 'app/server/controllers/VideoController.displayVideoAction',
        'get /getVideo/:id': 'app/server/controllers/VideoController.getVideoReadyAction'
      },
      private: {
        'get /videos/:id': 'app/server/controllers/VideoController.getEntityAction',
        'get /videos': 'app/server/controllers/VideoController.getEntitiesAction',
        'post /videos/:id': 'app/server/controllers/VideoController.updateEntityAction',
        'delete /videos/:id': 'app/server/controllers/VideoController.removeEntityAction',
        'post /addMedia': 'app/server/controllers/VideoController.addEntityAction',
        'post /retryVideo/:ids': 'app/server/controllers/VideoController.retryVideosAction',
        'post /startUpload/:ids/:platform': 'app/server/controllers/VideoController.startUploadAction',
        'post /publishVideo/:ids': 'app/server/controllers/VideoController.publishVideosAction',
        'post /unpublishVideo/:ids': 'app/server/controllers/VideoController.unpublishVideosAction',
        'get /getPlatforms': 'app/server/controllers/VideoController.getPlatformsAction',
        'get /configuration/all': 'app/server/controllers/ConfigurationController.getConfigurationAllAction',
        'get /configuration/googleOAuthAssociation':
        'app/server/controllers/ConfigurationController.handleGoogleOAuthCodeAction',
        'post /configuration/upload': 'app/server/controllers/ConfigurationController.saveUploadConfiguration',
        'post /updateVideoTags/:id': 'app/server/controllers/VideoController.updateTagsAction',
        'post /removeVideoTags/:id': 'app/server/controllers/VideoController.removeTagsAction'
      },
      ws: {
        'get /propertiesTypes': 'app/server/controllers/PropertyController.getPropertyTypesAction',
        'post /statistics/:entity/:type/:id': 'app/server/controllers/StatisticsController.statisticsAction',
        'get /videos': 'app/server/controllers/VideoController.getEntitiesAction',
        'post /videos': 'app/server/controllers/VideoController.updateEntityAction',
        'delete /videos': 'app/server/controllers/VideoController.removeEntityAction'
      }
    }
  },
  entities: {
    properties: 'app/server/controllers/PropertyController'
  },
  webServiceScopes: [
    {
      id: 'publish-statistics',
      name: 'PUBLISH.WS_SCOPES.INCREASE_VIEW_NAME',
      description: 'PUBLISH.WS_SCOPES.INCREASE_VIEW_DESCRIPTION',
      paths: [
        'post /publish/statistics*'
      ]
    },
    {
      id: 'publish-get-videos',
      name: 'PUBLISH.WS_SCOPES.GET_VIDEOS_NAME',
      description: 'PUBLISH.WS_SCOPES.GET_VIDEOS_DESCRIPTION',
      paths: [
        'get /publish/videos*'
      ]
    },
    {
      id: 'publish-update-videos',
      name: 'PUBLISH.WS_SCOPES.UPDATE_VIDEOS_NAME',
      description: 'PUBLISH.WS_SCOPES.UPDATE_VIDEOS_DESCRIPTION',
      paths: [
        'post /publish/videos*'
      ]
    },
    {
      id: 'publish-delete-videos',
      name: 'PUBLISH.WS_SCOPES.DELETE_VIDEOS_NAME',
      description: 'PUBLISH.WS_SCOPES.DELETE_VIDEOS_DESCRIPTION',
      paths: [
        'delete /publish/videos*'
      ]
    }
  ],
  permissions: [
    {
      label: 'PUBLISH.PERMISSIONS.GROUP_PROPERTIES',
      permissions: [
        {
          id: 'publish-access-properties-page',
          name: 'PUBLISH.PERMISSIONS.ACCESS_PROPERTIES_PAGE_NAME'
        }
      ]
    },
    {
      label: 'PUBLISH.PERMISSIONS.GROUP_CONFIGURATION',
      permissions: [
        {
          id: 'publish-access-conf-page',
          name: 'PUBLISH.PERMISSIONS.ACCESS_PUBLISH_CONF_PAGE_NAME',
          paths: [
            'get /publish/configuration/all',
            'post /publish/configuration/upload'
          ]
        },
        {
          id: 'publish-manage-publish-config',
          name: 'PUBLISH.PERMISSIONS.MANAGE_PUBLISH_CONF_NAME',
          description: 'PUBLISH.PERMISSIONS.MANAGE_PUBLISH_CONF_DESCRIPTION',
          paths: [
            'get /publish/configuration/all'
          ]
        }
      ]
    },
    {
      label: 'PUBLISH.PERMISSIONS.GROUP_CATEGORIES',
      permissions: [
        {
          id: 'publish-access-categories-page',
          name: 'PUBLISH.PERMISSIONS.ACCESS_CATEGORIES_PAGE_NAME'
        }
      ]
    },
    {
      label: 'PUBLISH.PERMISSIONS.GROUP_VIDEOS',
      permissions: [
        {
          id: 'publish-access-videos-page',
          name: 'PUBLISH.PERMISSIONS.ACCESS_VIDEOS_PAGE_NAME'
        },
        {
          id: 'publish-add-videos',
          name: 'PUBLISH.PERMISSIONS.ADD_VIDEOS_NAME',
          description: 'PUBLISH.PERMISSIONS.ADD_VIDEOS_DESCRIPTION',
          paths: ['post /publish/addMedia*']
        },
        {
          id: 'publish-update-videos',
          name: 'PUBLISH.PERMISSIONS.UPDATE_VIDEOS_NAME',
          description: 'PUBLISH.PERMISSIONS.UPDATE_VIDEOS_DESCRIPTION',
          paths: ['post /publish/videos*']
        },
        {
          id: 'publish-delete-videos',
          name: 'PUBLISH.PERMISSIONS.DELETE_VIDEOS_NAME',
          description: 'PUBLISH.PERMISSIONS.DELETE_VIDEOS_DESCRIPTION',
          paths: ['delete /publish/videos*']
        },
        {
          id: 'publish-publish-videos',
          name: 'PUBLISH.PERMISSIONS.PUBLISH_VIDEO_NAME',
          description: 'PUBLISH.PERMISSIONS.PUBLISH_VIDEO_DESCRIPTION',
          paths: [
            'get /publish/publishVideo*',
            'get /publish/unpublishVideo*'
          ]
        },
        {
          id: 'publish-chapter-videos',
          name: 'PUBLISH.PERMISSIONS.EDIT_CHAPTER_NAME',
          description: 'PUBLISH.PERMISSIONS.EDIT_CHAPTER_DESCRIPTION',
          paths: [
            'post /publish/updateVideoTags*',
            'post /publish/removeVideoTags*'
          ]
        },
        {
          id: 'publish-retry-videos',
          name: 'PUBLISH.PERMISSIONS.RETRY_VIDEO_NAME',
          description: 'PUBLISH.PERMISSIONS.RETRY_VIDEO_DESCRIPTION'
        },
        {
          id: 'publish-upload-videos',
          name: 'PUBLISH.PERMISSIONS.UPLOAD_VIDEO_NAME',
          description: 'PUBLISH.PERMISSIONS.UPLOAD_VIDEO_DESCRIPTION'
        }
      ]
    }
  ],
  backOffice: {
    menu: [
      {
        weight: -100,
        label: 'PUBLISH.MENU.PUBLISH',
        subMenu: [
          {
            label: 'PUBLISH.MENU.VIDEOS',
            path: 'publish/medias-list',
            permission: 'publish-access-videos-page'
          },
          {
            label: 'PUBLISH.MENU.CATEGORIES',
            path: 'publish/categories-list',
            permission: 'publish-access-categories-page'
          },
          {
            label: 'PUBLISH.MENU.PROPERTIES',
            path: 'publish/properties-list',
            permission: 'publish-access-properties-page'
          },
          {
            label: 'PUBLISH.MENU.CONFIGURATION',
            path: 'publish/configuration',
            permission: 'publish-access-conf-page'
          }
        ]
      }
    ],
    scriptLibFiles: {
      base: [
      ],
      dev: [
        '/publish/multirange/multirange.js',
        '/publish/timePolyfill/time-polyfill.js'
      ],
      prod: [
        '/publish/be/js/libOpenveoPublish.js'
      ]
    },
    scriptFiles: {
      base: [
        '/publish/lib/video.js/dist/video.min.js',
        '/publish/lib/dashjs/dist/dash.all.min.js',
        '/publish/lib/videojs-contrib-dash/index.js',
        '/publish/lib/videojs-contrib-hls/index.js',
        '/publish/lib/openveo-player/dist/openveo-player.min.js'
      ],
      dev: [
        '/publish/ovPub/PublishApp.js',
        '/publish/ovPub/MediaController.js',
        '/publish/ovPub/PropertiesController.js',
        '/publish/ovPub/CategoriesController.js',
        '/publish/ovPub/ChapterController.js',
        '/publish/ovPub/ConfigurationController.js',
        '/publish/ovPub/PublishService.js'
      ],
      prod: [
        '/publish/be/js/openveoPublish.js'
      ]
    },
    cssFiles: [
      '/publish/be/css/publish.css',
      '/publish/lib/openveo-player/dist/openveo-player.css',
      '/publish/lib/video.js/dist/video-js.min.css'
    ]
  },
  custom: {
    scriptFiles: {
      base: [
        '/publish/lib/angular/angular.min.js',
        '/publish/lib/angular-animate/angular-animate.min.js',
        '/publish/lib/angular-cookies/angular-cookies.min.js',
        '/publish/lib/openveo-player/dist/openveo-player.min.js',
        '/publish/lib/video.js/dist/video.min.js',
        '/publish/lib/dashjs/dist/dash.all.min.js',
        '/publish/lib/videojs-contrib-dash/index.js',
        '/publish/lib/videojs-contrib-hls/index.js'
      ],
      publishPlayer: {
        dev: [
          '/publish/PublishPlayerApp.js',
          '/publish/MediaService.js',
          '/publish/PlayerController.js'
        ],
        prod: [
          '/publish/player/js/openveoPublishPlayer.js'
        ]
      }
    },
    cssFiles: [
      '/publish/be/css/player_page.css',
      '/publish/lib/openveo-player/dist/openveo-player.css',
      '/publish/lib/video.js/dist/video-js.min.css'
    ]
  },
  viewsFolders: [
    'app/client/front/views'
  ],
  imageProcessing: {
    imagesFolders: ['assets/player/videos'],
    imagesStyle: {
      small: 200
    }
  }
};
<commit_msg>Fix path of videos<commit_after>'use strict';

module.exports = {
  http: {
    routes: {
      public: {
        'get /video/*': 'app/server/controllers/VideoController.displayVideoAction',
        'get /getVideo/:id': 'app/server/controllers/VideoController.getVideoReadyAction'
      },
      private: {
        'get /videos/:id': 'app/server/controllers/VideoController.getEntityAction',
        'get /videos*': 'app/server/controllers/VideoController.getEntitiesAction',
        'post /videos/:id': 'app/server/controllers/VideoController.updateEntityAction',
        'delete /videos/:id': 'app/server/controllers/VideoController.removeEntityAction',
        'post /addMedia': 'app/server/controllers/VideoController.addEntityAction',
        'post /retryVideo/:ids': 'app/server/controllers/VideoController.retryVideosAction',
        'post /startUpload/:ids/:platform': 'app/server/controllers/VideoController.startUploadAction',
        'post /publishVideo/:ids': 'app/server/controllers/VideoController.publishVideosAction',
        'post /unpublishVideo/:ids': 'app/server/controllers/VideoController.unpublishVideosAction',
        'get /getPlatforms': 'app/server/controllers/VideoController.getPlatformsAction',
        'get /configuration/all': 'app/server/controllers/ConfigurationController.getConfigurationAllAction',
        'get /configuration/googleOAuthAssociation':
        'app/server/controllers/ConfigurationController.handleGoogleOAuthCodeAction',
        'post /configuration/upload': 'app/server/controllers/ConfigurationController.saveUploadConfiguration',
        'post /updateVideoTags/:id': 'app/server/controllers/VideoController.updateTagsAction',
        'post /removeVideoTags/:id': 'app/server/controllers/VideoController.removeTagsAction'
      },
      ws: {
        'get /propertiesTypes': 'app/server/controllers/PropertyController.getPropertyTypesAction',
        'post /statistics/:entity/:type/:id': 'app/server/controllers/StatisticsController.statisticsAction',
        'get /videos/:id': 'app/server/controllers/VideoController.getEntityAction',
        'get /videos*': 'app/server/controllers/VideoController.getEntitiesAction',
        'post /videos/:id': 'app/server/controllers/VideoController.updateEntityAction',
        'delete /videos/:id': 'app/server/controllers/VideoController.removeEntityAction'
      }
    }
  },
  entities: {
    properties: 'app/server/controllers/PropertyController'
  },
  webServiceScopes: [
    {
      id: 'publish-statistics',
      name: 'PUBLISH.WS_SCOPES.INCREASE_VIEW_NAME',
      description: 'PUBLISH.WS_SCOPES.INCREASE_VIEW_DESCRIPTION',
      paths: [
        'post /publish/statistics*'
      ]
    },
    {
      id: 'publish-get-videos',
      name: 'PUBLISH.WS_SCOPES.GET_VIDEOS_NAME',
      description: 'PUBLISH.WS_SCOPES.GET_VIDEOS_DESCRIPTION',
      paths: [
        'get /publish/videos*'
      ]
    },
    {
      id: 'publish-update-videos',
      name: 'PUBLISH.WS_SCOPES.UPDATE_VIDEOS_NAME',
      description: 'PUBLISH.WS_SCOPES.UPDATE_VIDEOS_DESCRIPTION',
      paths: [
        'post /publish/videos*'
      ]
    },
    {
      id: 'publish-delete-videos',
      name: 'PUBLISH.WS_SCOPES.DELETE_VIDEOS_NAME',
      description: 'PUBLISH.WS_SCOPES.DELETE_VIDEOS_DESCRIPTION',
      paths: [
        'delete /publish/videos*'
      ]
    }
  ],
  permissions: [
    {
      label: 'PUBLISH.PERMISSIONS.GROUP_PROPERTIES',
      permissions: [
        {
          id: 'publish-access-properties-page',
          name: 'PUBLISH.PERMISSIONS.ACCESS_PROPERTIES_PAGE_NAME'
        }
      ]
    },
    {
      label: 'PUBLISH.PERMISSIONS.GROUP_CONFIGURATION',
      permissions: [
        {
          id: 'publish-access-conf-page',
          name: 'PUBLISH.PERMISSIONS.ACCESS_PUBLISH_CONF_PAGE_NAME',
          paths: [
            'get /publish/configuration/all',
            'post /publish/configuration/upload'
          ]
        },
        {
          id: 'publish-manage-publish-config',
          name: 'PUBLISH.PERMISSIONS.MANAGE_PUBLISH_CONF_NAME',
          description: 'PUBLISH.PERMISSIONS.MANAGE_PUBLISH_CONF_DESCRIPTION',
          paths: [
            'get /publish/configuration/all'
          ]
        }
      ]
    },
    {
      label: 'PUBLISH.PERMISSIONS.GROUP_CATEGORIES',
      permissions: [
        {
          id: 'publish-access-categories-page',
          name: 'PUBLISH.PERMISSIONS.ACCESS_CATEGORIES_PAGE_NAME'
        }
      ]
    },
    {
      label: 'PUBLISH.PERMISSIONS.GROUP_VIDEOS',
      permissions: [
        {
          id: 'publish-access-videos-page',
          name: 'PUBLISH.PERMISSIONS.ACCESS_VIDEOS_PAGE_NAME'
        },
        {
          id: 'publish-add-videos',
          name: 'PUBLISH.PERMISSIONS.ADD_VIDEOS_NAME',
          description: 'PUBLISH.PERMISSIONS.ADD_VIDEOS_DESCRIPTION',
          paths: ['post /publish/addMedia*']
        },
        {
          id: 'publish-update-videos',
          name: 'PUBLISH.PERMISSIONS.UPDATE_VIDEOS_NAME',
          description: 'PUBLISH.PERMISSIONS.UPDATE_VIDEOS_DESCRIPTION',
          paths: ['post /publish/videos*']
        },
        {
          id: 'publish-delete-videos',
          name: 'PUBLISH.PERMISSIONS.DELETE_VIDEOS_NAME',
          description: 'PUBLISH.PERMISSIONS.DELETE_VIDEOS_DESCRIPTION',
          paths: ['delete /publish/videos*']
        },
        {
          id: 'publish-publish-videos',
          name: 'PUBLISH.PERMISSIONS.PUBLISH_VIDEO_NAME',
          description: 'PUBLISH.PERMISSIONS.PUBLISH_VIDEO_DESCRIPTION',
          paths: [
            'get /publish/publishVideo*',
            'get /publish/unpublishVideo*'
          ]
        },
        {
          id: 'publish-chapter-videos',
          name: 'PUBLISH.PERMISSIONS.EDIT_CHAPTER_NAME',
          description: 'PUBLISH.PERMISSIONS.EDIT_CHAPTER_DESCRIPTION',
          paths: [
            'post /publish/updateVideoTags*',
            'post /publish/removeVideoTags*'
          ]
        },
        {
          id: 'publish-retry-videos',
          name: 'PUBLISH.PERMISSIONS.RETRY_VIDEO_NAME',
          description: 'PUBLISH.PERMISSIONS.RETRY_VIDEO_DESCRIPTION'
        },
        {
          id: 'publish-upload-videos',
          name: 'PUBLISH.PERMISSIONS.UPLOAD_VIDEO_NAME',
          description: 'PUBLISH.PERMISSIONS.UPLOAD_VIDEO_DESCRIPTION'
        }
      ]
    }
  ],
  backOffice: {
    menu: [
      {
        weight: -100,
        label: 'PUBLISH.MENU.PUBLISH',
        subMenu: [
          {
            label: 'PUBLISH.MENU.VIDEOS',
            path: 'publish/medias-list',
            permission: 'publish-access-videos-page'
          },
          {
            label: 'PUBLISH.MENU.CATEGORIES',
            path: 'publish/categories-list',
            permission: 'publish-access-categories-page'
          },
          {
            label: 'PUBLISH.MENU.PROPERTIES',
            path: 'publish/properties-list',
            permission: 'publish-access-properties-page'
          },
          {
            label: 'PUBLISH.MENU.CONFIGURATION',
            path: 'publish/configuration',
            permission: 'publish-access-conf-page'
          }
        ]
      }
    ],
    scriptLibFiles: {
      base: [
      ],
      dev: [
        '/publish/multirange/multirange.js',
        '/publish/timePolyfill/time-polyfill.js'
      ],
      prod: [
        '/publish/be/js/libOpenveoPublish.js'
      ]
    },
    scriptFiles: {
      base: [
        '/publish/lib/video.js/dist/video.min.js',
        '/publish/lib/dashjs/dist/dash.all.min.js',
        '/publish/lib/videojs-contrib-dash/index.js',
        '/publish/lib/videojs-contrib-hls/index.js',
        '/publish/lib/openveo-player/dist/openveo-player.min.js'
      ],
      dev: [
        '/publish/ovPub/PublishApp.js',
        '/publish/ovPub/MediaController.js',
        '/publish/ovPub/PropertiesController.js',
        '/publish/ovPub/CategoriesController.js',
        '/publish/ovPub/ChapterController.js',
        '/publish/ovPub/ConfigurationController.js',
        '/publish/ovPub/PublishService.js'
      ],
      prod: [
        '/publish/be/js/openveoPublish.js'
      ]
    },
    cssFiles: [
      '/publish/be/css/publish.css',
      '/publish/lib/openveo-player/dist/openveo-player.css',
      '/publish/lib/video.js/dist/video-js.min.css'
    ]
  },
  custom: {
    scriptFiles: {
      base: [
        '/publish/lib/angular/angular.min.js',
        '/publish/lib/angular-animate/angular-animate.min.js',
        '/publish/lib/angular-cookies/angular-cookies.min.js',
        '/publish/lib/openveo-player/dist/openveo-player.min.js',
        '/publish/lib/video.js/dist/video.min.js',
        '/publish/lib/dashjs/dist/dash.all.min.js',
        '/publish/lib/videojs-contrib-dash/index.js',
        '/publish/lib/videojs-contrib-hls/index.js'
      ],
      publishPlayer: {
        dev: [
          '/publish/PublishPlayerApp.js',
          '/publish/MediaService.js',
          '/publish/PlayerController.js'
        ],
        prod: [
          '/publish/player/js/openveoPublishPlayer.js'
        ]
      }
    },
    cssFiles: [
      '/publish/be/css/player_page.css',
      '/publish/lib/openveo-player/dist/openveo-player.css',
      '/publish/lib/video.js/dist/video-js.min.css'
    ]
  },
  viewsFolders: [
    'app/client/front/views'
  ],
  imageProcessing: {
    imagesFolders: ['assets/player/videos'],
    imagesStyle: {
      small: 200
    }
  }
};
<|endoftext|>


<commit_before>exports.conf = {
  nick: 'treslek',
  host: 'irc.freenode.net',
  ircOptions: {
    port: 6667,
    channels: ['##bullpeen'],
    userName: 'treslek',
    realName: 'treslek',
    autoConnect: 'false'
  },
  ignored: ['doslek'],
  redis: {
    host: 'localhost',
    port: '6379',
    prefix: 'treslek'
  },
  admins: ['jirwin'],
  plugins_dir: "/home/jirwin/projects/treslek/plugins/"
}
<commit_msg>Flood protection.<commit_after>exports.conf = {
  nick: 'treslek',
  host: 'irc.freenode.net',
  ircOptions: {
    port: 6667,
    channels: ['##bullpeen'],
    userName: 'treslek',
    realName: 'treslek',
    autoConnect: false,
    floodProtection: true,
    floodProtectionDelay: 500
  },
  ignored: ['doslek'],
  redis: {
    host: 'localhost',
    port: '6379',
    prefix: 'treslek'
  },
  admins: ['jirwin'],
  plugins_dir: "/home/jirwin/projects/treslek/plugins/"
}
<|endoftext|>


<commit_before>import { max } from 'd3-array';

export default (data, memberOf) => {
  if (data.length <= 14) return data;

  let yourPlace = -1;

  for ( var i = 0, len = data.length; i < len; i++ ) {
    if (data[i].id === memberOf) {
      yourPlace = i;
      break;
    }
  }

  if (yourPlace === -1) {
    return [];
  }

  const getEmpty = value => {
    return {
      id: `empty${value}`,
      value: null,
      sortValue: value,
      label: `empty${value}`
    };
  };

  // If you are top 5 (no placeholder above)
  if (yourPlace <= 5) {
    return [
      ...data.slice(0, yourPlace + 3),
      getEmpty(data[yourPlace + 3].value),
      ...data.slice(data.length - (14 - yourPlace - 4))
    ];
  // If you are last to 4rd last (no placeholder below)
  } else if (yourPlace > data.length - 5) {
    return [
      ...data.slice(0, 14 - (1 + data.length - yourPlace + 2)),
      getEmpty(data[yourPlace - 3].value),
      ...data.slice(yourPlace - 2, data.length)
    ];
  //Placeholder above and below
  } else {
    const toAdd = 14 - 5 - 2;
    return [
      ...data.slice(0, Math.ceil(toAdd / 2)),
      getEmpty(data[yourPlace - 3].value),
      ...data.slice(yourPlace - 2, yourPlace + 3),
      getEmpty(yourPlace + 3),
      ...data.slice(data.length - Math.floor(toAdd / 2))
    ];
  }
  return data.filter(d => d);
};
<commit_msg>Fixed graph top 10<commit_after>import { max } from 'd3-array';

export default (data, memberOf) => {
  if (data.length <= 14) return data;

  let yourPlace = -1;

  for ( var i = 0, len = data.length; i < len; i++ ) {
    if (data[i].id === memberOf) {
      yourPlace = i;
      break;
    }
  }

  if (yourPlace === -1) {
    return [];
  }

  const getEmpty = value => {
    return {
      id: `empty${value}`,
      value: null,
      sortValue: value,
      label: `empty${value}`
    };
  };

  // If you are top 5 (no placeholder above)
  if (yourPlace <= 5) {
    return [
      ...data.slice(0, 10)
      /*getEmpty(data[yourPlace + 3].value),
      ...data.slice(data.length - (14 - yourPlace - 4))*/
    ];
  // If you are last to 4rd last (no placeholder below)
  } else if (yourPlace > data.length - 5) {
    return [
      ...data.slice(0, 14 - (1 + data.length - yourPlace + 2)),
      getEmpty(data[yourPlace - 3].value),
      ...data.slice(yourPlace - 2, data.length)
    ];
  //Placeholder above and below
  } else {
    const toAdd = 14 - 5 - 2;
    return [
      ...data.slice(0, Math.ceil(toAdd / 2)),
      getEmpty(data[yourPlace - 3].value),
      ...data.slice(yourPlace - 2, yourPlace + 3),
      getEmpty(yourPlace + 3),
      ...data.slice(data.length - Math.floor(toAdd / 2))
    ];
  }
  return data.filter(d => d);
};
<|endoftext|>


<commit_before>const ClassLoader = require('./ClassLoader');

let ClassNotFoundException = undefined;
const FunctionPrototype = new Function();

/**
 * @memberOf Jymfony.Component.Autoloader
 */
class Namespace {
    /**
     * Constructor.
     *
     * @param {Jymfony.Component.Autoloader.Autoloader} autoloader
     * @param {string} fqn
     * @param {string[]|string} baseDirs
     * @param {Function} req
     *
     * @returns {Proxy} The namespace object
     */
    constructor(autoloader, fqn, baseDirs = [], req = require) {
        this._autoloader = autoloader;

        /**
         * @type {require|Function}
         * @private
         */
        this._internalRequire = req;

        this._fullyQualifiedName = fqn;
        if (undefined === ClassNotFoundException) {
            ClassNotFoundException = this._internalRequire('./Exception/ClassNotFoundException.js');
        }

        this._classLoader = new ClassLoader(autoloader.finder, this._internalRequire('path'), this._internalRequire('vm'));

        this._target = {
            __namespace: this,
        };

        this._baseDirs = new Set();
        if ('string' === typeof baseDirs) {
            baseDirs = [ baseDirs ];
        }

        for (const dir of baseDirs) {
            this.addDirectory(dir);
        }

        return new Proxy(this._target, {
            get: (target, name) => {
                return this._get(target, name);
            },
        });
    }

    /**
     * Add a base directory to search classes in
     *
     * @param {string} directory
     *
     * @returns {Jymfony.Component.Autoloader.Namespace}
     */
    addDirectory(directory) {
        this._baseDirs.add(directory);
        return this;
    }

    /**
     * Get the namespace FQN
     *
     * @returns {string}
     */
    get name() {
        return this._fullyQualifiedName;
    }

    /**
     * Gets the namespace base directories.
     *
     * @returns {string[]}
     */
    get directories() {
        return [ ...this._baseDirs ];
    }

    /**
     * Autoload/get a class or namespace
     *
     * @param {object} target
     * @param {string} name
     *
     * @returns {*}
     *
     * @private
     */
    _get(target, name) {
        if ('string' !== typeof name) {
            return undefined;
        }

        if ('__construct' === name) {
            return undefined;
        }

        if (undefined === target[name]) {
            let found;
            try {
                found = this._find(name);
            } catch (e) {
                if (! (e instanceof ClassNotFoundException) || this._autoloader.debug) {
                    throw e;
                }

                return undefined;
            }

            target[name] = found;
        }

        return target[name];
    }

    /**
     * Searches in all registered base dirs for
     * class/namespace and returns it if found
     *
     * @param {string} name
     *
     * @returns {*}
     *
     * @private
     */
    _find(name) {
        let stat;
        const finder = this._autoloader.finder;
        for (const dir of this._baseDirs) {
            stat = finder.find(dir, name);
            if (stat !== undefined) {
                break;
            }
        }

        if (! stat) {
            throw new ClassNotFoundException(`Cannot resolve "${this.name}.${name}". File or directory cannot be found`);
        }

        if (stat.directory) {
            return new Namespace(this._autoloader, this.name + '.' + name, stat.filename);
        }

        return this._require(stat.filename);
    }

    /**
     * @param {string} filename
     *
     * @returns {Function}
     *
     * @private
     */
    _require(filename) {
        const fn = this._internalRequire.resolve(filename);
        let realTarget = undefined, self = undefined;

        const init = () => {
            if (undefined !== realTarget) {
                return;
            }

            let mod;
            if (fn !== __filename) {
                mod = this._classLoader.load(fn, self);
            } else {
                mod = this._internalRequire(fn);
            }

            // Class constructor
            if ('function' !== typeof mod) {
                throw new ClassNotFoundException(`Class not found in ${fn}. The file was found, but the class isn't there.`);
            }

            realTarget = mod;

            const name = mod.definition ? mod.definition.name : mod.name;
            const meta = {
                filename: fn,
                fqcn: this._fullyQualifiedName + '.' + name,
                module: this._internalRequire.cache[fn],
                constructor: mod,
                namespace: this,
                isModule: (val) => {
                    return self === val || mod === val || mod.definition === val;
                },
            };

            if (! mod.hasOwnProperty('arguments')) {
                Object.defineProperty(mod, 'arguments', {value: null, writable: false, enumerable: false, configurable: false});
            }

            if (! mod.hasOwnProperty('caller')) {
                Object.defineProperty(mod, 'caller', {value: null, writable: false, enumerable: false, configurable: false});
            }

            Object.defineProperty(mod, Symbol.reflection, {
                enumerable: false,
                writable: false,
                configurable: false,
                value: meta,
            });

            if (mod.definition) {
                // Interface or Trait
                Object.defineProperty(mod.definition, Symbol.reflection, {
                    enumerable: false,
                    writable: false,
                    configurable: false,
                    value: meta,
                });
            }
        };

        const handlers = {
            get: (target, key) => {
                init();
                return Reflect.get(realTarget, key);
            },
            set: (target, key, value) => {
                init();
                return Reflect.set(realTarget, key, value);
            },
            has: (target, key) => {
                init();
                return Reflect.has(realTarget, key);
            },
            deleteProperty: (target, key) => {
                init();
                return Reflect.deleteProperty(realTarget, key);
            },
            defineProperty: (target, key, descriptor) => {
                init();
                return Reflect.defineProperty(realTarget, key, descriptor);
            },
            enumerate: () => {
                init();
                return Reflect.enumerate(realTarget);
            },
            ownKeys: () => {
                init();
                return Reflect.ownKeys(realTarget);
            },
            apply: (target, thisArgument, args) => {
                init();
                return Reflect.apply(realTarget, thisArgument, args);
            },
            construct: (target, argumentsList, newTarget) => {
                init();
                return Reflect.construct(realTarget, argumentsList, newTarget);
            },
            getPrototypeOf: () => {
                init();
                return Reflect.getPrototypeOf(realTarget);
            },
            setPrototypeOf: (target, proto) => {
                init();
                return Reflect.setPrototypeOf(realTarget, proto);
            },
            isExtensible: () => {
                init();
                return Reflect.isExtensible(realTarget);
            },
            preventExtensions: () => {
                init();
                return Reflect.preventExtensions(realTarget);
            },
            getOwnPropertyDescriptor: (target, key) => {
                init();
                return Reflect.getOwnPropertyDescriptor(realTarget, key);
            },
        };

        return self = new Proxy(FunctionPrototype, handlers);
    }
}

module.exports = Namespace;
<commit_msg>[Autoloader] do not report non-enumerable and not configurable key Symbol.reflection on ownKeys trap<commit_after>const ClassLoader = require('./ClassLoader');

let ClassNotFoundException = undefined;
const FunctionPrototype = new Function();

/**
 * @memberOf Jymfony.Component.Autoloader
 */
class Namespace {
    /**
     * Constructor.
     *
     * @param {Jymfony.Component.Autoloader.Autoloader} autoloader
     * @param {string} fqn
     * @param {string[]|string} baseDirs
     * @param {Function} req
     *
     * @returns {Proxy} The namespace object
     */
    constructor(autoloader, fqn, baseDirs = [], req = require) {
        this._autoloader = autoloader;

        /**
         * @type {require|Function}
         * @private
         */
        this._internalRequire = req;

        this._fullyQualifiedName = fqn;
        if (undefined === ClassNotFoundException) {
            ClassNotFoundException = this._internalRequire('./Exception/ClassNotFoundException.js');
        }

        this._classLoader = new ClassLoader(autoloader.finder, this._internalRequire('path'), this._internalRequire('vm'));

        this._target = {
            __namespace: this,
        };

        this._baseDirs = new Set();
        if ('string' === typeof baseDirs) {
            baseDirs = [ baseDirs ];
        }

        for (const dir of baseDirs) {
            this.addDirectory(dir);
        }

        return new Proxy(this._target, {
            get: (target, name) => {
                return this._get(target, name);
            },
        });
    }

    /**
     * Add a base directory to search classes in
     *
     * @param {string} directory
     *
     * @returns {Jymfony.Component.Autoloader.Namespace}
     */
    addDirectory(directory) {
        this._baseDirs.add(directory);
        return this;
    }

    /**
     * Get the namespace FQN
     *
     * @returns {string}
     */
    get name() {
        return this._fullyQualifiedName;
    }

    /**
     * Gets the namespace base directories.
     *
     * @returns {string[]}
     */
    get directories() {
        return [ ...this._baseDirs ];
    }

    /**
     * Autoload/get a class or namespace
     *
     * @param {object} target
     * @param {string} name
     *
     * @returns {*}
     *
     * @private
     */
    _get(target, name) {
        if ('string' !== typeof name) {
            return undefined;
        }

        if ('__construct' === name) {
            return undefined;
        }

        if (undefined === target[name]) {
            let found;
            try {
                found = this._find(name);
            } catch (e) {
                if (! (e instanceof ClassNotFoundException) || this._autoloader.debug) {
                    throw e;
                }

                return undefined;
            }

            target[name] = found;
        }

        return target[name];
    }

    /**
     * Searches in all registered base dirs for
     * class/namespace and returns it if found
     *
     * @param {string} name
     *
     * @returns {*}
     *
     * @private
     */
    _find(name) {
        let stat;
        const finder = this._autoloader.finder;
        for (const dir of this._baseDirs) {
            stat = finder.find(dir, name);
            if (stat !== undefined) {
                break;
            }
        }

        if (! stat) {
            throw new ClassNotFoundException(`Cannot resolve "${this.name}.${name}". File or directory cannot be found`);
        }

        if (stat.directory) {
            return new Namespace(this._autoloader, this.name + '.' + name, stat.filename);
        }

        return this._require(stat.filename);
    }

    /**
     * @param {string} filename
     *
     * @returns {Function}
     *
     * @private
     */
    _require(filename) {
        const fn = this._internalRequire.resolve(filename);
        let realTarget = undefined, self = undefined;

        const init = () => {
            if (undefined !== realTarget) {
                return;
            }

            let mod;
            if (fn !== __filename) {
                mod = this._classLoader.load(fn, self);
            } else {
                mod = this._internalRequire(fn);
            }

            // Class constructor
            if ('function' !== typeof mod) {
                throw new ClassNotFoundException(`Class not found in ${fn}. The file was found, but the class isn't there.`);
            }

            realTarget = mod;

            const name = mod.definition ? mod.definition.name : mod.name;
            const meta = {
                filename: fn,
                fqcn: this._fullyQualifiedName + '.' + name,
                module: this._internalRequire.cache[fn],
                constructor: mod,
                namespace: this,
                isModule: (val) => {
                    return self === val || mod === val || mod.definition === val;
                },
            };

            if (! mod.hasOwnProperty('arguments')) {
                Object.defineProperty(mod, 'arguments', {value: null, writable: false, enumerable: false, configurable: false});
            }

            if (! mod.hasOwnProperty('caller')) {
                Object.defineProperty(mod, 'caller', {value: null, writable: false, enumerable: false, configurable: false});
            }

            Object.defineProperty(mod, Symbol.reflection, {
                enumerable: false,
                writable: false,
                configurable: false,
                value: meta,
            });

            if (mod.definition) {
                // Interface or Trait
                Object.defineProperty(mod.definition, Symbol.reflection, {
                    enumerable: false,
                    writable: false,
                    configurable: false,
                    value: meta,
                });
            }
        };

        const handlers = {
            get: (target, key) => {
                init();
                return Reflect.get(realTarget, key);
            },
            set: (target, key, value) => {
                init();
                return Reflect.set(realTarget, key, value);
            },
            has: (target, key) => {
                init();
                return Reflect.has(realTarget, key);
            },
            deleteProperty: (target, key) => {
                init();
                return Reflect.deleteProperty(realTarget, key);
            },
            defineProperty: (target, key, descriptor) => {
                init();
                return Reflect.defineProperty(realTarget, key, descriptor);
            },
            enumerate: () => {
                init();
                return Reflect.enumerate(realTarget);
            },
            ownKeys: () => {
                init();
                return Reflect.ownKeys(realTarget)
                    .filter(k => k !== Symbol.reflection);
            },
            apply: (target, thisArgument, args) => {
                init();
                return Reflect.apply(realTarget, thisArgument, args);
            },
            construct: (target, argumentsList, newTarget) => {
                init();
                return Reflect.construct(realTarget, argumentsList, newTarget);
            },
            getPrototypeOf: () => {
                init();
                return Reflect.getPrototypeOf(realTarget);
            },
            setPrototypeOf: (target, proto) => {
                init();
                return Reflect.setPrototypeOf(realTarget, proto);
            },
            isExtensible: () => {
                init();
                return Reflect.isExtensible(realTarget);
            },
            preventExtensions: () => {
                init();
                return Reflect.preventExtensions(realTarget);
            },
            getOwnPropertyDescriptor: (target, key) => {
                init();
                return Reflect.getOwnPropertyDescriptor(realTarget, key);
            },
        };

        return self = new Proxy(FunctionPrototype, handlers);
    }
}

module.exports = Namespace;
<|endoftext|>


<commit_before>/* global acutePrefix */

/**
* Default directives
*/

acute.directives["class"] = (function () {

  var directive = {};

  directive.bind = function ( element, attr, scope ) {
    var expr = attr.value || attr.nodeValue;

    var evalFn = acute.parser.parse(expr);
    acute.trace.d("class", expr, evalFn);

    // var $el = $(element);
    // scope.watch(expr, function ( change ) {
    //   acute.trace.d("change class", change);
    //   // if ( change.value ) {
    //   //   $el.html(change.value);
    //   // } else {
    //   //   $el.html('');
    //   // }
    // });
  };

  directive.unbind = function ( element ) {
  };

  return directive;

}());
<commit_msg>fixed class directive<commit_after>/* global acutePrefix */

/**
* Default directives
*/

acute.directives["class"] = (function () {

  var directive = {};

  directive.bind = function ( element, attr, scope ) {
    var expr = attr.value || attr.nodeValue;
    var evalFn = acute.parser.parse(expr);
    var $el = $(element);
    scope.watch(evalFn.watches, function ( change ) {
      var classes = evalFn(scope);
      acute.trace.d("classes", classes);
      for ( var klass in classes ) {
        $el.toggleClass(klass, Boolean(classes[klass]));
      }
    });
  };

  directive.unbind = function ( element ) {
  };

  return directive;

}());
<|endoftext|>


<commit_before>import { connect } from 'react-redux';
import DataModelGraph from './DataModelGraph';

import { fetchWithCreds } from '../actions';
import { submissionApiPath } from '../localconf';

/**
 * Compose and send a single graphql query to get a count of how
 * many of each node and edge are in the current state
 *
 * @method getCounts
 * @param {Array<string>} typeList
 * @param {string} project
 * @param {Object} dictionary
 * @return {Function(dispatch => updates-redux-state)} async dispatch function
 *     that fetches data from backend and updates redux when dispatched
 */
export const getCounts = (typeList, project, dictionary) => {
  let query = '{';

  function appendCountToQuery(element) {
    const node = dictionary[element];
    if (element !== 'metaschema' && !element.startsWith('_') && node.category !== 'internal') {
      query += `_${element}_count (project_id:"${project}"),`;
    }
  }

  function appendLinkToQuery(source, dest, name) {
    if (source.id !== 'metaschema' && !source.id.startsWith('_') && source.category !== 'internal') {
      query += `${source.id}_${name}_to_${dest.id}_link: ${source.id}(with_links: ["${name}"], first:1, project_id:"${project}"){submitter_id},`;
    }
  }

  typeList.forEach((element) => {
    if (element !== 'program') {
      appendCountToQuery(element);
    }
  });

  const nodesToHide = { program: true };
  // Add links to query
  Object.keys(dictionary).filter(
    name => (!name.startsWith('_' && dictionary[name].links) && dictionary[name].category !== 'internal'),
  ).reduce( // extract links from each node
    (linkList, name) => {
      const node = dictionary[name];
      const newLinks = node.links;
      let results = linkList;
      if (newLinks) { // extract subgroups from each link
        const sgLinks = newLinks.reduce(
          (listlist, link) => {
            if (link.subgroup) {
              return link.subgroup.map(
                sg => ({
                  source: dictionary[name],
                  target: dictionary[sg.target_type],
                  name: sg.name,
                }),
              ).concat(listlist);
            }
            return listlist;
          }, [],
        );
        results = sgLinks.concat(linkList);
      }
      return newLinks ? newLinks.map(
        l => ({ source: dictionary[name], target: dictionary[l.target_type], name: l.name }),
      ).concat(results) : results;
    }, [],
  )
    .filter(
      l => l.source && l.target && !nodesToHide[l.source.id] && !nodesToHide[l.target.id],
    )
    .forEach(
      ({ source, target, name }) => appendLinkToQuery(source, target, name),
    );

  query = query.concat('}');

  return dispatch => fetchWithCreds({
    path: `${submissionApiPath}graphql`,
    body: JSON.stringify({
      query,
    }),
    method: 'POST',
    dispatch,
  })
    .then(
      ({ status, data }) => {
        switch (status) {
        case 200:
          return {
            type: 'RECEIVE_COUNTS',
            data: data.data,
          };
        default:
          return {
            type: 'FETCH_ERROR',
            error: data.data,
          };
        }
      },
      err => ({ type: 'FETCH_ERROR', error: err }),
    )
    .then((msg) => { dispatch(msg); });
};

const mapStateToProps = state => ({
  dictionary: state.submission.dictionary,
  counts_search: state.submission.counts_search,
  links_search: state.submission.links_search,
});

const mapDispatchToProps = dispatch => ({
  onGetCounts: (type, project) => dispatch(getCounts(type, project)),
});
const ReduxDataModelGraph = connect(mapStateToProps, mapDispatchToProps)(DataModelGraph);
export default ReduxDataModelGraph;
<commit_msg>Update ReduxDataModelGraph.js (#445)<commit_after>import { connect } from 'react-redux';
import DataModelGraph from './DataModelGraph';

import { fetchWithCreds } from '../actions';
import { submissionApiPath } from '../localconf';

/**
 * Compose and send a single graphql query to get a count of how
 * many of each node and edge are in the current state
 *
 * @method getCounts
 * @param {Array<string>} typeList
 * @param {string} project
 * @param {Object} dictionary
 * @return {Function(dispatch => updates-redux-state)} async dispatch function
 *     that fetches data from backend and updates redux when dispatched
 */
export const getCounts = (typeList, project, dictionary) => {
  let query = '{';

  function appendCountToQuery(element) {
    const node = dictionary[element];
    if (element !== 'metaschema' && !element.startsWith('_') && node.category !== 'internal') {
      query += `_${element}_count (project_id:"${project}"),`;
    }
  }

  function appendLinkToQuery(source, dest, name) {
    if (source.id !== 'metaschema' && !source.id.startsWith('_') && source.category !== 'internal' && name != null && dest != null) {
      query += `${source.id}_${name}_to_${dest.id}_link: ${source.id}(with_links: ["${name}"], first:1, project_id:"${project}"){submitter_id},`;
    }
  }

  typeList.forEach((element) => {
    if (element !== 'program') {
      appendCountToQuery(element);
    }
  });

  const nodesToHide = { program: true };
  // Add links to query
  Object.keys(dictionary).filter(
    name => (!name.startsWith('_' && dictionary[name].links) && dictionary[name].category !== 'internal'),
  ).reduce( // extract links from each node
    (linkList, name) => {
      const node = dictionary[name];
      const newLinks = node.links;
      let results = linkList;
      if (newLinks) { // extract subgroups from each link
        const sgLinks = newLinks.reduce(
          (listlist, link) => {
            if (link.subgroup) {
              return link.subgroup.map(
                sg => ({
                  source: dictionary[name],
                  target: dictionary[sg.target_type],
                  name: sg.name,
                }),
              ).concat(listlist);
            }
            return listlist;
          }, [],
        );
        results = sgLinks.concat(linkList);
      }
      return newLinks ? newLinks.map(
        l => ({ source: dictionary[name], target: dictionary[l.target_type], name: l.name }),
      ).concat(results) : results;
    }, [],
  )
    .filter(
      l => l.source && l.target && !nodesToHide[l.source.id] && !nodesToHide[l.target.id],
    )
    .forEach(
      ({ source, target, name }) => appendLinkToQuery(source, target, name),
    );

  query = query.concat('}');

  return dispatch => fetchWithCreds({
    path: `${submissionApiPath}graphql`,
    body: JSON.stringify({
      query,
    }),
    method: 'POST',
    dispatch,
  })
    .then(
      ({ status, data }) => {
        switch (status) {
        case 200:
          return {
            type: 'RECEIVE_COUNTS',
            data: data.data,
          };
        default:
          return {
            type: 'FETCH_ERROR',
            error: data.data,
          };
        }
      },
      err => ({ type: 'FETCH_ERROR', error: err }),
    )
    .then((msg) => { dispatch(msg); });
};

const mapStateToProps = state => ({
  dictionary: state.submission.dictionary,
  counts_search: state.submission.counts_search,
  links_search: state.submission.links_search,
});

const mapDispatchToProps = dispatch => ({
  onGetCounts: (type, project) => dispatch(getCounts(type, project)),
});
const ReduxDataModelGraph = connect(mapStateToProps, mapDispatchToProps)(DataModelGraph);
export default ReduxDataModelGraph;
<|endoftext|>


<commit_before>import * as Util from '../core/Util';
import {Evented} from '../core/Events';
import * as DomUtil from '../dom/DomUtil';

/*
 * @class PosAnimation
 * @aka L.PosAnimation
 * @inherits Evented
 * Used internally for panning animations, utilizing CSS3 Transitions for modern browsers and a timer fallback for IE6-9.
 *
 * @example
 * ```js
 * var fx = new L.PosAnimation();
 * fx.run(el, [300, 500], 0.5);
 * ```
 *
 * @constructor L.PosAnimation()
 * Creates a `PosAnimation` object.
 *
 */

export var PosAnimation = Evented.extend({

	// @method run(el: HTMLElement, newPos: Point, duration?: Number, easeLinearity?: Number)
	// Run an animation of a given element to a new position, optionally setting
	// duration in seconds (`0.25` by default) and easing linearity factor (3rd
	// argument of the [cubic bezier curve](https://cubic-bezier.com/#0,0,.5,1),
	// `0.5` by default).
	run: function (el, newPos, duration, easeLinearity) {
		this.stop();

		this._el = el;
		this._inProgress = true;
		this._duration = duration || 0.25;
		this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);

		this._startPos = DomUtil.getPosition(el);
		this._offset = newPos.subtract(this._startPos);
		this._startTime = +new Date();

		// @event start: Event
		// Fired when the animation starts
		this.fire('start');

		this._animate();
	},

	// @method stop()
	// Stops the animation (if currently running).
	stop: function () {
		if (!this._inProgress) { return; }

		this._step(true);
		this._complete();
	},

	_animate: function () {
		// animation loop
		this._animId = Util.requestAnimFrame(this._animate, this);
		this._step();
	},

	_step: function (round) {
		var elapsed = (+new Date()) - this._startTime,
		    duration = this._duration * 1000;

		if (elapsed < duration) {
			this._runFrame(this._easeOut(elapsed / duration), round);
		} else {
			this._runFrame(1);
			this._complete();
		}
	},

	_runFrame: function (progress, round) {
		var pos = this._startPos.add(this._offset.multiplyBy(progress));
		if (round) {
			pos._round();
		}
		DomUtil.setPosition(this._el, pos);

		// @event step: Event
		// Fired continuously during the animation.
		this.fire('step');
	},

	_complete: function () {
		Util.cancelAnimFrame(this._animId);

		this._inProgress = false;
		// @event end: Event
		// Fired when the animation ends.
		this.fire('end');
	},

	_easeOut: function (t) {
		return 1 - Math.pow(1 - t, this._easeOutPower);
	}
});
<commit_msg>Better PosAnimation example (#7386)<commit_after>import * as Util from '../core/Util';
import {Evented} from '../core/Events';
import * as DomUtil from '../dom/DomUtil';

/*
 * @class PosAnimation
 * @aka L.PosAnimation
 * @inherits Evented
 * Used internally for panning animations, utilizing CSS3 Transitions for modern browsers and a timer fallback for IE6-9.
 *
 * @example
 * ```js
 * var myPositionMarker = L.marker([48.864716, 2.294694]).addTo(map);
 *
 * myPositionMarker.on("click", function() {
 * 	var pos = map.latLngToLayerPoint(myPositionMarker.getLatLng());
 * 	pos.y -= 25;
 * 	var fx = new L.PosAnimation();
 *
 * 	fx.once('end',function() {
 * 		pos.y += 25;
 * 		fx.run(myPositionMarker._icon, pos, 0.8);
 * 	});
 *
 * 	fx.run(myPositionMarker._icon, pos, 0.3);
 * });
 *
 * ```
 *
 * @constructor L.PosAnimation()
 * Creates a `PosAnimation` object.
 *
 */

export var PosAnimation = Evented.extend({

	// @method run(el: HTMLElement, newPos: Point, duration?: Number, easeLinearity?: Number)
	// Run an animation of a given element to a new position, optionally setting
	// duration in seconds (`0.25` by default) and easing linearity factor (3rd
	// argument of the [cubic bezier curve](https://cubic-bezier.com/#0,0,.5,1),
	// `0.5` by default).
	run: function (el, newPos, duration, easeLinearity) {
		this.stop();

		this._el = el;
		this._inProgress = true;
		this._duration = duration || 0.25;
		this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);

		this._startPos = DomUtil.getPosition(el);
		this._offset = newPos.subtract(this._startPos);
		this._startTime = +new Date();

		// @event start: Event
		// Fired when the animation starts
		this.fire('start');

		this._animate();
	},

	// @method stop()
	// Stops the animation (if currently running).
	stop: function () {
		if (!this._inProgress) { return; }

		this._step(true);
		this._complete();
	},

	_animate: function () {
		// animation loop
		this._animId = Util.requestAnimFrame(this._animate, this);
		this._step();
	},

	_step: function (round) {
		var elapsed = (+new Date()) - this._startTime,
		    duration = this._duration * 1000;

		if (elapsed < duration) {
			this._runFrame(this._easeOut(elapsed / duration), round);
		} else {
			this._runFrame(1);
			this._complete();
		}
	},

	_runFrame: function (progress, round) {
		var pos = this._startPos.add(this._offset.multiplyBy(progress));
		if (round) {
			pos._round();
		}
		DomUtil.setPosition(this._el, pos);

		// @event step: Event
		// Fired continuously during the animation.
		this.fire('step');
	},

	_complete: function () {
		Util.cancelAnimFrame(this._animId);

		this._inProgress = false;
		// @event end: Event
		// Fired when the animation ends.
		this.fire('end');
	},

	_easeOut: function (t) {
		return 1 - Math.pow(1 - t, this._easeOutPower);
	}
});
<|endoftext|>


<commit_before>import {dockerode} from '../util'
import ContainerRepository from './container-repository'

/**
 * The container model.
 */
export default class Container {

  /**
   * @param {string} id The id
   * @param {string} name The name of the container
   * @param {string} image The name of the image
   * @param {string} cmd The command of the image
   * @param {boolean} isRunning true if it's running, false otherwise.
   * @param {Array<string>} ports The port bindings
   */
  constructor({id, name, image, cmd, isRunning, ports}) {

    this.id = id
    this.name = name
    this.image = image
    this.cmd = cmd
    this.isRunning = isRunning
    this.isRemoved = false
    this.ports = ports

  }

  /**
   * Gets the same container from docker and update itself.
   * @private
   * @return {Promise<Container>}
   */
  update() {

    return new ContainerRepository().getById(this.id).then(container => {

      this.id = container.id
      this.image = container.image
      this.name = container.name
      this.cmd = container.cmd
      this.isRunning = container.isRunning
      this.ports = container.ports

      return this

    })

  }

  /**
   * Starts the container and returns the promise of itself.
   * @return {Promise<Container>}
   */
  start() {

    return new Promise((resolve, reject) => {

      dockerode.getContainer(this.id).start(err => {

        if (err) {

          return reject(err)

        }

        return resolve()

      })

    }).then(() => this.update())

  }

  /**
   * Stops the container and returns the promise of itself.
   * @return {Promise}
   */
  stop() {

    return new Promise((resolve, reject) => {

      dockerode.getContainer(this.id).stop(err => {

        if (err) {

          return reject(err)

        }

        return resolve()

      })

    }).then(() => this.update(), err => {

      if (err.statusCode === 304) { // The container is already stopped
        return
      }

      throw err

    })

  }

  /**
   * Removes the container.
   * @return {Promise}
   */
  remove() {

    return new ContainerRepository().remove(this)

  }

  /**
   * Returns true iff the container has the id.
   */
  hasId() {

    return this.id != null

  }

  /**
   * Returns true iff the container has the name.
   */
  hasName() {

    return this.name != null

  }

  /**
   * Returns true iff this container has enough properties for being created.
   */
  isCreatable() {

    return this.image != null

  }

  /**
   * Sets the state of the container removed
   */
  setRemoved() {

    this.id = null
    this.isRunning = false
    this.isRemoved = true

  }

}
<commit_msg>Remove disused I/Fs<commit_after>import {dockerode} from '../util'
import ContainerRepository from './container-repository'

/**
 * The container model.
 */
export default class Container {

  /**
   * @param {string} id The id
   * @param {string} name The name of the container
   * @param {string} image The name of the image
   * @param {string} cmd The command of the image
   * @param {boolean} isRunning true if it's running, false otherwise.
   * @param {Array<string>} ports The port bindings
   */
  constructor({id, name, image, cmd, isRunning, ports}) {

    this.id = id
    this.name = name
    this.image = image
    this.cmd = cmd
    this.isRunning = isRunning
    this.isRemoved = false
    this.ports = ports

  }

  /**
   * Gets the same container from docker and update itself.
   * @private
   * @return {Promise<Container>}
   */
  update() {

    return new ContainerRepository().getById(this.id).then(container => {

      this.id = container.id
      this.image = container.image
      this.name = container.name
      this.cmd = container.cmd
      this.isRunning = container.isRunning
      this.ports = container.ports

      return this

    })

  }

  /**
   * Starts the container and returns the promise of itself.
   * @return {Promise<Container>}
   */
  start() {

    return new Promise((resolve, reject) => {

      dockerode.getContainer(this.id).start(err => {

        if (err) {

          return reject(err)

        }

        return resolve()

      })

    }).then(() => this.update())

  }

  /**
   * Stops the container and returns the promise of itself.
   * @return {Promise}
   */
  stop() {

    return new Promise((resolve, reject) => {

      dockerode.getContainer(this.id).stop(err => {

        if (err) {

          return reject(err)

        }

        return resolve()

      })

    }).then(() => this.update(), err => {

      if (err.statusCode === 304) { // The container is already stopped
        return
      }

      throw err

    })

  }

  /**
   * Removes the container.
   * @return {Promise}
   */
  remove() {

    return new ContainerRepository().remove(this)

  }

  /**
   * Returns true iff the container has the id.
   */
  hasId() {

    return this.id != null

  }

  /**
   * Sets the state of the container removed
   */
  setRemoved() {

    this.id = null
    this.isRunning = false
    this.isRemoved = true

  }

}
<|endoftext|>


<commit_before>var MACRO = require('./model/macro.js');
var mongoose = require('mongoose');
var https = require('https');
var fs = require('fs');

var Users = mongoose.model('Users');
var Notifications = mongoose.model('Notifications');
var Challenges = mongoose.model('Challenges');

var nextUserId = 0;
global.usersById = {};
var usersByGhId = {};

exports.send_mail = function (destination, type, body) {
  var nodemailer = require("nodemailer");

  // create reusable transport method (opens pool of SMTP connections)
  var smtpTransport = nodemailer.createTransport("SMTP",{
    service: "Gmail",
    auth: {
      user: global.config.mail_user,
      pass: global.config.mail_pass
    }
  });

  fs.readFile(__dirname + '/public/emails/' + type + '.html', 'utf8', function (err, html) {
      var mailOpt = {};

      if (type == 'welcome') {
        mailOpt['from']    = 'challenge@lists.rosedu.org';
        mailOpt['to']      = destination,
        mailOpt['subject'] = 'Welcome to Challenge by ROSEdu',
        mailOpt['text']    = '',
        mailOpt['html']    = html;
      } else if (type == 'feedback') {
        mailOpt['from']    = 'challenge@lists.rosedu.org';
        mailOpt['to']      = 'challenge@lists.rosedu.org',
        mailOpt['subject'] = 'Feedback: ' + body.email,
        mailOpt['text']    = body.msg
      }

      // send mail with defined transport object
      smtpTransport.sendMail(mailOpt, function(err, response){
        if (err) console.log(err);
        else console.log("* Email sent to " + destination);

        smtpTransport.close();
      });
  });
}

function addUser (source, sourceUser) {
  var user;
  if (arguments.length === 1) { // password-based
    user = sourceUser = source;
    user.id = ++nextUserId;
    return usersById[nextUserId] = user;
  } else { // non-password-based
    user = usersById[++nextUserId] = {id: nextUserId};
    user[source] = sourceUser;
  }
  return user;
}

exports.login = function(sess, accessToken, accessTokenExtra, ghUser) {
  sess.oauth = accessToken;
  if (typeof usersByGhId[ghUser.id] === 'undefined') {

    usersByGhId[ghUser.id] = addUser('github', ghUser);

    Users
    .findOne({ 'user_id': usersByGhId[ghUser.id].github.id },
               'user_name', function (err, user) {
      if (err) return handleError(err);
      if (user != null) {
        // update last_seen
        var conditions = {'user_name': user.user_name};
        var update = {$set: {
          'last_seen': Date.now(),
          'followers_no': usersByGhId[ghUser.id].github.followers,
          'following_no': usersByGhId[ghUser.id].github.following
        }};
        Users.update(conditions, update, function (err, num) {
          console.log("* User " + user.user_name + " logged in.");
        });

      } else {
        // Send welcome notification
        new Notifications({
          'src':    null,
          'dest':   usersByGhId[ghUser.id].github.login,
          'type':   "welcome",
          'link':   "/faq"
        }).save(function(err, todo, count) {
          if (err) console.log("[ERR] Notification not sent.");
        });

        // Import data from github
        return new Users ({
          user_id:       usersByGhId[ghUser.id].github.id,
          user_name:     usersByGhId[ghUser.id].github.login,
          user_fullname: usersByGhId[ghUser.id].github.name,
          user_email:    usersByGhId[ghUser.id].github.email,
          avatar_url:    usersByGhId[ghUser.id].github.avatar_url,
          location:      usersByGhId[ghUser.id].github.location,
          join_github:   usersByGhId[ghUser.id].github.created_at,
          followers_no:  usersByGhId[ghUser.id].github.followers,
          following_no:  usersByGhId[ghUser.id].github.following
        }).save (function (err, user, count) {
          console.log("* User " + user.user_name + " added.");
          // send welcome email
          module.exports.send_mail(user.user_email, 'welcome');
        });
      }
    });
    return usersByGhId[ghUser.id];

  } else {
    return usersByGhId[ghUser.id];
  }
}

exports.get_time_from = function (then) {
  var now = Date.now();

  // interval between time now and db date
  var msec = now - new Date(then).getTime();

  var hh = Math.floor(msec / 1000 / 60 / 60);
  if (hh > 24) { // older that 24 hours
    // return actual date
    return "on " + then.toString().substring(4, 15);

  } else if (hh > 1) { // older than 1 hour
    return hh + " hours ago";

  } else {
    msec -= hh * 1000 * 60 * 60;
    var mm = Math.floor(msec / 1000 / 60);

    if (mm > 1) { // older than 1 mnute
      return mm + " minutes ago";

    } else {
      return "one minute ago";
    }
  }
}

/*
Refresh all repos from all challeneges that are active ('live').
*/
exports.refresh_challenges = function() {

  Challenges.find({'status': 'live'}).exec(gotChallenges);

  function gotChallenges(err, all) {

    // For each challenge in pool
    for (var c in all) {

      var ch = all[c];

      // Update last refresh date
      var update = {$set: { 'refresh': Date.now()}};
      Challenges.update({'link': ch.link}, update).exec();

      //New request for each repo of challenge
      for (var r=0; r<ch.repos.length; r++) {

        var options = {
          host: "api.github.com",
          path: "/repos/" + ch.repos[r] + "/pulls?state=all",
          method: "GET",
          headers: { "User-Agent": "github-connect" }
        };

        var request = https.request(options, function(response){
          var body = '';
          response.on("data", function(chunk){ body+=chunk.toString("utf8"); });
          response.on("end", function(){
            var pulls = JSON.parse(body);

            // Log errors
            if (pulls.message)
              console.log("[ERR] " + pulls.message + " - " + options.path
                + " (" + pulls.documentation_url + ")");

            for (var p in pulls) {
              // Accept only pulls created after challenge start date, before end
              // date and only from registered users
              if (new Date(pulls[p].created_at).getTime() > ch.start.getTime() &&
                  new Date(pulls[p].created_at).getTime() < ch.end.getTime() &&
                  ch.users.indexOf(pulls[p].user.login) > -1) {

                // Check if merge date exists
                var merge_date;

                if (!pulls[p].merged_at) merge_date = null;
                else merge_date = new Date(pulls[p].merged_at);

                var update = {$addToSet: { 'pulls': {
                  repo:      ch.repos[r],
                  auth:      pulls[p].user.login,
                  url:       pulls[p].html_url,
                  title:     pulls[p].title,
                  created:   new Date(pulls[p].created_at),
                  merged:    merge_date
                }}};

                Challenges.update({'link': ch.link}, update).exec();
              }
            }

          });
        });
        request.end();
      }
    }
  }
}
<commit_msg>Actually fix pull req repo name<commit_after>var MACRO = require('./model/macro.js');
var mongoose = require('mongoose');
var https = require('https');
var fs = require('fs');

var Users = mongoose.model('Users');
var Notifications = mongoose.model('Notifications');
var Challenges = mongoose.model('Challenges');

var nextUserId = 0;
global.usersById = {};
var usersByGhId = {};

exports.send_mail = function (destination, type, body) {
  var nodemailer = require("nodemailer");

  // create reusable transport method (opens pool of SMTP connections)
  var smtpTransport = nodemailer.createTransport("SMTP",{
    service: "Gmail",
    auth: {
      user: global.config.mail_user,
      pass: global.config.mail_pass
    }
  });

  fs.readFile(__dirname + '/public/emails/' + type + '.html', 'utf8', function (err, html) {
      var mailOpt = {};

      if (type == 'welcome') {
        mailOpt['from']    = 'challenge@lists.rosedu.org';
        mailOpt['to']      = destination,
        mailOpt['subject'] = 'Welcome to Challenge by ROSEdu',
        mailOpt['text']    = '',
        mailOpt['html']    = html;
      } else if (type == 'feedback') {
        mailOpt['from']    = 'challenge@lists.rosedu.org';
        mailOpt['to']      = 'challenge@lists.rosedu.org',
        mailOpt['subject'] = 'Feedback: ' + body.email,
        mailOpt['text']    = body.msg
      }

      // send mail with defined transport object
      smtpTransport.sendMail(mailOpt, function(err, response){
        if (err) console.log(err);
        else console.log("* Email sent to " + destination);

        smtpTransport.close();
      });
  });
}

function addUser (source, sourceUser) {
  var user;
  if (arguments.length === 1) { // password-based
    user = sourceUser = source;
    user.id = ++nextUserId;
    return usersById[nextUserId] = user;
  } else { // non-password-based
    user = usersById[++nextUserId] = {id: nextUserId};
    user[source] = sourceUser;
  }
  return user;
}

exports.login = function(sess, accessToken, accessTokenExtra, ghUser) {
  sess.oauth = accessToken;
  if (typeof usersByGhId[ghUser.id] === 'undefined') {

    usersByGhId[ghUser.id] = addUser('github', ghUser);

    Users
    .findOne({ 'user_id': usersByGhId[ghUser.id].github.id },
               'user_name', function (err, user) {
      if (err) return handleError(err);
      if (user != null) {
        // update last_seen
        var conditions = {'user_name': user.user_name};
        var update = {$set: {
          'last_seen': Date.now(),
          'followers_no': usersByGhId[ghUser.id].github.followers,
          'following_no': usersByGhId[ghUser.id].github.following
        }};
        Users.update(conditions, update, function (err, num) {
          console.log("* User " + user.user_name + " logged in.");
        });

      } else {
        // Send welcome notification
        new Notifications({
          'src':    null,
          'dest':   usersByGhId[ghUser.id].github.login,
          'type':   "welcome",
          'link':   "/faq"
        }).save(function(err, todo, count) {
          if (err) console.log("[ERR] Notification not sent.");
        });

        // Import data from github
        return new Users ({
          user_id:       usersByGhId[ghUser.id].github.id,
          user_name:     usersByGhId[ghUser.id].github.login,
          user_fullname: usersByGhId[ghUser.id].github.name,
          user_email:    usersByGhId[ghUser.id].github.email,
          avatar_url:    usersByGhId[ghUser.id].github.avatar_url,
          location:      usersByGhId[ghUser.id].github.location,
          join_github:   usersByGhId[ghUser.id].github.created_at,
          followers_no:  usersByGhId[ghUser.id].github.followers,
          following_no:  usersByGhId[ghUser.id].github.following
        }).save (function (err, user, count) {
          console.log("* User " + user.user_name + " added.");
          // send welcome email
          module.exports.send_mail(user.user_email, 'welcome');
        });
      }
    });
    return usersByGhId[ghUser.id];

  } else {
    return usersByGhId[ghUser.id];
  }
}

exports.get_time_from = function (then) {
  var now = Date.now();

  // interval between time now and db date
  var msec = now - new Date(then).getTime();

  var hh = Math.floor(msec / 1000 / 60 / 60);
  if (hh > 24) { // older that 24 hours
    // return actual date
    return "on " + then.toString().substring(4, 15);

  } else if (hh > 1) { // older than 1 hour
    return hh + " hours ago";

  } else {
    msec -= hh * 1000 * 60 * 60;
    var mm = Math.floor(msec / 1000 / 60);

    if (mm > 1) { // older than 1 mnute
      return mm + " minutes ago";

    } else {
      return "one minute ago";
    }
  }
}

/*
Refresh all repos from all challeneges that are active ('live').
*/
exports.refresh_challenges = function() {

  Challenges.find({'status': 'live'}).exec(gotChallenges);

  function gotChallenges(err, all) {

    // For each challenge in pool
    for (var c in all) {

      var ch = all[c];

      // Update last refresh date
      var update = {$set: { 'refresh': Date.now()}};
      Challenges.update({'link': ch.link}, update).exec();

      //New request for each repo of challenge
      for (var r=0; r<ch.repos.length; r++) {

        var options = {
          host: "api.github.com",
          path: "/repos/" + ch.repos[r] + "/pulls?state=all",
          method: "GET",
          headers: { "User-Agent": "github-connect" }
        };

        var request = https.request(options, function(response){
          var body = '';
          response.on("data", function(chunk){ body+=chunk.toString("utf8"); });
          response.on("end", function(){
            var pulls = JSON.parse(body);

            // Log errors
            if (pulls.message)
              console.log("[ERR] " + pulls.message + " - " + options.path
                + " (" + pulls.documentation_url + ")");

            for (var p in pulls) {
              // Accept only pulls created after challenge start date, before end
              // date and only from registered users
              if (new Date(pulls[p].created_at).getTime() > ch.start.getTime() &&
                  new Date(pulls[p].created_at).getTime() < ch.end.getTime() &&
                  ch.users.indexOf(pulls[p].user.login) > -1) {

                // Check if merge date exists
                var merge_date;

                if (!pulls[p].merged_at) merge_date = null;
                else merge_date = new Date(pulls[p].merged_at);

                var update = {$addToSet: { 'pulls': {
                  'repo':      pulls[p].base.repo.full_name,
                  'auth':      pulls[p].user.login,
                  'url':       pulls[p].html_url,
                  'title':     pulls[p].title,
                  'created':   new Date(pulls[p].created_at),
                  'merged':    merge_date
                }}};

                Challenges.update({'link': ch.link}, update).exec();
              }
            }

          });
        });
        request.end();
      }
    }
  }
}
<|endoftext|>