text:
import functools
import itertools
from collections import OrderedDict

import numpy
import pandas
import scipy.sparse as spsparse
from interface_meta import override
from formulaic.utils.cast import as_columns

from .base import FormulaMaterializer
from .types import NAAction

class PandasMaterializer(FormulaMaterializer):

    REGISTER_NAME = "pandas"
    REGISTER_INPUTS = ("pandas.core.frame.DataFrame",)
    REGISTER_OUTPUTS = ("pandas", "numpy", "sparse")

    @override
    def _is_categorical(self, values):
        if isinstance(values, (pandas.Series, pandas.Categorical)):
            return values.dtype == object or isinstance(
                values.dtype, pandas.CategoricalDtype
            )
        return super()._is_categorical(values)

    @override
    def _check_for_nulls(self, name, values, na_action, drop_rows):

        if na_action is NAAction.IGNORE:
            return

        if isinstance(
            values, dict
        ):  # pragma: no cover; no formulaic transforms return dictionaries any more
            for key, vs in values.items():
                self._check_for_nulls(f"{name}[{key}]", vs, na_action, drop_rows)

        elif na_action is NAAction.RAISE:
            if isinstance(values, pandas.Series) and values.isnull().values.any():
                raise ValueError(f"`{name}` contains null values after evaluation.")

        elif na_action is NAAction.DROP:
            if isinstance(values, pandas.Series):
                drop_rows.update(numpy.flatnonzero(values.isnull().values))

        else:
            raise ValueError(
                f"Do not know how to interpret `na_action` = {repr(na_action)}."
            )  # pragma: no cover; this is currently impossible to reach

    @override
    def _encode_constant(self, value, metadata, encoder_state, spec, drop_rows):
        if spec.output == "sparse":
            return spsparse.csc_matrix(
                numpy.array([value] * self.nrows).reshape(
                    (self.nrows - len(drop_rows), 1)
                )
            )
        series = value * numpy.ones(self.nrows - len(drop_rows))
        return series

    @override
    def _encode_numerical(self, values, metadata, encoder_state, spec, drop_rows):
        if drop_rows:
            values = values.drop(index=values.index[drop_rows])
        if spec.output == "sparse":
            return spsparse.csc_matrix(numpy.array(values).reshape((self.nrows, 1)))
        return values

    @override
    def _encode_categorical(
        self, values, metadata, encoder_state, spec, drop_rows, reduced_rank=False
    ):
        # Even though we could reduce rank here, we do not, so that the same
        # encoding can be cached for both reduced and unreduced rank. The
        # rank will be reduced in the _encode_evaled_factor method.
        from formulaic.transforms import encode_contrasts

        if drop_rows:
            values = values.drop(index=values.index[drop_rows])
        return as_columns(
            encode_contrasts(
                values,
                reduced_rank=False,
                _metadata=metadata,
                _state=encoder_state,
                _spec=spec,
            )
        )

    @override
    def _get_columns_for_term(self, factors, spec, scale=1):
        out = OrderedDict()

        # Pre-multiply factors with only one set of values (improves performance)
        solo_factors = {}
        indices = []
        for i, factor in enumerate(factors):
            if len(factor) == 1:
                solo_factors.update(factor)
                indices.append(i)
        if solo_factors:
            for index in reversed(indices):
                factors.pop(index)
            if spec.output == "sparse":
                factors.append(
                    {
                        ":".join(solo_factors): functools.reduce(
                            spsparse.csc_matrix.multiply, solo_factors.values()
                        )
                    }
                )
            else:
                factors.append(
                    {
                        ":".join(solo_factors): functools.reduce(
                            numpy.multiply,
                            (numpy.asanyarray(p) for p in solo_factors.values()),
                        )
                    }
                )

        for product in itertools.product(*(factor.items() for factor in factors)):
            if spec.output == "sparse":
                out[":".join(p[0] for p in product)] = scale * functools.reduce(
                    spsparse.csc_matrix.multiply, (p[1] for p in product)
                )
            else:
                out[":".join(p[0] for p in product)] = scale * functools.reduce(
                    numpy.multiply,
                    (numpy.array(p[1]) for p in product),
                )
        return out

    @override
    def _combine_columns(self, cols, spec, drop_rows):
        # If we are outputing a pandas DataFrame, explicitly override index
        # in case transforms/etc have lost track of it.
        if spec.output == "pandas":
            pandas_index = self.data_context.index
            if drop_rows:
                pandas_index = pandas_index.drop(self.data_context.index[drop_rows])

        # Special case no columns to empty csc_matrix, array, or DataFrame
        if not cols:
            values = numpy.empty((self.data.shape[0], 0))
            if spec.output == "sparse":
                return spsparse.csc_matrix(values)
            if spec.output == "numpy":
                return values
            return pandas.DataFrame(index=pandas_index)

        # Otherwise, concatenate columns into model matrix
        if spec.output == "sparse":
            return spsparse.hstack([col[1] for col in cols])
        if spec.output == "numpy":
            return numpy.stack([col[1] for col in cols], axis=1)
        return pandas.DataFrame(
            {col[0]: col[1] for col in cols},
            index=pandas_index,
            copy=False,
        )


text:
"""Unit tests for test_record module."""

import sys
import unittest

from openhtf.core import test_record

def _get_obj_size(obj):
  size = 0
  for attr in obj.__slots__:  # pytype: disable=attribute-error
    size += sys.getsizeof(attr)
    size += sys.getsizeof(getattr(obj, attr))
  return size

class TestRecordTest(unittest.TestCase):

  def test_attachment_data(self):
    expected_data = b'test attachment data'
    attachment = test_record.Attachment(expected_data, 'text')
    data = attachment.data
    self.assertEqual(data, expected_data)

  def test_attachment_size(self):
    expected_size = 10
    data = b't' * expected_size
    attachment = test_record.Attachment(data, 'text')
    self.assertEqual(attachment.size, expected_size)

  def test_attachment_memory_safety(self):
    small_data = b' '  # Use non-empty so Attachment.size (ints) are equal size.
    empty_attachment = test_record.Attachment(small_data, 'text')
    expected_obj_size = _get_obj_size(empty_attachment)
    large_data = b'test attachment data' * 1000
    attachment = test_record.Attachment(large_data, 'text')
    obj_size = _get_obj_size(attachment)
    self.assertEqual(obj_size, expected_obj_size)

redpajama_set_name: RedPajamaGithub


text:
package org.apache.camel.impl;

import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;

public class OriginalMessageProcessor implements Processor {

    @Override
    public void process(Exchange exchange) throws Exception {
        Message original = null;
        if (exchange.getContext().isAllowUseOriginalMessage()) {
            original = exchange.getUnitOfWork().getOriginalInMessage();
        }
        if (original == null) {
            exchange.getIn().setHeader("HasOriginal", "false");
        } else {
            exchange.getIn().setHeader("HasOriginal", "true");
            exchange.getIn().setHeader("OriginalBody", original.getBody());
            exchange.getIn().setHeader("OriginalExchangeId", original.getExchange().getExchangeId());
        }
    }

}


text:
/**
 * @requires OpenLayers/Format/XML.js
 * @requires OpenLayers/Format/OWSCommon/v1_0_0.js
 */

/**
 * Class: OpenLayers.Format.OGCExceptionReport
 * Class to read exception reports for various OGC services and versions.
 *
 * Inherits from:
 *  - <OpenLayers.Format.XML>
 */
OpenLayers.Format.OGCExceptionReport = OpenLayers.Class(OpenLayers.Format.XML, {

    /**
     * Property: namespaces
     * {Object} Mapping of namespace aliases to namespace URIs.
     */
    namespaces: {
        ogc: "http://www.opengis.net/ogc"
    },

    /**
     * Property: regExes
     * Compiled regular expressions for manipulating strings.
     */
    regExes: {
        trimSpace: (/^\s*|\s*$/g),
        removeSpace: (/\s*/g),
        splitSpace: (/\s+/),
        trimComma: (/\s*,\s*/g)
    },

    /**
     * Property: defaultPrefix
     */
    defaultPrefix: "ogc",

    /**
     * Constructor: OpenLayers.Format.OGCExceptionReport
     * Create a new parser for OGC exception reports.
     *
     * Parameters:
     * options - {Object} An optional object whose properties will be set on
     *     this instance.
     */

    /**
     * APIMethod: read
     * Read OGC exception report data from a string, and return an object with
     * information about the exceptions.
     *
     * Parameters:
     * data - {String} or {DOMElement} data to read/parse.
     *
     * Returns:
     * {Object} Information about the exceptions that occurred.
     */
    read: function(data) {
        var result;
        if(typeof data == "string") {
            data = OpenLayers.Format.XML.prototype.read.apply(this, [data]);
        }
        var root = data.documentElement;
        var exceptionInfo = {exceptionReport: null};
        if (root) {
            this.readChildNodes(data, exceptionInfo);
            if (exceptionInfo.exceptionReport === null) {
                // fall-back to OWSCommon since this is a common output format for exceptions
                // we cannot easily use the ows readers directly since they differ for 1.0 and 1.1
                exceptionInfo = new OpenLayers.Format.OWSCommon().read(data);
            }
        }
        return exceptionInfo;
    },

    /**
     * Property: readers
     * Contains public functions, grouped by namespace prefix, that will
     *     be applied when a namespaced node is found matching the function
     *     name.  The function will be applied in the scope of this parser
     *     with two arguments: the node being read and a context object passed
     *     from the parent.
     */
    readers: {
        "ogc": {
            "ServiceExceptionReport": function(node, obj) {
                obj.exceptionReport = {exceptions: []};
                this.readChildNodes(node, obj.exceptionReport);
            },
            "ServiceException": function(node, exceptionReport) {
                var exception = {
                    code: node.getAttribute("code"),
                    locator: node.getAttribute("locator"),
                    text: this.getChildValue(node)
                };
                exceptionReport.exceptions.push(exception);
            }
        }
    },

    CLASS_NAME: "OpenLayers.Format.OGCExceptionReport"

});


text:
<Record>
<Term>Anemia due to Disorder of Glutathione Metabolism</Term>
<SemanticType>Disease or Syndrome</SemanticType>
<ParentTerm>Anemia</ParentTerm>
<ClassificationPath>Findings_and_Disorders_Kind/Disease, Disorder or Finding/Disease or Disorder/Non-Neoplastic Disorder/Non-Neoplastic Disorder by Site/Non-Neoplastic Hematologic and Lymphocytic Disorder/Anemia/Anemia due to Disorder of Glutathione Metabolism</ClassificationPath>
<BroaderTerm>Anemia due to Disorder of Glutathione Metabolism</BroaderTerm>
<BroaderTerm>Non-Neoplastic Disorder by Site</BroaderTerm>
<BroaderTerm>Non-Neoplastic Disorder</BroaderTerm>
<BroaderTerm>Disease or Disorder</BroaderTerm>
<BroaderTerm>Anemia</BroaderTerm>
<BroaderTerm>Non-Neoplastic Hematologic and Lymphocytic Disorder</BroaderTerm>
<BroaderTerm>Disease, Disorder or Finding</BroaderTerm>
<BroaderTerm>Findings_and_Disorders_Kind</BroaderTerm>
<Synonym>Anemia due to Disorder of Glutathione Metabolism</Synonym>
<Source>NCI Thesaurus</Source>
</Record>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Copyright 2011 Bluetooth SIG, Inc. All rights reserved. -->
<Service xsi:noNamespaceSchemaLocation="http://schemas.bluetooth.org/Documents/service.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" type="org.bluetooth.service.tx_power" uuid="1804" name="Tx Power">
    <InformativeText>
        <Abstract>
    This service exposes a device's current transmit power level when in a connection.
		</Abstract>
        <Summary>
    The Tx Power service is instantiated as a Primary Service.
    There is only one instance of the Tx Power service on a device.
    There is exactly one instance of the Tx Power Level characteristic</Summary>
  </InformativeText>
    <Dependencies>
        <Dependency>This service has no dependencies on other GATT-based services.</Dependency>
    </Dependencies>
