text:
package com.hazelcast.spi.impl.operationservice.impl;

import com.hazelcast.client.impl.ClientBackupAwareResponse;
import com.hazelcast.cluster.Address;
import com.hazelcast.cluster.ClusterState;
import com.hazelcast.cluster.Member;
import com.hazelcast.core.HazelcastInstanceNotActiveException;
import com.hazelcast.core.MemberLeftException;
import com.hazelcast.instance.impl.Node;
import com.hazelcast.instance.impl.NodeState;
import com.hazelcast.internal.cluster.ClusterClock;
import com.hazelcast.internal.cluster.ClusterService;
import com.hazelcast.internal.nio.Connection;
import com.hazelcast.internal.nio.Packet;
import com.hazelcast.internal.partition.InternalPartitionService;
import com.hazelcast.internal.serialization.InternalSerializationService;
import com.hazelcast.internal.server.Server;
import com.hazelcast.internal.server.ServerConnection;
import com.hazelcast.internal.server.ServerConnectionManager;
import com.hazelcast.internal.util.Clock;
import com.hazelcast.internal.util.counters.MwCounter;
import com.hazelcast.internal.util.executor.ManagedExecutorService;
import com.hazelcast.logging.ILogger;
import com.hazelcast.spi.exception.ResponseAlreadySentException;
import com.hazelcast.spi.exception.RetryableException;
import com.hazelcast.spi.exception.RetryableIOException;
import com.hazelcast.spi.exception.TargetNotMemberException;
import com.hazelcast.spi.exception.WrongTargetException;
import com.hazelcast.spi.impl.AbstractInvocationFuture.ExceptionalResult;
import com.hazelcast.spi.impl.AllowedDuringPassiveState;
import com.hazelcast.spi.impl.NodeEngine;
import com.hazelcast.spi.impl.executionservice.ExecutionService;
import com.hazelcast.spi.impl.operationexecutor.OperationExecutor;
import com.hazelcast.spi.impl.operationservice.BackupAwareOperation;
import com.hazelcast.spi.impl.operationservice.BlockingOperation;
import com.hazelcast.spi.impl.operationservice.ExceptionAction;
import com.hazelcast.spi.impl.operationservice.InvocationBuilder;
import com.hazelcast.spi.impl.operationservice.Operation;
import com.hazelcast.spi.impl.operationservice.OperationResponseHandler;
import com.hazelcast.spi.impl.operationservice.TargetAware;
import com.hazelcast.spi.impl.operationservice.impl.responses.CallTimeoutResponse;
import com.hazelcast.spi.impl.operationservice.impl.responses.ErrorResponse;
import com.hazelcast.spi.impl.operationservice.impl.responses.NormalResponse;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;

import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.logging.Level;

import static com.hazelcast.internal.util.ExceptionUtil.rethrow;
import static com.hazelcast.internal.util.StringUtil.timeToString;
import static com.hazelcast.spi.impl.operationservice.OperationAccessor.hasActiveInvocation;
import static com.hazelcast.spi.impl.operationservice.OperationAccessor.setCallTimeout;
import static com.hazelcast.spi.impl.operationservice.OperationAccessor.setCallerAddress;
import static com.hazelcast.spi.impl.operationservice.OperationAccessor.setInvocationTime;
import static com.hazelcast.spi.impl.operationservice.Operations.isJoinOperation;
import static com.hazelcast.spi.impl.operationservice.Operations.isMigrationOperation;
import static com.hazelcast.spi.impl.operationservice.Operations.isWanReplicationOperation;
import static com.hazelcast.spi.impl.operationservice.impl.Invocation.HeartbeatTimeout.NO_TIMEOUT__CALL_TIMEOUT_DISABLED;
import static com.hazelcast.spi.impl.operationservice.impl.Invocation.HeartbeatTimeout.NO_TIMEOUT__CALL_TIMEOUT_NOT_EXPIRED;
import static com.hazelcast.spi.impl.operationservice.impl.Invocation.HeartbeatTimeout.NO_TIMEOUT__HEARTBEAT_TIMEOUT_NOT_EXPIRED;
import static com.hazelcast.spi.impl.operationservice.impl.Invocation.HeartbeatTimeout.NO_TIMEOUT__RESPONSE_AVAILABLE;
import static com.hazelcast.spi.impl.operationservice.impl.Invocation.HeartbeatTimeout.TIMEOUT;
import static com.hazelcast.spi.impl.operationservice.impl.InvocationConstant.CALL_TIMEOUT;
import static com.hazelcast.spi.impl.operationservice.impl.InvocationConstant.HEARTBEAT_TIMEOUT;
import static com.hazelcast.spi.impl.operationservice.impl.InvocationConstant.INTERRUPTED;
import static com.hazelcast.spi.impl.operationservice.impl.InvocationConstant.VOID;
import static java.lang.Boolean.FALSE;
import static java.lang.Boolean.TRUE;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.util.concurrent.TimeUnit.SECONDS;
import static java.util.logging.Level.FINEST;
import static java.util.logging.Level.WARNING;

/**
 * Evaluates the invocation of an {@link Operation}.
 *

 * Using the {@link InvocationFuture}, one can wait for the completion of an invocation.
 *
 * @param <T> Target type of the Invocation
 */
@SuppressWarnings("checkstyle:methodcount")
public abstract class Invocation<T> extends BaseInvocation implements OperationResponseHandler {

    private static final AtomicReferenceFieldUpdater<Invocation, Boolean> RESPONSE_RECEIVED =
            AtomicReferenceFieldUpdater.newUpdater(Invocation.class, Boolean.class, "responseReceived");

    private static final long MIN_TIMEOUT_MILLIS = SECONDS.toMillis(10);
    private static final int MAX_FAST_INVOCATION_COUNT = 5;
    private static final int LOG_MAX_INVOCATION_COUNT = 99;
    private static final int LOG_INVOCATION_COUNT_MOD = 10;

    /**
     * The {@link Operation} this invocation is evaluating.
     */
    @SuppressWarnings("checkstyle:visibilitymodifier")
    public final Operation op;

    /**
     * The first time this invocation got executed.
     * This field is used to determine how long an invocation has actually been running.
     */
    @SuppressWarnings("checkstyle:visibilitymodifier")
    public final long firstInvocationTimeMillis = Clock.currentTimeMillis();

    /**
     * The time in nanoseconds the first time the invocation got executed.
     */
    @SuppressWarnings("checkstyle:visibilitymodifier")
    public final long firstInvocationTimeNanos = System.nanoTime();

    /**
     * A flag to prevent multiple responses to be send to the invocation (only needed for local operations).
     */
    // TODO: this should not be needed; it is taken care of by the future anyway
    volatile Boolean responseReceived = FALSE;

    /**
     * The last (local) time a heartbeat was received for the invocation.
     * The value 0 indicates that no heartbeat was received at all.
     */
    volatile long lastHeartbeatMillis;

    final Context context;
    final InvocationFuture future;
    final long callTimeoutMillis;

    /**
     * Shows number of times this Invocation is invoked.
     * On each call of {@link #doInvoke(boolean)} method, {@code invokeCount} is incremented by one.
     *

     * An invocation can be invoked at most {@link #tryCount} times.
     *

     * When invocation is notified with {@link CallTimeoutResponse}, {@code invokeCount} is decremented back.
     */
    private volatile int invokeCount;

    /**
     * Shows the address of current target.
     *

     * Target address can belong to an existing member or to a non-member in some cases (join, wan-replication etc.).
     * If it belongs to an existing member, then {@link #targetMember} field will be set too.
     */
    private Address targetAddress;
    /**
     * Shows the current target member.
     *

     * If this Invocation is targeting an existing member, then this field will be set.
     * Otherwise it can be null in some cases (join, wan-replication etc.).
     */
    private Member targetMember;
    /**
     * The connection endpoint which operation is sent through to the {@link #targetAddress}.
     * It can be null if invocation is local or there's no established connection to the target yet.
     *

     * Used mainly for logging/diagnosing the invocation.
     */
    private Connection connection;
    /**
     * Member list version read before operation is invoked on target. This version is used while notifying
     * invocation during a member left event.
     */
    private int memberListVersion;

    private final ServerConnectionManager connectionManager;

    /**
     * Shows maximum number of retry counts for this Invocation.
     *
     * @see #invokeCount
     */
    private final int tryCount;
    /**
     * Pause time, in milliseconds, between each retry of this Invocation.
     */
    private final long tryPauseMillis;

    /**
     * Refer to {@link InvocationBuilder#setDoneCallback(Runnable)} for an explanation
     */
    private final Runnable taskDoneCallback;

    Invocation(Context context,
               Operation op,
               Runnable taskDoneCallback,
               int tryCount,
               long tryPauseMillis,
               long callTimeoutMillis,
               boolean deserialize,
               ServerConnectionManager connectionManager) {
        this.context = context;
        this.op = op;
        this.taskDoneCallback = taskDoneCallback;
        this.tryCount = tryCount;
        this.tryPauseMillis = tryPauseMillis;
        this.callTimeoutMillis = getCallTimeoutMillis(callTimeoutMillis);
        this.future = new InvocationFuture(this, deserialize);
        this.connectionManager = getConnectionManager(connectionManager);
    }

    @Override
    public void sendResponse(Operation op, Object response) {
        if (!RESPONSE_RECEIVED.compareAndSet(this, FALSE, TRUE)) {
            throw new ResponseAlreadySentException("NormalResponse already responseReceived for callback: " + this
                    + ", current-response: " + response);
        }

        if (response instanceof CallTimeoutResponse) {
            notifyCallTimeout();
        } else if (response instanceof ErrorResponse || response instanceof Throwable) {
            notifyError(response);
        } else if (response instanceof NormalResponse) {
            NormalResponse normalResponse = (NormalResponse) response;
            notifyNormalResponse(normalResponse.getValue(), normalResponse.getBackupAcks());
        } else {
            // there are no backups or the number of expected backups has returned; so signal the future that the result is ready
            complete(response);
        }
    }

    public final InvocationFuture invoke() {
        invoke0(false);
        return future;
    }

    public final InvocationFuture invokeAsync() {
        invoke0(true);
        return future;
    }

    protected boolean shouldFailOnIndeterminateOperationState() {
        return false;
    }

    abstract ExceptionAction onException(Throwable t);

    boolean isActive() {
        return hasActiveInvocation(op);
    }

    boolean isRetryCandidate() {
        return op.getCallId() != 0;
    }

