text:
package io.katharsis.module;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import io.katharsis.dispatcher.filter.Filter;
import io.katharsis.errorhandling.mapper.ExceptionMapperLookup;
import io.katharsis.errorhandling.mapper.JsonApiExceptionMapper;
import io.katharsis.repository.RelationshipRepository;
import io.katharsis.repository.ResourceRepository;
import io.katharsis.resource.information.ResourceInformationBuilder;
import io.katharsis.resource.registry.ResourceLookup;

/**
 * Vanilla {@link Module} implementation that allows registration of extensions.
 */
public class SimpleModule implements Module {

	private List<ResourceInformationBuilder> resourceInformationBuilders = new ArrayList<ResourceInformationBuilder>();
	private List<Filter> filters = new ArrayList<Filter>();
	private List<ResourceLookup> resourceLookups = new ArrayList<ResourceLookup>();
	private List<com.fasterxml.jackson.databind.Module> jacksonModules = new ArrayList<com.fasterxml.jackson.databind.Module>();
	private List<RelationshipRepositoryRegistration> relationshipRepositoryRegistrations = new ArrayList<RelationshipRepositoryRegistration>();
	private List<ResourceRepositoryRegistration> resourceRepositoryRegistrations = new ArrayList<ResourceRepositoryRegistration>();
	private List<ExceptionMapperLookup> exceptionMapperLookups = new ArrayList<ExceptionMapperLookup>();

	private String moduleName;

	private ModuleContext context;

	public SimpleModule(String moduleName) {
		this.moduleName = moduleName;
	}

	@Override
	public String getModuleName() {
		return moduleName;
	}

	@Override
	public void setupModule(ModuleContext context) {
		this.context = context;
		for (ResourceInformationBuilder resourceInformationBuilder : resourceInformationBuilders) {
			context.addResourceInformationBuilder(resourceInformationBuilder);
		}
		for (ResourceLookup resourceLookup : resourceLookups) {
			context.addResourceLookup(resourceLookup);
		}
		for (Filter filter : filters) {
			context.addFilter(filter);
		}
		for (com.fasterxml.jackson.databind.Module jacksonModule : jacksonModules) {
			context.addJacksonModule(jacksonModule);
		}
		for (ResourceRepositoryRegistration reg : resourceRepositoryRegistrations) {
			context.addRepository(reg.resourceClass, reg.repository);
		}
		for (RelationshipRepositoryRegistration reg : relationshipRepositoryRegistrations) {
			context.addRepository(reg.sourceType, reg.targetType, reg.repository);
		}
		for (ExceptionMapperLookup exceptionMapperLookup : exceptionMapperLookups) {
			context.addExceptionMapperLookup(exceptionMapperLookup);
		}
	}

	private void checkInitialized(){
		if(context != null){
			throw new IllegalStateException("module cannot be changed addModule was called");
		}
	}

	/**
	 * Registers a new {@link ResourceInformationBuilder} with this module.
	 *
	 * @param resourceInformationBuilder
	 */
	public void addResourceInformationBuilder(ResourceInformationBuilder resourceInformationBuilder) {
		checkInitialized();
		resourceInformationBuilders.add(resourceInformationBuilder);
	}

	public void addExceptionMapperLookup(ExceptionMapperLookup exceptionMapperLookup) {
		checkInitialized();
		exceptionMapperLookups.add(exceptionMapperLookup);
	}

	public void addExceptionMapper(@SuppressWarnings("rawtypes") JsonApiExceptionMapper exceptionMapper) {
		checkInitialized();
		ExceptionMapperLookup exceptionMapperLookup = new CollectionExceptionMapperLookup(exceptionMapper);
		exceptionMapperLookups.add(exceptionMapperLookup);
	}

	protected List<ResourceInformationBuilder> getResourceInformationBuilders() {
		checkInitialized();
		return Collections.unmodifiableList(resourceInformationBuilders);
	}

	public void addFilter(Filter filter) {
		checkInitialized();
		filters.add(filter);
	}

	protected List<Filter> getFilters() {
		checkInitialized();
		return Collections.unmodifiableList(filters);
	}

	public void addJacksonModule(com.fasterxml.jackson.databind.Module module) {
		checkInitialized();
		jacksonModules.add(module);
	}

	protected List<com.fasterxml.jackson.databind.Module> getJacksonModules() {
		checkInitialized();
		return Collections.unmodifiableList(jacksonModules);
	}

	/**
	 * Registers a new {@link ResourceLookup} with this module.
	 *
	 * @param resourceLookup
	 */
	public void addResourceLookup(ResourceLookup resourceLookup) {
		checkInitialized();
		resourceLookups.add(resourceLookup);
	}

	protected List<ResourceLookup> getResourceLookups() {
		checkInitialized();
		return Collections.unmodifiableList(resourceLookups);
	}

	public void addRepository(Class<?> type, ResourceRepository<?, ?> repository) {
		checkInitialized();
		resourceRepositoryRegistrations.add(new ResourceRepositoryRegistration(type, repository));
	}

	public void addRepository(Class<?> sourceType, Class<?> targetType, RelationshipRepository<?, ?, ?, ?> repository) {
		checkInitialized();
		relationshipRepositoryRegistrations
				.add(new RelationshipRepositoryRegistration(sourceType, targetType, repository));
	}

	public List<RelationshipRepositoryRegistration> getRelationshipRepositoryRegistrations() {
		return Collections.unmodifiableList(relationshipRepositoryRegistrations);
	}

	public List<ResourceRepositoryRegistration> getResourceRepositoryRegistrations() {
		return Collections.unmodifiableList(resourceRepositoryRegistrations);
	}

	public static class RelationshipRepositoryRegistration {

		private Class<?> sourceType;
		private Class<?> targetType;
		private RelationshipRepository<?, ?, ?, ?> repository;

		public RelationshipRepositoryRegistration(Class<?> sourceType, Class<?> targetType,
				RelationshipRepository<?, ?, ?, ?> repository) {
			this.sourceType = sourceType;
			this.targetType = targetType;
			this.repository = repository;
		}

		public Class<?> getSourceType() {
			return sourceType;
		}

		public Class<?> getTargetType() {
			return targetType;
		}

		public RelationshipRepository<?, ?, ?, ?> getRepository() {
			return repository;
		}

	}

	public static class ResourceRepositoryRegistration {

		private Class<?> resourceClass;
		private ResourceRepository<?, ?> repository;

		public ResourceRepositoryRegistration(Class<?> resourceClass, ResourceRepository<?, ?> repository) {
			this.resourceClass = resourceClass;
			this.repository = repository;
		}

		public Class<?> getResourceClass() {
			return resourceClass;
		}

		public ResourceRepository<?, ?> getRepository() {
			return repository;
		}
	}

	public List<ExceptionMapperLookup> getExceptionMapperLookups() {
		return Collections.unmodifiableList(exceptionMapperLookups);
	}

	@SuppressWarnings("rawtypes")
	private static class CollectionExceptionMapperLookup implements ExceptionMapperLookup {

		private Set<JsonApiExceptionMapper> set;

		private CollectionExceptionMapperLookup(Set<JsonApiExceptionMapper> set) {
			this.set = set;
		}

		public CollectionExceptionMapperLookup(JsonApiExceptionMapper exceptionMapper) {
			this(new HashSet<JsonApiExceptionMapper>(Arrays.asList(exceptionMapper)));
		}

		@Override
		public Set<JsonApiExceptionMapper> getExceptionMappers() {
			return set;
		}
	}
}


