text:
package org.apache.ignite.internal.processors.datastructures;

import java.io.Externalizable;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.ObjectStreamException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteCondition;
import org.apache.ignite.IgniteException;
import org.apache.ignite.IgniteInterruptedException;
import org.apache.ignite.IgniteLock;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.internal.GridKernalContext;
import org.apache.ignite.internal.IgnitionEx;
import org.apache.ignite.internal.processors.cache.GridCacheContext;
import org.apache.ignite.internal.processors.cache.IgniteInternalCache;
import org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal;
import org.apache.ignite.internal.util.typedef.X;
import org.apache.ignite.internal.util.typedef.internal.CU;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.internal.processors.cluster.IgniteChangeGlobalStateSupport;
import org.apache.ignite.transactions.TransactionRollbackException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import static org.apache.ignite.internal.processors.cache.GridCacheUtils.retryTopologySafe;
import static org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC;
import static org.apache.ignite.transactions.TransactionIsolation.REPEATABLE_READ;

/**
 * Cache reentrant lock implementation based on AbstractQueuedSynchronizer.
 */
public final class GridCacheLockImpl implements GridCacheLockEx, IgniteChangeGlobalStateSupport, Externalizable {
    /** */
    private static final long serialVersionUID = 0L;

    /** Deserialization stash. */
    private static final ThreadLocal<String> stash = new ThreadLocal<>();

    /** Logger. */
    private IgniteLogger log;

    /** Reentrant lock name. */
    private String name;

    /** Removed flag. */
    private volatile boolean rmvd;

    /** Reentrant lock key. */
    private GridCacheInternalKey key;

    /** Reentrant lock projection. */
    private IgniteInternalCache<GridCacheInternalKey, GridCacheLockState> lockView;

    /** Cache context. */
    private GridCacheContext ctx;

    /** Initialization guard. */
    private final AtomicBoolean initGuard = new AtomicBoolean();

    /** Initialization latch. */
    private final CountDownLatch initLatch = new CountDownLatch(1);

    /** Lock that provides non-overlapping processing of updates. */
    private Lock updateLock = new ReentrantLock();

    /** Internal synchronization object. */
    private Sync sync;

    /** Flag indicating that every operation on this lock should be interrupted. */
    private volatile boolean interruptAll;

    /**
     * Empty constructor required by {@link Externalizable}.
     */
    public GridCacheLockImpl() {
        // This instance should never be used directly.
        ctx = null;
    }

    /**
     * Synchronization implementation for reentrant lock using AbstractQueuedSynchronizer.
     */
    @SuppressWarnings({"CallToThreadYield", "CallToSignalInsteadOfSignalAll"})
    private class Sync extends AbstractQueuedSynchronizer {
        /** */
        private static final long serialVersionUID = 1192457210091910933L;

        /** */
        private static final long LOCK_FREE = 0;

        /** Map containing condition objects. */
        private Map<String, ConditionObject> conditionMap;

        /** List of condition signal calls on this node. */
        private Map<String, Integer> outgoingSignals;

        /** Last condition waited on. */
        @Nullable
        private volatile String lastCondition;

        /** True if any node owning the lock had failed. */
        private volatile boolean isBroken;

        /** UUID of the node that currently owns the lock. */
        private volatile UUID currentOwnerNode;

        /** ID of the thread that currently owns the lock. */
        private volatile long currentOwnerThreadId;

        /** UUID of this node. */
        private final UUID thisNode;

        /** FailoverSafe flag. */
        private final boolean failoverSafe;

        /** Fairness flag. */
        private final boolean fair;

        /** Threads that are waiting on this lock. */
        private Set<Long> waitingThreads;

        /**
         * @param state State.
         */
        protected Sync(GridCacheLockState state) {
            setState(state.get());

            thisNode = ctx.localNodeId();

            currentOwnerNode = state.getId();

            currentOwnerThreadId = state.getThreadId();

            conditionMap = new HashMap<>();

            outgoingSignals = new HashMap<>();

            failoverSafe = state.isFailoverSafe();

            fair = state.isFair();

            waitingThreads = new ConcurrentSkipListSet<>();
        }

        /**
         *
         */
        protected void addOutgoingSignal(String condition) {
            int cnt = 0;

            if (outgoingSignals.containsKey(condition)) {
                cnt = outgoingSignals.get(condition);

                // SignalAll has already been called.
                if (cnt == 0)
                    return;
            }

            outgoingSignals.put(condition, cnt + 1);
        }

        /**
         * @param condition Condition.
         */
        protected void addOutgoingSignalAll(String condition) {
            outgoingSignals.put(condition, 0);
        }

        /**
         * Process any condition await calls on this node.
         */
        private String processAwait() {
            if (lastCondition == null)
                return null;

            String ret = lastCondition;

            lastCondition = null;

            return ret;
        }

        /** */
        private Map<String, Integer> processSignal() {
            Map<String,Integer> ret = new HashMap<>(outgoingSignals);

            outgoingSignals.clear();

            return ret;
        }

        /** Interrupt every thread on this node waiting on this lock. */
        private synchronized void interruptAll() {
            // First release all threads waiting on associated condition queues.
            if (!conditionMap.isEmpty()) {
                // Temporarily obtain ownership of the lock,
                // in order to signal all conditions.
                UUID tempUUID = getOwnerNode();

                long tempThreadID = currentOwnerThreadId;

                setCurrentOwnerNode(thisNode);

                currentOwnerThreadId = Thread.currentThread().getId();

                for (Condition c : conditionMap.values())
                    c.signalAll();

                // Restore owner node and owner thread.
                setCurrentOwnerNode(tempUUID);

                currentOwnerThreadId = tempThreadID;
            }

            // Interrupt any future call to acquire/release on this sync object.
            interruptAll = true;

            // Interrupt any ongoing transactions.
            for (Thread t: getQueuedThreads())
                t.interrupt();
        }

        /** Check if lock is in correct state (i.e. not broken in non-failoversafe mode),
         * if not throw  {@linkplain IgniteInterruptedException} */
        private void validate(final boolean throwInterrupt) {
            // Interrupted flag shouldn't be always cleared
            // (e.g. lock() method doesn't throw exception and doesn't clear interrupted)
            // but should be cleared if this method is called after lock breakage or node stop.
            // If interruptAll is set, exception is thrown anyway.
            boolean interrupted = Thread.currentThread().isInterrupted();

            // Clear interrupt flag.
            if (throwInterrupt || interruptAll)
                Thread.interrupted();

            if (interruptAll)
                throw new IgniteException("Lock broken (possible reason: node stopped" +
                    " or node owning lock failed while in non-failoversafe mode).");

            // Global queue should be synchronized only if interrupted exception should be thrown.
            if (fair && (throwInterrupt && interrupted) && !interruptAll) {
                synchronizeQueue(true, Thread.currentThread());

                throw new IgniteInterruptedException("Lock is interrupted.");
            }
        }

        /**
         * Sets the number of permits currently acquired on this lock. This method should only be used in {@linkplain
         * GridCacheLockImpl#onUpdate(GridCacheLockState)}.
         *
         * @param permits Number of permits acquired at this reentrant lock.
         */
        final synchronized void setPermits(int permits) {
            setState(permits);
        }

        /**
         * Gets the number of permissions currently acquired at this lock.
         *
         * @return Number of permits acquired at this reentrant lock.
         */
        final int getPermits() {
            return getState();
        }

        /**
         * Sets the UUID of the node that currently owns this lock. This method should only be used in {@linkplain
         * GridCacheLockImpl#onUpdate(GridCacheLockState)}.
         *
         * @param ownerNode UUID of the node owning this lock.
         */
        final synchronized void setCurrentOwnerNode(UUID ownerNode) {
            currentOwnerNode = ownerNode;
        }

        /**
         * Gets the UUID of the node that currently owns the lock.
         *
         * @return UUID of the node that currently owns the lock.
         */
        final UUID getOwnerNode() {
            return currentOwnerNode;
        }

        /**
         * Checks if latest call to acquire/release was called on this node.
         * Should only be called from update method.
         *
         * @param newOwnerID ID of the node that is about to acquire this lock (or null).
         * @return true if acquire/release that triggered last update came from this node.
         */
        protected boolean isLockedLocally(UUID newOwnerID) {
            return thisNode.equals(getOwnerNode()) || thisNode.equals(newOwnerID);
        }

        /**
         * @param newOwnerThreadId New owner thread id.
         */
        protected void setCurrentOwnerThread(long newOwnerThreadId) {
            currentOwnerThreadId = newOwnerThreadId;
        }

        /**
         * Returns true if node that owned the locked failed before call to unlock.
         *
         * @return true if any node failed while owning the lock.
         */
        protected boolean isBroken() {
            return isBroken;
        }

        /** */
        protected void setBroken(boolean isBroken) {
            this.isBroken = isBroken;
        }