    /**
     * Initializes the invocation target.
     *
     * @throws Exception if the initialization was a failure
     */
    final void initInvocationTarget() throws Exception {
        Member previousTargetMember = targetMember;
        T target = getInvocationTarget();
        if (target == null) {
            throw newTargetNullException();
        }

        targetMember = toTargetMember(target);
        if (targetMember != null) {
            targetAddress = targetMember.getAddress();
        } else {
            targetAddress = toTargetAddress(target);
        }
        memberListVersion = context.clusterService.getMemberListVersion();

        if (targetMember == null) {
            if (previousTargetMember != null) {
                // If a target member was found earlier but current target member is null
                // then it means a member left.
                throw new MemberLeftException(previousTargetMember);
            }
            if (!(isJoinOperation(op) || isWanReplicationOperation(op))) {
                throw new TargetNotMemberException(target, op.getPartitionId(), op.getClass().getName(), op.getServiceName());
            }
        }

        if (op instanceof TargetAware) {
            ((TargetAware) op).setTarget(targetAddress);
        }
    }

    /**
     * Returns the target of the Invocation.
     * This can be an {@code Address}, {@code Member} or any other type Invocation itself knows.
     */
    abstract T getInvocationTarget();

    /**
     * Convert invocation's target object, obtained using {@link #getInvocationTarget()} method, to an {@link Address}.
     */
    abstract Address toTargetAddress(T target);

    /**
     * Convert invocation's target object, obtained using {@link #getInvocationTarget()} method, to a {@link Member}.
     */
    abstract Member toTargetMember(T target);

    Exception newTargetNullException() {
        return new WrongTargetException(context.clusterService.getLocalMember(), null, op.getPartitionId(),
                op.getReplicaIndex(), op.getClass().getName(), op.getServiceName());
    }

    void notifyError(Object error) {
        assert error != null;

        Throwable cause = error instanceof Throwable
                ? (Throwable) error
                : ((ErrorResponse) error).getCause();

        switch (onException(cause)) {
            case THROW_EXCEPTION:
                notifyThrowable(cause, 0);
                break;
            case RETRY_INVOCATION:
                if (invokeCount < tryCount) {
                    // we are below the tryCount, so lets retry
                    handleRetry(cause);
                } else {
                    // we can't retry anymore, so lets send the cause to the future.
                    notifyThrowable(cause, 0);
                }
                break;
            default:
                throw new IllegalStateException("Unhandled ExceptionAction");
        }
    }

    void notifyNormalResponse(Object value, int expectedBackups) {
        //if client call id is set that means invocation is made by a backup aware client
        //we will complete the response immediately and delegate backup count to caller
        if (op.getClientCallId() != -1) {
            this.backupsAcksExpected = 0;
            if (value instanceof Packet) {
                NormalResponse response = context.serializationService.toObject(value);
                value = response.getValue();
            }
            complete(new ClientBackupAwareResponse(expectedBackups, value));
            return;
        }
        notifyResponse(value, expectedBackups);
    }

    protected void notifyThrowable(Throwable cause, int expectedBackups) {
        // if a regular response comes and there are backups, we need to wait for the backups
        // when the backups complete, the response will be send by the last backup or backup-timeout-handle mechanism kicks on

        if (expectedBackups > backupsAcksReceived) {
            // so the invocation has backups and since not all backups have completed, we need to wait
            // (it could be that backups arrive earlier than the response)

            this.pendingResponseReceivedMillis = Clock.currentTimeMillis();

            this.backupsAcksExpected = expectedBackups;

            // it is very important that the response is set after the backupsAcksExpected is set, else the system
            // can assume the invocation is complete because there is a response and no backups need to respond
            this.pendingResponse = new ExceptionalResult(cause);

            if (backupsAcksReceived != expectedBackups) {
                // we are done since not all backups have completed. Therefor we should not notify the future
                return;
            }
        }

        // we are going to notify the future that a response is available; this can happen when:
        // - we had a regular operation (so no backups we need to wait for) that completed
        // - we had a backup-aware operation that has completed, but also all its backups have completed
        completeExceptionally(cause);
    }

    @SuppressFBWarnings(value = "VO_VOLATILE_INCREMENT",
            justification = "We have the guarantee that only a single thread at any given time can change the volatile field")
    void notifyCallTimeout() {
        if (!(op instanceof BlockingOperation)) {
            // if the call is not a BLockingOperation, then in case of a call-timeout, we are not going to retry;
            // only blocking operations are going to be retried, because they rely on a repeated execution mechanism
            complete(CALL_TIMEOUT);
            return;
        }

        if (context.logger.isFinestEnabled()) {
            context.logger.finest("Call timed-out either in operation queue or during wait-notify phase, retrying call: " + this);
        }

        long oldWaitTimeout = op.getWaitTimeout();
        long newWaitTimeout;
        if (oldWaitTimeout < 0) {
            // The old wait-timeout is unbound; so the new wait-timeout will remain unbound.
            newWaitTimeout = oldWaitTimeout;
        } else {
            // The old wait-timeout was bound.
            // We need to subtract the elapsed time so that the waitTimeout gets smaller on every retry.

            // first we determine elapsed time. To prevent of the elapsed time being negative due to cluster-clock reset, and
            // the call timeout increasing instead of decreasing, the elapsedTime will be at least 0.
            // For elapsed time we rely on cluster-clock, since op.invocationTime is also based on it.
            long elapsedTime = max(0, context.clusterClock.getClusterTime() - op.getInvocationTime());

            // We need to take care of not running into a negative wait-timeout, because it will be interpreted as infinite.
            // That why the max with 0, so that 0 is going to be the smallest remaining timeout
            newWaitTimeout = max(0, oldWaitTimeout - elapsedTime);
        }
        op.setWaitTimeout(newWaitTimeout);

        invokeCount--;
        handleRetry("invocation timeout");
    }

    /**
     * Checks if this Invocation has received a heartbeat in time.
     *
     * If the response is already set, or if a heartbeat has been received in time, then {@code false} is returned.
     * If no heartbeat has been received, then the future.set is called with HEARTBEAT_TIMEOUT and {@code true} is returned.
     *
     * Gets called from the monitor-thread.
     *
     * @return {@code true} if there is a timeout detected, {@code false} otherwise.
     */
    boolean detectAndHandleTimeout(long heartbeatTimeoutMillis) {
        if (skipTimeoutDetection()) {
            return false;
        }

        HeartbeatTimeout heartbeatTimeout = detectTimeout(heartbeatTimeoutMillis);

        if (heartbeatTimeout == TIMEOUT) {
            complete(HEARTBEAT_TIMEOUT);
            return true;
        } else {
            return false;
        }
    }

    boolean skipTimeoutDetection() {
        // skip if local and not BackupAwareOperation
        return isLocal() && !(op instanceof BackupAwareOperation);
    }

    HeartbeatTimeout detectTimeout(long heartbeatTimeoutMillis) {
        if (pendingResponse != VOID) {
            // if there is a response, then we won't timeout
            return NO_TIMEOUT__RESPONSE_AVAILABLE;
        }

        long callTimeoutMillis = op.getCallTimeout();
        if (callTimeoutMillis <= 0 || callTimeoutMillis == Long.MAX_VALUE) {
            return NO_TIMEOUT__CALL_TIMEOUT_DISABLED;
        }

        // a call is always allowed to execute as long as its own call timeout
        long deadlineMillis = op.getInvocationTime() + callTimeoutMillis;
        if (deadlineMillis > context.clusterClock.getClusterTime()) {
            return NO_TIMEOUT__CALL_TIMEOUT_NOT_EXPIRED;
        }

        // on top of its own call timeout, it is allowed to execute until there is a heartbeat timeout;
        // so if the callTimeout is five minutes, and the heartbeatTimeout is one minute, then the operation is allowed
        // to execute for at least six minutes before it is timing out
        long lastHeartbeatMillis = this.lastHeartbeatMillis;
        long heartbeatExpirationTimeMillis = lastHeartbeatMillis == 0
                ? op.getInvocationTime() + callTimeoutMillis + heartbeatTimeoutMillis
                : lastHeartbeatMillis + heartbeatTimeoutMillis;

        if (heartbeatExpirationTimeMillis > Clock.currentTimeMillis()) {
            return NO_TIMEOUT__HEARTBEAT_TIMEOUT_NOT_EXPIRED;
        }

        return TIMEOUT;
    }

    protected boolean shouldCompleteWithoutBackups() {
        boolean targetDead = context.clusterService.getMember(targetAddress) == null;
        if (targetDead) {
            // the target doesn't exist, so we are going to re-invoke this invocation;
            // the reason for the re-invocation is that otherwise it's possible to lose data,
            // e.g. when a map.put() was done and the primary node has returned the response,
            // but has not yet completed the backups and then the primary node fails;
            // the consequence would be that the backups are never be made and the effects of the map.put() will never be visible,
            // even though the future returned a value;
            // so if we would complete the future, a response is sent even though its changes never made it into the system
            resetAndReInvoke();
            return false;
        }
        return true;
    }

    private boolean engineActive() {
        NodeState state = context.node.getState();
        if (state == NodeState.ACTIVE) {
            return true;
        }

        boolean allowed = true;
        if (state == NodeState.SHUT_DOWN) {
            notifyError(new HazelcastInstanceNotActiveException("State: " + state + " Operation: " + op.getClass()));
            allowed = false;
        } else if (!(op instanceof AllowedDuringPassiveState)
                && context.clusterService.getClusterState() == ClusterState.PASSIVE) {
            // Similar to OperationRunnerImpl.checkNodeState(op)
            notifyError(new IllegalStateException("Cluster is in " + ClusterState.PASSIVE + " state! Operation: " + op));
            allowed = false;
        }
        return allowed;
    }

    private void invoke0(boolean isAsync) {
        if (invokeCount > 0) {
            throw new IllegalStateException("This invocation is already in progress");
        } else if (isActive()) {
            throw new IllegalStateException(
                    "Attempt to reuse the same operation in multiple invocations. Operation is " + op);
        }

        try {
            setCallTimeout(op, callTimeoutMillis);
            setCallerAddress(op, context.thisAddress);
            op.setNodeEngine(context.nodeEngine);

            boolean isAllowed = context.operationExecutor.isInvocationAllowed(op, isAsync);
            if (!isAllowed && !isMigrationOperation(op)) {
                throw new IllegalThreadStateException(Thread.currentThread() + " cannot make remote call: " + op);
            }
            doInvoke(isAsync);
        } catch (Exception e) {
            handleInvocationException(e);
        }
    }

    @SuppressFBWarnings(value = "VO_VOLATILE_INCREMENT",
            justification = "We have the guarantee that only a single thread at any given time can change the volatile field")
    private void doInvoke(boolean isAsync) {
        if (!engineActive()) {
            return;
        }

        invokeCount++;

        setInvocationTime(op, context.clusterClock.getClusterTime());

        // We'll initialize the invocation before registering it. Invocation monitor iterates over
        // registered invocations and it must observe completely initialized invocations.
        Exception initializationFailure = null;
        try {
            initInvocationTarget();
        } catch (Exception e) {
            // We'll keep initialization failure and notify invocation with this failure
            // after invocation is registered to the invocation registry.
            initializationFailure = e;
        }

        if (!context.invocationRegistry.register(this)) {
            return;
        }

        if (initializationFailure != null) {
            notifyError(initializationFailure);
            return;
        }

        if (isLocal()) {
            doInvokeLocal(isAsync);
        } else {
            doInvokeRemote();
        }
    }