text:
(function (global, undefined) {
    "use strict"

    if ("function" !== typeof Object.create) {
        /**
         * The Object.create() method creates a new object with the specified prototype object and properties.
         * @function Object.create
         * @param proto
         * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create}
         */
        Object.create = (function () {
            var f = function () { };
            return function (proto) {
                if (arguments.length > 1) {
                    throw Error('Second argument not supported');
                }
                if (proto !== Object(proto) && proto !== null) {
                    throw TypeError('Argument must be an object or null');
                }
                if (proto === null) {
                    throw Error('null [[Prototype]] not supported');
                }
                f.prototype = proto;
                var result = new f();
                f.prototype = null;
                return result;
            };
        })();
    }
    if ("function" !== typeof Function.prototype.bind) {
        /**
         * The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
         * @function Function.prototype.bind
         * @param {} thisArg - The value to be passed as the this parameter to the target function when the bound function is called. The value is ignored if the bound function is constructed using the new operator.
         * @returns {}
         * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind}
         */
        Function.prototype.bind = function (thisArg) {
            if ("function" !== typeof this) {
                throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
            }
            var s = this;
            var args = Array.prototype.slice.call(arguments, 1);
            var f = function () { };
            var bound = function () {
                s.apply(this instanceof f ? this : thisArg, args.concat(Array.prototype.slice.call(arguments)));
            };
            if (this.prototype) {
                f.prototype = this.prototype;
            }
            bound.prototype = new f();
            return bound;
        };
    }

    if ("undefined" !== typeof global.Promise && !global.debugPromise) {
        return;
    }

    var Promise = (function () {
        /**
         * @enum enuPromiseState
         */
        var enuPromiseState = {
            "pending": "pending",
            "fulfilled": "fulfilled",
            "rejected": "rejected"
        };

        /**
         * @enum enuReactionHandler
         */
        var enuReactionHandler = {
            "identity": function (argument) {
                return argument;
            },
            "thrower": function (argument) {
                throw argument;
            }
        };

        /**
         * @class PromiseReaction
         * @param {object} capabilities - (PromiseCapability) The capabilities of the promise for which this record provides a reaction handler.
         * @param {string} handler - (enuReactionHandler) The function that should be applied to the incoming value, and whose return value will govern what happens to the derived promise. If [[Handler]] is "Identity" it is equivalent to a function that simply returns its first argument. If [[Handler]] is "Thrower" it is equivalent to a function that throws its first argument as an exception.
         */
        function PromiseReaction(capabilities, handler) {
            this._capabilities = capabilities;
            this._handler = handler;
        }

        /**
         * @class PromiseCapability
         * @param {object} promise - An object that is usable as a promise.
         * @param {function} resolve - The function that is used to resolve the given promise object.
         * @param {function} reject - The function that is used to reject the given promise object.
         */
        function PromiseCapability(promise, resolve, reject) {
            this._promise = promise;
            this._resolve = resolve;
            this._reject = reject;
        }

        var Iterator = (function () {
            /**
             * @class Iterator
             * @param {any[]} iterable
             */
            function Iterator(iterable) {
                this._index = undefined;
                if (!iterable || "undefined" === typeof iterable.length)
                    throw new TypeError("Invalid iterable");
                this.length = (this._iterable = iterable).length;
            }

            /**
             * @function Iterator.prototype.next
             * @param {any} [value]
             * @returns {boolean} - the iterator has successfully advanced to the next element; false if the iterator has passed the end of the collection.
             */
            Iterator.prototype.next = function (value) {
                this._index = "undefined" !== typeof this._index ? this._index + 1 : 0;
                return this._index < this.length;
            };

            /**
             * @function Iterator.prototype.getCurrent
             * @returns {any}
             */
            Iterator.prototype.getCurrent = function () {
                return this._iterable[this._index];
            };

            /**
             * @function Iterator.prototype.reset
             */
            Iterator.prototype.reset = function () {
                this._index = 0;
            };
            return Iterator;
        })();

        /**
         * @class IteratorRecord
         * @param {Iterator} iterator
         */
        function IteratorRecord(iterator) {
            this._iterator = iterator;
            this._done = false;
        }

        var jobHandler = (function () {
            var JobHandler = (function (undefined) {
                /**
                 * @class Job
                 * @param {string} name
                 * @param {function} action
                 * @param {any[]} [args]
                 */
                function Job(name, action, args) {
                    this.name = name;
                    this.action = action;
                    this.args = args;
                }

                Job.prototype.execute = function () {
                    this.action.apply(undefined, this.args);
                };

                /**
                 * @class JobHandler
                 * @param {number} [buffer] - available queue space. Default: 100
                 */
                function JobHandler(run, clear, buffer) {
                    if ("undefined" === buffer)
                        buffer = 20;
                    this._run = run;
                    this._clear = clear;
                    this._buffer = buffer;
                    this._queue = new Array(buffer);
                    this._queueIds = new Array(buffer);
                    this._length = 0;
                }

                JobHandler.prototype.isSupported = function () {
                    return "undefined" !== typeof this._queue
                        && "undefined" !== typeof this._run
                        && "undefined" !== typeof this._clear;
                };

                JobHandler.prototype.enqueue = function (name, action, args) {
                    if (!this.isSupported())
                        throw new TypeError();

                    if ("function" !== typeof action)
                        throw new TypeError("Unexpected action value. Expected type: function");

                    if (null != typeof args && ("object" !== typeof args || "undefined" === typeof args.length))
                        throw new TypeError("Unexpected args value. Expected type: Array, null or undefined");

                    var id = this._length;
                    this._length = this._length + 1;
                    this._queue[id] = new Job(name, action, args);
                    this._queueIds[id] = this._run(this._process.bind(this), 0);
                };

                JobHandler.prototype._process = function () {
                    var queue = this._queue;
                    var queueIds = this._queueIds;
                    var length = this._length;
                    this._queue = new Array(this._buffer);
                    this._queueIds = new Array(this._buffer);
                    this._length = 0;
                    for (var i = 0; i < length; i++) {
                        queue[i].execute();
                        this._clear(queueIds[i]);
                    }
                };

                return JobHandler;
            })();

            /**
             * @class ImmediateJobHandler
             * @extends JobHandler
             */
            function ImmediateJobHandler() {
                var run = window.setImmediate && window.setImmediate.bind(window);
                var clear = window.clearImmediate && window.clearImmediate.bind(window);
                JobHandler.call(this, run, clear);
            }
            ImmediateJobHandler.prototype = Object.create(JobHandler.prototype);

            /**
             * Based on the setImmediate polyfill
             * @class CustomImmediateJobHandler
             * @extends JobHandler
             * @see {@link https://github.com/YuzuJS/setImmediate}
             */
            function CustomImmediateJobHandler() {
                var run, clear;
                if (window.postMessage && !window.importScripts) {
                    var nextHandle = 1;
                    var tasks = {};
                    var messagePrefix = "setImmediate$" + Math.random() + "$";

                    run = function (handler) {
                        var args = Array.prototype.slice.call(arguments, 1);
                        tasks[nextHandle] = function () {
                            if (typeof handler === "function") {
                                handler.apply(undefined, args);
                            } else {
                                (new Function("" + handler))();
                            }
                        };
                        var handle = nextHandle++;
                        window.postMessage(messagePrefix + handle, "*");
                        return handle;
                    };

                    clear = function (handle) {
                        delete tasks[handle];
                    };

                    var onMessage = function (event) {
                        if (event.source == window &&
                            typeof event.data === "string" &&
                            event.data.indexOf(messagePrefix) === 0) {
                            var handle = (+event.data.slice(messagePrefix.length));

                            var task = tasks[handle];
                            if (task) {
                                try {
                                    task();
                                } finally {
                                    clear(handle);
                                }
                            }
                        }
                    };

                    if (window.addEventListener) {
                        window.addEventListener("message", onMessage, false);
                    } else {
                        window.attachEvent("onmessage", onMessage);
                    }
                }

                JobHandler.call(this, run, clear);
            }
            CustomImmediateJobHandler.prototype = Object.create(JobHandler.prototype);

            /**
             * @class MsImmediateJobHandler
             * @extends JobHandler
             */
            function MsImmediateJobHandler() {
                var run = window.msSetImmediate && window.msSetImmediate.bind(window);
                var clear = window.msClearImmediate && window.msClearImmediate.bind(window);
                JobHandler.call(this, run, clear);
            }
            MsImmediateJobHandler.prototype = Object.create(JobHandler.prototype);

            /**
             * @class TimeoutJobHandler
             * @extends JobHandler
             */
            function TimeoutJobHandler() {
                var run = window.setTimeout && window.setTimeout.bind(window);
                var clear = window.clearTimeout && window.clearTimeout.bind(window);
                JobHandler.call(this, run, clear);
            }
            TimeoutJobHandler.prototype = Object.create(JobHandler.prototype);

            /**
             * @class PromiseJobFactory
             */
            function JobHandlerFactory() {
                this._handlers = [ImmediateJobHandler, MsImmediateJobHandler, CustomImmediateJobHandler, TimeoutJobHandler];
            }

            /**
             * function createJobHandler
             * @returns {JobHandler}
             */
            JobHandlerFactory.prototype.createJobHandler = function () {
                var length = this._handlers.length;
                var handler;
                for (var i = 0; i < length; i++) {
                    var handler = new this._handlers[i]();
                    if (handler.isSupported()) {
                        return handler;
                    }
                }
                throw new Error("No job handler supported.");
            };
            var jobFactory = new JobHandlerFactory();
            return jobFactory.createJobHandler();
        })();

        /**
         * @static
         * @function createAllResolveFunction
         * @param {object} alreadyCalled
         * @param {number} index
         * @param {any[]} values
         * @param {PromiseCapability} capabilities
         * @param {object} remainingElements
         * @returns {function} - Promise.all resolve Function
         * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-promise.all-resolve-element-functions}
         */
        function createAllResolveFunction(alreadyCalled, index, values, capabilities, remainingElements) {
            var f = function (x) {
                var alreadyCalled = f._alreadyCalled;
                if (alreadyCalled._value)
                    return undefined;
                alreadyCalled._value = true;
                var index = f._index;
                var values = f._values;
                var promiseCapability = f._capabilities;
                var remainingElementsCount = f._remainingElements;
                values[index] = x;
                remainingElementsCount._value = remainingElementsCount._value - 1;
                if (remainingElementsCount._value == 0)
                    return promiseCapability._resolve(values);
                return undefined;
            };
            f._alreadyCalled = alreadyCalled;
            f._index = index;
            f._values = values;
            f._capabilities = capabilities;
            f._remainingElements = remainingElements;
            return f;
        }

        /**
         * @static
         * @function createRejectFunction
         * @param {Promise} promise
         * @param {object} alreadyResolved
         * @returns {function} - reject function
         * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-promise-reject-functions}
         */
        function createRejectFunction(promise, alreadyResolved) {
            var f = function (reason) {
                var promise = f._promise;
                var alreadyResolved = f._alreadyResolved;
                if (alreadyResolved._value)
                    return undefined;
                alreadyResolved._value = true;
                return rejectPromise(promise, reason);
            };
            f._promise = promise;
            f._alreadyResolved = alreadyResolved;
            return f;
        }

        /**
         * @static
         * @function createResolveFunction
         * @param {Promise} promise
         * @param {object} alreadyResolved
         * @returns {function} - resolveFunction
         * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-promise-resolve-functions}
         */
        function createResolveFunction(promise, alreadyResolved) {
            var f = function (resolution) {
                var promise = f._promise;
                var alreadyResolved = f._alreadyResolved;
                if (alreadyResolved._value)
                    return undefined;
                alreadyResolved._value = true;
                if (resolution === promise) {
                    return rejectPromise(promise, new TypeError());
                }
                if ("object" !== typeof resolution) {
                    return fulfillPromise(promise, resolution);
                }
                var then;
                try {
                    then = resolution.then;
                } catch (ex) {
                    return rejectPromise(promise, then);
                }
                if (!isCallable(then)) {
                    return fulfillPromise(promise, resolution);
                }
                jobHandler.enqueue("PromiseJobs", promiseResolveThenableJob, [promise, resolution, then]);
                return undefined;
            };
            f._promise = promise;
            f._alreadyResolved = alreadyResolved;
            return f;
        }

        /**
         * @static
         * @function createResolvingFunctions
         * @param {Promise} promise
         * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-createresolvingfunctions}
         */
        function createResolvingFunctions(promise) {
            var alreadyResolved = { _value: false };
            var resolve = createResolveFunction(promise, alreadyResolved);
            var reject = createRejectFunction(promise, alreadyResolved);
            return { _resolve: resolve, _reject: reject };
        }

        /**
         * @static
         * @function fulfillPromise
         * @param {Promise} promise
         * @param {any} value
         * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-fulfillpromise}
         */
        function fulfillPromise(promise, value) {
            var reactions = promise._promiseFulfillReactions;
            promise._promiseResult = value;
            promise._promiseFulfillReactions = undefined;
            promise._promiseRejectReactions = undefined;
            promise._promiseState = enuPromiseState.fulfilled;
            return triggerPromiseReactions(reactions, value);
        }

        /**
         * @static
         * @function getCapabilitiesExecutor
         * @param {PromiseCapability} capability
         * @returns {function} executor
         * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-getcapabilitiesexecutor-functions}
         */
        function getCapabilitiesExecutor(capability) {
            function f(resolve, reject) {
                var promiseCapability = f._capability;
                if (promiseCapability instanceof PromiseCapability) {
                    if ("undefined" !== typeof promiseCapability._resolve)
                        throw new TypeError();
                    if ("undefined" !== typeof promiseCapability._reject)
                        throw new TypeError();
                    promiseCapability._resolve = resolve;
                    promiseCapability._reject = reject;
                }
            }

            f._capability = capability;
            return f;
        }

        /**
         * @static
         * @function ifAbruptRejectPromise
         * @param {function} value
         * @param {PromiseCapability} capability
         * @returns {any}
         * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-ifabruptrejectpromise}
         */
        function ifAbruptRejectPromise(value, capability) {
            try {
                value();
            } catch (ex) {
                try {
                    var rejectResult = capability._reject.call(undefined, ex);
                    return rejectResult;
                } catch (ex2) {
                    return capability._promise;
                }
            }
        }

        /**
         * @function isCallable
         * @static
         * @param {object} argument
         * @returns {boolean}
         * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-iscallable}
         */
        function isCallable(argument) {
            return argument !== null && "function" === typeof argument;
        }

        /**
         * The abstract operation IsPromise checks for the promise brand on an object.
         * @function isPromise
         * @static
         * @param {object} x
         * @returns {boolean}
         * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-ispromise}
         */
        function isPromise(x) {
            return x !== null && "object" === typeof x && "undefined" !== x._promiseState;
        }

        /**
         * @static
         * @function newPromiseCapability
         * @param {Promise} c
         * @returns {PromiseCapability}
         * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-newpromisecapability}
         */
        function newPromiseCapability(c) {
            var promiseCapability = new PromiseCapability();
            var executor = getCapabilitiesExecutor(promiseCapability);
            var promise = new c(executor);
            if (!isCallable(promiseCapability._resolve))
                throw new TypeError();
            if (!isCallable(promiseCapability._reject))
                throw new TypeError();
            promiseCapability._promise = promise;
            return promiseCapability;
        }

        /**
         * @static
         * @function performPromiseAll
         * @param {IteratorRecord} iteratorRecord
         * @param {Promise} constructor
         * @param {PromiseCapability} resultCapability
         * @returns {Promise}
         * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-performpromiseall}
         */
        function performPromiseAll(iteratorRecord, constructor, resultCapability) {
            var values = [];
            var remainingElementCount = { _value: 1 };
            var index = 0;
            while (iteratorRecord._iterator.next()) {
                var nextValue = iteratorRecord._iterator.getCurrent();
                values.push(undefined);
                var nextPromise = constructor.resolve(nextValue);
                var resolveElement = createAllResolveFunction({ _value: false }, index, values, resultCapability, remainingElementCount);
                remainingElementCount._value = remainingElementCount._value + 1;
                var result = nextPromise.then(resolveElement, resultCapability._reject);
                index = index + 1;
            }
            iteratorRecord._done = true;
            remainingElementCount._value = remainingElementCount._value - 1;
            if (remainingElementCount._value === 0) {
                resultCapability._resolve.call(undefined, values);
            }
            return resultCapability._promise;
        }

        /**
         * @static
         * @function performPromiseRace
         * @param {IteratorRecord} iteratorRecord
         * @param {PromiseCapability} promiseCapability
         * @param {Promise} c
         * @returns {Promise}
         */
        function performPromiseRace(iteratorRecord, promiseCapability, c) {
            while (iteratorRecord._iterator.next()) {
                var nextValue = iteratorRecord._iterator.getCurrent();
                var nextPromise = c.resolve(nextValue);
                nextPromise.then(promiseCapability._resolve, promiseCapability._reject);
            }
            iteratorRecord._done = true;
            return promiseCapability._promise;
        }

        /**
         * The abstract operation PerformPromiseThen performs the "then" operation on promise using onFulfilled and onRejected as its settlement actions
         * @static
         * @function performPromiseThen
         * @param {Promise} promise
         * @param {function} onFulfilled
         * @param {function} onRejected
         * @param {PromiseCapability} resultCapability
         * @returns {Promise} - resultCapability's promise
         * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-performpromisethen}
         */
        function performPromiseThen(promise, onFulfilled, onRejected, resultCapability) {
            if (!isCallable(onFulfilled))
                onFulfilled = enuReactionHandler.identity;
            if (!isCallable(onRejected))
                onRejected = enuReactionHandler.thrower;

            var fulfillReaction = new PromiseReaction(resultCapability, onFulfilled);
            var rejectReaction = new PromiseReaction(resultCapability, onRejected);

            if (promise._promiseState === enuPromiseState.pending) {
                promise._promiseFulfillReactions.push(fulfillReaction);
                promise._promiseRejectReactions.push(rejectReaction);

            } else if (promise._promiseState === enuPromiseState.fulfilled) {
                var value = promise._promiseResult;
                jobHandler.enqueue("PromiseJobs", promiseReactionJob, [fulfillReaction, value]);

            } else if (promise._promiseState === enuPromiseState.rejected) {
                var reason = promise._promiseResult;
                jobHandler.enqueue("PromiseJobs", promiseReactionJob, [rejectReaction, reason]);
            }
            return resultCapability._promise;
        }

        /**
         * @static
         * @function promiseReactionJob
         * @param {PromiseReaction} reaction
         * @param {any} argument
         * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-promisereactionjob}
         */
        function promiseReactionJob(reaction, argument) {
            if (reaction instanceof PromiseReaction) {
                var promiseCapability = reaction._capabilities;
                var handler = reaction._handler;
                var handlerResult = null;
                var status = null;
                try {
                    if (handler === enuReactionHandler.identity) {
                        handlerResult = argument;
                    } else {
                        handlerResult = handler.call(undefined, argument);
                    }
                    status = promiseCapability._resolve(handlerResult);
                } catch (ex) {
                    status = promiseCapability._reject.call(undefined, ex);
                }
            }
        }

        /**
         * @static
         * @function promiseResolveThenableJob
         * @param {Promise} promiseToResolve
         * @param {object} thenable
         * @param {function} then
         * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-promiseresolvethenablejob}
         */
        function promiseResolveThenableJob(promiseToResolve, thenable, then) {
            var resolvingFunctions = createResolvingFunctions(promiseToResolve);
            try {
                var thenCallResult = then.call(thenable, resolvingFunctions._resolve, resolvingFunctions._reject);
            } catch (ex) {
                var status = resolvingFunctions._reject.call(undefined, thenCallResult);
            }
        }

        /**
         * @static
         * @function rejectPromise
         * @param {Promise} promise
         * @param {any} reason
         * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-rejectpromise}
         */
        function rejectPromise(promise, reason) {
            var reactions = promise._promiseRejectReactions;
            promise._promiseResult = reason;
            promise._promiseFulfillReactions = undefined;
            promise._promiseRejectReactions = undefined;
            promise._promiseState = enuPromiseState.rejected;
            return triggerPromiseReactions(reactions, reason);
        }

        /**
         * @static
         * @function triggerPromiseReactions
         * @param {function[]} reactions
         * @param {any} argument
         * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-triggerpromisereactions}
         */
        function triggerPromiseReactions(reactions, argument) {
            for (var i = 0, length = reactions.length; i < length; i++) {
                jobHandler.enqueue("PromiseJobs", promiseReactionJob, [reactions[i], argument]);
            }
            return undefined;
        }

        /**
         * The Promise object is used for deferred and asynchronous computations.
         * A Promise represents an operation that hasn't completed yet, but is expected in the future.
         * @class Promise
         * @returns {function} executor - Function object with two arguments resolve and reject.
         * @example new Promise(function(resolve, reject) { ... });
         * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-promise-executor}
         */
        function Promise(executor) {
            if ("function" !== typeof executor)
                throw new TypeError("Promise resolver must be function");
            this._promiseState = enuPromiseState.pending;
            this._promiseResult = undefined;
            this._promiseFulfillReactions = [];
            this._promiseRejectReactions = [];

            var resolvingFunctions = createResolvingFunctions(this);
            try {
                var completion = executor.call(undefined, resolvingFunctions._resolve, resolvingFunctions._reject);
            } catch (ex) {
                var status = resolvingFunctions._reject.call(undefined, completion);
            }
        }

        /**
         * @function catch
         * @param {function} onRejected
         * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-promise.prototype.catch}
         */
        Promise.prototype["catch"] = function (onRejected) {
            return Promise.prototype.then.call(this, null, onRejected);
        };

        /**
         * @function then
         * @param {function} onFulfilled
         * @param {function} onRejected
         * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-promise.prototype.then}
         */
        Promise.prototype.then = function (onFulfilled, onRejected) {
            var promise = this;
            if (!isPromise(promise))
                throw new TypeError("Invalid operation on a promise function");
            var c = promise.constructor;
            var resultCapability = newPromiseCapability(c);
            return performPromiseThen(promise, onFulfilled, onRejected, resultCapability);
        };

        /**
         * @static
         * @function Promise.all
         * @param {function[]} iterable
         * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-promise.all}
         */
        Promise.all = function (iterable) {
            var c = this;
            var result;
            var iterator;
            var abruptResult;

            var promiseCapability = newPromiseCapability(c);
            if (abruptResult = ifAbruptRejectPromise(function () {
                iterator = new Iterator(iterable);
            }, promiseCapability)) {
                return abruptResult;
            }
            var iteratorRecord = new IteratorRecord(iterator);
            if (abruptResult = ifAbruptRejectPromise(function () {
                result = performPromiseAll(iteratorRecord, c, promiseCapability);
            }, promiseCapability)) {
                return abruptResult;
            }
            return result;
        };

        /**
         * The race function returns a new promise which is settled in the same way as the first passed promise to settle.
         * It resolves all elements of the passed iterable to promises as it runs this algorithm.
         * @static
         * @function Promise.race
         * @param {function[]} iterable
         * @returns {Promise}
         * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-promise.race}
         */
        Promise.race = function (iterable) {
            var c = this;
            var result;
            var iterator;
            var abruptResult;

            var promiseCapability = newPromiseCapability(c);
            if (abruptResult = ifAbruptRejectPromise(function () {
                iterator = new Iterator(iterable);
            }, promiseCapability)) {
                return abruptResult;
            }
            var iteratorRecord = new IteratorRecord(iterator);
            if (abruptResult = ifAbruptRejectPromise(function () {
                result = performPromiseRace(iteratorRecord, promiseCapability, c);
            }, promiseCapability)) {
                return abruptResult;
            }
            return result;
        };

        /**
         * The reject function returns a new promise rejected with the passed argument.
         * @static
         * @function Promise.reject
         * @param {any} reason
         * @returns {Promise}
         * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-promise.reject}
         */
        Promise.reject = function (reason) {
            var c = this;
            var promiseCapability = newPromiseCapability(c);
            var rejectResult = promiseCapability._reject.call(undefined, r);
            return promiseCapability._promise;
        };

        /**
         * The resolve function returns either a new promise resolved with the passed argument, or the argument itself if the argument is a promise produced by this constructor.
         * @static
         * @function Promise.resolve
         * @param {Promise} x
         * @returns {Promise}
         * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-promise.resolve}
         */
        Promise.resolve = function (x) {
            var c = this;
            if (isPromise(x)) {
                var xConstructor = x.constructor;
                if (c === xConstructor)
                    return x;
            }
            var promiseCapability = newPromiseCapability(c);
            var resolveResult = promiseCapability._resolve.call(undefined, x);
            return promiseCapability._promise;
        };

        return Promise;
    })();

    if (global.debugPromise)
        global.PromisePolyfill = Promise;
    if ("undefined" === typeof global.Promise)
        global.Promise = Promise;
})(window);

