text:
package io.aos.concurrent.atomic;

import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.RandomAccess;
import java.util.Vector;

public class CollectionTest extends BaseTest {
    static int nLoops;

    public static void main(String... args) {

        nLoops = 10000;
        doTest(new Vector());
        doTest(new ModVector());
        doTest(new ArrayList());
        doTest(Collections.synchronizedList(new ArrayList()));
        nLoops = Integer.parseInt(args[0]);

        System.out.println("Starting synchronized vector test");
        cleanGC();
        Timestamp syncTS = new Timestamp();
        doTest(new Vector());
        syncTS.stop();
        System.out.println("Synchronized vector took " + syncTS);

        System.out.println("Starting unsynchronized vector test");
        cleanGC();
        Timestamp unsyncTS = new Timestamp();
        doTest(new ModVector());
        unsyncTS.stop();
        System.out.println("Unsynchronized vector took " + unsyncTS);

        double d = ((double) (syncTS.elapsedTime() - unsyncTS.elapsedTime()))
                / nLoops;
        System.out.println("Unsynchronized operation saves " + d + " "
                + syncTS.units() + " per call");

        System.out.println("Starting synchronized array list test");
        cleanGC();
        syncTS = new Timestamp();
        doTest(Collections.synchronizedList(new ArrayList()));
        syncTS.stop();
        System.out.println("Synchronized array list took " + syncTS);

        System.out.println("Starting unsynchronized array list test");
        cleanGC();
        unsyncTS = new Timestamp();
        doTest(new ArrayList());
        unsyncTS.stop();
        System.out.println("Unsynchronized aray list took " + unsyncTS);

        d = ((double) (syncTS.elapsedTime() - unsyncTS.elapsedTime())) / nLoops;
        System.out.println("Unsynchronized operation saves " + d + " "
                + syncTS.units() + " per call");
    }

    static void cleanGC() {
        System.gc();
        System.runFinalization();
        System.gc();
    }

    static void doTest(List l) {
        Integer n = new Integer(0);
        for (int i = 0; i < nLoops; i++)
            l.add(n);
    }

