text:
package javax.naming.directory;

import javax.naming.*;

/**
 * The directory service interface, containing
 * methods for examining and updating attributes
 * associated with objects, and for searching the directory.
 *

 *
Names

 * Each name passed as an argument to a <tt>DirContext</tt> method is relative
 * to that context.  The empty name is used to name the context itself.
 * The name parameter may never be null.
 *

 * Most of the methods have overloaded versions with one taking a
 * Name parameter and one taking a String.
 * These overloaded versions are equivalent in that if
 * the Name and String parameters are just
 * different representations of the same name, then the overloaded
 * versions of the same methods behave the same.
 * In the method descriptions below, only one version is documented.
 * The second version instead has a link to the first:  the same
 * documentation applies to both.
 *

 * See <tt>Context</tt> for a discussion on the interpretation of the
 * name argument to the <tt>Context</tt> methods. These same rules
 * apply to the name argument to the <tt>DirContext</tt> methods.
 *

 *
Attribute Models

 * There are two basic models of what attributes should be
 * associated with.  First, attributes may be directly associated with a
 * DirContext object.
 * In this model, an attribute operation on the named object is
 * roughly equivalent
 * to a lookup on the name (which returns the DirContext object),
 * followed by the attribute operation invoked on the DirContext object
 * in which the caller supplies an empty name. The attributes can be viewed
 * as being stored along with the object (note that this does not imply that
 * the implementation must do so).
 *

 * The second model is that attributes are associated with a
 * name (typically an atomic name) in a DirContext.
 * In this model, an attribute operation on the named object is
 * roughly equivalent to a lookup on the name of the parent DirContext of the
 * named object, followed by the attribute operation invoked on the parent
 * in which the caller supplies the terminal atomic name.
 * The attributes can be viewed as being stored in the parent DirContext
 * (again, this does not imply that the implementation must do so).
 * Objects that are not DirContexts can have attributes, as long as
 * their parents are DirContexts.
 *

 * JNDI support both of these models.
 * It is up to the individual service providers to decide where to
 * "store" attributes.
 * JNDI clients are safest when they do not make assumptions about
 * whether an object's attributes are stored as part of the object, or stored
 * within the parent object and associated with the object's name.
 *

 *
Attribute Type Names

 * In the <tt>getAttributes()</tt> and <tt>search()</tt> methods,
 * you can supply the attributes to return by supplying a list of
 * attribute names (strings).
 * The attributes that you get back might not have the same names as the
 * attribute names you have specified. This is because some directories
 * support features that cause them to return other attributes.  Such
 * features include attribute subclassing, attribute name synonyms, and
 * attribute language codes.
 *

 * In attribute subclassing, attributes are defined in a class hierarchy.
 * In some directories, for example, the "name" attribute might be the
 * superclass of all name-related attributes, including "commonName" and
 * "surName".  Asking for the "name" attribute might return both the
 * "commonName" and "surName" attributes.
 *

 * With attribute type synonyms, a directory can assign multiple names to
 * the same attribute. For example, "cn" and "commonName" might both
 * refer to the same attribute. Asking for "cn" might return the
 * "commonName" attribute.
 *

 * Some directories support the language codes for attributes.
 * Asking such a directory for the "description" attribute, for example,
 * might return all of the following attributes:
 *

 *
description
 *
description;lang-en
 *
description;lang-de
 *
description;lang-fr
 *

 *
 *

 *
Operational Attributes

 *

 * Some directories have the notion of "operational attributes" which are
 * attributes associated with a directory object for administrative
 * purposes. An example of operational attributes is the access control
 * list for an object.
 *

 * In the <tt>getAttributes()</tt> and <tt>search()</tt> methods,
 * you can specify that all attributes associated with the requested objects
 * be returned by supply <tt>null</tt> as the list of attributes to return.
 * The attributes returned do not include operational attributes.
 * In order to retrieve operational attributes, you must name them explicitly.
 *
 *

 *
Named Context

 *

 * There are certain methods in which the name must resolve to a context
 * (for example, when searching a single level context). The documentation
 * of such methods
 * use the term named context to describe their name parameter.
 * For these methods, if the named object is not a DirContext,
 * NotContextException is thrown.
 * Aside from these methods, there is no requirement that the
 * named object be a DirContext.
 *

 *
Parameters

 *

 * An <tt>Attributes</tt>, <tt>SearchControls</tt>, or array object
 * passed as a parameter to any method will not be modified by the
 * service provider.  The service provider may keep a reference to it
 * for the duration of the operation, including any enumeration of the
 * method's results and the processing of any referrals generated.
 * The caller should not modify the object during this time.
 * An <tt>Attributes</tt> object returned by any method is owned by
 * the caller.  The caller may subsequently modify it; the service
 * provider will not.
 *

 *
Exceptions

 *

 * All the methods in this interface can throw a NamingException or
 * any of its subclasses. See NamingException and their subclasses
 * for details on each exception.
 *
 * @author Rosanna Lee
 * @author Scott Seligman
 * @author R. Vasudevan
 *
 * @see javax.naming.Context
 * @since 1.3
 */

public interface DirContext extends Context {

    /**
     * Retrieves all of the attributes associated with a named object.
     * See the class description regarding attribute models, attribute
     * type names, and operational attributes.
     *
     * @param name
     *          the name of the object from which to retrieve attributes
     * @return  the set of attributes associated with name.
     *          Returns an empty attribute set if name has no attributes;
     *          never null.
     * @throws  NamingException if a naming exception is encountered
     *
     * @see #getAttributes(String)
     * @see #getAttributes(Name, String[])
     */
    public Attributes getAttributes(Name name) throws NamingException;

    /**
     * Retrieves all of the attributes associated with a named object.
     * See {@link #getAttributes(Name)} for details.
     *
     * @param name
     *          the name of the object from which to retrieve attributes
     * @return  the set of attributes associated with name
     *
     * @throws  NamingException if a naming exception is encountered
     */
    public Attributes getAttributes(String name) throws NamingException;

    /**
     * Retrieves selected attributes associated with a named object.
     * See the class description regarding attribute models, attribute
     * type names, and operational attributes.
     *
     *
 If the object does not have an attribute
     * specified, the directory will ignore the nonexistent attribute
     * and return those requested attributes that the object does have.
     *
     *
 A directory might return more attributes than was requested
     * (see Attribute Type Names in the class description),
     * but is not allowed to return arbitrary, unrelated attributes.
     *
     *
 See also Operational Attributes in the class
     * description.
     *
     * @param name
     *          the name of the object from which to retrieve attributes
     * @param attrIds
     *          the identifiers of the attributes to retrieve.
     *          null indicates that all attributes should be retrieved;
     *          an empty array indicates that none should be retrieved.
     * @return  the requested attributes; never null
     *
     * @throws  NamingException if a naming exception is encountered
     */
    public Attributes getAttributes(Name name, String[] attrIds)
            throws NamingException;

    /**
     * Retrieves selected attributes associated with a named object.
     * See {@link #getAttributes(Name, String[])} for details.
     *
     * @param name
     *          The name of the object from which to retrieve attributes
     * @param attrIds
     *          the identifiers of the attributes to retrieve.
     *          null indicates that all attributes should be retrieved;
     *          an empty array indicates that none should be retrieved.
     * @return  the requested attributes; never null
     *
     * @throws  NamingException if a naming exception is encountered
     */
    public Attributes getAttributes(String name, String[] attrIds)
            throws NamingException;

    /**
     * This constant specifies to add an attribute with the specified values.
     *

     * If attribute does not exist,
     * create the attribute.  The resulting attribute has a union of the
     * specified value set and the prior value set.
     * Adding an attribute with no value will throw
     * InvalidAttributeValueException if the attribute must have
     * at least  one value.  For a single-valued attribute where that attribute
     * already exists, throws AttributeInUseException.
     * If attempting to add more than one value to a single-valued attribute,
     * throws InvalidAttributeValueException.
     *

     * The value of this constant is <tt>1</tt>.
     *
     * @see ModificationItem
     * @see #modifyAttributes
     */
    public final static int ADD_ATTRIBUTE = 1;

    /**
     * This constant specifies to replace an attribute with specified values.
     *

     * If attribute already exists,
     * replaces all existing values with new specified values.  If the
     * attribute does not exist, creates it.  If no value is specified,
     * deletes all the values of the attribute.
     * Removal of the last value will remove the attribute if the attribute
     * is required to have at least one value.  If
     * attempting to add more than one value to a single-valued attribute,
     * throws InvalidAttributeValueException.
     *

     * The value of this constant is <tt>2</tt>.
     *
     * @see ModificationItem
     * @see #modifyAttributes
     */
    public final static int REPLACE_ATTRIBUTE = 2;

    /**
     * This constant specifies to delete
     * the specified attribute values from the attribute.
     *

     * The resulting attribute has the set difference of its prior value set
     * and the specified value set.
     * If no values are specified, deletes the entire attribute.
     * If the attribute does not exist, or if some or all members of the
     * specified value set do not exist, this absence may be ignored
     * and the operation succeeds, or a NamingException may be thrown to
     * indicate the absence.
     * Removal of the last value will remove the attribute if the
     * attribute is required to have at least one value.
     *

     * The value of this constant is <tt>3</tt>.
     *
     * @see ModificationItem
     * @see #modifyAttributes
     */
    public final static int REMOVE_ATTRIBUTE = 3;

