text:
package org.gearvrf;

import org.gearvrf.utility.Log;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.channels.IllegalBlockingModeException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Describes a set of vertices used by an indexed triangle mesh.
 *

 * Usually each vertex may have a position, normal and texture coordinate.
 * Skinned mesh vertices will also have bone weights and indices.
 * If the mesh uses a normal map for lighting, it will have tangents
 * and bitangents as well. These vertex components correspond to vertex
 * attributes in the OpenGL vertex shader.
 * Multiple meshes may share a single vertex buffer.
 *

 * When a vertex buffer is constructed, a string descriptor is
 * supplied which describes the format of the vertices (the name and
 * type of each vertex component). Once the format has been established,
 * it cannot be subsequently changed - you cannot add new vertex
 * components. You can change the vertex or index buffer associated
 * with a mesh at any time.
 *

 * Skinned meshes have bone weights and bone indices which designate
 * which bones affect each vertex and how much. The bones are supplied
 * as a list of {@link GVRBone} objects which have the name of the bone
 * and its associated matrices. The asset loader handles constructing
 * skinned meshes and their associated bones. GearVRF keeps the bones
 * for each mesh in a uniform buffer and skinning is performed by\
 * shaders on the GPU.
 * @see GVRMesh
 * @see GVRIndexBuffer
 * @see GVRBone
 * @see GVRAssetLoader
 */
public class GVRVertexBuffer extends GVRHybridObject implements PrettyPrint
{
    private static final String TAG = GVRVertexBuffer.class.getSimpleName();
    private String mDescriptor;

    /**
     * Construct a vertex buffer with the specified vertex layout.
     * @param gvrContext  GVRContext to associate vertex buffer with.
     * @param descriptor  string describing vertex layout.
     *                    Each vertex component has a name and a type.
     *                    The types may be "int", "float" or "mat"
     *                    followed by an integer indicating vector size.
     * @param vertexCount number of vertices in the buffer.
     *                    The vertex count cannot be changed once the
     *                    vertex buffer is constructed.
     * Vertex Descriptor Examples:
     *

     *
float3 a_position float2 a_texcoord float3 a_normal

     *
float3 a_position, int4 a_bone_indices, float4 a_bone_weights

     *

     */
    public GVRVertexBuffer(GVRContext gvrContext, String descriptor, int vertexCount)
    {
        super(gvrContext, NativeVertexBuffer.ctor(descriptor, vertexCount));
        mDescriptor = descriptor;
    }

    /**
     * Clone an existing vertex buffer with a specified layout.
     *

     * The vertex attribute data in the source vertex buffer is copied
     * into the new vertex buffer if that attribute is present in the descriptor.
     * Attributes in the descriptor but not in the source vertex buffer
     * remain uninitialized.
     * @param srcVerts    GVRVertexBuffer to clone.
     * @param descriptor  string describing vertex layout of new vertex buffer.
     *                    Each vertex component has a name and a type.
     *                    The types may be "int", "float" or "mat"
     *                    followed by an integer indicating vector size.
     * Vertex Descriptor Examples:
     *

     *
float3 a_position float2 a_texcoord float3 a_normal

     *
float3 a_position, int4 a_bone_indices, float4 a_bone_weights

     *

     */
    public GVRVertexBuffer(GVRVertexBuffer srcVerts, String descriptor)
    {
        super(srcVerts.getGVRContext(), NativeVertexBuffer.ctor(descriptor, srcVerts.getVertexCount()));
        Pattern pattern = Pattern.compile("([a-zA-Z0-9]+)[ \t]+([a-zA-Z0-9_]+)[^ ]*");
        final String srcDesc = srcVerts.getDescriptor();

        Matcher matcher = pattern.matcher(srcDesc);
        mDescriptor = descriptor;

        while (matcher.find())
        {
            String srcName = matcher.group(2);
            String srcType = matcher.group(1).toLowerCase();

            if (descriptor.contains(srcName))
            {
                if (srcType.charAt(0) == 'i')
                {
                    final int[] tempArray = srcVerts.getIntArray(srcName);
                    setIntArray(srcName, tempArray);
                }
                else
                {
                    final float[] tempArray = srcVerts.getFloatArray(srcName);
                    setFloatArray(srcName, tempArray);
                }
            }
        }
    }

    /**
     * Check if a vertex attribute is present in this buffer'
     * and has data.
     * @param attributeName name of vertex attribute
     * @return true if this vertex buffer has been populated with data.
     */
    public boolean hasAttribute(String attributeName)
    {
        return NativeVertexBuffer.isSet(getNative(), attributeName);
    }

