text:
package com.google.common.collect;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndex;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.CollectPreconditions.checkRemove;

import com.google.common.annotations.Beta;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.math.IntMath;

import java.util.AbstractQueue;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.PriorityQueue;
import java.util.Queue;

/**
 * A double-ended priority queue, which provides constant-time access to both
 * its least element and its greatest element, as determined by the queue's
 * specified comparator. If no comparator is given at construction time, the
 * natural order of elements is used.
 *
 *
As a {@link Queue} it functions exactly as a {@link PriorityQueue}: its
 * head element -- the implicit target of the methods {@link #peek()}, {@link
 * #poll()} and {@link #remove()} -- is defined as the least element in
 * the queue according to the queue's comparator. But unlike a regular priority
 * queue, the methods {@link #peekLast}, {@link #pollLast} and
 * {@link #removeLast} are also provided, to act on the greatest element
 * in the queue instead.
 *
 *
A min-max priority queue can be configured with a maximum size. If so,
 * each time the size of the queue exceeds that value, the queue automatically
 * removes its greatest element according to its comparator (which might be the
 * element that was just added). This is different from conventional bounded
 * queues, which either block or reject new elements when full.
 *
 *
This implementation is based on the
 * min-max heap
 * developed by Atkinson, et al. Unlike many other double-ended priority queues,
 * it stores elements in a single array, as compact as the traditional heap data
 * structure used in {@link PriorityQueue}.
 *
 *
This class is not thread-safe, and does not accept null elements.
 *
 *
Performance notes:
 *
 *

 *
The retrieval operations {@link #peek}, {@link #peekFirst}, {@link
 *     #peekLast}, {@link #element}, and {@link #size} are constant-time
 *
The enqueing and dequeing operations ({@link #offer}, {@link #add}, and
 *     all the forms of {@link #poll} and {@link #remove()}) run in {@code
 *     O(log n) time}
 *
The {@link #remove(Object)} and {@link #contains} operations require
 *     linear ({@code O(n)}) time
 *
If you only access one end of the queue, and don't use a maximum size,
 *     this class is functionally equivalent to {@link PriorityQueue}, but
 *     significantly slower.
 *

 *
 * @author Sverre Sundsdal
 * @author Torbjorn Gannholm
 * @since 8.0
 */
// TODO(kevinb): GWT compatibility
@Beta
public final class MinMaxPriorityQueue<E> extends AbstractQueue<E> {

  /**
   * Creates a new min-max priority queue with default settings: natural order,
   * no maximum size, no initial contents, and an initial expected size of 11.
   */
  public static <E extends Comparable<E>> MinMaxPriorityQueue<E> create() {
    return new Builder<Comparable>(Ordering.natural()).create();
  }

  /**
   * Creates a new min-max priority queue using natural order, no maximum size,
   * and initially containing the given elements.
   */
  public static <E extends Comparable<E>> MinMaxPriorityQueue<E> create(
      Iterable<? extends E> initialContents) {
    return new Builder<E>(Ordering.<E>natural()).create(initialContents);
  }

  /**
   * Creates and returns a new builder, configured to build {@code
   * MinMaxPriorityQueue} instances that use {@code comparator} to determine the
   * least and greatest elements.
   */
  public static  Builder orderedBy(Comparator comparator) {
    return new Builder(comparator);
  }

  /**
   * Creates and returns a new builder, configured to build {@code
   * MinMaxPriorityQueue} instances sized appropriately to hold {@code
   * expectedSize} elements.
   */
  public static Builder<Comparable> expectedSize(int expectedSize) {
    return new Builder<Comparable>(Ordering.natural())
        .expectedSize(expectedSize);
  }

  /**
   * Creates and returns a new builder, configured to build {@code
   * MinMaxPriorityQueue} instances that are limited to {@code maximumSize}
   * elements. Each time a queue grows beyond this bound, it immediately
   * removes its greatest element (according to its comparator), which might be
   * the element that was just added.
   */
  public static Builder<Comparable> maximumSize(int maximumSize) {
    return new Builder<Comparable>(Ordering.natural())
        .maximumSize(maximumSize);
  }

  /**
   * The builder class used in creation of min-max priority queues. Instead of
   * constructing one directly, use {@link
   * MinMaxPriorityQueue#orderedBy(Comparator)}, {@link
   * MinMaxPriorityQueue#expectedSize(int)} or {@link
   * MinMaxPriorityQueue#maximumSize(int)}.
   *
   * @param  the upper bound on the eventual type that can be produced by
   *     this builder (for example, a {@code Builder<Number>} can produce a
   *     {@code Queue<Number>} or {@code Queue<Integer>} but not a {@code
   *     Queue<Object>}).
   * @since 8.0
   */
  @Beta
  public static final class Builder {
    /*
     * TODO(kevinb): when the dust settles, see if we still need this or can
     * just default to DEFAULT_CAPACITY.
     */
    private static final int UNSET_EXPECTED_SIZE = -1;

    private final Comparator comparator;
    private int expectedSize = UNSET_EXPECTED_SIZE;
    private int maximumSize = Integer.MAX_VALUE;

    private Builder(Comparator comparator) {
      this.comparator = checkNotNull(comparator);
    }

    /**
     * Configures this builder to build min-max priority queues with an initial
     * expected size of {@code expectedSize}.
     */
    public Builder expectedSize(int expectedSize) {
      checkArgument(expectedSize >= 0);
      this.expectedSize = expectedSize;
      return this;
    }

    /**
     * Configures this builder to build {@code MinMaxPriorityQueue} instances
     * that are limited to {@code maximumSize} elements. Each time a queue grows
     * beyond this bound, it immediately removes its greatest element (according
     * to its comparator), which might be the element that was just added.
     */
    public Builder maximumSize(int maximumSize) {
      checkArgument(maximumSize > 0);
      this.maximumSize = maximumSize;
      return this;
    }

    /**
     * Builds a new min-max priority queue using the previously specified
     * options, and having no initial contents.
     */
    public <T extends B> MinMaxPriorityQueue<T> create() {
      return create(Collections.<T>emptySet());
    }

    /**
     * Builds a new min-max priority queue using the previously specified
     * options, and having the given initial elements.
     */
    public <T extends B> MinMaxPriorityQueue<T> create(
        Iterable<? extends T> initialContents) {
      MinMaxPriorityQueue<T> queue = new MinMaxPriorityQueue<T>(
          this, initialQueueSize(expectedSize, maximumSize, initialContents));
      for (T element : initialContents) {
        queue.offer(element);
      }
      return queue;
    }

    @SuppressWarnings("unchecked") // safe "contravariant cast"
    private <T extends B> Ordering<T> ordering() {
      return Ordering.from((Comparator<T>) comparator);
    }
  }

  private final Heap minHeap;
  private final Heap maxHeap;
  @VisibleForTesting final int maximumSize;
  private Object[] queue;
  private int size;
  private int modCount;

  private MinMaxPriorityQueue(Builder<? super E> builder, int queueSize) {
    Ordering<E> ordering = builder.ordering();
    this.minHeap = new Heap(ordering);
    this.maxHeap = new Heap(ordering.reverse());
    minHeap.otherHeap = maxHeap;
    maxHeap.otherHeap = minHeap;

    this.maximumSize = builder.maximumSize;
    // TODO(kevinb): pad?
    this.queue = new Object[queueSize];
  }

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

  /**
   * Adds the given element to this queue. If this queue has a maximum size,
   * after adding {@code element} the queue will automatically evict its
   * greatest element (according to its comparator), which may be {@code
   * element} itself.
   *
   * @return {@code true} always
   */
  @Override public boolean add(E element) {
    offer(element);
    return true;
  }

  @Override public boolean addAll(Collection<? extends E> newElements) {
    boolean modified = false;
    for (E element : newElements) {
      offer(element);
      modified = true;
    }
    return modified;
  }

  /**
   * Adds the given element to this queue. If this queue has a maximum size,
   * after adding {@code element} the queue will automatically evict its
   * greatest element (according to its comparator), which may be {@code
   * element} itself.
   */
  @Override public boolean offer(E element) {
    checkNotNull(element);
    modCount++;
    int insertIndex = size++;

    growIfNeeded();

    // Adds the element to the end of the heap and bubbles it up to the correct
    // position.
    heapForIndex(insertIndex).bubbleUp(insertIndex, element);
    return size <= maximumSize || pollLast() != element;
  }

  @Override public E poll() {
    return isEmpty() ? null : removeAndGet(0);
  }

  @SuppressWarnings("unchecked") // we must carefully only allow Es to get in
  E elementData(int index) {
    return (E) queue[index];
  }

  @Override public E peek() {
    return isEmpty() ? null : elementData(0);
  }

  /**
   * Returns the index of the max element.
   */
  private int getMaxElementIndex() {
    switch (size) {
      case 1:
        return 0; // The lone element in the queue is the maximum.
      case 2:
        return 1; // The lone element in the maxHeap is the maximum.
      default:
        // The max element must sit on the first level of the maxHeap. It is
        // actually the *lesser* of the two from the maxHeap's perspective.
        return (maxHeap.compareElements(1, 2) <= 0) ? 1 : 2;
    }
  }

  /**
   * Removes and returns the least element of this queue, or returns {@code
   * null} if the queue is empty.
   */
  public E pollFirst() {
    return poll();
  }

  /**
   * Removes and returns the least element of this queue.
   *
   * @throws NoSuchElementException if the queue is empty
   */
  public E removeFirst() {
    return remove();
  }

  /**
   * Retrieves, but does not remove, the least element of this queue, or returns
   * {@code null} if the queue is empty.
   */
  public E peekFirst() {
    return peek();
  }

  /**
   * Removes and returns the greatest element of this queue, or returns {@code
   * null} if the queue is empty.
   */
  public E pollLast() {
    return isEmpty() ? null : removeAndGet(getMaxElementIndex());
  }

  /**
   * Removes and returns the greatest element of this queue.
   *
   * @throws NoSuchElementException if the queue is empty
   */
  public E removeLast() {
    if (isEmpty()) {
      throw new NoSuchElementException();
    }
    return removeAndGet(getMaxElementIndex());
  }

  /**
   * Retrieves, but does not remove, the greatest element of this queue, or
   * returns {@code null} if the queue is empty.
   */
  public E peekLast() {
    return isEmpty() ? null : elementData(getMaxElementIndex());
  }

  /**
   * Removes the element at position {@code index}.
   *
   *
Normally this method leaves the elements at up to {@code index - 1},
   * inclusive, untouched.  Under these circumstances, it returns {@code null}.
   *
   *
Occasionally, in order to maintain the heap invariant, it must swap a
   * later element of the list with one before {@code index}. Under these
   * circumstances it returns a pair of elements as a {@link MoveDesc}. The
   * first one is the element that was previously at the end of the heap and is
   * now at some position before {@code index}. The second element is the one
   * that was swapped down to replace the element at {@code index}. This fact is
   * used by iterator.remove so as to visit elements during a traversal once and
   * only once.
   */
  @VisibleForTesting MoveDesc<E> removeAt(int index) {
    checkPositionIndex(index, size);
    modCount++;
    size--;
    if (size == index) {
      queue[size] = null;
      return null;
    }
    E actualLastElement = elementData(size);
    int lastElementAt = heapForIndex(size)
        .getCorrectLastElement(actualLastElement);
    E toTrickle = elementData(size);
    queue[size] = null;
    MoveDesc<E> changes = fillHole(index, toTrickle);
    if (lastElementAt < index) {
      // Last element is moved to before index, swapped with trickled element.
      if (changes == null) {
        // The trickled element is still after index.
        return new MoveDesc<E>(actualLastElement, toTrickle);
      } else {
        // The trickled element is back before index, but the replaced element
        // has now been moved after index.
        return new MoveDesc<E>(actualLastElement, changes.replaced);
      }
    }
    // Trickled element was after index to begin with, no adjustment needed.
    return changes;
  }