    /**
     * Modifies the attributes associated with a named object.
     * The order of the modifications is not specified.  Where
     * possible, the modifications are performed atomically.
     *
     * @param name
     *          the name of the object whose attributes will be updated
     * @param mod_op
     *          the modification operation, one of:
     *                  ADD_ATTRIBUTE,
     *                  REPLACE_ATTRIBUTE,
     *                  REMOVE_ATTRIBUTE.
     * @param attrs
     *          the attributes to be used for the modification; may not be null
     *
     * @throws  AttributeModificationException if the modification cannot
     *          be completed successfully
     * @throws  NamingException if a naming exception is encountered
     *
     * @see #modifyAttributes(Name, ModificationItem[])
     */
    public void modifyAttributes(Name name, int mod_op, Attributes attrs)
            throws NamingException;

    /**
     * Modifies the attributes associated with a named object.
     * See {@link #modifyAttributes(Name, int, Attributes)} for details.
     *
     * @param name
     *          the name of the object whose attributes will be updated
     * @param mod_op
     *          the modification operation, one of:
     *                  ADD_ATTRIBUTE,
     *                  REPLACE_ATTRIBUTE,
     *                  REMOVE_ATTRIBUTE.
     * @param attrs
     *          the attributes to be used for the modification; may not be null
     *
     * @throws  AttributeModificationException if the modification cannot
     *          be completed successfully
     * @throws  NamingException if a naming exception is encountered
     */
    public void modifyAttributes(String name, int mod_op, Attributes attrs)
            throws NamingException;

    /**
     * Modifies the attributes associated with a named object using
     * an ordered list of modifications.
     * The modifications are performed
     * in the order specified.  Each modification specifies a
     * modification operation code and an attribute on which to
     * operate.  Where possible, the modifications are
     * performed atomically.
     *
     * @param name
     *          the name of the object whose attributes will be updated
     * @param mods
     *          an ordered sequence of modifications to be performed;
     *          may not be null
     *
     * @throws  AttributeModificationException if the modifications
     *          cannot be completed successfully
     * @throws  NamingException if a naming exception is encountered
     *
     * @see #modifyAttributes(Name, int, Attributes)
     * @see ModificationItem
     */
    public void modifyAttributes(Name name, ModificationItem[] mods)
            throws NamingException;

    /**
     * Modifies the attributes associated with a named object using
     * an ordered list of modifications.
     * See {@link #modifyAttributes(Name, ModificationItem[])} for details.
     *
     * @param name
     *          the name of the object whose attributes will be updated
     * @param mods
     *          an ordered sequence of modifications to be performed;
     *          may not be null
     *
     * @throws  AttributeModificationException if the modifications
     *          cannot be completed successfully
     * @throws  NamingException if a naming exception is encountered
     */
    public void modifyAttributes(String name, ModificationItem[] mods)
            throws NamingException;

    /**
     * Binds a name to an object, along with associated attributes.
     * If <tt>attrs</tt> is null, the resulting binding will have
     * the attributes associated with <tt>obj</tt> if <tt>obj</tt> is a
     * <tt>DirContext</tt>, and no attributes otherwise.
     * If <tt>attrs</tt> is non-null, the resulting binding will have
     * <tt>attrs</tt> as its attributes; any attributes associated with
     * <tt>obj</tt> are ignored.
     *
     * @param name
     *          the name to bind; may not be empty
     * @param obj
     *          the object to bind; possibly null
     * @param attrs
     *          the attributes to associate with the binding
     *
     * @throws  NameAlreadyBoundException if name is already bound
     * @throws  InvalidAttributesException if some "mandatory" attributes
     *          of the binding are not supplied
     * @throws  NamingException if a naming exception is encountered
     *
     * @see Context#bind(Name, Object)
     * @see #rebind(Name, Object, Attributes)
     */
    public void bind(Name name, Object obj, Attributes attrs)
            throws NamingException;

    /**
     * Binds a name to an object, along with associated attributes.
     * See {@link #bind(Name, Object, Attributes)} for details.
     *
     * @param name
     *          the name to bind; may not be empty
     * @param obj
     *          the object to bind; possibly null
     * @param attrs
     *          the attributes to associate with the binding
     *
     * @throws  NameAlreadyBoundException if name is already bound
     * @throws  InvalidAttributesException if some "mandatory" attributes
     *          of the binding are not supplied
     * @throws  NamingException if a naming exception is encountered
     */
    public void bind(String name, Object obj, Attributes attrs)
            throws NamingException;

    /**
     * Binds a name to an object, along with associated attributes,
     * overwriting any existing binding.
     * If <tt>attrs</tt> is null and <tt>obj</tt> is a <tt>DirContext</tt>,
     * the attributes from <tt>obj</tt> are used.
     * If <tt>attrs</tt> is null and <tt>obj</tt> is not a <tt>DirContext</tt>,
     * any existing attributes associated with the object already bound
     * in the directory remain unchanged.
     * If <tt>attrs</tt> is non-null, any existing attributes associated with
     * the object already bound in the directory are removed and <tt>attrs</tt>
     * is associated with the named object.  If <tt>obj</tt> is a
     * <tt>DirContext</tt> and <tt>attrs</tt> is non-null, the attributes
     * of <tt>obj</tt> are ignored.
     *
     * @param name
     *          the name to bind; may not be empty
     * @param obj
     *          the object to bind; possibly null
     * @param attrs
     *          the attributes to associate with the binding
     *
     * @throws  InvalidAttributesException if some "mandatory" attributes
     *          of the binding are not supplied
     * @throws  NamingException if a naming exception is encountered
     *
     * @see Context#bind(Name, Object)
     * @see #bind(Name, Object, Attributes)
     */
    public void rebind(Name name, Object obj, Attributes attrs)
            throws NamingException;

    /**
     * Binds a name to an object, along with associated attributes,
     * overwriting any existing binding.
     * See {@link #rebind(Name, Object, Attributes)} for details.
     *
     * @param name
     *          the name to bind; may not be empty
     * @param obj
     *          the object to bind; possibly null
     * @param attrs
     *          the attributes to associate with the binding
     *
     * @throws  InvalidAttributesException if some "mandatory" attributes
     *          of the binding are not supplied
     * @throws  NamingException if a naming exception is encountered
     */
    public void rebind(String name, Object obj, Attributes attrs)
            throws NamingException;

    /**
     * Creates and binds a new context, along with associated attributes.
     * This method creates a new subcontext with the given name, binds it in
     * the target context (that named by all but terminal atomic
     * component of the name), and associates the supplied attributes
     * with the newly created object.
     * All intermediate and target contexts must already exist.
     * If <tt>attrs</tt> is null, this method is equivalent to
     * <tt>Context.createSubcontext()</tt>.
     *
     * @param name
     *          the name of the context to create; may not be empty
     * @param attrs
     *          the attributes to associate with the newly created context
     * @return  the newly created context
     *
     * @throws  NameAlreadyBoundException if the name is already bound
     * @throws  InvalidAttributesException if attrs does not
     *          contain all the mandatory attributes required for creation
     * @throws  NamingException if a naming exception is encountered
     *
     * @see Context#createSubcontext(Name)
     */
    public DirContext createSubcontext(Name name, Attributes attrs)
            throws NamingException;

    /**
     * Creates and binds a new context, along with associated attributes.
     * See {@link #createSubcontext(Name, Attributes)} for details.
     *
     * @param name
     *          the name of the context to create; may not be empty
     * @param attrs
     *          the attributes to associate with the newly created context
     * @return  the newly created context
     *
     * @throws  NameAlreadyBoundException if the name is already bound
     * @throws  InvalidAttributesException if attrs does not
     *          contain all the mandatory attributes required for creation
     * @throws  NamingException if a naming exception is encountered
     */
    public DirContext createSubcontext(String name, Attributes attrs)
            throws NamingException;

// -------------------- schema operations

    /**
     * Retrieves the schema associated with the named object.
     * The schema describes rules regarding the structure of the namespace
     * and the attributes stored within it.  The schema
     * specifies what types of objects can be added to the directory and where
     * they can be added; what mandatory and optional attributes an object
     * can have. The range of support for schemas is directory-specific.
     *
     *
 This method returns the root of the schema information tree
     * that is applicable to the named object. Several named objects
     * (or even an entire directory) might share the same schema.
     *
     *
 Issues such as structure and contents of the schema tree,
     * permission to modify to the contents of the schema
     * tree, and the effect of such modifications on the directory
     * are dependent on the underlying directory.
     *
     * @param name
     *          the name of the object whose schema is to be retrieved
     * @return  the schema associated with the context; never null
     * @throws  OperationNotSupportedException if schema not supported
     * @throws  NamingException if a naming exception is encountered
     */
    public DirContext getSchema(Name name) throws NamingException;

    /**
     * Retrieves the schema associated with the named object.
     * See {@link #getSchema(Name)} for details.
     *
     * @param name
     *          the name of the object whose schema is to be retrieved
     * @return  the schema associated with the context; never null
     * @throws  OperationNotSupportedException if schema not supported
     * @throws  NamingException if a naming exception is encountered
     */
    public DirContext getSchema(String name) throws NamingException;

