text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.operator;

import com.facebook.presto.ExceededMemoryLimitException;
import com.facebook.presto.Session;
import com.facebook.presto.memory.QueryContextVisitor;
import com.facebook.presto.memory.context.AggregatedMemoryContext;
import com.facebook.presto.memory.context.LocalMemoryContext;
import com.facebook.presto.memory.context.MemoryTrackingContext;
import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.sql.planner.plan.PlanNodeId;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import io.airlift.stats.CounterStat;
import io.airlift.units.Duration;

import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.ThreadSafe;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.util.Optional;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;

import static com.facebook.presto.operator.BlockedReason.WAITING_FOR_MEMORY;
import static com.facebook.presto.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static io.airlift.units.DataSize.succinctBytes;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.TimeUnit.NANOSECONDS;

/**
 * Only {@link #getOperatorStats()} and revocable-memory-related operations are ThreadSafe
 */
public class OperatorContext
{
    private static final ThreadMXBean THREAD_MX_BEAN = ManagementFactory.getThreadMXBean();

    private final int operatorId;
    private final PlanNodeId planNodeId;
    private final String operatorType;
    private final DriverContext driverContext;
    private final Executor executor;

    private final AtomicLong intervalWallStart = new AtomicLong();
    private final AtomicLong intervalCpuStart = new AtomicLong();
    private final AtomicLong intervalUserStart = new AtomicLong();

    private final AtomicLong addInputCalls = new AtomicLong();
    private final AtomicLong addInputWallNanos = new AtomicLong();
    private final AtomicLong addInputCpuNanos = new AtomicLong();
    private final AtomicLong addInputUserNanos = new AtomicLong();
    private final CounterStat inputDataSize = new CounterStat();
    private final CounterStat inputPositions = new CounterStat();

    private final AtomicLong getOutputCalls = new AtomicLong();
    private final AtomicLong getOutputWallNanos = new AtomicLong();
    private final AtomicLong getOutputCpuNanos = new AtomicLong();
    private final AtomicLong getOutputUserNanos = new AtomicLong();
    private final CounterStat outputDataSize = new CounterStat();
    private final CounterStat outputPositions = new CounterStat();

    private final AtomicLong physicalWrittenDataSize = new AtomicLong();

    private final AtomicReference<SettableFuture<?>> memoryFuture;
    private final AtomicReference<SettableFuture<?>> revocableMemoryFuture;
    private final AtomicReference<BlockedMonitor> blockedMonitor = new AtomicReference<>();
    private final AtomicLong blockedWallNanos = new AtomicLong();

    private final AtomicLong finishCalls = new AtomicLong();
    private final AtomicLong finishWallNanos = new AtomicLong();
    private final AtomicLong finishCpuNanos = new AtomicLong();
    private final AtomicLong finishUserNanos = new AtomicLong();

    private final SpillContext spillContext;
    private final AtomicReference<Supplier<OperatorInfo>> infoSupplier = new AtomicReference<>();
    private final boolean collectTimings;

    @GuardedBy("this")
    private boolean memoryRevokingRequested;

    @Nullable
    @GuardedBy("this")
    private Runnable memoryRevocationRequestListener;

    private final MemoryTrackingContext operatorMemoryContext;

    public OperatorContext(
            int operatorId,
            PlanNodeId planNodeId,
            String operatorType,
            DriverContext driverContext,
            Executor executor,
            MemoryTrackingContext operatorMemoryContext)
    {
        checkArgument(operatorId >= 0, "operatorId is negative");
        this.operatorId = operatorId;
        this.planNodeId = requireNonNull(planNodeId, "planNodeId is null");
        this.operatorType = requireNonNull(operatorType, "operatorType is null");
        this.driverContext = requireNonNull(driverContext, "driverContext is null");
        this.spillContext = new OperatorSpillContext(this.driverContext);
        this.executor = requireNonNull(executor, "executor is null");
        this.memoryFuture = new AtomicReference<>(SettableFuture.create());
        this.memoryFuture.get().set(null);
        this.revocableMemoryFuture = new AtomicReference<>(SettableFuture.create());
        this.revocableMemoryFuture.get().set(null);
        this.operatorMemoryContext = requireNonNull(operatorMemoryContext, "operatorMemoryContext is null");

        collectTimings = driverContext.isVerboseStats() && driverContext.isCpuTimerEnabled();
    }

    public int getOperatorId()
    {
        return operatorId;
    }

    public String getOperatorType()
    {
        return operatorType;
    }

    public DriverContext getDriverContext()
    {
        return driverContext;
    }

    public Session getSession()
    {
        return driverContext.getSession();
    }

    public boolean isDone()
    {
        return driverContext.isDone();
    }

    public void startIntervalTimer()
    {
        intervalWallStart.set(System.nanoTime());
        intervalCpuStart.set(currentThreadCpuTime());
        intervalUserStart.set(currentThreadUserTime());
    }

    public void recordAddInput(Page page)
    {
        addInputCalls.incrementAndGet();
        recordInputWallNanos(nanosBetween(intervalWallStart.get(), System.nanoTime()));
        addInputCpuNanos.getAndAdd(nanosBetween(intervalCpuStart.get(), currentThreadCpuTime()));
        addInputUserNanos.getAndAdd(nanosBetween(intervalUserStart.get(), currentThreadUserTime()));

        if (page != null) {
            inputDataSize.update(page.getSizeInBytes());
            inputPositions.update(page.getPositionCount());
        }
    }

    public void recordGeneratedInput(long sizeInBytes, long positions)
    {
        recordGeneratedInput(sizeInBytes, positions, 0);
    }

    public void recordGeneratedInput(long sizeInBytes, long positions, long readNanos)
    {
        inputDataSize.update(sizeInBytes);
        inputPositions.update(positions);
        recordInputWallNanos(readNanos);
    }

    public long recordInputWallNanos(long readNanos)
    {
        return addInputWallNanos.getAndAdd(readNanos);
    }

    public void recordGetOutput(Page page)
    {
        getOutputCalls.incrementAndGet();
        getOutputWallNanos.getAndAdd(nanosBetween(intervalWallStart.get(), System.nanoTime()));
        getOutputCpuNanos.getAndAdd(nanosBetween(intervalCpuStart.get(), currentThreadCpuTime()));
        getOutputUserNanos.getAndAdd(nanosBetween(intervalUserStart.get(), currentThreadUserTime()));

        if (page != null) {
            outputDataSize.update(page.getSizeInBytes());
            outputPositions.update(page.getPositionCount());
        }
    }

    public void recordGeneratedOutput(long sizeInBytes, long positions)
    {
        outputDataSize.update(sizeInBytes);
        outputPositions.update(positions);
    }

    public void recordPhysicalWrittenData(long sizeInBytes)
    {
        physicalWrittenDataSize.getAndAdd(sizeInBytes);
    }

    public void recordBlocked(ListenableFuture<?> blocked)
    {
        requireNonNull(blocked, "blocked is null");

        BlockedMonitor monitor = new BlockedMonitor();

        BlockedMonitor oldMonitor = blockedMonitor.getAndSet(monitor);
        if (oldMonitor != null) {
            oldMonitor.run();
        }

        blocked.addListener(monitor, executor);
        // Do not register blocked with driver context.  The driver handles this directly.
    }

    public void recordFinish()
    {
        finishCalls.incrementAndGet();
        finishWallNanos.getAndAdd(nanosBetween(intervalWallStart.get(), System.nanoTime()));
        finishCpuNanos.getAndAdd(nanosBetween(intervalCpuStart.get(), currentThreadCpuTime()));
        finishUserNanos.getAndAdd(nanosBetween(intervalUserStart.get(), currentThreadUserTime()));
    }

    public ListenableFuture<?> isWaitingForMemory()
    {
        return memoryFuture.get();
    }

    public ListenableFuture<?> isWaitingForRevocableMemory()
    {
        return revocableMemoryFuture.get();
    }

    // caller should close this context as it's a new context
    public LocalMemoryContext newLocalSystemMemoryContext()
    {
        return operatorMemoryContext.newSystemMemoryContext();
    }

    // caller shouldn't close this context as it's managed by the OperatorContext
    public LocalMemoryContext localUserMemoryContext()
    {
        return new DecoratedLocalMemoryContext(operatorMemoryContext.localUserMemoryContext(), memoryFuture);
    }

    // caller shouldn't close this context as it's managed by the OperatorContext
    public LocalMemoryContext localRevocableMemoryContext()
    {
        return new DecoratedLocalMemoryContext(operatorMemoryContext.localRevocableMemoryContext(), revocableMemoryFuture);
    }

    // caller should close this context as it's a new context
    public AggregatedMemoryContext newAggregateSystemMemoryContext()
    {
        return operatorMemoryContext.newAggregateSystemMemoryContext();
    }

    public long getReservedRevocableBytes()
    {
        return operatorMemoryContext.getRevocableMemory();
    }

    private static void updateMemoryFuture(ListenableFuture<?> memoryPoolFuture, AtomicReference<SettableFuture<?>> targetFutureReference)
    {
        if (!memoryPoolFuture.isDone()) {
            SettableFuture<?> currentMemoryFuture = targetFutureReference.get();
            while (currentMemoryFuture.isDone()) {
                SettableFuture<?> settableFuture = SettableFuture.create();
                // We can't replace one that's not done, because the task may be blocked on that future
                if (targetFutureReference.compareAndSet(currentMemoryFuture, settableFuture)) {
                    currentMemoryFuture = settableFuture;
                }
                else {
                    currentMemoryFuture = targetFutureReference.get();
                }
            }

            SettableFuture<?> finalMemoryFuture = currentMemoryFuture;
            // Create a new future, so that this operator can un-block before the pool does, if it's moved to a new pool
            Futures.addCallback(memoryPoolFuture, new FutureCallback<Object>()
            {
                @Override
                public void onSuccess(Object result)
                {
                    finalMemoryFuture.set(null);
                }

                @Override
                public void onFailure(Throwable t)
                {
                    finalMemoryFuture.set(null);
                }
            });
        }
    }