        /** */
        protected synchronized boolean hasPredecessor(LinkedList<UUID> nodes) {
            if (!fair)
                return false;

            for (Iterator<UUID> it = nodes.iterator(); it.hasNext(); ) {
                UUID node = it.next();

                if (ctx.discovery().node(node) == null) {
                    it.remove();

                    continue;
                }

                return !node.equals(thisNode);
            }

            return false;
        }

        /**
         * Performs tryLock.
         * @param acquires Number of permits to acquire.
         * @param fair Fairness parameter.
         * @return {@code True} if succeeded, false otherwise.
         */
        final boolean tryAcquire(final int acquires, final boolean fair) {
            // If broken in non-failoversafe mode, exit immediately.
            if (interruptAll)
                return true;

            final Thread current = Thread.currentThread();

            boolean failed = false;

            int c = getState();

            // Wait for lock to reach stable state.
            while (c != 0) {
                UUID currentOwner = currentOwnerNode;

                if (currentOwner != null) {
                    failed = ctx.discovery().node(currentOwner) == null;

                    break;
                }

                c = getState();
            }

            // Check if lock is released or current owner failed.
            if (c == 0 || failed) {
                if (compareAndSetGlobalState(0, acquires, current, fair)) {

                    // Not used for synchronization (we use ThreadID), but updated anyway.
                    setExclusiveOwnerThread(current);

                    while (!isHeldExclusively() && !interruptAll)
                        Thread.yield();

                    return true;
                }
            }
            else if (isHeldExclusively()) {
                int nextc = c + acquires;

                if (nextc < 0) // overflow
                    throw new Error("Maximum lock count exceeded.");

                setState(nextc);

                return true;
            }

            if (fair && !isQueued(current))
                synchronizeQueue(false, current);

            return false;
        }

        /**
         * Performs lock.
         */
        final void lock() {
            acquire(1);
        }

        /** {@inheritDoc} */
        @Override protected final boolean tryAcquire(int acquires) {
            return tryAcquire(acquires, fair);
        }

        /** {@inheritDoc} */
        @Override protected final boolean tryRelease(int releases) {
            // This method is called with release==0 only when trying to wake through update,
            // to check if some other node released the lock.
            if (releases == 0)
                return true;

            // If broken in non-failoversafe mode, exit immediately.
            if (interruptAll)
                return true;

            int c = getState() - releases;

            if (!isHeldExclusively()) {
                log.error("Lock.unlock() is called in illegal state [callerNodeId=" + thisNode + ", ownerNodeId="
                    + currentOwnerNode + ", callerThreadId=" + Thread.currentThread().getId() + ", ownerThreadId="
                    + currentOwnerThreadId + ", lockState=" + getState() + "]");

                throw new IllegalMonitorStateException();
            }

            boolean free = false;

            if (c == 0) {
                free = true;

                setGlobalState(0, processAwait(), processSignal());

                while (isHeldExclusively() && !interruptAll)
                    Thread.yield();
            }
            else
                setState(c);

            return free;
        }

        /** {@inheritDoc} */
        @Override protected final boolean isHeldExclusively() {
            // While we must in general read state before owner,
            // we don't need to do so to check if current thread is owner

            return currentOwnerThreadId == Thread.currentThread().getId() && thisNode.equals(currentOwnerNode);
        }

        /**
         * @param name Condition name.
         * @return Condition object.
         */
        final synchronized IgniteCondition newCondition(String name) {
            if (conditionMap.containsKey(name))
                return new IgniteConditionObject(name, conditionMap.get(name));

            ConditionObject cond = new ConditionObject();

            conditionMap.put(name, cond);

            return new IgniteConditionObject(name, cond);
        }

        // Methods relayed from outer class

        final int getHoldCount() {
            return isHeldExclusively() ? getState() : 0;
        }

        final boolean isLocked() throws IgniteCheckedException {
            return getState() != 0 || lockView.get(key).get() != 0;
        }

        /**
         * This method is used for synchronizing the reentrant lock state across all nodes.
         */
        boolean compareAndSetGlobalState(final int expVal, final int newVal,
            final Thread newThread, final boolean bargingProhibited) {
            try {
                return retryTopologySafe(new Callable<Boolean>() {
                        @Override public Boolean call() throws Exception {
                            try (GridNearTxLocal tx = CU.txStartInternal(ctx, lockView, PESSIMISTIC, REPEATABLE_READ)) {
                                GridCacheLockState val = lockView.get(key);

                                if (val == null)
                                    throw new IgniteCheckedException("Failed to find reentrant lock with given name: " + name);

                                final long newThreadID = newThread.getId();

                                LinkedList<UUID> nodes = val.getNodes();

                                // Barging is prohibited in fair mode unless tryLock() is called.
                                if (!(bargingProhibited && hasPredecessor(nodes))) {
                                    if (val.get() == expVal || ctx.discovery().node(val.getId()) == null) {
                                        val.set(newVal);

                                        val.setId(thisNode);

                                        val.setThreadId(newThreadID);

                                        val.setSignals(null);

                                        // This node is already in queue, except in cases where this is the only node
                                        // or this is a call to tryLock(), in which case barging is ok.
                                        // Queue is only updated if this is fair lock.
                                        if (val.isFair() && (nodes.isEmpty() || !bargingProhibited))
                                            nodes.addFirst(thisNode);

                                        val.setNodes(nodes);

                                        val.setChanged(true);

                                        lockView.put(key, val);

                                        tx.commit();

                                        return true;
                                    }
                                }

                                return false;
                            }
                            catch (Exception e) {
                                if (interruptAll) {
                                    log.info("Node is stopped (or lock is broken in non-failover safe mode)," +
                                        " aborting transaction.");

                                    // Return immediately, exception will be thrown later.
                                    return true;
                                }
                                else {
                                    if (Thread.currentThread().isInterrupted()) {
                                        log.info("Thread is interrupted while attempting to acquire lock.");

                                        // Delegate the decision to throw InterruptedException to the AQS.
                                        sync.release(0);

                                        return false;
                                    }

                                    U.error(log, "Failed to compare and set: " + this, e);
                                }

                                throw e;
                            }
                        }
                    });
            }
            catch (IgniteCheckedException e) {
                throw U.convertException(e);
            }
        }

        /**
         * This method is used for synchronizing the number of acquire attempts on this lock across all nodes.
         *
         * @param cancelled true if acquire attempt is cancelled, false if acquire attempt should be registered.
         */
        boolean synchronizeQueue(final boolean cancelled, final Thread thread) {
            final AtomicBoolean interrupted = new AtomicBoolean(false);

            try {
                return retryTopologySafe(new Callable<Boolean>() {
                        @Override public Boolean call() throws Exception {
                            try (GridNearTxLocal tx = CU.txStartInternal(ctx, lockView, PESSIMISTIC, REPEATABLE_READ)) {
                                GridCacheLockState val = lockView.get(key);

                                if (val == null)
                                    throw new IgniteCheckedException("Failed to find reentrant lock with given name: " + name);

                                LinkedList<UUID> nodes = val.getNodes();

                                if (!cancelled) {
                                    nodes.add(thisNode);

                                    val.setChanged(false);

                                    lockView.put(key, val);

                                    tx.commit();

                                    // Keep track of all threads that are queued in global queue.
                                    // We deliberately don't use #sync.isQueued(), because AQS
                                    // cancel threads immediately after throwing interrupted exception.
                                    sync.waitingThreads.add(thread.getId());

                                    return true;
                                }
                                else {
                                    if (sync.waitingThreads.contains(thread.getId())) {
                                        // Update other nodes if this is the first node in queue.
                                        val.setChanged(nodes.lastIndexOf(thisNode) == 0);

                                        nodes.removeLastOccurrence(thisNode);

                                        lockView.put(key, val);

                                        tx.commit();

                                        sync.waitingThreads.remove(thread.getId());

                                        return true;
                                    }
                                }

                                return false;
                            }
                            catch (Exception e) {
                                if (interruptAll) {
                                    log.info("Node is stopped (or lock is broken in non-failover safe mode)," +
                                        " aborting transaction.");

                                    // Abort this attempt to synchronize queue and start another one,
                                    // that will return immediately.
                                    sync.release(0);

                                    return false;
                                }
                                else {
                                    // If thread got interrupted, abort this attempt to synchronize queue,
                                    // clear interrupt flag and try again, and let the AQS decide
                                    // whether to throw an exception or ignore it.
                                    if (Thread.interrupted() || X.hasCause(e, InterruptedException.class)) {
                                        interrupted.set(true);

                                        throw new TransactionRollbackException("Thread got interrupted " +
                                            "while synchronizing the global queue, retrying. ");
                                    }

                                    U.error(log, "Failed to synchronize global lock queue: " + this, e);
                                }

                                throw e;
                            }
                        }
                    });
            }
            catch (IgniteCheckedException e) {
                throw U.convertException(e);
            }
            finally {
                // Restore interrupt flag and let AQS decide what to do with it.
                if (interrupted.get())
                    Thread.currentThread().interrupt();
            }
        }