<!--    <GATTRequirements>
        <Requirement subProcedure="Notification">Mandatory if one or more Tx Power Level characteristics supports notification</Requirement>
        <Requirement subProcedure="Read Characteristic Descriptors">Mandotory if more than one Tx Power Level characteristics is exposed</Requirement>
        <Requirement subProcedure="Write Characteristic Descriptors">Mandatory if Notification is claimed</Requirement>
    </GATTRequirements>
-->
    <Transports>
        <Classic>false</Classic>
        <LowEnergy>true</LowEnergy>
    </Transports>
    <ErrorCodes>
    	Replace table by: This service does not define any application error codes that are used in Attribute Protocol.
    </ErrorCodes>
    <Characteristics>
        <Characteristic name="Tx Power Level" type="org.bluetooth.characteristic.tx_power_level">
            <InformativeText>
        The Tx Power Level characteristic represents the current transmit power level of a physical layer for which the characteristic is associated.
      </InformativeText>
            <Requirement>Mandatory</Requirement>
            <Properties>
                <Read>Mandatory</Read>
                <Write>Excluded</Write>
                <WriteWithoutResponse>Excluded</WriteWithoutResponse>
                <SignedWrite>Excluded</SignedWrite>
                <ReliableWrite>Excluded</ReliableWrite>
                <Notify>Excluded</Notify>
                <Indicate>Excluded</Indicate>
                <WritableAuxiliaries>Excluded</WritableAuxiliaries>
                <Broadcast>Excluded</Broadcast>
            </Properties>
<!--            <SecuritySettings>

                <Security>Authentication</Security>
            </SecuritySettings>
-->
            <!--
            <Descriptors>
                <Descriptor name="Characteristic Presentation Format" type="org.bluetooth.descriptor.gatt.characteristic_presentation_format">
                    <InformativeText>
            If there is more than one instance of the Tx Power Level characteristic exposed by the Transmit Power service, the Characteristic Presentation Format descriptor is included to identify the physical layer and modulation scheme for which the transmit power level applies.
          </InformativeText>
                    <Requirement>if_multiple_characteristics_implemented</Requirement>
                    <Properties>
                        <Read>Mandatory</Read>
                        <Write>Excluded</Write>
                    </Properties>
                </Descriptor>
                <Descriptor name="Client Configuration" type="org.bluetooth.descriptor.gatt.client_characteristic_configuration">
                    <InformativeText>
            If the characteristic can be notified or indicated, as defined by a higher level specification, the Client Configuration Characteristic descriptor is included.
          </InformativeText>
                    <Requirement>if_notify_or_indicate_supported</Requirement>
                    <Properties>
                        <Read>Mandatory</Read>
                        <Write>Mandatory</Write>
                    </Properties>
                </Descriptor>
            </Descriptors>
            -->
        </Characteristic>
    </Characteristics>
</Service>


text:
package ru.job4j.chess;

/**
 * FigureNotFoundException.
 * The exception is thrown when the specified cell has no figure.
 * @author Ivan Belyaev
 * @since 16.11.2017
 * @version 1.0
 */
public class FigureNotFoundException extends ChessException {
    /**
     * The constructor creates the object FigureNotFoundException.
     * @param message - message.
     */
    public FigureNotFoundException(String message) {
        super(message);
    }
}


text:
package org.hisp.dhis.programrule;

import org.hisp.dhis.program.Program;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

/**
 * @author markusbekken
 */
@Transactional
public class DefaultProgramRuleService
    implements ProgramRuleService
{
    // -------------------------------------------------------------------------
    // Dependencies
    // -------------------------------------------------------------------------

    private ProgramRuleStore programRuleStore;

    public void setProgramRuleStore( ProgramRuleStore programRuleStore )
    {
        this.programRuleStore = programRuleStore;
    }

    // -------------------------------------------------------------------------
    // ProgramRule implementation
    // -------------------------------------------------------------------------

    @Override
    public int addProgramRule( ProgramRule programRule )
    {
        programRuleStore.save( programRule );
        return programRule.getId();
    }

    @Override
    public void deleteProgramRule( ProgramRule programRule )
    {
        programRuleStore.delete( programRule );
    }

    @Override
    public void updateProgramRule( ProgramRule programRule )
    {
        programRuleStore.update( programRule );
    }

    @Override
    public ProgramRule getProgramRule( int id )
    {
        return programRuleStore.get( id );
    }

    @Override
    public ProgramRule getProgramRule( String uid )
    {
        return programRuleStore.getByUid( uid );
    }

    @Override
    public ProgramRule getProgramRuleByName( String name, Program program )
    {
        return programRuleStore.getByName( name, program );
    }

    @Override
    public List<ProgramRule> getAllProgramRule()
    {
        return programRuleStore.getAll();
    }

    @Override
    public List<ProgramRule> getImplementableProgramRules( Program program, Set<ProgramRuleActionType> types )
    {
        return programRuleStore.getImplementableProgramRules( program, types );
    }

    @Override
    public List<ProgramRule> getProgramRule( Program program )
    {
        return programRuleStore.get( program );
    }

    @Override
    public List<ProgramRule> getProgramRules( Program program, String key )
    {
        return programRuleStore.get( program, key );
    }
}


text:
package dyvilx.tools.compiler.ast.classes.metadata;

import dyvil.reflect.Modifiers;
import dyvilx.tools.asm.AnnotationVisitor;
import dyvilx.tools.asm.MethodVisitor;
import dyvilx.tools.compiler.ast.attribute.annotation.Annotation;
import dyvilx.tools.compiler.ast.classes.IClass;
import dyvilx.tools.compiler.ast.context.IContext;
import dyvilx.tools.compiler.ast.expression.ArrayExpr;
import dyvilx.tools.compiler.ast.expression.IValue;
import dyvilx.tools.compiler.ast.expression.constant.EnumValue;
import dyvilx.tools.compiler.ast.member.Named;
import dyvilx.tools.compiler.ast.member.MemberKind;
import dyvilx.tools.compiler.ast.parameter.ArgumentList;
import dyvilx.tools.compiler.ast.parameter.IParameter;
import dyvilx.tools.compiler.backend.classes.ClassWriter;
import dyvilx.tools.compiler.backend.exception.BytecodeException;
import dyvilx.tools.compiler.transform.Names;
import dyvilx.tools.parsing.marker.MarkerList;

import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
import java.util.EnumSet;
import java.util.Set;

public final class AnnotationMetadata implements IClassMetadata
{
	private IClass           theClass;
	public  RetentionPolicy  retention;
	public  Set<ElementType> targets;

	public AnnotationMetadata(IClass iclass)
	{
		this.theClass = iclass;
	}

	@Override
	public MemberKind getKind()
	{
		return MemberKind.ANNOTATION;
	}

	@Override
	public RetentionPolicy getRetention()
	{
		return this.retention;
	}

	@Override
	public Set<ElementType> getTargets()
	{
		return this.targets;
	}

	@Override
	public boolean isTarget(ElementType target)
	{
		return this.targets == null || this.targets.isEmpty() || this.targets.contains(target);
	}

	@Override
	public void resolveTypesBeforeBody(MarkerList markers, IContext context)
	{
		// Add the java.lang.Annotation interface
		if (!this.theClass.isSubClassOf(Annotation.LazyFields.ANNOTATION))
		{
			this.theClass.getInterfaces().add(Annotation.LazyFields.ANNOTATION);
		}

		if (this.retention == null)
		{
			this.readRetention();
		}
		if (this.targets == null)
		{
			this.readTargets();
		}
	}

	private void readRetention()
	{
		final Annotation retention = this.theClass.getAnnotation(Annotation.LazyFields.RETENTION_CLASS);
		if (retention == null)
		{
			return;
		}

		final IValue value = retention.getArguments().get(0, Names.value);
		if (!(value instanceof EnumValue))
		{
			return;
		}

		try
		{
			final String name = ((EnumValue) value).getName().qualified;
			this.retention = RetentionPolicy.valueOf(name);
		}
		catch (IllegalArgumentException ignored)
		{
			// Problematic RetentionPolicy annotation - do not handle this
		}
	}

	private void readTargets()
	{
		final Annotation target = this.theClass.getAnnotation(Annotation.LazyFields.TARGET_CLASS);
		if (target == null)
		{
			return;
		}

		this.targets = EnumSet.noneOf(ElementType.class);

		final IValue argument = target.getArguments().get(0, Names.value);
		if (!(argument instanceof ArrayExpr))
		{
			return;
		}

		final ArgumentList values = ((ArrayExpr) argument).getValues();
		final int size = values.size();

		for (int i = 0; i < size; i++)
		{
			final Named value = (Named) values.get(i);
			try
			{
				this.targets.add(ElementType.valueOf(value.getName().qualified));
			}
			catch (IllegalArgumentException ignored)
			{
				// Problematic Target annotation - do not handle this
			}
		}
	}

	@Override
	public void resolveTypesAfterBody(MarkerList markers, IContext context)
	{
	}

	@Override
	public void resolve(MarkerList markers, IContext context)
	{
	}

	@Override
	public void checkTypes(MarkerList markers, IContext context)
	{
		for (IParameter parameter : this.theClass.getParameters())
		{
			final IValue value = parameter.getValue();
			if (value != null)
			{
				parameter.setValue(IValue.toAnnotationConstant(value, markers, context));
			}
		}
	}

	@Override
	public void write(ClassWriter writer) throws BytecodeException
	{
		for (IParameter parameter : this.theClass.getParameters())
		{
			final StringBuilder desc = new StringBuilder("()");
			parameter.getType().appendExtendedName(desc);

			final MethodVisitor methodVisitor = writer.visitMethod(Modifiers.PUBLIC | Modifiers.ABSTRACT,
			                                                       parameter.getInternalName(), desc.toString(), null,
			                                                       null);

			final IValue argument = parameter.getValue();
			if (argument != null && argument.isAnnotationConstant())
			{
				final AnnotationVisitor av = methodVisitor.visitAnnotationDefault();
				argument.writeAnnotationValue(av, parameter.getInternalName());
				av.visitEnd();
			}

			methodVisitor.visitEnd();
		}
	}
}


