text:
package org.uddi.v3_service;

import java.rmi.Remote;
import java.rmi.RemoteException;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.ws.Holder;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
import org.uddi.custody_v3.DiscardTransferToken;
import org.uddi.custody_v3.KeyBag;
import org.uddi.custody_v3.TransferEntities;

/**
 * This portType defines all of the UDDI custody transfer operations. This
 * section defines the UDDI Custody and Ownership Transfer API Set[28]. Data
 * custody is introduced in Section 1.5.6 Data Custody. Ownership transfer is
 * introduced in Section 1.5.7 Transfer of Ownership. By virtue of having
 * created an entity, a publisher has ownership of the entity and is said to be
 * the owner of the entity. A custodial node MUST maintain a relationship of
 * ownership between an entity and its publisher by means of authorization
 * mechanisms. Every node of a multi-node registry MUST guarantee the integrity
 * of an entity's custody. As such, a node MUST not permit changes to an entity
 * unless it has custody of it.
 *
 * The Custody and Ownership Transfer API Set enables any nodes of a registry to
 * cooperatively transfer custody of one or more businessEntity or tModel
 * structures from one node to another, as well as allowing the transfer of
 * ownership of these structures from one publisher to another. Associated
 * entities of a businessEntity such as its businessService, bindingTemplate,
 * and publisherAssertion structures are transferred as part of the custody
 * transfer of the business entity. * From a custody transfer point of view, the
 * publishers are always distinct, though it may be the case that the publishers
 * are the same person. Also, the two nodes may or may not be distinct;
 * intra-node transfer between two publishers is simply a degenerate case in
 * which node custody does not change. Thus, in the case of an inter-node
 * transfer, ownership transfer is implied. In the case of an intra-node
 * transfer the behavior results in the transfer of ownership between two
 * publishers.
 *
 * For example, one UDDI registry, UDDI-1, MAY allow each node in UDDI-1
 * (composed of nodes 1A, 1B and 1C) to define its own policies for
 * registration, authentication and authorization. In this case, a "person",
 * (P1) would need to review the policies of all 3 nodes and decide upon the
 * node with which it chooses to register with. P1 may choose to register with
 * more than one node. P1 registers with node1A . Node1A also specifies how P1
 * is authenticated. If P1 successfully authenticates and publishes a business
 * entity (BE1) then P1 becomes the "owner" of BE1. Node1A is said to be the
 * "custodian" of BE1. P1 can also register at node1B. If P1 successfully
 * authenticates and publishes a business entity (BE2) then P1 becomes the
 * "owner" of BE2. Node1B is said to be the "custodian" of BE2. There is no
 * assumption that the registry UDDI-1 or its nodes (node1A and node1B) are
 * aware that P1 is the same "person". P1 is responsible for maintaining the
 * appropriate identity and authenticating correctly to each node within a
 * registry.
 *
 * Another UDDI registry, UDDI-2, MAY require each of its nodes (node2-1,
 * node2-2 and node2-3) to use the same registration, authentication and
 * authorization mechanisms. In this case, the policies are the same across all
 * nodes. The relationship of registration, publication and ownership remains
 * the same. If P1 wants to register with different nodes in UDDI-2, then it
 * needs to differentiate its registration with the different nodes, since an
 * attempt to register at node2-2 after registering at node2-1, would fail as
 * "already registered" (since by policy the nodes all share the same
 * registration, authentication and authorization).
 *
 * 5.4.1 Overview There are a number of scenarios where a publisher may choose
 * to transfer custodianship or ownership of one or more entities. These are
 * described in this section.
 *
 * 5.4.1.1 Intra-Node Ownership Transfer Intra-node ownership transfer involves
 * transferring entity ownership from one publisher to another within the same
 * UDDI node. Usage scenarios for this type of transfer include the following:
 *
 * · Businesses or organizational merges: Multiple organizations need to be
 * consolidated under the control of a single publisher.
 *
 * · Domain key generators: One use of ownership transfer is the transfer of
 * ownership of a derived key generator from one publisher to another to enable
 * her or him to publish entities using keys in that domain.
 *
 * The save_xx APIs can also be used to move entities between parent entities
 * that are owned by the same publisher. The save_service API, for example, can
 * be used to move services (and binding templates) between one business entity
 * and another as described in Section 5.2.17.3 Behavior of the save_service
 * API. Changing the parent relationship in this way causes two businessEntity
 * structures to be changed. Doing so enables the following scenarios:
 *
 * · Divestitures: An organization needs to reassign the control of a set of
 * services to two or more publishers.
 *
 * · Consolidation of registry entities: There are multiple entities for a given
 * business that are to be consolidated under a single publisher.
 *
 * 5.4.1.2 Inter-Node Custody Transfer Inter-node custody transfer involves the
 * custody transfer of a set of entities across nodes of a UDDI registry. A
 * transfer of ownership ensues as a consequence of this custody transfer. In
 * addition to the intra-node scenarios described above, inter-node custody
 * transfer may be used to address the following use cases:
 *
 * · Unsatisfactory service level: The functionality or service level provided
 * by a given node operator is insufficient, and the publisher wishes to move
 * their UDDI data to another node.
 *
 * · Change in availability for a UDDI node: A node is no longer providing UDDI
 * services, and all publishers need to be migrated to one or more nodes of the
 * registry.
 *
 * · Organizational Mergers, Divestitures or Consolidations: Changes in
 * organizational structure may result in the need to make changes to the set of
 * publishers used to manage the entities at various nodes of a registry.
 *
 * For any of these intra and inter-node scenarios, a mechanism is specified to
 * facilitate the transfer the custody of businessEntity and tModel entities
 * between nodes whether the entity is being transferred within a single node or
 * whether a custody transfer occurs between nodes of a registry.
 *
 * 5.4.2 Custody Transfer Considerations When a businessEntity is transferred,
 * all related businessService and bindingTemplate elements are transferred as
 * well. In addition, any publisherAssertion elements that reference the
 * businessEntity element's businessKey that are owned by the publisher are also
 * transferred.
 *
 * Note that the relinquishing publisher is not required to transfer all of its
 * UDDI entities (i.e. businessEntity and/or tModel entities) in a single
 * custody transfer request, nor is it required to transfer all of its entities
 * to the same target publisher or target node. Any combination or subset of
 * UDDI registry entities may be transferred to any number of target publishers
 * or nodes.
 *
 * 5.4.3 Transfer Execution The Custody and Ownership Transfer API Set enables
 * two publishers P1 and P2 and two nodes, N1 and N2, in a registry to
 * cooperatively transfer custody of one or more existing businessEntity or
 * tModel structures, E1…En, from N1 to N2 and, and by extension to transfer
 * ownership of the entities from P1 to P2. Related businessService,
 * bindingTemplate, and publisherAssertion structures are transferred with their
 * related businessEntities. From the registry's point of view, the publishers
 * are always distinct, though it may be the case that P1 and P2 are the same
 * party. The two nodes may or may not be distinct; intra-node transfer of
 * ownership from P1 to P2 is simply a degenerate case in which node custody
 * does not change.
 *
 * The Custody and Ownership Transfer API Set is divided into two parts, a set
 * of two client APIs and a single inter-node API. These client APIs are
 * get_transferToken and transfer_entities; in short, this constitutes the
 * Ownership Transfer API portion of this API set. The inter-node-API is
 * transfer_ custody which when combined with replication makes up the Custody
 * Transfer API portion of this API set. * The overall flow of custody and
 * ownership transfer is as follows:
 *
 * Publisher P1 invokes get_transferToken on N1, specifying the keys K1…Kn of
 * the entities E1…En that are to be transferred. If P1 is authorized to do this
 * (i.e., if P1 has ownership of E1…En), N1 returns a structure T, called a
 * transfer token, that represents authority to transfer the entities, including
 * all of the naturally contained children and publisher assertions related to
 * business entities involved in the transfer that are owned by P1. The
 * transferToken is a structure that consists of an opaque string that is
 * meaningful only to the node that issued it, an expiration time, and a node
 * identifier.
 *
 * P1 then gives T to P2 (typically by some secure means since T is valuable).
 * The publisher obtaining the custody information needs to have previously
 * obtained a publishers account on the node accepting custody of the entity
 * before he/she can complete the custody transfer. P2 then invokes
 * transfer_entities on N2, passing K1…Kn and T. If transfer_entities completes
 * successfully, the entities E1…En and their related structures
 * (businessService, bindingTemplate, and publisherAssertion) are in the custody
 * of N2 and are owned by P2. If the operation fails, nothing happens to the
 * entities. The actual transfer proceeds as follows, in the processing of
 * transfer_entities.
 *
 * If N1 and N2 are not distinct nodes, the ownership transfer from P1 to P2 is
 * an operation that is purely internal to the node – how it happens is up to
 * the implementation. If N1 and N2 are distinct, the following protocol occurs
 * while processing the transfer_entities request on N2.
 *
 * Upon receipt of a transfer_entities request, N2 checks that K1…Kn are valid
 * keys. There is the possibility that P1 might transfer more data than P2 can
 * accept due to policy-based restrictions on the limit of entities allowed to
 * be owned by P2 at N2. As is described below, replication is used to complete
 * the custody transfer process. A question that arises is at the time of
 * accepting the datum related to the transfer, could N2 throw a replication
 * error because the data being transferred exceeds the limits of user P2? Such
 * limits can not be enforced during replication because they are node-local
 * policy decisions from the perspective of enforcement. Thus, it is therefore
 * possible that as a result of a custody transfer a publisher may be caused to
 * hold more data that he/she would have been able to publish. Should this
 * situation occur, P2 MUST not be allowed to publish any additional data unless
 * P2 first reduces the number of entries it owns to an allowable limit.
 *
 * If all is well, N2 invokes the inter-node API transfer_custody on N1,
 * presenting the keys of top-level entities to be transferred, K1…Kn, P2's
 * identity (using the publisher's authorizedName), N2's node identifier (as
 * known in the Replication Configuration structure, see Section 7.5.2
 * Configuration of a UDDI Node – operator element), and T. The transferToken,
 * T, implies permission to transfer the entire content of the entities it
 * identifies, including all of the contained entities and related
 * publisherAssertions, if any. N1 checks to see whether T is a valid
 * transferToken that it issued and that T represents the authority to transfer
 * E1…En. If the validation is successful, N1 prevents further changes to
 * entities E1…En. N1 then updates the authorizedName and nodeID of the
 * operationalInfo of E1…En and related entities so that they are shown to be in
 * the custody of N2 and owned by P2. Finally, N1 responds to N2 which triggers
 * N2 to respond to the transfer_entities caller. This completes the processing
 * for the transfer_entities request.
 *
 * In the case that the datum being transferred is a key generator tModel, N1
 * will disallow further generation of keys associated with this key partition
 * at its node.
 *
 * Following the issue of the empty message by N1 to the transfer_custody call,
 * N1 will submit into the replication stream a changeRecordNewData providing in
 * the operationalInfo, N2's nodeID identifying it as the node where the datum
 * is being transferred to, and the authorizedName of P2. The
 * acknowledgmentRequested attribute of this change record MUST be set to
 * "true".
 *
 * The last modified date timestamp in the operationalInfo must change to
 * reflect the custody transfer. Figure 2 depicts the flow of a custody transfer
 * between P1 and P2. This class was generated by the JAX-WS RI. JAX-WS RI
 * 2.1.5-b03- Generated source version: 2.1
 *
 */
