text:
#include "libkml_headers.h"

#include <ogr_geometry.h>
#include "ogr_p.h"

using kmldom::KmlFactory;
using kmldom::CoordinatesPtr;
using kmldom::PointPtr;
using kmldom::LatLonBoxPtr;
using kmldom::LineStringPtr;
using kmldom::LinearRingPtr;
using kmldom::OuterBoundaryIsPtr;
using kmldom::InnerBoundaryIsPtr;
using kmldom::PolygonPtr;
using kmldom::MultiGeometryPtr;
using kmldom::GeometryPtr;
using kmldom::ElementPtr;
using kmldom::GeometryPtr;
using kmldom::GxLatLonQuadPtr;
using kmldom::GxTrackPtr;
using kmldom::GxMultiTrackPtr;

using kmlbase::Vec3;

#include "ogrlibkmlgeometry.h"

/******************************************************************************
 function to write out a ogr geometry to kml

args:
          poOgrGeom     the ogr geometry
          extra         used in recursion, just pass -1
          poKmlFactory  pointer to the libkml dom factory

returns:
          ElementPtr to the geometry created

******************************************************************************/

ElementPtr geom2kml (
    OGRGeometry * poOgrGeom,
    int extra,
    KmlFactory * poKmlFactory )
{
    int i;

    if ( !poOgrGeom ) {
        return NULL;
    }

    /***** ogr geom vars *****/

    OGRPoint *poOgrPoint = NULL;
    OGRLineString *poOgrLineString;
    OGRPolygon *poOgrPolygon;
    OGRGeometryCollection *poOgrMultiGeom;

    /***** libkml geom vars *****/

    CoordinatesPtr coordinates;
    PointPtr poKmlPoint;
    LineStringPtr poKmlLineString;
    LinearRingPtr poKmlLinearRing;
    OuterBoundaryIsPtr poKmlOuterRing;
    InnerBoundaryIsPtr poKmlInnerRing;
    PolygonPtr poKmlPolygon;
    MultiGeometryPtr poKmlMultiGeometry;

    ElementPtr poKmlGeometry;
    ElementPtr poKmlTmpGeometry;

    /***** other vars *****/

    double x,
        y,
        z;

    int numpoints = 0;
    int nGeom;
    OGRwkbGeometryType type = poOgrGeom->getGeometryType (  );

    switch ( type ) {

    case wkbPoint:

        poOgrPoint = ( OGRPoint * ) poOgrGeom;
        if (poOgrPoint->getCoordinateDimension() == 0)
        {
            poKmlGeometry = poKmlPoint = poKmlFactory->CreatePoint (  );
        }
        else
        {
            x = poOgrPoint->getX (  );
            y = poOgrPoint->getY (  );

            if ( x > 180 )
                x -= 360;

            coordinates = poKmlFactory->CreateCoordinates (  );
            coordinates->add_latlng ( y, x );
            poKmlGeometry = poKmlPoint = poKmlFactory->CreatePoint (  );
            poKmlPoint->set_coordinates ( coordinates );
        }

        break;

    case wkbPoint25D:
        poOgrPoint = ( OGRPoint * ) poOgrGeom;

        x = poOgrPoint->getX (  );
        y = poOgrPoint->getY (  );
        z = poOgrPoint->getZ (  );

        if ( x > 180 )
            x -= 360;

        coordinates = poKmlFactory->CreateCoordinates (  );
        coordinates->add_latlngalt ( y, x, z );
        poKmlGeometry = poKmlPoint = poKmlFactory->CreatePoint (  );
        poKmlPoint->set_coordinates ( coordinates );

        break;

    case wkbLineString:
        poOgrLineString = ( OGRLineString * ) poOgrGeom;

        if( extra >= 0 )
        {
            ((OGRLinearRing*)poOgrGeom)->closeRings();
        }

        numpoints = poOgrLineString->getNumPoints (  );
        if( extra >= 0 )
        {
            if( numpoints < 4 &&
                CPLTestBool(CPLGetConfigOption("LIBKML_STRICT_COMPLIANCE", "TRUE")) )
            {
                CPLError(CE_Failure, CPLE_NotSupported, "A linearring should have at least 4 points");
                return NULL;
            }
        }
        else
        {
            if( numpoints < 2 &&
                CPLTestBool(CPLGetConfigOption("LIBKML_STRICT_COMPLIANCE", "TRUE")) )
            {
                CPLError(CE_Failure, CPLE_NotSupported, "A linestring should have at least 2 points");
                return NULL;
            }
        }

        coordinates = poKmlFactory->CreateCoordinates (  );

        poOgrPoint = new OGRPoint (  );

        for ( i = 0; i < numpoints; i++ ) {
            poOgrLineString->getPoint ( i, poOgrPoint );

            x = poOgrPoint->getX (  );
            y = poOgrPoint->getY (  );

            if ( x > 180 )
                x -= 360;

            coordinates->add_latlng ( y, x );
        }
        delete poOgrPoint;

        /***** check if its a wkbLinearRing *****/

        if ( extra < 0 ) {

            poKmlGeometry = poKmlLineString =
                poKmlFactory->CreateLineString (  );
            poKmlLineString->set_coordinates ( coordinates );

            break;
        }

      /***** fallthrough *****/

    case wkbLinearRing:        //this case is for readability only

        poKmlLinearRing = poKmlFactory->CreateLinearRing (  );
        poKmlLinearRing->set_coordinates ( coordinates );

        if ( !extra ) {
            poKmlOuterRing = poKmlFactory->CreateOuterBoundaryIs (  );
            poKmlOuterRing->set_linearring ( poKmlLinearRing );
            poKmlGeometry = poKmlOuterRing;
        }
        else {
            poKmlGeometry = poKmlInnerRing =
                poKmlFactory->CreateInnerBoundaryIs (  );
            poKmlInnerRing->set_linearring ( poKmlLinearRing );
        }

        break;

    case wkbLineString25D:

        poOgrLineString = ( OGRLineString * ) poOgrGeom;

        if( extra >= 0 )
        {
            ((OGRLinearRing*)poOgrGeom)->closeRings();
        }

        numpoints = poOgrLineString->getNumPoints (  );
        if( extra >= 0 )
        {
            if( numpoints < 4 &&
                CPLTestBool(CPLGetConfigOption("LIBKML_STRICT_COMPLIANCE", "TRUE")) )
            {
                CPLError(CE_Failure, CPLE_NotSupported, "A linearring should have at least 4 points");
                return NULL;
            }
        }
        else
        {
            if( numpoints < 2 &&
                CPLTestBool(CPLGetConfigOption("LIBKML_STRICT_COMPLIANCE", "TRUE")) )
            {
                CPLError(CE_Failure, CPLE_NotSupported, "A linestring should have at least 2 points");
                return NULL;
            }
        }

        coordinates = poKmlFactory->CreateCoordinates (  );
        poOgrPoint = new OGRPoint (  );

        for ( i = 0; i < numpoints; i++ ) {
            poOgrLineString->getPoint ( i, poOgrPoint );

            x = poOgrPoint->getX (  );
            y = poOgrPoint->getY (  );
            z = poOgrPoint->getZ (  );

            if ( x > 180 )
                x -= 360;

            coordinates->add_latlngalt ( y, x, z );
        }
        delete poOgrPoint;

        /***** check if its a wkbLinearRing *****/

        if ( extra < 0 ) {

            poKmlGeometry = poKmlLineString =
                poKmlFactory->CreateLineString (  );
            poKmlLineString->set_coordinates ( coordinates );

            break;
        }
            /***** fallthrough *****/

        //case wkbLinearRing25D: // this case is for readability only

        poKmlLinearRing = poKmlFactory->CreateLinearRing (  );
        poKmlLinearRing->set_coordinates ( coordinates );

        if ( !extra ) {
            poKmlGeometry = poKmlOuterRing =
                poKmlFactory->CreateOuterBoundaryIs (  );
            poKmlOuterRing->set_linearring ( poKmlLinearRing );
        }
        else {
            poKmlGeometry = poKmlInnerRing =
                poKmlFactory->CreateInnerBoundaryIs (  );
            poKmlInnerRing->set_linearring ( poKmlLinearRing );
        }

        break;

    case wkbPolygon:

        CPLErrorReset();
        if( CPLTestBool(CPLGetConfigOption("LIBKML_STRICT_COMPLIANCE", "TRUE")) &&
            OGRGeometryFactory::haveGEOS() && (!poOgrGeom->IsValid() ||
             CPLGetLastErrorType() != CE_None) )
        {
            CPLError(CE_Failure, CPLE_NotSupported, "Invalid polygon");
            return NULL;
        }
        poOgrPolygon = ( OGRPolygon * ) poOgrGeom;

        poKmlGeometry = poKmlPolygon = poKmlFactory->CreatePolygon (  );

        poKmlTmpGeometry = geom2kml ( poOgrPolygon->getExteriorRing (  ),
                                      0, poKmlFactory );
        poKmlPolygon->
            set_outerboundaryis ( AsOuterBoundaryIs ( poKmlTmpGeometry ) );

        nGeom = poOgrPolygon->getNumInteriorRings (  );
        for ( i = 0; i < nGeom; i++ ) {
            poKmlTmpGeometry = geom2kml ( poOgrPolygon->getInteriorRing ( i ),
                                          i + 1, poKmlFactory );
            poKmlPolygon->
                add_innerboundaryis ( AsInnerBoundaryIs ( poKmlTmpGeometry ) );
        }

        break;

    case wkbPolygon25D:

        CPLErrorReset();
        if( CPLTestBool(CPLGetConfigOption("LIBKML_STRICT_COMPLIANCE", "TRUE")) &&
            OGRGeometryFactory::haveGEOS() && (!poOgrGeom->IsValid() ||
             CPLGetLastErrorType() != CE_None) )
        {
            CPLError(CE_Failure, CPLE_NotSupported, "Invalid polygon");
            return NULL;
        }
        poOgrPolygon = ( OGRPolygon * ) poOgrGeom;

        poKmlGeometry = poKmlPolygon = poKmlFactory->CreatePolygon (  );

        poKmlTmpGeometry = geom2kml ( poOgrPolygon->getExteriorRing (  ),
                                      0, poKmlFactory );
        poKmlPolygon->
            set_outerboundaryis ( AsOuterBoundaryIs ( poKmlTmpGeometry ) );

        nGeom = poOgrPolygon->getNumInteriorRings (  );
        for ( i = 0; i < nGeom; i++ ) {
            poKmlTmpGeometry = geom2kml ( poOgrPolygon->getInteriorRing ( i ),
                                          i + 1, poKmlFactory );
            poKmlPolygon->
                add_innerboundaryis ( AsInnerBoundaryIs ( poKmlTmpGeometry ) );
        }

        break;

    case wkbMultiPoint:
    case wkbMultiLineString:
    case wkbMultiPolygon:
    case wkbGeometryCollection:
    case wkbMultiPoint25D:
    case wkbMultiLineString25D:
    case wkbMultiPolygon25D:
    case wkbGeometryCollection25D:

        poOgrMultiGeom = ( OGRGeometryCollection * ) poOgrGeom;

        nGeom = poOgrMultiGeom->getNumGeometries (  );

        if( nGeom == 1 &&
            CPLTestBool(CPLGetConfigOption("LIBKML_STRICT_COMPLIANCE", "TRUE")) )
        {
            CPLDebug("LIBKML", "Turning multiple geometry into single geometry");
            poKmlGeometry = geom2kml( poOgrMultiGeom->getGeometryRef ( 0 ),
                                      -1, poKmlFactory );
        }
        else
        {
            if( nGeom == 0 &&
                CPLTestBool(CPLGetConfigOption("LIBKML_STRICT_COMPLIANCE", "TRUE")) )
            {
                CPLError(CE_Warning, CPLE_AppDefined, "Empty multi geometry are not recommended");
            }
            poKmlGeometry = poKmlMultiGeometry =
                poKmlFactory->CreateMultiGeometry (  );
            for ( i = 0; i < nGeom; i++ ) {
                poKmlTmpGeometry = geom2kml ( poOgrMultiGeom->getGeometryRef ( i ),
                                            -1, poKmlFactory );
                poKmlMultiGeometry->
                    add_geometry ( AsGeometry ( poKmlTmpGeometry ) );
            }
        }

        break;

    case wkbUnknown:
    case wkbNone:
    default:
        break;

    }

    return poKmlGeometry;
}

