text:
/*                        __    __  __  __    __  ___
 *                       \  \  /  /    \  \  /  /  __/
 *                        \  \/  /  /\  \  \/  /  /
 *                         \____/__/  \__\____/__/.ɪᴏ
 * ᶜᵒᵖʸʳᶦᵍʰᵗ ᵇʸ ᵛᵃᵛʳ ⁻ ˡᶦᶜᵉⁿˢᵉᵈ ᵘⁿᵈᵉʳ ᵗʰᵉ ᵃᵖᵃᶜʰᵉ ˡᶦᶜᵉⁿˢᵉ ᵛᵉʳˢᶦᵒⁿ ᵗʷᵒ ᵈᵒᵗ ᶻᵉʳᵒ
 */
package io.vavr.collection;

import io.vavr.*;
import io.vavr.control.Option;

import java.util.*;
import java.util.function.*;
import java.util.stream.Collector;

import static io.vavr.collection.JavaConverters.ChangePolicy.IMMUTABLE;
import static io.vavr.collection.JavaConverters.ChangePolicy.MUTABLE;

/**
 * An immutable {@code Queue} stores elements allowing a first-in-first-out (FIFO) retrieval.
 *

 * Queue API:
 *
 *

 *
{@link #dequeue()}

 *
{@link #dequeueOption()}

 *
{@link #enqueue(Object)}

 *
{@link #enqueue(Object[])}

 *
{@link #enqueueAll(Iterable)}

 *
{@link #peek()}

 *
{@link #peekOption()}

 *

 *
 * A Queue internally consists of a front List containing the front elements of the Queue in the correct order and a
 * rear List containing the rear elements of the Queue in reverse order.
 *

 * When the front list is empty, front and rear are swapped and rear is reversed. This implies the following queue
 * invariant: {@code front.isEmpty() => rear.isEmpty()}.
 *

 * See Okasaki, Chris: Purely Functional Data Structures (p. 42 ff.). Cambridge, 2003.
 *
 * @param <T> Component type of the Queue
 * @author Daniel Dietrich
 */
public final class Queue<T> extends AbstractQueue<T, Queue<T>> implements LinearSeq<T> {

    private static final long serialVersionUID = 1L;

    private static final Queue<?> EMPTY = new Queue<>(io.vavr.collection.List.empty(), io.vavr.collection.List.empty());

    private final io.vavr.collection.List<T> front;
    private final io.vavr.collection.List<T> rear;

    /**
     * Creates a Queue consisting of a front List and a rear List.
     *

     * For a {@code Queue(front, rear)} the following invariant holds: {@code Queue is empty <=> front is empty}.
     * In other words: If the Queue is not empty, the front List contains at least one element.
     *
     * @param front A List of front elements, in correct order.
     * @param rear  A List of rear elements, in reverse order.
     */
    private Queue(io.vavr.collection.List<T> front, io.vavr.collection.List<T> rear) {
        final boolean frontIsEmpty = front.isEmpty();
        this.front = frontIsEmpty ? rear.reverse() : front;
        this.rear = frontIsEmpty ? front : rear;
    }

    /**
     * Returns a {@link java.util.stream.Collector} which may be used in conjunction with
     * {@link java.util.stream.Stream#collect(java.util.stream.Collector)} to obtain a {@link Queue}
     * .
     *
     * @param <T> Component type of the Queue.
     * @return A io.vavr.collection.Queue Collector.
     */
    public static <T> Collector<T, ArrayList<T>, Queue<T>> collector() {
        final Supplier<ArrayList<T>> supplier = ArrayList::new;
        final BiConsumer<ArrayList<T>, T> accumulator = ArrayList::add;
        final BinaryOperator<ArrayList<T>> combiner = (left, right) -> {
            left.addAll(right);
            return left;
        };
        final Function<ArrayList<T>, Queue<T>> finisher = Queue::ofAll;
        return Collector.of(supplier, accumulator, combiner, finisher);
    }

    /**
     * Returns the empty Queue.
     *
     * @param <T> Component type
     * @return The empty Queue.
     */
    @SuppressWarnings("unchecked")
    public static <T> Queue<T> empty() {
        return (Queue<T>) EMPTY;
    }

    /**
     * Narrows a widened {@code Queue<? extends T>} to {@code Queue<T>}
     * by performing a type-safe cast. This is eligible because immutable/read-only
     * collections are covariant.
     *
     * @param queue An {@code Queue}.
     * @param <T>   Component type of the {@code Queue}.
     * @return the given {@code queue} instance as narrowed type {@code Queue<T>}.
     */
    @SuppressWarnings("unchecked")
    public static <T> Queue<T> narrow(Queue<? extends T> queue) {
        return (Queue<T>) queue;
    }

    /**
     * Returns a singleton {@code Queue}, i.e. a {@code Queue} of one element.
     *
     * @param element An element.
     * @param <T>     The component type
     * @return A new Queue instance containing the given element
     */
    public static <T> Queue<T> of(T element) {
        return ofAll(io.vavr.collection.List.of(element));
    }

    /**
     * Creates a Queue of the given elements.
     *
     * @param <T>      Component type of the Queue.
     * @param elements Zero or more elements.
     * @return A queue containing the given elements in the same order.
     * @throws NullPointerException if {@code elements} is null
     */
    @SuppressWarnings("varargs")
    @SafeVarargs
    public static <T> Queue<T> of(T... elements) {
        Objects.requireNonNull(elements, "elements is null");
        return ofAll(io.vavr.collection.List.of(elements));
    }

    /**
     * Creates a Queue of the given elements.
     *
     * @param <T>      Component type of the Queue.
     * @param elements An Iterable of elements.
     * @return A queue containing the given elements in the same order.
     * @throws NullPointerException if {@code elements} is null
     */
    @SuppressWarnings("unchecked")
    public static <T> Queue<T> ofAll(Iterable<? extends T> elements) {
        Objects.requireNonNull(elements, "elements is null");
        if (elements instanceof Queue) {
            return (Queue<T>) elements;
        } else if (!elements.iterator().hasNext()) {
            return empty();
        } else if (elements instanceof io.vavr.collection.List) {
            return new Queue<>((io.vavr.collection.List<T>) elements, io.vavr.collection.List.empty());
        } else {
            return new Queue<>(io.vavr.collection.List.ofAll(elements), io.vavr.collection.List.empty());
        }
    }

    /**
     * Creates a Queue that contains the elements of the given {@link java.util.stream.Stream}.
     *
     * @param javaStream A {@link java.util.stream.Stream}
     * @param <T>        Component type of the Stream.
     * @return A Queue containing the given elements in the same order.
     */
    public static <T> Queue<T> ofAll(java.util.stream.Stream<? extends T> javaStream) {
        Objects.requireNonNull(javaStream, "javaStream is null");
        return new Queue<>(io.vavr.collection.List.ofAll(javaStream), io.vavr.collection.List.empty());
    }

    /**
     * Creates a Queue from boolean values.
     *
     * @param elements boolean values
     * @return A new Queue of Boolean values
     * @throws NullPointerException if elements is null
     */
    public static Queue<Boolean> ofAll(boolean... elements) {
        Objects.requireNonNull(elements, "elements is null");
        return ofAll(io.vavr.collection.List.ofAll(elements));
    }

    /**
     * Creates a Queue from byte values.
     *
     * @param elements byte values
     * @return A new Queue of Byte values
     * @throws NullPointerException if elements is null
     */
    public static Queue<Byte> ofAll(byte... elements) {
        Objects.requireNonNull(elements, "elements is null");
        return ofAll(io.vavr.collection.List.ofAll(elements));
    }

    /**
     * Creates a Queue from char values.
     *
     * @param elements char values
     * @return A new Queue of Character values
     * @throws NullPointerException if elements is null
     */
    public static Queue<Character> ofAll(char... elements) {
        Objects.requireNonNull(elements, "elements is null");
        return ofAll(io.vavr.collection.List.ofAll(elements));
    }

    /**
     * Creates a Queue from double values.
     *
     * @param elements double values
     * @return A new Queue of Double values
     * @throws NullPointerException if elements is null
     */
    public static Queue<Double> ofAll(double... elements) {
        Objects.requireNonNull(elements, "elements is null");
        return ofAll(io.vavr.collection.List.ofAll(elements));
    }

    /**
     * Creates a Queue from float values.
     *
     * @param elements float values
     * @return A new Queue of Float values
     * @throws NullPointerException if elements is null
     */
    public static Queue<Float> ofAll(float... elements) {
        Objects.requireNonNull(elements, "elements is null");
        return ofAll(io.vavr.collection.List.ofAll(elements));
    }

    /**
     * Creates a Queue from int values.
     *
     * @param elements int values
     * @return A new Queue of Integer values
     * @throws NullPointerException if elements is null
     */
    public static Queue<Integer> ofAll(int... elements) {
        Objects.requireNonNull(elements, "elements is null");
        return ofAll(io.vavr.collection.List.ofAll(elements));
    }

    /**
     * Creates a Queue from long values.
     *
     * @param elements  long values
     * @return A new Queue of Long values
     * @throws NullPointerException if elements is null
     */
    public static Queue<Long> ofAll(long... elements) {
        Objects.requireNonNull(elements, "elements is null");
        return ofAll(io.vavr.collection.List.ofAll(elements));
    }

    /**
     * Creates a Queue from short values.
     *
     * @param elements short values
     * @return A new Queue of Short values
     * @throws NullPointerException if elements is null
     */
    public static Queue<Short> ofAll(short... elements) {
        Objects.requireNonNull(elements, "elements is null");
        return ofAll(io.vavr.collection.List.ofAll(elements));
    }

    /**
     * Returns a Queue containing {@code n} values of a given Function {@code f}
     * over a range of integer values from 0 to {@code n - 1}.
     *
     * @param <T> Component type of the Queue
     * @param n   The number of elements in the Queue
     * @param f   The Function computing element values
     * @return A Queue consisting of elements {@code f(0),f(1), ..., f(n - 1)}
     * @throws NullPointerException if {@code f} is null
     */
    public static <T> Queue<T> tabulate(int n, Function<? super Integer, ? extends T> f) {
        Objects.requireNonNull(f, "f is null");
        return io.vavr.collection.Collections.tabulate(n, f, empty(), Queue::of);
    }

    /**
     * Returns a Queue containing {@code n} values supplied by a given Supplier {@code s}.
     *
     * @param <T> Component type of the Queue
     * @param n   The number of elements in the Queue
     * @param s   The Supplier computing element values
     * @return An Queue of size {@code n}, where each element contains the result supplied by {@code s}.
     * @throws NullPointerException if {@code s} is null
     */
    public static <T> Queue<T> fill(int n, Supplier<? extends T> s) {
        Objects.requireNonNull(s, "s is null");
        return io.vavr.collection.Collections.fill(n, s, empty(), Queue::of);
    }

    public static Queue<Character> range(char from, char toExclusive) {
        return ofAll(Iterator.range(from, toExclusive));
    }

    public static Queue<Character> rangeBy(char from, char toExclusive, int step) {
        return ofAll(Iterator.rangeBy(from, toExclusive, step));
    }

    @GwtIncompatible
    public static Queue<Double> rangeBy(double from, double toExclusive, double step) {
        return ofAll(Iterator.rangeBy(from, toExclusive, step));
    }

    /**
     * Creates a Queue of int numbers starting from {@code from}, extending to {@code toExclusive - 1}.
     *

     * Examples:
     *

     *
     * Queue.range(0, 0)  // = Queue()
     * Queue.range(2, 0)  // = Queue()
     * Queue.range(-2, 2) // = Queue(-2, -1, 0, 1)
     *
     *

     *
     * @param from        the first number
     * @param toExclusive the last number + 1
     * @return a range of int values as specified or {@code Nil} if {@code from >= toExclusive}
     */
    public static Queue<Integer> range(int from, int toExclusive) {
        return ofAll(Iterator.range(from, toExclusive));
    }

