text:
#include "OgreShaderPrecompiledHeaders.h"
#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS

namespace Ogre {
namespace RTShader {

/************************************************************************/
/*                                                                      */
/************************************************************************/
String FFPTexturing::Type = "FFP_Texturing";
const String SRS_TEXTURING = "FFP_Texturing";

#define _INT_VALUE(f) (*(int*)(&(f)))

const String c_ParamTexelEx("texel_");

//-----------------------------------------------------------------------
FFPTexturing::FFPTexturing() : mIsPointSprite(false), mLateAddBlend(false)
{
}

//-----------------------------------------------------------------------
const String& FFPTexturing::getType() const
{
    return SRS_TEXTURING;
}

//-----------------------------------------------------------------------
int FFPTexturing::getExecutionOrder() const
{
    return FFP_TEXTURING;
}

//-----------------------------------------------------------------------
bool FFPTexturing::resolveParameters(ProgramSet* programSet)
{
    for (auto & i : mTextureUnitParamsList)
    {
        TextureUnitParams* curParams = &i;

        if (false == resolveUniformParams(curParams, programSet))
            return false;

        if (false == resolveFunctionsParams(curParams, programSet))
            return false;
    }

    return true;
}

//-----------------------------------------------------------------------
bool FFPTexturing::resolveUniformParams(TextureUnitParams* textureUnitParams, ProgramSet* programSet)
{
    Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM);
    Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM);

    // Resolve texture sampler parameter.
    textureUnitParams->mTextureSampler = psProgram->resolveParameter(textureUnitParams->mTextureSamplerType, "gTextureSampler", textureUnitParams->mTextureSamplerIndex);

    // Resolve texture matrix parameter.
    if (needsTextureMatrix(textureUnitParams->mTextureUnitState))
    {
        textureUnitParams->mTextureMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_TEXTURE_MATRIX, textureUnitParams->mTextureSamplerIndex);
    }

    switch (textureUnitParams->mTexCoordCalcMethod)
    {
    case TEXCALC_NONE:
        break;

    // Resolve World + View matrices.
    case TEXCALC_ENVIRONMENT_MAP:
    case TEXCALC_ENVIRONMENT_MAP_PLANAR:
    case TEXCALC_ENVIRONMENT_MAP_NORMAL:
        //TODO: change the following 'mWorldITMatrix' member to 'mWorldViewITMatrix'
        mWorldITMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_INVERSE_TRANSPOSE_WORLDVIEW_MATRIX);
        mViewMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_VIEW_MATRIX);
        mWorldMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_WORLD_MATRIX);
        break;

    case TEXCALC_ENVIRONMENT_MAP_REFLECTION:
        mWorldMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_WORLD_MATRIX);
        mWorldITMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_INVERSE_TRANSPOSE_WORLD_MATRIX);
        mViewMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_VIEW_MATRIX);
        break;

    case TEXCALC_PROJECTIVE_TEXTURE:
        mWorldMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_WORLD_MATRIX);
        textureUnitParams->mTextureViewProjImageMatrix = vsProgram->resolveParameter(
            GpuProgramParameters::ACT_TEXTURE_VIEWPROJ_MATRIX, textureUnitParams->mTextureSamplerIndex);
        break;
    }

    return true;
}

//-----------------------------------------------------------------------
bool FFPTexturing::resolveFunctionsParams(TextureUnitParams* textureUnitParams, ProgramSet* programSet)
{
    Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM);
    Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM);
    Function* vsMain   = vsProgram->getEntryPointFunction();
    Function* psMain   = psProgram->getEntryPointFunction();
    Parameter::Content texCoordContent = Parameter::SPC_UNKNOWN;

    switch (textureUnitParams->mTexCoordCalcMethod)
    {
        case TEXCALC_NONE:
            // Resolve explicit vs input texture coordinates.

            if(mIsPointSprite)
                break;

            if (textureUnitParams->mTextureMatrix.get() == NULL)
                texCoordContent = Parameter::Content(Parameter::SPC_TEXTURE_COORDINATE0 + textureUnitParams->mTextureUnitState->getTextureCoordSet());

            // assume already resolved
            if(vsMain->getOutputParameter(texCoordContent, textureUnitParams->mVSInTextureCoordinateType))
                break;

            textureUnitParams->mVSInputTexCoord = vsMain->resolveInputParameter(
                Parameter::Content(Parameter::SPC_TEXTURE_COORDINATE0 +
                                   textureUnitParams->mTextureUnitState->getTextureCoordSet()),
                textureUnitParams->mVSInTextureCoordinateType);
            break;

        case TEXCALC_ENVIRONMENT_MAP:
        case TEXCALC_ENVIRONMENT_MAP_PLANAR:
        case TEXCALC_ENVIRONMENT_MAP_NORMAL:
            // Resolve vertex normal.
            mVSInputPos = vsMain->resolveInputParameter(Parameter::SPC_POSITION_OBJECT_SPACE);
            mVSInputNormal = vsMain->resolveInputParameter(Parameter::SPC_NORMAL_OBJECT_SPACE);
            break;

        case TEXCALC_ENVIRONMENT_MAP_REFLECTION:

            // Resolve vertex normal.
            mVSInputNormal = vsMain->resolveInputParameter(Parameter::SPC_NORMAL_OBJECT_SPACE);
            // Resolve vertex position.
            mVSInputPos = vsMain->resolveInputParameter(Parameter::SPC_POSITION_OBJECT_SPACE);
            break;

        case TEXCALC_PROJECTIVE_TEXTURE:
            // Resolve vertex position.
            mVSInputPos = vsMain->resolveInputParameter(Parameter::SPC_POSITION_OBJECT_SPACE);
            break;
    }

    if(mIsPointSprite)
    {
        textureUnitParams->mPSInputTexCoord = psMain->resolveInputParameter(Parameter::SPC_POINTSPRITE_COORDINATE);
    }
    else
    {
        // Resolve vs output texture coordinates.
        textureUnitParams->mVSOutputTexCoord =
            vsMain->resolveOutputParameter(texCoordContent, textureUnitParams->mVSOutTextureCoordinateType);

        // Resolve ps input texture coordinates.
        textureUnitParams->mPSInputTexCoord = psMain->resolveInputParameter(textureUnitParams->mVSOutputTexCoord);
    }

    mPSDiffuse = psMain->getInputParameter(Parameter::SPC_COLOR_DIFFUSE);
    if (mPSDiffuse.get() == NULL)
    {
        mPSDiffuse = psMain->getLocalParameter(Parameter::SPC_COLOR_DIFFUSE);
    }

    mPSSpecular = psMain->getInputParameter(Parameter::SPC_COLOR_SPECULAR);
    if (mPSSpecular.get() == NULL)
    {
        mPSSpecular = psMain->getLocalParameter(Parameter::SPC_COLOR_SPECULAR);
    }

    mPSOutDiffuse = psMain->resolveOutputParameter(Parameter::SPC_COLOR_DIFFUSE);

    if (!mPSDiffuse || !mPSSpecular)
    {
        OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,
                    "Not all parameters could be constructed for the sub-render state.");
    }
    return true;
}

//-----------------------------------------------------------------------
bool FFPTexturing::resolveDependencies(ProgramSet* programSet)
{
    //! [deps_resolve]
    Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM);
    Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM);

    vsProgram->addDependency(FFP_LIB_TEXTURING);
    psProgram->addDependency(FFP_LIB_TEXTURING);
    //! [deps_resolve]
    return true;
}

//-----------------------------------------------------------------------
bool FFPTexturing::addFunctionInvocations(ProgramSet* programSet)
{
    Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM);
    Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM);
    Function* vsMain   = vsProgram->getEntryPointFunction();
    Function* psMain   = psProgram->getEntryPointFunction();

    for (auto & i : mTextureUnitParamsList)
    {
        TextureUnitParams* curParams = &i;

        if (false == addVSFunctionInvocations(curParams, vsMain))
            return false;

        if (false == addPSFunctionInvocations(curParams, psMain))
            return false;
    }

    return true;
}

//-----------------------------------------------------------------------
bool FFPTexturing::addVSFunctionInvocations(TextureUnitParams* textureUnitParams, Function* vsMain)
{
    if(mIsPointSprite)
        return true;

    auto stage = vsMain->getStage(FFP_VS_TEXTURING);

    switch (textureUnitParams->mTexCoordCalcMethod)
    {
    case TEXCALC_NONE:
        if(textureUnitParams->mVSInputTexCoord)
        stage.assign(textureUnitParams->mVSInputTexCoord, textureUnitParams->mVSOutputTexCoord);
        break;
    case TEXCALC_ENVIRONMENT_MAP:
    case TEXCALC_ENVIRONMENT_MAP_PLANAR:
        stage.callFunction(FFP_FUNC_GENERATE_TEXCOORD_ENV_SPHERE,
                           {In(mWorldMatrix), In(mViewMatrix), In(mWorldITMatrix), In(mVSInputPos), In(mVSInputNormal),
                            Out(textureUnitParams->mVSOutputTexCoord)});
        break;
    case TEXCALC_ENVIRONMENT_MAP_REFLECTION:
        stage.callFunction(FFP_FUNC_GENERATE_TEXCOORD_ENV_REFLECT,
                           {In(mWorldMatrix), In(mWorldITMatrix), In(mViewMatrix), In(mVSInputNormal), In(mVSInputPos),
                            Out(textureUnitParams->mVSOutputTexCoord)});
        break;
    case TEXCALC_ENVIRONMENT_MAP_NORMAL:
        stage.callFunction(
            FFP_FUNC_GENERATE_TEXCOORD_ENV_NORMAL,
            {In(mWorldITMatrix), In(mViewMatrix), In(mVSInputNormal), Out(textureUnitParams->mVSOutputTexCoord)});
        break;
    case TEXCALC_PROJECTIVE_TEXTURE:
        stage.callFunction(FFP_FUNC_GENERATE_TEXCOORD_PROJECTION,
                           {In(mWorldMatrix), In(textureUnitParams->mTextureViewProjImageMatrix), In(mVSInputPos),
                            Out(textureUnitParams->mVSOutputTexCoord)});
        break;
    default:
        return false;
    }

    if (textureUnitParams->mTextureMatrix)
    {
        stage.callFunction(FFP_FUNC_TRANSFORM_TEXCOORD, textureUnitParams->mTextureMatrix,
                           textureUnitParams->mVSOutputTexCoord, textureUnitParams->mVSOutputTexCoord);
    }

    return true;
}
//-----------------------------------------------------------------------
bool FFPTexturing::addPSFunctionInvocations(TextureUnitParams* textureUnitParams, Function* psMain)
{
    const LayerBlendModeEx& colourBlend = textureUnitParams->mTextureUnitState->getColourBlendMode();
    const LayerBlendModeEx& alphaBlend  = textureUnitParams->mTextureUnitState->getAlphaBlendMode();
    ParameterPtr source1;
    ParameterPtr source2;
    int groupOrder = FFP_PS_TEXTURING;

    // Add texture sampling code.
    ParameterPtr texel = psMain->resolveLocalParameter(GCT_FLOAT4, c_ParamTexelEx + StringConverter::toString(textureUnitParams->mTextureSamplerIndex));

    // Build colour argument for source1.
    source1 = getPSArgument(texel, colourBlend.source1, colourBlend.colourArg1, colourBlend.alphaArg1, false);

    // Build colour argument for source2.
    source2 = getPSArgument(texel, colourBlend.source2, colourBlend.colourArg2, colourBlend.alphaArg2, false);

    if(source1 == texel || source2 == texel || colourBlend.operation == LBX_BLEND_TEXTURE_ALPHA)
        addPSSampleTexelInvocation(textureUnitParams, psMain, texel, FFP_PS_SAMPLING);

    bool needDifferentAlphaBlend = false;
    if (alphaBlend.operation != colourBlend.operation ||
        alphaBlend.source1 != colourBlend.source1 ||
        alphaBlend.source2 != colourBlend.source2 ||
        colourBlend.source1 == LBS_MANUAL ||
        colourBlend.source2 == LBS_MANUAL ||
        alphaBlend.source1 == LBS_MANUAL ||
        alphaBlend.source2 == LBS_MANUAL)
        needDifferentAlphaBlend = true;

    if(mLateAddBlend && colourBlend.operation == LBX_ADD)
    {
        groupOrder = FFP_PS_COLOUR_END + 50 + 1; // after PBR lighting
    }

    // Build colours blend
    addPSBlendInvocations(psMain, source1, source2, texel,
        textureUnitParams->mTextureSamplerIndex,
        colourBlend, groupOrder,
        needDifferentAlphaBlend ? Operand::OPM_XYZ : Operand::OPM_ALL);

    // Case we need different alpha channel code.
    if (needDifferentAlphaBlend)
    {
        // Build alpha argument for source1.
        source1 = getPSArgument(texel, alphaBlend.source1, alphaBlend.colourArg1, alphaBlend.alphaArg1, true);

        // Build alpha argument for source2.
        source2 = getPSArgument(texel, alphaBlend.source2, alphaBlend.colourArg2, alphaBlend.alphaArg2, true);

        if(source1 == texel || source2 == texel || alphaBlend.operation == LBX_BLEND_TEXTURE_ALPHA)
            addPSSampleTexelInvocation(textureUnitParams, psMain, texel, FFP_PS_SAMPLING);

        // Build alpha blend
        addPSBlendInvocations(psMain, source1, source2, texel,
                              textureUnitParams->mTextureSamplerIndex, alphaBlend, groupOrder,
                              Operand::OPM_W);
    }

    return true;
}