    /**
     * The ModVector class implements a growable array of objects.
     * Like an array, it contains components that can be accessed using an
     * integer index. However, the size of a ModVector can grow or
     * shrink as needed to accommodate adding and removing items after the
     * ModVector has been created.
     *

     *
     * Each vector tries to optimize storage management by maintaining a
     * capacity and a capacityIncrement. The
     * capacity is always at least as large as the vector size; it
     * is usually larger because as components are added to the vector, the
     * vector's storage increases in chunks the size of
     * capacityIncrement. An application can increase the capacity
     * of a vector before inserting a large number of components; this reduces
     * the amount of incremental reallocation.
     *

     *
     * As of the Java 2 platform v1.2, this class has been retrofitted to
     * implement List, so that it becomes a part of Java's collection framework.
     * Unlike the new collection implementations, ModVector is synchronized.
     *

     *
     * The Iterators returned by ModVector's iterator and listIterator methods
     * are fail-fast: if the ModVector is structurally modified at any
     * time after the Iterator is created, in any way except through the
     * Iterator's own remove or add methods, the Iterator will throw a
     * 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. The Enumerations returned by ModVector's elements method are
     * not fail-fast.
     *
     *

     * 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 <tt>ConcurrentModificationException</tt> 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.
     *

     *
     * This class is a member of the  Java Collections Framework.
     *
     * @author Lee Boynton
     * @author Jonathan Payne
     * @version 1.94, 06/22/03
     * @see Collection
     * @see List
     * @see ArrayList
     * @see LinkedList
     * @since JDK1.0
     */
    public static class ModVector<E> extends AbstractList<E> implements
            List<E>, RandomAccess, Cloneable, java.io.Serializable {
        /**
         * The array buffer into which the components of the vector are stored.
         * The capacity of the vector is the length of this array buffer, and is
         * at least large enough to contain all the vector's elements.
         *

         *
         * Any array elements following the last element in the ModVector are
         * null.
         *
         * @serial
         */
        protected Object[] elementData;

        /**
         * The number of valid components in this <tt>ModVector</tt> object.
         * Components <tt>elementData[0]</tt> through
         * <tt>elementData[elementCount-1]</tt> are the actual items.
         *
         * @serial
         */
        protected int elementCount;

        /**
         * The amount by which the capacity of the vector is automatically
         * incremented when its size becomes greater than its capacity. If the
         * capacity increment is less than or equal to zero, the capacity of the
         * vector is doubled each time it needs to grow.
         *
         * @serial
         */
        protected int capacityIncrement;

        /** use serialVersionUID from JDK 1.0.2 for interoperability */
        private static final long serialVersionUID = -2767605614048989439L;

        /**
         * Constructs an empty vector with the specified initial capacity and
         * capacity increment.
         *
         * @param initialCapacity
         *            the initial capacity of the vector.
         * @param capacityIncrement
         *            the amount by which the capacity is increased when the
         *            vector overflows.
         * @exception IllegalArgumentException
         *                if the specified initial capacity is negative
         */
        public ModVector(int initialCapacity, int capacityIncrement) {
            super();
            if (initialCapacity < 0)
                throw new IllegalArgumentException("Illegal Capacity: "
                        + initialCapacity);
            this.elementData = new Object[initialCapacity];
            this.capacityIncrement = capacityIncrement;
        }

        /**
         * Constructs an empty vector with the specified initial capacity and
         * with its capacity increment equal to zero.
         *
         * @param initialCapacity
         *            the initial capacity of the vector.
         * @exception IllegalArgumentException
         *                if the specified initial capacity is negative
         */
        public ModVector(int initialCapacity) {
            this(initialCapacity, 0);
        }

        /**
         * Constructs an empty vector so that its internal data array has size
         * <tt>10</tt> and its standard capacity increment is zero.
         */
        public ModVector() {
            this(10);
        }

        /**
         * Constructs a vector containing the elements of the specified
         * collection, in the order they are returned by the collection's
         * iterator.
         *
         * @param c
         *            the collection whose elements are to be placed into this
         *            vector.
         * @throws NullPointerException
         *             if the specified collection is null.
         * @since 1.2
         */
        public ModVector(Collection<? extends E> c) {
            elementCount = c.size();
            // 10% for growth
            elementData = new Object[(int) Math.min(
                    (elementCount * 110L) / 100, Integer.MAX_VALUE)];
            c.toArray(elementData);
        }

        /**
         * Copies the components of this vector into the specified array. The
         * item at index <tt>k</tt> in this vector is copied into component
         * <tt>k</tt> of <tt>anArray</tt>. The array must be big enough to hold
         * all the objects in this vector, else an
         * <tt>IndexOutOfBoundsException</tt> is thrown.
         *
         * @param anArray
         *            the array into which the components get copied.
         * @throws NullPointerException
         *             if the given array is null.
         */
        public void copyInto(Object[] anArray) {
            System.arraycopy(elementData, 0, anArray, 0, elementCount);
        }

        /**
         * Trims the capacity of this vector to be the vector's current size. If
         * the capacity of this vector is larger than its current size, then the
         * capacity is changed to equal the size by replacing its internal data
         * array, kept in the field <tt>elementData</tt>, with a smaller one. An
         * application can use this operation to minimize the storage of a
         * vector.
         */
        public void trimToSize() {
            modCount++;
            int oldCapacity = elementData.length;
            if (elementCount < oldCapacity) {
                Object oldData[] = elementData;
                elementData = new Object[elementCount];
                System.arraycopy(oldData, 0, elementData, 0, elementCount);
            }
        }

        /**
         * Increases the capacity of this vector, if necessary, to ensure that
         * it can hold at least the number of components specified by the
         * minimum capacity argument.
         *
         *

         * If the current capacity of this vector is less than
         * <tt>minCapacity</tt>, then its capacity is increased by replacing its
         * internal data array, kept in the field <tt>elementData</tt>, with a
         * larger one. The size of the new data array will be the old size plus
         * <tt>capacityIncrement</tt>, unless the value of
         * <tt>capacityIncrement</tt> is less than or equal to zero, in which
         * case the new capacity will be twice the old capacity; but if this new
         * size is still smaller than <tt>minCapacity</tt>, then the new
         * capacity will be <tt>minCapacity</tt>.
         *
         * @param minCapacity
         *            the desired minimum capacity.
         */
        public void ensureCapacity(int minCapacity) {
            modCount++;
            ensureCapacityHelper(minCapacity);
        }

        /**
         * This implements the unsynchronized semantics of ensureCapacity.
         * Synchronized methods in this class can internally call this method
         * for ensuring capacity without incurring the cost of an extra
         * synchronization.
         *
         * @see java.util.ModVector#ensureCapacity(int)
         */
        private void ensureCapacityHelper(int minCapacity) {
            int oldCapacity = elementData.length;
            if (minCapacity > oldCapacity) {
                Object[] oldData = elementData;
                int newCapacity = (capacityIncrement > 0) ? (oldCapacity + capacityIncrement)
                        : (oldCapacity * 2);
                if (newCapacity < minCapacity) {
                    newCapacity = minCapacity;
                }
                elementData = new Object[newCapacity];
                System.arraycopy(oldData, 0, elementData, 0, elementCount);
            }
        }

        /**
         * Sets the size of this vector. If the new size is greater than the
         * current size, new null items are added to the end of the
         * vector. If the new size is less than the current size, all components
         * at index newSize and greater are discarded.
         *
         * @param newSize
         *            the new size of this vector.
         * @throws ArrayIndexOutOfBoundsException
         *             if new size is negative.
         */
        public void setSize(int newSize) {
            modCount++;
            if (newSize > elementCount) {
                ensureCapacityHelper(newSize);
            } else {
                for (int i = newSize; i < elementCount; i++) {
                    elementData[i] = null;
                }
            }
            elementCount = newSize;
        }

        /**
         * Returns the current capacity of this vector.
         *
         * @return the current capacity (the length of its internal data array,
         *         kept in the field <tt>elementData</tt> of this vector).
         */
        public int capacity() {
            return elementData.length;
        }

        /**
         * Returns the number of components in this vector.
         *
         * @return the number of components in this vector.
         */
        public int size() {
            return elementCount;
        }

        /**
         * Tests if this vector has no components.
         *
         * @return true if and only if this vector has no
         *         components, that is, its size is zero; false
         *         otherwise.
         */
        public boolean isEmpty() {
            return elementCount == 0;
        }

        /**
         * Returns an enumeration of the components of this vector. The returned
         * <tt>Enumeration</tt> object will generate all items in this vector.
         * The first item generated is the item at index <tt>0</tt>, then the
         * item at index <tt>1</tt>, and so on.
         *
         * @return an enumeration of the components of this vector.
         * @see Enumeration
         * @see Iterator
         */
        public Enumeration<E> elements() {
            return new Enumeration<E>() {
                int count = 0;

                public boolean hasMoreElements() {
                    return count < elementCount;
                }

                public E nextElement() {
                    synchronized (ModVector.this) {
                        if (count < elementCount) {
                            return (E) elementData[count++];
                        }
                    }
                    throw new NoSuchElementException("ModVector Enumeration");
                }
            };
        }

        /**
         * Tests if the specified object is a component in this vector.
         *
         * @param elem
         *            an object.
         * @return true if and only if the specified object is the
         *         same as a component in this vector, as determined by the
         *         <tt>equals</tt> method; false otherwise.
         */
        public boolean contains(Object elem) {
            return indexOf(elem, 0) >= 0;
        }

        /**
         * Searches for the first occurence of the given argument, testing for
         * equality using the equals method.
         *
         * @param elem
         *            an object.
         * @return the index of the first occurrence of the argument in this
         *         vector, that is, the smallest value <tt>k</tt> such that
         *         <tt>elem.equals(elementData[k])</tt> is <tt>true</tt>;
         *         returns -1 if the object is not found.
         * @see Object#equals(Object)
         */
        public int indexOf(Object elem) {
            return indexOf(elem, 0);
        }

        /**
         * Searches for the first occurence of the given argument, beginning the
         * search at index, and testing for equality using the
         * equals method.
         *
         * @param elem
         *            an object.
         * @param index
         *            the non-negative index to start searching from.
         * @return the index of the first occurrence of the object argument in
         *         this vector at position index or later in the
         *         vector, that is, the smallest value <tt>k</tt> such that
         *         <tt>elem.equals(elementData[k]) && (k >= index)</tt> is
         *         <tt>true</tt>; returns -1 if the object is not
         *         found. (Returns -1 if <tt>index</tt> >= the
         *         current size of this <tt>ModVector</tt>.)
         * @exception IndexOutOfBoundsException
         *                if <tt>index</tt> is negative.
         * @see Object#equals(Object)
         */
        public int indexOf(Object elem, int index) {
            if (elem == null) {
                for (int i = index; i < elementCount; i++)
                    if (elementData[i] == null)
                        return i;
            } else {
                for (int i = index; i < elementCount; i++)
                    if (elem.equals(elementData[i]))
                        return i;
            }
            return -1;
        }

        /**
         * Returns the index of the last occurrence of the specified object in
         * this vector.
         *
         * @param elem
         *            the desired component.
         * @return the index of the last occurrence of the specified object in
         *         this vector, that is, the largest value <tt>k</tt> such that
         *         <tt>elem.equals(elementData[k])</tt> is <tt>true</tt>;
         *         returns -1 if the object is not found.
         */
        public int lastIndexOf(Object elem) {
            return lastIndexOf(elem, elementCount - 1);
        }

        /**
         * Searches backwards for the specified object, starting from the
         * specified index, and returns an index to it.
         *
         * @param elem
         *            the desired component.
         * @param index
         *            the index to start searching from.
         * @return the index of the last occurrence of the specified object in
         *         this vector at position less than or equal to
         *         index in the vector, that is, the largest value
         *         <tt>k</tt> such that
         *         <tt>elem.equals(elementData[k]) && (k <= index)</tt> is
         *         <tt>true</tt>; -1 if the object is not found.
         *         (Returns -1 if <tt>index</tt> is negative.)
         * @exception IndexOutOfBoundsException
         *                if <tt>index</tt> is greater than or equal to the
         *                current size of this vector.
         */
        public int lastIndexOf(Object elem, int index) {
            if (index >= elementCount)
                throw new IndexOutOfBoundsException(index + " >= "
                        + elementCount);

            if (elem == null) {
                for (int i = index; i >= 0; i--)
                    if (elementData[i] == null)
                        return i;
            } else {
                for (int i = index; i >= 0; i--)
                    if (elem.equals(elementData[i]))
                        return i;
            }
            return -1;
        }

        /**
         * Returns the component at the specified index.
         *

         *
         * This method is identical in functionality to the get method (which is
         * part of the List interface).
         *
         * @param index
         *            an index into this vector.
         * @return the component at the specified index.
         * @exception ArrayIndexOutOfBoundsException
         *                if the <tt>index</tt> is negative or not less than the
         *                current size of this <tt>ModVector</tt> object. given.
         * @see #get(int)
         * @see List
         */
        public E elementAt(int index) {
            if (index >= elementCount) {
                throw new ArrayIndexOutOfBoundsException(index + " >= "
                        + elementCount);
            }

            return (E) elementData[index];
        }

        /**
         * Returns the first component (the item at index <tt>0</tt>) of this
         * vector.
         *
         * @return the first component of this vector.
         * @exception NoSuchElementException
         *                if this vector has no components.
         */
        public E firstElement() {
            if (elementCount == 0) {
                throw new NoSuchElementException();
            }
            return (E) elementData[0];
        }

        /**
         * Returns the last component of the vector.
         *
         * @return the last component of the vector, i.e., the component at
         *         index size() - 1.
         * @exception NoSuchElementException
         *                if this vector is empty.
         */
        public E lastElement() {
            if (elementCount == 0) {
                throw new NoSuchElementException();
            }
            return (E) elementData[elementCount - 1];
        }

        /**
         * Sets the component at the specified index of this vector
         * to be the specified object. The previous component at that position
         * is discarded.
         *

         *
         * The index must be a value greater than or equal to 0 and
         * less than the current size of the vector.
         *

         *
         * This method is identical in functionality to the set method (which is
         * part of the List interface). Note that the set method reverses the
         * order of the parameters, to more closely match array usage. Note also
         * that the set method returns the old value that was stored at the
         * specified position.
         *
         * @param obj
         *            what the component is to be set to.
         * @param index
         *            the specified index.
         * @exception ArrayIndexOutOfBoundsException
         *                if the index was invalid.
         * @see #size()
         * @see List
         * @see #set(int, java.lang.Object)
         */
        public void setElementAt(E obj, int index) {
            if (index >= elementCount) {
                throw new ArrayIndexOutOfBoundsException(index + " >= "
                        + elementCount);
            }
            elementData[index] = obj;
        }

        /**
         * Deletes the component at the specified index. Each component in this
         * vector with an index greater or equal to the specified
         * index is shifted downward to have an index one smaller
         * than the value it had previously. The size of this vector is
         * decreased by <tt>1</tt>.
         *

         *
         * The index must be a value greater than or equal to 0 and
         * less than the current size of the vector.
         *

         *
         * This method is identical in functionality to the remove method (which
         * is part of the List interface). Note that the remove method returns
         * the old value that was stored at the specified position.
         *
         * @param index
         *            the index of the object to remove.
         * @exception ArrayIndexOutOfBoundsException
         *                if the index was invalid.
         * @see #size()
         * @see #remove(int)
         * @see List
         */
        public void removeElementAt(int index) {
            modCount++;
            if (index >= elementCount) {
                throw new ArrayIndexOutOfBoundsException(index + " >= "
                        + elementCount);
            } else if (index < 0) {
                throw new ArrayIndexOutOfBoundsException(index);
            }
            int j = elementCount - index - 1;
            if (j > 0) {
                System.arraycopy(elementData, index + 1, elementData, index, j);
            }
            elementCount--;
            elementData[elementCount] = null; /* to let gc do its work */
        }

        /**
         * Inserts the specified object as a component in this vector at the
         * specified index. Each component in this vector with an
         * index greater or equal to the specified index is shifted
         * upward to have an index one greater than the value it had previously.
         *

         *
         * The index must be a value greater than or equal to 0 and
         * less than or equal to the current size of the vector. (If the index
         * is equal to the current size of the vector, the new element is
         * appended to the ModVector.)
         *

         *
         * This method is identical in functionality to the add(Object, int)
         * method (which is part of the List interface). Note that the add
         * method reverses the order of the parameters, to more closely match
         * array usage.
         *
         * @param obj
         *            the component to insert.
         * @param index
         *            where to insert the new component.
         * @exception ArrayIndexOutOfBoundsException
         *                if the index was invalid.
         * @see #size()
         * @see #add(int, Object)
         * @see List
         */
        public void insertElementAt(E obj, int index) {
            modCount++;
            if (index > elementCount) {
                throw new ArrayIndexOutOfBoundsException(index + " > "
                        + elementCount);
            }
            ensureCapacityHelper(elementCount + 1);
            System.arraycopy(elementData, index, elementData, index + 1,
                    elementCount - index);
            elementData[index] = obj;
            elementCount++;
        }

        /**
         * Adds the specified component to the end of this vector, increasing
         * its size by one. The capacity of this vector is increased if its size
         * becomes greater than its capacity.
         *

         *
         * This method is identical in functionality to the add(Object) method
         * (which is part of the List interface).
         *
         * @param obj
         *            the component to be added.
         * @see #add(Object)
         * @see List
         */
        public void addElement(E obj) {
            modCount++;
            ensureCapacityHelper(elementCount + 1);
            elementData[elementCount++] = obj;
        }

        /**
         * Removes the first (lowest-indexed) occurrence of the argument from
         * this vector. If the object is found in this vector, each component in
         * the vector with an index greater or equal to the object's index is
         * shifted downward to have an index one smaller than the value it had
         * previously.
         *

         *
         * This method is identical in functionality to the remove(Object)
         * method (which is part of the List interface).
         *
         * @param obj
         *            the component to be removed.
         * @return true if the argument was a component of this
         *         vector; false otherwise.
         * @see List#remove(Object)
         * @see List
         */
        public boolean removeElement(Object obj) {
            modCount++;
            int i = indexOf(obj);
            if (i >= 0) {
                removeElementAt(i);
                return true;
            }
            return false;
        }

        /**
         * Removes all components from this vector and sets its size to zero.
         *

         *
         * This method is identical in functionality to the clear method (which
         * is part of the List interface).
         *
         * @see #clear
         * @see List
         */
        public void removeAllElements() {
            modCount++;
            // Let gc do its work
            for (int i = 0; i < elementCount; i++)
                elementData[i] = null;

            elementCount = 0;
        }

        /**
         * Returns a clone of this vector. The copy will contain a reference to
         * a clone of the internal data array, not a reference to the original
         * internal data array of this <tt>ModVector</tt> object.
         *
         * @return a clone of this vector.
         */
        public Object clone() {
            try {
                ModVector<E> v = (ModVector<E>) super.clone();
                v.elementData = new Object[elementCount];
                System.arraycopy(elementData, 0, v.elementData, 0, elementCount);
                v.modCount = 0;
                return v;
            } catch (CloneNotSupportedException e) {
                // this shouldn't happen, since we are Cloneable
                throw new InternalError();
            }
        }

        /**
         * Returns an array containing all of the elements in this ModVector in
         * the correct order.
         *
         * @since 1.2
         */
        public Object[] toArray() {
            Object[] result = new Object[elementCount];
            System.arraycopy(elementData, 0, result, 0, elementCount);
            return result;
        }

        /**
         * Returns an array containing all of the elements in this ModVector in
         * the correct order; the runtime type of the returned array is that of
         * the specified array. If the ModVector fits in the specified array, it
         * is returned therein. Otherwise, a new array is allocated with the
         * runtime type of the specified array and the size of this ModVector.
         *

         *
         * If the ModVector fits in the specified array with room to spare
         * (i.e., the array has more elements than the ModVector), the element
         * in the array immediately following the end of the ModVector is set to
         * null. This is useful in determining the length of the ModVector
         * only if the caller knows that the ModVector does not contain
         * any null elements.
         *
         * @param a
         *            the array into which the elements of the ModVector are to
         *            be stored, if it is big enough; otherwise, a new array of
         *            the same runtime type is allocated for this purpose.
         * @return an array containing the elements of the ModVector.
         * @exception ArrayStoreException
         *                the runtime type of a is not a supertype of the
         *                runtime type of every element in this ModVector.
         * @throws NullPointerException
         *             if the given array is null.
         * @since 1.2
         */
        public <T> T[] toArray(T[] a) {
            if (a.length < elementCount)
                a = (T[]) java.lang.reflect.Array.newInstance(a.getClass()
                        .getComponentType(), elementCount);

            System.arraycopy(elementData, 0, a, 0, elementCount);

            if (a.length > elementCount)
                a[elementCount] = null;

            return a;
        }

        // Positional Access Operations

        /**
         * Returns the element at the specified position in this ModVector.
         *
         * @param index
         *            index of element to return.
         * @return object at the specified index
         * @exception ArrayIndexOutOfBoundsException
         *                index is out of range (index < 0 || index >=
         *                size()).
         * @since 1.2
         */
        public E get(int index) {
            if (index >= elementCount)
                throw new ArrayIndexOutOfBoundsException(index);

            return (E) elementData[index];
        }

        /**
         * Replaces the element at the specified position in this ModVector with
         * the specified element.
         *
         * @param index
         *            index of element to replace.
         * @param element
         *            element to be stored at the specified position.
         * @return the element previously at the specified position.
         * @exception ArrayIndexOutOfBoundsException
         *                index out of range (index < 0 || index >=
         *                size()).
         * @since 1.2
         */
        public E set(int index, E element) {
            if (index >= elementCount)
                throw new ArrayIndexOutOfBoundsException(index);

            Object oldValue = elementData[index];
            elementData[index] = element;
            return (E) oldValue;
        }

        /**
         * Appends the specified element to the end of this ModVector.
         *
         * @param o
         *            element to be appended to this ModVector.
         * @return true (as per the general contract of Collection.add).
         * @since 1.2
         */
        public boolean add(E o) {
            modCount++;
            ensureCapacityHelper(elementCount + 1);
            elementData[elementCount++] = o;
            return true;
        }

        /**
         * Removes the first occurrence of the specified element in this
         * ModVector If the ModVector does not contain the element, it is
         * unchanged. More formally, removes the element with the lowest index i
         * such that (o==null ? get(i)==null : o.equals(get(i)))
         * (if such an element exists).
         *
         * @param o
         *            element to be removed from this ModVector, if present.
         * @return true if the ModVector contained the specified element.
         * @since 1.2
         */
        public boolean remove(Object o) {
            return removeElement(o);
        }

        /**
         * Inserts the specified element at the specified position in this
         * ModVector. Shifts the element currently at that position (if any) and
         * any subsequent elements to the right (adds one to their indices).
         *
         * @param index
         *            index at which the specified element is to be inserted.
         * @param element
         *            element to be inserted.
         * @exception ArrayIndexOutOfBoundsException
         *                index is out of range (index < 0 || index >
         *                size()).
         * @since 1.2
         */
        public void add(int index, E element) {
            insertElementAt(element, index);
        }

        /**
         * Removes the element at the specified position in this ModVector.
         * shifts any subsequent elements to the left (subtracts one from their
         * indices). Returns the element that was removed from the ModVector.
         *
         * @exception ArrayIndexOutOfBoundsException
         *                index out of range (index < 0 || index >=
         *                size()).
         * @param index
         *            the index of the element to removed.
         * @return element that was removed
         * @since 1.2
         */
        public E remove(int index) {
            modCount++;
            if (index >= elementCount)
                throw new ArrayIndexOutOfBoundsException(index);
            Object oldValue = elementData[index];

            int numMoved = elementCount - index - 1;
            if (numMoved > 0)
                System.arraycopy(elementData, index + 1, elementData, index,
                        numMoved);
            elementData[--elementCount] = null; // Let gc do its work

            return (E) oldValue;
        }

        /**
         * Removes all of the elements from this ModVector. The ModVector will
         * be empty after this call returns (unless it throws an exception).
         *
         * @since 1.2
         */
        public void clear() {
            removeAllElements();
        }

        // Bulk Operations

        /**
         * Returns true if this ModVector contains all of the elements in the
         * specified Collection.
         *
         * @param c
         *            a collection whose elements will be tested for containment
         *            in this ModVector
         * @return true if this ModVector contains all of the elements in the
         *         specified collection.
         * @throws NullPointerException
         *             if the specified collection is null.
         */
        public boolean containsAll(Collection<?> c) {
            return super.containsAll(c);
        }

        /**
         * Appends all of the elements in the specified Collection to the end of
         * this ModVector, in the order that they are returned by the specified
         * Collection's Iterator. The behavior of this operation is undefined if
         * the specified Collection is modified while the operation is in
         * progress. (This implies that the behavior of this call is undefined
         * if the specified Collection is this ModVector, and this ModVector is
         * nonempty.)
         *
         * @param c
         *            elements to be inserted into this ModVector.
         * @return <tt>true</tt> if this ModVector changed as a result of the
         *         call.
         * @throws NullPointerException
         *             if the specified collection is null.
         * @since 1.2
         */
        public boolean addAll(Collection<? extends E> c) {
            modCount++;
            Object[] a = c.toArray();
            int numNew = a.length;
            ensureCapacityHelper(elementCount + numNew);
            System.arraycopy(a, 0, elementData, elementCount, numNew);
            elementCount += numNew;
            return numNew != 0;
        }

        /**
         * Removes from this ModVector all of its elements that are contained in
         * the specified Collection.
         *
         * @param c
         *            a collection of elements to be removed from the ModVector
         * @return true if this ModVector changed as a result of the call.
         * @throws NullPointerException
         *             if the specified collection is null.
         * @since 1.2
         */
        public boolean removeAll(Collection<?> c) {
            return super.removeAll(c);
        }

        /**
         * Retains only the elements in this ModVector that are contained in the
         * specified Collection. In other words, removes from this ModVector all
         * of its elements that are not contained in the specified Collection.
         *
         * @param c
         *            a collection of elements to be retained in this ModVector
         *            (all other elements are removed)
         * @return true if this ModVector changed as a result of the call.
         * @throws NullPointerException
         *             if the specified collection is null.
         * @since 1.2
         */
        public boolean retainAll(Collection<?> c) {
            return super.retainAll(c);
        }

        /**
         * Inserts all of the elements in in the specified Collection into this
         * ModVector at the specified position. Shifts the element currently at
         * that position (if any) and any subsequent elements to the right
         * (increases their indices). The new elements will appear in the
         * ModVector in the order that they are returned by the specified
         * Collection's iterator.
         *
         * @param index
         *            index at which to insert first element from the specified
         *            collection.
         * @param c
         *            elements to be inserted into this ModVector.
         * @return <tt>true</tt> if this ModVector changed as a result of the
         *         call.
         * @exception ArrayIndexOutOfBoundsException
         *                index out of range (index < 0 || index >
         *                size()).
         * @throws NullPointerException
         *             if the specified collection is null.
         * @since 1.2
         */
        public boolean addAll(int index, Collection<? extends E> c) {
            modCount++;
            if (index < 0 || index > elementCount)
                throw new ArrayIndexOutOfBoundsException(index);

            Object[] a = c.toArray();
            int numNew = a.length;
            ensureCapacityHelper(elementCount + numNew);

            int numMoved = elementCount - index;
            if (numMoved > 0)
                System.arraycopy(elementData, index, elementData, index
                        + numNew, numMoved);

            System.arraycopy(a, 0, elementData, index, numNew);
            elementCount += numNew;
            return numNew != 0;
        }

        /**
         * Compares the specified Object with this ModVector for equality.
         * Returns true if and only if the specified Object is also a List, both
         * Lists have the same size, and all corresponding pairs of elements in
         * the two Lists are equal. (Two elements e1 and
         * e2 are equal if (e1==null ? e2==null :
         * e1.equals(e2)).) In other words, two Lists are defined to be
         * equal if they contain the same elements in the same order.
         *
         * @param o
         *            the Object to be compared for equality with this
         *            ModVector.
         * @return true if the specified Object is equal to this ModVector
         */
        public boolean equals(Object o) {
            return super.equals(o);
        }

        /**
         * Returns the hash code value for this ModVector.
         */
        public int hashCode() {
            return super.hashCode();
        }

        /**
         * Returns a string representation of this ModVector, containing the
         * String representation of each element.
         */
        public String toString() {
            return super.toString();
        }

        /**
         * Returns a view of the portion of this List between fromIndex,
         * inclusive, and toIndex, exclusive. (If fromIndex and ToIndex are
         * equal, the returned List is empty.) The returned List is backed by
         * this List, so changes in the returned List are reflected in this
         * List, and vice-versa. The returned List supports all of the optional
         * List operations supported by this List.
         *

         *
         * This method eliminates the need for explicit range operations (of the
         * sort that commonly exist for arrays). Any operation that expects a
         * List can be used as a range operation by operating on a subList view
         * instead of a whole List. For example, the following idiom removes a
         * range of elements from a List:
         *
         *

         * list.subList(from, to).clear();
         *

         *
         * Similar idioms may be constructed for indexOf and lastIndexOf, and
         * all of the algorithms in the Collections class can be applied to a
         * subList.
         *

         *
         * The semantics of the List returned by this method become undefined if
         * the backing list (i.e., this List) is structurally modified in
         * any way other than via the returned List. (Structural modifications
         * are those that change the size of the List, or otherwise perturb it
         * in such a fashion that iterations in progress may yield incorrect
         * results.)
         *
         * @param fromIndex
         *            low endpoint (inclusive) of the subList.
         * @param toIndex
         *            high endpoint (exclusive) of the subList.
         * @return a view of the specified range within this List.
         * @throws IndexOutOfBoundsException
         *             endpoint index value out of range
         *             (fromIndex < 0 || toIndex > size)
         * @throws IllegalArgumentException
         *             endpoint indices out of order
         *             (fromIndex > toIndex)
         */
        public List<E> subList(int fromIndex, int toIndex) {
            // return Collections.synchronizedList(super.subList(fromIndex,
            // toIndex),
            // this);
            return null;
        }

        /**
         * Removes from this List all of the elements whose index is between
         * fromIndex, inclusive and toIndex, exclusive. Shifts any succeeding
         * elements to the left (reduces their index). This call shortens the
         * ArrayList by (toIndex - fromIndex) elements. (If toIndex==fromIndex,
         * this operation has no effect.)
         *
         * @param fromIndex
         *            index of first element to be removed.
         * @param toIndex
         *            index after last element to be removed.
         */
        protected void removeRange(int fromIndex, int toIndex) {
            modCount++;
            int numMoved = elementCount - toIndex;
            System.arraycopy(elementData, toIndex, elementData, fromIndex,
                    numMoved);

            // Let gc do its work
            int newElementCount = elementCount - (toIndex - fromIndex);
            while (elementCount != newElementCount)
                elementData[--elementCount] = null;
        }

        /**
         * Save the state of the <tt>ModVector</tt> instance to a stream (that
         * is, serialize it). This method is present merely for synchronization.
         * It just calls the default readObject method.
         */
        private void writeObject(java.io.ObjectOutputStream s)
                throws java.io.IOException {
            s.defaultWriteObject();
        }
    }
}


