text:
#include "OgreStableHeaders.h"
#include "OgreInstanceBatchVTF.h"
#include "OgreSubMesh.h"
#include "OgreHardwareBufferManager.h"
#include "OgreHardwarePixelBuffer.h"
#include "OgreInstancedEntity.h"
#include "OgreMaterial.h"
#include "OgreTechnique.h"
#include "OgreMaterialManager.h"
#include "OgreTextureManager.h"
#include "OgreRoot.h"
#include "OgreDualQuaternion.h"

namespace Ogre
{
    static const uint16 c_maxTexWidth   = 4096;
    static const uint16 c_maxTexHeight  = 4096;

    BaseInstanceBatchVTF::BaseInstanceBatchVTF( IdType id, ObjectMemoryManager *objectMemoryManager,
                                        InstanceManager *creator, MeshPtr &meshReference,
                                        const MaterialPtr &material, size_t instancesPerBatch,
                                        const Mesh::IndexMap *indexToBoneMap ) :
                InstanceBatch( id, objectMemoryManager, creator, meshReference, material,
                                instancesPerBatch, indexToBoneMap ),
                mNumWorldMatrices( instancesPerBatch ),
                mWidthFloatsPadding( 0 ),
                mMaxFloatsPerLine( std::numeric_limits<size_t>::max() ),
                mRowLength(3),
                mWeightCount(1),
                mTempTransformsArray3x4(0),
                mMaxLookupTableInstances(16),
                mUseBoneDualQuaternions(false),
                mForceOneWeight(false),
                mUseOneWeight(false)
    {
        cloneMaterial( mMaterial );
    }

    BaseInstanceBatchVTF::~BaseInstanceBatchVTF()
    {
        //Remove cloned caster materials (if any)
        Material::TechniqueIterator techItor = mMaterial->getTechniqueIterator();
        while( techItor.hasMoreElements() )
        {
            Technique *technique = techItor.getNext();

            if( !technique->getShadowCasterMaterial().isNull() )
                MaterialManager::getSingleton().remove( technique->getShadowCasterMaterial()->getName() );
        }

        //Remove cloned material
        MaterialManager::getSingleton().remove( mMaterial->getName() );

        //Remove the VTF texture
        if( !mMatrixTexture.isNull() )
            TextureManager::getSingleton().remove( mMatrixTexture->getName() );

        OGRE_FREE(mTempTransformsArray3x4, MEMCATEGORY_GENERAL);
    }

    //-----------------------------------------------------------------------
    void BaseInstanceBatchVTF::buildFrom( const SubMesh *baseSubMesh, const RenderOperation &renderOperation )
    {
        if (useBoneMatrixLookup())
        {
            //when using bone matrix lookup resource are not shared
            //
            //Future implementation: while the instance vertex buffer can't be shared
            //The texture can be.
            //
            build(baseSubMesh);
        }
        else
        {
            createVertexTexture( baseSubMesh );
            InstanceBatch::buildFrom( baseSubMesh, renderOperation );
        }
    }
    //-----------------------------------------------------------------------
    void BaseInstanceBatchVTF::cloneMaterial( const MaterialPtr &material )
    {
        //Used to track down shadow casters, so the same material caster doesn't get cloned twice
        typedef map<String, MaterialPtr>::type MatMap;
        MatMap clonedMaterials;

        //We need to clone the material so we can have different textures for each batch.
        mMaterial = material->clone( mName + "/VTFMaterial" );

        //Now do the same with the techniques which have a material shadow caster
        Material::TechniqueIterator techItor = material->getTechniqueIterator();
        while( techItor.hasMoreElements() )
        {
            Technique *technique = techItor.getNext();

            if( !technique->getShadowCasterMaterial().isNull() )
            {
                const MaterialPtr &casterMat    = technique->getShadowCasterMaterial();
                const String &casterName        = casterMat->getName();

                //Was this material already cloned?
                MatMap::const_iterator itor = clonedMaterials.find(casterName);

                if( itor == clonedMaterials.end() )
                {
                    //No? Clone it and track it
                    MaterialPtr cloned = casterMat->clone( mName + "/VTFMaterialCaster" +
                                                    StringConverter::toString(clonedMaterials.size()) );
                    technique->setShadowCasterMaterial( cloned );
                    clonedMaterials[casterName] = cloned;
                }
                else
                    technique->setShadowCasterMaterial( itor->second ); //Reuse the previously cloned mat
            }
        }
    }
    //-----------------------------------------------------------------------
    void BaseInstanceBatchVTF::retrieveBoneIdx( VertexData *baseVertexData, HWBoneIdxVec &outBoneIdx )
    {
        const VertexElement *ve = baseVertexData->vertexDeclaration->
                                                            findElementBySemantic( VES_BLEND_INDICES );
        const VertexElement *veWeights = baseVertexData->vertexDeclaration->findElementBySemantic( VES_BLEND_WEIGHTS );

        HardwareVertexBufferSharedPtr buff = baseVertexData->vertexBufferBinding->getBuffer(ve->getSource());
        char const *baseBuffer = static_cast<char const*>(buff->lock( HardwareBuffer::HBL_READ_ONLY ));

        for( size_t i=0; i<baseVertexData->vertexCount; ++i )
        {
            float const *pWeights = reinterpret_cast<float const*>(baseBuffer + veWeights->getOffset());

            uint8 biggestWeightIdx = 0;
            for( size_t j=1; j< mWeightCount; ++j )
            {
                biggestWeightIdx = pWeights[biggestWeightIdx] < pWeights[j] ? j : biggestWeightIdx;
            }

            uint8 const *pIndex = reinterpret_cast<uint8 const*>(baseBuffer + ve->getOffset());
            outBoneIdx[i] = pIndex[biggestWeightIdx];

            baseBuffer += baseVertexData->vertexDeclaration->getVertexSize(ve->getSource());
        }

        buff->unlock();
    }

    //-----------------------------------------------------------------------
    void BaseInstanceBatchVTF::retrieveBoneIdxWithWeights(VertexData *baseVertexData, HWBoneIdxVec &outBoneIdx, HWBoneWgtVec &outBoneWgt)
    {
        const VertexElement *ve = baseVertexData->vertexDeclaration->findElementBySemantic( VES_BLEND_INDICES );
        const VertexElement *veWeights = baseVertexData->vertexDeclaration->findElementBySemantic( VES_BLEND_WEIGHTS );

        HardwareVertexBufferSharedPtr buff = baseVertexData->vertexBufferBinding->getBuffer(ve->getSource());
        char const *baseBuffer = static_cast<char const*>(buff->lock( HardwareBuffer::HBL_READ_ONLY ));

        for( size_t i=0; i<baseVertexData->vertexCount * mWeightCount; i += mWeightCount)
        {
            float const *pWeights = reinterpret_cast<float const*>(baseBuffer + veWeights->getOffset());
            uint8 const *pIndex = reinterpret_cast<uint8 const*>(baseBuffer + ve->getOffset());

            float weightMagnitude = 0.0f;
            for( size_t j=0; j < mWeightCount; ++j )
            {
                outBoneWgt[i+j] = pWeights[j];
                weightMagnitude += pWeights[j];
                outBoneIdx[i+j] = pIndex[j];
            }

            //Normalize the bone weights so they add to one
            for(size_t j=0; j < mWeightCount; ++j)
            {
                outBoneWgt[i+j] /= weightMagnitude;
            }

            baseBuffer += baseVertexData->vertexDeclaration->getVertexSize(ve->getSource());
        }

        buff->unlock();
    }

    //-----------------------------------------------------------------------
    void BaseInstanceBatchVTF::setupMaterialToUseVTF( TextureType textureType, MaterialPtr &material )
    {
        Material::TechniqueIterator techItor = material->getTechniqueIterator();
        while( techItor.hasMoreElements() )
        {
            Technique *technique = techItor.getNext();
            Technique::PassIterator passItor = technique->getPassIterator();

            while( passItor.hasMoreElements() )
            {
                bool bTexUnitFound = false;

                Pass *pass = passItor.getNext();
                Pass::TextureUnitStateIterator texUnitItor = pass->getTextureUnitStateIterator();

                while( texUnitItor.hasMoreElements() && !bTexUnitFound )
                {
                    TextureUnitState *texUnit = texUnitItor.getNext();

                    if( texUnit->getName() == "InstancingVTF" )
                    {
                        texUnit->setTextureName( mMatrixTexture->getName(), textureType );
                        texUnit->setTextureFiltering( TFO_NONE );
                        texUnit->setBindingType( TextureUnitState::BT_VERTEX );
                    }
                }
            }

            if( !technique->getShadowCasterMaterial().isNull() )
            {
                MaterialPtr matCaster = technique->getShadowCasterMaterial();
                setupMaterialToUseVTF( textureType, matCaster );
            }
        }
    }
    //-----------------------------------------------------------------------
    void BaseInstanceBatchVTF::createVertexTexture( const SubMesh* baseSubMesh )
    {
        /*
        TODO: Find a way to retrieve max texture resolution,
        http://www.ogre3d.org/forums/viewtopic.php?t=38305

        Currently assuming it's 4096x4096, which is a safe bet for any hardware with decent VTF*/

        size_t uniqueAnimations = mInstancesPerBatch;
        if (useBoneMatrixLookup())
        {
            uniqueAnimations = std::min<size_t>(getMaxLookupTableInstances(), uniqueAnimations);
        }
        mMatricesPerInstance = std::max<size_t>( 1, baseSubMesh->blendIndexToBoneIndexMap.size() );

        if(mUseBoneDualQuaternions && !mTempTransformsArray3x4)
        {
            mTempTransformsArray3x4 = OGRE_ALLOC_T(float, mMatricesPerInstance * 3 * 4, MEMCATEGORY_GENERAL);
        }

        mNumWorldMatrices = uniqueAnimations * mMatricesPerInstance;

        //Calculate the width & height required to hold all the matrices. Start by filling the width
        //first (i.e. 4096x1 4096x2 4096x3, etc)

        size_t texWidth         = std::min<size_t>( mNumWorldMatrices * mRowLength, c_maxTexWidth );
        size_t maxUsableWidth   = texWidth;
        if( matricesTogetherPerRow() )
        {
            //The technique requires all matrices from the same instance in the same row
            //i.e. 4094 -> 4095 -> skip 4096 -> 0 (next row) contains data from a new instance
            mWidthFloatsPadding = texWidth % (mMatricesPerInstance * mRowLength);

            if( mWidthFloatsPadding )
            {
                mMaxFloatsPerLine = texWidth - mWidthFloatsPadding;

                maxUsableWidth = mMaxFloatsPerLine;

                //Values are in pixels, convert them to floats (1 pixel = 4 floats)
                mWidthFloatsPadding *= 4;
                mMaxFloatsPerLine       *= 4;
            }
        }

        size_t texHeight = mNumWorldMatrices * mRowLength / maxUsableWidth;

        if( (mNumWorldMatrices * mRowLength) % maxUsableWidth )
            texHeight += 1;

        //Don't use 1D textures, as OGL goes crazy because the shader should be calling texture1D()...
        //TextureType texType = texHeight == 1 ? TEX_TYPE_1D : TEX_TYPE_2D;
        TextureType texType = TEX_TYPE_2D;

        mMatrixTexture = TextureManager::getSingleton().createManual(
                                        mName + "/VTF", mMeshReference->getGroup(), texType,
                                        (uint)texWidth, (uint)texHeight,
                                        0, PF_FLOAT32_RGBA, TU_DYNAMIC_WRITE_ONLY_DISCARDABLE );

        //Set our cloned material to use this custom texture!
        setupMaterialToUseVTF( texType, mMaterial );
    }