    private boolean isLocal() {
        return context.thisAddress.equals(targetAddress);
    }

    private void doInvokeLocal(boolean isAsync) {
        if (op.getCallerUuid() == null) {
            op.setCallerUuid(context.node.getThisUuid());
        }

        responseReceived = FALSE;
        op.setOperationResponseHandler(this);

        if (isAsync) {
            context.operationExecutor.execute(op);
        } else {
            context.operationExecutor.runOrExecute(op);
        }
    }

    private void doInvokeRemote() {
        assert connectionManager != null : "Endpoint manager was null";

        ServerConnection connection = connectionManager.getOrConnect(targetAddress, op.getPartitionId());
        this.connection = connection;
        boolean write;
        if (connection != null) {
            write = context.outboundOperationHandler.send(op, connection);
        } else {
            write = context.outboundOperationHandler.send(op, targetAddress);
        }

        if (!write) {
            notifyError(new RetryableIOException(getPacketNotSentMessage(connection)));
        }
    }

    private String getPacketNotSentMessage(Connection connection) {
        if (connection == null) {
            return "Packet not sent to -> " + targetAddress + ", there is no available connection";
        }

        return "Packet not sent to -> " + targetAddress + " over " + connection;
    }

    private ServerConnectionManager getConnectionManager(ServerConnectionManager connectionManager) {
        return connectionManager != null ? connectionManager : context.defaultServerConnectionManager;
    }

    private long getCallTimeoutMillis(long callTimeoutMillis) {
        if (callTimeoutMillis > 0) {
            return callTimeoutMillis;
        }

        long defaultCallTimeoutMillis = context.defaultCallTimeoutMillis;
        if (!(op instanceof BlockingOperation)) {
            return defaultCallTimeoutMillis;
        }

        long waitTimeoutMillis = op.getWaitTimeout();
        if (waitTimeoutMillis > 0 && waitTimeoutMillis < Long.MAX_VALUE) {
            /*
             * final long minTimeout = Math.min(defaultCallTimeout, MIN_TIMEOUT_MILLIS);
             * long callTimeoutMillis = Math.min(waitTimeoutMillis, defaultCallTimeout);
             * callTimeoutMillis = Math.max(a, minTimeout);
             * return callTimeoutMillis;
             *
             * Below two lines are shortened version of above*
             * using min(max(x,y),z)=max(min(x,z),min(y,z))
             */
            long max = max(waitTimeoutMillis, MIN_TIMEOUT_MILLIS);
            return min(max, defaultCallTimeoutMillis);
        }
        return defaultCallTimeoutMillis;
    }

    private void handleInvocationException(Exception e) {
        if (e instanceof RetryableException) {
            notifyError(e);
        } else {
            throw rethrow(e);
        }
    }

    // This is an idempotent operation
    // because both invocationRegistry.deregister() and future.complete() are idempotent.
    @Override
    protected void complete(Object value) {
        future.complete(value);
        complete0();
    }

    @Override
    protected void completeExceptionally(Throwable t) {
        future.completeExceptionallyInternal(t);
        complete0();
    }

    private void complete0() {
        if (context.invocationRegistry.deregister(this) && taskDoneCallback != null) {
            context.asyncExecutor.execute(taskDoneCallback);
        }
        context.invocationRegistry.retire(this);
    }

    private void handleRetry(Object cause) {
        context.retryCount.inc();

        if (invokeCount % LOG_INVOCATION_COUNT_MOD == 0) {
            Level level = invokeCount > LOG_MAX_INVOCATION_COUNT ? WARNING : FINEST;
            if (context.logger.isLoggable(level)) {
                context.logger.log(level, "Retrying invocation: " + toString() + ", Reason: " + cause);
            }
        }

        if (future.interrupted) {
            complete(INTERRUPTED);
        } else {
            try {
                InvocationRetryTask retryTask = new InvocationRetryTask();
                if (invokeCount < MAX_FAST_INVOCATION_COUNT) {
                    // fast retry for the first few invocations
                    context.invocationMonitor.execute(retryTask);
                } else {
                    // progressive retry delay
                    long delayMillis = Math.min(1 << (invokeCount - MAX_FAST_INVOCATION_COUNT), tryPauseMillis);
                    context.invocationMonitor.schedule(retryTask, delayMillis);
                }
            } catch (RejectedExecutionException e) {
                completeWhenRetryRejected(e);
            }
        }
    }

    private void completeWhenRetryRejected(RejectedExecutionException e) {
        if (context.logger.isFinestEnabled()) {
            context.logger.finest(e);
        }
        completeExceptionally(new HazelcastInstanceNotActiveException(e.getMessage()));
    }

    private void resetAndReInvoke() {
        if (!context.invocationRegistry.deregister(this)) {
            // another thread already did something else with this invocation
            return;
        }
        invokeCount = 0;
        pendingResponse = VOID;
        pendingResponseReceivedMillis = -1;
        backupsAcksExpected = 0;
        backupsAcksReceived = 0;
        lastHeartbeatMillis = 0;
        doInvoke(false);
    }

    Address getTargetAddress() {
        return targetAddress;
    }

    Member getTargetMember() {
        return targetMember;
    }

    int getMemberListVersion() {
        return memberListVersion;
    }

    @Override
    public String toString() {
        return "Invocation{"
                + "op=" + op
                + ", tryCount=" + tryCount
                + ", tryPauseMillis=" + tryPauseMillis
                + ", invokeCount=" + invokeCount
                + ", callTimeoutMillis=" + callTimeoutMillis
                + ", firstInvocationTimeMs=" + firstInvocationTimeMillis
                + ", firstInvocationTime='" + timeToString(firstInvocationTimeMillis) + '\''
                + ", lastHeartbeatMillis=" + lastHeartbeatMillis
                + ", lastHeartbeatTime='" + timeToString(lastHeartbeatMillis) + '\''
                + ", target=" + targetAddress
                + ", pendingResponse={" + pendingResponse + '}'
                + ", backupsAcksExpected=" + backupsAcksExpected
                + ", backupsAcksReceived=" + backupsAcksReceived
                + ", connection=" + connection
                + '}';
    }

    private class InvocationRetryTask implements Runnable {

        @Override
        public void run() {
            // When a cluster is being merged into another one then local node is marked as not-joined and invocations are
            // notified with MemberLeftException.
            // We do not want to retry them before the node is joined again because partition table is stale at this point.
            if (!context.clusterService.isJoined() && !isJoinOperation(op) && !(op instanceof AllowedDuringPassiveState)) {
                if (!engineActive()) {
                    context.invocationRegistry.deregister(Invocation.this);
                    return;
                }

                if (context.logger.isFinestEnabled()) {
                    context.logger.finest("Node is not joined. Re-scheduling " + this
                            + " to be executed in " + tryPauseMillis + " ms.");
                }
                try {
                    context.invocationMonitor.schedule(new InvocationRetryTask(), tryPauseMillis);
                } catch (RejectedExecutionException e) {
                    completeWhenRetryRejected(e);
                }
                return;
            }

            if (!context.invocationRegistry.deregister(Invocation.this)) {
                return;
            }

            // When retrying, we must reset lastHeartbeat, otherwise InvocationMonitor will see the old value
            // and falsely conclude that nothing has been done about this operation for a long time.
            lastHeartbeatMillis = 0;
            doInvoke(true);
        }

    }

    enum HeartbeatTimeout {
        NO_TIMEOUT__CALL_TIMEOUT_DISABLED,
        NO_TIMEOUT__RESPONSE_AVAILABLE,
        NO_TIMEOUT__HEARTBEAT_TIMEOUT_NOT_EXPIRED,
        NO_TIMEOUT__CALL_TIMEOUT_NOT_EXPIRED,
        TIMEOUT
    }

    /**
     * The {@link Context} contains all 'static' dependencies for an Invocation; dependencies that don't change between
     * invocations. All invocation specific dependencies/settings are passed in through the constructor of the invocation.
     *
     * This object should have no functionality apart from providing dependencies. So no methods should be added to this class.
     *
     * The goals of the Context are:
     *

     *
reduce the need on having a cluster running when testing Invocations. This is one of the primary drivers behind this
     * context

     *
prevent a.b.c.d call in the invocation by pulling all dependencies in the InvocationContext

     *
removed dependence on NodeEngineImpl. Only NodeEngine is needed to set on Operation

     *
reduce coupling to Node. All dependencies on Node, apart from Node.getState, have been removed. This will make it
     * easier to get rid of Node dependency in the near future completely.

     *

     */
    static class Context {
        final ManagedExecutorService asyncExecutor;
        final ClusterClock clusterClock;
        final ClusterService clusterService;
        final Server server;
        final ExecutionService executionService;
        final long defaultCallTimeoutMillis;
        final InvocationRegistry invocationRegistry;
        final InvocationMonitor invocationMonitor;
        final ILogger logger;
        final Node node;
        final NodeEngine nodeEngine;
        final InternalPartitionService partitionService;
        final OperationServiceImpl operationService;
        final OperationExecutor operationExecutor;
        final MwCounter retryCount;
        final InternalSerializationService serializationService;
        final Address thisAddress;
        final OutboundOperationHandler outboundOperationHandler;
        final ServerConnectionManager defaultServerConnectionManager;

