text:
namespace gl
{

void GL_APIENTRY BeginQueryEXT(GLenum target, GLuint id)
{
    EVENT("(GLenum target = 0x%X, GLuint %d)", target, id);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        if (!ValidateBeginQuery(context, target, id))
        {
            return;
        }

        Error error = context->beginQuery(target, id);
        if (error.isError())
        {
            context->recordError(error);
            return;
        }
    }
}

void GL_APIENTRY DeleteFencesNV(GLsizei n, const GLuint* fences)
{
    EVENT("(GLsizei n = %d, const GLuint* fences = 0x%0.8p)", n, fences);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        if (n < 0)
        {
            context->recordError(Error(GL_INVALID_VALUE));
            return;
        }

        for (int i = 0; i < n; i++)
        {
            context->deleteFenceNV(fences[i]);
        }
    }
}

void GL_APIENTRY DeleteQueriesEXT(GLsizei n, const GLuint *ids)
{
    EVENT("(GLsizei n = %d, const GLuint *ids = 0x%0.8p)", n, ids);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        if (n < 0)
        {
            context->recordError(Error(GL_INVALID_VALUE));
            return;
        }

        for (int i = 0; i < n; i++)
        {
            context->deleteQuery(ids[i]);
        }
    }
}

void GL_APIENTRY DrawArraysInstancedANGLE(GLenum mode, GLint first, GLsizei count, GLsizei primcount)
{
    EVENT("(GLenum mode = 0x%X, GLint first = %d, GLsizei count = %d, GLsizei primcount = %d)", mode, first, count, primcount);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        if (!ValidateDrawArraysInstancedANGLE(context, mode, first, count, primcount))
        {
            return;
        }

        Error error = context->drawArrays(mode, first, count, primcount);
        if (error.isError())
        {
            context->recordError(error);
            return;
        }
    }
}

void GL_APIENTRY DrawElementsInstancedANGLE(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount)
{
    EVENT("(GLenum mode = 0x%X, GLsizei count = %d, GLenum type = 0x%X, const GLvoid* indices = 0x%0.8p, GLsizei primcount = %d)",
          mode, count, type, indices, primcount);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        RangeUI indexRange;
        if (!ValidateDrawElementsInstancedANGLE(context, mode, count, type, indices, primcount, &indexRange))
        {
            return;
        }

        Error error = context->drawElements(mode, count, type, indices, primcount, indexRange);
        if (error.isError())
        {
            context->recordError(error);
            return;
        }
    }
}

void GL_APIENTRY EndQueryEXT(GLenum target)
{
    EVENT("GLenum target = 0x%X)", target);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        if (!ValidateEndQuery(context, target))
        {
            return;
        }

        Error error = context->endQuery(target);
        if (error.isError())
        {
            context->recordError(error);
            return;
        }
    }
}

void GL_APIENTRY FinishFenceNV(GLuint fence)
{
    EVENT("(GLuint fence = %d)", fence);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        FenceNV *fenceObject = context->getFenceNV(fence);

        if (fenceObject == NULL)
        {
            context->recordError(Error(GL_INVALID_OPERATION));
            return;
        }

        if (fenceObject->isSet() != GL_TRUE)
        {
            context->recordError(Error(GL_INVALID_OPERATION));
            return;
        }

        fenceObject->finish();
    }
}

void GL_APIENTRY GenFencesNV(GLsizei n, GLuint* fences)
{
    EVENT("(GLsizei n = %d, GLuint* fences = 0x%0.8p)", n, fences);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        if (n < 0)
        {
            context->recordError(Error(GL_INVALID_VALUE));
            return;
        }

        for (int i = 0; i < n; i++)
        {
            fences[i] = context->createFenceNV();
        }
    }
}

void GL_APIENTRY GenQueriesEXT(GLsizei n, GLuint* ids)
{
    EVENT("(GLsizei n = %d, GLuint* ids = 0x%0.8p)", n, ids);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        if (n < 0)
        {
            context->recordError(Error(GL_INVALID_VALUE));
            return;
        }

        for (GLsizei i = 0; i < n; i++)
        {
            ids[i] = context->createQuery();
        }
    }
}

void GL_APIENTRY GetFenceivNV(GLuint fence, GLenum pname, GLint *params)
{
    EVENT("(GLuint fence = %d, GLenum pname = 0x%X, GLint *params = 0x%0.8p)", fence, pname, params);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        FenceNV *fenceObject = context->getFenceNV(fence);

        if (fenceObject == NULL)
        {
            context->recordError(Error(GL_INVALID_OPERATION));
            return;
        }

        if (fenceObject->isSet() != GL_TRUE)
        {
            context->recordError(Error(GL_INVALID_OPERATION));
            return;
        }

        switch (pname)
        {
          case GL_FENCE_STATUS_NV:
            {
                // GL_NV_fence spec:
                // Once the status of a fence has been finished (via FinishFenceNV) or tested and the returned status is TRUE (via either TestFenceNV
                // or GetFenceivNV querying the FENCE_STATUS_NV), the status remains TRUE until the next SetFenceNV of the fence.
                GLboolean status = GL_TRUE;
                if (fenceObject->getStatus() != GL_TRUE)
                {
                    Error error = fenceObject->test(&status);
                    if (error.isError())
                    {
                        context->recordError(error);
                        return;
                    }
                }
                *params = status;
                break;
            }

          case GL_FENCE_CONDITION_NV:
            {
                *params = static_cast<GLint>(fenceObject->getCondition());
                break;
            }

          default:
            {
                context->recordError(Error(GL_INVALID_ENUM));
                return;
            }
        }
    }
}

GLenum GL_APIENTRY GetGraphicsResetStatusEXT(void)
{
    EVENT("()");

    Context *context = GetGlobalContext();

    if (context)
    {
        return context->getResetStatus();
    }

    return GL_NO_ERROR;
}

void GL_APIENTRY GetQueryivEXT(GLenum target, GLenum pname, GLint *params)
{
    EVENT("GLenum target = 0x%X, GLenum pname = 0x%X, GLint *params = 0x%0.8p)", target, pname, params);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        if (!ValidQueryType(context, target))
        {
            context->recordError(Error(GL_INVALID_ENUM));
            return;
        }

        switch (pname)
        {
          case GL_CURRENT_QUERY_EXT:
            params[0] = context->getState().getActiveQueryId(target);
            break;

          default:
            context->recordError(Error(GL_INVALID_ENUM));
            return;
        }
    }
}

void GL_APIENTRY GetQueryObjectuivEXT(GLuint id, GLenum pname, GLuint *params)
{
    EVENT("(GLuint id = %d, GLenum pname = 0x%X, GLuint *params = 0x%0.8p)", id, pname, params);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        Query *queryObject = context->getQuery(id, false, GL_NONE);

        if (!queryObject)
        {
            context->recordError(Error(GL_INVALID_OPERATION));
            return;
        }

        if (context->getState().getActiveQueryId(queryObject->getType()) == id)
        {
            context->recordError(Error(GL_INVALID_OPERATION));
            return;
        }

        switch(pname)
        {
          case GL_QUERY_RESULT_EXT:
            {
                Error error = queryObject->getResult(params);
                if (error.isError())
                {
                    context->recordError(error);
                    return;
                }
            }
            break;

          case GL_QUERY_RESULT_AVAILABLE_EXT:
            {
                Error error = queryObject->isResultAvailable(params);
                if (error.isError())
                {
                    context->recordError(error);
                    return;
                }
            }
            break;

          default:
            context->recordError(Error(GL_INVALID_ENUM));
            return;
        }
    }
}

void GL_APIENTRY GetTranslatedShaderSourceANGLE(GLuint shader, GLsizei bufsize, GLsizei* length, GLchar* source)
{
    EVENT("(GLuint shader = %d, GLsizei bufsize = %d, GLsizei* length = 0x%0.8p, GLchar* source = 0x%0.8p)",
          shader, bufsize, length, source);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        if (bufsize < 0)
        {
            context->recordError(Error(GL_INVALID_VALUE));
            return;
        }

        Shader *shaderObject = context->getShader(shader);

        if (!shaderObject)
        {
            context->recordError(Error(GL_INVALID_OPERATION));
            return;
        }

        // Only returns extra info if ANGLE_GENERATE_SHADER_DEBUG_INFO is defined
        shaderObject->getTranslatedSourceWithDebugInfo(bufsize, length, source);
    }
}

void GL_APIENTRY GetnUniformfvEXT(GLuint program, GLint location, GLsizei bufSize, GLfloat* params)
{
    EVENT("(GLuint program = %d, GLint location = %d, GLsizei bufSize = %d, GLfloat* params = 0x%0.8p)",
          program, location, bufSize, params);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        if (!ValidateGetnUniformfvEXT(context, program, location, bufSize, params))
        {
            return;
        }

        Program *programObject = context->getProgram(program);
        ASSERT(programObject);

        programObject->getUniformfv(location, params);
    }
}

void GL_APIENTRY GetnUniformivEXT(GLuint program, GLint location, GLsizei bufSize, GLint* params)
{
    EVENT("(GLuint program = %d, GLint location = %d, GLsizei bufSize = %d, GLint* params = 0x%0.8p)",
          program, location, bufSize, params);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        if (!ValidateGetnUniformivEXT(context, program, location, bufSize, params))
        {
            return;
        }

        Program *programObject = context->getProgram(program);
        ASSERT(programObject);

        programObject->getUniformiv(location, params);
    }
}

GLboolean GL_APIENTRY IsFenceNV(GLuint fence)
{
    EVENT("(GLuint fence = %d)", fence);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        FenceNV *fenceObject = context->getFenceNV(fence);

        if (fenceObject == NULL)
        {
            return GL_FALSE;
        }

        // GL_NV_fence spec:
        // A name returned by GenFencesNV, but not yet set via SetFenceNV, is not the name of an existing fence.
        return fenceObject->isSet();
    }

    return GL_FALSE;
}