/******************************************************************************
 recursive function to read a kml geometry and translate to ogr

Args:
            poKmlGeometry   pointer to the kml geometry to translate
            poOgrSRS        pointer to the spatial ref to set on the geometry

Returns:
            pointer to the new ogr geometry object

******************************************************************************/

static OGRGeometry *kml2geom_rec (
    GeometryPtr poKmlGeometry,
    OGRSpatialReference *poOgrSRS)

{

    /***** ogr geom vars *****/

    OGRPoint *poOgrPoint;
    OGRLineString *poOgrLineString;
    OGRLinearRing *poOgrLinearRing;
    OGRPolygon *poOgrPolygon;
    OGRGeometryCollection *poOgrMultiGeometry;
    OGRGeometry *poOgrGeometry = NULL;
    OGRGeometry *poOgrTmpGeometry = NULL;

    /***** libkml geom vars *****/

    CoordinatesPtr poKmlCoordinates;
    PointPtr poKmlPoint;
    LineStringPtr poKmlLineString;
    LinearRingPtr poKmlLinearRing;
    OuterBoundaryIsPtr poKmlOuterRing;
    InnerBoundaryIsPtr poKmlInnerRing;
    PolygonPtr poKmlPolygon;
    MultiGeometryPtr poKmlMultiGeometry;
    GxTrackPtr poKmlGxTrack;
    GxMultiTrackPtr poKmlGxMultiTrack;
    GeometryPtr poKmlTmpGeometry;

    Vec3 oKmlVec;

    size_t nRings,
        nCoords,
        nGeom,
        i;

    switch ( poKmlGeometry->Type (  ) ) {
    case kmldom::Type_Point:
        poKmlPoint = AsPoint ( poKmlGeometry );
        if ( poKmlPoint->has_coordinates (  ) ) {
            poKmlCoordinates = poKmlPoint->get_coordinates (  );
            nCoords = poKmlCoordinates->get_coordinates_array_size (  );
            if (nCoords > 0)
            {
                oKmlVec = poKmlCoordinates->get_coordinates_array_at ( 0 );

                if ( oKmlVec.has_altitude (  ) )
                    poOgrPoint = new OGRPoint ( oKmlVec.get_longitude (  ),
                                                oKmlVec.get_latitude (  ),
                                                oKmlVec.get_altitude (  ) );
                else
                    poOgrPoint = new OGRPoint ( oKmlVec.get_longitude (  ),
                                                oKmlVec.get_latitude (  ) );

                poOgrGeometry = poOgrPoint;
            }
            else
            {
                poOgrGeometry = new OGRPoint();
            }
        }
        else
        {
            poOgrGeometry = new OGRPoint();
        }

        break;

    case kmldom::Type_LineString:
        poKmlLineString = AsLineString ( poKmlGeometry );
        poOgrLineString = new OGRLineString (  );
        if ( poKmlLineString->has_coordinates (  ) ) {
            poKmlCoordinates = poKmlLineString->get_coordinates (  );

            nCoords = poKmlCoordinates->get_coordinates_array_size (  );
            for ( i = 0; i < nCoords; i++ ) {
                oKmlVec = poKmlCoordinates->get_coordinates_array_at ( i );
                if ( oKmlVec.has_altitude (  ) )
                    poOgrLineString->
                        addPoint ( oKmlVec.get_longitude (  ),
                                   oKmlVec.get_latitude (  ),
                                   oKmlVec.get_altitude (  ) );
                else
                    poOgrLineString->
                        addPoint ( oKmlVec.get_longitude (  ),
                                   oKmlVec.get_latitude (  ) );
            }
        }
        poOgrGeometry = poOgrLineString;

        break;
    case kmldom::Type_LinearRing:
        poKmlLinearRing = AsLinearRing ( poKmlGeometry );
        poOgrLinearRing = new OGRLinearRing (  );
        if ( poKmlLinearRing->has_coordinates (  ) ) {
            poKmlCoordinates = poKmlLinearRing->get_coordinates (  );

            nCoords = poKmlCoordinates->get_coordinates_array_size (  );
            for ( i = 0; i < nCoords; i++ ) {
                oKmlVec = poKmlCoordinates->get_coordinates_array_at ( i );
                if ( oKmlVec.has_altitude (  ) )
                    poOgrLinearRing->
                        addPoint ( oKmlVec.get_longitude (  ),
                                   oKmlVec.get_latitude (  ),
                                   oKmlVec.get_altitude (  ) );
                else
                    poOgrLinearRing->
                        addPoint ( oKmlVec.get_longitude (  ),
                                   oKmlVec.get_latitude (  ) );
            }
        }
        poOgrGeometry = poOgrLinearRing;

        break;
    case kmldom::Type_Polygon:
        poKmlPolygon = AsPolygon ( poKmlGeometry );

        poOgrPolygon = new OGRPolygon (  );
        if ( poKmlPolygon->has_outerboundaryis (  ) ) {

            poKmlOuterRing = poKmlPolygon->get_outerboundaryis (  );
            poKmlLinearRing = poKmlOuterRing->get_linearring (  );
            if (poKmlLinearRing)
            {
                poOgrTmpGeometry = kml2geom_rec ( poKmlLinearRing, poOgrSRS );

                poOgrPolygon->
                    addRingDirectly ( ( OGRLinearRing * ) poOgrTmpGeometry );
            }

        }
        nRings = poKmlPolygon->get_innerboundaryis_array_size (  );
        for ( i = 0; i < nRings; i++ ) {
            poKmlInnerRing = poKmlPolygon->get_innerboundaryis_array_at ( i );
            poKmlLinearRing = poKmlInnerRing->get_linearring (  );
            if (poKmlLinearRing)
            {
                poOgrTmpGeometry = kml2geom_rec ( poKmlLinearRing, poOgrSRS );

                poOgrPolygon->
                    addRingDirectly ( ( OGRLinearRing * ) poOgrTmpGeometry );
            }
        }
        poOgrGeometry = poOgrPolygon;

        break;
    case kmldom::Type_MultiGeometry:
    {
        poKmlMultiGeometry = AsMultiGeometry ( poKmlGeometry );
        nGeom = poKmlMultiGeometry->get_geometry_array_size (  );

        // Detect subgeometry type to instantiate appropriate
        // multi geometry type.
        kmldom::KmlDomType type = kmldom::Type_Unknown;
        for ( i = 0; i < nGeom; i++ ) {
            poKmlTmpGeometry = poKmlMultiGeometry->get_geometry_array_at ( i );
            if (type == kmldom::Type_Unknown)
                type = poKmlTmpGeometry->Type();
            else if (type != poKmlTmpGeometry->Type())
            {
                type = kmldom::Type_Unknown;
                break;
            }
        }

        if (type == kmldom::Type_Point)
            poOgrMultiGeometry = new OGRMultiPoint();
        else if (type == kmldom::Type_LineString)
            poOgrMultiGeometry = new OGRMultiLineString();
        else if (type == kmldom::Type_Polygon)
            poOgrMultiGeometry = new OGRMultiPolygon();
        else
            poOgrMultiGeometry = new OGRGeometryCollection ();

        for ( i = 0; i < nGeom; i++ ) {
            poKmlTmpGeometry = poKmlMultiGeometry->get_geometry_array_at ( i );
            poOgrTmpGeometry = kml2geom_rec ( poKmlTmpGeometry, poOgrSRS );

            poOgrMultiGeometry->addGeometryDirectly ( poOgrTmpGeometry );
        }
        poOgrGeometry = poOgrMultiGeometry;
        break;
    }

    case kmldom::Type_GxTrack:
        poKmlGxTrack = AsGxTrack ( poKmlGeometry );
        nCoords = poKmlGxTrack->get_gx_coord_array_size();
        poOgrLineString = new OGRLineString (  );
        for ( i = 0; i < nCoords; i++ ) {
            oKmlVec = poKmlGxTrack->get_gx_coord_array_at ( i );
            if ( oKmlVec.has_altitude (  ) )
                poOgrLineString->
                    addPoint ( oKmlVec.get_longitude (  ),
                                oKmlVec.get_latitude (  ),
                                oKmlVec.get_altitude (  ) );
            else
                poOgrLineString->
                    addPoint ( oKmlVec.get_longitude (  ),
                                oKmlVec.get_latitude (  ) );
        }
        poOgrGeometry = poOgrLineString;
        break;

    case kmldom::Type_GxMultiTrack:
    {
        poKmlGxMultiTrack = AsGxMultiTrack ( poKmlGeometry );
        nGeom = poKmlGxMultiTrack->get_gx_track_array_size (  );
        poOgrMultiGeometry = new OGRMultiLineString();
        for( size_t j = 0; j < nGeom; j++ )
        {
            poKmlGxTrack = poKmlGxMultiTrack->get_gx_track_array_at ( j );
            nCoords = poKmlGxTrack->get_gx_coord_array_size();
            poOgrLineString = new OGRLineString (  );
            for ( i = 0; i < nCoords; i++ ) {
                oKmlVec = poKmlGxTrack->get_gx_coord_array_at ( i );
                if ( oKmlVec.has_altitude (  ) )
                    poOgrLineString->
                        addPoint ( oKmlVec.get_longitude (  ),
                                    oKmlVec.get_latitude (  ),
                                    oKmlVec.get_altitude (  ) );
                else
                    poOgrLineString->
                        addPoint ( oKmlVec.get_longitude (  ),
                                    oKmlVec.get_latitude (  ) );
            }
            poOgrMultiGeometry->addGeometryDirectly(poOgrLineString);
        }
        poOgrGeometry = poOgrMultiGeometry;
        break;
    }

    default:
        break;
    }

    if (poOgrGeometry)
        poOgrGeometry->assignSpatialReference(poOgrSRS);

    return poOgrGeometry;
}