text:
```PowerShell
#Load Client Module
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")

#Param
$siteUrl = "https://<YourSPOName>.sharepoint.com/sites/<SiteCollection>/"
$username = "<Account mail address>"
$secpass = Read-Host -Prompt "Please enter your password" -AsSecureString
$listName = "<ListName>"

#Bind to Site
$context = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
$context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $secpass)

#Create a custom list
$listCreationInformation = New-Object Microsoft.SharePoint.Client.ListCreationInformation
$listCreationInformation.Title = $listName
$listCreationInformation.TemplateType = 101
$list = $context.Web.Lists.Add($listCreationInformation)
$context.Load($list)
$context.ExecuteQuery()

#Create fields

```

redpajama_set_name: RedPajamaGithub


text:
package com.springtranet.intranet.service;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.springtranet.intranet.model.Publicacion;

@Service
@Transactional
public interface PublicacionService {

	List<Publicacion> getAllPublicaciones();

	Publicacion getPublicacion(long id);

	long save(Publicacion publicacion);

	void update(Publicacion publicacion);

	void delete(long id);
}


text:
package de.iritgo.aktera.aktario.akteraconnector;

import de.iritgo.aktario.core.Engine;
import de.iritgo.aktario.framework.action.ActionTools;
import de.iritgo.aktario.framework.base.DataObject;
import de.iritgo.aktario.framework.client.command.ShowOtherFrame;
import de.iritgo.aktario.framework.client.command.ShowWindow;
import de.iritgo.aktario.framework.command.CommandTools;
import de.iritgo.aktario.framework.dataobject.gui.Controller;
import de.iritgo.aktario.framework.dataobject.gui.DataObjectCommand;
import de.iritgo.aktario.framework.dataobject.gui.GUIManager;
import de.iritgo.aktario.framework.dataobject.gui.QueryPane;
import java.awt.Rectangle;
import java.util.Properties;