GLboolean GL_APIENTRY IsQueryEXT(GLuint id)
{
    EVENT("(GLuint id = %d)", id);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        return (context->getQuery(id, false, GL_NONE) != NULL) ? GL_TRUE : GL_FALSE;
    }

    return GL_FALSE;
}

void GL_APIENTRY ReadnPixelsEXT(GLint x, GLint y, GLsizei width, GLsizei height,
                                GLenum format, GLenum type, GLsizei bufSize,
                                GLvoid *data)
{
    EVENT("(GLint x = %d, GLint y = %d, GLsizei width = %d, GLsizei height = %d, "
          "GLenum format = 0x%X, GLenum type = 0x%X, GLsizei bufSize = 0x%d, GLvoid *data = 0x%0.8p)",
          x, y, width, height, format, type, bufSize, data);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        if (width < 0 || height < 0 || bufSize < 0)
        {
            context->recordError(Error(GL_INVALID_VALUE));
            return;
        }

        if (!ValidateReadPixelsParameters(context, x, y, width, height,
                                              format, type, &bufSize, data))
        {
            return;
        }

        Framebuffer *framebufferObject = context->getState().getReadFramebuffer();
        ASSERT(framebufferObject);

        Rectangle area(x, y, width, height);
        Error error = framebufferObject->readPixels(context->getState(), area, format, type, data);
        if (error.isError())
        {
            context->recordError(error);
            return;
        }
    }
}

void GL_APIENTRY RenderbufferStorageMultisampleANGLE(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height)
{
    EVENT("(GLenum target = 0x%X, GLsizei samples = %d, GLenum internalformat = 0x%X, GLsizei width = %d, GLsizei height = %d)",
        target, samples, internalformat, width, height);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        if (!ValidateRenderbufferStorageParametersANGLE(context, target, samples, internalformat,
            width, height))
        {
            return;
        }

        Renderbuffer *renderbuffer = context->getState().getCurrentRenderbuffer();
        Error error = renderbuffer->setStorageMultisample(samples, internalformat, width, height);
        if (error.isError())
        {
            context->recordError(error);
            return;
        }
    }
}

void GL_APIENTRY SetFenceNV(GLuint fence, GLenum condition)
{
    EVENT("(GLuint fence = %d, GLenum condition = 0x%X)", fence, condition);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        if (condition != GL_ALL_COMPLETED_NV)
        {
            context->recordError(Error(GL_INVALID_ENUM));
            return;
        }

        FenceNV *fenceObject = context->getFenceNV(fence);

        if (fenceObject == NULL)
        {
            context->recordError(Error(GL_INVALID_OPERATION));
            return;
        }

        Error error = fenceObject->set(condition);
        if (error.isError())
        {
            context->recordError(error);
            return;
        }
    }
}

GLboolean GL_APIENTRY TestFenceNV(GLuint fence)
{
    EVENT("(GLuint fence = %d)", fence);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        FenceNV *fenceObject = context->getFenceNV(fence);

        if (fenceObject == NULL)
        {
            context->recordError(Error(GL_INVALID_OPERATION));
            return GL_TRUE;
        }

        if (fenceObject->isSet() != GL_TRUE)
        {
            context->recordError(Error(GL_INVALID_OPERATION));
            return GL_TRUE;
        }

        GLboolean result;
        Error error = fenceObject->test(&result);
        if (error.isError())
        {
            context->recordError(error);
            return GL_TRUE;
        }

        return result;
    }

    return GL_TRUE;
}

void GL_APIENTRY TexStorage2DEXT(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height)
{
    EVENT("(GLenum target = 0x%X, GLsizei levels = %d, GLenum internalformat = 0x%X, GLsizei width = %d, GLsizei height = %d)",
           target, levels, internalformat, width, height);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        if (!context->getExtensions().textureStorage)
        {
            context->recordError(Error(GL_INVALID_OPERATION));
            return;
        }

        if (context->getClientVersion() < 3 &&
            !ValidateES2TexStorageParameters(context, target, levels, internalformat, width, height))
        {
            return;
        }

        if (context->getClientVersion() >= 3 &&
            !ValidateES3TexStorageParameters(context, target, levels, internalformat, width, height, 1))
        {
            return;
        }

        Extents size(width, height, 1);
        Texture *texture = context->getTargetTexture(target);
        Error error = texture->setStorage(target, levels, internalformat, size);
        if (error.isError())
        {
            context->recordError(error);
            return;
        }
    }
}

void GL_APIENTRY VertexAttribDivisorANGLE(GLuint index, GLuint divisor)
{
    EVENT("(GLuint index = %d, GLuint divisor = %d)", index, divisor);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        if (index >= MAX_VERTEX_ATTRIBS)
        {
            context->recordError(Error(GL_INVALID_VALUE));
            return;
        }

        context->setVertexAttribDivisor(index, divisor);
    }
}

void GL_APIENTRY BlitFramebufferANGLE(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
                          GLbitfield mask, GLenum filter)
{
    EVENT("(GLint srcX0 = %d, GLint srcY0 = %d, GLint srcX1 = %d, GLint srcY1 = %d, "
          "GLint dstX0 = %d, GLint dstY0 = %d, GLint dstX1 = %d, GLint dstY1 = %d, "
          "GLbitfield mask = 0x%X, GLenum filter = 0x%X)",
          srcX0, srcY0, srcX1, srcX1, dstX0, dstY0, dstX1, dstY1, mask, filter);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        if (!ValidateBlitFramebufferParameters(context, srcX0, srcY0, srcX1, srcY1,
                                               dstX0, dstY0, dstX1, dstY1, mask, filter,
                                               true))
        {
            return;
        }

        Framebuffer *readFramebuffer = context->getState().getReadFramebuffer();
        ASSERT(readFramebuffer);

        Framebuffer *drawFramebuffer = context->getState().getDrawFramebuffer();
        ASSERT(drawFramebuffer);

        Rectangle srcArea(srcX0, srcY0, srcX1 - srcX0, srcY1 - srcY0);
        Rectangle dstArea(dstX0, dstY0, dstX1 - dstX0, dstY1 - dstY0);

        Error error = drawFramebuffer->blit(context->getState(), srcArea, dstArea, mask, filter, readFramebuffer);
        if (error.isError())
        {
            context->recordError(error);
            return;
        }
    }
}

void GL_APIENTRY TexImage3DOES(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth,
                   GLint border, GLenum format, GLenum type, const GLvoid* pixels)
{
    EVENT("(GLenum target = 0x%X, GLint level = %d, GLenum internalformat = 0x%X, "
          "GLsizei width = %d, GLsizei height = %d, GLsizei depth = %d, GLint border = %d, "
          "GLenum format = 0x%X, GLenum type = 0x%x, const GLvoid* pixels = 0x%0.8p)",
          target, level, internalformat, width, height, depth, border, format, type, pixels);

    UNIMPLEMENTED();   // FIXME
}

void GL_APIENTRY GetProgramBinaryOES(GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary)
{
    EVENT("(GLenum program = 0x%X, bufSize = %d, length = 0x%0.8p, binaryFormat = 0x%0.8p, binary = 0x%0.8p)",
          program, bufSize, length, binaryFormat, binary);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        Program *programObject = context->getProgram(program);

        if (!programObject || !programObject->isLinked())
        {
            context->recordError(Error(GL_INVALID_OPERATION));
            return;
        }

        Error error = programObject->saveBinary(binaryFormat, binary, bufSize, length);
        if (error.isError())
        {
            context->recordError(error);
            return;
        }
    }
}

void GL_APIENTRY ProgramBinaryOES(GLuint program, GLenum binaryFormat, const void *binary, GLint length)
{
    EVENT("(GLenum program = 0x%X, binaryFormat = 0x%x, binary = 0x%0.8p, length = %d)",
          program, binaryFormat, binary, length);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        const std::vector<GLenum> &programBinaryFormats = context->getCaps().programBinaryFormats;
        if (std::find(programBinaryFormats.begin(), programBinaryFormats.end(), binaryFormat) == programBinaryFormats.end())
        {
            context->recordError(Error(GL_INVALID_ENUM));
            return;
        }

        Program *programObject = context->getProgram(program);
        if (!programObject)
        {
            context->recordError(Error(GL_INVALID_OPERATION));
            return;
        }

        Error error = programObject->loadBinary(binaryFormat, binary, length);
        if (error.isError())
        {
            context->recordError(error);
            return;
        }
    }
}

void GL_APIENTRY DrawBuffersEXT(GLsizei n, const GLenum *bufs)
{
    EVENT("(GLenum n = %d, bufs = 0x%0.8p)", n, bufs);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        if (n < 0 || static_cast<GLuint>(n) > context->getCaps().maxDrawBuffers)
        {
            context->recordError(Error(GL_INVALID_VALUE));
            return;
        }

        ASSERT(context->getState().getDrawFramebuffer());

        if (context->getState().getDrawFramebuffer()->id() == 0)
        {
            if (n != 1)
            {
                context->recordError(Error(GL_INVALID_OPERATION));
                return;
            }

            if (bufs[0] != GL_NONE && bufs[0] != GL_BACK)
            {
                context->recordError(Error(GL_INVALID_OPERATION));
                return;
            }
        }
        else
        {
            for (int colorAttachment = 0; colorAttachment < n; colorAttachment++)
            {
                const GLenum attachment = GL_COLOR_ATTACHMENT0_EXT + colorAttachment;
                if (bufs[colorAttachment] != GL_NONE && bufs[colorAttachment] != attachment)
                {
                    context->recordError(Error(GL_INVALID_OPERATION));
                    return;
                }
            }
        }

        Framebuffer *framebuffer = context->getState().getDrawFramebuffer();
        ASSERT(framebuffer);

        framebuffer->setDrawBuffers(n, bufs);
    }
}

void GL_APIENTRY GetBufferPointervOES(GLenum target, GLenum pname, void** params)
{
    EVENT("(GLenum target = 0x%X, GLenum pname = 0x%X, GLvoid** params = 0x%0.8p)", target, pname, params);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        if (!ValidBufferTarget(context, target))
        {
            context->recordError(Error(GL_INVALID_ENUM));
            return;
        }

        if (pname != GL_BUFFER_MAP_POINTER)
        {
            context->recordError(Error(GL_INVALID_ENUM));
            return;
        }

        Buffer *buffer = context->getState().getTargetBuffer(target);

        if (!buffer || !buffer->isMapped())
        {
            *params = NULL;
        }
        else
        {
            *params = buffer->getMapPointer();
        }
    }
}