static
OGRGeometry *kml2geom_latlonbox_int (
    LatLonBoxPtr poKmlLatLonBox,
    OGRSpatialReference *poOgrSRS)

{
    OGRPolygon *poOgrPolygon;
    double north, south, east, west;
    if ( !poKmlLatLonBox->has_north (  ) ||
         !poKmlLatLonBox->has_south (  ) ||
         !poKmlLatLonBox->has_east (  ) ||
         !poKmlLatLonBox->has_west (  ) ) {

        return NULL;
    }
    poOgrPolygon = new OGRPolygon (  );
    north = poKmlLatLonBox->get_north (  );
    south = poKmlLatLonBox->get_south (  );
    east = poKmlLatLonBox->get_east (  );
    west = poKmlLatLonBox->get_west (  );
    OGRLinearRing* poOgrRing = new OGRLinearRing (  );
    poOgrRing->addPoint ( east, north, 0.0 );
    poOgrRing->addPoint ( east, south, 0.0 );
    poOgrRing->addPoint ( west, south, 0.0 );
    poOgrRing->addPoint ( west, north, 0.0 );
    poOgrRing->addPoint ( east, north, 0.0 );
    poOgrPolygon->
        addRingDirectly ( poOgrRing );
    poOgrPolygon->assignSpatialReference(poOgrSRS);

    return poOgrPolygon;
}

static
OGRGeometry *kml2geom_latlonquad_int (
    GxLatLonQuadPtr poKmlLatLonQuad,
    OGRSpatialReference *poOgrSRS)

{
    if( !poKmlLatLonQuad->has_coordinates() )
        return NULL;

    const CoordinatesPtr& poKmlCoordinates =
        poKmlLatLonQuad->get_coordinates();

    OGRLinearRing* poOgrLinearRing = new OGRLinearRing (  );

    size_t nCoords = poKmlCoordinates->get_coordinates_array_size (  );
    for ( size_t i = 0; i < nCoords; i++ ) {
        Vec3 oKmlVec = poKmlCoordinates->get_coordinates_array_at ( i );
        if ( oKmlVec.has_altitude (  ) )
            poOgrLinearRing->
                addPoint ( oKmlVec.get_longitude (  ),
                           oKmlVec.get_latitude (  ),
                           oKmlVec.get_altitude (  ) );
        else
            poOgrLinearRing->
                addPoint ( oKmlVec.get_longitude (  ),
                           oKmlVec.get_latitude (  ) );
    }
    poOgrLinearRing->closeRings();

    OGRPolygon *poOgrPolygon = new OGRPolygon();
    poOgrPolygon->
        addRingDirectly ( poOgrLinearRing );
    poOgrPolygon->assignSpatialReference(poOgrSRS);

    return poOgrPolygon;
}

/******************************************************************************
 main function to read a kml geometry and translate to ogr

Args:
            poKmlGeometry   pointer to the kml geometry to translate
            poOgrSRS        pointer to the spatial ref to set on the geometry

Returns:
            pointer to the new ogr geometry object

******************************************************************************/

OGRGeometry *kml2geom (
    GeometryPtr poKmlGeometry,
    OGRSpatialReference *poOgrSRS)

{

    /***** get the geometry *****/

    OGRGeometry *poOgrGeometry = kml2geom_rec (poKmlGeometry, poOgrSRS);

    /***** split the geometry at the dateline? *****/

    const char *pszWrap = CPLGetConfigOption ( "LIBKML_WRAPDATELINE", "no" );
    if (CPLTestBool(pszWrap)) {

        char **papszTransformOptions = NULL;
        papszTransformOptions = CSLAddString( papszTransformOptions,
                                                "WRAPDATELINE=YES");

        /***** transform *****/

        OGRGeometry *poOgrDstGeometry =
            OGRGeometryFactory::transformWithOptions(poOgrGeometry,
                                                        NULL,
                                                        papszTransformOptions);

        /***** replace the original geom *****/

        if (poOgrDstGeometry) {
            delete poOgrGeometry;
            poOgrGeometry = poOgrDstGeometry;
        }

        CSLDestroy(papszTransformOptions);
    }

    return poOgrGeometry;
}

OGRGeometry *kml2geom_latlonbox (
    LatLonBoxPtr poKmlLatLonBox,
    OGRSpatialReference *poOgrSRS)

{

    /***** get the geometry *****/

    OGRGeometry *poOgrGeometry = kml2geom_latlonbox_int (poKmlLatLonBox, poOgrSRS);

    /***** split the geometry at the dateline? *****/

    const char *pszWrap = CPLGetConfigOption ( "LIBKML_WRAPDATELINE", "no" );
    if (CPLTestBool(pszWrap)) {

        char **papszTransformOptions = NULL;
        papszTransformOptions = CSLAddString( papszTransformOptions,
                                                "WRAPDATELINE=YES");

        /***** transform *****/

        OGRGeometry *poOgrDstGeometry =
            OGRGeometryFactory::transformWithOptions(poOgrGeometry,
                                                        NULL,
                                                        papszTransformOptions);

        /***** replace the original geom *****/

        if (poOgrDstGeometry) {
            delete poOgrGeometry;
            poOgrGeometry = poOgrDstGeometry;
        }

        CSLDestroy(papszTransformOptions);
    }

    return poOgrGeometry;
}

OGRGeometry *kml2geom_latlonquad (
    GxLatLonQuadPtr poKmlLatLonQuad,
    OGRSpatialReference *poOgrSRS)

{

    /***** get the geometry *****/

    OGRGeometry *poOgrGeometry = kml2geom_latlonquad_int (poKmlLatLonQuad, poOgrSRS);

    /***** split the geometry at the dateline? *****/

    const char *pszWrap = CPLGetConfigOption ( "LIBKML_WRAPDATELINE", "no" );
    if (CPLTestBool(pszWrap)) {

        char **papszTransformOptions = NULL;
        papszTransformOptions = CSLAddString( papszTransformOptions,
                                                "WRAPDATELINE=YES");

        /***** transform *****/

        OGRGeometry *poOgrDstGeometry =
            OGRGeometryFactory::transformWithOptions(poOgrGeometry,
                                                        NULL,
                                                        papszTransformOptions);

        /***** replace the original geom *****/

        if (poOgrDstGeometry) {
            delete poOgrGeometry;
            poOgrGeometry = poOgrDstGeometry;
        }

        CSLDestroy(papszTransformOptions);
    }

    return poOgrGeometry;
}


text:
package com.mistraltech.smogen.codegenerator;

public class GenericSubclassTest extends AbstractGeneratorTest {

    public static final String TEST_NAME = "generic_subclass";