        @SuppressWarnings("checkstyle:parameternumber")
        Context(ManagedExecutorService asyncExecutor,
                ClusterClock clusterClock,
                ClusterService clusterService,
                Server server,
                ExecutionService executionService,
                long defaultCallTimeoutMillis,
                InvocationRegistry invocationRegistry,
                InvocationMonitor invocationMonitor,
                ILogger logger,
                Node node,
                NodeEngine nodeEngine,
                InternalPartitionService partitionService,
                OperationServiceImpl operationService,
                OperationExecutor operationExecutor,
                MwCounter retryCount,
                InternalSerializationService serializationService,
                Address thisAddress,
                OutboundOperationHandler outboundOperationHandler,
                ServerConnectionManager connectionManager) {
            this.asyncExecutor = asyncExecutor;
            this.clusterClock = clusterClock;
            this.clusterService = clusterService;
            this.server = server;
            this.executionService = executionService;
            this.defaultCallTimeoutMillis = defaultCallTimeoutMillis;
            this.invocationRegistry = invocationRegistry;
            this.invocationMonitor = invocationMonitor;
            this.logger = logger;
            this.node = node;
            this.nodeEngine = nodeEngine;
            this.partitionService = partitionService;
            this.operationService = operationService;
            this.operationExecutor = operationExecutor;
            this.retryCount = retryCount;
            this.serializationService = serializationService;
            this.thisAddress = thisAddress;
            this.outboundOperationHandler = outboundOperationHandler;
            this.defaultServerConnectionManager = connectionManager;
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace Article\Factory\View\Helper;

use Article\Service\EventService;
use Article\View\Helper\EventHelper;
use Interop\Container\ContainerInterface;

class EventHelperFactory
{
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        return new EventHelper(
            $container->get(EventService::class)
        );
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;

namespace Entitas {
    public partial class Entity {
        public MyStringComponent myString { get { return (MyStringComponent)GetComponent(ComponentIds.MyString); } }

        public bool hasMyString { get { return HasComponent(ComponentIds.MyString); } }

        static readonly Stack<MyStringComponent> _myStringComponentPool = new Stack<MyStringComponent>();

        public static void ClearMyStringComponentPool() {
            _myStringComponentPool.Clear();
        }

        public Entity AddMyString(string newMyString) {
            var component = _myStringComponentPool.Count > 0 ? _myStringComponentPool.Pop() : new MyStringComponent();
            component.myString = newMyString;
            return AddComponent(ComponentIds.MyString, component);
        }

        public Entity ReplaceMyString(string newMyString) {
            var previousComponent = hasMyString ? myString : null;
            var component = _myStringComponentPool.Count > 0 ? _myStringComponentPool.Pop() : new MyStringComponent();
            component.myString = newMyString;
            ReplaceComponent(ComponentIds.MyString, component);
            if (previousComponent != null) {
                _myStringComponentPool.Push(previousComponent);
            }
            return this;
        }

        public Entity RemoveMyString() {
            var component = myString;
            RemoveComponent(ComponentIds.MyString);
            _myStringComponentPool.Push(component);
            return this;
        }
    }

    public partial class Matcher {
        static IMatcher _matcherMyString;

        public static IMatcher MyString {
            get {
                if (_matcherMyString == null) {
                    var matcher = (Matcher)Matcher.AllOf(ComponentIds.MyString);
                    matcher.componentNames = ComponentIds.componentNames;
                    _matcherMyString = matcher;
                }

                return _matcherMyString;
            }
        }
    }
}


text:
package net.kuujo.vertigo.integration;

import net.kuujo.vertigo.component.MessageHandlerComponent;
import net.kuujo.vertigo.message.VertigoMessage;
import net.kuujo.vertigo.network.NetworkConfig;
import net.kuujo.vertigo.network.builder.NetworkBuilder;
import net.kuujo.vertigo.reference.NetworkReference;
import org.junit.Test;

import java.util.concurrent.CompletableFuture;

public class Forward_Sync_Ack_Test_ComponentFactory extends VertigoTestBase {
  static CompletableFuture<Void> targetReceived;

  @Override
  protected NetworkConfig createNetwork() {
    NetworkBuilder builder = NetworkConfig.builder();

    builder.component("A")
        .identifier(StartComponent.class.getName())
        .input().port("in")
        .output().port("out");

    builder.component("B")
        .identifier(TargetComponent.class.getName())
        .input().port("in");

    builder
        .connect("A").port("out")
        .to("B").port("in");

    return builder.build();
  }

  @Test
  public void sync_test() throws InterruptedException {
    NetworkReference network = getNetworkReference();
    targetReceived = new CompletableFuture<>();
    CompletableFuture<Void> sendCompleted = new CompletableFuture<>();

    network
        .component("A").input().port("in")
        .send("Word", message -> {
          logger().info("Send acked");
          sendCompleted.complete(null);
          // Verify that the target component has acked already
          assertTrue(targetReceived.isDone());
        });

    CompletableFuture.allOf(sendCompleted, targetReceived).join();
    testComplete();

  }

  @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
  public static class StartComponent extends MessageHandlerComponent<String> {

    @Override
    public void handle(VertigoMessage<String> event) {
      output()
          .port("out")
          .send(event.body(), event::handle);
    }
  }

  public static class TargetComponent extends MessageHandlerComponent<String> {

    @Override
    public void handle(VertigoMessage<String> event) {
      logger().info("Target received " + event.body());
      vertx.setTimer(100, id ->
      {
        logger().info("Target acking");
        targetReceived.complete(null);
        event.ack();
      });
    }

  }
}


text:
import collections
import itertools

import nengo

import pacman103
from .config import Config
import connection
import ensemble
import node
import probe
import utils

class Assembler(object):
    """The Assembler object takes a built collection of objects and connections
    and converts them into PACMAN vertices and edges, and returns the portion
    of the network to be simulated on host.
    """
    object_builders = dict()  # Map of classes to functions
    connection_builders = dict()  # Map of (pre_obj, post_obj) tuples to functions

    @classmethod
    def register_object_builder(cls, func, nengo_class):
        cls.object_builders[nengo_class] = func

    @classmethod
    def register_connection_builder(cls, func, pre_obj=None, post_obj=None):
        cls.connection_builders[(pre_obj, post_obj)] = func

    def build_object(self, obj):
        for obj_type in obj.__class__.__mro__:
            if obj_type in self.object_builders:
                break
        else:
            raise TypeError("Cannot assemble object of type '%s'." %
                            obj.__class__.__name__)

        vertex = self.object_builders[obj_type](obj, self)
        if vertex is not None:
            assert isinstance(vertex, pacman103.lib.graph.Vertex)
            vertex.runtime = self.time_in_seconds
        return vertex

    def build_connection(self, connection):
        pre_c = list(connection.pre_obj.__class__.__mro__) + [None]
        post_c = list(connection.post_obj.__class__.__mro__) + [None]

        for key in itertools.chain(*[[(a, b) for b in post_c] for a in pre_c]):
            if key in self.connection_builders:
                return self.connection_builders[key](connection, self)
        else:
            raise TypeError("Cannot build a connection from a '%s' to '%s'." %
                            (connection.pre_obj.__class__.__name__,
                             connection.post_obj.__class__.__name__))

    def __call__(self, objs, conns, time_in_seconds, dt, config=None):
        """Construct PACMAN vertices and edges, and a reduced version of the
        model for simulation on host.

        :param objs: A list of objects to convert into PACMAN vertices.
        :param conns: A list of connections which will become edges.
        :param time_in_seconds: The run time of the simulation (None means
                                infinite).
        :param dt: The time step of the simulation.
        :param config: Configuration options for the simulation.
        """
        # Store the config
        self.config = config
        if self.config is None:
            self.config = Config()

        self.timestep = 1000
        self.dt = dt
        self.time_in_seconds = time_in_seconds
        self.n_ticks = (int(time_in_seconds / dt) if
                        time_in_seconds is not None else 0)

        # Store for querying
        self.connections = conns

        # Construct each object in turn to produce vertices
        self.object_vertices = dict([(o, self.build_object(o)) for o in objs])
        self.vertices = [v for v in self.object_vertices.values() if
                         v is not None]

        # Construct each connection in turn to produce edges
        self.edges = filter(lambda x: x is not None, [self.build_connection(c)
                                                      for c in conns])

        return self.vertices, self.edges

    def get_object_vertex(self, obj):
        """Return the vertex which represents the given object."""
        return self.object_vertices[obj]

    def get_incoming_connections(self, obj):
        return [c for c in self.connections if c.post_obj == obj]

    def get_outgoing_connections(self, obj):
        return [c for c in self.connections if c.pre_obj == obj]

Assembler.register_connection_builder(connection.generic_connection_builder)

Assembler.register_object_builder(ensemble.EnsembleLIF.assemble,
                                  ensemble.IntermediateEnsembleLIF)
Assembler.register_object_builder(node.FilterVertex.assemble_from_intermediate,
                                  node.IntermediateFilter)
Assembler.register_object_builder(node.FilterVertex.assemble,
                                  node.FilterVertex)
Assembler.register_object_builder(probe.DecodedValueProbe.assemble,
                                  probe.IntermediateProbe)

def vertex_builder(vertex, assembler):
    return vertex

Assembler.register_object_builder(vertex_builder, pacman103.lib.graph.Vertex)

def assemble_node(node, assembler):
    pass

Assembler.register_object_builder(assemble_node, nengo.Node)

MulticastPacket = collections.namedtuple('MulticastPacket',
                                         ['timestamp', 'key', 'payload'])

class MulticastPlayer(utils.vertices.NengoVertex):
    # NOTE This is intended to be temporary while PACMAN is refactored
    MODEL_NAME = 'nengo_mc_player'
    MAX_ATOMS = 1

    def __init__(self):
        super(MulticastPlayer, self).__init__(1)
        self.regions = [None, None, None, None]

    @classmethod
    def assemble(cls, mcp, assembler):
        # Get all the symbols to transmit prior to and after the simulation
        sinks = set(
            c.post_obj for c in assembler.get_outgoing_connections(mcp))

        start_items = list()
        end_items = list()

        for sink in sinks:
            for p in sink.start_packets:
                start_items.extend([0, p.key,
                                    0 if p.payload is None else p.payload,
                                    p.payload is not None])

            for p in sink.end_packets:
                end_items.extend([0, p.key,
                                  0 if p.payload is None else p.payload,
                                  p.payload is not None])

        # Build the regions
        start_items.insert(0, len(start_items)/4)
        start_region = utils.vertices.UnpartitionedListRegion(
            start_items)
        end_items.insert(0, len(end_items)/4)
        end_region = utils.vertices.UnpartitionedListRegion(
            end_items)
        mcp.regions[1] = start_region
        mcp.regions[3] = end_region

        return mcp

Assembler.register_object_builder(MulticastPlayer.assemble, MulticastPlayer)


text:
import { isMatchWith } from "../index";
export = isMatchWith;


text:
(function ($) {
    $.fn.inputlimiter = function (options) {
        var opts = $.extend({}, $.fn.inputlimiter.defaults, options), $elements = $(this);
        if (opts.boxAttach && !$('#' + opts.boxId).length) {
            $('<div/>').appendTo("body").attr({id: opts.boxId, 'class': opts.boxClass}).css({'position': 'absolute'}).hide();
            if ($.fn.bgiframe) {
                $('#' + opts.boxId).bgiframe();
            }
        }
        var inputlimiterKeyup = function (e) {
            var $this = $(this), count = counter($this.val());
            if (!opts.allowExceed && count > opts.limit) {
                $this.val(truncater($this.val()));
            }
            if (opts.boxAttach) {
                $('#' + opts.boxId).css({'width': $this.outerWidth() - ($('#' + opts.boxId).outerWidth() - $('#' + opts.boxId).width()) + 'px', 'left': $this.offset().left + 'px', 'top': ($this.offset().top + $this.outerHeight()) - 1 + 'px', 'z-index': 2000});
            }
            var charsRemaining = (opts.limit - count > 0 ? opts.limit - count : 0), remText = opts.remTextFilter(opts, charsRemaining), limitText = opts.limitTextFilter(opts);
            if (opts.limitTextShow) {
                $('#' + opts.boxId).html(remText + ' ' + limitText);
                var textWidth = $("<span/>").appendTo("body").attr({id: '19cc9195583bfae1fad88e19d443be7a', 'class': opts.boxClass}).html(remText + ' ' + limitText).innerWidth();
                $("#19cc9195583bfae1fad88e19d443be7a").remove();
                if (textWidth > $('#' + opts.boxId).innerWidth()) {
                    $('#' + opts.boxId).html(remText + '<br />' + limitText);
                }
                $('#' + opts.boxId).show();
            } else {
                $('#' + opts.boxId).html(remText).show();
            }
        }, inputlimiterKeypress = function (e) {
            var count = counter($(this).val());
            if (!opts.allowExceed && count > opts.limit) {
                var modifierKeyPressed = e.ctrlKey || e.altKey || e.metaKey;
                if (!modifierKeyPressed && (e.which >= 32 && e.which <= 122) && this.selectionStart === this.selectionEnd) {
                    return false;
                }
            }
        }, inputlimiterBlur = function () {
            var $this = $(this);
            count = counter($this.val());
            if (!opts.allowExceed && count > opts.limit) {
                $this.val(truncater($this.val()));
            }
            if (opts.boxAttach) {
                $('#' + opts.boxId).fadeOut('fast');
            } else if (opts.remTextHideOnBlur) {
                var limitText = opts.limitText;
                limitText = limitText.replace(/\%n/g, opts.limit);
                limitText = limitText.replace(/\%s/g, (opts.limit === 1 ? '' : 's'));
                $('#' + opts.boxId).html(limitText);
            }
        }, counter = function (value) {
            if (opts.limitBy.toLowerCase() === "words") {
                return(value.length > 0 ? $.trim(value).replace(/\ +(?= )/g, '').split(' ').length : 0);
            }
            var count = value.length, newlines = value.match(/\n/g);
            if (newlines && opts.lineReturnCount > 1) {
                count += newlines.length * (opts.lineReturnCount - 1);
            }
            return count;
        }, truncater = function (value) {
            if (opts.limitBy.toLowerCase() === "words") {
                return $.trim(value).replace(/\ +(?= )/g, '').split(' ').splice(0, opts.limit).join(' ') + ' ';
            }
            return value.substring(0, opts.limit);
        };
        $(this).each(function (i) {
            var $this = $(this);
            if ((!options || !options.limit) && opts.useMaxlength && parseInt($this.attr('maxlength')) > 0 && parseInt($this.attr('maxlength')) != opts.limit) {
                $this.inputlimiter($.extend({}, opts, {limit: parseInt($this.attr('maxlength'))}));
            } else {
                if (!opts.allowExceed && opts.useMaxlength && opts.limitBy.toLowerCase() === "characters") {
                    $this.attr('maxlength', opts.limit);
                }
                $this.unbind('.inputlimiter');
                $this.bind('keyup.inputlimiter', inputlimiterKeyup);
                $this.bind('keypress.inputlimiter', inputlimiterKeypress);
                $this.bind('blur.inputlimiter', inputlimiterBlur);
            }
        });
    };
    $.fn.inputlimiter.remtextfilter = function (opts, charsRemaining) {
        var remText = opts.remText;
        if (charsRemaining === 0 && opts.remFullText !== null) {
            remText = opts.remFullText;
        }
        remText = remText.replace(/\%n/g, charsRemaining);
        remText = remText.replace(/\%s/g, (opts.zeroPlural ? (charsRemaining === 1 ? '' : 's') : (charsRemaining <= 1 ? '' : 's')));
        return remText;
    };
    $.fn.inputlimiter.limittextfilter = function (opts) {
        var limitText = opts.limitText;
        limitText = limitText.replace(/\%n/g, opts.limit);
        limitText = limitText.replace(/\%s/g, (opts.limit <= 1 ? '' : 's'));
        return limitText;
    };
    $.fn.inputlimiter.defaults = {limit: 255, boxAttach: true, boxId: 'limiterBox', boxClass: 'limiterBox', remText: '%n character%s remaining.', remTextFilter: $.fn.inputlimiter.remtextfilter, remTextHideOnBlur: true, remFullText: null, limitTextShow: true, limitText: 'Field limited to %n character%s.', limitTextFilter: $.fn.inputlimiter.limittextfilter, zeroPlural: true, allowExceed: false, useMaxlength: true, limitBy: 'characters', lineReturnCount: 1};
})(jQuery);


text:
from __future__ import annotations

from pants.core.util_rules.config_files import ConfigFilesRequest
from pants.core.util_rules.external_tool import TemplatedExternalTool
from pants.engine.platform import Platform
from pants.option.option_types import ArgsListOption, BoolOption, FileOption, SkipOption
from pants.util.strutil import softwrap

class GolangciLint(TemplatedExternalTool):
    options_scope = "golangci-lint"
    name = "golangci-lint"
    help = "A fast Go linters runner"

    default_version = "1.50.1"
    default_known_versions = [
        "1.50.1|macos_arm64 |3ca9753d7804b34f9165427fbe339dbea69bd80be8a10e3f02c6037393b2e1c4|9726190",  # noqa: E501
        "1.50.1|macos_x86_64|0f615fb8c364f6e4a213f2ed2ff7aa1fc2b208addf29511e89c03534067bbf57|10007042",  # noqa: E501
        "1.50.1|linux_arm64 |3ea0a6d5946340f6831646e2c67a317dd9b35bdc4e09b2df953a86f09ba05d74|8911583",  # noqa: E501
        "1.50.1|linux_x86_64|4ba1dc9dbdf05b7bdc6f0e04bdfe6f63aa70576f51817be1b2540bbce017b69a|9682295",  # noqa: E501
    ]
    default_url_template = (
        "https://github.com/golangci/golangci-lint/releases/download/v{version}/"
        "golangci-lint-{version}-{platform}.tar.gz"
    )
    default_url_platform_mapping = {
        "macos_arm64": "darwin-arm64",
        "macos_x86_64": "darwin-amd64",
        "linux_arm64": "linux-arm64",
        "linux_x86_64": "linux-amd64",
    }

    skip = SkipOption("lint")
    args = ArgsListOption(example="--enable gocritic")
    config = FileOption(
        "--config",
        default=None,
        advanced=True,
        help=lambda cls: softwrap(
            f"""
            Path to a YAML config file understood by golangci-lint
            (https://golangci-lint.run/usage/configuration/#config-file).

            Setting this option will disable `[{cls.options_scope}].config_discovery`.
            Use this option if the config is located in a non-standard location.
            """
        ),
    )
    config_discovery = BoolOption(
        "--config-discovery",
        default=True,
        advanced=True,
        help=lambda cls: softwrap(
            f"""
            If true, Pants will include all relevant config files during runs
            (`.golangci.yml`, `.golangci.yaml`, `golangci.toml`, and `golangci.json`).

            Use `[{cls.options_scope}].config` instead if your config is in a
            non-standard location.
            """
        ),
    )

    def config_request(self) -> ConfigFilesRequest:
        # Refer to https://golangci-lint.run/usage/configuration
        # for how config files are discovered.
        return ConfigFilesRequest(
            specified=self.config,
            specified_option_name=f"[{self.options_scope}].config",
            discovery=self.config_discovery,
            check_existence=[
                ".golangci.json",
                ".golangci.toml",
                ".golangci.yaml",
                ".golangci.yml",
            ],
        )

    def generate_exe(self, platform: Platform) -> str:
        return (
            f"./golangci-lint-{self.version}-"
            f"{self.url_platform_mapping[platform.value]}/golangci-lint"
        )


text:
/**
 * Store that gets data from any set of web services that implement
 * the JBrowse REST API.
 */
define("JBrowse/Store/SeqFeature/REST", [
           'dojo/_base/declare',
           'dojo/_base/lang',
           'dojo/_base/array',
           'dojo/io-query',
           'dojo/request',
           'dojo/Deferred',
           'JBrowse/Store/LRUCache',
           'JBrowse/Store/SeqFeature',
           'JBrowse/Store/DeferredFeaturesMixin',
           'JBrowse/Store/DeferredStatsMixin',
           'JBrowse/Util',
           'JBrowse/Model/SimpleFeature'
       ],
       function(
           declare,
           lang,
           array,
           ioquery,
           dojoRequest,
           Deferred,
           LRUCache,
           SeqFeatureStore,
           DeferredFeaturesMixin,
           DeferredStatsMixin,
           Util,
           SimpleFeature
       ) {

return declare( SeqFeatureStore,
{

    constructor: function( args ) {
        this.region_cache_hits = 0; //< stats mostly for unit tests

        // make sure the baseUrl has a trailing slash
        this.baseUrl = args.baseUrl || this.config.baseUrl;
        if( this.baseUrl.charAt( this.baseUrl.length-1 ) != '/' )
            this.baseUrl = this.baseUrl + '/';

        // enable feature density bin fetching if turned on
        if( this.config.region_feature_densities && ! this.getRegionFeatureDensities ) {
            this.getRegionFeatureDensities = this._getRegionFeatureDensities;
        }
    },

    _defaultConfig: function() {
        return {
            noCache: false
        };
    },

    getGlobalStats: function( callback, errorCallback ) {
        var url = this._makeURL( 'stats/global' );
        this._get({ url: url, type: 'globalStats' }, callback, errorCallback );
    },

    getRegionStats: function( query, successCallback, errorCallback ) {

        if( ! this.config.region_stats ) {
            this._getRegionStats.apply( this, arguments );
            return;
        }

        query = this._assembleQuery( query );
        var url = this._makeURL( 'stats/region', query );
        this._get( { url: url, query: query, type: 'regionStats' }, successCallback, errorCallback );
    },

    getFeatures: function( query, featureCallback, endCallback, errorCallback ) {
        var thisB = this;
        query = this._assembleQuery( query );
        var url = this._makeURL( 'features', query );

        // look for cached feature regions if configured to do so
        var cachedFeatureRegions;
        if( this.config.feature_range_cache
            && ! this.config.noCache
            && ( cachedFeatureRegions = this._getCachedFeatureRegions( query ) )
          ) {
            this.region_cache_hits++;
            this._makeFeaturesFromCachedRegions( cachedFeatureRegions, query, featureCallback, endCallback, errorCallback );
        }
        // otherwise just fetch and cache like all the other requests
        else {
            this._get( { url: url, query: query, type: 'features' },
                       dojo.hitch( this, '_makeFeatures',
                                   featureCallback, endCallback, errorCallback
                                 ),
                       errorCallback
                     );
        }
    },

    // look in the REST backend's cache for cached feature requests
    // that are relevant to the given query params (overlap the
    // start/end region, and match other params).  return an array
    // like [ {features: [...], start: 123, end: 456 }, ... ]
    _getCachedFeatureRegions: function( query ) {
        var cache = this._getCache();

        function tilingIsComplete( regions, start, end ) {
            regions.sort( function(a,b) { return a.start - b.start; });
            var coverStart = regions[0].start,
                  coverEnd;
            var i;
            var tilingComplete;
            for( i = 0; !tilingComplete && i < regions.length; i++ ) {
                if( coverEnd === undefined || regions[i].start <= coverEnd && regions[i].end > coverEnd ) {
                    coverEnd = regions[i].end;
                    tilingComplete = coverStart <= start && coverEnd >= end;
                }
            }

            if( tilingComplete ) {
                // touch all of the regions we processed in the cache,
                // cause we are going to use them
                for( i--; i >= 0; i-- )
                    cache.touchRecord( regions[i].cacheRecord );

                return true;
            }

            return false;
        }

        function queriesMatch( q1, q2 ) {
            var keys = Util.dojof.keys( q1 ).concat( Util.dojof.keys( q2 ) );
            for( var k in q1 ) {
                if( k == 'start' || k == 'end' ) continue;
                if( q1[k] != q2[k] )
                    return false;
            }
            for( var k in q2 ) {
                if( k == 'start' || k == 'end' ) continue;
                if( q1[k] != q2[k] )
                    return false;
            }
            return true;
        }

        var relevantRegions = [];
        if( cache.some(
                function( cacheRecord ) {
                    var cachedRequest = cacheRecord.value.request;
                    var cachedResponse = cacheRecord.value.response;
                    if( cachedRequest.type != 'features' || ! cachedResponse )
                        return false;
                    if( ! queriesMatch( cachedRequest.query, query ) )
                        return false;
                    if( ! ( cachedRequest.query.end < query.start || cachedRequest.query.start > query.end ) ) {
                        relevantRegions.push(
                            { features:    cachedResponse.features,
                              start:       cachedRequest.query.start,
                              end:         cachedRequest.query.end,
                              cacheRecord: cacheRecord
                            });
                        if( tilingIsComplete( relevantRegions, query.start, query.end ) )
                            return true;
                    }
                    return false;
                },
                this )
          ) {
              return relevantRegions;
          }
        return null;
    },

    // given an array of records of cached feature data like that
    // returned by _getCachedFeatureRegions, make feature objects from
    // them and emit them via the callbacks
    _makeFeaturesFromCachedRegions: function( cachedFeatureRegions, query, featureCallback, endCallback, errorCallback ) {
        // gather and uniqify all the relevant feature data objects from the cached regions
        var seen = {};
        var featureData = [];
        array.forEach( cachedFeatureRegions, function( region ) {
            if( region && region.features ) {
                array.forEach( region.features, function( feature ) {
                    if( ! seen[ feature.uniqueID ] ) {
                        seen[feature.uniqueID] = true;
                        if( !( feature.start > query.end || feature.end < query.start ) )
                            featureData.push( feature );
                    }
                });
            }
        });

        // iterate over them and make feature objects from them
        this._makeFeatures( featureCallback, endCallback, errorCallback, { features: featureData } );
    },

    // this method is copied to getRegionFeatureDensities in the
    // constructor if config.region_feature_densities is true
    _getRegionFeatureDensities: function( query, histDataCallback, errorCallback ) {
        var url = this._makeURL( 'stats/regionFeatureDensities', this._assembleQuery( query ) );
        this._get( { url: url}, histDataCallback, errorCallback );

        // query like:
        //    { ref: 'ctgA, start: 123, end: 456, basesPerBin: 200 }

        // callback like:
        //   histDataCallback({
        //     "bins":  [ 51,50,58,63,57,57,65,66,63,61,56,49,50,47,39,38,54,41,50,71,61,44,64,60,42 ],
        //     "stats": { "basesPerBin":"200","max":88,"mean":57.772 } //< `max` used to set the Y scale
        //   });

        // or error like:
        //   errorCallback( 'aieeee i died' );
    },
    // STUB method to satisfy requirements when setting the REST track to a VCF type
    getVCFHeader: function( query, filterFunctionCallback, errorCallback ) {
        return new Deferred(function() { /* console.log("REST store getVCFHeader"); */ });
    },

    clearCache: function() {
        delete this._cache;
    },

    // HELPER METHODS
    _get: function( request, callback, errorCallback ) {
        var thisB = this;
        if( this.config.noCache )
            dojoRequest( request.url, {
                         method: 'GET',
                         handleAs: 'json'
                     }).then(
                         callback,
                         this._errorHandler( errorCallback )
                     );
        else
            this._getCache().get( request, function( record, error ) {
                                      if( error )
                                          thisB._errorHandler(errorCallback)(error);
                                      else
                                          callback( record.response );
                                  });

    },

    _getCache: function() {
        var thisB = this;
        return this._cache || (
            this._cache = new LRUCache(
                {
                    name: 'REST data cache '+this.name,
                    maxSize: 25000, // cache up to about 5MB of data (assuming about 200B per feature)
                    sizeFunction: function( data ) { return data.length || 1; },
                    fillCallback: function( request, callback ) {
                        var get = dojoRequest( request.url, { method: 'GET', handleAs: 'json' },
                                               true // work around dojo/request bug
                                             );
                        get.then(
                            function(data) {
                                var nocacheResponse = /no-cache/.test(get.response.getHeader('Cache-Control'))
                                    || /no-cache/.test(get.response.getHeader('Pragma'));
                                callback({ response: data, request: request }, null, {nocache: nocacheResponse});
                            },
                            thisB._errorHandler( lang.partial( callback, null ) )
                        );
                    }
                }));
    },

    _errorHandler: function( handler ) {
        handler = handler || function(e) {
            console.error( e, e.stack );
            throw e;
        };
        return dojo.hitch( this, function( error ) {
            var httpStatus = ((error||{}).response||{}).status;
            if( httpStatus >= 400 ) {
                handler( "HTTP " + httpStatus + " fetching "+error.response.url+" : "+error.response.text );
            }
            else {
                handler( error );
            }
        });
    },

    _assembleQuery: function( query ) {
            return lang.mixin(
                { ref: (this.refSeq||{}).name },
                this.config.query || {},
                query || {}
            );
    },

    _makeURL: function( subpath, query ) {
        var url = this.baseUrl + subpath;

        if( query ) {
            if( query.ref ) {
                url += '/' + query.ref;
                query = lang.mixin({}, query );
                delete query.ref;
            }

            query = ioquery.objectToQuery( query );
            if( query )
                url += '?' + query;
        }

        return url;
    },

    _makeFeatures: function( featureCallback, endCallback, errorCallback, featureData ) {
        var features;
        if( featureData && ( features = featureData.features ) ) {
            for( var i = 0; i < features.length; i++ ) {
                featureCallback( this._makeFeature( features[i] ) );
            }
        }

        endCallback();
    },

    _parseInt: function( data ) {
        array.forEach(['start','end','strand'], function( field ) {
            if( field in data )
                data[field] = parseInt( data[field] );
        });
        if( 'score' in data )
            data.score = parseFloat( data.score );
        if( 'subfeatures' in data )
            for( var i=0; i<data.subfeatures.length; i++ )
                this._parseInt( data.subfeatures[i] );
    },

    _makeFeature: function( data, parent ) {
        this._parseInt( data );
        return new SimpleFeature( { data: data, parent: parent } );
    }
});
});


text:
#pragma once
#include "../utils/all.h"
#include "../transfer/transfer.h"
#include "../transfer/ServerWorkerRoute.h"

namespace swift_snails {

/**
 * base class of worker
 */
class ClusterWorker {
public:
  ClusterWorker() { init_transfer(); }

  Transfer<ServerWorkerRoute> &transfer() { return _transfer; }
  /**
   * @brief called after worker finish working
   */
  void finalize() {
    RAW_LOG(WARNING, "########################################");
    RAW_LOG(WARNING, "     Worker [%d] terminate normally",
            global_mpi().rank());
    RAW_LOG(WARNING, "########################################");
  }
  /**
   * @brief to tell whether local node's Worker is valid
   */
  bool is_valid() const { return _transfer.client_id() >= 0; }

protected:
  void init_transfer() {
    LOG(WARNING) << "init worker's transfer ...";
    std::string listen_addr =
        global_config().get("worker", "listen_addr").to_string();
    int service_thread_num =
        global_config().get("worker", "listen_thread_num").to_int32();
    int async_thread_num =
        global_config().get("worker", "async_exec_num").to_int32();
    if (!listen_addr.empty()) {
      _transfer.listen(listen_addr);
    } else {
      _transfer.listen();
    }
    _transfer.init_async_channel(async_thread_num);
    _transfer.set_thread_num(service_thread_num);
    _transfer.service_start();
  }

private:
  Transfer<ServerWorkerRoute> _transfer;
}; // end class Worker

inline ClusterWorker &global_worker() {
  static ClusterWorker worker;
  return worker;
}

}; // end namespace swift_snails


text:
<?php
return array (
  'Member in these spaces' => 'Partecipa in questi space',
);


text:
class test(HTMLParser.HTMLParser):
    intable = False
    titling = False
    capturing = True
    cdata = []
    out = u''
    def handle_starttag(self, tag, attrs):
        print tag,attrs
        if dict(attrs).get('class', None) == 'm': self.capturing = False
        if tag.lower() == 'table': self.intable = True
        elif tag.lower() == 'title': self.titling = True
        elif tag.lower() == 'td' and dict(attrs).get('class', None) != 'm':
            self.capturing = True
    def handle_endtag(self, tag):
        if self.titling and tag.lower() == 'title': self.titling=False
        if self.capturing:
            out = u'\n'.join(self.cdata)
            self.cdata = []
            self.out += '\n' + out
            #print out
    def handle_data(self, data):
        if self.capturing and self.intable and data.strip() != '': self.cdata.append(data.decode('utf-8'))
        if self.titling: self.cdata.append(u'HEADING: %s' % data.decode('utf-8'))

b=test()
for x in range(1,14):
    with file('3_%02d.html' % x, 'rU') as a: (b.reset(),setattr(b, 'capturing', True), b.feed(a.read()))
a = file('2_01.html')
b.feed(a.read())


text:
<?xml version="1.0" encoding="UTF-8"?><testrun name="GRADSIntfTest" project="GRADS" tests="18" started="18" failures="1" errors="1" ignored="0">
  <testsuite name="edu.sc.csce740.test.GRADSIntfTest" time="0.268">
    <testcase name="testGetStudentsIDsPasses" classname="edu.sc.csce740.test.GRADSIntfTest" time="0.031">
      <failure>java.lang.AssertionError: array lengths differed, expected.length=10 actual.length=5
	at org.junit.Assert.fail(Assert.java:88)
	at org.junit.internal.ComparisonCriteria.assertArraysAreSameLength(ComparisonCriteria.java:71)
	at org.junit.internal.ComparisonCriteria.arrayEquals(ComparisonCriteria.java:32)
	at org.junit.Assert.internalArrayEquals(Assert.java:473)
	at org.junit.Assert.assertArrayEquals(Assert.java:265)
	at org.junit.Assert.assertArrayEquals(Assert.java:280)
	at edu.sc.csce740.test.GRADSIntfTest.testGetStudentsIDsPasses(GRADSIntfTest.java:213)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:606)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
	at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
	at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
	at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
	at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
	at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

</failure>
    </testcase>
    <testcase name="testGetStudentsIDsExceptionThrown" classname="edu.sc.csce740.test.GRADSIntfTest" time="0.016"/>
    <testcase name="testSetUserExceptionThrown" classname="edu.sc.csce740.test.GRADSIntfTest" time="0.014"/>
    <testcase name="testClearSession" classname="edu.sc.csce740.test.GRADSIntfTest" time="0.01"/>
    <testcase name="testGetUserPasses" classname="edu.sc.csce740.test.GRADSIntfTest" time="0.009"/>
    <testcase name="simulateCoursesPasses" classname="edu.sc.csce740.test.GRADSIntfTest" time="0.107"/>
    <testcase name="testSetUserPasses" classname="edu.sc.csce740.test.GRADSIntfTest" time="0.006"/>
    <testcase name="testUpdateTranscriptPasses" classname="edu.sc.csce740.test.GRADSIntfTest" time="0.028"/>
    <testcase name="testAddNoteStudentExceptionThrown" classname="edu.sc.csce740.test.GRADSIntfTest" time="0.004"/>
    <testcase name="testGenerateProgressSummaryPHDPasses" classname="edu.sc.csce740.test.GRADSIntfTest" time="0.008">
      <error>edu.sc.csce740.exception.DataNotRetrievedException: Can not load records file
	at edu.sc.csce740.test.GRADSIntfTest.testGenerateProgressSummaryPHDPasses(GRADSIntfTest.java:420)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:606)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
	at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
	at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
	at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
	at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
	at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

</error>
    </testcase>
    <testcase name="testGetTranscriptPasses" classname="edu.sc.csce740.test.GRADSIntfTest" time="0.008"/>
    <testcase name="testUpdateTranscriptThrowException" classname="edu.sc.csce740.test.GRADSIntfTest" time="0.003"/>
    <testcase name="testAddNoteExceptionThrown" classname="edu.sc.csce740.test.GRADSIntfTest" time="0.004"/>
    <testcase name="testAddNotePasses" classname="edu.sc.csce740.test.GRADSIntfTest" time="0.004"/>
    <testcase name="testGetTranscriptPassesExceptionThrown" classname="edu.sc.csce740.test.GRADSIntfTest" time="0.004"/>
    <testcase name="testGetUserFails" classname="edu.sc.csce740.test.GRADSIntfTest" time="0.004"/>
    <testcase name="testUpdateTranscriptThrowTempException" classname="edu.sc.csce740.test.GRADSIntfTest" time="0.004"/>
    <testcase name="simulateCoursesThrowsException" classname="edu.sc.csce740.test.GRADSIntfTest" time="0.004"/>
  </testsuite>
</testrun>


text:
6850js
======

ACIA 6850 JavaScript emulator

Usage
-----

(a.k.a. The API)

You can use 6850 as standard JS file, AMD or CommonJS module.

- new MC6850() - get an instance
- instance.reset() - resets the circuit
- instance.setData(byte) - write data to data register
- instance.getData() - read data from data register
- instance.getStatus() - get status byte
- instance.setControl() - set control byte
- instance.receive(byte) - emulates receiving data via serial interface
- instance.transmit(callback) - hooks an event. Callback is called when data byte is sended via serial interface. Callback has single parameter: cb(byte)

6850js emulates just basic operation (transmit, receive). Doesn't provide parity check etc. It works "at full speed", not real timing.

Tests
-----

6850js is slightly tested with qUnit - just a basic functionality at this moment

Roadmap
-------

- Interrupts doesn't work now


text:
package org.apache.tapestry5.func;

import org.testng.annotations.Test;

public class StringPredicateTests extends BaseFuncTest
{
    @Test
    public void prefix_predicate()
    {
        Flow<String> names = F.flow("Howard", "Henry", "Anna", "Hubert");

        assertFlowValues(names.remove(F.startsWith("H")), "Anna");
    }