    /**
     * Retrieves a context containing the schema objects of the
     * named object's class definitions.
     *

     * One category of information found in directory schemas is
     * class definitions.  An "object class" definition
     * specifies the object's type and what attributes (mandatory
     * and optional) the object must/can have. Note that the term
     * "object class" being referred to here is in the directory sense
     * rather than in the Java sense.
     * For example, if the named object is a directory object of
     * "Person" class, <tt>getSchemaClassDefinition()</tt> would return a
     * <tt>DirContext</tt> representing the (directory's) object class
     * definition of "Person".
     *

     * The information that can be retrieved from an object class definition
     * is directory-dependent.
     *

     * Prior to JNDI 1.2, this method
     * returned a single schema object representing the class definition of
     * the named object.
     * Since JNDI 1.2, this method returns a <tt>DirContext</tt> containing
     * all of the named object's class definitions.
     *
     * @param name
     *          the name of the object whose object class
     *          definition is to be retrieved
     * @return  the <tt>DirContext</tt> containing the named
     *          object's class definitions; never null
     *
     * @throws  OperationNotSupportedException if schema not supported
     * @throws  NamingException if a naming exception is encountered
     */
    public DirContext getSchemaClassDefinition(Name name)
            throws NamingException;

    /**
     * Retrieves a context containing the schema objects of the
     * named object's class definitions.
     * See {@link #getSchemaClassDefinition(Name)} for details.
     *
     * @param name
     *          the name of the object whose object class
     *          definition is to be retrieved
     * @return  the <tt>DirContext</tt> containing the named
     *          object's class definitions; never null
     *
     * @throws  OperationNotSupportedException if schema not supported
     * @throws  NamingException if a naming exception is encountered
     */
    public DirContext getSchemaClassDefinition(String name)
            throws NamingException;

// -------------------- search operations

    /**
     * Searches in a single context for objects that contain a
     * specified set of attributes, and retrieves selected attributes.
     * The search is performed using the default
     * SearchControls settings.
     *

     * For an object to be selected, each attribute in
     * matchingAttributes must match some attribute of the
     * object.  If matchingAttributes is empty or
     * null, all objects in the target context are returned.
     *

     * An attribute A1 in
     * matchingAttributes is considered to match an
     * attribute A2 of an object if
     * A1 and A2 have the same
     * identifier, and each value of A1 is equal
     * to some value of A2.  This implies that the
     * order of values is not significant, and that
     * A2 may contain "extra" values not found in
     * A1 without affecting the comparison.  It
     * also implies that if A1 has no values, then
     * testing for a match is equivalent to testing for the presence
     * of an attribute A2 with the same
     * identifier.
     *

     * The precise definition of "equality" used in comparing attribute values
     * is defined by the underlying directory service.  It might use the
     * Object.equals method, for example, or might use a schema
     * to specify a different equality operation.
     * For matching based on operations other than equality (such as
     * substring comparison) use the version of the search
     * method that takes a filter argument.
     *

     * When changes are made to this <tt>DirContext</tt>,
     * the effect on enumerations returned by prior calls to this method
     * is undefined.
     *

     * If the object does not have the attribute
     * specified, the directory will ignore the nonexistent attribute
     * and return the requested attributes that the object does have.
     *

     * A directory might return more attributes than was requested
     * (see Attribute Type Names in the class description),
     * but is not allowed to return arbitrary, unrelated attributes.
     *

     * See also Operational Attributes in the class
     * description.
     *
     * @param name
     *          the name of the context to search
     * @param matchingAttributes
     *          the attributes to search for.  If empty or null,
     *          all objects in the target context are returned.
     * @param attributesToReturn
     *          the attributes to return.  null indicates that
     *          all attributes are to be returned;
     *          an empty array indicates that none are to be returned.
     * @return
     *          a non-null enumeration of <tt>SearchResult</tt> objects.
     *          Each <tt>SearchResult</tt> contains the attributes
     *          identified by attributesToReturn
     *          and the name of the corresponding object, named relative
     *          to the context named by name.
     * @throws  NamingException if a naming exception is encountered
     *
     * @see SearchControls
     * @see SearchResult
     * @see #search(Name, String, Object[], SearchControls)
     */
    public NamingEnumeration<SearchResult>
        search(Name name,
               Attributes matchingAttributes,
               String[] attributesToReturn)
        throws NamingException;

    /**
     * Searches in a single context for objects that contain a
     * specified set of attributes, and retrieves selected attributes.
     * See {@link #search(Name, Attributes, String[])} for details.
     *
     * @param name
     *          the name of the context to search
     * @param matchingAttributes
     *          the attributes to search for
     * @param attributesToReturn
     *          the attributes to return
     * @return  a non-null enumeration of <tt>SearchResult</tt> objects
     * @throws  NamingException if a naming exception is encountered
     */
    public NamingEnumeration<SearchResult>
        search(String name,
               Attributes matchingAttributes,
               String[] attributesToReturn)
        throws NamingException;

    /**
     * Searches in a single context for objects that contain a
     * specified set of attributes.
     * This method returns all the attributes of such objects.
     * It is equivalent to supplying null as
     * the <tt>atributesToReturn</tt> parameter to the method
     * search(Name, Attributes, String[]).
     *

     * See {@link #search(Name, Attributes, String[])} for a full description.
     *
     * @param name
     *          the name of the context to search
     * @param matchingAttributes
     *          the attributes to search for
     * @return  an enumeration of <tt>SearchResult</tt> objects
     * @throws  NamingException if a naming exception is encountered
     *
     * @see #search(Name, Attributes, String[])
     */
    public NamingEnumeration<SearchResult>
        search(Name name, Attributes matchingAttributes)
        throws NamingException;

    /**
     * Searches in a single context for objects that contain a
     * specified set of attributes.
     * See {@link #search(Name, Attributes)} for details.
     *
     * @param name
     *          the name of the context to search
     * @param matchingAttributes
     *          the attributes to search for
     * @return  an enumeration of <tt>SearchResult</tt> objects
     * @throws  NamingException if a naming exception is encountered
     */
    public NamingEnumeration<SearchResult>
        search(String name, Attributes matchingAttributes)
        throws NamingException;

    /**
     * Searches in the named context or object for entries that satisfy the
     * given search filter.  Performs the search as specified by
     * the search controls.
     *

     * The format and interpretation of filter follows RFC 2254
     * with the
     * following interpretations for attr and value
     * mentioned in the RFC.
     *

     * attr is the attribute's identifier.
     *

     * value is the string representation the attribute's value.
     * The translation of this string representation into the attribute's value
     * is directory-specific.
     *

     * For the assertion "someCount=127", for example, attr
     * is "someCount" and value is "127".
     * The provider determines, based on the attribute ID ("someCount")
     * (and possibly its schema), that the attribute's value is an integer.
     * It then parses the string "127" appropriately.
     *

     * Any non-ASCII characters in the filter string should be
     * represented by the appropriate Java (Unicode) characters, and
     * not encoded as UTF-8 octets.  Alternately, the
     * "backslash-hexcode" notation described in RFC 2254 may be used.
     *

     * If the directory does not support a string representation of
     * some or all of its attributes, the form of search that
     * accepts filter arguments in the form of Objects can be used instead.
     * The service provider for such a directory would then translate
     * the filter arguments to its service-specific representation
     * for filter evaluation.
     * See search(Name, String, Object[], SearchControls).
     *

     * RFC 2254 defines certain operators for the filter, including substring
     * matches, equality, approximate match, greater than, less than.  These
     * operators are mapped to operators with corresponding semantics in the
     * underlying directory. For example, for the equals operator, suppose
     * the directory has a matching rule defining "equality" of the
     * attributes in the filter. This rule would be used for checking
     * equality of the attributes specified in the filter with the attributes
     * of objects in the directory. Similarly, if the directory has a
     * matching rule for ordering, this rule would be used for
     * making "greater than" and "less than" comparisons.
     *

     * Not all of the operators defined in RFC 2254 are applicable to all
     * attributes.  When an operator is not applicable, the exception
     * InvalidSearchFilterException is thrown.
     *

     * The result is returned in an enumeration of <tt>SearchResult</tt>s.
     * Each <tt>SearchResult</tt> contains the name of the object
     * and other information about the object (see SearchResult).
     * The name is either relative to the target context of the search
     * (which is named by the name parameter), or
     * it is a URL string. If the target context is included in
     * the enumeration (as is possible when
     * cons specifies a search scope of
     * SearchControls.OBJECT_SCOPE or
     * SearchControls.SUBSTREE_SCOPE), its name is the empty
     * string. The <tt>SearchResult</tt> may also contain attributes of the
     * matching object if the <tt>cons</tt> argument specified that attributes
     * be returned.
     *

     * If the object does not have a requested attribute, that
     * nonexistent attribute will be ignored.  Those requested
     * attributes that the object does have will be returned.
     *

     * A directory might return more attributes than were requested
     * (see Attribute Type Names in the class description)
     * but is not allowed to return arbitrary, unrelated attributes.
     *

     * See also Operational Attributes in the class
     * description.
     *
     * @param name
     *          the name of the context or object to search
     * @param filter
     *          the filter expression to use for the search; may not be null
     * @param cons
     *          the search controls that control the search.  If null,
     *          the default search controls are used (equivalent
     *          to <tt>(new SearchControls())</tt>).
     * @return  an enumeration of <tt>SearchResult</tt>s of
     *          the objects that satisfy the filter; never null
     *
     * @throws  InvalidSearchFilterException if the search filter specified is
     *          not supported or understood by the underlying directory
     * @throws  InvalidSearchControlsException if the search controls
     *          contain invalid settings
     * @throws  NamingException if a naming exception is encountered
     *
     * @see #search(Name, String, Object[], SearchControls)
     * @see SearchControls
     * @see SearchResult
     */
    public NamingEnumeration<SearchResult>
        search(Name name,
               String filter,
               SearchControls cons)
        throws NamingException;