@WebService(name = "UDDI_CustodyTransfer_PortType", targetNamespace = "urn:uddi-org:api_v3_portType")
@XmlSeeAlso({
    org.uddi.custody_v3.ObjectFactory.class,
    org.uddi.repl_v3.ObjectFactory.class,
    org.uddi.subr_v3.ObjectFactory.class,
    org.uddi.api_v3.ObjectFactory.class,
    org.uddi.vscache_v3.ObjectFactory.class,
    org.uddi.vs_v3.ObjectFactory.class,
    org.uddi.sub_v3.ObjectFactory.class,
    org.w3._2000._09.xmldsig_.ObjectFactory.class,
    org.uddi.policy_v3.ObjectFactory.class,
    org.uddi.policy_v3_instanceparms.ObjectFactory.class
})
public interface UDDICustodyTransferPortType extends Remote {

    /**
     * The discard_transferToken API is a client API used to discard a
     * transferToken obtained through the get_transferToken API at the same
     * node. This API accepts either a transferToken or a keyBag as parameters
     * to remove the permission to transfer data associated with a particular
     * transferToken. If a keyBag is provided, all tokens corresponding to the
     * keys in the keyBag will be discarded and will no longer be valid for
     * custody or ownership transfer after the discard_transferToken is
     * processed, irrespective of whether the keys match any known business or
     * tmodelKey values. In the event that the keyBag represents a subset of the
     * keyBag for one or more transferToken elements, the transferToken is
     * discarded and will no longer be valid for transferring any entity. If the
     * token passed in the transferToken argument does not match an existing
     * token known to the system, no action is taken and success is reported.
     * Keys in the keyBag argument that do not have a corresponding token are
     * ignored.
     *
     * @param body
·
     * authInfo: This OPTIONAL argument is an
     * element that contains an authentication token.  Authentication
     * tokens are obtained using the get_authToken API call or through some
     * other means external to this specification, and represent the identity of
     * the publisher at a UDDI node.

     *
     *
·
     * transferToken: This is a known transferToken
     * obtained by a publisher at the node where the get_transferToken API was
     * invoked.

     *
     *
·
     * keyBag: One or more uddiKeys associated
     * either with businessEntity or tModel entities owned by the publisher that
     * were to be transferred to some other publisher and/or node in the
     * registry as the result of invocation of get_transferToken.  At least
     * one businessKey or tModelKey must be provided in a keyBag.

     *

     * Upon successful completion, an empty message is returned. See
     * section 4.8 Success and Error Reporting.
     *
     * No error will be reported if the transferToken provided in the call does
     * not match an existing token. No error will be reported if a token is not
     * found for a particular key in the keyBag.
     * @throws DispositionReportFaultMessage
     * @throws RemoteException
If an error occurs in
     * processing this API call, a dispositionReport structure MUST be returned
     * to the caller in a SOAP Fault. See Section 4.8 Success and Error Reporting.  In addition to the
     * errors common to all APIs, the following error information is relevant
     * here:

     *
     *
·
     * E_invalidKeyPassed: signifies that one of the
     * uddiKey values passed for entities to be transferred did not match
     * with any known businessKey or tModelKey values.  The key and element
     * or attribute that caused the problem SHOULD be clearly indicated in the
     * error text.

     */
    @WebMethod(operationName = "discard_transferToken", action = "discard_transferToken")
    @SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
    public void discardTransferToken(
            @WebParam(name = "discard_transferToken", targetNamespace = "urn:uddi-org:custody_v3", partName = "body") DiscardTransferToken body)
            throws DispositionReportFaultMessage, RemoteException;

    /**
     * The get_transferToken API is a client API used to initiate the transfer
     * of custody of one or more businessEntity or tModel entities from one node
     * to another. As previously stated, the two nodes may or may not be
     * distinct; intra-node transfer between two publishers is simply a
     * degenerate case in which node custody does not change. No actual transfer
     * takes place with the invocation of this API. Instead, this API obtains
     * permission from the custodial node, in the form of a transferToken, to
     * perform the transfer. The publisher who will be recipient of the
     * transferToken returned by this API must invoke the transfer_entities API
     * on the target custodial node to actually transfer the entities.
     *
     * @param authInfo · authInfo: This OPTIONAL argument is an element that
     * contains an authentication token. Authentication tokens are obtained
     * using the get_authToken API call or through some other means external to
     * this specification and represent the identity of the publisher at a UDDI
     * node.
     * @param keyBag keyBag: One or more key (of type uddi:uddiKey) associated
     * either with businessEntity or tModel entities owned by the publisher that
     * are to be transferred to some other publisher and/or node in the
     * registry. At least one businessKey or tModelKey must be provided.
     * @param nodeID this is a return value. The transfer token consists of a
     * nodeID, an expirationTime and an opaqueToken. The nodeID is used during
     * the transfer_entities API by the recipient node to confirm with the
     * relinquishing custodial node that the custody transfer is authorized and
     * still valid. The nodeID of the transferToken is the value of the nodeID
     * element of the Replication Configuration Structure. Refer to Section
     * 7.5.2 Configuration of a UDDI Node – operator Element.
     * @param expirationTime this is a return value. The expirationTime, defined
     * as xsd:dateTime, represents the time at which the transfer token is no
     * longer valid.
     * @param opaqueToken this is a return value. The opaqueToken is only
     * meaningful to the node that issues it. The opaqueToken is defined as
     * xsd:base64Binary to allow for a RECOMMENDED encryption of the token under
     * the relinquishing custody node's own encryption key.
     * @throws DispositionReportFaultMessage
     * @throws RemoteException
If an error occurs in
     * processing this API call, a dispositionReport structure MUST be returned
     * to the caller in a SOAP Fault. See section 4.8 Success and Error Reporting.  In addition to the
     * errors common to all APIs, the following error information is relevant
     * here:

     *
     *
·
     * E_invalidKeyPassed: signifies that one of the
     * uddiKey values passed for entities to be transferred did not match
     * with any known businessKey or tModelKey values.  The key and element
     * or attribute that caused the problem SHOULD be clearly indicated in the
     * error text.

     *
     *
·
     * E_tokenAlreadyExists: signifies that one or more of
     * the businessKey or tModelKey elements that identify entities to be
     * transferred are associated with a transferToken that is still valid and
     * has not been discarded, used or expired.  The error text SHOULD
     * clearly indicate which entity keys caused the error.

     *
     *
·
     * E_userMismatch: signifies that one or more of the
     * businessKey or tModelKey elements that identify entities to be
     * transferred are not owned by the publisher identified by the
     * authInfo element.  The error text SHOULD clearly indicate
     * which entity keys caused the error

     */
    @WebMethod(operationName = "get_transferToken", action = "get_transferToken")
    @RequestWrapper(localName = "get_transferToken", targetNamespace = "urn:uddi-org:custody_v3", className = "org.uddi.custody_v3.GetTransferToken")
    @ResponseWrapper(localName = "transferToken", targetNamespace = "urn:uddi-org:custody_v3", className = "org.uddi.custody_v3.TransferToken")
    public void getTransferToken(
            @WebParam(name = "authInfo", targetNamespace = "urn:uddi-org:api_v3") String authInfo,
            @WebParam(name = "keyBag", targetNamespace = "urn:uddi-org:custody_v3") KeyBag keyBag,
            @WebParam(name = "nodeID", targetNamespace = "urn:uddi-org:api_v3", mode = WebParam.Mode.OUT) Holder<String> nodeID,
            @WebParam(name = "expirationTime", targetNamespace = "urn:uddi-org:custody_v3", mode = WebParam.Mode.OUT) Holder<XMLGregorianCalendar> expirationTime,
            @WebParam(name = "opaqueToken", targetNamespace = "urn:uddi-org:custody_v3", mode = WebParam.Mode.OUT) Holder<byte[]> opaqueToken)
            throws DispositionReportFaultMessage, RemoteException;