    @Test
    public void case_insensitive_prefix_predicate()
    {
        Flow<String> names = F.flow("Howard", "Henry", "Anna", "Hubert");

        assertFlowValues(names.filter(F.startsWithIgnoringCase("h")), "Howard", "Henry", "Hubert");
    }

    @Test
    public void suffix_predicate()
    {
        Flow<String> names = F.flow("Ted", "Charly", "Fred", "Anna");

        assertFlowValues(names.filter(F.endsWith("red")), "Fred");
    }

    @Test
    public void case_insensitive_suffix_precicate()
    {
        Flow<String> names = F.flow("Ted", "Charly", "Fred", "Anna");

        assertFlowValues(names.filter(F.endsWithIgnoringCase("RED")), "Fred");
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>NamesQueryFilter (apache-cassandra API)</title>
<meta name="date" content="2015-06-05">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.cassandra.db.filter

Class NamesQueryFilter

java.lang.Object

org.apache.cassandra.db.filter.NamesQueryFilter

All Implemented Interfaces:

IDiskAtomFilter

public class NamesQueryFilter
extends java.lang.Object
implements IDiskAtomFilter

Nested Class Summary

Nested Classes

Modifier and Type
Class and Description

static class
NamesQueryFilter.Serializer

Field Summary

Fields

Modifier and Type
Field and Description

java.util.SortedSet<CellName>
columns

Constructor Summary

Constructors

Constructor and Description

NamesQueryFilter(java.util.SortedSet<CellName> columns)

NamesQueryFilter(java.util.SortedSet<CellName> columns,
                boolean countCQL3Rows)

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

NamesQueryFilter
cloneShallow()

void
collectReducedColumns(ColumnFamily container,
                     java.util.Iterator<Cell> reducedColumns,
                     DecoratedKey key,
                     int gcBefore,
                     long now)

collects columns from reducedColumns into returnCF.

ColumnCounter
columnCounter(CellNameType comparator,
             long now)

boolean
countCQL3Rows()

boolean
countCQL3Rows(CellNameType comparator)

java.util.Comparator<Cell>
getColumnComparator(CellNameType comparator)

java.util.Iterator<Cell>
getColumnIterator(ColumnFamily cf)

returns an iterator that returns columns from the given columnFamily
 matching the Filter criteria in sorted order.

OnDiskAtomIterator
getColumnIterator(DecoratedKey key,
                 ColumnFamily cf)

int
getLiveCount(ColumnFamily cf,
            long now)

java.util.Iterator<RangeTombstone>
getRangeTombstoneIterator(ColumnFamily source)

OnDiskAtomIterator
getSSTableColumnIterator(SSTableReader sstable,
                        DecoratedKey key)

returns an iterator that returns columns from the given SSTable
 matching the Filter criteria in sorted order.

OnDiskAtomIterator
getSSTableColumnIterator(SSTableReader sstable,
                        FileDataInput file,
                        DecoratedKey key,
                        RowIndexEntry indexEntry)

Get an iterator that returns columns from the given SSTable using the opened file
 matching the Filter criteria in sorted order.

boolean
isFullyCoveredBy(ColumnFamily cf,
                long now)

Whether the provided cf, that is assumed to contain the head of the
 partition, contains enough data to cover this filter.

boolean
isHeadFilter()

boolean
isReversed()

boolean
maySelectPrefix(CType type,
               Composite prefix)

boolean
shouldInclude(SSTableReader sstable)

java.lang.String
toString()

void
updateColumnsLimit(int newLimit)

NamesQueryFilter
withUpdatedColumns(java.util.SortedSet<CellName> newColumns)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

columns

public final java.util.SortedSet<CellName> columns

Constructor Detail

NamesQueryFilter

public NamesQueryFilter(java.util.SortedSet<CellName> columns)

NamesQueryFilter

public NamesQueryFilter(java.util.SortedSet<CellName> columns,
                        boolean countCQL3Rows)

Method Detail

cloneShallow

public NamesQueryFilter cloneShallow()

Specified by:

cloneShallow in interface IDiskAtomFilter

withUpdatedColumns

public NamesQueryFilter withUpdatedColumns(java.util.SortedSet<CellName> newColumns)

getColumnIterator

public java.util.Iterator<Cell> getColumnIterator(ColumnFamily cf)

Description copied from interface: IDiskAtomFilter

returns an iterator that returns columns from the given columnFamily
 matching the Filter criteria in sorted order.

Specified by:

getColumnIterator in interface IDiskAtomFilter

getColumnIterator

public OnDiskAtomIterator getColumnIterator(DecoratedKey key,
                                            ColumnFamily cf)

Specified by:

getColumnIterator in interface IDiskAtomFilter

getSSTableColumnIterator

public OnDiskAtomIterator getSSTableColumnIterator(SSTableReader sstable,
                                                   DecoratedKey key)

Description copied from interface: IDiskAtomFilter

returns an iterator that returns columns from the given SSTable
 matching the Filter criteria in sorted order.

Specified by:

getSSTableColumnIterator in interface IDiskAtomFilter

getSSTableColumnIterator

public OnDiskAtomIterator getSSTableColumnIterator(SSTableReader sstable,
                                                   FileDataInput file,
                                                   DecoratedKey key,
                                                   RowIndexEntry indexEntry)

Description copied from interface: IDiskAtomFilter

Get an iterator that returns columns from the given SSTable using the opened file
 matching the Filter criteria in sorted order.

Specified by:

getSSTableColumnIterator in interface IDiskAtomFilter

file - Already opened file data input, saves us opening another one

key - The key of the row we are about to iterate over

collectReducedColumns

public void collectReducedColumns(ColumnFamily container,
                                  java.util.Iterator<Cell> reducedColumns,
                                  DecoratedKey key,
                                  int gcBefore,
                                  long now)

Description copied from interface: IDiskAtomFilter

collects columns from reducedColumns into returnCF.  Termination is determined
 by the filter code, which should have some limit on the number of columns
 to avoid running out of memory on large rows.

Specified by:

collectReducedColumns in interface IDiskAtomFilter

getColumnComparator

public java.util.Comparator<Cell> getColumnComparator(CellNameType comparator)

Specified by:

getColumnComparator in interface IDiskAtomFilter

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Object

isReversed

public boolean isReversed()

Specified by:

isReversed in interface IDiskAtomFilter

updateColumnsLimit

public void updateColumnsLimit(int newLimit)

Specified by:

updateColumnsLimit in interface IDiskAtomFilter

getLiveCount

public int getLiveCount(ColumnFamily cf,
                        long now)

Specified by:

getLiveCount in interface IDiskAtomFilter

maySelectPrefix

public boolean maySelectPrefix(CType type,
                               Composite prefix)

Specified by:

maySelectPrefix in interface IDiskAtomFilter

shouldInclude

public boolean shouldInclude(SSTableReader sstable)

Specified by:

shouldInclude in interface IDiskAtomFilter

isFullyCoveredBy

public boolean isFullyCoveredBy(ColumnFamily cf,
                                long now)

Description copied from interface: IDiskAtomFilter

Whether the provided cf, that is assumed to contain the head of the
 partition, contains enough data to cover this filter.

Specified by:

isFullyCoveredBy in interface IDiskAtomFilter

isHeadFilter

public boolean isHeadFilter()

Specified by:

isHeadFilter in interface IDiskAtomFilter

countCQL3Rows

public boolean countCQL3Rows(CellNameType comparator)

Specified by:

countCQL3Rows in interface IDiskAtomFilter

countCQL3Rows

public boolean countCQL3Rows()

columnCounter

public ColumnCounter columnCounter(CellNameType comparator,
                                   long now)

Specified by:

columnCounter in interface IDiskAtomFilter

getRangeTombstoneIterator

public java.util.Iterator<RangeTombstone> getRangeTombstoneIterator(ColumnFamily source)

Specified by:

getRangeTombstoneIterator in interface IDiskAtomFilter

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2015 The Apache Software Foundation


text: a simple .net wrapper for instaflight search using instaflight api


text:
<?php namespace App\Exceptions;

use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
	protected $dontReport = [
		\Illuminate\Auth\AuthenticationException::class,
		\Illuminate\Auth\Access\AuthorizationException::class,
		\Symfony\Component\HttpKernel\Exception\HttpException::class,
		\Illuminate\Database\Eloquent\ModelNotFoundException::class,
		\Illuminate\Session\TokenMismatchException::class,
		\Illuminate\Validation\ValidationException::class,
	];

	public function report(Exception $exception)
	{
		parent::report($exception);
	}

	public function render($request, Exception $exception)
	{
		return parent::render($request, $exception);
	}

	protected function unauthenticated($request, AuthenticationException $exception)
	{
		if ($request->expectsJson()) {
			return response()->json(['error' => 'Unauthenticated.'], 401);
		}

		return redirect()->guest(route('login'));
	}
}


text:
using Client.MultiEntitySearch.ViewModels;
using SparkleXrm;
using SparkleXrm.GridEditor;
using System;
using System.Collections.Generic;
using Xrm.Sdk;

namespace Client.InlineSubGrids.ViewModels
{
    public class ActivitySubGridViewModel : ViewModelBase
    {