/**
 *
 */
public class EditAkteraObjectCommand extends DataObjectCommand
{
	/**
	 * Create a new startup command.
	 */
	public EditAkteraObjectCommand()
	{
		super("EditAkteraObjectCommand");
		properties = new Properties();
	}

	/**
	 *
	 */
	public void perform()
	{
		DataObject dataObject = (DataObject) ((QueryPane) swingGUIPane).getSelectedItem();

		if (dataObject == null)
		{
			return;
		}

		String onScreenUniqueId = "jFrameId-" + Engine.instance().getTransientIDGenerator().createId();

		String queryPaneId = ((QueryPane) swingGUIPane).getOnScreenUniqueId();

		Properties props = new Properties();

		props.put("closable", Boolean.FALSE);
		props.put("iconifiable", Boolean.FALSE);
		props.put("maximizable", Boolean.FALSE);
		props.put("maximized", Boolean.TRUE);
		props.put("titlebar", Boolean.FALSE);
		props.put("queryPaneId", queryPaneId);

		String controllerId = ((QueryPane) swingGUIPane).getControllerTypeId();

		Rectangle bounds = new Rectangle(400, 300, 800, 600);

		CommandTools.performSimple(new ShowOtherFrame(null, "address.embeddedview", onScreenUniqueId, bounds));

		GUIManager guiManager = (GUIManager) Engine.instance().getManagerRegistry().getManager("GUIManager");

		Controller controller = guiManager.getController(controllerId);

		String editModel = controller.getCommandDescription("EditAkteraObjectCommand").getValue();

		CommandTools
						.performSimple(new ShowWindow("DataObjectGUIPane", onScreenUniqueId, onScreenUniqueId, null),
										props);

		EditAkteraObjectRequest editAkteraObjectRequest = new EditAkteraObjectRequest(editModel, dataObject,
						onScreenUniqueId, queryPaneId);

		ActionTools.sendToServer(editAkteraObjectRequest);
	}
}