//-----------------------------------------------------------------------
void FFPTexturing::addPSSampleTexelInvocation(TextureUnitParams* textureUnitParams, Function* psMain,
                                              const ParameterPtr& texel, int groupOrder)
{
    auto stage = psMain->getStage(groupOrder);

    if (textureUnitParams->mTexCoordCalcMethod != TEXCALC_PROJECTIVE_TEXTURE)
    {
        stage.sampleTexture(textureUnitParams->mTextureSampler, textureUnitParams->mPSInputTexCoord, texel);
        return;
    }

    stage.callFunction(FFP_FUNC_SAMPLE_TEXTURE_PROJ, textureUnitParams->mTextureSampler,
                       textureUnitParams->mPSInputTexCoord, texel);
}

//-----------------------------------------------------------------------
ParameterPtr FFPTexturing::getPSArgument(ParameterPtr texel, LayerBlendSource blendSrc, const ColourValue& colourValue,
                                         Real alphaValue, bool isAlphaArgument) const
{
    switch(blendSrc)
    {
    case LBS_CURRENT:
        return mPSOutDiffuse;
    case LBS_TEXTURE:
        return texel;
    case LBS_DIFFUSE:
        return mPSDiffuse;
    case LBS_SPECULAR:
        return mPSSpecular;
    case LBS_MANUAL:
        if (isAlphaArgument)
        {
            return ParameterFactory::createConstParam(Vector4(alphaValue));
        }

        return ParameterFactory::createConstParam(Vector4((Real)colourValue.r, (Real)colourValue.g,
                                                         (Real)colourValue.b, (Real)colourValue.a));
    }

    return ParameterPtr();
}

//-----------------------------------------------------------------------
void FFPTexturing::addPSBlendInvocations(Function* psMain,
                                          ParameterPtr arg1,
                                          ParameterPtr arg2,
                                          ParameterPtr texel,
                                          int samplerIndex,
                                          const LayerBlendModeEx& blendMode,
                                          const int groupOrder,
                                          Operand::OpMask mask)
{
    auto stage = psMain->getStage(groupOrder);
    switch(blendMode.operation)
    {
    case LBX_SOURCE1:
        stage.assign(In(arg1).mask(mask), Out(mPSOutDiffuse).mask(mask));
        break;
    case LBX_SOURCE2:
        stage.assign(In(arg2).mask(mask), Out(mPSOutDiffuse).mask(mask));
        break;
    case LBX_MODULATE:
        stage.mul(In(arg1).mask(mask), In(arg2).mask(mask), Out(mPSOutDiffuse).mask(mask));
        break;
    case LBX_MODULATE_X2:
        stage.callFunction(FFP_FUNC_MODULATEX2, In(arg1).mask(mask), In(arg2).mask(mask),
                           Out(mPSOutDiffuse).mask(mask));
        break;
    case LBX_MODULATE_X4:
        stage.callFunction(FFP_FUNC_MODULATEX4, In(arg1).mask(mask), In(arg2).mask(mask),
                           Out(mPSOutDiffuse).mask(mask));
        break;
    case LBX_ADD:
        stage.add(In(arg1).mask(mask), In(arg2).mask(mask), Out(mPSOutDiffuse).mask(mask));
        break;
    case LBX_ADD_SIGNED:
        stage.callFunction(FFP_FUNC_ADDSIGNED, In(arg1).mask(mask), In(arg2).mask(mask),
                           Out(mPSOutDiffuse).mask(mask));
        break;
    case LBX_ADD_SMOOTH:
        stage.callFunction(FFP_FUNC_ADDSMOOTH, In(arg1).mask(mask), In(arg2).mask(mask),
                           Out(mPSOutDiffuse).mask(mask));
        break;
    case LBX_SUBTRACT:
        stage.sub(In(arg1).mask(mask), In(arg2).mask(mask), Out(mPSOutDiffuse).mask(mask));
        break;
    case LBX_BLEND_DIFFUSE_ALPHA:
        stage.callBuiltin(
            "mix", {In(arg2).mask(mask), In(arg1).mask(mask), In(mPSDiffuse).w(), Out(mPSOutDiffuse).mask(mask)});
        break;
    case LBX_BLEND_TEXTURE_ALPHA:
        stage.callBuiltin("mix",
                          {In(arg2).mask(mask), In(arg1).mask(mask), In(texel).w(), Out(mPSOutDiffuse).mask(mask)});
        break;
    case LBX_BLEND_CURRENT_ALPHA:
        stage.callBuiltin(
            "mix", {In(arg2).mask(mask), In(arg1).mask(mask), In(mPSOutDiffuse).w(), Out(mPSOutDiffuse).mask(mask)});
        break;
    case LBX_BLEND_MANUAL:
        stage.callBuiltin(
            "mix", {In(arg2).mask(mask), In(arg1).mask(mask), In(blendMode.factor), Out(mPSOutDiffuse).mask(mask)});
        break;
    case LBX_DOTPRODUCT:
        stage.callFunction(FFP_FUNC_DOTPRODUCT, In(arg2).mask(mask), In(arg1).mask(mask),
                           Out(mPSOutDiffuse).mask(mask));
        break;
    case LBX_BLEND_DIFFUSE_COLOUR:
        stage.callBuiltin("mix", {In(arg2).mask(mask), In(arg1).mask(mask), In(mPSDiffuse).mask(mask),
                                  Out(mPSOutDiffuse).mask(mask)});
        break;
    }
}

//-----------------------------------------------------------------------
TexCoordCalcMethod FFPTexturing::getTexCalcMethod(TextureUnitState* textureUnitState)
{
    TexCoordCalcMethod                      texCoordCalcMethod = TEXCALC_NONE;
    const TextureUnitState::EffectMap&      effectMap = textureUnitState->getEffects();
    TextureUnitState::EffectMap::const_iterator effi;

    for (effi = effectMap.begin(); effi != effectMap.end(); ++effi)
    {
        switch (effi->second.type)
        {
        case TextureUnitState::ET_ENVIRONMENT_MAP:
            if (effi->second.subtype == TextureUnitState::ENV_CURVED)
            {
                texCoordCalcMethod = TEXCALC_ENVIRONMENT_MAP;
            }
            else if (effi->second.subtype == TextureUnitState::ENV_PLANAR)
            {
                texCoordCalcMethod = TEXCALC_ENVIRONMENT_MAP_PLANAR;
            }
            else if (effi->second.subtype == TextureUnitState::ENV_REFLECTION)
            {
                texCoordCalcMethod = TEXCALC_ENVIRONMENT_MAP_REFLECTION;
            }
            else if (effi->second.subtype == TextureUnitState::ENV_NORMAL)
            {
                texCoordCalcMethod = TEXCALC_ENVIRONMENT_MAP_NORMAL;
            }
            break;
        case TextureUnitState::ET_UVSCROLL:
        case TextureUnitState::ET_USCROLL:
        case TextureUnitState::ET_VSCROLL:
        case TextureUnitState::ET_ROTATE:
        case TextureUnitState::ET_TRANSFORM:
            break;
        case TextureUnitState::ET_PROJECTIVE_TEXTURE:
            texCoordCalcMethod = TEXCALC_PROJECTIVE_TEXTURE;
            break;
        }
    }

    return texCoordCalcMethod;
}

//-----------------------------------------------------------------------
bool FFPTexturing::needsTextureMatrix(TextureUnitState* textureUnitState)
{
    const TextureUnitState::EffectMap&      effectMap = textureUnitState->getEffects();
    TextureUnitState::EffectMap::const_iterator effi;

    for (effi = effectMap.begin(); effi != effectMap.end(); ++effi)
    {
        switch (effi->second.type)
        {

        case TextureUnitState::ET_UVSCROLL:
        case TextureUnitState::ET_USCROLL:
        case TextureUnitState::ET_VSCROLL:
        case TextureUnitState::ET_ROTATE:
        case TextureUnitState::ET_TRANSFORM:
            return true;
        case TextureUnitState::ET_ENVIRONMENT_MAP:
        case TextureUnitState::ET_PROJECTIVE_TEXTURE:
            break;
        }
    }

    const Ogre::Matrix4 matTexture = textureUnitState->getTextureTransform();

    // Resolve texture matrix parameter.
    if (matTexture != Matrix4::IDENTITY)
        return true;

    return false;
}

bool FFPTexturing::setParameter(const String& name, const String& value)
{
    if(name == "late_add_blend")
    {
        StringConverter::parse(value, mLateAddBlend);
        return true;
    }
    return false;
}

//-----------------------------------------------------------------------
void FFPTexturing::copyFrom(const SubRenderState& rhs)
{
    const FFPTexturing& rhsTexture = static_cast<const FFPTexturing&>(rhs);

    mLateAddBlend = rhsTexture.mLateAddBlend;
    setTextureUnitCount(rhsTexture.getTextureUnitCount());

    for (unsigned int i=0; i < rhsTexture.getTextureUnitCount(); ++i)
    {
        setTextureUnit(i, rhsTexture.mTextureUnitParamsList[i].mTextureUnitState);
    }
}

//-----------------------------------------------------------------------
bool FFPTexturing::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass)
{
    mIsPointSprite = srcPass->getPointSpritesEnabled();

    if (auto rs = Root::getSingleton().getRenderSystem())
    {
        if (mIsPointSprite && !rs->getCapabilities()->hasCapability(RSC_POINT_SPRITES))
            return false;
    }

    setTextureUnitCount(srcPass->getTextureUnitStates().size());

    // Build texture stage sub states.
    for (unsigned short i=0; i < srcPass->getNumTextureUnitStates(); ++i)
    {
        TextureUnitState* texUnitState = srcPass->getTextureUnitState(i);
        setTextureUnit(i, texUnitState);
    }

    return true;
}

//-----------------------------------------------------------------------
void FFPTexturing::setTextureUnitCount(size_t count)
{
    mTextureUnitParamsList.resize(count);

    for (unsigned int i=0; i < count; ++i)
    {
        TextureUnitParams& curParams = mTextureUnitParamsList[i];

        curParams.mTextureUnitState             = NULL;
        curParams.mTextureSamplerIndex          = 0;
        curParams.mTextureSamplerType           = GCT_SAMPLER2D;
        curParams.mVSInTextureCoordinateType    = GCT_FLOAT2;
        curParams.mVSOutTextureCoordinateType   = GCT_FLOAT2;
    }
}