    /**
     * The transfer_entities API is used by publishers to whom custody is being
     * transferred to actually perform the transfer. The recipient publisher
     * must have an unexpired transferToken that was issued by the custodial
     * node for the entities being transferred.
     *
     * @param body authInfo: This OPTIONAL argument is an element that contains
     * an authentication token. Authentication tokens are obtained using the
     * get_authToken API call or through some other means external to this
     * specification, and represent the identity of the publisher at a UDDI
     * node, in this case, the new owner of the entities being transferred.
     *
     * · transferToken: Required argument obtained from the custodial node via a
     * call to get_transferToken by the publisher requesting a transfer of
     * custody. The transferToken contains an opaque token, an expiration date,
     * and the identity of the custodial node. The transferToken represents
     * permission to transfer the entities that have been identified via a prior
     * call to the get_transferToken API.
     *
     * · keyBag: One or more uddiKeys associated with businessEntity or tModel
     * entities that are to be transferred to this publisher at the target node
     * in the registry. The set of keys must be the same as the set of keys in
     * the keyBag of the get_transferToken API call from which the given
     * transferToken was once obtained.
     *

     *
The target node responds to this API by
     * performing the transfer operation.  This operation is comprised of
     * four steps:

     *
     *
·
     * Verification that the entity keys are valid.

     *
     *
·
     * Verification that ownership of the entities by the
     * recipient publisher is allowed and would not violate any policies at the
     * target node related to publisher limits.

     *
     *
·
     * Verification with the custodial node that the transfer of
     * the designated entities is allowed.  This is accomplished by
     * invoking transfer_custody on the custodial node that is identified by the
     * nodeID element in the transferToken.  Any errors returned by the
     * custodial node cause this API to fail and are propagated to the
     * caller.

     *
     *
·
     * Changing custody and ownership of the designated entities
     * and entering these changes into the replication stream.

     *
     *
Upon successful completion, an empty message is
     * returned indicating the success of the transfer operation. In the case of
     * an inter-node custody transfer, while the transfer is in process, the
     * entities being transferred are not available for modification. To
     * determine the state of the data, UDDI clients can use the
     * get_operationalInfo API to determine when custody and ownership transfer
     * has taken place. A change in the nodeID of the operationalInfo provides
     * such an indication.

     * @throws DispositionReportFaultMessage, RemoteException
If an error occurs in processing this API call, a
     * dispositionReport structure MUST be returned to the caller in a SOAP
     * Fault. See Section 4.8 Success and Error
     * Reporting.  In addition to the errors common to all APIs, the
     * following error information is relevant here:

     *
     *
·
     * E_accountLimitExceeded: signifies that the target
     * node has determined that the transfer of custody of the identified
     * entities would result in the target publisher exceeding policy limits for
     * the number of owned entities.  The error text SHOULD clearly
     * indicate which entities cause the publishers limits to be exceeded. It is
     * possible for a publisher to come into possession of more data than the
     * target node's policy allows. The condition and node behavior under these
     * circumstances are described in Section 5.4.3Transfer Execution.

     *
     *
·
     * E_invalidKeyPassed: signifies that one of the
     * uddiKey values passed for entities to be transferred did not match
     * with any known businessKey or tModelKey values.  The key and element
     * or attribute that caused the problem SHOULD be clearly indicated in the
     * error text.

     *
     *
·
     * E_transferNotAllowed: signifies that the transfer of
     * one or more entities has been rejected by the target node or the
     * custodial node.  Reasons for rejection include expiration of the
     * transferToken, use of an invalid transferToken, and attempts to transfer
     * a set of entities that does not match the one represented by the
     * transferToken. The reason for rejecting the custody transfer SHOULD be
     * clearly indicated in the error text.

     *
     *
     */
    @WebMethod(operationName = "transfer_entities", action = "transfer_entities")
    @SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
    public void transferEntities(
            @WebParam(name = "transfer_entities", targetNamespace = "urn:uddi-org:custody_v3", partName = "body") TransferEntities body)
            throws DispositionReportFaultMessage, RemoteException;
}


text:
package com.squareup.okhttp;

import java.io.IOException;
import okio.Buffer;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public final class FormEncodingBuilderTest {
  @Test public void urlEncoding() throws Exception {
    RequestBody formEncoding = new FormEncodingBuilder()
        .add("a+=& b", "c+=& d")
        .add("space, the", "final frontier")
        .add("%25", "%25")
        .build();

    assertEquals("application/x-www-form-urlencoded", formEncoding.contentType().toString());

    String expected = "a%2B%3D%26%20b=c%2B%3D%26%20d&space%2C%20the=final%20frontier&%2525=%2525";
    assertEquals(expected.length(), formEncoding.contentLength());

    Buffer out = new Buffer();
    formEncoding.writeTo(out);
    assertEquals(expected, out.readUtf8());
  }

  @Test public void addEncoded() throws Exception {
    RequestBody formEncoding = new FormEncodingBuilder()
        .addEncoded("a+=& b", "c+=& d")
        .addEncoded("e+=& f", "g+=& h")
        .addEncoded("%25", "%25")
        .build();

    String expected = "a+%3D%26%20b=c+%3D%26%20d&e+%3D%26%20f=g+%3D%26%20h&%25=%25";
    Buffer out = new Buffer();
    formEncoding.writeTo(out);
    assertEquals(expected, out.readUtf8());
  }

  @Test public void encodedPair() throws Exception {
    RequestBody formEncoding = new FormEncodingBuilder()
        .add("sim", "ple")
        .build();

    String expected = "sim=ple";
    assertEquals(expected.length(), formEncoding.contentLength());

    Buffer buffer = new Buffer();
    formEncoding.writeTo(buffer);
    assertEquals(expected, buffer.readUtf8());
  }

  @Test public void encodeMultiplePairs() throws Exception {
    RequestBody formEncoding = new FormEncodingBuilder()
        .add("sim", "ple")
        .add("hey", "there")
        .add("help", "me")
        .build();

    String expected = "sim=ple&hey=there&help=me";
    assertEquals(expected.length(), formEncoding.contentLength());

    Buffer buffer = new Buffer();
    formEncoding.writeTo(buffer);
    assertEquals(expected, buffer.readUtf8());
  }

  @Test public void buildEmptyForm() throws Exception {
    RequestBody formEncoding = new FormEncodingBuilder().build();

    String expected = "";
    assertEquals(expected.length(), formEncoding.contentLength());

    Buffer buffer = new Buffer();
    formEncoding.writeTo(buffer);
    assertEquals(expected, buffer.readUtf8());
  }

  @Test public void characterEncoding() throws Exception {
    assertEquals("%00", formEncode(0)); // Browsers convert '\u0000' to '%EF%BF%BD'.
    assertEquals("%01", formEncode(1));
    assertEquals("%02", formEncode(2));
    assertEquals("%03", formEncode(3));
    assertEquals("%04", formEncode(4));
    assertEquals("%05", formEncode(5));
    assertEquals("%06", formEncode(6));
    assertEquals("%07", formEncode(7));
    assertEquals("%08", formEncode(8));
    assertEquals("%09", formEncode(9));
    assertEquals("%0A", formEncode(10)); // Browsers convert '\n' to '\r\n'
    assertEquals("%0B", formEncode(11));
    assertEquals("%0C", formEncode(12));
    assertEquals("%0D", formEncode(13)); // Browsers convert '\r' to '\r\n'
    assertEquals("%0E", formEncode(14));
    assertEquals("%0F", formEncode(15));
    assertEquals("%10", formEncode(16));
    assertEquals("%11", formEncode(17));
    assertEquals("%12", formEncode(18));
    assertEquals("%13", formEncode(19));
    assertEquals("%14", formEncode(20));
    assertEquals("%15", formEncode(21));
    assertEquals("%16", formEncode(22));
    assertEquals("%17", formEncode(23));
    assertEquals("%18", formEncode(24));
    assertEquals("%19", formEncode(25));
    assertEquals("%1A", formEncode(26));
    assertEquals("%1B", formEncode(27));
    assertEquals("%1C", formEncode(28));
    assertEquals("%1D", formEncode(29));
    assertEquals("%1E", formEncode(30));
    assertEquals("%1F", formEncode(31));
    assertEquals("%20", formEncode(32)); // Browsers use '+' for space.
    assertEquals("%21", formEncode(33));
    assertEquals("%22", formEncode(34));
    assertEquals("%23", formEncode(35));
    assertEquals("%24", formEncode(36));
    assertEquals("%25", formEncode(37));
    assertEquals("%26", formEncode(38));
    assertEquals("%27", formEncode(39));
    assertEquals("%28", formEncode(40));
    assertEquals("%29", formEncode(41));
    assertEquals("*", formEncode(42));
    assertEquals("%2B", formEncode(43));
    assertEquals("%2C", formEncode(44));
    assertEquals("-", formEncode(45));
    assertEquals(".", formEncode(46));
    assertEquals("%2F", formEncode(47));
    assertEquals("0", formEncode(48));
    assertEquals("9", formEncode(57));
    assertEquals("%3A", formEncode(58));
    assertEquals("%3B", formEncode(59));
    assertEquals("%3C", formEncode(60));
    assertEquals("%3D", formEncode(61));
    assertEquals("%3E", formEncode(62));
    assertEquals("%3F", formEncode(63));
    assertEquals("%40", formEncode(64));
    assertEquals("A", formEncode(65));
    assertEquals("Z", formEncode(90));
    assertEquals("%5B", formEncode(91));
    assertEquals("%5C", formEncode(92));
    assertEquals("%5D", formEncode(93));
    assertEquals("%5E", formEncode(94));
    assertEquals("_", formEncode(95));
    assertEquals("%60", formEncode(96));
    assertEquals("a", formEncode(97));
    assertEquals("z", formEncode(122));
    assertEquals("%7B", formEncode(123));
    assertEquals("%7C", formEncode(124));
    assertEquals("%7D", formEncode(125));
    assertEquals("%7E", formEncode(126));
    assertEquals("%7F", formEncode(127));
    assertEquals("%C2%80", formEncode(128));
    assertEquals("%C3%BF", formEncode(255));
  }

  private String formEncode(int codePoint) throws IOException {
    // Wrap the codepoint with regular printable characters to prevent trimming.
    RequestBody body = new FormEncodingBuilder()
        .add("a", new String(new int[] { 'b', codePoint, 'c' }, 0, 3))
        .build();
    Buffer buffer = new Buffer();
    body.writeTo(buffer);
    buffer.skip(3); // Skip "a=b" prefix.
    return buffer.readUtf8(buffer.size() - 1); // Skip the "c" suffix.
  }
}