text:
<?php

namespace UploadFileTest;

class SampleTest extends Framework\TestCase
{

    public function testSample()
    {
        $this->assertInstanceOf('Zend\Di\LocatorInterface', $this->getLocator());
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.navercorp.pinpoint</groupId>
        <artifactId>pinpoint</artifactId>
        <version>1.8.0-SNAPSHOT</version>
    </parent>

    <artifactId>pinpoint-profiler</artifactId>
    <name>pinpoint-profiler</name>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>com.navercorp.pinpoint</groupId>
            <artifactId>pinpoint-annotations</artifactId>
        </dependency>
        <dependency>
            <groupId>com.navercorp.pinpoint</groupId>
            <artifactId>pinpoint-commons</artifactId>
        </dependency>
        <dependency>
            <groupId>com.navercorp.pinpoint</groupId>
            <artifactId>pinpoint-thrift</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.thrift</groupId>
                    <artifactId>libthrift</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.navercorp.pinpoint</groupId>
            <artifactId>pinpoint-bootstrap-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.navercorp.pinpoint</groupId>
            <artifactId>pinpoint-bootstrap</artifactId>
        </dependency>
        <dependency>
            <groupId>com.navercorp.pinpoint</groupId>
            <artifactId>pinpoint-rpc</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.inject</groupId>
            <artifactId>guice</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.inject.extensions</groupId>
            <artifactId>guice-grapher</artifactId>
            <version>4.1.0</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.navercorp.pinpoint</groupId>
            <artifactId>pinpoint-rpc</artifactId>
            <version>${project.version}</version>
            <type>test-jar</type>
            <scope>test</scope>
        </dependency>

        <!-- [End] Compile Interceptors -->

        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
        </dependency>
        <dependency>
            <groupId>org.ow2.asm</groupId>
            <artifactId>asm</artifactId>
        </dependency>
        <dependency>
            <groupId>org.ow2.asm</groupId>
            <artifactId>asm-commons</artifactId>
        </dependency>
        <dependency>
            <groupId>org.ow2.asm</groupId>
            <artifactId>asm-util</artifactId>
        </dependency>
        <dependency>
            <groupId>org.ow2.asm</groupId>
            <artifactId>asm-tree</artifactId>
        </dependency>
        <dependency>
            <groupId>org.ow2.asm</groupId>
            <artifactId>asm-analysis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.thrift</groupId>
            <artifactId>libthrift</artifactId>
            <exclusions>
                <exclusion>
                    <artifactId>httpclient</artifactId>
                    <groupId>org.apache.httpcomponents</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>httpcore</artifactId>
                    <groupId>org.apache.httpcomponents</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>slf4j-api</artifactId>
                    <groupId>org.slf4j</groupId>
                </exclusion>
                <exclusion>
                    <groupId>org.apache.commons</groupId>
                    <artifactId>commons-lang3</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- Logging depedencies -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <!-- commons-logging-adapter -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
        </dependency>
        <!-- log4j-xml dependency -->
        <!-- required java9 java.xml -->
        <!--<dependency>
            <groupId>xerces</groupId>
            <artifactId>xercesImpl</artifactId>
            <version>2.11.0</version>
            <exclusions>
                <exclusion>
                    <groupId>xml-apis</groupId>
                    <artifactId>xml-apis</artifactId>
                </exclusion>
            </exclusions>
        </dependency>-->

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>**/pinpoint.config</exclude>
                        <exclude>**/log4j.xml</exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniRx;

public class SunPivot : MonoBehaviour {

	private RectTransform rectTransform;
//	private float sunZ = 10f;

	void Awake() {
		rectTransform = GetComponent<RectTransform> ();
	}

	// Use this for initialization
	void Start () {
		GameManager.Instance.TimeOfTheDay.Subscribe (timeOfTheDay => {
			var degree = timeOfTheDay * 360f;
			rectTransform.rotation = Quaternion.Euler (new Vector3 (0, 0, -degree));
		}).AddTo (this);
	}

	// Update is called once per frame
	void Update () {
//		sunZ = sunZ - Time.deltaTime;
//		rectTransform.rotation = Quaternion.Euler (new Vector3 (0, 0, sunZ));
	}
}


text:
package com.ratings.kkantor.service;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import java.util.List;

import com.ratings.kkantor.common.Game;

/**
 * @author Kody Kantor
 * com.ratings.kkantor.service.GameServiceImpl is a com.ratings.kkantor.service.DatabaseService
 * that provides methods for users
 * to add games to the DB, and set them as owned/not owned.
 *
 * TODO add delete functionality
 */
public class GameServiceImpl extends DatabaseService implements GameService {
    private static final Logger logger = LogManager.getLogger(GameServiceImpl.class);

    /**
     * findGame converts game titles to gameIds.
     * @param title name of the game
     * @return id associated with title
     */
    public int findGame(String title) {
        Session session = getSessionFactory().openSession();
        logger.debug("Opened hibernate session");
        Criteria criteria = session.createCriteria(Game.class);
        criteria.add(Restrictions.like("title", title));
        List results = criteria.list();
        session.close();
        if (results.size() > 1) {
            logger.debug("Multiple games found with same title!");
        }
        if (results.size() < 1) {
            logger.debug("No game found with that title");
            return 0;
        }
        //if there are multiple games with the same title
        // (there shouldn't be), we will just return the first
        // in the list that was returned.
        Game game = (Game) results.get(0);
        return game.getId();
    }

    /**
     * addGame inserts a game record into the DB and makes the game voteable.
     * @param title name of the game
     * @return whether or not the game was successfully added
     */
    public boolean addGame(String title) {
        if (findGame(title) > 0) {
            //the game is already in the DB
            logger.debug("Game is already in the database");
            return false;
        }
        Session session = getSessionFactory().openSession();
        Transaction tx = null;
        Integer gameId;
        try {
            tx = session.beginTransaction();
            Game game = new Game();
            game.setTitle(title);
            gameId = (Integer) session.save(game);
            tx.commit();
        } catch (HibernateException e) {
            logger.error("Error adding game to database");
            if (tx != null) {
                tx.rollback(); //undo the unfinished transaction
            }
            e.printStackTrace();
            return false;
        } finally {
            session.close();
        }
        logger.debug("Added game to database");
        VotingService votingService = new VotingServiceImpl();
        votingService.makeVoteable(gameId); //autoboxing
        return true;
    }

    /**
     * addGame calls addGame() and then setOwned() to mark a game as owned or not.
     * @param title name of the game
     * @param owned if the game is owned; true=yes false=no
     * @return whether or not the game was successfully added
     */
    public boolean addGame(String title, boolean owned) {
        if (!addGame(title)) {
            //the game already exists in the db
            logger.debug("Game is already in the database");
            return false;
        }
        // else: game was inserted, now we will set it as owned
        return setOwned(findGame(title), owned);
    }

    /**
     * setOwned updates the Games table to specify if a game is/isn't owned. It covers
     * both functions
     * @param gameId unique identifier of the game
     * @param owned true=owned, false=not owned
     * @return whether or not the ownership changed successfully
     */
    public boolean setOwned(int gameId, boolean owned) {
        Session session = getSessionFactory().openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            Game game = (Game) session.get(Game.class, gameId);
            game.setOwned(owned);
            tx.commit();
        } catch (HibernateException e) {
            logger.error("Error changing 'owned' value");
            if (tx != null) {
                tx.rollback(); //undo the unfinished transaction
            }
            e.printStackTrace();
            return false;
        } finally {
            session.close();
        }
        logger.debug("Changed owned value");
        return true;
    }

    /**
     * deleteGame deletes a game from the database
     *
     * @param title name of the game
     * @return whether or not game was deleted successfully
     */
    public boolean deleteGame(String title) {
        int gameId = findGame(title);
        Session session = getSessionFactory().openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            Game game = (Game) session.get(Game.class, gameId);
            session.delete(game);
            tx.commit();
        } catch (HibernateException e) {
            logger.error("Error deleting game");
            if (tx != null) {
                tx.rollback(); //undo the unfinished transaction
            }
            e.printStackTrace();
            return false;
        } finally {
            session.close();
        }
        logger.debug("Deleted game");
        VotingService votingService = new VotingServiceImpl();
        votingService.deleteVotes(gameId);
        return true;
    }
}


