text:
package org.apache.nifi.processors.standard;

import org.apache.nifi.annotation.behavior.InputRequirement;
import org.apache.nifi.annotation.behavior.InputRequirement.Requirement;
import org.apache.nifi.annotation.behavior.SideEffectFree;
import org.apache.nifi.annotation.behavior.Stateful;
import org.apache.nifi.annotation.behavior.TriggerSerially;
import org.apache.nifi.annotation.behavior.TriggerWhenEmpty;
import org.apache.nifi.annotation.behavior.WritesAttribute;
import org.apache.nifi.annotation.behavior.WritesAttributes;
import org.apache.nifi.annotation.documentation.CapabilityDescription;
import org.apache.nifi.annotation.documentation.Tags;
import org.apache.nifi.annotation.lifecycle.OnScheduled;
import org.apache.nifi.annotation.lifecycle.OnStopped;
import org.apache.nifi.components.AllowableValue;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.components.ValidationResult;
import org.apache.nifi.components.state.Scope;
import org.apache.nifi.components.state.StateManager;
import org.apache.nifi.components.state.StateMap;
import org.apache.nifi.expression.ExpressionLanguageScope;
import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.flowfile.attributes.CoreAttributes;
import org.apache.nifi.logging.ComponentLog;
import org.apache.nifi.processor.AbstractProcessor;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.processor.ProcessSession;
import org.apache.nifi.processor.ProcessorInitializationContext;
import org.apache.nifi.processor.Relationship;
import org.apache.nifi.processor.exception.ProcessException;
import org.apache.nifi.processor.io.OutputStreamCallback;
import org.apache.nifi.processor.util.StandardValidators;
import org.apache.nifi.util.StringUtils;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;

@SideEffectFree
@TriggerSerially
@TriggerWhenEmpty
@InputRequirement(Requirement.INPUT_REQUIRED)
@Tags({"monitor", "flow", "active", "inactive", "activity", "detection"})
@CapabilityDescription("Monitors the flow for activity and sends out an indicator when the flow has not had any data for "
        + "some specified amount of time and again when the flow's activity is restored")
@WritesAttributes({
    @WritesAttribute(attribute = "inactivityStartMillis", description = "The time at which Inactivity began, in the form of milliseconds since Epoch"),
    @WritesAttribute(attribute = "inactivityDurationMillis", description = "The number of milliseconds that the inactivity has spanned")})
@Stateful(scopes = Scope.CLUSTER, description = "MonitorActivity stores the last timestamp at each node as state, so that it can examine activity at cluster wide." +
        "If 'Copy Attribute' is set to true, then flow file attributes are also persisted.")
public class MonitorActivity extends AbstractProcessor {

    public static final AllowableValue SCOPE_NODE = new AllowableValue("node");
    public static final AllowableValue SCOPE_CLUSTER = new AllowableValue("cluster");
    public static final AllowableValue REPORT_NODE_ALL = new AllowableValue("all");
    public static final AllowableValue REPORT_NODE_PRIMARY = new AllowableValue("primary");