    public void testGenericSubclass() {
        doTest(TEST_NAME, defaultGeneratorProperties().setMatcherSuperClassName("BaseWidgetMatcher"));
    }

    @Override
    protected void preLoadClasses() {
        super.preLoadClasses();
        loadTestClassFromFile(TEST_NAME, "superclass.java");
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Strimoid\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Routing\UrlGenerator;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Str;
use Strimoid\Models\Content;
use Strimoid\Models\Entry;
use Strimoid\Models\Group;

class GenerateSitemap extends Command
{
    protected $name = 'lara:generatesitemap';
    protected $description = 'Generate sitemap.';

    private UrlGenerator $urlGenerator;

    public function __construct(UrlGenerator $urlGenerator)
    {
        $this->urlGenerator = $urlGenerator;

        parent::__construct();
    }

    public function handle(): void
    {
        // Generate groups sitemap
        $sitemap = app('sitemap');
        $x = 1;

        foreach (Group::all() as $group) {
            $sitemap->add(URL::to($this->urlGenerator->route('group_contents', $group->getKey())), null, '1.0', 'daily');
            $sitemap->add(URL::to($this->urlGenerator->route('group_contents_new', $group->getKey())), null, '1.0', 'daily');
            $sitemap->add(URL::to($this->urlGenerator->route('group_entries', $group->getKey())), null, '1.0', 'daily');

            if (!$x % 100) {
                $this->info($x . ' groups processed');
            }

            $x++;
        }

        $this->info('All groups processed');
        $sitemap->store('xml', 'sitemap-groups');

        unset($sitemap);

        // Generate entries sitemap
        $sitemap = App::make('sitemap');
        $x = 1;

        foreach (Content::all() as $content) {
            $route = $this->urlGenerator->route('content_comments_slug', [$content->getKey(), Str::slug($content->title)]);

            $sitemap->add(URL::to($route), $content->modified_at, '1.0', 'daily');

            if (!$x % 100) {
                $this->info($x . ' contents processed');
            }

            $x++;
        }

        $this->info('All contents processed');
        $sitemap->store('xml', 'sitemap-contents');

        unset($sitemap);

        // Generate contents sitemap
        $sitemap = App::make('sitemap');
        $x = 1;

        foreach (Entry::all() as $entry) {
            $route = $this->urlGenerator->route('single_entry', $entry->getKey());

            $sitemap->add(URL::to($route), $entry->modified_at, '1.0', 'daily');

            if (!$x % 100) {
                $this->info($x . ' entries processed');
            }

            $x++;
        }

        $this->info('All entries processed');
        $sitemap->store('xml', 'sitemap-entries');

        unset($sitemap);

        // Generate global sitemap
        $sitemap = App::make('sitemap');

        $sitemap->addSitemap(URL::to('sitemap-groups.xml'));
        $sitemap->addSitemap(URL::to('sitemap-contents.xml'));
        $sitemap->addSitemap(URL::to('sitemap-entries.xml'));

        $sitemap->store('sitemapindex', 'sitemap');
    }
}


text:
package event

import "github.com/samuelngs/hyper/router"

// event struct
type event struct {
	field   string
	payload []byte
	filters map[string]interface{}
	eqIDs   []int64
	neIDs   []int64
	eqKeys  []string
	neKeys  []string
	strict  bool
}

// Field returns field name
func (v *event) Field() string {
	return v.field
}

// Payload returns payload data
func (v *event) Payload() []byte {
	return v.payload
}

// Filters return filter columns and values
func (v *event) Filters() map[string]interface{} {
	return v.filters
}

// EqIDs return matching condition identity ids
func (v *event) EqIDs() []int64 {
	return v.eqIDs
}

// NeIDs return not matching condition identity ids condition
func (v *event) NeIDs() []int64 {
	return v.neIDs
}

// EqKeys returns matcing condition identity keys
func (v *event) EqKeys() []string {
	return v.eqKeys
}

// NeKeys returns non matching condition identity keys
func (v *event) NeKeys() []string {
	return v.neKeys
}

// Strict returns strict mode status
// If strict mode is on, all variables and filters have to be equal match
func (v *event) Strict() bool {
	return v.strict
}

// New creates engine server
func New(opts ...Option) router.GQLEvent {
	o := newOptions(opts...)
	e := &event{
		field:   o.Field,
		payload: o.Payload,
		filters: o.Filters,
		eqIDs:   o.EqIDs,
		neIDs:   o.NeIDs,
		eqKeys:  o.EqKeys,
		neKeys:  o.NeKeys,
		strict:  o.Strict,
	}
	return e
}


text:
require 'spec_helper'

describe Dockistrano::Cli do

  let(:service) { double(registry: "registry.provider.tld", image_name: "application", tag: "develop", volumes: [], backing_services: { "postgresql" => backing_service }, environment_variables: {}, newer_version_available?: false, stop: nil) }
  let(:backing_service) { double(:backing_service, full_image_name: "registry.provider.tld/postgresql:develop", image_name: "postgresql", running?: false, newer_version_available?: false, start: nil, stop: nil) }
  let(:hipache) { double }
  let(:hipache_service) { double(running?: true, full_image_name: "hipache") }
  let(:output) { capture(:stdout) { described_class.start(command) } }

  before do
    allow(Dockistrano::Service).to receive(:factory).and_return(service)
  end

  context "doc status" do
    let(:command) { ["status"] }

    it "prints the DOCKISTRANO_ENVIRONMENT" do
      expect(output).to include("DOCKISTRANO_ENVIRONMENT: default")
    end

    it "prints the DOCKER_HOST_IP" do
      expect(output).to include("DOCKER_HOST_IP: 127.0.0.1")
    end

    it "prints the DOCKER_BINARY" do
      expect(output).to include("DOCKER_BINARY:")
    end

    it "prints the registry" do
      expect(output).to include("registry: #{service.registry}")
    end

    it "prints the name of the image" do
      expect(output).to include("image name: #{service.image_name}")
    end

    it "prints the tag" do
      expect(output).to include("tag: #{service.tag}")
    end

    it "lists all dependencies" do
      expect(output).to include(backing_service.full_image_name)
    end

    it "lists environment variables" do
      allow(service).to receive(:environment_variables).and_return({ "VARIABLE" => "value"} )
      expect(output).to include("VARIABLE=value")
    end

    it "lists the Hipache configuration" do
      allow(service).to receive(:backing_services).and_return({ "hipache" => hipache_service })
      allow(hipache_service).to receive(:ip_address).and_return("127.0.0.1")
      allow(Dockistrano::Hipache).to receive(:new).with("redis://127.0.0.1:6379").and_return(hipache)
      allow(hipache).to receive(:status).and_return({ "somehostname.dev" => ["127.0.0.1:1000", "23.45.56.75:1234"] })
      expect(output).to include("somehostname.dev: 127.0.0.1:1000, 23.45.56.75:1234")
    end
  end

  context "doc build" do
    let(:command) { ["build"] }

    it "builds a container" do
      expect(service).to receive(:build).and_return(true)
      expect(service).to receive(:test).and_return(true)
      expect(service).to receive(:push).and_return(true)
      expect(output).to include("built")
      expect(output).to include("tests")
      expect(output).to include("pushed")
    end

    it "doesn't run the tests and push when building failed" do
      expect(service).to receive(:build).and_return(false)
      expect(service).to_not receive(:test)
      expect(service).to_not receive(:push)
      expect { output }.to raise_error(SystemExit)
    end

    it "doesn't push when tests failed" do
      expect(service).to receive(:build).and_return(true)
      expect(service).to receive(:test).and_return(false)
      expect(service).to_not receive(:push)
      expect { output }.to raise_error(SystemExit)
    end
  end

  context "doc pull" do
    let(:command) { ["pull"] }

    it "pulls a backing service when newer versions are available" do
      expect(service).to receive(:backing_services).with(initialize: false).and_return({ "postgresql" => backing_service })
      expect(backing_service).to receive(:newer_version_available?).and_return(true)
      expect(backing_service).to receive(:pull)
      expect(output).to include("Pulled")
    end

    it "doesn't pull a service when no new versions are available" do
      expect(service).to receive(:backing_services).with(initialize: false).and_return({ "postgresql" => backing_service })
      expect(backing_service).to receive(:newer_version_available?).and_return(false)
      expect(backing_service).to_not receive(:pull)
      expect(output).to include("Uptodate")
    end

    it "pulls the application container when newer versions are available" do
      expect(service).to receive(:backing_services).with(initialize: false).and_return({ "postgresql" => backing_service })
      expect(service).to receive(:newer_version_available?).and_return(true)
      expect(service).to receive(:pull)
      expect(output).to include("Pulled")
    end

    it "doesn't pull the application container when no newer versions are available" do
      expect(service).to receive(:backing_services).with(initialize: false).and_return({ "postgresql" => backing_service })
      expect(service).to receive(:newer_version_available?).and_return(false)
      expect(service).to_not receive(:pull)
      expect(output).to include("Uptodate")
    end
  end

  context "doc push" do
    it "pushes the current container" do
      expect(service).to receive(:push)
      described_class.start(["push"])
    end
  end

  context "doc start-services" do
    let(:command) { ["start-services"] }

    it "starts a backing service when it is not running" do
      expect(backing_service).to receive(:running?).and_return(false)
      expect(backing_service).to receive(:start)
      expect(output).to include("Started")
    end

    it "does nothing when a backing services is already running" do
      expect(backing_service).to receive(:running?).and_return(true)
      expect(backing_service).to_not receive(:start)
      expect(output).to include("Running")
    end
  end

  context "doc stop-all" do
    let(:command) { ["stop-all"] }

    it "stops the current container" do
      expect(service).to receive(:stop)
      expect(output).to include("Stopped")
    end

    it "stops all backing services" do
      expect(backing_service).to receive(:running?).and_return(true)
      expect(backing_service).to receive(:stop)
      expect(output).to include("Stopped")
    end
  end

  context "doc start" do
    let(:command) { ["start"] }

    it "starts the services when not running" do
      expect(service).to receive(:running?).and_return(false)
      expect(service).to receive(:start)
      expect(output).to include("Started")
    end

    it "doesn't start the services when already running" do
      expect(service).to receive(:running?).and_return(true)
      expect(service).to_not receive(:start)
      expect(output).to include("Running")
    end

    it "prints an error when environment variables are missing" do
      expect(service).to receive(:running?).and_return(false)
      expect(service).to receive(:start).and_raise(Dockistrano::Service::EnvironmentVariablesMissing.new("error message"))
      expect(output).to include("error message")
    end
  end

  context "doc stop" do
    let(:command) { ["stop"] }

    it "stops the current container" do
      expect(service).to receive(:stop)
      expect(output).to include("Stopped")
    end
  end

  context "doc stop ID" do
    let(:command) { ["stop", "123456789"] }

    it "stops the container with the id" do
      expect(Dockistrano::Docker).to receive(:stop).with("123456789")
      expect(Dockistrano::Docker).to receive(:remove_container).with("123456789")
      expect(output).to include("Stopped")
    end
  end

  context "doc restart" do
    let(:command) { ["restart"] }

    it "restarts the current container" do
      expect(service).to receive(:stop)
      expect(service).to receive(:start)
      expect(output).to include("Stopped")
      expect(output).to include("Started")
    end
  end

  context "doc exec COMMAND" do
    let(:command) { ["exec", "bin/rspec", "-t", "spec/models/my_model_spec.rb"] }

    it "executes the command in the container" do
      expect(service).to receive(:exec).with("bin/rspec -t spec/models/my_model_spec.rb", { "environment" => "default" })
      output
    end

    it "prints an error when environment variables are missing" do
      expect(service).to receive(:exec).and_raise(Dockistrano::Service::EnvironmentVariablesMissing.new("error message"))
      expect(output).to include("error message")
    end
  end

  context "doc console" do
    let(:command) { ["console"] }

    it "starts a bash console in the container" do
      expect(service).to receive(:console).with("/bin/bash", { "environment" => "default" })
      output
    end

    it "prints an error when environment variables are missing" do
      expect(service).to receive(:console).and_raise(Dockistrano::Service::EnvironmentVariablesMissing.new("error message"))
      expect(output).to include("error message")
    end
  end

  context "doc console COMMAND" do
    let(:command) { ["console", "bin/rails console"] }

    it "starts a console in the container" do
      expect(service).to receive(:console).with("bin/rails console", { "environment" => "default" })
      output
    end

    it "prints an error when environment variables are missing" do
      expect(service).to receive(:console).and_raise(Dockistrano::Service::EnvironmentVariablesMissing.new("error message"))
      expect(output).to include("error message")
    end
  end

  context "doc clean" do
    let(:command) { ["clean"] }

    it "cleans the Docker instance and service dependency cache" do
      expect(Dockistrano::Docker).to receive(:clean)
      expect(Dockistrano::ServiceDependency).to receive(:clear_cache)
      output
    end
  end

  context "doc logs" do
    let(:command) { ["logs"] }

    it "attaches to the containers output when the container is running" do
      expect(service).to receive(:running?).and_return(true)
      expect(service).to receive(:attach).with(nil)
      expect(output).to include("Container application running, attaching to output")
    end

    it "prints the logs of the last run" do
      expect(service).to receive(:running?).and_return(false)
      expect(service).to receive(:logs).with(nil)
      expect(output).to include("Container application stopped, printing logs of last run")
    end
  end

  context "doc logs BACKING_SERVICE" do
    let(:command) { ["logs", "postgresql"] }

    it "attaches to the containers output when the container is running" do
      expect(backing_service).to receive(:running?).and_return(true)
      expect(backing_service).to receive(:attach).with(nil)
      expect(output).to include("Container postgresql running, attaching to output")
    end

    it "prints the logs of the last run" do
      expect(backing_service).to receive(:running?).and_return(false)
      expect(backing_service).to receive(:logs).with(nil)
      expect(output).to include("Container postgresql stopped, printing logs of last run")
    end
  end

  context "doc logs ADDITIONAL_COMMAND" do
    let(:command) { ["logs", "worker"] }

    it "attaches to the containers output when the container is running" do
      expect(service).to receive(:running?).and_return(true)
      expect(service).to receive(:attach).with("worker")
      expect(output).to include("Container application running, attaching to output")
    end

    it "prints the logs of the last run" do
      expect(service).to receive(:running?).and_return(false)
      expect(service).to receive(:logs).with("worker")
      expect(output).to include("Container application stopped, printing logs of last run")
    end
  end

  context "doc ALIAS ARGUMENTS" do
    let(:command) { ["rspec", "spec/models/my_model_spec.rb"] }

    it "executes aliases that are defined in the configuration" do
      allow(service).to receive(:config).and_return({ "aliases" => { "rspec" => "exec -e test bin/rspec" } })
      expect(Kernel).to receive(:exec).with("doc exec -e test bin/rspec spec/models/my_model_spec.rb")
      output
    end
  end

  context "doc setup" do
    let(:command) { ["setup"] }

    before do
      allow(backing_service).to receive(:setup)
      allow(service).to receive(:setup)
    end

    it "setups all backing services" do
      expect(backing_service).to receive(:setup)
      expect(output).to include("Setting up postgresql")
    end

    it "setups the current service" do
      expect(service).to receive(:setup)
      expect(output).to include("Setting up #{service.image_name}")
    end
  end

  context "doc reset" do
    let(:command) { ["reset"] }

    before do
      allow(backing_service).to receive(:reset)
      allow(service).to receive(:reset)
    end

    it "resets all backing services" do
      expect(backing_service).to receive(:reset)
      expect(output).to include("Reset postgresql")
    end

    it "resets the current service" do
      expect(service).to receive(:reset)
      expect(output).to include("Reset #{service.image_name}")
    end
  end

end


text:
/*
 * Do not modify this file. This file is generated from the kinesis-2013-12-02.normal.json service model.
 */

using System;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;

using Amazon.Kinesis.Model;
using Amazon.Kinesis.Model.Internal.MarshallTransformations;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;

namespace Amazon.Kinesis
{
    ///
    /// Implementation for accessing Kinesis
    ///
    /// Amazon Kinesis Service API Reference
    /// <para>
    /// Amazon Kinesis is a managed service that scales elastically for real time processing
    /// of streaming big data.
    /// </para>
    ///
    public partial class AmazonKinesisClient : AmazonServiceClient, IAmazonKinesis
    {

        #region Constructors

        ///
        /// Constructs AmazonKinesisClient with AWS Credentials
        ///
        /// <param name="credentials">AWS Credentials</param>
        public AmazonKinesisClient(AWSCredentials credentials)
            : this(credentials, new AmazonKinesisConfig())
        {
        }

        ///
        /// Constructs AmazonKinesisClient with AWS Credentials
        ///
        /// <param name="credentials">AWS Credentials</param>
        /// <param name="region">The region to connect.</param>
        public AmazonKinesisClient(AWSCredentials credentials, RegionEndpoint region)
            : this(credentials, new AmazonKinesisConfig{RegionEndpoint = region})
        {
        }

        ///
        /// Constructs AmazonKinesisClient with AWS Credentials and an
        /// AmazonKinesisClient Configuration object.
        ///
        /// <param name="credentials">AWS Credentials</param>
        /// <param name="clientConfig">The AmazonKinesisClient Configuration Object</param>
        public AmazonKinesisClient(AWSCredentials credentials, AmazonKinesisConfig clientConfig)
            : base(credentials, clientConfig)
        {
        }

        ///
        /// Constructs AmazonKinesisClient with AWS Access Key ID and AWS Secret Key
        ///
        /// <param name="awsAccessKeyId">AWS Access Key ID</param>
        /// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
        public AmazonKinesisClient(string awsAccessKeyId, string awsSecretAccessKey)
            : this(awsAccessKeyId, awsSecretAccessKey, new AmazonKinesisConfig())
        {
        }

        ///
        /// Constructs AmazonKinesisClient with AWS Access Key ID and AWS Secret Key
        ///
        /// <param name="awsAccessKeyId">AWS Access Key ID</param>
        /// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
        /// <param name="region">The region to connect.</param>
        public AmazonKinesisClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
            : this(awsAccessKeyId, awsSecretAccessKey, new AmazonKinesisConfig() {RegionEndpoint=region})
        {
        }

        ///
        /// Constructs AmazonKinesisClient with AWS Access Key ID, AWS Secret Key and an
        /// AmazonKinesisClient Configuration object.
        ///
        /// <param name="awsAccessKeyId">AWS Access Key ID</param>
        /// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
        /// <param name="clientConfig">The AmazonKinesisClient Configuration Object</param>
        public AmazonKinesisClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonKinesisConfig clientConfig)
            : base(awsAccessKeyId, awsSecretAccessKey, clientConfig)
        {
        }

        ///
        /// Constructs AmazonKinesisClient with AWS Access Key ID and AWS Secret Key
        ///
        /// <param name="awsAccessKeyId">AWS Access Key ID</param>
        /// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
        /// <param name="awsSessionToken">AWS Session Token</param>
        public AmazonKinesisClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
            : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonKinesisConfig())
        {
        }

        ///
        /// Constructs AmazonKinesisClient with AWS Access Key ID and AWS Secret Key
        ///
        /// <param name="awsAccessKeyId">AWS Access Key ID</param>
        /// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
        /// <param name="awsSessionToken">AWS Session Token</param>
        /// <param name="region">The region to connect.</param>
        public AmazonKinesisClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
            : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonKinesisConfig{RegionEndpoint = region})
        {
        }