    /**
     * Retrieves a vertex attribute as a float buffer.
     * The attribute name must be one of the
     * attributes named in the descriptor passed to the constructor.
     * @param attributeName name of the attribute to update
     * @throws IllegalArgumentException if attribute name not in descriptor vertex attribute is not float
     * @see #setFloatArray(String, float[])
     * @see #getFloatVec(String)
     */
    public FloatBuffer getFloatVec(String attributeName)
    {
        int size = getAttributeSize(attributeName);
        if (size <= 0)
        {
            return null;
        }
        size *= 4 * getVertexCount();
        ByteBuffer buffer = ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder());
        FloatBuffer data = buffer.asFloatBuffer();
        if (!NativeVertexBuffer.getFloatVec(getNative(), attributeName, data, 0, 0))
        {
            throw new IllegalArgumentException("Attribute name " + attributeName + " cannot be accessed");
        }
        return data;
    }

    /**
     * Retrieves a vertex attribute as a float array.
     * The attribute name must be one of the
     * attributes named in the descriptor passed to the constructor.
     * @param attributeName name of the attribute to update
     * @throws IllegalArgumentException if attribute name not in descriptor vertex attribute is not float
     * @see #setFloatVec(String, FloatBuffer)
     * @see #getFloatArray(String)
     */
    public float[] getFloatArray(String attributeName)
    {
        float[] array = NativeVertexBuffer.getFloatArray(getNative(), attributeName);
        if (array == null)
        {
            throw new IllegalArgumentException("Attribute name " + attributeName + " cannot be accessed");
        }
        return array;
    }

    /**
     * Retrieves a vertex attribute as an integer buffer.
     * The attribute name must be one of the
     * attributes named in the descriptor passed to the constructor.
     * @param attributeName name of the attribute to update
     * @throws IllegalArgumentException if attribute name not in descriptor vertex attribute is not int
     * @see #setIntArray(String, int[])
     * @see #getIntVec(String)
     */
    public IntBuffer getIntVec(String attributeName)
    {
        int size = getAttributeSize(attributeName);
        if (size <= 0)
        {
            return null;
        }
        size *= 4 * getVertexCount();
        ByteBuffer buffer = ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder());
        IntBuffer data = buffer.asIntBuffer();
        if (!NativeVertexBuffer.getIntVec(getNative(), attributeName, data, 0, 0))
        {
            throw new IllegalArgumentException("Attribute name " + attributeName + " cannot be accessed");
        }
        return data;
    }

    /**
     * Retrieves a vertex attribute as an integer array.
     * The attribute name must be one of the
     * attributes named in the descriptor passed to the constructor.
     * @param attributeName name of the attribute to update
     * @throws IllegalArgumentException if attribute name not in descriptor vertex attribute is not int
     * @see #setIntVec(String, IntBuffer)
     * @see #getIntArray(String)
     */
    public int[] getIntArray(String attributeName)
    {
        int[] array = NativeVertexBuffer.getIntArray(getNative(), attributeName);
        if (array == null)
        {
            throw new IllegalArgumentException("Attribute name " + attributeName + " cannot be accessed");
        }
        return array;
    }

    /**
     * Updates a vertex attribute from an integer array.
     * All of the entries of the input integer array are copied into
     * the storage for the named vertex attribute. Other vertex
     * attributes are not affected.
     * The attribute name must be one of the attributes named
     * in the descriptor passed to the constructor.
     *

     * All vertex attributes have the same number of entries.
     * If this is the first attribute added to the vertex buffer,
     * the size of the input data array will determine the number of vertices.
     * Updating subsequent attributes will fail if the data array
     * size is not consistent. For example, if you create a vertex
     * buffer with descriptor "float3 a_position float2 a_texcoord"
     * and provide an array of 12 floats for "a_position" this will result in
     * a vertex count of 4. The corresponding data array for the
     * "a_texcoord" attribute should contain 8 floats.
     * @param attributeName name of the attribute to update
     * @param data integer array containing the new values
     * @throws IllegalArgumentException if attribute name not in descriptor or int array is wrong size
     */
    public void setIntArray(String attributeName, int[] data)
    {
        if (!NativeVertexBuffer.setIntArray(getNative(), attributeName, data, 0, 0))
        {
            throw new IllegalArgumentException("Attribute name " + attributeName + " cannot be updated");
        }
    }

    /**
     * Updates a vertex attribute from an integer array.
     * All of the entries of the input integer array are copied into
     * the storage for the named vertex attribute. Other vertex
     * attributes are not affected.
     * The attribute name must be one of the attributes named
     * in the descriptor passed to the constructor.
     *

     * All vertex attributes have the same number of entries.
     * If this is the first attribute added to the vertex buffer,
     * the size of the input data array will determine the number of vertices.
     * Updating subsequent attributes will fail if the data array
     * size is not consistent. For example, if you create a vertex
     * buffer with descriptor "float3 a_position float2 a_texcoord"
     * and provide an array of 12 floats for "a_position" this will result in
     * a vertex count of 4. The corresponding data array for the
     * "a_texcoord" attribute should contain 8 floats.
     * @param attributeName name of the attribute to update
     * @param data integer array containing the new values
     * @param stride number of ints in the attribute
     * @param offset offset from start of array of where to start copying source data
     * @throws IllegalArgumentException if attribute name not in descriptor or int array is wrong size
     */
    public void setIntArray(String attributeName, int[] data, int stride, int offset)
    {
        if (!NativeVertexBuffer.setIntArray(getNative(), attributeName, data, stride, offset))
        {
            throw new IllegalArgumentException("Attribute name " + attributeName + " cannot be updated");
        }
    }

    /**
     * Updates a vertex attribute from a float array.
     * All of the entries of the input float array are copied into
     * the storage for the named vertex attribute. Other vertex
     * attributes are not affected.
     * The attribute name must be one of the attributes named
     * in the descriptor passed to the constructor.
     *

     * All vertex attributes have the same number of entries.
     * If this is the first attribute added to the vertex buffer,
     * the size of the input data array will determine the number of vertices.
     * Updating subsequent attributes will fail if the data array
     * size is not consistent. For example, if you create a vertex
     * buffer with descriptor "float3 a_position float2 a_texcoord"
     * and provide an array of 12 floats for "a_position" this will result in
     * a vertex count of 4. The corresponding data array for the
     * "a_texcoord" attribute should contain 8 floats.
     * @param attributeName name of the attribute to update
     * @param data float array containing the new values
     * @throws IllegalArgumentException if attribute name not in descriptor or float array is wrong size
     */
    public void setFloatArray(String attributeName, float[] data)
    {
        if (!NativeVertexBuffer.setFloatArray(getNative(), attributeName, data, 0, 0))
        {
            throw new IllegalArgumentException("Attribute name " + attributeName + " cannot be updated");
        }
    }

    /**
     * Updates a vertex attribute from a float array.
     * All of the entries of the input float array are copied into
     * the storage for the named vertex attribute. Other vertex
     * attributes are not affected.
     * The attribute name must be one of the attributes named
     * in the descriptor passed to the constructor.
     *

     * All vertex attributes have the same number of entries.
     * If this is the first attribute added to the vertex buffer,
     * the size of the input data array will determine the number of vertices.
     * Updating subsequent attributes will fail if the data array
     * size is not consistent. For example, if you create a vertex
     * buffer with descriptor "float3 a_position float2 a_texcoord"
     * and provide an array of 12 floats for "a_position" this will result in
     * a vertex count of 4. The corresponding data array for the
     * "a_texcoord" attribute should contain 8 floats.
     * @param attributeName name of the attribute to update
     * @param data float array containing the new values
     * @param stride number of floats in the attribute
     * @param offset offset from start of array of where to start copying source data
     * @throws IllegalArgumentException if attribute name not in descriptor or float array is wrong size
     */
    public void setFloatArray(String attributeName, float[] data, int stride, int offset)
    {
        if (!NativeVertexBuffer.setFloatArray(getNative(), attributeName, data, stride, offset))
        {
            throw new IllegalArgumentException("Attribute name " + attributeName + " cannot be updated");
        }
    }

    /**
     * Updates a vertex attribute from a float buffer.
     * All of the entries of the input float buffer are copied into
     * the storage for the named vertex attribute. Other vertex
     * attributes are not affected.
     * The attribute name must be one of the attributes named
     * in the descriptor passed to the constructor.
     *

     * All vertex attributes have the same number of entries.
     * If this is the first attribute added to the vertex buffer,
     * the size of the input data buffer will determine the number of vertices.
     * Updating subsequent attributes will fail if the data buffer
     * size is not consistent. For example, if you create a vertex
     * buffer with descriptor "float3 a_position float2 a_texcoord"
     * and provide an data buffer of 12 floats for "a_position" this will result in
     * a vertex count of 4. The corresponding data buffer for the
     * "a_texcoord" attribute should contain 8 floats.
     * @param attributeName name of the attribute to update
     * @param data float buffer containing the new values
     * @throws IllegalArgumentException if attribute name not in descriptor or float buffer is wrong size
     */
    public void setFloatVec(String attributeName, FloatBuffer data)
    {
        if (data.isDirect())
        {
            if (!NativeVertexBuffer.setFloatVec(getNative(), attributeName, data, 0, 0))
            {
                throw new IllegalArgumentException("Attribute name " + attributeName + " cannot be updated");
            }
        }
        else if (data.hasArray())
        {
            if (!NativeVertexBuffer.setFloatArray(getNative(), attributeName, data.array(), 0, 0))
            {
                throw new IllegalArgumentException("Attribute name " + attributeName + " cannot be updated");
            }
        }
        else
        {
            throw new UnsupportedOperationException("FloatBuffer type not supported. must be direct or have backing array");
        }
    }

    /**
     * Updates a vertex attribute from a float buffer.
     * All of the entries of the input float buffer are copied into
     * the storage for the named vertex attribute. Other vertex
     * attributes are not affected.
     * The attribute name must be one of the attributes named
     * in the descriptor passed to the constructor.
     *

     * All vertex attributes have the same number of entries.
     * If this is the first attribute added to the vertex buffer,
     * the size of the input data buffer will determine the number of vertices.
     * Updating subsequent attributes will fail if the data buffer
     * size is not consistent. For example, if you create a vertex
     * buffer with descriptor "float3 a_position float2 a_texcoord"
     * and provide an data buffer of 12 floats for "a_position" this will result in
     * a vertex count of 4. The corresponding data buffer for the
     * "a_texcoord" attribute should contain 8 floats.
     * @param attributeName name of the attribute to update
     * @param data float buffer containing the new values
     * @param stride number of floats in the attribute
     * @param offset offset from start of array of where to start copying source data
     * @throws IllegalArgumentException if attribute name not in descriptor or float buffer is wrong size
     */
    public void setFloatVec(String attributeName, FloatBuffer data, int stride, int offset)
    {
        if (data.isDirect())
        {
            if (!NativeVertexBuffer.setFloatVec(getNative(), attributeName, data, stride, offset))
            {
                throw new IllegalArgumentException("Attribute name " + attributeName + " cannot be updated");
            }
        }
        else if (data.hasArray())
        {
            if (!NativeVertexBuffer.setFloatArray(getNative(), attributeName, data.array(), stride, offset))
            {
                throw new IllegalArgumentException("Attribute name " + attributeName + " cannot be updated");
            }
        }
        else
        {
            throw new UnsupportedOperationException("FloatBuffer type not supported. must be direct or have backing array");
        }
    }

    /**
     * Updates a vertex attribute from an integer  buffer.
     * All of the entries of the input buffer are copied into
     * the storage for the named vertex attribute. Other vertex
     * attributes are not affected.
     * The attribute name must be one of the attributes named
     * in the descriptor passed to the constructor.
     *

     * All vertex attributes have the same number of entries.
     * If this is the first attribute added to the vertex buffer,
     * the size of the input data array will determine the number of vertices.
     * Updating subsequent attributes will fail if the data array
     * size is not consistent. For example, if you create a vertex
     * buffer with descriptor "... float4 a_bone_weights int4 a_bone_indices"
     * and provide an array of 16 ints this will result in
     * a vertex count of 4. The corresponding data array for the
     * "a_bone_indices" attribute should also contain 16 floats.
     * @param attributeName name of the attribute to update
     * @param data IntBuffer containing the new values
     * @throws IllegalArgumentException if attribute name not in descriptor or buffer is wrong size
     */
    public void setIntVec(String attributeName, IntBuffer data)
    {
        if (!NativeVertexBuffer.setIntVec(getNative(), attributeName, data, 0, 0))
        {
            throw new IllegalArgumentException("Attribute name " + attributeName + " cannot be updated");
        }
    }

    /**
     * Updates a vertex attribute from an integer  buffer.
     * All of the entries of the input buffer are copied into
     * the storage for the named vertex attribute. Other vertex
     * attributes are not affected.
     * The attribute name must be one of the attributes named
     * in the descriptor passed to the constructor.
     *

     * All vertex attributes have the same number of entries.
     * If this is the first attribute added to the vertex buffer,
     * the size of the input data array will determine the number of vertices.
     * Updating subsequent attributes will fail if the data array
     * size is not consistent. For example, if you create a vertex
     * buffer with descriptor "... float4 a_bone_weights int4 a_bone_indices"
     * and provide an array of 16 ints this will result in
     * a vertex count of 4. The corresponding data array for the
     * "a_bone_indices" attribute should also contain 16 floats.
     * @param attributeName name of the attribute to update
     * @param data IntBuffer containing the new values
     * @param stride number of ints in the attribute
     * @param offset offset from start of array of where to start copying source data
     * @throws IllegalArgumentException if attribute name not in descriptor or buffer is wrong size
     */
    public void setIntVec(String attributeName, IntBuffer data, int stride, int offset)
    {
        if (!NativeVertexBuffer.setIntVec(getNative(), attributeName, data, stride, offset))
        {
            throw new IllegalArgumentException("Attribute name " + attributeName + " cannot be updated");
        }
    }

    /**
     * Get the number of vertices in this vertex buffer.
     *

     * This value is established when the vertex buffer
     * is constructed and cannot be subsequently changed.
     * If no data has been provided, the vertex count is 0.
     * @return number of vertices in the buffer.
     */
    public int getVertexCount()
    {
        return NativeVertexBuffer.getVertexCount(getNative());
    }

    /**
     * Get the vertex descriptor with the names and types of vertex attributes.
     * The types may be "int", "float" or "mat"
     * followed by an integer indicating vector size.
     *

     * Vertex Descriptor Examples:
     *

     *
float3 a_position float2 a_texcoord float3 a_normal

     *
float3 a_position, int4 a_bone_indices, float4 a_bone_weights

     *

     * @return string descriptor for vertex layout.
     */
    public String getDescriptor()
    {
        return mDescriptor;
    }

    /**
     * Gets the number of floats/ints occupied by a particular attribute.
     * For a uniform block, this is the data area size. For a vertex array,
     * it is the size of the vertex component.
     *
     * @param name attribute name
     * @return number of floats/ints occupied by the attribute or 0 if not found
     */
    public int getAttributeSize(String name)
    {
        return NativeVertexBuffer.getAttributeSize(getNative(), name);
    }

    /**
     * Returns the bounding sphere of the vertices.
     * @param sphere destination array to get bounding sphere.
     *               The first entry is the radius, the next
     *               three are the center.
     * @return radius of bounding sphere or 0.0 if no vertices
     */
    public float getSphereBound(float[] sphere)
    {
        if ((sphere == null) || (sphere.length != 4) ||
            ((NativeVertexBuffer.getBoundingVolume(getNative(), sphere)) < 0))
        {
            throw new IllegalArgumentException("Cannot copy sphere bound into array provided");
        }
        return sphere[0];
    }

    /**
     * Returns the bounding box of the vertices.
     * @param corners destination array to get corners of bounding box.
     *               The first three entries are the minimum X,Y,Z values
     *               and the next three are the maximum X,Y,Z.
     * @return true if bounds are not empty, false if empty (no vertices)
     */
    public boolean getBoxBound(float[] corners)
    {
        int rc;
        if ((corners == null) || (corners.length != 6) ||
            ((rc = NativeVertexBuffer.getBoundingVolume(getNative(), corners)) < 0))
        {
            throw new IllegalArgumentException("Cannot copy box bound into array provided");
        }
        return rc != 0;
    }

    @Override
    public void prettyPrint(StringBuffer sb, int indent) {
        Integer n = getVertexCount();
        sb.append(getDescriptor() + " " + n.toString() + " vertices");
        sb.append(System.lineSeparator());
    }

    public void dump(String attrName) {
        NativeVertexBuffer.dump(getNative(), attrName);
    }
}

class NativeVertexBuffer {
    static native long ctor(String descriptor, int vertexCount);

    static native int getVertexCount(long vbuf);

    static native boolean isSet(long vbuf, String name);

    static native boolean getIntVec(long vbuf, String name, IntBuffer data, int stride, int offset);

    static native boolean setIntVec(long vbuf, String name, IntBuffer data, int stride, int offset);

    static native boolean getFloatVec(long vbuf, String name, FloatBuffer data, int stride, int offset);

    static native float[] getFloatArray(long vbuf, String name);

    static native int[] getIntArray(long vbuf, String name);