        /**
         * Sets the global state across all nodes after releasing the reentrant lock.
         *
         * @param newVal New state.
         * @param lastCond Id of the condition await is called.
         * @param outgoingSignals Map containing signal calls on this node since the last acquisition of the lock.
         */
        protected boolean setGlobalState(final int newVal,
            @Nullable final String lastCond,
            final Map<String, Integer> outgoingSignals) {
            try {
                return retryTopologySafe(new Callable<Boolean>() {
                        @Override public Boolean call() throws Exception {
                            try (GridNearTxLocal tx = CU.txStartInternal(ctx, lockView, PESSIMISTIC, REPEATABLE_READ)) {
                                GridCacheLockState val = lockView.get(key);

                                if (val == null)
                                    throw new IgniteCheckedException("Failed to find reentrant lock with given name: " + name);

                                val.set(newVal);

                                if (newVal == 0) {
                                    val.setId(null);

                                    val.setThreadId(LOCK_FREE);
                                }

                                val.setChanged(true);

                                // If this lock is fair, remove this node from queue.
                                if (val.isFair() && newVal == 0) {
                                    UUID rmvdNode = val.getNodes().removeFirst();

                                    assert(thisNode.equals(rmvdNode));
                                }

                                // Get global condition queue.
                                Map<String, LinkedList<UUID>> condMap = val.getConditionMap();

                                // Create map containing signals from this node.
                                Map<UUID, LinkedList<String>> signalMap = new HashMap<>();

                                // Put any signal calls on this node to global state.
                                if (!outgoingSignals.isEmpty()) {
                                    for (String condition : outgoingSignals.keySet()) {
                                        int cnt = outgoingSignals.get(condition);

                                        // Get queue for this condition.
                                        List<UUID> list = condMap.get(condition);

                                        if (list != null && !list.isEmpty()) {
                                            // Check if signalAll was called.
                                            if (cnt == 0)
                                                cnt = list.size();

                                            // Remove from global condition queue.
                                            for (int i = 0; i < cnt; i++) {
                                                if (list.isEmpty())
                                                    break;

                                                UUID uuid = list.remove(0);

                                                // Skip if node to be released is not alive anymore.
                                                if (ctx.discovery().node(uuid) == null) {
                                                    cnt++;

                                                    continue;
                                                }

                                                LinkedList<String> queue = signalMap.get(uuid);

                                                if (queue == null) {
                                                    queue = new LinkedList<>();

                                                    signalMap.put(uuid, queue);
                                                }

                                                queue.add(condition);
                                            }
                                        }
                                    }
                                }

                                val.setSignals(signalMap);

                                // Check if this release is called after condition.await() call;
                                // If true, add this node to the global waiting queue.
                                if (lastCond != null) {
                                    LinkedList<UUID> queue;

                                    //noinspection IfMayBeConditional
                                    if (!condMap.containsKey(lastCond))
                                        // New condition object.
                                        queue = new LinkedList<>();
                                    else
                                        // Existing condition object.
                                        queue = condMap.get(lastCond);

                                    queue.add(thisNode);

                                    condMap.put(lastCond, queue);
                                }

                                val.setConditionMap(condMap);

                                lockView.put(key, val);

                                tx.commit();

                                return true;
                            }
                            catch (Exception e) {
                                if (interruptAll) {
                                    log.info("Node is stopped (or lock is broken in non-failover safe mode)," +
                                        " aborting transaction.");

                                    return true;
                                }
                                else
                                    U.error(log, "Failed to release: " + this, e);

                                throw e;
                            }
                        }
                    });
            }
            catch (IgniteCheckedException e) {
                throw U.convertException(e);
            }
        }

        synchronized boolean checkIncomingSignals(GridCacheLockState state) {
            if (state.getSignals() == null)
                return false;

            LinkedList<String> signals = state.getSignals().get(thisNode);

            if (signals == null || signals.isEmpty())
                return false;

            UUID tempUUID = getOwnerNode();

            Thread tempThread = getExclusiveOwnerThread();

            long tempThreadID = currentOwnerThreadId;

            // Temporarily allow current thread to signal condition object.
            // This is safe to do because:
            // 1. if release was called on this node,
            // it was called from currently active thread;
            // 2. if release came from a thread on any other node,
            // all threads on this node are already blocked.
            setCurrentOwnerNode(thisNode);

            setExclusiveOwnerThread(Thread.currentThread());

            currentOwnerThreadId = Thread.currentThread().getId();

            for (String signal: signals)
                conditionMap.get(signal).signal();

            // Restore owner node and owner thread.
            setCurrentOwnerNode(tempUUID);

            setExclusiveOwnerThread(tempThread);

            currentOwnerThreadId = tempThreadID;

            return true;
        }

        /**
         *  Condition implementation for {@linkplain IgniteLock}.
         *
         **/
        private class IgniteConditionObject implements IgniteCondition {
            /** */
            private final String name;

            /** */
            private final AbstractQueuedSynchronizer.ConditionObject obj;

            /**
             * @param name Condition name.
             * @param obj Condition object.
             */
            protected IgniteConditionObject(String name, ConditionObject obj) {
                this.name = name;

                this.obj = obj;
            }

            /**
             * Name of this condition.
             *
             * @return name Name of this condition object.
             */
            @Override public String name() {
                return name;
            }

            /** {@inheritDoc} */
            @Override public void await() throws IgniteInterruptedException {
                ctx.kernalContext().gateway().readLock();

                try {
                    if (!isHeldExclusively())
                        throw new IllegalMonitorStateException();

                    lastCondition = name;

                    obj.await();

                    sync.validate(true);
                }
                catch (InterruptedException e) {
                    throw new IgniteInterruptedException(e);
                }
                finally {
                    ctx.kernalContext().gateway().readUnlock();
                }
            }

            /** {@inheritDoc} */
            @Override public void awaitUninterruptibly() {
                ctx.kernalContext().gateway().readLock();

                try {
                    if (!isHeldExclusively())
                        throw new IllegalMonitorStateException();

                    lastCondition = name;

                    obj.awaitUninterruptibly();

                    sync.validate(false);
                }
                finally {
                    ctx.kernalContext().gateway().readUnlock();
                }
            }

            /** {@inheritDoc} */
            @Override public long awaitNanos(long nanosTimeout) throws IgniteInterruptedException {
                ctx.kernalContext().gateway().readLock();

                try {
                    if (!isHeldExclusively())
                        throw new IllegalMonitorStateException();

                    lastCondition = name;

                    long result =  obj.awaitNanos(nanosTimeout);

                    sync.validate(true);

                    return result;
                }
                catch (InterruptedException e) {
                    throw new IgniteInterruptedException(e);
                }
                finally {
                    ctx.kernalContext().gateway().readUnlock();
                }
            }

            /** {@inheritDoc} */
            @Override public boolean await(long time, TimeUnit unit) throws IgniteInterruptedException {
                ctx.kernalContext().gateway().readLock();

                try {
                    if (!isHeldExclusively())
                        throw new IllegalMonitorStateException();

                    lastCondition = name;

                    boolean result = obj.await(time, unit);

                    sync.validate(true);

                    return result;
                }
                catch (InterruptedException e) {
                    throw new IgniteInterruptedException(e);
                }
                finally {
                    ctx.kernalContext().gateway().readUnlock();
                }
            }

            /** {@inheritDoc} */
            @Override public boolean awaitUntil(Date deadline) throws IgniteInterruptedException {
                ctx.kernalContext().gateway().readLock();

                try {
                    if (!isHeldExclusively())
                        throw new IllegalMonitorStateException();

                    lastCondition = name;

                    boolean result = obj.awaitUntil(deadline);

                    sync.validate(true);

                    return result;
                }
                catch (InterruptedException e) {
                    throw new IgniteInterruptedException(e);
                }
                finally {
                    ctx.kernalContext().gateway().readUnlock();
                }
            }

            /** {@inheritDoc} */
            @Override public void signal() {
                ctx.kernalContext().gateway().readLock();

                try {
                    if (!isHeldExclusively())
                        throw new IllegalMonitorStateException();

                    validate(false);

                    addOutgoingSignal(name);
                }
                finally {
                    ctx.kernalContext().gateway().readUnlock();
                }
            }

            /** {@inheritDoc} */
            @Override public void signalAll() {
                ctx.kernalContext().gateway().readLock();

                try {
                    if (!isHeldExclusively())
                        throw new IllegalMonitorStateException();

                    sync.validate(false);

                    addOutgoingSignalAll(name);
                }
                finally {
                    ctx.kernalContext().gateway().readUnlock();
                }
            }
        }
    }

    /**
     * Constructor.
     *
     * @param name Reentrant lock name.
     * @param key Reentrant lock key.
     * @param lockView Reentrant lock projection.
     * @param ctx Cache context.
     */
    @SuppressWarnings("unchecked")
    public GridCacheLockImpl(String name,
        GridCacheInternalKey key,
        IgniteInternalCache<GridCacheInternalKey, GridCacheLockState> lockView,
        GridCacheContext ctx) {
        assert name != null;
        assert key != null;
        assert ctx != null;
        assert lockView != null;

        this.name = name;
        this.key = key;
        this.lockView = lockView;
        this.ctx = ctx;

        log = ctx.logger(getClass());
    }

