text:
using namespace gl;

namespace rx
{

namespace
{

// This class needs to match OutputHLSL::decorate
class DecorateVariable final : angle::NonCopyable
{
  public:
    explicit DecorateVariable(const std::string &str) : mName(str) {}
    const std::string &getName() const { return mName; }

  private:
    const std::string &mName;
};

std::ostream &operator<<(std::ostream &o, const DecorateVariable &dv)
{
    if (dv.getName().compare(0, 3, "gl_") != 0)
    {
        o << "_";
    }
    o << dv.getName();
    return o;
}

const char *HLSLComponentTypeString(GLenum componentType)
{
    switch (componentType)
    {
        case GL_UNSIGNED_INT:
            return "uint";
        case GL_INT:
            return "int";
        case GL_UNSIGNED_NORMALIZED:
        case GL_SIGNED_NORMALIZED:
        case GL_FLOAT:
            return "float";
        default:
            UNREACHABLE();
            return "not-component-type";
    }
}

void HLSLComponentTypeString(std::ostringstream &ostream, GLenum componentType, int componentCount)
{
    ostream << HLSLComponentTypeString(componentType);
    if (componentCount > 1)
    {
        ostream << componentCount;
    }
}

const char *HLSLMatrixTypeString(GLenum type)
{
    switch (type)
    {
        case GL_FLOAT_MAT2:
            return "float2x2";
        case GL_FLOAT_MAT3:
            return "float3x3";
        case GL_FLOAT_MAT4:
            return "float4x4";
        case GL_FLOAT_MAT2x3:
            return "float2x3";
        case GL_FLOAT_MAT3x2:
            return "float3x2";
        case GL_FLOAT_MAT2x4:
            return "float2x4";
        case GL_FLOAT_MAT4x2:
            return "float4x2";
        case GL_FLOAT_MAT3x4:
            return "float3x4";
        case GL_FLOAT_MAT4x3:
            return "float4x3";
        default:
            UNREACHABLE();
            return "not-matrix-type";
    }
}

void HLSLTypeString(std::ostringstream &ostream, GLenum type)
{
    if (gl::IsMatrixType(type))
    {
        ostream << HLSLMatrixTypeString(type);
        return;
    }

    HLSLComponentTypeString(ostream, gl::VariableComponentType(type),
                            gl::VariableComponentCount(type));
}

const PixelShaderOutputVariable *FindOutputAtLocation(
    const std::vector<PixelShaderOutputVariable> &outputVariables,
    unsigned int location)
{
    for (size_t variableIndex = 0; variableIndex < outputVariables.size(); ++variableIndex)
    {
        if (outputVariables[variableIndex].outputIndex == location)
        {
            return &outputVariables[variableIndex];
        }
    }

    return nullptr;
}

void WriteArrayString(std::ostringstream &strstr, unsigned int i)
{
    static_assert(GL_INVALID_INDEX == UINT_MAX,
                  "GL_INVALID_INDEX must be equal to the max unsigned int.");
    if (i == UINT_MAX)
    {
        return;
    }

    strstr << "[";
    strstr << i;
    strstr << "]";
}

constexpr const char *VERTEX_ATTRIBUTE_STUB_STRING = "@@ VERTEX ATTRIBUTES @@";
constexpr const char *PIXEL_OUTPUT_STUB_STRING     = "@@ PIXEL OUTPUT @@";
}  // anonymous namespace

// DynamicHLSL implementation

DynamicHLSL::DynamicHLSL(RendererD3D *const renderer) : mRenderer(renderer)
{
}

std::string DynamicHLSL::generateVertexShaderForInputLayout(
    const std::string &sourceShader,
    const InputLayout &inputLayout,
    const std::vector<sh::Attribute> &shaderAttributes) const
{
    std::ostringstream structStream;
    std::ostringstream initStream;

    structStream << "struct VS_INPUT\n"
                 << "{\n";

    int semanticIndex       = 0;
    unsigned int inputIndex = 0;

    // If gl_PointSize is used in the shader then pointsprites rendering is expected.
    // If the renderer does not support Geometry shaders then Instanced PointSprite emulation
    // must be used.
    bool usesPointSize = sourceShader.find("GL_USES_POINT_SIZE") != std::string::npos;
    bool useInstancedPointSpriteEmulation =
        usesPointSize && mRenderer->getWorkarounds().useInstancedPointSpriteEmulation;

    // Instanced PointSprite emulation requires additional entries in the
    // VS_INPUT structure to support the vertices that make up the quad vertices.
    // These values must be in sync with the cooresponding values added during inputlayout creation
    // in InputLayoutCache::applyVertexBuffers().
    //
    // The additional entries must appear first in the VS_INPUT layout because
    // Windows Phone 8 era devices require per vertex data to physically come
    // before per instance data in the shader.
    if (useInstancedPointSpriteEmulation)
    {
        structStream << "    float3 spriteVertexPos : SPRITEPOSITION0;\n"
                     << "    float2 spriteTexCoord : SPRITETEXCOORD0;\n";
    }

    for (size_t attributeIndex = 0; attributeIndex < shaderAttributes.size(); ++attributeIndex)
    {
        const sh::Attribute &shaderAttribute = shaderAttributes[attributeIndex];
        if (!shaderAttribute.name.empty())
        {
            ASSERT(inputIndex < MAX_VERTEX_ATTRIBS);
            VertexFormatType vertexFormatType =
                inputIndex < inputLayout.size() ? inputLayout[inputIndex] : VERTEX_FORMAT_INVALID;

            // HLSL code for input structure
            if (IsMatrixType(shaderAttribute.type))
            {
                // Matrix types are always transposed
                structStream << "    "
                             << HLSLMatrixTypeString(TransposeMatrixType(shaderAttribute.type));
            }
            else
            {
                GLenum componentType = mRenderer->getVertexComponentType(vertexFormatType);

                if (shaderAttribute.name == "gl_InstanceID" ||
                    shaderAttribute.name == "gl_VertexID")
                {
                    // The input types of the instance ID and vertex ID in HLSL (uint) differs from
                    // the ones in ESSL (int).
                    structStream << " uint";
                }
                else
                {
                    structStream << "    ";
                    HLSLComponentTypeString(structStream, componentType,
                                            VariableComponentCount(shaderAttribute.type));
                }
            }

            structStream << " " << DecorateVariable(shaderAttribute.name) << " : ";

            if (shaderAttribute.name == "gl_InstanceID")
            {
                structStream << "SV_InstanceID";
            }
            else if (shaderAttribute.name == "gl_VertexID")
            {
                structStream << "SV_VertexID";
            }
            else
            {
                structStream << "TEXCOORD" << semanticIndex;
                semanticIndex += VariableRegisterCount(shaderAttribute.type);
            }

            structStream << ";\n";

            // HLSL code for initialization
            initStream << "    " << DecorateVariable(shaderAttribute.name) << " = ";

            // Mismatched vertex attribute to vertex input may result in an undefined
            // data reinterpretation (eg for pure integer->float, float->pure integer)
            // TODO: issue warning with gl debug info extension, when supported
            if (IsMatrixType(shaderAttribute.type) ||
                (mRenderer->getVertexConversionType(vertexFormatType) & VERTEX_CONVERT_GPU) != 0)
            {
                GenerateAttributeConversionHLSL(vertexFormatType, shaderAttribute, initStream);
            }
            else
            {
                initStream << "input." << DecorateVariable(shaderAttribute.name);
            }

            initStream << ";\n";

            inputIndex += VariableRowCount(TransposeMatrixType(shaderAttribute.type));
        }
    }

    structStream << "};\n"
                    "\n"
                    "void initAttributes(VS_INPUT input)\n"
                    "{\n"
                 << initStream.str() << "}\n";

    std::string vertexHLSL(sourceShader);

    size_t copyInsertionPos = vertexHLSL.find(VERTEX_ATTRIBUTE_STUB_STRING);
    vertexHLSL.replace(copyInsertionPos, strlen(VERTEX_ATTRIBUTE_STUB_STRING), structStream.str());

    return vertexHLSL;
}

std::string DynamicHLSL::generatePixelShaderForOutputSignature(
    const std::string &sourceShader,
    const std::vector<PixelShaderOutputVariable> &outputVariables,
    bool usesFragDepth,
    const std::vector<GLenum> &outputLayout) const
{
    const int shaderModel      = mRenderer->getMajorShaderModel();
    std::string targetSemantic = (shaderModel >= 4) ? "SV_TARGET" : "COLOR";
    std::string depthSemantic  = (shaderModel >= 4) ? "SV_Depth" : "DEPTH";

    std::ostringstream declarationStream;
    std::ostringstream copyStream;

    declarationStream << "struct PS_OUTPUT\n"
                         "{\n";

    // Workaround for HLSL 3.x: We can't do a depth/stencil only render, the runtime will complain.
    size_t numOutputs = outputLayout.empty() ? 1u : outputLayout.size();
    const PixelShaderOutputVariable defaultOutput(GL_FLOAT_VEC4, "dummy", "float4(0, 0, 0, 1)", 0);

    for (size_t layoutIndex = 0; layoutIndex < numOutputs; ++layoutIndex)
    {
        GLenum binding = outputLayout.empty() ? GL_COLOR_ATTACHMENT0 : outputLayout[layoutIndex];

        if (binding != GL_NONE)
        {
            unsigned int location = (binding - GL_COLOR_ATTACHMENT0);

            const PixelShaderOutputVariable *outputVariable =
                outputLayout.empty() ? &defaultOutput
                                     : FindOutputAtLocation(outputVariables, location);

            // OpenGL ES 3.0 spec $4.2.1
            // If [...] not all user-defined output variables are written, the values of fragment
            // colors
            // corresponding to unwritten variables are similarly undefined.
            if (outputVariable)
            {
                declarationStream << "    ";
                HLSLTypeString(declarationStream, outputVariable->type);
                declarationStream << " " << outputVariable->name << " : " << targetSemantic
                                  << static_cast<int>(layoutIndex) << ";\n";

                copyStream << "    output." << outputVariable->name << " = "
                           << outputVariable->source << ";\n";
            }
        }
    }

    if (usesFragDepth)
    {
        declarationStream << "    float gl_Depth : " << depthSemantic << ";\n";
        copyStream << "    output.gl_Depth = gl_Depth; \n";
    }

    declarationStream << "};\n"
                         "\n"
                         "PS_OUTPUT generateOutput()\n"
                         "{\n"
                         "    PS_OUTPUT output;\n"
                      << copyStream.str() << "    return output;\n"
                                             "}\n";

    std::string pixelHLSL(sourceShader);

    size_t outputInsertionPos = pixelHLSL.find(PIXEL_OUTPUT_STUB_STRING);
    pixelHLSL.replace(outputInsertionPos, strlen(PIXEL_OUTPUT_STUB_STRING),
                      declarationStream.str());

    return pixelHLSL;
}

void DynamicHLSL::generateVaryingLinkHLSL(const VaryingPacking &varyingPacking,
                                          const BuiltinInfo &builtins,
                                          bool programUsesPointSize,
                                          std::ostringstream &hlslStream) const
{
    ASSERT(builtins.dxPosition.enabled);
    hlslStream << "{\n"
               << "    float4 dx_Position : " << builtins.dxPosition.str() << ";\n";

    if (builtins.glPosition.enabled)
    {
        hlslStream << "    float4 gl_Position : " << builtins.glPosition.str() << ";\n";
    }

    if (builtins.glFragCoord.enabled)
    {
        hlslStream << "    float4 gl_FragCoord : " << builtins.glFragCoord.str() << ";\n";
    }

    if (builtins.glPointCoord.enabled)
    {
        hlslStream << "    float2 gl_PointCoord : " << builtins.glPointCoord.str() << ";\n";
    }

    if (builtins.glPointSize.enabled)
    {
        hlslStream << "    float gl_PointSize : " << builtins.glPointSize.str() << ";\n";
    }

    std::string varyingSemantic =
        GetVaryingSemantic(mRenderer->getMajorShaderModel(), programUsesPointSize);

    for (const PackedVaryingRegister &registerInfo : varyingPacking.getRegisterList())
    {
        const auto &varying = *registerInfo.packedVarying->varying;
        ASSERT(!varying.isStruct());

        // TODO: Add checks to ensure D3D interpolation modifiers don't result in too many
        // registers being used.
        // For example, if there are N registers, and we have N vec3 varyings and 1 float
        // varying, then D3D will pack them into N registers.
        // If the float varying has the 'nointerpolation' modifier on it then we would need
        // N + 1 registers, and D3D compilation will fail.

        switch (registerInfo.packedVarying->interpolation)
        {
            case sh::INTERPOLATION_SMOOTH:
                hlslStream << "    ";
                break;
            case sh::INTERPOLATION_FLAT:
                hlslStream << "    nointerpolation ";
                break;
            case sh::INTERPOLATION_CENTROID:
                hlslStream << "    centroid ";
                break;
            default:
                UNREACHABLE();
        }

        GLenum transposedType = gl::TransposeMatrixType(varying.type);
        GLenum componentType  = gl::VariableComponentType(transposedType);
        int columnCount       = gl::VariableColumnCount(transposedType);
        HLSLComponentTypeString(hlslStream, componentType, columnCount);
        unsigned int semanticIndex = registerInfo.semanticIndex;
        hlslStream << " v" << semanticIndex << " : " << varyingSemantic << semanticIndex << ";\n";
    }

    hlslStream << "};\n";
}

void DynamicHLSL::generateShaderLinkHLSL(const gl::Context *context,
                                         const gl::ProgramState &programData,
                                         const ProgramD3DMetadata &programMetadata,
                                         const VaryingPacking &varyingPacking,
                                         const BuiltinVaryingsD3D &builtinsD3D,
                                         std::string *pixelHLSL,
                                         std::string *vertexHLSL) const
{
    ASSERT(pixelHLSL->empty() && vertexHLSL->empty());

    const auto &data                   = context->getContextState();
    gl::Shader *vertexShaderGL         = programData.getAttachedVertexShader();
    gl::Shader *fragmentShaderGL       = programData.getAttachedFragmentShader();
    const ShaderD3D *fragmentShader    = GetImplAs<ShaderD3D>(fragmentShaderGL);
    const int shaderModel              = mRenderer->getMajorShaderModel();

    // usesViewScale() isn't supported in the D3D9 renderer
    ASSERT(shaderModel >= 4 || !programMetadata.usesViewScale());

    bool useInstancedPointSpriteEmulation =
        programMetadata.usesPointSize() &&
        mRenderer->getWorkarounds().useInstancedPointSpriteEmulation;

    // Validation done in the compiler
    ASSERT(!fragmentShader->usesFragColor() || !fragmentShader->usesFragData());

    std::ostringstream vertexStream;
    vertexStream << vertexShaderGL->getTranslatedSource(context);

    // Instanced PointSprite emulation requires additional entries originally generated in the
    // GeometryShader HLSL. These include pointsize clamp values.
    if (useInstancedPointSpriteEmulation)
    {
        vertexStream << "static float minPointSize = "
                     << static_cast<int>(data.getCaps().minAliasedPointSize) << ".0f;\n"
                     << "static float maxPointSize = "
                     << static_cast<int>(data.getCaps().maxAliasedPointSize) << ".0f;\n";
    }

    // Add stub string to be replaced when shader is dynamically defined by its layout
    vertexStream << "\n" << std::string(VERTEX_ATTRIBUTE_STUB_STRING) << "\n";

    const auto &vertexBuiltins = builtinsD3D[SHADER_VERTEX];

    // Write the HLSL input/output declarations
    vertexStream << "struct VS_OUTPUT\n";
    generateVaryingLinkHLSL(varyingPacking, vertexBuiltins, builtinsD3D.usesPointSize(),
                            vertexStream);
    vertexStream << "\n"
                 << "VS_OUTPUT main(VS_INPUT input)\n"
                 << "{\n"
                 << "    initAttributes(input);\n";

    vertexStream << "\n"
                 << "    gl_main();\n"
                 << "\n"
                 << "    VS_OUTPUT output;\n";

    if (vertexBuiltins.glPosition.enabled)
    {
        vertexStream << "    output.gl_Position = gl_Position;\n";
    }

    // On D3D9 or D3D11 Feature Level 9, we need to emulate large viewports using dx_ViewAdjust.
    if (shaderModel >= 4 && mRenderer->getShaderModelSuffix() == "")
    {
        vertexStream << "    output.dx_Position.x = gl_Position.x;\n";

        if (programMetadata.usesViewScale())
        {
            // This code assumes that dx_ViewScale.y = -1.0f when rendering to texture, and +1.0f
            // when rendering to the default framebuffer. No other values are valid.
            vertexStream << "    output.dx_Position.y = dx_ViewScale.y * gl_Position.y;\n";
        }
        else
        {
            vertexStream << "    output.dx_Position.y = - gl_Position.y;\n";
        }

        vertexStream << "    output.dx_Position.z = (gl_Position.z + gl_Position.w) * 0.5;\n"
                     << "    output.dx_Position.w = gl_Position.w;\n";
    }
    else
    {
        vertexStream << "    output.dx_Position.x = gl_Position.x * dx_ViewAdjust.z + "
                        "dx_ViewAdjust.x * gl_Position.w;\n";

        // If usesViewScale() is true and we're using the D3D11 renderer via Feature Level 9_*,
        // then we need to multiply the gl_Position.y by the viewScale.
        // usesViewScale() isn't supported when using the D3D9 renderer.
        if (programMetadata.usesViewScale() &&
            (shaderModel >= 4 && mRenderer->getShaderModelSuffix() != ""))
        {
            vertexStream << "    output.dx_Position.y = dx_ViewScale.y * (gl_Position.y * "
                            "dx_ViewAdjust.w + dx_ViewAdjust.y * gl_Position.w);\n";
        }
        else
        {
            vertexStream << "    output.dx_Position.y = -(gl_Position.y * dx_ViewAdjust.w + "
                            "dx_ViewAdjust.y * gl_Position.w);\n";
        }

        vertexStream << "    output.dx_Position.z = (gl_Position.z + gl_Position.w) * 0.5;\n"
                     << "    output.dx_Position.w = gl_Position.w;\n";
    }

    // We don't need to output gl_PointSize if we use are emulating point sprites via instancing.
    if (vertexBuiltins.glPointSize.enabled)
    {
        vertexStream << "    output.gl_PointSize = gl_PointSize;\n";
    }

    if (vertexBuiltins.glFragCoord.enabled)
    {
        vertexStream << "    output.gl_FragCoord = gl_Position;\n";
    }

    for (const PackedVaryingRegister &registerInfo : varyingPacking.getRegisterList())
    {
        const auto &packedVarying = *registerInfo.packedVarying;
        const auto &varying = *packedVarying.varying;
        ASSERT(!varying.isStruct());

        vertexStream << "    output.v" << registerInfo.semanticIndex << " = ";

        if (packedVarying.isStructField())
        {
            vertexStream << DecorateVariable(packedVarying.parentStructName) << ".";
        }

        vertexStream << DecorateVariable(varying.name);

        if (varying.isArray())
        {
            WriteArrayString(vertexStream, registerInfo.varyingArrayIndex);
        }

        if (VariableRowCount(varying.type) > 1)
        {
            WriteArrayString(vertexStream, registerInfo.varyingRowIndex);
        }

        vertexStream << ";\n";
    }

    // Instanced PointSprite emulation requires additional entries to calculate
    // the final output vertex positions of the quad that represents each sprite.
    if (useInstancedPointSpriteEmulation)
    {
        vertexStream << "\n"
                     << "    gl_PointSize = clamp(gl_PointSize, minPointSize, maxPointSize);\n";

        vertexStream << "    output.dx_Position.x += (input.spriteVertexPos.x * gl_PointSize / "
                        "(dx_ViewCoords.x*2)) * output.dx_Position.w;";

        if (programMetadata.usesViewScale())
        {
            // Multiply by ViewScale to invert the rendering when appropriate
            vertexStream << "    output.dx_Position.y += (-dx_ViewScale.y * "
                            "input.spriteVertexPos.y * gl_PointSize / (dx_ViewCoords.y*2)) * "
                            "output.dx_Position.w;";
        }
        else
        {
            vertexStream << "    output.dx_Position.y += (input.spriteVertexPos.y * gl_PointSize / "
                            "(dx_ViewCoords.y*2)) * output.dx_Position.w;";
        }

        vertexStream
            << "    output.dx_Position.z += input.spriteVertexPos.z * output.dx_Position.w;\n";

        if (programMetadata.usesPointCoord())
        {
            vertexStream << "\n"
                         << "    output.gl_PointCoord = input.spriteTexCoord;\n";
        }
    }

    // Renderers that enable instanced pointsprite emulation require the vertex shader output member
    // gl_PointCoord to be set to a default value if used without gl_PointSize. 0.5,0.5 is the same
    // default value used in the generated pixel shader.
    if (programMetadata.usesInsertedPointCoordValue())
    {
        ASSERT(!useInstancedPointSpriteEmulation);
        vertexStream << "\n"
                     << "    output.gl_PointCoord = float2(0.5, 0.5);\n";
    }

    vertexStream << "\n"
                 << "    return output;\n"
                 << "}\n";

    const auto &pixelBuiltins = builtinsD3D[SHADER_PIXEL];

    std::ostringstream pixelStream;
    pixelStream << fragmentShaderGL->getTranslatedSource(context);
    pixelStream << "struct PS_INPUT\n";
    generateVaryingLinkHLSL(varyingPacking, pixelBuiltins, builtinsD3D.usesPointSize(),
                            pixelStream);
    pixelStream << "\n";

    pixelStream << std::string(PIXEL_OUTPUT_STUB_STRING) << "\n";

    if (fragmentShader->usesFrontFacing())
    {
        if (shaderModel >= 4)
        {
            pixelStream << "PS_OUTPUT main(PS_INPUT input, bool isFrontFace : SV_IsFrontFace)\n"
                        << "{\n";
        }
        else
        {
            pixelStream << "PS_OUTPUT main(PS_INPUT input, float vFace : VFACE)\n"
                        << "{\n";
        }
    }
    else
    {
        pixelStream << "PS_OUTPUT main(PS_INPUT input)\n"
                    << "{\n";
    }

    if (pixelBuiltins.glFragCoord.enabled)
    {
        pixelStream << "    float rhw = 1.0 / input.gl_FragCoord.w;\n";

        // Certain Shader Models (4_0+ and 3_0) allow reading from dx_Position in the pixel shader.
        // Other Shader Models (4_0_level_9_3 and 2_x) don't support this, so we emulate it using
        // dx_ViewCoords.
        if (shaderModel >= 4 && mRenderer->getShaderModelSuffix() == "")
        {
            pixelStream << "    gl_FragCoord.x = input.dx_Position.x;\n"
                        << "    gl_FragCoord.y = input.dx_Position.y;\n";
        }
        else if (shaderModel == 3)
        {
            pixelStream << "    gl_FragCoord.x = input.dx_Position.x + 0.5;\n"
                        << "    gl_FragCoord.y = input.dx_Position.y + 0.5;\n";
        }
        else
        {
            // dx_ViewCoords contains the viewport width/2, height/2, center.x and center.y. See
            // Renderer::setViewport()
            pixelStream << "    gl_FragCoord.x = (input.gl_FragCoord.x * rhw) * dx_ViewCoords.x + "
                           "dx_ViewCoords.z;\n"
                        << "    gl_FragCoord.y = (input.gl_FragCoord.y * rhw) * dx_ViewCoords.y + "
                           "dx_ViewCoords.w;\n";
        }

        if (programMetadata.usesViewScale())
        {
            // For Feature Level 9_3 and below, we need to correct gl_FragCoord.y to account
            // for dx_ViewScale. On Feature Level 10_0+, gl_FragCoord.y is calculated above using
            // dx_ViewCoords and is always correct irrespective of dx_ViewScale's value.
            // NOTE: usesViewScale() can only be true on D3D11 (i.e. Shader Model 4.0+).
            if (shaderModel >= 4 && mRenderer->getShaderModelSuffix() == "")
            {
                // Some assumptions:
                //  - dx_ViewScale.y = -1.0f when rendering to texture
                //  - dx_ViewScale.y = +1.0f when rendering to the default framebuffer
                //  - gl_FragCoord.y has been set correctly above.
                //
                // When rendering to the backbuffer, the code inverts gl_FragCoord's y coordinate.
                // This involves subtracting the y coordinate from the height of the area being
                // rendered to.
                //
                // First we calculate the height of the area being rendered to:
                //    render_area_height = (2.0f / (1.0f - input.gl_FragCoord.y * rhw)) *
                //    gl_FragCoord.y
                //
                // Note that when we're rendering to default FB, we want our output to be
                // equivalent to:
                //    "gl_FragCoord.y = render_area_height - gl_FragCoord.y"
                //
                // When we're rendering to a texture, we want our output to be equivalent to:
                //    "gl_FragCoord.y = gl_FragCoord.y;"
                //
                // If we set scale_factor = ((1.0f + dx_ViewScale.y) / 2.0f), then notice that
                //  - When rendering to default FB: scale_factor = 1.0f
                //  - When rendering to texture:    scale_factor = 0.0f
                //
                // Therefore, we can get our desired output by setting:
                //    "gl_FragCoord.y = scale_factor * render_area_height - dx_ViewScale.y *
                //    gl_FragCoord.y"
                //
                // Simplifying, this becomes:
                pixelStream
                    << "    gl_FragCoord.y = (1.0f + dx_ViewScale.y) * gl_FragCoord.y /"
                       "(1.0f - input.gl_FragCoord.y * rhw)  - dx_ViewScale.y * gl_FragCoord.y;\n";
            }
        }

        pixelStream << "    gl_FragCoord.z = (input.gl_FragCoord.z * rhw) * dx_DepthFront.x + "
                       "dx_DepthFront.y;\n"
                    << "    gl_FragCoord.w = rhw;\n";
    }

    if (pixelBuiltins.glPointCoord.enabled && shaderModel >= 3)
    {
        pixelStream << "    gl_PointCoord.x = input.gl_PointCoord.x;\n"
                    << "    gl_PointCoord.y = 1.0 - input.gl_PointCoord.y;\n";
    }

    if (fragmentShader->usesFrontFacing())
    {
        if (shaderModel <= 3)
        {
            pixelStream << "    gl_FrontFacing = (vFace * dx_DepthFront.z >= 0.0);\n";
        }
        else
        {
            pixelStream << "    gl_FrontFacing = isFrontFace;\n";
        }
    }

    for (const PackedVaryingRegister &registerInfo : varyingPacking.getRegisterList())
    {
        const auto &packedVarying = *registerInfo.packedVarying;
        const auto &varying = *packedVarying.varying;
        ASSERT(!varying.isBuiltIn() && !varying.isStruct());

        // Don't reference VS-only transform feedback varyings in the PS. Note that we're relying on
        // that the staticUse flag is set according to usage in the fragment shader.
        if (packedVarying.vertexOnly || !varying.staticUse)
            continue;

        pixelStream << "    ";

        if (packedVarying.isStructField())
        {
            pixelStream << DecorateVariable(packedVarying.parentStructName) << ".";
        }

        pixelStream << DecorateVariable(varying.name);

        if (varying.isArray())
        {
            WriteArrayString(pixelStream, registerInfo.varyingArrayIndex);
        }

        GLenum transposedType = TransposeMatrixType(varying.type);
        if (VariableRowCount(transposedType) > 1)
        {
            WriteArrayString(pixelStream, registerInfo.varyingRowIndex);
        }

        pixelStream << " = input.v" << registerInfo.semanticIndex;

        switch (VariableColumnCount(transposedType))
        {
            case 1:
                pixelStream << ".x";
                break;
            case 2:
                pixelStream << ".xy";
                break;
            case 3:
                pixelStream << ".xyz";
                break;
            case 4:
                break;
            default:
                UNREACHABLE();
        }
        pixelStream << ";\n";
    }

    pixelStream << "\n"
                << "    gl_main();\n"
                << "\n"
                << "    return generateOutput();\n"
                << "}\n";

    *vertexHLSL = vertexStream.str();
    *pixelHLSL  = pixelStream.str();
}

std::string DynamicHLSL::generateComputeShaderLinkHLSL(const gl::Context *context,
                                                       const gl::ProgramState &programData) const
{
    gl::Shader *computeShaderGL = programData.getAttachedComputeShader();
    std::stringstream computeStream;
    std::string translatedSource = computeShaderGL->getTranslatedSource(context);
    computeStream << translatedSource;

    bool usesWorkGroupID = translatedSource.find("GL_USES_WORK_GROUP_ID") != std::string::npos;
    bool usesLocalInvocationID =
        translatedSource.find("GL_USES_LOCAL_INVOCATION_ID") != std::string::npos;
    bool usesGlobalInvocationID =
        translatedSource.find("GL_USES_GLOBAL_INVOCATION_ID") != std::string::npos;
    bool usesLocalInvocationIndex =
        translatedSource.find("GL_USES_LOCAL_INVOCATION_INDEX") != std::string::npos;

    computeStream << "\nstruct CS_INPUT\n{\n";
    if (usesWorkGroupID)
    {
        computeStream << "    uint3 dx_WorkGroupID : "
                      << "SV_GroupID;\n";
    }

    if (usesLocalInvocationID)
    {
        computeStream << "    uint3 dx_LocalInvocationID : "
                      << "SV_GroupThreadID;\n";
    }

    if (usesGlobalInvocationID)
    {
        computeStream << "    uint3 dx_GlobalInvocationID : "
                      << "SV_DispatchThreadID;\n";
    }

    if (usesLocalInvocationIndex)
    {
        computeStream << "    uint dx_LocalInvocationIndex : "
                      << "SV_GroupIndex;\n";
    }

    computeStream << "};\n\n";

    const sh::WorkGroupSize &localSize = computeShaderGL->getWorkGroupSize(context);
    computeStream << "[numthreads(" << localSize[0] << ", " << localSize[1] << ", " << localSize[2]
                  << ")]\n";

    computeStream << "void main(CS_INPUT input)\n"
                  << "{\n";

    if (usesWorkGroupID)
    {
        computeStream << "    gl_WorkGroupID = input.dx_WorkGroupID;\n";
    }
    if (usesLocalInvocationID)
    {
        computeStream << "    gl_LocalInvocationID = input.dx_LocalInvocationID;\n";
    }
    if (usesGlobalInvocationID)
    {
        computeStream << "    gl_GlobalInvocationID = input.dx_GlobalInvocationID;\n";
    }
    if (usesLocalInvocationIndex)
    {
        computeStream << "    gl_LocalInvocationIndex = input.dx_LocalInvocationIndex;\n";
    }

    computeStream << "\n"
                  << "    gl_main();\n"
                  << "}\n";

    return computeStream.str();
}

std::string DynamicHLSL::generateGeometryShaderPreamble(const VaryingPacking &varyingPacking,
                                                        const BuiltinVaryingsD3D &builtinsD3D) const
{
    ASSERT(mRenderer->getMajorShaderModel() >= 4);

    std::ostringstream preambleStream;

    const auto &vertexBuiltins = builtinsD3D[SHADER_VERTEX];

    preambleStream << "struct GS_INPUT\n";
    generateVaryingLinkHLSL(varyingPacking, vertexBuiltins, builtinsD3D.usesPointSize(),
                            preambleStream);
    preambleStream << "\n"
                   << "struct GS_OUTPUT\n";
    generateVaryingLinkHLSL(varyingPacking, builtinsD3D[SHADER_GEOMETRY],
                            builtinsD3D.usesPointSize(), preambleStream);
    preambleStream
        << "\n"
        << "void copyVertex(inout GS_OUTPUT output, GS_INPUT input, GS_INPUT flatinput)\n"
        << "{\n"
        << "    output.gl_Position = input.gl_Position;\n";

    if (vertexBuiltins.glPointSize.enabled)
    {
        preambleStream << "    output.gl_PointSize = input.gl_PointSize;\n";
    }

    for (const PackedVaryingRegister &varyingRegister : varyingPacking.getRegisterList())
    {
        preambleStream << "    output.v" << varyingRegister.semanticIndex << " = ";
        if (varyingRegister.packedVarying->interpolation == sh::INTERPOLATION_FLAT)
        {
            preambleStream << "flat";
        }
        preambleStream << "input.v" << varyingRegister.semanticIndex << "; \n";
    }

    if (vertexBuiltins.glFragCoord.enabled)
    {
        preambleStream << "    output.gl_FragCoord = input.gl_FragCoord;\n";
    }

    // Only write the dx_Position if we aren't using point sprites
    preambleStream << "#ifndef ANGLE_POINT_SPRITE_SHADER\n"
                   << "    output.dx_Position = input.dx_Position;\n"
                   << "#endif  // ANGLE_POINT_SPRITE_SHADER\n"
                   << "}\n";

    return preambleStream.str();
}

std::string DynamicHLSL::generateGeometryShaderHLSL(gl::PrimitiveType primitiveType,
                                                    const gl::ContextState &data,
                                                    const gl::ProgramState &programData,
                                                    const bool useViewScale,
                                                    const std::string &preambleString) const
{
    ASSERT(mRenderer->getMajorShaderModel() >= 4);

    std::stringstream shaderStream;

    const bool pointSprites   = (primitiveType == PRIMITIVE_POINTS);
    const bool usesPointCoord = preambleString.find("gl_PointCoord") != std::string::npos;

    const char *inputPT  = nullptr;
    const char *outputPT = nullptr;
    int inputSize        = 0;
    int maxVertexOutput  = 0;

    switch (primitiveType)
    {
        case PRIMITIVE_POINTS:
            inputPT         = "point";
            outputPT        = "Triangle";
            inputSize       = 1;
            maxVertexOutput = 4;
            break;

        case PRIMITIVE_LINES:
        case PRIMITIVE_LINE_STRIP:
        case PRIMITIVE_LINE_LOOP:
            inputPT         = "line";
            outputPT        = "Line";
            inputSize       = 2;
            maxVertexOutput = 2;
            break;

        case PRIMITIVE_TRIANGLES:
        case PRIMITIVE_TRIANGLE_STRIP:
        case PRIMITIVE_TRIANGLE_FAN:
            inputPT         = "triangle";
            outputPT        = "Triangle";
            inputSize       = 3;
            maxVertexOutput = 3;
            break;

        default:
            UNREACHABLE();
            break;
    }

    if (pointSprites)
    {
        shaderStream << "#define ANGLE_POINT_SPRITE_SHADER\n"
                        "\n"
                        "uniform float4 dx_ViewCoords : register(c1);\n";

        if (useViewScale)
        {
            shaderStream << "uniform float2 dx_ViewScale : register(c3);\n";
        }

        shaderStream << "\n"
                        "static float2 pointSpriteCorners[] = \n"
                        "{\n"
                        "    float2( 0.5f, -0.5f),\n"
                        "    float2( 0.5f,  0.5f),\n"
                        "    float2(-0.5f, -0.5f),\n"
                        "    float2(-0.5f,  0.5f)\n"
                        "};\n"
                        "\n"
                        "static float2 pointSpriteTexcoords[] = \n"
                        "{\n"
                        "    float2(1.0f, 1.0f),\n"
                        "    float2(1.0f, 0.0f),\n"
                        "    float2(0.0f, 1.0f),\n"
                        "    float2(0.0f, 0.0f)\n"
                        "};\n"
                        "\n"
                        "static float minPointSize = "
                     << static_cast<int>(data.getCaps().minAliasedPointSize)
                     << ".0f;\n"
                        "static float maxPointSize = "
                     << static_cast<int>(data.getCaps().maxAliasedPointSize) << ".0f;\n"
                     << "\n";
    }

    shaderStream << preambleString << "\n"
                 << "[maxvertexcount(" << maxVertexOutput << ")]\n"
                 << "void main(" << inputPT << " GS_INPUT input[" << inputSize << "], ";

    if (primitiveType == PRIMITIVE_TRIANGLE_STRIP)
    {
        shaderStream << "uint primitiveID : SV_PrimitiveID, ";
    }

    shaderStream << " inout " << outputPT << "Stream<GS_OUTPUT> outStream)\n"
                 << "{\n"
                 << "    GS_OUTPUT output = (GS_OUTPUT)0;\n";

    if (primitiveType == PRIMITIVE_TRIANGLE_STRIP)
    {
        shaderStream << "    uint lastVertexIndex = (primitiveID % 2 == 0 ? 2 : 1);\n";
    }
    else
    {
        shaderStream << "    uint lastVertexIndex = " << (inputSize - 1) << ";\n";
    }

    for (int vertexIndex = 0; vertexIndex < inputSize; ++vertexIndex)
    {
        shaderStream << "    copyVertex(output, input[" << vertexIndex
                     << "], input[lastVertexIndex]);\n";

        if (!pointSprites)
        {
            ASSERT(inputSize == maxVertexOutput);
            shaderStream << "    outStream.Append(output);\n";
        }
    }

    if (pointSprites)
    {
        shaderStream << "\n"
                        "    float4 dx_Position = input[0].dx_Position;\n"
                        "    float gl_PointSize = clamp(input[0].gl_PointSize, minPointSize, "
                        "maxPointSize);\n"
                        "    float2 viewportScale = float2(1.0f / dx_ViewCoords.x, 1.0f / "
                        "dx_ViewCoords.y) * dx_Position.w;\n";

        for (int corner = 0; corner < 4; corner++)
        {
            if (useViewScale)
            {
                shaderStream << "    \n"
                                "    output.dx_Position = dx_Position + float4(1.0f, "
                                "-dx_ViewScale.y, 1.0f, 1.0f)"
                                "        * float4(pointSpriteCorners["
                             << corner << "] * viewportScale * gl_PointSize, 0.0f, 0.0f);\n";
            }
            else
            {
                shaderStream << "\n"
                                "    output.dx_Position = dx_Position + float4(pointSpriteCorners["
                             << corner << "] * viewportScale * gl_PointSize, 0.0f, 0.0f);\n";
            }

            if (usesPointCoord)
            {
                shaderStream << "    output.gl_PointCoord = pointSpriteTexcoords[" << corner
                             << "];\n";
            }

            shaderStream << "    outStream.Append(output);\n";
        }
    }

    shaderStream << "    \n"
                    "    outStream.RestartStrip();\n"
                    "}\n";

    return shaderStream.str();
}

// static
void DynamicHLSL::GenerateAttributeConversionHLSL(gl::VertexFormatType vertexFormatType,
                                                  const sh::ShaderVariable &shaderAttrib,
                                                  std::ostringstream &outStream)
{
    // Matrix
    if (IsMatrixType(shaderAttrib.type))
    {
        outStream << "transpose(input." << DecorateVariable(shaderAttrib.name) << ")";
        return;
    }

    GLenum shaderComponentType = VariableComponentType(shaderAttrib.type);
    int shaderComponentCount   = VariableComponentCount(shaderAttrib.type);
    const gl::VertexFormat &vertexFormat = gl::GetVertexFormatFromType(vertexFormatType);

    // Perform integer to float conversion (if necessary)
    if (shaderComponentType == GL_FLOAT && vertexFormat.type != GL_FLOAT)
    {
        // TODO: normalization for 32-bit integer formats
        ASSERT(!vertexFormat.normalized && !vertexFormat.pureInteger);
        outStream << "float" << shaderComponentCount << "(input."
                  << DecorateVariable(shaderAttrib.name) << ")";
        return;
    }

    // No conversion necessary
    outStream << "input." << DecorateVariable(shaderAttrib.name);
}

void DynamicHLSL::getPixelShaderOutputKey(const gl::ContextState &data,
                                          const gl::ProgramState &programData,
                                          const ProgramD3DMetadata &metadata,
                                          std::vector<PixelShaderOutputVariable> *outPixelShaderKey)
{
    // Two cases when writing to gl_FragColor and using ESSL 1.0:
    // - with a 3.0 context, the output color is copied to channel 0
    // - with a 2.0 context, the output color is broadcast to all channels
    bool broadcast = metadata.usesBroadcast(data);
    const unsigned int numRenderTargets =
        (broadcast || metadata.usesMultipleFragmentOuts() ? data.getCaps().maxDrawBuffers : 1);

    if (metadata.getMajorShaderVersion() < 300)
    {
        for (unsigned int renderTargetIndex = 0; renderTargetIndex < numRenderTargets;
             renderTargetIndex++)
        {
            PixelShaderOutputVariable outputKeyVariable;
            outputKeyVariable.type = GL_FLOAT_VEC4;
            outputKeyVariable.name = "gl_Color" + Str(renderTargetIndex);
            outputKeyVariable.source =
                broadcast ? "gl_Color[0]" : "gl_Color[" + Str(renderTargetIndex) + "]";
            outputKeyVariable.outputIndex = renderTargetIndex;

            outPixelShaderKey->push_back(outputKeyVariable);
        }
    }
    else
    {
        const auto &shaderOutputVars =
            metadata.getFragmentShader()->getData().getActiveOutputVariables();

        for (auto outputPair : programData.getOutputLocations())
        {
            const VariableLocation &outputLocation   = outputPair.second;
            const sh::ShaderVariable &outputVariable = shaderOutputVars[outputLocation.index];
            const std::string &variableName = "out_" + outputLocation.name;
            const std::string &elementString =
                (outputLocation.element == GL_INVALID_INDEX ? "" : Str(outputLocation.element));

            ASSERT(outputVariable.staticUse);

            PixelShaderOutputVariable outputKeyVariable;
            outputKeyVariable.type        = outputVariable.type;
            outputKeyVariable.name        = variableName + elementString;
            outputKeyVariable.source      = variableName + ArrayString(outputLocation.element);
            outputKeyVariable.outputIndex = outputPair.first;

            outPixelShaderKey->push_back(outputKeyVariable);
        }
    }
}

// BuiltinVarying Implementation.
BuiltinVarying::BuiltinVarying() : enabled(false), index(0), systemValue(false)
{
}

std::string BuiltinVarying::str() const
{
    return (systemValue ? semantic : (semantic + Str(index)));
}

void BuiltinVarying::enableSystem(const std::string &systemValueSemantic)
{
    enabled     = true;
    semantic    = systemValueSemantic;
    systemValue = true;
}

void BuiltinVarying::enable(const std::string &semanticVal, unsigned int indexVal)
{
    enabled  = true;
    semantic = semanticVal;
    index    = indexVal;
}

// BuiltinVaryingsD3D Implementation.
BuiltinVaryingsD3D::BuiltinVaryingsD3D(const ProgramD3DMetadata &metadata,
                                       const VaryingPacking &packing)
{
    updateBuiltins(SHADER_VERTEX, metadata, packing);
    updateBuiltins(SHADER_PIXEL, metadata, packing);
    if (metadata.getRendererMajorShaderModel() >= 4)
    {
        updateBuiltins(SHADER_GEOMETRY, metadata, packing);
    }
}

void BuiltinVaryingsD3D::updateBuiltins(ShaderType shaderType,
                                        const ProgramD3DMetadata &metadata,
                                        const VaryingPacking &packing)
{
    const std::string &userSemantic = GetVaryingSemantic(metadata.getRendererMajorShaderModel(),
                                                         metadata.usesSystemValuePointSize());

    unsigned int reservedSemanticIndex = packing.getMaxSemanticIndex();

    BuiltinInfo *builtins = &mBuiltinInfo[shaderType];

    if (metadata.getRendererMajorShaderModel() >= 4)
    {
        builtins->dxPosition.enableSystem("SV_Position");
    }
    else if (shaderType == SHADER_PIXEL)
    {
        builtins->dxPosition.enableSystem("VPOS");
    }
    else
    {
        builtins->dxPosition.enableSystem("POSITION");
    }

    if (metadata.usesTransformFeedbackGLPosition())
    {
        builtins->glPosition.enable(userSemantic, reservedSemanticIndex++);
    }

    if (metadata.usesFragCoord())
    {
        builtins->glFragCoord.enable(userSemantic, reservedSemanticIndex++);
    }

    if (shaderType == SHADER_VERTEX ? metadata.addsPointCoordToVertexShader()
                                    : metadata.usesPointCoord())
    {
        // SM3 reserves the TEXCOORD semantic for point sprite texcoords (gl_PointCoord)
        // In D3D11 we manually compute gl_PointCoord in the GS.
        if (metadata.getRendererMajorShaderModel() >= 4)
        {
            builtins->glPointCoord.enable(userSemantic, reservedSemanticIndex++);
        }
        else
        {
            builtins->glPointCoord.enable("TEXCOORD", 0);
        }
    }

    // Special case: do not include PSIZE semantic in HLSL 3 pixel shaders
    if (metadata.usesSystemValuePointSize() &&
        (shaderType != SHADER_PIXEL || metadata.getRendererMajorShaderModel() >= 4))
    {
        builtins->glPointSize.enableSystem("PSIZE");
    }
}

}  // namespace rx