    static native boolean setIntArray(long vbuf, String name, int[] data, int stride, int offset);

    static native boolean setFloatVec(long vbuf, String name, FloatBuffer data, int stride, int offset);

    static native boolean setFloatArray(long vbuf, String name, float[] data, int stride, int offset);

    static native int  getAttributeSize(long vbuf, String name);

    static native int getBoundingVolume(long vbuf, float[] bv);

    static native void dump(long vbuf, String attrName);
}


text:
require "json"
require "alephant/logger"
require "rack"

module Alephant
  module Broker
    class Environment
      include Logger
      attr_reader :settings

      def initialize(env)
        @settings = env
      end

      def method
        settings["REQUEST_METHOD"]
      end

      def post?
        settings["REQUEST_METHOD"] == "POST"
      end

      def get?
        settings["REQUEST_METHOD"] == "GET"
      end

      def options?
        settings["REQUEST_METHOD"] == "OPTIONS"
      end

      def query
        settings["QUERY_STRING"] || ""
      end

      def path
        settings["PATH_INFO"]
      end

      def if_none_match
        settings["HTTP_IF_NONE_MATCH"]
      end

      def if_modified_since
        settings["HTTP_IF_MODIFIED_SINCE"]
      end

      def data
        parse(rack_input) if post?
      end

      def options
        Rack::Utils.parse_nested_query query
      end

      private

      def rack_input
        settings["rack.input"].read.tap { settings["rack.input"].rewind }
      end

      def parse(json)
        ::JSON.parse(json)
      rescue ::JSON::ParserError => error
        logger.error(
          method:  'Broker.environment#data',
          message: 'ParserError',
          error: error
        )
        logger.metric "JSONParserError"
        nil
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package com.amazonaws.services.apigateway.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *

 * The GET request to get the usage data of a usage plan in a specified time interval.
 *

 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetUsageRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The Id of the usage plan associated with the usage data.
     *

     */
    private String usagePlanId;
    /**
     *

     * The Id of the API key associated with the resultant usage data.
     *

     */
    private String keyId;
    /**
     *

     * The starting date (e.g., 2016-01-01) of the usage data.
     *

     */
    private String startDate;
    /**
     *

     * The ending date (e.g., 2016-12-31) of the usage data.
     *

     */
    private String endDate;
    /**
     *

     * The current pagination position in the paged result set.
     *

     */
    private String position;
    /**
     *

     * The maximum number of returned results per page.
     *

     */
    private Integer limit;

    /**
     *

     * The Id of the usage plan associated with the usage data.
     *

     *
     * @param usagePlanId
     *        The Id of the usage plan associated with the usage data.
     */

    public void setUsagePlanId(String usagePlanId) {
        this.usagePlanId = usagePlanId;
    }

    /**
     *

     * The Id of the usage plan associated with the usage data.
     *

     *
     * @return The Id of the usage plan associated with the usage data.
     */

    public String getUsagePlanId() {
        return this.usagePlanId;
    }

    /**
     *

     * The Id of the usage plan associated with the usage data.
     *

     *
     * @param usagePlanId
     *        The Id of the usage plan associated with the usage data.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetUsageRequest withUsagePlanId(String usagePlanId) {
        setUsagePlanId(usagePlanId);
        return this;
    }

    /**
     *

     * The Id of the API key associated with the resultant usage data.
     *

     *
     * @param keyId
     *        The Id of the API key associated with the resultant usage data.
     */

    public void setKeyId(String keyId) {
        this.keyId = keyId;
    }

    /**
     *

     * The Id of the API key associated with the resultant usage data.
     *

     *
     * @return The Id of the API key associated with the resultant usage data.
     */

    public String getKeyId() {
        return this.keyId;
    }

    /**
     *

     * The Id of the API key associated with the resultant usage data.
     *

     *
     * @param keyId
     *        The Id of the API key associated with the resultant usage data.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetUsageRequest withKeyId(String keyId) {
        setKeyId(keyId);
        return this;
    }

    /**
     *

     * The starting date (e.g., 2016-01-01) of the usage data.
     *

     *
     * @param startDate
     *        The starting date (e.g., 2016-01-01) of the usage data.
     */

    public void setStartDate(String startDate) {
        this.startDate = startDate;
    }

    /**
     *

     * The starting date (e.g., 2016-01-01) of the usage data.
     *

     *
     * @return The starting date (e.g., 2016-01-01) of the usage data.
     */

    public String getStartDate() {
        return this.startDate;
    }

    /**
     *

     * The starting date (e.g., 2016-01-01) of the usage data.
     *

     *
     * @param startDate
     *        The starting date (e.g., 2016-01-01) of the usage data.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetUsageRequest withStartDate(String startDate) {
        setStartDate(startDate);
        return this;
    }

    /**
     *

     * The ending date (e.g., 2016-12-31) of the usage data.
     *

     *
     * @param endDate
     *        The ending date (e.g., 2016-12-31) of the usage data.
     */

    public void setEndDate(String endDate) {
        this.endDate = endDate;
    }

    /**
     *

     * The ending date (e.g., 2016-12-31) of the usage data.
     *

     *
     * @return The ending date (e.g., 2016-12-31) of the usage data.
     */

    public String getEndDate() {
        return this.endDate;
    }

    /**
     *

     * The ending date (e.g., 2016-12-31) of the usage data.
     *

     *
     * @param endDate
     *        The ending date (e.g., 2016-12-31) of the usage data.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetUsageRequest withEndDate(String endDate) {
        setEndDate(endDate);
        return this;
    }

    /**
     *

     * The current pagination position in the paged result set.
     *

     *
     * @param position
     *        The current pagination position in the paged result set.
     */

    public void setPosition(String position) {
        this.position = position;
    }

    /**
     *

     * The current pagination position in the paged result set.
     *

     *
     * @return The current pagination position in the paged result set.
     */

    public String getPosition() {
        return this.position;
    }

    /**
     *

     * The current pagination position in the paged result set.
     *

     *
     * @param position
     *        The current pagination position in the paged result set.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetUsageRequest withPosition(String position) {
        setPosition(position);
        return this;
    }

    /**
     *

     * The maximum number of returned results per page.
     *

     *
     * @param limit
     *        The maximum number of returned results per page.
     */

    public void setLimit(Integer limit) {
        this.limit = limit;
    }

    /**
     *

     * The maximum number of returned results per page.
     *

     *
     * @return The maximum number of returned results per page.
     */

    public Integer getLimit() {
        return this.limit;
    }

    /**
     *

     * The maximum number of returned results per page.
     *

     *
     * @param limit
     *        The maximum number of returned results per page.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetUsageRequest withLimit(Integer limit) {
        setLimit(limit);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getUsagePlanId() != null)
            sb.append("UsagePlanId: ").append(getUsagePlanId()).append(",");
        if (getKeyId() != null)
            sb.append("KeyId: ").append(getKeyId()).append(",");
        if (getStartDate() != null)
            sb.append("StartDate: ").append(getStartDate()).append(",");
        if (getEndDate() != null)
            sb.append("EndDate: ").append(getEndDate()).append(",");
        if (getPosition() != null)
            sb.append("Position: ").append(getPosition()).append(",");
        if (getLimit() != null)
            sb.append("Limit: ").append(getLimit());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof GetUsageRequest == false)
            return false;
        GetUsageRequest other = (GetUsageRequest) obj;
        if (other.getUsagePlanId() == null ^ this.getUsagePlanId() == null)
            return false;
        if (other.getUsagePlanId() != null && other.getUsagePlanId().equals(this.getUsagePlanId()) == false)
            return false;
        if (other.getKeyId() == null ^ this.getKeyId() == null)
            return false;
        if (other.getKeyId() != null && other.getKeyId().equals(this.getKeyId()) == false)
            return false;
        if (other.getStartDate() == null ^ this.getStartDate() == null)
            return false;
        if (other.getStartDate() != null && other.getStartDate().equals(this.getStartDate()) == false)
            return false;
        if (other.getEndDate() == null ^ this.getEndDate() == null)
            return false;
        if (other.getEndDate() != null && other.getEndDate().equals(this.getEndDate()) == false)
            return false;
        if (other.getPosition() == null ^ this.getPosition() == null)
            return false;
        if (other.getPosition() != null && other.getPosition().equals(this.getPosition()) == false)
            return false;
        if (other.getLimit() == null ^ this.getLimit() == null)
            return false;
        if (other.getLimit() != null && other.getLimit().equals(this.getLimit()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getUsagePlanId() == null) ? 0 : getUsagePlanId().hashCode());
        hashCode = prime * hashCode + ((getKeyId() == null) ? 0 : getKeyId().hashCode());
        hashCode = prime * hashCode + ((getStartDate() == null) ? 0 : getStartDate().hashCode());
        hashCode = prime * hashCode + ((getEndDate() == null) ? 0 : getEndDate().hashCode());
        hashCode = prime * hashCode + ((getPosition() == null) ? 0 : getPosition().hashCode());
        hashCode = prime * hashCode + ((getLimit() == null) ? 0 : getLimit().hashCode());
        return hashCode;
    }

    @Override
    public GetUsageRequest clone() {
        return (GetUsageRequest) super.clone();
    }

}


text:
package org.jetbrains.plugins.scala.lang.psi.types.api.designator

import com.intellij.openapi.project.Project
import com.intellij.psi.{PsiClass, PsiNamedElement}
import org.jetbrains.plugins.scala.extensions.{PsiClassExt, PsiElementExt}
import org.jetbrains.plugins.scala.lang.psi.api.statements.params.ScParameter
import org.jetbrains.plugins.scala.lang.psi.api.statements.{ScTypeAlias, ScTypeAliasDefinition}
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.ScTypedDefinition
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.typedef.ScObject
import org.jetbrains.plugins.scala.lang.psi.types.api.{TypeInTypeSystem, TypeSystem, ValueType}
import org.jetbrains.plugins.scala.lang.psi.types.{ScSubstitutor, ScTypeExt}

import scala.collection.immutable.HashSet

/**
  * @author adkozlov
  */
trait DesignatorOwner extends ValueType with TypeInTypeSystem {
  val element: PsiNamedElement
  override implicit val typeSystem: TypeSystem = element.typeSystem

  val isSingleton = element match {
    case typedDefinition: ScTypedDefinition => typedDefinition.isStable
    case _ => false
  }

  def isStable = isSingleton || element.isInstanceOf[ScObject]

  override def isFinalType = element match {
    case clazz: PsiClass if clazz.isEffectivelyFinal => true
    case _ => false
  }

  private[types] def designatorSingletonType = element match {
    case scObject: ScObject => None
    case parameter: ScParameter if parameter.isStable => parameter.getRealParameterType().toOption
    case definition: ScTypedDefinition if definition.isStable => definition.getType().toOption
    case _ => None
  }