    //-----------------------------------------------------------------------
    size_t BaseInstanceBatchVTF::convert3x4MatricesToDualQuaternions(float* matrices, size_t numOfMatrices, float* outDualQuaternions)
    {
        DualQuaternion dQuat;
        Matrix4 matrix;
        size_t floatsWritten = 0;

        for (size_t m = 0; m < numOfMatrices; ++m)
        {
            for(int i = 0; i < 3; ++i)
            {
                for(int b = 0; b < 4; ++b)
                {
                    matrix[i][b] = *matrices++;
                }
            }

            matrix[3][0] = 0;
            matrix[3][1] = 0;
            matrix[3][2] = 0;
            matrix[3][3] = 1;

            dQuat.fromTransformationMatrix(matrix);

            //Copy the 2x4 matrix
            for(int i = 0; i < 8; ++i)
            {
                *outDualQuaternions++ = static_cast<float>( dQuat[i] );
                ++floatsWritten;
            }
        }

        return floatsWritten;
    }

    //-----------------------------------------------------------------------
    void BaseInstanceBatchVTF::updateVertexTexture(void)
    {
        //Now lock the texture and copy the 4x3 matrices!
        mMatrixTexture->getBuffer()->lock( HardwareBuffer::HBL_DISCARD );
        const PixelBox &pixelBox = mMatrixTexture->getBuffer()->getCurrentLock();

        float *pDest = static_cast<float*>(pixelBox.data);

        InstancedEntityVec::const_iterator itor = mInstancedEntities.begin();
        InstancedEntityVec::const_iterator end  = mInstancedEntities.end();

        float* transforms;

        //If using dual quaternion skinning, write the transforms to a temporary buffer,
        //then convert to dual quaternions, then later write to the pixel buffer
        //Otherwise simply write the transforms to the pixel buffer directly
        if(mUseBoneDualQuaternions)
        {
            transforms = mTempTransformsArray3x4;
        }
        else
        {
            transforms = pDest;
        }

        while( itor != end )
        {
            size_t floatsWritten = (*itor)->getTransforms3x4( transforms );

            if(mUseBoneDualQuaternions)
            {
                floatsWritten = convert3x4MatricesToDualQuaternions(transforms, floatsWritten / 12, pDest);
                pDest += floatsWritten;
            }
            else
            {
                transforms += floatsWritten;
            }

            ++itor;
        }

        mMatrixTexture->getBuffer()->unlock();
    }
    /** update the lookup numbers for entities with shared transforms */
    void BaseInstanceBatchVTF::updateSharedLookupIndexes()
    {
        if (mTransformSharingDirty)
        {
            if (useBoneMatrixLookup())
            {
                //In each entity update the "transform lookup number" so that:
                // 1. All entities sharing the same transformation will share the same unique number
                // 2. "transform lookup number" will be numbered from 0 up to getMaxLookupTableInstances
                size_t lookupCounter = 0;
#ifdef OGRE_LEGACY_ANIMATIONS
                typedef map<OldSkeletonInstance*,size_t>::type MapTransformId;
#else
                typedef map<SkeletonInstance*,size_t>::type MapTransformId;
#endif
                MapTransformId transformToId;
                InstancedEntityVec::const_iterator itEnt = mInstancedEntities.begin(),
                    itEntEnd = mInstancedEntities.end();
                for(;itEnt != itEntEnd ; ++itEnt)
                {
                    if ((*itEnt)->isInScene())
                    {
#ifdef OGRE_LEGACY_ANIMATIONS
                        OldSkeletonInstance* transformUniqueId = (*itEnt)->mSkeletonInstance;
#else
                        SkeletonInstance* transformUniqueId = (*itEnt)->mSkeletonInstance;
#endif
                        MapTransformId::iterator itLu = transformToId.find(transformUniqueId);
                        if (itLu == transformToId.end())
                        {
                            itLu = transformToId.insert(MapTransformId::value_type(transformUniqueId,lookupCounter)).first;
                            ++lookupCounter;
                        }
                        (*itEnt)->setTransformLookupNumber(itLu->second);
                    }
                    else
                    {
                        (*itEnt)->setTransformLookupNumber(0);
                    }
                }

                if (lookupCounter > getMaxLookupTableInstances())
                {
                    OGRE_EXCEPT(Exception::ERR_INVALID_STATE,"Number of unique bone matrix states exceeds current limitation.","BaseInstanceBatchVTF::updateSharedLookupIndexes()");
                }
            }

            mTransformSharingDirty = false;
        }
    }

    //-----------------------------------------------------------------------
    InstancedEntity* BaseInstanceBatchVTF::generateInstancedEntity(size_t num)
    {
        InstancedEntity* sharedTransformEntity = NULL;
        if ((useBoneMatrixLookup()) && (num >= getMaxLookupTableInstances()))
        {
            sharedTransformEntity = mInstancedEntities[num % getMaxLookupTableInstances()];
            if (sharedTransformEntity->mSharedTransformEntity)
            {
                sharedTransformEntity = sharedTransformEntity->mSharedTransformEntity;
            }
        }

        return OGRE_NEW InstancedEntity( Id::generateNewId<InstancedEntity>(),
                                         &mLocalObjectMemoryManager,
                                         this, static_cast<uint32>(num),
                                 #ifndef OGRE_LEGACY_ANIMATIONS
                                         0,
                                 #endif
                                         sharedTransformEntity );
    }