    /**
     * @throws IgniteCheckedException If operation failed.
     */
    private void initializeReentrantLock() throws IgniteCheckedException {
        if (initGuard.compareAndSet(false, true)) {
            try {
                sync = retryTopologySafe(new Callable<Sync>() {
                        @Override public Sync call() throws Exception {
                            try (GridNearTxLocal tx = CU.txStartInternal(ctx, lockView, PESSIMISTIC, REPEATABLE_READ)) {
                                GridCacheLockState val = lockView.get(key);

                                if (val == null) {
                                    if (log.isDebugEnabled())
                                        log.debug("Failed to find reentrant lock with given name: " + name);

                                    return null;
                                }

                                tx.rollback();

                                return new Sync(val);
                            }
                        }
                    });

                if (log.isDebugEnabled())
                    log.debug("Initialized internal sync structure: " + sync);
            }
            finally {
                initLatch.countDown();
            }
        }
        else {
            U.await(initLatch);

            if (sync == null)
                throw new IgniteCheckedException("Internal reentrant lock has not been properly initialized.");
        }
    }

    /** {@inheritDoc} */
    @Override public void onUpdate(GridCacheLockState val) {
        // Called only on initialization, so it's safe to ignore update.
        if (sync == null)
            return;

        updateLock.lock();

        try {
            // If this update is a result of unsuccessful acquire in fair mode, no local update should be done.
            if (!val.isChanged())
                return;

            // Check if update came from this node.
            boolean loc = sync.isLockedLocally(val.getId());

            // Process any incoming signals.
            boolean incomingSignals = sync.checkIncomingSignals(val);

            // Update permission count.
            sync.setPermits(val.get());

            // Update owner's node id.
            sync.setCurrentOwnerNode(val.getId());

            // Update owner's thread id.
            sync.setCurrentOwnerThread(val.getThreadId());

            // Check if any threads waiting on this node need to be notified.
            if ((incomingSignals || sync.getPermits() == 0) && !loc) {
                // Try to notify any waiting threads.
                sync.release(0);
            }

        } finally{
            updateLock.unlock();
        }
    }

    /** {@inheritDoc} */
    @Override public void onNodeRemoved(UUID nodeId) {
        updateLock.lock();

        try {
            if (nodeId.equals(sync.getOwnerNode())) {
                sync.setBroken(true);

                if (!sync.failoverSafe)
                    sync.interruptAll();
            }

            // Try to notify any waiting threads.
            sync.release(0);
        }
        finally {
            updateLock.unlock();
        }
    }

    /** {@inheritDoc} */
    @Override public void onStop() {
        if (sync == null) {
            interruptAll = true;

            return;
        }

        sync.setBroken(true);

        sync.interruptAll();

        // Try to notify any waiting threads.
        sync.release(0);
    }

    /** {@inheritDoc} */
    @Override public String name() {
        return name;
    }

    /** {@inheritDoc} */
    @Override public void lock() {
        ctx.kernalContext().gateway().readLock();

        try{
            initializeReentrantLock();

            sync.lock();

            sync.validate(false);
        }
        catch (IgniteCheckedException e) {
            throw U.convertException(e);
        }
        finally {
            ctx.kernalContext().gateway().readUnlock();
        }
    }

    /** {@inheritDoc} */
    @Override public void lockInterruptibly() throws IgniteInterruptedException {
        ctx.kernalContext().gateway().readLock();

        try {
            initializeReentrantLock();

            sync.acquireInterruptibly(1);

            sync.validate(true);
        }
        catch (IgniteCheckedException e) {
            throw U.convertException(e);
        }
        catch (InterruptedException e) {
            if (sync.fair)
                sync.synchronizeQueue(true, Thread.currentThread());

            throw new IgniteInterruptedException(e);
        }
        finally {
            ctx.kernalContext().gateway().readUnlock();
        }
    }

    /** {@inheritDoc} */
    @Override public boolean tryLock() {
        ctx.kernalContext().gateway().readLock();

        try{
            initializeReentrantLock();

            boolean result = sync.tryAcquire(1, false);

            sync.validate(false);

            return result;
        }
        catch (IgniteCheckedException e) {
            throw U.convertException(e);
        }
        finally {
            ctx.kernalContext().gateway().readUnlock();
        }
    }

    /** {@inheritDoc} */
    @Override public boolean tryLock(long timeout, TimeUnit unit) throws IgniteInterruptedException {
        ctx.kernalContext().gateway().readLock();

        try{
            initializeReentrantLock();

            boolean result = sync.tryAcquireNanos(1, unit.toNanos(timeout));

            sync.validate(true);

            return result;
        }
        catch (IgniteCheckedException e) {
            throw U.convertException(e);
        }
        catch (InterruptedException e) {
            if (sync.fair)
                sync.synchronizeQueue(true, Thread.currentThread());

            throw new IgniteInterruptedException(e);
        }
        finally {
            ctx.kernalContext().gateway().readUnlock();
        }
    }

    /** {@inheritDoc} */
    @Override public void unlock() {
        ctx.kernalContext().gateway().readLock();

        try{
            initializeReentrantLock();

            // Validate before release.
            sync.validate(false);

            sync.release(1);
        }
        catch (IgniteCheckedException e) {
            throw U.convertException(e);
        }
        finally {
            ctx.kernalContext().gateway().readUnlock();
        }
    }

    @NotNull @Override public Condition newCondition() {
        throw new UnsupportedOperationException("IgniteLock does not allow creation of nameless conditions. ");
    }

    /** {@inheritDoc} */
    @Override public IgniteCondition getOrCreateCondition(String name) {
        ctx.kernalContext().gateway().readLock();

        try{
            initializeReentrantLock();

            IgniteCondition result = sync.newCondition(name);

            sync.validate(false);

            return result;
        }
        catch (IgniteCheckedException e) {
            throw U.convertException(e);
        }
        finally {
            ctx.kernalContext().gateway().readUnlock();
        }
    }

    /** {@inheritDoc} */
    @Override public int getHoldCount() {
        try{
            initializeReentrantLock();

            return sync.getHoldCount();
        }
        catch (IgniteCheckedException e) {
            throw U.convertException(e);
        }
    }

    /** {@inheritDoc} */
    @Override public boolean isHeldByCurrentThread() {
        try{
            initializeReentrantLock();

            return sync.isHeldExclusively();
        }
        catch (IgniteCheckedException e) {
            throw U.convertException(e);
        }
    }

    /** {@inheritDoc} */
    @Override public boolean isLocked() {
        try{
            initializeReentrantLock();

            return sync.isLocked();
        }
        catch (IgniteCheckedException e) {
            throw U.convertException(e);
        }
    }

    /** {@inheritDoc} */
    @Override public boolean hasQueuedThreads() {
        try{
            initializeReentrantLock();

            return sync.hasQueuedThreads();
        }
        catch (IgniteCheckedException e) {
            throw U.convertException(e);
        }
    }

    /** {@inheritDoc} */
    @Override public boolean hasQueuedThread(Thread thread) {
        try{
            initializeReentrantLock();

            return sync.isQueued(thread);
        }
        catch (IgniteCheckedException e) {
            throw U.convertException(e);
        }
    }

    /** {@inheritDoc} */
    @Override public boolean hasWaiters(IgniteCondition condition) {
        try{
            initializeReentrantLock();

            AbstractQueuedSynchronizer.ConditionObject c = sync.conditionMap.get(condition.name());

            if (c == null)
                throw new IllegalArgumentException();

            return sync.hasWaiters(c);
        }
        catch (IgniteCheckedException e) {
            throw U.convertException(e);
        }
    }

    /** {@inheritDoc} */
    @Override public int getWaitQueueLength(IgniteCondition condition) {
        try{
            initializeReentrantLock();

            AbstractQueuedSynchronizer.ConditionObject c = sync.conditionMap.get(condition.name());

            if (c == null)
                throw new IllegalArgumentException();

            return sync.getWaitQueueLength(c);
        }
        catch (IgniteCheckedException e) {
            throw U.convertException(e);
        }
    }

    @Override public boolean isFailoverSafe() {
        try{
            initializeReentrantLock();

            return sync.failoverSafe;
        }
        catch (IgniteCheckedException e) {
            throw U.convertException(e);
        }
    }

    @Override public boolean isFair() {
        try{
            initializeReentrantLock();

            return sync.fair;
        }
        catch (IgniteCheckedException e) {
            throw U.convertException(e);
        }
    }

    /** {@inheritDoc} */
    @Override public boolean isBroken() {
        try{
            initializeReentrantLock();

            return sync.isBroken();
        }
        catch (IgniteCheckedException e) {
            throw U.convertException(e);
        }
    }

    /** {@inheritDoc} */
    @Override public GridCacheInternalKey key() {
        return key;
    }

    /** {@inheritDoc} */
    @Override public boolean removed() {
        return rmvd;
    }

    /** {@inheritDoc} */
    @Override public boolean onRemoved() {
        return rmvd = true;
    }