redpajama_set_name: RedPajamaGithub


text:
## Licensed to the Apache Software Foundation (ASF) under one
## or more contributor license agreements.  See the NOTICE file
## distributed with this work for additional information
## regarding copyright ownership.  The ASF licenses this file
## to you 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.

function CreateHealthServicesFromWatcherNodesList($discoveryData, $watcherNodes) {
    $healthServices = @()
    foreach ($watcherNodeName in $WatcherNodes.Split(';', [StringSplitOptions]::RemoveEmptyEntries)) {
        $healthServices += CreateHealthService $discoveryData $watcherNodeName
    }
    return ,$healthServices
}

function CreateHealthService($discoveryData, $computerName) {
    $healthService = $discoveryData.CreateClassInstance("$MPElement[Name="SC!Microsoft.SystemCenter.HealthService"]$")
    $healthService.AddProperty("$MPElement[Name="Windows!Microsoft.Windows.Computer"]/PrincipalName$", $computerName)
    $healthService
}

function AddManagementRelationship($discoveryData, $healthServices, [string]$targetName, $target) {
    $relationship = $discoveryData.CreateRelationshipInstance("$MPElement[Name="SC!Microsoft.SystemCenter.HealthServiceShouldManageEntity"]$")
    $relationship.Source = $healthServices[(GetHash $targetName) % $healthServices.Count]
    $relationship.Target = $target
    $discoveryData.AddInstance($relationship)
}