text:
import {isFunction} from "./isFunction.js"
import {isBlob} from "./isBlob.js"
import {isFile} from "./isFile.js"
import {File} from "./File.js"

/**
 * A `string` or `File` that represents a single value from a set of `FormData` key-value pairs.
 */
export type FormDataEntryValue = string | File

/**
 * The list of entry values. Must be a non-empty array.
 */
type FormDataEntryValues = [FormDataEntryValue, ...FormDataEntryValue[]]

/**
 * Private options for FormData#setEntry() method
 */
interface FormDataSetFieldOptions {
  /**
   * The name of the field whose data is contained in `value`.
   */
  name: string

  /**
   * The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
    or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string.
   */
  rawValue: unknown

  /**
   * The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename.
   */
  fileName?: string

  /**
   * Indicates how the existent entry must be modified:
   *
   * 1. If the `FormData#set()` is called, the value should be `false` and existent entry values list will be replaced.
   * 2. If the `FormData#append()` is called, the value should be `true` and the new entry value will be added at the end of the existent entry values list.
   */
  append: boolean

  /**
   * An amout of arguments, passed to `FormData#set()` or `FormData#append()` methods.
   * This value is only necessary for dynamic error messages.
   */
  argsLength: number
}

/**
 * Provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using fetch().
 *
 * Note that this object is not a part of Node.js, so you might need to check if an HTTP client of your choice support spec-compliant FormData.
 * However, if your HTTP client does not support FormData, you can use [`form-data-encoder`](https://npmjs.com/package/form-data-encoder) package to handle "multipart/form-data" encoding.
 */
export class FormData {
  /**
   * Stores internal data for every entry
   */
  readonly #entries = new Map<string, FormDataEntryValues>()

  static [Symbol.hasInstance](value: unknown): value is FormData {
    if (!value) {
      return false
    }

    const val = value as FormData

    return Boolean(
      isFunction(val.constructor)
        && val[Symbol.toStringTag] === "FormData"
        && isFunction(val.append)
        && isFunction(val.set)
        && isFunction(val.get)
        && isFunction(val.getAll)
        && isFunction(val.has)
        && isFunction(val.delete)
        && isFunction(val.entries)
        && isFunction(val.values)
        && isFunction(val.keys)
        && isFunction(val[Symbol.iterator])
        && isFunction(val.forEach)
    )
  }

  #setEntry({
    name,
    rawValue,
    append,
    fileName,
    argsLength
  }: FormDataSetFieldOptions): void {
    const methodName = append ? "append" : "set"

    // FormData required at least 2 arguments to be set.
    if (argsLength < 2) {
      throw new TypeError(
        `Failed to execute '${methodName}' on 'FormData': `
          + `2 arguments required, but only ${argsLength} present.`
      )
    }

    // Make sure the name of the entry is always a string.
    name = String(name)

    // Normalize value to a string or File
    let value: FormDataEntryValue
    if (isFile(rawValue)) {
      // Check if fileName argument is present
      value = fileName === undefined
        ? rawValue // if there's no fileName, return let the value be rawValue
        : new File([rawValue], fileName, { // otherwise, create new file with given fileName
          type: rawValue.type,
          lastModified: rawValue.lastModified
        })
    } else if (isBlob(rawValue)) {
      // Use "blob" as default filename if the 3rd argument is not present
      value = new File([rawValue], fileName === undefined ? "blob" : fileName, {
        type: rawValue.type
      })
    } else if (fileName) { // If value is not a File or Blob, but the filename is present, throw following error:
      throw new TypeError(
        `Failed to execute '${methodName}' on 'FormData': `
          + "parameter 2 is not of type 'Blob'."
      )
    } else {
      // A non-file entries must be converted to string
      value = String(rawValue)
    }

    // Get an entry associated with given name
    const values = this.#entries.get(name)

    // If there's no such entry, create a new set of values with the name.
    if (!values) {
      return void this.#entries.set(name, [value])
    }

    // If the entry exists:
    // Replace a value of the existing entry when the "set" method is called.
    if (!append) {
      return void this.#entries.set(name, [value])
    }

    // Otherwise append a new value to the existing entry.
    values.push(value)
  }

  /**
   * Appends a new value onto an existing key inside a FormData object,
   * or adds the key if it does not already exist.
   *
   * The difference between `set()` and `append()` is that if the specified key already exists, `set()` will overwrite all existing values with the new one, whereas `append()` will append the new value onto the end of the existing set of values.
   *
   * @param name The name of the field whose data is contained in `value`.
   * @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
    or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string.
   * @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename.
   */
  append(name: string, value: unknown, fileName?: string): void {
    this.#setEntry({
      name,
      fileName,
      append: true,
      rawValue: value,
      argsLength: arguments.length
    })
  }

  /**
   * Set a new value for an existing key inside FormData,
   * or add the new field if it does not already exist.
   *
   * @param name The name of the field whose data is contained in `value`.
   * @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
    or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string.
   * @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename.
   *
   */
  set(name: string, value: unknown, fileName?: string): void {
    this.#setEntry({
      name,
      fileName,
      append: false,
      rawValue: value,
      argsLength: arguments.length
    })
  }

  /**
   * Returns the first value associated with a given key from within a `FormData` object.
   * If you expect multiple values and want all of them, use the `getAll()` method instead.
   *
   * @param {string} name A name of the value you want to retrieve.
   *
   * @returns A `FormDataEntryValue` containing the value. If the key doesn't exist, the method returns null.
   */
  get(name: string): FormDataEntryValue | null {
    const field = this.#entries.get(String(name))

    if (!field) {
      return null
    }

    return field[0]
  }

  /**
   * Returns all the values associated with a given key from within a `FormData` object.
   *
   * @param {string} name A name of the value you want to retrieve.
   *
   * @returns An array of `FormDataEntryValue` whose key matches the value passed in the `name` parameter. If the key doesn't exist, the method returns an empty list.
   */
  getAll(name: string): FormDataEntryValue[] {
    const field = this.#entries.get(String(name))

    if (!field) {
      return []
    }

    return field.slice()
  }

  /**
   * Returns a boolean stating whether a `FormData` object contains a certain key.
   *
   * @param name A string representing the name of the key you want to test for.
   *
   * @return A boolean value.
   */
  has(name: string): boolean {
    return this.#entries.has(String(name))
  }

  /**
   * Deletes a key and its value(s) from a `FormData` object.
   *
   * @param name The name of the key you want to delete.
   */
  delete(name: string): void {
    this.#entries.delete(String(name))
  }

  /**
   * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all keys contained in this `FormData` object.
   * Each key is a `string`.
   */
  * keys(): Generator<string> {
    for (const key of this.#entries.keys()) {
      yield key
    }
  }

  /**
   * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through the `FormData` key/value pairs.
   * The key of each pair is a string; the value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue).
   */
  * entries(): Generator<[string, FormDataEntryValue]> {
    for (const name of this.keys()) {
      const values = this.getAll(name)

      // Yield each value of a field, like browser-side FormData does.
      for (const value of values) {
        yield [name, value]
      }
    }
  }

  /**
   * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all values contained in this object `FormData` object.
   * Each value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue).
   */
  * values(): Generator<FormDataEntryValue> {
    for (const [, value] of this) {
      yield value
    }
  }

  /**
   * An alias for FormData#entries()
   */
  [Symbol.iterator]() {
    return this.entries()
  }

  /**
   * Executes given callback function for each field of the FormData instance
   */
  forEach(
    callback: (value: FormDataEntryValue, key: string, form: FormData) => void,

    thisArg?: unknown
  ): void {
    for (const [name, value] of this) {
      callback.call(thisArg, value, name, this)
    }
  }

  get [Symbol.toStringTag](): string {
    return "FormData"
  }
}


text:
package revel

import (
	"reflect"
	"strings"
)

// Field represents a data field that may be collected in a web form.
type Field struct {
	Name       string
	Error      *ValidationError
	viewArgs   map[string]interface{}
	controller *Controller
}

func NewField(name string, viewArgs map[string]interface{}) *Field {
	err, _ := viewArgs["errors"].(map[string]*ValidationError)[name]
	controller, _ := viewArgs["_controller"].(*Controller)
	return &Field{
		Name:       name,
		Error:      err,
		viewArgs:   viewArgs,
		controller: controller,
	}
}

// ID returns an identifier suitable for use as an HTML id.
func (f *Field) ID() string {
	return strings.Replace(f.Name, ".", "_", -1)
}

// Flash returns the flashed value of this Field.
func (f *Field) Flash() string {
	v, _ := f.viewArgs["flash"].(map[string]string)[f.Name]
	return v
}

// Options returns the option list of this Field.
func (f *Field) Options() []string {
	if f.viewArgs["options"] == nil {
		return nil
	}
	v, _ := f.viewArgs["options"].(map[string][]string)[f.Name]
	return v
}

// FlashArray returns the flashed value of this Field as a list split on comma.
func (f *Field) FlashArray() []string {
	v := f.Flash()
	if v == "" {
		return []string{}
	}
	return strings.Split(v, ",")
}

// Value returns the current value of this Field.
func (f *Field) Value() interface{} {
	pieces := strings.Split(f.Name, ".")
	answer, ok := f.viewArgs[pieces[0]]
	if !ok {
		return ""
	}

	val := reflect.ValueOf(answer)
	for i := 1; i < len(pieces); i++ {
		if val.Kind() == reflect.Ptr {
			val = val.Elem()
		}
		val = val.FieldByName(pieces[i])
		if !val.IsValid() {
			return ""
		}
	}

	return val.Interface()
}

// ErrorClass returns ErrorCSSClass if this field has a validation error, else empty string.
func (f *Field) ErrorClass() string {
	if f.Error != nil {
		if errorClass, ok := f.viewArgs["ERROR_CLASS"]; ok {
			return errorClass.(string)
		}
		return ErrorCSSClass
	}
	return ""
}

// Get the short name and translate it.
func (f *Field) ShortName() string {
	name := f.Name
	if i := strings.LastIndex(name, "."); i > 0 {
		name = name[i+1:]
	}
	return f.Translate(name)
}

// Translate the text.
func (f *Field) Translate(text string, args ...interface{}) string {
	if f.controller != nil {
		text = f.controller.Message(text, args...)
	}
	return text
}


text:
<?php
class ConversationNotUniqueException extends ConversationException{ }


text:
package main

import (
	"fmt"
	"sort"
	"strconv"
	"strings"
	"testing"
	"time"

	"github.com/docker/docker/api/types/versions"
	"github.com/docker/docker/integration-cli/cli"
	"github.com/docker/docker/integration-cli/cli/build"
	"github.com/docker/docker/pkg/stringid"
	"gotest.tools/v3/assert"
	is "gotest.tools/v3/assert/cmp"
	"gotest.tools/v3/icmd"
	"gotest.tools/v3/skip"
)