text:
using System;
using FluentAssertions;
using Nest.Tests.MockData.Domain;
using NUnit.Framework;

namespace Nest.Tests.Integration.Mapping
{
	[TestFixture]
	public class MapTests : IntegrationTests
	{
		private void TestMapping(RootObjectMapping typeMapping)
		{
			Assert.NotNull(typeMapping);
			Assert.AreEqual("string", typeMapping.Properties["content"].Type.Name);
			Assert.AreEqual("string", typeMapping.Properties["country"].Type.Name);
			Assert.AreEqual("double", typeMapping.Properties["doubleValue"].Type.Name);
			Assert.AreEqual("long", typeMapping.Properties["longValue"].Type.Name);
			Assert.AreEqual("boolean", typeMapping.Properties["boolValue"].Type.Name);
			Assert.AreEqual("integer", typeMapping.Properties["intValues"].Type.Name);
			Assert.AreEqual("float", typeMapping.Properties["floatValues"].Type.Name);
			Assert.AreEqual("string", typeMapping.Properties["name"].Type.Name);
			Assert.AreEqual("date", typeMapping.Properties["startedOn"].Type.Name);
			Assert.AreEqual("long", typeMapping.Properties["stupidIntIWantAsLong"].Type.Name);
			Assert.AreEqual("float", typeMapping.Properties["floatValue"].Type.Name);
			Assert.AreEqual("integer", typeMapping.Properties["id"].Type.Name);
			Assert.AreEqual("integer", typeMapping.Properties["loc"].Type.Name);
			var mapping = typeMapping.Properties["country"] as StringMapping;
			Assert.NotNull(mapping);
			Assert.AreEqual(FieldIndexOption.not_analyzed, mapping.Index);
			//Assert.AreEqual("elasticsearchprojects", typeMapping.Parent.Type);

			Assert.AreEqual("geo_point", typeMapping.Properties["origin"].Type.Name);

			//Assert.IsTrue(typeMapping.Properties["origin"].Dynamic);
			//Assert.AreEqual("double", typeMapping.Properties["origin"].Properties["lat"].Type);
			//Assert.AreEqual("double", typeMapping.Properties["origin"].Properties["lon"].Type);

			//Assert.IsTrue(typeMapping.Properties["followers"].Dynamic);
			//Assert.AreEqual("long", typeMapping.Properties["followers"].Properties["age"].Type);
			//Assert.AreEqual("date", typeMapping.Properties["followers"].Properties["dateOfBirth"].Type);
			//Assert.AreEqual("string", typeMapping.Properties["followers"].Properties["email"].Type);
			//Assert.AreEqual("string", typeMapping.Properties["followers"].Properties["firstName"].Type);
			//Assert.AreEqual("long", typeMapping.Properties["followers"].Properties["id"].Type);
			//Assert.AreEqual("string", typeMapping.Properties["followers"].Properties["lastName"].Type);

			//Assert.IsTrue(typeMapping.Properties["followers"].Properties["placeOfBirth"].Dynamic);
			//Assert.AreEqual("double", typeMapping.Properties["followers"].Properties["placeOfBirth"].Properties["lat"].Type);
			//Assert.AreEqual("double", typeMapping.Properties["followers"].Properties["placeOfBirth"].Properties["lon"].Type);
		}