    /**
     * Creates a Queue of int numbers starting from {@code from}, extending to {@code toExclusive - 1},
     * with {@code step}.
     *

     * Examples:
     *

     *
     * Queue.rangeBy(1, 3, 1)  // = Queue(1, 2)
     * Queue.rangeBy(1, 4, 2)  // = Queue(1, 3)
     * Queue.rangeBy(4, 1, -2) // = Queue(4, 2)
     * Queue.rangeBy(4, 1, 2)  // = Queue()
     *
     *

     *
     * @param from        the first number
     * @param toExclusive the last number + 1
     * @param step        the step
     * @return a range of long values as specified or {@code Nil} if

     * {@code from >= toInclusive} and {@code step > 0} or

     * {@code from <= toInclusive} and {@code step < 0}
     * @throws IllegalArgumentException if {@code step} is zero
     */
    public static Queue<Integer> rangeBy(int from, int toExclusive, int step) {
        return ofAll(Iterator.rangeBy(from, toExclusive, step));
    }

    /**
     * Creates a Queue of long numbers starting from {@code from}, extending to {@code toExclusive - 1}.
     *

     * Examples:
     *

     *
     * Queue.range(0L, 0L)  // = Queue()
     * Queue.range(2L, 0L)  // = Queue()
     * Queue.range(-2L, 2L) // = Queue(-2L, -1L, 0L, 1L)
     *
     *

     *
     * @param from        the first number
     * @param toExclusive the last number + 1
     * @return a range of long values as specified or {@code Nil} if {@code from >= toExclusive}
     */
    public static Queue<Long> range(long from, long toExclusive) {
        return ofAll(Iterator.range(from, toExclusive));
    }

    /**
     * Creates a Queue of long numbers starting from {@code from}, extending to {@code toExclusive - 1},
     * with {@code step}.
     *

     * Examples:
     *

     *
     * Queue.rangeBy(1L, 3L, 1L)  // = Queue(1L, 2L)
     * Queue.rangeBy(1L, 4L, 2L)  // = Queue(1L, 3L)
     * Queue.rangeBy(4L, 1L, -2L) // = Queue(4L, 2L)
     * Queue.rangeBy(4L, 1L, 2L)  // = Queue()
     *
     *

     *
     * @param from        the first number
     * @param toExclusive the last number + 1
     * @param step        the step
     * @return a range of long values as specified or {@code Nil} if

     * {@code from >= toInclusive} and {@code step > 0} or

     * {@code from <= toInclusive} and {@code step < 0}
     * @throws IllegalArgumentException if {@code step} is zero
     */
    public static Queue<Long> rangeBy(long from, long toExclusive, long step) {
        return ofAll(Iterator.rangeBy(from, toExclusive, step));
    }

    public static Queue<Character> rangeClosed(char from, char toInclusive) {
        return ofAll(Iterator.rangeClosed(from, toInclusive));
    }

    public static Queue<Character> rangeClosedBy(char from, char toInclusive, int step) {
        return ofAll(Iterator.rangeClosedBy(from, toInclusive, step));
    }

    @GwtIncompatible
    public static Queue<Double> rangeClosedBy(double from, double toInclusive, double step) {
        return ofAll(Iterator.rangeClosedBy(from, toInclusive, step));
    }

    /**
     * Creates a Queue of int numbers starting from {@code from}, extending to {@code toInclusive}.
     *

     * Examples:
     *

     *
     * Queue.rangeClosed(0, 0)  // = Queue(0)
     * Queue.rangeClosed(2, 0)  // = Queue()
     * Queue.rangeClosed(-2, 2) // = Queue(-2, -1, 0, 1, 2)
     *
     *

     *
     * @param from        the first number
     * @param toInclusive the last number
     * @return a range of int values as specified or {@code Nil} if {@code from > toInclusive}
     */
    public static Queue<Integer> rangeClosed(int from, int toInclusive) {
        return ofAll(Iterator.rangeClosed(from, toInclusive));
    }

    /**
     * Creates a Queue of int numbers starting from {@code from}, extending to {@code toInclusive},
     * with {@code step}.
     *

     * Examples:
     *

     *
     * Queue.rangeClosedBy(1, 3, 1)  // = Queue(1, 2, 3)
     * Queue.rangeClosedBy(1, 4, 2)  // = Queue(1, 3)
     * Queue.rangeClosedBy(4, 1, -2) // = Queue(4, 2)
     * Queue.rangeClosedBy(4, 1, 2)  // = Queue()
     *
     *

     *
     * @param from        the first number
     * @param toInclusive the last number
     * @param step        the step
     * @return a range of int values as specified or {@code Nil} if

     * {@code from > toInclusive} and {@code step > 0} or

     * {@code from < toInclusive} and {@code step < 0}
     * @throws IllegalArgumentException if {@code step} is zero
     */
    public static Queue<Integer> rangeClosedBy(int from, int toInclusive, int step) {
        return ofAll(Iterator.rangeClosedBy(from, toInclusive, step));
    }

    /**
     * Creates a Queue of long numbers starting from {@code from}, extending to {@code toInclusive}.
     *

     * Examples:
     *

     *
     * Queue.rangeClosed(0L, 0L)  // = Queue(0L)
     * Queue.rangeClosed(2L, 0L)  // = Queue()
     * Queue.rangeClosed(-2L, 2L) // = Queue(-2L, -1L, 0L, 1L, 2L)
     *
     *

     *
     * @param from        the first number
     * @param toInclusive the last number
     * @return a range of long values as specified or {@code Nil} if {@code from > toInclusive}
     */
    public static Queue<Long> rangeClosed(long from, long toInclusive) {
        return ofAll(Iterator.rangeClosed(from, toInclusive));
    }

    /**
     * Transposes the rows and columns of a {@link Queue} matrix.
     *
     * @param <T> matrix element type
     * @param matrix to be transposed.
     * @return a transposed {@link Queue} matrix.
     * @throws IllegalArgumentException if the row lengths of {@code matrix} differ.
     *
     *

     * ex: {@code
     * Queue.transpose(Queue(Queue(1,2,3), Queue(4,5,6))) → Queue(Queue(1,4), Queue(2,5), Queue(3,6))
     * }
     */
    public static <T> Queue<Queue<T>> transpose(Queue<Queue<T>> matrix) {
        return io.vavr.collection.Collections.transpose(matrix, Queue::ofAll, Queue::of);
    }

    /**
     * Creates a Queue of long numbers starting from {@code from}, extending to {@code toInclusive},
     * with {@code step}.
     *

     * Examples:
     *

     *
     * Queue.rangeClosedBy(1L, 3L, 1L)  // = Queue(1L, 2L, 3L)
     * Queue.rangeClosedBy(1L, 4L, 2L)  // = Queue(1L, 3L)
     * Queue.rangeClosedBy(4L, 1L, -2L) // = Queue(4L, 2L)
     * Queue.rangeClosedBy(4L, 1L, 2L)  // = Queue()
     *
     *

     *
     * @param from        the first number
     * @param toInclusive the last number
     * @param step        the step
     * @return a range of int values as specified or {@code Nil} if

     * {@code from > toInclusive} and {@code step > 0} or

     * {@code from < toInclusive} and {@code step < 0}
     * @throws IllegalArgumentException if {@code step} is zero
     */
    public static Queue<Long> rangeClosedBy(long from, long toInclusive, long step) {
        return ofAll(Iterator.rangeClosedBy(from, toInclusive, step));
    }

    /**
     * Creates a Queue from a seed value and a function.
     * The function takes the seed at first.
     * The function should return {@code None} when it's
     * done generating the Queue, otherwise {@code Some} {@code Tuple}
     * of the element for the next call and the value to add to the
     * resulting Queue.
     *

     * Example:
     *

     *
     * Queue.unfoldRight(10, x -> x == 0
     *             ? Option.none()
     *             : Option.of(new Tuple2<>(x, x-1)));
     * // Queue(10, 9, 8, 7, 6, 5, 4, 3, 2, 1))
     *
     *

     *
     * @param <T>  type of seeds
     * @param   type of unfolded values
     * @param seed the start value for the iteration
     * @param f    the function to get the next step of the iteration
     * @return a Queue with the values built up by the iteration
     * @throws NullPointerException if {@code f} is null
     */
    public static <T, U> Queue unfoldRight(T seed, Function<? super T, Option<Tuple2<? extends U, ? extends T>>> f) {
        return Iterator.unfoldRight(seed, f).toQueue();
    }

    /**
     * Creates a Queue from a seed value and a function.
     * The function takes the seed at first.
     * The function should return {@code None} when it's
     * done generating the Queue, otherwise {@code Some} {@code Tuple}
     * of the value to add to the resulting Queue and
     * the element for the next call.
     *

     * Example:
     *

     *
     * Queue.unfoldLeft(10, x -> x == 0
     *             ? Option.none()
     *             : Option.of(new Tuple2<>(x-1, x)));
     * // Queue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
     *
     *

     *
     * @param <T>  type of seeds
     * @param   type of unfolded values
     * @param seed the start value for the iteration
     * @param f    the function to get the next step of the iteration
     * @return a Queue with the values built up by the iteration
     * @throws NullPointerException if {@code f} is null
     */
    public static <T, U> Queue unfoldLeft(T seed, Function<? super T, Option<Tuple2<? extends T, ? extends U>>> f) {
        return Iterator.unfoldLeft(seed, f).toQueue();
    }

    /**
     * Creates a Queue from a seed value and a function.
     * The function takes the seed at first.
     * The function should return {@code None} when it's
     * done generating the Queue, otherwise {@code Some} {@code Tuple}
     * of the value to add to the resulting Queue and
     * the element for the next call.
     *

     * Example:
     *

     *
     * Queue.unfold(10, x -> x == 0
     *             ? Option.none()
     *             : Option.of(new Tuple2<>(x-1, x)));
     * // Queue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
     *
     *

     *
     * @param <T>  type of seeds and unfolded values
     * @param seed the start value for the iteration
     * @param f    the function to get the next step of the iteration
     * @return a Queue with the values built up by the iteration
     * @throws NullPointerException if {@code f} is null
     */
    public static <T> Queue<T> unfold(T seed, Function<? super T, Option<Tuple2<? extends T, ? extends T>>> f) {
        return Iterator.unfold(seed, f).toQueue();
    }

    /**
     * Enqueues a new element.
     *
     * @param element The new element
     * @return a new {@code Queue} instance, containing the new element
     */
    @Override
    public Queue<T> enqueue(T element) {
        return new Queue<>(front, rear.prepend(element));
    }

    /**
     * Enqueues the given elements. A queue has FIFO order, i.e. the first of the given elements is
     * the first which will be retrieved.
     *
     * @param elements An Iterable of elements, may be empty
     * @return a new {@code Queue} instance, containing the new elements
     * @throws NullPointerException if elements is null
     */
    @SuppressWarnings("unchecked")
    public Queue<T> enqueueAll(Iterable<? extends T> elements) {
        Objects.requireNonNull(elements, "elements is null");
        if (isEmpty() && elements instanceof Queue) {
            return (Queue<T>) elements;
        } else {
            return io.vavr.collection.List.ofAll(elements).foldLeft(this, Queue::enqueue);
        }
    }

    // -- Adjusted return types of Seq methods

    @Override
    public Queue<T> append(T element) {
        return enqueue(element);
    }

    @Override
    public Queue<T> appendAll(Iterable<? extends T> elements) {
        return enqueueAll(elements);
    }

    @GwtIncompatible
    @Override
    public java.util.List<T> asJava() {
        return JavaConverters.asJava(this, IMMUTABLE);
    }