  private MoveDesc<E> fillHole(int index, E toTrickle) {
    Heap heap = heapForIndex(index);
    // We consider elementData(index) a "hole", and we want to fill it
    // with the last element of the heap, toTrickle.
    // Since the last element of the heap is from the bottom level, we
    // optimistically fill index position with elements from lower levels,
    // moving the hole down. In most cases this reduces the number of
    // comparisons with toTrickle, but in some cases we will need to bubble it
    // all the way up again.
    int vacated = heap.fillHoleAt(index);
    // Try to see if toTrickle can be bubbled up min levels.
    int bubbledTo = heap.bubbleUpAlternatingLevels(vacated, toTrickle);
    if (bubbledTo == vacated) {
      // Could not bubble toTrickle up min levels, try moving
      // it from min level to max level (or max to min level) and bubble up
      // there.
      return heap.tryCrossOverAndBubbleUp(index, vacated, toTrickle);
    } else {
      return (bubbledTo < index)
          ? new MoveDesc<E>(toTrickle, elementData(index))
          : null;
    }
  }

  // Returned from removeAt() to iterator.remove()
  static class MoveDesc<E> {
    final E toTrickle;
    final E replaced;

    MoveDesc(E toTrickle, E replaced) {
      this.toTrickle = toTrickle;
      this.replaced = replaced;
    }
  }

  /**
   * Removes and returns the value at {@code index}.
   */
  private E removeAndGet(int index) {
    E value = elementData(index);
    removeAt(index);
    return value;
  }

  private Heap heapForIndex(int i) {
    return isEvenLevel(i) ? minHeap : maxHeap;
  }

  private static final int EVEN_POWERS_OF_TWO = 0x55555555;
  private static final int ODD_POWERS_OF_TWO = 0xaaaaaaaa;

  @VisibleForTesting static boolean isEvenLevel(int index) {
    int oneBased = index + 1;
    checkState(oneBased > 0, "negative index");
    return (oneBased & EVEN_POWERS_OF_TWO) > (oneBased & ODD_POWERS_OF_TWO);
  }

  /**
   * Returns {@code true} if the MinMax heap structure holds. This is only used
   * in testing.
   *
   * TODO(kevinb): move to the test class?
   */
  @VisibleForTesting boolean isIntact() {
    for (int i = 1; i < size; i++) {
      if (!heapForIndex(i).verifyIndex(i)) {
        return false;
      }
    }
    return true;
  }

  /**
   * Each instance of MinMaxPriortyQueue encapsulates two instances of Heap:
   * a min-heap and a max-heap. Conceptually, these might each have their own
   * array for storage, but for efficiency's sake they are stored interleaved on
   * alternate heap levels in the same array (MMPQ.queue).
   */
  private class Heap {
    final Ordering<E> ordering;
    Heap otherHeap;

    Heap(Ordering<E> ordering) {
      this.ordering = ordering;
    }

    int compareElements(int a, int b) {
      return ordering.compare(elementData(a), elementData(b));
    }

    /**
     * Tries to move {@code toTrickle} from a min to a max level and
     * bubble up there. If it moved before {@code removeIndex} this method
     * returns a pair as described in {@link #removeAt}.
     */
    MoveDesc<E> tryCrossOverAndBubbleUp(
        int removeIndex, int vacated, E toTrickle) {
      int crossOver = crossOver(vacated, toTrickle);
      if (crossOver == vacated) {
        return null;
      }
      // Successfully crossed over from min to max.
      // Bubble up max levels.
      E parent;
      // If toTrickle is moved up to a parent of removeIndex, the parent is
      // placed in removeIndex position. We must return that to the iterator so
      // that it knows to skip it.
      if (crossOver < removeIndex) {
        // We crossed over to the parent level in crossOver, so the parent
        // has already been moved.
        parent = elementData(removeIndex);
      } else {
        parent = elementData(getParentIndex(removeIndex));
      }
      // bubble it up the opposite heap
      if (otherHeap.bubbleUpAlternatingLevels(crossOver, toTrickle)
          < removeIndex) {
        return new MoveDesc<E>(toTrickle, parent);
      } else {
        return null;
      }
    }

    /**
     * Bubbles a value from {@code index} up the appropriate heap if required.
     */
    void bubbleUp(int index, E x) {
      int crossOver = crossOverUp(index, x);

      Heap heap;
      if (crossOver == index) {
        heap = this;
      } else {
        index = crossOver;
        heap = otherHeap;
      }
      heap.bubbleUpAlternatingLevels(index, x);
    }

    /**
     * Bubbles a value from {@code index} up the levels of this heap, and
     * returns the index the element ended up at.
     */
    int bubbleUpAlternatingLevels(int index, E x) {
      while (index > 2) {
        int grandParentIndex = getGrandparentIndex(index);
        E e = elementData(grandParentIndex);
        if (ordering.compare(e, x) <= 0) {
          break;
        }
        queue[index] = e;
        index = grandParentIndex;
      }
      queue[index] = x;
      return index;
    }

    /**
     * Returns the index of minimum value between {@code index} and
     * {@code index + len}, or {@code -1} if {@code index} is greater than
     * {@code size}.
     */
    int findMin(int index, int len) {
      if (index >= size) {
        return -1;
      }
      checkState(index > 0);
      int limit = Math.min(index, size - len) + len;
      int minIndex = index;
      for (int i = index + 1; i < limit; i++) {
        if (compareElements(i, minIndex) < 0) {
          minIndex = i;
        }
      }
      return minIndex;
    }

    /**
     * Returns the minimum child or {@code -1} if no child exists.
     */
    int findMinChild(int index) {
      return findMin(getLeftChildIndex(index), 2);
    }

    /**
     * Returns the minimum grand child or -1 if no grand child exists.
     */
    int findMinGrandChild(int index) {
      int leftChildIndex = getLeftChildIndex(index);
      if (leftChildIndex < 0) {
        return -1;
      }
      return findMin(getLeftChildIndex(leftChildIndex), 4);
    }

    /**
     * Moves an element one level up from a min level to a max level
     * (or vice versa).
     * Returns the new position of the element.
     */
    int crossOverUp(int index, E x) {
      if (index == 0) {
        queue[0] = x;
        return 0;
      }
      int parentIndex = getParentIndex(index);
      E parentElement = elementData(parentIndex);
      if (parentIndex != 0) {
        // This is a guard for the case of the childless uncle.
        // Since the end of the array is actually the middle of the heap,
        // a smaller childless uncle can become a child of x when we
        // bubble up alternate levels, violating the invariant.
        int grandparentIndex = getParentIndex(parentIndex);
        int uncleIndex = getRightChildIndex(grandparentIndex);
        if (uncleIndex != parentIndex
            && getLeftChildIndex(uncleIndex) >= size) {
          E uncleElement = elementData(uncleIndex);
          if (ordering.compare(uncleElement, parentElement) < 0) {
            parentIndex = uncleIndex;
            parentElement = uncleElement;
          }
        }
      }
      if (ordering.compare(parentElement, x) < 0) {
        queue[index] = parentElement;
        queue[parentIndex] = x;
        return parentIndex;
      }
      queue[index] = x;
      return index;
    }

    /**
     * Returns the conceptually correct last element of the heap.
     *
     *
Since the last element of the array is actually in the
     * middle of the sorted structure, a childless uncle node could be
     * smaller, which would corrupt the invariant if this element
     * becomes the new parent of the uncle. In that case, we first
     * switch the last element with its uncle, before returning.
     */
    int getCorrectLastElement(E actualLastElement) {
      int parentIndex = getParentIndex(size);
      if (parentIndex != 0) {
        int grandparentIndex = getParentIndex(parentIndex);
        int uncleIndex = getRightChildIndex(grandparentIndex);
        if (uncleIndex != parentIndex
            && getLeftChildIndex(uncleIndex) >= size) {
          E uncleElement = elementData(uncleIndex);
          if (ordering.compare(uncleElement, actualLastElement) < 0) {
            queue[uncleIndex] = actualLastElement;
            queue[size] = uncleElement;
            return uncleIndex;
          }
        }
      }
      return size;
    }

    /**
     * Crosses an element over to the opposite heap by moving it one level down
     * (or up if there are no elements below it).
     *
     * Returns the new position of the element.
     */
    int crossOver(int index, E x) {
      int minChildIndex = findMinChild(index);
      // TODO(kevinb): split the && into two if's and move crossOverUp so it's
      // only called when there's no child.
      if ((minChildIndex > 0)
          && (ordering.compare(elementData(minChildIndex), x) < 0)) {
        queue[index] = elementData(minChildIndex);
        queue[minChildIndex] = x;
        return minChildIndex;
      }
      return crossOverUp(index, x);
    }

    /**
     * Fills the hole at {@code index} by moving in the least of its
     * grandchildren to this position, then recursively filling the new hole
     * created.
     *
     * @return the position of the new hole (where the lowest grandchild moved
     *     from, that had no grandchild to replace it)
     */
    int fillHoleAt(int index) {
      int minGrandchildIndex;
      while ((minGrandchildIndex = findMinGrandChild(index)) > 0) {
        queue[index] = elementData(minGrandchildIndex);
        index = minGrandchildIndex;
      }
      return index;
    }

    private boolean verifyIndex(int i) {
      if ((getLeftChildIndex(i) < size)
          && (compareElements(i, getLeftChildIndex(i)) > 0)) {
        return false;
      }
      if ((getRightChildIndex(i) < size)
          && (compareElements(i, getRightChildIndex(i)) > 0)) {
        return false;
      }
      if ((i > 0) && (compareElements(i, getParentIndex(i)) > 0)) {
        return false;
      }
      if ((i > 2) && (compareElements(getGrandparentIndex(i), i) > 0)) {
        return false;
      }
      return true;
    }

    // These would be static if inner classes could have static members.

    private int getLeftChildIndex(int i) {
      return i * 2 + 1;
    }

    private int getRightChildIndex(int i) {
      return i * 2 + 2;
    }

    private int getParentIndex(int i) {
      return (i - 1) / 2;
    }

    private int getGrandparentIndex(int i) {
      return getParentIndex(getParentIndex(i)); // (i - 3) / 4
    }
  }

  /**
   * Iterates the elements of the queue in no particular order.
   *
   * If the underlying queue is modified during iteration an exception will be
   * thrown.
   */
  private class QueueIterator implements Iterator<E> {
    private int cursor = -1;
    private int expectedModCount = modCount;
    private Queue<E> forgetMeNot;
    private List<E> skipMe;
    private E lastFromForgetMeNot;
    private boolean canRemove;

    @Override public boolean hasNext() {
      checkModCount();
      return (nextNotInSkipMe(cursor + 1) < size())
          || ((forgetMeNot != null) && !forgetMeNot.isEmpty());
    }

    @Override public E next() {
      checkModCount();
      int tempCursor = nextNotInSkipMe(cursor + 1);
      if (tempCursor < size()) {
        cursor = tempCursor;
        canRemove = true;
        return elementData(cursor);
      } else if (forgetMeNot != null) {
        cursor = size();
        lastFromForgetMeNot = forgetMeNot.poll();
        if (lastFromForgetMeNot != null) {
          canRemove = true;
          return lastFromForgetMeNot;
        }
      }
      throw new NoSuchElementException(
          "iterator moved past last element in queue.");
    }

    @Override public void remove() {
      checkRemove(canRemove);
      checkModCount();
      canRemove = false;
      expectedModCount++;
      if (cursor < size()) {
        MoveDesc<E> moved = removeAt(cursor);
        if (moved != null) {
          if (forgetMeNot == null) {
            forgetMeNot = new ArrayDeque<E>();
            skipMe = new ArrayList<E>(3);
          }
          forgetMeNot.add(moved.toTrickle);
          skipMe.add(moved.replaced);
        }
        cursor--;
      } else { // we must have set lastFromForgetMeNot in next()
        checkState(removeExact(lastFromForgetMeNot));
        lastFromForgetMeNot = null;
      }
    }

    // Finds only this exact instance, not others that are equals()
    private boolean containsExact(Iterable<E> elements, E target) {
      for (E element : elements) {
        if (element == target) {
          return true;
        }
      }
      return false;
    }

    // Removes only this exact instance, not others that are equals()
    boolean removeExact(Object target) {
      for (int i = 0; i < size; i++) {
        if (queue[i] == target) {
          removeAt(i);
          return true;
        }
      }
      return false;
    }

    void checkModCount() {
      if (modCount != expectedModCount) {
        throw new ConcurrentModificationException();
      }
    }

    /**
     * Returns the index of the first element after {@code c} that is not in
     * {@code skipMe} and returns {@code size()} if there is no such element.
     */
    private int nextNotInSkipMe(int c) {
      if (skipMe != null) {
        while (c < size() && containsExact(skipMe, elementData(c))) {
          c++;
        }
      }
      return c;
    }
  }