# TODO: Concider replacing this with MurMur-based consistent hashing?
# For instance, based on few runs - this provides better distribution, then standard GetHashCode(), and do we care about consistency at all?
function GetHash([Char[]]$s) { # Linear Congruential Generator
    $s+([UInt64]$r=0)|%{$r=($r*[UInt32]0x8EF6E7+$_-band[UInt32]::MaxValue)%0x7FFFFFFF};$r
}


text:
require 'test_helper'

class Evergreen::PasswordsControllerTest < ActionController::TestCase
  context "on GET to new" do
    setup { get :new }

    should_respond_with :success
    should_render_template :new
    should_not_set_the_flash
    should_render_a_form
    should_not_have_missing_translations
  end

  context "on GET to edit with valid email and token" do
    setup do
      @user = Factory :user
      @user.forgot_password!
      get :edit, :user_id => @user.id, :token => @user.token
    end

    should_respond_with :success
    should_render_template :edit
    should_assign_to(:user) { @user }
    should_not_set_the_flash
    should_render_a_form
    should_not_have_missing_translations
  end

  context "on POST to create with valid email" do
    setup do
      @user = Factory :user
      User.any_instance.expects(:forgot_password!)
      post :create, :email => @user.email
    end

    should_respond_with :redirect
    should_assign_to(:user) { @user }
    should_set_the_flash_to I18n.t('evergreen.passwords.create.success')

    should "sent email" do
      assert_sent_email
    end
  end

  context "on POST to create with unknown email" do
    setup do
      post :create, :email => 'unknown@example.com'
    end

    before_should "not generate password token" do
      User.any_instance.expects(:forgot_password!).never
    end

    before_should "not send email" do
      ::AuthMailer.expects(:deliver_password_change).never
    end

    should_respond_with :success
    should_render_template :new
    should_set_the_flash_to I18n.t('evergreen.passwords.create.invalid_email')
    should_not_have_missing_translations
  end

  context "on POST to update with valid passwords" do
    setup do
      @user = Factory :user
      @user.forgot_password!
      User.any_instance.stubs(:set_new_password).returns(true)
      put :update, :user_id => @user.id, :token => @user.token, :user => {}
    end

    should_respond_with :redirect
    should_assign_to(:user) { @user }
    should_set_the_flash_to I18n.t('evergreen.passwords.update.success')
  end

  context "on POST to update with non matching passwords" do
    setup do
      @user = Factory :user
      @user.forgot_password!
      User.any_instance.stubs(:set_new_password).returns(false)
      put :update, :user_id => @user.id, :token => @user.token, :user => {}
    end

    should_respond_with :success
    should_assign_to(:user) { @user }
    should_render_template :edit
    should_not_have_missing_translations
  end
end


text:
package org.yeastrc.xlink.www.qc_plots.scan_retention_time;

/**
 *
 *
 */
public class ScanRetentionTimeJSONChartBucket {

	private int binStart;
	private int binEnd;
	private double binCenter;
	private int totalCount;
	private int countForPsmsThatMeetCriteria;

	public int getBinStart() {
		return binStart;
	}
	public void setBinStart(int binStart) {
		this.binStart = binStart;
	}
	public int getBinEnd() {
		return binEnd;
	}
	public void setBinEnd(int binEnd) {
		this.binEnd = binEnd;
	}
	public double getBinCenter() {
		return binCenter;
	}
	public void setBinCenter(double binCenter) {
		this.binCenter = binCenter;
	}
	public int getTotalCount() {
		return totalCount;
	}
	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}
	public int getCountForPsmsThatMeetCriteria() {
		return countForPsmsThatMeetCriteria;
	}
	public void setCountForPsmsThatMeetCriteria(int countForPsmsThatMeetCriteria) {
		this.countForPsmsThatMeetCriteria = countForPsmsThatMeetCriteria;
	}
}


text:
$(document).ready(function(){

// responsive navigation js for 768px
var wid = $(window).width();

//  navigation start

$(".nav li").click(function(e){
	e.preventDefault();
	if($(this).hasClass('active'))
	{
		$(this).removeClass('active');
		$(this).children("ul").slideUp();
	}
	else
	{
		$(".nav li").removeClass('active');
		$(this).addClass('active');
		$(".nav li ul").slideUp();
		$(this).children("ul").slideDown();
	}
	$(".container").css("min-height","650px")
});

$(".nav li ul li a").click(function(e){
	$(".nav li ul li a").removeClass('this');
	$(this).toggleClass('this');
	e.stopPropagation();
});
//  navigation end

// user area box
$(".user-area .box").click(function(){
	$('.info').slideToggle('fast');

});

$(".info a").click(function(e){
	e.stopPropagation();

});

// datepicker
   $(function() {
        $( "#datepicker, #datepicker2" ).datepicker({
		defaultDate: +7,
		showOtherMonths:true,
		autoSize: true,
		appendText: '(dd-mm-yyyy)',
		dateFormat: 'dd-mm-yy'
	});
    });

// ----------------tabs	--------------

$('.tabcontent').hide();
$('.tabcontent:first').show();
$('.tabs a:first').addClass('active');

$(".tabs a").click(function(){
	$(".tabs a").removeClass('active');
	$(this).addClass('active');
	var id = $(this).attr('href');
	$('.tabcontent').hide();
	$(id).show();
	return false;
});

// ----------------add more category start-------------
var $addcat = {
add : function(){
 $(".addcatBtn").click(function(){
	//alert("gi");
	$(this).closest('div').find('input').show();
	$(this).closest('div').find('span').show();
	$("input.addInLast").hide();
	$(this).hide();

});
},
remove : function(){
 $(".addMore .cancel").click(function(){
	$(this).closest('div').find('input').hide();
	$(this).closest('div').find('a').show();
	$("input.addInLast").show();
	$(this).hide();

});
}
}
$addcat.add();
$addcat.remove();
// ----------------add more category end-------------

});


text:
const { bar } = require('./objects.js');
console.log(bar, '!');


text:
Only generated the system module in C# generators.
Fixed missing save of generated module template to outputs.
Fixed code generator to generate the system module even in single file per unit mode.
Silenced verbose duplicate constructor and operator warnings.
Improved the defaults of necessary generation options to improve accessibility.
Called the parser setup code in CLI.
Only included header files when scanning directories in CLI.


text:
var fun   = require('../../../uki-core/function'),
    utils = require('../../../uki-core/utils'),
    view  = require('../../../uki-core/view'),
    dom   = require('../../../uki-core/dom'),

    Mustache = require('../../../uki-core/mustache').Mustache,
    Base     = require('../../../uki-core/view/base').Base;

var Pack = view.newClass('dataList.Pack', Base, {

    template: fun.newProp('template'),

    formatter: fun.newProp('formatter'),

    key: fun.newProp('key'),

    render: function(rows, selectedInPack, globalIndex) {
        this._dom.innerHTML = this._toHTML(rows, globalIndex);
        this._restorePackSelection(selectedInPack || [], globalIndex);
    },

    updateRow: function(index, rows, globalIndex) {
        var tmp = dom.createElement('div', {
            html: this._toHTML(rows, globalIndex)
        });
        var item = this._rowAt(index);
        item.parentNode.replaceChild(tmp.childNodes[0], item);
    },

    setSelected: function(index, state) {
        if (this.dom()) {
            var row = this._rowAt(index);
            if (row) {
                dom.toggleClass(row, 'uki-dataList-row_selected', state);
            }
        }
    },

    _toHTML: function(rows, globalIndex) {
        var formated = utils.map(rows, function(r, i) {
            i = i + globalIndex;
            return {
                value: this._formatRow(r, i),
                row: r,
                index: i,
                even: i & 1
            };
        }, this);

        return Mustache.to_html(
            this.template(), { rows: formated }
        );
    },

    _formatRow: function(row, index) {
        return this.formatter()(
            this.key() ? utils.prop(row, this.key()) : row,
            row,
            index);
    },

    _createDom: function(initArgs) {
        this._dom = dom.createElement('ul', {
            className: 'uki-dataList-pack'
        });
    },

    _restorePackSelection: function(selectedInPack, globalIndex) {
        for (var i = selectedInPack.length - 1; i >= 0; i--){
            this.setSelected(selectedInPack[i] - globalIndex, true);
        };
    },

    _rowAt: function(index) {
        return this.dom().childNodes[index];
    }

});

exports.Pack = Pack;


text:
package net.collaud.fablab.manager.data.virtual;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import net.collaud.fablab.manager.data.type.HistoryEntryType;

/**
 *
 * @author Gaetan Collaud <gaetancollaud@gmail.com>
 */
@Getter
@Setter
@EqualsAndHashCode(of = {"id", "type"})
public class HistoryEntryId {

	private Long id;
	private HistoryEntryType type;

}


text:
OpenMV is an open-source tiny machine vision module based on the STM32F4xx ARM Cortex-M4 MCU and the OV2640 JPEG sensor.

OpenMV is programmable in Python3 (MicroPython) and capable of doing face detection and tracking, keypoint extraction, color tracking and more..The board has USB, a uSD connector and an expansion header (USART/SPI/I2C).

A Python IDE with syntax highlighting is available for the camera, it can run/upload scripts to the camera, view the framebuffer and update the firmware.

**This is a video of the color tracking:**

**This is a video of the face detection:**