		[Test]
		public void SimpleMapByAttributes()
		{
			var index = ElasticsearchConfiguration.NewUniqueIndexName();
			var x = this._client.CreateIndex(index, s => s
				.AddMapping<ElasticsearchProject>(m => m.MapFromAttributes())
			);
			Assert.IsTrue(x.Acknowledged, x.ConnectionStatus.ToString());

			var typeMapping = this._client.GetMapping(i => i.Index(index).Type("elasticsearchprojects"));
			typeMapping.Should().NotBeNull();
			TestMapping(typeMapping.Mapping);
		}

		[Test]
		public void SimpleMapByAttributesUsingType()
		{
			var index = ElasticsearchConfiguration.NewUniqueIndexName();
			var x = this._client.CreateIndex(index, s => s
				.AddMapping<ElasticsearchProject>(a=>a.MapFromAttributes())
			);
			Assert.IsTrue(x.Acknowledged, x.ConnectionStatus.ToString());
			var xx = this._client.Map<object>(m=>m.Type(typeof(ElasticsearchProject)).Index(index));
			Assert.IsTrue(xx.Acknowledged);

			var typeMapping = this._client.GetMapping(i => i.Index(index).Type("elasticsearchprojects"));
			typeMapping.Should().NotBeNull();
			TestMapping(typeMapping.Mapping);
		}