redpajama_set_name: RedPajamaGithub


text:
package com.github.cc007.sciencespinoffsquiz.quiz.model;

/**
 *
 * @author Rik Schaaf aka CC007 <http://coolcat007.nl/>
 */
public enum Answer {

    A("A"),
    B("B"),
    C("C");

    private final String answer;

    private Answer(String s) {
        answer = s;
    }

    public boolean equalsAnswer(Answer otherAnswer) {
        return (otherAnswer == null) ? false : answer.equals(otherAnswer.toString());
    }

    @Override
    public String toString() {
        return answer;
    }

    public static Answer fromString(String a) {
        switch (a) {
            case "A":
                return Answer.A;
            case "B":
                return Answer.B;
            case "C":
                return Answer.C;
            default:
                return null;
        }
    }
}


text:
package predicate

import (
	"sigs.k8s.io/controller-runtime/pkg/event"
	"sigs.k8s.io/controller-runtime/pkg/predicate"
	logf "sigs.k8s.io/controller-runtime/pkg/runtime/log"
)

var log = logf.Log.WithName("predicate").WithName("eventFilters")

// GenerationChangedPredicate implements a default update predicate function on generation change
// (adapted from sigs.k8s.io/controller-runtime/pkg/predicate/predicate.ResourceVersionChangedPredicate)
type GenerationChangedPredicate struct {
	predicate.Funcs
}

// Update implements default UpdateEvent filter for validating generation change
func (GenerationChangedPredicate) Update(e event.UpdateEvent) bool {
	if e.MetaOld == nil {
		log.Error(nil, "Update event has no old metadata", "event", e)
		return false
	}
	if e.ObjectOld == nil {
		log.Error(nil, "Update event has no old runtime object to update", "event", e)
		return false
	}
	if e.ObjectNew == nil {
		log.Error(nil, "Update event has no new runtime object for update", "event", e)
		return false
	}
	if e.MetaNew == nil {
		log.Error(nil, "Update event has no new metadata", "event", e)
		return false
	}
	if e.MetaNew.GetGeneration() == e.MetaOld.GetGeneration() {
		return false
	}
	return true
}


text:
<?php

namespace Rexmac\Zyndax\View\Helper;

/**
 * Helper class for displaying page module names
 *
 * @category   Zyndax
 * @package    Rexmac_Zyndax
 * @subpackage View_Helper
 * @copyright  Copyright (c) 2011-2012 Rex McConnell (http://rexmac.com/)
 * @license    http://rexmac.com/license/bsd2c.txt Modified BSD License
 * @author     Rex McConnell <rex@rexmac.com>
 */
class PageModule extends \Zend_View_Helper_Abstract {

  /**
   * Helper method to display page module name
   *
   * @return string
   */
  public function pageModule() {
    if($this->view) {
      if($page = $this->view->navigation()->findActive($this->view->navigation()->getContainer())) {
        return $page['page']->getModule();
      }
      return '';
    }
  }
}


text:
using QuantConnect.Data.Market;

namespace QuantConnect.Indicators
{
    /// <summary>
    /// The Chaikin Money Flow Index (CMF) is a volume-weighted average of accumulation and distribution over
    /// a specified period.
    ///
    /// CMF = n-day Sum of [(((C - L) - (H - C)) / (H - L)) x Vol] / n-day Sum of Vol
    ///
    /// Where:
    /// n = number of periods, typically 21
    /// H = high
    /// L = low
    /// C = close
    /// Vol = volume
    ///
    /// https://www.fidelity.com/learning-center/trading-investing/technical-analysis/technical-indicator-guide/cmf
    /// </summary>
    public class ChaikinMoneyFlow : TradeBarIndicator, IIndicatorWarmUpPeriodProvider
    {
        /// <summary>
        /// Holds the point-wise flow-sum and volume terms.
        /// </summary>
        private readonly Sum _flowRatioSum;

        private readonly Sum _volumeSum;

        /// <summary>
        /// Gets a flag indicating when this indicator is ready and fully initialized
        /// </summary>
        public override bool IsReady => _flowRatioSum.IsReady;

        /// <summary>
        /// Required period, in data points, for the indicator to be ready and fully initialized.
        /// </summary>
        public int WarmUpPeriod { get; }

        /// <summary>
        /// Resets this indicator to its initial state
        /// </summary>
        public override void Reset()
        {
            _volumeSum.Reset();
            _flowRatioSum.Reset();
            base.Reset();
        }

        /// <summary>
        /// Initializes a new instance of the ChaikinMoneyFlow class
        /// </summary>
        /// <param name="name">A name for the indicator</param>
        /// <param name="period">The period over which to perform computation</param>
        public ChaikinMoneyFlow(string name, int period)
            : base($"CMF({name})")
        {
            WarmUpPeriod = period;
            _flowRatioSum = new Sum(period);
            _volumeSum = new Sum(period);
        }

        /// <summary>
        /// Computes the next value for this indicator from the given state.
        /// </summary>
        /// <param name="input">The input value to this indicator on this time step</param>
        /// <returns>A new value for this indicator</returns>
        protected override decimal ComputeNextValue(TradeBar input)
        {
            var denominator = (input.High - input.Low);
            var flowRatio = denominator > 0
                ? input.Volume * (input.Close - input.Low - (input.High - input.Close)) / denominator
                : 0m;

            _flowRatioSum.Update(input.EndTime, flowRatio);
            _volumeSum.Update(input.EndTime, input.Volume);

            return !IsReady || _volumeSum == 0m ? 0m : _flowRatioSum / _volumeSum;
        }
    }
}


text:
BOOST_AUTO_TEST_SUITE(test_tinympl)
BOOST_AUTO_TEST_SUITE(algorithm_variadic)

BOOST_AUTO_TEST_CASE(always_pass)
{
  BOOST_CHECK( true );
}

BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()

#endif // TINYMPL_ALGORITHM_VARIADIC_TEST_ENABLED


text:
require 'oauth'