        public FetchQuerySettings ViewConfig;
        private QueryParser _parser;
        #region Constructors
        public ActivitySubGridViewModel()
        {

            // Get the Quick Find View for the entity
            string getviewfetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                              <entity name='savedquery'>
                                <attribute name='name' />
                                <attribute name='fetchxml' />
                                <attribute name='layoutxml' />
                                <attribute name='returnedtypecode' />
                                <filter type='and'>
                                <filter type='or'>";

            getviewfetchXml += @"<condition attribute='returnedtypecode' operator='eq' value='" + "4200" + @"'/>";

            getviewfetchXml += @"
                                    </filter>
                                 <condition attribute='isquickfindquery' operator='eq' value='1'/>
                                    <condition attribute='isdefault' operator='eq' value='1'/>
                                </filter>

                              </entity>
                            </fetch>";
            // Get the Quick Find View
            EntityCollection quickFindQuery = OrganizationServiceProxy.RetrieveMultiple(getviewfetchXml);
            _parser = new QueryParser();
            Entity view = quickFindQuery.Entities[0];
            string fetchXml = view.GetAttributeValueString("fetchxml");
            string layoutXml = view.GetAttributeValueString("layoutxml");

            // Parse the fetch and layout to get the attributes and columns
            ViewConfig = _parser.Parse(fetchXml, layoutXml);
            ViewConfig.DataView = new EntityDataViewModel(10, typeof(Entity), true);

            // Load the display name metadata
            _parser.QueryDisplayNames();

        }
        #endregion