func (s *DockerSuite) TestPsListContainersBase(c *testing.T) {
	existingContainers := ExistingContainerIDs(c)

	out := runSleepingContainer(c, "-d")
	firstID := strings.TrimSpace(out)

	out = runSleepingContainer(c, "-d")
	secondID := strings.TrimSpace(out)

	// not long running
	out, _ = dockerCmd(c, "run", "-d", "busybox", "true")
	thirdID := strings.TrimSpace(out)

	out = runSleepingContainer(c, "-d")
	fourthID := strings.TrimSpace(out)

	// make sure the second is running
	assert.Assert(c, waitRun(secondID) == nil)

	// make sure third one is not running
	dockerCmd(c, "wait", thirdID)

	// make sure the forth is running
	assert.Assert(c, waitRun(fourthID) == nil)

	// all
	out, _ = dockerCmd(c, "ps", "-a")
	assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), []string{fourthID, thirdID, secondID, firstID}), true, fmt.Sprintf("ALL: Container list is not in the correct order: \n%s", out))

	// running
	out, _ = dockerCmd(c, "ps")
	assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), []string{fourthID, secondID, firstID}), true, fmt.Sprintf("RUNNING: Container list is not in the correct order: \n%s", out))

	// limit
	out, _ = dockerCmd(c, "ps", "-n=2", "-a")
	expected := []string{fourthID, thirdID}
	assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("LIMIT & ALL: Container list is not in the correct order: \n%s", out))

	out, _ = dockerCmd(c, "ps", "-n=2")
	assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("LIMIT: Container list is not in the correct order: \n%s", out))

	// filter since
	out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-a")
	expected = []string{fourthID, thirdID, secondID}
	assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("SINCE filter & ALL: Container list is not in the correct order: \n%s", out))

	out, _ = dockerCmd(c, "ps", "-f", "since="+firstID)
	expected = []string{fourthID, secondID}
	assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("SINCE filter: Container list is not in the correct order: \n%s", out))

	out, _ = dockerCmd(c, "ps", "-f", "since="+thirdID)
	expected = []string{fourthID}
	assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("SINCE filter: Container list is not in the correct order: \n%s", out))

	// filter before
	out, _ = dockerCmd(c, "ps", "-f", "before="+fourthID, "-a")
	expected = []string{thirdID, secondID, firstID}
	assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("BEFORE filter & ALL: Container list is not in the correct order: \n%s", out))

	out, _ = dockerCmd(c, "ps", "-f", "before="+fourthID)
	expected = []string{secondID, firstID}
	assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("BEFORE filter: Container list is not in the correct order: \n%s", out))

	out, _ = dockerCmd(c, "ps", "-f", "before="+thirdID)
	expected = []string{secondID, firstID}
	assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("SINCE filter: Container list is not in the correct order: \n%s", out))

	// filter since & before
	out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-f", "before="+fourthID, "-a")
	expected = []string{thirdID, secondID}
	assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("SINCE filter, BEFORE filter & ALL: Container list is not in the correct order: \n%s", out))

	out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-f", "before="+fourthID)
	expected = []string{secondID}
	assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("SINCE filter, BEFORE filter: Container list is not in the correct order: \n%s", out))

	// filter since & limit
	out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-n=2", "-a")
	expected = []string{fourthID, thirdID}

	assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("SINCE filter, LIMIT & ALL: Container list is not in the correct order: \n%s", out))

	out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-n=2")
	assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("SINCE filter, LIMIT: Container list is not in the correct order: \n%s", out))

	// filter before & limit
	out, _ = dockerCmd(c, "ps", "-f", "before="+fourthID, "-n=1", "-a")
	expected = []string{thirdID}
	assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("BEFORE filter, LIMIT & ALL: Container list is not in the correct order: \n%s", out))

	out, _ = dockerCmd(c, "ps", "-f", "before="+fourthID, "-n=1")
	assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("BEFORE filter, LIMIT: Container list is not in the correct order: \n%s", out))

	// filter since & filter before & limit
	out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-f", "before="+fourthID, "-n=1", "-a")
	expected = []string{thirdID}
	assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("SINCE filter, BEFORE filter, LIMIT & ALL: Container list is not in the correct order: \n%s", out))

	out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-f", "before="+fourthID, "-n=1")
	assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("SINCE filter, BEFORE filter, LIMIT: Container list is not in the correct order: \n%s", out))

}

func assertContainerList(out string, expected []string) bool {
	lines := strings.Split(strings.Trim(out, "\n "), "\n")

	if len(lines)-1 != len(expected) {
		return false
	}

	containerIDIndex := strings.Index(lines[0], "CONTAINER ID")
	for i := 0; i < len(expected); i++ {
		foundID := lines[i+1][containerIDIndex : containerIDIndex+12]
		if foundID != expected[i][:12] {
			return false
		}
	}

	return true
}

func (s *DockerSuite) TestPsListContainersSize(c *testing.T) {
	// Problematic on Windows as it doesn't report the size correctly @swernli
	testRequires(c, DaemonIsLinux)
	dockerCmd(c, "run", "-d", "busybox")

	baseOut, _ := dockerCmd(c, "ps", "-s", "-n=1")
	baseLines := strings.Split(strings.Trim(baseOut, "\n "), "\n")
	baseSizeIndex := strings.Index(baseLines[0], "SIZE")
	baseFoundsize := baseLines[1][baseSizeIndex:]
	baseBytes, err := strconv.Atoi(strings.Split(baseFoundsize, "B")[0])
	assert.NilError(c, err)

	name := "test_size"
	dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo 1 > test")
	id := getIDByName(c, name)

	var result *icmd.Result

	wait := make(chan struct{})
	go func() {
		result = icmd.RunCommand(dockerBinary, "ps", "-s", "-n=1")
		close(wait)
	}()
	select {
	case <-wait:
	case <-time.After(3 * time.Second):
		c.Fatalf("Calling \"docker ps -s\" timed out!")
	}
	result.Assert(c, icmd.Success)
	lines := strings.Split(strings.Trim(result.Combined(), "\n "), "\n")
	assert.Equal(c, len(lines), 2, "Expected 2 lines for 'ps -s -n=1' output, got %d", len(lines))
	sizeIndex := strings.Index(lines[0], "SIZE")
	idIndex := strings.Index(lines[0], "CONTAINER ID")
	foundID := lines[1][idIndex : idIndex+12]
	assert.Equal(c, foundID, id[:12], fmt.Sprintf("Expected id %s, got %s", id[:12], foundID))
	expectedSize := fmt.Sprintf("%dB", 2+baseBytes)
	foundSize := lines[1][sizeIndex:]
	assert.Assert(c, strings.Contains(foundSize, expectedSize), "Expected size %q, got %q", expectedSize, foundSize)
}

func (s *DockerSuite) TestPsListContainersFilterStatus(c *testing.T) {
	existingContainers := ExistingContainerIDs(c)

	// start exited container
	out := cli.DockerCmd(c, "run", "-d", "busybox").Combined()
	firstID := strings.TrimSpace(out)

	// make sure the exited container is not running
	cli.DockerCmd(c, "wait", firstID)

	// start running container
	out = cli.DockerCmd(c, "run", "-itd", "busybox").Combined()
	secondID := strings.TrimSpace(out)

	// filter containers by exited
	out = cli.DockerCmd(c, "ps", "--no-trunc", "-q", "--filter=status=exited").Combined()
	containerOut := strings.TrimSpace(out)
	assert.Equal(c, RemoveOutputForExistingElements(containerOut, existingContainers), firstID)

	out = cli.DockerCmd(c, "ps", "-a", "--no-trunc", "-q", "--filter=status=running").Combined()
	containerOut = strings.TrimSpace(out)
	assert.Equal(c, RemoveOutputForExistingElements(containerOut, existingContainers), secondID)

	result := cli.Docker(cli.Args("ps", "-a", "-q", "--filter=status=rubbish"), cli.WithTimeout(time.Second*60))
	err := "Invalid filter 'status=rubbish'"
	if versions.LessThan(testEnv.DaemonAPIVersion(), "1.32") {
		err = "Unrecognised filter value for status: rubbish"
	}
	result.Assert(c, icmd.Expected{
		ExitCode: 1,
		Err:      err,
	})
	// Windows doesn't support pausing of containers
	if testEnv.OSType != "windows" {
		// pause running container
		out = cli.DockerCmd(c, "run", "-itd", "busybox").Combined()
		pausedID := strings.TrimSpace(out)
		cli.DockerCmd(c, "pause", pausedID)
		// make sure the container is unpaused to let the daemon stop it properly
		defer func() { cli.DockerCmd(c, "unpause", pausedID) }()

		out = cli.DockerCmd(c, "ps", "--no-trunc", "-q", "--filter=status=paused").Combined()
		containerOut = strings.TrimSpace(out)
		assert.Equal(c, RemoveOutputForExistingElements(containerOut, existingContainers), pausedID)
	}
}

func (s *DockerSuite) TestPsListContainersFilterHealth(c *testing.T) {
	existingContainers := ExistingContainerIDs(c)
	// Test legacy no health check
	out := runSleepingContainer(c, "--name=none_legacy")
	containerID := strings.TrimSpace(out)

	cli.WaitRun(c, containerID)

	out = cli.DockerCmd(c, "ps", "-q", "-l", "--no-trunc", "--filter=health=none").Combined()
	containerOut := strings.TrimSpace(out)
	assert.Equal(c, containerOut, containerID, fmt.Sprintf("Expected id %s, got %s for legacy none filter, output: %q", containerID, containerOut, out))

	// Test no health check specified explicitly
	out = runSleepingContainer(c, "--name=none", "--no-healthcheck")
	containerID = strings.TrimSpace(out)

	cli.WaitRun(c, containerID)

	out = cli.DockerCmd(c, "ps", "-q", "-l", "--no-trunc", "--filter=health=none").Combined()
	containerOut = strings.TrimSpace(out)
	assert.Equal(c, containerOut, containerID, fmt.Sprintf("Expected id %s, got %s for none filter, output: %q", containerID, containerOut, out))

	// Test failing health check
	out = runSleepingContainer(c, "--name=failing_container", "--health-cmd=exit 1", "--health-interval=1s")
	containerID = strings.TrimSpace(out)

	waitForHealthStatus(c, "failing_container", "starting", "unhealthy")

	out = cli.DockerCmd(c, "ps", "-q", "--no-trunc", "--filter=health=unhealthy").Combined()
	containerOut = strings.TrimSpace(out)
	assert.Equal(c, containerOut, containerID, fmt.Sprintf("Expected containerID %s, got %s for unhealthy filter, output: %q", containerID, containerOut, out))

	// Check passing healthcheck
	out = runSleepingContainer(c, "--name=passing_container", "--health-cmd=exit 0", "--health-interval=1s")
	containerID = strings.TrimSpace(out)

	waitForHealthStatus(c, "passing_container", "starting", "healthy")

	out = cli.DockerCmd(c, "ps", "-q", "--no-trunc", "--filter=health=healthy").Combined()
	containerOut = strings.TrimSpace(RemoveOutputForExistingElements(out, existingContainers))
	assert.Equal(c, containerOut, containerID, fmt.Sprintf("Expected containerID %s, got %s for healthy filter, output: %q", containerID, containerOut, out))
}