class SorceryController < ActionController::Base
  protect_from_forgery

  before_action :require_login_from_http_basic, only: [:test_http_basic_auth]
  before_action :require_login, only: [:test_logout, :test_logout_with_force_forget_me, :test_should_be_logged_in, :some_action]

  def index
  end

  def some_action
    render nothing: true
  end

  def some_action_making_a_non_persisted_change_to_the_user
    current_user.email = 'to_be_ignored'
    render nothing: true
  end

  def test_login
    @user = login(params[:email], params[:password])
    render nothing: true
  end

  def test_auto_login
    @user = User.first
    auto_login(@user)
    @result = current_user
    render nothing: true
  end

  def test_return_to
    @user = login(params[:email], params[:password])
    redirect_back_or_to(:index, notice: 'haha!')
  end

  def test_logout
    logout
    render nothing: true
  end

  def test_logout_with_remember
    remember_me!
    logout
    render nothing: true
  end

  def test_logout_with_force_forget_me
    remember_me!
    force_forget_me!
    logout
    render nothing: true
  end

  def test_login_with_remember
    @user = login(params[:email], params[:password])
    remember_me!

    render nothing: true
  end

  def test_login_with_remember_in_login
    @user = login(params[:email], params[:password], params[:remember])

    render nothing: true
  end

  def test_login_from_cookie
    @user = current_user
    render nothing: true
  end

  def test_not_authenticated_action
    render text: 'test_not_authenticated_action'
  end

  def test_should_be_logged_in
    render nothing: true
  end

  def test_http_basic_auth
    render text: 'HTTP Basic Auth'
  end

  def login_at_test_twitter
    login_at(:twitter)
  end

  alias :login_at_test :login_at_test_twitter

  def login_at_test_facebook
    login_at(:facebook)
  end

  def login_at_test_github
    login_at(:github)
  end

  def login_at_test_paypal
    login_at(:paypal)
  end

  def login_at_test_google
    login_at(:google)
  end

  def login_at_test_liveid
    login_at(:liveid)
  end

  def login_at_test_jira
    login_at(:jira)
  end

  def login_at_test_vk
    login_at(:vk)
  end

  def login_at_test_salesforce
    login_at(:salesforce)
  end

  def login_at_test_with_state
    login_at(:facebook, {state: 'bla'})
  end

  def test_login_from_twitter
    if @user = login_from(:twitter)
      redirect_to 'bla', notice: 'Success!'
    else
      redirect_to 'blu', alert: 'Failed!'
    end
  end

  alias :test_login_from :test_login_from_twitter

  def test_login_from_facebook
    if @user = login_from(:facebook)
      redirect_to 'bla', notice: 'Success!'
    else
      redirect_to 'blu', alert: 'Failed!'
    end
  end

  def test_login_from_github
    if @user = login_from(:github)
      redirect_to 'bla', notice: 'Success!'
    else
      redirect_to 'blu', alert: 'Failed!'
    end
  end

  def test_login_from_paypal
    if @user = login_from(:paypal)
      redirect_to 'bla', notice: 'Success!'
    else
      redirect_to 'blu', alert: 'Failed!'
    end
  end

  def test_login_from_google
    if @user = login_from(:google)
      redirect_to 'bla', notice: 'Success!'
    else
      redirect_to 'blu', alert: 'Failed!'
    end
  end

  def test_login_from_liveid
    if @user = login_from(:liveid)
      redirect_to 'bla', notice: 'Success!'
    else
      redirect_to 'blu', alert: 'Failed!'
    end
  end

  def test_login_from_vk
    if @user = login_from(:vk)
      redirect_to 'bla', notice: 'Success!'
    else
      redirect_to 'blu', alert: 'Failed!'
    end
  end

  def test_login_from_jira
    if @user = login_from(:jira)
      redirect_to 'bla', notice: 'Success!'
    else
      redirect_to 'blu', alert: 'Failed!'
    end
  end

  def test_login_from_salesforce
    if @user = login_from(:salesforce)
      redirect_to 'bla', notice: 'Success!'
    else
      redirect_to 'blu', alert: 'Failed!'
    end
  end

  def test_return_to_with_external_twitter
    if @user = login_from(:twitter)
      redirect_back_or_to 'bla', notice: 'Success!'
    else
      redirect_to 'blu', alert: 'Failed!'
    end
  end

  def test_return_to_with_external_jira
    if @user = login_from(:jira)
      redirect_back_or_to 'bla', notice: 'Success!'
    else
      redirect_to 'blu', alert: 'Failed!'
    end
  end

  alias :test_return_to_with_external :test_return_to_with_external_twitter

  def test_return_to_with_external_facebook
    if @user = login_from(:facebook)
      redirect_back_or_to 'bla', notice: 'Success!'
    else
      redirect_to 'blu', alert: 'Failed!'
    end
  end

  def test_return_to_with_external_github
    if @user = login_from(:github)
      redirect_back_or_to 'bla', notice: 'Success!'
    else
      redirect_to 'blu', alert: 'Failed!'
    end
  end

  def test_return_to_with_external_paypal
    if @user = login_from(:paypal)
      redirect_back_or_to 'bla', notice: 'Success!'
    else
      redirect_to 'blu', alert: 'Failed!'
    end
  end

  def test_return_to_with_external_google
    if @user = login_from(:google)
      redirect_back_or_to 'bla', notice: 'Success!'
    else
      redirect_to 'blu', alert: 'Failed!'
    end
  end

  def test_return_to_with_external_liveid
    if @user = login_from(:liveid)
      redirect_back_or_to 'bla', notice: 'Success!'
    else
      redirect_to 'blu', alert: 'Failed!'
    end
  end

  def test_return_to_with_external_vk
    if @user = login_from(:vk)
      redirect_back_or_to 'bla', notice: 'Success!'
    else
      redirect_to 'blu', alert: 'Failed!'
    end
  end

  def test_return_to_with_external_salesforce
    if @user = login_from(:salesforce)
      redirect_back_or_to 'bla', notice: 'Success!'
    else
      redirect_to 'blu', alert: 'Failed!'
    end
  end

  def test_create_from_provider
    provider = params[:provider]
    login_from(provider)
    if @user = create_from(provider)
      redirect_to 'bla', notice: 'Success!'
    else
      redirect_to 'blu', alert: 'Failed!'
    end
  end

  def test_add_second_provider
    provider = params[:provider]
    if logged_in?
      if @user = add_provider_to_user(provider)
        redirect_to "bla", :notice => "Success!"
      else
        redirect_to "blu", :alert => "Failed!"
      end
    end
  end

  def test_create_from_provider_with_block
    provider = params[:provider]
    login_from(provider)
    @user = create_from(provider) do |user|
      # check uniqueness of email
      # User.where(email: user.email).empty?
      false
    end
    if @user
      redirect_to 'bla', notice: 'Success!'
    else
      redirect_to 'blu', alert: 'Failed!'
    end
  end

end


text:
package com.kubakhov.viritin.collections.impl;

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

public class CacheableSetImpl<T> extends CacheableListImpl<T> implements Set<T> {

	public CacheableSetImpl(List<T> list) {
		super(list);
	}

	@Override
	public boolean add(T entity) {
		if (contains(entity))
			return false;
		return super.add(entity);
	}

	@Override
	public boolean addExisted(T entity) {
		if (!add(entity))
			return false;
		return addedExisted.add(entity);
	}
}


text:
URL=https://github.com/github/codeql-cli-binaries/releases
LATEST_VERSION=$(curl -L -s -H 'Accept: application/json' $URL/latest | sed -e 's/.*"tag_name":"\([^"]*\)".*/\1/')
CURRENT_VERSION=v$(codeql version 2>/dev/null | sed -ne 's/.*release \([0-9.]*\)\./\1/p')
if [[ $CURRENT_VERSION != $LATEST_VERSION ]]; then
  if [[ $UID != 0 ]]; then
    echo "update required, please run this script with sudo:"
    echo "  sudo $0"
    exit 1
  fi
  ZIP=$(mktemp codeql.XXXX.zip)
  curl -fSqL -o $ZIP $URL/download/$LATEST_VERSION/codeql-linux64.zip
  unzip -q $ZIP -d /opt
  rm $ZIP
  ln -sf /opt/codeql/codeql /usr/local/bin/codeql
  echo installed version $LATEST_VERSION
else
  echo current version $CURRENT_VERSION is up-to-date
fi


text:
@interface PanGestureViewController : UIViewController

@end


text:
// bugfix for https://svn.boost.org/trac/boost/ticket/5722
#include <boost/asio.hpp>

#include "Client"
#include "Message"
#include "Wt/WApplication"
#include "Wt/WException"

#include <boost/lexical_cast.hpp>

namespace Wt {

LOGGER("Mail.Client");

namespace {
  bool logged = false;
}

  namespace Mail {

using boost::asio::ip::tcp;

class Client::Impl
{
public:
  enum ReplyCode {
    Ready = 220,
    Bye = 221,
    Ok = 250,
    StartMailInput = 354
  };

  Impl(const std::string& host, const std::string& selfFQDN, int port)
    : socket_(io_service_)
  {
    // Get a list of endpoints corresponding to the server name.
    tcp::resolver resolver(io_service_);

    tcp::resolver::query query(host, boost::lexical_cast<std::string>(port));
    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
    tcp::resolver::iterator end;

    // Try each endpoint until we successfully establish a connection.
    boost::system::error_code error = boost::asio::error::host_not_found;
    while (error && endpoint_iterator != end) {
      socket_.close();
      socket_.connect(*endpoint_iterator++, error);
    }

    if (error) {
      socket_.close();
      LOG_ERROR("could not connect to: " << host << ":" << port);
      return;
    }

    try {
      failIfReplyCodeNot(Ready);

      send("EHLO " + selfFQDN + "\r\n");

      failIfReplyCodeNot(Ok);
    } catch (std::exception& e) {
      socket_.close();
      LOG_ERROR(e.what());
      return;
    }
  }

  bool good() const {
    return socket_.is_open();
  }

  ~Impl()
  {
    if (good()) {
      try {
	send("QUIT\r\n");
	failIfReplyCodeNot(Bye);
      } catch (std::exception& e) {
	socket_.close();
	LOG_ERROR(e.what());
	return;
      }
    }
  }

  bool send(const Message& message)
  {
    try {
      send("MAIL FROM:<" + message.from().address() + ">\r\n");
      failIfReplyCodeNot(Ok);
      for (unsigned i = 0; i < message.recipients().size(); ++i) {
	const Mailbox& m = message.recipients()[i].mailbox;

	send("RCPT TO:<" + m.address() + ">\r\n");
	failIfReplyCodeNot(Ok);
      }

      send("DATA\r\n");
      failIfReplyCodeNot(StartMailInput);

      boost::asio::streambuf buf;
      std::ostream data(&buf);
      message.write(data);
      data << ".\r\n";

      boost::asio::write(socket_, buf);

      failIfReplyCodeNot(Ok);
    } catch (std::exception& e) {
      socket_.close();
      LOG_ERROR(e.what());
      return false;
    }
    return true;
  }

private:
  void send(const std::string& s)
  {
    LOG_DEBUG("C " << s);
    // boost::asio::const_buffer request = boost::asio::buffer(s);
    boost::asio::write(socket_, boost::asio::buffer(s));

    // FIXME error handling ?
  }

  void failIfReplyCodeNot(ReplyCode expected)
  {
    int r = readResponse();

    if (r != expected)
      throw WException("Unexpected response "
		       + boost::lexical_cast<std::string>(r));
  }