        #region Methods
        public void Init()
        {
            ViewConfig.DataView.FetchXml = _parser.GetFetchXmlForQuery(ViewConfig, "%" + "" + "%");
            ViewConfig.DataView.Reset();
            ViewConfig.DataView.ResetPaging();
            ViewConfig.DataView.Refresh();
        }
        #endregion

    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<fileResource exportedWithPermissions="false" dataFile="Yellow.data">
    <folder>/public/Samples/Resources/Images</folder>
    <name>Yellow</name>
    <version>0</version>
    <label>Yellow</label>
    <creationDate>2015-01-14T17:45:35.586+01:00</creationDate>
    <updateDate>2014-09-24T23:19:27.669+02:00</updateDate>
    <fileType>img</fileType>
</fileResource>


text:
v1.7
====
- Setting to determine if homework of today is shown

- Automatic reminders are deleted if corresponding homework is marked as done

- Settings to control when automatic reminders are set

- Automatic reminders are not re-created when they are deleted once

- Changed references to E1b to E2b

v1.6
====
- Possibility to mark homework as done

- Refresh button added

- Use offline cache if no internet connection is present

- Setting to limit mobile data usage

- Bug fixed where notifications would not always be shown

v1.5
====
- Offline cache

- Filter homework by subject

- Automatic reminders

- Fix several bugs ands crashes

v1.4
====
- Possibility to let yourself be reminded of homework

- Fix bug, where NoUpdateDialog might not be shown

- Fix bug, where the app would crash if exited while certain dialogs were open

v1.3
====
- Show NoUpdateDialog even when Activity is paused while checking for updates

- Ability to copy homework entries

- Homework ListItems take up entire width

v1.2
====
- Fix crash when MainActivity is paused while the app is checking for new updates

- Remove unnecessary Settings button in HomeworkDetailActivity

v1.1
====
Initial release of the app.

Just showing homework.


text:
require_relative '../model'
module Spaceship
  class ConnectAPI
    class AppDataUsage
      include Spaceship::ConnectAPI::Model