    public void destroy()
    {
        // reset memory revocation listener so that OperatorContext doesn't hold any references to Driver instance
        synchronized (this) {
            memoryRevocationRequestListener = null;
        }

        operatorMemoryContext.close();

        if (operatorMemoryContext.getSystemMemory() != 0) {
            throw new PrestoException(GENERIC_INTERNAL_ERROR, format("Operator %s has non-zero system memory (%d bytes) after destroy()", this, operatorMemoryContext.getSystemMemory()));
        }

        if (operatorMemoryContext.getUserMemory() != 0) {
            throw new PrestoException(GENERIC_INTERNAL_ERROR, format("Operator %s has non-zero user memory (%d bytes) after destroy()", this, operatorMemoryContext.getUserMemory()));
        }

        if (operatorMemoryContext.getRevocableMemory() != 0) {
            throw new PrestoException(GENERIC_INTERNAL_ERROR, format("Operator %s has non-zero revocable memory (%d bytes) after destroy()", this, operatorMemoryContext.getRevocableMemory()));
        }
    }

    public SpillContext getSpillContext()
    {
        return spillContext;
    }

    public void moreMemoryAvailable()
    {
        memoryFuture.get().set(null);
    }

    /**
     * This method is not thread safe. If multiple threads work on the same
     * transferredBytesMemoryContext instance it's possible that one of the writes
     * is lost by the last transferredBytesMemoryContext.setBytes() call.
     *
     * @param taskBytes The number of bytes to transfer from the OperatorContext to TaskContext.
     * @param transferredBytesMemoryContext This context should be created with {@link com.facebook.presto.operator.TaskContext#createNewTransferredBytesMemoryContext()}.
     */
    public void transferMemoryToTaskContext(long taskBytes, LocalMemoryContext transferredBytesMemoryContext)
    {
        checkArgument(taskBytes >= 0, "taskBytes is negative");
        long bytes = operatorMemoryContext.getUserMemory();
        long bytesBeforeTransfer = transferredBytesMemoryContext.getBytes();
        operatorMemoryContext.localUserMemoryContext().transferMemory(transferredBytesMemoryContext);
        try {
            transferredBytesMemoryContext.setBytes(transferredBytesMemoryContext.getBytes() + taskBytes - bytes);
        }
        catch (ExceededMemoryLimitException e) {
            // Since we can reserve an extra amount of memory above (when taskBytes > bytes),
            // ExceededMemoryLimitException can be thrown when reserving this extra amount.
            // This will happen after "bytes" is moved from the operator context to the task context.
            // At this point "bytes" isn't tracked by the operator context.
            // When drivers get destroyed, only memory tracked in its operators are freed.
            // Therefore, we have to cleanup the memory here by resetting the
            // state of the transferredBytesMemoryContext.
            transferredBytesMemoryContext.setBytes(bytesBeforeTransfer);
            throw e;
        }
    }

    public synchronized boolean isMemoryRevokingRequested()
    {
        return memoryRevokingRequested;
    }

    /**
     * Returns how much revocable memory will be revoked by the operator
     */
    public long requestMemoryRevoking()
    {
        long revokedMemory = 0L;
        Runnable listener = null;
        synchronized (this) {
            if (!isMemoryRevokingRequested() && operatorMemoryContext.getRevocableMemory() > 0) {
                memoryRevokingRequested = true;
                revokedMemory = operatorMemoryContext.getRevocableMemory();
                listener = memoryRevocationRequestListener;
            }
        }
        if (listener != null) {
            runListener(listener);
        }
        return revokedMemory;
    }

    public synchronized void resetMemoryRevokingRequested()
    {
        memoryRevokingRequested = false;
    }

    public void setMemoryRevocationRequestListener(Runnable listener)
    {
        requireNonNull(listener, "listener is null");

        boolean shouldNotify;
        synchronized (this) {
            checkState(memoryRevocationRequestListener == null, "listener already set");
            memoryRevocationRequestListener = listener;
            shouldNotify = memoryRevokingRequested;
        }
        // if memory revoking is requested immediately run the listener
        if (shouldNotify) {
            runListener(listener);
        }
    }

    private static void runListener(Runnable listener)
    {
        requireNonNull(listener, "listener is null");
        try {
            listener.run();
        }
        catch (RuntimeException e) {
            throw new PrestoException(GENERIC_INTERNAL_ERROR, "Exception while running the listener", e);
        }
    }

    public void setInfoSupplier(Supplier<OperatorInfo> infoSupplier)
    {
        requireNonNull(infoSupplier, "infoProvider is null");
        this.infoSupplier.set(infoSupplier);
    }

    public CounterStat getInputDataSize()
    {
        return inputDataSize;
    }

    public CounterStat getInputPositions()
    {
        return inputPositions;
    }

    public CounterStat getOutputDataSize()
    {
        return outputDataSize;
    }

    public CounterStat getOutputPositions()
    {
        return outputPositions;
    }

    public long getPhysicalWrittenDataSize()
    {
        return physicalWrittenDataSize.get();
    }

    @Override
    public String toString()
    {
        return format("%s-%s", operatorType, planNodeId);
    }

    public OperatorStats getOperatorStats()
    {
        Supplier<OperatorInfo> infoSupplier = this.infoSupplier.get();
        OperatorInfo info = Optional.ofNullable(infoSupplier).map(Supplier::get).orElse(null);

        long inputPositionsCount = inputPositions.getTotalCount();

        return new OperatorStats(
                driverContext.getPipelineContext().getPipelineId(),
                operatorId,
                planNodeId,
                operatorType,

                1,

                addInputCalls.get(),
                new Duration(addInputWallNanos.get(), NANOSECONDS).convertToMostSuccinctTimeUnit(),
                new Duration(addInputCpuNanos.get(), NANOSECONDS).convertToMostSuccinctTimeUnit(),
                new Duration(addInputUserNanos.get(), NANOSECONDS).convertToMostSuccinctTimeUnit(),
                succinctBytes(inputDataSize.getTotalCount()),
                inputPositionsCount,
                (double) inputPositionsCount * inputPositionsCount,

                getOutputCalls.get(),
                new Duration(getOutputWallNanos.get(), NANOSECONDS).convertToMostSuccinctTimeUnit(),
                new Duration(getOutputCpuNanos.get(), NANOSECONDS).convertToMostSuccinctTimeUnit(),
                new Duration(getOutputUserNanos.get(), NANOSECONDS).convertToMostSuccinctTimeUnit(),
                succinctBytes(outputDataSize.getTotalCount()),
                outputPositions.getTotalCount(),

                succinctBytes(physicalWrittenDataSize.get()),

                new Duration(blockedWallNanos.get(), NANOSECONDS).convertToMostSuccinctTimeUnit(),

                finishCalls.get(),
                new Duration(finishWallNanos.get(), NANOSECONDS).convertToMostSuccinctTimeUnit(),
                new Duration(finishCpuNanos.get(), NANOSECONDS).convertToMostSuccinctTimeUnit(),
                new Duration(finishUserNanos.get(), NANOSECONDS).convertToMostSuccinctTimeUnit(),

                succinctBytes(operatorMemoryContext.getUserMemory()),
                succinctBytes(getReservedRevocableBytes()),
                succinctBytes(operatorMemoryContext.getSystemMemory()),
                memoryFuture.get().isDone() ? Optional.empty() : Optional.of(WAITING_FOR_MEMORY),
                info);
    }

    public <C, R> R accept(QueryContextVisitor<C, R> visitor, C context)
    {
        return visitor.visitOperatorContext(this, context);
    }

    private long currentThreadUserTime()
    {
        if (!collectTimings) {
            return 0;
        }
        return THREAD_MX_BEAN.getCurrentThreadUserTime();
    }

    private long currentThreadCpuTime()
    {
        if (!collectTimings) {
            return 0;
        }
        return THREAD_MX_BEAN.getCurrentThreadCpuTime();
    }

    private static long nanosBetween(long start, long end)
    {
        return Math.abs(end - start);
    }

    private class BlockedMonitor
            implements Runnable
    {
        private final long start = System.nanoTime();
        private boolean finished;

        @Override
        public synchronized void run()
        {
            if (finished) {
                return;
            }
            finished = true;
            blockedMonitor.compareAndSet(this, null);
            blockedWallNanos.getAndAdd(getBlockedTime());
        }

        public long getBlockedTime()
        {
            return nanosBetween(start, System.nanoTime());
        }
    }

    @ThreadSafe
    private class OperatorSpillContext
            implements SpillContext
    {
        private final DriverContext driverContext;
        private final AtomicLong reservedBytes = new AtomicLong();

        public OperatorSpillContext(DriverContext driverContext)
        {
            this.driverContext = driverContext;
        }

        @Override
        public void updateBytes(long bytes)
        {
            if (bytes >= 0) {
                reservedBytes.addAndGet(bytes);
                driverContext.reserveSpill(bytes);
            }
            else {
                reservedBytes.accumulateAndGet(-bytes, this::decrementSpilledReservation);
                driverContext.freeSpill(-bytes);
            }
        }

        private long decrementSpilledReservation(long reservedBytes, long bytesBeingFreed)
        {
            checkArgument(bytesBeingFreed >= 0);
            checkArgument(bytesBeingFreed <= reservedBytes, "tried to free %s spilled bytes from %s bytes reserved", bytesBeingFreed, reservedBytes);
            return reservedBytes - bytesBeingFreed;
        }

        @Override
        public void close()
        {
            // Only products of SpillContext.newLocalSpillContext() should be closed.
            throw new UnsupportedOperationException(format("%s should not be closed directly", getClass()));
        }

        @Override
        public String toString()
        {
            return toStringHelper(this)
                    .add("usedBytes", reservedBytes.get())
                    .toString();
        }
    }