    //-----------------------------------------------------------------------
    void BaseInstanceBatchVTF::getWorldTransforms( Matrix4* xform ) const
    {
        *xform = Matrix4::IDENTITY;
    }
    //-----------------------------------------------------------------------
    unsigned short BaseInstanceBatchVTF::getNumWorldTransforms(void) const
    {
        return 1;
    }
    //-----------------------------------------------------------------------
    void BaseInstanceBatchVTF::_updateRenderQueue(RenderQueue* queue, Camera *camera,
                                                  const Camera *lodCamera)
    {
        InstanceBatch::_updateRenderQueue( queue, camera, lodCamera );
    }
    //-----------------------------------------------------------------------
    // InstanceBatchVTF
    //-----------------------------------------------------------------------
    InstanceBatchVTF::InstanceBatchVTF(
        IdType id, ObjectMemoryManager *objectMemoryManager,
        InstanceManager *creator, MeshPtr &meshReference,
        const MaterialPtr &material, size_t instancesPerBatch,
        const Mesh::IndexMap *indexToBoneMap )
            : BaseInstanceBatchVTF (id, objectMemoryManager, creator, meshReference, material,
                                    instancesPerBatch, indexToBoneMap)
    {

    }
    //-----------------------------------------------------------------------
    InstanceBatchVTF::~InstanceBatchVTF()
    {
    }
    //-----------------------------------------------------------------------
    void InstanceBatchVTF::setupVertices( const SubMesh* baseSubMesh )
    {
        mRenderOperation.vertexData = OGRE_NEW VertexData();
        mRemoveOwnVertexData = true; //Raise flag to remove our own vertex data in the end (not always needed)

        VertexData *thisVertexData = mRenderOperation.vertexData;
        VertexData *baseVertexData = baseSubMesh->vertexData;

        thisVertexData->vertexStart = 0;
        thisVertexData->vertexCount = baseVertexData->vertexCount * mInstancesPerBatch;

        HardwareBufferManager::getSingleton().destroyVertexDeclaration( thisVertexData->vertexDeclaration );
        thisVertexData->vertexDeclaration = baseVertexData->vertexDeclaration->clone();

        HWBoneIdxVec hwBoneIdx;
        HWBoneWgtVec hwBoneWgt;

        //Blend weights may not be present because HW_VTF does not require to be skeletally animated
        const VertexElement *veWeights = baseVertexData->vertexDeclaration->
                                                    findElementBySemantic( VES_BLEND_WEIGHTS );
        if( veWeights )
        {
            //One weight is recommended for VTF
            mWeightCount = (forceOneWeight() || useOneWeight()) ?
                                1 : veWeights->getSize() / sizeof(float);
        }
        else
        {
            mWeightCount = 1;
        }

        hwBoneIdx.resize( baseVertexData->vertexCount * mWeightCount, 0 );

        if( mMeshReference->hasSkeleton() && !mMeshReference->getOldSkeleton().isNull() )
        {
            if(mWeightCount > 1)
            {
                hwBoneWgt.resize( baseVertexData->vertexCount * mWeightCount, 0 );
                retrieveBoneIdxWithWeights(baseVertexData, hwBoneIdx, hwBoneWgt);
            }
            else
            {
                retrieveBoneIdx( baseVertexData, hwBoneIdx );
                thisVertexData->vertexDeclaration->removeElement( VES_BLEND_INDICES );
                thisVertexData->vertexDeclaration->removeElement( VES_BLEND_WEIGHTS );

                thisVertexData->vertexDeclaration->closeGapsInSource();
            }

        }

        for( unsigned short i=0; i<thisVertexData->vertexDeclaration->getMaxSource()+1; ++i )
        {
            //Create our own vertex buffer
            HardwareVertexBufferSharedPtr vertexBuffer =
                HardwareBufferManager::getSingleton().createVertexBuffer(
                thisVertexData->vertexDeclaration->getVertexSize(i),
                thisVertexData->vertexCount,
                HardwareBuffer::HBU_STATIC_WRITE_ONLY );
            thisVertexData->vertexBufferBinding->setBinding( i, vertexBuffer );

            //Grab the base submesh data
            HardwareVertexBufferSharedPtr baseVertexBuffer =
                baseVertexData->vertexBufferBinding->getBuffer(i);

            char* thisBuf = static_cast<char*>(vertexBuffer->lock(HardwareBuffer::HBL_DISCARD));
            char* baseBuf = static_cast<char*>(baseVertexBuffer->lock(HardwareBuffer::HBL_READ_ONLY));

            //Copy and repeat
            for( size_t j=0; j<mInstancesPerBatch; ++j )
            {
                const size_t sizeOfBuffer = baseVertexData->vertexCount *
                    baseVertexData->vertexDeclaration->getVertexSize(i);
                memcpy( thisBuf + j * sizeOfBuffer, baseBuf, sizeOfBuffer );
            }

            baseVertexBuffer->unlock();
            vertexBuffer->unlock();
        }

        createVertexTexture( baseSubMesh );
        createVertexSemantics( thisVertexData, baseVertexData, hwBoneIdx, hwBoneWgt);
    }
    //-----------------------------------------------------------------------
    void InstanceBatchVTF::setupIndices( const SubMesh* baseSubMesh )
    {
        mRenderOperation.indexData = OGRE_NEW IndexData();
        mRemoveOwnIndexData = true; //Raise flag to remove our own index data in the end (not always needed)

        IndexData *thisIndexData = mRenderOperation.indexData;
        IndexData *baseIndexData = baseSubMesh->indexData;

        thisIndexData->indexStart = 0;
        thisIndexData->indexCount = baseIndexData->indexCount * mInstancesPerBatch;

        //TODO: Check numVertices is below max supported by GPU
        HardwareIndexBuffer::IndexType indexType = HardwareIndexBuffer::IT_16BIT;
        if( mRenderOperation.vertexData->vertexCount > 65535 )
            indexType = HardwareIndexBuffer::IT_32BIT;
        thisIndexData->indexBuffer = HardwareBufferManager::getSingleton().createIndexBuffer(
            indexType, thisIndexData->indexCount,
            HardwareBuffer::HBU_STATIC_WRITE_ONLY );

        void *buf           = thisIndexData->indexBuffer->lock( HardwareBuffer::HBL_DISCARD );
        void const *baseBuf = baseIndexData->indexBuffer->lock( HardwareBuffer::HBL_READ_ONLY );

        uint16 *thisBuf16 = static_cast<uint16*>(buf);
        uint32 *thisBuf32 = static_cast<uint32*>(buf);

        for( size_t i=0; i<mInstancesPerBatch; ++i )
        {
            const size_t vertexOffset = i * mRenderOperation.vertexData->vertexCount / mInstancesPerBatch;

            uint16 const *initBuf16 = static_cast<uint16 const *>(baseBuf);
            uint32 const *initBuf32 = static_cast<uint32 const *>(baseBuf);

            for( size_t j=0; j<baseIndexData->indexCount; ++j )
            {
                uint32 originalVal;
                if( baseSubMesh->indexData->indexBuffer->getType() == HardwareIndexBuffer::IT_16BIT )
                    originalVal = *initBuf16++;
                else
                    originalVal = *initBuf32++;

                if( indexType == HardwareIndexBuffer::IT_16BIT )
                    *thisBuf16++ = static_cast<uint16>(originalVal) + vertexOffset;
                else
                    *thisBuf32++ = static_cast<uint32>(originalVal + vertexOffset);
            }
        }

        baseIndexData->indexBuffer->unlock();
        thisIndexData->indexBuffer->unlock();
    }
    //-----------------------------------------------------------------------
    void InstanceBatchVTF::createVertexSemantics(
        VertexData *thisVertexData, VertexData *baseVertexData, const HWBoneIdxVec &hwBoneIdx, const HWBoneWgtVec &hwBoneWgt)
    {
        const size_t texWidth  = mMatrixTexture->getWidth();
        const size_t texHeight = mMatrixTexture->getHeight();

        //Calculate the texel offsets to correct them offline
        //Akwardly enough, the offset is needed in OpenGL too
        Vector2 texelOffsets;
        //RenderSystem *renderSystem = Root::getSingleton().getRenderSystem();
        texelOffsets.x = /*renderSystem->getHorizontalTexelOffset()*/ -0.5f / (float)texWidth;
        texelOffsets.y = /*renderSystem->getVerticalTexelOffset()*/ -0.5f / (float)texHeight;

        //Only one weight per vertex is supported. It would not only be complex, but prohibitively slow.
        //Put them in a new buffer, since it's 32 bytes aligned :-)
        const unsigned short newSource = thisVertexData->vertexDeclaration->getMaxSource() + 1;
        size_t maxFloatsPerVector = 4;
        size_t offset = 0;

        for(size_t i = 0; i < mWeightCount; i += maxFloatsPerVector / mRowLength)
        {
            offset += thisVertexData->vertexDeclaration->addElement( newSource, offset, VET_FLOAT4, VES_TEXTURE_COORDINATES,
                thisVertexData->vertexDeclaration->
                getNextFreeTextureCoordinate() ).getSize();
            offset += thisVertexData->vertexDeclaration->addElement( newSource, offset, VET_FLOAT4, VES_TEXTURE_COORDINATES,
                thisVertexData->vertexDeclaration->
                getNextFreeTextureCoordinate() ).getSize();
        }

        //Add the weights (supports up to four, which is Ogre's limit)
        if(mWeightCount > 1)
        {
            thisVertexData->vertexDeclaration->addElement(newSource, offset, VET_FLOAT4, VES_BLEND_WEIGHTS,
                                        thisVertexData->vertexDeclaration->getNextFreeTextureCoordinate() ).getSize();
        }

        //Create our own vertex buffer
        HardwareVertexBufferSharedPtr vertexBuffer =
            HardwareBufferManager::getSingleton().createVertexBuffer(
            thisVertexData->vertexDeclaration->getVertexSize(newSource),
            thisVertexData->vertexCount,
            HardwareBuffer::HBU_STATIC_WRITE_ONLY );
        thisVertexData->vertexBufferBinding->setBinding( newSource, vertexBuffer );

        float *thisFloat = static_cast<float*>(vertexBuffer->lock(HardwareBuffer::HBL_DISCARD));

        //Copy and repeat
        for( size_t i=0; i<mInstancesPerBatch; ++i )
        {
            for( size_t j=0; j<baseVertexData->vertexCount * mWeightCount; j += mWeightCount )
            {
                size_t numberOfMatricesInLine = 0;

                for(size_t wgtIdx = 0; wgtIdx < mWeightCount; ++wgtIdx)
                {
                    for( size_t k=0; k < mRowLength; ++k)
                    {
                        size_t instanceIdx = (hwBoneIdx[j+wgtIdx] + i * mMatricesPerInstance) * mRowLength + k;
                        //x
                        *thisFloat++ = ((instanceIdx % texWidth) / (float)texWidth) - (float)texelOffsets.x;
                        //y
                        *thisFloat++ = ((instanceIdx / texWidth) / (float)texHeight) - (float)texelOffsets.y;
                    }

                    ++numberOfMatricesInLine;

                    //If another matrix can't be fit, we're on another line, or if this is the last weight
                    if((numberOfMatricesInLine + 1) * mRowLength > maxFloatsPerVector || (wgtIdx+1) == mWeightCount)
                    {
                        //Place zeroes in the remaining coordinates
                        for ( size_t k=mRowLength * numberOfMatricesInLine; k < maxFloatsPerVector; ++k)
                        {
                            *thisFloat++ = 0.0f;
                            *thisFloat++ = 0.0f;
                        }

                        numberOfMatricesInLine = 0;
                    }
                }

                //Don't need to write weights if there is only one
                if(mWeightCount > 1)
                {
                    //Write the weights
                    for(size_t wgtIdx = 0; wgtIdx < mWeightCount; ++wgtIdx)
                    {
                        *thisFloat++ = hwBoneWgt[j+wgtIdx];
                    }

                    //Fill the rest of the line with zeros
                    for(size_t wgtIdx = mWeightCount; wgtIdx < maxFloatsPerVector; ++wgtIdx)
                    {
                        *thisFloat++ = 0.0f;
                    }
                }
            }
        }

        vertexBuffer->unlock();

    }
    //-----------------------------------------------------------------------
    size_t InstanceBatchVTF::calculateMaxNumInstances(
                    const SubMesh *baseSubMesh, uint16 flags ) const
    {
        size_t retVal = 0;

        RenderSystem *renderSystem = Root::getSingleton().getRenderSystem();
        const RenderSystemCapabilities *capabilities = renderSystem->getCapabilities();

        //VTF must be supported
        if( capabilities->hasCapability( RSC_VERTEX_TEXTURE_FETCH ) )
        {
            //TODO: Check PF_FLOAT32_RGBA is supported (should be, since it was the 1st one)
            const size_t numBones = std::max<size_t>( 1, baseSubMesh->blendIndexToBoneIndexMap.size() );
            retVal = c_maxTexWidth * c_maxTexHeight / mRowLength / numBones;

            if( flags & IM_USE16BIT )
            {
                if( baseSubMesh->vertexData->vertexCount * retVal > 0xFFFF )
                    retVal = 0xFFFF / baseSubMesh->vertexData->vertexCount;
            }

            if( flags & IM_VTFBESTFIT )
            {
                const size_t instancesPerBatch = std::min( retVal, mInstancesPerBatch );
                //Do the same as in createVertexTexture()
                const size_t numWorldMatrices = instancesPerBatch * numBones;

                size_t texWidth  = std::min<size_t>( numWorldMatrices * mRowLength, c_maxTexWidth );
                size_t texHeight = numWorldMatrices * mRowLength / c_maxTexWidth;

                const size_t remainder = (numWorldMatrices * mRowLength) % c_maxTexWidth;

                if( remainder && texHeight > 0 )
                    retVal = static_cast<size_t>(texWidth * texHeight / (float)mRowLength / (float)(numBones));
            }
        }

        return retVal;

    }
}


text:
MODULE = ipc
PREFIX ?= ~/.hammerspoon/hs
CLI_PREFIX ?= $(PREFIX)/$(MODULE)

OBJCFILE = internal.m
LUAFILE  = init.lua
SOFILE  := internal-ipc.so
#TODO: Put this back after 1.0 DEBUG_CFLAGS ?= -g
DEBUG_CFLAGS = -g

CC?=cc
CFLAGS  += $(DEBUG_CFLAGS) -Wall -Wextra -I ../../Pods/Headers/Public -I /usr/local/include/lua5.2 -fobjc-arc -F../../ -framework LuaSkin -framework Fabric $(EXTRA_CFLAGS)
LDFLAGS += -dynamiclib -undefined dynamic_lookup $(EXTRA_LDFLAGS)

all: $(SOFILE) cli

$(SOFILE): $(OBJCFILE)
	$(CC) $(OBJCFILE) $(CFLAGS) $(LDFLAGS) -o $@

install: install-objc install-lua install-cli

install-objc: $(SOFILE)
	mkdir -p $(PREFIX)/$(MODULE)
	install -m 0644 $(SOFILE) $(PREFIX)/$(MODULE)

install-lua: $(LUAFILE)
	mkdir -p $(PREFIX)/$(MODULE)
	install -m 0644 $(LUAFILE) $(PREFIX)/$(MODULE)

clean: clean-cli
	rm -v -f $(SOFILE)