func (s *DockerSuite) TestPsListContainersFilterID(c *testing.T) {
	// start container
	out, _ := dockerCmd(c, "run", "-d", "busybox")
	firstID := strings.TrimSpace(out)

	// start another container
	runSleepingContainer(c)

	// filter containers by id
	out, _ = dockerCmd(c, "ps", "-a", "-q", "--filter=id="+firstID)
	containerOut := strings.TrimSpace(out)
	assert.Equal(c, containerOut, firstID[:12], fmt.Sprintf("Expected id %s, got %s for exited filter, output: %q", firstID[:12], containerOut, out))
}

func (s *DockerSuite) TestPsListContainersFilterName(c *testing.T) {
	// start container
	dockerCmd(c, "run", "--name=a_name_to_match", "busybox")
	id := getIDByName(c, "a_name_to_match")

	// start another container
	runSleepingContainer(c, "--name=b_name_to_match")

	// filter containers by name
	out, _ := dockerCmd(c, "ps", "-a", "-q", "--filter=name=a_name_to_match")
	containerOut := strings.TrimSpace(out)
	assert.Equal(c, containerOut, id[:12], fmt.Sprintf("Expected id %s, got %s for exited filter, output: %q", id[:12], containerOut, out))
}

// Test for the ancestor filter for ps.
// There is also the same test but with image:tag@digest in docker_cli_by_digest_test.go
//
// What the test setups :
// - Create 2 image based on busybox using the same repository but different tags
// - Create an image based on the previous image (images_ps_filter_test2)
// - Run containers for each of those image (busybox, images_ps_filter_test1, images_ps_filter_test2)
// - Filter them out :P
func (s *DockerSuite) TestPsListContainersFilterAncestorImage(c *testing.T) {
	existingContainers := ExistingContainerIDs(c)

	// Build images
	imageName1 := "images_ps_filter_test1"
	buildImageSuccessfully(c, imageName1, build.WithDockerfile(`FROM busybox
		 LABEL match me 1`))
	imageID1 := getIDByName(c, imageName1)

	imageName1Tagged := "images_ps_filter_test1:tag"
	buildImageSuccessfully(c, imageName1Tagged, build.WithDockerfile(`FROM busybox
		 LABEL match me 1 tagged`))
	imageID1Tagged := getIDByName(c, imageName1Tagged)

	imageName2 := "images_ps_filter_test2"
	buildImageSuccessfully(c, imageName2, build.WithDockerfile(fmt.Sprintf(`FROM %s
		 LABEL match me 2`, imageName1)))
	imageID2 := getIDByName(c, imageName2)

	// start containers
	dockerCmd(c, "run", "--name=first", "busybox", "echo", "hello")
	firstID := getIDByName(c, "first")

	// start another container
	dockerCmd(c, "run", "--name=second", "busybox", "echo", "hello")
	secondID := getIDByName(c, "second")

	// start third container
	dockerCmd(c, "run", "--name=third", imageName1, "echo", "hello")
	thirdID := getIDByName(c, "third")

	// start fourth container
	dockerCmd(c, "run", "--name=fourth", imageName1Tagged, "echo", "hello")
	fourthID := getIDByName(c, "fourth")

	// start fifth container
	dockerCmd(c, "run", "--name=fifth", imageName2, "echo", "hello")
	fifthID := getIDByName(c, "fifth")

	var filterTestSuite = []struct {
		filterName  string
		expectedIDs []string
	}{
		// non existent stuff
		{"nonexistent", []string{}},
		{"nonexistent:tag", []string{}},
		// image
		{"busybox", []string{firstID, secondID, thirdID, fourthID, fifthID}},
		{imageName1, []string{thirdID, fifthID}},
		{imageName2, []string{fifthID}},
		// image:tag
		{fmt.Sprintf("%s:latest", imageName1), []string{thirdID, fifthID}},
		{imageName1Tagged, []string{fourthID}},
		// short-id
		{stringid.TruncateID(imageID1), []string{thirdID, fifthID}},
		{stringid.TruncateID(imageID2), []string{fifthID}},
		// full-id
		{imageID1, []string{thirdID, fifthID}},
		{imageID1Tagged, []string{fourthID}},
		{imageID2, []string{fifthID}},
	}

	var out string
	for _, filter := range filterTestSuite {
		out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=ancestor="+filter.filterName)
		checkPsAncestorFilterOutput(c, RemoveOutputForExistingElements(out, existingContainers), filter.filterName, filter.expectedIDs)
	}

	// Multiple ancestor filter
	out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=ancestor="+imageName2, "--filter=ancestor="+imageName1Tagged)
	checkPsAncestorFilterOutput(c, RemoveOutputForExistingElements(out, existingContainers), imageName2+","+imageName1Tagged, []string{fourthID, fifthID})
}

func checkPsAncestorFilterOutput(c *testing.T, out string, filterName string, expectedIDs []string) {
	var actualIDs []string
	if out != "" {
		actualIDs = strings.Split(out[:len(out)-1], "\n")
	}
	sort.Strings(actualIDs)
	sort.Strings(expectedIDs)

	assert.Equal(c, len(actualIDs), len(expectedIDs), fmt.Sprintf("Expected filtered container(s) for %s ancestor filter to be %v:%v, got %v:%v", filterName, len(expectedIDs), expectedIDs, len(actualIDs), actualIDs))
	if len(expectedIDs) > 0 {
		same := true
		for i := range expectedIDs {
			if actualIDs[i] != expectedIDs[i] {
				c.Logf("%s, %s", actualIDs[i], expectedIDs[i])
				same = false
				break
			}
		}
		assert.Equal(c, same, true, fmt.Sprintf("Expected filtered container(s) for %s ancestor filter to be %v, got %v", filterName, expectedIDs, actualIDs))
	}
}

func (s *DockerSuite) TestPsListContainersFilterLabel(c *testing.T) {
	// start container
	dockerCmd(c, "run", "--name=first", "-l", "match=me", "-l", "second=tag", "busybox")
	firstID := getIDByName(c, "first")

	// start another container
	dockerCmd(c, "run", "--name=second", "-l", "match=me too", "busybox")
	secondID := getIDByName(c, "second")

	// start third container
	dockerCmd(c, "run", "--name=third", "-l", "nomatch=me", "busybox")
	thirdID := getIDByName(c, "third")

	// filter containers by exact match
	out, _ := dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=label=match=me")
	containerOut := strings.TrimSpace(out)
	assert.Equal(c, containerOut, firstID, fmt.Sprintf("Expected id %s, got %s for exited filter, output: %q", firstID, containerOut, out))

	// filter containers by two labels
	out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=label=match=me", "--filter=label=second=tag")
	containerOut = strings.TrimSpace(out)
	assert.Equal(c, containerOut, firstID, fmt.Sprintf("Expected id %s, got %s for exited filter, output: %q", firstID, containerOut, out))

	// filter containers by two labels, but expect not found because of AND behavior
	out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=label=match=me", "--filter=label=second=tag-no")
	containerOut = strings.TrimSpace(out)
	assert.Equal(c, containerOut, "", fmt.Sprintf("Expected nothing, got %s for exited filter, output: %q", containerOut, out))

	// filter containers by exact key
	out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=label=match")
	containerOut = strings.TrimSpace(out)
	assert.Assert(c, strings.Contains(containerOut, firstID))
	assert.Assert(c, strings.Contains(containerOut, secondID))
	assert.Assert(c, !strings.Contains(containerOut, thirdID))
}

func (s *DockerSuite) TestPsListContainersFilterExited(c *testing.T) {
	// TODO Flaky on  Windows CI [both RS1 and RS5]
	// On slower machines the container may not have exited
	// yet when we filter below by exit status/exit value.
	skip.If(c, DaemonIsWindows(), "FLAKY on Windows, see #20819")
	runSleepingContainer(c, "--name=sleep")

	firstZero, _ := dockerCmd(c, "run", "-d", "busybox", "true")
	secondZero, _ := dockerCmd(c, "run", "-d", "busybox", "true")

	out, _, err := dockerCmdWithError("run", "--name", "nonzero1", "busybox", "false")
	assert.Assert(c, err != nil, "Should fail. out: %s", out)
	firstNonZero := getIDByName(c, "nonzero1")

	out, _, err = dockerCmdWithError("run", "--name", "nonzero2", "busybox", "false")
	assert.Assert(c, err != nil, "Should fail. out: %s", out)
	secondNonZero := getIDByName(c, "nonzero2")

	// filter containers by exited=0
	out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=exited=0")
	assert.Assert(c, strings.Contains(out, strings.TrimSpace(firstZero)))
	assert.Assert(c, strings.Contains(out, strings.TrimSpace(secondZero)))
	assert.Assert(c, !strings.Contains(out, strings.TrimSpace(firstNonZero)))
	assert.Assert(c, !strings.Contains(out, strings.TrimSpace(secondNonZero)))
	out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=exited=1")
	assert.Assert(c, strings.Contains(out, strings.TrimSpace(firstNonZero)))
	assert.Assert(c, strings.Contains(out, strings.TrimSpace(secondNonZero)))
	assert.Assert(c, !strings.Contains(out, strings.TrimSpace(firstZero)))
	assert.Assert(c, !strings.Contains(out, strings.TrimSpace(secondZero)))
}

func (s *DockerSuite) TestPsRightTagName(c *testing.T) {
	// TODO Investigate further why this fails on Windows to Windows CI
	testRequires(c, DaemonIsLinux)

	existingContainers := ExistingContainerNames(c)

	tag := "asybox:shmatest"
	dockerCmd(c, "tag", "busybox", tag)

	var id1 string
	out := runSleepingContainer(c)
	id1 = strings.TrimSpace(out)

	var id2 string
	out = runSleepingContainerInImage(c, tag)
	id2 = strings.TrimSpace(out)

	var imageID string
	out = inspectField(c, "busybox", "Id")
	imageID = strings.TrimSpace(out)

	var id3 string
	out = runSleepingContainerInImage(c, imageID)
	id3 = strings.TrimSpace(out)

	out, _ = dockerCmd(c, "ps", "--no-trunc")
	lines := strings.Split(strings.TrimSpace(out), "\n")
	lines = RemoveLinesForExistingElements(lines, existingContainers)
	// skip header
	lines = lines[1:]
	assert.Equal(c, len(lines), 3, "There should be 3 running container, got %d", len(lines))
	for _, line := range lines {
		f := strings.Fields(line)
		switch f[0] {
		case id1:
			assert.Equal(c, f[1], "busybox", fmt.Sprintf("Expected %s tag for id %s, got %s", "busybox", id1, f[1]))
		case id2:
			assert.Equal(c, f[1], tag, fmt.Sprintf("Expected %s tag for id %s, got %s", tag, id2, f[1]))
		case id3:
			assert.Equal(c, f[1], imageID, fmt.Sprintf("Expected %s imageID for id %s, got %s", tag, id3, f[1]))
		default:
			c.Fatalf("Unexpected id %s, expected %s and %s and %s", f[0], id1, id2, id3)
		}
	}
}