        ///
        /// Constructs AmazonKinesisClient with AWS Access Key ID, AWS Secret Key and an
        /// AmazonKinesisClient Configuration object.
        ///
        /// <param name="awsAccessKeyId">AWS Access Key ID</param>
        /// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
        /// <param name="awsSessionToken">AWS Session Token</param>
        /// <param name="clientConfig">The AmazonKinesisClient Configuration Object</param>
        public AmazonKinesisClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonKinesisConfig clientConfig)
            : base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig)
        {
        }

        #endregion

        #region Overrides

        ///
        /// Creates the signer for the service.
        ///
        protected override AbstractAWSSigner CreateSigner()
        {
            return new AWS4Signer();
        }

        #endregion

        #region Dispose

        ///
        /// Disposes the service client.
        ///
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
        }

        #endregion

        #region  AddTagsToStream

        internal AddTagsToStreamResponse AddTagsToStream(AddTagsToStreamRequest request)
        {
            var marshaller = new AddTagsToStreamRequestMarshaller();
            var unmarshaller = AddTagsToStreamResponseUnmarshaller.Instance;

            return Invoke<AddTagsToStreamRequest,AddTagsToStreamResponse>(request, marshaller, unmarshaller);
        }

        ///
        /// Initiates the asynchronous execution of the AddTagsToStream operation.
        ///
        ///
        /// <param name="request">Container for the necessary parameters to execute the AddTagsToStream operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public Task<AddTagsToStreamResponse> AddTagsToStreamAsync(AddTagsToStreamRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new AddTagsToStreamRequestMarshaller();
            var unmarshaller = AddTagsToStreamResponseUnmarshaller.Instance;

            return InvokeAsync<AddTagsToStreamRequest,AddTagsToStreamResponse>(request, marshaller,
                unmarshaller, cancellationToken);
        }

        #endregion

        #region  CreateStream

        internal CreateStreamResponse CreateStream(CreateStreamRequest request)
        {
            var marshaller = new CreateStreamRequestMarshaller();
            var unmarshaller = CreateStreamResponseUnmarshaller.Instance;

            return Invoke<CreateStreamRequest,CreateStreamResponse>(request, marshaller, unmarshaller);
        }

        ///
        /// Initiates the asynchronous execution of the CreateStream operation.
        ///
        ///
        /// <param name="request">Container for the necessary parameters to execute the CreateStream operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public Task<CreateStreamResponse> CreateStreamAsync(CreateStreamRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new CreateStreamRequestMarshaller();
            var unmarshaller = CreateStreamResponseUnmarshaller.Instance;

            return InvokeAsync<CreateStreamRequest,CreateStreamResponse>(request, marshaller,
                unmarshaller, cancellationToken);
        }

        #endregion

        #region  DecreaseStreamRetentionPeriod

        internal DecreaseStreamRetentionPeriodResponse DecreaseStreamRetentionPeriod(DecreaseStreamRetentionPeriodRequest request)
        {
            var marshaller = new DecreaseStreamRetentionPeriodRequestMarshaller();
            var unmarshaller = DecreaseStreamRetentionPeriodResponseUnmarshaller.Instance;

            return Invoke<DecreaseStreamRetentionPeriodRequest,DecreaseStreamRetentionPeriodResponse>(request, marshaller, unmarshaller);
        }

        ///
        /// Decreases the stream's retention period, which is the length of time data records
        /// are accessible after they are added to the stream. The minimum value of a stream's
        /// retention period is 24 hours.
        ///
        ///
        /// <para>
        /// This operation may result in lost data. For example, if the stream's retention period
        /// is 48 hours and is decreased to 24 hours, any data already in the stream that is older
        /// than 24 hours is inaccessible.
        /// </para>
        ///
        /// <param name="streamName">The name of the stream to modify.</param>
        /// <param name="retentionPeriodHours">The new retention period of the stream, in hours. Must be less than the current retention period.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        ///
        /// <returns>The response from the DecreaseStreamRetentionPeriod service method, as returned by Kinesis.</returns>
        /// <exception cref="Amazon.Kinesis.Model.InvalidArgumentException">
        /// A specified parameter exceeds its restrictions, is not supported, or can't be used.
        /// For more information, see the returned message.
        /// </exception>
        /// <exception cref="Amazon.Kinesis.Model.LimitExceededException">
        /// The requested resource exceeds the maximum number allowed, or the number of concurrent
        /// stream requests exceeds the maximum number allowed (5).
        /// </exception>
        /// <exception cref="Amazon.Kinesis.Model.ResourceInUseException">
        /// The resource is not available for this operation. For successful operation, the resource
        /// needs to be in the ACTIVE state.
        /// </exception>
        /// <exception cref="Amazon.Kinesis.Model.ResourceNotFoundException">
        /// The requested resource could not be found. The stream might not be specified correctly,
        /// or it might not be in the ACTIVE state if the operation requires it.
        /// </exception>
        public Task<DecreaseStreamRetentionPeriodResponse> DecreaseStreamRetentionPeriodAsync(string streamName, int retentionPeriodHours, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var request = new DecreaseStreamRetentionPeriodRequest();
            request.StreamName = streamName;
            request.RetentionPeriodHours = retentionPeriodHours;
            return DecreaseStreamRetentionPeriodAsync(request, cancellationToken);
        }

        ///
        /// Initiates the asynchronous execution of the DecreaseStreamRetentionPeriod operation.
        ///
        ///
        /// <param name="request">Container for the necessary parameters to execute the DecreaseStreamRetentionPeriod operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public Task<DecreaseStreamRetentionPeriodResponse> DecreaseStreamRetentionPeriodAsync(DecreaseStreamRetentionPeriodRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new DecreaseStreamRetentionPeriodRequestMarshaller();
            var unmarshaller = DecreaseStreamRetentionPeriodResponseUnmarshaller.Instance;

            return InvokeAsync<DecreaseStreamRetentionPeriodRequest,DecreaseStreamRetentionPeriodResponse>(request, marshaller,
                unmarshaller, cancellationToken);
        }

        #endregion

        #region  DeleteStream

        internal DeleteStreamResponse DeleteStream(DeleteStreamRequest request)
        {
            var marshaller = new DeleteStreamRequestMarshaller();
            var unmarshaller = DeleteStreamResponseUnmarshaller.Instance;

            return Invoke<DeleteStreamRequest,DeleteStreamResponse>(request, marshaller, unmarshaller);
        }

        ///
        /// Initiates the asynchronous execution of the DeleteStream operation.
        ///
        ///
        /// <param name="request">Container for the necessary parameters to execute the DeleteStream operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public Task<DeleteStreamResponse> DeleteStreamAsync(DeleteStreamRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new DeleteStreamRequestMarshaller();
            var unmarshaller = DeleteStreamResponseUnmarshaller.Instance;

            return InvokeAsync<DeleteStreamRequest,DeleteStreamResponse>(request, marshaller,
                unmarshaller, cancellationToken);
        }

        #endregion

        #region  DescribeStream

        internal DescribeStreamResponse DescribeStream(DescribeStreamRequest request)
        {
            var marshaller = new DescribeStreamRequestMarshaller();
            var unmarshaller = DescribeStreamResponseUnmarshaller.Instance;

            return Invoke<DescribeStreamRequest,DescribeStreamResponse>(request, marshaller, unmarshaller);
        }

        ///
        /// Initiates the asynchronous execution of the DescribeStream operation.
        ///
        ///
        /// <param name="request">Container for the necessary parameters to execute the DescribeStream operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public Task<DescribeStreamResponse> DescribeStreamAsync(DescribeStreamRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new DescribeStreamRequestMarshaller();
            var unmarshaller = DescribeStreamResponseUnmarshaller.Instance;

            return InvokeAsync<DescribeStreamRequest,DescribeStreamResponse>(request, marshaller,
                unmarshaller, cancellationToken);
        }

        #endregion

        #region  GetRecords

        internal GetRecordsResponse GetRecords(GetRecordsRequest request)
        {
            var marshaller = new GetRecordsRequestMarshaller();
            var unmarshaller = GetRecordsResponseUnmarshaller.Instance;

            return Invoke<GetRecordsRequest,GetRecordsResponse>(request, marshaller, unmarshaller);
        }

        ///
        /// Initiates the asynchronous execution of the GetRecords operation.
        ///
        ///
        /// <param name="request">Container for the necessary parameters to execute the GetRecords operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public Task<GetRecordsResponse> GetRecordsAsync(GetRecordsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new GetRecordsRequestMarshaller();
            var unmarshaller = GetRecordsResponseUnmarshaller.Instance;

            return InvokeAsync<GetRecordsRequest,GetRecordsResponse>(request, marshaller,
                unmarshaller, cancellationToken);
        }

        #endregion

        #region  GetShardIterator

        internal GetShardIteratorResponse GetShardIterator(GetShardIteratorRequest request)
        {
            var marshaller = new GetShardIteratorRequestMarshaller();
            var unmarshaller = GetShardIteratorResponseUnmarshaller.Instance;

            return Invoke<GetShardIteratorRequest,GetShardIteratorResponse>(request, marshaller, unmarshaller);
        }

        ///
        /// Initiates the asynchronous execution of the GetShardIterator operation.
        ///
        ///
        /// <param name="request">Container for the necessary parameters to execute the GetShardIterator operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public Task<GetShardIteratorResponse> GetShardIteratorAsync(GetShardIteratorRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new GetShardIteratorRequestMarshaller();
            var unmarshaller = GetShardIteratorResponseUnmarshaller.Instance;

            return InvokeAsync<GetShardIteratorRequest,GetShardIteratorResponse>(request, marshaller,
                unmarshaller, cancellationToken);
        }

        #endregion

        #region  IncreaseStreamRetentionPeriod

        internal IncreaseStreamRetentionPeriodResponse IncreaseStreamRetentionPeriod(IncreaseStreamRetentionPeriodRequest request)
        {
            var marshaller = new IncreaseStreamRetentionPeriodRequestMarshaller();
            var unmarshaller = IncreaseStreamRetentionPeriodResponseUnmarshaller.Instance;

            return Invoke<IncreaseStreamRetentionPeriodRequest,IncreaseStreamRetentionPeriodResponse>(request, marshaller, unmarshaller);
        }

        ///
        /// Increases the stream's retention period, which is the length of time data records
        /// are accessible after they are added to the stream. The maximum value of a stream's
        /// retention period is 168 hours (7 days).
        ///
        ///
        /// <para>
        /// Upon choosing a longer stream retention period, this operation will increase the time
        /// period records are accessible that have not yet expired. However, it will not make
        /// previous data that has expired (older than the stream's previous retention period)
        /// accessible after the operation has been called. For example, if a stream's retention
        /// period is set to 24 hours and is increased to 168 hours, any data that is older than
        /// 24 hours will remain inaccessible to consumer applications.
        /// </para>
        ///
        /// <param name="streamName">The name of the stream to modify.</param>
        /// <param name="retentionPeriodHours">The new retention period of the stream, in hours. Must be more than the current retention period.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        ///
        /// <returns>The response from the IncreaseStreamRetentionPeriod service method, as returned by Kinesis.</returns>
        /// <exception cref="Amazon.Kinesis.Model.InvalidArgumentException">
        /// A specified parameter exceeds its restrictions, is not supported, or can't be used.
        /// For more information, see the returned message.
        /// </exception>
        /// <exception cref="Amazon.Kinesis.Model.LimitExceededException">
        /// The requested resource exceeds the maximum number allowed, or the number of concurrent
        /// stream requests exceeds the maximum number allowed (5).
        /// </exception>
        /// <exception cref="Amazon.Kinesis.Model.ResourceInUseException">
        /// The resource is not available for this operation. For successful operation, the resource
        /// needs to be in the ACTIVE state.
        /// </exception>
        /// <exception cref="Amazon.Kinesis.Model.ResourceNotFoundException">
        /// The requested resource could not be found. The stream might not be specified correctly,
        /// or it might not be in the ACTIVE state if the operation requires it.
        /// </exception>
        public Task<IncreaseStreamRetentionPeriodResponse> IncreaseStreamRetentionPeriodAsync(string streamName, int retentionPeriodHours, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var request = new IncreaseStreamRetentionPeriodRequest();
            request.StreamName = streamName;
            request.RetentionPeriodHours = retentionPeriodHours;
            return IncreaseStreamRetentionPeriodAsync(request, cancellationToken);
        }

        ///
        /// Initiates the asynchronous execution of the IncreaseStreamRetentionPeriod operation.
        ///
        ///
        /// <param name="request">Container for the necessary parameters to execute the IncreaseStreamRetentionPeriod operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public Task<IncreaseStreamRetentionPeriodResponse> IncreaseStreamRetentionPeriodAsync(IncreaseStreamRetentionPeriodRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new IncreaseStreamRetentionPeriodRequestMarshaller();
            var unmarshaller = IncreaseStreamRetentionPeriodResponseUnmarshaller.Instance;

            return InvokeAsync<IncreaseStreamRetentionPeriodRequest,IncreaseStreamRetentionPeriodResponse>(request, marshaller,
                unmarshaller, cancellationToken);
        }

        #endregion

        #region  ListStreams

        internal ListStreamsResponse ListStreams()
        {
            return ListStreams(new ListStreamsRequest());
        }
        internal ListStreamsResponse ListStreams(ListStreamsRequest request)
        {
            var marshaller = new ListStreamsRequestMarshaller();
            var unmarshaller = ListStreamsResponseUnmarshaller.Instance;

            return Invoke<ListStreamsRequest,ListStreamsResponse>(request, marshaller, unmarshaller);
        }

        ///
        /// Lists your streams.
        ///
        ///
        /// <para>
        ///  The number of streams may be too large to return from a single call to ListStreams.
        /// You can limit the number of returned streams using the Limit parameter.
        /// If you do not specify a value for the Limit parameter, Amazon Kinesis
        /// uses the default limit, which is currently 10.
        /// </para>
        ///
        /// <para>
        ///  You can detect if there are more streams available to list by using the HasMoreStreams
        /// flag from the returned output. If there are more streams available, you can request
        /// more streams by using the name of the last stream returned by the ListStreams
        /// request in the ExclusiveStartStreamName parameter in a subsequent request
        /// to ListStreams. The group of stream names returned by the subsequent
        /// request is then added to the list. You can continue this process until all the stream
        /// names have been collected in the list.
        /// </para>
        ///
        /// <para>
        /// ListStreams has a limit of 5 transactions per second per account.
        /// </para>
        ///
        /// <param name="cancellationToken"> ttd1
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        ///
        /// <returns>The response from the ListStreams service method, as returned by Kinesis.</returns>
        /// <exception cref="Amazon.Kinesis.Model.LimitExceededException">
        /// The requested resource exceeds the maximum number allowed, or the number of concurrent
        /// stream requests exceeds the maximum number allowed (5).
        /// </exception>
        public Task<ListStreamsResponse> ListStreamsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            return ListStreamsAsync(new ListStreamsRequest(), cancellationToken);
        }

        ///
        /// Initiates the asynchronous execution of the ListStreams operation.
        ///
        ///
        /// <param name="request">Container for the necessary parameters to execute the ListStreams operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public Task<ListStreamsResponse> ListStreamsAsync(ListStreamsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new ListStreamsRequestMarshaller();
            var unmarshaller = ListStreamsResponseUnmarshaller.Instance;

            return InvokeAsync<ListStreamsRequest,ListStreamsResponse>(request, marshaller,
                unmarshaller, cancellationToken);
        }

        #endregion

        #region  ListTagsForStream

        internal ListTagsForStreamResponse ListTagsForStream(ListTagsForStreamRequest request)
        {
            var marshaller = new ListTagsForStreamRequestMarshaller();
            var unmarshaller = ListTagsForStreamResponseUnmarshaller.Instance;

            return Invoke<ListTagsForStreamRequest,ListTagsForStreamResponse>(request, marshaller, unmarshaller);
        }

        ///
        /// Initiates the asynchronous execution of the ListTagsForStream operation.
        ///
        ///
        /// <param name="request">Container for the necessary parameters to execute the ListTagsForStream operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public Task<ListTagsForStreamResponse> ListTagsForStreamAsync(ListTagsForStreamRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new ListTagsForStreamRequestMarshaller();
            var unmarshaller = ListTagsForStreamResponseUnmarshaller.Instance;

            return InvokeAsync<ListTagsForStreamRequest,ListTagsForStreamResponse>(request, marshaller,
                unmarshaller, cancellationToken);
        }

        #endregion

        #region  MergeShards

        internal MergeShardsResponse MergeShards(MergeShardsRequest request)
        {
            var marshaller = new MergeShardsRequestMarshaller();
            var unmarshaller = MergeShardsResponseUnmarshaller.Instance;

            return Invoke<MergeShardsRequest,MergeShardsResponse>(request, marshaller, unmarshaller);
        }

        ///
        /// Initiates the asynchronous execution of the MergeShards operation.
        ///
        ///
        /// <param name="request">Container for the necessary parameters to execute the MergeShards operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public Task<MergeShardsResponse> MergeShardsAsync(MergeShardsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new MergeShardsRequestMarshaller();
            var unmarshaller = MergeShardsResponseUnmarshaller.Instance;

            return InvokeAsync<MergeShardsRequest,MergeShardsResponse>(request, marshaller,
                unmarshaller, cancellationToken);
        }

        #endregion

        #region  PutRecord

        internal PutRecordResponse PutRecord(PutRecordRequest request)
        {
            var marshaller = new PutRecordRequestMarshaller();
            var unmarshaller = PutRecordResponseUnmarshaller.Instance;

            return Invoke<PutRecordRequest,PutRecordResponse>(request, marshaller, unmarshaller);
        }

        ///
        /// Initiates the asynchronous execution of the PutRecord operation.
        ///
        ///
        /// <param name="request">Container for the necessary parameters to execute the PutRecord operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public Task<PutRecordResponse> PutRecordAsync(PutRecordRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new PutRecordRequestMarshaller();
            var unmarshaller = PutRecordResponseUnmarshaller.Instance;

            return InvokeAsync<PutRecordRequest,PutRecordResponse>(request, marshaller,
                unmarshaller, cancellationToken);
        }

        #endregion

        #region  PutRecords

        internal PutRecordsResponse PutRecords(PutRecordsRequest request)
        {
            var marshaller = new PutRecordsRequestMarshaller();
            var unmarshaller = PutRecordsResponseUnmarshaller.Instance;

            return Invoke<PutRecordsRequest,PutRecordsResponse>(request, marshaller, unmarshaller);
        }

        ///
        /// Initiates the asynchronous execution of the PutRecords operation.
        ///
        ///
        /// <param name="request">Container for the necessary parameters to execute the PutRecords operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public Task<PutRecordsResponse> PutRecordsAsync(PutRecordsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new PutRecordsRequestMarshaller();
            var unmarshaller = PutRecordsResponseUnmarshaller.Instance;

            return InvokeAsync<PutRecordsRequest,PutRecordsResponse>(request, marshaller,
                unmarshaller, cancellationToken);
        }

        #endregion

        #region  RemoveTagsFromStream

        internal RemoveTagsFromStreamResponse RemoveTagsFromStream(RemoveTagsFromStreamRequest request)
        {
            var marshaller = new RemoveTagsFromStreamRequestMarshaller();
            var unmarshaller = RemoveTagsFromStreamResponseUnmarshaller.Instance;

            return Invoke<RemoveTagsFromStreamRequest,RemoveTagsFromStreamResponse>(request, marshaller, unmarshaller);
        }

        ///
        /// Initiates the asynchronous execution of the RemoveTagsFromStream operation.
        ///
        ///
        /// <param name="request">Container for the necessary parameters to execute the RemoveTagsFromStream operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public Task<RemoveTagsFromStreamResponse> RemoveTagsFromStreamAsync(RemoveTagsFromStreamRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new RemoveTagsFromStreamRequestMarshaller();
            var unmarshaller = RemoveTagsFromStreamResponseUnmarshaller.Instance;

            return InvokeAsync<RemoveTagsFromStreamRequest,RemoveTagsFromStreamResponse>(request, marshaller,
                unmarshaller, cancellationToken);
        }

        #endregion

        #region  SplitShard

        internal SplitShardResponse SplitShard(SplitShardRequest request)
        {
            var marshaller = new SplitShardRequestMarshaller();
            var unmarshaller = SplitShardResponseUnmarshaller.Instance;

            return Invoke<SplitShardRequest,SplitShardResponse>(request, marshaller, unmarshaller);
        }

        ///
        /// Initiates the asynchronous execution of the SplitShard operation.
        ///
        ///
        /// <param name="request">Container for the necessary parameters to execute the SplitShard operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public Task<SplitShardResponse> SplitShardAsync(SplitShardRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new SplitShardRequestMarshaller();
            var unmarshaller = SplitShardResponseUnmarshaller.Instance;

            return InvokeAsync<SplitShardRequest,SplitShardResponse>(request, marshaller,
                unmarshaller, cancellationToken);
        }

        #endregion

    }
}