text:
@extends('layouts.master')
@section('content')

  @include('subadmin.partials.sidebar')

Kullanıcılar

            Kullanıcı Adı
            Moderatörlük
            İşlem

            @foreach($users as $user)

                {{ DB::Table('users')->where('id',$user->user_id)->first()->username }}
                @if($user->isAdmin == 1) Admin @elseif($user->isAdmin == 0) Kullanıcı @elseif($user->isAdmin == 2) Moderatör @endif
                @if($user->isAdmin == 1) Admin @elseif($user->isAdmin == 0) {{ HTML::linkRoute('subadmin.makemod','Moderatör Yap',[$subtitle->slug,$user->user_id]) }} @elseif($user->isAdmin == 2) {{ HTML::linkRoute('subadmin.makeuser','Kullanıcı Yap',[$subtitle->slug,$user->user_id]) }} @endif

            @endforeach

@stop


text:
'use strict';

angular.module('myApp.view1', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/view1', {
    templateUrl: 'view1/view1.html',
    controller: 'View1Ctrl'
  });
}])

.controller('View1Ctrl', ['$scope','UnicornFactory', function($scope ,UnicornFactory) {
    $scope.resetAdd = function(){

        $scope.unicorn.name = "";
        $scope.unicorn.gender = "F";
        $scope.unicorn.likes = [];
        $scope.unicorn.date;
        $scope.unicorn.vampires = 0;
        $scope.input = {};
        $scope.input.like = "";
    };
    $scope.unicorn = {};
    $scope.resetAdd();

    $scope.unicorns = [];

    $scope.input.update = false;
    $scope.action = "Add a new unicorn"

    $scope.message = "";

    $scope.loadList = function(){
        UnicornFactory.getAllUnicorns()
            .success(function(data){
                $scope.unicorns = data;
            })
            .error(function(err){
                $scope.message = "An error has occured";
            });
    };

    $scope.loadList();

  $scope.deleteUnicornClick = function(id){
      UnicornFactory.removeUnicorn(id)
          .success(function(data){
              console.log(data);
              $scope.loadList();
          })
          .error(function(err){
              $scope.message = "An error has occured";
          });
  };

    $scope.addLikes= function(){
        $scope.unicorn.likes.push($scope.input.like);
        $scope.input.like = "";
    };

    $scope.getUnicorn = function(id){
        UnicornFactory.getUnicorn(id).success(function(data){
            $scope.action = "Edit an unicorn";
            $scope.input.update = true;
            $scope.unicorn = data;
            $scope.unicorn.date = new Date($scope.unicorn.date);
            $scope.loadList();
        }).error(function(err){
            $scope.message = "An error has occured";
        });
    };

    /*
        Add or update a unicorn
     */
    $scope.ok = function(){
        if($scope.input.update){
            UnicornFactory.updateUnicorn($scope.unicorn).success(function(data){
                $scope.message = "A unicorn has been updated";
                $scope.loadList();
                $scope.input.update = false;
                $scope.action = "Add a new unicorn"
                $scope.resetAdd();
            }).error(function(err){
                $scope.message = "An error has occured";
                $scope.input.update = false;
            })
        }
        else{
            UnicornFactory.addUnicorn($scope.unicorn).success(function(data){
                $scope.message = "A unicorn has been added";
                $scope.loadList();
            }).error(function(err){
                $scope.message = "An error has occured";
            })
        }

    }

}]);


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Lich. univ. 361 (1810)

#### Original name
Lecanora cenisia Ach.

### Remarks
null


text:
package musicbrainz

import (
	"encoding/xml"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
)

func MakeQuery(url string) []byte {
	log.Printf("Getting URL %s", url)
	res, err := http.Get(url)
	if err != nil {
		log.Fatal(err)
	}
	bytes, err := ioutil.ReadAll(res.Body)

	res.Body.Close()
	if err != nil {
		log.Fatal(err)
	}

	return bytes
}

func SearchArtist(artist string) ArtistResult {
	result := ArtistResult{}

	bytes := MakeQuery("http://musicbrainz.org/ws/2/artist/?limit=10&query=artist:" + url.QueryEscape(artist))

	xml.Unmarshal(bytes, &result)

	return result
}

func GetReleases(artistId string) ReleaseResult {
	result := ReleaseResult{}
	bytes := MakeQuery("http://musicbrainz.org/ws/2/artist/" + artistId + "?inc=release-groups")

	err := xml.Unmarshal(bytes, &result)

	if err != nil {
		log.Printf("error: %v", err)
	}

	return result
}


text:
class Fichas::Invasividad < Ficha

	self.table_name = "#{CONFIG.bases.fichasespecies}.invasividad"
	self.primary_keys = :invaisvidadId,  :especieId

end


text:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ESRI.ArcGIS;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.DataSourcesRaster;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;

/*
    This sample opens a Mosaic Dataset and goes through each row in the attribute table.
    It checks whether the dataset in the row has any band information (band properties)
    associated with it.
    If the item has no band information, it inserts band properties for the first 3 bands
    in the item (if the item has 3 or more bands).
    Finally the mosaic dataset product definition is changed to Natural Color RGB so that
    ArcGIS can use the band names of the mosaic dataset.
    The sample also shows how to set a key property on the mosaic dataset.

    The sample has functions to get/set any key property for a dataset.
    The sample has functions to get/set any band property for a dataset.
    The sample has functions to get all the properties and all the band properties
    for a dataset.

    Key Properties:

    Key Properties of type 'double':
    CloudCover
    SunElevation
    SunAzimuth
    SensorElevation
    SensorAzimuth
    OffNadir
    VerticalAccuracy
    HorizontalAccuracy
    LowCellSize
    HighCellSize
    MinCellSize
    MaxCellSize

    Key Properties of type 'date':
    AcquisitionDate

    Key Properties of type 'string':
    SensorName
    ParentRasterType
    DataType
    ProductName
    DatasetTag
*/

namespace RasterSamples
{
    class GetSetKeyProperty
    {
        [STAThread]
        static void Main(string[] args)
        {
            #region Initialize
            ESRI.ArcGIS.esriSystem.AoInitialize aoInit = null;
            try
            {
                Console.WriteLine("Obtaining license");
                ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop);
                aoInit = new AoInitialize();
                esriLicenseStatus licStatus = aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeAdvanced);
                Console.WriteLine("Ready with license.");
            }
            catch (Exception exc)
            {
                // If it fails at this point, shutdown the test and ignore any subsequent errors.
                Console.WriteLine(exc.Message);
            }
            #endregion

            try
            {
                // Input database and Mosaic Dataset
                string MDWorkspaceFolder = @"e:\md\Samples\GetSetKP\RasterSamples.gdb";
                string MDName = @"LAC";

                // Command line setting of above input if provided.
                string[] commandLineArgs = Environment.GetCommandLineArgs();
                if (commandLineArgs.GetLength(0) > 1)
                {
                    MDWorkspaceFolder = commandLineArgs[1];
                    MDName = commandLineArgs[2];
                }

                // Open MD
                Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory");
                IWorkspaceFactory mdWorkspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType);
                IWorkspace mdWorkspace = mdWorkspaceFactory.OpenFromFile(MDWorkspaceFolder, 0);
                IRasterWorkspaceEx workspaceEx = (IRasterWorkspaceEx)(mdWorkspace);
                IMosaicDataset mosaicDataset = (IMosaicDataset)workspaceEx.OpenRasterDataset(MDName);

                // Set Mosaic Dataset item information.
                SetMosaicDatasetItemInformation(mosaicDataset);

                // Set Key Property 'DataType' on the Mosaic Dataset to value 'Processed'
                // The change will be reflected on the 'General' page of the mosaic dataset
                // properties under the 'Source Type' property.
                SetKeyProperty((IDataset)mosaicDataset, "DataType", "Processed");

                // Set the Product Definition on the Mosaic Dataset to 'NATURAL_COLOR_RGB'
                // First set the 'BandDefinitionKeyword' key property to natural color RGB.
                SetKeyProperty((IDataset)mosaicDataset, "BandDefinitionKeyword", "NATURAL_COLOR_RGB");
                // Then set band names and wavelengths on the mosaic dataset.
                SetBandProperties((IDataset)mosaicDataset);
                // Last and most important, refresh the mosaic dataset so the changes are saved.
                ((IRasterDataset3)mosaicDataset).Refresh();