      attr_accessor :category
      attr_accessor :grouping
      attr_accessor :purpose
      attr_accessor :data_protection

      attr_mapping({
        "category" => "category",
        "grouping" => "grouping",
        "dataProtection" => "data_protection"
      })

      def self.type
        return "appDataUsages"
      end

      #
      # Helpers
      #

      def is_not_collected?
        return false unless data_protection
        return data_protection.id == "DATA_NOT_COLLECTED"
      end

      #
      # API
      #

      def self.all(app_id:, filter: {}, includes: nil, limit: nil, sort: nil)
        raise "app_id is required " if app_id.nil?

        resps = Spaceship::ConnectAPI.get_app_data_usages(app_id: app_id, filter: filter, includes: includes, limit: limit, sort: sort).all_pages
        return resps.flat_map(&:to_models)
      end

      def self.create(app_id:, app_data_usage_category_id: nil, app_data_usage_protection_id: nil, app_data_usage_purpose_id: nil)
        raise "app_id is required " if app_id.nil?

        resp = Spaceship::ConnectAPI.post_app_data_usage(
          app_id: app_id,
          app_data_usage_category_id: app_data_usage_category_id,
          app_data_usage_protection_id: app_data_usage_protection_id,
          app_data_usage_purpose_id: app_data_usage_purpose_id
        )
        return resp.to_models.first
      end

      def delete!
        Spaceship::ConnectAPI.delete_app_data_usage(app_data_usage_id: id)
      end
    end
  end
end


text:
package it.prisma.dal.entities.paas.services.appaas;
// Generated 8-ott-2014 17.56.50 by Hibernate Tools 4.0.0

import javax.persistence.Column;
import javax.persistence.Embeddable;

/**
 * APPaaSEnvironmentDetailsViewId generated by hbm2java
 */
@Embeddable
public class APPaaSEnvironmentDetailsViewId  implements java.io.Serializable {

     /**
	 *
	 */
	private static final long serialVersionUID = 970668916386255297L;
	private long Id;
     private long Id_1;
     private String serverType;
     private long Id_2;

    public APPaaSEnvironmentDetailsViewId() {
    }

    public APPaaSEnvironmentDetailsViewId(long Id, long Id_1, String serverType, long Id_2) {
       this.Id = Id;
       this.Id_1 = Id_1;
       this.serverType = serverType;
       this.Id_2 = Id_2;
    }

    @Column(name="APPaaSEnvironmentID", nullable=false)
    public long getId() {
        return this.Id;
    }

    public void setId(long Id) {
        this.Id = Id;
    }

    @Column(name="APPaaSID", nullable=false)
    public long getId_1() {
        return this.Id_1;
    }

    public void setId_1(long Id_1) {
        this.Id_1 = Id_1;
    }

    @Column(name="serverType", nullable=false, length=64)
    public String getServerType() {
        return this.serverType;
    }

    public void setServerType(String serverType) {
        this.serverType = serverType;
    }

    @Column(name="currentAppFile_ApplicationRepositoryEntryID", nullable=false)
    public long getId_2() {
        return this.Id_2;
    }

    public void setId_2(long Id_2) {
        this.Id_2 = Id_2;
    }

   public boolean equals(Object other) {
         if ( (this == other ) ) return true;
		 if ( (other == null ) ) return false;
		 if ( !(other instanceof APPaaSEnvironmentDetailsViewId) ) return false;
		 APPaaSEnvironmentDetailsViewId castOther = ( APPaaSEnvironmentDetailsViewId ) other;

		 return (this.getId()==castOther.getId())
 && (this.getId_1()==castOther.getId_1())
 && ( (this.getServerType()==castOther.getServerType()) || ( this.getServerType()!=null && castOther.getServerType()!=null && this.getServerType().equals(castOther.getServerType()) ) )
 && (this.getId_2()==castOther.getId_2());
   }

   public int hashCode() {
         int result = 17;

         result = 37 * result + (int) this.getId();
         result = 37 * result + (int) this.getId_1();
         result = 37 * result + ( getServerType() == null ? 0 : this.getServerType().hashCode() );
         result = 37 * result + (int) this.getId_2();
         return result;
   }

}