void *GL_APIENTRY MapBufferOES(GLenum target, GLenum access)
{
    EVENT("(GLenum target = 0x%X, GLbitfield access = 0x%X)", target, access);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        if (!ValidBufferTarget(context, target))
        {
            context->recordError(Error(GL_INVALID_ENUM));
            return NULL;
        }

        Buffer *buffer = context->getState().getTargetBuffer(target);

        if (buffer == NULL)
        {
            context->recordError(Error(GL_INVALID_OPERATION));
            return NULL;
        }

        if (access != GL_WRITE_ONLY_OES)
        {
            context->recordError(Error(GL_INVALID_ENUM));
            return NULL;
        }

        if (buffer->isMapped())
        {
            context->recordError(Error(GL_INVALID_OPERATION));
            return NULL;
        }

        Error error = buffer->map(access);
        if (error.isError())
        {
            context->recordError(error);
            return NULL;
        }

        return buffer->getMapPointer();
    }

    return NULL;
}

GLboolean GL_APIENTRY UnmapBufferOES(GLenum target)
{
    EVENT("(GLenum target = 0x%X)", target);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        if (!ValidBufferTarget(context, target))
        {
            context->recordError(Error(GL_INVALID_ENUM));
            return GL_FALSE;
        }

        Buffer *buffer = context->getState().getTargetBuffer(target);

        if (buffer == NULL || !buffer->isMapped())
        {
            context->recordError(Error(GL_INVALID_OPERATION));
            return GL_FALSE;
        }

        GLboolean result;
        Error error = buffer->unmap(&result);
        if (error.isError())
        {
            context->recordError(error);
            return GL_FALSE;
        }

        return result;
    }

    return GL_FALSE;
}

void *GL_APIENTRY MapBufferRangeEXT(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access)
{
    EVENT("(GLenum target = 0x%X, GLintptr offset = %d, GLsizeiptr length = %d, GLbitfield access = 0x%X)",
          target, offset, length, access);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        if (!ValidBufferTarget(context, target))
        {
            context->recordError(Error(GL_INVALID_ENUM));
            return NULL;
        }

        if (offset < 0 || length < 0)
        {
            context->recordError(Error(GL_INVALID_VALUE));
            return NULL;
        }

        Buffer *buffer = context->getState().getTargetBuffer(target);

        if (buffer == NULL)
        {
            context->recordError(Error(GL_INVALID_OPERATION));
            return NULL;
        }

        // Check for buffer overflow
        size_t offsetSize = static_cast<size_t>(offset);
        size_t lengthSize = static_cast<size_t>(length);

        if (!rx::IsUnsignedAdditionSafe(offsetSize, lengthSize) ||
            offsetSize + lengthSize > static_cast<size_t>(buffer->getSize()))
        {
            context->recordError(Error(GL_INVALID_VALUE));
            return NULL;
        }

        // Check for invalid bits in the mask
        GLbitfield allAccessBits = GL_MAP_READ_BIT |
                                   GL_MAP_WRITE_BIT |
                                   GL_MAP_INVALIDATE_RANGE_BIT |
                                   GL_MAP_INVALIDATE_BUFFER_BIT |
                                   GL_MAP_FLUSH_EXPLICIT_BIT |
                                   GL_MAP_UNSYNCHRONIZED_BIT;

        if (access & ~(allAccessBits))
        {
            context->recordError(Error(GL_INVALID_VALUE));
            return NULL;
        }

        if (length == 0 || buffer->isMapped())
        {
            context->recordError(Error(GL_INVALID_OPERATION));
            return NULL;
        }

        // Check for invalid bit combinations
        if ((access & (GL_MAP_READ_BIT | GL_MAP_WRITE_BIT)) == 0)
        {
            context->recordError(Error(GL_INVALID_OPERATION));
            return NULL;
        }

        GLbitfield writeOnlyBits = GL_MAP_INVALIDATE_RANGE_BIT |
                                   GL_MAP_INVALIDATE_BUFFER_BIT |
                                   GL_MAP_UNSYNCHRONIZED_BIT;

        if ((access & GL_MAP_READ_BIT) != 0 && (access & writeOnlyBits) != 0)
        {
            context->recordError(Error(GL_INVALID_OPERATION));
            return NULL;
        }

        if ((access & GL_MAP_WRITE_BIT) == 0 && (access & GL_MAP_FLUSH_EXPLICIT_BIT) != 0)
        {
            context->recordError(Error(GL_INVALID_OPERATION));
            return NULL;
        }

        Error error = buffer->mapRange(offset, length, access);
        if (error.isError())
        {
            context->recordError(error);
            return NULL;
        }

        return buffer->getMapPointer();
    }

    return NULL;
}

void GL_APIENTRY FlushMappedBufferRangeEXT(GLenum target, GLintptr offset, GLsizeiptr length)
{
    EVENT("(GLenum target = 0x%X, GLintptr offset = %d, GLsizeiptr length = %d)", target, offset, length);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        if (offset < 0 || length < 0)
        {
            context->recordError(Error(GL_INVALID_VALUE));
            return;
        }

        if (!ValidBufferTarget(context, target))
        {
            context->recordError(Error(GL_INVALID_ENUM));
            return;
        }

        Buffer *buffer = context->getState().getTargetBuffer(target);

        if (buffer == NULL)
        {
            context->recordError(Error(GL_INVALID_OPERATION));
            return;
        }

        if (!buffer->isMapped() || (buffer->getAccessFlags() & GL_MAP_FLUSH_EXPLICIT_BIT) == 0)
        {
            context->recordError(Error(GL_INVALID_OPERATION));
            return;
        }

        // Check for buffer overflow
        size_t offsetSize = static_cast<size_t>(offset);
        size_t lengthSize = static_cast<size_t>(length);

        if (!rx::IsUnsignedAdditionSafe(offsetSize, lengthSize) ||
            offsetSize + lengthSize > static_cast<size_t>(buffer->getMapLength()))
        {
            context->recordError(Error(GL_INVALID_VALUE));
            return;
        }

        // We do not currently support a non-trivial implementation of FlushMappedBufferRange
    }
}

}


text:
package main

import (
	"net/http"
	"os"
	"time"

	"github.com/drone/drone/router"
	"github.com/drone/drone/router/middleware"

	"github.com/Sirupsen/logrus"
	"github.com/gin-gonic/contrib/ginrus"
	"github.com/ianschenck/envflag"
	_ "github.com/joho/godotenv/autoload"
)

var (
	addr = envflag.String("SERVER_ADDR", ":8000", "")
	cert = envflag.String("SERVER_CERT", "", "")
	key  = envflag.String("SERVER_KEY", "", "")

	debug = envflag.Bool("DEBUG", false, "")
)

func main() {
	if os.Getenv("CANARY") == "true" {
		main2()
		return
	}

	envflag.Parse()

	// debug level if requested by user
	if *debug {
		logrus.SetLevel(logrus.DebugLevel)
	} else {
		logrus.SetLevel(logrus.WarnLevel)
	}

	// setup the server and start the listener
	handler := router.Load(
		ginrus.Ginrus(logrus.StandardLogger(), time.RFC3339, true),
		middleware.Version,
		middleware.Queue(),
		middleware.Stream(),
		middleware.Bus(),
		middleware.Cache(),
		middleware.Store(),
		middleware.Remote(),
		middleware.Engine(),
	)

	if *cert != "" {
		logrus.Fatal(
			http.ListenAndServeTLS(*addr, *cert, *key, handler),
		)
	} else {
		logrus.Fatal(
			http.ListenAndServe(*addr, handler),
		)
	}
}

redpajama_set_name: RedPajamaGithub


text:
@implementation JTCalendarDayView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(!self){
        return nil;
    }

    [self commonInit];

    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if(!self){
        return nil;
    }

    [self commonInit];

    return self;
}

- (void)commonInit
{
    self.clipsToBounds = YES;

    _circleRatio = .9;
    _dotRatio = 1. / 9.;

    {
        _circleView = [UIView new];
        [self addSubview:_circleView];

        _circleView.backgroundColor = [UIColor colorWithRed:0x33/256. green:0xB3/256. blue:0xEC/256. alpha:.5];
        _circleView.hidden = YES;
    }

    {
        _dotView = [UIView new];
        [self addSubview:_dotView];

        _dotView.backgroundColor = [UIColor redColor];
        _dotView.hidden = YES;
    }

    {
        _textLabel = [UILabel new];
        [self addSubview:_textLabel];

        _textLabel.textColor = [UIColor blackColor];
        _textLabel.textAlignment = NSTextAlignmentCenter;
        _textLabel.font = [UIFont systemFontOfSize:[UIFont systemFontSize]];
    }

    {
        UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTouch)];

        self.userInteractionEnabled = YES;
        [self addGestureRecognizer:gesture];
    }
}

- (void)layoutSubviews
{
    _textLabel.frame = self.bounds;

    CGFloat sizeCircle = MIN(self.frame.size.width, self.frame.size.height);
    CGFloat sizeDot = sizeCircle;

    sizeCircle = sizeCircle * _circleRatio;
    sizeDot = sizeDot * _dotRatio;

    sizeCircle = roundf(sizeCircle);
    sizeDot = roundf(sizeDot);

    _circleView.frame = CGRectMake(0, 0, sizeCircle, sizeCircle);
    _circleView.center = CGPointMake(self.frame.size.width / 2., self.frame.size.height / 2.);
    _circleView.layer.cornerRadius = sizeCircle / 2.;

    _dotView.frame = CGRectMake(0, 0, sizeDot, sizeDot);
    _dotView.center = CGPointMake(self.frame.size.width / 2., (self.frame.size.height / 2.) +sizeDot * 2.5);
    _dotView.layer.cornerRadius = sizeDot / 2.;
}