func (s *DockerSuite) TestPsListContainersFilterCreated(c *testing.T) {
	// create a container
	out, _ := dockerCmd(c, "create", "busybox")
	cID := strings.TrimSpace(out)
	shortCID := cID[:12]

	// Make sure it DOESN'T show up w/o a '-a' for normal 'ps'
	out, _ = dockerCmd(c, "ps", "-q")
	assert.Assert(c, !strings.Contains(out, shortCID), "Should have not seen '%s' in ps output:\n%s", shortCID, out)
	// Make sure it DOES show up as 'Created' for 'ps -a'
	out, _ = dockerCmd(c, "ps", "-a")

	hits := 0
	for _, line := range strings.Split(out, "\n") {
		if !strings.Contains(line, shortCID) {
			continue
		}
		hits++
		assert.Assert(c, strings.Contains(line, "Created"), "Missing 'Created' on '%s'", line)
	}

	assert.Equal(c, hits, 1, fmt.Sprintf("Should have seen '%s' in ps -a output once:%d\n%s", shortCID, hits, out))

	// filter containers by 'create' - note, no -a needed
	out, _ = dockerCmd(c, "ps", "-q", "-f", "status=created")
	containerOut := strings.TrimSpace(out)
	assert.Assert(c, strings.HasPrefix(cID, containerOut))
}

// Test for GitHub issue #12595
func (s *DockerSuite) TestPsImageIDAfterUpdate(c *testing.T) {
	// TODO: Investigate why this fails on Windows to Windows CI further.
	testRequires(c, DaemonIsLinux)
	originalImageName := "busybox:TestPsImageIDAfterUpdate-original"
	updatedImageName := "busybox:TestPsImageIDAfterUpdate-updated"

	existingContainers := ExistingContainerIDs(c)

	icmd.RunCommand(dockerBinary, "tag", "busybox:latest", originalImageName).Assert(c, icmd.Success)

	originalImageID := getIDByName(c, originalImageName)

	result := icmd.RunCommand(dockerBinary, append([]string{"run", "-d", originalImageName}, sleepCommandForDaemonPlatform()...)...)
	result.Assert(c, icmd.Success)
	containerID := strings.TrimSpace(result.Combined())

	result = icmd.RunCommand(dockerBinary, "ps", "--no-trunc")
	result.Assert(c, icmd.Success)

	lines := strings.Split(strings.TrimSpace(result.Combined()), "\n")
	lines = RemoveLinesForExistingElements(lines, existingContainers)
	// skip header
	lines = lines[1:]
	assert.Equal(c, len(lines), 1)

	for _, line := range lines {
		f := strings.Fields(line)
		assert.Equal(c, f[1], originalImageName)
	}

	icmd.RunCommand(dockerBinary, "commit", containerID, updatedImageName).Assert(c, icmd.Success)
	icmd.RunCommand(dockerBinary, "tag", updatedImageName, originalImageName).Assert(c, icmd.Success)

	result = icmd.RunCommand(dockerBinary, "ps", "--no-trunc")
	result.Assert(c, icmd.Success)

	lines = strings.Split(strings.TrimSpace(result.Combined()), "\n")
	lines = RemoveLinesForExistingElements(lines, existingContainers)
	// skip header
	lines = lines[1:]
	assert.Equal(c, len(lines), 1)

	for _, line := range lines {
		f := strings.Fields(line)
		assert.Equal(c, f[1], originalImageID)
	}

}

func (s *DockerSuite) TestPsNotShowPortsOfStoppedContainer(c *testing.T) {
	testRequires(c, DaemonIsLinux)
	dockerCmd(c, "run", "--name=foo", "-d", "-p", "6000:5000", "busybox", "top")
	assert.Assert(c, waitRun("foo") == nil)
	ports, _ := dockerCmd(c, "ps", "--format", "{{ .Ports }}", "--filter", "name=foo")
	expected := ":6000->5000/tcp"
	assert.Assert(c, is.Contains(ports, expected), "Expected: %v, got: %v", expected, ports)

	dockerCmd(c, "kill", "foo")
	dockerCmd(c, "wait", "foo")
	ports, _ = dockerCmd(c, "ps", "--format", "{{ .Ports }}", "--filter", "name=foo")
	assert.Equal(c, ports, "", "Should not got %v", expected)
}

func (s *DockerSuite) TestPsShowMounts(c *testing.T) {
	existingContainers := ExistingContainerNames(c)

	prefix, slash := getPrefixAndSlashFromDaemonPlatform()

	mp := prefix + slash + "test"

	dockerCmd(c, "volume", "create", "ps-volume-test")
	// volume mount containers
	runSleepingContainer(c, "--name=volume-test-1", "--volume", "ps-volume-test:"+mp)
	assert.Assert(c, waitRun("volume-test-1") == nil)
	runSleepingContainer(c, "--name=volume-test-2", "--volume", mp)
	assert.Assert(c, waitRun("volume-test-2") == nil)
	// bind mount container
	var bindMountSource string
	var bindMountDestination string
	if DaemonIsWindows() {
		bindMountSource = "c:\\"
		bindMountDestination = "c:\\t"
	} else {
		bindMountSource = "/tmp"
		bindMountDestination = "/t"
	}
	runSleepingContainer(c, "--name=bind-mount-test", "-v", bindMountSource+":"+bindMountDestination)
	assert.Assert(c, waitRun("bind-mount-test") == nil)

	out, _ := dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}")

	lines := strings.Split(strings.TrimSpace(out), "\n")
	lines = RemoveLinesForExistingElements(lines, existingContainers)
	assert.Equal(c, len(lines), 3)

	fields := strings.Fields(lines[0])
	assert.Equal(c, len(fields), 2)
	assert.Equal(c, fields[0], "bind-mount-test")
	assert.Equal(c, fields[1], bindMountSource)

	fields = strings.Fields(lines[1])
	assert.Equal(c, len(fields), 2)

	anonymousVolumeID := fields[1]

	fields = strings.Fields(lines[2])
	assert.Equal(c, fields[1], "ps-volume-test")

	// filter by volume name
	out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume=ps-volume-test")

	lines = strings.Split(strings.TrimSpace(out), "\n")
	lines = RemoveLinesForExistingElements(lines, existingContainers)
	assert.Equal(c, len(lines), 1)

	fields = strings.Fields(lines[0])
	assert.Equal(c, fields[1], "ps-volume-test")

	// empty results filtering by unknown volume
	out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume=this-volume-should-not-exist")
	assert.Equal(c, len(strings.TrimSpace(out)), 0)

	// filter by mount destination
	out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume="+mp)

	lines = strings.Split(strings.TrimSpace(out), "\n")
	lines = RemoveLinesForExistingElements(lines, existingContainers)
	assert.Equal(c, len(lines), 2)

	fields = strings.Fields(lines[0])
	assert.Equal(c, fields[1], anonymousVolumeID)
	fields = strings.Fields(lines[1])
	assert.Equal(c, fields[1], "ps-volume-test")

	// filter by bind mount source
	out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume="+bindMountSource)

	lines = strings.Split(strings.TrimSpace(out), "\n")
	lines = RemoveLinesForExistingElements(lines, existingContainers)
	assert.Equal(c, len(lines), 1)

	fields = strings.Fields(lines[0])
	assert.Equal(c, len(fields), 2)
	assert.Equal(c, fields[0], "bind-mount-test")
	assert.Equal(c, fields[1], bindMountSource)

	// filter by bind mount destination
	out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume="+bindMountDestination)

	lines = strings.Split(strings.TrimSpace(out), "\n")
	lines = RemoveLinesForExistingElements(lines, existingContainers)
	assert.Equal(c, len(lines), 1)

	fields = strings.Fields(lines[0])
	assert.Equal(c, len(fields), 2)
	assert.Equal(c, fields[0], "bind-mount-test")
	assert.Equal(c, fields[1], bindMountSource)

	// empty results filtering by unknown mount point
	out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume="+prefix+slash+"this-path-was-never-mounted")
	assert.Equal(c, len(strings.TrimSpace(out)), 0)
}

func (s *DockerSuite) TestPsListContainersFilterNetwork(c *testing.T) {
	existing := ExistingContainerIDs(c)

	// TODO default network on Windows is not called "bridge", and creating a
	// custom network fails on Windows fails with "Error response from daemon: plugin not found")
	testRequires(c, DaemonIsLinux)

	// create some containers
	runSleepingContainer(c, "--net=bridge", "--name=onbridgenetwork")
	runSleepingContainer(c, "--net=none", "--name=onnonenetwork")

	// Filter docker ps on non existing network
	out, _ := dockerCmd(c, "ps", "--filter", "network=doesnotexist")
	containerOut := strings.TrimSpace(out)
	lines := strings.Split(containerOut, "\n")

	// skip header
	lines = lines[1:]

	// ps output should have no containers
	assert.Equal(c, len(RemoveLinesForExistingElements(lines, existing)), 0)

	// Filter docker ps on network bridge
	out, _ = dockerCmd(c, "ps", "--filter", "network=bridge")
	containerOut = strings.TrimSpace(out)

	lines = strings.Split(containerOut, "\n")

	// skip header
	lines = lines[1:]

	// ps output should have only one container
	assert.Equal(c, len(RemoveLinesForExistingElements(lines, existing)), 1)

	// Making sure onbridgenetwork is on the output
	assert.Assert(c, strings.Contains(containerOut, "onbridgenetwork"), "Missing the container on network\n")
	// Filter docker ps on networks bridge and none
	out, _ = dockerCmd(c, "ps", "--filter", "network=bridge", "--filter", "network=none")
	containerOut = strings.TrimSpace(out)

	lines = strings.Split(containerOut, "\n")

	// skip header
	lines = lines[1:]

	// ps output should have both the containers
	assert.Equal(c, len(RemoveLinesForExistingElements(lines, existing)), 2)

	// Making sure onbridgenetwork and onnonenetwork is on the output
	assert.Assert(c, strings.Contains(containerOut, "onnonenetwork"), "Missing the container on none network\n")
	assert.Assert(c, strings.Contains(containerOut, "onbridgenetwork"), "Missing the container on bridge network\n")
	nwID, _ := dockerCmd(c, "network", "inspect", "--format", "{{.ID}}", "bridge")

	// Filter by network ID
	out, _ = dockerCmd(c, "ps", "--filter", "network="+nwID)
	containerOut = strings.TrimSpace(out)

	assert.Assert(c, is.Contains(containerOut, "onbridgenetwork"))

	// Filter by partial network ID
	partialnwID := nwID[0:4]

	out, _ = dockerCmd(c, "ps", "--filter", "network="+partialnwID)
	containerOut = strings.TrimSpace(out)

	lines = strings.Split(containerOut, "\n")

	// skip header
	lines = lines[1:]

	// ps output should have only one container
	assert.Equal(c, len(RemoveLinesForExistingElements(lines, existing)), 1)

	// Making sure onbridgenetwork is on the output
	assert.Assert(c, strings.Contains(containerOut, "onbridgenetwork"), "Missing the container on network\n")
}