  int readResponse() {
    int replyCode = -1;

    boost::asio::streambuf response;
    for (;;) {
      boost::asio::read_until(socket_, response, "\r\n");

      std::istream in(&response);
      int code;
      in >> code;

      if (!in)
	throw WException("Invalid response");

      std::string msg;
      std::getline(in, msg);

      LOG_DEBUG("S " << code << msg);

      if (replyCode == -1)
	replyCode = code;
      else if (code != replyCode)
	throw WException("Inconsistent multi-line response");

      if (msg.length() > 0 && msg[0] == '-')
	continue;
      else
	return replyCode;
    }

    return -1; // Not reachable
  }

private:
  boost::asio::io_service io_service_;
  tcp::socket socket_;
};

Client::Client(const std::string& selfHost)
  : impl_(0),
    selfHost_(selfHost)
{
  if (selfHost_.empty()) {
    selfHost_ = "localhost";
    WApplication::readConfigurationProperty("smtp-self-host", selfHost_);

    if (!logged)
      LOG_INFO("Smtp::Client: using '" << selfHost_ << "' (from smtp-self-host property) "
	       "as self host");
  } else
    if (!logged)
      LOG_INFO("Smtp::Client: using '" << selfHost_ << "' as self host");
}

Client::~Client()
{
  disconnect();
}

bool Client::connect()
{
  std::string smtpHost = "localhost";
  std::string smtpPortStr = "25";

  WApplication::readConfigurationProperty("smtp-host", smtpHost);
  WApplication::readConfigurationProperty("smtp-port", smtpPortStr);

  int smtpPort = boost::lexical_cast<int>(smtpPortStr);

  if (!logged)
    LOG_INFO("Smtp::Client: using '" << smtpHost << ":" << smtpPortStr
	     << "' (from smtp-host and smtp-port properties) as SMTP host");

  return connect(smtpHost, smtpPort);
}

bool Client::connect(const std::string& smtpHost, int smtpPort)
{
  if (!logged) {
    LOG_INFO("Smtp::Client: connecting to '" << smtpHost << ":" << smtpPort);
    logged = true;
  }

  delete impl_;
  impl_ = new Impl(smtpHost, selfHost_, smtpPort);

  return impl_->good();
}

void Client::disconnect()
{
  delete impl_;
  impl_ = 0;
}

bool Client::send(const Message& message)
{
  return impl_->send(message);
}

  }
}


text:
require 'test_helper'
module ActionController
  module TestProcess
    # Executes a request simulating OPTIONS HTTP method and set/volley the response
    def options(action, parameters = nil, session = nil, flash = nil)
      process(action, parameters, session, flash, "OPTIONS")
    end
  end
end

class OrdersControllerTest < ControllerTestSupport
  test "should get index" do
    get :index
    assert_response :success
    assert_not_nil assigns(:orders)
  end

  test "should get index as XML" do
    @request.env['HTTP_ACCEPT'] = 'application/xml'
    get :index
    assert_response :success
    assert_allows %w(HEAD GET POST)
    orders = assigns(:orders)
    assert_not_nil orders
    assert_equal 4, orders.size
  end

  test "should get index as XML with state equals all" do
    @request.env['HTTP_ACCEPT'] = 'application/xml'
    get :index, :state => 'all'
    assert_response :success
    assert_allows %w(HEAD GET POST)
    orders = assigns(:orders)
    assert_not_nil orders
    assert_equal 4, orders.size
  end

  test "should get orders in state cancelled" do
    @request.env['HTTP_ACCEPT'] = 'application/xml'
    get :index, :state => :cancelled
    assert_response :success
    assert_allows %w(HEAD GET POST)
    orders = assigns(:orders)
    assert_not_nil orders
    assert_equal 2, orders.size
  end

  test "should get new" do
    get :new
    assert_response :success
  end

  test "should create order" do
    assert_difference('Order.count') do
      post :create, :order => { :customer => 'http://localhost:3001/customers/5',
                                :order_date => '2008-11-30',
                                :billing_address => 'New York' }
    end

    assert_redirected_to order_path(assigns(:order))
  end

  test "should create order via XML" do
    xml = <<-XML
<?xml version="1.0" encoding="UTF-8"?>
<order xmlns="http://example.com/schemas/ordermanagement">
  <date>2009-01-22</date>
  <shippingDate>2009-01-25</shippingDate>
  <customer>
    <name>New customer</name>
    <link>http://localhost:3001/customers/4711</link>
  </customer>
  <billingAddress>Geneva</billingAddress>
  <shippingAddress>Paris</shippingAddress>
</order>
    XML

    @request.env['RAW_POST_DATA'] = xml
    @request.env['CONTENT_TYPE'] = 'application/xml'
    @request.env['HTTP_ACCEPT'] = 'application/xml'
    post :create
    assert_response :created
    location = @response.header['Location']
    assert_allows %w(HEAD GET PUT DELETE)
    assert_equal order_url(assigns(:order)), location
  end

  test "should update order via XML" do
    xml = <<-XML
<?xml version="1.0" encoding="UTF-8"?>
<order xmlns="http://example.com/schemas/ordermanagement">
  <customer><name>Changed description of customer</name></customer>
</order>
    XML

    @request.env['RAW_POST_DATA'] = xml
    @request.env['CONTENT_TYPE'] = 'application/xml'
    @request.env['HTTP_ACCEPT'] = 'application/xml'
    id = orders(:one).id
    put :update, :id => id
    assert_response :success
    assert_allows %w(HEAD GET PUT DELETE)
    assert_equal "Changed description of customer", Order.find(id).customer_description
  end

  test "should show order" do
    get :show, :id => orders(:one).id
    assert_response :success
  end

  test "should get edit" do
    get :edit, :id => orders(:one).id
    assert_response :success
  end

  test "should update order" do
    put :update, :id => orders(:one).id, :order => { }
    assert_redirected_to order_path(assigns(:order))
  end

  test "should destroy order" do
    assert_difference('Order.count', -1) do
      delete :destroy, :id => orders(:one).id
    end

    assert_redirected_to orders_path
  end

  test "new order should have received state" do
    xml = <<-XML
<?xml version="1.0" encoding="UTF-8"?>
<order xmlns="http://example.com/schemas/ordermanagement">
  <date>2009-01-22</date>
  <shippingDate>2009-01-25</shippingDate>
  <customer>
    <name>New customer</name>
    <link>http://localhost:3001/customers/4711</link>
  </customer>
  <billingAddress>Geneva</billingAddress>
  <shippingAddress>Paris</shippingAddress>
</order>
    XML

    @request.env['RAW_POST_DATA'] = xml
    @request.env['CONTENT_TYPE'] = 'application/xml'
    @request.env['HTTP_ACCEPT'] = 'application/xml'
    post :create
    location = @response.header['Location']
    assert_equal order_url(assigns(:order)), location
    id = assigns(:order).id
    get :show, :id => id
    order = assigns(:order)
    assert_equal order.id, id
    assert_equal :received, order.state.to_sym
    assert_allows %w(HEAD GET PUT DELETE)
  end

  test "options for order collection should be correct" do
    options :options
    assert_response :success
    assert_allows %w(HEAD GET POST)
  end

  test "options for order should be correct" do
    options :options, :id => orders(:one).id
    assert_response :success
    assert_allows %w(HEAD GET PUT DELETE)
    orders(:one).accept!
    assert orders(:one).state = :accepted, "Order state should be 'accepted'"
    options :options, :id => orders(:one).id
    assert_response :success
    assert_allows %w(HEAD GET)
  end

  test "state resource should reflect order state as plain text" do
      @request.env['HTTP_ACCEPT'] = 'text/plain'
      get :get_state, :id => orders(:one).id
      assert_response :success
      assert_allows %w(HEAD GET PUT)
      assert_equal "received", @response.body.strip
  end

  test "state resource should reflect order state as XML" do
      xml = <<-XML
<?xml version="1.0" encoding="UTF-8"?>
<orderState xmlns="http://example.com/schemas/ordermanagement">received</orderState>
      XML
      @request.env['HTTP_ACCEPT'] = 'application/xml'
      get :get_state, :id => orders(:one).id
      assert_response :success
      assert_allows %w(HEAD GET PUT)
      assert_dom_equal xml, @response.body
  end

  test "should create order cancellation via XML" do
    xml = <<-XML
<?xml version="1.0" encoding="UTF-8"?>
<cancellation xmlns="http://example.com/schemas/ordermanagement">
  <date>2009-01-22</date>
  <reason>Unknown</reason>
</cancellation>
    XML

    @request.env['RAW_POST_DATA'] = xml.sub('<%= url %>', order_url(orders(:one)))
    @request.env['CONTENT_TYPE'] = 'application/xml'
    @request.env['HTTP_ACCEPT'] = 'application/xml'
    assert_difference('Cancellation.count') do
      post :cancel, :id => orders(:one).id
    end
    assert_response :success
    assert_allows %w(HEAD GET)
    order = Order.find(orders(:one).id)
    assert_equal :cancelled, order.state
    assert_not_nil order.cancellation
    assert_xml @response.body, 'om:http://example.com/schemas/ordermanagement' do |xml|
      xml.assert_node_not_nil '//om:order'
      xml.assert_node_not_nil '//om:order/om:cancellation'
      xml.assert_content_not_nil '//om:order/om:cancellation'
      xml.assert_content_equal cancellation_path(order.cancellation), '//om:order/om:cancellation'
    end

  end

  test "order cancellation via XML should fail on accepted orders" do
    xml = <<-XML
<?xml version="1.0" encoding="UTF-8"?>
<cancellation xmlns="http://example.com/schemas/ordermanagement">
  <date>2009-01-22</date>
  <reason>Unknown</reason>
</cancellation>
    XML

    @request.env['RAW_POST_DATA'] = xml.sub('<%= url %>', order_url(orders(:one)))
    @request.env['CONTENT_TYPE'] = 'application/xml'
    @request.env['HTTP_ACCEPT'] = 'application/xml'
    assert_no_difference('Cancellation.count') do
      assert_raises(Order::StateError) { post :cancel, :id => orders(:two).id }
    end
  end
end


text:
#region License