    class DecoratedLocalMemoryContext
            implements LocalMemoryContext
    {
        private final LocalMemoryContext delegate;
        private final AtomicReference<SettableFuture<?>> memoryFuture;

        public DecoratedLocalMemoryContext(LocalMemoryContext delegate, AtomicReference<SettableFuture<?>> memoryFuture)
        {
            this.delegate = requireNonNull(delegate, "delegate is null");
            this.memoryFuture = requireNonNull(memoryFuture, "memoryFuture is null");
        }

        @Override
        public long getBytes()
        {
            return delegate.getBytes();
        }

        @Override
        public ListenableFuture<?> setBytes(long bytes)
        {
            ListenableFuture<?> blocked = delegate.setBytes(bytes);
            updateMemoryFuture(blocked, memoryFuture);
            return blocked;
        }

        @Override
        public boolean trySetBytes(long bytes)
        {
            return delegate.trySetBytes(bytes);
        }

        @Override
        public void transferMemory(LocalMemoryContext to)
        {
            throw new UnsupportedOperationException();
        }

        @Override
        public void close()
        {
            throw new UnsupportedOperationException("Caller shouldn't call close on DecoratedLocalMemoryContext");
        }
    }

    @VisibleForTesting
    public MemoryTrackingContext getOperatorMemoryContext()
    {
        return operatorMemoryContext;
    }
}


text:
//===--- AdjointValue.h - Helper class for differentiation ----*- C++ -*---===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2019 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// AdjointValue - a symbolic representation for adjoint values enabling
// efficient differentiation by avoiding zero materialization.
//
//===----------------------------------------------------------------------===//

#ifndef SWIFT_SILOPTIMIZER_UTILS_DIFFERENTIATION_ADJOINTVALUE_H
#define SWIFT_SILOPTIMIZER_UTILS_DIFFERENTIATION_ADJOINTVALUE_H

#include "swift/AST/Decl.h"
#include "swift/SIL/SILValue.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/Support/Debug.h"

namespace swift {
namespace autodiff {

enum AdjointValueKind {
  /// An empty adjoint, i.e. zero. This case exists due to its special
  /// mathematical properties: `0 + x = x`. This is a guaranteed optimization
  /// when we combine a zero adjoint with another (e.g. differentiating a
  /// fanout).
  Zero,

  /// An aggregate of adjoint values: a struct or tuple.
  Aggregate,

  /// A concrete SIL value.
  Concrete,
};

class AdjointValue;

class AdjointValueBase {
  friend class AdjointValue;

  /// The kind of this adjoint value.
  AdjointValueKind kind;

  /// The type of this value as if it were materialized as a SIL value.
  SILType type;

  /// The underlying value.
  union Value {
    llvm::ArrayRef<AdjointValue> aggregate;
    SILValue concrete;
    Value(llvm::ArrayRef<AdjointValue> v) : aggregate(v) {}
    Value(SILValue v) : concrete(v) {}
    Value() {}
  } value;

  explicit AdjointValueBase(SILType type,
                            llvm::ArrayRef<AdjointValue> aggregate)
      : kind(AdjointValueKind::Aggregate), type(type), value(aggregate) {}

  explicit AdjointValueBase(SILValue v)
      : kind(AdjointValueKind::Concrete), type(v->getType()), value(v) {}

  explicit AdjointValueBase(SILType type)
      : kind(AdjointValueKind::Zero), type(type) {}
};

/// A symbolic adjoint value that is capable of representing zero value 0 and
/// 1, in addition to a materialized SILValue. This is expected to be passed
/// around by value in most cases, as it's two words long.
class AdjointValue final {

private:
  /// The kind of this adjoint value.
  AdjointValueBase *base;
  /*implicit*/ AdjointValue(AdjointValueBase *base = nullptr) : base(base) {}

public:
  AdjointValueBase *operator->() const { return base; }
  AdjointValueBase &operator*() const { return *base; }

  static AdjointValue createConcrete(llvm::BumpPtrAllocator &allocator,
                                     SILValue value) {
    return new (allocator.Allocate<AdjointValueBase>()) AdjointValueBase(value);
  }

  static AdjointValue createZero(llvm::BumpPtrAllocator &allocator,
                                 SILType type) {
    return new (allocator.Allocate<AdjointValueBase>()) AdjointValueBase(type);
  }

  static AdjointValue createAggregate(llvm::BumpPtrAllocator &allocator,
                                      SILType type,
                                      llvm::ArrayRef<AdjointValue> aggregate) {
    return new (allocator.Allocate<AdjointValueBase>())
        AdjointValueBase(type, aggregate);
  }

  AdjointValueKind getKind() const { return base->kind; }
  SILType getType() const { return base->type; }
  CanType getSwiftType() const { return getType().getASTType(); }

  NominalTypeDecl *getAnyNominal() const {
    return getSwiftType()->getAnyNominal();
  }

  bool isZero() const { return getKind() == AdjointValueKind::Zero; }
  bool isAggregate() const { return getKind() == AdjointValueKind::Aggregate; }
  bool isConcrete() const { return getKind() == AdjointValueKind::Concrete; }

  unsigned getNumAggregateElements() const {
    assert(isAggregate());
    return base->value.aggregate.size();
  }

  AdjointValue getAggregateElement(unsigned i) const {
    assert(isAggregate());
    return base->value.aggregate[i];
  }

  llvm::ArrayRef<AdjointValue> getAggregateElements() const {
    return base->value.aggregate;
  }

  SILValue getConcreteValue() const {
    assert(isConcrete());
    return base->value.concrete;
  }

  void print(llvm::raw_ostream &s) const {
    switch (getKind()) {
    case AdjointValueKind::Zero:
      s << "Zero[" << getType() << ']';
      break;
    case AdjointValueKind::Aggregate:
      s << "Aggregate[" << getType() << "](";
      if (auto *decl =
              getType().getASTType()->getStructOrBoundGenericStruct()) {
        interleave(
            llvm::zip(decl->getStoredProperties(), base->value.aggregate),
            [&s](std::tuple<VarDecl *, const AdjointValue &> elt) {
              s << std::get<0>(elt)->getName() << ": ";
              std::get<1>(elt).print(s);
            },
            [&s] { s << ", "; });
      } else if (getType().is<TupleType>()) {
        interleave(
            base->value.aggregate,
            [&s](const AdjointValue &elt) { elt.print(s); },
            [&s] { s << ", "; });
      } else {
        llvm_unreachable("Invalid aggregate");
      }
      s << ')';
      break;
    case AdjointValueKind::Concrete:
      s << "Concrete[" << getType() << "](" << base->value.concrete << ')';
      break;
    }
  }

  SWIFT_DEBUG_DUMP { print(llvm::dbgs()); };
};

inline llvm::raw_ostream &operator<<(llvm::raw_ostream &os,
                                     const AdjointValue &adjVal) {
  adjVal.print(os);
  return os;
}

} // end namespace autodiff
} // end namespace swift

#endif // SWIFT_SILOPTIMIZER_UTILS_DIFFERENTIATION_ADJOINTVALUE_H

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
    android:background="@android:color/holo_red_dark">

    <TextView android:text="@string/dangerous_activity_text" android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="@android:color/white"
        android:textSize="30sp"/>
</FrameLayout>


text:
package org.apache.hadoop.mapred.join;

import org.apache.hadoop.io.Writable;

/**
 * Writable type storing multiple {@link org.apache.hadoop.io.Writable}s.
 *
 * This is *not* a general-purpose tuple type. In almost all cases, users are
 * encouraged to implement their own serializable types, which can perform
 * better validation and provide more efficient encodings than this class is
 * capable. TupleWritable relies on the join framework for type safety and
 * assumes its instances will rarely be persisted, assumptions not only
 * incompatible with, but contrary to the general case.
 *
 * @see org.apache.hadoop.io.Writable
 *
 * @deprecated Use
 * {@link org.apache.hadoop.mapreduce.lib.join.TupleWritable} instead
 */
@Deprecated
public class TupleWritable
    extends org.apache.hadoop.mapreduce.lib.join.TupleWritable {

  /**
   * Create an empty tuple with no allocated storage for writables.
   */
  public TupleWritable() {
    super();
  }

  /**
   * Initialize tuple with storage; unknown whether any of them contain
   * "written" values.
   */
  public TupleWritable(Writable[] vals) {
    super(vals);
  }

  /**
   * Record that the tuple contains an element at the position provided.
   */
  void setWritten(int i) {
    written.set(i);
  }

  /**
   * Record that the tuple does not contain an element at the position
   * provided.
   */
  void clearWritten(int i) {
    written.clear(i);
  }

  /**
   * Clear any record of which writables have been written to, without
   * releasing storage.
   */
  void clearWritten() {
    written.clear();
  }

}


text:
namespace base {
namespace android {

typedef testing::Test PathUtilsTest;

namespace {
void ExpectEither(const std::string& expected1,
                  const std::string& expected2,
                  const std::string& actual) {
  EXPECT_TRUE(expected1 == actual || expected2 == actual)
      << "Value of: " << actual << std::endl
      << "Expected either: " << expected1 << std::endl
      << "or: " << expected2;
}
}  // namespace

TEST_F(PathUtilsTest, TestGetDataDirectory) {
  // The string comes from the Java side and depends on the APK
  // we are running in. Assumes that we are packaged in
  // org.chromium.native_test
  FilePath path;
  GetDataDirectory(&path);

  ExpectEither("/data/data/org.chromium.native_test/app_chrome",
               "/data/user/0/org.chromium.native_test/app_chrome",
               path.value());
}

TEST_F(PathUtilsTest, TestGetCacheDirectory) {
  // The string comes from the Java side and depends on the APK
  // we are running in. Assumes that we are packaged in
  // org.chromium.native_test
  FilePath path;
  GetCacheDirectory(&path);
  ExpectEither("/data/data/org.chromium.native_test/cache",
               "/data/user/0/org.chromium.native_test/cache",
               path.value());
}

TEST_F(PathUtilsTest, TestGetNativeLibraryDirectory) {
  // The string comes from the Java side and depends on the APK
  // we are running in. Assumes that the directory contains
  // the base tests shared object.
  FilePath path;
  GetNativeLibraryDirectory(&path);
  EXPECT_TRUE(
      base::PathExists(path.Append("libbase_unittests.so")) ||
      base::PathExists(path.Append("libbase_unittests.cr.so")) ||
      base::PathExists(path.Append("libbase_unittests__library.so")) ||
      base::PathExists(path.Append("libbase_unittests__library.cr.so")));
}

}  // namespace android
}  // namespace base