func (s *DockerSuite) TestPsByOrder(c *testing.T) {
	out := runSleepingContainer(c, "--name", "xyz-abc")
	container1 := strings.TrimSpace(out)

	out = runSleepingContainer(c, "--name", "xyz-123")
	container2 := strings.TrimSpace(out)

	runSleepingContainer(c, "--name", "789-abc")
	runSleepingContainer(c, "--name", "789-123")

	// Run multiple time should have the same result
	out = cli.DockerCmd(c, "ps", "--no-trunc", "-q", "-f", "name=xyz").Combined()
	assert.Equal(c, strings.TrimSpace(out), fmt.Sprintf("%s\n%s", container2, container1))

	// Run multiple time should have the same result
	out = cli.DockerCmd(c, "ps", "--no-trunc", "-q", "-f", "name=xyz").Combined()
	assert.Equal(c, strings.TrimSpace(out), fmt.Sprintf("%s\n%s", container2, container1))
}

func (s *DockerSuite) TestPsListContainersFilterPorts(c *testing.T) {
	testRequires(c, DaemonIsLinux)
	existingContainers := ExistingContainerIDs(c)

	out, _ := dockerCmd(c, "run", "-d", "--publish=80", "busybox", "top")
	id1 := strings.TrimSpace(out)

	out, _ = dockerCmd(c, "run", "-d", "--expose=8080", "busybox", "top")
	id2 := strings.TrimSpace(out)

	out, _ = dockerCmd(c, "run", "-d", "-p", "1090:90", "busybox", "top")
	id3 := strings.TrimSpace(out)

	out, _ = dockerCmd(c, "ps", "--no-trunc", "-q")
	assert.Assert(c, strings.Contains(strings.TrimSpace(out), id1))
	assert.Assert(c, strings.Contains(strings.TrimSpace(out), id2))
	assert.Assert(c, strings.Contains(strings.TrimSpace(out), id3))

	out, _ = dockerCmd(c, "ps", "--no-trunc", "-q", "--filter", "publish=80-8080/udp")
	assert.Assert(c, strings.TrimSpace(out) != id1)
	assert.Assert(c, strings.TrimSpace(out) != id2)
	assert.Assert(c, strings.TrimSpace(out) != id3)

	out, _ = dockerCmd(c, "ps", "--no-trunc", "-q", "--filter", "expose=8081")
	assert.Assert(c, strings.TrimSpace(out) != id1)
	assert.Assert(c, strings.TrimSpace(out) != id2)
	assert.Assert(c, strings.TrimSpace(out) != id3)

	out, _ = dockerCmd(c, "ps", "--no-trunc", "-q", "--filter", "publish=80-81")
	assert.Assert(c, strings.TrimSpace(out) != id1)
	assert.Assert(c, strings.TrimSpace(out) != id2)
	assert.Assert(c, strings.TrimSpace(out) != id3)

	out, _ = dockerCmd(c, "ps", "--no-trunc", "-q", "--filter", "expose=80/tcp")
	assert.Equal(c, strings.TrimSpace(out), id1)
	assert.Assert(c, strings.TrimSpace(out) != id2)
	assert.Assert(c, strings.TrimSpace(out) != id3)

	out, _ = dockerCmd(c, "ps", "--no-trunc", "-q", "--filter", "publish=1090")
	assert.Assert(c, strings.TrimSpace(out) != id1)
	assert.Assert(c, strings.TrimSpace(out) != id2)
	assert.Equal(c, strings.TrimSpace(out), id3)

	out, _ = dockerCmd(c, "ps", "--no-trunc", "-q", "--filter", "expose=8080/tcp")
	out = RemoveOutputForExistingElements(out, existingContainers)
	assert.Assert(c, strings.TrimSpace(out) != id1)
	assert.Equal(c, strings.TrimSpace(out), id2)
	assert.Assert(c, strings.TrimSpace(out) != id3)
}

func (s *DockerSuite) TestPsNotShowLinknamesOfDeletedContainer(c *testing.T) {
	testRequires(c, DaemonIsLinux, MinimumAPIVersion("1.31"))
	existingContainers := ExistingContainerNames(c)

	dockerCmd(c, "create", "--name=aaa", "busybox", "top")
	dockerCmd(c, "create", "--name=bbb", "--link=aaa", "busybox", "top")

	out, _ := dockerCmd(c, "ps", "--no-trunc", "-a", "--format", "{{.Names}}")
	lines := strings.Split(strings.TrimSpace(out), "\n")
	lines = RemoveLinesForExistingElements(lines, existingContainers)
	expected := []string{"bbb", "aaa,bbb/aaa"}
	var names []string
	names = append(names, lines...)
	assert.Assert(c, is.DeepEqual(names, expected), "Expected array with non-truncated names: %v, got: %v", expected, names)

	dockerCmd(c, "rm", "bbb")

	out, _ = dockerCmd(c, "ps", "--no-trunc", "-a", "--format", "{{.Names}}")
	out = RemoveOutputForExistingElements(out, existingContainers)
	assert.Equal(c, strings.TrimSpace(out), "aaa")
}