    /** {@inheritDoc} */
    @Override public void needCheckNotRemoved() {

    }

    /** {@inheritDoc} */
    @Override public void onActivate(GridKernalContext kctx) throws IgniteCheckedException {
        this.lockView = kctx.cache().atomicsCache();
        this.ctx = lockView.context();
    }

    /** {@inheritDoc} */
    @Override public void onDeActivate(GridKernalContext kctx) throws IgniteCheckedException {

    }

    /** {@inheritDoc} */
    @Override public void writeExternal(ObjectOutput out) throws IOException {
        out.writeUTF(name);
    }

    /** {@inheritDoc} */
    @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        stash.set(in.readUTF());
    }

    /**
     * Reconstructs object on unmarshalling.
     *
     * @return Reconstructed object.
     * @throws ObjectStreamException Thrown in case of unmarshalling error.
     */
    private Object readResolve() throws ObjectStreamException {
        String name = stash.get();

        assert name != null;

        try {
            IgniteLock lock = IgnitionEx.localIgnite().context().dataStructures().reentrantLock(
                name,
                false,
                false,
                false);

            if (lock == null)
                throw new IllegalStateException("Lock was not found on deserialization: " + name);

            return lock;
        }
        catch (IgniteCheckedException e) {
            throw U.withCause(new InvalidObjectException(e.getMessage()), e);
        }
        finally {
            stash.remove();
        }
    }

    /** {@inheritDoc} */
    @Override public void close() {
        if (!rmvd) {
            try {
                boolean force = sync != null && (sync.isBroken() && !sync.failoverSafe);

                ctx.kernalContext().dataStructures().removeReentrantLock(name, force);
            }
            catch (IgniteCheckedException e) {
                throw U.convertException(e);
            }
        }
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        return S.toString(GridCacheLockImpl.class, this);
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Rusts of Australia 172 (1906)

#### Original name
Uredo zorniae Berk.

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
TRN.Behaviours.ParticleSystem = function(nbhv, gameData) {
    this.nbhv = nbhv;
}

TRN.Behaviours.ParticleSystem.prototype = {

    constructor : TRN.Behaviours.ParticleSystem,

    init : async function(lstObjs, resolve) {
        resolve(TRN.Consts.Behaviour.retKeepBehaviour);
    }

}


text:
using Sniper.Common;
using Sniper.Http;
using Sniper.TargetProcess.Routes;
using Xunit;

namespace Sniper.Tests.CRUD.Update.Common.RequestTypes
{
    public class UpdateRequestTypeTests
    {
        [Fact]
        public void RequestTypeThrowsError()
        {
            var client = new TargetProcessClient
            {
                ApiSiteInfo = new ApiSiteInfo(TargetProcessRoutes.Route.RequestTypes)
            };
            var requestType = new RequestType
            {
            };
        }
    }
}


text:
<?php

namespace ITB\BackupCommands\Providers;

use Illuminate\Support\ServiceProvider;
use ITB\BackupCommands\Console\Commands\BackupDatabaseCommand;
use ITB\BackupCommands\Console\Commands\BackupFilesCommand;

class BackupCommandsServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->publishes([
            __DIR__ . '/../../config/backupcmds.php' => config_path('backupcmds.php'),
        ], 'config');
        $this->publishes([
            __DIR__ . '/../../exec-scripts/_backup.sh' => base_path()  . '/_backup.sh',
            __DIR__ . '/../../exec-scripts/_backup.cmd' => base_path() . '/_backup.cmd',
        ], 'exec-scripts');
    }

    public function register()
    {
        $this->mergeConfigFrom( __DIR__ . '/../../config/backupcmds.php', 'backupcmds' );

        $this->app->singleton('command.backup-commands.database', function () {
            return new BackupDatabaseCommand;
        });

        $this->app->singleton('command.backup-commands.files', function () {
            return new BackupFilesCommand;
        });

        $this->commands('command.backup-commands.database');

        $this->commands('command.backup-commands.files');
    }
}


text:
/*
 * In my app, I have custom font, images, and icons.
 * Please download them so the contents will show up properly!
 * Please download the following:
 *   - the folder "fonts", under "Resources"
 *   - the folder "images", under "Resources"
 *   - two image files "briefcase.png" and "user.png", under "Resources"
 * I have also included screenshots of what the app should look like,
 * under "screenshots", just in case of... whatever? :P
 *
 * Social media is not included, so no need for any configuration.
 * Thanks for reviewing my app!
 *
 * I use iPhone 5s emulator. Results may look different in other devices' emulator.
 */

Titanium.UI.setBackgroundColor('#000');
// Create tab group
var tabGroup = Titanium.UI.createTabGroup({
	activeTabIconTint: '#ffffff', tabsBackgroundColor:'#282828'});

// Navigation Setup
var win1 = Titanium.UI.createWindow({
	title:'Business Card', backgroundColor:'#ffffff'});
var tab1 = Titanium.UI.createTab({
    icon:'user.png', title:'Profile',
    window:win1 });

var view1 = Ti.UI.createView({
	backgroundImage: '/images/blur.jpg',
	width:'100%', height:'100%'});
win1.add(view1);

var win2 = Titanium.UI.createWindow({
    title:'Resume', backgroundColor:'#fff'});
var tab2 = Titanium.UI.createTab({
    icon:'briefcase.png', title:'Resume',
    window:win2 });

var view2 = Ti.UI.createView({
	backgroundImage: '/images/blur.jpg',
	width:'100%', height:'100%'});
win2.add(view2);

// Content Setup - Landing Page - Profile
var customFont = 'Mathilde';

var label1 = Titanium.UI.createLabel({
	color:'#FFFFFF', text:'Darien Huang',
	font:{fontSize:86,fontFamily: customFont},
	textAlign:'center', width:'auto', top:'35%'
});
var text1 = Titanium.UI.createLabel({
	color:'#FFFFFF',
	text:'University of Idaho\nInformation System\nGraduating May 2015',
	font:{fontSize:40,fontFamily: customFont},
	textAlign:'center', width:'auto', top:'50%'
});

// All images used in the app
var profileImg = Ti.UI.createImageView({
  	image:'/images/doge.png', top:'5%', width:'150'});
var tblImg = Ti.UI.createImageView({
  	image:'/images/tumblr.png', top:'78%', left:'15%'});
var fbImg = Ti.UI.createImageView({
  	image:'/images/facebook.png', top:tblImg.top, left:'34%'});
var linkImg = Ti.UI.createImageView({
   	image:'/images/linkedin.png', top:tblImg.top, right:'34%'});
var gitImg = Ti.UI.createImageView({
  	image:'/images/github.png', top:tblImg.top, right:'15%'});
var phoneImg = Ti.UI.createImageView({
  	image:'/images/skype.png', top:'86%', left: '25%'});
var emailImg = Ti.UI.createImageView({
  	image:'/images/email.png', top:'86%', right: '25%'});

view1.add(profileImg);
view1.add(tblImg);
view1.add(fbImg);
view1.add(linkImg);
view1.add(gitImg);
view1.add(phoneImg);
view1.add(emailImg);

view1.add(label1);
view1.add(text1);

// Content Setup - Tab2 - Resume
var label2 = Titanium.UI.createLabel({
	color:'FFFFFF', font:{fontSize:20,fontFamily:'Ariel'},
	text:'Work Experience', textAlign:'left', top:'10%'
});
var text2 = Titanium.UI.createLabel({
	color:label2.color, font:{fontSize:16, fontFamily: 'Helvetica Neue'},
	text:'Old Navy\nSellebrity, Techspert, Fitologist\nMay 2014 to Current\nEmployee of the Month Oct 2014',
	textAlign:'left', top:'15%'
});
var label4 = Titanium.UI.createLabel({
	color:label2.color, font:label2.font,
	text:'Honors',
	textAlign:'left', top:'35%'
});
var text4 = Titanium.UI.createLabel({
	color:label2.color, font:text2.font,
	text:'Alpha Iota Mu (2015)\nGamma Beta Phi (2012 to 2013)',
	textAlign:'left', top:'40%'
});
var label3 = Titanium.UI.createLabel({
	color: label2.color, font:label2.font,
	text:'Languages',
	textAlign:'left', top:'50%'
});
var text3 = Titanium.UI.createLabel({
	color:label2.color, font:text2.font,
	text:'Fluent: Mandarin, English\nCompetent: Japanese, German',
	textAlign:'left', top:'55%'
});
var label5 = Titanium.UI.createLabel({
	color: label2.color, font:label2.font,
	text:'Skills',
	textAlign:'left', top:'65%'
});
var text5 = Titanium.UI.createLabel({
	color:label2.color, font:text2.font,
	text:'Social Media\nMicrosoft Office\nMac OS X\nWindows\nJavaScript\nHTML/CSS',
	textAlign:'left', top:'70%'
});

view2.add(label2);
view2.add(label3);
view2.add(label4);
view2.add(label5);
view2.add(text2);
view2.add(text3);
view2.add(text4);
view2.add(text5);