		[Test]
		public void GetMapping()
		{
			var typeMapping = this._client.GetMapping(i => i.Index(ElasticsearchConfiguration.DefaultIndex).Type("elasticsearchprojects"));
			typeMapping.Should().NotBeNull();
			TestMapping(typeMapping.Mapping);
		}

		[Test]
		public void GetMappingOnNonExistingIndexType()
		{
			Assert.DoesNotThrow(() =>
			{
				var typeMapping = this._client.GetMapping(i=>i.Index("asfasfasfasfasf").Type("asdasdasdasdasdasdasdasd"));
				typeMapping.IsValid.Should().BeFalse();
				Assert.Null(typeMapping.Mapping);
			});

		}

		[Test]
		public void DynamicMap()
		{
			var index = ElasticsearchConfiguration.NewUniqueIndexName();
			var x = this._client.CreateIndex(index, s => s);
			Assert.IsTrue(x.Acknowledged, x.ConnectionStatus.ToString());
			var typeMappingResult = this._client.GetMapping(gm=>gm.Index(ElasticsearchConfiguration.DefaultIndex).Type("elasticsearchprojects"));
			typeMappingResult.IsValid.Should().BeTrue();
			var typeMapping = typeMappingResult.Mapping;
			var mapping = typeMapping.Properties["country"] as StringMapping;
			Assert.NotNull(mapping);
			mapping.Boost = 3;
			this._client.Map<object>(m=>m.InitializeUsing(typeMapping).Index(index).Type("elasticsearchprojects2"));

			typeMapping = this._client.GetMapping(gm=>gm.Index(index).Type("elasticsearchprojects2")).Mapping;
			var countryMapping = typeMapping.Properties["country"] as StringMapping;
			Assert.NotNull(countryMapping);
			Assert.AreEqual(3, countryMapping.Boost);
		}