- (void)setDate:(NSDate *)date
{
    NSAssert(date != nil, @"date cannot be nil");
    NSAssert(_manager != nil, @"manager cannot be nil");

    self->_date = date;
    [self reload];
}

- (void)reload
{
    static NSDateFormatter *dateFormatter = nil;
    if(!dateFormatter){
        dateFormatter = [_manager.dateHelper createDateFormatter];
        [dateFormatter setDateFormat:@"dd"];
    }

    _textLabel.text = [dateFormatter stringFromDate:_date];

    [_manager.delegateManager prepareDayView:self];
}

- (void)didTouch
{
    [_manager.delegateManager didTouchDayView:self];
}

@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bol. Secr. Agric. (Pernambuco) 17: 60 (1950)

#### Original name
Hypoxylon dispersa Bat.

### Remarks
null


text:
if Rails.env.development? || Rails.env.test?
  require File.expand_path("#{Rails.root}/spec/support/fake_twilio_client")
  silence_warnings do
    Twilio::REST::Client = FakeTwilioClient
  end
elsif Rails.env.production?
  Twilio.configure do |config|
    config.account_sid = Rails.application.secrets.twilio_account_sid
    config.auth_token = Rails.application.secrets.twilio_auth_token
  end
end


text:
namespace app { namespace Fuse { namespace Animations { struct Change__Fuse_Navigation_SnapTo; } } }
namespace app { namespace Fuse { namespace Animations { struct CreateStateParams; } } }
namespace app { namespace Uno { struct Float4; } }

namespace app {
namespace Fuse {
namespace Animations {

struct ContinuousTrackChangeState__Fuse_Navigation_SnapTo;

struct ContinuousTrackChangeState__Fuse_Navigation_SnapTo__uType : ::app::Fuse::Animations::TrackAnimatorState__uType
{
};

ContinuousTrackChangeState__Fuse_Navigation_SnapTo__uType* ContinuousTrackChangeState__Fuse_Navigation_SnapTo__typeof();

void ContinuousTrackChangeState__Fuse_Navigation_SnapTo___ObjInit_2(ContinuousTrackChangeState__Fuse_Navigation_SnapTo* __this, ::app::Fuse::Animations::Change__Fuse_Navigation_SnapTo* animator, ::app::Fuse::Animations::CreateStateParams* p);
void ContinuousTrackChangeState__Fuse_Navigation_SnapTo__Disable(ContinuousTrackChangeState__Fuse_Navigation_SnapTo* __this);
ContinuousTrackChangeState__Fuse_Navigation_SnapTo* ContinuousTrackChangeState__Fuse_Navigation_SnapTo__New_1(::uStatic* __this, ::app::Fuse::Animations::Change__Fuse_Navigation_SnapTo* animator, ::app::Fuse::Animations::CreateStateParams* p);
void ContinuousTrackChangeState__Fuse_Navigation_SnapTo__SeekValue(ContinuousTrackChangeState__Fuse_Navigation_SnapTo* __this, ::app::Uno::Float4 value, float strength);

struct ContinuousTrackChangeState__Fuse_Navigation_SnapTo : ::app::Fuse::Animations::TrackAnimatorState
{
    ::uStrong< ::uObject*> mixHandle;
    ::uStrong< ::app::Fuse::Animations::Change__Fuse_Navigation_SnapTo*> Animator_1;

    void _ObjInit_2(::app::Fuse::Animations::Change__Fuse_Navigation_SnapTo* animator, ::app::Fuse::Animations::CreateStateParams* p) { ContinuousTrackChangeState__Fuse_Navigation_SnapTo___ObjInit_2(this, animator, p); }
};

}}}

#endif


text:
@implementation FriendsCell