//-----------------------------------------------------------------------
void FFPTexturing::setTextureUnit(unsigned short index, TextureUnitState* textureUnitState)
{
    OgreAssert(index < mTextureUnitParamsList.size(), "FFPTexturing unit index out of bounds");

    TextureUnitParams& curParams = mTextureUnitParamsList[index];

    curParams.mTextureSamplerIndex = index;
    curParams.mTextureUnitState    = textureUnitState;

    bool isGLES2 = ShaderGenerator::getSingleton().getTargetLanguage() == "glsles";

    switch (curParams.mTextureUnitState->getTextureType())
    {
    case TEX_TYPE_1D:
        curParams.mTextureSamplerType = GCT_SAMPLER1D;
        curParams.mVSInTextureCoordinateType = GCT_FLOAT1;
        if(!isGLES2) // no 1D texture support
            break;
        OGRE_FALLTHROUGH;
    case TEX_TYPE_2D:
        curParams.mTextureSamplerType = GCT_SAMPLER2D;
        curParams.mVSInTextureCoordinateType = GCT_FLOAT2;
        break;
    case TEX_TYPE_EXTERNAL_OES:
        curParams.mTextureSamplerType = GCT_SAMPLER_EXTERNAL_OES;
        curParams.mVSInTextureCoordinateType = GCT_FLOAT2;
        break;
    case TEX_TYPE_2D_ARRAY:
        curParams.mTextureSamplerType = GCT_SAMPLER2DARRAY;
        curParams.mVSInTextureCoordinateType = GCT_FLOAT3;
        break;
    case TEX_TYPE_3D:
        curParams.mTextureSamplerType = GCT_SAMPLER3D;
        curParams.mVSInTextureCoordinateType = GCT_FLOAT3;
        break;
    case TEX_TYPE_CUBE_MAP:
        curParams.mTextureSamplerType = GCT_SAMPLERCUBE;
        curParams.mVSInTextureCoordinateType = GCT_FLOAT3;
        break;
    }

     curParams.mVSOutTextureCoordinateType = curParams.mVSInTextureCoordinateType;
     curParams.mTexCoordCalcMethod = getTexCalcMethod(curParams.mTextureUnitState);

    if (curParams.mTexCoordCalcMethod == TEXCALC_PROJECTIVE_TEXTURE)
        curParams.mVSOutTextureCoordinateType = GCT_FLOAT3;

    // let TexCalcMethod override texture type, as it might be wrong for
    // content_type shadow & content_type compositor
    if (curParams.mTexCoordCalcMethod == TEXCALC_ENVIRONMENT_MAP_REFLECTION ||
        curParams.mTexCoordCalcMethod == TEXCALC_ENVIRONMENT_MAP_NORMAL)
    {
        if (textureUnitState->getContentType() == TextureUnitState::CONTENT_NAMED &&
            curParams.mTextureSamplerType != GCT_SAMPLERCUBE)
        {
            const auto& matname = textureUnitState->getParent()->getParent()->getParent()->getName();
            LogManager::getSingleton().logError(matname + " - env_map setting requires a cubic texture");
        }
        curParams.mVSOutTextureCoordinateType = GCT_FLOAT3;
        curParams.mTextureSamplerType = GCT_SAMPLERCUBE;
    }

    if (curParams.mTexCoordCalcMethod == TEXCALC_ENVIRONMENT_MAP_PLANAR ||
        curParams.mTexCoordCalcMethod == TEXCALC_ENVIRONMENT_MAP)
    {
        if (textureUnitState->getContentType() == TextureUnitState::CONTENT_NAMED &&
            curParams.mTextureSamplerType != GCT_SAMPLER2D)
        {
            const auto& matname = textureUnitState->getParent()->getParent()->getParent()->getName();
            LogManager::getSingleton().logError(matname + " - env_map setting requires a 2d texture");
        }
        curParams.mVSOutTextureCoordinateType = GCT_FLOAT2;
        curParams.mTextureSamplerType = GCT_SAMPLER2D;
    }
}

//-----------------------------------------------------------------------
const String& FFPTexturingFactory::getType() const
{
    return SRS_TEXTURING;
}

//-----------------------------------------------------------------------
SubRenderState* FFPTexturingFactory::createInstance(ScriptCompiler* compiler,
                                                 PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator)
{
    if (prop->name == "texturing_stage")
    {
        if(prop->values.size() == 1)
        {
            const String& value = prop->values.front()->getString();

            auto inst = createOrRetrieveInstance(translator);

            if (value == "ffp")
                return inst;

            if (value == "late_add_blend")
                inst->setParameter(value, "true");

            return inst;
        }
    }

    return NULL;
}

//-----------------------------------------------------------------------
void FFPTexturingFactory::writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState,
                                     Pass* srcPass, Pass* dstPass)
{
    ser->writeAttribute(4, "texturing_stage");
    ser->writeValue("ffp");
}

//-----------------------------------------------------------------------
SubRenderState* FFPTexturingFactory::createInstanceImpl()
{
    return OGRE_NEW FFPTexturing;
}

}
}

#endif


text:
static VALUE rb_cKetama;
ketama_continuum cont;

static VALUE initialize(VALUE self, VALUE filename_str) {
  char *filename;
  filename = StringValuePtr(filename_str);
  ketama_roll(&cont, filename);
  return self;
}

static VALUE get_server(VALUE self, VALUE key_str) {
  char *key;
  mcs *server;
  key = StringValuePtr(key_str);
  server = ketama_get_server(key, cont);
  return rb_str_new2(server->ip);
}

void Init_ketama() {
  VALUE rb_cKetama = rb_define_class("Ketama", rb_cObject);
  rb_define_method(rb_cKetama, "initialize", initialize, 1);
  rb_define_method(rb_cKetama, "server", get_server, 1);
}

redpajama_set_name: RedPajamaGithub


text:
class CreateUserTokens < ActiveRecord::Migration
  def change
    create_table :auths, :id => false do |t|
      t.integer :user_id
      t.string :user_token
      t.string :expiration
      t.string :access_token
      t.integer :charityid
      t.timestamps
    end
  end
end


text:
/*
 * 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.
 */
package com.facebook.presto.tests;

import com.facebook.presto.Session;
import com.facebook.presto.common.QualifiedObjectName;
import com.facebook.presto.common.type.LongEnumParametricType;
import com.facebook.presto.common.type.LongEnumType.LongEnumMap;
import com.facebook.presto.common.type.VarcharEnumParametricType;
import com.facebook.presto.common.type.VarcharEnumType.VarcharEnumMap;
import com.facebook.presto.testing.MaterializedResult;
import com.facebook.presto.testing.MaterializedRow;
import com.facebook.presto.testing.QueryRunner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import org.intellij.lang.annotations.Language;
import org.testng.annotations.Test;

import java.util.List;
import java.util.stream.Collectors;

import static com.facebook.presto.testing.TestingSession.testSessionBuilder;
import static java.util.Collections.singletonList;
import static org.testng.Assert.assertEquals;