  /**
   * Returns an iterator over the elements contained in this collection,
   * in no particular order.
   *
   *
The iterator is fail-fast: If the MinMaxPriorityQueue is modified
   * at any time after the iterator is created, in any way except through the
   * iterator's own remove method, the iterator will generally throw a
   * {@link ConcurrentModificationException}. Thus, in the face of concurrent
   * modification, the iterator fails quickly and cleanly, rather than risking
   * arbitrary, non-deterministic behavior at an undetermined time in the
   * future.
   *
   *
Note that the fail-fast behavior of an iterator cannot be guaranteed
   * as it is, generally speaking, impossible to make any hard guarantees in the
   * presence of unsynchronized concurrent modification.  Fail-fast iterators
   * throw {@code ConcurrentModificationException} on a best-effort basis.
   * Therefore, it would be wrong to write a program that depended on this
   * exception for its correctness: the fail-fast behavior of iterators
   * should be used only to detect bugs.
   *
   * @return an iterator over the elements contained in this collection
   */
  @Override public Iterator<E> iterator() {
    return new QueueIterator();
  }

  @Override public void clear() {
    for (int i = 0; i < size; i++) {
      queue[i] = null;
    }
    size = 0;
  }

  @Override public Object[] toArray() {
    Object[] copyTo = new Object[size];
    System.arraycopy(queue, 0, copyTo, 0, size);
    return copyTo;
  }

  /**
   * Returns the comparator used to order the elements in this queue. Obeys the
   * general contract of {@link PriorityQueue#comparator}, but returns {@link
   * Ordering#natural} instead of {@code null} to indicate natural ordering.
   */
  public Comparator<? super E> comparator() {
    return minHeap.ordering;
  }

  @VisibleForTesting int capacity() {
    return queue.length;
  }

  // Size/capacity-related methods

  private static final int DEFAULT_CAPACITY = 11;

  @VisibleForTesting static int initialQueueSize(int configuredExpectedSize,
      int maximumSize, Iterable<?> initialContents) {
    // Start with what they said, if they said it, otherwise DEFAULT_CAPACITY
    int result = (configuredExpectedSize == Builder.UNSET_EXPECTED_SIZE)
        ? DEFAULT_CAPACITY
        : configuredExpectedSize;

    // Enlarge to contain initial contents
    if (initialContents instanceof Collection) {
      int initialSize = ((Collection<?>) initialContents).size();
      result = Math.max(result, initialSize);
    }

    // Now cap it at maxSize + 1
    return capAtMaximumSize(result, maximumSize);
  }

  private void growIfNeeded() {
    if (size > queue.length) {
      int newCapacity = calculateNewCapacity();
      Object[] newQueue = new Object[newCapacity];
      System.arraycopy(queue, 0, newQueue, 0, queue.length);
      queue = newQueue;
    }
  }

  /** Returns ~2x the old capacity if small; ~1.5x otherwise. */
  private int calculateNewCapacity() {
    int oldCapacity = queue.length;
    int newCapacity = (oldCapacity < 64)
        ? (oldCapacity + 1) * 2
        : IntMath.checkedMultiply(oldCapacity / 2, 3);
    return capAtMaximumSize(newCapacity, maximumSize);
  }

  /** There's no reason for the queueSize to ever be more than maxSize + 1 */
  private static int capAtMaximumSize(int queueSize, int maximumSize) {
    return Math.min(queueSize - 1, maximumSize) + 1; // don't overflow
  }
}


text:
Core::Core()
{
	fullscreen = false;
	keys[_KEY_UP] = false;
	keys[_KEY_DOWN] = false;
	keys[_KEY_LEFT] = false;
	keys[_KEY_RIGHT] = false;
	keys[_KEY_SPACE] = false;

	s_mouse[_MOUSE_DOWN] = false;
	s_mouse[_MOUSE_UP] = false;

	p_mouse[_MOUSE_DOWN].x = -1;
	p_mouse[_MOUSE_DOWN].y = -1;

	p_mouse[_MOUSE_UP].x = -1;
	p_mouse[_MOUSE_UP].y = -1;

	p_mouse[_MOUSE_MOVE].x = -1;
	p_mouse[_MOUSE_MOVE].y = -1;

	b_mouse = _MOUSE_BUTTON_NONE_OTHER;

	title = "";
	done = true;
	render = false;
	isDrawFPS = false;
	gameTime = 0;
	frames = 0;
	gameFPS = 60;
	soundSamples = 1;
	maxFPS = 0;
	minFPS = 9999;
	loopCount = 0;

	 fps1 = 0;
	 frames_done = 0;
	 old_time = 0;

	 frame_index = 0;//used to store the index of the last updated value in the array
	for(int ii = 0; ii < 10; ii++)
		frames_array[ii] = 0;//initialize the array to 0

	qTree = Quadtree( 0.0f, 0.0f, SCREEN_W, SCREEN_H, 1, nivelMaximo,NULL);

}

void Core::Start(void)
{
	GameLoop();
}

void Core::Stop(void)
{
	Destr();
}

int Core::Init()
{
	if(Allegro_Init() == -1)
	{
		al_rest(5);
		return -1;
	}
	done = false;

	return 0;
}

int Core::Allegro_Init()
{
	if(!al_init()) {
		fprintf(stderr, "failed to initialize allegro!\n");
		return -1;
	}

	if(!al_install_mouse()) {
		fprintf(stderr, "failed to initialize the mouse!\n");
		return -1;
	}

	if(!al_install_keyboard())
	{
		fprintf(stderr, "failed to install keyboard!\n");
		return -1;
	}

	if(!al_init_primitives_addon())
	{
		fprintf(stderr, "failed to init primitive addon!\n");
		return -1;
	}

	timer = al_create_timer(1.0 / gameFPS);
	if(!timer) {
		fprintf(stderr, "failed to create timer!\n");
		return -1;
	}

	display = createDisplay();
	if(!display) {
		fprintf(stderr, "failed to create display!\n");
		return -1;
	}

	buffer = al_create_bitmap(SCREEN_W,SCREEN_H);
	if(!buffer) {
		fprintf(stderr, "failed to create buffer bitmap!\n");
		return -1;
	}

	event_queue = al_create_event_queue();
	if(!event_queue)
	{
		fprintf(stderr, "failed to create event queue!\n");
		return -1;
	}

	al_init_font_addon();
	al_init_ttf_addon();

	font = al_load_ttf_font("DefaultFont.ttf",12,0);
	if(!font)
	{
		fprintf(stderr, al_path_cstr(resourcePath, '/'));
		return -1;
	}

	if(!al_install_audio()){
		fprintf(stderr, "failed to initialize audio!\n");
		return -1;
	}

	if(!al_init_acodec_addon()){
		fprintf(stderr, "failed to initialize audio codecs!\n");
		return -1;
	}

	if (!al_reserve_samples(soundSamples)){
		fprintf(stderr, "failed to reserve samples!\n");
		return -1;
	}
	al_init_image_addon();

	background = al_load_bitmap("C:/bg.jpg");

	if(!background)
	{
		fprintf(stderr,"Carregar Imagens falhou");
		return -1;
	}

	return 0;
}

void Core::Destr()
{
	al_destroy_font(font);
	al_destroy_event_queue(event_queue);
	al_destroy_display(display);
	al_destroy_timer(timer);
	for(std::list<GameObject *>::iterator iter = objects.begin(); iter != objects.end();)
	{
		(*iter)->Destroy();
		delete (*iter);
		iter = objects.erase(iter);

	}
}

void Core::GameLoop()
{

	ALLEGRO_KEYBOARD_STATE key_state;
	bool redraw = false;
	GradeUniforme grade(0,0,SCREEN_W,SCREEN_H,50,50);

	al_get_keyboard_state(&key_state);
	al_register_event_source(event_queue,al_get_mouse_event_source());//Register Mouse queue
	al_register_event_source(event_queue,al_get_keyboard_event_source());//Register Keyboard queue
	al_register_event_source(event_queue,al_get_timer_event_source(timer));//Register Timer queue
	al_register_event_source(event_queue,al_get_display_event_source(display));//Register Display queue
	al_flip_display();
	al_start_timer(timer);

	while(!done){

		ALLEGRO_EVENT event;
		al_wait_for_event(event_queue,&event);
		if(UpdateDisplay(event,redraw) == -1) done = true;

		#pragma region
		if(event.type == ALLEGRO_EVENT_KEY_DOWN){
			switch (event.keyboard.keycode)
			{
			case ALLEGRO_KEY_UP:
				keys[_KEY_UP] = true;
				break;
			case ALLEGRO_KEY_DOWN:
				keys[_KEY_DOWN] = true;
				break;
			case ALLEGRO_KEY_LEFT:
				keys[_KEY_LEFT] = true;
				break;
			case ALLEGRO_KEY_RIGHT:
				keys[_KEY_RIGHT] = true;
				break;
			case ALLEGRO_KEY_SPACE:
				keys[_KEY_SPACE] = true;
				break;
			default:
				break;
			}

		}
		#pragma endregion KeyDown

		#pragma region
		else if(event.type == ALLEGRO_EVENT_KEY_UP){
			switch (event.keyboard.keycode)
			{
			case ALLEGRO_KEY_UP:
				keys[_KEY_UP] = false;
				break;
			case ALLEGRO_KEY_DOWN:
				keys[_KEY_DOWN] = false;
				break;
			case ALLEGRO_KEY_LEFT:
				keys[_KEY_LEFT] = false;
				break;
			case ALLEGRO_KEY_RIGHT:
				keys[_KEY_RIGHT] = false;
				break;
			case ALLEGRO_KEY_SPACE:
				keys[_KEY_SPACE] = true;
				break;
			default:
				break;
			}
		}
		#pragma endregion KeyUp

		#pragma region

		if(event.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN)
		{

			switch (event.mouse.button)
			{
			case 1:
				b_mouse = _MOUSE_LEFT;
				break;
			case 2:
				b_mouse = _MOUSE_RIGHT;
				break;
			default:
				b_mouse = _MOUSE_BUTTON_NONE_OTHER;
				break;
			}

			s_mouse[_MOUSE_DOWN] = true;

			p_mouse[_MOUSE_DOWN].x = event.mouse.x;
			p_mouse[_MOUSE_DOWN].y = event.mouse.y;

			s_mouse[_MOUSE_UP] = false;
			p_mouse[_MOUSE_UP].x = -1;
			p_mouse[_MOUSE_UP].y = -1;
		}

		#pragma endregion MouseDown

		#pragma region

		else if(event.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP)
		{
			switch (event.mouse.button)
			{
			case 1:
				b_mouse = _MOUSE_LEFT;
				break;
			case 2:
				b_mouse = _MOUSE_RIGHT;
				break;
			default:
				b_mouse = _MOUSE_BUTTON_NONE_OTHER;
				break;
			}

			s_mouse[_MOUSE_UP] = true;

			p_mouse[_MOUSE_UP].x = event.mouse.x;
			p_mouse[_MOUSE_UP].y = event.mouse.y;

			s_mouse[_MOUSE_DOWN] = false;
			p_mouse[_MOUSE_DOWN].x = -1;
			p_mouse[_MOUSE_DOWN].y = -1;

		}

		#pragma endregion MouseUp

		#pragma region

		if(event.type == ALLEGRO_EVENT_MOUSE_AXES)
		{
			p_mouse[_MOUSE_MOVE].x = event.mouse.x;
			p_mouse[_MOUSE_MOVE].y = event.mouse.y;

			if(s_mouse[_MOUSE_DOWN])
				p_mouse[_MOUSE_DOWN] = p_mouse[_MOUSE_MOVE];
			if(s_mouse[_MOUSE_UP])
				p_mouse[_MOUSE_UP] = p_mouse[_MOUSE_MOVE];
		}

		#pragma endregion MouseMove

		#pragma region
		if(event.type == ALLEGRO_EVENT_TIMER){

			Tick();

			if(s_mouse[_MOUSE_DOWN])
			{
				if(!isInsertMultiple)
					s_mouse[_MOUSE_DOWN] = false;
				MouseDown();
			}
			if(s_mouse[_MOUSE_UP])
			{
				s_mouse[_MOUSE_UP] = false;
				MouseUp();
			}

			if(keys[_KEY_UP]){
				KeyUp();
			}
			else if(keys[_KEY_DOWN])
				KeyDown();
			if(keys[_KEY_LEFT])
				KeyLeft();
			else if(keys[_KEY_RIGHT])
			{
				KeyRight();
			}
			if(keys[_KEY_SPACE]){
				KeySpace();
			}

			#pragma region ForcaBruta
			if(isForcaBruta)
			{
				for(std::list<GameObject *>::iterator iter = objects.begin(); iter != objects.end(); ++iter)
				if(*iter){
					(*iter)->Update();
					for(std::list<GameObject *>::iterator it2 = iter; it2 != objects.end(); ++it2)
				{
					if(*iter != *it2){
						(*iter)->CheckCollisions(*it2);
					}
					loopCount++;
				}
				}
			}
			#pragma endregion ForcaBruta
			#pragma region QuadTree
			else if(isQuadTree){
				for(std::list<GameObject *>::iterator iter = objects.begin(); iter != objects.end(); ++iter){
					if(*iter){
						(*iter)->Update();

						qTree.AddObject(*iter);
						loopCount++;
						std::list<GameObject *> objlist = qTree.GetObjectsAt((*iter)->getX(),(*iter)->getY());

						for(std::list<GameObject *>::iterator it2 = objlist.begin(); it2 != objlist.end(); ++it2)
						{
							if(*iter != *it2){
								(*iter)->CheckCollisions(*it2);
							}
							loopCount++;
						}
					}
				}
				if(debug)
					qTree.draw();
				qTree.Clear();
			}
			#pragma endregion QuadTree
			#pragma region GUniforme
			else if(isGUniforme)
			{
				for(std::list<GameObject *>::iterator iter = objects.begin(); iter != objects.end(); ++iter){
					if(*iter){
						(*iter)->Update();

						grade.AddObject(*iter);
						loopCount++;
						std::list<GameObject *> objlist = grade.GetObjectsAt((*iter)->getX(),(*iter)->getY());

						for(std::list<GameObject *>::iterator it2 = objlist.begin(); it2 != objlist.end(); ++it2)
						{
							if(*iter != *it2){
								(*iter)->CheckCollisions(*it2);
							}
							loopCount++;
						}
					}

				}
				if(debug)
						grade.draw();
				grade.Clear();
			}
			#pragma endregion GUniforme
			#pragma region Sem Física
			else{
				for(std::list<GameObject *>::iterator iter = objects.begin(); iter != objects.end(); ++iter){
					if(*iter)
						(*iter)->Update();
					loopCount++;
				}
			}
			#pragma endregion Sem Física

			redraw = true;
		}
		#pragma endregion Timer/Draw

	}
}