tabGroup.addTab(tab1);
tabGroup.addTab(tab2);

tabGroup.open();


text:
module Stitch
  module Event
    class Dispatcher

      include ActiveModel::Observing

      def self.dispatch(event_name, timestamp, data, async = true)
        event_object = Stitch::Event::Base.new(event_name, timestamp, data)
        if async
          event_object.compress_data
          Resque.enqueue(Stitch::Event::Worker, event_object) if defined?(Resque)
        else
          binding.pry
          notify_observers(event_object.method_name, event_object)
        end
      end
    end
  end
end


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <link rel="stylesheet" href="../theme/default/style.css" type="text/css">
    <link rel="stylesheet" href="style.css" type="text/css">

Filter Encoding

        filter, format, comparison, filter encoding, fe, logical, attribute,
        attributive, spatial, advanced

        Using the filter format write out filter objects.

    <textarea id="in">
filter = new OpenLayers.Filter.Logical({
    type: OpenLayers.Filter.Logical.AND,
    filters: [
        new OpenLayers.Filter.Comparison({
            type: OpenLayers.Filter.Comparison.LIKE,
            property: "person",
            value: "me"
        }),
        new OpenLayers.Filter.Comparison({
            type: OpenLayers.Filter.Comparison.NOT_EQUAL_TO,
            property: "mean",
            value: "yes"
        }),
        new OpenLayers.Filter.Spatial({
            type: OpenLayers.Filter.Spatial.BBOX,
            value: new OpenLayers.Bounds(-180, -90, 180, 90),
            projection: "EPSG:4326"
        })
    ]
});
    </textarea>
    <button id="write">write</button>

    Filter Encoding 1.0
    <textarea id="out0"></textarea>

    Filter Encoding 1.1
    <textarea id="out1"></textarea>


text:
PKGBASE=base-locale-hy
TINY_VERSION=0
.include "../../../mk/bsd.syspkg.mk"


text:
package ai.elimu.rest.v2.crowdsource;

import ai.elimu.dao.ContributorDao;
import ai.elimu.dao.AudioContributionEventDao;
import ai.elimu.dao.AudioDao;
import ai.elimu.dao.AudioPeerReviewEventDao;
import ai.elimu.model.content.multimedia.Audio;
import ai.elimu.model.contributor.Contributor;
import ai.elimu.model.contributor.AudioContributionEvent;
import ai.elimu.model.contributor.AudioPeerReviewEvent;
import ai.elimu.model.enums.PeerReviewStatus;
import ai.elimu.model.enums.Platform;
import ai.elimu.model.v2.gson.crowdsource.AudioContributionEventGson;
import ai.elimu.model.v2.gson.crowdsource.AudioPeerReviewEventGson;
import ai.elimu.rest.v2.JpaToGsonConverter;
import ai.elimu.util.DiscordHelper;
import ai.elimu.web.content.peer_review.AudioPeerReviewEventCreateController;
import ai.elimu.web.context.EnvironmentContextLoaderListener;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * REST API for the Crowdsource application: https://github.com/elimu-ai/crowdsource
 */
@RestController
@RequestMapping(value = "/rest/v2/crowdsource/audio-peer-reviews", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class AudioPeerReviewsRestController {

    private Logger logger = LogManager.getLogger();

    @Autowired
    private ContributorDao contributorDao;

    @Autowired
    private AudioDao audioDao;

    @Autowired
    private AudioContributionEventDao audioContributionEventDao;

    @Autowired
    private AudioPeerReviewEventDao audioPeerReviewEventDao;

    /**
     * Get {@link AudioContributionEvent}s pending a {@link AudioPeerReviewEvent} for the current {@link Contributor}.
     */
    @RequestMapping(value = "/words", method = RequestMethod.GET)
    public String listWordRecordingsPendingPeerReview(
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        logger.info("listWordRecordingsPendingPeerReview");

        JSONObject jsonObject = new JSONObject();

        // Lookup the Contributor by ID
        String providerIdGoogle = request.getHeader("providerIdGoogle");
        logger.info("providerIdGoogle: " + providerIdGoogle);
        if (StringUtils.isBlank(providerIdGoogle)) {
            jsonObject.put("result", "error");
            jsonObject.put("errorMessage", "Missing providerIdGoogle");
            response.setStatus(HttpStatus.BAD_REQUEST.value());

            String jsonResponse = jsonObject.toString();
            logger.info("jsonResponse: " + jsonResponse);
            return jsonResponse;
        }
        Contributor contributor = contributorDao.readByProviderIdGoogle(providerIdGoogle);
        logger.info("contributor: " + contributor);
        if (contributor == null) {
            jsonObject.put("result", "error");
            jsonObject.put("errorMessage", "The Contributor was not found.");
            response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());

            String jsonResponse = jsonObject.toString();
            logger.info("jsonResponse: " + jsonResponse);
            return jsonResponse;
        }

        List<AudioContributionEvent> allAudioContributionEvents = audioContributionEventDao.readAll();
        logger.info("allAudioContributionEvents.size(): " + allAudioContributionEvents.size());

        // Get the most recent AudioContributionEvent for each Audio
        List<AudioContributionEvent> mostRecentAudioContributionEvents = new ArrayList<>();
        HashMap<Long, Void> idsOfAudiosWithContributionEventHashMap = new HashMap<>();
        for (AudioContributionEvent audioContributionEvent : allAudioContributionEvents) {
            // Ignore AudioContributionEvent if one has already been added for this Audio
            if (idsOfAudiosWithContributionEventHashMap.containsKey(audioContributionEvent.getAudio().getId())) {
                continue;
            }

            // Keep track of the Audio ID
            idsOfAudiosWithContributionEventHashMap.put(audioContributionEvent.getAudio().getId(), null);

            // Ignore AudioContributionEvents made by the current Contributor
            if (audioContributionEvent.getContributor().getId().equals(contributor.getId())) {
                continue;
            }

            mostRecentAudioContributionEvents.add(audioContributionEvent);
        }
        logger.info("mostRecentAudioContributionEvents.size(): " + mostRecentAudioContributionEvents.size());

        // For each AudioContributionEvent, check if the Contributor has already performed a peer review.
        // If not, add it to the list of pending peer reviews.
        List<AudioContributionEvent> audioContributionEventsPendingPeerReview = new ArrayList<>();
        for (AudioContributionEvent mostRecentAudioContributionEvent : mostRecentAudioContributionEvents) {
            AudioPeerReviewEvent audioPeerReviewEvent = audioPeerReviewEventDao.read(mostRecentAudioContributionEvent, contributor);
            if (audioPeerReviewEvent == null) {
                audioContributionEventsPendingPeerReview.add(mostRecentAudioContributionEvent);
            }
        }
        logger.info("audioContributionEventsPendingPeerReview.size(): " + audioContributionEventsPendingPeerReview.size());

        // Convert to JSON
        JSONArray audioContributionEventsJsonArray = new JSONArray();
        for (AudioContributionEvent audioContributionEvent : audioContributionEventsPendingPeerReview) {
            AudioContributionEventGson audioContributionEventGson = JpaToGsonConverter.getAudioContributionEventGson(audioContributionEvent);
            String json = new Gson().toJson(audioContributionEventGson);
            audioContributionEventsJsonArray.put(new JSONObject(json));
        }

        String jsonResponse = audioContributionEventsJsonArray.toString();
        logger.info("jsonResponse: " + jsonResponse);
        return jsonResponse;
    }

    /**
     * Note: The logic in this method is similar to the one used at {@link AudioPeerReviewEventCreateController#handleSubmit}
     */
    @RequestMapping(value = "/words", method = RequestMethod.POST)
    public String uploadAudioPeerReview(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestBody String requestBody
    ) {
        logger.info("uploadAudioPeerReview");

        JSONObject jsonObject = new JSONObject();

        String providerIdGoogle = request.getHeader("providerIdGoogle");
        logger.info("providerIdGoogle: " + providerIdGoogle);
        if (StringUtils.isBlank(providerIdGoogle)) {
            jsonObject.put("result", "error");
            jsonObject.put("errorMessage", "Missing providerIdGoogle");
            response.setStatus(HttpStatus.BAD_REQUEST.value());

            String jsonResponse = jsonObject.toString();
            logger.info("jsonResponse: " + jsonResponse);
            return jsonResponse;
        }

        // Lookup the Contributor by ID
        Contributor contributor = contributorDao.readByProviderIdGoogle(providerIdGoogle);
        logger.info("contributor: " + contributor);
        if (contributor == null) {
            jsonObject.put("result", "error");
            jsonObject.put("errorMessage", "The Contributor was not found.");
            response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());

            String jsonResponse = jsonObject.toString();
            logger.info("jsonResponse: " + jsonResponse);
            return jsonResponse;
        }

        try {
            // Convert from Gson (POJO) to JPA/Hibernate
            logger.info("requestBody: " + requestBody);
            AudioPeerReviewEventGson audioPeerReviewEventGson = new Gson().fromJson(requestBody, AudioPeerReviewEventGson.class);
            logger.info("audioPeerReviewEventGson: " + audioPeerReviewEventGson);
            AudioContributionEventGson audioContributionEventGson = audioPeerReviewEventGson.getAudioContributionEvent();
            logger.info("audioContributionEventGson: " + audioContributionEventGson);
            Long audioContributionEventGsonId = audioContributionEventGson.getId();
            logger.info("audioContributionEventGsonId: " + audioContributionEventGsonId);
            AudioContributionEvent audioContributionEvent = audioContributionEventDao.read(audioContributionEventGsonId);
            logger.info("audioContributionEvent: " + audioContributionEvent);

            AudioPeerReviewEvent audioPeerReviewEvent = new AudioPeerReviewEvent();
            audioPeerReviewEvent.setContributor(contributor);
            audioPeerReviewEvent.setAudioContributionEvent(audioContributionEvent);
            audioPeerReviewEvent.setApproved(audioPeerReviewEventGson.isApproved());
            audioPeerReviewEvent.setComment(StringUtils.abbreviate(audioPeerReviewEventGson.getComment(), 1000));
            audioPeerReviewEvent.setTime(audioPeerReviewEventGson.getTime());
            audioPeerReviewEvent.setPlatform(Platform.CROWDSOURCE_APP);
            audioPeerReviewEventDao.create(audioPeerReviewEvent);

            String contentUrl = "http://" + EnvironmentContextLoaderListener.PROPERTIES.getProperty("content.language").toLowerCase() + ".elimu.ai/content/multimedia/audio/edit/" + audioContributionEvent.getAudio().getId();
            DiscordHelper.sendChannelMessage(
                    "Audio peer-reviewed: " + contentUrl,
                    "\"" + audioContributionEvent.getAudio().getTranscription() + "\"",
                    "Comment: \"" + audioPeerReviewEvent.getComment() + "\"",
                    audioPeerReviewEvent.isApproved(),
                    null
            );

            // Update the audio's peer review status
            int approvedCount = 0;
            int notApprovedCount = 0;
            for (AudioPeerReviewEvent peerReviewEvent : audioPeerReviewEventDao.readAll(audioContributionEvent)) {
                if (peerReviewEvent.isApproved()) {
                    approvedCount++;
                } else {
                    notApprovedCount++;
                }
            }
            logger.info("approvedCount: " + approvedCount);
            logger.info("notApprovedCount: " + notApprovedCount);
            Audio audio = audioContributionEvent.getAudio();
            if (approvedCount >= notApprovedCount) {
                audio.setPeerReviewStatus(PeerReviewStatus.APPROVED);
            } else {
                audio.setPeerReviewStatus(PeerReviewStatus.NOT_APPROVED);
            }
            audioDao.update(audio);
        } catch (Exception ex) {
            logger.error(ex);

            jsonObject.put("result", "error");
            jsonObject.put("errorMessage", ex.getMessage());
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }

        String jsonResponse = jsonObject.toString();
        logger.info("jsonResponse: " + jsonResponse);
        return jsonResponse;
    }
}