#endregion
using System;
using System.Abstract.Parts;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
namespace Contoso.Abstract.Parts
{
    /// <summary>
    /// WcfTypeSerializer
    /// </summary>
    public class WcfTypeSerializer : ITypeSerializer
    {
        /// <summary>
        /// Reads the object.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="type">The type.</param>
        /// <param name="s">The s.</param>
        /// <returns></returns>
        public T ReadObject<T>(Type type, Stream s)
            where T : class
        {
            if (type == null)
                throw new ArgumentNullException("type");
            if (s == null)
                throw new ArgumentNullException("s");
            var serializer = new DataContractSerializer(type);
            return (serializer.ReadObject(s) as T);
        }

        /// <summary>
        /// Reads the objects.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="type">The type.</param>
        /// <param name="s">The s.</param>
        /// <returns></returns>
        public IEnumerable<T> ReadObjects<T>(Type type, Stream s)
            where T : class
        {
            if (type == null)
                throw new ArgumentNullException("type");
            if (s == null)
                throw new ArgumentNullException("s");
            var serializer = new DataContractSerializer(type);
            return (serializer.ReadObject(s) as IEnumerable<T>);
        }

        /// <summary>
        /// Writes the object.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="type">The type.</param>
        /// <param name="s">The s.</param>
        /// <param name="graph">The graph.</param>
        public void WriteObject<T>(Type type, Stream s, T graph)
            where T : class
        {
            if (type == null)
                throw new ArgumentNullException("type");
            if (s == null)
                throw new ArgumentNullException("s");
            if (graph == null)
                throw new ArgumentNullException("graph");
            var serializer = new DataContractSerializer(type);
            serializer.WriteObject(s, graph);
        }

        /// <summary>
        /// Writes the objects.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="type">The type.</param>
        /// <param name="s">The s.</param>
        /// <param name="graphs">The graphs.</param>
        public void WriteObjects<T>(Type type, Stream s, IEnumerable<T> graphs)
            where T : class
        {
            if (type == null)
                throw new ArgumentNullException("type");
            if (s == null)
                throw new ArgumentNullException("s");
            if (graphs == null)
                throw new ArgumentNullException("graphs");
            var serializer = new DataContractSerializer(type);
            serializer.WriteObject(s, graphs);
        }
    }
}


text:
require "rbpath/version"

module RbPath
  autoload :Query, 'rbpath/query'
  autoload :Utils, 'rbpath/utils'
  autoload :ObjectMixin, 'rbpath/object_mixin'
  autoload :ClassMixin,  'rbpath/class_mixin'

  def self.included(klass)
    klass.send(:include, RbPath::ObjectMixin)
    klass.extend RbPath::ClassMixin
  end

  def self.extended(obj)
    obj.singleton_class.send(:include, RbPath::ObjectMixin)
  end
end


text:
<!DOCTYPE html>

    <title>Mapbox Vector Tiles</title>
    <link href="../Build/Cesium/Widgets/widgets.css" rel="stylesheet">


text:
require 'json'
require_relative '../../spec_helper'

describe Desk::Api::Customers do

  before { @connection = Minitest::Mock.new }

  subject { Desk::Api::Customers.new(@connection) }

  describe "#all" do

    before { @connection.expect(:get, customers_fixture, ["customers"]) }

    it "will connect to the customers endpoint" do
      subject.all
    end

    it "will return an array of customers" do
      result = subject.all

      assert result.is_a? Array
      assert result.first.is_a? Desk::Customer
    end
  end

  describe "#show" do

    before { @connection.expect(:get, customer_fixture, ["customers/1234"]) }

    it "will connect to the customer show endpoint" do
      subject.show(1234)

      @connection.verify
    end

    it "will return a single customer object" do
      result = subject.show(1234)

      assert result.is_a? Desk::Customer
    end
  end

  describe "#create" do

    before do
      @data = {
          first_name: "Johnny",
          last_name: "Bravo",
          emails: [
              {
                  type: "work",
                  value: "johnny@acme.com"
              },
              {
                  type: "other",
                  value: "johnny@other.com"
              }
          ]
      }

      @connection.expect(:post, customer_fixture, ["customers", @data])
    end

    it "will connect to the customer creation endpoint" do
      subject.create(@data)

      @connection.verify
    end
  end

  describe "#update" do
    before do
      @data = {
                first_name: "Johnny",
                  emails: [
                    {
                      type: "work",
                      value: "johnny@acme.com"
                    },
                    {
                        type: "other",
                        value: "johnny@other.com"
                    }
                  ]
              }

      @connection.expect(:patch, customer_fixture, ["customers/1234", @data])
    end

    it "will connect to the customer update endpoint" do
      subject.update(1234, @data)

      @connection.verify
    end
  end

  describe "#search" do

    it "will connect to the customer search endpoint" do
      @connection.expect(:get, customers_fixture, ["customers/search", {first_name: "Johnny"}])

      subject.search(first_name: "Johnny")

      @connection.verify
    end

    it "will pass last name into the search query" do
      @connection.expect(:get, customers_fixture, ["customers/search", {first_name: "Johhny", last_name: "Bravo"}])

      subject.search(first_name: "Johhny", last_name: "Bravo")

      @connection.verify
    end

  end

  def customers_fixture
    JSON.load(fixture("customers.json"))
  end

  def customer_fixture
    JSON.load(fixture("customer.json"))
  end
end


text:
#pragma once
#include<system_error>

namespace websocket
{
    enum class error;
    enum class condition;
}

namespace std {
    template<>
    struct is_error_code_enum<websocket::error>
    {
        static bool const value = true;
    };
    template<>
    struct is_error_condition_enum<websocket::condition>
    {
        static bool const value = true;
    };
} // std

namespace websocket
{
    enum class error
    {
        buffer_overflow = 800000,
        read_message_too_big,//The socket message exceeded the locally configured limit
        write_message_too_big,//The socket message exceeded the locally configured limit
        read_timeout, //socket read time out
        send_queue_too_big, // send message queue size exceeded config.h configured limit
        ws_bad_http_header,// websocket parse http header failed
        ws_bad_http_version,// The WebSocket handshake was not HTTP/1.1
        ws_bad_method,//The WebSocket handshake method was not GET
        ws_bad_http_status_code,//The WebSocket handshake http status code was not 101
        ws_no_host,//The WebSocket handshake Host field is missing
        ws_no_connection,//The WebSocket handshake Connection field is missing
        ws_no_connection_upgrade,//The WebSocket handshake Connection field is missing the upgrade token
        ws_no_upgrade,//The WebSocket handshake Upgrade field is missing
        ws_no_upgrade_websocket,//The WebSocket handshake Upgrade field is missing the websocket token
        ws_no_sec_key,//The WebSocket handshake Sec-WebSocket-Key field is missing
        ws_bad_sec_key,//The WebSocket handshake Sec-WebSocket-Key field is invalid
        ws_no_sec_version,//The WebSocket handshake Sec-WebSocket-Version field is missing
        ws_bad_sec_version,//The WebSocket handshake Sec-WebSocket-Version field is invalid
        ws_no_sec_accept,//The WebSocket handshake Sec-WebSocket-Accept field is missing
        ws_bad_sec_accept,//The WebSocket handshake Sec-WebSocket-Accept field is invalid
        ws_bad_opcode,//The WebSocket frame contained an illegal opcode
        ws_bad_data_frame,//The WebSocket data frame was unexpected
        ws_bad_continuation,//The WebSocket continuation frame was unexpected
        ws_bad_reserved_bits,//The WebSocket frame contained illegal reserved bits
        ws_bad_control_fragment,//The WebSocket control frame was fragmented
        ws_bad_control_size,//The WebSocket control frame size was invalid
        ws_bad_unmasked_frame,//The WebSocket frame was unmasked
        ws_bad_masked_frame,//The WebSocket frame was masked
        ws_bad_size,//The WebSocket frame size was not canonical
        bad_frame_payload,//The WebSocket frame payload was not valid utf8
        ws_closed,//The WebSocket receive close frame
        ws_complete_frame,//The WebSocket receive a complete frame
    };

    /// Error conditions corresponding to sets of error codes.
    enum class condition
    {
        /** The WebSocket handshake failed

            This condition indicates that the WebSocket handshake failed. If
            the corresponding HTTP response indicates the keep-alive behavior,
            then the handshake may be reattempted.
        */
        ws_handshake_failed = 1,

        /** A WebSocket protocol violation occurred

            This condition indicates that the remote peer on the WebSocket
            connection sent data which violated the protocol.
        */
        ws_protocol_violation
    };

    namespace detail
    {
        class error_codes : public std::error_category
        {
        public:
            const char* name() const noexcept override
            {
                return "websocket";
            }