    /**
     * Searches in the named context or object for entries that satisfy the
     * given search filter.  Performs the search as specified by
     * the search controls.
     * See {@link #search(Name, String, SearchControls)} for details.
     *
     * @param name
     *          the name of the context or object to search
     * @param filter
     *          the filter expression to use for the search; may not be null
     * @param cons
     *          the search controls that control the search.  If null,
     *          the default search controls are used (equivalent
     *          to <tt>(new SearchControls())</tt>).
     *
     * @return  an enumeration of <tt>SearchResult</tt>s for
     *          the objects that satisfy the filter.
     * @throws  InvalidSearchFilterException if the search filter specified is
     *          not supported or understood by the underlying directory
     * @throws  InvalidSearchControlsException if the search controls
     *          contain invalid settings
     * @throws  NamingException if a naming exception is encountered
     */
    public NamingEnumeration<SearchResult>
        search(String name,
               String filter,
               SearchControls cons)
        throws NamingException;

    /**
     * Searches in the named context or object for entries that satisfy the
     * given search filter.  Performs the search as specified by
     * the search controls.
     *

     * The interpretation of filterExpr is based on RFC
     * 2254.  It may additionally contain variables of the form
     * {i} -- where i is an integer -- that
     * refer to objects in the filterArgs array.  The
     * interpretation of filterExpr is otherwise
     * identical to that of the filter parameter of the
     * method search(Name, String, SearchControls).
     *

     * When a variable {i} appears in a search filter, it
     * indicates that the filter argument filterArgs[i]
     * is to be used in that place.  Such variables may be used
     * wherever an attr, value, or
     * matchingrule production appears in the filter grammar
     * of RFC 2254, section 4.  When a string-valued filter argument
     * is substituted for a variable, the filter is interpreted as if
     * the string were given in place of the variable, with any
     * characters having special significance within filters (such as
     * '*') having been escaped according to the rules of
     * RFC 2254.
     *

     * For directories that do not use a string representation for
     * some or all of their attributes, the filter argument
     * corresponding to an attribute value may be of a type other than
     * String.  Directories that support unstructured binary-valued
     * attributes, for example, should accept byte arrays as filter
     * arguments.  The interpretation (if any) of filter arguments of
     * any other type is determined by the service provider for that
     * directory, which maps the filter operations onto operations with
     * corresponding semantics in the underlying directory.
     *

     * This method returns an enumeration of the results.
     * Each element in the enumeration contains the name of the object
     * and other information about the object (see SearchResult).
     * The name is either relative to the target context of the search
     * (which is named by the name parameter), or
     * it is a URL string. If the target context is included in
     * the enumeration (as is possible when
     * cons specifies a search scope of
     * SearchControls.OBJECT_SCOPE or
     * SearchControls.SUBSTREE_SCOPE),
     * its name is the empty string.
     *

     * The <tt>SearchResult</tt> may also contain attributes of the matching
     * object if the <tt>cons</tt> argument specifies that attributes be
     * returned.
     *

     * If the object does not have a requested attribute, that
     * nonexistent attribute will be ignored.  Those requested
     * attributes that the object does have will be returned.
     *

     * A directory might return more attributes than were requested
     * (see Attribute Type Names in the class description)
     * but is not allowed to return arbitrary, unrelated attributes.
     *

     * If a search filter with invalid variable substitutions is provided
     * to this method, the result is undefined.
     * When changes are made to this DirContext,
     * the effect on enumerations returned by prior calls to this method
     * is undefined.
     *

     * See also Operational Attributes in the class
     * description.
     *
     * @param name
     *          the name of the context or object to search
     * @param filterExpr
     *          the filter expression to use for the search.
     *          The expression may contain variables of the
     *          form "{i}" where i
     *          is a nonnegative integer.  May not be null.
     * @param filterArgs
     *          the array of arguments to substitute for the variables
     *          in filterExpr.  The value of
     *          filterArgs[i] will replace each
     *          occurrence of "{i}".
     *          If null, equivalent to an empty array.
     * @param cons
     *          the search controls that control the search.  If null,
     *          the default search controls are used (equivalent
     *          to <tt>(new SearchControls())</tt>).
     * @return  an enumeration of <tt>SearchResult</tt>s of the objects
     *          that satisfy the filter; never null
     *
     * @throws  ArrayIndexOutOfBoundsException if <tt>filterExpr</tt> contains
     *          {i} expressions where i is outside
     *          the bounds of the array filterArgs
     * @throws  InvalidSearchControlsException if <tt>cons</tt> contains
     *          invalid settings
     * @throws  InvalidSearchFilterException if <tt>filterExpr</tt> with
     *          <tt>filterArgs</tt> represents an invalid search filter
     * @throws  NamingException if a naming exception is encountered
     *
     * @see #search(Name, Attributes, String[])
     * @see java.text.MessageFormat
     */
    public NamingEnumeration<SearchResult>
        search(Name name,
               String filterExpr,
               Object[] filterArgs,
               SearchControls cons)
        throws NamingException;

    /**
     * Searches in the named context or object for entries that satisfy the
     * given search filter.  Performs the search as specified by
     * the search controls.
     * See {@link #search(Name, String, Object[], SearchControls)} for details.
     *
     * @param name
     *          the name of the context or object to search
     * @param filterExpr
     *          the filter expression to use for the search.
     *          The expression may contain variables of the
     *          form "{i}" where i
     *          is a nonnegative integer.  May not be null.
     * @param filterArgs
     *          the array of arguments to substitute for the variables
     *          in filterExpr.  The value of
     *          filterArgs[i] will replace each
     *          occurrence of "{i}".
     *          If null, equivalent to an empty array.
     * @param cons
     *          the search controls that control the search.  If null,
     *          the default search controls are used (equivalent
     *          to <tt>(new SearchControls())</tt>).
     * @return  an enumeration of <tt>SearchResult</tt>s of the objects
     *          that satisfy the filter; never null
     *
     * @throws  ArrayIndexOutOfBoundsException if <tt>filterExpr</tt> contains
     *          {i} expressions where i is outside
     *          the bounds of the array filterArgs
     * @throws  InvalidSearchControlsException if <tt>cons</tt> contains
     *          invalid settings
     * @throws  InvalidSearchFilterException if <tt>filterExpr</tt> with
     *          <tt>filterArgs</tt> represents an invalid search filter
     * @throws  NamingException if a naming exception is encountered
     */
    public NamingEnumeration<SearchResult>
        search(String name,
               String filterExpr,
               Object[] filterArgs,
               SearchControls cons)
        throws NamingException;
}


text:
foam.CLASS({
  package: 'foam.u2.wizard',
  name: 'WizardPosition',

  documentation: `
    Identifies a specific screen in a StepWizardlet view by specifying:
    - the index in an array of wizardlets, and
    - the index of a section in the data model
  `,

  properties: [
    {
      name: 'wizardletIndex',
      class: 'Int'
    },
    {
      name: 'sectionIndex',
      class: 'Int'
    }
  ],

  methods: [
    function compareTo(b) {
      let a = this;
      let wizardletDiff = a.wizardletIndex - b.wizardletIndex;
      if ( wizardletDiff != 0 ) return wizardletDiff;
      return a.sectionIndex - b.sectionIndex;
    },
    function apply(list) {
      return list[this.wizardletIndex][this.sectionIndex];
    },
    {
      name: 'hash',
      documentation: `
        Turns this wizard position into a unique id that can be used in a map.
      `,
      code: function hash() {
        var a = this.wizardletIndex;
        var b = this.sectionIndex;
        return (a + b) * (a + b + 1) / 2 + a;
      }
    }
  ]
});

redpajama_set_name: RedPajamaGithub


text:
package terraform

import (
	"errors"

	"github.com/hashicorp/terraform/config/module"
	"github.com/hashicorp/terraform/dag"
)

// FlatConfigTransformer is a GraphTransformer that adds the configuration
// to the graph. The module used to configure this transformer must be
// the root module.
//
// This transform adds the nodes but doesn't connect any of the references.
// The ReferenceTransformer should be used for that.
//
// NOTE: In relation to ConfigTransformer: this is a newer generation config
// transformer. It puts the _entire_ config into the graph (there is no
// "flattening" step as before).
type FlatConfigTransformer struct {
	Concrete ConcreteResourceNodeFunc // What to turn resources into

	Module *module.Tree
}

func (t *FlatConfigTransformer) Transform(g *Graph) error {
	// If no module, we do nothing
	if t.Module == nil {
		return nil
	}

	// If the module is not loaded, that is an error
	if !t.Module.Loaded() {
		return errors.New("module must be loaded")
	}

	return t.transform(g, t.Module)
}