    @GwtIncompatible
    @Override
    public Queue<T> asJava(Consumer<? super java.util.List<T>> action) {
        return Collections.asJava(this, action, IMMUTABLE);
    }

    @GwtIncompatible
    @Override
    public java.util.List<T> asJavaMutable() {
        return JavaConverters.asJava(this, MUTABLE);
    }

    @GwtIncompatible
    @Override
    public Queue<T> asJavaMutable(Consumer<? super java.util.List<T>> action) {
        return Collections.asJava(this, action, MUTABLE);
    }

    @Override
    public <R> Queue<R> collect(PartialFunction<? super T, ? extends R> partialFunction) {
        return ofAll(iterator().<R> collect(partialFunction));
    }

    @Override
    public Queue<Queue<T>> combinations() {
        return ofAll(toList().combinations().map(Queue::ofAll));
    }

    @Override
    public Queue<Queue<T>> combinations(int k) {
        return ofAll(toList().combinations(k).map(Queue::ofAll));
    }

    @Override
    public Iterator<Queue<T>> crossProduct(int power) {
        return io.vavr.collection.Collections.crossProduct(empty(), this, power);
    }

    @Override
    public Queue<T> distinct() {
        return ofAll(toList().distinct());
    }

    @Override
    public Queue<T> distinctBy(Comparator<? super T> comparator) {
        Objects.requireNonNull(comparator, "comparator is null");
        return ofAll(toList().distinctBy(comparator));
    }

    @Override
    public  Queue<T> distinctBy(Function<? super T, ? extends U> keyExtractor) {
        Objects.requireNonNull(keyExtractor, "keyExtractor is null");
        return ofAll(toList().distinctBy(keyExtractor));
    }

    @Override
    public Queue<T> drop(int n) {
        if (n <= 0) {
            return this;
        }
        if (n >= length()) {
            return empty();
        }
        return new Queue<>(front.drop(n), rear.dropRight(n - front.length()));
    }

    @Override
    public Queue<T> dropWhile(Predicate<? super T> predicate) {
        Objects.requireNonNull(predicate, "predicate is null");
        final List<T> dropped = toList().dropWhile(predicate);
        return ofAll(dropped.length() == length() ? this : dropped);
    }

    @Override
    public Queue<T> dropRight(int n) {
        if (n <= 0) {
            return this;
        }
        if (n >= length()) {
            return empty();
        }
        return new Queue<>(front.dropRight(n - rear.length()), rear.drop(n));
    }

    @Override
    public Queue<T> dropRightUntil(Predicate<? super T> predicate) {
        Objects.requireNonNull(predicate, "predicate is null");
        return reverse().dropUntil(predicate).reverse();
    }

    @Override
    public Queue<T> dropRightWhile(Predicate<? super T> predicate) {
        Objects.requireNonNull(predicate, "predicate is null");
        return dropRightUntil(predicate.negate());
    }

    @Override
    public Queue<T> filter(Predicate<? super T> predicate) {
        Objects.requireNonNull(predicate, "predicate is null");
        final io.vavr.collection.List<T> filtered = toList().filter(predicate);

        if (filtered.isEmpty()) {
            return empty();
        } else if (filtered.length() == length()) {
            return this;
        } else {
            return ofAll(filtered);
        }
    }

    @Override
    public  Queue flatMap(Function<? super T, ? extends Iterable<? extends U>> mapper) {
        Objects.requireNonNull(mapper, "mapper is null");
        if (isEmpty()) {
            return empty();
        } else {
            return new Queue<>(front.flatMap(mapper), rear.flatMap(mapper));
        }
    }

    @Override
    public T get(int index) {
        if (isEmpty()) {
            throw new IndexOutOfBoundsException("get(" + index + ") on empty Queue");
        }
        if (index < 0) {
            throw new IndexOutOfBoundsException("get(" + index + ")");
        }
        final int length = front.length();
        if (index < length) {
            return front.get(index);
        } else {
            final int rearIndex = index - length;
            final int rearLength = rear.length();
            if (rearIndex < rearLength) {
                final int reverseRearIndex = rearLength - rearIndex - 1;
                return rear.get(reverseRearIndex);
            } else {
                throw new IndexOutOfBoundsException("get(" + index + ") on Queue of length " + length());
            }
        }
    }

    @Override
    public <C> Map<C, Queue<T>> groupBy(Function<? super T, ? extends C> classifier) {
        return io.vavr.collection.Collections.groupBy(this, classifier, Queue::ofAll);
    }

    @Override
    public Iterator<Queue<T>> grouped(int size) {
        return sliding(size, size);
    }

    @Override
    public boolean hasDefiniteSize() {
        return true;
    }

    @Override
    public T head() {
        if (isEmpty()) {
            throw new NoSuchElementException("head of empty " + stringPrefix());
        } else {
            return front.head();
        }
    }

    @Override
    public int indexOf(T element, int from) {
        final int frontIndex = front.indexOf(element, from);
        if (frontIndex != -1) {
            return frontIndex;
        } else {
            // we need to reverse because we search the first occurrence
            final int rearIndex = rear.reverse().indexOf(element, from - front.length());
            return (rearIndex == -1) ? -1 : rearIndex + front.length();
        }
    }

    @Override
    public Queue<T> init() {
        if (isEmpty()) {
            throw new UnsupportedOperationException("init of empty " + stringPrefix());
        } else if (rear.isEmpty()) {
            return new Queue<>(front.init(), rear);
        } else {
            return new Queue<>(front, rear.tail());
        }
    }