text:
package model

import "github.com/ionous/sashimi/util/ident"

type PropertyType string

const (
	NumProperty     PropertyType = "NumProperty"
	TextProperty                 = "TextProperty"
	PointerProperty              = "PointerProperty"
	EnumProperty                 = "EnumProperty"
)

type PropertyModel struct {
	Id   ident.Id     `json:"id"`
	Type PropertyType `json:"type"`
	Name string       `json:"name"`
	// pointer, relation
	Relates ident.Id `json:"relates,omitempty"`
	// relation
	Relation ident.Id `json:"relation,omitempty"`
	// num, text, pointer, relation; but, not enum
	IsMany bool `json:"many,omitempty"`
}


text:
//                 HFDownLoad
//                 HFSession.m
//

#import "HFSession.h"

@interface HFSession () <NSURLSessionDownloadDelegate>

@property (weak, nonatomic) IBOutlet UILabel *pgLabel;

@property (weak, nonatomic) IBOutlet UIProgressView *myPregress;
/**
 *  下载任务
 */
@property (nonatomic, strong) NSURLSessionDownloadTask* downloadTask;
/**
 *  resumeData记录下载位置
 */
@property (nonatomic, strong) NSData* resumeData;
/**
 *  session
 */
@property (nonatomic, strong) NSURLSession* session;