void Core::Tick(){};

void Core::MouseDown(void){};
void Core::MouseUp(void){};
void Core::MouseMove(void){};

void Core::KeyUp(void){};
void Core::KeyDown(void){};
void Core::KeyLeft(void){};
void Core::KeyRight(void){};
void Core::KeySpace(void){};//Add more action Keys if nedded

redpajama_set_name: RedPajamaGithub


text:
@interface TTXMPPController : NSObject<XMPPStreamDelegate, XMPPReconnectDelegate, XMPPPingDelegate, XMPPAutoPingDelegate>
{
    NSString * _username;
    NSString * _password;
}

@property (nonatomic, retain) NSString * username;
@property (nonatomic, retain) NSString * password;

@property (nonatomic, assign) int packageCount;     //开始sm后收到服务器发送数据包数量

+ (id)shareInstance;

//设置当前连接XMPP的用户名和密码,会断开连接再从新连接XMPP服务器
+ (void)setupSharedUsername:(NSString *)username andPassword:(NSString *)password;

//发送消息
- (void)sendMessage:(NSString *)message userId:(NSString *)userId;

//卸载,将保存的用户密码清空,并且断开连接
+ (void)uninstallShared;

- (BOOL)connect;   //连接服务器
- (void)connectAfterDelay:(NSTimeInterval)delay;
- (void)disconnect;//断开连接
- (BOOL)isConnecting;//是否连接着

- (void)goOnline;  //上线
- (void)goOffline; //下线

@end


text:
package net.sf.sojo.core;

/**
 * This interface is a extension from the ConverterInterceptor. The method from this
 * interface are calling, if a conversion is recursive. This is the case by maps, collctions, arrays,
 * object graphs and so on.
 *
 * @author Linke
 *
 */
public interface ConverterInterceptorRecursive extends ConverterInterceptor {

	public void beforeConvertRecursion(ConversionContext pvContext);

	public void afterConvertRecursion(ConversionContext pvContext);
}


text:
package org.onosproject.net.sensorflow;

import org.onosproject.net.flow.instructions.Instruction;

import java.util.Arrays;

/**
 * Created by aca on 7/16/15.
 */
public class SensorFlowSetGeoNxHopCoordinatesInstruction implements SensorFlowInstruction {
    private byte[] coords;

    public SensorFlowSetGeoNxHopCoordinatesInstruction(byte[] coordinates) {
        setCoords(coordinates);
    }

    public byte[] getCoords() {
        return coords;
    }

    public void setCoords(byte[] coordinates) {
        this.coords = new byte[coordinates.length];
        System.arraycopy(coordinates, 0, this.coords, 0, coordinates.length);
    }

    @Override
    public Type getSensorFlowInstructionType() {
        return Type.SET_GEO_NX_HOP_COORD;
    }

    @Override
    public boolean multimatch() {
        return false;
    }

    @Override
    public Instruction.Type type() {
        return null;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof SensorFlowSetGeoNxHopCoordinatesInstruction)) {
            return false;
        }

        SensorFlowSetGeoNxHopCoordinatesInstruction that = (SensorFlowSetGeoNxHopCoordinatesInstruction) o;

        return Arrays.equals(coords, that.coords);

    }

    @Override
    public int hashCode() {
        return coords != null ? Arrays.hashCode(coords) : 0;
    }
}


text:
var url = require('url');
var config = require ('./config.js');
var configData = config.data;
var http = require('http');
var https = require('https');
var qs = require ('querystring');
var secure_post = false;
var pull_field = configData.pullField || "ref";
var POST_MESSAGE_SIZE = 65536; // limit the most someone can post to 64k
var deploy = false;
var fs = require('fs');

// this function restarts the application
function restart (code){
    code = code || 0;
    console.log ("Restarting the app. If you launched this manually you will have to re-launch manually");
    setTimeout (function (){
        process.exit (code);
    }, 1000);
}

// start up our pull server
function startServer (instance_data, checkAndUpdateEnvironment, cb){
    deploy = instance_data && instance_data.deploy;
    // create a server to listen for pull requests
    function handleRequests (req, res){
        function parseURL (req){
            var url_in = url.parse (req.url, true);
            req.query = url_in.query;
            req.href = url_in.href;
        }
        function bodyParser (req, res, func){
            if (req.method == 'POST') {
                var body = '';
                req.on('data', function (data) {
                    body += data;
                    if (body.length > POST_MESSAGE_SIZE) { // limit the most data someone can send
                        request.connection.destroy();
                    }
                });
                req.on('end', function () {
                    try{req.body = JSON.parse (body);}
                    catch (e){req.body = qs.parse (body);}
                    if (func){func (req, res);}
                });
            }
            res.send = function (str){
                this.writeHead(404, {'Content-Type': 'text/plain'});
                this.end(str);
            };
        }
        // handle pull requests, only pull if deploy is set to true
        if (req.url.search ("/pull") !== -1 && deploy){ // handle a command to pull
            var valid_request = true;
            parseURL (req);
            if (configData.pullSecret){
                valid_request = (req.query.secret == configData.pullSecret) ? true : false;
            }
            if (valid_request){
                bodyParser (req, res, function (){
                    var _restart = false;
                    var listensTo = (instance_data && instance_data.listensTo) ? instance_data.listensTo : "";
                    req.body[pull_field] = req.body[pull_field] || "";
                    if (req.body[pull_field].search (listensTo) !== -1){
                        if (req.body.args){
                            var args;
                            try {args = JSON.parse (req.body.args);}
                            catch (e){}
                            args = args || req.body.args;
                            if (args){ // only save these out if we have new ones
                                _restart = false;
                                console.log ("\tApplying pullArgs:%j", args);
                                if (typeof args === 'string'){
				                    if (configData.pullArgs !== args){
                                    	configData.pullArgs = args;
                                        _restart = true;
				                    }
                                }
                                else{
                                    configData.pullArgs = configData.pullArgs || {};
                                    for (var k in args){
                                        if (configData.pullArgs[k] !== args[k]){
                                            configData.pullArgs[k] = args[k];
                                            _restart = true;
                                        }
                                    }
                                }
                                config.update ();
                            }
                            else{
                                console.log ("\tNo pullArgs passed in");
                            }
                        }

                        var _master = req.query.master;
                        checkAndUpdateEnvironment (_restart, function (){
                            res.send("Pull Accepted");
                            var date = new Date ();
                            console.log ("\nPull Command, master:" + _master + " @" + date.toString ());
                        }, req.query.master, req, res, true);
                    }
                    else{
                        var msg = "\nIgnoring Pull Request, wrong branch. \n\tListening for: " + listensTo +
                            "\n\t Recieved:" + req.body[pull_field];
                        console.log (msg);
                        res.send ("Ignoring Pull Request, wrong branch.");
                    }
                });
            }
            else{
                res.send ("Pull Not Authorized");
                console.log ("\nPull Not Authorized");
            }
        }
        else if (req.url.search ("/restart") !== -1){
            var valid_request = true;
            parseURL (req);
            if (configData.pullSecret){
                valid_request = (req.query.secret == configData.pullSecret) ? true : false;
            }
            if (valid_request){
                res.send ("Restarting");
                console.log ("\nRestart command received. Restarting...");
                restart (0);
            }
            else {
                res.send ("Restart Not Authorized");
                console.log ("\nRestart Not Authorized");
            }
        }
        else if (req.url.search ("/rebuild") !== -1 && deploy){
            var valid_request = true;
            parseURL (req);
            if (configData.pullSecret){
                valid_request = (req.query.secret == configData.pullSecret) ? true : false;
            }
            if (valid_request){

                // blow away the package.json copy and restart
                if (config.data.applicationDirectory){
                    var packageCopy = config.data.applicationDirectory + '/package.copy';
                    try {fs.unlinkSync (packageCopy);}
                    catch (e){}
                    // now blow away all the dependency package.copy files
                    if (configData.dependencies && configData.homePath){
                        configData.dependencies.forEach (function (dependency){
                            packageCopy = configData.homePath + "/" + dependency + "/package.copy";
                            try {fs.unlinkSync (packageCopy);}
                            catch (e){}
                        });
                    }
                    res.send ("Rebuilding");
                    console.log ("\nRebuild command received. Rebuilding...");
                    restart (0); // restart
                }else{
                    res.send ("node-aws-deploy is not configured properly");
                }
            }
            else{
                res.send ("Rebuild Not Authorized");
                console.log ("\nRebuild Not Authorized");
            }
        }
        else{
            res.send ("Unrecognized command");
            console.log ("\nUnrecognized command");
        }
    }
    var http_port = (configData.pullPort || 8000), key, cert, options;
    if (configData.pullKey && configData.pullCert){
        try {key = fs.readFileSync (configData.pullKey);}
        catch (err) {key = null;}
        try {cert = fs.readFileSync (configData.pullCert);}
        catch (err) {cert = null;}
        if (key && cert) {
            options = {key:key, cert:cert,
                ciphers: 'ECDHE-RSA-AES128-SHA256:AES128-GCM-SHA256:RC4:HIGH:!MD5:!aNULL:!EDH',
                honorCipherOrder: true
            };
        }
        if (options && configData.pullPassphrase){
            options.passphrase = configData.pullPassphrase;
        }
        if (options && configData.pullCa && configData.pullCa.length){
            var ca = [];
            configData.pullCa.forEach (function (_ca){
                try {__ca = fs.readFileSync (_ca, {encoding: "aascii"});}
                catch (err) {__ca = null;}
                if (__ca){ ca.push (__ca);}
            });
            if (ca.length){
                options.ca = ca;
            }
        }
    }
    if (key && cert){
        secure_post = true;
        console.log ("\nHTTPS Pull Server Started. Listening on Port:" + http_port);
        https.createServer (options, handleRequests).listen (http_port);
    }
    else{
        secure_post = false;
        console.log ("\nWARNING cert and key not specified or invalid. Falling back to HTTP");
        console.log ("HTTP Pull Server Started. Listening on Port:" + http_port);
        http.createServer (handleRequests).listen (http_port);
    }
    cb && cb ();
}