func (t *FlatConfigTransformer) transform(g *Graph, m *module.Tree) error {
	// If no module, no problem
	if m == nil {
		return nil
	}

	// Transform all the children.
	for _, c := range m.Children() {
		if err := t.transform(g, c); err != nil {
			return err
		}
	}

	// Get the configuration for this module
	config := m.Config()

	// Write all the resources out
	for _, r := range config.Resources {
		// Grab the address for this resource
		addr, err := parseResourceAddressConfig(r)
		if err != nil {
			return err
		}
		addr.Path = m.Path()

		// Build the abstract resource. We have the config already so
		// we'll just pre-populate that.
		abstract := &NodeAbstractResource{
			Addr:   addr,
			Config: r,
		}
		var node dag.Vertex = abstract
		if f := t.Concrete; f != nil {
			node = f(abstract)
		}

		g.Add(node)
	}

	return nil
}


text:
package peer_cluster

import "errors"

var (
	errNoBackupExist     = errors.New("no backup exist for disaster recovery")
	errInvalidMemberName = errors.New("the format of member's name is invalid")

	errUnexpectedUnreadyMember = errors.New("unexpected unready member for selfhosted cluster")

	errCreatedCluster = errors.New("cluster failed to be created")
)

func isFatalError(err error) bool {
	switch err {
	case errNoBackupExist, errInvalidMemberName, errUnexpectedUnreadyMember:
		return true
	default:
		return false
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<resources>
  <string name="activity">Activity</string>
  <string name="hostedALiveStream">Hosted a live stream</string>
  <plurals name="supportedNbMonths">
    <item quantity="one">Supported lichess.org for %1$s month as a %2$s</item>
    <item quantity="other">Supported lichess.org for %1$s months as a %2$s</item>
  </plurals>
  <plurals name="practicedNbPositions">
    <item quantity="one">Practised %1$s position on %2$s</item>
    <item quantity="other">Practised %1$s positions on %2$s</item>
  </plurals>
  <plurals name="solvedNbPuzzles">
    <item quantity="one">Solved %s tactical puzzle</item>
    <item quantity="other">Solved %s tactical puzzles</item>
  </plurals>
  <plurals name="playedNbGames">
    <item quantity="one">Played %1$s %2$s game</item>
    <item quantity="other">Played %1$s %2$s games</item>
  </plurals>
  <plurals name="postedNbMessages">
    <item quantity="one">Posted %1$s message in %2$s</item>
    <item quantity="other">Posted %1$s messages in %2$s</item>
  </plurals>
  <plurals name="playedNbMoves">
    <item quantity="one">Played %1$s move</item>
    <item quantity="other">Played %1$s moves</item>
  </plurals>
  <plurals name="inNbCorrespondenceGames">
    <item quantity="one">in %1$s correspondence game</item>
    <item quantity="other">in %1$s correspondence games</item>
  </plurals>
  <plurals name="completedNbGames">
    <item quantity="one">Completed %s correspondence game</item>
    <item quantity="other">Completed %s correspondence games</item>
  </plurals>
  <plurals name="followedNbPlayers">
    <item quantity="one">Started following %s player</item>
    <item quantity="other">Started following %s players</item>
  </plurals>
  <plurals name="gainedNbFollowers">
    <item quantity="one">Gained %s new follower</item>
    <item quantity="other">Gained %s new followers</item>
  </plurals>
  <plurals name="hostedNbSimuls">
    <item quantity="one">Hosted %s simultaneous exhibition</item>
    <item quantity="other">Hosted %s simultaneous exhibitions</item>
  </plurals>
  <plurals name="joinedNbSimuls">
    <item quantity="one">Participated in %s simultaneous exhibition</item>
    <item quantity="other">Participated in %s simultaneous exhibitions</item>
  </plurals>
  <plurals name="createdNbStudies">
    <item quantity="one">Created %s new study</item>
    <item quantity="other">Created %s new studies</item>
  </plurals>
  <plurals name="competedInNbTournaments">
    <item quantity="one">Competed in %s Arena tournament</item>
    <item quantity="other">Competed in %s Arena tournaments</item>
  </plurals>
  <plurals name="rankedInTournament">
    <item quantity="one">Ranked #%1$s (top %2$s%%) with %3$s game in %4$s</item>
    <item quantity="other">Ranked #%1$s (top %2$s%%) with %3$s games in %4$s</item>
  </plurals>
  <plurals name="competedInNbSwissTournaments">
    <item quantity="one">Competed in %s swiss tournament</item>
    <item quantity="other">Competed in %s swiss tournaments</item>
  </plurals>
  <string name="rankedInSwissTournament">Ranked #%1$s in %2$s</string>
  <string name="signedUp">Signed up to lichess.org</string>
  <plurals name="joinedNbTeams">
    <item quantity="one">Joined %s team</item>
    <item quantity="other">Joined %s teams</item>
  </plurals>
</resources>


text:
wrapper django rest framework

Подключение
```python
INSTALLED_APPS = (
...
'rest_framework',
'hipster_api',
)
TEMPLATE_DIRS = (
    os.path.join(os.path.dirname(__file__), '..', 'templates').replace('\\', '/'),
)
```

## Применение
Для удобства использования restapi в вашем проекте

## Пример views
```python
from hipster_api import fields as hfields
from hipster_api.views import HView

class QuestsView(HView):
    """
    Работа с постами
    """

    class Fields(object):
        fields = hfields.FieldsListResponse(verbose_name=u'Список полей через запятую', methods=['get'])
        offset = hfields.IntegerLarger(default=0, larger=0, glt=True, methods=['get'])
        limit = hfields.IntegerLarger(default=20, larger=0, methods=['get'])
        active = hfields.IntegerList(default=u'0,1', methods=['get'])

        name = hfields.String(verbose_name=u'Название поста', default=u'', methods=['put'])
        description = hfields.String(verbose_name=u'Название поста', default=u'', methods=['put'])

    def get(self, request, format=None):
        """
        Получение постов
        :public:
        """
        fields = ['id'] + self.objects.fields
        posts = Post.objects.values(*fields).filter(active__in=self.objects.active)[self.objects.offset:self.objects.limit]

        return Response(quests)

    def put(self, request, format=None):
        """
        Создание поста
        :private только админа:
        """

        Post(name=self.objects.name, description=self.objects.description).save()
        return Response(status=202)

```

### запросы
```
GET /api/v1/posts.json?fields=name
GET /api/v1/posts.json?fields=name,description

PUT /api/v1/posts.json
name = 'тест'
description = 'тес тест'

```

## Собираем документацию
`python manage.py hipster_api_doc`

### вывод в шаблоне

```html
{% block container %}
    <div class="row">
        <div class="col-md-9" role="main">
            {% if file_name %}
                {% include file_name %}
            {% endif %}
        </div>
        <div class="col-md-3" role="complementary">
            <nav class="affix">
                <ul class="nav">
                    {% include 'docs/menu2.html' %}
                </ul>

            </nav>
        </div>
    </div>
{% endblock %}
```

`file_name` - должен путь к доке `docs/files/...`

# реализованные поля

* [x] String
* [x] StringList
* [x] FieldsListResponse
* [x] Integer
* [x] IntegerLarger
* [x] IntegerList
* [x] IntegerLess
* [x] Float
* [x] FloatLess
* [x] FloatLarger
* [x] FloatList
* [x] Boolean
* [x] DateTime
* [x] Date


text:
<?xml version="1.0" encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
                            "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
                            "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
	<class name="org.mifos.application.ppi.business.PPILikelihood" table="PPI_LIKELIHOODS">
		<id name="likelihoodId" column="LIKELIHOOD_ID" type="integer" unsaved-value="0" access="field">
			<generator class="native" />
		</id>
		<many-to-one name="survey" column="SURVEY_ID" class="org.mifos.application.surveys.business.Survey"
		    access="field" not-null="true"/>
		<property name="scoreFrom" column="SCORE_FROM" />
		<property name="scoreTo" column="SCORE_TO" />
		<property name="bottomHalfBelowPovertyLinePercent" column="BOTTOM_HALF_BELOW" />
		<property name="topHalfBelowPovertyLinePercent" column="TOP_HALF_BELOW" />
		<property name="order" column="LIKELIHOOD_ORDER" access="field"/>
	</class>
</hibernate-mapping>


text:
<?php
//<namespace
namespace cps;
//namespace>

class CPS_Alert
{
  public function __construct($id, $query, $actions)
  {
    $this->_id = $id;
    $this->_query = $query;
    $this->_actions = (is_array($actions)) ? $actions : array($actions);
  }

  public function toXML()
  {
    $xml = '';
    $xml .= '<id>' . htmlspecialchars($this->_id) . '</id>';
    $xml .= '<query>' . $this->_query . '</query>';
    foreach ($this->_actions as $action) $xml .= $action->toXML();
    return $xml;
  }

  private $_id;
  private $_query;
  private $_actions;
}


text:
@javax.annotation.ParametersAreNonnullByDefault
package org.unbrokendome.jsonwebtoken.signature.impl;


text:
package exec

import (
	"context"
	"encoding/binary"
	"fmt"
	"reflect"
	"runtime"
	"strconv"
	"testing"

	"github.com/apache/beam/sdks/v2/go/pkg/beam/core/graph"
	"github.com/apache/beam/sdks/v2/go/pkg/beam/core/graph/coder"
	"github.com/apache/beam/sdks/v2/go/pkg/beam/core/graph/window"
	"github.com/apache/beam/sdks/v2/go/pkg/beam/core/runtime/coderx"
	"github.com/apache/beam/sdks/v2/go/pkg/beam/core/typex"
	"github.com/apache/beam/sdks/v2/go/pkg/beam/core/util/reflectx"
	"github.com/apache/beam/sdks/v2/go/pkg/beam/internal/errors"
)

var intInput = []interface{}{int(1), int(2), int(3), int(4), int(5), int(6)}
var int64Input = []interface{}{int64(1), int64(2), int64(3), int64(4), int64(5), int64(6)}
var strInput = []interface{}{"1", "2", "3", "4", "5", "6"}

var tests = []struct {
	Fn         interface{}
	AccumCoder *coder.Coder
	Input      []interface{}
	Expected   interface{}
}{
	{Fn: mergeFn, AccumCoder: intCoder(reflectx.Int), Input: intInput, Expected: int(21)},
	{Fn: nonBinaryMergeFn, AccumCoder: intCoder(reflectx.Int), Input: intInput, Expected: int(21)},
	{Fn: &MyCombine{}, AccumCoder: intCoder(reflectx.Int64), Input: intInput, Expected: int(21)},
	{Fn: &MyOtherCombine{}, AccumCoder: intCoder(reflectx.Int64), Input: intInput, Expected: "21"},
	{Fn: &MyThirdCombine{}, AccumCoder: intCoder(reflectx.Int), Input: strInput, Expected: int(21)},
	{Fn: &MyContextCombine{}, AccumCoder: intCoder(reflectx.Int64), Input: intInput, Expected: int(21)},
	{Fn: &MyErrorCombine{}, AccumCoder: intCoder(reflectx.Int64), Input: intInput, Expected: int(21)},
}

func fnName(x interface{}) string {
	v := reflect.ValueOf(x)
	if v.Kind() != reflect.Func {
		return v.Type().String()
	}
	return runtime.FuncForPC(uintptr(v.Pointer())).Name()
}

// TestCombine verifies that the Combine node works correctly.
func TestCombine(t *testing.T) {
	for _, test := range tests {
		t.Run(fnName(test.Fn), func(t *testing.T) {
			edge := getCombineEdge(t, test.Fn, reflectx.Int, test.AccumCoder)

			out := &CaptureNode{UID: 1}
			combine := &Combine{UID: 2, Fn: edge.CombineFn, Out: out}
			n := &FixedRoot{UID: 3, Elements: makeKeyedInput(42, test.Input...), Out: combine}

			constructAndExecutePlan(t, []Unit{n, combine, out})

			expected := makeKV(42, test.Expected)
			if !equalList(out.Elements, expected) {
				t.Errorf("combine(%s) = %v, want %v", edge.CombineFn.Name(), extractKeyedValues(out.Elements...), extractKeyedValues(expected...))
			}
		})
	}
}

// TestLiftedCombine verifies that the LiftedCombine, MergeAccumulators, and
// ExtractOutput nodes work correctly after the lift has been performed.
func TestLiftedCombine(t *testing.T) {
	withCoder := func(t *testing.T, suffix string, key interface{}, keyCoder *coder.Coder) {
		// The test values are all single global window.
		wc := coder.NewGlobalWindow()
		for _, test := range tests {
			t.Run(fnName(test.Fn)+"_"+suffix, func(t *testing.T) {
				edge := getCombineEdge(t, test.Fn, reflectx.Int, test.AccumCoder)

				out := &CaptureNode{UID: 1}
				extract := &ExtractOutput{Combine: &Combine{UID: 2, Fn: edge.CombineFn, Out: out}}
				merge := &MergeAccumulators{Combine: &Combine{UID: 3, Fn: edge.CombineFn, Out: extract}}
				gbk := &simpleGBK{UID: 4, KeyCoder: keyCoder, WindowCoder: wc, Out: merge}
				precombine := &LiftedCombine{Combine: &Combine{UID: 5, Fn: edge.CombineFn, Out: gbk}, KeyCoder: keyCoder, WindowCoder: wc}
				n := &FixedRoot{UID: 6, Elements: makeKVInput(key, test.Input...), Out: precombine}

				constructAndExecutePlan(t, []Unit{n, precombine, gbk, merge, extract, out})
				expected := makeKV(key, test.Expected)
				if !equalList(out.Elements, expected) {
					t.Errorf("liftedCombineChain(%s) = %v, want %v", edge.CombineFn.Name(), extractKeyedValues(out.Elements...), extractKeyedValues(expected...))
				}
			})
		}
	}
	withCoder(t, "intKeys", 42, intCoder(reflectx.Int))
	withCoder(t, "int64Keys", int64(42), intCoder(reflectx.Int64))

	cc, err := coder.NewCustomCoder("codable", myCodableType, codableEncoder, codableDecoder)
	if err != nil {
		t.Fatalf("%v", err)
	}
	withCoder(t, "pointerKeys", &myCodable{42}, &coder.Coder{Kind: coder.Custom, T: typex.New(myCodableType), Custom: cc})

}

// pigeonHasher only returns 0 for even hashes, and 1 for odd hashes
// nearly guaranteeing that overflow behavior must be tested for small sets.
type pigeonHasher struct {
	hasher elementHasher
}

func (p *pigeonHasher) Hash(element interface{}, w typex.Window) (uint64, error) {
	k, err := p.hasher.Hash(element, w)
	if err != nil {
		return 0, err
	}
	return k & 0x1, nil
}

func TestLiftingCache(t *testing.T) {
	zeroVal, zeroWindow := &FullValue{Elm: 0}, window.SingleGlobalWindow[0]
	t.Run("lookup", func(t *testing.T) {
		c := newLiftingCache(1, intCoder(reflectx.Int), coder.NewGlobalWindow())
		// Replace with pigeon hasher to ensure pigeonholing.
		c.keyHash = &pigeonHasher{hasher: c.keyHash}
		c.start()

		zerokey, fv, notfirst, err := c.lookup(zeroVal, zeroWindow)
		if err != nil {
			t.Fatalf("error on liftingCache.lookup(0, GW) = %v", err)
		}

		// Check properties of the cache
		if got, want := len(c.cache), 1; got != want {
			t.Fatalf("len(liftingCache.cache) = %v, want %v after first lookup", got, want)
		}
		if notfirst {
			t.Fatalf("liftingCache.lookup(0, GW) = key(%v), %v, notfirst(%v) but want first value for key", zerokey, fv, notfirst)
		}
		// Set value to ensure we get the same one we expect later.
		// the cache expects the value to have the key (Elm) and
		// a window set.
		fv.Elm = 0
		fv.Elm2 = "want"
		fv.Windows = window.SingleGlobalWindow

		key, fv2, notfirst, err := c.lookup(zeroVal, zeroWindow)
		if err != nil {
			t.Fatalf("error on liftingCache.lookup(0, GW) = %v", err)
		}
		if got, want := len(c.cache), 1; got != want {
			t.Fatalf("len(liftingCache.cache) = %v, want %v after lookup of existing key", got, want)
		}
		if got, want := key, zerokey; got != want {
			t.Fatalf("liftingCache.lookup(0, GW) = key(%v), want %v", got, want)
		}
		// This shouldn't be the first value.
		if !notfirst {
			t.Fatalf("liftingCache.lookup(0, GW) = key(%v), %v, notfirst(%v) but want existing value for key", key, fv2, notfirst)
		}
		if got, want := fv2.Elm2, fv.Elm2; got != want {
			t.Fatalf("liftingCache.lookup(0, GW) = %v, want %v", got, want)
		}

		// Now the hard part: We lookup new values until we pigeon hole & get a collision.
		// This will validates overflow lookups.
		var collision *FullValue
		for i := 1; i < 100; i++ {
			collision = &FullValue{Elm: i}
			key, fv2, notfirst, err = c.lookup(collision, zeroWindow)
			if err != nil {
				t.Fatalf("error on liftingCache.lookup(%v, GW) = %v", i, err)
			}
			if key == zerokey {
				break
			}
			// Set values so subsequent hits won't fail.
			fv2.Elm = collision.Elm
			fv2.Elm2 = "ignoreme"
			fv2.Windows = window.SingleGlobalWindow
		}
		if notfirst {
			t.Errorf("liftingCache.lookup(%v, GW) = key(%v), %v, notfirst(%v) but want first value for key", collision.Elm, key, fv2, notfirst)
		}
		// Set values so we can validate later.
		fv2.Elm = collision.Elm
		fv2.Elm2 = "newthing"
		fv2.Windows = window.SingleGlobalWindow

		key, fv2, notfirst, err = c.lookup(collision, zeroWindow)
		if err != nil {
			t.Fatalf("error on liftingCache.lookup(%v, GW) = %v", collision.Elm, err)
		}
		if !notfirst {
			t.Errorf("liftingCache.lookup(%v, GW) = key(%v), %v, notfirst(%v) but want first value for key", collision.Elm, key, fv2, notfirst)
		}
		if got, want := fv2.Elm2, "newthing"; got != want {
			t.Fatalf("liftingCache.lookup(%v, GW) = %v, want %v", collision.Elm, got, want)
		}

		// Check the original key again.
		key, fv2, notfirst, err = c.lookup(zeroVal, zeroWindow)
		if err != nil {
			t.Fatalf("error on liftingCache.lookup(0, GW) = %v", err)
		}
		if got, want := key, zerokey; got != want {
			t.Fatalf("liftingCache.lookup(0, GW) = key(%v), want %v", got, want)
		}
		if !notfirst {
			t.Fatalf("liftingCache.lookup(0, GW) = key(%v), %v, notfirst(%v) but want existing value for key", key, fv2, notfirst)
		}
		if got, want := fv2.Elm2, "want"; got != want {
			t.Fatalf("liftingCache.lookup(0, GW) = %v, want %v", got, want)
		}
	})
	load := func(c *liftingCache, n int) {
		t.Helper()
		for i := 0; i < n; i++ {
			_, fv, _, err := c.lookup(&FullValue{Elm: i}, zeroWindow)
			if err != nil {
				t.Fatalf("error on liftingCache.lookup(%v, GW) = %v", i, err)
			}
			// Set values so subsequent hits won't fail.
			fv.Elm = i
			fv.Elm2 = "ignoreme"
			fv.Windows = window.SingleGlobalWindow
		}
	}
	t.Run("compact_sparse", func(t *testing.T) {
		max := 10
		c := newLiftingCache(max, intCoder(reflectx.Int), coder.NewGlobalWindow())
		c.start()
		load(c, 100)
		zerokey, _, _, err := c.lookup(zeroVal, zeroWindow)
		if err != nil {
			t.Fatalf("error on liftingCache.lookup(%v, GW) = %v", 0, err)
		}
		c.compact(context.Background(), zerokey, func(ctx context.Context, elm *FullValue, values ...ReStream) error { return nil })
		if got := len(c.cache); got >= max {
			t.Errorf("len(c.cache) = %v, want < %v", got, max)
		}
		// Validate that "current" key wasn't removed.
		key, fv, notfirst, err := c.lookup(zeroVal, zeroWindow)
		if err != nil {
			t.Fatalf("error on liftingCache.lookup(%v, GW) = %v", 0, err)
		}
		if !notfirst {
			t.Fatalf("liftingCache.lookup(0, GW) = key(%v), %v, notfirst(%v) but want existing value for key", key, fv, notfirst)
		}
		if got, want := fv.Elm2, "ignoreme"; got != want {
			t.Fatalf("liftingCache.lookup(0, GW) = %v, want %v", got, want)
		}
	})
	t.Run("compact_dense", func(t *testing.T) {
		max := 1
		c := newLiftingCache(max, intCoder(reflectx.Int), coder.NewGlobalWindow())
		// Replace with pigeon hasher to ensure pigeonholing.
		c.keyHash = &pigeonHasher{hasher: c.keyHash}
		c.start()
		load(c, 100)
		zerokey, _, _, err := c.lookup(zeroVal, zeroWindow)
		if err != nil {
			t.Fatalf("error on liftingCache.lookup(%v, GW) = %v", 0, err)
		}
		c.compact(context.Background(), zerokey, func(ctx context.Context, elm *FullValue, values ...ReStream) error { return nil })
		if got, want := len(c.cache), 1; got != want {
			t.Errorf("len(c.cache) = %v, want %v", got, want)
		}
		key, fv, notfirst, err := c.lookup(zeroVal, zeroWindow)
		if err != nil {
			t.Fatalf("error on liftingCache.lookup(%v, GW) = %v", 0, err)
		}
		if !notfirst {
			t.Fatalf("liftingCache.lookup(0, GW) = key(%v), %v, notfirst(%v) but want existing value for key", key, fv, notfirst)
		}
		if got, want := fv.Elm2, "ignoreme"; got != want {
			t.Fatalf("liftingCache.lookup(0, GW) = %v, want %v", got, want)
		}
	})
	t.Run("emitAll", func(t *testing.T) {
		c := newLiftingCache(1, intCoder(reflectx.Int), coder.NewGlobalWindow())
		// Replace with pigeon hasher to ensure pigeonholing.
		c.keyHash = &pigeonHasher{hasher: c.keyHash}
		c.start()
		want := 100
		load(c, want)
		var got int
		c.emitAll(context.Background(), func(ctx context.Context, elm *FullValue, values ...ReStream) error {
			got++
			return nil
		})
		if got != want {
			t.Errorf("c.emitAll emitted %v values, want %v", got, want)
		}
		if got, want := len(c.cache), 0; got != want {
			t.Errorf("len(c.cache) = %v, want %v", got, want)
		}

	})
}

// TestConvertToAccumulators verifies that the ConvertToAccumulators phase
// correctly doesn't accumulate values at all.
func TestConvertToAccumulators(t *testing.T) {
	tests := []struct {
		Fn         interface{}
		AccumCoder *coder.Coder
		Input      []interface{}
		Expected   []interface{}
	}{
		{Fn: mergeFn, AccumCoder: intCoder(reflectx.Int), Input: intInput, Expected: intInput},
		{Fn: nonBinaryMergeFn, AccumCoder: intCoder(reflectx.Int), Input: intInput, Expected: intInput},
		{Fn: &MyCombine{}, AccumCoder: intCoder(reflectx.Int64), Input: intInput, Expected: int64Input},
		{Fn: &MyOtherCombine{}, AccumCoder: intCoder(reflectx.Int64), Input: intInput, Expected: int64Input},
		{Fn: &MyThirdCombine{}, AccumCoder: intCoder(reflectx.Int), Input: strInput, Expected: intInput},
		{Fn: &MyContextCombine{}, AccumCoder: intCoder(reflectx.Int64), Input: intInput, Expected: int64Input},
		{Fn: &MyErrorCombine{}, AccumCoder: intCoder(reflectx.Int64), Input: intInput, Expected: int64Input},
	}
	for _, test := range tests {
		t.Run(fnName(test.Fn), func(t *testing.T) {
			edge := getCombineEdge(t, test.Fn, reflectx.Int, test.AccumCoder)

			testKey := 42
			out := &CaptureNode{UID: 1}
			convertToAccumulators := &ConvertToAccumulators{Combine: &Combine{UID: 2, Fn: edge.CombineFn, Out: out}}
			n := &FixedRoot{UID: 3, Elements: makeKVInput(testKey, test.Input...), Out: convertToAccumulators}

			constructAndExecutePlan(t, []Unit{n, convertToAccumulators, out})

			expected := makeKVValues(testKey, test.Expected...)
			if !equalList(out.Elements, expected) {
				t.Errorf("convertToAccumulators(%s) = %#v, want %#v", edge.CombineFn.Name(), extractKeyedValues(out.Elements...), extractKeyedValues(expected...))
			}
		})
	}
}

type codable interface {
	EncodeMe() []byte
	DecodeMe([]byte)
}

func codableEncoder(v codable) []byte {
	return v.EncodeMe()
}

var myCodableType = reflect.TypeOf((*myCodable)(nil))

func codableDecoder(t reflect.Type, b []byte) codable {
	var v codable
	switch t {
	case myCodableType:
		v = &myCodable{}
	default:
		panic("don't know this type" + t.String())
	}
	v.DecodeMe(b)
	return v
}

type myCodable struct {
	val uint64
}

func (c *myCodable) EncodeMe() []byte {
	data := make([]byte, 8)
	binary.LittleEndian.PutUint64(data, c.val)
	return data
}

func (c *myCodable) DecodeMe(b []byte) {
	c.val = binary.LittleEndian.Uint64(b)
}

func getCombineEdge(t *testing.T, cfn interface{}, kt reflect.Type, ac *coder.Coder) *graph.MultiEdge {
	t.Helper()
	fn, err := graph.NewCombineFn(cfn)
	if err != nil {
		t.Fatalf("invalid function: %v", err)
	}

	g := graph.New()
	var vtype reflect.Type
	if fn.AddInputFn() != nil {
		// This makes the assumption that the AddInput function is unkeyed.
		vtype = fn.AddInputFn().Param[1].T
	} else {
		vtype = fn.MergeAccumulatorsFn().Param[1].T
	}
	inT := typex.NewCoGBK(typex.New(kt), typex.New(vtype))
	in := g.NewNode(inT, window.DefaultWindowingStrategy(), true)

	edge, err := graph.NewCombine(g, g.Root(), fn, in, ac, nil)
	if err != nil {
		t.Fatalf("invalid combinefn: %v", err)
	}
	return edge
}

func constructAndExecutePlan(t *testing.T, us []Unit) {
	p, err := NewPlan("a", us)
	if err != nil {
		t.Fatalf("failed to construct plan: %v", err)
	}

	if err := p.Execute(context.Background(), "1", DataContext{}); err != nil {
		t.Fatalf("execute failed: %v", err)
	}
	if err := p.Down(context.Background()); err != nil {
		t.Fatalf("down failed: %v", err)
	}
}

// The following functions and struct represent the combine contract implemented
// in various ways.
//
// Instead of a ProcessElement method, a liftable combine can be written by
// breaking down an operation into four component methods:
//
//   CreateAccumulator() AccumT
//   AddInput(a AccumT, v InputT) AccumT
//   MergeAccumulators(a, b AccumT) AccumT
//   ExtractOutput(v AccumT) OutputT
//
// In addition, there can be three distinct types, depending on where
// they are used in the combine, the input type, InputT, the output type, OutputT,
// and the accumulator type AccumT. Depending on the equality of the types, one
// or more of the methods can be unspecified.
//
// The only required method is MergeAccumulators.
//
// When InputT == OutputT == AccumT, the only required method is MergeAccumulators.
//
// When InputT == AccumT , then AddInput can be omitted, and MergeAccumulators used instead.
// When AccumT == Output , then ExtractOutput can be omitted, and the identity used instead.
//
// These two combined mean that when InputT == OutputT == AccumT, only MergeAccumulators
// needs to be specified.
//
// CreateAccumulator() is only required if the AccumT cannot be used in it's zero state,
// and needs initialization.

// mergeFn represents a combine that is just a binary merge, where
//
//  InputT == OutputT == AccumT == int
func mergeFn(a, b int) int {
	return a + b
}

// nonBinaryMergeFn represents a combine with a context parameter and an error return, where
//
//  InputT == OutputT == AccumT == int
func nonBinaryMergeFn(ctx context.Context, a, b int) (int, error) {
	return a + b, nil
}

// MyCombine represents a combine with the same Input and Output type (int), but a
// distinct accumulator type (int64).
//
//  InputT == OutputT == int
//  AccumT == int64
type MyCombine struct{}

func (*MyCombine) AddInput(a int64, v int) int64 {
	return a + int64(v)
}

func (*MyCombine) MergeAccumulators(a, b int64) int64 {
	return a + b
}

func (*MyCombine) ExtractOutput(a int64) int {
	return int(a)
}

// MyOtherCombine is the same as MyCombine, but has strings extracted as output.
//
//  InputT == int
//  AccumT == int64
//  OutputT == string
type MyOtherCombine struct {
	MyCombine // Embedding to re-use the exisitng AddInput and MergeAccumulators implementations
}

func (*MyOtherCombine) ExtractOutput(a int64) string {
	return fmt.Sprintf("%d", a)
}

// MyThirdCombine parses strings as Input, and doesn't specify an ExtractOutput
//
//  InputT == string
//  AccumT == int
//  OutputT == int
type MyThirdCombine struct{}

func (c *MyThirdCombine) AddInput(a int, s string) (int, error) {
	v, err := strconv.ParseInt(s, 0, 0)
	if err != nil {
		return 0, err
	}
	return c.MergeAccumulators(a, int(v)), nil
}

func (*MyThirdCombine) MergeAccumulators(a, b int) int {
	return a + b
}

// MyContextCombine is the same as MyCombine, but requires a context parameter.
//
//  InputT == int
//  AccumT == int64
//  OutputT == string
type MyContextCombine struct {
	MyCombine // Embedding to re-use the exisitng AddInput implementations
}

func (*MyContextCombine) MergeAccumulators(_ context.Context, a, b int64) int64 {
	return a + b
}

// MyErrorCombine is the same as MyCombine, but may return an error.
//
//  InputT == int
//  AccumT == int64
//  OutputT == string
type MyErrorCombine struct {
	MyCombine // Embedding to re-use the exisitng AddInput implementations
}

func (*MyErrorCombine) CreateAccumulator() (int64, error) {
	return 0, nil
}

func (*MyErrorCombine) MergeAccumulators(a, b int64) (int64, error) {
	return a + b, nil
}

func intCoder(t reflect.Type) *coder.Coder {
	c, err := coderx.NewVarIntZ(t)
	if err != nil {
		panic(errors.Wrapf(err, "Couldn't get VarInt coder for %v", t))
	}
	return coder.CoderFrom(c)
}

// simpleGBK buffers all input and continues on FinishBundle. Use with small single-bundle data only.
type simpleGBK struct {
	UID         UnitID
	Out         Node
	KeyCoder    *coder.Coder
	WindowCoder *coder.WindowCoder

	hasher elementHasher
	m      map[uint64]*group
}

type group struct {
	key    FullValue
	values []FullValue
}

func (n *simpleGBK) ID() UnitID {
	return n.UID
}

func (n *simpleGBK) Up(ctx context.Context) error {
	n.m = make(map[uint64]*group)
	n.hasher = makeElementHasher(n.KeyCoder, n.WindowCoder)
	return nil
}

func (n *simpleGBK) StartBundle(ctx context.Context, id string, data DataContext) error {
	return n.Out.StartBundle(ctx, id, data)
}

func (n *simpleGBK) ProcessElement(ctx context.Context, elm *FullValue, _ ...ReStream) error {
	key := elm.Elm
	value := elm.Elm2

	// Consider generalizing this to multiple windows.
	// The test values are all single global window.
	keyHash, err := n.hasher.Hash(key, elm.Windows[0])
	if err != nil {
		return err
	}
	g, ok := n.m[keyHash]
	if !ok {
		g = &group{
			key:    FullValue{Elm: key, Timestamp: elm.Timestamp, Windows: elm.Windows},
			values: make([]FullValue, 0),
		}
		n.m[keyHash] = g
	}
	g.values = append(g.values, FullValue{Elm: value, Timestamp: elm.Timestamp})

	return nil
}

func (n *simpleGBK) FinishBundle(ctx context.Context) error {
	for _, g := range n.m {
		values := &FixedReStream{Buf: g.values}
		if err := n.Out.ProcessElement(ctx, &g.key, values); err != nil {
			return err
		}
	}
	return n.Out.FinishBundle(ctx)
}

func (n *simpleGBK) Down(ctx context.Context) error {
	return nil
}

func (n *simpleGBK) String() string {
	return fmt.Sprintf("simpleGBK: %v Out:%v", n.ID(), n.Out.ID())
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

    <fragment
        android:id="@+id/editCategoriesFragment"
        android:name="fr.upem.journal.fragment.EditCategoriesFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>


text:
let requirejs = require('requirejs')
requirejs(['dfntly'], function(dfntly) {

  // We need a context to place our data in. We could use `this`, of course,
  // but as we're not in an object and as we don't want to pollute the global
  // namespace we'll create an empty object for ths purpose instead:
  const the = { }

  // This is the number we'll be calculating the square root for.
  dfntly.define(the, 'number', 100)

  // The approximation needs an initial guess of the square root. I've
  // arbitrarily chosen one third of the initial value to be a good enough
  // guess.
  dfntly.define(the, 'guess', () => {
    const guess = the.number/3

    console.log(
      `[${the.number}] Initial guess: ${guess} (Squared: ${guess*guess})`)

    return guess
  })

  // The approximation of the square root repeatedly keeps improving on the
  // initial guess through a simple calculation.
  dfntly.define(the, 'approximation', () => (the.guess + the.number/the.guess)/2)

  // If the current guess is a close enough approximation of the square root
  // we show the final answer. If not we update the value for the guess with
  // the latest approximation. This will trigger the dataflow engine again
  // for another round of approximating the square root.
  dfntly.define(the, 'iterate', () => {
    const square = the.approximation*the.approximation

    if (Math.abs(the.number - square) < 0.000000001)
      console.log(
        `[${the.number}] Final answer: ${the.approximation} (Math.sqrt: ${Math.sqrt(the.number)})`)
    else {
      console.log(
        `[${the.number}] Current guess: ${the.approximation} (Squared: ${square})`)

      the.guess = the.approximation
    }
  })

  // We can ask for the square root of another number by changing the value of
  // the node. Note that we must schedule this for later, so that the engine
  // has a chance of calculating the root of the first number first.
  setImmediate(() => { the.number = 77 })
})


text:
package ru.job4j.tracker.models;

/**
 * Class Item.
 * @author Maxim Ignashov (mailto:ignashov.m@icloud.com)
 * @version 1.0
 * @since 21.04.17
 */
public class Item {
    /**
     * Item name.
     */
    private String name;
    /**
     * Item description.
     */
    private String description;
    /**
     * Item create date.
     */
    private long create;
    /**
     * Item id.
     */
    private String id;
    /**
     * Constructor default.
     */
    public Item() {
    }
    /**
     * Constructor.
     * @param create item create date
     * @param description item description
     * @param name item name
     */
    public Item(String name, String description, long create) {
        this.name = name;
        this.description = description;
        this.create = create;
    }
    /**
     * Set name.
     * @param name item name
     */
    public void setName(String name) {
        this.name = name;
    }
    /**
     * Set description.
     * @param description item description
     */
    public void setDescription(String description) {
        this.description = description;
    }
    /**
     * Set create.
     * @param create item create date
     */
    public void setCreate(long create) {
        this.create = create;
    }
    /**
     * Set id.
     * @param id items id
     */
    public void setId(String id) {
        this.id = id;
    }
    /**
     * Get name.
     * @return name.
     */
    public String getName() {
        return this.name;
    }
    /**
     * Get description.
     * @return description.
     */
    public String getDescription() {
        return this.description;
    }
    /**
     * Get create.
     * @return create.
     */
    public long getCreate() {
        return this.create;
    }
    /**
     * Get id.
     * @return id.
     */
    public String getId() {
        return this.id;
    }
}