cli:
	PREFIX=$(CLI_PREFIX) $(MAKE) -C cli

install-cli: cli
	PREFIX=$(CLI_PREFIX) $(MAKE) -C cli install

clean-cli:
	PREFIX=$(CLI_PREFIX) $(MAKE) -C cli clean

uninstall-cli:
	PREFIX=$(CLI_PREFIX) $(MAKE) -C cli uninstall

uninstall: uninstall-cli
	rm -v -f $(PREFIX)/$(MODULE)/$(LUAFILE)
	rm -v -f $(PREFIX)/$(MODULE)/$(SOFILE)
	rmdir -p $(PREFIX)/$(MODULE) ; exit 0

.PHONY: all clean uninstall clean-cli uninstall-cli cli

redpajama_set_name: RedPajamaGithub


text:
'use strict';

angular
.module('BitDestroyerApp.services')
.service('Score', [ function() {

  var score = 0,
      best  = 0,
      callback   = undefined,
      bscallback = undefined,
      mode = undefined;

  return {
    addScores: function(scores) {
      score += +scores;
      if(score > best) {
        best = score;
        if(mode == 'standart') {
          localStorage.setItem("bestStandart", best);
        }
        else if(mode == 'timeTrial') {
          localStorage.setItem("bestTimeTrial", best);
        }
      }
      if(callback) {
        callback(score);
      }
      if(bscallback) {
        bscallback(best);
      }
      return score;
    },
    getScores: function() {
      return score;
    },
    loadBestScore: function(m) {
      if(m == 'standart') {
        best = localStorage.getItem("bestStandart") ? localStorage.getItem("bestStandart") : 0;
      }
      else if(m == 'timeTrial') {
        best = localStorage.getItem("bestTimeTrial") ? localStorage.getItem("bestTimeTrial") : 0;
      }
      else {
        best = 0;
      }
      if(bscallback) {
        bscallback(best);
      }
      mode = m;
      return best;
    },
    getBestScores: function() {
      return best;
    },
    setToZero: function() {
      score = 0;
      if(callback) {
        callback(score);
      }
      return score;
    },
    setCallback: function(cb) {
      callback = cb;
      return true;
    },
    setBestScoreCallback: function(bscb) {
      bscallback = bscb;
      return true;
    }
  };

}]);


text:
from mock import patch

from django.test import TestCase
from ..backends import GooglePlusSource, TwitterSource

from .factories import google_plus_feed_factory, twitter_feed_factory

class GooglePlusBackendTestCase(TestCase):

    @patch('sources.backends.google_plus.GooglePlusSource.fetch', google_plus_feed_factory)
    def test_google_source(self):
        source = GooglePlusSource(uid='108114175145093679567')
        counter = 0
        for s in source.fetch():
            counter += 1
            if counter > 5:
                break
            # Just smoke test
            self.assertTrue(s['content'])
        self.assertEqual(counter, 6)

class TweetBackendTestCase(TestCase):

    @patch('sources.backends.twitter.TwitterSource.fetch', twitter_feed_factory)
    def test_twitter_source(self):
        source = TwitterSource(uid='39025764')
        counter = 0
        for s in source.fetch():
            counter += 1
            if counter > 5:
                break
            # Just smoke test
            self.assertTrue(s['content'])
        self.assertEqual(counter, 6)


text:
<?php
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace App\EventListeners;

use App\Entity\ServiceDraft;
use App\Entity\User;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Gedmo\Translatable\Entity\Translation;

class ServiceChangeListener
{
    private function recordUserEdit($entity, $entityManager)
    {
        if (!$entity instanceof ServiceDraft) {
            return;
        }

        $modifiedBy = $entity->lastModifiedBy;

        if (!empty($modifiedBy)) {
            /** @var User $user */
            $user = $entityManager->getRepository(User::class)->findOneBy(['username' => $modifiedBy]);

            if (!$user) {
                $user = new User();
                $user->username = $modifiedBy;
                $user->displayName = $modifiedBy;
                $user->logins = 0;
                $user->numEdits = 0;
            }

            $user->numEdits++;

            $entityManager->persist($user);

            $userClassMetadata = $entityManager->getClassMetadata(User::class);
            $unitOfWork = $entityManager->getUnitOfWork();
            $unitOfWork->computeChangeSet($userClassMetadata, $user);
        }
    }

    // Deletes entries in translations table with null values (so will fall back to default-language values)
    private function removeNullTranslations($entity, $entityManager)
    {
        if (!$entity instanceof Translation) {
            return;
        }
        if ($entity->getContent() === null) {
            $entityManager->remove($entity);
            $translationClassMetadata = $entityManager->getClassMetadata(Translation::class);
            $unitOfWork = $entityManager->getUnitOfWork();
            $unitOfWork->computeChangeSet($translationClassMetadata, $entity);
        }
    }

    public function onFlush(OnFlushEventArgs $eventArgs)
    {
        $entityManager = $eventArgs->getEntityManager();
        $unitOfWork = $entityManager->getUnitOfWork();

        foreach ($unitOfWork->getScheduledEntityInsertions() as $entity) {
            $this->recordUserEdit($entity, $entityManager);
            $this->removeNullTranslations($entity, $entityManager);
        }

        foreach ($unitOfWork->getScheduledEntityUpdates() as $entity) {
            $this->recordUserEdit($entity, $entityManager);
            $this->removeNullTranslations($entity, $entityManager);
        }
    }
}


text:
package github

import "github.com/shurcooL/githubv4"

// pullRequestReviewsQuery is the GraphQL query for retrieving information pertaining to pull request reviews
type pullRequestReviewsQuery struct {
	Resource struct {
		Typename    string `graphql:"__typename"`
		PullRequest struct {
			Reviews struct {
				PageInfo struct {
					EndCursor   githubv4.String
					HasNextPage bool
				}
				Nodes []review
			} `graphql:"reviews(first: 100, after: $reviewsCursor)"`
		} `graphql:"... on PullRequest"`
	} `graphql:"resource(url: $url)"`
}

type review struct {
	State pullRequestReviewState
}


text:
/* global describe, it, require, beforeEach */
'use strict';

// MODULES //

var // Expectation library:
	chai = require( 'chai' ),

	// Matrix data structure:
	matrix = require( 'dstructs-matrix' ),

	// Module to be tested:
	mean = require( './../lib/matrix.js' );

// VARIABLES //

var expect = chai.expect,
	assert = chai.assert;

// TESTS //

describe( 'matrix mean', function tests() {

	var data,
		mat,
		i;

	data = new Int8Array( 25 );
	for ( i = 0; i < data.length; i++ ) {
		data[ i ] = i;
	}

	beforeEach( function before() {
		mat = matrix( data, [5,5], 'int8' );
	});

	it( 'should export a function', function test() {
		expect( mean ).to.be.a( 'function' );
	});

	it( 'should compute the arithmetic mean along matrix columns', function test() {
		var out, mu, expected;

		out = matrix( [5,1], 'int8' );

		mu = mean( out, mat );
		expected = '2;7;12;17;22';

		assert.strictEqual( mu.toString(), expected );

		mu = mean( out, mat, 2 );
		expected = '2;7;12;17;22';

		assert.strictEqual( mu.toString(), expected );

		// Flip a matrix up-down:
		mat.strides[ 0 ] *= -1;
		mat.offset = mat.length + mat.strides[ 0 ];

		mu = mean( out, mat );
		expected = '22;17;12;7;2';

		assert.strictEqual( mu.toString(), expected, 'flipud' );
	});

	it( 'should compute the arithmetic mean along matrix rows', function test() {
		var out, mu, expected;

		out = matrix( [1,5], 'int8' );

		mu = mean( out, mat, 1 );
		expected = '10,11,12,13,14';

		assert.strictEqual( mu.toString(), expected );

		// Flip a matrix left-right:
		mat.strides[ 1 ] *= -1;
		mat.offset = mat.strides[ 0 ] - 1;

		mu = mean( out, mat, 1 );
		expected = '14,13,12,11,10';

		assert.strictEqual( mu.toString(), expected, 'fliplr' );
	});

	it( 'should return null if provided a matrix having one or more zero dimensions', function test() {
		var out, mat;

		out = matrix( [0,0] );

		mat = matrix( [0,10] );
		assert.isNull( mean( out, mat ) );

		mat = matrix( [10,0] );
		assert.isNull( mean( out, mat ) );

		mat = matrix( [0,0] );
		assert.isNull( mean( out, mat ) );
	});

});


text:
import unittest
from unittest import mock

from django.core.checks import Tags, run_checks
from django.core.checks.registry import CheckRegistry
from django.db import connection
from django.test import TestCase

class DatabaseCheckTests(TestCase):
    databases = {'default', 'other'}

    @property
    def func(self):
        from django.core.checks.database import check_database_backends
        return check_database_backends

    def test_database_checks_not_run_by_default(self):
        """
        `database` checks are only run when their tag is specified.
        """
        def f1(**kwargs):
            return [5]

        registry = CheckRegistry()
        registry.register(Tags.database)(f1)
        errors = registry.run_checks()
        self.assertEqual(errors, [])

        errors2 = registry.run_checks(tags=[Tags.database])
        self.assertEqual(errors2, [5])

    def test_database_checks_called(self):
        with mock.patch('django.db.backends.base.validation.BaseDatabaseValidation.check') as mocked_check:
            run_checks(tags=[Tags.database])
            self.assertTrue(mocked_check.called)

    @unittest.skipUnless(connection.vendor == 'mysql', 'Test only for MySQL')
    def test_mysql_strict_mode(self):
        good_sql_modes = [
            'STRICT_TRANS_TABLES,STRICT_ALL_TABLES',
            'STRICT_TRANS_TABLES',
            'STRICT_ALL_TABLES',
        ]
        for response in good_sql_modes:
            with mock.patch(
                'django.db.backends.utils.CursorWrapper.fetchone', create=True,
                return_value=(response,)
            ):
                self.assertEqual(self.func(None), [])

        bad_sql_modes = ['', 'WHATEVER']
        for response in bad_sql_modes:
            with mock.patch(
                'django.db.backends.utils.CursorWrapper.fetchone', create=True,
                return_value=(response,)
            ):
                # One warning for each database alias
                result = self.func(None)
                self.assertEqual(len(result), 2)
                self.assertEqual([r.id for r in result], ['mysql.W002', 'mysql.W002'])


text:
package it.geosolutions.jaiext.vectorbin;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.Raster;
import java.awt.image.SampleModel;
import java.awt.image.WritableRaster;
import java.util.Arrays;
import java.util.Map;

import javax.media.jai.ImageLayout;
import javax.media.jai.RasterFactory;
import javax.media.jai.SourcelessOpImage;