- (void)awakeFromNib
{
    _lbl_name.font = [UIFont fontWithSize:15.f];
    _lbl_name.textColor = K_COLOR_DARK;
    _lbl_grouptitle.font = [UIFont fontWithSize:12.f];
    _lbl_grouptitle.textColor = K_COLOR_DARK_Cell;
    _lbl_grouptitle.numberOfLines = 1;
    self.iv_avatar.layer.cornerRadius = 48/2;
    _iv_avatar.contentMode = UIViewContentModeScaleAspectFill;
    _iv_avatar.clipsToBounds = YES;
    self.iv_avatar.backgroundColor = [UIColor blackColor];
    self.iv_line.image = [Util imageWithColor:K_COLOR_MOST_LIGHT_GRAY];
    self.backgroundColor = [UIColor clearColor];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end


text:
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <syslog.h>
#include <errno.h>
#include <string.h>
#include <systemd/sd-bus.h>
#include <stdbool.h>

#include "log.h"

#ifndef CONFIGURATION_H
#define CONFIGURATION_H
#include "configuration.h"
#endif

#define BUFF_SIZE 		512
#define ARGUMENT_COUT_MAX 	256
#define DELIMITER 		";"

#define BUS_PATH "kernel:path=/sys/fs/kdbus/0-system/bus"

#define io_sdbus_error_ret(message, err)  if (r < 0) { bootLogger(LOG_ERR, message ": %s\n",strerror(-err)); return err; }

static sd_bus_slot *slot = NULL;
static sd_bus *bus = NULL;
static Settings *conf;

static void (*messageCallback)(int *,char *);
static void (*exitCallback)(void);

void registerMessageCallbackComm(void (*callback)(int *,char *)) {
    messageCallback = callback;
}

void registerExitCallbackComm(void (*callback)(void)) {
    exitCallback = callback;
}

int openComm(Settings *settings)
{
    int r;
    conf = settings;

    bootLogger(LOG_DEBUG, "connect to bus\n");

    r = sd_bus_new(&bus);
    io_sdbus_error_ret("Failed to allocate bus", r);

    r = sd_bus_negotiate_creds(bus,true,_SD_BUS_CREDS_ALL);
    io_sdbus_error_ret("Failed to set bus creds", r);

    r = sd_bus_negotiate_timestamp(bus, true);
    io_sdbus_error_ret("Failed to negotiate timestamp", r);

    r = sd_bus_negotiate_fds(bus,true);
    io_sdbus_error_ret("Failed to negotiate filedesciptor passing", r);

    r = sd_bus_set_address(bus, BUS_PATH);
    io_sdbus_error_ret("Failed to set bus address", r);

    r = sd_bus_start(bus);
    io_sdbus_error_ret("Failed to start bus", r);

    r = sd_bus_add_match(bus, NULL, "", NULL, NULL);
    io_sdbus_error_ret("Failed to add gerneric match to bus", r);

    return 0;
}

void startComm() {
    const char *path, *result, *unit;
    uint32_t id;
    sd_bus_message *m = NULL;
    sd_bus_error error = SD_BUS_ERROR_NULL;
    int percent = 0;
    double float_percent = 0.0;
    char * message;
    int len  = 0;
    int r;

    /* Process requests */
    r = sd_bus_process(bus, &m);

    if (r < 0) {
            bootLogger(LOG_ERR, "Failed to process bus: %s\n", strerror(-r));
//                        goto finish;
    }
    if(m) {
        if (sd_bus_message_is_signal(m, "org.freedesktop.systemd1.Manager", "JobRemoved") > 0) {
            r = sd_bus_message_read(m, "uoss", &id,&path, &unit,&result);

	    if (r < 0) bootLogger(LOG_ERR, "Failed to decode Message: %s\n", strerror(-r));

    	    r = sd_bus_get_property(bus,
    				"org.freedesktop.systemd1",
    				"/org/freedesktop/systemd1",
    				"org.freedesktop.systemd1.Manager",
    				"Progress", &error, &m,"d");

	    if (r < 0) bootLogger(LOG_ERR, "Failed to get progress property: %s\n", strerror(-r));

    	    /* Parse the response message */
    	    r = sd_bus_message_read_basic(m,  'd', (void *) &float_percent );
    	    if (r < 0) bootLogger(LOG_ERR, "Failed to decode property: %s\n", strerror(-r));

	    percent = float_percent * 100;

	    len = strnlen(unit,conf->status_text_maxlen);
	    message = (char *)malloc((len + 20) *(sizeof(char)));
	    if(message == 0) {
    		bootLogger(LOG_ERR, "cant allocate any memory: %s\n", strerror(errno));
    		return;
	    }
	    memset(message,0,len + 20);
	    strncpy(message,unit,len);
	    if(len > conf->status_text_maxlen - 3) strncat(message,"...",3);
	    strncat(message,", ",2);
	    strncat(message,result,10);
	    bootLogger(LOG_DEBUG,"Calling messageCallback with message=%s, percent=%d, %f\n",message,percent, float_percent);
	    messageCallback(&percent, message);
            free(message);
	}

        return;
    }

    if (r > 0) /* we processed a request, try to process another one, right-away */
            return;

    /* Wait for the next request to process */
    r = sd_bus_wait(bus, (uint64_t) -1);
    if (r < 0) {
        bootLogger(LOG_ERR, "Failed to process bus: %s\n", strerror(-r));
//                        goto finish;
    }

}

void closeComm()
{
    bootLogger(LOG_DEBUG, "disconnect from bus\n");
    sd_bus_slot_unref(slot);
    sd_bus_unref(bus);
}


text:
<?php

namespace App\Controllers\Auth;

use App\Models\User;
use App\Controllers\Controller;
use Respect\Validation\Validator as v;

class AuthController extends Controller
{

		public function getSignOut($request, $response) //Metoda pomocu koje izlogujemo korisnika
	{
		session_unset();
		session_destroy();
		return $response->withRedirect($this->router->pathFor('auth.signin'));
	}
	public function getSignIn($request, $response) // Ovom metodom preusmeravamo korisnika na twig template za logovanje korisnika
	{
			return $this->view->render($response, 'auth/signin.twig');
	}

	public function postSignIn($request, $response) // Pomocu ove metode prosledjujemo podatke iz forme za logovanje korsinika
	{
		$auth = $this->auth->attempt(				//Koristimo nasu auth klasu i proveravamo da li postoji korisnik sa istim emailom i sa tim passwordom

			$request->getParam('email'),
			$request->getparam('password')

			);

		if(!$auth){
			return $response->withRedirect($this->router->pathFor('auth.signin')); 	// Ukoliko se ne poklapa, vrati nas na stranicu za logvanje
		}

		return $response->withRedirect($this->router->pathFor('home'));		//Ukoliko je sve uspesno ulogujemo se
	}

	public function getSignUp($request, $response) // Kada se klikne sign up dugme ova metoda generise  signup.twig fajl.
	{
		//var_dump($request->getAttribute('csrf_value'));

		return $this->view->render($response, 'auth/signup.twig');
	}

	public function postSignUp($request, $response) 			//Prosledjujemo formu za registraciju
	{

		$validaton = $this->validator->validate($request, [		//Prvo proveravamo dali su sva pravila koja smo mi naveli u ovom nizu izpostovana, ako nisu izbacice gresku.

				'name' => v::notEmpty()->alpha(),								//Proveravamo da li je prazno polje
				'email' => v::noWhitespace()->notEmpty()->email()->emailSlobodan(),	//nema space-a u email-u, i nase pravilo da li je Email zauzet
				'password' => v::noWhitespace()->notEmpty(),

			]);

		if($validaton->failed()){			//Ukoliko neko pravilo nije izpostovano, preusmerice nas ponovo na registracijonu formu

				return $response->withRedirect($this->router->pathFor('auth.signup'));
		}

		$user = User::create([																		//Ako je validacija prosla uspesno pravimo korisnika i prosledjujemo parametre iz polja

				'email' => $request->getParam('email'),
				'name' => $request->getparam('name'),
				'password' => password_hash($request->getParam('password'), PASSWORD_DEFAULT),		// password_hash funkcijom Hash-ujemo sifru i tako cemo je cuvati u bazi podataka, prvi parametar funkcije je sta hocemo da hashujemo, a drugi je algoritam koji hocemo da koristimo.
			]);

		$this->auth->attempt($user->email, $request->getParam('password'));							//Kada smo napravili korisnika, ulogujemo ga tj. autentikaciju odradimo preko attempt funkcije

		return $response->withRedirect($this->router->pathFor('home')); 							// Ako je sve proslo kako treba onda ce se prikazati pocetna stranica ulogovanom korisniku.
	}

}


text:
class GroupName < ApplicationRecord
  belongs_to :group
  belongs_to :name

  validates_presence_of :name, :group
end


text:
<?php

namespace Yiban\PushBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Yiban\PushBundle\Entity\App;

class AppAdmin extends Admin
{

    protected $container;

    protected $formOptions = array(
        'validation_groups' => array('App')
    );

    public function getFormBuilder() {
        $request = $this->container->get('request')->request;
        $keys = $request->keys();
        if(count($keys)){
            $data = $request->filter($keys[0]);
            $type = $data['type'];
            if($type){
                $this->formOptions['validation_groups'] = array_merge($this->formOptions['validation_groups'], array(strtolower($type)));
            }
        }

        $formBuilder = parent::getFormBuilder();
        return $formBuilder;
    }

    public function __construct($code, $class, $baseControllerName, $container)
    {
        parent::__construct($code, $class, $baseControllerName);
        $this->container = $container;
    }

    public function createQuery($context = 'list')
    {
        if($this->container->get('security.context')->isGranted('ROLE_ADMIN')){
            return parent::createQuery($context);
        }
        $user = $this->container->get('security.context')->getToken()->getUser();
        $query = parent::createQuery($context);
        $query->leftJoin($query->getRootAlias() . '.users', 'u')
                ->where('u.id = :ss')
                ->setParameter('ss', $user->getId())
                ;
        return $query;
    }

    public function prePersist($object)
    {
        #生成app的access_token
        $object->setAccessToken($this->container->get('fos_user.util.token_generator')->generateToken());
    }

    public function postPersist($object)
    {
        $user = $this->container->get('security.context')->getToken()->getUser();
        $user->addApp($object);
        $this->getModelManager()->update($user);
    }

    protected function configureRoutes(\Sonata\AdminBundle\Route\RouteCollection $collection)
    {
        $collection->add('pushnotice', $this->getRouterIdParameter() . '/push/notice');
        $collection->add('pushusernotice', $this->getRouterIdParameter() . '/push/user/notice');
        $collection->add('pushmessage', $this->getRouterIdParameter() . '/push/message');
        $collection->add('statistics', $this->getRouterIdParameter() . '/statistics');
    }

    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
                ->add('name', 'text', array('label' => '应用名称'))
                ->add('app_id', 'text', array('label' => 'app id', 'required' => false))
                ->add('app_key', 'text', array('label' => 'app key'))
                ->add('app_secret', 'text', array('label' => 'app secret'))
                ->add('master_secret', 'text', array('label' => 'master secret', 'required' => false))
                ->add('platform', 'choice', array('label' => '平台', 'required' => false, 'choices' => array('ANDROID' => 'Android', 'IOS' => 'IOS'), 'expanded' => true, 'multiple' => true))
                ->add('type', 'choice', array('label' => '第三方服务', 'choices' => array('' => '----选择第三方服务----', App::BAIDU_TYPE => '百度云推送', App::GETUI_TYPE => '个推推送', App::JPUSH_TYPE => '极光推送')))
        ;
    }

    // Fields to be shown on filter forms
    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
                ->add('name')
                ->add('app_id')
                ->add('app_key')
                ->add('app_secret')
                ->add('master_secret')
                ->add('access_token')
        ;
    }

    // Fields to be shown on lists
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
                ->addIdentifier('id', null, array('label' => 'ID'))
                ->addIdentifier('name', null, array('label' => '应用名'))
                ->add('第三方秘钥', null, array('template' => 'YibanPushBundle:App:_keys.html.twig'))
                ->add('access_token')
                ->add('app_platform', NULL, array('template' => 'YibanPushBundle:App:_platform.html.twig', 'label' => '平台'))
                ->add('app_type', null, array('label' => '第三方服务', 'template' => 'YibanPushBundle:App:_type.html.twig'))
                ->add('_action', 'actions', array(
                    'actions' => array(
                        'pushnotice' => array(
                            'template' => 'YibanPushBundle:App:_pushnotice_action.html.twig'
                        ),
                        'pushmessage' => array(
                            'template' => 'YibanPushBundle:App:_pushmessage_action.html.twig'
                        ),
                        'pushusernotice' => array(
                            'template' => 'YibanPushBundle:App:_pushusernotice_action.html.twig'
                        ),
                        'statistics' => array(
                            'template' => 'YibanPushBundle:App:_statistics.html.twig'
                        )
                    )
                ))
        ;
    }

}


text:
{-- snippet findCarrierBillingAddress --}
import qualified Data.Map as M

type PersonName = String
type PhoneNumber = String
type BillingAddress = String
data MobileCarrier = Honest_Bobs_Phone_Network
                   | Morrisas_Marvelous_Mobiles
                   | Petes_Plutocratic_Phones
                     deriving (Eq, Ord)

findCarrierBillingAddress :: PersonName
                          -> M.Map PersonName PhoneNumber
                          -> M.Map PhoneNumber MobileCarrier
                          -> M.Map MobileCarrier BillingAddress
                          -> Maybe BillingAddress
{-- /snippet findCarrierBillingAddress --}
findCarrierBillingAddress = undefined

{-- snippet variation1 --}
variation1 person phoneMap carrierMap addressMap =
    case M.lookup person phoneMap of
      Nothing -> Nothing
      Just number ->
          case M.lookup number carrierMap of
            Nothing -> Nothing
            Just carrier -> M.lookup carrier addressMap
{-- /snippet variation1 --}

{-- snippet variation2 --}
variation2 person phoneMap carrierMap addressMap = do
  number <- M.lookup person phoneMap
  carrier <- M.lookup number carrierMap
  address <- M.lookup carrier addressMap
  return address
{-- /snippet variation2 --}

{-- snippet variation2a --}
variation2a person phoneMap carrierMap addressMap = do
  number <- M.lookup person phoneMap
  carrier <- M.lookup number carrierMap
  M.lookup carrier addressMap
{-- /snippet variation2a --}

{-- snippet variation3 --}
variation3 person phoneMap carrierMap addressMap =
    lookup phoneMap person >>= lookup carrierMap >>= lookup addressMap
  where lookup = flip M.lookup
{-- /snippet variation3 --}


text:
require "will_paginate/view_helpers/action_view"
require "materialize_pagination/materialize_renderer"

module MaterializePagination
  # A custom renderer class for WillPaginate that produces markup suitable for use with MaterializeCSS
  class Rails < WillPaginate::ActionView::LinkRenderer
    include MaterializeRenderer
  end
end


text:
package org.cobogw.gwt.waveapi.gadget.client.ui;

import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.ui.SimplePanel;

/**
 * A Wave style decorated simple panel.
 *
 * Note: while the wave api method generates a header into this panel no access
 * is provided to set content into this header. Mainly because the api method
 * itself doesn't provide access and thus it's not clear if the header is
 * supported in the future.
 *
 *
CSS Style Rules

 *
 *

 *
.wavebox { the outside of the panel }

 *
.wavebox .waveboxhead { the head of the panel }

 *
.wavebox .waveboxbody { the body of the panel }

 *

 *
 *
Generated wrapped HTML

 *
 * The Wave provided make frame wraps around the given div element, which
 * results in the following HTML code:
 *
 *

 *   <div class="wavebox">
 *     <div class="waveboxhead">
 *       <span> </span>
 *     </div>
 *     <div class="waveboxbody"> body </div>
 *   </div>
 *

 */
public class DecoratedSimplePanel extends SimplePanel {

  public DecoratedSimplePanel() {
    super();
    makeFrame(getElement());
  }

  @Override
  protected com.google.gwt.user.client.Element getContainerElement() {
    return getElement().getFirstChildElement().getNextSiblingElement().cast();
  }

  private native void makeFrame(Element e) /*-{
    $wnd.wave.ui.makeFrame(e);
  }-*/;
}


text:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace WordPressPCL.Models
{
	public class Post
	{
        /// <summary>
        ///     The date the object was published, in the site's timezone.
        /// </summary>
        /// <remarks>Context: view, edit, embed</remarks>
		[JsonProperty("date")]
		public DateTime Date { get; set; }

        /// <summary>
        ///     The date the object was published, as GMT.
        /// </summary>
        /// <remarks>Context: view, edit</remarks>
        [JsonProperty("date_gmt")]
		public DateTime DateGmt { get; set; }

        /// <summary>
        /// The globally unique identifier for the object.
        /// </summary>
        /// <remarks>Context: view, edit</remarks>
        [JsonProperty("guid")]
        public Guid Guid { get; set; }

        [JsonProperty("id")]
        public int Id { get; set; }

        [JsonProperty("modified")]
		public string Modified { get; set; }

		[JsonProperty("modified_gmt")]
		public string ModifiedGmt { get; set; }

        [JsonProperty("password")]
        public string Password { get; set; }

        [JsonProperty("slug")]
		public string Slug { get; set; }

        // One of: publish, future, draft, pending, private
        [JsonProperty("status")]
        public string Status { get; set; }

        [JsonProperty("type")]
		public string Type { get; set; }

        [JsonProperty("title")]
        public Title Title { get; set; }

        [JsonProperty("link")]
		public string Link { get; set; }

		[JsonProperty("content")]
		public Content Content { get; set; }

		[JsonProperty("excerpt")]
		public Excerpt Excerpt { get; set; }

		[JsonProperty("author")]
		public int Author { get; set; }

		[JsonProperty("featured_media")]
		public int FeaturedMedia { get; set; }

        // One of: open, closed
        [JsonProperty("comment_status")]
		public string CommentStatus { get; set; }

		[JsonProperty("ping_status")]
		public string PingStatus { get; set; }

		[JsonProperty("sticky")]
		public bool Sticky { get; set; }

        /// <summary>
        ///     The format for the object.
        /// </summary>
        /// <remarks>
        ///     Context: view, edit
        ///     One of: standard
        /// </remarks>
        [JsonProperty("format")]
		public string Format { get; set; }

        [JsonProperty("categories")]
        public int[] Categories { get; set; }

        [JsonProperty("tags")]
        public int[] Tags { get; set; }

        [JsonProperty("template")]
        public string Template { get; set; }

        [JsonProperty("_links")]
        public Links Links { get; set; }

        [JsonProperty("_embedded")]
        public Embedded Embedded { get; set; }
    }

    public class Embedded
    {
        [JsonProperty("author")]
        public IList<User> Author { get; set; }

        [JsonProperty("replies")]
        public IList<IList<Comment>> Replies { get; set; }

        [JsonProperty("wp:featuredmedia")]
        public IList<Media> WpFeaturedmedia { get; set; }

        [JsonProperty("wp:term")]
        public IList<IList<Term>> WpTerm { get; set; }
    }

    public enum OrderBy
    {
        date, id, include, title, slug
    }

    public class Guid
	{
		[JsonProperty("rendered")]
		public string Rendered { get; set; }
        [JsonProperty("raw")]
        public string Raw { get; set; }
    }

	public class Title
	{
		[JsonProperty("rendered")]
		public string Rendered { get; set; }
        [JsonProperty("raw")]
        public string Raw { get; set; }

    }

    public class Excerpt
	{
		[JsonProperty("rendered")]
		public string Rendered { get; set; }
        [JsonProperty("raw")]
        public string Raw { get; set; }
    }

	public class VersionHistory
	{
		[JsonProperty("href")]
		public string Href { get; set; }
	}

	public class HttpsApiWOrgFeaturedmedia
	{
		[JsonProperty("embeddable")]
		public bool Embeddable { get; set; }

		[JsonProperty("href")]
		public string Href { get; set; }
	}
}


text:
package com.gilesc

import java.util.UUID

package object mynab {
  case class UserId(value: Long) extends AnyVal

  case class CategoryName(value: String) extends AnyVal

  case class CategoryGroupId(value: Long) extends AnyVal
  case class CategoryGroup(id: CategoryGroupId, userId: UserId, name: CategoryName)
  case class CategoryGroupContext(userId: UserId, value: CategoryName)

  case class CategoryId(value: Long) extends AnyVal
  case class Category(id: CategoryId, userId: UserId, group: CategoryGroup, name: CategoryName)
  case class CategoryContext(userId: UserId, group: CategoryGroup, name: CategoryName)

//  // user
//  case class UserId(value: UUID) extends AnyVal
//
//  // account
//  case class AccountId(value: UUID) extends AnyVal
//  case class AccountName(value: String) extends AnyVal
//  case class Account(id: AccountId, userId: UserId, name: AccountName, transactions: Vector[Transaction])
//
//  case class AccountContext(userId: UserId, name: AccountName)
//
//  // category
//  case class MajorCategory(value: String) extends AnyVal
//  case class MinorCategory(value: String) extends AnyVal
//  case class Category(major: MajorCategory, minor: MinorCategory)
//
//  // transaction
//  import java.time.{LocalDate => Date}
//
//  case class TransactionId(value: UUID) extends AnyVal
//  case class Payee(value: String) extends AnyVal
//  case class Memo(value: String) extends AnyVal
//  case class Amount(value: BigDecimal) extends AnyVal
//  case class Cleared(value: Boolean) extends AnyVal
//
//  case class Transaction(id: TransactionId, date: Date, payee: Payee,
//    category: Category, memo: Memo, withdrawal: Amount, deposit: Amount,
//    cleared: Cleared)
//
//  case class TransactionContext(date: Date, payee: Payee,
//    category: Category, memo: Memo, withdrawal: Amount, deposit: Amount,
//    cleared: Cleared)
//
//  object Transaction {
//    def fromCtx(id: TransactionId, ctx: TransactionContext): Transaction =
//      Transaction(id, ctx.date, ctx.payee, ctx.category, ctx.memo,
//        ctx.withdrawal, ctx.deposit, ctx.cleared)
//  }
}


text:
// Copyright 2013 Bobby Powers. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/*

The xmile package implements the system dynamics XML Interface
Language (XMILE) standard currently being drafted by the OASIS
Technical Committee.

For more information, see:
https://www.oasis-open.org/apps/org/workgroup/xmile/

*/
package xmile


text:
FROM elasticsearch:2.1.0
MAINTAINER Benjamin Wenderoth

ENV ES_HOME /usr/share/elasticsearch
WORKDIR ${ES_HOME}
ADD ./elasticsearch.yml /etc/elasticsearch/elasticsearch.yml
RUN bin/plugin install royrusso/elasticsearch-HQ
RUN bin/plugin install discovery-multicast
RUN bin/plugin install analysis-icu
RUN bin/plugin install analysis-phonetic
RUN bin/plugin install http://dl.bintray.com/content/imotov/elasticsearch-plugins/org/elasticsearch/elasticsearch-analysis-morphology/2.1.0/elasticsearch-analysis-morphology-2.1.0.zip
RUN bin/plugin install lmenezes/elasticsearch-kopf/2.1.1
RUN bin/plugin install https://github.com/NLPchina/elasticsearch-sql/releases/download/2.1.0/elasticsearch-sql-2.1.0.zip
RUN bin/plugin install http://xbib.org/repository/org/xbib/elasticsearch/plugin/elasticsearch-analysis-decompound/2.1.0.0/elasticsearch-analysis-decompound-2.1.0.0-plugin.zip
##RUN bin/plugin install http://xbib.org/repository/org/xbib/elasticsearch/plugin/elasticsearch-analysis-standardnumber/2.0.0-beta2.0/elasticsearch-analysis-standardnumber-2.0.0-beta2.0-plugin.zip
## RUN bin/plugin install lukas-vlcek/bigdesk
RUN bin/plugin install http://xbib.org/repository/org/xbib/elasticsearch/plugin/elasticsearch-langdetect/2.1.0.0/elasticsearch-langdetect-2.1.0.0-plugin.zip
RUN bin/plugin install org.codelibs/elasticsearch-reindexing/2.1.0
RUN bin/plugin install org.codelibs/elasticsearch-analyze-api/2.1.0
RUN bin/plugin install mobz/elasticsearch-head

## MAybe in future we needto identify numbers
## bin/plugin install http://xbib.org/repository/org/xbib/elasticsearch/plugin/elasticsearch-analysis-standardnumber/2.0.0-beta2.0/elasticsearch-analysis-standardnumber-2.0.0-beta2.0-plugin.zip


text:
package org.olat.core.gui.control.state;

/**
 * Description:

 * a state represents the state of a controller. its implementation must be immutable objects, that is they cannot change once they are constructed
 *

 *
 * @author Felix Jost
 */
public interface ControllerState {
	/**
	 * @return the state of the controller in string form, e.g shownode:123 for the runmaincontroller.java. the empty string means initial state
	 */
	public String getSerializedState();

	/**
	 * @param controllerState
	 * @return true if it represents the same state, that is: if serialstate1.equals(serialstate2)
	 */
	public boolean isSame(ControllerState controllerState);

}


text:
package com.ray3k.skincomposer.dialog.scenecomposer.undoables;

public class ListDeleteUndoable extends ActorDeleteUndoable {
    @Override
    public String getRedoString() {
        return "Redo \"Delete List\"";
    }

    @Override
    public String getUndoString() {
        return "Undo \"Delete List\"";
    }
}


text:
package cartesianTree;

import cartesianTree.nodes.CartesianTreeNode;

public interface ICartesianTreeManager
{
    CartesianTree getEmptyTree();
    CartesianTree createNewTree(long value);
    CartesianTree createNewTree(CartesianTreeNode root);
    CartesianTree concatenate(CartesianTree leftTree, CartesianTree rightTree);
}


text:
<?php

/**
 * @file
 * Contains \Drupal\page_cache_form_test\Form\TestForm.
 */

namespace Drupal\page_cache_form_test\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class TestForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'page_cache_form_test';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['#prefix'] = '
Llamas are awesome, but kittens are pretty cool too!
';
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) { }

}