text:
package jp.co.recruit.mtl.osharetenki.multilinemarquee;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import jp.co.recruit.mtl.osharetenki.multilinemarqueelibrary.MultiLineMarqueeTextView;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final MultiLineMarqueeTextView marqueeText = (MultiLineMarqueeTextView)findViewById(R.id.marquee);
        findViewById(R.id.button_stop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                marqueeText.stopMarquee();
            }
        });
        findViewById(R.id.button_start).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                marqueeText.startMarquee();
            }
        });
        findViewById(R.id.button_four).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                marqueeText.getLayoutParams().height = getResources().getDimensionPixelSize(R.dimen.marquee_area_one_line) * 4;
                marqueeText.requestLayout();
            }
        });
        findViewById(R.id.button_three).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                marqueeText.getLayoutParams().height = getResources().getDimensionPixelSize(R.dimen.marquee_area_one_line) * 3;
                marqueeText.requestLayout();
            }
        });
        findViewById(R.id.button_two).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                marqueeText.getLayoutParams().height = getResources().getDimensionPixelSize(R.dimen.marquee_area_one_line) * 2;
                marqueeText.requestLayout();
            }
        });
        findViewById(R.id.button_one).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                marqueeText.getLayoutParams().height = getResources().getDimensionPixelSize(R.dimen.marquee_area_one_line);
                marqueeText.requestLayout();
            }
        });
        ScrollViewEx scroll = (ScrollViewEx) findViewById(R.id.scroll);
        scroll.setOnScrollViewListener(new ScrollViewEx.ScrollViewListener() {
            @Override
            public void onScrollChanged(View view, int l, int t, int oldl, int oldt) {
                marqueeText.autoMarquee();
            }

            @Override
            public void onScrollStopped(View view) {
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


text:
<!doctype html>

    <meta charset="utf-8">


text:
<?php
/**
 * Created by PhpStorm.
 * User: Utilisateur
 * Date: 07/10/2014
 * Time: 20:10
 */

namespace vpourvalek\BannissementsBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use vpourvalek\UserBundle\Entity\User;

class TableauController extends Controller{

    public function afficherIndexAction()
    {
        if($this->getUser()->getStatut() >= User::MODO_TEST){
            return $this->render('vpourvalekBannissementsBundle:Tableau:tableauIndex.html.twig', array(
            ));
        }
        else{
            return $this->redirect($this->generateUrl('profil', array('id' => $this->getUser()->getId())));
        }
    }

    public function afficherBansHistoAction()
    {
        if($this->getUser()->getStatut() >= User::MODO_TEST){
            $repository = $this->getDoctrine()
                ->getManager()
                ->getRepository('vpourvalekBannissementsBundle:HistoBan');

            $bans = $repository->findAll();
            $userBanni = 'tous';
            $formBuilder = $this->createFormBuilder();
            $formBuilder->add('user','text',array('label' => 'Utilisateur cherché : ','mapped' => false));

            $form = $formBuilder->getForm();
            $request = $this->get('request');

            if ($request->getMethod() == 'POST') {
                $form->bind($request);
                $repository = $this->getDoctrine()
                    ->getManager()
                    ->getRepository('vpourvalekUserBundle:User');
                $userBanni = $form->get('user')->getData();
                $user = $repository->findOneBy(array('username' => $userBanni));

                $repository = $this->getDoctrine()
                    ->getManager()
                    ->getRepository('vpourvalekBannissementsBundle:HistoBan');
                $bans = $repository->findBy(array('userBanni' => $user));
                if(!is_null($user)){
                    return $this->render('vpourvalekBannissementsBundle:Tableau:tableauBans.html.twig', array(
                        'bans' => $bans,
                        'userBanni' => $userBanni,
                        'form' => $form->createView()
                    ));
                }
            }
            return $this->render('vpourvalekBannissementsBundle:Tableau:tableauBans.html.twig', array(
                'bans' => $bans,
                'userBanni' => $userBanni,
                'form' => $form->createView()
            ));
        }
        else{
            return $this->redirect($this->generateUrl('profil', array('id' => $this->getUser()->getId())));
        }
    }

    public function afficherBansAction()
    {
        if($this->getUser()->getStatut() >= User::MODO_TEST){
            $repository = $this->getDoctrine()
                ->getManager()
                ->getRepository('vpourvalekBannissementsBundle:Ban');

            $bans = $repository->findAll();
            $userBanni = 'tous';
            $formBuilder = $this->createFormBuilder();
            $formBuilder->add('user','text',array('label' => 'Utilisateur cherché : ','mapped' => false));

            $form = $formBuilder->getForm();
            $request = $this->get('request');

            if ($request->getMethod() == 'POST') {
                $form->bind($request);
                $repository = $this->getDoctrine()
                    ->getManager()
                    ->getRepository('vpourvalekUserBundle:User');
                $userBanni = $form->get('user')->getData();
                $user = $repository->findOneBy(array('username' => $userBanni));

                $repository = $this->getDoctrine()
                    ->getManager()
                    ->getRepository('vpourvalekBannissementsBundle:Ban');
                $bans = $repository->findBy(array('userBanni' => $user));
                if(!is_null($user)){
                    return $this->render('vpourvalekBannissementsBundle:Tableau:tableauBans.html.twig', array(
                        'bans' => $bans,
                        'userBanni' => $userBanni,
                        'form' => $form->createView()
                    ));
                }
            }
            return $this->render('vpourvalekBannissementsBundle:Tableau:tableauBans.html.twig', array(
                'bans' => $bans,
                'userBanni' => $userBanni,
                'form' => $form->createView()
            ));
        }
        else{
            return $this->redirect($this->generateUrl('profil', array('id' => $this->getUser()->getId())));
        }
    }

    public function afficherLocksAction()
    {
        if($this->getUser()->getStatut() >= User::MODO_TEST){
            $repository = $this->getDoctrine()
                ->getManager()
                ->getRepository('vpourvalekBannissementsBundle:LockHisto');

            $locks = $repository->findAll();
            return $this->render('vpourvalekBannissementsBundle:Tableau:tableauLocks.html.twig', array(
                'locks' => $locks
            ));
        }
        else{
            return $this->redirect($this->generateUrl('profil', array('id' => $this->getUser()->getId())));
        }
    }

    public function afficherDeplacementsAction()
    {
        if($this->getUser()->getStatut() >= User::MODO_TEST){
            $repository = $this->getDoctrine()
                ->getManager()
                ->getRepository('vpourvalekBannissementsBundle:DeplacementHisto');

            $deplacements = $repository->findAll();
            return $this->render('vpourvalekBannissementsBundle:Tableau:tableauDeplacements.html.twig', array(
                'deplacements' => $deplacements
            ));
        }
        else{
            return $this->redirect($this->generateUrl('profil', array('id' => $this->getUser()->getId())));
        }
    }

    public function afficherAvertissementsAction()
    {
        if($this->getUser()->getStatut() >= User::MODO_TEST){
            $repository = $this->getDoctrine()
                ->getManager()
                ->getRepository('vpourvalekBannissementsBundle:Avertissement');

            $avertissements = $repository->findAll();
            $userAverti = 'tous';
            $formBuilder = $this->createFormBuilder();
            $formBuilder->add('user','text',array('label' => 'Utilisateur cherché : ','mapped' => false));

            $form = $formBuilder->getForm();
            $request = $this->get('request');

            if ($request->getMethod() == 'POST') {
                $form->bind($request);
                $repository = $this->getDoctrine()
                    ->getManager()
                    ->getRepository('vpourvalekUserBundle:User');
                $userAverti = $form->get('user')->getData();
                $user = $repository->findOneBy(array('username' => $userAverti));

                $repository = $this->getDoctrine()
                    ->getManager()
                    ->getRepository('vpourvalekBannissementsBundle:Avertissement');
                $avertissements = $repository->findBy(array('userAverti' => $user));
                if(!is_null($user)){
                    return $this->render('vpourvalekBannissementsBundle:Tableau:tableauAvertissements.html.twig', array(
                        'avertissements' => $avertissements,
                        'userAverti' => $userAverti,
                        'form' => $form->createView()
                    ));
                }
            }
            return $this->render('vpourvalekBannissementsBundle:Tableau:tableauAvertissements.html.twig', array(
                'avertissements' => $avertissements,
                'userAverti' => $userAverti,
                'form' => $form->createView()
            ));
        }
        else{
            return $this->redirect($this->generateUrl('profil', array('id' => $this->getUser()->getId())));
        }
    }
}


text:
using System;

namespace Taron.Model
{
    /// <summary>
    /// Represents an enumeration value node
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class EnumValue : ValueNode
    {
        /// <summary>
        /// Gets or sets the value of this node
        /// </summary>
        public string[] Value { get; set; }

        /// <summary>
        /// Gets or sets the concatenated value of this node
        /// </summary>
        public string Full
        {
            get
            {
                return string.Join(".", Value);
            }
            set
            {
                Value = value.Split('.');
            }
        }

        /// <summary>
        /// Initialises a new instance of the EnumValue class
        /// </summary>
        /// <param name="value"></param>
        public EnumValue(string[] value)
        {
            Value = value;
        }

        /// <summary>
        /// Initialises a new instance of the EnumValue class
        /// </summary>
        /// <param name="value"></param>
        public EnumValue(string value)
        {
            Full = value;
        }

        public override string ToString()
        {
            return $"{base.ToString()} ({Full})";
        }
    }
}


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

namespace Most.Client
{
	internal class QueryOptions
	{
		public QueryOptions ()
		{
			//
		}

		public string filter {
			get;
			set;
		}

		public string select {
			get;
			set;
		}

		public string expand {
			get;
			set;
		}

		public string order {
			get;
			set;
		}

		public string group {
			get;
			set;
		}

		public object inlinecount {
			get;
			set;
		}

		public object top {
			get;
			set;
		}

		public object skip {
			get;
			set;
		}

		public object first {
			get;
			set;
		}

		public NameValueCollection ToNameValueCollection() {
			NameValueCollection result = new NameValueCollection();
			foreach (var prop in this.GetType().GetProperties()) {
				if (prop.GetValue (this) != null) {
					result.Add ("$" + prop.Name, ClientDataQueryable.escape(prop.GetValue (this), true));
				}
			}
			return result;
		}

	}
}


text:
<?php
namespace File\Service;

use File\Entity\FileEntity;
use File\Mapper\FileMapperInterface;

class FileService implements FileServiceInterface
{

    /**
     *
     * @var FileMapperInterface
     */
    protected $mapper;

    /**
     *
     * @param FileMapperInterface $mapper
     */
    public function __construct(FileMapperInterface $mapper)
    {
        $this->mapper = $mapper;
    }

    /**
     *
     * {@inheritdoc}
     *
     * @see \File\Service\FileServiceInterface::getAll()
     */
    public function getAll($filter)
    {
        return $this->mapper->getAll($filter);
    }

    /**
     *
     * {@inheritdoc}
     *
     * @see \File\Service\FileServiceInterface::get()
     */
    public function get($id)
    {
        return $this->mapper->get($id);
    }

    /**
     *
     * {@inheritdoc}
     *
     * @see \File\Service\FileServiceInterface::save()
     */
    public function save(FileEntity $entity)
    {
        return $this->mapper->save($entity);
    }

    /**
     *
     * {@inheritdoc}
     *
     * @see \File\Service\FileServiceInterface::delete()
     */
    public function delete(FileEntity $entity)
    {
        return $this->mapper->delete($entity);
    }
}


text:
package com.capitalone.dashboard.rest;

import com.capitalone.dashboard.config.TestConfig;
import com.capitalone.dashboard.config.WebMVCConfig;
import com.capitalone.dashboard.model.Collector;
import com.capitalone.dashboard.model.CollectorItem;
import com.capitalone.dashboard.model.CollectorType;
import com.capitalone.dashboard.service.CollectorService;
import org.bson.types.ObjectId;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import java.util.Arrays;

import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestConfig.class, WebMVCConfig.class})
@WebAppConfiguration
public class CollectorControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext wac;
    @Autowired private CollectorService collectorService;

    @Before
    public void before() {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }

    @Test
    public void collectorItemsByType() throws Exception {
        Collector collector = makeCollector("Hudson", CollectorType.Build);
        CollectorItem item1 = makeCollectorItem(collector, "Build 1", false);
        CollectorItem item2 = makeCollectorItem(collector, "Build 2", true);

        when(collectorService.collectorItemsByType(CollectorType.Build)).thenReturn(Arrays.asList(item1, item2));

        mockMvc.perform(get("/collector/item/type/build"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$", hasSize(2)))
                .andExpect(jsonPath("$[0].id", is(item1.getId().toString())))
                .andExpect(jsonPath("$[0].collectorId", is(item1.getCollectorId().toString())))
                .andExpect(jsonPath("$[0].collector.id", is(collector.getId().toString())))
                .andExpect(jsonPath("$[0].collector.name", is(collector.getName())))
                .andExpect(jsonPath("$[0].description", is(item1.getDescription())))
                .andExpect(jsonPath("$[0].enabled", is(item1.isEnabled())))
                .andExpect(jsonPath("$[1].id", is(item2.getId().toString())))
                .andExpect(jsonPath("$[1].collectorId", is(item2.getCollectorId().toString())))
                .andExpect(jsonPath("$[1].collector.id", is(collector.getId().toString())))
                .andExpect(jsonPath("$[1].collector.name", is(collector.getName())))
                .andExpect(jsonPath("$[1].description", is(item2.getDescription())))
                .andExpect(jsonPath("$[1].enabled", is(item2.isEnabled())));
    }

    @Test
    public void getCollectorItemById() throws Exception {
        Collector collector = makeCollector("Hudson", CollectorType.Build);
        CollectorItem item1 = makeCollectorItem(collector, "Build 1", false);

        when(collectorService.getCollectorItem(item1.getId())).thenReturn(item1);

        mockMvc.perform(get("/collector/item/" + item1.getId().toString()))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.id", is(item1.getId().toString())))
                .andExpect(jsonPath("$.collectorId", is(item1.getCollectorId().toString())))
                .andExpect(jsonPath("$.collector.id", is(collector.getId().toString())))
                .andExpect(jsonPath("$.collector.name", is(collector.getName())))
                .andExpect(jsonPath("$.description", is(item1.getDescription())))
                .andExpect(jsonPath("$.enabled", is(item1.isEnabled())));
    }

    private Collector makeCollector(String name, CollectorType type) {
        Collector collector = new Collector();
        collector.setId(ObjectId.get());
        collector.setName(name);
        collector.setCollectorType(type);
        collector.setEnabled(true);
        collector.setOnline(true);
        collector.setLastExecuted(System.currentTimeMillis());
        return collector;
    }
    private CollectorItem makeCollectorItem(Collector collector, String desc, boolean enabled) {
        CollectorItem item = new CollectorItem();
        item.setId(ObjectId.get());
        item.setCollectorId(collector.getId());
        item.setCollector(collector);
        item.setDescription(desc);
        item.setEnabled(enabled);
        return item;
    }

}


text:
FOUNDATION_EXPORT double KeychainKitVersionNumber;

//! Project version string for KeychainKit.
FOUNDATION_EXPORT const unsigned char KeychainKitVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <KeychainKit/PublicHeader.h>

#import <KeychainKit/SSKeychain.h>
#import <KeychainKit/SSKeychainQuery.h>


text:
package com.endless.android.candybomb;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity implements View.OnTouchListener {
    private static final String TAG = MainActivity.class.getSimpleName();

    private TextView mTextView;
    private CandiesView mCandiesView;
    private String mHighScore;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTextView = (TextView) findViewById(R.id.hello_world_text_view);
        mCandiesView = (CandiesView) findViewById(R.id.candies_view);
        mCandiesView.setOnTouchListener(this);

        //   new FetchHighScoreTask().execute();

    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        mTextView.setText("" + mCandiesView.getLevelScore());
        return false;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    private class FetchHighScoreTask extends AsyncTask<Void, Void, String> {
        @Override
        protected String doInBackground(Void... params) {
            return new HighScoreFetch().FetchHighScore();
        }

        @Override
        protected void onPostExecute(String highScore) {
            mHighScore = highScore;
            mTextView.setText(mHighScore);
        }
    }
}


text:
@interface UIImageAlpha : NSObject
{
}
+ (BOOL)hasAlpha:(UIImage*)image;
+ (UIImage *)imageWithAlpha:(UIImage*)image;
+ (UIImage *)transparentBorderImage:(NSUInteger)borderSize image:(UIImage*)image;
@end


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model common\models\Category */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>

<?//= $form->field($model, 'id')->textInput() ?>

    <?= $form->field($model, 'name')->textInput(['maxlength' => 255]) ?>

<?//= $form->field($model, 'parent_id')->textInput() ?>

    <?= $form->field($model, 'picture')->textInput() ?>
    <?= $form->field($model, 'picture')->fileInput()->label('') ?>

        <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>