                #region Shutdown
                Console.WriteLine("Success.");
                Console.WriteLine("Press any key...");
                Console.ReadKey();

                // Shutdown License
                aoInit.Shutdown();
                #endregion
            }
            catch (Exception exc)
            {
                #region Shutdown
                Console.WriteLine("Exception Caught while creating Function Raster Dataset. " + exc.Message);
                Console.WriteLine("Failed.");
                Console.WriteLine("Press any key...");
                Console.ReadKey();

                // Shutdown License
                aoInit.Shutdown();
                #endregion
            }
        }

        /// <summary>
        /// Sets band information on items in a mosaic dataset
        /// </summary>
        /// <param name="md">The mosaic dataset with the items</param>
        private static void SetMosaicDatasetItemInformation(IMosaicDataset md)
        {
            // Get the Attribute table from the Mosaic Dataset.
            IFeatureClass featureClass = md.Catalog;
            ISchemaLock schemaLock = (ISchemaLock)featureClass;
            IRasterDataset3 rasDs = null;
            try
            {
                // A try block is necessary, as an exclusive lock might not be available.
                schemaLock.ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock);

                // Get an update cursor going through all the rows in the Moasic Dataset.
                IFeatureCursor fcCursor = featureClass.Update(null, false);
                // Alternatively, a read cursor can be used if the item does not need to be changed.
                // featureClass.Search(null, false);

                // For each row,
                IRasterCatalogItem rasCatItem = (IRasterCatalogItem)fcCursor.NextFeature();
                while (rasCatItem != null)
                {
                    // get the functionrasterdataset from the Raster field.
                    IFunctionRasterDataset funcDs = (IFunctionRasterDataset)rasCatItem.RasterDataset;
                    if (funcDs != null)
                    {
                        // Check if the 'BandName' property exists in the dataset.
                        bool propertyExists = false;
                        for (int bandID = 0; bandID < funcDs.RasterInfo.BandCount; ++bandID)
                        {
                            object bandNameProperty = null;
                            bandNameProperty = GetBandProperty((IDataset)funcDs, "BandName", bandID);
                            if (bandNameProperty != null)
                                propertyExists = true;
                        }
                        if (propertyExists == false && funcDs.RasterInfo.BandCount > 2)
                        {
                            // If the property does not exist and the dataset has atleast 3 bands,
                            // set Band Definition Properties for first 3 bands of the dataset.
                            SetBandProperties((IDataset)funcDs);
                            funcDs.AlterDefinition();
                            rasDs = (IRasterDataset3)funcDs;
                            // Refresh the dataset.
                            rasDs.Refresh();
                        }
                    }
                    fcCursor.UpdateFeature((IFeature)rasCatItem);
                    rasDs = null;
                    rasCatItem = (IRasterCatalogItem)fcCursor.NextFeature();
                }
                rasCatItem = null;
                fcCursor = null;
                featureClass = null;
            }
            catch (Exception exc) { Console.WriteLine("Exception Caught in SetMosaicDatasetItemInformation: " + exc.Message); }
            finally
            {
                // Set the lock to shared, whether or not an error occurred.
                schemaLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock);
            }
        }

        /// <summary>
        /// Sets band properties on a given dataset
        /// </summary>
        /// <param name="ds">The target dataset</param>
        private static void SetBandProperties(IDataset dataset)
        {
            try
            {
                // Set properties for Band 1.
                SetBandProperty(dataset, "BandName", 0, "Red");
                SetBandProperty(dataset, "WavelengthMin", 0, 630);
                SetBandProperty(dataset, "WavelengthMax", 0, 690);

                // Set properties for Band 2.
                SetBandProperty(dataset, "BandName", 1, "Green");
                SetBandProperty(dataset, "WavelengthMin", 1, 530);
                SetBandProperty(dataset, "WavelengthMax", 1, 570);

                // Set properties for Band 3.
                SetBandProperty(dataset, "BandName", 2, "Blue");
                SetBandProperty(dataset, "WavelengthMin", 2, 440);
                SetBandProperty(dataset, "WavelengthMax", 2, 480);
            }
            catch (Exception) { }
        }

        /// <summary>
        /// Get all the properties associated with the dataset.
        /// </summary>
        /// <param name="dataset">Dataset to get the property from.</param>
        /// <param name="allKeys">String Array passed in by reference to fill with all keys.</param>
        /// <param name="allProperties">Object array passed in by reference to fill with all properties.</param>
        static void GetAllProperties(IDataset dataset, ref IStringArray allKeys, ref IVariantArray allProperties)
        {
            IRasterKeyProperties rasterKeyProps = (IRasterKeyProperties)dataset;
            rasterKeyProps.GetAllProperties(out allKeys, out allProperties);
        }

        /// <summary>
        /// Get all the properties associated with a particular band of the dataset.
        /// </summary>
        /// <param name="dataset">Dataset to get the property from.</param>
        /// <param name="bandIndex">band for which to get all properties.</param>
        /// <param name="bandKeys">String Array passed in by reference to fill with all keys.</param>
        /// <param name="bandProperties">Object array passed in by reference to fill with all properties.</param>
        static void GetAllBandProperties(IDataset dataset, int bandIndex, ref IStringArray bandKeys, ref IVariantArray bandProperties)
        {
            IRasterKeyProperties rasterKeyProps = (IRasterKeyProperties)dataset;
            rasterKeyProps.GetAllBandProperties(bandIndex, out bandKeys, out bandProperties);
        }

        /// <summary>
        /// Get the Key Property corresponding to the key 'key' from the dataset.
        /// </summary>
        /// <param name="dataset">Dataset to get the property from.</param>
        /// <param name="key">The key for which to get the value.</param>
        /// <returns>Property corresponding to the key or null if it doesnt exist.</returns>
        static object GetKeyProperty(IDataset dataset, string key)
        {
            IRasterKeyProperties rasterKeyProps = (IRasterKeyProperties)dataset;
            object value = null;
            try { value = rasterKeyProps.GetProperty(key); }
            catch (Exception) { }
            return value;
        }

        /// <summary>
        /// Set the Key Property 'value' corresponding to the key 'key' on the dataset.
        /// </summary>
        /// <param name="dataset">Dataset to set the property on.</param>
        /// <param name="key">The key on which to set the property.</param>
        /// <param name="value">The value to set.</param>
        static void SetKeyProperty(IDataset dataset, string key, object value)
        {
            IRasterKeyProperties rasterKeyProps = (IRasterKeyProperties)dataset;
            rasterKeyProps.SetProperty(key, value);
        }

        /// <summary>
        /// Get the KeyProperty corresponding to the bandIndex and 'key' from the dataset.
        /// </summary>
        /// <param name="dataset">Dataset to get the property from.</param>
        /// <param name="key">The key for which to get the value.</param>
        /// <param name="bandIndex">Band for which to get the property.</param>
        /// <returns>Property corresponding to the key or null if none found.</returns>
        static object GetBandProperty(IDataset dataset, string key, int bandIndex)
        {
            IRasterKeyProperties rasterKeyProps = (IRasterKeyProperties)dataset;
            object value = null;
            try { value = rasterKeyProps.GetBandProperty(key, bandIndex); }
            catch (Exception) { }

            return value;
        }

        /// <summary>
        /// Set the KeyProperty corresponding to the bandIndex and 'key' from the dataset.
        /// </summary>
        /// <param name="dataset">Dataset to set the property on.</param>
        /// <param name="key">The key on which to set the property.</param>
        /// <param name="bandIndex">Band from which to get the property.</param>
        /// <param name="value">The value to set.</param>
        static void SetBandProperty(IDataset dataset, string key, int bandIndex, object value)
        {
            IRasterKeyProperties rasterKeyProps = (IRasterKeyProperties)dataset;
            rasterKeyProps.SetBandProperty(key, bandIndex, value);
        }
    }
}


text:
D3DUtil::D3DUtil(void){
}

D3DUtil::D3DUtil(IDirect3DDevice9 *d3ddev, const NxDebugRenderable **dbgRenderable){
    d3d_ = d3ddev;
	dbgRenderable_ = dbgRenderable;
	D3DXMatrixIdentity(&matIdentity_);
}

D3DUtil::~D3DUtil(void){
}

void D3DUtil::debugRender(){
	//Test current scene != 0 using *dbdRenderable_

	//disable lighting?
	if(*dbgRenderable_){
		d3d_->SetTransform(D3DTS_WORLD, &matIdentity_);
		d3d_->SetRenderState(D3DRS_LIGHTING, FALSE);
		d3d_->SetFVF(D3DFVF_XYZ | D3DFVF_DIFFUSE);
		this->drawLines();
		this->drawPoints();
		this->drawTriangles();
	}
}

void D3DUtil::drawTriangles(){
	unsigned int triCount = (*dbgRenderable_)->getNbTriangles();
	//NOT TESTED
	const NxDebugTriangle* tri = (*dbgRenderable_)->getTriangles();
	while(triCount--){
		d3d_->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 1, &tri->p0.x, 12);
		tri++;
	}
}