@end

@implementation HFSession
/**
 *  session的懒加载
 */
- (NSURLSession *)session
{
    if (nil == _session) {

        NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
        self.session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    }
    return _session;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

}
/**
 *  从0开始下载
 */
- (void)startDownload
{
#warning 使用我们自己服务器的地址执行断点下载没问题,但是百度软件的下载链接不成功,应该是百度服务器做了限制吧,或者我写的不完美,有想法欢迎交流
//    NSURL* url = [NSURL URLWithString:@"http://localhost:8080/shudai99/resources/The_Fixer.mp4"];
    NSURL* url = [NSURL URLWithString:@"http://dlsw.baidu.com/sw-search-sp/soft/9d/25765/sogou_mac_32c_V3.2.0.1437101586.dmg"];

    // 创建任务
    self.downloadTask = [self.session downloadTaskWithURL:url];

    // 开始任务
    [self.downloadTask resume];
}

/**
 *  恢复下载
 */

- (void)resume
{
     // 传入上次暂停下载返回的数据,就可以恢复下载
    self.downloadTask = [self.session downloadTaskWithResumeData:self.resumeData];

    [self.downloadTask resume]; // 开始任务

    self.resumeData = nil;
}

/**
 *  暂停
 */
- (void)pause
{
    __weak typeof(self) selfVc = self;
    [self.downloadTask cancelByProducingResumeData:^(NSData *resumeData) {
        //  resumeData : 包含了继续下载的开始位置\下载的url
        selfVc.resumeData = resumeData;
        selfVc.downloadTask = nil;
    }];
}