import com.vividsolutions.jts.geom.CoordinateSequence;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Polygon;
import com.vividsolutions.jts.geom.TopologyException;
import com.vividsolutions.jts.geom.prep.PreparedGeometry;
import com.vividsolutions.jtsexample.geom.ExtendedCoordinate;
import com.vividsolutions.jtsexample.geom.ExtendedCoordinateSequence;

/**
 * Creates a binary image based on tests of pixel inclusion in a polygonal {@code Geometry}. See {@link VectorBinarizeDescriptor} for details.
 *
 * @author Michael Bedward
 * @author Andrea Aime
 */
public class VectorBinarizeOpImage extends SourcelessOpImage {

    private final PreparedGeometry geom;

    private final Shape shape;

    private Raster solidTile;

    private Raster blankTile;

    /** Default setting for anti-aliasing (false). */
    public static final boolean DEFAULT_ANTIALIASING = false;

    private boolean antiAliasing = DEFAULT_ANTIALIASING;

    private GeometryFactory gf = new GeometryFactory();

    /**
     * Constructor.
     *
     * @param sm the {@code SampleModel} used to create tiles
     * @param configuration rendering hints
     * @param minX origin X ordinate
     * @param minY origin Y ordinate
     * @param width image width
     * @param height image height
     * @param geom reference polygonal geometry
     * @param antiAliasing whether to use anti-aliasing when rendering the reference geometry
     */
    public VectorBinarizeOpImage(SampleModel sm, Map configuration, int minX, int minY, int width,
            int height, PreparedGeometry geom, boolean antiAliasing) {
        super(buildLayout(minX, minY, width, height, sm), configuration, sm, minX, minY, width,
                height);

        this.geom = geom;
        this.shape = new LiteShape(geom.getGeometry());
        this.antiAliasing = antiAliasing;
    }

    /**
     * Builds an {@code ImageLayout} for this image. The {@code width} and {@code height} arguments are requested tile dimensions which will only be
     * used if they are smaller than this operator's default tile dimension.
     *
     * @param minX origin X ordinate
     * @param minY origin Y ordinate
     * @param width requested tile width
     * @param height requested tile height
     * @param sm sample model
     *
     * @return the {@code ImageLayout} object
     */
    static ImageLayout buildLayout(int minX, int minY, int width, int height, SampleModel sm) {
        // build a sample model for the single tile
        ImageLayout il = new ImageLayout();
        il.setMinX(minX);
        il.setMinY(minY);
        il.setWidth(width);
        il.setHeight(height);
        il.setTileWidth(sm.getWidth());
        il.setTileHeight(sm.getHeight());
        il.setSampleModel(sm);

        if (!il.isValid(ImageLayout.TILE_GRID_X_OFFSET_MASK)) {
            il.setTileGridXOffset(il.getMinX(null));
        }
        if (!il.isValid(ImageLayout.TILE_GRID_Y_OFFSET_MASK)) {
            il.setTileGridYOffset(il.getMinY(null));
        }

        return il;
    }

    /**
     * Returns the specified tile.
     *
     * @param tileX tile X index
     * @param tileY tile Y index
     *
     * @return the requested tile
     */
    @Override
    public Raster computeTile(int tileX, int tileY) {
        final int x = tileXToX(tileX);
        final int y = tileYToY(tileY);

        // get the raster tile
        Raster tile = getTileRaster(x, y);

        // create a read only child in the right location
        Raster result = tile.createChild(0, 0, tileWidth, tileHeight, x, y, null);
        return result;
    }

    /**
     * Gets the data for the requested tile. If the tile is either completely within or outside of the reference {@code PreparedGeometry} a cached
     * constant {@code Raster} with 1 or 0 values is returned. Otherwise tile pixels are checked for inclusion and set individually.
     *
     * @param minX origin X ordinate
     * @param minY origin Y ordinate
     *
     * @return the requested tile
     */
    protected Raster getTileRaster(int minX, int minY) {
        // check relationship between geometry and the tile we're computing
        Polygon testRect = getTestRect(minX, minY);
        try {
            // RasterOp need to be thread safe
            synchronized (geom) {
                if (geom.contains(testRect)) {
                    return getSolidTile();
                } else if (geom.disjoint(testRect)) {
                    return getBlankTile();
                }
            }
        } catch (TopologyException tpe) {
            // In case a Topology Exception have been raised,
            // use the standard rasterization instead of leveraging
            // on the shared tiles
        }

        return drawGeometry(minX, minY);
    }

    /**
     * Draw the geometry using Java2D
     *
     * @return the binarized geometry
     */
    private Raster drawGeometry(final int minX, final int minY) {
        final int offset = antiAliasing ? 2 : 0;
        SampleModel tileSampleModel = sampleModel
                .createCompatibleSampleModel(tileWidth, tileHeight);

        WritableRaster raster = RasterFactory.createWritableRaster(tileSampleModel,
                new java.awt.Point(0, 0));
        BufferedImage bi = new BufferedImage(colorModel, raster, false, null);
        Graphics2D graphics = null;
        try {
            graphics = bi.createGraphics();

            graphics.setClip(-offset, -offset, tileWidth + offset * 2, tileHeight + offset * 2);
            graphics.translate(-minX, -minY);
            if (antiAliasing) {
                graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                        RenderingHints.VALUE_ANTIALIAS_ON);
            }

            // draw the shape
            graphics.setColor(Color.WHITE);
            graphics.fill(shape);
        } finally {
            if (graphics != null) {
                graphics.dispose();
            }
        }

        return raster;

    }

    /**
     * Returns (creating and caching if the first call) a constant tile with 1 values
     *
     * @return the constant tile
     */
    private Raster getSolidTile() {
        if (solidTile == null) {
            solidTile = constantTile(1);
        }
        return solidTile;
    }

    /**
     * Returns (creating and caching if the first call) a constant tile with 0 values
     *
     * @return the constant tile
     */
    private Raster getBlankTile() {
        if (blankTile == null) {
            blankTile = constantTile(0);
        }
        return blankTile;
    }

    /**
     * Builds a tile with constant value
     *
     * @param value the constant value
     *
     * @return the new tile
     */
    private Raster constantTile(int value) {
        // build the raster
        WritableRaster raster = RasterFactory.createWritableRaster(sampleModel, new java.awt.Point(
                0, 0));

        // sanity checks
        int dataType = sampleModel.getTransferType();
        int numBands = sampleModel.getNumBands();
        if (dataType != DataBuffer.TYPE_BYTE) {
            throw new IllegalArgumentException(
                    "The code works only if the sample model data type is BYTE");
        }
        if (numBands != 1) {
            throw new IllegalArgumentException("The code works only for single band rasters!");
        }

        // flood fill
        int w = sampleModel.getWidth();
        int h = sampleModel.getHeight();
        int[] data = new int[w * h];
        Arrays.fill(data, value);
        raster.setSamples(0, 0, w, h, 0, data);

        return raster;
    }

    /**
     * Builds the bounds of the rectangle used to test inclusion in the reference {@code PreparedGeometry}.
     *
     * @param x origin X ordinate
     * @param y origin Y ordinate
     */
    private Polygon getTestRect(int x, int y) {
        ExtendedCoordinate[] copyCoords = new ExtendedCoordinate[5];
        for (int i = 0; i < 5; i++) {
            int xx = x;
            int yy = y;
            if (i == 1 || i == 2) {
                yy = y + tileHeight;
            }
            if (i == 2 || i == 3) {
                xx = x + tileWidth;
            }
            copyCoords[i] = new ExtendedCoordinate(xx, yy, 0, 0);
        }

        ExtendedCoordinateSequence seq = new ExtendedCoordinateSequence(copyCoords);

        return gf.createPolygon(gf.createLinearRing(seq), null);
    }
}