For more information, please visit my [blog](http://sigalrm.blogspot.com/search/label/OpenMV)


text:
#ifndef MIDIInput_h
#define MIDIInput_h

#include "modules/EventTargetModules.h"
#include "modules/webmidi/MIDIAccessor.h"
#include "modules/webmidi/MIDIPort.h"

namespace blink {

class MIDIAccess;

class MIDIInput final : public MIDIPort {
    DEFINE_WRAPPERTYPEINFO();
public:
    static MIDIInput* create(MIDIAccess*, const String& id, const String& manufacturer, const String& name, const String& version, MIDIAccessor::MIDIPortState);
    ~MIDIInput() override { }

    EventListener* onmidimessage();
    void setOnmidimessage(PassRefPtrWillBeRawPtr<EventListener>);

    // EventTarget
    const AtomicString& interfaceName() const override { return EventTargetNames::MIDIInput; }

    // |timeStamp| is a DOMHighResTimeStamp in the time coordinate system of performance.now().
    void didReceiveMIDIData(unsigned portIndex, const unsigned char* data, size_t length, double timeStamp);

    DECLARE_VIRTUAL_TRACE();

protected:
    bool addEventListenerInternal(const AtomicString& eventType, PassRefPtrWillBeRawPtr<EventListener>, const EventListenerOptions&) override;

private:
    MIDIInput(MIDIAccess*, const String& id, const String& manufacturer, const String& name, const String& version, MIDIAccessor::MIDIPortState);
};

} // namespace blink

#endif // MIDIInput_h


text:
package com.mimaraslan;

public class Ogrenci {

	private Integer yasi;
	private String adi, soyadi;
	// ---------------------------
	public void setYasi(Integer yasi) {
		this.yasi = yasi;
	}
	public Integer getYasi() {
		return yasi;
	}
	// ---------------------------
	public void setAdi(String adi) {
		this.adi = adi;
	}
	public String getAdi() {
		return adi;
	}
	// ---------------------------
	public void setSoyadi(String soyadi) {
		this.soyadi = soyadi;
	}
	public String getSoyadi() {
		return soyadi;
	}

}


text:
import nnabla.functions as F

def scatter_nd_backward(grad_inputs, inputs, input_shapes, outputs, output_shapes, shape, add):
    """
    Args:
      grad_inputs (list of :obj:`nnabla.Variable`): Propagated grads to this backward function.
      inputs (list of :obj:`nnabla.Variable` and None): Input Variables of the forward function
          if this backward function depends on it. Otherwise, None is set instead.
      input_shapes (list of tuple of :obj:`int`): Input shapes of the forward function.
          The shapes of the inputs in which None is set can be passed.
      outputs (list of :obj:`nnabla.Variable` and None): Output Variables of the forward function
          if this backward function depends on it. Otherwise, None is set instead.
      output_shapes (list of tuple of :obj:`int`): Output shapes of the forward function.
          The shapes of the outputs in which None is set can be passed.
      kwargs (dict of arguments): Dictionary of the corresponding function arguments.

    Return:
      list of Variable: Return the gradients wrt inputs of the corresponding function.
    """
    dy = grad_inputs[0]
    _ = inputs[0]
    idx = inputs[1]
    dx0 = F.gather_nd(dy, idx)
    return dx0, None


text:
Aerospike::queryRole - Query a given user defined role in a security-enabled Aerospike database

## Description

```
public int queryRole ( string $role, array &$privileges [, array $options ] )
```

**Aerospike::queryRole()** will query  a user defined role.

## Parameters

**role** string rolename.

**privileges** an array of privileges possessed by the role.

**[options](aerospike.md)** including
- **Aerospike::OPT_WRITE_TIMEOUT**

## Return Values

Returns an integer status code.  Compare to the Aerospike class status
constants.  When non-zero the **Aerospike::error()** and
**Aerospike::errorno()** methods can be used.

## Example

```php
<?php

$config = ["hosts" => [["addr"=>"localhost", "port"=>3000]],
           "shm"=>[],
           "user"=>"admin", "pass"=>"admin"];
$client = new Aerospike($config, true);
if (!$client->isConnected()) {
   echo "Aerospike failed to connect[{$client->errorno()} {$client->error()}";
   exit(1);
}

$res = $client->grantPrivileges("example_role", [["code": Aerospike::PRIV_READ]]);
if ($res == Aerospike::OK) {
    echo "read privileges successfully granted to role";
    $res = $client->queryRole("example_role", $privileges);
    if ($res == Aerospike::OK) {
        var_dump($privileges);
    } else {
        echo "[{$client->errorno()}] ".$client->error();
    }
} else {
    echo "[{$client->errorno()}] ".$client->error();
}

?>
```

We expect to see:

```
read privileges successfully granted to role
array(2) {
  [0]=>
  array(3) {
    ["ns"]=>
    string(0) ""
    ["set"]=>
    string(0) ""
    ["code"]=>
    int(10)
  }
  [1]=>
  array(3) {
    ["ns"]=>
    string(4) "test"
    ["set"]=>
    string(4) "demo"
    ["code"]=>
    int(11)
  }
}
```


text:
/*
 *
 *  Blockstrap v0.6.0.1
 *  http://blockstrap.com
 *
 *  Designed, Developed and Maintained by Neuroware.io Inc
 *  All Work Released Under MIT License
 *
 */

(function($)
{
    var data = {};

    data.find = function(collection, key, callback)
    {
        if(localStorage && localStorage.getItem(data.item(collection, key)))
        {
            var obj = localStorage.getItem(data.item(collection, key));
            if(blockstrap_functions.json(obj)) obj = $.parseJSON(obj);
            callback(obj);
        }
        else
        {
            callback(false);
        }
    };

    data.item = function(collection, key)
    {
        return 'nw_' + collection + '_' + key;
    };

    data.option = function(key)
    {
        var value = false;
        var options = localStorage.getItem('nw_blockstrap_options');
        if(blockstrap_functions.json(options)) options = $.parseJSON(options);
        if(options)
        {
            $.each(options, function(k, v)
            {
                if(k == key) value = v;
            });
        }
        return value
    }

    data.save = function(collection, key, value, callback)
    {
        if(localStorage)
        {
            var simple = false;
            if(value === 'true' || value === 'false') simple = true;
            if(value === 'true') value = true;
            else if(value === 'false') value = false;
            var results = JSON.stringify(value);
            if(simple === true) results = value;
            localStorage.setItem(data.item(collection, key), results);
            callback(value);
        }
        else
        {
            callback(false);
        }
    };

    // MERGE THE NEW FUNCTIONS WITH CORE
    $.extend(true, $.fn.blockstrap, {data:data});
})
(jQuery);


text:
import Element from './Element';
import Dialog from './Dialog';

/**
 * Creates dialog (modal) elements
 * @type {Dialog}
 * @param {String}      title   title for the element
 * @param {String}      id      editor ID to associate with the element
 */
export default class LinkDialog extends Dialog {
  constructor(id) {
    super(id, 'Link Dialog');

    this.form = new Element('form', {
      id: `${id}-link-form`,
      title: 'Link Form',
    })
      .appendToElement(this);

    this.urlInput = new Element('input', {
      type: 'text',
      name: `${id}-link-url-input`,
      placeholder: 'http://url.com',
      title: 'Link Url',
    })
      .addClass('link-url-input');

    this.nameInput = new Element('input', {
      type: 'text',
      name: `${id}-link-display-input`,
      placeholder: 'Display text',
      title: 'Link Display',
    })
      .addClass('link-display-input');

    this.insertButton = new Element('button', {
      type: 'submit',
      textContent: 'Insert',
      title: 'Insert Link',
    })
      .addClass('insert-link');

    this.form.appendElements([
      this.urlInput,
      this.nameInput,
      this.insertButton,
    ]);
  }
}


text:
..
 This work is licensed under a Creative Commons Attribution 3.0 Unported
 License.

 http://creativecommons.org/licenses/by/3.0/legalcode

=================================
Grenade Upgrade Testing - Phase 1
=================================

https://blueprints.launchpad.net/ceilometer/+spec/grenade-upgrade-testing

Integrated projects are required to participate in the `grenade`_ upgrade
testing harness. Ceilometer was integrated before these requirements were
added but the requirements apply retroactively. Therefore, ceilometer must be
added to the harness.

.. _grenade: https://github.com/openstack-dev/grenade

Problem description
===================

Testing with grenade involves:

* Installing a basic DevStack of the old version, confirming it
  with smoke and scenario `tempest`_ tests.
* Establishing a javelin project which makes assertions about
  resources in the project.
* Shutting down the original installation, upgrading to the new
  version of the code but not configuration, applying the relevant
  database migrations to update the schema, and repeating the
  `tempest`_ tests.
* Testing the javelin project again to assert the integrity of
  resources across the upgrade.

This document considers the upgrade and `tempest`_ testing but not the javelin
testing. Javelin will be addressed in another (forthcoming) document.

Prior to the Juno cycle ceilometer was neither a default service in DevStack
nor enabled in tempest. The relevant configuration must be changed to allow
testing in Grenade.

.. _tempest: https://github.com/openstack/tempest

Proposed change
===============

Enable ceilometer in Grenade (see Work Items for details).

Alternatives
------------

Given the commitment to Grenade and the project graduation requirements, this
is the way to go.

Data model impact
-----------------

None.

REST API impact
---------------

None.

Security impact
---------------

None.

Pipeline impact
---------------

None.

Other end user impact
---------------------

These changes will mean a more positive upgrade experience for end users.

Performance/Scalability Impacts
-------------------------------

There have been concerns that running ceilometer in the gate will negatively
impact performance there. This had been true but recent changes in the
sqlalchemy driver and database schema have shown enough improvement that
ceilometer can be turned on.

Other deployer impact
---------------------

None

Developer impact
----------------

Active testing will mean the discovery of bugs that someone will have to fix.

Implementation
==============

Assignee(s)
-----------

Who is leading the writing of the code? Or is this a blueprint where you're
throwing it out there to see who picks it up?

If more than one person is working on the implementation, please designate the
primary author and contact.

Primary assignee:
  emilienm

Other contributors:
  vrovachev
  dbelova

Ongoing maintainer:
  chdent

Work Items
----------

* Add upgrade calls to ``grenade.sh``.
* Add ceilometer upgrade scripts to grenade.
* Add ceilometer directories to grenade cleanup procedures.
* Ensure ceilometer data dumped between upgrades.

Note: These work items are captured in a `pending patchset`_

.. _pending patchset: https://review.openstack.org/#/c/94468/

Future lifecycle
================

As/when ceilometer expands to include additional services, it will be necessary
to adjust devstack and grenade to manage (stop, start, cleanup) those services.

Dependencies
============

Other than those listed above, no additional dependencies.

Testing
=======

These changes improve testing and will be validated there.

Documentation Impact
====================

None.

References
==========

None.


text:
package config

import (
	"time"

	"github.com/brocaar/chirpstack-api/go/v3/nc"
	"github.com/brocaar/lorawan"
	"github.com/brocaar/lorawan/band"
)

// Version defines the ChirpStack Network Server version.
var Version string

// Config defines the configuration structure.
type Config struct {
	General struct {
		LogLevel                  int    `mapstructure:"log_level"`
		LogToSyslog               bool   `mapstructure:"log_to_syslog"`
		GRPCDefaultResolverScheme string `mapstructure:"grpc_default_resolver_scheme"`
	} `mapstructure:"general"`

	PostgreSQL struct {
		DSN                string `mapstructure:"dsn"`
		Automigrate        bool   `mapstructure:"automigrate"`
		MaxOpenConnections int    `mapstructure:"max_open_connections"`
		MaxIdleConnections int    `mapstructure:"max_idle_connections"`
	} `mapstructure:"postgresql"`

	Redis struct {
		URL        string   `mapstructure:"url"` // deprecated
		Servers    []string `mapstructure:"servers"`
		Cluster    bool     `mapstructure:"cluster"`
		MasterName string   `mapstructure:"master_name"`
		PoolSize   int      `mapstructure:"pool_size"`
		Password   string   `mapstructure:"password"`
		Database   int      `mapstructure:"database"`
		TLSEnabled bool     `mapstructure:"tls_enabled"`
		KeyPrefix  string   `mapstructure:"key_prefix"`
	} `mapstructure:"redis"`

	NetworkServer struct {
		NetID                lorawan.NetID
		NetIDString          string        `mapstructure:"net_id"`
		DeduplicationDelay   time.Duration `mapstructure:"deduplication_delay"`
		DeviceSessionTTL     time.Duration `mapstructure:"device_session_ttl"`
		GetDownlinkDataDelay time.Duration `mapstructure:"get_downlink_data_delay"`

		Band struct {
			Name                   band.Name `mapstructure:"name"`
			UplinkDwellTime400ms   bool      `mapstructure:"uplink_dwell_time_400ms"`
			DownlinkDwellTime400ms bool      `mapstructure:"downlink_dwell_time_400ms"`
			UplinkMaxEIRP          float32   `mapstructure:"uplink_max_eirp"`
			RepeaterCompatible     bool      `mapstructure:"repeater_compatible"`
		} `mapstructure:"band"`

		NetworkSettings struct {
			InstallationMargin      float64  `mapstructure:"installation_margin"`
			RXWindow                int      `mapstructure:"rx_window"`
			RX1Delay                int      `mapstructure:"rx1_delay"`
			RX1DROffset             int      `mapstructure:"rx1_dr_offset"`
			RX2DR                   int      `mapstructure:"rx2_dr"`
			RX2Frequency            int64    `mapstructure:"rx2_frequency"`
			RX2PreferOnRX1DRLt      int      `mapstructure:"rx2_prefer_on_rx1_dr_lt"`
			RX2PreferOnLinkBudget   bool     `mapstructure:"rx2_prefer_on_link_budget"`
			GatewayPreferMinMargin  float64  `mapstructure:"gateway_prefer_min_margin"`
			DownlinkTXPower         int      `mapstructure:"downlink_tx_power"`
			EnabledUplinkChannels   []int    `mapstructure:"enabled_uplink_channels"`
			DisableMACCommands      bool     `mapstructure:"disable_mac_commands"`
			DisableADR              bool     `mapstructure:"disable_adr"`
			MaxMACCommandErrorCount int      `mapstructure:"max_mac_command_error_count"`
			ADRPlugins              []string `mapstructure:"adr_plugins"`

			ExtraChannels []struct {
				Frequency uint32 `mapstructure:"frequency"`
				MinDR     int    `mapstructure:"min_dr"`
				MaxDR     int    `mapstructure:"max_dr"`
			} `mapstructure:"extra_channels"`

			ClassB struct {
				PingSlotDR        int    `mapstructure:"ping_slot_dr"`
				PingSlotFrequency uint32 `mapstructure:"ping_slot_frequency"`
			} `mapstructure:"class_b"`

			RejoinRequest struct {
				Enabled   bool `mapstructure:"enabled"`
				MaxCountN int  `mapstructure:"max_count_n"`
				MaxTimeN  int  `mapstructure:"max_time_n"`
			} `mapstructure:"rejoin_request"`
		} `mapstructure:"network_settings"`

		Scheduler struct {
			SchedulerInterval time.Duration `mapstructure:"scheduler_interval"`

			ClassC struct {
				GatewayDownlinkLockDuration time.Duration `mapstructure:"gateway_downlink_lock_duration"`
				DeviceDownlinkLockDuration  time.Duration `mapstructure:"device_downlink_lock_duration"`
				MulticastGatewayDelay       time.Duration `mapstructure:"multicast_gateway_delay"`
			} `mapstructure:"class_c"`
		} `mapstructure:"scheduler"`

		API struct {
			Bind    string `mapstructure:"bind"`
			CACert  string `mapstructure:"ca_cert"`
			TLSCert string `mapstructure:"tls_cert"`
			TLSKey  string `mapstructure:"tls_key"`
		} `mapstructure:"api"`

		Gateway struct {
			// Deprecated
			Stats struct {
				Timezone string
			}

			CACert             string        `mapstructure:"ca_cert"`
			CAKey              string        `mapstructure:"ca_key"`
			ClientCertLifetime time.Duration `mapstructure:"client_cert_lifetime"`
			DownlinkTimeout    time.Duration `mapstructure:"downlink_timeout"`

			ForceGwsPrivate bool `mapstructure:"force_gws_private"`

			Backend struct {
				Type                 string `mapstructure:"type"`
				MultiDownlinkFeature string `mapstructure:"multi_downlink_feature"`

				MQTT struct {
					Server               string        `mapstructure:"server"`
					Username             string        `mapstructure:"username"`
					Password             string        `mapstructure:"password"`
					MaxReconnectInterval time.Duration `mapstructure:"max_reconnect_interval"`
					QOS                  uint8         `mapstructure:"qos"`
					CleanSession         bool          `mapstructure:"clean_session"`
					ClientID             string        `mapstructure:"client_id"`
					CACert               string        `mapstructure:"ca_cert"`
					TLSCert              string        `mapstructure:"tls_cert"`
					TLSKey               string        `mapstructure:"tls_key"`

					EventTopic           string `mapstructure:"event_topic"`
					CommandTopicTemplate string `mapstructure:"command_topic_template"`
				} `mapstructure:"mqtt"`

				AMQP struct {
					URL                       string `mapstructure:"url"`
					EventQueueName            string `mapstructure:"event_queue_name"`
					EventRoutingKey           string `mapstructure:"event_routing_key"`
					CommandRoutingKeyTemplate string `mapstructure:"command_routing_key_template"`
				} `mapstructure:"amqp"`

				GCPPubSub struct {
					CredentialsFile         string        `mapstructure:"credentials_file"`
					ProjectID               string        `mapstructure:"project_id"`
					UplinkTopicName         string        `mapstructure:"uplink_topic_name"`
					DownlinkTopicName       string        `mapstructure:"downlink_topic_name"`
					UplinkRetentionDuration time.Duration `mapstructure:"uplink_retention_duration"`
				} `mapstructure:"gcp_pub_sub"`

				AzureIoTHub struct {
					EventsConnectionString   string `mapstructure:"events_connection_string"`
					CommandsConnectionString string `mapstructure:"commands_connection_string"`
				} `mapstructure:"azure_iot_hub"`
			} `mapstructure:"backend"`
		} `mapstructure:"gateway"`
	} `mapstructure:"network_server"`

	JoinServer struct {
		ResolveJoinEUI      bool   `mapstructure:"resolve_join_eui"`
		ResolveDomainSuffix string `mapstructure:"resolve_domain_suffix"`

		Servers []struct {
			Server       string        `mapstructure:"server"`
			JoinEUI      string        `mapstructure:"join_eui"`
			Async        bool          `mapstructure:"async"`
			AsyncTimeout time.Duration `mapstructure:"async_timeout"`
			CACert       string        `mapstructure:"ca_cert"`
			TLSCert      string        `mapstructure:"tls_cert"`
			TLSKey       string        `mapstructure:"tls_key"`
		} `mapstructure:"servers"`

		Default struct {
			Server       string        `mapstructure:"server"`
			Async        bool          `mapstructure:"async"`
			AsyncTimeout time.Duration `mapstructure:"async_timeout"`
			CACert       string        `mapstructure:"ca_cert"`
			TLSCert      string        `mapstructure:"tls_cert"`
			TLSKey       string        `mapstructure:"tls_key"`
		} `mapstructure:"default"`

		KEK struct {
			Set []KEK `mapstructure:"set"`
		} `mapstructure:"kek"`
	} `mapstructure:"join_server"`

	Roaming struct {
		ResolveNetIDDomainSuffix string `mapstructure:"resolve_netid_domain_suffix"`

		API struct {
			Bind    string `mapstructure:"bind"`
			CACert  string `mapstructure:"ca_cert"`
			TLSCert string `mapstructure:"tls_cert"`
			TLSKey  string `mapstructure:"tls_key"`
		} `mapstructure:"api"`

		Servers []RoamingServer      `mapstructure:"servers"`
		Default DefaultRoamingServer `mapstructure:"default"`

		KEK struct {
			Set []KEK `mapstructure:"set"`
		} `mapstructure:"kek"`
	} `mapstructure:"roaming"`

	NetworkController struct {
		Client nc.NetworkControllerServiceClient `mapstructure:"client"`

		Server  string `mapstructure:"server"`
		CACert  string `mapstructure:"ca_cert"`
		TLSCert string `mapstructure:"tls_cert"`
		TLSKey  string `mapstructure:"tls_key"`
	} `mapstructure:"network_controller"`

	Metrics struct {
		Timezone string `mapstructure:"timezone"`

		Prometheus struct {
			EndpointEnabled    bool   `mapstructure:"endpoint_enabled"`
			Bind               string `mapstructure:"bind"`
			APITimingHistogram bool   `mapstructure:"api_timing_histogram"`
		} `mapstructure:"prometheus"`
	} `mapstructure:"metrics"`

	Monitoring struct {
		Bind                         string `mapstructure:"bind"`
		PrometheusEndpoint           bool   `mapstructure:"prometheus_endpoint"`
		PrometheusAPITimingHistogram bool   `mapstructure:"prometheus_api_timing_histogram"`
		HealthcheckEndpoint          bool   `mapstructure:"healthcheck_endpoint"`
		DeviceFrameLogMaxHistory     int64  `mapstructure:"device_frame_log_max_history"`
		GatewayFrameLogMaxHistory    int64  `mapstructure:"gateway_frame_log_max_history"`
		PerDeviceFrameLogMaxHistory  int64  `mapstructure:"per_device_frame_log_max_history"`
		PerGatewayFrameLogMaxHistory int64  `mapstructure:"per_gateway_frame_log_max_history"`
	} `mapstructure:"monitoring"`
}

type RoamingServer struct {
	NetID                  lorawan.NetID
	NetIDString            string        `mapstructure:"net_id"`
	Async                  bool          `mapstructure:"async"`
	AsyncTimeout           time.Duration `mapstructure:"async_timeout"`
	PassiveRoaming         bool          `mapstructure:"passive_roaming"`
	PassiveRoamingLifetime time.Duration `mapstructure:"passive_roaming_lifetime"`
	PassiveRoamingKEKLabel string        `mapstructure:"passive_roaming_kek_label"`
	Server                 string        `mapstructure:"server"`
	CACert                 string        `mapstructure:"ca_cert"`
	TLSCert                string        `mapstructure:"tls_cert"`
	TLSKey                 string        `mapstructure:"tls_key"`
	Authorization          string        `mapstructure:"authorization"`
}

type DefaultRoamingServer struct {
	Enabled                bool          `mapstructure:"enabled"`
	Async                  bool          `mapstructure:"async"`
	AsyncTimeout           time.Duration `mapstructure:"async_timeout"`
	PassiveRoaming         bool          `mapstructure:"passive_roaming"`
	PassiveRoamingLifetime time.Duration `mapstructure:"passive_roaming_lifetime"`
	PassiveRoamingKEKLabel string        `mapstructure:"passive_roaming_kek_label"`
	Server                 string        `mapstructure:"server"`
	CACert                 string        `mapstructure:"ca_cert"`
	TLSCert                string        `mapstructure:"tls_cert"`
	TLSKey                 string        `mapstructure:"tls_key"`
	Authorization          string        `mapstructure:"authorization"`
}

type KEK struct {
	Label string `mapstructure:"label"`
	KEK   string `mapstructure:"kek"`
}

// SpreadFactorToRequiredSNRTable contains the required SNR to demodulate a
// LoRa frame for the given spreadfactor.
// These values are taken from the SX1276 datasheet.
var SpreadFactorToRequiredSNRTable = map[int]float64{
	6:  -5,
	7:  -7.5,
	8:  -10,
	9:  -12.5,
	10: -15,
	11: -17.5,
	12: -20,
}

// C holds the global configuration.
var C Config

// ClassBEnqueueMargin contains the margin duration when scheduling Class-B
// messages.
var ClassBEnqueueMargin = time.Second * 5

// MulticastClassCInterval defines the interval between the gateway scheduling
// for Class-C multicast.
var MulticastClassCInterval = time.Second

// Get returns the configuration.
func Get() *Config {
	return &C
}

// Set sets the configuration.
func Set(c Config) {
	C = c
}


text:
package main

import (
	"log"
	"time"
)

func main() {
	config, err := ReadConfiguration()
	if err != nil {
		log.Fatal(err)
		return
	}
	for {
		time.Sleep(time.Duration(config.Interval) * time.Second)
		if ok := Check(config.Ping); !ok {
			log.Println("router reset")
			err := Reset(config.Router)
			if err != nil {
				log.Println(err)
			}
		}
	}
}


text:
[![License MIT](https://img.shields.io/badge/license-MIT-green.svg?style=flat)](https://raw.githubusercontent.com/xiaofei86/LPMultiViewController/master/LICENSE)
[![CocoaPods](http://img.shields.io/cocoapods/p/YYKit.svg?style=flat)](http://www.apple.com/ios/)
[![Support](https://img.shields.io/badge/support-iOS%207%2B%20-blue.svg?style=flat)](https://en.wikipedia.org/wiki/IOS_7)
[![Support](https://img.shields.io/badge/blog-xuyafei.cn-orange.svg)](http://www.xuyafei.cn)

如果基于CocoaTouch进行iOS开发,那UIViewController基本控制着App中几乎所有的交互。但是,UIViewController只能控制单个View,App不可能只由单个View构成。在多视图的App中,必须要有控制器来同时控制多个View,以便实现他们之间的切换和跳转。UIKit供了UINavigationController和UITabBarCotroller来满足这样的需求。基本所有的APP都会同时用到这两种控制器,可见其重要性和普遍性。但是对于一些不常用的场景,苹果可能并不打算提供对应的控制器。LPMultiViewController(视图集控制器)打算补充一些常用(但并不是每个APP都能用到)的控制器。

对主流APP分析后,暂时总结出来了三个需要补充的控制器,LPHPageViewController、LPVPageViewController和LPSideBarController。
LPHPageViewController为横向滑动翻页的控制器
LPVPageViewController为纵向滑动翻页的控制器
LPSideBarController为侧向滑动展开隐藏分区的控制器
暂时只实现LPHPageViewController(类似于安卓的ViewPager)。

[图片备用链接](http://b.picphotos.baidu.com/album/s%3D680%3Bq%3D90/sign=2f14d669af773912c0268669c822f725/37d12f2eb9389b5096d570868335e5dde7116e38.jpg)

[图片备用链接](http://g.picphotos.baidu.com/album/s%3D680%3Bq%3D90/sign=e99cfd267f310a55c024ddfc877e3294/caef76094b36acaf3077f1297ad98d1000e99c4b.jpg)

#DesignPattern

设计模式参照了UINavigationController和UITabBarCotroller。即通过category结合runtime的关联对象给UIViewController加property "pageBarItem",然后在controller中通过item控制LPHPageViewController上的pageBar的样式。

通过关联controller中的scrollView和pageBar中的scrollView,实现pageBar中指示器的联动和字体颜色的渐变。

pageBar中的每一个tab宽度会进行自适应。当最大的字体宽度(加上边距)乘以tab数超过屏幕宽度,则每个tab的宽度为字体宽度。如果不超过屏幕宽度,则会将每个tab的宽度等分屏幕宽度。如果用户在对应的controller里设置其中任意一个或多个tab的宽度,就算满足"最大的字体宽度乘以tab数不超过屏幕宽度"也不会进行等分,而是以用户设置的为准。没有设置的会根据字体去自适应。

指示器的宽度默认与tab相同。用户也可以单独设置。

架构基本与UINavigationController、UITabBarCotroller一致。用法对比如下。

	self.hPageController.pageBar.tintColor = [UIColor orangeColor];
    self.navigationController.navigationBar.tintColor = [UIColor orangeColor];

	self.navigationItem.title = @"LPHPageController";
    self.pageBarItem.title = @"LPHPageController";

    self.viewControllers = @[tabViewController1, tabViewController2];//LPHPageController
    self.viewControllers = @[tabViewController1, tabViewController2];//UITabBarCotroller

    self.selectedIndex = 0;//LPHPageController
    self.selectedIndex = 0;//UITabBarCotroller

#Usage

用法于UITabBarCotroller相似。通过子类化LPHPageController并在init方法中给self.viewControllers赋值。pageBar的样式分别在每个controller中通过pageBarItem配置。

通过self.pageItem可配置的单个tab样式。

	@property (nonatomic, strong) NSString *title;
	@property (nonatomic, assign) CGFloat itemWidth;
	@property (nonatomic, assign) CGFloat indicatorWidth;
	@property (nonatomic, assign) BOOL showBadge;//红色通知标示
	@property (nonatomic, strong) UIView *customView;//如果设置了customView其他参数将无效,整个tab就显示customView。

通过self.pageBar可整体配置的tab样式。

	@property (nonatomic, strong) UIColor *textColor;
	@property (nonatomic, strong) UIFont *itemFont;
	@property (nonatomic, assign) CGFloat itemHeight;
	@property (nonatomic, assign) CGFloat indicatorHeight;
	@property (nonatomic, assign) CGFloat offsetScale;//指示器从当前tab向下个tab的偏移、缩放及渐变的比例。范围[0,1]。

LPHPageController可配置的属性。

	@property (nonatomic, strong) LPHPageBar *pageBar;
	@property (nonatomic, strong) NSArray<UIViewController *> *viewControllers;
	@property (nonatomic, strong) UIView *bottomView;//不跟随滑动的尾部视图,在页面最底
	@property (nonatomic, strong) UIView *topView;//不跟随滑动的头部视图,在pageBar之上
	@property (nonatomic, assign) NSUInteger selectedIndex;
	- (void)reloadViews;
	- (void)reloadPageBarViews;


text:
Pattern: Assignment of `ignored_columns`

Issue: -

## Description

Looks for assignments of `ignored_columns` that may override previous
assignments.

Overwriting previous assignments is usually a mistake, since it will
un-ignore the first set of columns. Since duplicate column names is not
a problem, it is better to simply append to the list.

## Examples

```ruby
# bad
class User < ActiveRecord::Base
  self.ignored_columns = [:one]
end

# bad
class User < ActiveRecord::Base
  self.ignored_columns = [:one, :two]
end

# good
class User < ActiveRecord::Base
  self.ignored_columns += [:one, :two]
end

# good
class User < ActiveRecord::Base
  self.ignored_columns += [:one]
  self.ignored_columns += [:two]
end
```

## Further Reading

* [Rails - Rails/IgnoredColumnsAssignment](https://docs.rubocop.org/rubocop-rails/cops_rails.html#railsignoredcolumnsassignment)
* https://rails.rubystyle.guide/#append-ignored-columns


text:
import React, {Component} from 'react';
import Page from '../pages/page.js';

import CSSModules from 'react-css-modules';
import styles from '../pages/page.scss';

@CSSModules(styles, {allowMultiple: true})
class NotFoundLayout extends Component {
  render() {
    return (
      <Page>

404 - Page Not Found

      </Page>
    );
  }
}

export default NotFoundLayout;


text:
<?xml version="1.0" encoding="UTF-8"?>
<result>
  <group>
    <city name="Barcelona" country="Espana"/>
    <city name="Madrid" country="Espana"/>
  </group>
  <group>
    <city name="Paris" country="France"/>
    <city name="Lyon" country="France"/>
  </group>
  <group>
    <city name="Roma" country="Italia"/>
    <city name="Milano" country="Italia"/>
    <city name="Firenze" country="Italia"/>
    <city name="Napoli" country="Italia"/>
  </group>
</result>


text:
package org.o3project.odenos.core.component.network.flow.query;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;
import org.o3project.odenos.core.component.network.topology.Topology;
import org.powermock.reflect.Whitebox;

/**
 * Test class for FlowQuery.
 */
public class FlowQueryTest {

  private FlowQuery target;

  /**
   * @throws java.lang.Exception throws Exception in targets
   */
  @BeforeClass
  public static void setUpBeforeClass() throws Exception {
  }

  /**
   * @throws java.lang.Exception throws Exception in targets
   */
  @AfterClass
  public static void tearDownAfterClass() throws Exception {
  }

  /**
   * @throws java.lang.Exception throws Exception in targets
   */
  @Before
  public void setUp() throws Exception {

    target = Mockito.spy(new FlowQuery("type=BasicFlow") {
    });
  }

  /**
   * @throws java.lang.Exception throws Exception in targets
   */
  @After
  public void tearDown() throws Exception {

    target = null;
  }

  /**
   * Test method for
   * {@link org.o3project.odenos.core.component.network.flow.query.FlowQuery#FlowQuery(java.lang.String)}
   * .
   */
  @Test
  public void testFlowQuery() {

    /*
     * test
     */
    target = new FlowQuery("type=BasicFlow") {
    };

    /*
     * check
     */
    String queriesString = Whitebox.getInternalState(target, "queriesString");
    assertThat(queriesString, is("type=BasicFlow"));

  }

  /**
   * Test method for
   * {@link org.o3project.odenos.core.component.network.flow.query.FlowQuery#FlowQuery(java.lang.String)}
   * .
   */
  @Test
  public void testFlowQuery_Null() {

    /*
     * test
     */
    target = new FlowQuery(null) {
    };

    /*
     * check
     */
    String queriesString = Whitebox.getInternalState(target, "queriesString");
    assertThat(queriesString, is(nullValue()));

  }

  /**
   * Test method for
   * {@link org.o3project.odenos.core.component.network.flow.query.FlowQuery#setTopology(org.o3project.odenos.core.component.network.topology.Topology)}
   * .
   */
  @Test
  public void testSetTopology() {

    /*
     * setting
     */
    Topology topology = Mockito.mock(Topology.class);

    /*
     * test
     */
    target.setTopology(topology);

    /*
     * check
     */
    assertThat(target.topology, is(topology));

  }

}


text:
/**
 *

 * This is the API Reference for Amazon
 * Rekognition Image, Amazon
 * Rekognition Custom Labels, Amazon
 * Rekognition Stored Video, Amazon
 * Rekognition Streaming Video. It provides descriptions of actions, data types, common parameters, and common
 * errors.
 *

 *

 * Amazon Rekognition Image
 *

 *

 *

 *

 * CompareFaces
 *

 *

 *

 *

 * CreateCollection
 *

 *

 *

 *

 * DeleteCollection
 *

 *

 *

 *

 * DeleteFaces
 *

 *

 *

 *

 * DescribeCollection
 *

 *

 *

 *

 * DetectFaces
 *

 *

 *

 *

 * DetectLabels
 *

 *

 *

 *

 *
 * DetectModerationLabels
 *

 *

 *

 *

 *
 * DetectProtectiveEquipment
 *

 *

 *

 *

 * DetectText
 *

 *

 *

 *

 * GetCelebrityInfo
 *

 *

 *

 *

 * IndexFaces
 *

 *

 *

 *

 * ListCollections
 *

 *

 *

 *

 * ListFaces
 *

 *

 *

 *

 *
 * RecognizeCelebrities
 *

 *

 *

 *

 * SearchFaces
 *

 *

 *

 *

 * SearchFacesByImage
 *

 *

 *

 *

 * Amazon Rekognition Custom Labels
 *

 *

 *

 *

 * CopyProjectVersion
 *

 *

 *

 *

 * CreateDataset
 *

 *

 *

 *

 * CreateProject
 *

 *

 *

 *

 *
 * CreateProjectVersion
 *

 *

 *

 *

 * DeleteDataset
 *

 *

 *

 *

 * DeleteProject
 *

 *

 *

 *

 * DeleteProjectPolicy
 *
 *

 *

 *

 *

 *
 * DeleteProjectVersion
 *

 *

 *

 *

 * DescribeDataset
 *

 *

 *

 *

 * DescribeProjects
 *

 *

 *

 *

 *
 * DescribeProjectVersions
 *

 *

 *

 *

 * DetectCustomLabels
 *

 *

 *

 *

 *
 * DistributeDatasetEntries
 *

 *

 *

 *

 * ListDatasetEntries
 *

 *

 *

 *

 * ListDatasetLabels
 *

 *

 *

 *

 * ListProjectPolicies
 *
 *

 *

 *

 *

 * PutProjectPolicy
 *

 *

 *

 *

 * StartProjectVersion
 *
 *

 *

 *

 *

 * StopProjectVersion
 *

 *

 *

 *

 *
 * UpdateDatasetEntries
 *

 *

 *

 *

 * Amazon Rekognition Video Stored Video
 *

 *

 *

 *

 *
 * GetCelebrityRecognition
 *

 *

 *

 *

 *
 * GetContentModeration
 *

 *

 *

 *

 * GetFaceDetection
 *

 *

 *

 *

 * GetFaceSearch
 *

 *

 *

 *

 * GetLabelDetection
 *

 *

 *

 *

 * GetPersonTracking
 *

 *

 *

 *

 * GetSegmentDetection
 *
 *

 *

 *

 *

 * GetTextDetection
 *

 *

 *

 *

 *
 * StartCelebrityRecognition
 *

 *

 *

 *

 *
 * StartContentModeration
 *

 *

 *

 *

 * StartFaceDetection
 *

 *

 *

 *

 * StartFaceSearch
 *

 *

 *

 *

 * StartLabelDetection
 *
 *

 *

 *

 *

 * StartPersonTracking
 *
 *

 *

 *

 *

 *
 * StartSegmentDetection
 *

 *

 *

 *

 * StartTextDetection
 *

 *

 *

 *

 * Amazon Rekognition Video Streaming Video
 *

 *

 *

 *

 *
 * CreateStreamProcessor
 *

 *

 *

 *

 *
 * DeleteStreamProcessor
 *

 *

 *

 *

 *
 * DescribeStreamProcessor
 *

 *

 *

 *

 *
 * ListStreamProcessors
 *

 *

 *

 *

 *
 * StartStreamProcessor
 *

 *

 *

 *

 * StopStreamProcessor
 *
 *

 *

 *

 *

 *
 * UpdateStreamProcessor
 *

 *

 *

 */
package com.amazonaws.services.rekognition;


text:
package com.ptoceti.osgi.obix.impl.service;

import java.util.concurrent.Callable;

import org.osgi.service.wireadmin.BasicEnvelope;

import com.ptoceti.osgi.obix.impl.back.converters.OsgiConverterFactory;
import com.ptoceti.osgi.obix.impl.back.converters.OsgiObixConverter;
import com.ptoceti.osgi.obix.object.Val;
import com.ptoceti.osgi.obix.resources.ObjResource;

/**
 * Handle a command that is to be sent to one of the wire consumer attached to the Obix service. The command take the form of an
 * Obix object.
 *
 * The handler convert the obix object to one understood by the wire consumer and place inside an enveloppe. The enveloppe is then
 * forwarded to the wire handler that will dispatch it to the proper wire consumer, based to the wire scope.
 *
 * @author lor
 *
 */
public class CommandHandler  {

	/**
	 * Send a command to a wire consumer. Consumer scope is extracted from the obix href value. The name of the obix val is
	 * used as the identification.
	 *
	 * @param commandIn Obix command object.
	 */
	public void sendCommand( Val commandIn){

		Object commandOut;
		OsgiObixConverter converter = OsgiConverterFactory.getInstance().getConverterFromObixContract(commandIn);
		if( converter != null) {
			commandOut = converter.fromBaseObix(commandIn);
		} else {
			converter = OsgiConverterFactory.getInstance().getConverterFromObix(commandIn);
			commandOut = converter.fromObix(commandIn);
		}

		String name = commandIn.getName();
		String scope = extractScope(commandIn);

		BasicEnvelope env = new BasicEnvelope(commandOut, name, scope);

		Activator.getObixService().getExecutorService().submit(new AsyncCommand(env));
		//Activator.getObixService().getWireHandler().updateWire(env);

	}

	/**
	 * Extract original scope from the object href path.
	 *
	 * @param commandIn Obix value as the command
	 * @return String the scope.
	 */
	protected String extractScope(Val commandIn) {
		String href = commandIn.getHref().getPath();
		// extract as well the root uri for an object resource.
		href = href.substring(href.indexOf(ObjResource.uri) + ObjResource.uri.length());
		href = href.replaceAll("[//]", ".");

		// name was added the the href as a subpath ...
		String namePath = "." + commandIn.getName();
		// ... extract it
		String scope = href.substring(0, href.indexOf(namePath));

		return scope;
	}

	protected class AsyncCommand implements Callable {

		BasicEnvelope enveloppe;

		public AsyncCommand(BasicEnvelope env){
			enveloppe = env;
		}

		@Override
		public Object call() throws Exception {
			boolean result = false;
			WireHandler wHandler = Activator.getObixService().getWireHandler();
			if( wHandler != null){
				result = wHandler.updateWire(enveloppe);
			}

			return Boolean.valueOf(result);
		}

	}
}


text:
static QStringList parseCsv(const QString& in) {
    QStringList result;

    std::vector<std::string> parsed;
    const std::string line = in.toStdString();
    sfcsv::parse_line(line, std::back_inserter(parsed), ',');
    for(auto&& res : parsed) {
        result.append(QString::fromStdString(res));
    }

    return result;
}

static QStringList parseFile(const QString& in) {
    QStringList results;

    QFile inFile(in);
    if(!inFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        throw std::runtime_error("Unable to open file");
    }

    QTextStream stream(&inFile);
    stream.setCodec("UTF-8");
    while(!stream.atEnd()) {
        const QString line = stream.readLine().remove("\n");
        results << line;
    }

    return results;
}

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    config("CsvScreenshotFinderConfig.ini", QSettings::IniFormat)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_actionOpen_triggered() try
{
    const QString openedFile = QFileDialog::getOpenFileName(this, tr("Open..."),
                                                            config.value("last_opened").toString());
    if(openedFile.isEmpty()) {
        return;
    }

    config.setValue("last_opened", openedFile);

    QStringList lines = parseFile(openedFile);
    const QString header = lines.takeFirst();
    QStringList headerParsed = parseCsv(header);
    headerParsed.prepend("Thumbnail");

    ui->tableCsv->clear();
    ui->tableCsv->setColumnCount(headerParsed.size() + 1);
    ui->tableCsv->setHorizontalHeaderLabels(headerParsed);
    ui->tableCsv->setRowCount(lines.size());
    ui->tableCsv->verticalHeader()->hide();
    ui->tableCsv->setColumnWidth(0, 155);

    QProgressDialog progress(tr("Loading images"), tr("Cancel"), 0, lines.size() - 1);
    progress.setMinimumDuration(0);
    progress.setModal(true);

    const QStringList imageDirectories = config.value("image_dirs").toStringList();
    for(int dirIdx = 0; dirIdx < imageDirectories.size(); ++dirIdx) {
        const QString& imageDirectory = imageDirectories.at(dirIdx);
        progress.setLabelText(tr("(%1/%2) Loading images from %3")
                              .arg(dirIdx + 1).arg(imageDirectories.size()).arg(imageDirectory));
        QDir inputDir(imageDirectory);
        for(int row = 0; row < lines.size(); ++row) {
            const QStringList columns = parseCsv(lines.at(row));

            for(int column = 0; column < columns.size(); ++column) {
                auto item = new QTableWidgetItem(columns.at(column));
                ui->tableCsv->setItem(row, column + 1, item);
            }

            if(columns.size() >= 2) {
                const QString imageName = QString("%1.jpg").arg(columns.at(1));
                const QString imagePath = inputDir.absoluteFilePath(imageName);
                //qDebug() << imagePath;
                if(QFile::exists(imagePath)) {
                    QImage image(imagePath);
                    setRowImage(row, image);
                }
            }

            progress.setValue(row);
            if(progress.wasCanceled()) {
                ui->tableCsv->setRowCount(row);
                break;
            }
        }
    }
}
catch(const std::exception& exc) {
    QMessageBox::critical(this, tr("CSV Error"), QString(exc.what()));
}

void MainWindow::on_buttonBrowseOutput_clicked()
{
    const auto outputPath =
            QFileDialog::getExistingDirectory(this,
                                              tr("Select output directory"),
                                              config.value("last_output_dir").toString());
    if(outputPath.isEmpty()) {
        return;
    }

    ui->outputDir->setText(outputPath);

    config.setValue("last_output_dir", outputPath);
}

void MainWindow::setRowImage(const int row, const QImage& image)
{
    QPixmap thumb = QPixmap::fromImage(image.scaledToWidth(150));
    auto item = new QTableWidgetItem;
    item->setData(Qt::DecorationRole, thumb);
    //item->setData(Qt::SizeHintRole, thumb.size());
    //item->setSizeHint(thumb.size());
    ui->tableCsv->setItem(row, 0, item);
    ui->tableCsv->setRowHeight(row, thumb.height());
}

void MainWindow::on_actionDirectories_triggered()
{
    DirectoryDialog dlg;
    dlg.exec();
}

void MainWindow::on_checkBoxOverwrite_toggled(bool checked)
{
    config.setValue("overwrite", checked);
}