@Test(singleThreaded = true)
public class TestEnums
        extends AbstractTestQueryFramework
{
    private static final Long BIG_VALUE = Integer.MAX_VALUE + 10L; // 2147483657

    private static final LongEnumParametricType MOOD_ENUM = new LongEnumParametricType(QualifiedObjectName.valueOf("test.enum.mood"), new LongEnumMap(ImmutableMap.of(
            "HAPPY", 0L,
            "SAD", 1L,
            "MELLOW", BIG_VALUE,
            "curious", -2L)));
    private static final VarcharEnumParametricType COUNTRY_ENUM = new VarcharEnumParametricType(QualifiedObjectName.valueOf("test.enum.country"), new VarcharEnumMap(ImmutableMap.of(
            "US", "United States",
            "BAHAMAS", "The Bahamas",
            "FRANCE", "France",
            "CHINA", "中国",
            "भारत", "India")));
    private static final VarcharEnumParametricType TEST_ENUM = new VarcharEnumParametricType(QualifiedObjectName.valueOf("test.enum.testenum"), new VarcharEnumMap(ImmutableMap.of(
            "TEST", "\"}\"",
            "TEST2", "",
            "TEST3", " ",
            "TEST4", ")))\"\"")));
    private static final LongEnumParametricType TEST_LONG_ENUM = new LongEnumParametricType(QualifiedObjectName.valueOf("test.enum.testlongenum"), new LongEnumMap(ImmutableMap.of(
            "TEST", 6L,
            "TEST2", 8L)));

    protected TestEnums()
    {
        super(TestEnums::createQueryRunner);
    }

    private static QueryRunner createQueryRunner()
    {
        try {
            Session session = testSessionBuilder().build();
            DistributedQueryRunner queryRunner = DistributedQueryRunner.builder(session).setNodeCount(1).build();
            queryRunner.enableTestFunctionNamespaces(ImmutableList.of("test"), ImmutableMap.of());
            queryRunner.getMetadata().getFunctionAndTypeManager().addParametricType(MOOD_ENUM);
            queryRunner.getMetadata().getFunctionAndTypeManager().addParametricType(COUNTRY_ENUM);
            queryRunner.getMetadata().getFunctionAndTypeManager().addParametricType(TEST_ENUM);
            queryRunner.getMetadata().getFunctionAndTypeManager().addParametricType(TEST_LONG_ENUM);
            return queryRunner;
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void assertQueryResultUnordered(@Language("SQL") String query, List<List<Object>> expectedRows)
    {
        MaterializedResult rows = computeActual(query);
        assertEquals(
                ImmutableSet.copyOf(rows.getMaterializedRows()),
                expectedRows.stream().map(row -> new MaterializedRow(1, row)).collect(Collectors.toSet()));
    }

    private void assertSingleValue(@Language("SQL") String expression, Object expectedResult)
    {
        assertQueryResultUnordered("SELECT " + expression, singletonList(singletonList(expectedResult)));
    }

    @Test
    public void testEnumLiterals()
    {
        assertQueryResultUnordered(
                "SELECT test.enum.mood.HAPPY, test.enum.mood.happY, \"test.enum.mood\".SAD, \"test.enum.mood\".\"mellow\"",
                singletonList(ImmutableList.of(0L, 0L, 1L, BIG_VALUE)));

        assertQueryResultUnordered(
                "SELECT test.enum.country.us, test.enum.country.\"CHINA\", test.enum.country.\"भारत\"",
                singletonList(ImmutableList.of("United States", "中国", "India")));

        assertQueryResultUnordered(
                "SELECT test.enum.testEnum.TEST, test.enum.testEnum.TEST2, test.enum.testEnum.TEST3, array[test.enum.testEnum.TEST4]",
                singletonList(ImmutableList.of("\"}\"", "", " ", ImmutableList.of(")))\"\""))));

        assertQueryFails("SELECT test.enum.mood.hello", ".*No key 'HELLO' in enum 'test.enum.mood'");
    }

    @Test
    public void testEnumCasts()
    {
        assertSingleValue("CAST(CAST(1 AS TINYINT) AS test.enum.mood)", 1L);
        assertSingleValue("CAST('The Bahamas' AS test.enum.country)", "The Bahamas");
        assertSingleValue("CAST(row(1, 1) as row(x BIGINT, y test.enum.mood))", ImmutableList.of(1L, 1L));
        assertSingleValue("CAST(test.enum.mood.MELLOW AS BIGINT)", BIG_VALUE);
        assertSingleValue(
                "cast(map(array[test.enum.country.FRANCE], array[array[test.enum.mood.HAPPY]]) as JSON)",
                "{\"France\":[0]}");
        assertSingleValue(
                "map_filter(MAP(ARRAY[test.enum.country.FRANCE, test.enum.country.US], ARRAY[test.enum.mood.HAPPY, test.enum.mood.SAD]), (k,v) -> CAST(v AS BIGINT) > 0)",
                ImmutableMap.of("United States", 1L));
        assertSingleValue(
                "cast(JSON '{\"France\": [0]}' as MAP<test.enum.country,ARRAY<test.enum.mood>>)",
                ImmutableMap.of("France", singletonList(0L)));
        assertQueryFails("select cast(7 as test.enum.mood)", ".*No value '7' in enum 'test.enum.mood'");
    }

    @Test
    public void testVarcharEnumComparisonOperators()
    {
        assertSingleValue("test.enum.country.US = CAST('United States' AS test.enum.country)", true);
        assertSingleValue("test.enum.country.FRANCE = test.enum.country.BAHAMAS", false);

        assertSingleValue("test.enum.country.FRANCE != test.enum.country.US", true);
        assertSingleValue("array[test.enum.country.FRANCE, test.enum.country.BAHAMAS] != array[test.enum.country.US, test.enum.country.BAHAMAS]", true);

        assertSingleValue("test.enum.country.CHINA IN (test.enum.country.US, null, test.enum.country.BAHAMAS, test.enum.country.China)", true);
        assertSingleValue("test.enum.country.BAHAMAS IN (test.enum.country.US, test.enum.country.FRANCE)", false);

        assertSingleValue("test.enum.country.BAHAMAS < test.enum.country.US", true);
        assertSingleValue("test.enum.country.BAHAMAS < test.enum.country.BAHAMAS", false);

        assertSingleValue("test.enum.country.\"भारत\" <= test.enum.country.\"भारत\"", true);
        assertSingleValue("test.enum.country.\"भारत\" <= test.enum.country.FRANCE", false);

        assertSingleValue("test.enum.country.\"भारत\" >= test.enum.country.FRANCE", true);
        assertSingleValue("test.enum.country.BAHAMAS >= test.enum.country.US", false);

        assertSingleValue("test.enum.country.\"भारत\" > test.enum.country.FRANCE", true);
        assertSingleValue("test.enum.country.CHINA > test.enum.country.CHINA", false);

        assertSingleValue("test.enum.country.\"भारत\" between test.enum.country.FRANCE and test.enum.country.BAHAMAS", true);
        assertSingleValue("test.enum.country.US between test.enum.country.FRANCE and test.enum.country.\"भारत\"", false);

        assertQueryFails("select test.enum.country.US = test.enum.mood.HAPPY", ".* '=' cannot be applied to test.enum.country.*, test.enum.mood.*");
        assertQueryFails("select test.enum.country.US IN (test.enum.country.CHINA, test.enum.mood.SAD)", ".* All IN list values must be the same type.*");
        assertQueryFails("select test.enum.country.US IN (test.enum.mood.HAPPY, test.enum.mood.SAD)", ".* IN value and list items must be the same type: test.enum.country");
        assertQueryFails("select test.enum.country.US > 2", ".* '>' cannot be applied to test.enum.country.*, integer");
    }

    @Test
    public void testLongEnumComparisonOperators()
    {
        assertSingleValue("test.enum.mood.HAPPY = CAST(0 AS test.enum.mood)", true);
        assertSingleValue("test.enum.mood.HAPPY = test.enum.mood.SAD", false);

        assertSingleValue("test.enum.mood.SAD != test.enum.mood.MELLOW", true);
        assertSingleValue("array[test.enum.mood.HAPPY, test.enum.mood.SAD] != array[test.enum.mood.SAD, test.enum.mood.HAPPY]", true);

        assertSingleValue("test.enum.mood.SAD IN (test.enum.mood.HAPPY, null, test.enum.mood.SAD)", true);
        assertSingleValue("test.enum.mood.HAPPY IN (test.enum.mood.SAD, test.enum.mood.MELLOW)", false);

        assertSingleValue("test.enum.mood.CURIOUS < test.enum.mood.MELLOW", true);
        assertSingleValue("test.enum.mood.SAD < test.enum.mood.HAPPY", false);

        assertSingleValue("test.enum.mood.HAPPY <= test.enum.mood.HAPPY", true);
        assertSingleValue("test.enum.mood.HAPPY <= test.enum.mood.CURIOUS", false);

        assertSingleValue("test.enum.mood.MELLOW >= test.enum.mood.SAD", true);
        assertSingleValue("test.enum.mood.HAPPY >= test.enum.mood.SAD", false);

        assertSingleValue("test.enum.mood.SAD > test.enum.mood.HAPPY", true);
        assertSingleValue("test.enum.mood.HAPPY > test.enum.mood.HAPPY", false);

        assertSingleValue("test.enum.mood.HAPPY between test.enum.mood.CURIOUS and test.enum.mood.SAD ", true);
        assertSingleValue("test.enum.mood.MELLOW between test.enum.mood.SAD and test.enum.mood.HAPPY", false);

        assertQueryFails("select test.enum.mood.HAPPY = 3", ".* '=' cannot be applied to test.enum.mood.*, integer");
    }

    @Test
    public void testEnumHashOperators()
    {
        assertQueryResultUnordered(
                "SELECT DISTINCT x " +
                        "FROM (VALUES test.enum.mood.happy, test.enum.mood.sad, test.enum.mood.sad, test.enum.mood.happy) t(x)",
                ImmutableList.of(
                        ImmutableList.of(0L),
                        ImmutableList.of(1L)));

        assertQueryResultUnordered(
                "SELECT DISTINCT x " +
                        "FROM (VALUES test.enum.country.FRANCE, test.enum.country.FRANCE, test.enum.country.\"भारत\") t(x)",
                ImmutableList.of(
                        ImmutableList.of("France"),
                        ImmutableList.of("India")));

        assertQueryResultUnordered(
                "SELECT APPROX_DISTINCT(x), APPROX_DISTINCT(y)" +
                        "FROM (VALUES (test.enum.country.FRANCE, test.enum.mood.HAPPY), " +
                        "             (test.enum.country.FRANCE, test.enum.mood.SAD)," +
                        "             (test.enum.country.US, test.enum.mood.HAPPY)) t(x, y)",
                ImmutableList.of(
                        ImmutableList.of(2L, 2L)));
    }

    @Test
    public void testEnumAggregation()
    {
        assertQueryResultUnordered(
                "  SELECT a, ARRAY_AGG(DISTINCT b) " +
                        "FROM (VALUES (test.enum.mood.happy, test.enum.country.us), " +
                        "             (test.enum.mood.happy, test.enum.country.china)," +
                        "             (test.enum.mood.happy, test.enum.country.CHINA)," +
                        "             (test.enum.mood.sad, test.enum.country.us)) t(a, b)" +
                        "GROUP BY a",
                ImmutableList.of(
                        ImmutableList.of(0L, ImmutableList.of("United States", "中国")),
                        ImmutableList.of(1L, ImmutableList.of("United States"))));
    }

    @Test
    public void testEnumJoin()
    {
        assertQueryResultUnordered(
                "  SELECT t1.a, t2.b " +
                        "FROM (VALUES test.enum.mood.happy, test.enum.mood.sad, test.enum.mood.mellow) t1(a) " +
                        "JOIN (VALUES (test.enum.mood.sad, 'hello'), (test.enum.mood.happy, 'world')) t2(a, b) " +
                        "ON t1.a = t2.a",
                ImmutableList.of(
                        ImmutableList.of(1L, "hello"),
                        ImmutableList.of(0L, "world")));
    }

    @Test
    public void testEnumWindow()
    {
        assertQueryResultUnordered(
                "  SELECT first_value(b) OVER (PARTITION BY a ORDER BY a) AS rnk " +
                        "FROM (VALUES (test.enum.mood.happy, 1), (test.enum.mood.happy, 3), (test.enum.mood.sad, 5)) t(a, b)",
                ImmutableList.of(singletonList(1), singletonList(1), singletonList(5)));
    }

    @Test
    public void testCastFunctionCaching()
    {
        assertSingleValue("CAST(' ' as test.enum.TestEnum)", " ");
        assertSingleValue("CAST(8 as test.enum.TestLongEnum)", 8L);
    }
}


text:
package revel

import (
	"fmt"
	stdlog "log"
	"runtime"
	"strings"

	"github.com/revel/revel"
	"gopkg.in/birkirb/loggers.v1"
	"gopkg.in/birkirb/loggers.v1/mappers"
)

// Logger is a Contextual logger wrapper over Revel's logger.
type Logger struct{}

// NewLogger returns a Contextual Logger for revel's internal logger.
// Note that Revel's loggers must be initialized before any logging can be made.
func NewLogger() loggers.Contextual {
	var l *Logger
	var a = mappers.NewContextualMap(l)
	a.Info("Now using Revel's logger package (via loggers/mappers/revel).")

	// Remove filename printing from revel logger.
	revel.TRACE.SetFlags(stdlog.Ldate | stdlog.Ltime)
	revel.INFO.SetFlags(stdlog.Ldate | stdlog.Ltime)
	revel.WARN.SetFlags(stdlog.Ldate | stdlog.Ltime)
	revel.ERROR.SetFlags(stdlog.Ldate | stdlog.Ltime)
	return a
}

// LevelPrint is a Mapper method
func (l *Logger) LevelPrint(lev mappers.Level, i ...interface{}) {
	i = append([]interface{}{caller(3) + " "}, i...)
	getRevelLevel(lev).Print(i...)
}

// LevelPrintf is a Mapper method
func (l *Logger) LevelPrintf(lev mappers.Level, format string, i ...interface{}) {
	getRevelLevel(lev).Printf(caller(3)+" "+format, i...)
}

// LevelPrintln is a Mapper method
func (l *Logger) LevelPrintln(lev mappers.Level, i ...interface{}) {
	i = append([]interface{}{caller(3)}, i...)
	getRevelLevel(lev).Println(i...)
}

// WithField returns an advanced logger with a pre-set field.
func (l *Logger) WithField(key string, value interface{}) loggers.Advanced {
	return l.WithFields(key, value)
}

// WithFields returns an advanced logger with pre-set fields.
func (l *Logger) WithFields(fields ...interface{}) loggers.Advanced {
	s := make([]string, len(fields)/2)
	for i := 0; i+1 < len(fields); i = i + 2 {
		key := fields[i]
		value := fields[i+1]
		s = append(s, fmt.Sprint(key, "=", value))
	}

	r := revelPostfixLogger{strings.Join(s, " ")}
	return mappers.NewAdvancedMap(&r)
}

type revelPostfixLogger struct {
	postfix string
}

func (r *revelPostfixLogger) LevelPrint(lev mappers.Level, i ...interface{}) {
	i = append(i, r.postfix)
	getRevelLevel(lev).Print(i...)
}

func (r *revelPostfixLogger) LevelPrintf(lev mappers.Level, format string, i ...interface{}) {
	if len(r.postfix) > 0 {
		format = format + " %s"
		i = append(i, r.postfix)
	}
	getRevelLevel(lev).Printf(format, i...)
}

func (r *revelPostfixLogger) LevelPrintln(lev mappers.Level, i ...interface{}) {
	i = append(i, r.postfix)
	getRevelLevel(lev).Println(i...)
}

func getRevelLevel(lev mappers.Level) loggers.Standard {
	switch lev {
	case mappers.LevelDebug:
		return revel.TRACE
	case mappers.LevelInfo:
		return revel.INFO
	case mappers.LevelWarn:
		return revel.WARN
	case mappers.LevelError:
		return revel.ERROR
	case mappers.LevelFatal:
		return revel.ERROR
	case mappers.LevelPanic:
		return revel.ERROR
	default:
		panic("unreachable")
	}
}

// shortenFile returns the folder and file name of an absolute file path.
func shortenFile(file string) string {
	short := file
	foundOne := false
	for i := len(file) - 1; i > 0; i-- {
		if file[i] == '/' {
			if !foundOne {
				foundOne = true
				continue
			}
			short = file[i+1:]
			break
		}
	}
	return short
}

// caller returns the funtion call line at the specified depth
// as "dir/file.go:n:
func caller(depth int) string {
	_, file, line, ok := runtime.Caller(depth + 1)
	if !ok {
		file = "???"
		line = 0
	}
	return fmt.Sprintf("%s:%d:", shortenFile(file), line)
}


text: Press button in shitty life situations. Built just before the NFL Super Bowl XLIX.


text:
import logging
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

from cache_service import CRMProjects, CRMProjectIam, ServiceAccountService, \
    ServiceAccountKeyService, BQDataset, BQDatasets, GCSBuckets, GCSBucketACL, \
    ServiceManagement

from oauth2client.client import GoogleCredentials

class GcpIamIterator:
    def __init__(self, use_cache=True):
        credentials = GoogleCredentials.get_application_default()
        google_crm_service = build('cloudresourcemanager', 'v1',
                                   credentials=credentials)
        google_iam_service = build('iam', 'v1', credentials=credentials)
        google_bq_service = build('bigquery', 'v2', credentials=credentials)
        google_gcs_service = build('storage', 'v1', credentials=credentials)
        google_service_management = build('servicemanagement', 'v1',
                                          credentials=credentials)
        self.crm_service = CRMProjects(google_crm_service, use_cache)
        self.crm_iam_service = CRMProjectIam(google_crm_service, use_cache)
        self.sa_service = ServiceAccountService(google_iam_service, use_cache)
        self.sak_service = ServiceAccountKeyService(google_iam_service,
                                                    use_cache)
        self.datasets_service = BQDatasets(google_bq_service, use_cache)
        self.dataset_iam_service = BQDataset(google_bq_service, use_cache)
        self.gcs_service = GCSBuckets(google_gcs_service, use_cache)
        self.gcs_acl_service = GCSBucketACL(google_gcs_service, use_cache)
        self.service_management = ServiceManagement(google_service_management,
                                                    use_cache)

    def list_projects(self):
        response = self.crm_service.get()

        while response:
            for project in response['projects']:
                yield project

            if 'nextPageToken' in response:
                response = self.crm_service.get(
                    nextPageToken=response['nextPageToken'])
            else:
                response = None

    def list_project_iam(self, project_id):
        try:
            iam_policy = self.crm_iam_service.get(project_id=project_id)
        except HttpError as e:
            if e.resp.status == 403:
                logging.warning("403 received for project_id: {0}, content: {1}"
                                .format(project_id, e.content))
                return
            else:
                raise e

        if 'bindings' in iam_policy:
            for binding in iam_policy['bindings']:
                yield binding

    def list_service_accounts(self, project_id):
        try:
            response = self.sa_service.get(project_id=project_id)
        except HttpError as e:
            if e.resp.status == 404:
                logging.info("404 received for project_id: {0}, content: {1}"
                             .format(project_id, e.content))
                return
            elif e.resp.status == 403:
                logging.warning("403 received for project_id: {0}, content: {1}"
                                .format(project_id, e.content))
                return
            else:
                raise e

        while response:
            for account in response['accounts']:
                yield account

            if 'nextPageToken' in response:
                response = self.sa_service \
                    .get(project_id=project_id,
                         nextPageToken=response['nextPageToken'])
            else:
                response = None

    def list_service_account_keys(self, email):
        response = self.sak_service.get(email=email)

        if 'keys' in response:
            for key in response['keys']:
                yield key

    def list_datasets(self, project_id):
        response = None
        try:
            response = self.datasets_service.get(project_id=project_id)
        except HttpError as e:
            if e.resp.status == 400:
                logging.warning("400 received for project_id: {0}, content: {1}"
                                .format(project_id, e.content))
                return

        while response:
            if 'datasets' in response:
                for dataset in response['datasets']:
                    yield dataset

            if 'nextPageToken' in response:
                response = self.datasets_service.get(project_id=project_id,
                                                     pageToken=response[
                                                         'nextPageToken'])
            else:
                response = None

    def list_dataset_access(self, project_id, dataset_id):
        response = self.dataset_iam_service.get(project_id=project_id,
                                                dataset_id=dataset_id)
        if 'access' in response:
            for access in response['access']:
                yield access

    def list_buckets(self, project_id):
        try:
            response = self.gcs_service.get(project_id=project_id)
        except HttpError as e:
            if e.resp.status == 400:
                logging.warning(
                    "400 received during listing buckets for project_id: {0}, "
                    "content: {1}".format(project_id, e.content))
                return
            elif e.resp.status == 403:
                logging.warning(
                    "403 received during listing buckets for project_id: {0}, "
                    "content: {1}".format(project_id, e.content))
                return
            else:
                raise e

        while response:
            if 'items' in response:
                for bucket in response['items']:
                    yield bucket

            if 'nextPageToken' in response:
                response = self.gcs_service.get(project_id=project_id,
                                                pageToken=response[
                                                    'nextPageToken'])
            else:
                response = None

    def list_bucket_access(self, bucket_id):
        try:
            response = self.gcs_acl_service.get(bucket_id=bucket_id)
        except HttpError as e:
            if e.resp.status == 403:
                logging.warning("403 received for bucket_id: {0}, content: {1}"
                                .format(bucket_id, e.content))
                return
            else:
                raise e

        for item in response['items']:
            yield item

    def list_enabled_services(self, project_id):
        try:
            response = self.service_management.get(project_id=project_id)
        except HttpError as e:
            if e.resp.status == 400 or e.resp.status == 403 \
                    or e.resp.status == 404:
                logging.warning(
                    "{0} received during listing services for project_id: {1}, "
                    "content: {2}".format(e.resp.status, project_id, e.content))
                return
            else:
                raise e

        while response:
            if 'services' in response:
                for service in response['services']:
                    yield service

            if 'nextPageToken' in response:
                response = self.service_management.get(project_id=project_id,
                                                       pageToken=response[
                                                           'nextPageToken'])
            else:
                response = None


text:
package com.tonybeltramelli.lab;

import com.tonybeltramelli.lab.brain.Brain;
import com.tonybeltramelli.lab.config.Config;
import com.tonybeltramelli.lab.data.DataManager;
import com.tonybeltramelli.lab.display.Display;
import javafx.stage.Stage;

/**
 * @author Tony Beltramelli www.tonybeltramelli.com - created 27/04/2014
 */
public class Controller
{
    private Display _display;
    private Brain _brain;
    private DataManager _dataManager;
    //
    private int _individualCounter = 0;

    public Controller(Stage stage)
    {
        super();

        _display = new Display(this, stage);

        _dataManager = new DataManager();

        _brain = new Brain();

        _createIndividual();
    }

    public void _createIndividual()
    {
        _individualCounter++;

        _display.build(_brain);
        _display.setProgress("organism : " + _individualCounter + " / " + Config.populationSize + ", generation : " + _dataManager.getGenerationNumber() + " / " + Config.generationNumber);
    }

    public void saveFitnessScore(int fitnessScore)
    {
        _dataManager.save(fitnessScore, _brain.getEncoding());

        if(_individualCounter < Config.populationSize)
        {
            _brain.mutate();

            _createIndividual();
        } else
        {
            _individualCounter = 0;

            if(_dataManager.getGenerationNumber() < Config.generationNumber)
            {
                if(Config.reproductionStrategy == Config.ReproductionStrategy.ASEXUAL)
                {
                    _brain.generate(_dataManager.getBestDna());
                } else if(Config.reproductionStrategy == Config.ReproductionStrategy.SEXUAL)
                {
                    _brain.mate(_dataManager.getBestDna(), _dataManager.getSecondBestDna());
                }

                _dataManager.nextGeneration();

                _createIndividual();
            } else
            {
                _dataManager.print();

                System.exit(0);
            }
        }
    }
}


text:
namespace Proactima.AzureWorkers
{
    public interface IStartupTask
    {
        void Start();
    }
}


text:
{-# LANGUAGE RankNTypes, RecordWildCards #-}

-- |
-- Module      : Network.Wreq.Session
-- Copyright   : (c) 2014 Bryan O'Sullivan
--
-- License     : BSD-style
-- Maintainer  : bos@serpentine.com
-- Stability   : experimental
-- Portability : GHC
--
-- The functions in this module use a 'Session' to handle the
-- following common needs:
--
-- * TCP connection reuse.  This is important for performance when
--   multiple requests go to a single server, particularly if TLS is
--   being used.
--
-- * Transparent cookie management.  Any cookies set by the server
--   persist from one request to the next.  (Bypass this overhead
--   using 'newAPISession'.)
--
--
-- This module is designed to be used alongside the "Network.Wreq"
-- module.  Typical usage will look like this:
--
-- @
-- import "Network.Wreq"
-- import qualified "Network.Wreq.Session" as Sess
--
-- main = do
--   sess <- Sess.'newSession'
--   Sess.'get' sess \"http:\/\/httpbin.org\/get\"
-- @
--
-- We create a 'Session' using 'newSession', then pass the session to
-- subsequent functions.  When talking to a REST-like service that does
-- not use cookies, it is more efficient to use 'newAPISession'.
--
-- Note the use of qualified import statements in the examples above,
-- so that we can refer unambiguously to the 'Session'-specific
-- implementation of HTTP GET.
--
-- One 'Network.HTTP.Client.Manager' (possibly set with 'newSessionControl') is used for all
-- session requests. The manager settings in the 'Options' parameter
-- for the 'getWith', 'postWith' and similar functions is ignored.

module Network.Wreq.Session
    (
    -- * Session creation
      Session
    , newSession
    , newAPISession
    , withSession
    , withAPISession
    -- ** More control-oriented session creation
    , newSessionControl
    , withSessionWith
    , withSessionControl
    -- ** Get information about session state
    , getSessionCookieJar
    -- * HTTP verbs
    , get
    , post
    , head_
    , options
    , put
    , delete
    , customMethod
    -- ** Configurable verbs
    , getWith
    , postWith
    , headWith
    , optionsWith
    , putWith
    , deleteWith
    , customMethodWith
    , customPayloadMethodWith
    , customHistoriedMethodWith
    , customHistoriedPayloadMethodWith
    -- * Extending a session
    , Lens.seshRun
    ) where

import Control.Lens ((&), (.~))
import Data.Foldable (forM_)
import Data.IORef (newIORef, readIORef, writeIORef)
import Network.Wreq (Options, Response, HistoriedResponse)
import Network.Wreq.Internal
import Network.Wreq.Internal.Types (Body(..), Req(..), Session(..), RunHistory)
import Network.Wreq.Types (Postable, Putable, Run)
import Prelude hiding (head)
import qualified Data.ByteString.Char8 as BC8
import qualified Data.ByteString.Lazy as L
import qualified Network.HTTP.Client as HTTP
import qualified Network.Wreq.Internal.Lens as Lens
import qualified Network.Wreq.Lens as Lens
import Data.Traversable as T

-- | Create a 'Session', passing it to the given function.  The
-- 'Session' will no longer be valid after that function returns.
--
-- This session manages cookies and uses default session manager
-- configuration.
withSession :: (Session -> IO a) -> IO a
withSession act = newSession >>= act
{-# DEPRECATED withSession "Use newSession instead." #-}

-- | Create a 'Session'.
--
-- This session manages cookies and uses default session manager
-- configuration.
--
-- @since 0.5.2.0
newSession :: IO Session
newSession = newSessionControl (Just (HTTP.createCookieJar [])) defaultManagerSettings

-- | Create a session.
--
-- This uses the default session manager settings, but does not manage
-- cookies.  It is intended for use with REST-like HTTP-based APIs,
-- which typically do not use cookies.
withAPISession :: (Session -> IO a) -> IO a
withAPISession act = newAPISession >>= act
{-# DEPRECATED withAPISession "Use newAPISession instead." #-}

-- | Create a session.
--
-- This uses the default session manager settings, but does not manage
-- cookies.  It is intended for use with REST-like HTTP-based APIs,
-- which typically do not use cookies.
--
-- @since 0.5.2.0
newAPISession :: IO Session
newAPISession = newSessionControl Nothing defaultManagerSettings

-- | Create a session, using the given manager settings.  This session
-- manages cookies.
withSessionWith :: HTTP.ManagerSettings -> (Session -> IO a) -> IO a
withSessionWith = withSessionControl (Just (HTTP.createCookieJar []))
{-# DEPRECATED withSessionWith "Use newSessionControl instead." #-}

-- | Create a session, using the given cookie jar and manager settings.
withSessionControl :: Maybe HTTP.CookieJar
                  -- ^ If 'Nothing' is specified, no cookie management
                  -- will be performed.
               -> HTTP.ManagerSettings
               -> (Session -> IO a) -> IO a
withSessionControl mj settings act = do
    sess <- newSessionControl mj settings
    act sess
{-# DEPRECATED withSessionControl "Use newSessionControl instead." #-}

-- | Create a session, using the given cookie jar and manager settings.
--
-- @since 0.5.2.0
newSessionControl ::  Maybe HTTP.CookieJar
                  -- ^ If 'Nothing' is specified, no cookie management
                  -- will be performed.
               -> HTTP.ManagerSettings
               -> IO Session
newSessionControl mj settings = do
     mref <- maybe (return Nothing) (fmap Just . newIORef) mj
     mgr <- HTTP.newManager settings
     return Session { seshCookies = mref
                     , seshManager = mgr
                     , seshRun = runWith
                     , seshRunHistory = runWithHistory
                     }

-- | Extract current 'Network.HTTP.Client.CookieJar' from a 'Session'
--
-- @since 0.5.2.0
getSessionCookieJar :: Session -> IO (Maybe HTTP.CookieJar)
getSessionCookieJar = T.traverse readIORef . seshCookies

-- | 'Session'-specific version of 'Network.Wreq.get'.
get :: Session -> String -> IO (Response L.ByteString)
get = getWith defaults

-- | 'Session'-specific version of 'Network.Wreq.post'.
post :: Postable a => Session -> String -> a -> IO (Response L.ByteString)
post = postWith defaults

-- | 'Session'-specific version of 'Network.Wreq.head_'.
head_ :: Session -> String -> IO (Response ())
head_ = headWith (defaults & Lens.redirects .~ 0)

-- | 'Session'-specific version of 'Network.Wreq.options'.
options :: Session -> String -> IO (Response ())
options = optionsWith defaults

-- | 'Session'-specific version of 'Network.Wreq.put'.
put :: Putable a => Session -> String -> a -> IO (Response L.ByteString)
put = putWith defaults

-- | 'Session'-specific version of 'Network.Wreq.delete'.
delete :: Session -> String -> IO (Response L.ByteString)
delete = deleteWith defaults

-- | 'Session'-specific version of 'Network.Wreq.customMethod'.
customMethod :: String -> Session -> String -> IO (Response L.ByteString)
customMethod = flip customMethodWith defaults

-- | 'Session'-specific version of 'Network.Wreq.getWith'.
getWith :: Options -> Session -> String -> IO (Response L.ByteString)
getWith opts sesh url = run string sesh =<< prepareGet opts url

-- | 'Session'-specific version of 'Network.Wreq.postWith'.
postWith :: Postable a => Options -> Session -> String -> a
         -> IO (Response L.ByteString)
postWith opts sesh url payload =
  run string sesh =<< preparePost opts url payload

-- | 'Session'-specific version of 'Network.Wreq.headWith'.
headWith :: Options -> Session -> String -> IO (Response ())
headWith opts sesh url = run ignore sesh =<< prepareHead opts url

-- | 'Session'-specific version of 'Network.Wreq.optionsWith'.
optionsWith :: Options -> Session -> String -> IO (Response ())
optionsWith opts sesh url = run ignore sesh =<< prepareOptions opts url

-- | 'Session'-specific version of 'Network.Wreq.putWith'.
putWith :: Putable a => Options -> Session -> String -> a
        -> IO (Response L.ByteString)
putWith opts sesh url payload = run string sesh =<< preparePut opts url payload

-- | 'Session'-specific version of 'Network.Wreq.deleteWith'.
deleteWith :: Options -> Session -> String -> IO (Response L.ByteString)
deleteWith opts sesh url = run string sesh =<< prepareDelete opts url

-- | 'Session'-specific version of 'Network.Wreq.customMethodWith'.
customMethodWith :: String -> Options -> Session -> String -> IO (Response L.ByteString)
customMethodWith method opts sesh url = run string sesh =<< prepareMethod methodBS opts url
  where
    methodBS = BC8.pack method

-- | 'Session'-specific version of 'Network.Wreq.customHistoriedMethodWith'.
--
-- @since 0.5.2.0
customHistoriedMethodWith :: String -> Options -> Session -> String -> IO (HistoriedResponse L.ByteString)
customHistoriedMethodWith method opts sesh url =
    runHistory stringHistory sesh =<< prepareMethod methodBS opts url
  where
    methodBS = BC8.pack method

-- | 'Session'-specific version of 'Network.Wreq.customPayloadMethodWith'.
customPayloadMethodWith :: Postable a => String -> Options -> Session -> String -> a
                        -> IO (Response L.ByteString)
customPayloadMethodWith method opts sesh url payload =
  run string sesh =<< preparePayloadMethod methodBS opts url payload
  where
    methodBS = BC8.pack method

-- | 'Session'-specific version of 'Network.Wreq.customHistoriedPayloadMethodWith'.
--
-- @since 0.5.2.0
customHistoriedPayloadMethodWith :: Postable a => String -> Options -> Session -> String -> a
                        -> IO (HistoriedResponse L.ByteString)
customHistoriedPayloadMethodWith method opts sesh url payload =
  runHistory stringHistory sesh =<< preparePayloadMethod methodBS opts url payload
  where
    methodBS = BC8.pack method

runWithGeneric :: (resp -> Response b) -> Session -> (Req -> IO resp) -> Req -> IO resp
runWithGeneric extract Session{..} act (Req _ req) = do
  req' <- (\c -> req & Lens.cookieJar .~ c) `fmap` T.traverse readIORef seshCookies
  resp <- act (Req (Right seshManager) req')
  forM_ seshCookies $ \ref ->
    writeIORef ref (HTTP.responseCookieJar (extract resp))
  return resp

runWith :: Session -> Run Body -> Run Body
runWith = runWithGeneric id

runWithHistory :: Session -> RunHistory Body -> RunHistory Body
runWithHistory = runWithGeneric HTTP.hrFinalResponse

type Mapping a = (Body -> a, a -> Body, Run a)
type MappingHistory a = (Body -> a, a -> Body, RunHistory a)

run :: Mapping a -> Session -> Run a
run (to,from,act) sesh =
  fmap (fmap to) . seshRun sesh sesh (fmap (fmap from) . act)

runHistory :: MappingHistory a -> Session -> RunHistory a
runHistory (to,from,act) sesh =
  fmap (fmap to) . seshRunHistory sesh sesh (fmap (fmap from) . act)

string :: Mapping L.ByteString
string = (\(StringBody s) -> s, StringBody, runRead)

stringHistory :: MappingHistory L.ByteString
stringHistory = (\(StringBody s) -> s, StringBody, runReadHistory)

ignore :: Mapping ()
ignore = (const (), const NoBody, runIgnore)


text:
# PostCSS Prefixer font-face

[PostCSS] plugin to prefix font-faces.

[PostCSS]: https://github.com/postcss/postcss

```css
/* Input example */

@font-face {
  font-family: MyWebFont;
}

div {
  width: 100px;
  background: red;
  position: relative;
  font-family: Arial;
}

a {
  color: green;
  position: relative;
  font-family: MyWebFont;
}

```

```css
/* Output example */

@font-face {
    font-family: myWebsite-MyWebFont;
}

div {
    width: 100px;
    background: red;
    position: relative;
    font-family: Arial;
}

a {
    color: green;
    position: relative;
    font-family: myWebsite-MyWebFont;
}
```

## Usage

```js
var prefix = require('postcss-prefixer-font-face');
postcss([ prefix({prefix: 'myWebsite-'}) ])
```

See [PostCSS] docs for examples for your environment.


text:
public class StringtoInteger {
    public static int myAtoi(String str) {
        int len = str == null ? 0 : str.length();
        if (len == 0) return 0;
        int sign = 1, i = 0;
        char c = ' ';
        Long ret = 0l;
        // skip the blank characters
        while (i < len && Character.isWhitespace(c = str.charAt(i)))
            i++;
        sign = c == '-' ? -1 : 1;
        i = Character.isDigit(c) ? i : i + 1;
        // skip the blank characters between the sign and the digits
        while (i < len && Character.isWhitespace(c = str.charAt(i)))
            i++;
        while (i < len && Character.isDigit(c = str.charAt(i))) {
            ret  = ret * 10 + c - '0';
            i++;
        }
        ret *= sign;
        if (ret > Integer.MAX_VALUE) return Integer.MAX_VALUE;
        else if (ret < Integer.MIN_VALUE) return Integer.MIN_VALUE;
        else return new Long(ret).intValue();
    }

    public static void main(String[] args) {
        System.out.println(myAtoi("    + 123   "));
        System.out.println(myAtoi(" - 12300 "));
    }

}


text:
package org.apache.camel.component.xmpp.integration;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.camel.builder.RouteBuilder;
import org.junit.jupiter.api.Test;

import static org.apache.camel.test.junit5.TestSupport.body;

public class XmppProducerConcurrentIT extends XmppBaseIT {

    @Test
    public void testNoConcurrentProducers() throws Exception {
        doSendMessages(1, 1);
    }

    @Test
    public void testConcurrentProducers() throws Exception {
        doSendMessages(10, 5);
    }

    private void doSendMessages(int files, int poolSize) throws Exception {
        getMockEndpoint("mock:result").expectedMessageCount(files);
        getMockEndpoint("mock:result").assertNoDuplicates(body());

        ExecutorService executor = Executors.newFixedThreadPool(poolSize);
        for (int i = 0; i < files; i++) {
            final int index = i;
            executor.submit(() -> template.sendBody("direct:start", "Hello " + index));
        }

        assertMockEndpointsSatisfied();
        executor.shutdownNow();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start")
                        .to("xmpp://" + getUrl()
                            + "?connectionConfig=#customConnectionConfig&room=camel-test&user=camel_consumer&password=secret&serviceName=apache.camel")
                        .to("mock:result");
            }
        };
    }
}


text:
<?php

namespace Tapestry\Plates\Extensions;

use League\Plates\Engine;
use Tapestry\Entities\Configuration;
use League\Plates\Extension\ExtensionInterface;

class Site implements ExtensionInterface
{
    /**
     * @var Configuration
     */
    private $configuration;

    /**
     * Site constructor.
     *
     * @param Configuration $configuration
     */
    public function __construct(Configuration $configuration)
    {
        $this->configuration = $configuration;
    }

    public function register(Engine $engine)
    {
        $engine->registerFunction('site', [$this, 'site']);
    }

    public function site($key, $default = null)
    {
        $key = 'site.'.$key;
        if ($value = $this->configuration->get($key, $default)) {
            return $value;
        }

        return $default;
    }
}


text:
from collections import defaultdict
from matplotlib.font_manager import FontProperties
from matplotlib.table import Table as mpl_Table

import param

from .element import ElementPlot
from ...core.util import safe_unicode

class TablePlot(ElementPlot):
    """
    A TablePlot can plot both TableViews and ViewMaps which display
    as either a single static table or as an animated table
    respectively.
    """

    border = param.Number(default=0.05, bounds=(0.0, 0.5), doc="""
        The fraction of the plot that should be empty around the
        edges.""")

    float_precision = param.Integer(default=3, doc="""
        The floating point precision to use when printing float
        numeric data types.""")

    max_value_len = param.Integer(default=20, doc="""
        The maximum allowable string length of a value shown in any
        table cell. Any strings longer than this length will be
        truncated.""")

    max_font_size = param.Integer(default=12, doc="""
        The largest allowable font size for the text in each table
        cell.""")

    max_rows = param.Integer(default=15, doc="""
        The maximum number of Table rows before the table is
        summarized.""")

    font_types = param.Dict(default={'heading': FontProperties(weight='bold',
                                                               family='DejaVu Sans')},
       doc="""The font style used for heading labels used for emphasis.""")

    style_opts = ['alpha', 'sketch_params']

    # Disable axes handling for Table plots
    _has_axes = False

    def __init__(self, table, **params):
        super(TablePlot, self).__init__(table, **params)
        self.cell_values, self.cell_widths = self._format_table()

    def _format_table(self):
        cell_values = defaultdict(dict)
        cell_widths = defaultdict(int)
        for key in self.keys:
            frame = self._get_frame(key)
            if frame is None:
                continue

            # Mapping from the cell coordinates to the dictionary key.
            summarize = frame.rows > self.max_rows
            half_rows = self.max_rows//2
            rows = min([self.max_rows, frame.rows])
            for row in range(rows):
                adjusted_row = row
                for col in range(frame.cols):
                    if summarize and row == half_rows:
                        cell_text = "..."
                    else:
                        if summarize and row > half_rows:
                            adjusted_row = (frame.rows - self.max_rows + row)
                        value = frame.pprint_cell(adjusted_row, col)
                        cell_text = self.pprint_value(value)
                    cell_values[key][(row, col)] = cell_text
                    if len(cell_text) + 2 > cell_widths[col]:
                        cell_widths[col] = len(cell_text) + 2
        return cell_values, cell_widths

    def pprint_value(self, value):
        """
        Generate the pretty printed representation of a value for
        inclusion in a table cell.
        """
        if isinstance(value, float):
            formatter = '{:.%df}' % self.float_precision
            formatted = formatter.format(value)
        elif isinstance(value, str):
            formatted = safe_unicode(value)
        else:
            formatted = str(value)

        if len(formatted) > self.max_value_len:
            return formatted[:(self.max_value_len-3)]+'...'
        else:
            return formatted

    def initialize_plot(self, ranges=None):
        element = self.hmap.last
        axis = self.handles['axis']

        axis.set_axis_off()
        size_factor = (1.0 - 2*self.border)
        table = mpl_Table(axis, bbox=[self.border, self.border,
                                      size_factor, size_factor])
        total_width = sum(self.cell_widths.values())
        height = size_factor / element.rows

        summarize = element.rows > self.max_rows
        half_rows = self.max_rows/2
        rows = min([self.max_rows, element.rows])
        for row in range(rows):
            adjusted_row = row
            for col in range(element.cols):
                if summarize and row > half_rows:
                    adjusted_row = (element.rows - self.max_rows + row)
                cell_value = self.cell_values[self.keys[-1]][(row, col)]
                cellfont = self.font_types.get(element.cell_type(adjusted_row,col), None)
                width = self.cell_widths[col] / float(total_width)
                font_kwargs = dict(fontproperties=cellfont) if cellfont else {}
                table.add_cell(row, col, width, height, text=cell_value,  loc='center',
                               **font_kwargs)

        table.set_fontsize(self.max_font_size)
        table.auto_set_font_size(True)
        axis.add_table(table)

        self.handles['artist'] = table

        return self._finalize_axis(self.keys[-1])

    def update_handles(self, key, axis, view, ranges, style):
        table = self.handles['artist']

        for coords, cell in table.get_celld().items():
            value = self.cell_values[key][coords]
            cell.set_text_props(text=value)

        # Resize fonts across table as necessary
        table.set_fontsize(self.max_font_size)
        table.auto_set_font_size(True)


text:
package util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.json.JSONObject;

import model.City;
import model.County;
import model.Province;
import db.CoolWeatherDB;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import android.text.TextUtils;

public class ParseUtil {

	/*
	 * ½âÎö¸÷Ê¡ÊÐÏØ·µ»ØµÄ×Ö·û´®
	 */
	public synchronized static boolean handleProvinceResponse(CoolWeatherDB db, String response) {
		if (!TextUtils.isEmpty(response)) {
			String [] allProvinces = response.split(",");
			if (allProvinces != null && allProvinces.length > 0) {
				for (String p : allProvinces) {
					String [] arr = p.split("\\|");
					Province province = new Province();
					province.setProvinceCode(arr[0]);
					province.setProvinceName(arr[1]);
					db.saveProvince(province);
				}
			}
			return true;

		}
		return false;
	}
	public synchronized static boolean handleCityResponse(CoolWeatherDB db, String response,int provinceId) {
		if (!TextUtils.isEmpty(response)) {
			String [] allCites = response.split(",");
			if (allCites != null && allCites.length > 0) {
				for (String c : allCites) {
					String [] arr = c.split("\\|");
					City city = new City();
					city.setCityCode(arr[0]);
					city.setCityName(arr[1]);
					city.setProvinceId(provinceId);
					db.saveCity(city);
				}
			}
			return true;
		}
		return false;
	}

	public synchronized static boolean handleCountyResponse(CoolWeatherDB db, String response ,int cityId) {
		if (!TextUtils.isEmpty(response)) {
			String [] allCounties = response.split(",");
			if (allCounties != null && allCounties.length > 0) {
				for (String c : allCounties) {
					String [] arr = c.split("\\|");
					County county = new County();
					county.setCountyCode(arr[0]);
					county.setCountyName(arr[1]);
					county.setCityId(cityId);
					db.saveCounty(county);
				}
				return true;
			}

		}
		return false;
	}
	/*
	 * ´¦ÀíÆøÏóÔ¤±¨Êý¾Ý·µ»ØµÄjson¸ñʽÊý¾Ý
	 */
	public static void handleWeatherResponse(String response, Context context) {
		try {
			JSONObject jsonObject = new JSONObject(response);
			JSONObject weatherInfo = jsonObject.getJSONObject("weatherinfo");
			String cityName = weatherInfo.getString("city");
			String weatherCode = weatherInfo.getString("cityid");
			String temp1 = weatherInfo.getString("temp1");
			String temp2 = weatherInfo.getString("temp2");
			String weatherDesp = weatherInfo.getString("weather");
			String publishTime = weatherInfo.getString("ptime");
			saveWeatherInfo(context, cityName, weatherCode, temp1, temp2,
					weatherDesp, publishTime);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void saveWeatherInfo(Context context, String cityName,
			String weatherCode, String temp1, String temp2, String weatherDesp,
			String publishTime) {
		SharedPreferences.Editor editor = (Editor) PreferenceManager
				.getDefaultSharedPreferences(context).edit();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/M/d",
				Locale.CHINA);
		editor.putBoolean("city_selected", true);
		editor.putString("city_name", cityName);
		editor.putString("weather_code", weatherCode);
		editor.putString("temp1", temp1);
		editor.putString("temp2", temp2);
		editor.putString("weather_desp", weatherDesp);
		editor.putString("publish_time", publishTime);
		editor.putString("current_date", sdf.format(new Date()));
		editor.commit();
	}
}


text:
class HomeController < ApplicationController
  caches_action :index, :unless => Proc.new { |c| c.logged_in? }

  # GET /index
  # GET /index.xml
  def index
    @featured_categories = Category.find( :all, :conditions => { :is_featured => true } )
    @featured_categories.delete_if {|x| !x.allowed_to_read} #Hide Private Featured Categories

    @categories = Category.roots
    @categories.delete_if {|x| !x.allowed_to_read} #Hide Private Root Categories

    respond_to do |format|
      format.html # index.html.erb
      format.rss
      format.xml  { render :xml => @categories }
    end
  end
end


text:
// $Id$

/// \ingroup evemacros
/// \file MUON_makeGeom.C
///
/// \author B. Vulpescu, LPC
#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TGeoManager.h>

#include <AliMpCDB.h>
#include <AliRun.h>
#endif

void MUON_makeGeom()
{
  AliMpCDB::LoadMpSegmentation2();
  gAlice->SetConfigFunction("$ALICE_ROOT/MUON/Config.C");
  //gAlice->Init("Config.C");

  gGeoManager->Export("geometry.root");

}


text:
<link href="../../../../../../../Mainpage/summaries_v3.css" rel="stylesheet" />
<title>Linear Summary with Context</title>

Loading...
The first figure following the title shows a panoramic view of the entire lecture board. The following note presents figures and transcript in the order they appear in the lecture. The RIGHT figure shows the line that is being discussed, and the LEFT figure shows that line in the context of the panorama.

Swapping the bounds for definite integral  (2)

We want to find the derivative with respect to x of all of this business right over here. And you might guess-- and this is definitely a function of x. x is one of the boundaries of integration for this definite integral.

And you might say, well, it looks like the fundamental theorem of calculus might apply, but I'm used to seeing the x, or the function x, as the upper bound, not as the lower bound. How do I deal with this? And the key realization is to realize what happens when you switch bounds for a definite integral. And I'll do a little bit of an aside to review that.

So if I'm taking the definite integral from a to b of f of t, dt, we know that this is capital F, the antiderivative of f, evaluated at b minus the antiderivative of F evaluated at a.

This is corollary to the fundamental theorem, or it's the fundamental theorem part two, or the second fundamental theorem of calculus. This is how we evaluate definite integrals. Now, let's think about what the negative of this is.

So the negative of that-- of a to b of f of t, dt, is just going to be equal to the negative of this, which is equal to-- so it's the negative of f of b minus f of a, which is equal to capital F of a minus capital F of b.

All I did is distribute the negative sign and then switch the two terms.

But this right over here is equal to the definite integral from, instead of a to b, but from b to a of f of t, dt.

So notice, when you put a negative, that's just like switching the signs or switching the boundaries. Or if you switch the boundaries, they are the negatives of each other. So we can go back to our original problem.

We can rewrite this as being equal to the derivative with respect to x of-- instead of this, it'll be the negative of the same definite integral but with the boundaries switched-- the negative of x with the upper boundary is x, the lower bound is 3 of the square root of the absolute value of cosine t, dt, which is equal to-- we can take the negative out front-- negative times the derivative with respect to x of all of this business. I should just copy and paste that, so I'll just copy and paste. Let me-- and paste it. So times the derivative with respect to x of all that, and now the fundamental theorem of calculus directly applies.

This is going to be equal to-- we deserve a drum roll now. This is going to be equal to the negative-- can't forget the negative. And the fundamental theorem of calculus tells us that that's just going to be this function as a function of x.

So it's going to be negative square root of the absolute value of cosine of not t anymore, but x.

And we are done.

 Loading...


text:
<?php

namespace app\commands;

#namespace yii\console\controllers;

use Yii;
use yii\console\Controller;
use yii\console\Exception;
use yii\helpers\Console;
use yii\helpers\FileHelper;
use yii\helpers\VarDumper;
use yii\i18n\GettextPoFile;
use yii\console\controllers\MessageController;
use Stichoza\Google\GoogleTranslate;

/**
 * This command echoes the first argument that you have entered.
 *
 * This command is provided as an example for you to learn how to create console commands.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class TranslateController extends MessageController
{
    /**
     * This command echoes what you have entered as the message.
     * @param string $message the message to be echoed.
     */
     public function actionIndex($message = 'hello {world} apple beta {gamma {horse, cat}} this {mysite} this is a draw {apple {beta,{cat,dog} dog} house} farm')
     {
       echo GoogleTranslate::staticTranslate('hello world', "en", "es"). "\n";
        $message='The image "{file}" is too large. The height cannot be larger than {limit, number} {limit, plural, one{pixel} other{pixels}}.';
        print_r($this->parse_safe_translate($message));
        /*
        $message='{nFormatted} {n, plural, =1{kibibyte} other{kibibytes}}';
       print_r($this->parse_safe_translate($message));
       $message='The "apple" {is} good.';
       print_r($this->parse_safe_translate($message));
       $message='The image "{file}" is too large. The height cannot be larger than {limit, number} {limit, plural, one{pixel} other{pixels}}.';
       print_r($this->parse_safe_translate($message));
       var_dump($this->parse_safe_translate('Are you sure you want to delete this item?'));
       var_dump($this->parse_safe_translate('Create {modelClass}'));
       */
     }

     /**
      * Extracts messages to be translated from source code.
      *
      * This command will search through source code files and extract
      * messages that need to be translated in different languages.
      *
      * @param string $configFile the path or alias of the configuration file.
      * You may use the "yii message/config" command to generate
      * this file and then customize it for your needs.
      * @throws Exception on failure.
      */
     public function actionGoogle_extract($configFile)
     {
         $configFile = Yii::getAlias($configFile);
         if (!is_file($configFile)) {
             throw new Exception("The configuration file does not exist: $configFile");
         }

         $config = array_merge([
             'translator' => 'Yii::t',
             'overwrite' => false,
             'removeUnused' => false,
             'sort' => false,
             'format' => 'php',
         ], require($configFile));

         if (!isset($config['sourcePath'], $config['languages'])) {
             throw new Exception('The configuration file must specify "sourcePath" and "languages".');
         }
         if (!is_dir($config['sourcePath'])) {
             throw new Exception("The source path {$config['sourcePath']} is not a valid directory.");
         }
         if (empty($config['format']) || !in_array($config['format'], ['php', 'po', 'db'])) {
             throw new Exception('Format should be either "php", "po" or "db".');
         }
         if (in_array($config['format'], ['php', 'po'])) {
             if (!isset($config['messagePath'])) {
                 throw new Exception('The configuration file must specify "messagePath".');
             } elseif (!is_dir($config['messagePath'])) {
                 throw new Exception("The message path {$config['messagePath']} is not a valid directory.");
             }
         }
         if (empty($config['languages'])) {
             throw new Exception("Languages cannot be empty.");
         }

         $files = FileHelper::findFiles(realpath($config['sourcePath']), $config);

         $messages = [];
         foreach ($files as $file) {
             $messages = array_merge_recursive($messages, $this->extractMessages($file, $config['translator']));
         }
         if (in_array($config['format'], ['php', 'po'])) {
             foreach ($config['languages'] as $language) {
                 $dir = $config['messagePath'] . DIRECTORY_SEPARATOR . $language;
                 if (!is_dir($dir)) {
                     @mkdir($dir);
                 }
                 if ($config['format'] === 'po') {
                     $catalog = isset($config['catalog']) ? $config['catalog'] : 'messages';
                     $this->saveMessagesToPO($messages, $dir, $config['overwrite'], $config['removeUnused'], $config['sort'], $catalog);
                 } else {
                     $this->saveMessagesToPHPEnhanced($messages, $dir, $config['overwrite'], $config['removeUnused'], $config['sort'],$language);
                 }
             }
         } elseif ($config['format'] === 'db') {
             $db = \Yii::$app->get(isset($config['db']) ? $config['db'] : 'db');
             if (!$db instanceof \yii\db\Connection) {
                 throw new Exception('The "db" option must refer to a valid database application component.');
             }
             $sourceMessageTable = isset($config['sourceMessageTable']) ? $config['sourceMessageTable'] : '{{%source_message}}';
             $messageTable = isset($config['messageTable']) ? $config['messageTable'] : '{{%message}}';
             $this->saveMessagesToDb(
                 $messages,
                 $db,
                 $sourceMessageTable,
                 $messageTable,
                 $config['removeUnused'],
                 $config['languages']
             );
         }
     }

     /**
      * Writes messages into PHP files
      *
      * @param array $messages
      * @param string $dirName name of the directory to write to
      * @param boolean $overwrite if existing file should be overwritten without backup
      * @param boolean $removeUnused if obsolete translations should be removed
      * @param boolean $sort if translations should be sorted
      */
     protected function saveMessagesToPHPEnhanced($messages, $dirName, $overwrite, $removeUnused, $sort,$language)
     {
         foreach ($messages as $category => $msgs) {
             $file = str_replace("\\", '/', "$dirName/$category.php");
             $path = dirname($file);
             FileHelper::createDirectory($path);
             $msgs = array_values(array_unique($msgs));
             $coloredFileName = Console::ansiFormat($file, [Console::FG_CYAN]);
             $this->stdout("Saving messages to $coloredFileName...\n");
             $this->saveMessagesCategoryToPHPEnhanced($msgs, $file, $overwrite, $removeUnused, $sort, $category,$language);
         }
     }

         /**
          * Writes category messages into PHP file
          *
          * @param array $messages
          * @param string $fileName name of the file to write to
          * @param boolean $overwrite if existing file should be overwritten without backup
          * @param boolean $removeUnused if obsolete translations should be removed
          * @param boolean $sort if translations should be sorted
          * @param boolean $language language to translate to
          * @param boolean $force google translate
          * @param string $category message category
          */
         protected function saveMessagesCategoryToPHPEnhanced($messages, $fileName, $overwrite, $removeUnused, $sort, $category,$language,$force=true)
         {
             if (is_file($fileName)) {
                 $existingMessages = require($fileName);
                 sort($messages);
                 ksort($existingMessages);
                 if (!$force) {
                   if (array_keys($existingMessages) == $messages) {
                       $this->stdout("Nothing new in \"$category\" category... Nothing to save.\n\n", Console::FG_GREEN);
                       return;
                   }
                 }
                 $merged = [];
                 $untranslated = [];
                 foreach ($messages as $message) {
                     if (array_key_exists($message, $existingMessages) && strlen($existingMessages[$message]) > 0) {
                         $merged[$message] = $existingMessages[$message];
                     } else {
                         $untranslated[] = $message;
                     }
                 }
                 ksort($merged);
                 sort($untranslated);
                 $todo = [];
                 foreach ($untranslated as $message) {
                     $todo[$message] = $this->getGoogleTranslation($message,$language);
                 }
                 ksort($existingMessages);
                 foreach ($existingMessages as $message => $translation) {
                     if (!isset($merged[$message]) && !isset($todo[$message]) && !$removeUnused) {
                         if (!empty($translation) && strncmp($translation, '@@', 2) === 0 && substr_compare($translation, '@@', -2, 2) === 0) {
                             $todo[$message] = $translation;
                         } else {
                             $todo[$message] = '@@' . $translation . '@@';
                         }
                     }
                 }

                 $merged = array_merge($todo, $merged);
                 if ($sort) {
                     ksort($merged);
                 }
                 if (false === $overwrite) {
                     $fileName .= '.merged';
                 }
                 $this->stdout("Translation merged.\n");
             } else {
                 $merged = [];
                 foreach ($messages as $message) {
                     $merged[$message] = '';
                 }
                 ksort($merged);
             }

             $array = VarDumper::export($merged);
             $content = <<<EOD
<?php
/**
* Message translations.
*
* This file is automatically generated by 'yii {$this->id}' command.
* It contains the localizable messages extracted from source code.
* You may modify this file by translating the extracted messages.
*
* Each array element represents the translation (value) of a message (key).
* If the value is empty, the message is considered as not translated.
* Messages that no longer need translation will have their translations
* enclosed between a pair of '@@' marks.
*
* Message string can be used with plural forms format. Check i18n section
* of the guide for details.
*
* NOTE: this file must be saved in UTF-8 encoding.
*/
return $array;
EOD;

             file_put_contents($fileName, $content);
             $this->stdout("Translation saved.\n\n", Console::FG_GREEN);
         }

         public function getGoogleTranslation($message,$language) {
           $arr_parts=$this->parse_safe_translate($message);
           $translation='';
           foreach ($arr_parts as $str) {
             if (!stristr($str,'{')) {
               if (strlen($translation)>0 and substr($translation,-1)=='}') $translation.=' ';
               $translation.=GoogleTranslate::staticTranslate($str, Yii::$app->language, $language);
             } else {
               // add space prefix unless it's first
               if (strlen($translation)>0)
                 $translation.=' '.$str;
                else
                  $translation.=$str;
             }
           }
           print_r($translation);
           return $translation;
         }
     /*
     * parses a string into an array
     * splitting by any curly bracket segments
     * including nested curly brackets
     */
     public function parse_safe_translate($s) {
       $debug = false;
       $result = array();
       $start=0;
       $nest =0;
       $ptr_first_curly=0;
       $total_len = strlen($s);
       for($i=0; $i<$total_len; $i++) {
          if ($s[$i]=='{') {
            // found left curly
            if ($nest==0) {
              // it was the first one, nothing is nested yet
              $ptr_first_curly=$i;
            }
            // increment nesting
            $nest+=1;
          } elseif ($s[$i]=='}')  {
            // found right curly
            // reduce nesting
            $nest-=1;
            if ($nest==0) {
              // end of nesting
              if ($ptr_first_curly-$start>=0) {
                // push string leading up to first left curly
                $prefix = substr ( $s ,  $start , $ptr_first_curly-$start);
                if (strlen($prefix)>0) {
                  array_push($result,$prefix);
                }
              }
              // push (possibly nested) curly string
              $suffix=substr ( $s ,  $ptr_first_curly , $i-$ptr_first_curly+1);
              if (strlen($suffix)>0) {
                array_push($result,$suffix);
              }
              if ($debug) {
                echo '|'.substr ( $s ,  $start , $ptr_first_curly-$start-1)."|\n";
                echo '|'.substr ( $s ,  $ptr_first_curly , $i-$ptr_first_curly+1)."|\n";
              }
              $start=$i+1;
              $ptr_first_curly=0;
              if ($debug) {
                echo 'next start: '.$start."\n";
              }
            }
          }
       }
       $suffix = substr ( $s ,  $start , $total_len-$start);
       if ($debug) {
         echo 'Start:'.$start."\n";
         echo 'Pfc:'.$ptr_first_curly."\n";
         echo $suffix."\n";
       }
       if (strlen($suffix)>0) {
         array_push($result,substr ( $s ,  $start , $total_len-$start));
       }
       return $result;
     }

}


text:
<!DOCTYPE HTML>

<meta charset="UTF-8"/>
<title>Barcode Scanner Help</title>
<link rel="stylesheet" href="../style.css" type="text/css"/>

Barcode Scanner 4.5.2

The official Android app of the open source ZXing project:

http://code.google.com/p/zxing

Barcode Scanner uses the camera on your phone to read barcodes and look up product information such as prices and reviews.

It also reads 2D barcodes such as QR Codes and Data Matrix. These can contain links to web sites, contact information such as phone numbers and email addresses, and more.

What's new in this version

How to scan

About 1D barcodes

About 2D barcodes

How to create QR Codes

Privacy Policy, Legal and License Information


text:
<?php
define("APPLICATION_PATH", dirname(dirname(__FILE__)));

include_once(APPLICATION_PATH."/config/config.inc.php");
$oTemplate = new GS_Template();
if(!empty($_REQUEST["url"])){
    $ch = curl_init(); //初始化CURL句柄
    curl_setopt($ch, CURLOPT_URL, $_REQUEST["url"]); //设置请求的URL
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //设为TRUE把curl_exec()结果转化为字串,而不是直接输出
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); // 设置超时限制防止死循环
    curl_setopt($ch, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-HTTP-Method-Override: $method")); //设置HTTP头信息
    $document = curl_exec($ch); //执行预定义的CURL
    if (!curl_errno($ch)) {
        $info = curl_getinfo($ch);
            //	echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url'];
    } else {
        echo 'Curl error: ' . curl_error($ch);
    }
    curl_close($ch);
    $oTemplate->assign("sInputUrl", $_REQUEST["url"])->assign("sInputContents",$document)->display("se.tpl");
}else{
    $oTemplate->assign("sInputUrl", "")->assign("sInputContents","")->display("se.tpl");
}