void D3DUtil::drawPoints(){
	unsigned int pointCount = (*dbgRenderable_)->getNbPoints();
	//NOT TESTED
	const NxDebugPoint* point = (*dbgRenderable_)->getPoints();
	while(pointCount--){
		d3d_->DrawPrimitiveUP(D3DPT_POINTLIST, 1, &point->p.x, 8);
		point++;
	}
}

void D3DUtil::drawLines(){
	unsigned int lineCount = (*dbgRenderable_)->getNbLines();
	const NxDebugLine* line = (*dbgRenderable_)->getLines();
	while(lineCount--){
		d3d_->DrawPrimitiveUP(D3DPT_LINELIST, 1, &line->p0.x, 12);
		line++;
	}
}


text:
from django.conf import settings
from django.dispatch import receiver

try:
    from django.contrib.contenttypes.fields import GenericForeignKey
except ImportError:
    from django.contrib.contenttypes.generic import GenericForeignKey

from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from django.core import urlresolvers
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ValidationError
from django.utils.encoding import python_2_unicode_compatible

from social_graph import Graph

from managers import CommentManager, CommentCurrentSiteManager
from mixins import author_edge, target_edge
from signals import item_commented, item_comment_removed

graph = Graph()

class BaseCommentAbstractModel(models.Model):
    """
    An abstract base class that any custom comment models probably should
    subclass.
    """

    # Content-object field
    content_type = models.ForeignKey(ContentType,
                                     verbose_name=_(u'content type'),
                                     related_name="content_type_set_for_%(class)s")
    object_pk = models.TextField(_(u'object ID'))
    content_object = GenericForeignKey(ct_field="content_type", fk_field="object_pk")

    # Metadata about the comment
    site = models.ForeignKey(Site)

    class Meta:
        abstract = True

def validate_level(value):
    if value > settings.COMMENT_MAX_LEVELS:
        raise ValidationError(_('Max comment level exceeded.'))

@python_2_unicode_compatible
class Comment(BaseCommentAbstractModel):
    """
    A user comment about some object.
    """

    # Who posted this comment? If ``user`` is set then it was an authenticated
    # user; otherwise at least user_name should have been set and the comment
    # was posted by a non-authenticated user.
    user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_(u'user'),
                             blank=True, null=True, related_name="%(class)s_comments")
    user_name = models.CharField(_(u"name"), max_length=50, blank=True)
    # Explicit `max_length` to apply both to Django 1.7 and 1.8+.
    user_email = models.EmailField(_(u"email"), max_length=254,
                                   blank=True)
    user_url = models.URLField(_(u"user's URL"), blank=True)

    comment = models.TextField(_(u'comment'), max_length=settings.COMMENT_MAX_LENGTH)

    answer_to = models.ForeignKey(
        'self', verbose_name=_(u'answer to'), related_name='answers', blank=True, null=True
    )

    level = models.IntegerField(_(u'comment level'), blank=True, null=True, validators=[validate_level])

    # Metadata about the comment
    submit_date = models.DateTimeField(_(u'date/time submitted'), auto_now_add=True)
    ip_address = models.GenericIPAddressField(_(u'IP address'), unpack_ipv4=True, blank=True, null=True)
    is_public = models.BooleanField(_(u'is public'), default=True,
                                    help_text=_(u'Uncheck this box to make the comment effectively '
                                                u'disappear from the site.'))
    is_removed = models.BooleanField(_(u'is removed'), default=False,
                                     help_text=_(u'Check this box if the comment is inappropriate. '
                                                 u'A "This comment has been removed" message will '
                                                 u'be displayed instead.'))

    # Manager
    objects = CommentManager()
    on_site = CommentCurrentSiteManager()
    historical = models.Manager()

    class Meta:
        ordering = ('submit_date',)
        permissions = [("can_moderate", "Can moderate comments")]
        verbose_name = _(u'comment')
        verbose_name_plural = _(u'comments')

    def __str__(self):
        return "%s: %s..." % (self.name, self.comment[:50])

    @property
    def user_info(self):
        """
        Get a dictionary that pulls together information about the poster
        safely for both authenticated and non-authenticated comments.

        This dict will have ``name``, ``email``, and ``url`` fields.
        """
        if not hasattr(self, "_user_info"):
            user_info = {
                "name": self.user_name,
                "email": self.user_email,
                "url": self.user_url
            }
            if self.user_id:
                u = self.user
                if u.email:
                    user_info["email"] = u.email

                # If the user has a full name, use that for the user name.
                # However, a given user_name overrides the raw user.username,
                # so only use that if this comment has no associated name.
                if u.get_full_name():
                    user_info["name"] = self.user.get_full_name()
                elif not self.user_name:
                    user_info["name"] = u.get_username()
            self._user_info = user_info
        return self._user_info

    def _get_name(self):
        return self.user_info["name"]

    def _set_name(self, val):
        if self.user_id:
            raise AttributeError(_(u"This comment was posted by an authenticated "
                                   u"user and thus the name is read-only."))
        self.user_name = val

    name = property(_get_name, _set_name, doc="The name of the user who posted this comment")

    def _get_email(self):
        return self.user_info["email"]

    def _set_email(self, val):
        if self.user_id:
            raise AttributeError(_(u"This comment was posted by an authenticated "
                                   u"user and thus the email is read-only."))
        self.user_email = val

    email = property(_get_email, _set_email, doc="The email of the user who posted this comment")

    def _get_url(self):
        return self.userinfo["url"]

    def _set_url(self, val):
        self.user_url = val

    url = property(_get_url, _set_url, doc="The URL given by the user who posted this comment")

    def get_as_text(self):
        """
        Return this comment as plain text.  Useful for emails.
        """
        data = {
            'user': self.user or self.name,
            'date': self.submit_date,
            'comment': self.comment,
            'domain': self.site.domain,
            'url': self.get_absolute_url()
        }
        return _(u'Posted by %(user)s at %(date)s\n\n%(comment)s\n\nhttp://%(domain)s%(url)s') % data

    def delete(self, using=None):
        for answer in self.answers.all():
            answer.delete()
        self.is_removed = True
        self.save()

@receiver(models.signals.pre_save, sender=Comment, dispatch_uid="fill_comment_user_data")
def fill_comment_user_data(instance, **kwargs):
    if not instance.user_name or not instance.user_email:
        instance.user_name = instance.user.get_full_name() or instance.user.username
        instance.user_email = instance.user.email
    if not instance.level:
        instance.level = instance.answer_to.level + 1 if instance.answer_to else 1

@receiver(models.signals.post_save, sender=Comment, dispatch_uid="manage_comment_edges")
def create_comment_edges(instance, created, **kwargs):
    if created:
        if instance.user:
            graph.edge(instance.user, instance, author_edge(), instance.site, {})
        graph.edge(instance, instance.content_object, target_edge(), instance.site, {})

        item_commented.send(sender=Comment, instance=instance, user=instance.user, answer_to=instance.answer_to)
    elif instance.is_removed:
        if instance.user:
            graph.no_edge(instance.user, instance, author_edge(), instance.site)
        graph.no_edge(instance, instance.content_object, target_edge(), instance.site)

        item_comment_removed.send(
            sender=Comment, instance=instance, user=instance.content_object.get_comments_manager() or instance.user
        )


text:
{% extends "base.html" %}
{% load navigation_tags %}
{% load authorization_tags %}
{% block content %}
    {{ block.super }}

                    WARNING: The Rules Framework is an unsupported beta feature, only for power users. It is possible to ruin your data if you're not careful.

                        Rules Framework

                            <button id="show-filters" data-toggle="collapse" data-target="#the-filters" class="btn btn-primary toggle-filters">   </button>
                            {% if "dojo.add_rule"|has_configuration_permission:"superuser" %}
                            <button class="btn btn-primary dropdown-toggle" type="button" id="dropdownMenu1"
                                    data-toggle="dropdown" aria-expanded="true">

                            </button>

                                             Add Rule

                            {% endif %}

                    {% include "dojo/filter_snippet.html" with form=rules.form %}

            {% if rules %}

                    {% include "dojo/paging_snippet.html" with page=rules page_size=True %}

                            {% dojo_sort request 'Rule' 'text' 'asc' %}
                             Operation
                             Match
                             Applies

                        {% for rule in rules %}

                                 {{ rule.text }}
                                {{ rule.operator }}
                                 {{ rule.model_object }}:{{rule.match_field}}
                                 {{ rule.applies_to }}:{{rule.applied_field}}

                                            {% if "dojo.change_rule"|has_configuration_permission:"superuser" %}

                                                 Edit

                                            {% endif %}
                                            {% if "dojo.delete_rule"|has_configuration_permission:"superuser" %}

                                                 Delete

                                            {% endif %}

                        {% endfor %}

                    {% include "dojo/paging_snippet.html" with page=rules page_size=True %}

            {% else %}

No rules found.

            {% endif %}

    {% include "dojo/filter_js_snippet.html" %}
{% endblock %}