		[Test]
		public void GetMissingMap()
		{
			Assert.DoesNotThrow(() => {
				var typeMapping = this._client.GetMapping(gm => gm.Index("asdasdasdsada").Type("elasticsearchprojects2")).Mapping;
			});
		}

	}
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef IVW_SEED3DTO4D_H
#define IVW_SEED3DTO4D_H

#include <modules/vectorfieldvisualization/vectorfieldvisualizationmoduledefine.h>
#include <inviwo/core/common/inviwo.h>
#include <inviwo/core/processors/processor.h>
#include <inviwo/core/properties/ordinalproperty.h>
#include <inviwo/core/ports/imageport.h>
#include <modules/vectorfieldvisualization/ports/seedpointsport.h>

namespace inviwo {

class IVW_MODULE_VECTORFIELDVISUALIZATION_API Seed3Dto4D : public Processor {
public:
    Seed3Dto4D();
    virtual ~Seed3Dto4D() = default;

    virtual void process() override;

    virtual const ProcessorInfo getProcessorInfo() const override;
    static const ProcessorInfo processorInfo_;

private:
    SeedPoints3DInport seed3d_;
    SeedPoints4DOutport seed4d_;

    FloatProperty w_;
};

}  // namespace inviwo

#endif  // IVW_SEED3DTO4D_H


text:
'use strict'

var assert = require('assert')

module.exports = function verifyOptions (opts) {
  if (opts.expeditious) {
    assert(
      typeof opts.expeditious === 'object',
      'opts.expeditious must be an object containing valid expeditious options'
    )

    assert(
      opts.expeditious.isObjectMode() === true,
      'opts.expeditious.objectMode should be set to true on the instance ' +
      'provided to ' + require('../package.json').name
    )
  } else {
    assert(
      typeof opts.defaultTtl === 'number' ||
      typeof opts.defaultTtl === 'string',
      `opts.defaultTtl must be a number of milliseconds or a timestring, e.g
      supply 60000 or "1 minute" to cache responses for a minute`
    )

    assert(
      typeof opts.namespace === 'string' && opts.namespace.length > 0,
      'opts.namespace must be a non-empty string e.g "usersCache"'
    )
  }

  assert(
    !opts.shouldCache || typeof opts.shouldCache === 'function',
    'opts.shouldCache should be a function if provided'
  )

  assert(
    !opts.genCacheKey || typeof opts.genCacheKey === 'function',
    'opts.genCacheKey should be a function if provided'
  )

  assert(
    !opts.statusCodeExpires || typeof opts.statusCodeExpires === 'object',
    'opts.statusCodeExpires should be an object if provided'
  )

  assert(
    !opts.cacheStatusHeader || typeof opts.cacheStatusHeader === 'boolean' ||
      typeof opts.cacheStatusHeader === 'string',
    'opts.cacheStatusHeader should be a boolean or string if provided'
  )
}


text:
package org.holoeverywhere.addon;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import org.holoeverywhere.addon.IAddon.Addon;

public final class IAddonBasicAttacher<V extends IAddonBase<Z>, Z> implements IAddonAttacher<V> {
    private final class AddonComparator implements Comparator<V> {
        @Override
        public int compare(V lhs, V rhs) {
            final int i1 = getWeight(lhs.getParent());
            final int i2 = getWeight(rhs.getParent());
            return i1 > i2 ? 1 : i1 < i2 ? -1 : 0;
        }

        private int getWeight(IAddon addon) {
            if (addon.getClass().isAnnotationPresent(Addon.class)) {
                return addon.getClass().getAnnotation(Addon.class).weight();
            }
            return -1;
        }
    }

    private final Map<Class<? extends IAddon>, V> mAddons = new HashMap<Class<? extends IAddon>, V>();
    private List<V> mAddonsList;
    private final Set<V> mAddonsSet = new TreeSet<V>(new AddonComparator());
    private boolean mLockAttaching = false;
    private Z mObject;

    public IAddonBasicAttacher(Z object) {
        mObject = object;
    }

    @Override
    public <T extends V> T addon(Class<? extends IAddon> clazz) {
        return addon(clazz, true);
    }

    @SuppressWarnings("unchecked")
    private <T extends V> T addon(Class<? extends IAddon> clazz, boolean checkConflicts) {
        T addon = (T) mAddons.get(clazz);
        if (addon == null) {
            if (mLockAttaching) {
                throw AttachException.afterInit(mObject, clazz);
            }
            addon = IAddon.obtain(clazz, mObject);
            if (addon == null) {
                return null;
            }
            mAddons.put(clazz, addon);
            mAddonsSet.add(addon);
            mAddonsList = null;
            if (checkConflicts) {
                checkConflicts();
            }
        }
        return addon;
    }

    @Override
    public void addon(Collection<Class<? extends IAddon>> classes) {
        if (classes == null || classes.size() == 0) {
            return;
        }
        for (Class<? extends IAddon> clazz : classes) {
            addon(clazz, false);
        }
        checkConflicts();
    }

    @Override
    public <T extends V> T addon(String classname) {
        return addon(IAddon.makeAddonClass(classname));
    }

    private void checkConflicts() {
        Set<String> attachedAddons = new HashSet<String>();
        Map<String, String> conflictAddons = new HashMap<String, String>();
        for (V addon : mAddonsSet) {
            Class<? extends IAddon> clazz = addon.getParent().getClass();
            final String clazzName = clazz.getName();
            attachedAddons.add(clazzName);
            if (!clazz.isAnnotationPresent(Addon.class)) {
                continue;
            }
            Addon addonMeta = clazz.getAnnotation(Addon.class);
            for (String a : addonMeta.conflictStrings()) {
                conflictAddons.put(a, clazzName);
            }
            for (Class<? extends IAddon> a : addonMeta.conflict()) {
                conflictAddons.put(a.getName(), clazzName);
            }
        }
        StringBuilder builder = null;
        for (String addon : conflictAddons.keySet()) {
            if (attachedAddons.contains(addon)) {
                if (builder == null) {
                    builder = new StringBuilder();
                } else {
                    builder.append('\n');
                }
                builder.append(String.format(
                        "Found addon conflict: %s is cannot be attached together with %s",
                        addon, conflictAddons.get(addon)));
            }
        }
        if (builder != null) {
            throw AttachException.conflict(builder.toString());
        }
    }

    public void inhert(Collection<Class<? extends IAddon>> sourceClasses) {
        if (sourceClasses == null || sourceClasses.size() == 0) {
            return;
        }
        List<Class<? extends IAddon>> classes = new ArrayList<Class<? extends IAddon>>();
        for (Class<? extends IAddon> clazz : sourceClasses) {
            if (!clazz.isAnnotationPresent(Addon.class)) {
                continue;
            }
            Addon addon = clazz.getAnnotation(Addon.class);
            if (addon.inhert()) {
                classes.add(clazz);
            }
        }
        addon(classes);
    }

    public void inhert(IAddonAttacher<?> attacher) {
        inhert(attacher == null ? null : attacher.obtainAddonsList());
    }

    @Override
    public boolean isAddonAttached(Class<? extends IAddon> clazz) {
        return mAddons.containsKey(clazz);
    }

    @Override
    public void lockAttaching() {
        mLockAttaching = true;
    }

    @Override
    public Collection<Class<? extends IAddon>> obtainAddonsList() {
        return new ArrayList<Class<? extends IAddon>>(mAddons.keySet());
    }

    @Override
    public boolean performAddonAction(AddonCallback<V> callback) {
        if (mAddonsSet.size() == 0) {
            return callback.post();
        }
        if (mAddonsList == null) {
            mAddonsList = new ArrayList<V>(mAddonsSet);
        }
        final int addonCount = mAddonsList.size();
        for (int i = 0; i < addonCount; i++) {
            if (callback.action(mAddonsList.get(i))) {
                return true;
            }
        }
        return callback.post();
    }

    public void reset() {
        mAddons.clear();
        mAddonsSet.clear();
        mAddonsList = null;
        mLockAttaching = false;
    }
}


text:
/**
 * LessonUser.js
 *
 * @description :: TODO: You might write a short summary of how this model works and what it represents here.
 * @docs        :: http://sailsjs.org/documentation/concepts/models-and-orm/models
 */

module.exports = {

  attributes: {
        userID: {type:'string', required: true},
        groupID: {type: 'string',required: true},
  }
};


text:
#import "NSObject-Protocol.h"

@protocol UICollectionViewDataSource <NSObject>
- (id)collectionView:(id)arg1 cellForItemAtIndexPath:(id)arg2;
- (long long)collectionView:(id)arg1 numberOfItemsInSection:(long long)arg2;

@optional
- (id)collectionView:(id)arg1 viewForSupplementaryElementOfKind:(id)arg2 atIndexPath:(id)arg3;
- (long long)numberOfSectionsInCollectionView:(id)arg1;
@end


text:
package org.sparkcommerce.common.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sparkcommerce.common.locale.domain.Locale;
import org.sparkcommerce.common.locale.service.LocaleService;
import org.sparkcommerce.common.util.SCRequestUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Responsible for returning the Locale to use for the current request.
 *
 * @author jdasari
 */
@Component("blLocaleResolver")
public class SparkLocaleResolverImpl implements SparkLocaleResolver {
    private final Log LOG = LogFactory.getLog(SparkLocaleResolverImpl.class);

    /**
     * Parameter/Attribute name for the current language
     */
    public static String LOCALE_VAR = "blLocale";

    /**
     * Parameter/Attribute name for the current language
     */
    public static String LOCALE_CODE_PARAM = "blLocaleCode";

    /**
     * Attribute indicating that the LOCALE was pulled from session.   Other filters may want to
     * behave differently if this is the case.
     */
    public static String LOCALE_PULLED_FROM_SESSION = "blLocalePulledFromSession";

    @Resource(name = "blLocaleService")
    private LocaleService localeService;

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        return resolveLocale(new ServletWebRequest(request));
    }