text:
layout:     post
title:      "How to Know Oneself?"
subtitle:   "Practice of Mindfulness"
date:       2016-05-21 12:00:00
author:     "Supakorn Laohasongkram"
tags: ['practice-of-true-happiness']
---

We Meditate.

Meditation is simply to know. "Know" in this sense is not knowing in our thoughts or knowing from reading, listening, or thinking but knowing as in to experience, be aware of, or be mindful of.

What do we know in meditation?

The objects that we must know in meditation are ourselves. The self can be divided into two main parts: the mind and the body.

However, it could further be separated it into five parts which are..

Body

Consciousness

Knowledge

Thoughts

Feeling

 These are the objects of meditations.

What do we do once we are mindful of our body, consciousness, knowledge, thoughts, and feeling?

 Nothing. Simply by being mindful of ourselves is enough. This might sounds very strange in this age where one has to always do more or always take a more active stance in achieving something. But this is not the case for meditation.

What is the correct way to know in meditation?

Know objectively as is. Without any need to change or to desire how our body, consciousness, knowledge, thoughts, and feeling should or should not be. If you are upset, know that you are upset. If we have a stomach ache, know that we have the stomach ache. This is how we develop our mindfulness.

Why should I develop my mindfulness? What is the purpose of meditation?

The purpose of meditation is to allow the mind to see its own reality. Our life is full of ups and downs, positive emotions and negative emotions, good thoughts and bad thoughts, birth and death, and of knowledge of what is "good" and "evil".

How do we live and navigate in the world which is full of these dualities of life is the real question that one must know the answer to live a  happy life.

When life is not going the way we want we can always say to ourselves that, "life is uncertain" or that "it will soon pass." But do our hearts really accept this fact? Even with the knowledge that life is uncertain, we still suffer. For this reason, knowing by knowledge is not enough. What we need is to know life by heart. This is why meditation is needed as the tool for our hearts to come to know truth.

By allowing our hearts to see the dualities of life, we can see that life with its ups and downs has three characteristics:

Everything is impermanent.

Nothing lasted.

Reality has nothing to do with what we want, but it has everything to do with the natural law of cause and effect. (For a more detailed explanation, click here.)

Meditation is how one comes to understand reality. It is how our hearts learn about how everything comes and goes, how all must inevitably progress from birth to death, and how the world is not about what we want but about the absolute law of cause and effect. These are the truth that our hearts will come to see for itself just by being mindful.

Once the hearts could come to understand the truth of life. Life becomes easier to live and harder for it to suffer. Like learning how to ride a horse, if you do not know how, riding becomes a nightmare. And often times than not, the horse rides you more than you ride the horse. Life is very much the same. This is why one must learn life to live it. And meditation is how.

Types of Meditation

1. Meditation in Daily Life

The most important type of meditation is not one in which most people believe. Many have the idea of meditation as sitting down, closing our eyes, and watch our breathing. But for meditation to be effective it must be practical in our daily life.

And there are two ways one could develop mindfulness in our daily life.

Being mindful of our mind

Our mind consists of our consciousness, knowledge, thoughts, and feelings. Consciousness's only task is to know. Knowledge is what we know. Thoughts are our cognitive thinking. And feeling is... feeling! (However, it could be further generalized into three types of feelings: positive, negative, and neutral.)

We develop our mindfulness by noticing our thoughts and feelings. When a thought takes our mind from places to places we know our mind is wandering. When we are happy, we know that we are happy. When we are sad we know that we are sad. This is all it takes to develop mindfulness. (Really?) Really!

Being mindful of our body

In our daily life, we can develop our mindfulness by knowing our bodies in the present moment like when we are breathing, walking, eating, sitting, and etc. Simple right? Just know our bodily movement through out the day and we are all set!

In short, meditation in daily life is to know our body, consciousness, knowledge, thoughts, and feelings.

How much daily meditation is enough?

All day is enough. True practictioners of mindfulness begin their practice starting from the moment they wake up until the moment they go to bed. They are mindful of when they get out of bed, brush their teeth, eat, walk, go to work, come home, and go to bed. They are mindful of all their positive or negative thoughts and emotions through out the day. The practice of mindfulness is easy; but to practice it consistently through out the day is not. Slowly build your mindfulness in daily life until it becomes a second-nature.

2. Sitting and Walking Meditation

Sitting Meditation

Sitting meditation is ultimately to be mindful of our in breath and out breath. Let's first begin with the steps:

Find a suitable spot for sitting meditation. Preferably any place that is quiet and give you a sense of peace and tranquility.

Sit in a comfortable position. It is not required for you to sit on the floor. Sitting on a chair would do. But I would recommend that the chair should not be too comfortable because it would make you fall asleep!

You can begin noticing your out breath and in breath with your eyes open or closed. If you easily get sleepy while doing your sitting meditation then it would be good to start with your eyes open and just notice the in and out breath before closing your eyes once you feel more concentrated.

Continuosly be mindful of the breath. If you mind wanders, simply bring it back to the breath and continue.

These are the steps to sitting meditation which can seem pretty simple but once you are into the practice and actuality of doing it, it is not. So here are some tips.

		Quick Tips on Sitting Meditation

Meditation is not about control nor is it about letting the mind runs loose. The trick is to find the perfect balance between controlling and not. To know the breath by being not too tight and not too loose. Sitting meditation is like holding a chick. If you hold it too loosely it runs away. If you hold it too tightly, the chick suffocates. If you find yourself feeling tight, stiff, having a headache, or finding it difficult to just breathe during or after meditation then it is a clear sign that you are exerting too much control. If you are sleepy, find your mind wandering from places to places without being able to come back to the breath, then it might be possible that you are too loose. Learning sitting meditaiton is like learning how to ride a bike. It will take time and experience to adjust and know your own balance. And practice is key to finding it.

Walking Meditation

Since my practice in walking meditation has been trained from the Theravada Buddhist tradition. I want to offer what I know from my own experience. So follow the links below to learn about how as well as why we do walking meditation. (Make sure you turn on the subtitle.) This knowledge will also aid you in your sitting meditation since it pretty much has the same concept.

Video on "How to practice walking meditation?" #1