exports.startServer = startServer;


text:
[CmdletBinding()]
param()

# For more information on the VSTS Task SDK:
# https://github.com/Microsoft/vsts-task-lib
Trace-VstsEnteringInvocation $MyInvocation
try {
    Import-Module $PSScriptRoot\ps_modules\Microsoft.Xrm.Data.PowerShell

    $url = Get-VstsInput -Name url -Require
    $usn = Get-VstsInput -Name usn -Require
    $pwd = Get-VstsInput -Name pwd -Require
    $dmn = Get-VstsInput -Name dmn
    $auth = Get-VstsInput -Name auth -Require
    $sln = Get-VstsInput -Name sln -Require
    $act = Get-VstsInput -Name act -AsBool
    $pub = Get-VstsInput -Name pub -AsBool
    $mwt = Get-VstsInput -Name mwt -AsInt
    $ovw = Get-VstsInput -Name ovw -AsBool
    $skp = Get-VstsInput -Name skp -AsBool

    $connString = "AuthType=$auth;Domain=$dmn;Username=$usn;Password=$pwd;Url=$url"
    $connString

    $conn = Get-CrmConnection -ConnectionString $connString

    $slnFile = Get-Item $sln
    $root = $slnFile.Directory.FullName

    #get solution version from zip
    Expand-Archive -Path $sln -DestinationPath "$root\temp" -Force
    [xml]$slnXml = Get-Content "$root\temp\solution.xml"
    $slnZipVersion = $slnXml.ImportExportXml.SolutionManifest.Version
    Write-Host "Solution version from zip file is $slnZipVersion"
    $slnZipUniqueName = $slnXml.ImportExportXml.SolutionManifest.UniqueName
    Write-Host "Solution name from zip file is $slnZipUniqueName"

    #get solution version from Dynamics 365
    $solutions = Get-CrmRecords -conn $conn -EntityLogicalName solution -FilterAttribute uniquename -FilterOperator eq -FilterValue $slnZipUniqueName -Fields "version"
    if($solutions.CrmRecords.Count -gt 0)
    {
        $solution = $solutions.CrmRecords[0]
        $solutionVersion = $solution.version
        Write-Host "Solution version already installed is $solutionVersion"

        if($skp -and $slnZipVersion -eq $solutionVersion)
        {
            Write-Warning "Skipping! Solution versions match ($solutionVersion)"
            return;
        }
    }

    #import solution
    $exp = "Import-CrmSolution -conn `$conn -SolutionFilePath `$sln"
    if($act) {$exp = "$exp -ActivatePlugIns"}
    if($pub) {$exp = "$exp -PublishChanges"}
    if($mwt -gt 0) {$exp = "$exp -MaxWaitTimeInSeconds $mwt"}
    if($ovw) {$exp = "$exp -OverwriteUnManagedCustomizations"}

    Write-Host "Invoking `"$exp`""

    Invoke-Expression $exp

    Write-Host "Solution Imported"

} finally {
    Trace-VstsLeavingInvocation $MyInvocation
}


text:
			Back

			 to the previous question


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RenderingLibrary.Graphics
{
    public class LayerCameraSettings
    {
        /// <summary>
        /// Whether the current layer is in Screen Space. If true, then the Camera position does
        /// not impact the position of objects on this layer.
        /// </summary>
        public bool IsInScreenSpace
        {
            get;
            set;
        }

        public float? Zoom
        {
            get;
            set;
        }
    }
}


text:
namespace TestCases.SS.Formula.Functions
{
    using System;
    using NUnit.Framework;
    using NPOI.HSSF.UserModel;
    using NPOI.SS.Formula.Eval;
    using NPOI.SS.Formula.Functions;
    using NPOI.SS.UserModel;
    using TestCases.HSSF;

    /**
     * Tests for {@link Subtotal}
     *
     * @author Paul Tomlin
     */
    [TestFixture]
    public class TestSubtotal
    {
        private static int FUNCTION_AVERAGE = 1;
        private static int FUNCTION_COUNT = 2;
        private static int FUNCTION_MAX = 4;
        private static int FUNCTION_MIN = 5;
        private static int FUNCTION_PRODUCT = 6;
        private static int FUNCTION_STDEV = 7;
        private static int FUNCTION_SUM = 9;

        private static double[] TEST_VALUES0 = {
		1, 2,
		3, 4,
		5, 6,
		7, 8,
		9, 10
	};

        private static void ConfirmSubtotal(int function, double expected)
        {
            ValueEval[] values = new ValueEval[TEST_VALUES0.Length];
            for (int i = 0; i < TEST_VALUES0.Length; i++)
            {
                values[i] = new NumberEval(TEST_VALUES0[i]);
            }

            AreaEval arg1 = EvalFactory.CreateAreaEval("C1:D5", values);
            ValueEval[] args = { new NumberEval(function), arg1 };

            ValueEval result = new Subtotal().Evaluate(args, 0, 0);

            Assert.AreEqual(typeof(NumberEval), result.GetType());
            Assert.AreEqual(expected, ((NumberEval)result).NumberValue, 0.0);
        }
        [Test]
        public void TestBasics()
        {
            ConfirmSubtotal(FUNCTION_SUM, 55.0);
            ConfirmSubtotal(FUNCTION_AVERAGE, 5.5);
            ConfirmSubtotal(FUNCTION_COUNT, 10.0);
            ConfirmSubtotal(FUNCTION_MAX, 10.0);
            ConfirmSubtotal(FUNCTION_MIN, 1.0);
            ConfirmSubtotal(FUNCTION_PRODUCT, 3628800.0);
            ConfirmSubtotal(FUNCTION_STDEV, 3.0276503540974917);
        }
        [Test]
        public void TestAvg()
        {

            IWorkbook wb = new HSSFWorkbook();

            IFormulaEvaluator fe = wb.GetCreationHelper().CreateFormulaEvaluator();

            ISheet sh = wb.CreateSheet();
            ICell a1 = sh.CreateRow(1).CreateCell(1);
            a1.SetCellValue(1);
            ICell a2 = sh.CreateRow(2).CreateCell(1);
            a2.SetCellValue(3);
            ICell a3 = sh.CreateRow(3).CreateCell(1);
            a3.CellFormula = ("SUBTOTAL(1,B2:B3)");
            ICell a4 = sh.CreateRow(4).CreateCell(1);
            a4.SetCellValue(1);
            ICell a5 = sh.CreateRow(5).CreateCell(1);
            a5.SetCellValue(7);
            ICell a6 = sh.CreateRow(6).CreateCell(1);
            a6.CellFormula = ("SUBTOTAL(1,B2:B6)*2 + 2");
            ICell a7 = sh.CreateRow(7).CreateCell(1);
            a7.CellFormula = ("SUBTOTAL(1,B2:B7)");

            fe.EvaluateAll();

            Assert.AreEqual(2.0, a3.NumericCellValue);
            Assert.AreEqual(8.0, a6.NumericCellValue);
            Assert.AreEqual(3.0, a7.NumericCellValue);
        }
        [Test]
        public void TestSum()
        {

            IWorkbook wb = new HSSFWorkbook();

            IFormulaEvaluator fe = wb.GetCreationHelper().CreateFormulaEvaluator();

            ISheet sh = wb.CreateSheet();
            ICell a1 = sh.CreateRow(1).CreateCell(1);
            a1.SetCellValue(1);
            ICell a2 = sh.CreateRow(2).CreateCell(1);
            a2.SetCellValue(3);
            ICell a3 = sh.CreateRow(3).CreateCell(1);
            a3.CellFormula = ("SUBTOTAL(9,B2:B3)");
            ICell a4 = sh.CreateRow(4).CreateCell(1);
            a4.SetCellValue(1);
            ICell a5 = sh.CreateRow(5).CreateCell(1);
            a5.SetCellValue(7);
            ICell a6 = sh.CreateRow(6).CreateCell(1);
            a6.CellFormula = ("SUBTOTAL(9,B2:B6)*2 + 2");
            ICell a7 = sh.CreateRow(7).CreateCell(0);
            a7.CellFormula = ("SUBTOTAL(9,B2:B7)");

            fe.EvaluateAll();

            Assert.AreEqual(4.0, a3.NumericCellValue);
            Assert.AreEqual(26.0, a6.NumericCellValue);
            Assert.AreEqual(12.0, a7.NumericCellValue);
        }
        [Test]
        public void TestCount()
        {

            IWorkbook wb = new HSSFWorkbook();

            IFormulaEvaluator fe = wb.GetCreationHelper().CreateFormulaEvaluator();

            ISheet sh = wb.CreateSheet();
            ICell a1 = sh.CreateRow(1).CreateCell(1);
            a1.SetCellValue(1);
            ICell a2 = sh.CreateRow(2).CreateCell(1);
            a2.SetCellValue(3);
            ICell a3 = sh.CreateRow(3).CreateCell(1);
            a3.CellFormula = ("SUBTOTAL(2,B2:B3)");
            ICell a4 = sh.CreateRow(4).CreateCell(1);
            a4.SetCellValue("POI");                  // A4 is string and not counted
            ICell a5 = sh.CreateRow(5).CreateCell(1); // A5 is blank and not counted

            ICell a6 = sh.CreateRow(6).CreateCell(1);
            a6.CellFormula = ("SUBTOTAL(2,B2:B6)*2 + 2");
            ICell a7 = sh.CreateRow(7).CreateCell(1);
            a7.CellFormula = ("SUBTOTAL(2,B2:B7)");

            fe.EvaluateAll();

            Assert.AreEqual(2.0, a3.NumericCellValue);
            Assert.AreEqual(6.0, a6.NumericCellValue);
            Assert.AreEqual(2.0, a7.NumericCellValue);
        }
        [Test]
        public void TestCounta()
        {

            IWorkbook wb = new HSSFWorkbook();

            IFormulaEvaluator fe = wb.GetCreationHelper().CreateFormulaEvaluator();

            ISheet sh = wb.CreateSheet();
            ICell a1 = sh.CreateRow(1).CreateCell(1);
            a1.SetCellValue(1);
            ICell a2 = sh.CreateRow(2).CreateCell(1);
            a2.SetCellValue(3);
            ICell a3 = sh.CreateRow(3).CreateCell(1);
            a3.CellFormula = ("SUBTOTAL(3,B2:B3)");
            ICell a4 = sh.CreateRow(4).CreateCell(1);
            a4.SetCellValue("POI");                  // A4 is string and not counted
            ICell a5 = sh.CreateRow(5).CreateCell(1); // A5 is blank and not counted

            ICell a6 = sh.CreateRow(6).CreateCell(1);
            a6.CellFormula = ("SUBTOTAL(3,B2:B6)*2 + 2");
            ICell a7 = sh.CreateRow(7).CreateCell(1);
            a7.CellFormula = ("SUBTOTAL(3,B2:B7)");

            fe.EvaluateAll();

            Assert.AreEqual(2.0, a3.NumericCellValue);
            Assert.AreEqual(8.0, a6.NumericCellValue);
            Assert.AreEqual(3.0, a7.NumericCellValue);
        }
        [Test]
        public void TestMax()
        {

            IWorkbook wb = new HSSFWorkbook();

            IFormulaEvaluator fe = wb.GetCreationHelper().CreateFormulaEvaluator();

            ISheet sh = wb.CreateSheet();
            ICell a1 = sh.CreateRow(1).CreateCell(1);
            a1.SetCellValue(1);
            ICell a2 = sh.CreateRow(2).CreateCell(1);
            a2.SetCellValue(3);
            ICell a3 = sh.CreateRow(3).CreateCell(1);
            a3.CellFormula = ("SUBTOTAL(4,B2:B3)");
            ICell a4 = sh.CreateRow(4).CreateCell(1);
            a4.SetCellValue(1);
            ICell a5 = sh.CreateRow(5).CreateCell(1);
            a5.SetCellValue(7);
            ICell a6 = sh.CreateRow(6).CreateCell(1);
            a6.CellFormula = ("SUBTOTAL(4,B2:B6)*2 + 2");
            ICell a7 = sh.CreateRow(7).CreateCell(1);
            a7.CellFormula = ("SUBTOTAL(4,B2:B7)");

            fe.EvaluateAll();

            Assert.AreEqual(3.0, a3.NumericCellValue);
            Assert.AreEqual(16.0, a6.NumericCellValue);
            Assert.AreEqual(7.0, a7.NumericCellValue);
        }
        [Test]
        public void TestMin()
        {

            IWorkbook wb = new HSSFWorkbook();

            IFormulaEvaluator fe = wb.GetCreationHelper().CreateFormulaEvaluator();

            ISheet sh = wb.CreateSheet();
            ICell a1 = sh.CreateRow(1).CreateCell(1);
            a1.SetCellValue(1);
            ICell a2 = sh.CreateRow(2).CreateCell(1);
            a2.SetCellValue(3);
            ICell a3 = sh.CreateRow(3).CreateCell(1);
            a3.CellFormula = ("SUBTOTAL(5,B2:B3)");
            ICell a4 = sh.CreateRow(4).CreateCell(1);
            a4.SetCellValue(1);
            ICell a5 = sh.CreateRow(5).CreateCell(1);
            a5.SetCellValue(7);
            ICell a6 = sh.CreateRow(6).CreateCell(1);
            a6.CellFormula = ("SUBTOTAL(5,B2:B6)*2 + 2");
            ICell a7 = sh.CreateRow(7).CreateCell(1);
            a7.CellFormula = ("SUBTOTAL(5,B2:B7)");

            fe.EvaluateAll();

            Assert.AreEqual(1.0, a3.NumericCellValue);
            Assert.AreEqual(4.0, a6.NumericCellValue);
            Assert.AreEqual(1.0, a7.NumericCellValue);
        }
        [Test]
        public void TestStdev()
        {

            IWorkbook wb = new HSSFWorkbook();

            IFormulaEvaluator fe = wb.GetCreationHelper().CreateFormulaEvaluator();

            ISheet sh = wb.CreateSheet();
            ICell a1 = sh.CreateRow(1).CreateCell(1);
            a1.SetCellValue(1);
            ICell a2 = sh.CreateRow(2).CreateCell(1);
            a2.SetCellValue(3);
            ICell a3 = sh.CreateRow(3).CreateCell(1);
            a3.CellFormula = ("SUBTOTAL(7,B2:B3)");
            ICell a4 = sh.CreateRow(4).CreateCell(1);
            a4.SetCellValue(1);
            ICell a5 = sh.CreateRow(5).CreateCell(1);
            a5.SetCellValue(7);
            ICell a6 = sh.CreateRow(6).CreateCell(1);
            a6.CellFormula = ("SUBTOTAL(7,B2:B6)*2 + 2");
            ICell a7 = sh.CreateRow(7).CreateCell(1);
            a7.CellFormula = ("SUBTOTAL(7,B2:B7)");

            fe.EvaluateAll();

            Assert.AreEqual(1.41421, a3.NumericCellValue, 0.0001);
            Assert.AreEqual(7.65685, a6.NumericCellValue, 0.0001);
            Assert.AreEqual(2.82842, a7.NumericCellValue, 0.0001);
        }
        [Test]
        public void Test50209()
        {
            IWorkbook wb = new HSSFWorkbook();
            ISheet sh = wb.CreateSheet();
            ICell a1 = sh.CreateRow(1).CreateCell(1);
            a1.SetCellValue(1);
            ICell a2 = sh.CreateRow(2).CreateCell(1);
            a2.CellFormula = ("SUBTOTAL(9,B2)");
            ICell a3 = sh.CreateRow(3).CreateCell(1);
            a3.CellFormula = ("SUBTOTAL(9,B2:B3)");

            IFormulaEvaluator fe = wb.GetCreationHelper().CreateFormulaEvaluator();
            fe.EvaluateAll();
            Assert.AreEqual(1.0, a2.NumericCellValue);
            Assert.AreEqual(1.0, a3.NumericCellValue);
        }

        private static void ConfirmExpectedResult(IFormulaEvaluator Evaluator, String msg, ICell cell, double expected)
        {

            CellValue value = Evaluator.Evaluate(cell);
            if (value.ErrorValue != 0)
                throw new Exception(msg + ": " + value.FormatAsString());
            Assert.AreEqual(expected, value.NumberValue, msg);
        }
        [Test]
        public void TestFunctionsFromTestSpreadsheet()
        {
            HSSFWorkbook workbook = HSSFTestDataSamples.OpenSampleWorkbook("SubtotalsNested.xls");
            ISheet sheet = workbook.GetSheetAt(0);
            IFormulaEvaluator evaluator = workbook.GetCreationHelper().CreateFormulaEvaluator();

            Assert.AreEqual(10.0, sheet.GetRow(1).GetCell(1).NumericCellValue, "B2");
            Assert.AreEqual(20.0, sheet.GetRow(2).GetCell(1).NumericCellValue, "B3");

            //Test simple subtotal over one area
            ICell cellA3 = sheet.GetRow(3).GetCell(1);
            ConfirmExpectedResult(evaluator, "B4", cellA3, 30.0);

            //Test existence of the second area
            Assert.IsNotNull(sheet.GetRow(1).GetCell(2), "C2 must not be null");
            Assert.AreEqual(7.0, sheet.GetRow(1).GetCell(2).NumericCellValue, "C2");

            ICell cellC1 = sheet.GetRow(1).GetCell(3);
            ICell cellC2 = sheet.GetRow(2).GetCell(3);
            ICell cellC3 = sheet.GetRow(3).GetCell(3);

            //Test Functions SUM, COUNT and COUNTA calculation of SUBTOTAL
            //a) areas A and B are used
            //b) first 2 subtotals don't consider the value of nested subtotal in A3
            ConfirmExpectedResult(evaluator, "SUBTOTAL(SUM;B2:B8;C2:C8)", cellC1, 37.0);
            ConfirmExpectedResult(evaluator, "SUBTOTAL(COUNT;B2:B8;C2:C8)", cellC2, 3.0);
            ConfirmExpectedResult(evaluator, "SUBTOTAL(COUNTA;B2:B8;C2:C8)", cellC3, 5.0);
        }
    }

}


text:
import os
import time
import pprint
from slackclient import SlackClient
import api_ai
import purchase_amazon as pa

#from environ variable
BOT_ID = os.environ.get("AMAZON_BUYER_ID")
BOT_MANAGER_CHANNEL = os.environ.get("BOT_MANAGER_CHANNEL")

#constants
AT_BOT = "<@" + BOT_ID + ">"
BOT_SESSION_ID = "amazon_buyer_bot"

#instantiate Slack client
slack_client = SlackClient(os.environ.get('AMAZON_BUYER_TOKEN'))

def handle_command(command, channel):
    """
        Receives commands directed at the bot and determines if they
        are valid commands. If so, then acts on the commands. If not,
        returns back what it needs for clarification.
    """
    response = "I'm not sure what you mean. Can you please repeat that?\n"

    apiai_query = command
    print command
    apiai_resp = api_ai.query_apiai(apiai_query, BOT_SESSION_ID)
    pprint.pprint(apiai_resp)

    response = unicode(apiai_resp['result']['fulfillment']['speech'])
    slack_client.api_call("chat.postMessage", channel=channel,
							text=response, as_user=True)

    if apiai_resp['result']['action'] == 'buy_items':
        if apiai_resp['result']['actionIncomplete'] == False:
            items = api_ai.parse_buy_items(apiai_resp)
            item_and_quantity, item_names, item_prices, subtotal, purchase_url = pa.buy_items(items)

            response = ""
            for item_id in item_names.keys():
                response = response + "Buying {0} unit of {1}. Costs {2}\n".format(item_and_quantity[item_id], item_names[item_id], item_prices[item_id])
            response = response + "The total cost comes out to {0}\n".format(subtotal)
            response = response + "Here's the link to checkout: {0}\n".format(purchase_url)

    slack_client.api_call("chat.postMessage", channel=channel,
							text=response, as_user=True)

def parse_slack_output(slack_rtm_output):
    """
        The Slack Real Time Messaging API is an events firehose.
        this parsing function returns None unless a message is
        directed at the Bot, based on its ID.
    """
    output_list = slack_rtm_output
    if output_list and len(output_list) > 0:
        for output in output_list:
            if output and 'text' in output and AT_BOT in output['text']:
				#return text after the @mention, whitespace removed
                return output['text'].split(AT_BOT)[1].strip().lower(), \
                        output['channel']

    return None, None

if __name__ == "__main__":
    READ_WEBSOCKET_DELAY = 1
    if slack_client.rtm_connect():
        print "amazon_buyer bot connected and running!\n"
        while True:
            command, channel = parse_slack_output(slack_client.rtm_read())
            if command and channel and (channel != BOT_MANAGER_CHANNEL):
                handle_command(command, channel)
            elif channel and (channel == BOT_MANAGER_CHANNEL):
                print "got a message from the computer_networks channel"
            time.sleep(READ_WEBSOCKET_DELAY)
            print None
    else:
        print "Connection failed. Invalid Slack token or Bot ID?\n"


text:
function insert_doc(_dbName, _params){
	console.log('Insert doc Db: '+JSON.stringify(_dbName));
	console.log('Insert doc params: '+JSON.stringify(_params));

	var db = nano.use(_dbName);

	db.insert(_params, function(error, body){
		if(error){
			console.log(error);
			if(error.status_code === 404){
				nano.db.create(_dbName, function(error){
					if(error){
						console.log(error);
						responseObj.success = false;
						responseObj.error = error.error;
						responseObj.message = error.reason;
						return responseObj;
					}else{
						insert_doc(_dbName, _params);
					}
				});
			}
		}else{
			console.log(body);
			responseObj.data = {
				createdDoc_id: body.id,
				createdDoc_rev: body.rev
			};
			responseObj.message = body.ok;
			return responseObj;
		}
	});
}

function retrieve_doc(_dbName, _params, res){
	console.log('Retrieve doc Db: '+JSON.stringify(_dbName));
	console.log('Retrieve doc params: '+JSON.stringify(_params));

	var db = nano.use(_dbName);

	db.list(function(error, body){
		if(!error){
			body.rows.forEach(function(doc){
				db.get(doc.id, function(error, body){
					if(!error){
						responseObj.data.push(body);
					}else{
						responseObj.error = error;
					}

					res.send(responseObj);
				});
			});
		}else{
			responseObj.success = false;
			responseObj.error = error;

			res.send(responseObj);
		}
	});
}

module.exports = {
	insert_doc: insert_doc,
	retrieve_doc: retrieve_doc
};


text:
Sequel.migration do
  up do
    create_table :blogs do
      primary_key  :id

      # utility
      DateTime  :created_at
      DateTime  :updated_at

      # content
      String  :title
      String  :body,   :text => true
    end
  end

  down do
    drop_table :blogs
  end
end


text:
package com.dsatab.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.dsatab.data.Hero;

public class EmptyFragment extends BaseFragment {

	/*
	 * (non-Javadoc)
	 *
	 * @see com.dsatab.fragment.BaseFragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
	 */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return new FrameLayout(getActivity());
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see com.dsatab.fragment.BaseFragment#onHeroLoaded(com.dsatab.data.Hero)
	 */
	@Override
	public void onHeroLoaded(Hero hero) {

	}
}


text:
package de.vandermeer.skb.datatool.commons;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

/**
 * A map of data entry types and associated loader classes.
 *
 * @author     Sven van der Meer <vdmeer.sven@mykolab.com>
 * @version    v0.0.1 build 160301 (01-Mar-16) for Java 1.8
 * @since      v0.0.1
 */
public class TypeLoaderMap {

	/** The type/loader map. */
	private final Map<DataEntryType, DataSetLoader<?>> tlMap;

	/**
	 * Returns a new type/loader map.
	 */
	public TypeLoaderMap(){
		this.tlMap = new HashMap<>();
	}

	/**
	 * Puts a new entry in the map, if all arguments are not null.
	 * @param loader associated loader object
	 * @param <E> type of the data entry and the associated loader
	 * @return self to allow chaining
	 */
	public <E extends DataEntry> TypeLoaderMap put(DataSetLoader<E> loader){
		if(loader !=null){
			this.tlMap.put(loader.getDataEntryType(), loader);
		}
		return this;
	}

	/**
	 * Returns a loader for a given type.
	 * @param type the data entry type to lookup
	 * @param <E> type of the data entry and the associated loader
	 * @return null if no loader exists (or type was null), a loader otherwise
	 */
	@SuppressWarnings("unchecked")
	public <E extends DataEntry> DataSetLoader<E> getLoader(DataEntryType type){
		return (DataSetLoader<E>) this.tlMap.get(type);
	}

	/**
	 * Returns the local type/loader map.
	 * @return type/loader map
	 */
	public Map<DataEntryType, DataSetLoader<?>> getMap(){
		return this.tlMap;
	}

	/**
	 * Returns all types with their supported targets as string to list mapping
	 * @return all types and their supported targets
	 */
	public Map<String, Set<String>> getTypes(){
		Map<String, Set<String>> ret = new TreeMap<>();
		for(DataEntryType type : this.tlMap.keySet()){
			ret.put(type.getType(), new TreeSet<>(type.getSupportedTargets().keySet()));
		}
		return ret;
	}

	/**
	 * Returns all known targets and the types that support them as a string to list mapping.
	 * @return all targets and the types that support them
	 */
	public Map<String, Set<String>> getTargets(){
		Map<String, Set<String>> ret = new TreeMap<>();
		for(DataEntryType type : this.tlMap.keySet()){
			for(String target : type.getSupportedTargets().keySet()){
				if(!ret.containsKey(target)){
					ret.put(target, new TreeSet<String>());
				}
				ret.get(target).add(type.getType());
			}
		}
		return ret;
	}
}


text:
========
Releases
========

.. include:: ../README.rst

Table of Contents
=================

.. toctree::
    :maxdepth: 2

    concepts
    usage
    changelog


text:
const _ = require('lodash');
const urlService = require('../../../../../../../frontend/services/url');
const urlUtils = require('../../../../../../../shared/url-utils');
const localUtils = require('../../../index');

const forPost = (id, attrs, frame) => {
    attrs.url = urlService.getUrlByResourceId(id, {absolute: true});

    /**
     * CASE: admin api should serve preview urls
     *
     * @NOTE
     * The url service has no clue of the draft/scheduled concept. It only generates urls for published resources.
     * Adding a hardcoded fallback into the url service feels wrong IMO.
     *
     * Imagine the site won't be part of core and core does not serve urls anymore.
     * Core needs to offer a preview API, which returns draft posts.
     * That means the url is no longer /p/:uuid, it's e.g. GET /api/canary/content/preview/:uuid/.
     * /p/ is a concept of the site, not of core.
     *
     * The site is not aware of existing drafts. It won't be able to get the uuid.
     *
     * Needs further discussion.
     */
    if (!localUtils.isContentAPI(frame)) {
        if (attrs.status !== 'published' && attrs.url.match(/\/404\//)) {
            attrs.url = urlUtils.urlFor({
                relativeUrl: urlUtils.urlJoin('/p', attrs.uuid, '/')
            }, null, true);
        }
    }

    if (attrs.mobiledoc) {
        attrs.mobiledoc = urlUtils.mobiledocRelativeToAbsolute(
            attrs.mobiledoc,
            attrs.url
        );
    }

    ['html', 'codeinjection_head', 'codeinjection_foot'].forEach((attr) => {
        if (attrs[attr]) {
            attrs[attr] = urlUtils.htmlRelativeToAbsolute(
                attrs[attr],
                attrs.url
            );
        }
    });

    ['feature_image', 'canonical_url', 'posts_meta.og_image', 'posts_meta.twitter_image'].forEach((path) => {
        const value = _.get(attrs, path);
        if (value) {
            _.set(attrs, path, urlUtils.relativeToAbsolute(value));
        }
    });

    if (frame.options.columns && !frame.options.columns.includes('url')) {
        delete attrs.url;
    }

    return attrs;
};

const forUser = (id, attrs, options) => {
    if (!options.columns || (options.columns && options.columns.includes('url'))) {
        attrs.url = urlService.getUrlByResourceId(id, {absolute: true});
    }

    if (attrs.profile_image) {
        attrs.profile_image = urlUtils.urlFor('image', {image: attrs.profile_image}, true);
    }

    if (attrs.cover_image) {
        attrs.cover_image = urlUtils.urlFor('image', {image: attrs.cover_image}, true);
    }

    return attrs;
};

const forTag = (id, attrs, options) => {
    if (!options.columns || (options.columns && options.columns.includes('url'))) {
        attrs.url = urlService.getUrlByResourceId(id, {absolute: true});
    }

    if (attrs.feature_image) {
        attrs.feature_image = urlUtils.urlFor('image', {image: attrs.feature_image}, true);
    }

    return attrs;
};

const forSettings = (attrs) => {
    // @TODO: https://github.com/TryGhost/Ghost/issues/10106
    // @NOTE: Admin & Content API return a different format, need to mappers
    if (_.isArray(attrs)) {
        attrs.forEach((obj) => {
            if (['cover_image', 'logo', 'icon', 'portal_button_icon'].includes(obj.key) && obj.value) {
                obj.value = urlUtils.urlFor('image', {image: obj.value}, true);
            }
        });
    } else {
        if (attrs.cover_image) {
            attrs.cover_image = urlUtils.urlFor('image', {image: attrs.cover_image}, true);
        }

        if (attrs.logo) {
            attrs.logo = urlUtils.urlFor('image', {image: attrs.logo}, true);
        }

        if (attrs.icon) {
            attrs.icon = urlUtils.urlFor('image', {image: attrs.icon}, true);
        }
    }

    return attrs;
};

const forImage = (path) => {
    return urlUtils.urlFor('image', {image: path}, true);
};

module.exports.forPost = forPost;
module.exports.forUser = forUser;
module.exports.forTag = forTag;
module.exports.forSettings = forSettings;
module.exports.forImage = forImage;


text:
package com.intellij.openapi.editor.impl.softwrap.mapping;

import com.intellij.openapi.editor.*;
import javax.annotation.Nonnull;

public class EditorPosition implements Cloneable {
  public int logicalLine;
  public int offset;
  public int x;

  private final Editor myEditor;

  public EditorPosition(@Nonnull Editor editor) {
    myEditor = editor;
  }

  public EditorPosition(@Nonnull LogicalPosition logical, int offset, @Nonnull Editor editor) {
    myEditor = editor;
    logicalLine = logical.line;
    this.offset = offset;
  }

  public void onNewLine() {
    logicalLine++;
    x = 0;
    offset++;
  }

  /**
   * Updates state of the current processing position in order to point it to the end offset of the given fold region.
   *
   * @param foldRegion                        fold region which end offset should be pointed by the current position
   */
  public void advance(@Nonnull FoldRegion foldRegion) {
    offset = foldRegion.getEndOffset();

    Document document = myEditor.getDocument();
    int endOffsetLogicalLine = document.getLineNumber(foldRegion.getEndOffset());
    if (logicalLine != endOffsetLogicalLine) {
      int linesDiff = endOffsetLogicalLine - logicalLine;
      logicalLine += linesDiff;
    }
  }

  public void from(@Nonnull EditorPosition position) {
    logicalLine = position.logicalLine;
    offset = position.offset;
    x = position.x;
  }

  @Override
  public EditorPosition clone() {
    EditorPosition result = new EditorPosition(myEditor);
    result.logicalLine = logicalLine;
    result.offset = offset;
    result.x = x;
    return result;
  }

  @Override
  public String toString() {
    return String.format("logical line: %d; offset: %d", logicalLine, offset);
  }
}


text:
NSString * const kARMediatorTargetReader = @"Reader";

NSString * const kARMediatorActionParseContent = @"parseContent";
NSString * const kARMediatorActionViewController = @"viewController";
NSString * const kARMediatorActionCell = @"readerCell";
NSString * const kARMediatorActionConfigCell = @"configReaderCell";

@implementation ARMediator (Reader)

- (UIViewController *)Reader_center
{
    ARReaderCenter *center = [self performTarget:kARMediatorTargetReader action:kARMediatorActionViewController params:nil shouldCacheTarget:NO];
    if ([center isKindOfClass:[UIViewController class]]) {
        return center;
    } else {
        return [[UIViewController alloc] init];
    }
}

- (NSArray *)Reader_parseContentWithParser:(ARPageParser *)parser content:(NSString *)content
{
    return [self performTarget:kARMediatorTargetReader
                        action:kARMediatorActionParseContent
                        params:@{
                                 @"parser":parser,
                                 @"content":content
                                 }
             shouldCacheTarget:YES];
}

- (UICollectionViewCell *)Reader_cellWithIdentifier:(NSString *)identifier collectionView:(UICollectionView *)collectionView indexPath:(NSIndexPath *)indexPath
{
    return [self performTarget:kARMediatorTargetReader
                        action:kARMediatorActionCell
                        params:@{
                                 @"identifier":identifier,
                                 @"collectionView":collectionView,
                                 @"indexPath":indexPath
                                 }
             shouldCacheTarget:YES];
}

- (void)Reader_configCollectionViewCell:(UICollectionViewCell *)cell pageData:(ARPageData *)pageData
{
    [self performTarget:kARMediatorTargetReader
                 action:kARMediatorActionConfigCell
                 params:@{
                          @"cell":cell,
                          @"pageData":pageData
                          }
      shouldCacheTarget:YES];
}

- (void)Reader_cleanCollectionViewCellTarget
{
    [self releaseCachedTargetWithTargetName:kARMediatorTargetReader];
}

@end


text: collection of the tutorials


text:
import React from 'react';
import getCx from 'decorators/get-cx';
import getCy from 'decorators/get-cy';
import setStateFromProps from 'decorators/set-state-from-props';

@getCx
@getCy
@setStateFromProps
export default class LineMarker extends React.Component {

  static propTypes = {
    style: React.PropTypes.object,
    x: React.PropTypes.number.isRequired,
    y: React.PropTypes.number.isRequired,
  }

  static defaultProps = {
    style: {},
    x: 0,
    y: 0,
  }

  static getRadius() {
    return 7;
  }

  state = {
    cx: 0,
    cy: 0,
  }

  setStateFromProps(props) {
    this.setState({
      cx: this.getCx(props.x),
      cy: this.getCy(props.y),
    });
  }

  render() {
    return (
      <circle
        className={'line-marker'}
        cx={this.state.cx}
        cy={this.state.cy}
        r={LineMarker.getRadius()}
        style={this.props.style} />
    );
  }

}


text:
package org.bouncycastle.asn1.ess;

import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.DigestInfo;
import org.bouncycastle.asn1.x509.IssuerSerial;

public class OtherCertID
    extends ASN1Object
{
    private ASN1Encodable otherCertHash;
    private IssuerSerial issuerSerial;

    public static OtherCertID getInstance(Object o)
    {
        if (o instanceof OtherCertID)
        {
            return (OtherCertID) o;
        }
        else if (o != null)
        {
            return new OtherCertID(ASN1Sequence.getInstance(o));
        }

        return null;
    }

    /**
     * constructor
     */
    private OtherCertID(ASN1Sequence seq)
    {
        if (seq.size() < 1 || seq.size() > 2)
        {
            throw new IllegalArgumentException("Bad sequence size: "
                    + seq.size());
        }

        if (seq.getObjectAt(0).toASN1Primitive() instanceof ASN1OctetString)
        {
            otherCertHash = ASN1OctetString.getInstance(seq.getObjectAt(0));
        }
        else
        {
            otherCertHash = DigestInfo.getInstance(seq.getObjectAt(0));

        }

        if (seq.size() > 1)
        {
            issuerSerial = IssuerSerial.getInstance(seq.getObjectAt(1));
        }
    }

    public OtherCertID(
        AlgorithmIdentifier  algId,
        byte[]               digest)
    {
        this.otherCertHash = new DigestInfo(algId, digest);
    }

    public OtherCertID(
        AlgorithmIdentifier  algId,
        byte[]               digest,
        IssuerSerial    issuerSerial)
    {
        this.otherCertHash = new DigestInfo(algId, digest);
        this.issuerSerial = issuerSerial;
    }

    public AlgorithmIdentifier getAlgorithmHash()
    {
        if (otherCertHash.toASN1Primitive() instanceof ASN1OctetString)
        {
            // SHA-1
            return new AlgorithmIdentifier("1.3.14.3.2.26");
        }
        else
        {
            return DigestInfo.getInstance(otherCertHash).getAlgorithmId();
        }
    }

    public byte[] getCertHash()
    {
        if (otherCertHash.toASN1Primitive() instanceof ASN1OctetString)
        {
            // SHA-1
            return ((ASN1OctetString)otherCertHash.toASN1Primitive()).getOctets();
        }
        else
        {
            return DigestInfo.getInstance(otherCertHash).getDigest();
        }
    }

    public IssuerSerial getIssuerSerial()
    {
        return issuerSerial;
    }

    /**
     * <pre>
     * OtherCertID ::= SEQUENCE {
     *     otherCertHash    OtherHash,
     *     issuerSerial     IssuerSerial OPTIONAL }
     *
     * OtherHash ::= CHOICE {
     *     sha1Hash     OCTET STRING,
     *     otherHash    OtherHashAlgAndValue }
     *
     * OtherHashAlgAndValue ::= SEQUENCE {
     *     hashAlgorithm    AlgorithmIdentifier,
     *     hashValue        OCTET STRING }
     *
     * </pre>
     */
    public ASN1Primitive toASN1Primitive()
    {
        ASN1EncodableVector v = new ASN1EncodableVector();

        v.add(otherCertHash);

        if (issuerSerial != null)
        {
            v.add(issuerSerial);
        }

        return new DERSequence(v);
    }
}


text:
static NSString *VWWRemindersPermissionType = @"Reminders";

@interface VWWRemindersPermission : VWWPermission

@end


text:
    missing_docs,
    missing_debug_implementations,
    missing_copy_implementations,
    trivial_casts,
    trivial_numeric_casts,
    unsafe_code,
    unstable_features,
    unused_import_braces,
    unused_qualifications
)]

mod cli;
mod rm;

use std::process;

use clap::Parser;

fn main() {
    let args = cli::Command::parse();

    if let Err(err) = args.exec() {
        eprintln!("Error: {:?}", err);

        process::exit(1);
    }
}


text:
package org.jboss.pnc.causewayclient;

import org.jboss.pnc.api.causeway.dto.push.BuildImportRequest;
import org.jboss.pnc.api.causeway.dto.untag.UntagRequest;

/**
 * @author Matej Lazar
 */
public interface CausewayClient {

    boolean importBuild(BuildImportRequest buildImportRequest, String authToken);

    boolean untagBuild(UntagRequest untagRequest, String authToken);
}


text:
module Jekyll
  module Commands
    module Watch
      extend self

      def init_with_program(prog)
      end

      # Build your jekyll site
      # Continuously watch if `watch` is set to true in the config.
      def process(options)
        Jekyll.logger.log_level = :error if options['quiet']
        watch(site, options) if options['watch']
      end

      # Watch for file changes and rebuild the site.
      #
      # site - A Jekyll::Site instance
      # options - A Hash of options passed to the command
      #
      # Returns nothing.
      def watch(_site, options)
        Jekyll::Watcher.watch(options)
      end

    end
  end
end


text:
<?php

namespace SP\DataModel;

defined('APP_ROOT') || die();

/**
 * Class UserBasicData
 *
 * @package SP\DataModel
 */
class UserData extends UserPassData implements DataModelInterface
{
    /**
     * @var string
     */
    public $user_login = '';
    /**
     * @var string
     */
    public $user_name = '';
    /**
     * @var string
     */
    public $user_email = '';
    /**
     * @var string
     */
    public $user_notes = '';
    /**
     * @var int
     */
    public $user_groupId = 0;
    /**
     * @var int
     */
    public $user_profileId = 0;
    /**
     * @var bool
     */
    public $user_isAdminApp = 0;
    /**
     * @var bool
     */
    public $user_isAdminAcc = 0;
    /**
     * @var bool
     */
    public $user_isDisabled = 0;
    /**
     * @var bool
     */
    public $user_isChangePass = 0;
    /**
     * @var bool
     */
    public $user_isChangedPass = 0;
    /**
     * @var bool
     */
    public $user_isLdap = 0;
    /**
     * @var int
     */
    public $user_count = 0;
    /**
     * @var string
     */
    public $user_lastLogin = '';
    /**
     * @var string
     */
    public $user_lastUpdate = '';
    /**
     * @var bool
     */
    public $user_isMigrate = 0;
    /**
     * @var
     */
    public $user_preferences;
    /**
     * @var string
     */
    public $usergroup_name = '';

    /**
     * @return int
     */
    public function getUserCount()
    {
        return (int)$this->user_count;
    }

    /**
     * @param int $user_count
     */
    public function setUserCount($user_count)
    {
        $this->user_count = (int)$user_count;
    }

    /**
     * @return string
     */
    public function getUserLastLogin()
    {
        return $this->user_lastLogin;
    }

    /**
     * @param string $user_lastLogin
     */
    public function setUserLastLogin($user_lastLogin)
    {
        $this->user_lastLogin = $user_lastLogin;
    }

    /**
     * @return string
     */
    public function getUserLastUpdate()
    {
        return $this->user_lastUpdate;
    }

    /**
     * @param string $user_lastUpdate
     */
    public function setUserLastUpdate($user_lastUpdate)
    {
        $this->user_lastUpdate = $user_lastUpdate;
    }

    /**
     * @return boolean
     */
    public function isUserIsMigrate()
    {
        return (int)$this->user_isMigrate;
    }

    /**
     * @param boolean $user_isMigrate
     */
    public function setUserIsMigrate($user_isMigrate)
    {
        $this->user_isMigrate = (int)$user_isMigrate;
    }

    /**
     * @return mixed
     */
    public function getUserPreferences()
    {
        return $this->user_preferences;
    }

    /**
     * @param mixed $user_preferences
     */
    public function setUserPreferences($user_preferences)
    {
        $this->user_preferences = $user_preferences;
    }

    /**
     * @return string
     */
    public function getUserEmail()
    {
        return $this->user_email;
    }

    /**
     * @param string $user_email
     */
    public function setUserEmail($user_email)
    {
        $this->user_email = $user_email;
    }

    /**
     * @return string
     */
    public function getUserNotes()
    {
        return $this->user_notes;
    }

    /**
     * @param string $user_notes
     */
    public function setUserNotes($user_notes)
    {
        $this->user_notes = $user_notes;
    }

    /**
     * @return int
     */
    public function getUserGroupId()
    {
        return (int)$this->user_groupId;
    }

    /**
     * @param int $user_groupId
     */
    public function setUserGroupId($user_groupId)
    {
        $this->user_groupId = (int)$user_groupId;
    }

    /**
     * @return int
     */
    public function getUserProfileId()
    {
        return (int)$this->user_profileId;
    }

    /**
     * @param int $user_profileId
     */
    public function setUserProfileId($user_profileId)
    {
        $this->user_profileId = (int)$user_profileId;
    }

    /**
     * @return boolean
     */
    public function isUserIsAdminApp()
    {
        return (int)$this->user_isAdminApp;
    }

    /**
     * @param boolean $user_isAdminApp
     */
    public function setUserIsAdminApp($user_isAdminApp)
    {
        $this->user_isAdminApp = (int)$user_isAdminApp;
    }

    /**
     * @return boolean
     */
    public function isUserIsAdminAcc()
    {
        return (int)$this->user_isAdminAcc;
    }

    /**
     * @param boolean $user_isAdminAcc
     */
    public function setUserIsAdminAcc($user_isAdminAcc)
    {
        $this->user_isAdminAcc = (int)$user_isAdminAcc;
    }

    /**
     * @return boolean
     */
    public function isUserIsDisabled()
    {
        return (int)$this->user_isDisabled;
    }

    /**
     * @param boolean $user_isDisabled
     */
    public function setUserIsDisabled($user_isDisabled)
    {
        $this->user_isDisabled = (int)$user_isDisabled;
    }

    /**
     * @return boolean
     */
    public function isUserIsChangePass()
    {
        return (int)$this->user_isChangePass;
    }

    /**
     * @param boolean $user_isChangePass
     */
    public function setUserIsChangePass($user_isChangePass)
    {
        $this->user_isChangePass = (int)$user_isChangePass;
    }

    /**
     * @return boolean
     */
    public function isUserIsLdap()
    {
        return (int)$this->user_isLdap;
    }

    /**
     * @param boolean $user_isLdap
     */
    public function setUserIsLdap($user_isLdap)
    {
        $this->user_isLdap = (int)$user_isLdap;
    }

    /**
     * @return string
     */
    public function getUserLogin()
    {
        return $this->user_login;
    }

    /**
     * @param string $user_login
     */
    public function setUserLogin($user_login)
    {
        $this->user_login = $user_login;
    }

    /**
     * @return string
     */
    public function getUserName()
    {
        return $this->user_name;
    }

    /**
     * @param string $user_name
     */
    public function setUserName($user_name)
    {
        $this->user_name = $user_name;
    }

    /**
     * @return string
     */
    public function getUsergroupName()
    {
        return $this->usergroup_name;
    }

    /**
     * @param string $usergroup_name
     */
    public function setUsergroupName($usergroup_name)
    {
        $this->usergroup_name = $usergroup_name;
    }

    /**
     * @return int
     */
    public function getId()
    {
        return (int)$this->user_id;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->user_name;
    }

    /**
     * @return bool
     */
    public function isUserIsChangedPass()
    {
        return (int)$this->user_isChangedPass;
    }

    /**
     * @param bool $user_isChangedPass
     */
    public function setUserIsChangedPass($user_isChangedPass)
    {
        $this->user_isChangedPass = (int)$user_isChangedPass;
    }
}


text:
var request = require('request');
var colors = require('colors');
var argv = require('yargs').argv;

if (argv._.length > 2) {
    request('http://mymemory.translated.net/api/get?q=' + argv._[0] + '&langpair=' + argv._[1] + '|' + argv._[2], function (error, response, body) {

        if (response.statusCode === 200) {

            var data = JSON.parse(body.trim());

            data.matches.forEach(function (val, index, theArray) {

                console.log(colors.green(val.translation));

            });
        }else{
            console.error(colors.red('translating error !'));

        }

    });
} else {

    console.error(colors.red('missing parameters'));
}


text:
        <form th:action="@{/acp/general/logging}" th:object="${loggingSettingsForm}"
              method="post">

                <button type="button" class="close" data-dismiss="alert">×</button>
                Settings saved correctly

                Debug logging framework:

                    <input type="checkbox" th:field="*{debugLoggingFrameworkMode}"
                           class="form-check-input" id="debugLoggingFrameworkMode">
                    Enable debug informations about logging configuration

                Packaging data visible in stacktraces:

                    <input type="checkbox" th:field="*{showPackagingData}"
                           class="form-check-input" id="showPackagingData">
                    Show packaging data (jar target) in visible stacktraces

            <button type="submit" class="btn btn-primary">Save</button>

            Logging console appenders:

                    #
                    Name
                    Target
                    Filter
                    Log pattern
                    Use color
                    Actions

                    1
                    Name
                    Target
                    Filter
                    Log pattern
                    Use color

                            Edit

Delete

Add new console
                appender

            Logging file appenders:

                    #
                    Name
                    Current log file name
                    File name pattern
                    Max file size
                    Max history
                    Filter
                    Log pattern
                    Actions

                    1
                    Name
                    Current log file name
                    File name pattern
                    Max file size
                    Max history
                    Filter
                    Log pattern

                            Edit

Delete

Add new file appender

            Loggers:

                    #
                    Name
                    Level
                    Addivity
                    Appenders
                    Actions

                    1
                    Name
                    Level
                    Addivity

Edit

Edit

Delete

Add new logger

        </form>


text:
"use strict";

// This module is suitable for passing as options.parser when calling
// recast.parse to process JavaScript code with Acorn:
//
//   const ast = recast.parse(source, {
//     parser: require("recast/parsers/acorn")
//   });
//
const getOption = require("../lib/util.js").getOption;

exports.parse = function parse(source, options) {
  const comments = [];
  const tokens = [];
  const ast = require("acorn").parse(source, {
    allowHashBang: true,
    allowImportExportEverywhere: true,
    allowReturnOutsideFunction: true,
    ecmaVersion: getOption(options, "ecmaVersion", 8),
    sourceType: getOption(options, "sourceType", "module"),
    locations: true,
    onComment: comments,
    onToken: tokens,
  });

  if (! ast.comments) {
    ast.comments = comments;
  }

  if (! ast.tokens) {
    ast.tokens = tokens;
  }

  return ast;
};