  private[types] def designated(implicit withoutAliases: Boolean): Option[(PsiNamedElement, ScSubstitutor)] = element match {
    case definition: ScTypeAliasDefinition if withoutAliases =>
      definition.aliasedType().toOption.flatMap {
        _.extractDesignated
      }
    case _ => Some(element, ScSubstitutor.empty)
  }

  private[types] def classType(project: Project,
                               visitedAlias: HashSet[ScTypeAlias]): Option[(PsiClass, ScSubstitutor)] = element match {
    case clazz: PsiClass => Some(clazz, ScSubstitutor.empty)
    case definition: ScTypeAliasDefinition if !visitedAlias.contains(definition) =>
      definition.aliasedType.toOption.flatMap {
        _.extractClassType(project, visitedAlias + definition)
      }
    case _ => None
  }
}


text:
This sample shows the use of @Produces and @Consumes annotations for bean conversions.

### How @Produces work

When you need to return a bean from a resource method you can specify @Produces annotation with mime types you need to
support. In this case, at runtime WSO2 MSS framework matches the request's Accept header with the @Produce annotation
and dispatches the correct resource method. Then, when the response is sent, the returned bean will be automatically
serialized to the matched mime type. See the following example.

```java
    @GET
    @Path("/{symbol}")
    @Produces({"application/json", "text/xml"})
    public Response getQuote(@PathParam("symbol") String symbol) {
        Stock stock = stockQuotes.get(symbol);
        return (stock == null) ?
                Response.status(Response.Status.NOT_FOUND).build() :
                Response.status(Response.Status.OK).entity(stock).build();
    }
```

In the above example, if the requests Accept header is application/json, then the Stock bean object will be serialized
as JSON and will be sent as the response. In the same way if the requests Accept header is text/xml, then the bean
will be serialized as XML and will be sent as the respond.

### How @Consumes work

If a request body is JSON or XML, then you can receive a bean for it as shown in the following example.

```java
    @POST
    @Consumes("application/json")
    public void addStock(Stock stock) {
        stockQuotes.put(stock.getSymbol(), stock);
    }
```

In the above example, since @Consumes is set to application/json, if a JSON object that matches to the type of stock
parameter is arrived in the request body, a Stock object will be automatically populated from it and passed to the
resource method.

## How to build the sample
------------------------------------------

From this directory, run

```
mvn clean install
```

## How to run the sample
------------------------------------------

Use following command to run the application
```
java -jar target/stockquote-service-*.jar
```

## How to test the sample
------------------------------------------

Use following cURL commands.
```
curl http://localhost:8080/stockquote/IBM
```


text:
"""Gradient Boosted Regression Trees

This module contains methods for fitting gradient boosted regression trees for
both classification and regression.

The module structure is the following:

- The ``BaseGradientBoosting`` base class implements a common ``fit`` method
  for all the estimators in the module. Regression and classification
  only differ in the concrete ``LossFunction`` used.

- ``GradientBoostingClassifier`` implements gradient boosting for
  classification problems.

- ``GradientBoostingRegressor`` implements gradient boosting for
  regression problems.
"""

# Authors: Peter Prettenhofer, Scott White, Gilles Louppe, Emanuele Olivetti,
#          Arnaud Joly
# License: BSD 3 clause

from __future__ import print_function
from __future__ import division
from abc import ABCMeta, abstractmethod
from warnings import warn
from time import time

import numpy as np

from scipy import stats

from .base import BaseEnsemble
from ..base import BaseEstimator
from ..base import ClassifierMixin
from ..base import RegressorMixin
from ..utils import check_random_state, array2d, check_arrays, column_or_1d
from ..utils.extmath import logsumexp
from ..utils.fixes import unique
from ..externals import six

from ..tree.tree import DecisionTreeRegressor
from ..tree._tree import DTYPE, TREE_LEAF

from ._gradient_boosting import predict_stages
from ._gradient_boosting import predict_stage
from ._gradient_boosting import _random_sample_mask

class QuantileEstimator(BaseEstimator):
    """An estimator predicting the alpha-quantile of the training targets."""
    def __init__(self, alpha=0.9):
        if not 0 < alpha < 1.0:
            raise ValueError("`alpha` must be in (0, 1.0)")
        self.alpha = alpha

    def fit(self, X, y):
        self.quantile = stats.scoreatpercentile(y, self.alpha * 100.0)

    def predict(self, X):
        y = np.empty((X.shape[0], 1), dtype=np.float64)
        y.fill(self.quantile)
        return y

class MeanEstimator(BaseEstimator):
    """An estimator predicting the mean of the training targets."""
    def fit(self, X, y):
        self.mean = np.mean(y)

    def predict(self, X):
        y = np.empty((X.shape[0], 1), dtype=np.float64)
        y.fill(self.mean)
        return y

class LogOddsEstimator(BaseEstimator):
    """An estimator predicting the log odds ratio."""
    def fit(self, X, y):
        n_pos = np.sum(y)
        n_neg = y.shape[0] - n_pos
        if n_neg == 0 or n_pos == 0:
            raise ValueError('y contains non binary labels.')
        self.prior = np.log(n_pos / n_neg)

    def predict(self, X):
        y = np.empty((X.shape[0], 1), dtype=np.float64)
        y.fill(self.prior)
        return y

class PriorProbabilityEstimator(BaseEstimator):
    """An estimator predicting the probability of each
    class in the training data.
    """
    def fit(self, X, y):
        class_counts = np.bincount(y)
        self.priors = class_counts / float(y.shape[0])

    def predict(self, X):
        y = np.empty((X.shape[0], self.priors.shape[0]), dtype=np.float64)
        y[:] = self.priors
        return y

class LossFunction(six.with_metaclass(ABCMeta, object)):
    """Abstract base class for various loss functions.

    Attributes
    ----------
    K : int
        The number of regression trees to be induced;
        1 for regression and binary classification;
        ``n_classes`` for multi-class classification.
    """

    is_multi_class = False

    def __init__(self, n_classes):
        self.K = n_classes

    def init_estimator(self, X, y):
        """Default ``init`` estimator for loss function. """
        raise NotImplementedError()

    @abstractmethod
    def __call__(self, y, pred):
        """Compute the loss of prediction ``pred`` and ``y``. """

    @abstractmethod
    def negative_gradient(self, y, y_pred, **kargs):
        """Compute the negative gradient.

        Parameters
        ---------
        y : np.ndarray, shape=(n,)
            The target labels.
        y_pred : np.ndarray, shape=(n,):
            The predictions.
        """

    def update_terminal_regions(self, tree, X, y, residual, y_pred,
                                sample_mask, learning_rate=1.0, k=0):
        """Update the terminal regions (=leaves) of the given tree and
        updates the current predictions of the model. Traverses tree
        and invokes template method `_update_terminal_region`.

        Parameters
        ----------
        tree : tree.Tree
            The tree object.
        X : np.ndarray, shape=(n, m)
            The data array.
        y : np.ndarray, shape=(n,)
            The target labels.
        residual : np.ndarray, shape=(n,)
            The residuals (usually the negative gradient).
        y_pred : np.ndarray, shape=(n,):
            The predictions.
        """
        # compute leaf for each sample in ``X``.
        terminal_regions = tree.apply(X)

        # mask all which are not in sample mask.
        masked_terminal_regions = terminal_regions.copy()
        masked_terminal_regions[~sample_mask] = -1

        # update each leaf (= perform line search)
        for leaf in np.where(tree.children_left == TREE_LEAF)[0]:
            self._update_terminal_region(tree, masked_terminal_regions,
                                         leaf, X, y, residual,
                                         y_pred[:, k])

        # update predictions (both in-bag and out-of-bag)
        y_pred[:, k] += (learning_rate
                         * tree.value[:, 0, 0].take(terminal_regions, axis=0))

    @abstractmethod
    def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
                                residual, pred):
        """Template method for updating terminal regions (=leaves). """

class RegressionLossFunction(six.with_metaclass(ABCMeta, LossFunction)):
    """Base class for regression loss functions. """

    def __init__(self, n_classes):
        if n_classes != 1:
            raise ValueError("``n_classes`` must be 1 for regression")
        super(RegressionLossFunction, self).__init__(n_classes)

class LeastSquaresError(RegressionLossFunction):
    """Loss function for least squares (LS) estimation.
    Terminal regions need not to be updated for least squares. """
    def init_estimator(self):
        return MeanEstimator()

    def __call__(self, y, pred):
        return np.mean((y - pred.ravel()) ** 2.0)

    def negative_gradient(self, y, pred, **kargs):
        return y - pred.ravel()

    def update_terminal_regions(self, tree, X, y, residual, y_pred,
                                sample_mask, learning_rate=1.0, k=0):
        """Least squares does not need to update terminal regions.

        But it has to update the predictions.
        """
        # update predictions
        y_pred[:, k] += learning_rate * tree.predict(X).ravel()

    def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
                                residual, pred):
        pass

class LeastAbsoluteError(RegressionLossFunction):
    """Loss function for least absolute deviation (LAD) regression. """
    def init_estimator(self):
        return QuantileEstimator(alpha=0.5)

    def __call__(self, y, pred):
        return np.abs(y - pred.ravel()).mean()

    def negative_gradient(self, y, pred, **kargs):
        """1.0 if y - pred > 0.0 else -1.0"""
        pred = pred.ravel()
        return 2.0 * (y - pred > 0.0) - 1.0

    def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
                                residual, pred):
        """LAD updates terminal regions to median estimates. """
        terminal_region = np.where(terminal_regions == leaf)[0]
        tree.value[leaf, 0, 0] = np.median(y.take(terminal_region, axis=0) -
                                           pred.take(terminal_region, axis=0))

class HuberLossFunction(RegressionLossFunction):
    """Loss function for least absolute deviation (LAD) regression. """

    def __init__(self, n_classes, alpha=0.9):
        super(HuberLossFunction, self).__init__(n_classes)
        self.alpha = alpha

    def init_estimator(self):
        return QuantileEstimator(alpha=0.5)

    def __call__(self, y, pred):
        pred = pred.ravel()
        diff = y - pred
        gamma = self.gamma
        gamma_mask = np.abs(diff) <= gamma
        sq_loss = np.sum(0.5 * diff[gamma_mask] ** 2.0)
        lin_loss = np.sum(gamma * (np.abs(diff[~gamma_mask]) - gamma / 2.0))
        return (sq_loss + lin_loss) / y.shape[0]

    def negative_gradient(self, y, pred, **kargs):
        pred = pred.ravel()
        diff = y - pred
        gamma = stats.scoreatpercentile(np.abs(diff), self.alpha * 100)
        gamma_mask = np.abs(diff) <= gamma
        residual = np.zeros((y.shape[0],), dtype=np.float64)
        residual[gamma_mask] = diff[gamma_mask]
        residual[~gamma_mask] = gamma * np.sign(diff[~gamma_mask])
        self.gamma = gamma
        return residual

    def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
                                residual, pred):
        """LAD updates terminal regions to median estimates. """
        terminal_region = np.where(terminal_regions == leaf)[0]
        gamma = self.gamma
        diff = (y.take(terminal_region, axis=0)
                - pred.take(terminal_region, axis=0))
        median = np.median(diff)
        diff_minus_median = diff - median
        tree.value[leaf, 0] = median + np.mean(
            np.sign(diff_minus_median) *
            np.minimum(np.abs(diff_minus_median), gamma))