Video on "How to practice walking meditation?" #2

How much sitting/walking meditation is enough?

Twice a day. I would suggest to make this into a habit by chaining it with some daily routine you have been doing. For example, right after you shower or before you go to bed. It does not need to be a hour long session. In fact one minute would do. But the important thing is to not lose the routine. Once you keep the routine for around 3 weeks, the habit of meditating will stick with you.

Conclusion

I can only show you the door. But you are the only who has to walk through it.

All in all, I could talk all day about how you should meditate; but in the end you have to do it. Only through meditation will you find out for yourself what meditation actually is. You can't learn how to ride a horse or swim from just reading a textbook. You must do it to learn it. Life is where we can learn about life's truth. This is why meditation is defined as the process of knowing oneself. Enough talking and start doing!

Recommended readings about "Meditation":

Why Meditation?

Learn goals behind the art of meditation, click here

Why Meditation Matters to The World?

If you are curious about why meditation is important to this world, click here

What I Have Received from Meditation as a Long-Time Practitioner?

Click here to learn more about my experience with meditation.


text:
package tracker.server.request.handlers;

/**
 * Created by sohan on 7/3/2017.
 */
public interface DelegatingRequestHandler extends RequestHandler {
}


text:
/* Main configuration */

@import 'corporate/index.css';
@import 'typography/index.css';
@import 'generic/index.css';
@import 'fx/index.css';
@import 'elements/index.css';


text:
layout: page
permalink: /publications/
title: publications
description: publications by categories in reversed chronological order.
years: []
nav: true
nav_order: 1
sort_by: year
order: descending
---

Preprint(s)

  {% bibliography -f papers -q @preprint %}

International journal papers

  {% bibliography -f papers -q @article %}

International conference papers

  {% bibliography -f papers -q @inproceedings[language!=French] %}

National conference papers

  {% bibliography -f papers -q @inproceedings[language=French] %}

Technical reports

  {% bibliography -f papers -q @techreport %}

Thesis

  {% bibliography -f papers -q @phdthesis %}


text:
module Lang.Hask.Pretty where

import Outputable
import Lang.Hask.Compat
import FP
import qualified FP.Pretty as P
import Lang.Hask.CPS
import Lang.Hask.Semantics
import DataCon
import Name
import Literal
import CoreSyn (AltCon(..))

makePrettyUnion ''Pico
makePrettySum ''Moment
makePrettySum ''Addr
makePrettySum ''ArgVal
makePrettySum ''Data
makePrettySum ''FunClo
makePrettySum ''Ref
makePrettySum ''KonClo
makePrettySum ''ThunkClo
makePrettySum ''KonMemoClo
makePrettySum ''Forced
makePrettySum ''𝒮

instance Pretty Name where pretty = P.bdr . fromChars . showSDoc (dynFlags ()) . ppr
instance Pretty Literal where pretty = P.lit . fromChars . showSDoc (dynFlags ()) . ppr
instance Pretty DataCon where pretty = P.con . fromChars . showSDoc (dynFlags ()) . ppr

instance Pretty AltCon where
  pretty (DataAlt dc) = pretty dc
  pretty (LitAlt l) = pretty l
  pretty DEFAULT = P.key "DEFAULT"

data VarLam n e = VarLam [n] e
instance (Pretty n, Pretty e) => Pretty (VarLam n e) where
  pretty (VarLam xs e) = P.nest 2 $ P.hvsep
    [ P.hsep $ concat
      [ single $ P.key "λ"
      , map pretty xs
      , single $ P.keyPun "->"
      ]
    , pretty e
    ]

instance (Pretty e) => Pretty (PreAtom e) where
  pretty (Pico p) = pretty p
  pretty (LamF x k e) = pretty $ VarLam [x, k] e
  pretty (LamK x e) = pretty $ VarLam [x] e
  pretty (Thunk r xi x k p₁ p₂) = exec
    [ P.key "THUNK"
    , P.collection "[" "]" "," [ pretty r , P.pun $ show xi , pretty x , pretty k ]
    , P.parens $ P.app (pretty p₁) [pretty p₂]
    ]

instance (Pretty e) => Pretty (PreCaseBranch e) where
  pretty (CaseBranch con cs e) = P.nest 2 $ P.hvsep
    [ P.hsep
        [ P.app (pretty con) $ map pretty cs
        , P.keyPun "->"
        ]
    , P.nest 2 $ pretty e
    ]

instance (Pretty e) => Pretty (PreCall e) where
  pretty (Let x a e) = P.hvsep
    [ P.hsep [P.key "let", pretty x, P.keyPun ":=", P.hvsep [P.nest 2 $ pretty a, P.key "in"]]
    , pretty e
    ]
  pretty (Rec rxs e) = P.hvsep
    [ P.hsep $ concat [single $ P.key "rec", map pretty rxs, single $ P.key "in"]
    , pretty e
    ]
  pretty (Letrec xas e) = P.hvsep
    [ P.key "letrec"
    , exec
        [ P.space 2
        , P.align $ P.hvsep $ mapOn xas $ \ (x, a) -> P.hsep [pretty x, P.keyPun ":=" , P.nest 2 $ pretty a]
        ]
    , P.key "in"
    , pretty e
    ]
  pretty (AppK p₁ p₂) = P.parens $ P.app (P.con "K") [pretty p₁, pretty p₂]
  pretty (AppF xi x p₁ p₂ p₃) =
    P.app (exec [P.con "F", P.collection "[" "]" "," [P.pun $ show xi, pretty x]])
          [pretty p₁, pretty p₂, pretty p₃]
  pretty (Case xi x p bs) = P.hvsep
    [ exec
        [ P.key "CASE["
        , P.pun $ show xi
        , P.pun ","
        , pretty x
        , P.key "]"
        , P.parens $ pretty p
        ]
    , P.key "of"
    , exec
        [ P.space 2
        , P.align $ P.hvsep $ map pretty bs
        ]
    ]
  pretty (Halt p) = P.app (P.con "HALT") [pretty p]
instance (Functorial Pretty PreCall) where functorial = W


text:
Opslag Daemons

Iedere ingang op deze pagina bepaald een verbinding naar een particulier
apparaat op een Bacula opslag deamon.Normaal gesproken werkt de deamon op
hetzelfde systeem, echter het is mogelijk om meer dan 1 deamon te definieren
waarbij sommige deamons zich kunnen bevinden op een remote hosts met verschillende
tape drives of met meer harddisk ruimte.

De belangrijke attributen voor iedere deamon zijn :

Opslag naam

Een unieke naam die gebruikt word op dit systeem om de deamon te identificeren.

Bacula SD wachtwoord

Dit veld moet het wachtwoord bevatten wat gebruikt word door de opslag deamon op het remote
systeem, welke gevonden kan worden in de <tt>/etc/bacula/bacula-sd.conf</tt> file.

Hostnaam of IP adres

De volledige hostnaam of het IP adres van het systeem waar de opslag deamon werkt.

Opslag apparaat naam

In iedere opslag deamon kunnen 1 of meerdere apparaten gedefinieerd worden, waarbij ze allemaal
corresponderen met een verschillende directory of tape drive. Dit veld bepaald welk apparaat
welke particuliere deamon verbinding gebruikt.

Media type naam

Dit veld moet een korte naam bevatten voor het type media wat word gebruikt door het opslag
apparaat, bijvoorbeeld File of DDS-2. Het moet wel hetzelfde zijn als in de
Opslag Apparaten sectie op de opslag server.

Het is vaak nuttig om meerdere ingangen voor dezelfde host te hebben op deze pagina,
waarbij een ieder een verschillend opslag apparaat heeft. Hierdoor kunt u backups maken
die geschreven worden naar verschillende directory's of tape drives.

Indien de TLS opties worden getoont in het opslag deamon formulier kunt u deze gebruiken
om een veilige verbinding op te zetten tussen de director en de remote opslag server.
Dit is normaal gesproken niet nodig in een simpele Bacula configuratie omdat de opslag
en director deamons normaal gesproken op hetzelfde systeem werken.


text:
package uk.ac.ox.oucs.oxpoints.gaboto.beans;

import uk.ac.ox.oucs.oxpoints.gaboto.beans.SpaceConfiguration;

/**
 * Gaboto generated bean.
 * @see net.sf.gaboto.generation.GabotoGenerator
 */
public class Theatre extends SpaceConfiguration {

  @Override
  public String getType(){
    return "http://purl.org/openorg/space-configuration/Theatre";
  }

  public String toString() {
    return this.capacity + ", " + this.comment ;
  }
}


text:
@protocol OALSuspendManager <OALSuspendListener>
- (void)addSuspendListener:(id <OALSuspendListener>)arg1;
- (void)removeSuspendListener:(id <OALSuspendListener>)arg1;
@property(readonly, nonatomic) _Bool suspended;
@end


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" tools:context="none.areyoualive.Activity4">
    <item android:id="@+id/action_settings" android:title="@string/action_settings"
        android:orderInCategory="100" app:showAsAction="never" />
</menu>