text:
This intention replaces a post fix increment or
decrement expression with an equivalent assignment expression.

New in 9


text:
import json
import logging

from django.core.management.base import BaseCommand, CommandError

from lots_admin.models import ApplicationStatus, DenialReason, Review, User

class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument('--pins_with_denials',
                            help='JSON object, wherein the PIN is the key and the denial reason is the value')

        parser.add_argument('--user_email',
                            default='reginafcompton@datamade.us')

    def handle(self, *args, **options):
        pins_with_denials = json.loads(options['pins_with_denials'])
        user_email = options['user_email']
        user = User.objects.get(email=user_email)

        self.stdout.write('Begin: Denying applications!')

        for pin, reason_text in pins_with_denials.items():
            applications = ApplicationStatus.objects.filter(lot=pin)
            for app in applications:
                reason, _ = DenialReason.objects.get_or_create(value=reason_text)
                review = Review(reviewer=user, email_sent=True, denial_reason=reason, application=app)
                review.save()
                app.denied = True
                app.current_step = None
                app.save()

                self.stdout.write(('{0} {1} | {2}').format(app.application.first_name, app.application.last_name, pin))


text:
package org.omg.CORBA;

/**
 * This exception is raised if an operation implementation
 * throws a non-CORBA exception (such as an exception
 * specific to the implementation's programming language),
 * or if an operation raises a user exception that does not
 * appear in the operation's raises expression. UNKNOWN is
 * also raised if the server returns a system exception that
 * is unknown to the client. (This can happen if the server
 * uses a later version of CORBA than the client and new system
 * exceptions have been added to the later version.)

 * It contains a minor code, which gives more detailed information about
 * what caused the exception, and a completion status. It may also contain
 * a string describing the exception.
 *

 * See the section Minor
 * Code Meanings to see the minor codes for this exception.
 *
 * @see documentation on
 * Java IDL exceptions
 */

public final class UNKNOWN extends SystemException {
    /**
     * Constructs an UNKNOWN exception with a default minor code
     * of 0, a completion state of CompletionStatus.COMPLETED_NO,
     * and a null description.
     */
    public UNKNOWN() {
        this("");
    }

    /**
     * Constructs an UNKNOWN exception with the specified description message,
     * a minor code of 0, and a completion state of COMPLETED_NO.
     * @param s the String containing a detail message
     */
    public UNKNOWN(String s) {
        this(s, 0, CompletionStatus.COMPLETED_NO);
    }

    /**
     * Constructs an UNKNOWN exception with the specified
     * minor code and completion status.
     * @param minor the minor code
     * @param completed the completion status
     */
    public UNKNOWN(int minor, CompletionStatus completed) {
        this("", minor, completed);
    }

    /**
     * Constructs an UNKNOWN exception with the specified description
     * message, minor code, and completion status.
     * @param s the String containing a description message
     * @param minor the minor code
     * @param completed the completion status
     */
    public UNKNOWN(String s, int minor, CompletionStatus completed) {
        super(s, minor, completed);
    }
}


text:
/**
 * A display-only text field which is not validated and not submitted. This is useful for when you want to display a
 * value from a form's {@link Ext.form.Basic#load loaded data} but do not want to allow the user to edit or submit that
 * value. The value can be optionally {@link #htmlEncode HTML encoded} if it contains HTML markup that you do not want
 * to be rendered.
 *
 * If you have more complex content, or need to include components within the displayed content, also consider using a
 * {@link Ext.form.FieldContainer} instead.
 *
 * Example:
 *
 *     @example
 *     Ext.create('Ext.form.Panel', {
 *         renderTo: Ext.getBody(),
 *         width: 175,
 *         height: 150,
 *         bodyPadding: 10,
 *         title: 'Final Score',
 *         items: [{
 *             xtype: 'displayfield',
 *             fieldLabel: 'Home',
 *             name: 'home_score',
 *             value: '10'
 *         }, {
 *             xtype: 'displayfield',
 *             fieldLabel: 'Visitor',
 *             name: 'visitor_score',
 *             value: '11'
 *         }],
 *         buttons: [{
 *             text: 'Update'
 *         }]
 *     });
 */
Ext.define('Ext.form.field.Display', {
    extend:'Ext.form.field.Base',
    alias: 'widget.displayfield',
    requires: ['Ext.util.Format', 'Ext.XTemplate'],
    alternateClassName: ['Ext.form.DisplayField', 'Ext.form.Display'],

    fieldSubTpl: [
        '<div id="{id}" data-ref="inputEl" tabindex="-1" role="textbox" aria-readonly="true"',
        ' aria-labelledby="{cmpId}-labelEl" {inputAttrTpl}',
        '<tpl if="fieldStyle"> style="{fieldStyle}"</tpl>',
        ' class="{fieldCls} {fieldCls}-{ui}">{value}
',
        {
            compiled: true,
            disableFormats: true
        }
    ],

    // We have the ARIA markup pre-rendered so we don't want it to be applied
    ariaRole: undefined,

    focusable: false,

    /**
     * @cfg {Boolean} readOnly
     * @private
     */
    readOnly: true,

    /**
     * @cfg {String} [fieldCls="x-form-display-field"]
     * The default CSS class for the field.
     */
    fieldCls: Ext.baseCSSPrefix + 'form-display-field',

    fieldBodyCls: Ext.baseCSSPrefix + 'form-display-field-body',

    /**
     * @cfg {Boolean} htmlEncode
     * True to escape HTML in text when rendering it.
     */
    htmlEncode: false,

    /**
     * @cfg {Function} renderer
     * A function to transform the raw value for display in the field.
     *
     *     Ext.create('Ext.form.Panel', {
     *         renderTo: document.body,
     *         width: 175,
     *         bodyPadding: 10,
     *         title: 'Final Score',
     *         items: [{
     *             xtype: 'displayfield',
     *             fieldLabel: 'Grade',
     *             name: 'final_grade',
     *             value: 68,
     *             renderer: function (value, field) {
     *                 var color = (value < 70) ? 'red' : 'black';
     *                 return '' + value + '';
     *             }
     *         }]
     *     });
     *
     * @param {Object} value The raw field {@link #value}
     * @param {Ext.form.field.Display} field The display field
     * @return {String} displayValue The HTML string to be rendered
     */

    /**
     * @cfg {Object} scope
     * The scope to execute the {@link #renderer} function. Defaults to this.
     */

    noWrap: false,

    /**
     * @cfg {Boolean} validateOnChange
     * @private
     */
    validateOnChange: false,

    initEvents: Ext.emptyFn,

    submitValue: false,

    getValue: function() {
        return this.value;
    },

    valueToRaw: function(value) {
        if (value || value === 0 || value === false) {
            return value;
        } else {
            return '';
        }
    },

    isDirty: function(){
        return false;
    },

    isValid: Ext.returnTrue,

    validate: Ext.returnTrue,

    getRawValue: function() {
        return this.rawValue;
    },

    setRawValue: function(value) {
        var me = this;

        value = Ext.valueFrom(value, '');
        me.rawValue = value;
        if (me.rendered) {
            me.inputEl.dom.innerHTML = me.getDisplayValue();
            me.updateLayout();
        }
        return value;
    },

    /**
     * @private
     * Format the value to display.
     */
    getDisplayValue: function() {
        var me = this,
            value = this.getRawValue(),
            display;
        if (me.renderer) {
             display = me.renderer.call(me.scope || me, value, me);
        } else {
             display = me.htmlEncode ? Ext.util.Format.htmlEncode(value) : value;
        }
        return display;
    },

    getSubTplData: function(fieldData) {
        var ret = this.callParent(arguments);

        ret.value = this.getDisplayValue();

        return ret;
    }

    /**
     * @cfg {String} inputType
     * @private
     */
    /**
     * @cfg {Boolean} disabled
     * @private
     */
    /**
     * @cfg {Number} checkChangeEvents
     * @private
     */
    /**
     * @cfg {Number} checkChangeBuffer
     * @private
     */
});


text:
namespace ray {
namespace rpc {

void DefaultWorkerInfoHandler::HandleReportWorkerFailure(
    const ReportWorkerFailureRequest &request, ReportWorkerFailureReply *reply,
    SendReplyCallback send_reply_callback) {
  Address worker_address = request.worker_failure().worker_address();
  RAY_LOG(DEBUG) << "Reporting worker failure, " << worker_address.DebugString();
  auto worker_failure_data = std::make_shared<WorkerFailureData>();
  worker_failure_data->CopyFrom(request.worker_failure());
  auto on_done = [worker_address, send_reply_callback](Status status) {
    if (!status.ok()) {
      RAY_LOG(ERROR) << "Failed to report worker failure, "
                     << worker_address.DebugString();
    }
    send_reply_callback(status, nullptr, nullptr);
  };

  Status status =
      gcs_client_.Workers().AsyncReportWorkerFailure(worker_failure_data, on_done);
  if (!status.ok()) {
    on_done(status);
  }
  RAY_LOG(DEBUG) << "Finished reporting worker failure, " << worker_address.DebugString();
}

}  // namespace rpc
}  // namespace ray


text:
if (!window.mybtcprice) {
  window.mybtcprice = {};
}