#pragma mark -- NSURLSessionDownloadDelegate
/**
 *  下载完毕会调用
 *
 *  @param location     文件临时地址
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    // response.suggestedFilename : 建议使用的文件名,一般跟服务器端的文件名一致
    NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];

    // 将临时文件剪切或者复制Caches文件夹
    NSFileManager *mgr = [NSFileManager defaultManager];

    // AtPath : 剪切前的文件路径
    // ToPath : 剪切后的文件路径
    [mgr moveItemAtPath:location.path toPath:file error:nil];

    // 提示下载完成
    [[[UIAlertView alloc] initWithTitle:@"下载完成" message:downloadTask.response.suggestedFilename delegate:self cancelButtonTitle:@"知道了" otherButtonTitles: nil] show];
}

/**
 *  每次写入沙盒完毕调用
 *  在这里面监听下载进度,totalBytesWritten/totalBytesExpectedToWrite
 *
 *  @param bytesWritten              这次写入的大小
 *  @param totalBytesWritten         已经写入沙盒的大小
 *  @param totalBytesExpectedToWrite 文件总大小
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    self.myPregress.progress = (double)totalBytesWritten/totalBytesExpectedToWrite;
    self.pgLabel.text = [NSString stringWithFormat:@"下载进度:%f",(double)totalBytesWritten/totalBytesExpectedToWrite];
}

/**
 *  恢复下载后调用,
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes
{

}

#pragma mark --按钮点击事件

- (IBAction)btnClicked:(UIButton *)sender {

    // 按钮状态取反
    sender.selected = !sender.isSelected;

    if (nil == self.downloadTask) { // 开始(继续)下载
        if (self.resumeData) { // 继续下载
            [self resume];
        }else{ // 从0开始下载
            [self startDownload];
        }

    }else{ // 暂停
        [self pause];
    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/**
 *  Sesstion 简单执行下载
 */
- (void)SesstionDownLoad
{
    NSURL* url = [NSURL URLWithString:@"http://dlsw.baidu.com/sw-search-sp/soft/9d/25765/sogou_mac_32c_V3.2.0.1437101586.dmg"];

    // 得到session对象
    NSURLSession* session = [NSURLSession sharedSession];

    // 创建任务
    NSURLSessionDownloadTask* downloadTask = [session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
        // location : 临时文件的路径(下载好的文件)

        NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        // response.suggestedFilename : 建议使用的文件名,一般跟服务器端的文件名一致
        NSString *file = [caches stringByAppendingPathComponent:response.suggestedFilename];

        // 将临时文件剪切或者复制Caches文件夹
        NSFileManager *mgr = [NSFileManager defaultManager];

        // AtPath : 剪切前的文件路径
        // ToPath : 剪切后的文件路径
        [mgr moveItemAtPath:location.path toPath:file error:nil];
    }];

    // 开始任务
    [downloadTask resume];
}

/**
 *  NSURLSession简单使用
 */
- (void)sessiondemo
{
    // 1.得到session对象
    NSURLSession* session = [NSURLSession sharedSession];
    NSURL* url = [NSURL URLWithString:@""];

    // 2.创建一个task,任务
    NSURLSessionDataTask* dataTask = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        // data 为返回数据
    }];

    // 发送POST
//    [session dataTaskWithRequest:<#(NSURLRequest *)#> completionHandler:<#^(NSData *data, NSURLResponse *response, NSError *error)completionHandler#>]

    // 3.开始任务
    [dataTask resume];
}

@end


text:
import {combineReducers} from 'redux'

import search             from './components/AppSearch/reducer'
import maps               from './scenes/Maps/reducer'
import mapOverview        from './scenes/MapOverview/reducer'
import activity           from './scenes/Home/scenes/Activity/reducer'
import playerOverview     from './scenes/PlayerOverview/reducer'
import playerLeaderboards from './scenes/PlayerLeaderboards/reducer'
import servers            from './scenes/Home/reducer.js'
import serverDemos        from './scenes/Home/scenes/Server/scenes/ServerDemoList/reducer.js'
import demoOverview       from './scenes/DemoOverview/reducer.js'
import recordOverview     from './scenes/RecordOverview/reducer.js'

export default combineReducers(
  { search
  , maps
  , mapOverview
  , activity
  , playerOverview
  , playerLeaderboards
  , servers
  , serverDemos
  , demoOverview
  , recordOverview
  })