    @Override
    public Locale resolveLocale(WebRequest request) {
        Locale locale = null;

        // First check for request attribute
        locale = (Locale) request.getAttribute(LOCALE_VAR, WebRequest.SCOPE_REQUEST);

        // Second, check for a request parameter
        if (locale == null && SCRequestUtils.getURLorHeaderParameter(request, LOCALE_CODE_PARAM) != null) {
            String localeCode = SCRequestUtils.getURLorHeaderParameter(request, LOCALE_CODE_PARAM);
            locale = localeService.findLocaleByCode(localeCode);
            if (SCRequestUtils.isOKtoUseSession(request)) {
                request.removeAttribute(SparkCurrencyResolverImpl.CURRENCY_VAR, WebRequest.SCOPE_GLOBAL_SESSION);
            }
            if (LOG.isTraceEnabled()) {
                LOG.trace("Attempt to find locale by param " + localeCode + " resulted in " + locale);
            }
        }

        // Third, check the session
        if (locale == null && SCRequestUtils.isOKtoUseSession(request)) {
            locale = (Locale) request.getAttribute(LOCALE_VAR, WebRequest.SCOPE_GLOBAL_SESSION);
            if (LOG.isTraceEnabled()) {
                LOG.trace("Attempt to find locale from session resulted in " + locale);
            }

            if (locale != null) {
                request.setAttribute(LOCALE_PULLED_FROM_SESSION, Boolean.TRUE, WebRequest.SCOPE_REQUEST);
            }

        }

        // Finally, use the default
        if (locale == null) {
            locale = localeService.findDefaultLocale();
            if (SCRequestUtils.isOKtoUseSession(request)) {
                request.removeAttribute(SparkCurrencyResolverImpl.CURRENCY_VAR, WebRequest.SCOPE_GLOBAL_SESSION);
            }
            if (LOG.isTraceEnabled()) {
                LOG.trace("Locale set to default locale " + locale);
            }
        }

        // Set the default locale to override Spring's cookie resolver
        request.setAttribute(LOCALE_VAR, locale, WebRequest.SCOPE_REQUEST);
        java.util.Locale javaLocale = SparkRequestContext.convertLocaleToJavaLocale(locale);
        request.setAttribute(CookieLocaleResolver.LOCALE_REQUEST_ATTRIBUTE_NAME, javaLocale, WebRequest.SCOPE_REQUEST);

        if (SCRequestUtils.isOKtoUseSession(request)) {
            request.setAttribute(LOCALE_VAR, locale, WebRequest.SCOPE_GLOBAL_SESSION);
        }
        return locale;
    }
}


text:
__all__ = ['filter', 'multimer', 'sites']

import nextgen4b.process.filter
import nextgen4b.process.multimer
import nextgen4b.process.sites


text:
/**
 * @author Igor V. Stolyarov
 * Created on 13.03.2006
 *
 */
package org.apache.harmony.awt.gl.image;

public interface DataBufferListener {

    void dataChanged();
    void dataTaken();
    void dataReleased();

}


text:
package microsoft.exchange.webservices.data;

/**
 * The Class ServiceRequestException.
 */
public class ServiceRequestException extends ServiceRemoteException {

  /**
   * Constant serialized ID used for compatibility.
   */
  private static final long serialVersionUID = 1L;

  /**
   * ServiceRequestException Constructor.
   */
  public ServiceRequestException() {
    super();
  }

  /**
   * ServiceRequestException Constructor.
   *
   * @param message the message
   */
  public ServiceRequestException(String message) {
    super(message);
  }

  /**
   * ServiceRequestException Constructor.
   *
   * @param message        the message
   * @param innerException the inner exception
   */
  public ServiceRequestException(String message, Exception innerException) {
    super(message, innerException);
  }
}


text:
{{ if $.Site.Params.googleAnalyticsTrackingId }}
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-3687044-6"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', '{{ $.Site.Params.googleAnalyticsTrackingId }}');
</script>
{{ end }}


text:
@implementation ClassificationEntry

- (id)initWithName:(NSString *)categoryName andProbability:(NSNumber *)guessProbability {
    self = [super init];
    if (self) {
        self.name = categoryName;
        self.probability = guessProbability;
    }
    return self;
}

- (NSString *)getPercentage
{
    return [NSString stringWithFormat:@"%.1f%%", [self.probability floatValue]*100];
}

- (NSComparisonResult)compare:(ClassificationEntry *)anotherGuess
{
    return [anotherGuess.probability compare:self.probability];
}

- (double)probabilityAsDouble
{
    return self.probability == nil ? 0 : [self.probability doubleValue];
}

@end


text:
function percept = populateInputsOutputs(percept)
%