$(document).ready(function() {
  var rate = 0;

  function getPrice() {
    $.ajax({
      url: "https://apiv2.bitcoinaverage.com/indices/global/ticker/BTCUSD", success: function(result) {
      if (result && result.last) {
        rate = result.last;
        var myTime = new Date(result.timestamp * 1000);
        $('#time').text(myTime);
        $("#price-label").text(rate);
        $('#refresh').text('Refresh');
        calculate();
      } else {
        console.error('ajax error');
      }
    }});
  }

  // Reload price on clicking "Refresh"
  $( "#refresh" ).click(function() {
    $('#refresh').text('Refreshing');
    $('#time').text('Refreshing time');
    getPrice();
  });

  // Trigger calculation on text change.
  $( "input" ).change(function() {
    calculate(this.name);
  });
  $( "input" ).on('input', function() {
    calculate(this.name);
  });

  // Rounding value to the nearest x
  function nearest(n, v) {
    n = n / v;
    n = Math.round(n) * v;
    return n;
  }
  // Rounding value to the x decimal
  function precision(n, dp) {
    dp = Math.pow(10, dp);
    n = n * dp;
    n = Math.round(n);
    n = n / dp;
    return n;
  }

  function init() {
    // Set the commission
    $("input[name='commission']").val(mybtcprice.commission);
    $("input[name='commission']").prop('disabled', mybtcprice.commission_locked);
    getPrice();
  }

  // Calculate other fields based on the "change" parameter.
  // "change" is the name of the field which has changed.
  function calculate(change) {
    var buy_amount_USD = Number($("input[name='buy_amount_USD']").val());
    var buy_amount_BTC = Number($("input[name='buy_amount_BTC']").val());
    var buy_amount_mBTC = Number($("input[name='buy_amount_mBTC']").val());
    var total_USD = Number($("input[name='total_USD']").val());
    var commission = Number($("input[name='commission']").val());

    // If the user knows how much BTC they want.
    if (change === 'buy_amount_BTC') {
      // buy_amount_BTC * rate
      buy_amount_USD = precision(buy_amount_BTC * rate, 2);
    }
    if (change === 'buy_amount_mBTC') {
      // (buy_amount_mBTC / 1000) * rate
      buy_amount_USD = precision((buy_amount_mBTC / 1000) * rate, 2);
    }

    if (change !== 'total_USD') {
      // buy_amount_USD * (1 + commission / 100)
      total_USD = nearest(buy_amount_USD / (1 - (commission / 100.00)), 1);
      total_USD = (total_USD <= buy_amount_USD && buy_amount_USD !== 0) ? total_USD + 5 : total_USD;
      $("input[name='total_USD']").val(total_USD);
    }
    if (change !== 'buy_amount_USD') {
      // total_USD / (1 + commission / 100)
      buy_amount_USD = nearest(total_USD * (1 - (commission / 100.00)), 1);
      $("input[name='buy_amount_USD']").val(buy_amount_USD);
    }
    if (change !== 'buy_amount_BTC' && change !== 'buy_amount_mBTC') {
      // rate / buy_amount_USD
      buy_amount_BTC = precision(buy_amount_USD / rate, 8);
      $("input[name='buy_amount_BTC']").val(buy_amount_BTC);
    }
    if (change !== 'buy_amount_BTC' && change === 'buy_amount_mBTC') {
      // buy_amount_mBTC / 1000
      buy_amount_BTC = precision(buy_amount_mBTC / 1000, 8);
      $("input[name='buy_amount_BTC']").val(buy_amount_BTC);
    }
    if (change !== 'buy_amount_mBTC') {
      // buy_amount_BTC * 1000
      buy_amount_mBTC = precision(buy_amount_BTC * 1000, 8);
      $("input[name='buy_amount_mBTC']").val(buy_amount_mBTC);
    }

    // total_USD - buy_amount_USD
    $('#fee_total').text(total_USD - buy_amount_USD);
  }

  init();
});


text:
require 'spec_helper'

feature 'visitor has consecutive bad logins' do
  before do
    @user = create(:user)
    Authenticate.configuration.max_consecutive_bad_logins_allowed = 2
  end

  scenario 'less than max bad logins does not lock account' do
    sign_in_with @user.email, 'badpassword'
    sign_in_with @user.email, 'badpassword'
    sign_in_with @user.email, @user.password

    expect_user_to_be_signed_in
  end

  scenario 'exceeds max bad logins and locks account' do
    sign_in_with @user.email, 'badpassword'
    sign_in_with @user.email, 'badpassword'
    sign_in_with @user.email, 'badpassword'

    expect_locked_account
    expect_lockout_time_to_be_displayed
    expect_user_to_be_signed_out
  end

  scenario 'user locks account, waits for lock to expire, logs in successfully' do
    sign_in_with @user.email, 'badpassword'
    sign_in_with @user.email, 'badpassword'
    sign_in_with @user.email, 'badpassword'

    Timecop.travel 50.minutes do
      sign_in_with @user.email, @user.password
      expect_user_to_be_signed_in
    end
  end
end

def expect_locked_account
  expect(page).to have_content 'Your account is locked'
end

def expect_lockout_time_to_be_displayed
  expect(page).to have_content '10 minutes'
end


text:
package org.drools.builder;

/**
 * An enum of the available problem types
 *
 */
public enum ResultSeverity {
    ERROR,
    WARNING,
    INFO

}


text:
/*global define,$,document,setTimeout */
/*jslint sloppy:true */
/*
| Copyright 2014 Esri
|
| Licensed under the Apache License, Version 2.0 (the "License");
| you may not use this file except in compliance with the License.
| You may obtain a copy of the License at
|
|    http://www.apache.org/licenses/LICENSE-2.0
|
| Unless required by applicable law or agreed to in writing, software
| distributed under the License is distributed on an "AS IS" BASIS,
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
| See the License for the specific language governing permissions and
| limitations under the License.
*/
define([
    "dojo/_base/declare",
    "dojo/dom-construct",
    "dojo/text!./templates/warning.html",
    "dijit/_WidgetBase",
    "dijit/_TemplatedMixin",
    "dijit/_WidgetsInTemplateMixin",
    "dojo/_base/lang",
    "dojo/domReady!"
], function (
    declare,
    domConstruct,
    template,
    _WidgetBase,
    _TemplatedMixin,
    _WidgetsInTemplateMixin,
    lang

) {
    return declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin], {
        templateString: template,  //  a string representing the HTML of the template

        /**
        * This function is called when widget is constructed.
        * @param{object} parameters of widget
        * @memberOf widgets/warning/warning
        */
        constructor: function (options) {
            lang.mixin(this, options);
        },

        /**
        * This method is designed to handle processing after any DOM fragments have been actually added to the document.
        * @memberOf widgets/warning/warning
        */
        startup: function () {
            this._setHelpWindowTitle();
            this._setHelpWindowContent();
            this._showHelpDialog();
        },

        /**
        * This function is used to set title of help dialog
        * @memberOf widgets/warning/warning
        */
        _setHelpWindowTitle: function () {
            domConstruct.place(template, document.body, 'last');
            $('#helpModalWrapperContainer').find('.modal-title').html(this.appConfig.helpDialogTitle);
        },

        /**
        * This function is used to set content of help dialog
        * @memberOf widgets/warning/warning
        */
        _setHelpWindowContent: function () {
            $('#helpModalWrapperContainer').find('.modal-body').html(this.appConfig.helpDialogContent);
        },

        /**
        * This function is used to show help dialog
        * @memberOf widgets/warning/warning
        */
        _showHelpDialog: function () {
            $("#helpModalWrapperContainer").modal("show");
            // set modal templates scroll position to 0
            setTimeout(function () {
                $('#helpModalWrapperContainer').find('.modal-body')[0].scrollTop = 0;
            }, 200);
        }
    });
});


text: var GMapJSONTiles = (function() {


text:
cask "navicat-for-mariadb" do
  version "15.0.22"
  sha256 "a3461c161b3dd14265ff9e7e8db6366598fdd25c3b65f97034b9962ffaf9fcaa"

  url "http://download.navicat.com/download/navicat#{version.major_minor.no_dots}_mariadb_en.dmg"
  appcast "https://updater.navicat.com/mac/navicat_updates.php?appName=Navicat%20for%20MariaDB&appLang=en"
  name "Navicat for MariaDB"
  desc "Database management and administration tool for MariaDB"
  homepage "https://www.navicat.com/products/navicat-for-mariadb"

  app "Navicat for MariaDB.app"
end


text:
This package contains classes that implement a logging
    mechanism similar to the one in JDK
    1.4.  While the basic mechanism is present, many of the more
    advanced features (such as writing logs as XML and performing
    filtering) are not implemented.

Logger logger = Logger.getLogger("com.gemstone.persistence.jdo");
...
// Send logging output to a file, by default it will go to System.err
Handler handler = new StreamHandler(new FileOutputStream(file),
                                    new SimpleFormatter());
logger.addHandler(handler);
...
logger.warning("Could not find file: " + fileName);
...
// Ignore all messages that are lower than Level.INFO
logger.setLevel(Level.INFO);
...
logger.throwing("com.gemstone.persistence.jdo.StateManagerImpl",
                "readFile", ex);
..
logger.info("Found these objects: ", objs);

A Logger's level may also be specified at runtime using a
      system propery.  To set the level of the logger name
      "com.gemstone.persistence.jdo.Logger" to FINE use

<TT>-Dcom.gemstone.persistence.jdo.Logger.LEVEL=FINE</TT>

If the com.gemstone.persistence.logging.StackTraces
system property is set to true, then a stack trace will
be printed along with every message.


text:
import { swap, left, right } from "./util"
import { Sortable } from "../model/Sortable";

export class Quicksort implements Sortable {

    /**
     * Takes -> O ( k )
     *
     * @param {*} arr
     * @param {*} leftIndex
     * @param {*} rightIndex
     */
    partition(arr: number[], leftIndex: number, rightIndex: number): number {
        let pivotValue: number = arr[rightIndex];
        let maxMinIndex = leftIndex - 1;

        for (let index = leftIndex; index < rightIndex; index++) {
            if (arr[index] <= pivotValue) {
                maxMinIndex = maxMinIndex + 1;
                swap(arr, index, maxMinIndex);
            }
        }
        maxMinIndex = maxMinIndex + 1;
        swap(arr, maxMinIndex, rightIndex);
        return maxMinIndex;
    }

    quicksort(arr: number[], leftIndex: number, rightIndex: number): void {
        if (leftIndex < rightIndex) {
            let middle: number = this.partition(arr, leftIndex, rightIndex);
            this.quicksort(arr, leftIndex, middle - 1);
            this.quicksort(arr, middle + 1, rightIndex);
        }
    }

    /**
     * Take -> O( n log n )
     *
     * @param arr
     */
    sort(arr: number[]) {
        this.quicksort(arr, 0, arr.length - 1);
    }
}