    @Override
    public Queue<T> insert(int index, T element) {
        if (index < 0) {
            throw new IndexOutOfBoundsException("insert(" + index + ", element)");
        }
        final int length = front.length();
        if (index <= length) {
            return new Queue<>(front.insert(index, element), rear);
        } else {
            final int rearIndex = index - length;
            final int rearLength = rear.length();
            if (rearIndex <= rearLength) {
                final int reverseRearIndex = rearLength - rearIndex;
                return new Queue<>(front, rear.insert(reverseRearIndex, element));
            } else {
                throw new IndexOutOfBoundsException("insert(" + index + ", element) on Queue of length " + length());
            }
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public Queue<T> insertAll(int index, Iterable<? extends T> elements) {
        Objects.requireNonNull(elements, "elements is null");
        if (index < 0) {
            throw new IndexOutOfBoundsException("insertAll(" + index + ", elements)");
        }
        final int length = front.length();
        if (index <= length) {
            if (isEmpty() && elements instanceof Queue) {
                return (Queue<T>) elements;
            } else {
                final io.vavr.collection.List<T> newFront = front.insertAll(index, elements);
                return (newFront == front) ? this : new Queue<>(newFront, rear);
            }
        } else {
            final int rearIndex = index - length;
            final int rearLength = rear.length();
            if (rearIndex <= rearLength) {
                final int reverseRearIndex = rearLength - rearIndex;
                final io.vavr.collection.List<T> newRear = rear.insertAll(reverseRearIndex, io.vavr.collection.List.ofAll(elements).reverse());
                return (newRear == rear) ? this : new Queue<>(front, newRear);
            } else {
                throw new IndexOutOfBoundsException("insertAll(" + index + ", elements) on Queue of length " + length());
            }
        }
    }

    @Override
    public Queue<T> intersperse(T element) {
        if (isEmpty()) {
            return this;
        } else if (rear.isEmpty()) {
            return new Queue<>(front.intersperse(element), rear);
        } else {
            return new Queue<>(front.intersperse(element), rear.intersperse(element).append(element));
        }
    }

    /**
     * A {@code Queue} is computed synchronously.
     *
     * @return false
     */
    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean isEmpty() {
        return front.isEmpty();
    }

    /**
     * A {@code Queue} is computed eagerly.
     *
     * @return false
     */
    @Override
    public boolean isLazy() {
        return false;
    }

    @Override
    public boolean isTraversableAgain() {
        return true;
    }

    @Override
    public int lastIndexOf(T element, int end) {
        return toList().lastIndexOf(element, end);
    }

    @Override
    public int length() {
        return front.length() + rear.length();
    }

    @Override
    public  Queue map(Function<? super T, ? extends U> mapper) {
        Objects.requireNonNull(mapper, "mapper is null");
        return new Queue<>(front.map(mapper), rear.map(mapper));
    }

    @Override
    public Queue<T> orElse(Iterable<? extends T> other) {
        return isEmpty() ? ofAll(other) : this;
    }

    @Override
    public Queue<T> orElse(Supplier<? extends Iterable<? extends T>> supplier) {
        return isEmpty() ? ofAll(supplier.get()) : this;
    }

    @Override
    public Queue<T> padTo(int length, T element) {
        final int actualLength = length();
        if (length <= actualLength) {
            return this;
        } else {
            return ofAll(toList().padTo(length, element));
        }
    }

    @Override
    public Queue<T> leftPadTo(int length, T element) {
        final int actualLength = length();
        if (length <= actualLength) {
            return this;
        } else {
            return ofAll(toList().leftPadTo(length, element));
        }
    }

    @Override
    public Queue<T> patch(int from, Iterable<? extends T> that, int replaced) {
        from = from < 0 ? 0 : from;
        replaced = replaced < 0 ? 0 : replaced;
        Queue<T> result = take(from).appendAll(that);
        from += replaced;
        result = result.appendAll(drop(from));
        return result;
    }

    @Override
    public Tuple2<Queue<T>, Queue<T>> partition(Predicate<? super T> predicate) {
        Objects.requireNonNull(predicate, "predicate is null");
        return toList().partition(predicate).map(io.vavr.collection.List::toQueue, io.vavr.collection.List::toQueue);
    }

    @Override
    public Queue<Queue<T>> permutations() {
        return ofAll(toList().permutations().map(io.vavr.collection.List::toQueue));
    }

    @Override
    public Queue<T> prepend(T element) {
        return new Queue<>(front.prepend(element), rear);
    }

    @SuppressWarnings("unchecked")
    @Override
    public Queue<T> prependAll(Iterable<? extends T> elements) {
        Objects.requireNonNull(elements, "elements is null");
        if (isEmpty() && elements instanceof Queue) {
            return (Queue<T>) elements;
        } else {
            final io.vavr.collection.List<T> newFront = front.prependAll(elements);
            return (newFront == front) ? this : new Queue<>(newFront, rear);
        }
    }

    @Override
    public Queue<T> remove(T element) {
        final io.vavr.collection.List<T> removed = toList().remove(element);
        return ofAll(removed.length() == length() ? this : removed);
    }

    @Override
    public Queue<T> removeFirst(Predicate<T> predicate) {
        final io.vavr.collection.List<T> removed = toList().removeFirst(predicate);
        return ofAll(removed.length() == length() ? this : removed);
    }

    @Override
    public Queue<T> removeLast(Predicate<T> predicate) {
        final io.vavr.collection.List<T> removed = toList().removeLast(predicate);
        return ofAll(removed.length() == length() ? this : removed);
    }

    @Override
    public Queue<T> removeAt(int index) {
        return ofAll(toList().removeAt(index));
    }

    @Override
    public Queue<T> removeAll(T element) {
        return io.vavr.collection.Collections.removeAll(this, element);
    }

    @Override
    public Queue<T> replace(T currentElement, T newElement) {
        final io.vavr.collection.List<T> newFront = front.replace(currentElement, newElement);
        final io.vavr.collection.List<T> newRear = rear.replace(currentElement, newElement);
        return newFront.size() + newRear.size() == 0 ? empty()
                                                     : newFront == front && newRear == rear ? this
                                                                                : new Queue<>(newFront, newRear);
    }

    @Override
    public Queue<T> replaceAll(T currentElement, T newElement) {
        final io.vavr.collection.List<T> newFront = front.replaceAll(currentElement, newElement);
        final io.vavr.collection.List<T> newRear = rear.replaceAll(currentElement, newElement);
        return newFront.size() + newRear.size() == 0 ? empty()
                                                     : newFront == front && newRear == rear ? this
                                                                                : new Queue<>(newFront, newRear);
    }

    @Override
    public Queue<T> reverse() {
        return isEmpty() ? this : ofAll(toList().reverse());
    }

    @Override
    public Queue<T> scan(T zero, BiFunction<? super T, ? super T, ? extends T> operation) {
        return scanLeft(zero, operation);
    }

    @Override
    public  Queue scanLeft(U zero, BiFunction<? super U, ? super T, ? extends U> operation) {
        return io.vavr.collection.Collections.scanLeft(this, zero, operation, Iterator::toQueue);
    }

    @Override
    public  Queue scanRight(U zero, BiFunction<? super T, ? super U, ? extends U> operation) {
        return io.vavr.collection.Collections.scanRight(this, zero, operation, Iterator::toQueue);
    }

    @Override
    public Queue<T> shuffle() {
        return io.vavr.collection.Collections.shuffle(this, Queue::ofAll);
    }

    @Override
    public Queue<T> slice(int beginIndex, int endIndex) {
        return ofAll(toList().slice(beginIndex, endIndex));
    }

    @Override
    public Iterator<Queue<T>> slideBy(Function<? super T, ?> classifier) {
        return iterator().slideBy(classifier).map(Queue::ofAll);
    }

    @Override
    public Iterator<Queue<T>> sliding(int size) {
        return sliding(size, 1);
    }

    @Override
    public Iterator<Queue<T>> sliding(int size, int step) {
        return iterator().sliding(size, step).map(Queue::ofAll);
    }

    @Override
    public Queue<T> sorted() {
        return ofAll(toList().sorted());
    }

    @Override
    public Queue<T> sorted(Comparator<? super T> comparator) {
        Objects.requireNonNull(comparator, "comparator is null");
        return ofAll(toList().sorted(comparator));
    }

    @Override
    public <U extends Comparable<? super U>> Queue<T> sortBy(Function<? super T, ? extends U> mapper) {
        return sortBy(U::compareTo, mapper);
    }

    @Override
    public  Queue<T> sortBy(Comparator<? super U> comparator, Function<? super T, ? extends U> mapper) {
        final Function<? super T, ? extends U> domain = Function1.of(mapper::apply).memoized();
        return toJavaStream()
                .sorted((e1, e2) -> comparator.compare(domain.apply(e1), domain.apply(e2)))
                .collect(collector());
    }

    @Override
    public Tuple2<Queue<T>, Queue<T>> span(Predicate<? super T> predicate) {
        Objects.requireNonNull(predicate, "predicate is null");
        return toList().span(predicate).map(io.vavr.collection.List::toQueue, io.vavr.collection.List::toQueue);
    }

    @Override
    public Tuple2<Queue<T>, Queue<T>> splitAt(int n) {
        return toList().splitAt(n).map(io.vavr.collection.List::toQueue, io.vavr.collection.List::toQueue);
    }

    @Override
    public Tuple2<Queue<T>, Queue<T>> splitAt(Predicate<? super T> predicate) {
        return toList().splitAt(predicate).map(io.vavr.collection.List::toQueue, io.vavr.collection.List::toQueue);
    }

    @Override
    public Tuple2<Queue<T>, Queue<T>> splitAtInclusive(Predicate<? super T> predicate) {
        return toList().splitAtInclusive(predicate).map(io.vavr.collection.List::toQueue, io.vavr.collection.List::toQueue);
    }

    @Override
    public boolean startsWith(Iterable<? extends T> that, int offset) {
        return toList().startsWith(that, offset);
    }

    @Override
    public Queue<T> subSequence(int beginIndex) {
        if (beginIndex < 0 || beginIndex > length()) {
            throw new IndexOutOfBoundsException("subSequence(" + beginIndex + ")");
        } else {
            return drop(beginIndex);
        }
    }

    @Override
    public Queue<T> subSequence(int beginIndex, int endIndex) {
        Collections.subSequenceRangeCheck(beginIndex, endIndex, length());
        if (beginIndex == endIndex) {
            return empty();
        } else if (beginIndex == 0 && endIndex == length()) {
            return this;
        } else {
            return ofAll(toList().subSequence(beginIndex, endIndex));
        }
    }

    @Override
    public Queue<T> tail() {
        if (isEmpty()) {
            throw new UnsupportedOperationException("tail of empty " + stringPrefix());
        } else {
            return new Queue<>(front.tail(), rear);
        }
    }

    @Override
    public Queue<T> take(int n) {
        if (n <= 0) {
            return empty();
        }
        if (n >= length()) {
            return this;
        }
        final int frontLength = front.length();
        if (n < frontLength) {
            return new Queue<>(front.take(n), io.vavr.collection.List.empty());
        } else if (n == frontLength) {
            return new Queue<>(front, io.vavr.collection.List.empty());
        } else {
            return new Queue<>(front, rear.takeRight(n - frontLength));
        }
    }

    @Override
    public Queue<T> takeUntil(Predicate<? super T> predicate) {
        Objects.requireNonNull(predicate, "predicate is null");
        final io.vavr.collection.List<T> taken = toList().takeUntil(predicate);
        return taken.length() == length() ? this : ofAll(taken);
    }

    @Override
    public Queue<T> takeRight(int n) {
        if (n <= 0) {
            return empty();
        }
        if (n >= length()) {
            return this;
        }
        final int rearLength = rear.length();
        if (n < rearLength) {
            return new Queue<>(rear.take(n).reverse(), io.vavr.collection.List.empty());
        } else if (n == rearLength) {
            return new Queue<>(rear.reverse(), io.vavr.collection.List.empty());
        } else {
            return new Queue<>(front.takeRight(n - rearLength), rear);
        }
    }

    @Override
    public Queue<T> takeRightUntil(Predicate<? super T> predicate) {
        Objects.requireNonNull(predicate, "predicate is null");
        final io.vavr.collection.List<T> taken = toList().takeRightUntil(predicate);
        return taken.length() == length() ? this : ofAll(taken);
    }

    @Override
    public Queue<T> takeRightWhile(Predicate<? super T> predicate) {
        Objects.requireNonNull(predicate, "predicate is null");
        return takeRightUntil(predicate.negate());
    }

    /**
     * Transforms this {@code Queue}.
     *
     * @param f   A transformation
     * @param  Type of transformation result
     * @return An instance of type {@code U}
     * @throws NullPointerException if {@code f} is null
     */
    public  U transform(Function<? super Queue<T>, ? extends U> f) {
        Objects.requireNonNull(f, "f is null");
        return f.apply(this);
    }

    @Override
    public <T1, T2> Tuple2<Queue<T1>, Queue<T2>> unzip(
            Function<? super T, Tuple2<? extends T1, ? extends T2>> unzipper) {
        Objects.requireNonNull(unzipper, "unzipper is null");
        return toList().unzip(unzipper).map(io.vavr.collection.List::toQueue, io.vavr.collection.List::toQueue);
    }

    @Override
    public <T1, T2, T3> Tuple3<Queue<T1>, Queue<T2>, Queue<T3>> unzip3(Function<? super T, Tuple3<? extends T1, ? extends T2, ? extends T3>> unzipper) {
        Objects.requireNonNull(unzipper, "unzipper is null");
        return toList().unzip3(unzipper).map(io.vavr.collection.List::toQueue, io.vavr.collection.List::toQueue, io.vavr.collection.List::toQueue);
    }

    @Override
    public Queue<T> update(int index, T element) {
        return ofAll(toList().update(index, element));
    }

    @Override
    public Queue<T> update(int index, Function<? super T, ? extends T> updater) {
        Objects.requireNonNull(updater, "updater is null");
        return update(index, updater.apply(get(index)));
    }

    @Override
    public  Queue<Tuple2<T, U>> zip(Iterable<? extends U> that) {
        return zipWith(that, Tuple::of);
    }

    @SuppressWarnings("unchecked")
    @Override
    public  Queue<R> zipWith(Iterable<? extends U> that, BiFunction<? super T, ? super U, ? extends R> mapper) {
        Objects.requireNonNull(that, "that is null");
        Objects.requireNonNull(mapper, "mapper is null");
        return ofAll(toList().zipWith(that, mapper));
    }

    @Override
    public  Queue<Tuple2<T, U>> zipAll(Iterable<? extends U> that, T thisElem, U thatElem) {
        Objects.requireNonNull(that, "that is null");
        return ofAll(toList().zipAll(that, thisElem, thatElem));
    }

    @Override
    public Queue<Tuple2<T, Integer>> zipWithIndex() {
        return zipWithIndex(Tuple::of);
    }

    @Override
    public  Queue zipWithIndex(BiFunction<? super T, ? super Integer, ? extends U> mapper) {
        Objects.requireNonNull(mapper, "mapper is null");
        return ofAll(toList().zipWithIndex(mapper));
    }

    private Object readResolve() {
        return isEmpty() ? EMPTY : this;
    }

    @Override
    public String stringPrefix() {
        return "Queue";
    }

    @Override
    public boolean equals(Object o) {
        return io.vavr.collection.Collections.equals(this, o);
    }

    @Override
    public int hashCode() {
        return io.vavr.collection.Collections.hashOrdered(this);
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>net.networkdowntime</groupId>
	<artifactId>embeddableSearch</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<build>

		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.3</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>

	</build>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.codehaus.sonar</groupId>
			<artifactId>sonar-maven-plugin</artifactId>
			<version>5.1</version>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.4</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>net.sf.trove4j</groupId>
			<artifactId>trove4j</artifactId>
			<version>3.0.3</version>
		</dependency>

		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-api</artifactId>
			<version>2.4.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
			<version>2.4.1</version>
		</dependency>
	</dependencies>

</project>

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using RecommendationSystem.Entities;
using RecommendationSystem.Prediction;
using RecommendationSystem.Svd.Foundation.Models;
using RecommendationSystem.Training;

namespace RecommendationSystem.Svd.Foundation.Training
{
    public class SvdBiasBinsCalculator<TSvdBiasBinsModel> : BiasBinsCalculatorBase<TSvdBiasBinsModel>
        where TSvdBiasBinsModel : ISvdBiasBinsModel
    {
        public SvdBiasBinsCalculator(IPredictor<TSvdBiasBinsModel> predictor)
            : base(predictor)
        {}

        #region CalculateBiasBins
        public override void CalculateBiasBins(TSvdBiasBinsModel model, List<IRating> ratings, List<IUser> users, List<IArtist> artists, int biasBinCount)
        {
            Console.WriteLine("Calculating BiasBins...");

            var biasBins = new float[biasBinCount];
            var biasBinsPopulation = new int[biasBinCount];

            var percent = users.Count / 100;
            for (var i = 0; i < users.Count; i++)
            {
                var user = users[i];
                lock (user)
                {
                    if (user.Ratings.Count > 1)
                    {
                        var originalRatings = user.Ratings;
                        foreach (var rating in user.Ratings)
                        {
                            user.Ratings = originalRatings.Where(r => r != rating).ToList();
                            var predictedRating = Predictor.PredictRatingForArtist(user, model, artists, rating.ArtistIndex);

                            var error = predictedRating - rating.Value;
                            var biasBinIndex = GetBiasBinIndex(predictedRating, biasBinCount);
                            biasBins[biasBinIndex] += error;
                            biasBinsPopulation[biasBinIndex]++;
                        }
                        user.Ratings = originalRatings;
                    }

                    if (i % percent == 0)
                        Console.WriteLine("BiasBins calculation at {0} ({1}%)", i, i / percent);
                }
            }

            for (var i = 0; i < biasBinCount; i++)
            {
                if (biasBinsPopulation[i] > 0)
                    biasBins[i] /= biasBinsPopulation[i];
                else
                    biasBins[i] = 0.0f;
            }

            model.BiasBins = biasBins;

            Console.WriteLine("BiasBins calculation complete");
        }
        #endregion
    }
}


text:
package org.kiji.express.flow.framework

import org.apache.hadoop.hbase.HBaseConfiguration
import org.apache.hadoop.mapred.JobConf
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

import org.kiji.express.KijiSuite
import org.kiji.express.flow.ColumnInputSpec
import org.kiji.express.flow.InvalidKijiTapException
import org.kiji.express.flow.RowFilterSpec
import org.kiji.express.flow.RowRangeSpec
import org.kiji.express.flow.TimeRangeSpec
import org.kiji.express.flow.util.ResourceUtil
import org.kiji.express.flow.util.TestingResourceUtil
import org.kiji.schema.KijiURI
import org.kiji.schema.layout.KijiTableLayout

@RunWith(classOf[JUnitRunner])
class KijiTapSuite extends KijiSuite {
  val instanceName: String = "test_KijiTap_instance"
  val testKijiTableLayout: KijiTableLayout = TestingResourceUtil.layout("layout/avro-types.json")
  val config: JobConf = new JobConf(HBaseConfiguration.create())

  test("KijiTap validates a valid instance/table/column.") {
    val testTable = makeTestKijiTable(testKijiTableLayout, instanceName)
    val kijiURI = testTable.getURI

    val testScheme: KijiScheme = new KijiScheme(
        tableAddress = kijiURI.toString,
        timeRange = TimeRangeSpec.All,
        timestampField = None,
        icolumns = Map(
            "dummy_field1" -> ColumnInputSpec("searches"),
            "dummy_field2" -> ColumnInputSpec("family:column1")),
        rowRangeSpec = RowRangeSpec.All,
        rowFilterSpec = RowFilterSpec.NoFilter)

    val testTap: KijiTap = new KijiTap(kijiURI, testScheme)

    testTap.validate(config)
  }

  test("KijiTap validates a nonexistent instance.") {
    val testTable = makeTestKijiTable(testKijiTableLayout, instanceName)
    val kijiURI = testTable.getURI

    val testScheme: KijiScheme = new KijiScheme(
        tableAddress = kijiURI.toString,
        timeRange = TimeRangeSpec.All,
        timestampField = None,
        icolumns = Map(
            "dummy_field1" -> ColumnInputSpec("searches"),
            "dummy_field2" -> ColumnInputSpec("family:column1")),
        rowRangeSpec = RowRangeSpec.All,
        rowFilterSpec = RowFilterSpec.NoFilter)

    val testURI: KijiURI = KijiURI.newBuilder(kijiURI)
        .withInstanceName("nonexistent_instance")
        .build()

    val testTap: KijiTap = new KijiTap(testURI, testScheme)

    intercept[InvalidKijiTapException] {
      testTap.validate(config)
    }
  }

  test("KijiTap validates a nonexistent table.") {
    val testTable = makeTestKijiTable(testKijiTableLayout, instanceName)
    val kijiURI = testTable.getURI

    val testScheme: KijiScheme = new KijiScheme(
        tableAddress = kijiURI.toString,
        timeRange = TimeRangeSpec.All,
        timestampField = None,
        icolumns = Map(
            "dummy_field1" -> ColumnInputSpec("searches"),
            "dummy_field2" -> ColumnInputSpec("family:column1")),
        rowRangeSpec = RowRangeSpec.All,
        rowFilterSpec = RowFilterSpec.NoFilter)

    val testURI: KijiURI = KijiURI.newBuilder(kijiURI)
        .withTableName("nonexistent_table")
        .build()

    val testTap: KijiTap = new KijiTap(testURI, testScheme)

    intercept[InvalidKijiTapException] {
      testTap.validate(config)
    }
  }

  test("KijiTap validates a nonexistent column.") {
    val testTable = makeTestKijiTable(testKijiTableLayout, instanceName)
    val kijiURI = testTable.getURI

    val testScheme: KijiScheme = new KijiScheme(
        tableAddress = kijiURI.toString,
        timeRange = TimeRangeSpec.All,
        timestampField = None,
        icolumns = Map(
            "dummy_field1" -> ColumnInputSpec("searches"),
            "dummy_field2" -> ColumnInputSpec("family:nonexistent")),
        rowRangeSpec = RowRangeSpec.All,
        rowFilterSpec = RowFilterSpec.NoFilter)

    val testTap: KijiTap = new KijiTap(kijiURI, testScheme)

    val exception = intercept[InvalidKijiTapException] {
      testTap.validate(config)
    }

    assert(exception.getMessage.contains("nonexistent"))
  }

  test("KijiTap validates multiple nonexistent columns.") {
    val testTable = makeTestKijiTable(testKijiTableLayout, instanceName)
    val kijiURI = testTable.getURI

    val testScheme: KijiScheme = new KijiScheme(
        tableAddress = kijiURI.toString,
        timeRange = TimeRangeSpec.All,
        timestampField = None,
        icolumns = Map(
            "dummy_field1" -> ColumnInputSpec("nonexistent1"),
            "dummy_field2" -> ColumnInputSpec("family:nonexistent2")),
        rowRangeSpec = RowRangeSpec.All,
        rowFilterSpec = RowFilterSpec.NoFilter)

    val testTap: KijiTap = new KijiTap(kijiURI, testScheme)

    val exception = intercept[InvalidKijiTapException] {
      testTap.validate(config)
    }

    assert(exception.getMessage.contains("nonexistent1"))
    assert(exception.getMessage.contains("nonexistent2"))
  }
}


text:
@interface PodsDummy_YSMCategory : NSObject
@end
@implementation PodsDummy_YSMCategory
@end


text:
import bpy, mathutils
from macouno import mesh_extras

# Select all faces (or deselect)
def all(invert=False):
	for f in bpy.context.active_object.data.faces:
		f.select = True
	return

# Select all faces (or deselect)
def none():
	for f in bpy.context.active_object.data.faces:
		f.select = False
	return

# Faces connected to the current selection
def connected(extend=False):

	mesh = bpy.context.active_object.data

	if len(mesh.faces):

		# Get a list of all vertices in selected faces
		vList = []
		for f in mesh.faces:
			if f.select:
				vList.extend(f.vertices)

		if len(vList):
			# For every deselected face, see if it shares a vert with a selected face
			selFaces = []
			for f in mesh.faces:
				if not f.select:
					for v in f.vertices:
						if v in vList:
							selFaces.append(f)
							break

			if len(selFaces):
				# Select only the connected faces
				if not extend:
					for f in mesh.faces:
						if f in selFaces:
							f.select = True
						else:
							f.select = False

				# Add the connected faces to the current selection
				else:
					for f in selFaces:
						f.select=True

	return

# Innermost faces
def innermost(invert=False):

	mesh = bpy.context.active_object.data

	# No use continueing if there's no edges
	if len(mesh.faces):

		# Get a list with the selected items
		oItems = mesh_extras.get_selected('faces',False)
		oLen = len(oItems)

		# No use continueing if there's no selected items and deselected items
		if oLen and mesh_extras.has_selected('faces',True):

			nItems = oItems
			nLen = oLen

			while True:
				cLen = nLen
				cItems = nItems

				# Deselect the outermost items
				outermost(True)

				nItems = mesh_extras.get_selected('faces',False)
				nLen = len(nItems)

				if nLen >= cLen or not nLen:
					break

			# If we have a list with items, and it's smaller than the original
			if cLen and cLen < oLen:
				for item in oItems:
					if not invert and item in cItems:
						item.select = True

					elif invert and not item in cItems:
						item.select = True

	return

# Select the outermost items in the current selection
# mesh=mesh data, invert = True or False
def outermost(invert=False):

	mesh = bpy.context.active_object.data

	if len(mesh.faces):

		# Get a list of all vertices in deselected faces
		vList = []
		for f in mesh.faces:
			if not f.select:
				vList.extend(f.vertices)

		if len(vList):
			# For every deselected face, see if it shares a vert with a selected face
			selFaces = []
			for f in mesh.faces:
				if  f.select:
					for v in f.vertices:
						if v in vList:
							selFaces.append(f)
							break

			if len(selFaces):
				# Select only the connected faces
				if not invert:
					for f in mesh.faces:
						if f in selFaces:
							f.select = True
						else:
							f.select = False

				# Add the connected faces to the current selection
				else:
					for f in selFaces:
						f.select=False

	return

# Select checkered faces
def checkered(seed=0, extend=False):

	import random
	random.seed(str(seed))

	mesh = bpy.context.active_object.data

	# Two lists of faces selFaces to be selected unFaces to be deselected
	selFaces = []
	unFaces = list(mesh.faces)

	# Put 1 face in the list of selected faces (and remove from unselected faces)
	f = random.choice(unFaces)
	selFaces.append(f)
	unFaces.remove(f)

	preSel = len(selFaces)

	# make sure there's faces before we continue!
	if not preSel:
		return

	postSel = preSel + 1
	start = True

	# As long as we keep selecting more... we have to continue (to go over all the mesh)
	while postSel > preSel:

		if start:
			start = False
		else:
			preSel = postSel

		# Add the faces at the corners of the current selection to this one
		selFaces, unFaces = addCornered(selFaces, unFaces)

		postSel = len(selFaces)

	# Select the faces we found!
	selectFaces(selFaces, extend)

	return

def addCornered(selFaces, unFaces):

	# Loop through the unselected faces to find out if they should be selected
	for f in unFaces:

		verts = f.vertices
		sel = 0

		# Check against the selected faces
		for fs in selFaces:

			# Find the verts shared between these faces
			intersection = [v for v in verts if v in fs.vertices]
			intLen = len(intersection)

			# If there's just the one intersection it's a corner connection
			if intLen == 1 and sel == 0:
				sel = 1

			# If there's more than one... it's sharing an edge
			elif intLen > 1:
				sel = 2
				break

		# If it's just a corner
		if sel == 1:
			selFaces.append(f)
			unFaces.remove(f)

	return selFaces, unFaces

# Select all the faces in a certain vertex group
def in_group(group,extend=False):

	groupId = group.index
	mesh = bpy.context.active_object.data

	selFaces = []

	# Find all the faces with all verts (3 or more) in this group
	for f in mesh.faces:
		grCnt = 0
		for v in f.vertices:
			vert = mesh.vertices[v]
			try:
				for g in vert.groups:
					if g.group == groupId:
						grCnt += 1
						break
			except:
				pass

		if grCnt == len(f.vertices):
			selFaces.append(f)

	selectFaces(selFaces, extend)

	return

# Go select a list of faces (if they need to be, depending on settings and situations)
def selectFaces(selFaces, extend=False):

	mesh = bpy.context.active_object.data

	hasSelected = mesh_extras.contains_selected_item(mesh.faces)

	for f in mesh.faces:

		# We extend and have a selection, so we just need to select extra stuff
		# Selecting what is already selected does no harm
		if extend and hasSelected:

			if f in selFaces:
				f.select = True

		# If we already have a selection and we don't extend.. we just deselect what is selected
		elif hasSelected:

			if not f in selFaces:
				f.select = False

		# If we have no selection yet.. we only select what's in the list
		else:

			if f in selFaces:
				f.select = True

	return

# Select by direction
def by_direction(direction, divergence, extend=False):

	mesh = bpy.context.active_object.data
	direction = mathutils.Vector(direction)

	hasSelected = mesh_extras.contains_selected_item(mesh.faces)

	# Make sure there's an actual directions
	if direction.length:

		# Loop through all the given faces
		for f in mesh.faces:

			isSelected = f.select
			s = selectCheck(isSelected, hasSelected, extend)
			d = deselectCheck(isSelected, hasSelected, extend)

			angle = direction.angle(f.normal)

			if s and angle <= divergence:
				f.select = True
			elif d and angle > divergence:
				f.select = False

	return

# Do a semi random select based on a number
def liberal(key='', extend=False):

	from macouno import liberty
	lib = liberty.liberty('bool', key)

	mesh = bpy.context.active_object.data

	hasSelected = mesh_extras.contains_selected_item(mesh.faces)

	# Loop through all the given faces
	for f in mesh.faces:

		s = selectCheck(f.select, hasSelected, extend)
		d = deselectCheck(f.select, hasSelected, extend)

		# Check if the faces match any of the directions
		if s and lib.Choose('bool'):
			f.select = True

		if d and not lib.Choose('bool'):
			f.select = False

	return

# Make sure there are less faces selected than the limit
def limit(limit=1, key=''):

	from macouno import liberty
	lib = liberty.liberty('string', key)

	nuFaces = lib.makeDict(mesh_extras.get_selected_faces())
	nuLen = len(nuFaces)

	while nuLen > limit:

		deFace = lib.Choose('select',nuFaces)

		deFace.select = False

		nuFaces = lib.makeDict(mesh_extras.get_selected_faces())
		nuLen = len(nuFaces)

	return

# See if the current item should be selected or not
def selectCheck(isSelected, hasSelected, extend):

	# If we are extending or nothing is selected we want to select
	if extend or not hasSelected:
		return True

	return False

# See if the current item should be deselected or not
def deselectCheck(isSelected, hasSelected, extend):

	# If something is selected and we're not extending we want to deselect
	if hasSelected and not extend:
		return True

	return False


text:
import cm = require('../common');
import ctxm = require('../context');
import path = require('path');
import shell = require('shelljs');
import tm = require('../tracing');
import cmdm = require('../commands/command');
import agentifm = require('vso-node-api/interfaces/TaskAgentInterfaces');

var vsotask = require('vso-task-lib');

var _commandPath = path.resolve(__dirname, '../commands');

var _trace: tm.Tracing;

var _cmdQueue: cm.IAsyncCommandQueue;

function _processLine(line: string, executionContext: cm.IExecutionContext): void {
	if (line.startsWith(cm.CMD_PREFIX)) {
        _handleCommand(line, executionContext);
	}
    else {
        executionContext.info(line);
    }
}

function _handleCommand(commandLine: string, executionContext: cm.IExecutionContext) {
    var cmd: cm.ITaskCommand;

    try {
        var temp = vsotask.commandFromString(commandLine);
        cmd = new cmdm.TaskCommand(temp.command, temp.properties, temp.message);
    }
    catch(err) {
        executionContext.warning(err.message + ': ' + commandLine);
        return;
    }

    var cmdModulePath = path.join(__dirname, '..', 'commands', cmd.command + '.js');
    if (!shell.test('-f', cmdModulePath)) {
        executionContext.warning('command module does not exist: ' + cmd.command);
        return;
    }

    var cmdPlugin = require(cmdModulePath);

    if (cmdPlugin.createSyncCommand) {
        var syncCmd = cmdPlugin.createSyncCommand(cmd);
        syncCmd.runCommand(executionContext);
    }
    else if (cmdPlugin.createAsyncCommand) {
        var asyncCmd = cmdPlugin.createAsyncCommand(executionContext, cmd);
        _cmdQueue.push(asyncCmd);
    }
    else {
        executionContext.warning('Command does not implement runCommand or runCommandAsync: ' + cmd.command);
    }
}

export function run(scriptEngine: string, scriptPath: string, executionContext: cm.IExecutionContext, callback) {
    _trace = new tm.Tracing(__filename, executionContext);
    _cmdQueue = executionContext.service.createAsyncCommandQueue(executionContext);
    _cmdQueue.startProcessing();

    var jobMessage: agentifm.JobRequestMessage = executionContext.jobInfo.jobMessage;

    //
    // Inputs
    //
    var env = {}

    // deep copy the vars so we don't dirty the workers environment with
    // a specific tasks inputs etc...
    for (var key in process.env) {
        env[key] = process.env[key];
    }

    _trace.write('setting inputs as environment variables');
    for (var key in executionContext.inputs){
        var envVarName = 'INPUT_' + key.replace(' ', '_').toUpperCase();
        env[envVarName] = executionContext.inputs[key];
        _trace.write('INPUT VAR: ' + envVarName + '=' + env[envVarName]);
    }

    //
    // Variables
    //
    var vars = jobMessage.environment.variables;
    for (var variable in vars) {
        var envVarName: string = variable.replace(".", "_").toUpperCase();
        env[envVarName] = vars[variable];
        _trace.write('VAR VAL: ' + envVarName + '=' + vars[variable]);
    }

    //
    // Endpoints
    //

    //system
    env['ENDPOINT_URL_SYSTEMVSSCONNECTION'] = jobMessage.environment.systemConnection.url;
    _trace.write('ENDPOINT_URL_SYSTEMVSSCONNECTION=' + env['ENDPOINT_URL_SYSTEMVSSCONNECTION']);
    env['ENDPOINT_AUTH_SYSTEMVSSCONNECTION'] = JSON.stringify(jobMessage.environment.systemConnection.authorization);
    _trace.state('ENDPOINT_AUTH_SYSTEMVSSCONNECTION', JSON.parse(env['ENDPOINT_AUTH_SYSTEMVSSCONNECTION']));

    //external
    var endpoints = jobMessage.environment.endpoints;
    if (endpoints) {
        for (var i=0; i < endpoints.length; i++) {
            var endpoint = endpoints[i];
            _trace.state('service endpoint', endpoint);

            if (endpoint.id && endpoint.url && endpoint.authorization) {
                env['ENDPOINT_URL_' + endpoint.id] = endpoint.url;
                env['ENDPOINT_AUTH_' + endpoint.id] = JSON.stringify(endpoint.authorization);
            }
        }
    }

    var ops = {
        cwd: process.cwd(),
        env: env
    };

    executionContext.verbose('cwd: ' + ops.cwd);

    var cp = require('child_process').spawn;

    var engPath = shell.which(scriptEngine);
    if (!engPath) {
        callback(new Error('Invalid script engine: ' + scriptEngine), 1);
        return;
    }
    _trace.write('engPath: ' + engPath);

    if (!shell.test('-f', scriptPath)) {
        callback(new Error('Invalid script path: ' + scriptPath), 1);
        return;
    }
    _trace.write('scriptPath: ' + scriptPath);

    var runCP = cp(engPath, [scriptPath], ops);

    var _handleData = function(data, buffer, onLine:(line: string) => void) {
    	var s = buffer + data.toString();
    	var n = s.indexOf('\n');

    	while(n > -1) {
    		var line = s.substring(0, n);
    		onLine(line);

    		s = s.substring(n + 1);
    		n = s.indexOf('\n');
    	}

    	buffer = s;
    }

    var _flushErrorBuffer = function() {
        if (_errBuffer.length > 0) {
            executionContext.error(_errBuffer);
            _errBuffer = '';
        }
    }

    // we want to split stdout on lines for commands
	var _outBuffer = '';
    runCP.stdout.on('data', function(data) {
        _flushErrorBuffer();
        _handleData(data, _outBuffer, (line: string) => {
            _processLine(line, executionContext);
        });
    });

    // for errors however, we want to send a whole block
    // of errout as one error (issue) up until we hit stdout again (stack trace for example)
    var _errBuffer = '';
    runCP.stderr.on('data', function(data) {
        _errBuffer += data.toString();
    });

    runCP.on('exit', function(code) {
        _trace.write('exit: ' + code);

        // drain buffers
        if (_outBuffer.length > 0) {
            executionContext.info(_outBuffer);
        }

        _flushErrorBuffer();

        // drain async commands
        _cmdQueue.finishAdding();
        _cmdQueue.waitForEmpty()
        .then(function() {
            if (code == 0) {
                if (_cmdQueue.failed) {
                    callback(_cmdQueue.errorMessage, code);
                }
                else {
                    callback(null, code);
                }
            } else {
                var msg = 'Return code: ' + code;
                executionContext.error(msg);

                callback(new Error(msg), code);
            }
        })
    });
}


text:
from django.shortcuts import render_to_response
from django.template import RequestContext

from forms import Example1, Example2, Example3, Example4

def example1(request, form_class=Example1,
        template_name="foo/example1.html"):
    message = None
    if request.method == "POST":
        form = form_class(request.POST)
        if form.is_valid():
            message = "OK"
    else:
        form = form_class()
    return render_to_response(template_name, {
        "form": form,
        "message": message,
    }, context_instance=RequestContext(request))

def example2(request, form_class=Example2,
        template_name="foo/example2.html"):
    message = None
    if request.method == "POST":
        form = form_class(request.POST, prefix="test")
        if form.is_valid():
            message = "OK"
    else:
        form = form_class(prefix="test")
    return render_to_response(template_name, {
        "form": form,
        "message": message,
    }, context_instance=RequestContext(request))

def example3(request, form_class=Example3,
        template_name="foo/example3.html"):
    message = None
    if request.method == "POST":
        form = form_class(request.POST)
        if form.is_valid():
            message = "OK"
    else:
        form = form_class()
    return render_to_response(template_name, {
        "form": form,
        "message": message,
    }, context_instance=RequestContext(request))

def example4(request, form_class=Example4,
        template_name="foo/example4.html"):
    message = None
    if request.method == "POST":
        form = form_class(request.POST)
        if form.is_valid():
            message = "OK"
    else:
        form = form_class()
    return render_to_response(template_name, {
        "form": form,
        "message": message,
    }, context_instance=RequestContext(request))


text:
package org.dozer.vo.iface;

/**
 * @author Rob Volden
 */
public interface SubscriberIF {

    String getSubscriberNumber();
}


text:
@class DHCommand;

@interface DHCommandQueue : DHQueue

- (NSUInteger)enqueueAllNotCompleted:(NSArray*)commands;

@end


text:
var mqtt = require("mqtt");
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var io = require("socket.io-client");

function Connection(opt){

  EventEmitter.call(this);

  this.options = opt || {};
  this.options.forceNew = (opt.forceNew != null) ? opt.forceNew : false;

  this.socket = io.connect(this.options.server || "http://skynet.im", {
    port: this.options.port || 80,
    forceNew: this.options.forceNew,
    multiplex: !this.options.forceNew,
    'force new connection': this.options.forceNew
  });

  // mqttclient connection
  if (this.options.protocol == "mqtt") {
    this.mqttsettings = {
      keepalive: 1000,
      protocolId: 'MQIsdp',
      protocolVersion: 3,
      clientId: this.options.uuid
    }

    if (this.options.qos == undefined){
      this.options.qos = 0;
    }

    try {
      this.mqttclient = mqtt.createClient(this.options.mqttport || 1883, this.options.mqtthost || 'mqtt.skynet.im', this.mqttsettings);

      this.mqttclient.subscribe(this.options.uuid, {qos: this.options.qos});
      this.mqttclient.subscribe('broadcast', {qos: this.options.qos});
    } catch(err) {
      console.log(err);
    }
  } else {
    this.options.protocol = "websocket";

  }

  this.setup();
}

util.inherits(Connection, EventEmitter);

Connection.prototype.setup = function(){
  this.socket.once('connect', function(){
    this.emit('connect');

    if (this.options.protocol == "mqtt"){
      this.mqttclient.on('message', this.emit.bind(this, 'message'));
    } else {
      this.socket.on('message', this.emit.bind(this, 'message'));
    }

    this.socket.on('config', this.emit.bind(this, 'config'));
    this.socket.on('disconnect', this.emit.bind(this, 'disconnect'));
    this.socket.on('identify', this.identify.bind(this));
    this.socket.on('ready', this.emit.bind(this, 'ready'));
    this.socket.on('notReady', this.emit.bind(this, 'notReady'));

  }.bind(this));

  return this;
};

Connection.prototype.identify = function(){
  this.socket.emit('identity', {
    uuid: this.options.uuid,
    token: this.options.token,
    protocol: this.options.protocol
  });
  return this;
};

// Connection.prototype.send = function(data) {
Connection.prototype.message = function(data) {

  // Send the API request to Skynet
  if (typeof data !== 'object'){
    try{
      data = JSON.parse(data);
    } catch(e){
      data = {message: data};
    }
  }

  // if(data.payload == undefined){
  //   data.payload = data.message;
  //   try{
  //     delete data["message"];
  //   } catch (e){
  //     console.log(e);
  //   }
  // }

  data.protocol = this.options.protocol;
  data.fromUuid = this.options.uuid;
  data.qos = this.options.qos;

  // this.socket.emit('message', JSON.stringify(data));
  this.socket.emit('message', data);

  if (this.options.protocol == "mqtt"){
    // Publish to MQTT
    if(data.devices == "all" || data.devices == "*"){
      this.mqttclient.publish('broadcast', JSON.stringify(data.payload), {qos: this.options.qos});
    } else {

      if( typeof data.devices === 'string' ) {
        devices = [ data.devices ];
      } else {
        devices = data.devices;
      }

      for (var i = 0; i < devices.length; i++) {
        this.mqttclient.publish(devices[i], JSON.stringify(data.payload), {qos: this.options.qos});
      };

    }
  }else{
    this.socket.emit('message', data);
  }

  return this;
};

Connection.prototype.config = function(data, fn) {
  this.socket.emit('gatewayConfig', data, fn);
  return this;
};

Connection.prototype.update = function(data, fn) {
  this.socket.emit('update', data, fn);
  return this;
};

Connection.prototype.register = function(data, fn) {
  this.socket.emit('register', data, fn);
  return this;
};

Connection.prototype.unregister = function(data, fn) {
  this.socket.emit('unregister', data, fn);
  return this;
};

Connection.prototype.whoami = function(data, fn) {
  this.socket.emit('whoami', data, fn);
  return this;
};

Connection.prototype.devices = function(data, fn) {
  this.socket.emit('devices', data, fn);
  return this;
};

Connection.prototype.gatewayConfig = function(data, fn) {
  this.socket.emit('gatewayConfig', data, fn);
  return this;
};

Connection.prototype.status = function(data) {
  this.socket.emit('status', data);
  return this;
};

Connection.prototype.subscribe = function(data, fn) {
  this.socket.emit('subscribe', data, fn);
  if (this.options.protocol == "mqtt") {
    this.mqttclient.subscribe(data.uuid, {qos: this.options.qos});
  }
  return this;
};

Connection.prototype.unsubscribe = function(data, fn) {
  this.socket.emit('unsubscribe', data, fn);
  if (this.options.protocol == "mqtt") {
    this.mqttclient.subscribe(data.uuid);
  }
  return this;
};

Connection.prototype.authenticate = function(data, fn) {
  this.socket.emit('authenticate', data, fn);
  return this;
};

Connection.prototype.events = function(data, fn) {
  this.socket.emit('events', data, fn);
  return this;
};

Connection.prototype.close = function(){
  return this;
};

module.exports = Connection;


text:
<?xml version="1.0" encoding="UTF-8"?>
<extension id="textboxfield" status="released" xmlns="http://symphony-cms.com/schemas/extension/1.0">
	<name>Text Box</name>
	<description>The Text Box field is a replacement for both the standard text input and textarea fields. It combines both to create a field that supports text formatting and validation rules.</description>
	<repo type="github">https://github.com/rowan-lewis/textboxfield</repo>
	<url type="discuss">http://symphony-cms.com/discuss/thread/387/</url>
	<types>
		<type>Field Types</type>
	</types>
	<authors>
		<author>
			<name github="rowan-lewis" symphony="buzzomatic">Rowan Lewis</name>
			<website>http://nbsp.io</website>
		</author>
	</authors>
	<releases>
		<release version="2.3.3" date="2013-07-09" min="2.3.2">
			- Add class to the filter prefixes on the DSE for Symphony 2.3.3 compatibility
			- Add Polish translation. Thanks @idea07
		</release>
		<release version="2.3.2" date="2013-06-04" min="2.3.2">
			- Add support for `ImportableField` and `ExportableField` interfaces
			- Fix grouping output for field. Thanks @PascalPiche
			- Improve localisation. Thanks @jurajkapsz
		</release>
		<release version="2.3.1" date="2013-02-03" min="2.3">
			- General cleanup of Field to align closer with the core implementations.
			- Added Italian translation.
			- Fix character limiter feature, now with better UTF-8 support.
			- Add 'None' when the Textbox field is the first display column and the entry has no data so the entry link is created.
		</release>
		<release version="2.3" date="2012-06-02" min="2.3">
			- General maintenance for Symphony 2.3.
			- Added German translation.
			- Fixed issue where text formatter was causing corrupt handles.
			- Sorting is now done on `handle`, rather than `value` for a speed boost.
			- Fix empty elements appearing in the XML.
		</release>
		<release version="2.2" date="2011-04-11" min="2.2" max="2.2.5">
			- Fixed incorrect setting name for `column_length`.
			- Fixed issue causing JavaScript to be executed on the wrong page.
			- Don't rely on MySQL to create tables with the MyISAM, do it ourself.
		</release>
		<release version="2.1" date="2010-11-01" min="2.1">
			- Added checkbox to wrap output in CDATA regardless of formatting.
			- Added checkbox to toggle inclusion of handles in output.
			- Output values instead of handles as parameters if handles are disabled.
			- Fixed datasource filter editor JavaScript.
			- A couple of other minor issues.
		</release>
		<release version="2.0.14" date="2010-02-19">
			- Improved upgrade process.
			- Added a setting that lets you display more than 75 characters in publish table columns.
		</release>
		<release version="2.0.11" date="2009-12-09">
			- Really fixed the upgrade issues, *really!*
			- Changed the way handles are created to make sure they are always unique.
		</release>
		<release version="2.0.10" date="2009-12-01">
			- Fixed issue where upgrades for 2.0.9 where not being applied due to a Symphony bug.
		</release>
		<release version="2.0.9" date="2009-12-01">
			- Added a fancy interface to select filter modes when editing data sources.
			- Added ability to limit input to a specified length.
			- Fixed a few minor bugs.
		</release>
		<release version="2.0.6" date="2009-07-24">
			- Added 'raw' output mode to get unformatted data.
			- Added delegates to modify the publish panel.
		</release>
		<release version="2.0.4" date="2009-06-20">
			- Fixed a couple of minor issues with data sanitisation.
			- Added `starts-with`, `ends-with` and `contains` filter methods.
		</release>
		<release version="2.0.2" date="2009-05-11">
			- This is a complete rewrite of the old extension, it isn't backwards compatible, so don't try to upgrade.
		</release>
	</releases>
</extension>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Sydowia 11: 112 (1958)

#### Original name
Meliola roureae var. santaloidis Deighton

### Remarks
null


text:
module Batsir
  class FilterQueue
    include Enumerable

    attr_accessor :filters
    attr_accessor :notifiers

    def initialize
      @filters = []
      @notifiers = []
    end

    def add(operation)
      @filters << operation
    end

    def add_notifier(notifier)
      @notifiers << notifier
    end

    def each
      @filters.each {|op| yield op}
      @notifiers.each {|n| yield n}
    end

    def empty?
      !(@notifiers.any? || @filters.any?)
    end
  end
end


text:
namespace Microsoft.Azure.Management.TrafficManager.Models
{
    using Newtonsoft.Json;

    /// <summary>
    /// Defines values for EndpointMonitorStatus.
    /// </summary>
    /// <summary>
    /// Determine base value for a given allowed value if exists, else return
    /// the value itself
    /// </summary>
    [JsonConverter(typeof(EndpointMonitorStatusConverter))]
    public struct EndpointMonitorStatus : System.IEquatable<EndpointMonitorStatus>
    {
        private EndpointMonitorStatus(string underlyingValue)
        {
            UnderlyingValue=underlyingValue;
        }

        public static readonly EndpointMonitorStatus CheckingEndpoint = "CheckingEndpoint";

        public static readonly EndpointMonitorStatus Online = "Online";

        public static readonly EndpointMonitorStatus Degraded = "Degraded";

        public static readonly EndpointMonitorStatus Disabled = "Disabled";

        public static readonly EndpointMonitorStatus Inactive = "Inactive";

        public static readonly EndpointMonitorStatus Stopped = "Stopped";

        /// <summary>
        /// Underlying value of enum EndpointMonitorStatus
        /// </summary>
        private readonly string UnderlyingValue;

        /// <summary>
        /// Returns string representation for EndpointMonitorStatus
        /// </summary>
        public override string ToString()
        {
            return UnderlyingValue.ToString();
        }

        /// <summary>
        /// Compares enums of type EndpointMonitorStatus
        /// </summary>
        public bool Equals(EndpointMonitorStatus e)
        {
            return UnderlyingValue.Equals(e.UnderlyingValue);
        }

        /// <summary>
        /// Implicit operator to convert string to EndpointMonitorStatus
        /// </summary>
        public static implicit operator EndpointMonitorStatus(string value)
        {
            return new EndpointMonitorStatus(value);
        }

        /// <summary>
        /// Implicit operator to convert EndpointMonitorStatus to string
        /// </summary>
        public static implicit operator string(EndpointMonitorStatus e)
        {
            return e.UnderlyingValue;
        }

        /// <summary>
        /// Overriding == operator for enum EndpointMonitorStatus
        /// </summary>
        public static bool operator == (EndpointMonitorStatus e1, EndpointMonitorStatus e2)
        {
            return e2.Equals(e1);
        }

        /// <summary>
        /// Overriding != operator for enum EndpointMonitorStatus
        /// </summary>
        public static bool operator != (EndpointMonitorStatus e1, EndpointMonitorStatus e2)
        {
            return !e2.Equals(e1);
        }

        /// <summary>
        /// Overrides Equals operator for EndpointMonitorStatus
        /// </summary>
        public override bool Equals(object obj)
        {
            return obj is EndpointMonitorStatus && Equals((EndpointMonitorStatus)obj);
        }

        /// <summary>
        /// Returns for hashCode EndpointMonitorStatus
        /// </summary>
        public override int GetHashCode()
        {
            return UnderlyingValue.GetHashCode();
        }

    }
}


text:
var pokedraw = {

    screenSpecs : function() {
        return "width: " + screen.width + ", " +
               "height: " + screen.height + ", " +
               "depth: " + screen.colorDepth + ", " +
               "pixel: " + screen.pixelDepth;
    },
    handleEnd : function(evt) {
        evt.preventDefault();
        //alert(evt.clientX + "," + evt.clientY);
        dispatchClick(evt.clientX,evt.clientY)
    },
    updateDebug : function(box, message) {
	    // bit of a hack
        document.getElementById(box).innerHTML = message;
    }
};

const pokedraw_version = "0.9.6";

//
//    Setup the Canvas
//
var canvas               = document.getElementById("pokedraw_canvas");
var canvas_context       = canvas.getContext("2d");
canvas_context.fillStyle = cPokedrawColor.value;
canvas_context.fillRect(0,0, cPokedrawDim.canvas_width, cPokedrawDim.canvas_height);

// Touch API not working as of 2013-09-02
//canvas.addEventListener("touchend", pokedraw.handleEnd, false);
canvas.addEventListener('mouseup', pokedraw.handleEnd, false);

//
// Text (about)
//
var doc_title = document.getElementById('drawpoke_title');
var doc_heading = document.getElementById('AppName');
var doc_libversion = document.getElementById('LibVersion');
var doc_toolversion = document.getElementById('toolVersion');
var doc_buttonversion = document.getElementById('buttonVersion');
var span_screenSpec = document.getElementById('screenSpecs');

doc_title.innerHTML = doc_title.innerHTML + " " + pokedraw_version;
doc_heading.innerHTML = doc_heading.innerHTML + " " + pokedraw_version;
doc_libversion.innerHTML = drawtools_version;
//doc_toolversion.innerHTML = poketools_version;
doc_buttonversion.innerHTML = pokebuttons_version;
// poketools_version
// pokebuttons_version
span_screenSpec.innerHTML = pokedraw.screenSpecs();

//
// User tool status
//
objectToDraw = cPointsToOjectDraw[current_numPoints.value];
widthToDraw = cWidthToOjectDraw[current_width.value];
//somethingSomething = current_numPoints.value + "," + objectToDraw;

pokedraw.updateDebug('db3', objectToDraw);
// width of line use to draw
pokedraw.updateDebug('db2', widthToDraw);
// lineSegment Values
pokedraw.updateDebug('db1', '');
pokedraw.updateDebug('db0', '');


text:
package edu.columbia.tjw.item.fit.curve;

import edu.columbia.tjw.item.*;
import edu.columbia.tjw.item.algo.QuantileBreakdown;
import edu.columbia.tjw.item.algo.QuantileStatistics;
import edu.columbia.tjw.item.fit.ParamFittingGrid;
import edu.columbia.tjw.item.util.LogLikelihood;

import java.util.List;

/**
 * @param <S> The status type for this quantile distribution
 * @param <R> The regressor type for this quantile distribution
 * @author tyler
 */
public final class ItemQuantileDistribution<S extends ItemStatus<S>, R extends ItemRegressor<R>,
        T extends ItemCurveType<T>>
{
    private final LogLikelihood<S> _likelihood;
    private final QuantileStatistics _orig;
    private final QuantileStatistics _adjusted;

    public ItemQuantileDistribution(final ParamFittingGrid<S, R, T> grid_,
                                    final ItemModel<S, R, T> model_,
                                    final S fromStatus_, R field_, S toStatus_, QuantileBreakdown quantiles_)
    {
        this(grid_, model_, fromStatus_, grid_.getRegressorReader(field_), toStatus_, quantiles_);
    }

    public ItemQuantileDistribution(final ParamFittingGrid<S, R, T> grid_,
                                    final ItemModel<S, R, T> model_,
                                    final S fromStatus_, final ItemRegressorReader reader_, S toStatus_,
                                    QuantileBreakdown quantiles_)
    {
        _likelihood = new LogLikelihood<>(fromStatus_);

        final ItemRegressorReader yReader = new InnerResponseReader<>(toStatus_, grid_, model_,
                _likelihood);

        final QuantileStatistics stats = QuantileStatistics.generate(reader_, yReader, quantiles_);
        final int size = quantiles_.getSize();

        double[] adjY = new double[size];
        double[] devAdjY = new double[size];

        for (int i = 0; i < size; i++)
        {
            //We want next / exp(adjustment) = 1.0
            final double next = stats.getMeanY(i);
            final double nextDev = stats.getMeanDevY(i);
            final long nextCount = stats.getCount(i);

            if (nextCount < 1)
            {
                continue;
            }

            //We are actually looking at something like E[actual / predicted]
            final double nextMin = 0.5 / nextCount; //We can't justify a probability smaller than this given our
            // observation count.
            final double nextMax = 1.0 / nextMin; //1.0 - nextMin;
            final double boundedNext = Math.max(nextMin, Math.min(nextMax, next));

            final double adjustment = Math.log(boundedNext);

            //The operating theory here is that dev is small relative to the adjustment, so we can approximate this...
            final double adjDev = Math.log(nextDev + boundedNext) - adjustment;

            adjY[i] = adjustment;
            devAdjY[i] = adjDev;
        }

        final QuantileStatistics adjStats = new QuantileStatistics(stats, adjY, devAdjY);
        _orig = stats;
        _adjusted = adjStats;
    }

    public QuantileStatistics getAdjusted()
    {
        return _adjusted;
    }

    private static final class InnerResponseReader<S extends ItemStatus<S>, R extends ItemRegressor<R>,
            T extends ItemCurveType<T>> implements ItemRegressorReader
    {
        private final double[] _probabilities;
        private final ItemModel<S, R, T> _model;

        private final int[] _toStatusOrdinals;
        private final ParamFittingGrid<S, R, T> _grid;
        private final LogLikelihood<S> _likelihood;

        public InnerResponseReader(final S toStatus_, final ParamFittingGrid<S, R, T> grid_,
                                   final ItemModel<S, R, T> model_, final LogLikelihood<S> likelihood_)
        {
            _grid = grid_;
            _likelihood = likelihood_;
            _model = model_;
            _probabilities = new double[_model.getStatus().getReachableCount()];

            final List<S> indi = toStatus_.getIndistinguishable();
            _toStatusOrdinals = new int[indi.size()];

            for (int i = 0; i < indi.size(); i++)
            {
                _toStatusOrdinals[i] = indi.get(i).ordinal();
            }
        }

        @Override
        public double asDouble(int index_)
        {
            _model.transitionProbability(_grid, index_, _probabilities);
            final int statusIndex = _grid.getNextStatus(index_);

            double probSum = 0.0;
            double actValue = 0.0;

            for (int i = 0; i < _toStatusOrdinals.length; i++)
            {
                final int nextOffset = _likelihood.ordinalToOffset(_toStatusOrdinals[i]);
                probSum += _probabilities[nextOffset];

                if (_toStatusOrdinals[i] == statusIndex)
                {
                    //We took this transition (or one indistinguishable from it).
                    actValue = 1.0;

                    //Don't break out, we need to sum up all the probability mass...
                    //break;
                }
            }

            //N.B: We know that we will never divide by zero here.
            //Ideally, this ratio is approximately 1, or at least E[ratio] = 1.
            //We can compute -ln(1/E[ratio]) and that will give us a power score adjustment we can
            //use to improve our fit. Notice that we are ignoring the non-multiplcative nature of the logistic
            // function.
            //We will need to run the optimizer over this thing eventually, but this should give us a good starting
            // point.
            final double ratio = (actValue / probSum);
            return ratio;
        }

        @Override
        public int size()
        {
            return _grid.size();
        }

    }

}


text:
#ifndef __ET1310_EEPROM_H__
#define __ET1310_EEPROM_H__

#include "et1310_address_map.h"

#ifndef SUCCESS
#define SUCCESS		0
#define FAILURE		1
#endif

/* Forward declaration of the private adapter structure */
struct et131x_adapter;

int32_t EepromWriteByte(struct et131x_adapter *adapter, u32 unAddress,
			u8 bData);
int32_t EepromReadByte(struct et131x_adapter *adapter, u32 unAddress,
			u8 *pbData);

#endif /* _ET1310_EEPROM_H_ */


text:
[Index](../index.md)

## Coupling ( = dependencies )
- Degree of dependency between two modules/systems
- Tighty coupled systems are harder to maintian
- When two modules are tightly coupled, changes to one class will impact the other
- Strive for low coupled systems

## Cohesion ( = responsibility::SRP )
- Degree of focus of an object
- High cohesion implies the object is highly focused and has single intent/responsibility
- Strive for high cohesion

## Charset:
- set of characters you can use
- eg: ASCII, Unicode

## Encoding
- the way these characters are stored into memory
- eg: ASCII uses 7 bits, UTF-8 uses 8 bits while UTF-16 uses 16 bits

## Bindings
- basically are libraries that "bind" two different programming languages so that code written in one language can be used in code written in another library.
- https://stackoverflow.com/questions/20382396/what-are-node-js-bindings

## Content negotiation
- In HTTP, content negotiation is the mechanism that is used for serving different representations of a resource at the same URI, so that the user agent can specify which is best suited for the user (for example, which language of a document, which image format, or which content encoding).

## Web server
- A server that is **capable serving only static content** is a web server
  - eg: npm's **http-server** server
- Serves content to the web using http protocol.
- **Web server can not generate dynamic page or save data to database**

## Application server
- A server that is **capable serving static as well as dynamic content** is an application server
    - eg: nodeJS
- Application server can also function as a web server.

## Internationalization (i18n)
-  The broadest definition has to do with translating your user interface to other languages.

## Localization (l10n)
- is a more specific term, and it describes how to adapt your application to a specific locale or market. Different locales can have the same language, but they still have their customs, like date formatting or measures.

## Signed cookie
- Ensures the cookie sent and received by the server is tampered. Signed cookie has a signature which can be used to detect if the client modified the cookie.
```js
res.cookie('name', 'value', {signed: true})
```
## CGI
- Common Gateway Interface is a term used to refer a **web server helper app**

## HTTP
- HTTP is the network protocol used on the web. It runs on top of TCP/IP

## Idempotent and/or safe methods?
- Safe methods are HTTP methods that do not modify resources.
- For instance, using GET or HEAD on a resource URL, should NEVER change the resource. However, this is not completely true. It means: it won't change the resource representation. It is still possible, that safe methods do change things on a server or resource, but this should not reflect in a different representation.

## Authentication
- process of verifying who the user is. When you log on to a PC with a user name and password you are authenticating.
- eg: login

## Authorization
- process of verifying that the user has access to something.
- Gaining access to a resource (e.g. directory on a hard disk) because the permissions configured on it allow you access is authorization.
- eg: roles: does a non-admin member have access to configuration page?

## Instantiation
- Object creation ( Memory allocation )

## Initialization
- Passing (initial) value to object

## Arity
- The arity of a function is the number of arguments that the function takes.

## Scripting vs Programming language
- Scripting language are interpreted language ( no compilation step )
- Programming language are faster than scripting language, since they are compiled to native machine code
- Ref: https://www.geeksforgeeks.org/whats-the-difference-between-scripting-and-programming-languages/
- Eg: scripting language: javascript, python, php
- Eg: programming language: C, C++, Java

## Functional vs Non-functional requirement
- Functional requirement dictate WHAT a software does
- Non-Functional requirement dictates HOW a software does it
  - Examples include performance, security, usability, extensibility, maintainability, scalability etc
- Eg: Functional: User should receive OTP for login
- Eg: Non-functional: OTP should be received within 2 seconds.

## Preventing SQL Injection
- ref
  - [OWASP SQL_Injection_Prevention_](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.md)
- Use prepared statements
- Use stored procedures
- White List Input Validation
- Sanitize user input
- Least Privilege


text:
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def reverseKGroup(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        def rev(start, stop, k):
            while k:
                tmp = start.next
                start.next = stop
                stop = start
                start = tmp
                k -= 1
            return stop, start

        dummy = ListNode(0)
        dummy.next = head
        preHead = None
        cur, cnt = head, 0
        while cur is not None:
            while cur is not None and cnt < k:
                cur = cur.next
                cnt += 1
            if cnt == k:
                beg, end = rev(head, cur, cnt)
                if preHead:
                    preHead.next = beg
                else:
                    dummy.next = beg
                cnt = 0
                preHead = head
                head = cur = end
        return dummy.next

def print_nodes(head):
    while head:
        print head.val,
        head = head.next
    print

def gen_nodes(arr):
    dummy = ListNode(0)
    cur = dummy
    for i in arr:
        cur.next = ListNode(i)
        cur = cur.next
    return dummy.next

a = gen_nodes([1,2,3,4])
print 'input1:',
print_nodes(a)
print
# c = gen_nodes
t = Solution().reverseKGroup(a,4)
print 'result',
print_nodes(t)