    public static final PropertyDescriptor THRESHOLD = new PropertyDescriptor.Builder()
            .name("Threshold Duration")
            .description("Determines how much time must elapse before considering the flow to be inactive")
            .required(true)
            .addValidator(StandardValidators.TIME_PERIOD_VALIDATOR)
            .defaultValue("5 min")
            .build();
    public static final PropertyDescriptor CONTINUALLY_SEND_MESSAGES = new PropertyDescriptor.Builder()
            .name("Continually Send Messages")
            .description("If true, will send inactivity indicator continually every Threshold Duration amount of time until activity is restored; "
                    + "if false, will send an indicator only when the flow first becomes inactive")
            .required(true)
            .allowableValues("true", "false")
            .defaultValue("false")
            .build();
    public static final PropertyDescriptor ACTIVITY_RESTORED_MESSAGE = new PropertyDescriptor.Builder()
            .name("Activity Restored Message")
            .description("The message that will be the content of FlowFiles that are sent to 'activity.restored' relationship")
            .required(true)
            .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES)
            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
            .defaultValue("Activity restored at time: ${now():format('yyyy/MM/dd HH:mm:ss')} after being inactive for ${inactivityDurationMillis:toNumber():divide(60000)} minutes")
            .build();
    public static final PropertyDescriptor INACTIVITY_MESSAGE = new PropertyDescriptor.Builder()
            .name("Inactivity Message")
            .description("The message that will be the content of FlowFiles that are sent to the 'inactive' relationship")
            .required(true)
            .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES)
            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
            .defaultValue("Lacking activity as of time: ${now():format('yyyy/MM/dd HH:mm:ss')}; flow has been inactive for ${inactivityDurationMillis:toNumber():divide(60000)} minutes")
            .build();
    public static final PropertyDescriptor COPY_ATTRIBUTES = new PropertyDescriptor.Builder()
            .name("Copy Attributes")
            .description("If true, will copy all flow file attributes from the flow file that resumed activity to the newly created indicator flow file")
            .required(false)
            .allowableValues("true", "false")
            .defaultValue("false")
            .build();
    public static final PropertyDescriptor MONITORING_SCOPE = new PropertyDescriptor.Builder()
            .name("Monitoring Scope")
            .description("Specify how to determine activeness of the flow. 'node' means that activeness is examined at individual node separately." +
                    " It can be useful if DFM expects each node should receive flow files in a distributed manner." +
                    " With 'cluster', it defines the flow is active while at least one node receives flow files actively." +
                    " If NiFi is running as standalone mode, this should be set as 'node'," +
                    " if it's 'cluster', NiFi logs a warning message and act as 'node' scope.")
            .required(true)
            .allowableValues(SCOPE_NODE, SCOPE_CLUSTER)
            .defaultValue(SCOPE_NODE.getValue())
            .build();
    public static final PropertyDescriptor REPORTING_NODE = new PropertyDescriptor.Builder()
            .name("Reporting Node")
            .description("Specify which node should send notification flow-files to inactive and activity.restored relationships." +
                    " With 'all', every node in this cluster send notification flow-files." +
                    " 'primary' means flow-files will be sent only from a primary node." +
                    " If NiFi is running as standalone mode, this should be set as 'all'," +
                    " even if it's 'primary', NiFi act as 'all'.")
            .required(true)
            .allowableValues(REPORT_NODE_ALL, REPORT_NODE_PRIMARY)
            .addValidator(((subject, input, context) -> {
                boolean invalid = REPORT_NODE_PRIMARY.equals(input) && SCOPE_NODE.equals(context.getProperty(MONITORING_SCOPE).getValue());
                return new ValidationResult.Builder().subject(subject).input(input)
                        .explanation("'" + REPORT_NODE_PRIMARY + "' is only available with '" + SCOPE_CLUSTER + "' scope.").valid(!invalid).build();
            }))
            .defaultValue(REPORT_NODE_ALL.getValue())
            .build();

    public static final Relationship REL_SUCCESS = new Relationship.Builder()
            .name("success")
            .description("All incoming FlowFiles are routed to success")
            .build();
    public static final Relationship REL_INACTIVE = new Relationship.Builder()
            .name("inactive")
            .description("This relationship is used to transfer an Inactivity indicator when no FlowFiles are routed to 'success' for Threshold "
                    + "Duration amount of time")
            .build();
    public static final Relationship REL_ACTIVITY_RESTORED = new Relationship.Builder()
            .name("activity.restored")
            .description("This relationship is used to transfer an Activity Restored indicator when FlowFiles are routing to 'success' following a "
                    + "period of inactivity")
            .build();
    public static final Charset UTF8 = Charset.forName("UTF-8");

    private List<PropertyDescriptor> properties;
    private Set<Relationship> relationships;

    private final AtomicLong latestSuccessTransfer = new AtomicLong(System.currentTimeMillis());
    private final AtomicLong latestReportedNodeState = new AtomicLong(System.currentTimeMillis());
    private final AtomicBoolean inactive = new AtomicBoolean(false);
    private final AtomicBoolean connectedWhenLastTriggered = new AtomicBoolean(false);
    private final AtomicLong lastInactiveMessage = new AtomicLong(System.currentTimeMillis());
    public static final String STATE_KEY_LATEST_SUCCESS_TRANSFER = "MonitorActivity.latestSuccessTransfer";

    @Override
    protected void init(final ProcessorInitializationContext context) {
        final List<PropertyDescriptor> properties = new ArrayList<>();
        properties.add(THRESHOLD);
        properties.add(CONTINUALLY_SEND_MESSAGES);
        properties.add(INACTIVITY_MESSAGE);
        properties.add(ACTIVITY_RESTORED_MESSAGE);
        properties.add(COPY_ATTRIBUTES);
        properties.add(MONITORING_SCOPE);
        properties.add(REPORTING_NODE);
        this.properties = Collections.unmodifiableList(properties);

        final Set<Relationship> relationships = new HashSet<>();
        relationships.add(REL_SUCCESS);
        relationships.add(REL_INACTIVE);
        relationships.add(REL_ACTIVITY_RESTORED);
        this.relationships = Collections.unmodifiableSet(relationships);
    }

    @Override
    public Set<Relationship> getRelationships() {
        return relationships;
    }

    @Override
    protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
        return properties;
    }

    @OnScheduled
    public void onScheduled(final ProcessContext context) {
        // Check configuration.
        isClusterScope(context, true);
        resetLastSuccessfulTransfer();
        inactive.set(false);
    }

    protected void resetLastSuccessfulTransfer() {
        setLastSuccessfulTransfer(System.currentTimeMillis());
    }

    protected final void setLastSuccessfulTransfer(final long timestamp) {
        latestSuccessTransfer.set(timestamp);
        latestReportedNodeState.set(timestamp);
    }

    protected final long getLatestSuccessTransfer() {
        return latestSuccessTransfer.get();
    }

    private boolean isClusterScope(final ProcessContext context, boolean logInvalidConfig) {
        if (SCOPE_CLUSTER.equals(context.getProperty(MONITORING_SCOPE).getValue())) {
            if (getNodeTypeProvider().isConfiguredForClustering()) {
                return true;
            }
            if (logInvalidConfig) {
                getLogger().warn("NiFi is running as a Standalone mode, but 'cluster' scope is set." +
                        " Fallback to 'node' scope. Fix configuration to stop this message.");
            }
        }
        return false;
    }

    private boolean shouldReportOnlyOnPrimary(boolean isClusterScope, final ProcessContext context) {
        if (REPORT_NODE_PRIMARY.equals(context.getProperty(REPORTING_NODE).getValue())) {
            if (isClusterScope) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void onTrigger(final ProcessContext context, final ProcessSession session) {
        final long thresholdMillis = context.getProperty(THRESHOLD).asTimePeriod(TimeUnit.MILLISECONDS);
        final long now = System.currentTimeMillis();

        final ComponentLog logger = getLogger();
        final boolean copyAttributes = context.getProperty(COPY_ATTRIBUTES).asBoolean();
        final boolean isClusterScope = isClusterScope(context, false);
        final boolean isConnectedToCluster = context.isConnectedToCluster();
        final boolean shouldReportOnlyOnPrimary = shouldReportOnlyOnPrimary(isClusterScope, context);
        final List<FlowFile> flowFiles = session.get(50);

        if (isClusterScope(context, true)) {
            if (isReconnectedToCluster(isConnectedToCluster)) {
                reconcileState(context);
                connectedWhenLastTriggered.set(true);
            } else if (!isConnectedToCluster) {
                connectedWhenLastTriggered.set(false);
            }
        }

        boolean isInactive = false;
        long updatedLatestSuccessTransfer = -1;
        StateMap clusterState = null;

        if (flowFiles.isEmpty()) {
            final long previousSuccessMillis = latestSuccessTransfer.get();

            boolean sendInactiveMarker = false;

            isInactive = (now >= previousSuccessMillis + thresholdMillis);
            logger.debug("isInactive={}, previousSuccessMillis={}, now={}", new Object[]{isInactive, previousSuccessMillis, now});
            if (isInactive && isClusterScope && isConnectedToCluster) {
                // Even if this node has been inactive, there may be other nodes handling flow actively.
                // However, if this node is active, we don't have to look at cluster state.
                try {
                    clusterState = context.getStateManager().getState(Scope.CLUSTER);
                    if (clusterState != null && !StringUtils.isEmpty(clusterState.get(STATE_KEY_LATEST_SUCCESS_TRANSFER))) {
                        final long latestReportedClusterActivity = Long.valueOf(clusterState.get(STATE_KEY_LATEST_SUCCESS_TRANSFER));
                        isInactive = (now >= latestReportedClusterActivity + thresholdMillis);
                        if (!isInactive) {
                            // This node has been inactive, but other node has more recent activity.
                            updatedLatestSuccessTransfer = latestReportedClusterActivity;
                        }
                        logger.debug("isInactive={}, latestReportedClusterActivity={}", new Object[]{isInactive, latestReportedClusterActivity});
                    }
                } catch (IOException e) {
                    logger.error("Failed to access cluster state. Activity will not be monitored properly until this is addressed.", e);
                }
            }

            if (isInactive) {
                final boolean continual = context.getProperty(CONTINUALLY_SEND_MESSAGES).asBoolean();
                sendInactiveMarker = !inactive.getAndSet(true) || (continual && (now > lastInactiveMessage.get() + thresholdMillis));
            }

            if (sendInactiveMarker && shouldThisNodeReport(isClusterScope, shouldReportOnlyOnPrimary, context)) {
                lastInactiveMessage.set(System.currentTimeMillis());

                FlowFile inactiveFlowFile = session.create();
                inactiveFlowFile = session.putAttribute(inactiveFlowFile, "inactivityStartMillis", String.valueOf(previousSuccessMillis));
                inactiveFlowFile = session.putAttribute(inactiveFlowFile, "inactivityDurationMillis", String.valueOf(now - previousSuccessMillis));

                final byte[] outBytes = context.getProperty(INACTIVITY_MESSAGE).evaluateAttributeExpressions(inactiveFlowFile).getValue().getBytes(UTF8);
                inactiveFlowFile = session.write(inactiveFlowFile, new OutputStreamCallback() {
                    @Override
                    public void process(final OutputStream out) throws IOException {
                        out.write(outBytes);
                    }
                });

                session.getProvenanceReporter().create(inactiveFlowFile);
                session.transfer(inactiveFlowFile, REL_INACTIVE);
                logger.info("Transferred {} to 'inactive'", new Object[]{inactiveFlowFile});
            } else {
                context.yield();    // no need to dominate CPU checking times; let other processors run for a bit.
            }

        } else {
            session.transfer(flowFiles, REL_SUCCESS);
            updatedLatestSuccessTransfer = now;
            logger.info("Transferred {} FlowFiles to 'success'", new Object[]{flowFiles.size()});

            final long latestStateReportTimestamp = latestReportedNodeState.get();
            if (isClusterScope
                    && isConnectedToCluster
                    && (now - latestStateReportTimestamp) > (thresholdMillis / 3)) {
                // We don't want to hit the state manager every onTrigger(), but often enough to detect activeness.
                try {
                    final StateManager stateManager = context.getStateManager();
                    final StateMap state = stateManager.getState(Scope.CLUSTER);

                    final Map<String, String> newValues = new HashMap<>();

                    // Persist attributes so that other nodes can copy it
                    if (copyAttributes) {
                        newValues.putAll(flowFiles.get(0).getAttributes());
                    }
                    newValues.put(STATE_KEY_LATEST_SUCCESS_TRANSFER, String.valueOf(now));

                    if (state == null || state.getVersion() == -1) {
                        stateManager.setState(newValues, Scope.CLUSTER);
                    } else {
                        final String existingTimestamp = state.get(STATE_KEY_LATEST_SUCCESS_TRANSFER);
                        if (StringUtils.isEmpty(existingTimestamp)
                                || Long.parseLong(existingTimestamp) < now) {
                            // If this returns false due to race condition, it's not a problem since we just need
                            // the latest active timestamp.
                            stateManager.replace(state, newValues, Scope.CLUSTER);
                        } else {
                            logger.debug("Existing state has more recent timestamp, didn't update state.");
                        }
                    }
                    latestReportedNodeState.set(now);
                } catch (IOException e) {
                    logger.error("Failed to access cluster state. Activity will not be monitored properly until this is addressed.", e);
                }
            }
        }

        if (!isInactive) {
            final long inactivityStartMillis = latestSuccessTransfer.get();
            if (updatedLatestSuccessTransfer > -1) {
                latestSuccessTransfer.set(updatedLatestSuccessTransfer);
            }
            if (inactive.getAndSet(false) && shouldThisNodeReport(isClusterScope, shouldReportOnlyOnPrimary, context)) {
                FlowFile activityRestoredFlowFile = session.create();

                if (copyAttributes) {

                    final Map<String, String> attributes = new HashMap<>();
                    if (flowFiles.size() > 0) {
                        // copy attributes from the first flow file in the list
                        attributes.putAll(flowFiles.get(0).getAttributes());
                    } else if (clusterState != null) {
                        attributes.putAll(clusterState.toMap());
                        attributes.remove(STATE_KEY_LATEST_SUCCESS_TRANSFER);
                    }
                    // don't copy the UUID
                    attributes.remove(CoreAttributes.UUID.key());
                    activityRestoredFlowFile = session.putAllAttributes(activityRestoredFlowFile, attributes);
                }

                activityRestoredFlowFile = session.putAttribute(activityRestoredFlowFile, "inactivityStartMillis", String.valueOf(inactivityStartMillis));
                activityRestoredFlowFile = session.putAttribute(activityRestoredFlowFile, "inactivityDurationMillis", String.valueOf(now - inactivityStartMillis));

                final byte[] outBytes = context.getProperty(ACTIVITY_RESTORED_MESSAGE).evaluateAttributeExpressions(activityRestoredFlowFile).getValue().getBytes(UTF8);
                activityRestoredFlowFile = session.write(activityRestoredFlowFile, out -> out.write(outBytes));

                session.getProvenanceReporter().create(activityRestoredFlowFile);
                session.transfer(activityRestoredFlowFile, REL_ACTIVITY_RESTORED);
                logger.info("Transferred {} to 'activity.restored'", new Object[]{activityRestoredFlowFile});
            }
        }
    }

    @OnStopped
    public void onStopped(final ProcessContext context) {
        if (getNodeTypeProvider().isPrimary()) {
            final StateManager stateManager = context.getStateManager();
            try {
                stateManager.clear(Scope.CLUSTER);
            } catch (IOException e) {
                getLogger().error("Failed to clear cluster state due to " + e, e);
            }
        }
    }

    /**
     * Will return true when the last known state is "not connected" and the current state is "connected". This might
     * happen when during last @OnTrigger the node was not connected but currently it is (reconnection); or when the
     * processor is triggered first time (initial connection).
     *
     * This second case is due to safety reasons: it is possible that during the first trigger the node is not connected
     * to the cluster thus the default value of the #connected attribute is false and stays as false until it's proven
     * otherwise.
     *
     * @param isConnectedToCluster Current state of the connection.
     *
     * @return The node connected between the last trigger and the current one.
     */
    private boolean isReconnectedToCluster( final boolean isConnectedToCluster) {
        return !connectedWhenLastTriggered.get() && isConnectedToCluster;
    }

    private void reconcileState(final ProcessContext context)  {
        try {
            final StateMap state = context.getStateManager().getState(Scope.CLUSTER);
            final Map<String, String> newState = new HashMap<>();
            newState.putAll(state.toMap());

            final long validLastSuccessTransfer = StringUtils.isEmpty(state.get(STATE_KEY_LATEST_SUCCESS_TRANSFER))
                    ? latestSuccessTransfer.get()
                    : Math.max(Long.valueOf(state.get(STATE_KEY_LATEST_SUCCESS_TRANSFER)), latestSuccessTransfer.get());

            newState.put(STATE_KEY_LATEST_SUCCESS_TRANSFER, String.valueOf(validLastSuccessTransfer));
            context.getStateManager().replace(state, newState, Scope.CLUSTER);
        } catch (IOException e) {
            getLogger().error("Could not reconcile state after (re)connection! Reason: " + e.getMessage());
            throw new ProcessException(e);
        }
    }

    private boolean shouldThisNodeReport(final boolean isClusterScope, final boolean isReportOnlyOnPrimary, final ProcessContext context) {
        return !isClusterScope || ((!isReportOnlyOnPrimary || getNodeTypeProvider().isPrimary()) && context.isConnectedToCluster());
    }
}


text:
package org.apache.isis.core.commons.ensure;

public final class Assert {

    public static void assertEquals(final Object expected, final Object actual) {
        assertEquals("", expected, actual);
    }

    public static void assertEquals(final String message, final int expected, final int value) {
        if (expected != value) {
            throw new IsisAssertException(message + " expected " + expected + "; but was " + value);
        }
    }

    public static void assertEquals(final String message, final Object expected, final Object actual) {
        assertTrue(message + ": expected " + expected + " but was " + actual, (expected == null && actual == null) || (expected != null && expected.equals(actual)));
    }

    public static void assertFalse(final boolean flag) {
        assertFalse("expected false", flag);
    }

    public static void assertFalse(final String message, final boolean flag) {
        assertTrue(message, !flag);
    }

    public static void assertFalse(final String message, final Object target, final boolean flag) {
        assertTrue(message, target, !flag);
    }

    public static void assertNotNull(final Object object) {
        assertNotNull("", object);
    }

    public static void assertNotNull(final String message, final Object object) {
        assertTrue("unexpected null: " + message, object != null);
    }

    public static void assertNotNull(final String message, final Object target, final Object object) {
        assertTrue(message, target, object != null);
    }

    public static void assertNull(final Object object) {
        assertTrue("unexpected reference; should be null", object == null);
    }

    public static void assertNull(final String message, final Object object) {
        assertTrue(message, object == null);
    }

    public static void assertSame(final Object expected, final Object actual) {
        assertSame("", expected, actual);
    }

    public static void assertSame(final String message, final Object expected, final Object actual) {
        assertTrue(message + ": expected " + expected + " but was " + actual, expected == actual);
    }

    public static void assertTrue(final boolean flag) {
        assertTrue("expected true", flag);
    }

    public static void assertTrue(final String message, final boolean flag) {
        assertTrue(message, null, flag);
    }

    public static void assertTrue(final String message, final Object target, final boolean flag) {
        if (!flag) {
            throw new IsisAssertException(message + (target == null ? "" : (": " + target)));
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
package mockit;

import java.util.*;
import javax.annotation.*;

import mockit.internal.expectations.*;
import mockit.internal.expectations.argumentMatching.*;
import mockit.internal.state.*;

/**
 * Used to verify a set of expectations on available {@linkplain mockit.Mocked mocked} types and/or instances,
 * against the invocations which actually occurred during the test.
 * As such, these verifications can only appear after having exercised the code under test.
 *

 * An expectation verification attempts to match a number of method or constructor invocations, that we expect have
 * occurred during the execution of code under test.
 * By default, at least one matching invocation must be found for the verification to be successful; if no
 * matching invocations are found, an assertion error is thrown.
 *

 * Expectations are verified simply by invoking the desired method or constructor on a mocked type/instance, during
 * the initialization of a {@code Verifications} object.
 * Typically, this is done by instantiating an anonymous subclass containing an instance initialization body, or as we
 * call it, a verification block:
 *

 * // Exercise tested code.
 * codeUnderTest.doSomething();
 *
 * // Now verify that the expected invocations actually occurred (in any order).
 * new Verifications() {{
 *    mock1.expectedMethod(anyInt);
 *    mock2.anotherExpectedMethod(1, "test"); times = 2;
 * }};
 *

 * The relative order between the invocations that match two or more verifications is not taken into consideration; when
 * that is desired, the {@link mockit.VerificationsInOrder} class should be used instead.
 *

 * Naturally, not all invocations that occurred during the execution of code under test need to be explicitly verified
 * in a verification block.
 * If desired, however, we can make sure that all such invocations are verified, by using the
 * {@link mockit.FullVerifications} class instead.
 *
 * @see #Verifications()
 * @see #Verifications(int)
 * @see #withCapture()
 * @see mockit.Expectations
 * @see Tutorial
 */
public abstract class Verifications extends Invocations
{
   @Nonnull final BaseVerificationPhase verificationPhase;

   /**
    * Begins a set of unordered expectation verifications, on the available mocked types and/or mocked instances.
    * Such verifications are meant to be executed after the call to code under test has been made.
    *
    * @see #Verifications(int)
    */
   protected Verifications() { this(false); }

   /**
    * Same as {@link #Verifications()}, but considering that such invocations occurred in a given number of iterations.
    *

    * The effect of specifying a (positive) number of iterations is equivalent to setting to that number the lower and
    * upper invocation count limits for each expectation verified.
    * If, however, the lower/upper limit is explicitly specified for an expectation, the given number of iterations
    * becomes a multiplier.
    * When not specified, at least one matching invocation will be required to have occurred; therefore, specifying
    * 1 (one) iteration is different from not specifying the number of iterations at all.
    *
    * @param numberOfIterations the positive number of iterations for the whole set of verified expectations
    *
    * @see #times
    * @see #minTimes
    * @see #maxTimes
    * @see Tutorial
    */
   protected Verifications(int numberOfIterations)
   {
      this(false);
      verificationPhase.setNumberOfIterations(numberOfIterations);
   }

   Verifications(boolean inOrder)
   {
      RecordAndReplayExecution instance = TestRun.getRecordAndReplayForVerifications();
      verificationPhase = instance.startVerifications(inOrder);
   }

   @Nonnull @Override
   final BaseVerificationPhase getCurrentPhase() { return verificationPhase; }

   /**
    * Captures the argument value passed into the associated expectation parameter, for a matching invocation that
    * occurred when the tested code was exercised.
    * This method should be used in a local variable assignment expression inside a verification block.
    * For example:
    *

    * codeUnderTest.doSomething();
    *
    * new Verifications() {{
    *    String name;
    *    int age;
    *    personDAOMock.create(age = withCapture(), name = withCapture());
    *    assertFalse(name.isEmpty());
    *    assertTrue(age >= 18);
    * }};
    *

    * If there is more than one matching invocation, then only the last one to have occurred is considered.
    *
    * @return the captured argument value
    *
    * @see #withCapture(java.util.List)
    * @see #withCapture(Object)
    * @see Tutorial
    */
   protected final <T> T withCapture()
   {
      verificationPhase.addArgMatcher(AlwaysTrueMatcher.ANY_VALUE);
      //noinspection ConstantConditions
      return null;
   }

   /**
    * Captures new instances of type {@code T} that were created by the code under test.
    * Said instances are only those which were created through constructor invocations matching the constructor
    * verification that was passed as argument in a call to this method.
    * For example:
    *

    * codeUnderTest.doSomething();
    *
    * new Verifications() {{
    *    List<Person> newPersons = withCapture(new Person());
    *    Person newPerson = newPersons.get(0);
    *
    *    Person personCreated;
    *    personDAOMock.create(personCreated = withCapture());
    *
    *    assertSame(newPerson, personCreated);
    * }};
    *

    *
    * @param constructorVerification a new instance of the desired mocked class, created through a regular constructor
    *                                verification
    *
    * @return a list with the (zero, one, or more) captured new instances that match the verified constructor invocation
    *
    * @see #withCapture()
    * @see #withCapture(java.util.List)
    * @see Tutorial
    */
   protected final <T> List<T> withCapture(@SuppressWarnings("unused") T constructorVerification)
   {
      return verificationPhase.getNewInstancesMatchingVerifiedConstructorInvocation();
   }
}


text:
void * memcpy(void * restrict, const void * restrict, size_t);
char * memmove(void *, const void *, size_t);
char * strcpy(char * restrict, const char * restrict);
char * strdup(const char *);

int memcmp(const void *, const void *, size_t);
int strcmp(const char *, const char *);

char * strchr(const char *, int);
size_t strcspn(const char *, const char *);
char * strpbrk(const char *, const char *);
char * strrchr(const char *, int);
size_t strspn(const char *, const char *);
char * strstr(const char *, const char *);
char * strtok(char * restrict, const char * restrict);

void * memset(void *, int, size_t);
char * strerror(int);
size_t strlen(const char *);
char * strsignal(int);

#endif


text:
package models

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"encoding/json"
	"strconv"

	strfmt "github.com/go-openapi/strfmt"

	"github.com/go-openapi/errors"
	"github.com/go-openapi/swag"
	"github.com/go-openapi/validate"
)

// PartBasedSimulationParameters part based simulation parameters
// swagger:model PartBasedSimulationParameters
type PartBasedSimulationParameters struct {

	// should be a number between 0.5 and 1.5
	BladeCrashThreshold float64 `json:"bladeCrashThreshold,omitempty"`

	// Id of build file being simulated, mutually exclusive with simulationParts
	BuildFileID int32 `json:"buildFileId,omitempty"`

	// cutoff method
	// Required: true
	CutoffMethod *string `json:"cutoffMethod"`

	// detect blade crash
	// Required: true
	DetectBladeCrash *bool `json:"detectBladeCrash"`

	// detect support failure
	DetectSupportFailure bool `json:"detectSupportFailure,omitempty"`

	// The amount of steps MAPDL will use for directional cut off
	// Maximum: 2.147483647e+09
	// Minimum: 1
	DirectionCutoffSteps int32 `json:"directionCutoffSteps,omitempty"`

	// The direction of the MAPDL directional cut off
	DirectionalCutoffDirection string `json:"directionalCutoffDirection,omitempty"`

	// a value that is used to scale the after cutoff simulated distortion values
	// Maximum: 5
	// Minimum: -5
	DistortionAfterCutoffScaleFactor *float64 `json:"distortionAfterCutoffScaleFactor,omitempty"`

	// Array of distortion after cutoff scale factor values, each one will produce a separate distortion after cutoff output
	DistortionAfterCutoffScaleFactorValues []*float64 `json:"distortionAfterCutoffScaleFactorValues"`

	// a value that is used to scale the simulated distortion value
	// Maximum: 5
	// Minimum: -5
	DistortionScaleFactor *float64 `json:"distortionScaleFactor,omitempty"`

	// Array of distortion scale factor values, each one will produce a separate distortion output
	DistortionScaleFactorValues []*float64 `json:"distortionScaleFactorValues"`

	// elastic modulus
	// Required: true
	ElasticModulus *float64 `json:"elasticModulus"`

	// if true, contour scan vectors is used in scan pattern simulation
	EnableContours bool `json:"enableContours,omitempty"`

	// generate support voxels
	// Required: true
	GenerateSupportVoxels *bool `json:"generateSupportVoxels"`

	// hardening factor
	// Required: true
	// Maximum: 0.5
	// Minimum: 0
	HardeningFactor *float64 `json:"hardeningFactor"`

	// if true, the on-plate stress output file will include the on-plate strain
	IncludeOnPlateStrainOutput bool `json:"includeOnPlateStrainOutput,omitempty"`

	// the maximum number of bytes to be written in layer-wise VTK files before subsequent VTK layer-wise VTK files will be skipped. Ignored if outputLayerVtk is false and required if true.
	// Minimum: 1.048576e+06
	LayerVtkMaxSize int64 `json:"layerVtkMaxSize,omitempty"`

	// load stepping type
	LoadSteppingType string `json:"loadSteppingType,omitempty"`

	// load steps
	// Maximum: 200
	// Minimum: 1
	LoadSteps int32 `json:"loadSteps,omitempty"`

	// Must be between 0.00015 to 0.002 meters, Must be greater than minimumWallThickness
	// Maximum: 0.01
	// Minimum: 2e-05
	MaximumThickWallThickness float64 `json:"maximumThickWallThickness,omitempty"`

	// The maximum distance between thinwalls
	// Maximum: 0.01
	// Minimum: 2e-05
	MaximumThinWallDistance float64 `json:"maximumThinWallDistance,omitempty"`

	// Distance to move the part off the base plate for supports, Must be between 0 to 0.005 meters
	// Required: true
	// Maximum: 0.005
	// Minimum: 0
	MinimumSupportHeight *float64 `json:"minimumSupportHeight"`

	// Must be between 0.00005 to 0.0003 meters, Must be less than maximumWallThickness
	// Maximum: 0.01
	// Minimum: 2e-05
	MinimumThickWallThickness float64 `json:"minimumThickWallThickness,omitempty"`

	// output displacement after cutoff
	// Required: true
	OutputDisplacementAfterCutoff *bool `json:"outputDisplacementAfterCutoff"`

	// if true, mechanics solver output will include a zip file with the stress / distortion state at the end of each voxel layer
	// Required: true
	OutputLayerVtk *bool `json:"outputLayerVtk"`

	// if true, mechanics solver output will include files related to passing mesh and inital state to ANSYS Workbench
	// Required: true
	OutputMapdl *bool `json:"outputMapdl"`

	// if true, a VTK file of the support structure will be created
	OutputSupportsVtk bool `json:"outputSupportsVtk,omitempty"`

	// should be a number between 0.01 and 1.0
	PartFailureThreshold float64 `json:"partFailureThreshold,omitempty"`

	// part file location
	PartFileLocation string `json:"partFileLocation,omitempty"`

	// if true, a predistorted STL file will be created using the distortion simulated by the mechanics solver
	PerformDistortionCompensation bool `json:"performDistortionCompensation,omitempty"`

	// if true, a predistorted STL file will be created using the distortion after cutoff simulated by the mechanics solver
	PerformDistortionCompensationAfterCutoff bool `json:"performDistortionCompensationAfterCutoff,omitempty"`

	// perform support only cutoff
	// Required: true
	PerformSupportOnlyCutoff *bool `json:"performSupportOnlyCutoff"`

	// perform support optimization
	// Required: true
	PerformSupportOptimization *bool `json:"performSupportOptimization"`

	// poisson ratio
	// Required: true
	PoissonRatio *float64 `json:"poissonRatio"`

	// The offset between the positioned part and the origin in x direction
	PositionedPartOffsetX float64 `json:"positionedPartOffsetX,omitempty"`

	// The offset between the positioned part and the origin in y direction
	PositionedPartOffsetY float64 `json:"positionedPartOffsetY,omitempty"`

	// The offset between the positioned part and the origin in z direction
	PositionedPartOffsetZ float64 `json:"positionedPartOffsetZ,omitempty"`

	// List of parts to simulate (current limit is one part, imposed by server)
	SimulationParts []*SimulationPart `json:"simulationParts"`

	// strain scaling factor
	// Required: true
	StrainScalingFactor *float64 `json:"strainScalingFactor"`

	// should be a number between 0.01 and 1.0
	StrainWarningThreshold float64 `json:"strainWarningThreshold,omitempty"`

	// stress mode
	// Required: true
	StressMode *string `json:"stressMode"`

	// Must be between 1 to 89 degrees
	// Required: true
	// Maximum: 89
	// Minimum: 1
	SupportAngle *float64 `json:"supportAngle"`

	// Multiplier for support calculations, Must be between 0.1 to 10
	// Required: true
	// Maximum: 10
	// Minimum: 0.1
	SupportFactorOfSafety *float64 `json:"supportFactorOfSafety"`

	// should be a number between 0.01 and 1.0
	SupportFailureThreshold float64 `json:"supportFailureThreshold,omitempty"`

	// support file location
	SupportFileLocation string `json:"supportFileLocation,omitempty"`

	// type of support used for simulation.
	// Required: true
	SupportType *string `json:"supportType"`

	// support yield strength
	// Required: true
	SupportYieldStrength *float64 `json:"supportYieldStrength"`

	// support yield strength ratio
	// Required: true
	SupportYieldStrengthRatio *float64 `json:"supportYieldStrengthRatio"`

	// The distance between thickwall supports
	// Maximum: 0.01
	// Minimum: 2e-05
	ThickWallDistance float64 `json:"thickWallDistance,omitempty"`

	// The width of the thinwall supports
	// Maximum: 0.0005
	// Minimum: 2e-05
	ThinWallThickness float64 `json:"thinWallThickness,omitempty"`

	// the amount of sub voxels per voxel in each direction (x,y,z)
	// Maximum: 10
	// Minimum: 1
	VoxelSampleRate int32 `json:"voxelSampleRate,omitempty"`

	// Must be between 0.00002 to 0.002 meters
	// Required: true
	// Maximum: 0.002
	// Minimum: 2e-05
	VoxelSize *float64 `json:"voxelSize"`
}

// Validate validates this part based simulation parameters
func (m *PartBasedSimulationParameters) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateCutoffMethod(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateDetectBladeCrash(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateDirectionCutoffSteps(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateDirectionalCutoffDirection(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateDistortionAfterCutoffScaleFactor(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateDistortionAfterCutoffScaleFactorValues(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateDistortionScaleFactor(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateDistortionScaleFactorValues(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateElasticModulus(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateGenerateSupportVoxels(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateHardeningFactor(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateLayerVtkMaxSize(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateLoadSteppingType(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateLoadSteps(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateMaximumThickWallThickness(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateMaximumThinWallDistance(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateMinimumSupportHeight(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateMinimumThickWallThickness(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateOutputDisplacementAfterCutoff(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateOutputLayerVtk(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateOutputMapdl(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validatePerformSupportOnlyCutoff(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validatePerformSupportOptimization(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validatePoissonRatio(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateSimulationParts(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateStrainScalingFactor(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateStressMode(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateSupportAngle(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateSupportFactorOfSafety(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateSupportType(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateSupportYieldStrength(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateSupportYieldStrengthRatio(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateThickWallDistance(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateThinWallThickness(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateVoxelSampleRate(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if err := m.validateVoxelSize(formats); err != nil {
		// prop
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

var partBasedSimulationParametersTypeCutoffMethodPropEnum []interface{}

func init() {
	var res []string
	if err := json.Unmarshal([]byte(`["Legacy","Instantaneous","Directional"]`), &res); err != nil {
		panic(err)
	}
	for _, v := range res {
		partBasedSimulationParametersTypeCutoffMethodPropEnum = append(partBasedSimulationParametersTypeCutoffMethodPropEnum, v)
	}
}

const (
	// PartBasedSimulationParametersCutoffMethodLegacy captures enum value "Legacy"
	PartBasedSimulationParametersCutoffMethodLegacy string = "Legacy"
	// PartBasedSimulationParametersCutoffMethodInstantaneous captures enum value "Instantaneous"
	PartBasedSimulationParametersCutoffMethodInstantaneous string = "Instantaneous"
	// PartBasedSimulationParametersCutoffMethodDirectional captures enum value "Directional"
	PartBasedSimulationParametersCutoffMethodDirectional string = "Directional"
)

// prop value enum
func (m *PartBasedSimulationParameters) validateCutoffMethodEnum(path, location string, value string) error {
	if err := validate.Enum(path, location, value, partBasedSimulationParametersTypeCutoffMethodPropEnum); err != nil {
		return err
	}
	return nil
}

func (m *PartBasedSimulationParameters) validateCutoffMethod(formats strfmt.Registry) error {

	if err := validate.Required("cutoffMethod", "body", m.CutoffMethod); err != nil {
		return err
	}

	// value enum
	if err := m.validateCutoffMethodEnum("cutoffMethod", "body", *m.CutoffMethod); err != nil {
		return err
	}

	return nil
}

func (m *PartBasedSimulationParameters) validateDetectBladeCrash(formats strfmt.Registry) error {

	if err := validate.Required("detectBladeCrash", "body", m.DetectBladeCrash); err != nil {
		return err
	}

	return nil
}

func (m *PartBasedSimulationParameters) validateDirectionCutoffSteps(formats strfmt.Registry) error {

	if swag.IsZero(m.DirectionCutoffSteps) { // not required
		return nil
	}

	if err := validate.MinimumInt("directionCutoffSteps", "body", int64(m.DirectionCutoffSteps), 1, false); err != nil {
		return err
	}

	if err := validate.MaximumInt("directionCutoffSteps", "body", int64(m.DirectionCutoffSteps), 2.147483647e+09, false); err != nil {
		return err
	}

	return nil
}

var partBasedSimulationParametersTypeDirectionalCutoffDirectionPropEnum []interface{}

func init() {
	var res []string
	if err := json.Unmarshal([]byte(`["POS_X","NEG_X","POS_Y","NEG_Y"]`), &res); err != nil {
		panic(err)
	}
	for _, v := range res {
		partBasedSimulationParametersTypeDirectionalCutoffDirectionPropEnum = append(partBasedSimulationParametersTypeDirectionalCutoffDirectionPropEnum, v)
	}
}

const (
	// PartBasedSimulationParametersDirectionalCutoffDirectionPOSX captures enum value "POS_X"
	PartBasedSimulationParametersDirectionalCutoffDirectionPOSX string = "POS_X"
	// PartBasedSimulationParametersDirectionalCutoffDirectionNEGX captures enum value "NEG_X"
	PartBasedSimulationParametersDirectionalCutoffDirectionNEGX string = "NEG_X"
	// PartBasedSimulationParametersDirectionalCutoffDirectionPOSY captures enum value "POS_Y"
	PartBasedSimulationParametersDirectionalCutoffDirectionPOSY string = "POS_Y"
	// PartBasedSimulationParametersDirectionalCutoffDirectionNEGY captures enum value "NEG_Y"
	PartBasedSimulationParametersDirectionalCutoffDirectionNEGY string = "NEG_Y"
)

// prop value enum
func (m *PartBasedSimulationParameters) validateDirectionalCutoffDirectionEnum(path, location string, value string) error {
	if err := validate.Enum(path, location, value, partBasedSimulationParametersTypeDirectionalCutoffDirectionPropEnum); err != nil {
		return err
	}
	return nil
}

func (m *PartBasedSimulationParameters) validateDirectionalCutoffDirection(formats strfmt.Registry) error {

	if swag.IsZero(m.DirectionalCutoffDirection) { // not required
		return nil
	}

	// value enum
	if err := m.validateDirectionalCutoffDirectionEnum("directionalCutoffDirection", "body", m.DirectionalCutoffDirection); err != nil {
		return err
	}

	return nil
}

func (m *PartBasedSimulationParameters) validateDistortionAfterCutoffScaleFactor(formats strfmt.Registry) error {

	if swag.IsZero(m.DistortionAfterCutoffScaleFactor) { // not required
		return nil
	}

	if err := validate.Minimum("distortionAfterCutoffScaleFactor", "body", float64(*m.DistortionAfterCutoffScaleFactor), -5, false); err != nil {
		return err
	}

	if err := validate.Maximum("distortionAfterCutoffScaleFactor", "body", float64(*m.DistortionAfterCutoffScaleFactor), 5, false); err != nil {
		return err
	}

	return nil
}

func (m *PartBasedSimulationParameters) validateDistortionAfterCutoffScaleFactorValues(formats strfmt.Registry) error {

	if swag.IsZero(m.DistortionAfterCutoffScaleFactorValues) { // not required
		return nil
	}

	for i := 0; i < len(m.DistortionAfterCutoffScaleFactorValues); i++ {

		if swag.IsZero(m.DistortionAfterCutoffScaleFactorValues[i]) { // not required
			continue
		}

		if err := validate.Minimum("distortionAfterCutoffScaleFactorValues"+"."+strconv.Itoa(i), "body", float64(*m.DistortionAfterCutoffScaleFactorValues[i]), -5, false); err != nil {
			return err
		}

		if err := validate.Maximum("distortionAfterCutoffScaleFactorValues"+"."+strconv.Itoa(i), "body", float64(*m.DistortionAfterCutoffScaleFactorValues[i]), 5, false); err != nil {
			return err
		}

	}

	return nil
}

func (m *PartBasedSimulationParameters) validateDistortionScaleFactor(formats strfmt.Registry) error {

	if swag.IsZero(m.DistortionScaleFactor) { // not required
		return nil
	}

	if err := validate.Minimum("distortionScaleFactor", "body", float64(*m.DistortionScaleFactor), -5, false); err != nil {
		return err
	}

	if err := validate.Maximum("distortionScaleFactor", "body", float64(*m.DistortionScaleFactor), 5, false); err != nil {
		return err
	}

	return nil
}

func (m *PartBasedSimulationParameters) validateDistortionScaleFactorValues(formats strfmt.Registry) error {

	if swag.IsZero(m.DistortionScaleFactorValues) { // not required
		return nil
	}

	for i := 0; i < len(m.DistortionScaleFactorValues); i++ {

		if swag.IsZero(m.DistortionScaleFactorValues[i]) { // not required
			continue
		}

		if err := validate.Minimum("distortionScaleFactorValues"+"."+strconv.Itoa(i), "body", float64(*m.DistortionScaleFactorValues[i]), -5, false); err != nil {
			return err
		}

		if err := validate.Maximum("distortionScaleFactorValues"+"."+strconv.Itoa(i), "body", float64(*m.DistortionScaleFactorValues[i]), 5, false); err != nil {
			return err
		}

	}

	return nil
}

func (m *PartBasedSimulationParameters) validateElasticModulus(formats strfmt.Registry) error {

	if err := validate.Required("elasticModulus", "body", m.ElasticModulus); err != nil {
		return err
	}

	return nil
}

func (m *PartBasedSimulationParameters) validateGenerateSupportVoxels(formats strfmt.Registry) error {

	if err := validate.Required("generateSupportVoxels", "body", m.GenerateSupportVoxels); err != nil {
		return err
	}

	return nil
}

func (m *PartBasedSimulationParameters) validateHardeningFactor(formats strfmt.Registry) error {

	if err := validate.Required("hardeningFactor", "body", m.HardeningFactor); err != nil {
		return err
	}

	if err := validate.Minimum("hardeningFactor", "body", float64(*m.HardeningFactor), 0, false); err != nil {
		return err
	}

	if err := validate.Maximum("hardeningFactor", "body", float64(*m.HardeningFactor), 0.5, false); err != nil {
		return err
	}

	return nil
}

func (m *PartBasedSimulationParameters) validateLayerVtkMaxSize(formats strfmt.Registry) error {

	if swag.IsZero(m.LayerVtkMaxSize) { // not required
		return nil
	}

	if err := validate.MinimumInt("layerVtkMaxSize", "body", int64(m.LayerVtkMaxSize), 1.048576e+06, false); err != nil {
		return err
	}

	return nil
}

var partBasedSimulationParametersTypeLoadSteppingTypePropEnum []interface{}

func init() {
	var res []string
	if err := json.Unmarshal([]byte(`["DynamicLoadStepping","FixedLoadStepping"]`), &res); err != nil {
		panic(err)
	}
	for _, v := range res {
		partBasedSimulationParametersTypeLoadSteppingTypePropEnum = append(partBasedSimulationParametersTypeLoadSteppingTypePropEnum, v)
	}
}

const (
	// PartBasedSimulationParametersLoadSteppingTypeDynamicLoadStepping captures enum value "DynamicLoadStepping"
	PartBasedSimulationParametersLoadSteppingTypeDynamicLoadStepping string = "DynamicLoadStepping"
	// PartBasedSimulationParametersLoadSteppingTypeFixedLoadStepping captures enum value "FixedLoadStepping"
	PartBasedSimulationParametersLoadSteppingTypeFixedLoadStepping string = "FixedLoadStepping"
)

// prop value enum
func (m *PartBasedSimulationParameters) validateLoadSteppingTypeEnum(path, location string, value string) error {
	if err := validate.Enum(path, location, value, partBasedSimulationParametersTypeLoadSteppingTypePropEnum); err != nil {
		return err
	}
	return nil
}

func (m *PartBasedSimulationParameters) validateLoadSteppingType(formats strfmt.Registry) error {

	if swag.IsZero(m.LoadSteppingType) { // not required
		return nil
	}

	// value enum
	if err := m.validateLoadSteppingTypeEnum("loadSteppingType", "body", m.LoadSteppingType); err != nil {
		return err
	}

	return nil
}

func (m *PartBasedSimulationParameters) validateLoadSteps(formats strfmt.Registry) error {

	if swag.IsZero(m.LoadSteps) { // not required
		return nil
	}

	if err := validate.MinimumInt("loadSteps", "body", int64(m.LoadSteps), 1, false); err != nil {
		return err
	}

	if err := validate.MaximumInt("loadSteps", "body", int64(m.LoadSteps), 200, false); err != nil {
		return err
	}

	return nil
}

func (m *PartBasedSimulationParameters) validateMaximumThickWallThickness(formats strfmt.Registry) error {

	if swag.IsZero(m.MaximumThickWallThickness) { // not required
		return nil
	}

	if err := validate.Minimum("maximumThickWallThickness", "body", float64(m.MaximumThickWallThickness), 2e-05, false); err != nil {
		return err
	}

	if err := validate.Maximum("maximumThickWallThickness", "body", float64(m.MaximumThickWallThickness), 0.01, false); err != nil {
		return err
	}

	return nil
}

func (m *PartBasedSimulationParameters) validateMaximumThinWallDistance(formats strfmt.Registry) error {

	if swag.IsZero(m.MaximumThinWallDistance) { // not required
		return nil
	}

	if err := validate.Minimum("maximumThinWallDistance", "body", float64(m.MaximumThinWallDistance), 2e-05, false); err != nil {
		return err
	}

	if err := validate.Maximum("maximumThinWallDistance", "body", float64(m.MaximumThinWallDistance), 0.01, false); err != nil {
		return err
	}

	return nil
}

func (m *PartBasedSimulationParameters) validateMinimumSupportHeight(formats strfmt.Registry) error {

	if err := validate.Required("minimumSupportHeight", "body", m.MinimumSupportHeight); err != nil {
		return err
	}

	if err := validate.Minimum("minimumSupportHeight", "body", float64(*m.MinimumSupportHeight), 0, false); err != nil {
		return err
	}

	if err := validate.Maximum("minimumSupportHeight", "body", float64(*m.MinimumSupportHeight), 0.005, false); err != nil {
		return err
	}

	return nil
}

func (m *PartBasedSimulationParameters) validateMinimumThickWallThickness(formats strfmt.Registry) error {

	if swag.IsZero(m.MinimumThickWallThickness) { // not required
		return nil
	}

	if err := validate.Minimum("minimumThickWallThickness", "body", float64(m.MinimumThickWallThickness), 2e-05, false); err != nil {
		return err
	}

	if err := validate.Maximum("minimumThickWallThickness", "body", float64(m.MinimumThickWallThickness), 0.01, false); err != nil {
		return err
	}

	return nil
}

func (m *PartBasedSimulationParameters) validateOutputDisplacementAfterCutoff(formats strfmt.Registry) error {

	if err := validate.Required("outputDisplacementAfterCutoff", "body", m.OutputDisplacementAfterCutoff); err != nil {
		return err
	}

	return nil
}

func (m *PartBasedSimulationParameters) validateOutputLayerVtk(formats strfmt.Registry) error {

	if err := validate.Required("outputLayerVtk", "body", m.OutputLayerVtk); err != nil {
		return err
	}

	return nil
}

func (m *PartBasedSimulationParameters) validateOutputMapdl(formats strfmt.Registry) error {

	if err := validate.Required("outputMapdl", "body", m.OutputMapdl); err != nil {
		return err
	}

	return nil
}

func (m *PartBasedSimulationParameters) validatePerformSupportOnlyCutoff(formats strfmt.Registry) error {

	if err := validate.Required("performSupportOnlyCutoff", "body", m.PerformSupportOnlyCutoff); err != nil {
		return err
	}

	return nil
}

func (m *PartBasedSimulationParameters) validatePerformSupportOptimization(formats strfmt.Registry) error {

	if err := validate.Required("performSupportOptimization", "body", m.PerformSupportOptimization); err != nil {
		return err
	}

	return nil
}

func (m *PartBasedSimulationParameters) validatePoissonRatio(formats strfmt.Registry) error {

	if err := validate.Required("poissonRatio", "body", m.PoissonRatio); err != nil {
		return err
	}

	return nil
}

func (m *PartBasedSimulationParameters) validateSimulationParts(formats strfmt.Registry) error {

	if swag.IsZero(m.SimulationParts) { // not required
		return nil
	}

	for i := 0; i < len(m.SimulationParts); i++ {

		if swag.IsZero(m.SimulationParts[i]) { // not required
			continue
		}

		if m.SimulationParts[i] != nil {

			if err := m.SimulationParts[i].Validate(formats); err != nil {
				if ve, ok := err.(*errors.Validation); ok {
					return ve.ValidateName("simulationParts" + "." + strconv.Itoa(i))
				}
				return err
			}
		}

	}

	return nil
}

func (m *PartBasedSimulationParameters) validateStrainScalingFactor(formats strfmt.Registry) error {

	if err := validate.Required("strainScalingFactor", "body", m.StrainScalingFactor); err != nil {
		return err
	}

	return nil
}

var partBasedSimulationParametersTypeStressModePropEnum []interface{}

func init() {
	var res []string
	if err := json.Unmarshal([]byte(`["LinearElastic","J2Plasticity"]`), &res); err != nil {
		panic(err)
	}
	for _, v := range res {
		partBasedSimulationParametersTypeStressModePropEnum = append(partBasedSimulationParametersTypeStressModePropEnum, v)
	}
}

const (
	// PartBasedSimulationParametersStressModeLinearElastic captures enum value "LinearElastic"
	PartBasedSimulationParametersStressModeLinearElastic string = "LinearElastic"
	// PartBasedSimulationParametersStressModeJ2Plasticity captures enum value "J2Plasticity"
	PartBasedSimulationParametersStressModeJ2Plasticity string = "J2Plasticity"
)

// prop value enum
func (m *PartBasedSimulationParameters) validateStressModeEnum(path, location string, value string) error {
	if err := validate.Enum(path, location, value, partBasedSimulationParametersTypeStressModePropEnum); err != nil {
		return err
	}
	return nil
}

func (m *PartBasedSimulationParameters) validateStressMode(formats strfmt.Registry) error {

	if err := validate.Required("stressMode", "body", m.StressMode); err != nil {
		return err
	}

	// value enum
	if err := m.validateStressModeEnum("stressMode", "body", *m.StressMode); err != nil {
		return err
	}

	return nil
}

func (m *PartBasedSimulationParameters) validateSupportAngle(formats strfmt.Registry) error {

	if err := validate.Required("supportAngle", "body", m.SupportAngle); err != nil {
		return err
	}

	if err := validate.Minimum("supportAngle", "body", float64(*m.SupportAngle), 1, false); err != nil {
		return err
	}

	if err := validate.Maximum("supportAngle", "body", float64(*m.SupportAngle), 89, false); err != nil {
		return err
	}

	return nil
}

func (m *PartBasedSimulationParameters) validateSupportFactorOfSafety(formats strfmt.Registry) error {

	if err := validate.Required("supportFactorOfSafety", "body", m.SupportFactorOfSafety); err != nil {
		return err
	}

	if err := validate.Minimum("supportFactorOfSafety", "body", float64(*m.SupportFactorOfSafety), 0.1, false); err != nil {
		return err
	}

	if err := validate.Maximum("supportFactorOfSafety", "body", float64(*m.SupportFactorOfSafety), 10, false); err != nil {
		return err
	}

	return nil
}

var partBasedSimulationParametersTypeSupportTypePropEnum []interface{}

func init() {
	var res []string
	if err := json.Unmarshal([]byte(`["Generated","UserDefined"]`), &res); err != nil {
		panic(err)
	}
	for _, v := range res {
		partBasedSimulationParametersTypeSupportTypePropEnum = append(partBasedSimulationParametersTypeSupportTypePropEnum, v)
	}
}

const (
	// PartBasedSimulationParametersSupportTypeGenerated captures enum value "Generated"
	PartBasedSimulationParametersSupportTypeGenerated string = "Generated"
	// PartBasedSimulationParametersSupportTypeUserDefined captures enum value "UserDefined"
	PartBasedSimulationParametersSupportTypeUserDefined string = "UserDefined"
)

// prop value enum
func (m *PartBasedSimulationParameters) validateSupportTypeEnum(path, location string, value string) error {
	if err := validate.Enum(path, location, value, partBasedSimulationParametersTypeSupportTypePropEnum); err != nil {
		return err
	}
	return nil
}

func (m *PartBasedSimulationParameters) validateSupportType(formats strfmt.Registry) error {

	if err := validate.Required("supportType", "body", m.SupportType); err != nil {
		return err
	}

	// value enum
	if err := m.validateSupportTypeEnum("supportType", "body", *m.SupportType); err != nil {
		return err
	}

	return nil
}

func (m *PartBasedSimulationParameters) validateSupportYieldStrength(formats strfmt.Registry) error {

	if err := validate.Required("supportYieldStrength", "body", m.SupportYieldStrength); err != nil {
		return err
	}

	return nil
}

func (m *PartBasedSimulationParameters) validateSupportYieldStrengthRatio(formats strfmt.Registry) error {

	if err := validate.Required("supportYieldStrengthRatio", "body", m.SupportYieldStrengthRatio); err != nil {
		return err
	}

	return nil
}

func (m *PartBasedSimulationParameters) validateThickWallDistance(formats strfmt.Registry) error {

	if swag.IsZero(m.ThickWallDistance) { // not required
		return nil
	}

	if err := validate.Minimum("thickWallDistance", "body", float64(m.ThickWallDistance), 2e-05, false); err != nil {
		return err
	}

	if err := validate.Maximum("thickWallDistance", "body", float64(m.ThickWallDistance), 0.01, false); err != nil {
		return err
	}

	return nil
}

func (m *PartBasedSimulationParameters) validateThinWallThickness(formats strfmt.Registry) error {

	if swag.IsZero(m.ThinWallThickness) { // not required
		return nil
	}

	if err := validate.Minimum("thinWallThickness", "body", float64(m.ThinWallThickness), 2e-05, false); err != nil {
		return err
	}

	if err := validate.Maximum("thinWallThickness", "body", float64(m.ThinWallThickness), 0.0005, false); err != nil {
		return err
	}

	return nil
}

func (m *PartBasedSimulationParameters) validateVoxelSampleRate(formats strfmt.Registry) error {

	if swag.IsZero(m.VoxelSampleRate) { // not required
		return nil
	}

	if err := validate.MinimumInt("voxelSampleRate", "body", int64(m.VoxelSampleRate), 1, false); err != nil {
		return err
	}

	if err := validate.MaximumInt("voxelSampleRate", "body", int64(m.VoxelSampleRate), 10, false); err != nil {
		return err
	}

	return nil
}

func (m *PartBasedSimulationParameters) validateVoxelSize(formats strfmt.Registry) error {

	if err := validate.Required("voxelSize", "body", m.VoxelSize); err != nil {
		return err
	}

	if err := validate.Minimum("voxelSize", "body", float64(*m.VoxelSize), 2e-05, false); err != nil {
		return err
	}

	if err := validate.Maximum("voxelSize", "body", float64(*m.VoxelSize), 0.002, false); err != nil {
		return err
	}

	return nil
}

// MarshalBinary interface implementation
func (m *PartBasedSimulationParameters) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

// UnmarshalBinary interface implementation
func (m *PartBasedSimulationParameters) UnmarshalBinary(b []byte) error {
	var res PartBasedSimulationParameters
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Functional.Maybe;

namespace OpeningsMoeWpfClient
{
    class PlayerModel : INotifyPropertyChanged, IDisposable
    {
        private Random random;
        private readonly IMovieProvider movieProvider;

        private ObservableCollection<MovieDescription> allMovies = new ObservableCollection<MovieDescription>();

        private IEnumerator<Task<KeyValuePair<MovieDescription, string>>> movieSequenceEnumerator;

        public IReadOnlyList<MovieDescription> AllMovies => allMovies;

        public event PropertyChangedEventHandler PropertyChanged;

        private MovieDescription currentMovieDescription;

        private MovieDescription CurrentMovieDescription
        {
            get => currentMovieDescription;
            set
            {
                if(currentMovieDescription == value)
                    return;
                currentMovieDescription = value;
                OnPropertyChanged();
                OnPropertyChanged(nameof(CurrentlyPlaying));
            }
        }

        private float volume = 0.5f;

        public float Volume
        {
            get => volume;
            set
            {
                if(volume == value)
                    return;
                volume = Math.Min(1.0f, Math.Max(0.0f, value));
                OnPropertyChanged();
            }
        }

        public string CurrentlyPlaying => CurrentMovieDescription != null
            ? $"{CurrentMovieDescription.Title} - {CurrentMovieDescription.Source}"
            : "Loading...";

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public async Task<string> RequestNextMovie()
        {
            if(CurrentMovieDescription == null)
                movieSequenceEnumerator.MoveNext();
            var moviePathPair = await movieSequenceEnumerator.Current;
            CurrentMovieDescription = moviePathPair.Key;
            movieSequenceEnumerator.MoveNext();
            return moviePathPair.Value;
        }

        private PlayerModel(Random random, IMovieProvider movieProvider, DirectoryInfo targetDirectory)
        {
            this.random = random;
            this.movieProvider = movieProvider;
            targetDirectory.Create();
        }

        public static async Task<PlayerModel> Create(Random random, IMovieProvider movieProvider, DirectoryInfo targetDirectory)
        {
            var playerModel = new PlayerModel(random, movieProvider, targetDirectory);
            var movies = await movieProvider.Movies();
            var shuffledMovies = CollectionUtils.Shuffled(movies.ToList(), random);
            CollectionUtils.ReplaceContentsWith(playerModel.allMovies, shuffledMovies);

            var moviesReady = (await movieProvider.MoviesReady()).ToList();
            var movieSequence = CollectionUtils.Choice(moviesReady, random)
                .ToEnumerable()
                .Concat(CollectionUtils.Cycle(playerModel.AllMovies));

            playerModel.movieSequenceEnumerator = movieSequence
                .Select(async movie => new KeyValuePair<MovieDescription, string>(movie, await movieProvider.GetPathToTheMovieFile(movie)))
                .GetEnumerator();
            return playerModel;
        }

        /// <inheritdoc />
        public void Dispose()
        {
            movieSequenceEnumerator?.Dispose();
        }
    }
}


text:
The IBM MQ Appliance provides an SSH interface for executing commands from a remote system. However, to maintain the integrity of the appliance, the SSH interface that is provided does not support all the features of an standard SSH server. The current restrictions mean that it is necessary for scripts to simulate an interactive user session with the appliance, which is commonly achieved by using *expect*.

This MQ CLI client can be used to simplify scripts on remote systems by hiding the use of *expect*. A command can be supplied to the client as a parameter, or commands can be supplied using standard input (either interactively or piped in from a file), which makes it easy to script commands as per on other MQ server platforms.

In the interactive mode a custom command is available that can be used to change the expect timeout for subsequent commands that are executed in the session. This command is useful when executing commands that are potentially long-running. To set the timeout use the command *timeout <seconds>*. For example, to set the timeout to 30 seconds use *timeout 30*.

Two implementations of the client are provided; one written in Perl (*mqcli.pl*) and another written in Python (*mqcli.py*). These scripting languages are commonly installed on UNIX and Linux systems.

The Expect module used by the Python client is often provided as a separate package on Linux, named either *python-pexpect* or *pexpect*. Alternatively, the module can be downloaded from the Python Package Index https://pypi.org using the *pip* utility.

The Expect module used by the Perl client is not usually provided with a default Perl installation, but it can be readily downloaded from CPAN (Comprehensive Perl Archive Network), which is the public repository for a wide range of Perl modules. CPAN is available at www.cpan.org. Perl installations include a *cpan* utility that can be used to download Perl modules and prerequisites they require.

## Using the MQ CLI client with runmqsc

To use *runmqsc* with this client you need to configure *runmqsc* to have a non-blank command prompt on the MQ Appliance. This is required because *expect* needs a prompt that it can wait for to determine that the previous command has completed and the next command can be entered. To configure a non-blank command prompt for *runmqsc* you use the *setmqvar* command in the *mqcli* to set the MQPROMPT environment variable. This is a global setting so it will set the prompt for all users of *runmqsc* on the appliance.

To set the command prompt for *runmqsc* to `MQSC >` use the following *setmqvar* command:
```
mqa(mqcli)# setmqvar -k MQPROMPT -v "MQSC >"
```
If you then start *runmqsc* the custom prompt is displayed:
```
mqa(mqcli)# runmqsc QM1
5724-H72 (C) Copyright IBM Corp. 1994, 2022.
Starting MQSC for queue manager QM1.

MQSC >DISPLAY QMGR QMNAME
     1 : DISPLAY QMGR QMNAME
AMQ8408I: Display Queue Manager details.
   QMNAME(QM1)
MQSC >END
     2 : END
One MQSC command read.
No commands have a syntax error.
All valid MQSC commands were processed.
```
Note: The *runmqsc* command prompt cannot have trailing whitespace on the appliance.

The configured *runmqsc* command prompt must also be provided to the MQ CLI client so it knows what prompt to expect. You can specify the prompt by either providing the -m parameter, or by setting the MQPROMPT environment variable before starting the client. For example, in *bash* on Linux you could use:
```
export MQPROMPT="MQSC >"
```
When the MQ CLI client is run interactively, its own prompt changes from `[user@hostname mqcli]$` to `[user@hostname runmqsc]$` when the *runmqsc* command has been started.

For more information about configuring a custom command prompt for *runmqsc* see https://www.ibm.com/docs/en/ibm-mq/9.2?topic=interactively-setting-mqsc-command-prompt in the IBM MQ documentation.

## Usage

```
------------------------------
IBM MQ Appliance MQ CLI client
------------------------------

To display usage information:

  mqcli.pl [ -h|help|? ]

To execute MQ CLI commands:

  mqcli.pl -c|command <command> | -i|interactive
           [ -a|appliance <hostname> ]
           [ -m|mqprompt] <prompt> ]
           [ -u|username <username> ]
           [ -p|password <password> ]
           [ -s|sshoptions <options> ]
           [ -t|timeout <seconds> ]

Parameter information:

  -a : The hostname or IP address of the appliance
  -c : A single MQ control command to execute
  -i : Interactive mode
  -m : Configured runmqsc command prompt
  -p : The password for the MQ administrator
  -s : Extra SSH command line options, if required
  -t : The timeout to use for expect in seconds
  -u : The username of the MQ administrator on the appliance

Some parameters can alternatively be set as environment variables:

 - APPLIANCENAME : The hostname or IP address of the appliance
 - APPLIANCEUSER : The username of the MQ administrator on the appliance
 - APPLIANCEPASS : The password for the MQ administrator
 - MQPROMPT      : Configured runmqsc command prompt

If credentials are not specified on the command line, or by using
environment variables, then the user is prompted to enter them
interactively if a terminal is available.

In interactive mode the expect timeout can be modified for subsequent
commands by entering 'timeout <seconds>'. This is useful when executing
a potentially long-running command.

A custom runmqsc command prompt is required to execute MQSC commands by
using this client. To configure a custom runmqsc command prompt you set
the global MQPROMPT environment variable on the appliance by using the
setmqvar command in the mqcli. You then provide the configured prompt to
this client by using either the -m parameter, or by setting the same
environment variable locally.
```

## Example 1: Execute a single command

This example illustrates how to use the Perl client to execute a single command by providing the hostname, the credentials and the command using parameters.

```
$ mqcli.pl -a mqappl1 -u admin -p abcd1234 -c dspmqver
Name:        IBM MQ Appliance
Version:     9.1.2.0
Level:       p912-L190308
BuildType:   IKAP - (Production)
Platform:    IBM MQ Appliance
MaxCmdLevel: 912
```

## Example 2: Interactive use

This example illustrates how to enter multiple commands using an interactive session. Output from each MQ control command is returned to the user when the command completes. The user is also prompted to enter their appliance credentials interactively.

```
$ mqcli.pl -a mqappl1 -i
login: admin
password:
[admin@mqappl1 mqcli]$ dspmq
[admin@mqappl1 mqcli]$ crtmqm QM1
Please wait while 64 GB file system is initialized for queue manager 'QM1'.
IBM MQ Appliance queue manager created.
The queue manager is associated with installation 'MQAppliance'.
Creating or replacing default objects for queue manager 'QM1'.
Default objects statistics : 83 created. 0 replaced. 0 failed.
Completing setup.
Setup completed.
[admin@mqappl1 mqcli]$ strmqm QM1
IBM MQ Appliance queue manager 'QM1' starting.
The queue manager is associated with installation 'MQAppliance'.
5 log records accessed on queue manager 'QM1' during the log replay phase.
Log replay for queue manager 'QM1' complete.
Transaction manager state recovered for queue manager 'QM1'.
IBM MQ Appliance queue manager 'QM1' started using V9.1.2.0.
[admin@mqappl1 mqcli]$ dspmq
QMNAME(QM1)                                               STATUS(Running)
[admin@mqappl1 mqcli]$ exit
```

## Example 3: Execute multiple commands non-interactively

This example illustrates how commands can be defined in a file then executed non-interactively using a standard Linux/UNIX pipe. The prompt and commands are included in the output to identify the start of each command. This example also illustrates how the appliance hostname and the credentials can be defined using environment variables.

```
$ cat mqcli.in
dspmqver
dspmq
status
status QM1

$ export APPLIANCENAME=mqappl1
$ export APPLIANCENAME=admin
$ export APPLIANCEPASS=abcd1234

$ cat mqcli.in | mqcli.pl -i > mqcli.out

$ cat mqcli.out
[admin@mqappl1 mqcli]$ dspmqver
Name:        IBM MQ Appliance
Version:     9.1.2.0
Level:       p912-L190308
BuildType:   IKAP - (Production)
Platform:    IBM MQ Appliance
MaxCmdLevel: 912
[admin@mqappl1 mqcli]$ dspmq
QMNAME(QM1)                                               STATUS(Running)
[admin@mqappl1 mqcli]$ status
Memory:                                  5323MB used, 189.1GB total [3%]
CPU:                                     0%
CPU load:                                0.28, 0.11, 0.17
Internal disk:                           196608MB allocated, 2979.5GB total [6%]
System volume:                           5435MB used, 14.7GB allocated [36%]
MQ errors file system:                   173MB used, 1 FDCs, 15.8GB allocated [1%]
MQ trace file system:                    177MB used, 31.5GB allocated [1%]
[admin@mqappl1 mqcli]$ status QM1
QM(QM1)                                  Status(Running)
CPU:                                     0.00%
Memory:                                  189MB
Queue manager file system:               245MB used, 63.0GB allocated [0%]
[admin@mqappl1 mqcli]$ exit
```

## Example 4: Executing MQSC commands using runmqsc

This example illustrates how to use *runmqsc* to enter MQSC commands using an interactive session. It assumes that the MQPROMPT environment variable has already been set to the same value on the MQ Appliance.

```
$ export APPLIANCEUSER=admin
$ export APPLIANCEPASS=abcd1234
$ export MQPROMPT="MQSC >"

$ mqcli.pl -a mqappl1 -i
[admin@mqappl1 mqcli]$ dspmq
QMNAME(QM1)                                               STATUS(Running)
[admin@mqappl1 mqcli]$ runmqsc QM1
5724-H72 (C) Copyright IBM Corp. 1994, 2022.
Starting MQSC for queue manager QM1.

[admin@mqappl1 runmqsc]$ DISPLAY QMGR QMNAME
     1 : DISPLAY QMGR QMNAME
AMQ8408I: Display Queue Manager details.
   QMNAME(QM1)
[admin@mqappl1 runmqsc]$ DEFINE QLOCAL(TEST.QUEUE) MAXDEPTH(100)
     2 : DEFINE QLOCAL(TEST.QUEUE) MAXDEPTH(100)
AMQ8006I: IBM MQ Appliance queue created.
[admin@mqappl1 runmqsc]$ DISPLAY QLOCAL(TEST.QUEUE) MAXDEPTH CURDEPTH
     3 : DISPLAY QLOCAL(TEST.QUEUE) MAXDEPTH CURDEPTH
AMQ8409I: Display Queue details.
   QUEUE(TEST.QUEUE)                       TYPE(QLOCAL)
   CURDEPTH(0)                             MAXDEPTH(100)
[admin@mqappl1 runmqsc]$ END
     4 : END
3 MQSC commands read.
No commands have a syntax error.
All valid MQSC commands were processed.
[admin@mqappl1 mqcli]$ exit
```


text:
import { IteratorClass } from '../iterator'
import { IterableClass, isIterable } from '../iterable'
import { RecursiveOrElement } from './recursiveType'
import { $$iterator } from '../symbol'

export class ConcatAllIterator<T> extends IteratorClass<T> {
  protected i = 0
  protected iterators: Iterator<RecursiveOrElement<T>>[]

  constructor(it: { [Symbol.iterator](): Iterator<RecursiveOrElement<T>> }) {
    super()
    this.iterators = [it[$$iterator]()]
  }

  next() {
    const self = this

    function recurse(): IteratorResult<T> {
      if (self.iterators.length === 0) {
        return self.settleReturn()
      } else {
        const lastR = self.iterators[self.iterators.length - 1]
        const next = lastR.next()
        if (next.done) {
          self.iterators.pop()
          return recurse()
        } else {
          const _value = next.value
          if (isIterable(_value)) {
            self.iterators.push(_value[$$iterator]())
            return recurse()
          } else {
            return self.settleNext(<T>_value)
          }
        }
      }
    }

    return recurse()
  }
}

export class ConcatAllIterable<T> extends IterableClass<T> {
  constructor(tSource: { [Symbol.iterator](): Iterator<RecursiveOrElement<T>> }) {
    super(new ConcatAllIterator(tSource))
  }
}

export function concatAll<T>() {
  return new ConcatAllIterable(this)
}


text:
import angular from 'angular';
angular.module('dimLogin', []);


text:
package hpl.lang;

import java.util.*;
import hpl.sys.*;

/**
 * An instance of the PIRSequence class is a sequence of
 * PIRExp objects.  Each expression representation is
 * treated as if it were a statement -- even if it yields a result.
 *
 * @author Daniel Coore
 * @version 1.0
 */
public class PIRSequence extends PIRExp {

    protected ArrayList<PIRStatement> sequence;

    /**
     * Create an empty sequence of statements
     *
     */
    public PIRSequence() {
	sequence = new ArrayList<>();
    }

    /**
     * Creates a new PIRSequence instance.
     *
     * @param seq an ArrayList value
     */
    public PIRSequence(ArrayList<PIRStatement> seq) {
	sequence = seq;
    }

    /**
     * Add an HPL statement to the end of this sequence.
     *
     * @param stmt the statement to be added.
     */
    public void addStatement(PIRStatement stmt) {
	sequence.add(stmt);
    }

    public final ArrayList<PIRStatement> getStatements() {
	return sequence;
    }

    /**
     * Call the visitPIRSequence method within v on this
     * sequence representation and the given argument.
     *
     * @param v a Visitor value
     * @param state the data to be passed to this sequence's components
     * @return the result of visiting this sequence
     * @throws hpl.sys.HPLException
     */
    @Override
    public <S, T> T visit(HPLVisitor<S, T> v, S state) throws HPLException {
	return v.visitPIRSequence(this, state);
    }
}


text:
package org.onosproject.cordvtn.rest;

import org.onosproject.rest.AbstractWebResource;

import javax.ws.rs.Path;

/**
 * Manages service dependency.
 */
@Path("service-dependency")
public class ServiceDependencyWebResource extends AbstractWebResource {
}


text:
@class GitHub;

@interface GitHubService : NSObject <GitHubDelegate>
{
    IBOutlet id<GitHubServiceDelegate> delegate;

    IBOutlet NSObject<ConfigReader> * configReader;

    IBOutlet NSObject<LogInStateReader> * logInStateReader;
    IBOutlet NSObject<LogInStateSetter> * logInStateSetter;
    IBOutlet NSObject<UserCacheSetter> * userCacheSetter;
    IBOutlet NSObject<UserCacheReader> * userCacheReader;
    IBOutlet NSObject<RepoCacheSetter> * repoCacheSetter;
    IBOutlet NSObject<RepoCacheReader> * repoCacheReader;
    IBOutlet NSObject<CommitCacheSetter> * commitCacheSetter;
    IBOutlet NSObject<CommitCacheReader> * commitCacheReader;
    IBOutlet NSObject<UserNetworkCacheSetter> * userNetworkCacheSetter;

    NSString * usernameForLogInAttempt;

    GitHub * gitHub;
}

@property (nonatomic, retain) <GitHubServiceDelegate> delegate;

#pragma mark Initialization

- (id)initWithConfigReader:(NSObject<ConfigReader> *)aConfigReader
    logInState:(LogInState *)logInState
    userCache:(UserCache*)userCache repoCache:(RepoCache *)repoCache
    commitCache:(CommitCache *)commitCache
    userNetworkCache:(UserNetworkCache *)userNetworkCache;

#pragma mark Logging in

//
// Only one log in attempt is permitted at a time.
//

- (void)logIn:(NSString *)username;
- (void)logIn:(NSString *)username token:(NSString *)token;

#pragma mark Fetching user info

- (void)fetchInfoForUsername:(NSString *)username;

#pragma mark Fetching repository information

- (void)fetchInfoForRepo:(NSString *)repo username:(NSString *)username;

#pragma mark Fetching commit information

- (void)fetchInfoForCommit:(NSString *)commitKey
                      repo:(NSString *)repo
                  username:(NSString *)username;

#pragma mark Fetching followers

- (void)fetchFollowingForUsername:(NSString *)username;
- (void)fetchFollowersForUsername:(NSString *)username;

- (void)followUsername:(NSString *)followee;
- (void)unfollowUsername:(NSString *)followee;

#pragma mark Searching GitHub

- (void)searchUsers:(NSString *)searchString;
- (void)searchRepos:(NSString *)searchString;

@end


text:
"use strict"

var recurso;
var init = function(tiles){
    console.log("called with "+tiles)
    if ( (! !!window.parentCallback) && (! !!window.globals) ){
        console.error("parentCallback or globals were not passed into the window!");
    } else {
        recurso = new Recurso(window.globals.playerNames, tiles);
        initWindow();
    }
}

var playTurnButton, autoPlayButton;
var initWindow = function(){
    playTurnButton = document.getElementById("playTurn");
    playTurnButton.onclick = function(){recurso.playTurn();};

    autoPlayButton = document.getElementById("autoPlay");
    autoPlayButton.onclick = function(){onAutoPlay();};

    recurso.displayGame();
}

var autoSpeed = 200;
var timeOut;
var isAutoPlaying = false;
var onAutoPlay = function(){
    isAutoPlaying = true;
    clearTimeout(timeOut);
    recurso.playTurn();
    timeOut = setTimeout(onAutoPlay, autoSpeed);
}

var diceRoll = function(){
    return Math.ceil(Math.random()*6)
}

var makePlayerArray = function(names){
    var l = [];
    for (var i = 0; i < names.length; ++i){
        l.push({name:names[i], tile: 0});
    }
    return l;
}

// RECURSO ///////////////////////////////////////////////

var Recurso = function(playerNames, tiles) {
    this.playerNames = playerNames;
    this.players = makePlayerArray(playerNames);
    this.tiles = parseInt(tiles);
    this.currentTurn = 0;

    this.isRecursoGameActive = false;
};

Recurso.prototype = {
    constructor: Recurso,
    playTurn: function(){
        if (this.isRecursoGameActive){
            // recurso game in progress: do not play turn
            return;
        }

        var p = this.players[this.currentTurn];
        var roll = diceRoll();
        p.tile += roll;

        if (p.tile >= this.tiles-1){
            this.onGameEnd();
            return;
        }

        document.getElementById("rollResult").textContent = this.players[this.currentTurn].name + " rolled a " + roll + "!";
        this.displayGame();

        if (p.tile != 0 && p.tile % 2 != 0){
            this.onChallenge();
            // note that currentTurn is not incremented in this case
            // the result of the challenge determines whether or not the player gets to roll twice
            return;
        }

        this.currentTurn = (this.currentTurn+1) % this.players.length;
    },
    onGameEnd: function(){
        console.log(this.players[this.currentTurn].name + " won");
        parentCallback({winner: this.currentTurn, winnerName: this.players[this.currentTurn].name});
        window.close();
    },
    onChallenge: function(){
        document.getElementById("lastEvent").textContent = (this.players[this.currentTurn].name + " set off a challenge square!");
        globals.addInstances(1);
        globals.incrementTotalInstances();

        this.isRecursoGameActive = true;

        var childWindow = window.open("index.html", "Recurso #"+globals.totalInstances, "width=300, height=400");
        childWindow.window.globals = globals;
        childWindow.window.parentCallback = function(results){recurso.childCallback(results);};
        var tileAm = this.tiles;
        childWindow.window.onload = function(){
            childWindow.window.init(tileAm-1);
            childWindow.document.title = "Recurso #"+globals.totalInstances;

            if (isAutoPlaying){
                childWindow.window.isAutoPlaying = true;
                childWindow.window.onAutoPlay();
            }
        };

    },
    childCallback: function(results){
        if (results.winner === -1){
            document.getElementById("lastEvent").textContent = "challenge board size <3, ignored.";
            return;
        }
        if (results.winner != this.currentTurn){
            this.currentTurn = (this.currentTurn+1)%this.players.length;
        }
        globals.addInstances(-1);
        this.isRecursoGameActive = false;
        document.getElementById("lastEvent").textContent = results.winnerName + " won the challenge!";
        this.displayGame();
    },
    displayGame: function(){
        document.getElementById("boardState").textContent = this.toString();
    },
    toString: function(){
        var s = "";

        s += "< ";
        for (var i = 0; i < this.players.length; ++i){
            if (this.players[i].tile === 0){
                    s += (i+1) + " ";
            }
        }
        s += ">";

        for (var j = 1; j < this.tiles-1; ++j){
            s += (j%2 === 0) ? "{ " : "[ ";
            for (var k = 0; k < this.players.length; ++k){
                if (this.players[k].tile === j){
                    s += (k+1) + " ";
                }
            }
            s += (j%2 === 0) ? "}" : "]";
        }

        s += "< ";
        for (var i = 0; i < this.players.length; ++i){
            if (this.players[i].tile === this.tiles-1){
                    s += (i+1) + " ";
            }
        }
        s += ">";

        return s;
    }
};


text:
import React from 'react';

import Image from 'react-native-image-progress';
import styled from 'styled-components/native';
import type { ThemeType } from 'constants/theme';
import defaultPicture from 'assets/default_user.png';

import type { Story as StoryType } from 'types';

type Props = {
  story: StoryType,
  style?: ?any,
};

const getTextColor = ({
  theme,
  secondary = false,
}: { theme: ThemeType, secondary?: boolean }) =>
  (secondary ? theme.text.colors.secondary : theme.text.colors.primary);

const Container = styled.View`
  flex: 1;
  flex-direction: row;
  background-color: ${({ theme }: { theme: ThemeType }) => theme.colors.white};
  height: 120;
`;
const ImageContainer = styled.View`
  width: 120;
  align-items: center;
  justify-content: center;
`;
const AuthorImage = styled(Image)`
  width: 100;
  height: 100;

`;
const TextArea = styled.View`
  flex: 1;
  padding: 16;
  flex-direction: column;

`;
const BaseText = styled.Text`
  color: ${props => getTextColor(props)};
  font-size: 16;
`;

const Story = ({ story, style }: Props): ElementType => (
  <Container style={style}>
    <ImageContainer>
      <AuthorImage
        source={
          story.author.picture ? { uri: story.author.picture } : defaultPicture
        }
        resizemode="cover"
      />
    </ImageContainer>
    <TextArea>
      <BaseText secondary>{story.author.name}</BaseText>
      <BaseText>{story.content}</BaseText>
    </TextArea>
  </Container>
);

export default Story;


text:
.class public final enum Lcom/caverock/androidsvg/SVG$Unit;
.super Ljava/lang/Enum;
.source "SVG.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/caverock/androidsvg/SVG;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x401c
    name = "Unit"
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Ljava/lang/Enum",
        "<",
        "Lcom/caverock/androidsvg/SVG$Unit;",
        ">;"
    }
.end annotation

# static fields
.field private static final synthetic $VALUES:[Lcom/caverock/androidsvg/SVG$Unit;

.field public static final enum cm:Lcom/caverock/androidsvg/SVG$Unit;

.field public static final enum em:Lcom/caverock/androidsvg/SVG$Unit;

.field public static final enum ex:Lcom/caverock/androidsvg/SVG$Unit;

.field public static final enum in:Lcom/caverock/androidsvg/SVG$Unit;

.field public static final enum mm:Lcom/caverock/androidsvg/SVG$Unit;

.field public static final enum pc:Lcom/caverock/androidsvg/SVG$Unit;

.field public static final enum percent:Lcom/caverock/androidsvg/SVG$Unit;

.field public static final enum pt:Lcom/caverock/androidsvg/SVG$Unit;

.field public static final enum px:Lcom/caverock/androidsvg/SVG$Unit;

# direct methods
.method static constructor <clinit>()V
    .locals 8

    const/4 v7, 0x4

    const/4 v6, 0x3

    const/4 v5, 0x2

    const/4 v4, 0x1

    const/4 v3, 0x0

    new-instance v0, Lcom/caverock/androidsvg/SVG$Unit;

    const-string/jumbo v1, "px"

    invoke-direct {v0, v1, v3}, Lcom/caverock/androidsvg/SVG$Unit;-><init>(Ljava/lang/String;I)V

    sput-object v0, Lcom/caverock/androidsvg/SVG$Unit;->px:Lcom/caverock/androidsvg/SVG$Unit;

    new-instance v0, Lcom/caverock/androidsvg/SVG$Unit;

    const-string/jumbo v1, "em"

    invoke-direct {v0, v1, v4}, Lcom/caverock/androidsvg/SVG$Unit;-><init>(Ljava/lang/String;I)V

    sput-object v0, Lcom/caverock/androidsvg/SVG$Unit;->em:Lcom/caverock/androidsvg/SVG$Unit;

    new-instance v0, Lcom/caverock/androidsvg/SVG$Unit;

    const-string/jumbo v1, "ex"

    invoke-direct {v0, v1, v5}, Lcom/caverock/androidsvg/SVG$Unit;-><init>(Ljava/lang/String;I)V

    sput-object v0, Lcom/caverock/androidsvg/SVG$Unit;->ex:Lcom/caverock/androidsvg/SVG$Unit;

    new-instance v0, Lcom/caverock/androidsvg/SVG$Unit;

    const-string/jumbo v1, "in"

    invoke-direct {v0, v1, v6}, Lcom/caverock/androidsvg/SVG$Unit;-><init>(Ljava/lang/String;I)V

    sput-object v0, Lcom/caverock/androidsvg/SVG$Unit;->in:Lcom/caverock/androidsvg/SVG$Unit;

    new-instance v0, Lcom/caverock/androidsvg/SVG$Unit;

    const-string/jumbo v1, "cm"

    invoke-direct {v0, v1, v7}, Lcom/caverock/androidsvg/SVG$Unit;-><init>(Ljava/lang/String;I)V

    sput-object v0, Lcom/caverock/androidsvg/SVG$Unit;->cm:Lcom/caverock/androidsvg/SVG$Unit;

    new-instance v0, Lcom/caverock/androidsvg/SVG$Unit;

    const-string/jumbo v1, "mm"

    const/4 v2, 0x5

    invoke-direct {v0, v1, v2}, Lcom/caverock/androidsvg/SVG$Unit;-><init>(Ljava/lang/String;I)V

    sput-object v0, Lcom/caverock/androidsvg/SVG$Unit;->mm:Lcom/caverock/androidsvg/SVG$Unit;

    new-instance v0, Lcom/caverock/androidsvg/SVG$Unit;

    const-string/jumbo v1, "pt"

    const/4 v2, 0x6

    invoke-direct {v0, v1, v2}, Lcom/caverock/androidsvg/SVG$Unit;-><init>(Ljava/lang/String;I)V

    sput-object v0, Lcom/caverock/androidsvg/SVG$Unit;->pt:Lcom/caverock/androidsvg/SVG$Unit;

    new-instance v0, Lcom/caverock/androidsvg/SVG$Unit;

    const-string/jumbo v1, "pc"

    const/4 v2, 0x7

    invoke-direct {v0, v1, v2}, Lcom/caverock/androidsvg/SVG$Unit;-><init>(Ljava/lang/String;I)V

    sput-object v0, Lcom/caverock/androidsvg/SVG$Unit;->pc:Lcom/caverock/androidsvg/SVG$Unit;

    new-instance v0, Lcom/caverock/androidsvg/SVG$Unit;

    const-string/jumbo v1, "percent"

    const/16 v2, 0x8

    invoke-direct {v0, v1, v2}, Lcom/caverock/androidsvg/SVG$Unit;-><init>(Ljava/lang/String;I)V

    sput-object v0, Lcom/caverock/androidsvg/SVG$Unit;->percent:Lcom/caverock/androidsvg/SVG$Unit;

    const/16 v0, 0x9

    new-array v0, v0, [Lcom/caverock/androidsvg/SVG$Unit;

    sget-object v1, Lcom/caverock/androidsvg/SVG$Unit;->px:Lcom/caverock/androidsvg/SVG$Unit;

    aput-object v1, v0, v3

    sget-object v1, Lcom/caverock/androidsvg/SVG$Unit;->em:Lcom/caverock/androidsvg/SVG$Unit;

    aput-object v1, v0, v4

    sget-object v1, Lcom/caverock/androidsvg/SVG$Unit;->ex:Lcom/caverock/androidsvg/SVG$Unit;

    aput-object v1, v0, v5

    sget-object v1, Lcom/caverock/androidsvg/SVG$Unit;->in:Lcom/caverock/androidsvg/SVG$Unit;

    aput-object v1, v0, v6

    sget-object v1, Lcom/caverock/androidsvg/SVG$Unit;->cm:Lcom/caverock/androidsvg/SVG$Unit;

    aput-object v1, v0, v7

    sget-object v1, Lcom/caverock/androidsvg/SVG$Unit;->mm:Lcom/caverock/androidsvg/SVG$Unit;

    const/4 v2, 0x5

    aput-object v1, v0, v2

    sget-object v1, Lcom/caverock/androidsvg/SVG$Unit;->pt:Lcom/caverock/androidsvg/SVG$Unit;

    const/4 v2, 0x6

    aput-object v1, v0, v2

    sget-object v1, Lcom/caverock/androidsvg/SVG$Unit;->pc:Lcom/caverock/androidsvg/SVG$Unit;

    const/4 v2, 0x7

    aput-object v1, v0, v2

    sget-object v1, Lcom/caverock/androidsvg/SVG$Unit;->percent:Lcom/caverock/androidsvg/SVG$Unit;

    const/16 v2, 0x8

    aput-object v1, v0, v2

    sput-object v0, Lcom/caverock/androidsvg/SVG$Unit;->$VALUES:[Lcom/caverock/androidsvg/SVG$Unit;

    return-void
.end method

.method private constructor <init>(Ljava/lang/String;I)V
    .locals 0
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()V"
        }
    .end annotation

    invoke-direct {p0, p1, p2}, Ljava/lang/Enum;-><init>(Ljava/lang/String;I)V

    return-void
.end method

.method public static valueOf(Ljava/lang/String;)Lcom/caverock/androidsvg/SVG$Unit;
    .locals 1

    const-class v0, Lcom/caverock/androidsvg/SVG$Unit;

    invoke-static {v0, p0}, Ljava/lang/Enum;->valueOf(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;

    move-result-object v0

    check-cast v0, Lcom/caverock/androidsvg/SVG$Unit;

    return-object v0
.end method

.method public static values()[Lcom/caverock/androidsvg/SVG$Unit;
    .locals 1

    sget-object v0, Lcom/caverock/androidsvg/SVG$Unit;->$VALUES:[Lcom/caverock/androidsvg/SVG$Unit;

    invoke-virtual {v0}, Ljava/lang/Object;->clone()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, [Lcom/caverock/androidsvg/SVG$Unit;

    return-object v0
.end method


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

namespace MvcRouteTester.Common
{
	public class PropertyReader
	{
		private static readonly IgnoreAttributes IgnoreAttributes = new IgnoreAttributes();

		public static void AddIgnoreAttributes(IEnumerable<Type> types)
		{
			IgnoreAttributes.Add(types);
		}

		public static void AddIgnoreAttribute(Type type)
		{
			IgnoreAttributes.Add(type);
		}

		public static void ClearIgnoreAttributes()
		{
			IgnoreAttributes.Clear();
		}

		public bool IsSimpleType(Type type)
		{
			return TypeHelper.CanConvertFromString(type);
		}

		public RouteValues RouteValues(object dataObject)
		{
			var propertiesList = PropertiesList(dataObject);

			var expectedProps = new RouteValues();
			expectedProps.AddRangeWithParse(propertiesList);
			return expectedProps;
		}

		public IList<RouteValue> PropertiesList(object dataObject, RouteValueOrigin origin = RouteValueOrigin.Unknown)
		{
			var result = new List<RouteValue>();
			if (dataObject == null)
			{
				return result;
			}

			var type = dataObject.GetType();
			var objectProperties = GetPublicObjectProperties(type);

			foreach (PropertyInfo objectProperty in objectProperties)
			{
				if (IsSimpleType(objectProperty.PropertyType))
				{
					var value = GetPropertyValue(dataObject, objectProperty);
					result.Add(new RouteValue(objectProperty.Name, value, origin));
				}
			}

			return result;
		}

		private object GetPropertyValue(object dataObject, PropertyInfo objectProperty)
		{
			var getMethod = objectProperty.GetGetMethod();
			return getMethod.Invoke(dataObject, null);
		}

		public IEnumerable<string> SimplePropertyNames(Type type)
		{
			if (type == null)
			{
				throw new ArgumentNullException("type");
			}

			var objectProperties = GetPublicObjectProperties(type);

			var result = new List<string>();
			foreach (PropertyInfo objectProperty in objectProperties)
			{
				if (IsSimpleType(objectProperty.PropertyType))
				{
					result.Add(objectProperty.Name);
				}
			}

			return result;
		}

		private static IEnumerable<PropertyInfo> GetPublicObjectProperties(Type type)
		{
			return type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
				.Where(p => ! IgnoreAttributes.PropertyIsIgnored(p))
				.ToList();
		}
	}
}