%have set up the basic parameters now generate a set of gaussian curves.
[percept.Intervals, percept.MemoryCurves] = getFadingGaussians(percept);
%and the corresponding expected outputs
percept.ATOMOutputs =    ATOMrepresentation(percept.Intervals',percept.outputWidth,percept.minInterval, percept.maxInterval);
percept.BODYOutputs = BODYMapRepresentation(percept.Intervals',percept.outputWidth,percept.minInterval, percept.maxInterval,false,percept.useBODYBinaryOut);


text:
/**
 * Created by dsky on 2017/3/22.
 */
const fs = require('fs'),
    path = require('path'),
    StyleLintPlugin = require('stylelint-webpack-plugin'),
    webpack = require('webpack'),
    webpackConf = require('./webpack.dev.conf'),
    express = require('express'),
    app = express(),
    compiler = webpack(webpackConf),
    devMiddleware = require('webpack-dev-middleware')(compiler, {
        publicPath: webpackConfig.output.publicPath,
        quite: true
    }),
    hotMiddleware = require('webpack-hot-middleware')(compiler, {
        log: () => {}
    }),
    config = require('../config');
// get filePath

//get floder path
const filePath = JSON.parse(fs.readFileSync('./file.json', 'utf8'));
const buildCss = filePath.build.css,
    buildJs = filePath.build.js,
    buildImg = filePath.build.img,
    distCss = filePath.dist.css,
    distImg = filePath.dist.img,
    distJs = filePath.dist.js;

// mkdir fun
const mkdirSync = function (path) {
    if(path){
        try {
            fs.mkdirSync(path);
        } catch(e) {
            if ( e.code != 'EEXIST' ) throw e;
        }
    }
};

const mkdirpSync = function (dirpath) {
    if(dirpath){
        const parts = dirpath.split(path.sep);
        const len = parts.length;
        for( let i = 1; i <= len ; i++ ) {
            mkdirSync( path.join.apply(null, parts.slice(0, i)) );
        }
    }
};
// creat floder
mkdirpSync(distCss);
mkdirpSync(distImg);
mkdirpSync(distJs);


text:
<!doctype html>

    <title>Textarea inside draggable element</title>

Press your mouse button down on the orange block and drag downwards. It may optionally focus the dummy text. Use your mouse to select part of the dummy text, moving the mouse vertically and horizontally. It should select the text. Try to drag the input's scrollbar thumb. It should not drag the block or text in any case.

<textarea rows="5" cols="50" wrap="off">Dummy text
Dummy text
Dummy text
Dummy text
Dummy text
Dummy text
Dummy text
Dummy text
Dummy text
Dummy text
Dummy text
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</textarea>


text:
import { ServiceConfiguration } from 'meteor/service-configuration';

const env = process.env.NODE_ENV || 'development';

export default function () {
  // Heroku service configuration
  if (env === 'heroku') {
    ServiceConfiguration.configurations.update(
      { service: 'twitter' },
      {
        service: 'twitter',
        consumerKey: 'herokutwitterKey',
        loginStyle: 'popup',
        secret: 'herokutwitterSecret'
      },
      { upsert: true }
    );

    ServiceConfiguration.configurations.update(
      { service: 'facebook' },
      {
        service: 'facebook',
        appId: 'herokufacebookKey',
        secret: 'herokufacebookSecret'
      },
      { upsert: true}
    );

    ServiceConfiguration.configurations.update(
      { service: 'google' },
      {
        service: 'google',
        clientId: 'herokugoogleKey',
        secret: 'herokugoogleSecret'
      },
      { upsert: true}
    );

  // Default service Configuration
  } else {
    ServiceConfiguration.configurations.update(
      { service: 'twitter' },
      {
        service: 'twitter',
        consumerKey: 'twitterKey',
        loginStyle: 'popup',
        secret: 'twitterSecret'
      },
      { upsert: true }
    );

    ServiceConfiguration.configurations.update(
      { service: 'facebook' },
      {
        service: 'facebook',
        appId: 'facebookKey',
        secret: 'facebookSecret'
      },
      { upsert: true}
    );

    ServiceConfiguration.configurations.update(
      { service: 'google' },
      {
        service: 'google',
        clientId: 'googleKey',
        secret: 'googleSecret'
      },
      { upsert: true}
    );
  }

}


text:
<?php

namespace DataSift\Storyplayer\Injectables;

use DataSift\Storyplayer\Cli\StaticConfigManager;

/**
 * support for Storyplayer's static config file manager
 *
 * @category  Libraries
 * @package   Storyplayer/Injectables
 * @author    Stuart Herbert <stuart.herbert@datasift.com>
 * @copyright 2011-present Mediasift Ltd www.datasift.com
 * @license   http://www.opensource.org/licenses/bsd-license.php  BSD License
 * @link      http://datasift.github.io/storyplayer
 */
trait StaticConfigManagerSupport
{
    public $staticConfigManager;

    public function initStaticConfigManagerSupport()
    {
        // create an object to manage the static config
        $this->staticConfigManager = new StaticConfigManager;

        // all done
        return $this->staticConfigManager;
    }
}


text:
using AbstractFactory.Entities.Enums;

namespace AbstractFactory.Abstract
{
	public interface IWorkplaceEquipment
	{
		/// <summary>
		/// The model of office equipment.
		/// </summary>
		string Model { get; }

		/// <summary>
		/// The vendor of office equipment.
		/// </summary>
		Company Vendor { get; }

		/// <summary>
		/// The price of office equipment.
		/// </summary>
		decimal Price { get; }
	}
}


text:
@import QuartzCore;

@implementation X_VIEW (Helpers)

//-(void)setBackgroundColour:(NSColor *)backgroundColour
//{
//	self.wantsLayer = YES;
//	self.layer.backgroundColor = backgroundColour.CGColor;
//}
//
//-(NSColor *)backgroundColour
//{
//	NSColor* colour = [NSColor colorWithCGColor:self.layer.backgroundColor];
//
//	if (!colour)
//	{
//		colour = [NSColor clearColor];
//	}
//
//	return colour;
//
//}

@end


text:
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;

namespace winerack.Logic {
	public class BlobHandler {

		#region Constructor

		public BlobHandler(string imageDirectory) {
			this.imageDirectory = imageDirectory;

			var connectionString = ConfigurationManager.ConnectionStrings["AzureJobsStorage"].ConnectionString;
			storageAccount = CloudStorageAccount.Parse(connectionString);

			CloudBlobClient client = storageAccount.CreateCloudBlobClient();
			CloudBlobContainer container = client.GetContainerReference(imageDirectory);
			container.CreateIfNotExists();
			container.SetPermissions(new BlobContainerPermissions {
				PublicAccess = BlobContainerPublicAccessType.Blob
			});
		}

		#endregion Constructor

		#region Declarations

		string imageDirectory;

		CloudStorageAccount storageAccount;

		#endregion Declarations

		#region Public Methods

		public Guid? UploadImage(HttpPostedFileBase file, IList<Logic.ImageSize> sizes) {
			CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
			CloudBlobContainer container = blobClient.GetContainerReference(imageDirectory);

			if (file != null) {
				var name = Guid.NewGuid();
				string filename;
				CloudBlockBlob blockBlob;

				// Save the original
				filename = name.ToString() + "_o.jpg";
				blockBlob = container.GetBlockBlobReference(filename);
				blockBlob.UploadFromStream(file.InputStream);

				// Handle each size
				foreach (var size in sizes) {
					MemoryStream thumb;
					if (size.Crop) {
						thumb = Images.ResizeAndCrop(file.InputStream, size.MaxWidth, size.MaxHeight, true);
					} else {
						thumb = Images.Resize(file.InputStream, size.MaxWidth, size.MaxHeight, true, false);
					}

					filename = name.ToString() + "_" + size.Suffix + ".jpg";

					blockBlob = container.GetBlockBlobReference(filename);
					blockBlob.UploadFromStream(thumb);
				}

				return name;
			}

			return null;
		}

		#endregion Public Methods

	}
}


text:
#include <utility>
#include "util/lazy_list_fn.h"
#include "util/sstream.h"
#include "util/name_map.h"
#include "util/sexpr/option_declarations.h"
#include "kernel/for_each_fn.h"
#include "kernel/replace_fn.h"
#include "kernel/instantiate.h"
#include "kernel/abstract.h"
#include "kernel/error_msgs.h"
#include "kernel/type_checker.h"
#include "library/reducible.h"
#include "library/kernel_bindings.h"
#include "library/unifier.h"
#include "library/occurs.h"
#include "library/constants.h"
#include "library/metavar_closure.h"
#include "library/type_util.h"
#include "library/local_context.h"
#include "library/class_instance_synth.h"
#include "library/tactic/expr_to_tactic.h"
#include "library/tactic/apply_tactic.h"

#ifndef LEAN_DEFAULT_APPLY_CLASS_INSTANCE
#define LEAN_DEFAULT_APPLY_CLASS_INSTANCE true
#endif

namespace lean {
static name * g_apply_class_instance = nullptr;
bool get_apply_class_instance(options const & opts) {
    return opts.get_bool(*g_apply_class_instance, LEAN_DEFAULT_APPLY_CLASS_INSTANCE);
}

/**
    \brief Given a sequence metas: <tt>(?m_1 ...) (?m_2 ... ) ... (?m_k ...)</tt>,
    we say ?m_i is "redundant" if it occurs in the type of some ?m_j.
    This procedure removes from metas any redundant element.
*/
static void remove_redundant_metas(buffer<expr> & metas) {
    buffer<expr> mvars;
    for (expr const & m : metas)
        mvars.push_back(get_app_fn(m));
    unsigned k = 0;
    for (unsigned i = 0; i < metas.size(); i++) {
        bool found = false;
        for (unsigned j = 0; j < metas.size(); j++) {
            if (j != i) {
                if (occurs(mvars[i], mlocal_type(mvars[j]))) {
                    found = true;
                    break;
                }
            }
        }
        if (!found) {
            metas[k] = metas[i];
            k++;
        }
    }
    metas.shrink(k);
}

enum subgoals_action_kind { IgnoreSubgoals, AddRevSubgoals, AddSubgoals, AddAllSubgoals };

enum add_meta_kind { DoNotAdd, AddDiff, AddAll };

static proof_state_seq apply_tactic_core(environment const & env, io_state const & ios, proof_state const & s,
                                         expr const & _e, buffer<constraint> & cs,
                                         add_meta_kind add_meta, subgoals_action_kind subgoals_action,
                                         optional<unifier_kind> const & uk = optional<unifier_kind>()) {
    goals const & gs = s.get_goals();
    if (empty(gs)) {
        throw_no_goal_if_enabled(s);
        return proof_state_seq();
    }
    bool class_inst   = get_apply_class_instance(ios.get_options());
    name_generator ngen = s.get_ngen();
    std::shared_ptr<type_checker> tc(mk_type_checker(env, ngen.mk_child()));
    goal  g           = head(gs);
    goals tail_gs     = tail(gs);
    expr  t           = g.get_type();
    expr  e           = _e;
    auto e_t_cs       = tc->infer(e);
    e_t_cs.second.linearize(cs);
    expr  e_t         = e_t_cs.first;
    buffer<expr> metas;
    local_context ctx;
    bool initialized_ctx = false;
    unifier_config cfg(ios.get_options());
    if (uk)
        cfg.m_kind = *uk;
    if (add_meta != DoNotAdd) {
        unsigned num_e_t = get_expect_num_args(*tc, e_t);
        if (add_meta == AddDiff) {
            unsigned num_t   = get_expect_num_args(*tc, t);
            if (num_t <= num_e_t)
                num_e_t -= num_t;
            else
                num_e_t = 0;
        } else {
            lean_assert(add_meta == AddAll);
        }
        for (unsigned i = 0; i < num_e_t; i++) {
            auto e_t_cs = tc->whnf(e_t);
            e_t_cs.second.linearize(cs);
            e_t        = e_t_cs.first;
            expr meta;
            if (class_inst && binding_info(e_t).is_inst_implicit()) {
                if (!initialized_ctx) {
                    ctx = g.to_local_context();
                    initialized_ctx = true;
                }
                bool use_local_insts = true;
                bool is_strict       = false;
                auto mc = mk_class_instance_elaborator(
                    env, ios, ctx, ngen.next(), optional<name>(),
                    use_local_insts, is_strict,
                    some_expr(head_beta_reduce(binding_domain(e_t))), e.get_tag(), cfg, nullptr);
                meta    = mc.first;
                cs.push_back(mc.second);
            } else {
                meta  = g.mk_meta(ngen.next(), head_beta_reduce(binding_domain(e_t)));
            }
            e          = mk_app(e, meta);
            e_t        = instantiate(binding_body(e_t), meta);
            metas.push_back(meta);
        }
    }
    metavar_closure cls(t);
    cls.mk_constraints(s.get_subst(), justification());
    pair<bool, constraint_seq> dcs = tc->is_def_eq(t, e_t);
    if (!dcs.first) {
        throw_tactic_exception_if_enabled(s, [=](formatter const & fmt) {
                format r = format("invalid 'apply' tactic, failed to unify");
                r       += pp_indent_expr(fmt, t);
                r       += compose(line(), format("with"));
                r       += pp_indent_expr(fmt, e_t);
                return r;
            });
        return proof_state_seq();
    }
    dcs.second.linearize(cs);
    unify_result_seq rseq = unify(env, cs.size(), cs.data(), ngen.mk_child(), s.get_subst(), cfg);
    list<expr> meta_lst   = to_list(metas.begin(), metas.end());
    return map2<proof_state>(rseq, [=](pair<substitution, constraints> const & p) -> proof_state {
            substitution const & subst    = p.first;
            constraints const & postponed = p.second;
            name_generator new_ngen(ngen);
            substitution new_subst = subst;
            expr new_e = new_subst.instantiate_all(e);
            assign(new_subst, g, new_e);
            goals new_gs = tail_gs;
            if (subgoals_action != IgnoreSubgoals) {
                buffer<expr> metas;
                for (auto m : meta_lst) {
                    if (!new_subst.is_assigned(get_app_fn(m)))
                        metas.push_back(m);
                }
                if (subgoals_action == AddRevSubgoals) {
                    for (unsigned i = 0; i < metas.size(); i++)
                        new_gs = cons(goal(metas[i], new_subst.instantiate_all(tc->infer(metas[i]).first)), new_gs);
                } else {
                    lean_assert(subgoals_action == AddSubgoals || subgoals_action == AddAllSubgoals);
                    if (subgoals_action == AddSubgoals)
                        remove_redundant_metas(metas);
                    unsigned i = metas.size();
                    while (i > 0) {
                        --i;
                        new_gs = cons(goal(metas[i], new_subst.instantiate_all(tc->infer(metas[i]).first)), new_gs);
                    }
                }
            }
            return proof_state(s, new_gs, new_subst, new_ngen, postponed);
        });
}

proof_state_seq apply_tactic_core(environment const & env, io_state const & ios, proof_state const & s, expr const & e, constraint_seq const & cs) {
    buffer<constraint> tmp_cs;
    cs.linearize(tmp_cs);
    return apply_tactic_core(env, ios, s, e, tmp_cs, AddDiff, AddSubgoals);
}

proof_state_seq fapply_tactic_core(environment const & env, io_state const & ios, proof_state const & s, expr const & e, constraint_seq const & cs) {
    buffer<constraint> tmp_cs;
    cs.linearize(tmp_cs);
    return apply_tactic_core(env, ios, s, e, tmp_cs, AddDiff, AddAllSubgoals);
}

tactic apply_tactic_core(expr const & e, constraint_seq const & cs) {
    return tactic([=](environment const & env, io_state const & ios, proof_state const & s) {
            return apply_tactic_core(env, ios, s, e, cs);
        });
}

tactic apply_tactic_core(elaborate_fn const & elab, expr const & e, add_meta_kind add_meta, subgoals_action_kind k) {
    return tactic([=](environment const & env, io_state const & ios, proof_state const & s) {
            goals const & gs = s.get_goals();
            if (empty(gs)) {
                throw_no_goal_if_enabled(s);
                return proof_state_seq();
            }
            goal const & g      = head(gs);
            name_generator ngen = s.get_ngen();
            expr       new_e; substitution new_subst; constraints cs_;
            try {
                auto ecs = elab(g, ngen.mk_child(), e, none_expr(), s.get_subst(), false);
                std::tie(new_e, new_subst, cs_) = ecs;
                buffer<constraint> cs;
                to_buffer(cs_, cs);
                to_buffer(s.get_postponed(), cs);
                proof_state new_s(s, new_subst, ngen, constraints());
                return apply_tactic_core(env, ios, new_s, new_e, cs, add_meta, k);
            } catch (exception &) {
                if (s.report_failure())
                    throw;
                else
                    return proof_state_seq();
            }
        });
}

tactic apply_tactic(elaborate_fn const & elab, expr const & e) {
    return apply_tactic_core(elab, e, AddDiff, AddSubgoals);
}

tactic fapply_tactic(elaborate_fn const & elab, expr const & e) {
    return apply_tactic_core(elab, e, AddDiff, AddAllSubgoals);
}

tactic eapply_tactic(elaborate_fn const & elab, expr const & e) {
    return apply_tactic_core(elab, e, AddAll, AddSubgoals);
}

void initialize_apply_tactic() {
    g_apply_class_instance = new name{"apply", "class_instance"};
    register_bool_option(*g_apply_class_instance, LEAN_DEFAULT_APPLY_CLASS_INSTANCE,
                         "(apply tactic) if true apply tactic uses class-instances "
                         "resolution for instance implicit arguments");

    register_tac(get_tactic_apply_name(),
                 [](type_checker &, elaborate_fn const & fn, expr const & e, pos_info_provider const *) {
                     check_tactic_expr(app_arg(e), "invalid 'apply' tactic, invalid argument");
                     return apply_tactic(fn, get_tactic_expr_expr(app_arg(e)));
                 });

    register_tac(get_tactic_eapply_name(),
                 [](type_checker &, elaborate_fn const & fn, expr const & e, pos_info_provider const *) {
                     check_tactic_expr(app_arg(e), "invalid 'eapply' tactic, invalid argument");
                     return eapply_tactic(fn, get_tactic_expr_expr(app_arg(e)));
                 });

    register_tac(get_tactic_fapply_name(),
                 [](type_checker &, elaborate_fn const & fn, expr const & e, pos_info_provider const *) {
                     check_tactic_expr(app_arg(e), "invalid 'fapply' tactic, invalid argument");
                     return fapply_tactic(fn, get_tactic_expr_expr(app_arg(e)));
                 });
}

void finalize_apply_tactic() {
    delete g_apply_class_instance;
}
}


text:
#include "lullaby/systems/reticle/reticle_trail_system.h"

#include "mathfu/constants.h"
#include "lullaby/systems/render/render_system.h"
#include "lullaby/systems/transform/transform_system.h"
#include "lullaby/util/math.h"
#include "lullaby/util/mathfu_fb_conversions.h"
#include "lullaby/util/time.h"
#include "lullaby/util/trace.h"
#include "lullaby/util/vertex.h"

namespace lull {

const HashValue kReticleTrailDef = Hash("ReticleTrailDef");
const int kNumVerticesPerTrailQuad = 4;
const int kNumIndicesPerTrailQuad = 6;
const float kMaxDeltaTime = 0.05f;

ReticleTrailSystem::ReticleTrail::ReticleTrail(Entity e)
    : Component(e),
      default_color(mathfu::kZeros4f),
      average_trail_length(0),
      trail_length(0),
      curve_samples(0),
      quad_size(0.f),
      average_speed(0.f) {}

ReticleTrailSystem::ReticleTrailSystem(Registry* registry) : System(registry) {
  RegisterDef(this, kReticleTrailDef);
  RegisterDependency<RenderSystem>(this);
  RegisterDependency<TransformSystem>(this);
}

void ReticleTrailSystem::Create(Entity entity, HashValue type, const Def* def) {
  CHECK_NE(def, nullptr);

  if (type == kReticleTrailDef) {
    const auto* data = ConvertDef<ReticleTrailDef>(def);
    CreateReticleTrail(entity, data);
  } else {
    DCHECK(false) << "Unsupported ComponentDef type: " << type;
  }
}

void ReticleTrailSystem::CreateReticleTrail(Entity entity,
                                            const ReticleTrailDef* data) {
  reticle_trail_.reset(new ReticleTrail(entity));
  reticle_trail_->curve_samples = data->curve_samples();
  reticle_trail_->average_trail_length = data->average_trail_length();
  reticle_trail_->average_speed = data->average_speed();
  reticle_trail_->quad_size = data->quad_size();
  MathfuVec4FromFbColor(data->default_color(), &reticle_trail_->default_color);

  reticle_trail_->position_history.resize(4, mathfu::kZeros3f);
  reticle_trail_->trail_positions.resize(reticle_trail_->average_trail_length,
                                         mathfu::kZeros3f);
}

void ReticleTrailSystem::Destroy(Entity entity) {
  if (reticle_trail_ && reticle_trail_->GetEntity() == entity) {
    reticle_trail_.reset();
  }
}

void ReticleTrailSystem::AdvanceFrame(const Clock::duration& delta_time) {
  LULLABY_CPU_TRACE_CALL();
  if (!reticle_trail_) {
    return;
  }

  auto* transform_system = registry_->Get<TransformSystem>();
  Sqt sqt = *(transform_system->GetSqt(reticle_trail_->GetEntity()));

  // Save the positions of the current frame and last three frames in order to
  // create our cubic interpolated curve.
  if (reticle_trail_->position_history.size() ==
      static_cast<uint16_t>(reticle_trail_->curve_samples)) {
    reticle_trail_->position_history.pop_front();
  }
  reticle_trail_->position_history.push_back(sqt.translation);

  // If the last frame was more than kMaxDeltaTime ago, don't draw a trail
  if (SecondsFromDuration(delta_time) > kMaxDeltaTime) {
    reticle_trail_->trail_length = 1;
  } else {
    // Attenuate the number of reticles drawn based on the speed of the current
    // reticle
    const float length = (reticle_trail_->position_history[3] -
                          reticle_trail_->position_history[2])
                             .Length();
    const float lengthOverSpeed = length / reticle_trail_->average_speed;
    const float currSpeedLength =
        lengthOverSpeed *
        static_cast<float>(reticle_trail_->average_trail_length);

    reticle_trail_->trail_length = 1 + static_cast<int>(floor(currSpeedLength));
  }

  reticle_trail_->trail_positions.resize(reticle_trail_->trail_length,
                                         sqt.translation);

  UpdateTrailMesh(sqt);
}

void ReticleTrailSystem::UpdateTrailMesh(Sqt sqt) {
  auto* render_system = registry_->Get<RenderSystem>();

  const mathfu::vec3 reticle_pos = sqt.translation;

  const mathfu::quat reticle_rot = sqt.rotation;

  mathfu::vec4 reticle_color = reticle_trail_->default_color;
  render_system->GetUniform(reticle_trail_->GetEntity(), "color", 4,
                            &reticle_color[0]);

  auto trail_fn = [this, render_system, reticle_pos, reticle_color,
                   reticle_rot](MeshData* mesh) {
    uint16_t index_base = 0;

    for (int i = 0; i < reticle_trail_->trail_length; i++) {
      // Draw a trail of reticles from the last frame to current frame position,
      // using a cubic spline to interpolate.
      reticle_trail_->trail_positions[i] = EvaluateCubicSpline(
          (static_cast<float>(i + 1)) /
              static_cast<float>(reticle_trail_->trail_length),
          reticle_trail_->position_history[0],
          reticle_trail_->position_history[1],
          reticle_trail_->position_history[2], reticle_pos);

      VertexPTC v;

      reticle_trail_->trail_positions[i] =
          reticle_rot.Inverse() *
          (reticle_trail_->trail_positions[i] - reticle_pos);

      float x = reticle_trail_->trail_positions[i][0];
      float y = reticle_trail_->trail_positions[i][1];
      float z = reticle_trail_->trail_positions[i][2];
      float w = reticle_trail_->quad_size;
      float h = reticle_trail_->quad_size;

      mathfu::vec4 color = reticle_color;

      // Set the opacity of each reticle in the trail such that when the reticle
      // is still and they are all drawn on top of each other, they appear to be
      // a full opacity single reticle.
      color[3] *= 1.00f / static_cast<float>(reticle_trail_->trail_length);
      v.color = Color4ub(color);
      v.u0 = 0.0f;
      v.v0 = 0.0f;
      mathfu::vec3 vert = mathfu::vec3(-.5f * w, -.5f * h, 0.0f);
      v.x = x + vert[0];
      v.y = y + vert[1];
      v.z = z + vert[2];
      mesh->AddVertex(v);

      v.u0 = 1.0f;
      vert = mathfu::vec3(.5f * w, -.5f * h, 0.0f);
      v.x = x + vert[0];
      v.y = y + vert[1];
      v.z = z + vert[2];
      mesh->AddVertex(v);

      v.v0 = 1.0f;
      vert = mathfu::vec3(.5f * w, .5f * h, 0.0f);
      v.x = x + vert[0];
      v.y = y + vert[1];
      v.z = z + vert[2];
      mesh->AddVertex(v);

      v.u0 = 0.0f;
      vert = mathfu::vec3(-.5f * w, .5f * h, 0.0f);
      v.x = x + vert[0];
      v.y = y + vert[1];
      v.z = z + vert[2];
      mesh->AddVertex(v);

      mesh->AddIndex(static_cast<MeshData::Index>(index_base + 0));
      mesh->AddIndex(static_cast<MeshData::Index>(index_base + 1));
      mesh->AddIndex(static_cast<MeshData::Index>(index_base + 2));
      mesh->AddIndex(static_cast<MeshData::Index>(index_base + 2));
      mesh->AddIndex(static_cast<MeshData::Index>(index_base + 3));
      mesh->AddIndex(static_cast<MeshData::Index>(index_base + 0));

      index_base = static_cast<MeshData::Index>(index_base + 4);
    }
  };

  render_system->UpdateDynamicMesh(
      reticle_trail_->GetEntity(), MeshData::PrimitiveType::kTriangles,
      VertexPTC::kFormat,
      kNumVerticesPerTrailQuad * reticle_trail_->trail_length,
      kNumIndicesPerTrailQuad * reticle_trail_->trail_length, trail_fn);
}

}  // namespace lull


text:
@(org: com.bryzek.apidoc.api.v0.models.Organization,
  app: com.bryzek.apidoc.api.v0.models.Application,
  version: String,
  service: com.bryzek.apidoc.spec.v0.models.Service,
  typeName: String)

@Html(lib.TypeLabel(org, app, version, service, typeName).link)


text:
package org.jrimum.bopepo.campolivre;

import org.jrimum.bopepo.BancosSuportados;
import org.jrimum.domkee.financeiro.banco.febraban.Agencia;
import org.jrimum.domkee.financeiro.banco.febraban.Carteira;
import org.jrimum.domkee.financeiro.banco.febraban.NumeroDaConta;
import org.junit.Before;

/**
 *

 * Teste unitário do campo livre do banco itaú para carteiras especiais
 *

 *
 * @author Gilmar P.S.L
 * @author Misael Barreto
 * @author Rômulo Augusto
 * @author Nordeste Fomento Mercantil
 *
 * @since 0.2
 *
 * @version 0.2
 *
 */
public class TestCLItauComCarteirasEspeciais extends AbstractCampoLivreBaseTest<CLItauComCarteirasEspeciais> {

	@Before
	public void setUp(){

		titulo.getContaBancaria().setBanco(BancosSuportados.BANCO_ITAU.create());
		titulo.getContaBancaria().setAgencia(new Agencia(57, "1"));
		titulo.getContaBancaria().setCarteira(new Carteira(198));
		titulo.getContaBancaria().setNumeroDaConta(new NumeroDaConta(12345));
		titulo.setNumeroDoDocumento("1234567");
		titulo.setNossoNumero("12345678");

		createCampoLivreToTest();

		setCampoLivreEsperadoComoString("1981234567812345671234580");
	}

}


text:
package zttc.itat.user;

import junit.framework.Assert;
import org.apache.shiro.authz.UnauthorizedException;
import org.junit.Test;

import java.util.Arrays;

/**
 *
User: Zhang Kaitao
 *
Date: 14-1-26
 *
Version: 1.0
 */
public class RoleTest extends BaseTest {

    @Test
    public void testHasRole() {
        login("classpath:shiro-role.ini", "zhang", "123");
        //判断拥有角色:role1
        Assert.assertTrue(subject().hasRole("role1"));
        //判断拥有角色:role1 and role2
        Assert.assertTrue(subject().hasAllRoles(Arrays.asList("role1", "role2")));
        //判断拥有角色:role1 and role2 and !role3
        boolean[] result = subject().hasRoles(Arrays.asList("role1", "role2", "role3"));
        Assert.assertEquals(true, result[0]);
        Assert.assertEquals(true, result[1]);
        Assert.assertEquals(false, result[2]);
    }

    @Test(expected = UnauthorizedException.class)
    public void testCheckRole() {
        login("classpath:shiro-role.ini", "zhang", "123");
        //断言拥有角色:role1
        subject().checkRole("role1");
        //断言拥有角色:role1 and role3 失败抛出异常
        subject().checkRoles("role1", "role3");
    }

}


text:
ACCESS_TOKEN = 'INSERT YOUR ACCESS TOKEN HERE'
# get your access token at this URL:
# https://stackexchange.com/oauth/dialog?client_id=2666&redirect_uri=http://keyboardfire.com/chatdump.html&scope=no_expiry
$root = 'http://stackexchange.com'
$chatroot = 'http://chat.stackexchange.com'
$room_number = 13215
site = 'codegolf'
# the default is configured for http://chat.stackexchange.com/rooms/13215/chatbot-room
email = 'INSERT YOUR EMAIL HERE'
password = 'INSERT YOUR PASSWORD HERE'

require 'rubygems'
require 'mechanize'
require 'logger'
require 'faye/websocket'
require 'eventmachine'
require 'json'
require 'cgi'
require 'net/http'
puts 'requires finished'

loop{begin

$agent = Mechanize.new
$agent.agent.http.verify_mode = OpenSSL::SSL::VERIFY_NONE
#$agent.log = Logger.new STDOUT

login_form = $agent.get('https://openid.stackexchange.com/account/login').forms.first
login_form.email = email
login_form.password = password
$agent.submit login_form, login_form.buttons.first
puts 'logged in with SE openid'

meta_login_form = $agent.get($root + '/users/login').forms.last
meta_login_form.openid_identifier = 'https://openid.stackexchange.com/'
$agent.submit meta_login_form, meta_login_form.buttons.last
puts 'logged in to root'

chat_login_form = $agent.get('http://stackexchange.com/users/chat-login').forms.last
$agent.submit chat_login_form, chat_login_form.buttons.last
puts 'logged in to chat'

$fkey = $agent.get($chatroot + '/chats/join/favorite').forms.last.fkey
puts 'found fkey'

def send_message text
  loop {
    begin
      resp = $agent.post("#{$chatroot}/chats/#{$room_number}/messages/new", [['text', text], ['fkey', $fkey]]).body
      success = JSON.parse(resp)['id'] != nil
      return if success
    rescue Mechanize::ResponseCodeError => e
      puts "Error: #{e.inspect}"
    end
    puts 'sleeping'
    sleep 3
  }
end

send_message $ERR ? "An unknown error occurred. Bot restarted." : "Bot initialized."
puts 'bot initialized'

last_date = 0
loop {
  uri = URI.parse "https://api.stackexchange.com/2.2/events?pagesize=100&since=#{last_date}&site=#{site}&filter=!9WgJfejF6&key=thqRkHjZhayoReI9ARAODA((&access_token=#{ACCESS_TOKEN}"
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  data = JSON.parse http.get(uri.request_uri).body
  events = data['items']

  data['items'].each do |event|
    last_date = [last_date, event['creation_date'].to_i + 1].max
    #send_message "#{event['event_type'].sub('_', " #{event['event_id']} ").capitalize}: [`#{event['excerpt'].gsub(/\s/, ' ')}`](#{event['link']})"
    unless ['post_edited'].include? event['event_type']
      send_message event['link']
    end
  end

  puts "#{data['quota_remaining']}/#{data['quota_max']} quota remaining"
  sleep(40 + (data['backoff'] || 0).to_i) # add backoff time if any, just in case
}

=begin
Old thing that dumps *all* activity
EM.run {
  ws = Faye::WebSocket::Client.new('ws://sockets.ny.stackexchange.com')

  ws.on :open do |event|
    ws.send('155-questions-active')
  end

  ws.on :message do |event|
    data = JSON.parse JSON.parse(event.data)['data']
    p data
    send_message "Question on #{data['apiSiteParameter']}: [#{data['titleEncodedFancy']}](#{data['url']}) (#{data['tags'] * ','})"
  end
}
=end

rescue => e
  $ERR = e
  p e
end}


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace JustPressPlay.UnitTests.Controllers
{
    [TestClass]
    public class TestQuestsController
    {
        [TestMethod]
        public void TestMethod1()
        {
        }
    }
}