class QuantileLossFunction(RegressionLossFunction):
    """Loss function for quantile regression.

    Quantile regression allows to estimate the percentiles
    of the conditional distribution of the target.
    """

    def __init__(self, n_classes, alpha=0.9):
        super(QuantileLossFunction, self).__init__(n_classes)
        assert 0 < alpha < 1.0
        self.alpha = alpha
        self.percentile = alpha * 100.0

    def init_estimator(self):
        return QuantileEstimator(self.alpha)

    def __call__(self, y, pred):
        pred = pred.ravel()
        diff = y - pred
        alpha = self.alpha

        mask = y > pred
        return (alpha * diff[mask].sum() +
                (1.0 - alpha) * diff[~mask].sum()) / y.shape[0]

    def negative_gradient(self, y, pred, **kargs):
        alpha = self.alpha
        pred = pred.ravel()
        mask = y > pred
        return (alpha * mask) - ((1.0 - alpha) * ~mask)

    def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
                                residual, pred):
        """LAD updates terminal regions to median estimates. """
        terminal_region = np.where(terminal_regions == leaf)[0]
        diff = (y.take(terminal_region, axis=0)
                - pred.take(terminal_region, axis=0))
        val = stats.scoreatpercentile(diff, self.percentile)
        tree.value[leaf, 0] = val

class BinomialDeviance(LossFunction):
    """Binomial deviance loss function for binary classification.

    Binary classification is a special case; here, we only need to
    fit one tree instead of ``n_classes`` trees.
    """
    def __init__(self, n_classes):
        if n_classes != 2:
            raise ValueError("{0:s} requires 2 classes.".format(
                self.__class__.__name__))
        # we only need to fit one tree for binary clf.
        super(BinomialDeviance, self).__init__(1)

    def init_estimator(self):
        return LogOddsEstimator()

    def __call__(self, y, pred):
        """Compute the deviance (= 2 * negative log-likelihood). """
        # logaddexp(0, v) == log(1.0 + exp(v))
        pred = pred.ravel()
        return -2.0 * np.mean((y * pred) - np.logaddexp(0.0, pred))

    def negative_gradient(self, y, pred, **kargs):
        """Compute the residual (= negative gradient). """
        return y - 1.0 / (1.0 + np.exp(-pred.ravel()))

    def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
                                residual, pred):
        """Make a single Newton-Raphson step.

        our node estimate is given by:

            sum(y - prob) / sum(prob * (1 - prob))

        we take advantage that: y - prob = residual
        """
        terminal_region = np.where(terminal_regions == leaf)[0]
        residual = residual.take(terminal_region, axis=0)
        y = y.take(terminal_region, axis=0)

        numerator = residual.sum()
        denominator = np.sum((y - residual) * (1 - y + residual))

        if denominator == 0.0:
            tree.value[leaf, 0, 0] = 0.0
        else:
            tree.value[leaf, 0, 0] = numerator / denominator

class MultinomialDeviance(LossFunction):
    """Multinomial deviance loss function for multi-class classification.

    For multi-class classification we need to fit ``n_classes`` trees at
    each stage.
    """

    is_multi_class = True

    def __init__(self, n_classes):
        if n_classes < 3:
            raise ValueError("{0:s} requires more than 2 classes.".format(
                self.__class__.__name__))
        super(MultinomialDeviance, self).__init__(n_classes)

    def init_estimator(self):
        return PriorProbabilityEstimator()

    def __call__(self, y, pred):
        # create one-hot label encoding
        Y = np.zeros((y.shape[0], self.K), dtype=np.float64)
        for k in range(self.K):
            Y[:, k] = y == k

        return np.sum(-1 * (Y * pred).sum(axis=1) +
                      logsumexp(pred, axis=1))

    def negative_gradient(self, y, pred, k=0):
        """Compute negative gradient for the ``k``-th class. """
        return y - np.nan_to_num(np.exp(pred[:, k] -
                                        logsumexp(pred, axis=1)))

    def _update_terminal_region(self, tree, terminal_regions, leaf, X, y,
                                residual, pred):
        """Make a single Newton-Raphson step. """
        terminal_region = np.where(terminal_regions == leaf)[0]
        residual = residual.take(terminal_region, axis=0)

        y = y.take(terminal_region, axis=0)

        numerator = residual.sum()
        numerator *= (self.K - 1) / self.K

        denominator = np.sum((y - residual) * (1.0 - y + residual))

        if denominator == 0.0:
            tree.value[leaf, 0, 0] = 0.0
        else:
            tree.value[leaf, 0, 0] = numerator / denominator

LOSS_FUNCTIONS = {'ls': LeastSquaresError,
                  'lad': LeastAbsoluteError,
                  'huber': HuberLossFunction,
                  'quantile': QuantileLossFunction,
                  'bdeviance': BinomialDeviance,
                  'mdeviance': MultinomialDeviance,
                  'deviance': None}  # for both, multinomial and binomial