            std::string message(int ev) const override
            {
                switch (static_cast<error>(ev))
                {
                default:
                case error::buffer_overflow: return "The websocket handshake buffer exceeded configured limit";
                case error::read_message_too_big:  return "The socket read message  exceeded the locally configured limit";
                case error::write_message_too_big: return "The socket write message  exceeded the locally configured limit";
                case error::read_timeout:  return "Socket read timeout";
                case error::send_queue_too_big: return "The socket send message queue size exceeded configured(config.hpp) limit";
                case error::ws_bad_http_header: return "Websocket parse http header failed";
                case error::ws_bad_http_version: return "The WebSocket handshake was not HTTP/1.1";
                case error::ws_bad_method: return "The WebSocket handshake method was not GET";
                case error::ws_bad_http_status_code: return "The WebSocket handshake http status code was not 101";
                case error::ws_no_host: return "The WebSocket handshake Host field is missing";
                case error::ws_no_connection: return "The WebSocket handshake Connection field is missing";
                case error::ws_no_connection_upgrade:  return "The WebSocket handshake Connection field is missing the upgrade token";
                case error::ws_no_upgrade: return "The WebSocket handshake Upgrade field is missing";
                case error::ws_no_upgrade_websocket:   return "The WebSocket handshake Upgrade field is missing the websocket token";
                case error::ws_no_sec_key: return "The WebSocket handshake Sec-WebSocket-Key field is missing";
                case error::ws_bad_sec_key: return "The WebSocket handshake Sec-WebSocket-Key field is invalid";
                case error::ws_no_sec_version: return "The WebSocket handshake Sec-WebSocket-Version field is missing";
                case error::ws_bad_sec_version: return "The WebSocket handshake Sec-WebSocket-Version field is invalid";
                case error::ws_no_sec_accept: return "The WebSocket handshake Sec-WebSocket-Accept field is missing";
                case error::ws_bad_sec_accept: return "The WebSocket handshake Sec-WebSocket-Accept field is invalid";

                case error::ws_bad_opcode: return "The WebSocket frame contained an illegal opcode";
                case error::ws_bad_data_frame: return "The WebSocket data frame was unexpected";
                case error::ws_bad_continuation: return "The WebSocket continuation frame was unexpected";
                case error::ws_bad_reserved_bits: return "The WebSocket frame contained illegal reserved bits";
                case error::ws_bad_control_fragment: return "The WebSocket control frame was fragmented";
                case error::ws_bad_control_size: return "The WebSocket control frame size was invalid";
                case error::ws_bad_unmasked_frame: return "The WebSocket frame was unmasked";
                case error::ws_bad_masked_frame: return "The WebSocket frame was masked";
                case error::ws_bad_size: return "The WebSocket frame size was not canonical";
                case error::bad_frame_payload: return "The WebSocket frame payload was not valid utf8";
                case error::ws_closed: return "The WebSocket receive close frame";
                }
            }

            std::error_condition default_error_condition(int ev) const noexcept override
            {
                switch (static_cast<error>(ev))
                {
                default:
                case error::buffer_overflow:
                case error::read_message_too_big:
                case error::write_message_too_big:
                case error::read_timeout:
                case error::send_queue_too_big:
                    return { ev, *this };
                case error::ws_bad_http_version:
                case error::ws_bad_method:
                case error::ws_no_host:
                case error::ws_no_connection:
                case error::ws_no_connection_upgrade:
                case error::ws_no_upgrade:
                case error::ws_no_upgrade_websocket:
                case error::ws_no_sec_key:
                case error::ws_bad_sec_key:
                case error::ws_no_sec_version:
                case error::ws_bad_sec_version:
                case error::ws_no_sec_accept:
                case error::ws_bad_sec_accept:
                    return condition::ws_handshake_failed;
                case error::ws_bad_opcode:
                case error::ws_bad_data_frame:
                case error::ws_bad_continuation:
                case error::ws_bad_reserved_bits:
                case error::ws_bad_control_fragment:
                case error::ws_bad_control_size:
                case error::ws_bad_unmasked_frame:
                case error::ws_bad_masked_frame:
                case error::ws_bad_size:
                case error::bad_frame_payload:
                    return condition::ws_protocol_violation;
                }
            }
        };

        class error_conditions : public std::error_category
        {
        public:
            const char* name() const noexcept override
            {
                return "websocket";
            }

            std::string message(int cv) const override
            {
                switch (static_cast<condition>(cv))
                {
                default:
                case condition::ws_handshake_failed: return "The WebSocket handshake failed";
                case condition::ws_protocol_violation: return "A WebSocket protocol violation occurred";
                }
            }
        };
    }

    inline std::error_code
        make_error_code(error e)
    {
        static detail::error_codes const cat{};
        return std::error_code{ static_cast<
            std::underlying_type<error>::type>(e), cat };
    }

    inline std::error_condition
        make_error_condition(condition c)
    {
        static detail::error_conditions const cat{};
        return std::error_condition{ static_cast<
            std::underlying_type<condition>::type>(c), cat };
    }
}


text:
require 'spec_helper'

describe 'validate_domain_name' do
  describe 'signature validation' do
    it { is_expected.not_to eq(nil) }
    it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) }
  end

  describe 'valid inputs' do
    it { is_expected.to run.with_params('com', 'com.') }
    it { is_expected.to run.with_params('x.com', 'x.com.') }
    it { is_expected.to run.with_params('foo.example.com', 'foo.example.com.') }
    it { is_expected.to run.with_params('2foo.example.com', '2foo.example.com.') }
    it { is_expected.to run.with_params('www.2foo.example.com', 'www.2foo.example.com.') }
    it { is_expected.to run.with_params('domain.tld', 'puppet.com') }
  end

  describe 'invalid inputs' do
    it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, %r{is not a string}) }
    it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{is not a string}) }
    it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{is not a string}) }
    it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{is not a string}) }

    it { is_expected.to run.with_params('foo.example.com', []).and_raise_error(Puppet::ParseError, %r{is not a string}) }
    it { is_expected.to run.with_params('foo.example.com', {}).and_raise_error(Puppet::ParseError, %r{is not a string}) }
    it { is_expected.to run.with_params('foo.example.com', 1).and_raise_error(Puppet::ParseError, %r{is not a string}) }
    it { is_expected.to run.with_params('foo.example.com', true).and_raise_error(Puppet::ParseError, %r{is not a string}) }

    it { is_expected.to run.with_params('').and_raise_error(Puppet::ParseError, %r{is not a syntactically correct domain name}) }
    it { is_expected.to run.with_params('invalid domain').and_raise_error(Puppet::ParseError, %r{is not a syntactically correct domain name}) }
    it { is_expected.to run.with_params('-foo.example.com').and_raise_error(Puppet::ParseError, %r{is not a syntactically correct domain name}) }
    it { is_expected.to run.with_params('www.example.2com').and_raise_error(Puppet::ParseError, %r{is not a syntactically correct domain name}) }
    it { is_expected.to run.with_params('192.168.1.1').and_raise_error(Puppet::ParseError, %r{is not a syntactically correct domain name}) }
  end
end


text:
/*
 * Created on Jul 15, 2004
 */
package org.jkiss.dbeaver.ext.erd.policy;

import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.editpolicies.ComponentEditPolicy;
import org.eclipse.gef.requests.GroupRequest;
import org.jkiss.dbeaver.ext.erd.command.EntityDeleteCommand;
import org.jkiss.dbeaver.ext.erd.model.EntityDiagram;
import org.jkiss.dbeaver.ext.erd.part.EntityPart;

/**
 * Handles deletion of tables
 * @author Serge Rider
 */
public class EntityEditPolicy extends ComponentEditPolicy
{

	@Override
    protected Command createDeleteCommand(GroupRequest request)
	{
		EntityPart entityPart = (EntityPart) getHost();
		Rectangle bounds = entityPart.getFigure().getBounds().getCopy();
		EntityDiagram parent = (EntityDiagram) (entityPart.getParent().getModel());
		return new EntityDeleteCommand(parent, entityPart, bounds);
	}

}


text:
module RubyToBlock
  module Block
    # キャラクターのメソッドや属性に共通するメソッドや定数を定義するモジュール
    module CharacterOperation
      extend ActiveSupport::Concern

      CHAR_NAME_RE = '([a-z]\S*)'
      CHAR_RE = '(?:' + CHAR_NAME_RE + '\.)?'

      attr_accessor :character

      module ClassMethods
        # コンテキストからキャラクターを取得する
        #
        # キャラクターの名前がnil、または'self'の場合はコンテキストのレシー
        # バの名前を利用する。
        #
        # コンテキストからキャラクターが取得できない場合は例外が発生する。
        #
        # @param [RubyToBlock::Context] context コンテキスト
        # @param [String] name キャラクターの名前
        # @return [Character] キャラクター
        def get_character(context, name)
          name = context.receiver.try(:name) if !name || name == 'self'
          fail unless context.characters.key?(name)
          context.characters[name]
        end

        # 必要であればcharacter_newブロックを作成してから指定したブロッ
        # クをcharacter_newブロックの子供として追加する
        #
        # @param [RubyToBlock::Context] context コンテキスト
        # @param [String] name キャラクターの名前
        # @param [ブロック] block ブロックのインスタンス
        # @return [Array<ブロック, ブロック>]
        #   最初の要素がcharacter_newブロック、次の要素がカレントブロックの配列
        def add_child_or_create_character_new_block(context, name, block)
          character = get_character(context, name)

          block.character = character

          cb = context.current_block
          if cb && cb.type == 'character_new' && cb.character == character
            cb.add_statement(:DO, block)
            [cb, cb]
          elsif character == context.receiver
            cb.sibling = block
            [cb.parent, block]
          else
            character_new =
              create_character_new_block(context, character, block)
            [character_new, character_new]
          end
        end

        # character_newブロックを生成する
        #
        # @param [RubyToBlock::Context] context コンテキスト
        # @param [RubyToBlock::Block::Character] character キャラクター
        # @param [RubyToBlock::Block::Baseのサブクラス] block ブロック
        # @return [RubyToBlock::Block::CharacterNew] character_newブロック
        def create_character_new_block(context, character, block)
          character_new_block = Block.new('character_new',
                                          fields: { NAME: character.name },
                                          statements: { DO: block })
          character_new_block.character = character

          cb = context.current_block
          if cb && cb.type != 'character_new'
            cb.sibling = character_new_block
          else
            context.blocks.push(character_new_block)
          end

          character_new_block
        end
      end
    end
  end
end


text:
/// <reference path="api.d.ts" />
module API.Client {
    'use strict';
    /**
     * An analyzer examines the text of fields and generates a token stream.
     */
    export interface Analyzer {
        /**
         * Name of the analyzer
         */
        analyzerName: string;
        tokenizer: Tokenizer;
        /**
         *
         */
        filters?: Array<Filter>;
    }
}