text:
using System;
using System.Threading.Tasks;
using Nimbus.Tests.Common;
using NUnit.Framework;

namespace Nimbus.IntegrationTests
{
    [TestFixture]
    [Timeout(15*1000)]
    public abstract class TestForBus
    {
        protected Bus Bus { get; private set; }

        [TestFixtureSetUp]
        public void TestFixtureSetUp()
        {
            Task.Run(async () =>
            {
                MethodCallCounter.Clear();

                Bus = await new TestHarnessBusFactory(GetType()).CreateAndStart();
                Console.WriteLine();
                Console.WriteLine();

                await Given();
                Console.WriteLine();
                Console.WriteLine();

                await When();
                MethodCallCounter.Stop();
                Console.WriteLine();
                Console.WriteLine();
            }).Wait();
        }

        [TestFixtureTearDown]
        public void TearDown()
        {
            Console.WriteLine();
            Console.WriteLine();
            Bus.Dispose();
        }

        protected virtual async Task Given()
        {
        }

        protected abstract Task When();
    }
}


text:
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Graphics.Urho3D.Input.Input(
    Input
  , MouseMode(..)
  -- * Touch State
  , TouchState
  , touchedElement
  , touchID
  , touchPosition
  , touchLastPosition
  , touchDelta
  , touchPressure
  -- * Joystick State
  , JoystickState(..)
  , HasJoystick(..)
  , HasJoystickID(..)
  , HasController(..)
  , HasScreenJoystick(..)
  , HasName(..)
  , HasButtons(..)
  , HasButtonPress(..)
  , HasAxes(..)
  , HasHats(..)
  , JoystickID
  , Joystick
  , GameController
  , SDL_Joystick
  , SDL_GameController
  , toSDLJoystick
  , toSDLController
  , fromSDLJoystick
  , fromSDLController
  -- * Input API
  , inputContext
  , mousePoistionOffscreen
  -- ** Input methods
  , inputUpdate
  , inputSetToggleFullscreen
  , inputSetMouseVisible
  , inputResetMouseVisible
  , inputSetMouseGrabbed
  , inputResetMouseGrabbed
  , inputSetMouseMode
  , inputResetMouseMode
  , inputAddScreenJoystick
  , inputRemoveScreenJoystick
  , inputSetScreenJoystickVisible
  , inputSetScreenKeyboardVisible
  , inputSetTouchEmulation
  , inputRecordGesture
  , inputSaveGestures
  , inputSaveGesture
  , inputLoadGestures
  , inputRemoveGesture
  , inputRemoveAllGestures
  , inputGetKeyFromName
  , inputGetKeyFromScancode
  , inputGetKeyName
  , inputGetScancodeFromKey
  , inputGetScancodeFromName
  , inputGetScancodeName
  , inputGetKeyDown
  , inputGetKeyPress
  , inputGetScancodeDown
  , inputGetScancodePress
  , inputGetMouseButtonDown
  , inputGetMouseButtonPress
  , inputGetQualifierDown
  , inputGetQualifierPress
  , inputGetQualifiers
  , inputGetMousePosition
  , inputGetMouseMove
  , inputGetMouseMoveX
  , inputGetMouseMoveY
  , inputGetMouseMoveWheel
  , inputGetNumTouches
  , inputGetTouch
  , inputGetNumJoysticks
  , inputGetJoystick
  , inputGetJoystickByIndex
  , inputGetJoystickByName
  , inputGetToggleFullscreen
  , inputIsScreenJoystickVisible
  , inputGetScreenKeyboardSupport
  , inputIsScreenKeyboardVisible
  , inputGetTouchEmulation
  , inputIsMouseVisible
  , inputIsMouseGrabbed
  , inputIsMouseLocked
  , inputGetMouseMode
  , inputHasFocus
  , inputIsMinimized
  ) where

import qualified Language.C.Inline as C
import qualified Language.C.Inline.Cpp as C

import Control.Lens
import Data.Monoid
import Foreign
import Foreign.C.String
import Graphics.Urho3D.Container.FlagSet
import Graphics.Urho3D.Container.ForeignVector
import Graphics.Urho3D.Container.Ptr
import Graphics.Urho3D.Container.Vector.Common
import Graphics.Urho3D.Core.Object
import Graphics.Urho3D.Input.InputConstants
import Graphics.Urho3D.Input.Internal.Input
import Graphics.Urho3D.IO.Deserializer
import Graphics.Urho3D.IO.Serializer
import Graphics.Urho3D.Math.Vector2
import Graphics.Urho3D.Monad
import Graphics.Urho3D.Parent
import Graphics.Urho3D.Resource.XMLFile
import Graphics.Urho3D.UI.Element
import System.IO.Unsafe (unsafePerformIO)
import Text.RawString.QQ

C.context (C.cppCtx
  <> inputCntx
  <> objectContext
  <> xmlFileContext
  <> vector2Context
  <> uiElementContext
  <> vectorContext
  <> serializerContext
  <> deserializerContext)

C.include "<Urho3D/Input/Input.h>"
C.using "namespace Urho3D"

C.verbatim "typedef WeakPtr<UIElement> WeakUIElement;"
C.verbatim "typedef PODVector<bool> PODVectorBool;"
C.verbatim "typedef PODVector<float> PODVectorFloat;"
C.verbatim "typedef PODVector<int> PODVectorInt;"

inputContext :: C.Context
inputContext = objectContext <> inputCntx <> vector2Context

deriveParent ''Object ''Input

instance Subsystem Input where
  getSubsystemImpl ptr = [C.exp| Input* { $(Object* ptr)->GetSubsystem<Input>() } |]

C.verbatim [r|
template <class T>
class Traits
{
public:
    struct AlignmentFinder
    {
      char a;
      T b;
    };

    enum {AlignmentOf = sizeof(AlignmentFinder) - sizeof(T)};
};
|]

instance Storable TouchState where
  sizeOf _ = fromIntegral $ [C.pure| int { (int)sizeof(TouchState) } |]
  alignment _ = fromIntegral $ [C.pure| int { (int)Traits<TouchState>::AlignmentOf } |]
  peek ptr = do
    tid <- fromIntegral <$> [C.exp| int { $(TouchState* ptr)->touchID_ } |]
    pv <- peek =<< [C.exp| IntVector2* { &$(TouchState* ptr)->position_ } |]
    lpv <- peek =<< [C.exp| IntVector2* { &$(TouchState* ptr)->lastPosition_ } |]
    dv <- peek =<< [C.exp| IntVector2* { &$(TouchState* ptr)->delta_ } |]
    pr <- realToFrac <$> [C.exp| float { $(TouchState* ptr)->pressure_ } |]
    e <- peekWeakPtr =<< [C.exp| WeakUIElement* { new WeakPtr<UIElement>($(TouchState* ptr)->touchedElement_) }|]
    return $ TouchState e tid pv lpv dv pr

  poke ptr ts = do
    with (ts ^. touchPosition) $ \pv ->
      with (ts ^. touchLastPosition) $ \lpv ->
        with (ts ^. touchDelta) $ \dv -> do
          let tid = fromIntegral $ ts ^. touchID
              pr = realToFrac $ ts ^. touchPressure
              e = parentPointer $ ts ^. touchedElement
          [C.block| void {
            $(TouchState* ptr)->touchID_ = $(float tid);
            $(TouchState* ptr)->position_ = *$(IntVector2* pv);
            $(TouchState* ptr)->lastPosition_ = *$(IntVector2* lpv);
            $(TouchState* ptr)->delta_ = *$(IntVector2* dv);
            $(TouchState* ptr)->pressure_ = $(float pr);
            $(TouchState* ptr)->touchedElement_ = WeakPtr<UIElement>($(UIElement* e));
          } |]