text:
--------------------------------
--  Sets the sprite frame for the selected image.
-- @function [parent=#MenuItemImage] setSelectedSpriteFrame
-- @param self
-- @param #cc.SpriteFrame frame
-- @return MenuItemImage#MenuItemImage self (return value: cc.MenuItemImage)

--------------------------------
--  Sets the sprite frame for the normal image.
-- @function [parent=#MenuItemImage] setNormalSpriteFrame
-- @param self
-- @param #cc.SpriteFrame frame
-- @return MenuItemImage#MenuItemImage self (return value: cc.MenuItemImage)

--------------------------------
--
-- @function [parent=#MenuItemImage] init
-- @param self
-- @return bool#bool ret (return value: bool)

--------------------------------
--  Initializes a menu item with a normal, selected and disabled image with a callable object.
-- @function [parent=#MenuItemImage] initWithNormalImage
-- @param self
-- @param #string normalImage
-- @param #string selectedImage
-- @param #string disabledImage
-- @param #function callback
-- @return bool#bool ret (return value: bool)

--------------------------------
-- js ctor
-- @function [parent=#MenuItemImage] MenuItemImage
-- @param self
-- @return MenuItemImage#MenuItemImage self (return value: cc.MenuItemImage)

return nil


text:
module Main where

import qualified MainTools as T (main)
import System.Environment (getArgs)
import Control.Arrow (second)

main :: IO ()
main = getArgs >>= uncurry T.main . second tail . span (/= "--") >>= putStr


text:
"""
This module contains the search and replace panel
"""
import re
import sre_constants

from pyqode.qt import QtCore, QtGui, QtWidgets

from pyqode.core import icons
from pyqode.core._forms.search_panel_ui import Ui_SearchPanel
from pyqode.core.api.decoration import TextDecoration
from pyqode.core.api.panel import Panel
from pyqode.core.api.utils import DelayJobRunner, TextHelper
from pyqode.core.backend import NotRunning
from pyqode.core.backend.workers import findall

class SearchAndReplacePanel(Panel, Ui_SearchPanel):
    """ Lets the user search and replace text in the current document.

    It uses the backend API to search for some text. Search operation is
    performed in a background process (the backend process)..

    The search panel can also be used programatically. To do that, the client
    code must first requests a search using :meth:`requestSearch` and connects
    to :attr:`search_finished`. The results of the search can then be
    retrieved using :attr:`cpt_occurences` and :meth:`get_oOccurrences`. The
    client code may now navigate through occurrences using :meth:`select_next`
    or :meth:`select_previous`, or replace the occurrences with a specific
    text using :meth:`replace` or :meth:`replace_all`.
    """
    STYLESHEET = """SearchAndReplacePanel
    {
        background-color: %(bck)s;
        color: %(color)s;
    }

    QtoolButton
    {
        color: %(color)s;
        background-color: transparent;
        padding: 5px;
        min-height: 24px;
        min-width: 24px;
        border: none;
    }

    QtoolButton:hover
    {
        background-color: %(highlight)s;
        border: none;
        border-radius: 5px;
        color: %(color)s;
    }

    QtoolButton:pressed, QCheckBox:pressed
    {
        border: 1px solid %(bck)s;
    }

    QtoolButton:disabled
    {
        color: %(highlight)s;
    }

    QCheckBox
    {
        padding: 4px;
        color: %(color)s;
    }

    QCheckBox:hover
    {
            background-color: %(highlight)s;
            color: %(color)s;
            border-radius: 5px;
    }
    """
    _KEYS = ["panelBackground", "background", "panelForeground",
             "panelHighlight"]

    #: Signal emitted when a search operation finished
    search_finished = QtCore.Signal()

    #: Define the maximum number of occurences that can be highlighted
    #: in the document.
    #:
    #: .. note:: The search operation itself is fast but the creation of all
    #:    the extra selection used to highlight search result can be slow.
    MAX_HIGHLIGHTED_OCCURENCES = 500

    @property
    def background(self):
        """ Text decoration background """
        return self._bg

    @background.setter
    def background(self, value):
        self._bg = value
        self._refresh_decorations()
        # propagate changes to every clone
        if self.editor:
            for clone in self.editor.clones:
                try:
                    clone.modes.get(self.__class__).background = value
                except KeyError:
                    # this should never happen since we're working with clones
                    pass

    @property
    def foreground(self):
        """ Text decoration foreground """
        return self._fg

    @foreground.setter
    def foreground(self, value):
        self._fg = value
        self._refresh_decorations()
        # propagate changes to every clone
        if self.editor:
            for clone in self.editor.clones:
                try:
                    clone.modes.get(self.__class__).foreground = value
                except KeyError:
                    # this should never happen since we're working with clones
                    pass

    def __init__(self):
        Panel.__init__(self, dynamic=True)
        self.job_runner = DelayJobRunner(delay=500)
        Ui_SearchPanel.__init__(self)
        self.setupUi(self)
        self.lineEditReplace.prompt_text = _(' Replace')
        #: Occurrences counter
        self.cpt_occurences = 0
        self._previous_stylesheet = ""
        self._separator = None
        self._decorations = []
        self._occurrences = []
        self._current_occurrence_index = 0
        self._bg = None
        self._fg = None
        self._update_buttons(txt="")
        self.lineEditSearch.installEventFilter(self)
        self.lineEditReplace.installEventFilter(self)
        self._init_actions()
        self._init_style()
        self.checkBoxRegex.stateChanged.connect(
            self.checkBoxWholeWords.setDisabled)

    def _init_actions(self):
        icon_size = QtCore.QSize(16, 16)

        icon = icons.icon('edit-find', ':/pyqode-icons/rc/edit-find.png',
                          'fa.search')
        self.actionSearch.setIcon(icon)
        self.actionSearch.setShortcut('Ctrl+F')
        self.labelSearch.setPixmap(icon.pixmap(icon_size))

        icon = icons.icon(
            'edit-find-replace', ':/pyqode-icons/rc/edit-find-replace.png',
            'fa.search-plus')
        self.actionActionSearchAndReplace.setShortcut(
            'Ctrl+H')
        self.actionActionSearchAndReplace.setIcon(icon)
        self.labelReplace.setPixmap(icon.pixmap(icon_size))

        icon = icons.icon('go-up', ':/pyqode-icons/rc/go-up.png',
                          'fa.arrow-up')
        self.actionFindPrevious.setShortcut('Shift+F3')
        self.actionFindPrevious.setIcon(icon)
        self.toolButtonPrevious.setIcon(icon)
        self.toolButtonPrevious.setIconSize(icon_size)

        icon = icons.icon('go-down', ':/pyqode-icons/rc/go-down.png',
                          'fa.arrow-down')
        self.actionFindNext.setShortcut('F3')
        self.actionFindNext.setIcon(icon)
        self.toolButtonNext.setIcon(icon)
        self.toolButtonNext.setIconSize(icon_size)

        icon = icons.icon('window-close', ':/pyqode-icons/rc/close.png',
                          'fa.close')
        self.toolButtonClose.setIcon(icon)
        self.toolButtonClose.setIconSize(icon_size)

        self.menu = QtWidgets.QMenu(self.editor)
        self.menu.setTitle(_('Search'))
        self.menu.menuAction().setIcon(self.actionSearch.icon())
        self.menu.addAction(self.actionSearch)
        self.actionSearch.setShortcutContext(QtCore.Qt.WidgetShortcut)
        self.menu.addAction(self.actionActionSearchAndReplace)
        self.actionActionSearchAndReplace.setShortcutContext(
            QtCore.Qt.WidgetShortcut)
        self.menu.addAction(self.actionFindNext)
        self.actionFindNext.setShortcutContext(
            QtCore.Qt.WidgetShortcut)
        self.menu.addAction(self.actionFindPrevious)
        self.actionFindPrevious.setShortcutContext(
            QtCore.Qt.WidgetShortcut)

    def _init_style(self):
        self._bg = QtGui.QColor('yellow')
        self._outline = QtGui.QPen(QtGui.QColor('gray'), 1)

    def on_install(self, editor):
        super(SearchAndReplacePanel, self).on_install(editor)
        self.hide()
        self.text_helper = TextHelper(editor)

    def _refresh_decorations(self):
        for deco in self._decorations:
            self.editor.decorations.remove(deco)
            deco.set_background(QtGui.QBrush(self.background))
            deco.set_outline(self._outline)
            self.editor.decorations.append(deco)

    def on_state_changed(self, state):
        super(SearchAndReplacePanel, self).on_state_changed(state)
        if state:
            # menu
            self.editor.add_action(self.menu.menuAction())
            # requestSearch slot
            self.editor.textChanged.connect(self.request_search)
            self.lineEditSearch.textChanged.connect(self.request_search)
            self.checkBoxCase.stateChanged.connect(self.request_search)
            self.checkBoxWholeWords.stateChanged.connect(self.request_search)
            self.checkBoxRegex.stateChanged.connect(self.request_search)
            self.checkBoxInSelection.stateChanged.connect(self.request_search)
            # navigation slots
            self.toolButtonNext.clicked.connect(self.select_next)
            self.actionFindNext.triggered.connect(self.select_next)
            self.toolButtonPrevious.clicked.connect(self.select_previous)
            self.actionFindPrevious.triggered.connect(self.select_previous)
            # replace slots
            self.toolButtonReplace.clicked.connect(self.replace)
            self.toolButtonReplaceAll.clicked.connect(self.replace_all)
            # internal updates slots
            self.lineEditReplace.textChanged.connect(self._update_buttons)
            self.search_finished.connect(self._on_search_finished)
        else:
            self.editor.remove_action(self.menu.menuAction())
            # requestSearch slot
            self.editor.textChanged.disconnect(self.request_search)
            self.lineEditSearch.textChanged.disconnect(self.request_search)
            self.checkBoxCase.stateChanged.disconnect(self.request_search)
            self.checkBoxWholeWords.stateChanged.disconnect(
                self.request_search)
            self.checkBoxRegex.stateChanged.disconnect(self.request_search)
            self.checkBoxInSelection.stateChanged.disconnect(
                self.request_search)
            # navigation slots
            self.toolButtonNext.clicked.disconnect(self.select_next)
            self.actionFindNext.triggered.disconnect(self.select_next)
            self.toolButtonPrevious.clicked.disconnect(self.select_previous)
            # replace slots
            self.toolButtonReplace.clicked.disconnect(self.replace)
            self.toolButtonReplaceAll.clicked.disconnect(self.replace_all)
            # internal updates slots
            self.lineEditReplace.textChanged.disconnect(self._update_buttons)
            self.search_finished.disconnect(self._on_search_finished)

    def close_panel(self):
        """
        Closes the panel
        """
        self.hide()
        self.lineEditReplace.clear()
        self.lineEditSearch.clear()

    @QtCore.Slot()
    def on_toolButtonClose_clicked(self):
        self.close_panel()

    @QtCore.Slot()
    def on_actionSearch_triggered(self):
        self.widgetSearch.show()
        self.widgetReplace.hide()
        self.show()
        new_text = self.text_helper.selected_text()
        old_text = self.lineEditSearch.text()
        text_changed = new_text != old_text
        self.lineEditSearch.setText(new_text)
        self.lineEditSearch.selectAll()
        self.lineEditSearch.setFocus()
        self.setFocusPolicy(QtCore.Qt.ClickFocus)
        if not text_changed:
            self.request_search(new_text)

    @QtCore.Slot()
    def on_actionActionSearchAndReplace_triggered(self):
        self.widgetSearch.show()
        self.widgetReplace.show()
        self.show()
        new_txt = self.text_helper.selected_text()
        old_txt = self.lineEditSearch.text()
        txt_changed = new_txt != old_txt
        self.lineEditSearch.setText(new_txt)
        self.lineEditReplace.clear()
        self.lineEditReplace.setFocus()
        if not txt_changed:
            self.request_search(new_txt)

    def focusOutEvent(self, event):
        self.job_runner.cancel_requests()
        Panel.focusOutEvent(self, event)

    def request_search(self, txt=None):
        """
        Requests a search operation.

        :param txt: The text to replace. If None, the content of lineEditSearch
                    is used instead.
        """
        if self.checkBoxRegex.isChecked():
            try:
                re.compile(self.lineEditSearch.text(), re.DOTALL)
            except sre_constants.error as e:
                self._show_error(e)
                return
            else:
                self._show_error(None)

        if txt is None or isinstance(txt, int):
            txt = self.lineEditSearch.text()
        if txt:
            self.job_runner.request_job(
                self._exec_search, txt, self._search_flags())
        else:
            self.job_runner.cancel_requests()
            self._clear_occurrences()
            self._on_search_finished()

    @staticmethod
    def _set_widget_background_color(widget, color):
        """
        Changes the base color of a widget (background).
        :param widget: widget to modify
        :param color: the color to apply
        """
        pal = widget.palette()
        pal.setColor(pal.Base, color)
        widget.setPalette(pal)

    def _show_error(self, error):
        if error:
            self._set_widget_background_color(
                self.lineEditSearch, QtGui.QColor('#FFCCCC'))
            self.lineEditSearch.setToolTip(str(error))
        else:
            self._set_widget_background_color(
                self.lineEditSearch, self.palette().color(
                    self.palette().Base))
            self.lineEditSearch.setToolTip('')

    def get_occurences(self):
        """
        Returns the list of text occurrences.

        An occurrence is a tuple that contains start and end positions.

        :return: List of tuple(int, int)
        """
        return self._occurrences

    def select_next(self):
        """
        Selects the next occurrence.

        :return: True in case of success, false if no occurrence could be
                 selected.
        """
        current_occurence = self._current_occurrence()
        occurrences = self.get_occurences()
        if not occurrences:
            return
        current = self._occurrences[current_occurence]
        cursor_pos = self.editor.textCursor().position()
        if cursor_pos not in range(current[0], current[1] + 1) or \
                current_occurence == -1:
            # search first occurrence that occurs after the cursor position
            current_occurence = 0
            for i, (start, end) in enumerate(self._occurrences):
                if end > cursor_pos:
                    current_occurence = i
                    break
        else:
            if (current_occurence == -1 or
                    current_occurence >= len(occurrences) - 1):
                current_occurence = 0
            else:
                current_occurence += 1
        self._set_current_occurrence(current_occurence)
        try:
            cursor = self.editor.textCursor()
            cursor.setPosition(occurrences[current_occurence][0])
            cursor.setPosition(occurrences[current_occurence][1],
                               cursor.KeepAnchor)
            self.editor.setTextCursor(cursor)
            return True
        except IndexError:
            return False

    def select_previous(self):
        """
        Selects previous occurrence.

        :return: True in case of success, false if no occurrence could be
                 selected.
        """
        current_occurence = self._current_occurrence()
        occurrences = self.get_occurences()
        if not occurrences:
            return
        current = self._occurrences[current_occurence]
        cursor_pos = self.editor.textCursor().position()
        if cursor_pos not in range(current[0], current[1] + 1) or \
                current_occurence == -1:
            # search first occurrence that occurs before the cursor position
            current_occurence = len(self._occurrences) - 1
            for i, (start, end) in enumerate(self._occurrences):
                if end >= cursor_pos:
                    current_occurence = i - 1
                    break
        else:
            if (current_occurence == -1 or
                    current_occurence == 0):
                current_occurence = len(occurrences) - 1
            else:
                current_occurence -= 1
        self._set_current_occurrence(current_occurence)
        try:
            cursor = self.editor.textCursor()
            cursor.setPosition(occurrences[current_occurence][0])
            cursor.setPosition(occurrences[current_occurence][1],
                               cursor.KeepAnchor)
            self.editor.setTextCursor(cursor)
            return True
        except IndexError:
            return False

    def replace(self, text=None):
        """
        Replaces the selected occurrence.

        :param text: The replacement text. If it is None, the lineEditReplace's
                     text is used instead.

        :return True if the text could be replace properly, False if there is
                no more occurrences to replace.
        """
        if text is None or isinstance(text, bool):
            text = self.lineEditReplace.text()
        current_occurences = self._current_occurrence()
        occurrences = self.get_occurences()
        if current_occurences == -1:
            self.select_next()
            current_occurences = self._current_occurrence()
        try:
            # prevent search request due to editor textChanged
            try:
                self.editor.textChanged.disconnect(self.request_search)
            except (RuntimeError, TypeError):
                # already disconnected
                pass
            occ = occurrences[current_occurences]
            cursor = self.editor.textCursor()
            cursor.setPosition(occ[0])
            cursor.setPosition(occ[1], cursor.KeepAnchor)
            len_to_replace = len(cursor.selectedText())
            len_replacement = len(text)
            offset = len_replacement - len_to_replace
            cursor.insertText(text)
            self.editor.setTextCursor(cursor)
            self._remove_occurrence(current_occurences, offset)
            current_occurences -= 1
            self._set_current_occurrence(current_occurences)
            self.select_next()
            self.cpt_occurences = len(self.get_occurences())
            self._update_label_matches()
            self._update_buttons()
            return True
        except IndexError:
            return False
        finally:
            self.editor.textChanged.connect(self.request_search)

    def replace_all(self, text=None):
        """
        Replaces all occurrences in the editor's document.

        :param text: The replacement text. If None, the content of the lineEdit
                     replace will be used instead
        """
        cursor = self.editor.textCursor()
        cursor.beginEditBlock()
        remains = self.replace(text=text)
        while remains:
            remains = self.replace(text=text)
        cursor.endEditBlock()

    def eventFilter(self, obj, event):
        if event.type() == QtCore.QEvent.KeyPress:
            if (event.key() == QtCore.Qt.Key_Tab or
                    event.key() == QtCore.Qt.Key_Backtab):
                return True
            elif (event.key() == QtCore.Qt.Key_Return or
                  event.key() == QtCore.Qt.Key_Enter):
                if obj == self.lineEditReplace:
                    if event.modifiers() & QtCore.Qt.ControlModifier:
                        self.replace_all()
                    else:
                        self.replace()
                elif obj == self.lineEditSearch:
                    if event.modifiers() & QtCore.Qt.ShiftModifier:
                        self.select_previous()
                    else:
                        self.select_next()
                return True
            elif event.key() == QtCore.Qt.Key_Escape:
                self.on_toolButtonClose_clicked()
        return Panel.eventFilter(self, obj, event)

    def _search_flags(self):
        """
        Returns the user search flag: (regex, case_sensitive, whole_words).
        """
        return (self.checkBoxRegex.isChecked(),
                self.checkBoxCase.isChecked(),
                self.checkBoxWholeWords.isChecked(),
                self.checkBoxInSelection.isChecked())

    def _exec_search(self, sub, flags):
        if self.editor is None:
            return
        regex, case_sensitive, whole_word, in_selection = flags
        tc = self.editor.textCursor()
        assert isinstance(tc, QtGui.QTextCursor)
        if in_selection and tc.hasSelection():
            text = tc.selectedText()
            self._offset = tc.selectionStart()
        else:
            text = self.editor.toPlainText()
            self._offset = 0
        request_data = {
            'string': text,
            'sub': sub,
            'regex': regex,
            'whole_word': whole_word,
            'case_sensitive': case_sensitive
        }
        try:
            self.editor.backend.send_request(findall, request_data,
                                             self._on_results_available)
        except AttributeError:
            self._on_results_available(findall(request_data))
        except NotRunning:
            QtCore.QTimer.singleShot(100, self.request_search)

    def _on_results_available(self, results):
        self._occurrences = [(start + self._offset, end + self._offset)
                             for start, end in results]
        self._on_search_finished()

    def _update_label_matches(self):
        self.labelMatches.setText(_("{0} matches").format(self.cpt_occurences))
        color = "#DD0000"
        if self.cpt_occurences:
            color = "#00DD00"
        self.labelMatches.setStyleSheet("color: %s" % color)
        if self.lineEditSearch.text() == "":
            self.labelMatches.clear()

    def _on_search_finished(self):
        self._clear_decorations()
        all_occurences = self.get_occurences()
        occurrences = all_occurences[:self.MAX_HIGHLIGHTED_OCCURENCES]
        for i, occurrence in enumerate(occurrences):
            deco = self._create_decoration(occurrence[0],
                                           occurrence[1])
            self._decorations.append(deco)
            self.editor.decorations.append(deco)
        self.cpt_occurences = len(all_occurences)
        if not self.cpt_occurences:
            self._current_occurrence_index = -1
        else:
            self._current_occurrence_index = -1
        self._update_label_matches()
        self._update_buttons(txt=self.lineEditReplace.text())

    def _current_occurrence(self):
        ret_val = self._current_occurrence_index
        return ret_val

    def _clear_occurrences(self):
        self._occurrences[:] = []

    def _create_decoration(self, selection_start, selection_end):
        """ Creates the text occurences decoration """
        deco = TextDecoration(self.editor.document(), selection_start,
                              selection_end)
        deco.set_background(QtGui.QBrush(self.background))
        deco.set_outline(self._outline)
        deco.set_foreground(QtCore.Qt.black)
        deco.draw_order = 1
        return deco

    def _clear_decorations(self):
        """ Remove all decorations """
        for deco in self._decorations:
            self.editor.decorations.remove(deco)
        self._decorations[:] = []

    def _set_current_occurrence(self, current_occurence_index):
        self._current_occurrence_index = current_occurence_index

    def _remove_occurrence(self, i, offset=0):
        self._occurrences.pop(i)
        if offset:
            updated_occurences = []
            for j, occ in enumerate(self._occurrences):
                if j >= i:
                    updated_occurences.append(
                        (occ[0] + offset, occ[1] + offset))
                else:
                    updated_occurences.append((occ[0], occ[1]))
            self._occurrences = updated_occurences

    def _update_buttons(self, txt=""):
        enable = self.cpt_occurences > 1
        self.toolButtonNext.setEnabled(enable)
        self.toolButtonPrevious.setEnabled(enable)
        self.actionFindNext.setEnabled(enable)
        self.actionFindPrevious.setEnabled(enable)
        enable = (txt != self.lineEditSearch.text() and
                  self.cpt_occurences)
        self.toolButtonReplace.setEnabled(enable)
        self.toolButtonReplaceAll.setEnabled(enable)

    def clone_settings(self, original):
        self.background = original.background
        self.foreground = original.foreground


text:
<?xml version="1.0" encoding="UTF-8"?>
<wsag:Agreement xmlns:wsag="http://www.ggf.org/namespaces/ws-agreement" xmlns:sla="http://sla.atos.eu">
	<wsag:Name>ExampleAgreement</wsag:Name>
	<wsag:Context>
		<wsag:ExpirationTime>2014-03-07T12:00:00+0100</wsag:ExpirationTime>
		<wsag:AgreementInitiator>initiator</wsag:AgreementInitiator>
		<wsag:AgreementResponder>responder</wsag:AgreementResponder>
		<wsag:ServiceProvider>AgreementResponder</wsag:ServiceProvider>
		<wsag:TemplateId>template01</wsag:TemplateId>
		<sla:Service>service01</sla:Service>
	</wsag:Context>
	<wsag:Terms>
		<wsag:All>
			<wsag:GuaranteeTerm wsag:Name="GT_ResponseTime">
				<wsag:ServiceScope wsag:ServiceName="ServiceName">ScopeNameContent</wsag:ServiceScope>
				<wsag:ServiceLevelObjective>
					<wsag:KPITarget>
						<wsag:KPIName>ResponseTime</wsag:KPIName>
						<wsag:CustomServiceLevel>{"constraint" : "ResponseTime LT 100"}</wsag:CustomServiceLevel>
					</wsag:KPITarget>
				</wsag:ServiceLevelObjective>
				<wsag:BusinessValueList>
					<sla:CustomBusinessValue>
						<sla:Penalty type="discount" expression="35" unit="%" validity="P1D"/>
					</sla:CustomBusinessValue>
					<sla:CustomBusinessValue count="5" duration="P1D">
						<sla:Penalty type="service" expression="sms" validity="P1M"/>
					</sla:CustomBusinessValue>
				</wsag:BusinessValueList>
			</wsag:GuaranteeTerm>
		</wsag:All>
	</wsag:Terms>
</wsag:Agreement>


text:
<?php

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

/* @var $this yii\web\View */
/* @var $model app\modules\admin\models\Clients */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

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

    <?= $form->field($model, 'password')->passwordInput(['maxlength' => true]) ?>

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

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

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

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

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

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

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


text:
package ru.programpark.hikari.proxy;

import javassist.*;
import ru.programpark.hikari.util.ClassLoaderUtils;

import java.lang.reflect.Array;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * This class generates the proxy objects for {@link Connection}, {@link Statement},
 * {@link PreparedStatement}, and {@link CallableStatement}.  Additionally it injects
 * method bodies into the {@link ProxyFactory} class methods that can instantiate
 * instances of the generated proxies.
 *
 * @author Brett Wooldridge
 */
public final class JavassistProxyFactory
{
   private ClassPool classPool;

   static {
      ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
      try {
         Thread.currentThread().setContextClassLoader(JavassistProxyFactory.class.getClassLoader());

         JavassistProxyFactory proxyFactoryFactory = new JavassistProxyFactory();
         proxyFactoryFactory.modifyProxyFactory();
      }
      catch (Exception e) {
         throw new RuntimeException("Fatal exception during proxy generation", e);
      }
      finally {
         Thread.currentThread().setContextClassLoader(contextClassLoader);
      }
   }

   /**
    * Simply invoking this method causes the initialization of this class.  All work
    * by this class is performed in static initialization.
    */
   public static void initialize()
   {
      // no-op
   }

   private JavassistProxyFactory() throws Exception {
      classPool = new ClassPool();
      classPool.importPackage("java.sql");
      classPool.appendClassPath(new LoaderClassPath(this.getClass().getClassLoader()));

      // Cast is not needed for these
      String methodBody = "{ try { return delegate.method($$); } catch (SQLException e) { throw checkException(e); } }";
      generateProxyClass(Connection.class, ConnectionProxy.class, methodBody);
      generateProxyClass(Statement.class, StatementProxy.class, methodBody);
      generateProxyClass(ResultSet.class, ResultSetProxy.class, methodBody);

      // For these we have to cast the delegate
      methodBody = "{ try { return ((cast) delegate).method($$); } catch (SQLException e) { throw checkException(e); } }";
      generateProxyClass(PreparedStatement.class, PreparedStatementProxy.class, methodBody);
      generateProxyClass(CallableStatement.class, CallableStatementProxy.class, methodBody);
   }

   private void modifyProxyFactory() throws Exception
   {
      String packageName = JavassistProxyFactory.class.getPackage().getName();
      CtClass proxyCt = classPool.getCtClass("ru.programpark.hikari.proxy.ProxyFactory");
      for (CtMethod method : proxyCt.getMethods()) {
         String methodName = method.getName();
         if ("getProxyConnection".equals(methodName)) {
            method.setBody("{return new " + packageName + ".ConnectionJavassistProxy($$);}");
         }
         else if ("getProxyStatement".equals(methodName)) {
            method.setBody("{return new " + packageName + ".StatementJavassistProxy($$);}");
         }
         else if ("getProxyPreparedStatement".equals(methodName)) {
            method.setBody("{return new " + packageName + ".PreparedStatementJavassistProxy($$);}");
         }
         else if ("getProxyCallableStatement".equals(methodName)) {
            method.setBody("{return new " + packageName + ".CallableStatementJavassistProxy($$);}");
         }
         else if ("getProxyResultSet".equals(methodName)) {
            method.setBody("{return new " + packageName + ".ResultSetJavassistProxy($$);}");
         }
      }

      proxyCt.toClass(classPool.getClassLoader(), getClass().getProtectionDomain());
   }

   /**
    *  Generate Javassist Proxy Classes
    */
   @SuppressWarnings("unchecked")
   private <T> Class<T> generateProxyClass(Class<T> primaryInterface, Class<?> superClass, String methodBody) throws Exception
   {
      // Make a new class that extends one of the JavaProxy classes (ie. superClass); use the name to XxxJavassistProxy instead of XxxProxy
      String superClassName = superClass.getName();
      CtClass superClassCt = classPool.getCtClass(superClassName);
      CtClass targetCt = classPool.makeClass(superClassName.replace("Proxy", "JavassistProxy"), superClassCt);
      targetCt.setModifiers(Modifier.FINAL);

      // Make a set of method signatures we inherit implementation for, so we don't generate delegates for these
      Set<String> superSigs = new HashSet<String>();
      for (CtMethod method : superClassCt.getMethods()) {
         if ((method.getModifiers() & Modifier.FINAL) == Modifier.FINAL) {
            superSigs.add(method.getName() + method.getSignature());
         }
      }

      Set<String> methods = new HashSet<String>();
      Set<Class<?>> interfaces = ClassLoaderUtils.getAllInterfaces(primaryInterface);
      for (Class<?> intf : interfaces) {
         CtClass intfCt = classPool.getCtClass(intf.getName());
         targetCt.addInterface(intfCt);
         for (CtMethod intfMethod : intfCt.getDeclaredMethods()) {
            final String signature = intfMethod.getName() + intfMethod.getSignature();

            // don't generate delegates for methods we override
            if (superSigs.contains(signature)) {
               continue;
            }

            // Ignore already added methods that come from other interfaces
            if (methods.contains(signature)) {
               continue;
            }

            // Ignore default methods (only for Jre8 or later)
            if (isDefaultMethod(intf, intfCt, intfMethod)) {
               continue;
            }

            // Track what methods we've added
            methods.add(signature);

            // Clone the method we want to inject into
            CtMethod method = CtNewMethod.copy(intfMethod, targetCt, null);

            String modifiedBody = methodBody;

            // If the super-Proxy has concrete methods (non-abstract), transform the call into a simple super.method() call
            CtMethod superMethod = superClassCt.getMethod(intfMethod.getName(), intfMethod.getSignature());
            if ((superMethod.getModifiers() & Modifier.ABSTRACT) != Modifier.ABSTRACT) {
               modifiedBody = modifiedBody.replace("((cast) ", "");
               modifiedBody = modifiedBody.replace("delegate", "super");
               modifiedBody = modifiedBody.replace("super)", "super");
            }

            modifiedBody = modifiedBody.replace("cast", primaryInterface.getName());

            // Generate a method that simply invokes the same method on the delegate
            if (isThrowsSqlException(intfMethod)) {
               modifiedBody = modifiedBody.replace("method", method.getName());
            }
            else {
               modifiedBody = "{ return ((cast) delegate).method($$); }".replace("method", method.getName()).replace("cast", primaryInterface.getName());
            }

            if (method.getReturnType() == CtClass.voidType) {
               modifiedBody = modifiedBody.replace("return", "");
            }

            method.setBody(modifiedBody);
            targetCt.addMethod(method);
         }
      }

      return targetCt.toClass(classPool.getClassLoader(), getClass().getProtectionDomain());
   }

   private boolean isThrowsSqlException(CtMethod method)
   {
      try {
         for (CtClass clazz : method.getExceptionTypes()) {
            if (clazz.getSimpleName().equals("SQLException")) {
               return true;
            }
         }
      }
      catch (NotFoundException e) {
         // fall thru
      }

      return false;
   }

   private boolean isDefaultMethod(Class<?> intf, CtClass intfCt, CtMethod intfMethod) throws Exception
   {
      List<Class<?>> paramTypes = new ArrayList<Class<?>>();

      for (CtClass pt : intfMethod.getParameterTypes()) {
         paramTypes.add(toJavaClass(pt));
      }

      return intf.getDeclaredMethod(intfMethod.getName(), paramTypes.toArray(new Class[0])).toString().contains("default ");
   }

   private Class<?> toJavaClass(CtClass cls) throws Exception
   {
      if (cls.getName().endsWith("[]")) {
         return Array.newInstance(toJavaClass(cls.getName().replace("[]", "")), 0).getClass();
      }
      else {
         return toJavaClass(cls.getName());
      }
   }

   private Class<?> toJavaClass(String cn) throws Exception
   {
      if ("int".equals(cn)) {
         return int.class;
      }
      if ("long".equals(cn)) {
         return long.class;
      }
      if ("short".equals(cn)) {
         return short.class;
      }
      if ("byte".equals(cn)) {
         return byte.class;
      }
      if ("float".equals(cn)) {
         return float.class;
      }
      if ("double".equals(cn)) {
         return double.class;
      }
      if ("boolean".equals(cn)) {
         return boolean.class;
      }
      if ("char".equals(cn)) {
         return char.class;
      }
      if ("void".equals(cn)) {
         return void.class;
      }

      return Class.forName(cn);
   }
}


text:
package uk.ac.st_andrews.cs.host.mk74.inlocy;

import java.util.ArrayList;

public class AccelerometerDataClassifier {
	private static final double MOVEMENT_THRESHOLD = 15.0;
	private static final int WINDOW_TIME_MILLISECS = 2666;
	private static final int WINDOW_N = 3;

	private int predictedMoving = 0;
	private int leftWindowN = WINDOW_N;

	private double lastStandardDeviation = 0.0; //only for debugging(printing values in real time)

	private boolean moving=true;
	private long timeWindowStart = 0;
	private ArrayList<Long> timestamps = new ArrayList<Long>();
	private ArrayList<Double> magnitudes = new ArrayList<Double>();

	public boolean add(float[] values) {
		//todo race condtion

		//add new fixtures
		long currentTime = System.currentTimeMillis();
		if(timeWindowStart==0)
			timeWindowStart = currentTime;
		timestamps.add(currentTime);
		magnitudes.add(calcMagnitude(values));
		long windowDurationTime = currentTime - timeWindowStart;

		//check whether window is complete
		if(windowDurationTime >= WINDOW_TIME_MILLISECS){
			//classify current window
			classify();

			//clear before next window
			timeWindowStart=0;
			timestamps.clear();
			magnitudes.clear();

			//check whether enough windows check to interference
			leftWindowN--;
			if(leftWindowN == 0){
				if(predictedMoving>0){
					moving = true;
				}
				if(predictedMoving<0){
					moving = false;
				}
				predictedMoving = 0;
				leftWindowN = WINDOW_N;
			}
		}
		return moving;
	}

	private Double calcMagnitude(float[] values) {
		double magnitude = 0;
		for(int i=0; i<3; i++)
			magnitude += Math.pow(values[i], 2);
		return magnitude;
	}

	private void classify() {
		double mean = calcMean();
		double standard_deviation = calcStandardDeviation(mean);
		lastStandardDeviation = standard_deviation;

		if(standard_deviation > MOVEMENT_THRESHOLD)
			predictedMoving++;
		else
			predictedMoving--;
	}

	private double calcStandardDeviation(double mean) {
		double standard_deviation = 0;
		for(double magnitude:magnitudes){
			standard_deviation += Math.pow(mean - magnitude, 2);
		}
		standard_deviation /= magnitudes.size();
		standard_deviation = Math.sqrt(standard_deviation);
		return standard_deviation;
	}

	private double calcMean() {
		double mean = 0;
		for(double magnitude : magnitudes){
			mean+=magnitude;
		}
		mean /= magnitudes.size();
		return mean;
	}

	public String getInfo() {
		double rounded = (double) Math.round(lastStandardDeviation * 100) / 100;
		return "isMoving: " + moving + " | predictableMoving: " + predictedMoving +
				" | left window n: " + leftWindowN + " | last stddev: " + rounded + "\n";
	}

}