class BaseGradientBoosting(six.with_metaclass(ABCMeta, BaseEnsemble)):
    """Abstract base class for Gradient Boosting. """

    @abstractmethod
    def __init__(self, loss, learning_rate, n_estimators, min_samples_split,
                 min_samples_leaf, max_depth, init, subsample, max_features,
                 random_state, alpha=0.9, verbose=0):

        self.n_estimators = n_estimators
        self.learning_rate = learning_rate
        self.loss = loss
        self.min_samples_split = min_samples_split
        self.min_samples_leaf = min_samples_leaf
        self.subsample = subsample
        self.max_features = max_features
        self.max_depth = max_depth
        self.init = init
        self.random_state = random_state
        self.alpha = alpha
        self.verbose = verbose
        self.estimators_ = np.empty((0, 0), dtype=np.object)

    def _fit_stage(self, i, X, y, y_pred, sample_mask,
                   random_state):
        """Fit another stage of ``n_classes_`` trees to the boosting model. """
        loss = self.loss_
        original_y = y

        for k in range(loss.K):
            if loss.is_multi_class:
                y = np.array(original_y == k, dtype=np.float64)

            residual = loss.negative_gradient(y, y_pred, k=k)

            # induce regression tree on residuals
            tree = DecisionTreeRegressor(
                criterion="mse",
                max_depth=self.max_depth,
                min_samples_split=self.min_samples_split,
                min_samples_leaf=self.min_samples_leaf,
                max_features=self.max_features,
                random_state=random_state)

            sample_weight = None
            if self.subsample < 1.0:
                sample_weight = sample_mask.astype(np.float64)

            tree.fit(X, residual,
                     sample_weight=sample_weight, check_input=False)

            # update tree leaves
            loss.update_terminal_regions(tree.tree_, X, y, residual, y_pred,
                                         sample_mask, self.learning_rate, k=k)

            # add tree to ensemble
            self.estimators_[i, k] = tree

        return y_pred

    def _check_params(self):
        """Check validity of parameters and raise ValueError if not valid. """
        if self.n_estimators <= 0:
            raise ValueError("n_estimators must be greater than 0")

        if self.learning_rate <= 0.0:
            raise ValueError("learning_rate must be greater than 0")

        if (self.loss not in self._SUPPORTED_LOSS or
            self.loss not in LOSS_FUNCTIONS):
            raise ValueError("Loss '{0:s}' not supported. ".format(self.loss))

        if self.loss in ('mdeviance', 'bdeviance'):
            warn(("Loss '{0:s}' is deprecated as of version 0.14. "
                 "Use 'deviance' instead. ").format(self.loss))

        if self.loss == 'deviance':
            loss_class = (MultinomialDeviance
                          if len(self.classes_) > 2
                          else BinomialDeviance)
        else:
            loss_class = LOSS_FUNCTIONS[self.loss]

        if self.loss in ('huber', 'quantile'):
            self.loss_ = loss_class(self.n_classes_, self.alpha)
        else:
            self.loss_ = loss_class(self.n_classes_)

        if self.subsample <= 0.0 or self.subsample > 1:
            raise ValueError("subsample must be in (0,1]")

        if self.init is not None:
            if (not hasattr(self.init, 'fit')
                    or not hasattr(self.init, 'predict')):
                raise ValueError("init must be valid estimator")
            self.init_ = self.init
        else:
            self.init_ = self.loss_.init_estimator()

        if not (0.0 < self.alpha and self.alpha < 1.0):
            raise ValueError("alpha must be in (0.0, 1.0)")

    def fit(self, X, y):
        """Fit the gradient boosting model.

        Parameters
        ----------
        X : array-like, shape = [n_samples, n_features]
            Training vectors, where n_samples is the number of samples
            and n_features is the number of features.

        y : array-like, shape = [n_samples]
            Target values (integers in classification, real numbers in
            regression)
            For classification, labels must correspond to classes
            ``0, 1, ..., n_classes_-1``

        Returns
        -------
        self : object
            Returns self.
        """
        self._check_params()

        # Check input
        X, = check_arrays(X, dtype=DTYPE, sparse_format="dense",
                          check_ccontiguous=True)
        y = column_or_1d(y, warn=True)
        n_samples, n_features = X.shape
        self.n_features = n_features
        random_state = check_random_state(self.random_state)

        # pull freq used parameters into local scope
        subsample = self.subsample
        loss_ = self.loss_
        do_oob = subsample < 1.0

        # allocate model state data structures
        self.estimators_ = np.empty((self.n_estimators, self.loss_.K),
                                    dtype=np.object)
        self.train_score_ = np.zeros((self.n_estimators,), dtype=np.float64)
        if do_oob:
            self._oob_score_ = np.zeros((self.n_estimators), dtype=np.float64)
            self.oob_improvement_ = np.zeros((self.n_estimators),
                                             dtype=np.float64)

        sample_mask = np.ones((n_samples,), dtype=np.bool)
        n_inbag = max(1, int(subsample * n_samples))

        if self.verbose:
            # header fields and line format str
            header_fields = ['Iter', 'Train Loss']
            verbose_fmt = ['{iter:>10d}', '{train_score:>16.4f}']
            if do_oob:
                header_fields.append('OOB Improve')
                verbose_fmt.append('{oob_impr:>16.4f}')
            header_fields.append('Remaining Time')
            verbose_fmt.append('{remaining_time:>16s}')
            verbose_fmt = ' '.join(verbose_fmt)
            # print the header line
            print(('%10s ' + '%16s ' *
                   (len(header_fields) - 1)) % tuple(header_fields))
            # plot verbose info each time i % verbose_mod == 0
            verbose_mod = 1
            start_time = time()

        # fit initial model
        self.init_.fit(X, y)

        # init predictions
        y_pred = self.init_.predict(X)

        # perform boosting iterations
        for i in range(self.n_estimators):

            # subsampling
            if do_oob:
                sample_mask = _random_sample_mask(n_samples, n_inbag,
                                                  random_state)
                # OOB score before adding this stage
                old_oob_score = loss_(y[~sample_mask],
                                      y_pred[~sample_mask])

            # fit next stage of trees
            y_pred = self._fit_stage(i, X, y, y_pred, sample_mask,
                                     random_state)

            # track deviance (= loss)
            if do_oob:
                self.train_score_[i] = loss_(y[sample_mask],
                                             y_pred[sample_mask])
                self._oob_score_[i] = loss_(y[~sample_mask],
                                            y_pred[~sample_mask])
                self.oob_improvement_[i] = old_oob_score - self._oob_score_[i]
            else:
                # no need to fancy index w/ no subsampling
                self.train_score_[i] = self.loss_(y, y_pred)

            if self.verbose > 0:
                if (i + 1) % verbose_mod == 0:
                    oob_impr = self.oob_improvement_[i] if do_oob else 0
                    remaining_time = ((self.n_estimators - (i + 1)) *
                                      (time() - start_time) / float(i + 1))
                    if remaining_time > 60:
                        remaining_time = '{0:.2f}m'.format(remaining_time / 60.0)
                    else:
                        remaining_time = '{0:.2f}s'.format(remaining_time)
                    print(verbose_fmt.format(iter=i + 1,
                                             train_score=self.train_score_[i],
                                             oob_impr=oob_impr,
                                             remaining_time=remaining_time))
                if self.verbose == 1 and ((i + 1) // (verbose_mod * 10) > 0):
                    # adjust verbose frequency (powers of 10)
                    verbose_mod *= 10

        return self

    def _make_estimator(self, append=True):
        # we don't need _make_estimator
        raise NotImplementedError()

    def _init_decision_function(self, X):
        """Check input and compute prediction of ``init``. """
        if self.estimators_ is None or len(self.estimators_) == 0:
            raise ValueError("Estimator not fitted, call `fit` "
                             "before making predictions`.")
        if X.shape[1] != self.n_features:
            raise ValueError("X.shape[1] should be {0:d}, not {1:d}.".format(
                self.n_features, X.shape[1]))
        score = self.init_.predict(X).astype(np.float64)
        return score

    def decision_function(self, X):
        """Compute the decision function of ``X``.

        Parameters
        ----------
        X : array-like of shape = [n_samples, n_features]
            The input samples.

        Returns
        -------
        score : array, shape = [n_samples, k]
            The decision function of the input samples. Classes are
            ordered by arithmetical order. Regression and binary
            classification are special cases with ``k == 1``,
            otherwise ``k==n_classes``.
        """
        X = array2d(X, dtype=DTYPE, order="C")
        score = self._init_decision_function(X)
        predict_stages(self.estimators_, X, self.learning_rate, score)
        return score

    def staged_decision_function(self, X):
        """Compute decision function of ``X`` for each iteration.

        This method allows monitoring (i.e. determine error on testing set)
        after each stage.

        Parameters
        ----------
        X : array-like of shape = [n_samples, n_features]
            The input samples.

        Returns
        -------
        score : generator of array, shape = [n_samples, k]
            The decision function of the input samples. Classes are
            ordered by arithmetical order. Regression and binary
            classification are special cases with ``k == 1``,
            otherwise ``k==n_classes``.
        """
        X = array2d(X, dtype=DTYPE, order="C")
        score = self._init_decision_function(X)
        for i in range(self.n_estimators):
            predict_stage(self.estimators_, i, X, self.learning_rate, score)
            yield score

    @property
    def feature_importances_(self):
        """Return the feature importances (the higher, the more important the
           feature).

        Returns
        -------
        feature_importances_ : array, shape = [n_features]
        """
        if self.estimators_ is None or len(self.estimators_) == 0:
            raise ValueError("Estimator not fitted, "
                             "call `fit` before `feature_importances_`.")

        total_sum = np.zeros((self.n_features, ), dtype=np.float64)
        for stage in self.estimators_:
            stage_sum = sum(tree.feature_importances_
                            for tree in stage) / len(stage)
            total_sum += stage_sum

        importances = total_sum / len(self.estimators_)
        return importances

    @property
    def oob_score_(self):
        warn("The oob_score_ argument is replaced by oob_improvement_"
             " as of version 0.14 and will be removed in 0.16.",
             DeprecationWarning)
        try:
            return self._oob_score_
        except AttributeError:
            raise ValueError("Estimator not fitted, "
                             "call `fit` before `oob_score_`.")

class GradientBoostingClassifier(BaseGradientBoosting, ClassifierMixin):
    """Gradient Boosting for classification.

    GB builds an additive model in a
    forward stage-wise fashion; it allows for the optimization of
    arbitrary differentiable loss functions. In each stage ``n_classes_``
    regression trees are fit on the negative gradient of the
    binomial or multinomial deviance loss function. Binary classification
    is a special case where only a single regression tree is induced.

    Parameters
    ----------
    loss : {'deviance'}, optional (default='deviance')
        loss function to be optimized. 'deviance' refers to
        deviance (= logistic regression) for classification
        with probabilistic outputs.

    learning_rate : float, optional (default=0.1)
        learning rate shrinks the contribution of each tree by `learning_rate`.
        There is a trade-off between learning_rate and n_estimators.

    n_estimators : int (default=100)
        The number of boosting stages to perform. Gradient boosting
        is fairly robust to over-fitting so a large number usually
        results in better performance.

    max_depth : integer, optional (default=3)
        maximum depth of the individual regression estimators. The maximum
        depth limits the number of nodes in the tree. Tune this parameter
        for best performance; the best value depends on the interaction
        of the input variables.

    min_samples_split : integer, optional (default=2)
        The minimum number of samples required to split an internal node.

    min_samples_leaf : integer, optional (default=1)
        The minimum number of samples required to be at a leaf node.

    subsample : float, optional (default=1.0)
        The fraction of samples to be used for fitting the individual base
        learners. If smaller than 1.0 this results in Stochastic Gradient
        Boosting. `subsample` interacts with the parameter `n_estimators`.
        Choosing `subsample < 1.0` leads to a reduction of variance
        and an increase in bias.

    max_features : int, float, string or None, optional (default="auto")
        The number of features to consider when looking for the best split:
          - If int, then consider `max_features` features at each split.
          - If float, then `max_features` is a percentage and
            `int(max_features * n_features)` features are considered at each
            split.
          - If "auto", then `max_features=sqrt(n_features)`.
          - If "sqrt", then `max_features=sqrt(n_features)`.
          - If "log2", then `max_features=log2(n_features)`.
          - If None, then `max_features=n_features`.

        Choosing `max_features < n_features` leads to a reduction of variance
        and an increase in bias.

    init : BaseEstimator, None, optional (default=None)
        An estimator object that is used to compute the initial
        predictions. ``init`` has to provide ``fit`` and ``predict``.
        If None it uses ``loss.init_estimator``.

    verbose : int, default: 0
        Enable verbose output. If 1 then it prints progress and performance
        once in a while (the more trees the lower the frequency).
        If greater than 1 then it prints progress and performance for every tree.

    Attributes
    ----------
    `feature_importances_` : array, shape = [n_features]
        The feature importances (the higher, the more important the feature).

    `oob_improvement_` : array, shape = [n_estimators]
        The improvement in loss (= deviance) on the out-of-bag samples
        relative to the previous iteration.
        ``oob_improvement_[0]`` is the improvement in
        loss of the first stage over the ``init`` estimator.

    `oob_score_` : array, shape = [n_estimators]
        Score of the training dataset obtained using an out-of-bag estimate.
        The i-th score ``oob_score_[i]`` is the deviance (= loss) of the
        model at iteration ``i`` on the out-of-bag sample.
        Deprecated: use `oob_improvement_` instead.

    `train_score_` : array, shape = [n_estimators]
        The i-th score ``train_score_[i]`` is the deviance (= loss) of the
        model at iteration ``i`` on the in-bag sample.
        If ``subsample == 1`` this is the deviance on the training data.

    `loss_` : LossFunction
        The concrete ``LossFunction`` object.

    `init` : BaseEstimator
        The estimator that provides the initial predictions.
        Set via the ``init`` argument or ``loss.init_estimator``.

    `estimators_`: list of DecisionTreeRegressor
        The collection of fitted sub-estimators.

    See also
    --------
    sklearn.tree.DecisionTreeClassifier, RandomForestClassifier

    References
    ----------
    J. Friedman, Greedy Function Approximation: A Gradient Boosting
    Machine, The Annals of Statistics, Vol. 29, No. 5, 2001.

    J. Friedman, Stochastic Gradient Boosting, 1999

    T. Hastie, R. Tibshirani and J. Friedman.
    Elements of Statistical Learning Ed. 2, Springer, 2009.
    """

    _SUPPORTED_LOSS = ('deviance', 'mdeviance', 'bdeviance')

    def __init__(self, loss='deviance', learning_rate=0.1, n_estimators=100,
                 subsample=1.0, min_samples_split=2, min_samples_leaf=1,
                 max_depth=3, init=None, random_state=None,
                 max_features=None, verbose=0):

        super(GradientBoostingClassifier, self).__init__(
            loss, learning_rate, n_estimators, min_samples_split,
            min_samples_leaf, max_depth, init, subsample, max_features,
            random_state, verbose=verbose)

    def fit(self, X, y):
        """Fit the gradient boosting model.

        Parameters
        ----------
        X : array-like, shape = [n_samples, n_features]
            Training vectors, where n_samples is the number of samples
            and n_features is the number of features.

        y : array-like, shape = [n_samples]
            Target values (integers in classification, real numbers in
            regression)
            For classification, labels must correspond to classes
            ``0, 1, ..., n_classes_-1``

        Returns
        -------
        self : object
            Returns self.
        """
        y = column_or_1d(y, warn=True)
        self.classes_, y = unique(y, return_inverse=True)
        self.n_classes_ = len(self.classes_)

        return super(GradientBoostingClassifier, self).fit(X, y)

    def _score_to_proba(self, score):
        """Compute class probability estimates from decision scores. """
        proba = np.ones((score.shape[0], self.n_classes_), dtype=np.float64)
        if not self.loss_.is_multi_class:
            proba[:, 1] = 1.0 / (1.0 + np.exp(-score.ravel()))
            proba[:, 0] -= proba[:, 1]
        else:
            proba = np.nan_to_num(
                np.exp(score - (logsumexp(score, axis=1)[:, np.newaxis])))
        return proba

    def predict_proba(self, X):
        """Predict class probabilities for X.

        Parameters
        ----------
        X : array-like of shape = [n_samples, n_features]
            The input samples.

        Returns
        -------
        p : array of shape = [n_samples]
            The class probabilities of the input samples. Classes are
            ordered by arithmetical order.
        """
        score = self.decision_function(X)
        return self._score_to_proba(score)

    def staged_predict_proba(self, X):
        """Predict class probabilities at each stage for X.

        This method allows monitoring (i.e. determine error on testing set)
        after each stage.

        Parameters
        ----------
        X : array-like of shape = [n_samples, n_features]
            The input samples.

        Returns
        -------
        y : array of shape = [n_samples]
            The predicted value of the input samples.
        """
        for score in self.staged_decision_function(X):
            yield self._score_to_proba(score)

    def predict(self, X):
        """Predict class for X.

        Parameters
        ----------
        X : array-like of shape = [n_samples, n_features]
            The input samples.

        Returns
        -------
        y : array of shape = [n_samples]
            The predicted classes.
        """
        proba = self.predict_proba(X)
        return self.classes_.take(np.argmax(proba, axis=1), axis=0)

    def staged_predict(self, X):
        """Predict class probabilities at each stage for X.

        This method allows monitoring (i.e. determine error on testing set)
        after each stage.

        Parameters
        ----------
        X : array-like of shape = [n_samples, n_features]
            The input samples.

        Returns
        -------
        y : array of shape = [n_samples]
            The predicted value of the input samples.
        """
        for proba in self.staged_predict_proba(X):
            yield self.classes_.take(np.argmax(proba, axis=1), axis=0)

class GradientBoostingRegressor(BaseGradientBoosting, RegressorMixin):
    """Gradient Boosting for regression.

    GB builds an additive model in a forward stage-wise fashion;
    it allows for the optimization of arbitrary differentiable loss functions.
    In each stage a regression tree is fit on the negative gradient of the
    given loss function.

    Parameters
    ----------
    loss : {'ls', 'lad', 'huber', 'quantile'}, optional (default='ls')
        loss function to be optimized. 'ls' refers to least squares
        regression. 'lad' (least absolute deviation) is a highly robust
        loss function solely based on order information of the input
        variables. 'huber' is a combination of the two. 'quantile'
        allows quantile regression (use `alpha` to specify the quantile).

    learning_rate : float, optional (default=0.1)
        learning rate shrinks the contribution of each tree by `learning_rate`.
        There is a trade-off between learning_rate and n_estimators.

    n_estimators : int (default=100)
        The number of boosting stages to perform. Gradient boosting
        is fairly robust to over-fitting so a large number usually
        results in better performance.

    max_depth : integer, optional (default=3)
        maximum depth of the individual regression estimators. The maximum
        depth limits the number of nodes in the tree. Tune this parameter
        for best performance; the best value depends on the interaction
        of the input variables.

    min_samples_split : integer, optional (default=2)
        The minimum number of samples required to split an internal node.

    min_samples_leaf : integer, optional (default=1)
        The minimum number of samples required to be at a leaf node.

    subsample : float, optional (default=1.0)
        The fraction of samples to be used for fitting the individual base
        learners. If smaller than 1.0 this results in Stochastic Gradient
        Boosting. `subsample` interacts with the parameter `n_estimators`.
        Choosing `subsample < 1.0` leads to a reduction of variance
        and an increase in bias.

    max_features : int, float, string or None, optional (default=None)
        The number of features to consider when looking for the best split:
          - If int, then consider `max_features` features at each split.
          - If float, then `max_features` is a percentage and
            `int(max_features * n_features)` features are considered at each
            split.
          - If "auto", then `max_features=n_features`.
          - If "sqrt", then `max_features=sqrt(n_features)`.
          - If "log2", then `max_features=log2(n_features)`.
          - If None, then `max_features=n_features`.

        Choosing `max_features < n_features` leads to a reduction of variance
        and an increase in bias.

    alpha : float (default=0.9)
        The alpha-quantile of the huber loss function and the quantile
        loss function. Only if ``loss='huber'`` or ``loss='quantile'``.

    init : BaseEstimator, None, optional (default=None)
        An estimator object that is used to compute the initial
        predictions. ``init`` has to provide ``fit`` and ``predict``.
        If None it uses ``loss.init_estimator``.

    verbose : int, default: 0
        Enable verbose output. If 1 then it prints progress and performance
        once in a while (the more trees the lower the frequency).
        If greater than 1 then it prints progress and performance for every tree.

    Attributes
    ----------
    `feature_importances_` : array, shape = [n_features]
        The feature importances (the higher, the more important the feature).

    `oob_improvement_` : array, shape = [n_estimators]
        The improvement in loss (= deviance) on the out-of-bag samples
        relative to the previous iteration.
        ``oob_improvement_[0]`` is the improvement in
        loss of the first stage over the ``init`` estimator.

    `oob_score_` : array, shape = [n_estimators]
        Score of the training dataset obtained using an out-of-bag estimate.
        The i-th score ``oob_score_[i]`` is the deviance (= loss) of the
        model at iteration ``i`` on the out-of-bag sample.
        Deprecated: use `oob_improvement_` instead.

    `train_score_` : array, shape = [n_estimators]
        The i-th score ``train_score_[i]`` is the deviance (= loss) of the
        model at iteration ``i`` on the in-bag sample.
        If ``subsample == 1`` this is the deviance on the training data.

    `loss_` : LossFunction
        The concrete ``LossFunction`` object.

    `init` : BaseEstimator
        The estimator that provides the initial predictions.
        Set via the ``init`` argument or ``loss.init_estimator``.

    `estimators_`: list of DecisionTreeRegressor
        The collection of fitted sub-estimators.

    See also
    --------
    DecisionTreeRegressor, RandomForestRegressor

    References
    ----------
    J. Friedman, Greedy Function Approximation: A Gradient Boosting
    Machine, The Annals of Statistics, Vol. 29, No. 5, 2001.

    J. Friedman, Stochastic Gradient Boosting, 1999

    T. Hastie, R. Tibshirani and J. Friedman.
    Elements of Statistical Learning Ed. 2, Springer, 2009.
    """

    _SUPPORTED_LOSS = ('ls', 'lad', 'huber', 'quantile')

    def __init__(self, loss='ls', learning_rate=0.1, n_estimators=100,
                 subsample=1.0, min_samples_split=2, min_samples_leaf=1,
                 max_depth=3, init=None, random_state=None,
                 max_features=None, alpha=0.9, verbose=0):

        super(GradientBoostingRegressor, self).__init__(
            loss, learning_rate, n_estimators, min_samples_split,
            min_samples_leaf, max_depth, init, subsample, max_features,
            random_state, alpha, verbose)

    def fit(self, X, y):
        """Fit the gradient boosting model.

        Parameters
        ----------
        X : array-like, shape = [n_samples, n_features]
            Training vectors, where n_samples is the number of samples
            and n_features is the number of features.

        y : array-like, shape = [n_samples]
            Target values (integers in classification, real numbers in
            regression)
            For classification, labels must correspond to classes
            ``0, 1, ..., n_classes_-1``

        Returns
        -------
        self : object
            Returns self.
        """
        self.n_classes_ = 1
        return super(GradientBoostingRegressor, self).fit(X, y)

    def predict(self, X):
        """Predict regression target for X.

        Parameters
        ----------
        X : array-like of shape = [n_samples, n_features]
            The input samples.

        Returns
        -------
        y: array of shape = [n_samples]
            The predicted values.
        """
        return self.decision_function(X).ravel()

    def staged_predict(self, X):
        """Predict regression target at each stage for X.

        This method allows monitoring (i.e. determine error on testing set)
        after each stage.

        Parameters
        ----------
        X : array-like of shape = [n_samples, n_features]
            The input samples.

        Returns
        -------
        y : array of shape = [n_samples]
            The predicted value of the input samples.
        """
        for y in self.staged_decision_function(X):
            yield y.ravel()


text:
using namespace std;
using namespace Eigen;
using namespace Drake;
using namespace tinyxml2;

RigidBodySystem::StateVector<double> RigidBodySystem::dynamics(const double& t, const RigidBodySystem::StateVector<double>& x, const RigidBodySystem::InputVector<double>& u) const {
  using namespace std;
  using namespace Eigen;
  eigen_aligned_unordered_map<const RigidBody *, Matrix<double, 6, 1> > f_ext;

  // todo: make kinematics cache once and re-use it (but have to make one per type)
  auto nq = tree->num_positions;
  auto nv = tree->num_velocities;
  auto num_actuators = tree->actuators.size();
  auto q = x.topRows(nq);
  auto v = x.bottomRows(nv);
  auto kinsol = tree->doKinematics(q,v);

  // todo: preallocate the optimization problem and constraints, and simply update them then solve on each function eval.
  // happily, this clunkier version seems fast enough for now
  // the optimization framework should support this (though it has not been tested thoroughly yet)
  OptimizationProblem prog;
  auto const & vdot = prog.addContinuousVariables(nv,"vdot");

  auto H = tree->massMatrix(kinsol);
  Eigen::MatrixXd H_and_neg_JT = H;

  { // loop through rigid body force elements and accumulate f_ext

    // todo: distinguish between AppliedForce and ConstraintForce
    // todo: have AppliedForce output tau (instead of f_ext).  it's more direct, and just as easy to compute.

    int u_index = 0;
    const NullVector<double> force_state;  // todo:  will have to handle this case
    for (auto const & prop : props) {
      RigidBodyFrame* frame = prop->getFrame();
      RigidBody* body = frame->body.get();
      int num_inputs = 1;  // todo: generalize this
      RigidBodyPropellor::InputVector<double> u_i(u.middleRows(u_index,num_inputs));
      // todo: push the frame to body transform into the dynamicsBias method?
      Matrix<double,6,1> f_ext_i = transformSpatialForce(frame->transform_to_body,prop->output(t,force_state,u_i,kinsol));
      if (f_ext.find(body)==f_ext.end()) f_ext[body] = f_ext_i;
      else f_ext[body] = f_ext[body]+f_ext_i;
      u_index += num_inputs;
    }
  }

  VectorXd C = tree->dynamicsBiasTerm(kinsol,f_ext);
  if (num_actuators > 0) C -= tree->B*u.topRows(num_actuators);

  { // apply contact forces
    const bool use_multi_contact = false;
    VectorXd phi;
    Matrix3Xd normal, xA, xB;
    vector<int> bodyA_idx, bodyB_idx;
    if (use_multi_contact)
      tree->potentialCollisions(kinsol,phi,normal,xA,xB,bodyA_idx,bodyB_idx);
    else
      tree->collisionDetect(kinsol,phi,normal,xA,xB,bodyA_idx,bodyB_idx);

    for (int i=0; i<phi.rows(); i++) {
      if (phi(i)<0.0) { // then i have contact
        double mu = 1.0; // todo: make this a parameter

        // todo: move this entire block to a shared an updated "contactJacobian" method in RigidBodyTree
        auto JA = tree->transformPointsJacobian(kinsol, xA.col(i), bodyA_idx[i], 0, false);
        auto JB = tree->transformPointsJacobian(kinsol, xB.col(i), bodyB_idx[i], 0, false);
        Vector3d this_normal = normal.col(i);

        // compute the surface tangent basis
        Vector3d tangent1;
        if (1.0 - this_normal(2) < EPSILON) { // handle the unit-normal case (since it's unit length, just check z)
          tangent1 << 1.0, 0.0, 0.0;
        } else if (1 + this_normal(2) < EPSILON) {
          tangent1 << -1.0, 0.0, 0.0;  //same for the reflected case
        } else {// now the general case
          tangent1 << this_normal(1), -this_normal(0), 0.0;
          tangent1 /= sqrt(this_normal(1)*this_normal(1) + this_normal(0)*this_normal(0));
        }
        Vector3d tangent2 = tangent1.cross(this_normal);
        Matrix3d R;  // rotation into normal coordinates
        R << tangent1, tangent2, this_normal;
        auto J = R*(JA-JB);  // J = [ D1; D2; n ]
        auto relative_velocity = J*v;  // [ tangent1dot; tangent2dot; phidot ]

        if (false) {
          // spring law for normal force:  fA_normal = -k*phi - b*phidot
          // and damping for tangential force:  fA_tangent = -b*tangentdot (bounded by the friction cone)
          double k = 150, b = k / 10;  // todo: put these somewhere better... or make them parameters?
          Vector3d fA;
          fA(2) = -k * phi(i) - b * relative_velocity(2);
          fA.head(2) = -std::min(b, mu*fA(2)/(relative_velocity.head(2).norm()+EPSILON)) * relative_velocity.head(2);  // epsilon to avoid divide by zero

          // equal and opposite: fB = -fA.
          // tau = (R*JA)^T fA + (R*JB)^T fB = J^T fA
          C -= J.transpose()*fA;
        } else { // linear acceleration constraints (more expensive, but less tuning required for robot mass, etc)
          // note: this does not work for the multi-contact case (it overly constrains the motion of the link).  Perhaps if I made them inequality constraints...
          static_assert(!use_multi_contact, "The acceleration contact constraints do not play well with multi-contact");

          // phiddot = -2*alpha*phidot - alpha^2*phi   // critically damped response
          // tangential_velocity_dot = -2*alpha*tangential_velocity
          double alpha = 20;  // todo: put this somewhere better... or make them parameters?
          Vector3d desired_relative_acceleration = -2*alpha*relative_velocity;
          desired_relative_acceleration(2) += -alpha*alpha*phi(i);
          // relative_acceleration = J*vdot + R*(JAdotv - JBdotv) // uses the standard dnormal/dq = 0 assumption

          cout << "phi = " << phi << endl;
          cout << "desired acceleration = " << desired_relative_acceleration.transpose() << endl;
//          cout << "acceleration = " << (J*vdot + R*(JAdotv - JBdotv)).transpose() << endl;

          prog.addContinuousVariables(3,"contact normal force");
          auto JAdotv = tree->transformPointsJacobianDotTimesV(kinsol, xA.col(i).eval(), bodyA_idx[i], 0);
          auto JBdotv = tree->transformPointsJacobianDotTimesV(kinsol, xB.col(i).eval(), bodyB_idx[i], 0);

          prog.addLinearEqualityConstraint(J,desired_relative_acceleration - R*(JAdotv - JBdotv),{vdot});
          H_and_neg_JT.conservativeResize(NoChange,H_and_neg_JT.cols()+3);
          H_and_neg_JT.rightCols(3) = -J.transpose();
        }
      }
    }
  }

  if (tree->getNumPositionConstraints()) {
    int nc = tree->getNumPositionConstraints();
    const double alpha = 5.0;  // 1/time constant of position constraint satisfaction (see my latex rigid body notes)

    prog.addContinuousVariables(nc,"position constraint force");  // don't actually need to use the decision variable reference that would be returned...

    // then compute the constraint force
    auto phi = tree->positionConstraints(kinsol);
    auto J = tree->positionConstraintsJacobian(kinsol,false);
    auto Jdotv = tree->positionConstraintsJacDotTimesV(kinsol);

    // phiddot = -2 alpha phidot - alpha^2 phi  (0 + critically damped stabilization term)
    prog.addLinearEqualityConstraint(J,-(Jdotv + 2*alpha*J*v + alpha*alpha*phi),{vdot});
    H_and_neg_JT.conservativeResize(NoChange,H_and_neg_JT.cols()+J.rows());
    H_and_neg_JT.rightCols(J.rows()) = -J.transpose();
  }

  // add [H,-J^T]*[vdot;f] = -C
  prog.addLinearEqualityConstraint(H_and_neg_JT,-C);

  prog.solve();
  //      prog.printSolution();

  StateVector<double> dot(nq+nv);
  dot << kinsol.transformPositionDotMappingToVelocityMapping(Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>::Identity(nq, nq))*v, vdot.value();
  return dot;
}

DRAKERBSYSTEM_EXPORT RigidBodySystem::StateVector<double> Drake::getInitialState(const RigidBodySystem& sys) {

  VectorXd x0(sys.tree->num_positions + sys.tree->num_velocities);
  default_random_engine generator;
  x0 << sys.tree->getRandomConfiguration(generator), VectorXd::Random(sys.tree->num_velocities);

  if (sys.tree->getNumPositionConstraints()) {
    // todo: move this up to the system level?

    std::vector<RigidBodyLoop,Eigen::aligned_allocator<RigidBodyLoop> > const& loops = sys.tree->loops;

    int nq = sys.tree->num_positions;
    int num_constraints = 2*loops.size();
    RigidBodyConstraint** constraint_array = new RigidBodyConstraint*[num_constraints];

    Matrix<double,7,1> bTbp = Matrix<double,7,1>::Zero();  bTbp(3)=1.0;
    Vector2d tspan; tspan<<-std::numeric_limits<double>::infinity(),std::numeric_limits<double>::infinity();
    Vector3d zero = Vector3d::Zero();
    for (int i=0; i<loops.size(); i++) {
      constraint_array[2*i] = new RelativePositionConstraint(sys.tree.get(), zero, zero, zero, loops[i].frameA->frame_index, loops[i].frameB->frame_index,bTbp,tspan);
      constraint_array[2*i+1] = new RelativePositionConstraint(sys.tree.get(), loops[i].axis, loops[i].axis, loops[i].axis, loops[i].frameA->frame_index, loops[i].frameB->frame_index,bTbp,tspan);
    }

    int info;
    vector<string> infeasible_constraint;
    IKoptions ikoptions(sys.tree.get());

    VectorXd q_guess = x0.topRows(nq);
    VectorXd q(nq);

    inverseKin(sys.tree.get(),q_guess,q_guess,num_constraints,constraint_array,q,info,infeasible_constraint,ikoptions);
    if (info>=10) {
      cout << "INFO = " << info << endl;
      cout << infeasible_constraint.size() << " infeasible constraints:";
      size_t limit = infeasible_constraint.size();
      if (limit>5) { cout << " (only printing first 5)" << endl; limit=5; }
      cout << endl;
      for (int i=0; i<limit; i++)
        cout << infeasible_constraint[i] << endl;
    }
    x0 << q, VectorXd::Zero(sys.tree->num_velocities);

    for (int i=0; i<num_constraints; i++) {
      delete constraint_array[i];
    }
    delete[] constraint_array;
  }
  return x0;
}

RigidBodyPropellor::RigidBodyPropellor(RigidBodySystem *sys, XMLElement *node, std::string name) :
        sys(sys), name(name),
        scale_factor_thrust(1.0), scale_factor_moment(1.0),
        lower_limit(-numeric_limits<double>::infinity()),
        upper_limit(numeric_limits<double>::infinity())
{
  auto tree = sys->getRigidBodyTree();

  XMLElement* parent_node = node->FirstChildElement("parent");
  if (!parent_node) throw runtime_error("propellor " + name + " is missing the parent node");
  frame = allocate_shared<RigidBodyFrame>(aligned_allocator<RigidBodyFrame>(),tree.get(),parent_node,node->FirstChildElement("origin"),name+"Frame");
  tree->addFrame(frame);

  axis << 1.0, 0.0, 0.0;
  XMLElement* axis_node = node->FirstChildElement("axis");
  if (axis_node) {
    parseVectorAttribute(axis_node, "xyz", axis);
    if (axis.norm()<1e-8) throw runtime_error("ERROR: axis is zero.  don't do that");
    axis.normalize();
  }

  parseScalarAttribute(node,"scale_factor_thrust",scale_factor_thrust);
  parseScalarAttribute(node,"scale_factor_moment",scale_factor_moment);
  parseScalarAttribute(node,"lower_limit",lower_limit);
  parseScalarAttribute(node,"upper_limit",upper_limit);

  // todo: parse visual info?
}

void parseForceElement(RigidBodySystem *sys, XMLElement* node) {
  string name = node->Attribute("name");

  if (XMLElement* propellor_node = node->FirstChildElement("propellor")) {
    sys->addForceElement(allocate_shared<RigidBodyPropellor>(Eigen::aligned_allocator<RigidBodyPropellor>(),sys,propellor_node,name));
  }
}

void parseRobot(RigidBodySystem *sys, XMLElement* node)
{
  if (!node->Attribute("name"))
    throw runtime_error("Error: your robot must have a name attribute");
  string robotname = node->Attribute("name");

  // parse force elements
  for (XMLElement* force_node = node->FirstChildElement("force_element"); force_node; force_node = force_node->NextSiblingElement("force_element"))
    parseForceElement(sys, force_node);
}

void parseURDF(RigidBodySystem *sys, XMLDocument *xml_doc)
{
  XMLElement *node = xml_doc->FirstChildElement("robot");
  if (!node) throw std::runtime_error("ERROR: This urdf does not contain a robot tag");

  parseRobot(sys, node);
}

void RigidBodySystem::addRobotFromURDFString(const string &xml_string, const string &root_dir, const DrakeJoint::FloatingBaseType floating_base_type)
{
  // first add the urdf to the rigid body tree
  tree->addRobotFromURDFString(xml_string, root_dir, floating_base_type);

  // now parse additional tags understood by rigid body system (actuators, sensors, etc)
  XMLDocument xml_doc;
  xml_doc.Parse(xml_string.c_str());
  parseURDF(this,&xml_doc);
}

void RigidBodySystem::addRobotFromURDF(const string &urdf_filename, const DrakeJoint::FloatingBaseType floating_base_type)
{
  // first add the urdf to the rigid body tree
  tree->addRobotFromURDF(urdf_filename, floating_base_type);

  // now parse additional tags understood by rigid body system (actuators, sensors, etc)
  XMLDocument xml_doc;
  xml_doc.LoadFile(urdf_filename.data());
  if (xml_doc.ErrorID() != XML_SUCCESS) {
    throw std::runtime_error("failed to parse xml in file " + urdf_filename + "\n" + xml_doc.ErrorName());
  }
  parseURDF(this,&xml_doc);
}