instance Storable JoystickState where
  sizeOf _ = fromIntegral $ [C.pure| int { (int)sizeof(JoystickState) } |]
  alignment _ = fromIntegral $ [C.pure| int { (int)Traits<JoystickState>::AlignmentOf } |]
  peek ptr = do
    _joystickStateJoystick <- toSDLJoystick <$> [C.exp| SDL_Joystick* {$(JoystickState* ptr)->joystick_} |]
    _joystickStateJoystickID <- fromIntegral <$> [C.exp| int {(int)$(JoystickState* ptr)->joystickID_} |]
    _joystickStateController <- toSDLController <$> [C.exp| SDL_GameController* {$(JoystickState* ptr)->controller_} |]
    _joystickStateScreenJoystick <- [C.exp| UIElement* {$(JoystickState* ptr)->screenJoystick_} |]
    _joystickStateName <- peekCString =<< [C.exp| const char* {$(JoystickState* ptr)->name_.CString()} |]
    _joystickStateButtons <- peekForeignVectorAs =<< [C.exp| PODVectorBool* {&$(JoystickState* ptr)->buttons_} |]
    _joystickStateButtonPress <- peekForeignVectorAs =<< [C.exp| PODVectorBool* {&$(JoystickState* ptr)->buttonPress_} |]
    _joystickStateAxes <- peekForeignVectorAs =<< [C.exp| PODVectorFloat* {&$(JoystickState* ptr)->axes_} |]
    _joystickStateHats <- peekForeignVectorAs =<< [C.exp| PODVectorInt* {&$(JoystickState* ptr)->hats_} |]
    return $ JoystickState {..}

  poke ptr JoystickState{..} =
    withCString _joystickStateName $ \_joystickStateName' ->
    withForeignVector () _joystickStateButtons $ \_joystickStateButtons' ->
    withForeignVector () _joystickStateButtonPress $ \_joystickStateButtonPress' ->
    withForeignVector () _joystickStateAxes $ \_joystickStateAxes' ->
    withForeignVector () _joystickStateHats $ \_joystickStateHats' ->
      [C.block| void {
        $(JoystickState* ptr)->joystick_ = $(SDL_Joystick* _joystickStateJoystick');
        $(JoystickState* ptr)->joystickID_ = (SDL_JoystickID)$(int _joystickStateJoystickID');
        $(JoystickState* ptr)->controller_ = $(SDL_GameController* _joystickStateController');
        $(JoystickState* ptr)->screenJoystick_ = $(UIElement* _joystickStateScreenJoystick');
        $(JoystickState* ptr)->name_ = String($(const char* _joystickStateName'));
        $(JoystickState* ptr)->buttons_ = PODVectorBool(*$(PODVectorBool* _joystickStateButtons'));
        $(JoystickState* ptr)->buttonPress_ = PODVectorBool(*$(PODVectorBool* _joystickStateButtonPress'));
        $(JoystickState* ptr)->axes_ = PODVectorFloat(*$(PODVectorFloat* _joystickStateAxes'));
        $(JoystickState* ptr)->hats_ = PODVectorInt(*$(PODVectorInt* _joystickStateHats'));
      } |]
    where
    _joystickStateJoystick' = fromSDLJoystick _joystickStateJoystick
    _joystickStateJoystickID' = fromIntegral _joystickStateJoystickID
    _joystickStateController' = fromSDLController _joystickStateController
    _joystickStateScreenJoystick' = _joystickStateScreenJoystick

mousePoistionOffscreen :: IntVector2
mousePoistionOffscreen = unsafePerformIO $ peek =<< [C.exp| const IntVector2* {&MOUSE_POSITION_OFFSCREEN} |]

-- | Poll for window messages. Called by HandleBeginFrame().
inputUpdate :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> m ()
inputUpdate p = liftIO $ do
  let ptr = parentPointer p
  [C.exp| void { $(Input* ptr)->Update() } |]

-- | Set whether ALT-ENTER fullscreen toggle is enabled.
inputSetToggleFullscreen :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> Bool -- ^ enable
  -> m ()
inputSetToggleFullscreen p e = liftIO $ do
  let ptr = parentPointer p
      e' = fromBool e
  [C.exp| void { $(Input* ptr)->SetToggleFullscreen($(int e')) } |]

-- | Set whether the operating system mouse cursor is visible. When not visible (default), is kept centered to prevent leaving the window. Mouse visibility event can be suppressed-- this also recalls any unsuppressed SetMouseVisible which can be returned by ResetMouseVisible().
inputSetMouseVisible :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> Bool -- ^ Flag of visibility for mouse
  -> Bool -- ^ supress event (def false)
  -> m ()
inputSetMouseVisible p flag se = liftIO $ do
  let ptr = parentPointer p
      flag' = fromBool flag
      se' = fromBool se
  [C.exp| void { $(Input* ptr)->SetMouseVisible($(int flag'), $(int se')) } |]

-- | Reset last mouse visibility that was not suppressed in SetMouseVisible.
inputResetMouseVisible :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> m ()
inputResetMouseVisible p = liftIO $ do
  let ptr = parentPointer p
  [C.exp| void { $(Input* ptr)->ResetMouseVisible() } |]

-- | Set whether the mouse is currently being grabbed by an operation.
inputSetMouseGrabbed :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> Bool -- ^ grab
  -> Bool -- ^ supress event (def false)
  -> m ()
inputSetMouseGrabbed p gr se = liftIO $ do
  let ptr = parentPointer p
      se' = fromBool se
      gr' = fromBool gr
  [C.exp| void { $(Input* ptr)->SetMouseGrabbed($(int gr'), $(int se')) } |]

-- | Reset the mouse grabbed to the last unsuppressed SetMouseGrabbed call
inputResetMouseGrabbed :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> m ()
inputResetMouseGrabbed p = liftIO $ do
  let ptr = parentPointer p
  [C.exp| void { $(Input* ptr)->ResetMouseGrabbed() } |]

-- | Set the mouse mode.
--
-- Set the mouse mode behaviour.
--
-- MM_ABSOLUTE is the default behaviour, allowing the toggling of operating system cursor visibility and allowing the cursor to escape the window when visible.
-- When the operating system cursor is invisible in absolute mouse mode, the mouse is confined to the window.
-- If the operating system and UI cursors are both invisible, interaction with the Urho UI will be limited (eg: drag move / drag end events will not trigger).
-- SetMouseMode(MM_ABSOLUTE) will call SetMouseGrabbed(false).
--
-- MM_RELATIVE sets the operating system cursor to invisible and confines the cursor to the window.
-- The operating system cursor cannot be set to be visible in this mode via SetMouseVisible(), however changes are tracked and will be restored when another mouse mode is set.
-- When the virtual cursor is also invisible, UI interaction will still function as normal (eg: drag events will trigger).
-- SetMouseMode(MM_RELATIVE) will call SetMouseGrabbed(true).
--
-- MM_WRAP grabs the mouse from the operating system and confines the operating system cursor to the window, wrapping the cursor when it is near the edges.
-- SetMouseMode(MM_WRAP) will call SetMouseGrabbed(true).
--
-- MM_FREE does not grab/confine the mouse cursor even when it is hidden. This can be used for cases where the cursor should render using the operating system
-- outside the window, and perform custom rendering (with SetMouseVisible(false)) inside.
inputSetMouseMode :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> MouseMode -- ^ mode
  -> Bool -- ^ supress event (default false)
  -> m ()
inputSetMouseMode p mm se = liftIO $ do
  let ptr = parentPointer p
      mm' = fromIntegral . fromEnum $ mm
      se' = fromBool se
  [C.exp| void { $(Input* ptr)->SetMouseMode((MouseMode)$(int mm'), $(int se')) } |]

-- | Reset the last mouse mode that wasn't suppressed in SetMouseMode
inputResetMouseMode :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> m ()
inputResetMouseMode p = liftIO $ do
  let ptr = parentPointer p
  [C.exp| void { $(Input* ptr)->ResetMouseMode() } |]

-- | Add screen joystick.
--
-- Return the joystick instance ID when successful or negative on error.
-- If layout file is not given, use the default screen joystick layout.
-- If style file is not given, use the default style file from root UI element.
--
-- This method should only be called in main thread.
inputAddScreenJoystick :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> Ptr XMLFile -- ^ layout file, could be nullPtr
  -> Ptr XMLFile -- ^ style file, could be nullPtr
  -> m JoystickID -- ^ Joystick ID
inputAddScreenJoystick p layoutFile styleFile = liftIO $ do
  let ptr = parentPointer p
  fromIntegral <$> [C.exp| SDL_JoystickID { $(Input* ptr)->AddScreenJoystick($(XMLFile* layoutFile), $(XMLFile* styleFile)) } |]

-- | Remove screen joystick by instance ID.
-- Return true if successful.
--
-- This method should only be called in main thread.
inputRemoveScreenJoystick :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> JoystickID -- ^ id
  -> m ()
inputRemoveScreenJoystick p i = liftIO $ do
  let ptr = parentPointer p
      i' = fromIntegral i
  [C.exp| void { $(Input* ptr)->RemoveScreenJoystick((SDL_JoystickID)$(int i')) } |]

-- | Set whether the virtual joystick is visible.
inputSetScreenJoystickVisible :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> JoystickID -- ^ id
  -> Bool -- ^ enable
  -> m ()
inputSetScreenJoystickVisible p i e = liftIO $ do
  let ptr = parentPointer p
      i' = fromIntegral i
      e' = fromBool e
  [C.exp| void { $(Input* ptr)->SetScreenJoystickVisible((SDL_JoystickID)$(int i'), $(int e') != 0) } |]

-- | Show or hide on-screen keyboard on platforms that support it. When shown, keypresses from it are delivered as key events.
inputSetScreenKeyboardVisible :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> Bool -- ^ enable
  -> m ()
inputSetScreenKeyboardVisible p e = liftIO $ do
  let ptr = parentPointer p
      e' = fromBool e
  [C.exp| void { $(Input* ptr)->SetScreenKeyboardVisible($(int e')) } |]

-- | Set touch emulation by mouse. Only available on desktop platforms. When enabled, actual mouse events are no longer sent and the mouse cursor is forced visible.
inputSetTouchEmulation :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> Bool -- ^ enable
  -> m ()
inputSetTouchEmulation p e = liftIO $ do
  let ptr = parentPointer p
      e' = fromBool e
  [C.exp| void { $(Input* ptr)->SetTouchEmulation($(int e')) } |]

-- | Begin recording a touch gesture. Return true if successful. The E_GESTURERECORDED event (which contains the ID for the new gesture) will be sent when recording finishes.
inputRecordGesture :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> m Bool
inputRecordGesture p = liftIO $ do
  let ptr = parentPointer p
  toBool <$> [C.exp| int { (int) $(Input* ptr)->RecordGesture() } |]

-- | Save all in-memory touch gestures. Return true if successful.
inputSaveGestures :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> Ptr Serializer -- ^ dest
  -> m  Bool
inputSaveGestures p s = liftIO $ do
  let ptr = parentPointer p
  toBool <$> [C.exp| int { (int) $(Input* ptr)->SaveGestures(*$(Serializer* s)) } |]

-- | Save a specific in-memory touch gesture to a file. Return true if successful.
inputSaveGesture :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> Ptr Serializer -- ^ dest
  -> Word -- ^ gesture id
  -> m Bool
inputSaveGesture p s gid = liftIO $ do
  let ptr = parentPointer p
      gid' = fromIntegral gid
  toBool <$> [C.exp| int { (int) $(Input* ptr)->SaveGesture(*$(Serializer* s), $(unsigned int gid')) } |]

-- | Load touch gestures from a file. Return number of loaded gestures, or 0 on failure.
inputLoadGestures :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> Ptr Deserializer -- ^ source
  -> m Word
inputLoadGestures p d = liftIO $ do
  let ptr = parentPointer p
  fromIntegral <$> [C.exp| unsigned int { $(Input* ptr)->LoadGestures(*$(Deserializer* d)) } |]

-- | Remove an in-memory gesture by ID. Return true if was found.
inputRemoveGesture :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> Word -- ^ gesture id
  -> m Bool
inputRemoveGesture p gid = liftIO $ do
  let ptr = parentPointer p
      gid' = fromIntegral gid
  toBool <$> [C.exp| int { (int) $(Input* ptr)->RemoveGesture($(unsigned int gid')) } |]

-- | Remove all in-memory gestures.
inputRemoveAllGestures :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> m ()
inputRemoveAllGestures p = liftIO $ do
  let ptr = parentPointer p
  [C.exp| void { $(Input* ptr)->RemoveAllGestures() } |]

-- | Return keycode from key name.
inputGetKeyFromName :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> String -- ^ name
  -> m Key
inputGetKeyFromName p n = liftIO $ withCString n $ \n' -> do
  let ptr = parentPointer p
  toEnum . fromIntegral <$> [C.exp| int { $(Input* ptr)->GetKeyFromName(String($(const char* n'))) } |]

-- | Return keycode from scancode.
inputGetKeyFromScancode :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> Scancode -- ^ scancode
  -> m Key
inputGetKeyFromScancode p sc = liftIO $ do
  let ptr = parentPointer p
      sc' = fromIntegral . fromEnum $ sc
  toEnum . fromIntegral <$> [C.exp| int { $(Input* ptr)->GetKeyFromScancode((Scancode)$(int sc')) } |]

-- | Return name of key from keycode.
inputGetKeyName :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> Key -- ^ key
  -> m String
inputGetKeyName p k = liftIO $ do
  let ptr = parentPointer p
      k' = fromIntegral . fromEnum $ k
  peekCString =<< [C.exp| const char* { $(Input* ptr)->GetKeyName((Key)$(int k')).CString() } |]

-- | Return scancode from keycode.
inputGetScancodeFromKey :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> Key -- ^ key
  -> m Scancode
inputGetScancodeFromKey p k = liftIO $ do
  let ptr = parentPointer p
      k' = fromIntegral . fromEnum $ k
  toEnum . fromIntegral <$> [C.exp| int { (int)$(Input* ptr)->GetScancodeFromKey((Key)$(int k')) } |]

-- | Return scancode from key name.
inputGetScancodeFromName :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> String -- ^ name
  -> m Scancode
inputGetScancodeFromName p n = liftIO $ withCString n $ \n' -> do
  let ptr = parentPointer p
  toEnum . fromIntegral <$> [C.exp| int { (int)$(Input* ptr)->GetScancodeFromName(String($(const char* n'))) } |]

-- | Return name of key from scancode.
inputGetScancodeName :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> Scancode -- ^ scancode
  -> m String
inputGetScancodeName p sc = liftIO $ do
  let ptr = parentPointer p
      sc' = fromIntegral . fromEnum $ sc
  peekCString =<< [C.exp| const char* { $(Input* ptr)->GetScancodeName((Scancode)$(int sc')).CString() } |]

-- | Check if a key is held down.
inputGetKeyDown :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> Key -- ^ Key to test
  -> m Bool
inputGetKeyDown p k = liftIO $ do
  let ptr = parentPointer p
      ki = fromIntegral . fromEnum $ k
  toBool <$> [C.exp| int { (int)$(Input* ptr)->GetKeyDown((Key)$(int ki)) } |]

-- | Check if a key has been pressed on this frame.
inputGetKeyPress :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> Key -- ^ key
  -> m Bool
inputGetKeyPress p k = liftIO $ do
  let ptr = parentPointer p
      k' = fromIntegral . fromEnum $ k
  toBool <$> [C.exp| int { (int)$(Input* ptr)->GetKeyPress((Key)$(int k')) } |]

-- | Check if a key is held down by scancode.
inputGetScancodeDown :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> Scancode -- ^ scancode
  -> m Bool
inputGetScancodeDown p sc = liftIO $ do
  let ptr = parentPointer p
      sc' = fromIntegral . fromEnum $ sc
  toBool <$> [C.exp| int { (int)$(Input* ptr)->GetScancodeDown((Scancode)$(int sc')) } |]

-- | Check if a key has been pressed on this frame by scancode.
inputGetScancodePress :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> Scancode -- ^ scancode
  -> m Bool
inputGetScancodePress p sc = liftIO $ do
  let ptr = parentPointer p
      sc' = fromIntegral . fromEnum $ sc
  toBool <$> [C.exp| int { (int)$(Input* ptr)->GetScancodePress((Scancode)$(int sc')) } |]

-- |  Check if a mouse button is held down.
inputGetMouseButtonDown :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> MouseButton -- ^ button
  -> m Bool
inputGetMouseButtonDown p b = liftIO $ do
  let ptr = parentPointer p
      b' = fromIntegral . fromEnum $ b
  toBool <$> [C.exp| int { (int)$(Input* ptr)->GetMouseButtonDown((MouseButton)$(int b')) } |]

-- | Check if a mouse button has been pressed on this frame.
inputGetMouseButtonPress :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> MouseButton -- ^ button
  -> m Bool
inputGetMouseButtonPress p b = liftIO $ do
  let ptr = parentPointer p
      b' = fromIntegral . fromEnum $ b
  toBool <$> [C.exp| int { (int)$(Input* ptr)->GetMouseButtonPress((MouseButton)$(int b')) } |]

-- | Check if a qualifier key is held down.
inputGetQualifierDown :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> Qualifier -- ^ qualifier
  -> m Bool
inputGetQualifierDown p q = liftIO $ do
  let ptr = parentPointer p
      q' = fromIntegral . fromEnum $ q
  toBool <$> [C.exp| int { (int)$(Input* ptr)->GetQualifierDown((Qualifier)$(int q')) } |]

-- | Check if a qualifier key has been pressed on this frame.
inputGetQualifierPress :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> Qualifier -- ^ qualifier
  -> m Bool
inputGetQualifierPress p q = liftIO $ do
  let ptr = parentPointer p
      q' = fromIntegral . fromEnum $ q
  toBool <$> [C.exp| int { (int)$(Input* ptr)->GetQualifierPress((Qualifier)$(int q')) } |]

-- | Return the currently held down qualifiers.
inputGetQualifiers :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> m QualifierFlags
inputGetQualifiers p = liftIO $ do
  let ptr = parentPointer p
  FlagSet . fromIntegral <$> [C.exp| unsigned int { (unsigned)$(Input* ptr)->GetQualifiers() } |]

-- | Return mouse position within window. Should only be used with a visible mouse cursor.
inputGetMousePosition :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> m IntVector2
inputGetMousePosition p = liftIO $ alloca $ \vptr -> do
  let ptr = parentPointer p
  [C.exp| void { *($(IntVector2* vptr)) = $(Input* ptr)->GetMousePosition() } |]
  peek vptr

-- | Return mouse movement since last frame.
inputGetMouseMove :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> m IntVector2
inputGetMouseMove p = liftIO $ alloca $ \vptr -> do
  let ptr = parentPointer p
  [C.exp| void { *($(IntVector2* vptr)) = $(Input* ptr)->GetMouseMove(); } |]
  peek vptr

-- | Return horizontal mouse movement since last frame.
inputGetMouseMoveX :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> m Int
inputGetMouseMoveX p = liftIO $ do
  let ptr = parentPointer p
  fromIntegral <$> [C.exp| int { $(Input* ptr)->GetMouseMoveX() } |]

-- | Return vertical mouse movement since last frame.
inputGetMouseMoveY :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> m Int
inputGetMouseMoveY p = liftIO $ do
  let ptr = parentPointer p
  fromIntegral <$> [C.exp| int { $(Input* ptr)->GetMouseMoveY() } |]

-- | Return mouse wheel movement since last frame.
inputGetMouseMoveWheel :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> m Int
inputGetMouseMoveWheel p = liftIO $ do
  let ptr = parentPointer p
  fromIntegral <$> [C.exp| int { $(Input* ptr)->GetMouseMoveWheel() } |]

-- | Return number of active finger touches.
inputGetNumTouches :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> m Word
inputGetNumTouches p = liftIO $ do
  let ptr = parentPointer p
  fromIntegral <$> [C.exp| unsigned int {$(Input* ptr)->GetNumTouches()}|]

-- | Return active finger touch by index.
inputGetTouch :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> Word
  -> m (Maybe TouchState)
inputGetTouch p i = liftIO $ do
  let ptr = parentPointer p
      i' = fromIntegral i
  ts <- [C.exp| TouchState* {$(Input* ptr)->GetTouch($(unsigned int i'))} |]
  checkNullPtr' ts peek

-- | Return number of connected joysticks.
inputGetNumJoysticks :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> m Int
inputGetNumJoysticks p = liftIO $ do
  let ptr = parentPointer p
  fromIntegral <$> [C.exp| int { $(Input* ptr)->GetNumJoysticks() } |]

-- | Return joystick state by ID, or null if does not exist.
inputGetJoystick :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> JoystickID -- ^ id
  -> m (Maybe (Ptr JoystickState))
inputGetJoystick p i = liftIO $ do
  let ptr = parentPointer p
      i' = fromIntegral i
  sp <- [C.exp| JoystickState* { $(Input* ptr)->GetJoystick($(SDL_JoystickID i')) } |]
  checkNullPtr' sp return

-- | Return joystick state by index, or null if does not exist. 0 = first connected joystick.
inputGetJoystickByIndex :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> Word -- ^ index
  -> m (Maybe (Ptr JoystickState))
inputGetJoystickByIndex p i = liftIO $ do
  let ptr = parentPointer p
      i' = fromIntegral i
  sp <- [C.exp| JoystickState* { $(Input* ptr)->GetJoystickByIndex($(unsigned int i')) } |]
  checkNullPtr' sp return

-- | Return joystick state by name, or null if does not exist.
inputGetJoystickByName :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> String -- ^ name
  -> m (Maybe (Ptr JoystickState))
inputGetJoystickByName p n = liftIO $ withCString n $ \n' -> do
  let ptr = parentPointer p
  sp <- [C.exp| JoystickState* { $(Input* ptr)->GetJoystickByName(String($(const char* n'))) } |]
  checkNullPtr' sp return

-- | Return whether fullscreen toggle is enabled.
inputGetToggleFullscreen :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> m Bool
inputGetToggleFullscreen p = liftIO $ do
  let ptr = parentPointer p
  toBool <$> [C.exp| int { (int)$(Input* ptr)->GetToggleFullscreen() } |]

-- | Return whether a virtual joystick is visible.
inputIsScreenJoystickVisible :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> JoystickID -- ^ id
  -> m Bool
inputIsScreenJoystickVisible p i = liftIO $ do
  let ptr = parentPointer p
      i' = fromIntegral i
  toBool <$> [C.exp| int { (int) $(Input* ptr)->IsScreenJoystickVisible((SDL_JoystickID)$(int i')) } |]

-- | Return whether on-screen keyboard is supported.
inputGetScreenKeyboardSupport :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> m Bool
inputGetScreenKeyboardSupport p = liftIO $ do
  let ptr = parentPointer p
  toBool <$> [C.exp| int { (int) $(Input* ptr)->GetScreenKeyboardSupport() } |]

-- | Return whether on-screen keyboard is being shown.
inputIsScreenKeyboardVisible :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> m Bool
inputIsScreenKeyboardVisible p = liftIO $ do
  let ptr = parentPointer p
  toBool <$> [C.exp| int { (int) $(Input* ptr)->IsScreenKeyboardVisible() } |]

-- | Return whether touch emulation is enabled.
inputGetTouchEmulation :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> m Bool
inputGetTouchEmulation p = liftIO $ do
  let ptr = parentPointer p
  toBool <$> [C.exp| int { (int) $(Input* ptr)->GetTouchEmulation() } |]

-- | Return whether the operating system mouse cursor is visible.
inputIsMouseVisible :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> m Bool
inputIsMouseVisible p = liftIO $ do
  let ptr = parentPointer p
  toBool <$> [C.exp| int { (int) $(Input* ptr)->IsMouseVisible() } |]

-- | Return whether the mouse is currently being grabbed by an operation.
inputIsMouseGrabbed :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> m Bool
inputIsMouseGrabbed p = liftIO $ do
  let ptr = parentPointer p
  toBool <$> [C.exp| int { (int) $(Input* ptr)->IsMouseGrabbed() } |]

-- | Return whether the mouse is locked to the window
inputIsMouseLocked :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> m Bool
inputIsMouseLocked p = liftIO $ do
  let ptr = parentPointer p
  toBool <$> [C.exp| int { (int) $(Input* ptr)->IsMouseLocked() } |]

-- | Return the mouse mode.
inputGetMouseMode :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> m MouseMode
inputGetMouseMode p = liftIO $ do
  let ptr = parentPointer p
  toEnum . fromIntegral <$> [C.exp| int { (int)$(Input* ptr)->GetMouseMode() } |]

-- | Return whether application window has input focus.
inputHasFocus :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> m Bool
inputHasFocus p = liftIO $ do
  let ptr = parentPointer p
  toBool <$> [C.exp| int { (int) $(Input* ptr)->HasFocus() } |]

-- | Return whether application window is minimized.
inputIsMinimized :: (Parent Input a, Pointer p a, MonadIO m)
  => p -- ^ Pointer to Input or ascentor
  -> m Bool
inputIsMinimized p = liftIO $ do
  let ptr = parentPointer p
  toBool <$> [C.exp| int { (int) $(Input* ptr)->IsMinimized() } |]


text:
package com.surya.quakealert;

import android.database.Cursor;
import android.support.annotation.IntDef;
import android.support.annotation.Nullable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.surya.quakealert.data.QuakeContract;
import com.surya.quakealert.sync.QuakeSyncAdapter;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A placeholder fragment containing a simple view.
 */
public class MainActivityFragment extends Fragment implements
        QuakeAdapter.ListItemClickListener,LoaderManager.LoaderCallbacks<Cursor> {

    private static final String TAG = MainActivityFragment.class.getSimpleName();
    private Unbinder unbinder;
    @BindView(R.id.quake_recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.error_message)
    TextView tv;
    @BindView(R.id.adView)
    AdView mAdView;
    private QuakeAdapter mQuakeAdapter;

    @Retention(RetentionPolicy.SOURCE)
    @IntDef({QUAKE_STATUS_OK, QUAKE_SERVER_DOWN, QUAKE_STATUS_SERVER_INVALID, QUAKE_STATUS_INVALID})
    public @interface QuakeStatus {}

    public static final int QUAKE_STATUS_OK = 0;
    public static final int QUAKE_SERVER_DOWN = 1;
    public static final int QUAKE_STATUS_SERVER_INVALID = 2;
    public static final int QUAKE_STATUS_INVALID = 3;

    public interface QuakeClickListener{

        void OnItemClick(int position, QuakeAdapter.QuakeViewHolder holder);

    }

    public MainActivityFragment() {
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        getLoaderManager().initLoader(1, null, this);
        super.onActivityCreated(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView =  inflater.inflate(R.layout.fragment_main, container, false);

        unbinder = ButterKnife.bind(this,rootView);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());

        AdRequest adRequest = new AdRequest.Builder()
                .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
                .addTestDevice("4215BD5E098396AB228F6CBEF9C2516A")
                .build();
        if(mAdView != null)
            mAdView.loadAd(adRequest);

        mQuakeAdapter = new QuakeAdapter(getActivity(),null,this);

        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mRecyclerView.getContext(),
                layoutManager.getOrientation());
        mRecyclerView.addItemDecoration(dividerItemDecoration);
        mRecyclerView.setLayoutManager(layoutManager);

        mRecyclerView.setAdapter(mQuakeAdapter);

        return rootView;
    }

    @Override
    public void onPause() {
        if (mAdView != null) {
            mAdView.pause();
        }
        super.onPause();
    }

    @Override
    public void onResume() {

        if (mAdView != null) {
            mAdView.resume();
        }
        super.onResume();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mAdView != null)
            mAdView.destroy();
        unbinder.unbind();
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {

        String selection = QuakeContract.QuakeEntry.COLUMN_QUAKE_MAGNITUDE + " >= ?";
        String sortOrder = QuakeContract.QuakeEntry.COLUMN_QUAKE_MAGNITUDE + " DESC";

        return new CursorLoader(getActivity(),
                                QuakeContract.QuakeEntry.CONTENT_URI,
                                null,
                                selection,
                                new String[]{Utility.getPreference(getActivity(),getString(R.string.quake_order_by_key))},
                                sortOrder);

    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        updateEmptyView();
        if (data.getCount() > 0)
            tv.setVisibility(View.GONE);
        else
            tv.setVisibility(View.VISIBLE);
        mQuakeAdapter.swapCursor(data);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        mQuakeAdapter.swapCursor(null);
    }

    @Override
    public void onListItemClick(int position, QuakeAdapter.QuakeViewHolder holder) {
        Cursor cursor = mQuakeAdapter.getCursor();
        cursor.moveToPosition(position);
        ((QuakeClickListener)getActivity()).OnItemClick(cursor.getInt(0),holder);
    }

    private void updateEmptyView() {
        if ( mQuakeAdapter.getItemCount() == 0 ) {

            if ( null != tv ) {

                tv.setVisibility(View.VISIBLE);
                int message = R.string.empty_quake_list;
                @QuakeSyncAdapter.QuakeStatus int location = Utility.getLocationStatus(getActivity());
                switch (location) {
                    case QuakeSyncAdapter.QUAKE_SERVER_DOWN:
                        message = R.string.empty_quake_list_server_down;
                        break;
                    case QuakeSyncAdapter.QUAKE_STATUS_SERVER_INVALID:
                        message = R.string.empty_quake_list_server_error;
                        break;
                    case QuakeSyncAdapter.QUAKE_STATUS_INVALID:
                        message = R.string.empty_quake_list;
                        break;
                    default:
                        if (!Utility.isNetworkAvailable(getActivity())) {
                            message = R.string.empty_quake_list_no_network;
                        }
                }
                tv.setText(message);
            }
        }
    }
}


text:
<editor>
    <help>https://docs.cloudbees.com/docs/cloudbees-cd/latest/plugins/ec-websphere#DeleteJMSActivationSpec</help>
    <formElement>
        <type>entry</type>
        Configuration Name:

        <configuration>1</configuration>

        <property>configname</property>
        <propertyReference>/plugins/@PLUGIN_NAME@/project/websphere_cfgs</propertyReference>
        <documentation>Name of the configuration to be used. URL, port and credentials are retrieved from the given configuration. To view or create a new configuration, go to the Administration -> Plugins tab, and select 'Configure' action for @PLUGIN_KEY@ plugin.</documentation>
        <htmlDocumentation>Name of the configuration to be used. URL, port and credentials are retrieved from the given configuration.</htmlDocumentation>
        <required>1</required>
    </formElement>
    <formElement>
        Messaging System Type:
        <property>messagingSystemType</property>
        <type>select</type>
        <option><name>WMQ</name><value>WMQ</value></option>
        <option><name>SIB</name><value>SIB</value></option>
        <required>1</required>
        <documentation>The name of the messaging provider. Pass in either WMQ or SIB.</documentation>
    </formElement>
    <formElement>
        Scope of the Activation Spec:
        <property>activationSpecScope</property>
        <type>entry</type>
        <required>1</required>
        <documentation>Scope of the messaging provider at which the JMS Activation Spec is to be deleted.</documentation>
    </formElement>
    <formElement>
        Activation Spec Administrative Name:
        <property>activationSpecAdministrativeName</property>
        <type>entry</type>
        <required>1</required>
        <documentation>The administrative name assigned to this WebSphere MQ messaging provider Activation Spec.</documentation>
    </formElement>
</editor>


text:
FOUNDATION_EXPORT double MapboxVersionNumber;

/// Project version string for Mapbox.
FOUNDATION_EXPORT const unsigned char MapboxVersionString[];

#import "MGLAnnotationView.h"
#import "MGLAccountManager.h"
#import "MGLAnnotation.h"
#import "MGLAnnotationImage.h"
#import "MGLCalloutView.h"
#import "MGLClockDirectionFormatter.h"
#import "MGLCompassDirectionFormatter.h"
#import "MGLCoordinateFormatter.h"
#import "MGLFeature.h"
#import "MGLGeometry.h"
#import "MGLMapCamera.h"
#import "MGLMapView.h"
#import "MGLMapView+IBAdditions.h"
#import "MGLMapView+MGLCustomStyleLayerAdditions.h"
#import "MGLMapViewDelegate.h"
#import "MGLMultiPoint.h"
#import "MGLOfflinePack.h"
#import "MGLOfflineRegion.h"
#import "MGLOfflineStorage.h"
#import "MGLOverlay.h"
#import "MGLPointAnnotation.h"
#import "MGLPolygon.h"
#import "MGLPolyline.h"
#import "MGLShape.h"
#import "MGLShapeCollection.h"
#import "MGLStyle.h"
#import "MGLTilePyramidOfflineRegion.h"
#import "MGLTypes.h"
#import "MGLUserLocation.h"
#import "NSValue+MGLAdditions.h"


text:
package fake

import (
	v2 "github.com/cilium/cilium/pkg/k8s/apis/cilium.io/v2"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	labels "k8s.io/apimachinery/pkg/labels"
	schema "k8s.io/apimachinery/pkg/runtime/schema"
	types "k8s.io/apimachinery/pkg/types"
	watch "k8s.io/apimachinery/pkg/watch"
	testing "k8s.io/client-go/testing"
)

// FakeCiliumNetworkPolicies implements CiliumNetworkPolicyInterface
type FakeCiliumNetworkPolicies struct {
	Fake *FakeCiliumV2
	ns   string
}

var ciliumnetworkpoliciesResource = schema.GroupVersionResource{Group: "cilium.io", Version: "v2", Resource: "ciliumnetworkpolicies"}

var ciliumnetworkpoliciesKind = schema.GroupVersionKind{Group: "cilium.io", Version: "v2", Kind: "CiliumNetworkPolicy"}

// Get takes name of the ciliumNetworkPolicy, and returns the corresponding ciliumNetworkPolicy object, and an error if there is any.
func (c *FakeCiliumNetworkPolicies) Get(name string, options v1.GetOptions) (result *v2.CiliumNetworkPolicy, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewGetAction(ciliumnetworkpoliciesResource, c.ns, name), &v2.CiliumNetworkPolicy{})

	if obj == nil {
		return nil, err
	}
	return obj.(*v2.CiliumNetworkPolicy), err
}

// List takes label and field selectors, and returns the list of CiliumNetworkPolicies that match those selectors.
func (c *FakeCiliumNetworkPolicies) List(opts v1.ListOptions) (result *v2.CiliumNetworkPolicyList, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewListAction(ciliumnetworkpoliciesResource, ciliumnetworkpoliciesKind, c.ns, opts), &v2.CiliumNetworkPolicyList{})

	if obj == nil {
		return nil, err
	}

	label, _, _ := testing.ExtractFromListOptions(opts)
	if label == nil {
		label = labels.Everything()
	}
	list := &v2.CiliumNetworkPolicyList{ListMeta: obj.(*v2.CiliumNetworkPolicyList).ListMeta}
	for _, item := range obj.(*v2.CiliumNetworkPolicyList).Items {
		if label.Matches(labels.Set(item.Labels)) {
			list.Items = append(list.Items, item)
		}
	}
	return list, err
}

// Watch returns a watch.Interface that watches the requested ciliumNetworkPolicies.
func (c *FakeCiliumNetworkPolicies) Watch(opts v1.ListOptions) (watch.Interface, error) {
	return c.Fake.
		InvokesWatch(testing.NewWatchAction(ciliumnetworkpoliciesResource, c.ns, opts))

}

// Create takes the representation of a ciliumNetworkPolicy and creates it.  Returns the server's representation of the ciliumNetworkPolicy, and an error, if there is any.
func (c *FakeCiliumNetworkPolicies) Create(ciliumNetworkPolicy *v2.CiliumNetworkPolicy) (result *v2.CiliumNetworkPolicy, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewCreateAction(ciliumnetworkpoliciesResource, c.ns, ciliumNetworkPolicy), &v2.CiliumNetworkPolicy{})

	if obj == nil {
		return nil, err
	}
	return obj.(*v2.CiliumNetworkPolicy), err
}

// Update takes the representation of a ciliumNetworkPolicy and updates it. Returns the server's representation of the ciliumNetworkPolicy, and an error, if there is any.
func (c *FakeCiliumNetworkPolicies) Update(ciliumNetworkPolicy *v2.CiliumNetworkPolicy) (result *v2.CiliumNetworkPolicy, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewUpdateAction(ciliumnetworkpoliciesResource, c.ns, ciliumNetworkPolicy), &v2.CiliumNetworkPolicy{})

	if obj == nil {
		return nil, err
	}
	return obj.(*v2.CiliumNetworkPolicy), err
}

// UpdateStatus was generated because the type contains a Status member.
// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().
func (c *FakeCiliumNetworkPolicies) UpdateStatus(ciliumNetworkPolicy *v2.CiliumNetworkPolicy) (*v2.CiliumNetworkPolicy, error) {
	obj, err := c.Fake.
		Invokes(testing.NewUpdateSubresourceAction(ciliumnetworkpoliciesResource, "status", c.ns, ciliumNetworkPolicy), &v2.CiliumNetworkPolicy{})

	if obj == nil {
		return nil, err
	}
	return obj.(*v2.CiliumNetworkPolicy), err
}

// Delete takes name of the ciliumNetworkPolicy and deletes it. Returns an error if one occurs.
func (c *FakeCiliumNetworkPolicies) Delete(name string, options *v1.DeleteOptions) error {
	_, err := c.Fake.
		Invokes(testing.NewDeleteAction(ciliumnetworkpoliciesResource, c.ns, name), &v2.CiliumNetworkPolicy{})

	return err
}

// DeleteCollection deletes a collection of objects.
func (c *FakeCiliumNetworkPolicies) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error {
	action := testing.NewDeleteCollectionAction(ciliumnetworkpoliciesResource, c.ns, listOptions)

	_, err := c.Fake.Invokes(action, &v2.CiliumNetworkPolicyList{})
	return err
}

// Patch applies the patch and returns the patched ciliumNetworkPolicy.
func (c *FakeCiliumNetworkPolicies) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v2.CiliumNetworkPolicy, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewPatchSubresourceAction(ciliumnetworkpoliciesResource, c.ns, name, data, subresources...), &v2.CiliumNetworkPolicy{})

	if obj == nil {
		return nil, err
	}
	return obj.(*v2.CiliumNetworkPolicy), err
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:task="http://www.springframework.org/schema/task"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/mvc
 		http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/task
        http://www.springframework.org/schema/task/spring-task-3.0.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    <description>Spring-MVC</description>

    <mvc:annotation-driven/>
    <context:component-scan base-package="com.youzan.dts"/>
    <aop:aspectj-autoproxy/>

    <bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
        <property name="resourceLoaderPath" value="/pages/"/>
        <property name="configLocation" value="/WEB-INF/velocity.properties"/>
    </bean>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver">
        <property name="dateToolAttribute">
            <value>dateTool</value>
        </property>

        <property name="numberToolAttribute">
            <value>numberTool</value>
        </property>

        <property name="cache" value="true"/>
        <property name="prefix" value=""/>
        <property name="suffix" value=".vm"/>
        <property name="layoutUrl" value="layout/blank.vm"/>
        <property name="contentType">
            <value>text/html;charset=UTF-8</value>
        </property>
        <property name="exposeSpringMacroHelpers" value="true"/>
        <property name="requestContextAttribute" value="rc"/>
        <property name="exposeSessionAttributes" value="true"/>
    </bean>

    <mvc:resources mapping="/assets/**" location="/assets/"/>
</beans>


text:
class Filter {
 public:
  explicit Filter(PersistentContext context);
  ~Filter();

 public:
  bool Load(const char* fileName);
  bool ProcessIncoming(const int argc, v8::Handle<v8::Value> args[]);
  bool ProcessOutgoing(const int argc, v8::Handle<v8::Value> argv[]);

  const std::string GetName() { return name_; }
  PersistentContext GetContext() { return context_; }

 private:
  bool LoadMeta();
  v8::Local<v8::String> LoadSource(const char* fileName);
  void ReportException(v8::TryCatch* tryCatch);
  bool Eval(v8::Handle<v8::Script> script);
  bool LoadProcessor(const char *fnName);
  bool Run(const char *processorName,
            const int argc,
            v8::Handle<v8::Value> argv[]);

  v8::Handle<v8::Function> GetFunction(const char *fnName);
  // v8::Isolate* const GetIsolate() { return context_->GetIsolate(); }

  v8::Local<v8::Context> GetLocalContext() {
    return v8::Local<v8::Context>::New(v8::Isolate::GetCurrent(), context_);
  }

 private:
  std::string name_ = "Unknown";

  PersistentContext context_;
  v8::Handle<v8::String> scriptName_;

  std::map<const char *, PersistentFunction> processors_;
};

#endif