text:
using gpu::gles2::GLES2Interface;
using gpu::ContextSupport;

namespace {

class ScopedCallingGLFromSkia {
 public:
  ScopedCallingGLFromSkia(ContextSupport* context_support)
      : context_support_(context_support) {
    context_support_->WillCallGLFromSkia();
  }
  ~ScopedCallingGLFromSkia() { context_support_->DidCallGLFromSkia(); }

 private:
  raw_ptr<ContextSupport> context_support_;
};

template <typename R, typename... Args>
GrGLFunction<R GR_GL_FUNCTION_TYPE(Args...)> gles_bind(
    R (GLES2Interface::*func)(Args...),
    GLES2Interface* gles2_interface,
    ContextSupport* context_support) {
  if (context_support->HasGrContextSupport()) {
    return [func, context_support, gles2_interface](Args... args) {
      ScopedCallingGLFromSkia guard(context_support);
      return (gles2_interface->*func)(args...);
    };
  }

  // This fallback binding should only be used by unit tests which do not care
  // about GrContext::resetContext() getting called automatically.
  return [func, gles2_interface](Args... args) {
    return (gles2_interface->*func)(args...);
  };
}
}  // namespace

namespace skia_bindings {

sk_sp<GrGLInterface> CreateGLES2InterfaceBindings(
    GLES2Interface* impl,
    ContextSupport* context_support) {
  sk_sp<GrGLInterface> interface(new GrGLInterface);
  interface->fStandard = kGLES_GrGLStandard;

  // Allowing Skia to use GL ES 3.0 caused a perf test regression (see Issue
  // 719572). Until that can be understood we are limiting to ES 2.0 (with
  // extensions).
  auto get_string = [impl](GLenum name) {
    if (name == GL_VERSION)
      return reinterpret_cast<const GLubyte*>("OpenGL ES 2.0 Chromium");
    return impl->GetString(name);
  };
  auto get_stringi =
      gles_bind(&GLES2Interface::GetStringi, impl, context_support);
  auto get_integerv =
      gles_bind(&GLES2Interface::GetIntegerv, impl, context_support);
  interface->fExtensions.init(kGLES_GrGLStandard, get_string, get_stringi,
                              get_integerv);

  GrGLInterface::Functions* functions = &interface->fFunctions;
  functions->fActiveTexture =
      gles_bind(&GLES2Interface::ActiveTexture, impl, context_support);
  functions->fAttachShader =
      gles_bind(&GLES2Interface::AttachShader, impl, context_support);
  functions->fBindAttribLocation =
      gles_bind(&GLES2Interface::BindAttribLocation, impl, context_support);
  functions->fBindBuffer =
      gles_bind(&GLES2Interface::BindBuffer, impl, context_support);
  functions->fBindTexture =
      gles_bind(&GLES2Interface::BindTexture, impl, context_support);
  functions->fBindSampler =
      gles_bind(&GLES2Interface::BindSampler, impl, context_support);
  functions->fBindVertexArray =
      gles_bind(&GLES2Interface::BindVertexArrayOES, impl, context_support);
  functions->fBlendBarrier =
      gles_bind(&GLES2Interface::BlendBarrierKHR, impl, context_support);
  functions->fBlendColor =
      gles_bind(&GLES2Interface::BlendColor, impl, context_support);
  functions->fBlendEquation =
      gles_bind(&GLES2Interface::BlendEquation, impl, context_support);
  functions->fBlendFunc =
      gles_bind(&GLES2Interface::BlendFunc, impl, context_support);
  functions->fBufferData =
      gles_bind(&GLES2Interface::BufferData, impl, context_support);
  functions->fBufferSubData =
      gles_bind(&GLES2Interface::BufferSubData, impl, context_support);
  functions->fClear = gles_bind(&GLES2Interface::Clear, impl, context_support);
  functions->fClearColor =
      gles_bind(&GLES2Interface::ClearColor, impl, context_support);
  functions->fClearStencil =
      gles_bind(&GLES2Interface::ClearStencil, impl, context_support);
  functions->fClientWaitSync =
      gles_bind(&GLES2Interface::ClientWaitSync, impl, context_support);
  functions->fColorMask =
      gles_bind(&GLES2Interface::ColorMask, impl, context_support);
  functions->fCompileShader =
      gles_bind(&GLES2Interface::CompileShader, impl, context_support);
  functions->fCompressedTexImage2D =
      gles_bind(&GLES2Interface::CompressedTexImage2D, impl, context_support);
  functions->fCompressedTexSubImage2D = gles_bind(
      &GLES2Interface::CompressedTexSubImage2D, impl, context_support);
  functions->fCopyBufferSubData =
        gles_bind(&GLES2Interface::CopyBufferSubData, impl, context_support);
  functions->fCopyTexSubImage2D =
      gles_bind(&GLES2Interface::CopyTexSubImage2D, impl, context_support);
  functions->fCreateProgram =
      gles_bind(&GLES2Interface::CreateProgram, impl, context_support);
  functions->fCreateShader =
      gles_bind(&GLES2Interface::CreateShader, impl, context_support);
  functions->fCullFace =
      gles_bind(&GLES2Interface::CullFace, impl, context_support);
  functions->fDeleteBuffers =
      gles_bind(&GLES2Interface::DeleteBuffers, impl, context_support);
  functions->fDeleteProgram =
      gles_bind(&GLES2Interface::DeleteProgram, impl, context_support);
  functions->fDeleteSamplers =
      gles_bind(&GLES2Interface::DeleteSamplers, impl, context_support);
  functions->fDeleteShader =
      gles_bind(&GLES2Interface::DeleteShader, impl, context_support);
  functions->fDeleteSync =
      gles_bind(&GLES2Interface::DeleteSync, impl, context_support);
  functions->fDeleteTextures =
      gles_bind(&GLES2Interface::DeleteTextures, impl, context_support);
  functions->fDeleteVertexArrays =
      gles_bind(&GLES2Interface::DeleteVertexArraysOES, impl, context_support);
  functions->fDepthMask =
      gles_bind(&GLES2Interface::DepthMask, impl, context_support);
  functions->fDisable =
      gles_bind(&GLES2Interface::Disable, impl, context_support);
  functions->fDisableVertexAttribArray = gles_bind(
      &GLES2Interface::DisableVertexAttribArray, impl, context_support);
  functions->fDiscardFramebuffer =
      gles_bind(&GLES2Interface::DiscardFramebufferEXT, impl, context_support);
  functions->fDrawArrays =
      gles_bind(&GLES2Interface::DrawArrays, impl, context_support);
  functions->fDrawArraysInstanced = gles_bind(
      &GLES2Interface::DrawArraysInstancedANGLE, impl, context_support);
  functions->fDrawBuffers =
      gles_bind(&GLES2Interface::DrawBuffersEXT, impl, context_support);
  functions->fDrawElements =
      gles_bind(&GLES2Interface::DrawElements, impl, context_support);
  functions->fDrawElementsInstanced = gles_bind(
      &GLES2Interface::DrawElementsInstancedANGLE, impl, context_support);
  functions->fDrawRangeElements =
      gles_bind(&GLES2Interface::DrawRangeElements, impl, context_support);
  functions->fEnable =
      gles_bind(&GLES2Interface::Enable, impl, context_support);
  functions->fEnableVertexAttribArray = gles_bind(
      &GLES2Interface::EnableVertexAttribArray, impl, context_support);
  functions->fEndQuery =
      gles_bind(&GLES2Interface::EndQueryEXT, impl, context_support);
  functions->fFenceSync =
      gles_bind(&GLES2Interface::FenceSync, impl, context_support);
  functions->fFinish =
      gles_bind(&GLES2Interface::Finish, impl, context_support);
  functions->fFlush = gles_bind(&GLES2Interface::Flush, impl, context_support);
  functions->fFlushMappedBufferRange =
      gles_bind(&GLES2Interface::FlushMappedBufferRange, impl, context_support);
  functions->fFrontFace =
      gles_bind(&GLES2Interface::FrontFace, impl, context_support);
  functions->fGenBuffers =
      gles_bind(&GLES2Interface::GenBuffers, impl, context_support);
  functions->fGenSamplers =
      gles_bind(&GLES2Interface::GenSamplers, impl, context_support);
  functions->fGenTextures =
      gles_bind(&GLES2Interface::GenTextures, impl, context_support);
  functions->fGenVertexArrays =
      gles_bind(&GLES2Interface::GenVertexArraysOES, impl, context_support);
  functions->fGetBufferParameteriv =
      gles_bind(&GLES2Interface::GetBufferParameteriv, impl, context_support);
  functions->fGetError =
      gles_bind(&GLES2Interface::GetError, impl, context_support);
  functions->fGetFloatv =
      gles_bind(&GLES2Interface::GetFloatv, impl, context_support);
  functions->fGetIntegerv = get_integerv;
  functions->fGetInternalformativ =
      gles_bind(&GLES2Interface::GetInternalformativ, impl, context_support);
  functions->fGetProgramInfoLog =
      gles_bind(&GLES2Interface::GetProgramInfoLog, impl, context_support);
  functions->fGetProgramiv =
      gles_bind(&GLES2Interface::GetProgramiv, impl, context_support);
  functions->fGetQueryiv =
      gles_bind(&GLES2Interface::GetQueryivEXT, impl, context_support);
  functions->fGetQueryObjectuiv =
      gles_bind(&GLES2Interface::GetQueryObjectuivEXT, impl, context_support);
  functions->fGetShaderInfoLog =
      gles_bind(&GLES2Interface::GetShaderInfoLog, impl, context_support);
  functions->fGetShaderiv =
      gles_bind(&GLES2Interface::GetShaderiv, impl, context_support);
  functions->fGetShaderPrecisionFormat = gles_bind(
      &GLES2Interface::GetShaderPrecisionFormat, impl, context_support);
  functions->fGetString = get_string;
  functions->fGetStringi = get_stringi;
  functions->fGetUniformLocation =
      gles_bind(&GLES2Interface::GetUniformLocation, impl, context_support);
  functions->fInsertEventMarker =
      gles_bind(&GLES2Interface::InsertEventMarkerEXT, impl, context_support);
  functions->fInvalidateFramebuffer =
      gles_bind(&GLES2Interface::InvalidateFramebuffer, impl, context_support);
  functions->fInvalidateSubFramebuffer = gles_bind(
      &GLES2Interface::InvalidateSubFramebuffer, impl, context_support);
  functions->fIsSync =
      gles_bind(&GLES2Interface::IsSync, impl, context_support);
  functions->fIsTexture =
      gles_bind(&GLES2Interface::IsTexture, impl, context_support);
  functions->fLineWidth =
      gles_bind(&GLES2Interface::LineWidth, impl, context_support);
  functions->fLinkProgram =
      gles_bind(&GLES2Interface::LinkProgram, impl, context_support);
  functions->fMapBufferRange =
      gles_bind(&GLES2Interface::MapBufferRange, impl, context_support);
  functions->fMapBufferSubData = gles_bind(
      &GLES2Interface::MapBufferSubDataCHROMIUM, impl, context_support);
  functions->fMapTexSubImage2D = gles_bind(
      &GLES2Interface::MapTexSubImage2DCHROMIUM, impl, context_support);
  functions->fPixelStorei =
      gles_bind(&GLES2Interface::PixelStorei, impl, context_support);
  functions->fPopGroupMarker =
      gles_bind(&GLES2Interface::PopGroupMarkerEXT, impl, context_support);
  functions->fPushGroupMarker =
      gles_bind(&GLES2Interface::PushGroupMarkerEXT, impl, context_support);
  functions->fReadBuffer =
      gles_bind(&GLES2Interface::ReadBuffer, impl, context_support);
  functions->fReadPixels =
      gles_bind(&GLES2Interface::ReadPixels, impl, context_support);
  functions->fSamplerParameterf =
      gles_bind(&GLES2Interface::SamplerParameterf, impl, context_support);
  functions->fSamplerParameteri =
      gles_bind(&GLES2Interface::SamplerParameteri, impl, context_support);
  functions->fSamplerParameteriv =
      gles_bind(&GLES2Interface::SamplerParameteriv, impl, context_support);
  functions->fScissor =
      gles_bind(&GLES2Interface::Scissor, impl, context_support);
  functions->fShaderSource =
      gles_bind(&GLES2Interface::ShaderSource, impl, context_support);
  functions->fStencilFunc =
      gles_bind(&GLES2Interface::StencilFunc, impl, context_support);
  functions->fStencilFuncSeparate =
      gles_bind(&GLES2Interface::StencilFuncSeparate, impl, context_support);
  functions->fStencilMask =
      gles_bind(&GLES2Interface::StencilMask, impl, context_support);
  functions->fStencilMaskSeparate =
      gles_bind(&GLES2Interface::StencilMaskSeparate, impl, context_support);
  functions->fStencilOp =
      gles_bind(&GLES2Interface::StencilOp, impl, context_support);
  functions->fStencilOpSeparate =
      gles_bind(&GLES2Interface::StencilOpSeparate, impl, context_support);
  functions->fTexImage2D =
      gles_bind(&GLES2Interface::TexImage2D, impl, context_support);
  functions->fTexParameterf =
      gles_bind(&GLES2Interface::TexParameterf, impl, context_support);
  functions->fTexParameterfv =
      gles_bind(&GLES2Interface::TexParameterfv, impl, context_support);
  functions->fTexParameteri =
      gles_bind(&GLES2Interface::TexParameteri, impl, context_support);
  functions->fTexParameteriv =
      gles_bind(&GLES2Interface::TexParameteriv, impl, context_support);
  functions->fTexStorage2D =
      gles_bind(&GLES2Interface::TexStorage2DEXT, impl, context_support);
  functions->fTexSubImage2D =
      gles_bind(&GLES2Interface::TexSubImage2D, impl, context_support);
  functions->fUniform1f =
      gles_bind(&GLES2Interface::Uniform1f, impl, context_support);
  functions->fUniform1i =
      gles_bind(&GLES2Interface::Uniform1i, impl, context_support);
  functions->fUniform1fv =
      gles_bind(&GLES2Interface::Uniform1fv, impl, context_support);
  functions->fUniform1iv =
      gles_bind(&GLES2Interface::Uniform1iv, impl, context_support);
  functions->fUniform2f =
      gles_bind(&GLES2Interface::Uniform2f, impl, context_support);
  functions->fUniform2i =
      gles_bind(&GLES2Interface::Uniform2i, impl, context_support);
  functions->fUniform2fv =
      gles_bind(&GLES2Interface::Uniform2fv, impl, context_support);
  functions->fUniform2iv =
      gles_bind(&GLES2Interface::Uniform2iv, impl, context_support);
  functions->fUniform3f =
      gles_bind(&GLES2Interface::Uniform3f, impl, context_support);
  functions->fUniform3i =
      gles_bind(&GLES2Interface::Uniform3i, impl, context_support);
  functions->fUniform3fv =
      gles_bind(&GLES2Interface::Uniform3fv, impl, context_support);
  functions->fUniform3iv =
      gles_bind(&GLES2Interface::Uniform3iv, impl, context_support);
  functions->fUniform4f =
      gles_bind(&GLES2Interface::Uniform4f, impl, context_support);
  functions->fUniform4i =
      gles_bind(&GLES2Interface::Uniform4i, impl, context_support);
  functions->fUniform4fv =
      gles_bind(&GLES2Interface::Uniform4fv, impl, context_support);
  functions->fUniform4iv =
      gles_bind(&GLES2Interface::Uniform4iv, impl, context_support);
  functions->fUniformMatrix2fv =
      gles_bind(&GLES2Interface::UniformMatrix2fv, impl, context_support);
  functions->fUniformMatrix3fv =
      gles_bind(&GLES2Interface::UniformMatrix3fv, impl, context_support);
  functions->fUniformMatrix4fv =
      gles_bind(&GLES2Interface::UniformMatrix4fv, impl, context_support);
  functions->fUnmapBufferSubData = gles_bind(
      &GLES2Interface::UnmapBufferSubDataCHROMIUM, impl, context_support);
  functions->fUnmapTexSubImage2D = gles_bind(
      &GLES2Interface::UnmapTexSubImage2DCHROMIUM, impl, context_support);
  functions->fUseProgram =
      gles_bind(&GLES2Interface::UseProgram, impl, context_support);
  functions->fVertexAttrib1f =
      gles_bind(&GLES2Interface::VertexAttrib1f, impl, context_support);
  functions->fVertexAttrib2fv =
      gles_bind(&GLES2Interface::VertexAttrib2fv, impl, context_support);
  functions->fVertexAttrib3fv =
      gles_bind(&GLES2Interface::VertexAttrib3fv, impl, context_support);
  functions->fVertexAttrib4fv =
      gles_bind(&GLES2Interface::VertexAttrib4fv, impl, context_support);
  functions->fVertexAttribDivisor = gles_bind(
      &GLES2Interface::VertexAttribDivisorANGLE, impl, context_support);
  functions->fVertexAttribPointer =
      gles_bind(&GLES2Interface::VertexAttribPointer, impl, context_support);
  functions->fVertexAttribIPointer =
      gles_bind(&GLES2Interface::VertexAttribIPointer, impl, context_support);
  functions->fViewport =
      gles_bind(&GLES2Interface::Viewport, impl, context_support);
  functions->fWaitSync =
      gles_bind(&GLES2Interface::WaitSync, impl, context_support);
  functions->fBindFramebuffer =
      gles_bind(&GLES2Interface::BindFramebuffer, impl, context_support);
  functions->fBeginQuery =
      gles_bind(&GLES2Interface::BeginQueryEXT, impl, context_support);
  functions->fBindRenderbuffer =
      gles_bind(&GLES2Interface::BindRenderbuffer, impl, context_support);
  functions->fCheckFramebufferStatus =
      gles_bind(&GLES2Interface::CheckFramebufferStatus, impl, context_support);
  functions->fDeleteFramebuffers =
      gles_bind(&GLES2Interface::DeleteFramebuffers, impl, context_support);
  functions->fDeleteQueries =
      gles_bind(&GLES2Interface::DeleteQueriesEXT, impl, context_support);
  functions->fDeleteRenderbuffers =
      gles_bind(&GLES2Interface::DeleteRenderbuffers, impl, context_support);
  functions->fFramebufferRenderbuffer = gles_bind(
      &GLES2Interface::FramebufferRenderbuffer, impl, context_support);
  functions->fFramebufferTexture2D =
      gles_bind(&GLES2Interface::FramebufferTexture2D, impl, context_support);
  functions->fFramebufferTexture2DMultisample =
      gles_bind(&GLES2Interface::FramebufferTexture2DMultisampleEXT, impl,
                context_support);
  functions->fGenFramebuffers =
      gles_bind(&GLES2Interface::GenFramebuffers, impl, context_support);
  functions->fGenRenderbuffers =
      gles_bind(&GLES2Interface::GenRenderbuffers, impl, context_support);
  functions->fGetFramebufferAttachmentParameteriv =
      gles_bind(&GLES2Interface::GetFramebufferAttachmentParameteriv, impl,
                context_support);
  functions->fGetRenderbufferParameteriv = gles_bind(
      &GLES2Interface::GetRenderbufferParameteriv, impl, context_support);
  functions->fGenQueries =
      gles_bind(&GLES2Interface::GenQueriesEXT, impl, context_support);
  functions->fRenderbufferStorage =
      gles_bind(&GLES2Interface::RenderbufferStorage, impl, context_support);
  functions->fRenderbufferStorageMultisample =
      gles_bind(&GLES2Interface::RenderbufferStorageMultisampleCHROMIUM, impl,
                context_support);
  functions->fRenderbufferStorageMultisampleES2EXT =
      gles_bind(&GLES2Interface::RenderbufferStorageMultisampleEXT, impl,
                context_support);
  functions->fBindFragDataLocation = gles_bind(
      &GLES2Interface::BindFragDataLocationEXT, impl, context_support);
  functions->fBindFragDataLocationIndexed = gles_bind(
      &GLES2Interface::BindFragDataLocationIndexedEXT, impl, context_support);
  functions->fBindUniformLocation = gles_bind(
      &GLES2Interface::BindUniformLocationCHROMIUM, impl, context_support);
  functions->fBlitFramebuffer = gles_bind(
      &GLES2Interface::BlitFramebufferCHROMIUM, impl, context_support);
  functions->fGenerateMipmap =
      gles_bind(&GLES2Interface::GenerateMipmap, impl, context_support);
  functions->fCoverageModulation = gles_bind(
      &GLES2Interface::CoverageModulationCHROMIUM, impl, context_support);
  functions->fWindowRectangles =
      gles_bind(&GLES2Interface::WindowRectanglesEXT, impl, context_support);
  // Skia should not use program binaries over the command buffer. Allowing
  // clients to submit them would be unsafe, and we already cache program
  // binaries internally anyway.
  functions->fGetProgramBinary = [](GLuint, GLsizei, GLsizei*, GLenum*, void*) {
    LOG(FATAL) << "Skia shouldn't use program binaries over the command buffer";
  };
  functions->fProgramBinary = [](GLuint, GLenum, const void*, GLsizei) {
    LOG(FATAL) << "Skia shouldn't use program binaries over the command buffer";
  };
  functions->fProgramParameteri = [](GLuint, GLenum pname, GLint) {
    // This method is only used for GL_PROGRAM_BINARY_RETRIEVABLE_HINT in ES3.
    LOG(FATAL) << "Skia shouldn't use program binaries over the command buffer";
  };
  return interface;
}

}  // namespace skia_bindings


text:
import { VNodeContent } from "../common"

import {
    TableDataCellKey,
    TableDataColumnSimple,
    TableDataHeaderSimple,
    TableDataParams,
    TableDataSummarySimple,
    TableDataView,
    TableDataVisibleKeys,
} from "../core"

import { tableDataMutable_base } from "../mutable/base"
import { tableDataMutable_leaf } from "../mutable/leaf"
import { TableDataMutable_base, TableDataMutable_leaf } from "../mutable"
import {
    isVisibleKey,
    TableDataAlwaysVisible,
    TableDataColumnContentProvider,
    TableDataInvisible,
    TableDataRelatedParams,
    TableCellSimple,
    TableDataStyledParams,
} from "../cell"
import {
    decorateContent,
    decorateStyle,
    TableDataColumnDecorator,
    TableDataColumnRelatedDecorator,
    TableDataContentDecorator,
    TableDataHeaderDecorator,
    TableDataHorizontalBorderProvider,
    TableDataSummaryContentProvider,
    TableDataSummaryDecorator,
    TableDataSummaryProvider,
    TableDataViewDecorator,
} from "../decorator"
import {
    extendStyle,
    mergeVerticalBorder,
    TableDataHorizontalBorder,
    TableDataStyle,
    TableDataVerticalBorder,
    TableDataVerticalBorderStyle,
} from "../style"

export type TableDataSimpleContent<M, R> =
    | TableDataSimpleContent_base<R>
    | (TableDataSimpleContent_base<R> & TableDataSimpleContent_summary<M>)
    | (TableDataSimpleContent_base<R> & TableDataSimpleContent_footer<M>)
    | (TableDataSimpleContent_base<R> &
          TableDataSimpleContent_summary<M> &
          TableDataSimpleContent_footer<M>)

type TableDataSimpleContent_base<R> = Readonly<{
    label: VNodeContent
    header: TableDataContentDecorator
    column: TableDataColumnContentProvider<R>
}>
type TableDataSimpleContent_summary<M> = Readonly<{ summary: TableDataSummaryContentProvider<M> }>
type TableDataSimpleContent_footer<M> = Readonly<{ footer: TableDataSummaryContentProvider<M> }>

export function tableCell<M, R>(
    key: TableDataCellKey,
    content: { (key: TableDataCellKey): TableDataSimpleContent<M, R> },
): TableCellSimple<M, R> {
    return new Cell(key, content(key))
}
class Cell<M, R> implements TableCellSimple<M, R> {
    readonly type = "simple" as const

    key: TableDataCellKey
    content: TableDataSimpleContent<M, R>
    mutable: Readonly<{
        base: TableDataMutable_base<R>
        leaf: TableDataMutable_leaf
    }>

    constructor(key: TableDataCellKey, content: TableDataSimpleContent<M, R>) {
        this.key = key
        this.content = content
        this.mutable = {
            base: tableDataMutable_base(),
            leaf: tableDataMutable_leaf(),
        }
    }

    isVisible(visibleKeys: TableDataVisibleKeys): boolean {
        const { visibleType: visible } = this.mutable.leaf.visibleMutable()
        return visible === "always" || isVisibleKey(this.key, visibleKeys)
    }

    verticalBorder(): TableDataVerticalBorderStyle {
        return this.mutable.leaf.verticalBorderMutable().border
    }

    view({ visibleKeys }: TableDataParams<M>): TableDataView | TableDataAlwaysVisible {
        const { visibleType: visible } = this.mutable.leaf.visibleMutable()
        if (visible === "always") {
            return { type: "always-visible" }
        }

        const { decorator } = this.mutable.leaf.viewMutable()
        return {
            type: "view",
            key: this.key,
            content: decorateContent(this.content.label, decorator),
            isVisible: this.isVisible(visibleKeys),
        }
    }
    header({
        visibleKeys,
        base,
    }: TableDataStyledParams<M>): TableDataHeaderSimple | TableDataInvisible {
        if (!this.isVisible(visibleKeys)) {
            return { type: "invisible" }
        }
        const { style } = this.mutable.base.headerStyleMutable()
        return {
            type: "simple",
            key: this.key,
            style: mergeVerticalBorder(extendStyle({ base, style }), this.verticalBorder()),
            content: this.content.header(this.content.label),
            length: 1,
            height: 1,
        }
    }
    summary(params: TableDataStyledParams<M>): TableDataSummarySimple | TableDataInvisible {
        const { style } = this.mutable.base.summaryStyleMutable()
        return this.summaryContent(params, { style, content: content(this.content) })

        function content(content: TableDataSimpleContent<M, R>): TableDataSummaryProvider<M> {
            if ("summary" in content) {
                return { type: "content", content: content.summary }
            }
            return { type: "none" }
        }
    }
    column({
        visibleKeys,
        base,
        row,
    }: TableDataRelatedParams<M, R>): TableDataColumnSimple | TableDataInvisible {
        if (!this.isVisible(visibleKeys)) {
            return { type: "invisible" }
        }
        const { style } = this.mutable.base.columnStyleMutable()
        const { decorators } = this.mutable.base.columnMutable()
        return {
            type: "simple",
            key: this.key,
            style: mergeVerticalBorder(
                decorators.reduce(
                    (acc, decorator) => decorateStyle(acc, decorator(row)),
                    extendStyle({ base, style }),
                ),
                this.verticalBorder(),
            ),
            content: this.content.column(row),
            length: 1,
            height: 1,
        }
    }
    footer(params: TableDataStyledParams<M>): TableDataSummarySimple | TableDataInvisible {
        const { style } = this.mutable.base.footerStyleMutable()
        return this.summaryContent(params, { style, content: content(this.content) })

        function content(content: TableDataSimpleContent<M, R>): TableDataSummaryProvider<M> {
            if ("footer" in content) {
                return { type: "content", content: content.footer }
            }
            return { type: "none" }
        }
    }
    summaryContent(
        { visibleKeys, base, model }: TableDataStyledParams<M>,
        { style, content }: SummaryContentParams<M>,
    ): TableDataSummarySimple | TableDataInvisible {
        if (!this.isVisible(visibleKeys)) {
            return { type: "invisible" }
        }
        const shared = {
            key: this.key,
            style: mergeVerticalBorder(extendStyle({ base, style }), this.verticalBorder()),
            length: 1 as const,
        }
        switch (content.type) {
            case "none":
                return { type: "empty", ...shared }

            case "content":
                return {
                    type: "simple",
                    ...shared,
                    content: content.content(model),
                }
        }
    }

    alwaysVisible(): TableCellSimple<M, R> {
        this.mutable.leaf.alwaysVisible()
        return this
    }
    border(borders: TableDataVerticalBorder[]): TableCellSimple<M, R> {
        this.mutable.leaf.border(borders)
        return this
    }

    horizontalBorder(borders: TableDataHorizontalBorder[]): TableCellSimple<M, R> {
        this.mutable.base.horizontalBorder(borders)
        return this
    }
    horizontalBorderRelated(borders: TableDataHorizontalBorderProvider<R>): TableCellSimple<M, R> {
        this.mutable.base.horizontalBorderRelated(borders)
        return this
    }
    horizontalBorder_header(borders: TableDataHorizontalBorder[]): TableCellSimple<M, R> {
        this.mutable.base.horizontalBorder_header(borders)
        return this
    }
    horizontalBorder_summary(borders: TableDataHorizontalBorder[]): TableCellSimple<M, R> {
        this.mutable.base.horizontalBorder_summary(borders)
        return this
    }
    horizontalBorder_footer(borders: TableDataHorizontalBorder[]): TableCellSimple<M, R> {
        this.mutable.base.horizontalBorder_footer(borders)
        return this
    }

    decorateView(decorator: TableDataViewDecorator): TableCellSimple<M, R> {
        this.mutable.leaf.decorateView(decorator)
        return this
    }
    decorateHeader(decorator: TableDataHeaderDecorator): TableCellSimple<M, R> {
        this.mutable.base.decorateHeader(decorator)
        return this
    }
    decorateSummary(decorator: TableDataSummaryDecorator): TableCellSimple<M, R> {
        this.mutable.base.decorateSummary(decorator)
        return this
    }
    decorateColumn(decorator: TableDataColumnDecorator): TableCellSimple<M, R> {
        this.mutable.base.decorateColumn(decorator)
        return this
    }
    decorateColumnRelated(decorator: TableDataColumnRelatedDecorator<R>): TableCellSimple<M, R> {
        this.mutable.base.decorateColumnRelated(decorator)
        return this
    }
    decorateFooter(decorator: TableDataSummaryDecorator): TableCellSimple<M, R> {
        this.mutable.base.decorateFooter(decorator)
        return this
    }
}

type SummaryContentParams<M> = Readonly<{
    style: TableDataStyle
    content: TableDataSummaryProvider<M>
}>

redpajama_set_name: RedPajamaGithub


text:
package com.lichkin.framework.bases.enums.interfaces;

/**
 * 基本枚举接口
 * @author SuZhou LichKin Information Technology Co., Ltd.
 */
public interface LKBaseEnum extends LKEnum, LKPairEnum {

	/**
	 * 获取编码
	 * @return 编码
	 */
	@Override
	public abstract Integer getCode();

	/**
	 * 获取中文名称
	 * @return 中文名称
	 */
	@Override
	public abstract String getName();

	/**
	 * 获取英文名称
	 * @return 英文名称
	 */
	public abstract String getNameEn();

}


text:
package com.mossle.party.data;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import com.mossle.api.user.UserConnector;
import com.mossle.api.user.UserDTO;

import com.mossle.party.PartyConstants;
import com.mossle.party.persistence.domain.PartyEntity;
import com.mossle.party.persistence.domain.PartyStruct;
import com.mossle.party.persistence.domain.PartyStructRule;
import com.mossle.party.persistence.domain.PartyStructType;
import com.mossle.party.persistence.domain.PartyType;
import com.mossle.party.persistence.manager.PartyEntityManager;
import com.mossle.party.persistence.manager.PartyStructManager;
import com.mossle.party.persistence.manager.PartyStructRuleManager;
import com.mossle.party.persistence.manager.PartyStructTypeManager;
import com.mossle.party.persistence.manager.PartyTypeManager;

import org.apache.commons.lang3.StringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PartyDataDeployer {
    private static Logger logger = LoggerFactory
            .getLogger(PartyDataDeployer.class);
    private PartyStructTypeManager partyStructTypeManager;
    private PartyTypeManager partyTypeManager;
    private PartyStructRuleManager partyStructRuleManager;
    private PartyEntityManager partyEntityManager;
    private PartyStructManager partyStructManager;
    private String defaultTenantId = "1";
    private String orgDataFilePath = "data/party-org.json";
    private String orgDataEncoding = "UTF-8";
    private String employeeDataFilePath = "data/party-user.csv";
    private String employeeDataEncoding = "GB2312";
    private List<EmployeeDTO> employeeDtos = new ArrayList<EmployeeDTO>();
    private OrgProcessor orgProcessor = new OrgProcessor();
    private UserConnector userConnector;

    public void init() throws Exception {
        // 解析employee.csv
        this.parseEmployee();

        // 解析org.json
        this.parseOrg();

        // 为user初始化partyEntity
        this.initUserPartyEntity();

        // 为org初始化partyEntity
        this.initOrgPartyEntity();

        // 为position初始化partyEntity
        this.initPositionPartyEntity();

        // 设置部门关系
        this.initDepartmentRelation();

        // 设置部门人员关系
        this.initDepartmentUser();

        // 设置部门管理关系
        this.initDepartmentAdmin();

        // 设置用户岗位关系
        this.initPositionUser();
    }

    public void parseEmployee() throws Exception {
        List<String[]> list = new CsvParser().parse(employeeDataFilePath,
                employeeDataEncoding);

        for (String[] item : list) {
            String username = item[0];
            String company = item[1];
            String department = item[2];
            String position = item[3];
            EmployeeDTO employeeDto = new EmployeeDTO();
            employeeDto.setUsername(username);
            employeeDto.setCompany(company);
            employeeDto.setDepartment(department);
            employeeDto.setPosition(position);
            employeeDtos.add(employeeDto);
        }
    }

    public void parseOrg() throws Exception {
        this.orgProcessor.init(orgDataFilePath, orgDataEncoding);
    }

    public void initUserPartyEntity() {
        PartyType partyType = partyTypeManager.findUniqueBy("type",
                PartyConstants.TYPE_USER);

        if (partyType == null) {
            logger.info("cannot find partyType : {}", PartyConstants.TYPE_USER);

            return;
        }

        for (EmployeeDTO employeeDto : employeeDtos) {
            String username = employeeDto.getUsername();
            PartyEntity partyEntity = this.findUserPartyEntity(username);

            if (partyEntity != null) {
                logger.info("partyEntity exists. skip. {}", username);

                continue;
            }

            UserDTO userDto = userConnector.findByUsername(username,
                    defaultTenantId);

            if (userDto == null) {
                logger.info("cannot find user : {}", username);

                continue;
            }

            partyEntity = new PartyEntity();
            partyEntity.setCode(userDto.getUsername());
            partyEntity.setName(userDto.getDisplayName());
            partyEntity.setRef(userDto.getId());
            partyEntity.setPartyType(partyType);
            partyEntity.setTenantId(defaultTenantId);
            partyEntityManager.save(partyEntity);
        }
    }

    public void initOrgPartyEntity() {
        for (OrgDTO orgDto : orgProcessor.getOrgDtos()) {
            PartyEntity partyEntity = this.findOrgPartyEntity(orgDto.getCode(),
                    orgDto.getType());

            if (partyEntity != null) {
                continue;
            }

            String typeHql = "from PartyType where ref=? and type=?";
            PartyType partyType = partyTypeManager.findUnique(typeHql,
                    orgDto.getType(), PartyConstants.TYPE_ORG);

            if (partyType == null) {
                logger.info("cannot find partyType : {}",
                        PartyConstants.TYPE_ORG);

                continue;
            }

            partyEntity = new PartyEntity();
            partyEntity.setCode(orgDto.getCode());
            partyEntity.setName(orgDto.getName());
            partyEntity.setRef(orgDto.getCode());
            partyEntity.setPartyType(partyType);
            partyEntity.setTenantId(defaultTenantId);
            partyEntityManager.save(partyEntity);
        }
    }

    public void initPositionPartyEntity() {
        PartyType partyType = partyTypeManager.findUniqueBy("type",
                PartyConstants.TYPE_POSITION);

        if (partyType == null) {
            logger.info("cannot find partyType : {}",
                    PartyConstants.TYPE_POSITION);

            return;
        }

        for (EmployeeDTO employeeDto : employeeDtos) {
            String position = employeeDto.getPosition();

            if (StringUtils.isBlank(position)) {
                continue;
            }

            String hql = "from PartyEntity where ref=? and partyType=?";
            PartyEntity partyEntity = this.partyEntityManager.findUnique(hql,
                    position, partyType);

            if (partyEntity != null) {
                logger.debug("partyEntity exists. skip. {}", position);

                continue;
            }

            partyEntity = new PartyEntity();
            partyEntity.setName(position);
            partyEntity.setRef(position);
            partyEntity.setPartyType(partyType);
            partyEntity.setTenantId(defaultTenantId);
            partyEntityManager.save(partyEntity);
        }
    }

    public void initDepartmentRelation() {
        // root
        PartyEntity rootPartyEntity = this.findOrgPartyEntity(orgProcessor
                .getRoot().getCode(), orgProcessor.getRoot().getType());

        if (rootPartyEntity != null) {
            this.createPartyStruct("struct", null, rootPartyEntity);
        } else {
            logger.info("cannot find root partyEntity : {} {}", orgProcessor
                    .getRoot().getCode(), orgProcessor.getRoot().getType());
        }

        // not root
        for (OrgDTO orgDto : orgProcessor.getOrgDtos()) {
            PartyEntity parentPartyEntity = this.findOrgPartyEntity(
                    orgDto.getCode(), orgDto.getType());

            if (parentPartyEntity == null) {
                logger.info("partyEntity not exists. skip. {} {}",
                        orgDto.getCode(), orgDto.getType());

                continue;
            }

            for (OrgDTO child : orgDto.getChildren()) {
                PartyEntity childPartyEntity = this.findOrgPartyEntity(
                        child.getCode(), child.getType());

                if (childPartyEntity == null) {
                    continue;
                }

                this.createPartyStruct("struct", parentPartyEntity,
                        childPartyEntity);
            }
        }
    }

    public void initDepartmentUser() {
        for (EmployeeDTO employeeDto : employeeDtos) {
            String username = employeeDto.getUsername();
            PartyEntity userPartyEntity = this.findUserPartyEntity(username);

            if (userPartyEntity == null) {
                logger.info("partyEntity not exists. skip. {}", username);

                continue;
            }

            String department = employeeDto.getDepartment();
            OrgDTO orgDto = orgProcessor.findByCode(department);

            if (orgDto == null) {
                logger.info("cannot find orgDto : {}", department);

                continue;
            }

            PartyEntity orgPartyEntity = this.findOrgPartyEntity(
                    orgDto.getCode(), orgDto.getType());

            if (orgPartyEntity == null) {
                logger.info("partyEntity not exists. skip. {} {}",
                        orgDto.getCode(), orgDto.getType());

                continue;
            }

            this.createPartyStruct("struct", orgPartyEntity, userPartyEntity);
        }
    }

    public void initDepartmentAdmin() {
        for (OrgDTO orgDto : orgProcessor.getOrgDtos()) {
            if (orgDto.getLeader() == null) {
                continue;
            }

            PartyEntity orgPartyEntity = this.findOrgPartyEntity(
                    orgDto.getCode(), orgDto.getType());

            if (orgPartyEntity == null) {
                logger.info("partyEntity not exists. skip. {} {}",
                        orgDto.getCode(), orgDto.getType());

                continue;
            }

            PartyEntity userPartyEntity = this.findUserPartyEntity(orgDto
                    .getLeader());

            if (userPartyEntity == null) {
                logger.info("partyEntity not exists. skip. {}",
                        orgDto.getLeader());

                continue;
            }

            this.createPartyStructAdmin(orgPartyEntity, userPartyEntity);
        }
    }

    public void initPositionUser() {
        PartyType partyType = partyTypeManager.findUniqueBy("type",
                PartyConstants.TYPE_POSITION);

        if (partyType == null) {
            logger.info("cannot find partyType : {}",
                    PartyConstants.TYPE_POSITION);

            return;
        }

        for (EmployeeDTO employeeDto : employeeDtos) {
            String username = employeeDto.getUsername();
            String department = employeeDto.getDepartment();
            String position = employeeDto.getPosition();

            OrgDTO orgDto = orgProcessor.findByCode(department);

            PartyEntity userPartyEntity = this.findUserPartyEntity(username);

            if (userPartyEntity == null) {
                logger.info("partyEntity not exists. skip. {}", username);

                continue;
            }

            PartyEntity orgPartyEntity = this.findOrgPartyEntity(
                    orgDto.getCode(), orgDto.getType());

            if (orgPartyEntity == null) {
                logger.info("partyEntity not exists. skip. {} {}",
                        orgDto.getCode(), orgDto.getType());

                continue;
            }

            PartyEntity positionPartyEntity = this
                    .findPositionPartyEntity(position);

            if (positionPartyEntity == null) {
                logger.debug("partyEntity not exists. skip. {}", position);

                continue;
            }

            // user position
            this.createPartyStruct("department-position", orgPartyEntity,
                    positionPartyEntity);
            this.createPartyStruct("user-position", userPartyEntity,
                    positionPartyEntity);
        }
    }

    //
    public PartyEntity findOrgPartyEntity(String code, String type) {
        String typeHql = "from PartyType where ref=? and type=?";
        PartyType partyType = partyTypeManager.findUnique(typeHql, type,
                PartyConstants.TYPE_ORG);

        if (partyType == null) {
            logger.info("cannot find partyType : {}", PartyConstants.TYPE_ORG);

            return null;
        }

        String hql = "from PartyEntity where ref=? and partyType=?";
        PartyEntity partyEntity = partyEntityManager.findUnique(hql, code,
                partyType);

        if (partyEntity == null) {
            logger.debug("partyEntity not exists. skip. {} {}", code,
                    partyType.getName());

            return null;
        }

        return partyEntity;
    }

    public PartyEntity findUserPartyEntity(String username) {
        PartyType partyType = partyTypeManager.findUniqueBy("type",
                PartyConstants.TYPE_USER);

        if (partyType == null) {
            logger.info("cannot find partyType : {}", PartyConstants.TYPE_USER);

            return null;
        }

        UserDTO userDto = userConnector.findByUsername(username,
                defaultTenantId);

        if (userDto == null) {
            logger.info("cannot find user : {}", username);

            return null;
        }

        String hql = "from PartyEntity where ref=? and partyType=?";
        PartyEntity partyEntity = partyEntityManager.findUnique(hql,
                userDto.getId(), partyType);

        if (partyEntity == null) {
            logger.debug("partyEntity not exists. skip. {}", username);

            return null;
        }

        return partyEntity;
    }

    public PartyEntity findPositionPartyEntity(String positionName) {
        if (StringUtils.isBlank(positionName)) {
            logger.debug("position is blank");

            return null;
        }

        PartyType partyType = partyTypeManager.findUniqueBy("type",
                PartyConstants.TYPE_POSITION);

        if (partyType == null) {
            logger.info("cannot find partyType : {}",
                    PartyConstants.TYPE_POSITION);

            return null;
        }

        String hql = "from PartyEntity where ref=? and partyType=?";
        PartyEntity partyEntity = partyEntityManager.findUnique(hql,
                positionName, partyType);

        if (partyEntity == null) {
            logger.debug("partyEntity not exists. skip. {}", positionName);

            return null;
        }

        return partyEntity;
    }

    public void createPartyStruct(String type, PartyEntity parentPartyEntity,
            PartyEntity childPartyEntity) {
        PartyStructType partyStructType = this.partyStructTypeManager
                .findUniqueBy("type", type);

        if (partyStructType == null) {
            logger.info("partyStructType not exists. skip. {}", type);

            return;
        }

        PartyStruct partyStruct = null;

        if (parentPartyEntity == null) {
            String hql = "from PartyStruct where partyStructType=? and parentEntity is null and childEntity=?";
            partyStruct = this.partyStructManager.findUnique(hql,
                    partyStructType, childPartyEntity);
        } else {
            String hql = "from PartyStruct where partyStructType=? and parentEntity=? and childEntity=?";
            partyStruct = this.partyStructManager.findUnique(hql,
                    partyStructType, parentPartyEntity, childPartyEntity);
        }

        if (partyStruct != null) {
            if (parentPartyEntity == null) {
                logger.info("partyStruct not exists. skip. {} {} {}", type,
                        "null", childPartyEntity.getName());
            } else {
                logger.info("partyStruct not exists. skip. {} {} {}", type,
                        parentPartyEntity.getName(), childPartyEntity.getName());
            }

            return;
        }

        partyStruct = new PartyStruct();
        partyStruct.setPartyStructType(partyStructType);
        partyStruct.setParentEntity(parentPartyEntity);
        partyStruct.setChildEntity(childPartyEntity);
        partyStruct.setTenantId(defaultTenantId);
        this.partyStructManager.save(partyStruct);
    }

    public void createPartyStructAdmin(PartyEntity parentPartyEntity,
            PartyEntity childPartyEntity) {
        PartyStructType partyStructType = this.partyStructTypeManager
                .findUniqueBy("type", "manage");

        if (partyStructType == null) {
            logger.info("partyStructType not exists. skip. {}", "manage");

            return;
        }

        String hql = "from PartyStruct where partyStructType=? and parentEntity=? and childEntity=?";
        PartyStruct partyStruct = this.partyStructManager.findUnique(hql,
                partyStructType, parentPartyEntity, childPartyEntity);

        if (partyStruct != null) {
            if (!Integer.valueOf(1).equals(partyStruct.getAdmin())) {
                partyStruct.setAdmin(1);
                this.partyStructManager.save(partyStruct);
            }

            return;
        }

        partyStruct = new PartyStruct();
        partyStruct.setPartyStructType(partyStructType);
        partyStruct.setParentEntity(parentPartyEntity);
        partyStruct.setChildEntity(childPartyEntity);
        partyStruct.setTenantId(defaultTenantId);
        partyStruct.setAdmin(1);
        this.partyStructManager.save(partyStruct);
    }

    @Resource
    public void setPartystructTypeManager(
            PartyStructTypeManager partyStructTypeManager) {
        this.partyStructTypeManager = partyStructTypeManager;
    }

    @Resource
    public void setPartyTypeManager(PartyTypeManager partyTypeManager) {
        this.partyTypeManager = partyTypeManager;
    }

    @Resource
    public void setPartyStructRuleManager(
            PartyStructRuleManager partyStructRuleManager) {
        this.partyStructRuleManager = partyStructRuleManager;
    }

    @Resource
    public void setPartyEntityManager(PartyEntityManager partyEntityManager) {
        this.partyEntityManager = partyEntityManager;
    }

    @Resource
    public void setPartyStructManager(PartyStructManager partyStructManager) {
        this.partyStructManager = partyStructManager;
    }

    @Resource
    public void setUserConnector(UserConnector userConnector) {
        this.userConnector = userConnector;
    }
}


text:
[![Build Status](https://travis-ci.org/evrone/evrone-common-spawn.png)](https://travis-ci.org/evrone/evrone-common-spawn)
[![Code Climate](https://codeclimate.com/github/evrone/evrone-common-spawn.png)](https://codeclimate.com/github/evrone/evrone-common-spawn)

This gem helps to spawn processes in a shell capturing output in realtime.
It also allows to set the temeouts.

## Getting Started
### Prerequisites

MRI 1.9.3 or 2.0.0.

### Installation

Add this line to your application's Gemfile:

    gem 'evrone-common-spawn'

And then execute the bundler:

    $ bundle

Or install it via `gem` command:

    $ gem install evrone-common-spawn

### Usage

The following snippet demonstrates the usage:

```ruby
# Spawn system processes example

include Evrone::Common::Spawn

spawn "ls -la" do |output|
  print output
  # prints directory listing
end

spawn({'ENV_VAR' => 'VALUE'}, "echo $VALUE", timeout: 10) do |output|
  print output
  #  its print "VALUE\n"
end
```

```ruby
# Spawn remote processes example

open_ssh('localhost', 'user') do |ssh|
  ssh.spawn("ls -la") do |output|
    print output
    # prints directory listing
  end

  spawn({'ENV_VAR' => 'VALUE'}, "echo $VALUE", read_timeout: 10) do |output|
    print output
    #  its print "VALUE\n"
  end
end

```

When a timeout is reached spawn raises ```Evrone::Common::Spawn::TimeoutError``` or
```Evrone::Common::Spawn::ReadTimeoutError```. Both exceptions inherit
from Timeout::Error

Both ```spawn``` methods return process exit code. If a process was terminated by a signal, for example
KILL or INT, the methods return negative number identical to a signal number (-9 for KILL, etc.)

## Contributing

Please read [Code of Conduct](CODE-OF-CONDUCT.md) and [Contributing Guidelines](CONTRIBUTING.md)
for submitting pull requests to us.

## Versioning

We use [SemVer](http://semver.org/) for versioning. For the versions available,
see the [tags on this repository](https://github.com/evrone/evrone-common-spawn/tags).

## Authors

* [Dmitry Galinsky](https://github.com/dmexe) - *Initial work*

See also the list of [contributors](https://github.com/evrone/evrone-common-spawn/contributors)
who participated in this project.

## License

This project is licensed under the [MIT License](LICENSE).


text:
import React from 'react';
import {IntlProvider, injectIntl} from 'react-intl';
import {shape, func} from 'prop-types';

import {setWrappedDisplayName} from '@webex/react-component-utils';

export default function withIntl({
  messages,
  locale
}) {
  // eslint-disable-reason Dynamically loading locale data to lower overhead
  /* eslint-disable import/no-dynamic-require, global-require */
  if (!Intl.PluralRules) {
    require('@formatjs/intl-pluralrules/polyfill');
    require(`@formatjs/intl-pluralrules/dist/locale-data/${locale}`);
  }

  if (!Intl.RelativeTimeFormat) {
    require('@formatjs/intl-relativetimeformat/polyfill');
    require(`@formatjs/intl-relativetimeformat/dist/locale-data/${locale}`);
  }
  /* eslint-enable import/no-dynamic-require, global-require */

  return (BaseComponent) => {
    const WrappedComponent = injectIntl(BaseComponent);

    function WithIntl(props) {
      return (
        <IntlProvider locale={locale} messages={messages} >
          <WrappedComponent {...props} />
        </IntlProvider>
      );
    }

    WrappedComponent.propTypes = {
      // Grabbed from https://github.com/sharetribe/ftw-daily/blob/master/src/util/reactIntl.js#L10
      intl: shape({
        formatDate: func.isRequired,
        formatHTMLMessage: func.isRequired,
        formatMessage: func.isRequired,
        formatNumber: func.isRequired,
        formatPlural: func.isRequired,
        formatRelativeTime: func.isRequired,
        formatTime: func.isRequired
      })
    };

    return setWrappedDisplayName('WithIntl')(WithIntl);
  };
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:util="http://www.springframework.org/schema/util" xmlns:security="http://www.springframework.org/schema/security"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
                              http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                              http://www.springframework.org/schema/aop
                              http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
                              http://www.springframework.org/schema/util
                              http://www.springframework.org/schema/util/spring-util-2.5.xsd
                              http://www.springframework.org/schema/security
                              http://www.springframework.org/schema/security/spring-security-3.0.xsd">

	<bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased">
		<property name="decisionVoters">
			<list>
				<bean class="org.springframework.security.access.vote.RoleVoter" />
			</list>
		</property>
	</bean>

	<bean id="authorizationSupport" class="ajia.security.AuthorizationSupport">
		<property name="accessDecisionManager" ref="accessDecisionManager" />
		<property name="securityMetadataSource" ref="securityMetadataSource" />
	</bean>

    <bean id="securityMetadataSource"
          class="org.springframework.security.access.annotation.SecuredAnnotationSecurityMetadataSource"/>

    <bean id="authorizationAspect"
          class="ajia.security.SecuredAnnotationAuthorizationAspect"
          factory-method="aspectOf">
          <property name="authorizationSupport"
                    ref="authorizationSupport"/>
    </bean>

	<security:authentication-manager alias="authenticationManager">
		<security:authentication-provider>
		    <security:user-service>
		        <security:user name="ramnivas" password="aop"
		                  authorities="ROLE_USER,ROLE_SUPERVISOR"/>
		        <security:user name="rod" password="spring"
		                  authorities="ROLE_USER"/>
		    </security:user-service>
		</security:authentication-provider>
	</security:authentication-manager>

	<bean id="authenticationSupport" class="ajia.security.AuthenticationSupport">
		<property name="authenticationManager" ref="authenticationManager" />
		<property name="loginUI" ref="loginService" />
	</bean>

	<bean id="loginService" class="ajia.security.SysoutLoginService" />

	<bean id="authenticationAspect" class="ajia.security.ConsoleApplicationAuthenticationAspect"
		factory-method="aspectOf">
		<property name="authenticationSupport" ref="authenticationSupport" />
	</bean>

</beans>

<!-- Listing 15.12 Authorization configuration for a simple aspect -->
<!-- Listing 15.9 Authorization configuration for simple aspect -->
<!-- Listing 15.4 Configuration for authentication -->


text:
var helpers = require(__dirname+'/../lib/helpers'),
    assert = require('assert');

var stub = __dirname+'/stubs/child_stub.py';

describe('startProc', function() {
  it('should start a child process', function(done) {
    helpers.startProc(stub, function(err, child) {
      assert.equal(null, err);
      done();
    });
  }),
  it('should produce an error if command not found', function(done) {
    helpers.startProc('HELLOWORLD', function(err, child) {
      assert.notEqual(null, err);
      done();
    });
  })
});


text:
@implementation BRImageTools

static id tool;
static dispatch_once_t onceToken;

+ (instancetype)shareTools
{
    dispatch_once(&onceToken, ^{
        tool = [[self alloc] init];
    });

    return tool;
}

- (NSString *)dealImage:(NSString *)image
{
    return [NSString stringWithFormat:@"%@超人", image];
}

+ (NSString *)dealImage:(NSString *)image
{
    return [NSString stringWithFormat:@"%@超人", image];
}
@end


text:
package org.homedns.mkh.ui.client.filter;

import org.homedns.mkh.dataservice.client.Column;
import com.gwtextux.client.widgets.grid.plugins.GridDateFilter;

/**
 * Filter for grid date columns
 *
 */
public class DateFilter extends GridDateFilter {
	private Column _col;
	private DateFilterClause _clause;

	/**
	 * @param col the column for which filter will be defined
	 */
	public DateFilter( Column col, DateFilterClause clause ) {
		super( col.getName( ) );
		_col = col;
		_clause = clause;
	}

	/**
	 * @see com.gwtextux.client.widgets.grid.plugins.GridFilter#getCondition()
	 */
	@Override
	public String getCondition( ) {
		return( _clause.getCondition( _col, new Object[] { getValue( ) } ) );
	}
}


text:
var config = {
    /*
        [string]    client side origin
        e.g.    'http://my-domain.com'
    */
    origin: 'http://hudidit.com'
    /*
        [number]    port number for Node.js server created by parser.js
    */
    ,port:  6031
    /*
        [string]    path of the directory in which you save your posts' markdown files. Could be absolute or relative.
    */
//    ,postsDir:   '../posts/'
	,postsDir: '/home/ubuntu/web/blog/node-blog/posts/'
};

module.exports = config;


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

        <title>
      How Designers
      Design and Program Interactive Behaviors
    </title>

            How Designers
      Design and Program Interactive Behaviors

      Authors

      Brad Myers, Sun Young Park, Yoko Nakano, Greg Mueller, Andrew Ko

      Notes

      Boundary Objects

      Sketches, Storyboards, wireframes, formal design documents

      Field of Study

      Concepts

      Quotations

      "In our survey of 259 designers, 86% reported that the behavior is more
      difficult to prototype than the appearance. Often (78% of

      the time), designing the behavior requires collaborating with developers,
      but 76% of designers reported that communicating the behavior to
      developers was more difficult than the appearance. Other results include
      that annotations such as arrows and paragraphs of text are used on top of
      sketches and storyboards to explain behaviors, and designers want to
      explore multiple versions of behaviors, but today's tools make this
      difficult."

      "There have been many previous studies of the processes, techniques and
      tools that are used by designers, but none have focused on how the
      interactive behavior of the interface is created and communicated.
      Creating the behaviors inherently deals with programming concepts, such
      as conditionality (e.g., behaviors that only happen if the user interface
      is in a certain mode), and abstrac-

      tion (e.g., a behavior should happen when users click on any object of a
      particular type)."

      "Designers can be classified as end-user programmers (EUP), since they do
      not write programs as a primary goal, but rather in

      support of designing a web page or an animation"

      "For example, tools for early design focused on use by designers who are
      not programmers include SILK [11], Electronic Cocktail

      Napkin [8], DENIM [14], SketchWizard [7], DEMAIS [2], Designer's Outpost
      [10], and many others."

      "Designing the behaviors was reported to be an ongoing process while
      designing appearance is a simpler process of creating a single static
      image. Behaviors were said to often remain ill-defined until the
      application is actually implemented"

      "[Verbatims where designers express issues with defining interactions]

Interactions must be specified at a low-level of detail:

"Details are important, and you never have them all until full
          implementation."

"There are so many factors that can influence the behavior. It
          isn't a controlled event and [it's] very difficult to communicate the
          entire experience via a prototype.

"Because of the many different states that must be demonstrated
          and their dependence on different conditions preceding those states."

"It's more complex with more variables and constraints attached.
          There are also more stakeholders and coworkers involved"

"It's harder for people to fill in the gaps with imagination.
          Small changes make big differences in experiential outcomes so if
          something is not quite right it can cloud whole thing."

"There's no such thing as low-fidelity interaction, it has to be
          right."

Difficulty with today's tools:

"I work in mobile, so often I have to wait until developers have
          something working before I can actually test out how a new behavior
          'feels' on a phone. What it looks like is easy to test by just
          putting a picture of the mockup onto the phone."

"Current tools for defining behavior suck."

"I can represent very exactly the desired appearance. However, I
          can only approximate the backend behaviors."

The richness of the interactions themselves..."

      "55% of the participants said that they had had an interactive behavior
      they wanted to explore on paper but could not, and therefore had to
      explore by implementing it."

      "participants also agreed that sketches and storyboards were not
      sufficient for exploring interactive behaviors, consistent with previous
      studies (e.g., [2, 4])."

      "people can imagine the final detailed appearance even from a vague
      sketch; however, it is very hard to communicate behavior and to get a
      sense of the final version from a prototype"

      "designers frequently wanted to have multiple designs side-by-side,
      either in their sketchbooks, on big displays, or on the wall. However,
      this is difficult to achieve for behaviors – there is no built-in way in
      today's implementation tools to have two versions of a behavior operating
      side-by-side."

      "Our results suggest that there is definitely a need among designers for
      quickly and easily prototyping interactive behaviors. Many do not
      program, and have difficulty prototyping behaviors. Consequently, they
      resort to heavy use of annotations and other means for communicating
      their intentions to people who do program. Specifying behaviors textually
      is often inadequate, time-consuming and sometimes leads to
      miscommunication and confusion between designers and developers. Since
      designers strive to be creative and

      explore new and complex behaviors, this is a significant pain point for
      them both today and in the future."

      References

      Methodology


text:
package org.jetbrains.plugins.scala
package lang
package psi
package api
package statements
import org.jetbrains.plugins.scala.lang.psi.api.base.ScIdList
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.ScTypedDefinition

/**
* @author Alexander Podkhalyuzin
*/

trait ScVariableDeclaration extends ScVariable with ScTypedDeclaration {
  def getIdList: ScIdList
  def declaredElements : Seq[ScTypedDefinition]
}


text:
Greymind Turns is a quick and intuitive way to track turns within various groups and contexts. Track who has paid for lunch and who may pay next. Track whose turn it is to do the laundry. You get the idea.

## Team
* [Balki (Balakrishnan Ranganathan)](https://github.com/greymind)
* Marija Viskovič

## License
MIT


text:
package datamsg

const (
	NoReceiver = "NoReceiver"
)

type DataMsg struct {
	Sender   string
	Receiver string
	meta     map[string]interface{}
	MsgFlag  int //? can it be integrated to meta?
	Payload  interface{}
	Next     *DataMsg
}

func NewDataMsg(sender, recv string, msgtype int, payload interface{}) *DataMsg {
	var msg = &DataMsg{
		Sender:   sender,
		Receiver: recv,
		MsgFlag:  msgtype,
		meta:     make(map[string]interface{}),
		Next:     nil,
		Payload:  payload,
	}
	return msg
}

func (t *DataMsg) SetMeta(owner string, m interface{}) {
	t.meta[owner] = m
}

func (t *DataMsg) Meta(owner string) (interface{}, bool) {
	i, ok := t.meta[owner]
	return i, ok
}

func (t *DataMsg) PushBack(n *DataMsg) (d *DataMsg) {
	if t == nil {
		return n
	}
	m := t
	for ; m.Next != nil; m = m.Next {
	}
	m.Next = n
	return t
}

func (t *DataMsg) PushFront(n *DataMsg) (d *DataMsg) {
	if n == nil {
		return t
	}
	n.Next = t
	return n
}


text:
package org.lwjgl.opengl;

/**
 * Native bindings to the KHR_blend_equation_advanced_coherent extension.
 *
 *
This extension guarantees that blending is done coherently and in API primitive order. An enable is provided to allow implementations to opt out of
 * fully coherent blending and instead behave as though only {@link KHRBlendEquationAdvanced KHR_blend_equation_advanced} were supported.

 *
 *
Requires {@link GL20 OpenGL 2.0}.

 */
public final class KHRBlendEquationAdvancedCoherent {

	/**
	 * Accepted by the {@code cap} parameter of Disable, Enable, and IsEnabled, and by the {@code pname} parameter of GetIntegerv, GetBooleanv, GetFloatv,
	 * GetDoublev and GetInteger64v.
	 */
	public static final int GL_BLEND_ADVANCED_COHERENT_KHR = 0x9285;

	private KHRBlendEquationAdvancedCoherent() {}

}


text:
/*
 * Interactions with IMAP and SMTP servers should be scheduled using the queue
 * defined in this module. Schedule an action using the `actions` action creator
 * map, and the `schedule` function. For example:
 *
 *     schedule(actions.archive({ accountId, box, uids }))
 *
 * `schedule` returns a promise that resolves with the value of the promise
 * returned in the `process` stage (see below). But note that you must not rely
 * on that promise to keep application state up-to-date because the scheduled
 * task might not run until after an application restart at which time any
 * promise callbacks will no longer exist.
 *
 * Once in the queue tasks are seralized in a sqlite store so that tasks persist
 * across application restarts.
 *
 * Each action is defined by a handler, which is made up of at least two stages:
 *
 * - enqueue : Called immediately. Update the local cache to reflect pending
 *             changes, and compute parameters for the next stage. The return
 *             value of the `enqueue` stage is given as an argument to the
 *             `process` and `failure` stages. If the return value is an object
 *             with an `id` property, that value will be used as the task ID for
 *             purposes of merging duplicate tasks. The return value *must* be
 *             serializable.
 * - process : Called when the task gets to the front of the queue. Make calls
 *             to IMAP and SMTP services. Returns a promise. The resolved value
 *             of the promise becomes the resolved value of the promise returned
 *             by the top-level `schedule` function. An rejected value from the
 *             `process` promise will be wrapped, and the wrapped value will
 *             become the rejected value of the promise returned by `schedule`.
 * - failure : (Optional) Called in case a task fails. Gets two arguments: an
 *             error value, and the same argument that was given to the
 *             `process` stage. This is the place to undo changes to the local
 *             cache to reflect the fact that expected changes did not take
 *             place server-side.
 *
 * In addition to the handler stage callbacks, handlers may have these optional
 * properties:
 *
 * - merge    : When two tasks are scheduled with the same ID the merge callback
 *              will be called to create one unified tasks. `merge` will be
 *              called with the return values from the `enqueue` stages of each
 *              task. `merge` returns a promise that resolves to a value to pass
 *              to the `process` stage. (Set the ID of a task by including an
 *              `id` property in the return value of the `enqueue` stage.)
 * - priority : Determines order in which scheduled tasks process. Default is
 *              `DEFAULT_PRIORITY`, which runs before `LOW_PRIORITY`, and after
 *              `HIGH_PRIORITY`. Tasks that send data upstream (e.g. setting
 *              the "Seen" flag on a message) should run *before* tasks that get
 *              data from upstream (e.g. sync and search).
 * - unique   : If set to `true` and there is a task that is already queued with
 *              the same ID then the new task will *not* be scheduled. Note that
 *              the `enqueue` callback will run regardless! (Set the ID of
 *              a task by including an `id` property in the return value of the
 *              `enqueue` stage.)
 */

import electronIsDev from "electron-is-dev"
import * as fs from "fs"
import { Transporter } from "nodemailer"
import * as cache from "../cache"
import { ComposedMessage, serialize } from "../compose"
import db, { getDbPath } from "../db"
import AccountManager from "../managers/AccountManager"
import ConnectionManager from "../managers/ConnectionManager"
import * as M from "../models/Message"
import * as request from "../request"
import { search, sync } from "../sync"
import { MessageAttributes } from "../types"
import * as promises from "../util/promises"
import SqliteStore from "./better-queue-better-sqlite3"
import { combineHandlers, handler, LOW_PRIORITY, Task } from "./combineHandlers"

type ID = string

const handlers = {
  archive: handler({
    enqueue(params: { accountId: ID; box: { name: string }; uids: number[] }) {
      cache.delLabels({ ...params, labels: ["\\Inbox"] })
      return params
    },

    process({
      accountId,
      box,
      uids
    }: {
      accountId: ID
      box: { name: string }
      uids: number[]
    }): Promise<void> {
      return withConnectionManager(accountId, connectionManager =>
        connectionManager
          .request(
            request.actions.delLabels(
              { name: box.name, readonly: false },
              uids,
              ["\\Inbox"]
            )
          )
          .toPromise()
      )
    },
    failure(
      _error,
      {
        accountId,
        box,
        uids
      }: {
        accountId: ID
        box: { name: string }
        uids: number[]
      }
    ) {
      cache.addLabels({ accountId, box, uids, labels: ["\\Inbox"] })
    }
  }),

  markAsRead: handler({
    enqueue(params: { accountId: ID; box: { name: string }; uids: number[] }) {
      cache.addFlag({ ...params, flag: "\\Seen" })
      return params
    },

    process({
      accountId,
      box,
      uids
    }: {
      accountId: ID
      box: { name: string }
      uids: number[]
    }): Promise<void> {
      return withConnectionManager(accountId, connectionManager =>
        connectionManager
          .request(
            request.actions.addFlags(
              { name: box.name, readonly: false },
              uids,
              ["\\Seen"]
            )
          )
          .toPromise()
      )
    },
    failure(_error, { accountId, box, uids }) {
      cache.delFlags({ accountId, box, uids, flags: ["\\Seen"] })
    }
  }),

  unmarkAsRead: handler({
    enqueue(params: { accountId: ID; box: { name: string }; uids: number[] }) {
      cache.delFlags({ ...params, flags: ["\\Seen"] })
      return params
    },

    process({
      accountId,
      box,
      uids
    }: {
      accountId: ID
      box: { name: string }
      uids: number[]
    }): Promise<void> {
      return withConnectionManager(accountId, connectionManager =>
        connectionManager
          .request(
            request.actions.delFlags(
              { name: box.name, readonly: false },
              uids,
              ["\\Seen"]
            )
          )
          .toPromise()
      )
    },

    failure(_error, { accountId, box, uids }) {
      cache.addFlag({ accountId, box, uids, flag: "\\Seen" })
    }
  }),

  search: handler({
    priority: LOW_PRIORITY,
    unique: true,
    enqueue(searchRecord: cache.Search) {
      return { id: `search--${searchRecord.query}`, searchRecord }
    },
    process({ searchRecord }: { searchRecord: cache.Search }) {
      return withConnectionManager(
        String(searchRecord.account_id),
        connectionManager => search(searchRecord, connectionManager)
      )
    }
  }),

  sendMessage: handler({
    enqueue({
      accountId,
      message
    }: {
      accountId: ID
      message: ComposedMessage
    }) {
      const { attributes, headers, partHeaders, bodies } = message
      let messageId: cache.ID | null = null
      db.transaction(() => {
        const updatedAt = new Date().toISOString()
        messageId = cache.persistAttributes(
          { accountId, updatedAt },
          attributes
        )
        cache.persistHeadersAndReferences(messageId, headers, attributes)
        for (const [partId, content] of Object.entries(bodies)) {
          const part = M.getPartByPartId(partId, attributes)
          if (!part) {
            throw new Error("Error saving message body")
          }
          cache.persistBody(messageId, part, content)
        }
        cache.persistPartHeaders(messageId, partHeaders)
      })()
      if (!messageId) {
        throw new Error("error saving message")
      }
      return {
        accountId,
        message: { attributes, headers, partHeaders },
        messageId
      }
    },

    process({
      accountId,
      message,
      messageId
    }: {
      accountId: ID
      message: {
        attributes: MessageAttributes
        headers: cache.SerializedHeaders
        partHeaders: Record<string, cache.SerializedHeaders>
      }
      messageId: cache.ID
    }): Promise<void> {
      return withSmtpTransporter(accountId, transporter => {
        return (async () => {
          const { attributes, headers, partHeaders } = message
          const bodies = (partID: string) =>
            cache.getBody(messageId, { partID }) || undefined
          const mimeNode = serialize({
            attributes,
            headers,
            partHeaders,
            bodies
          })
          const raw = await promises.lift1<Buffer>(cb => mimeNode.build(cb))
          return transporter.sendMail({
            envelope: mimeNode.getEnvelope(),
            raw
          })
        })()
      })
    },

    failure(_error, { messageId }) {
      cache.removeMessage(messageId)
    }
  }),

  sync: handler({
    priority: LOW_PRIORITY,
    unique: true,
    enqueue(params: { accountId: ID }) {
      return { ...params, id: "sync" }
    },
    process({ accountId }: { accountId: ID }) {
      return withConnectionManager(accountId, connectionManager =>
        sync(accountId, connectionManager)
      )
    }
  }),

  setFlagged: handler({
    enqueue(params: {
      accountId: ID
      box: { name: string }
      uids: number[]
      isFlagged: boolean
    }) {
      params.isFlagged
        ? cache.addFlag({ ...params, flag: "\\Flagged" })
        : cache.delFlags({ ...params, flags: ["\\Flagged"] })

      return params
    },

    process({
      accountId,
      box,
      uids,
      isFlagged
    }: {
      accountId: ID
      box: { name: string }
      uids: number[]
      isFlagged: boolean
    }): Promise<void> {
      return withConnectionManager(accountId, connectionManager =>
        connectionManager
          .request(
            isFlagged
              ? request.actions.addFlags(
                  { name: box.name, readonly: false },
                  uids,
                  ["\\Flagged"]
                )
              : request.actions.delFlags(
                  { name: box.name, readonly: false },
                  uids,
                  ["\\Flagged"]
                )
          )
          .toPromise()
      )
    },

    failure(_error, { accountId, box, uids, isFlagged }) {
      isFlagged
        ? cache.delFlags({ accountId, box, uids, flags: ["\\Flagged"] })
        : cache.addFlag({ accountId, box, uids, flag: "\\Flagged" })
    }
  })
}

const isTest = process.env.NODE_ENV
const dbPath = getDbPath("queue.sqlite", electronIsDev)

const store = isTest
  ? new SqliteStore<Task<typeof handlers>>({ memory: true })
  : new SqliteStore<Task<typeof handlers>>({
      path: dbPath
    })

if (process.env.NODE_ENV !== "test") {
  fs.chmodSync(dbPath, 0o600)
}

const queueOptions = {
  maxRetries: 3,
  maxTimeout: isTest ? 150 : Infinity,
  retryDelay: isTest ? 1 : 10000,
  store
} as const

export const { actions, queue, schedule } = combineHandlers(
  queueOptions,
  handlers
)

async function withConnectionManager<T>(
  accountId: ID,
  fn: (cm: ConnectionManager) => Promise<T>
): Promise<T> {
  const connectionManager = AccountManager.getConnectionManager(accountId)
  if (connectionManager) {
    return fn(connectionManager)
  } else {
    throw new Error(
      `could not get connection manager for account ID, ${accountId}`
    )
  }
}

async function withSmtpTransporter<T>(
  accountId: ID,
  fn: (cm: Transporter) => Promise<T>
): Promise<T> {
  const transporter = AccountManager.getSmtpTransporter(accountId)
  if (transporter) {
    return fn(transporter)
  } else {
    throw new Error(
      `could not get SMTP transporter for account ID, ${accountId}`
    )
  }
}

export function getQueuedTasks(): Array<Task<typeof handlers>> {
  return store.getAll()
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnitTestInitialization.xUnitUtils;
using Xunit;

namespace UnitTestInitialization
{
    [PrioritizedFixture]
    public class xUnitTest
    {
        private int _instanceCounter = 0;
        private static int _classCounter = 0;

        public xUnitTest()
        {
            ++_instanceCounter;
            ++_classCounter;
        }

        [Fact]
        [TestPriority(1)]
        public void Test1()
        {
            Assert.Equal(1, _instanceCounter);
        }

        [Fact, TestPriority(2)]
        public void Test2()
        {
            Assert.Equal(2, _instanceCounter);
        }

        [Fact, TestPriority(3)]
        public void Test3()
        {
            Assert.Equal(3, _instanceCounter);
        }

        [Fact, TestPriority(4)]
        public void StaticTest4()
        {
            Assert.Equal(4, _classCounter);
        }

        [Fact, TestPriority(5)]
        public void StaticTest5()
        {
            Assert.Equal(5, _classCounter);
        }

        [Fact, TestPriority(6)]
        public void StaticTest6()
        {
            Assert.Equal(6, _classCounter);
        }
    }
}


text:
Malay Name Parser: A simple script for parsing complex Malay names into their individual components.

- Salutation
- First Name
- Last Name
- Gender

## Example Usage

```php
$siapa = Siapa::name("Dato' Dr. Ir Hj. Hariadi Bin Hinta");
echo $siapa->salutation(); // Dato' Dr. Ir Hj.
echo $siapa->first(); // Hariadi
echo $siapa->last(); // Bin Hinta
echo $siapa->gender(); // M
```

## Install

If you're using Composer to manage dependencies, you can include the following
in your composer.json file:

    `composer require hariadi/siapa`

Then, after running `composer update` or `php composer.phar update`, you can
load the class using Composer's autoloading:

```php
require 'vendor/autoload.php';
```

Otherwise, you can simply require the file directly:

```php
require_once 'path/to/Siapa/src/Siapa.php';
```

## OO and Procedural

The library offers both OO method chaining with `Hariadi\Siapa`. An example
of the former is the following:

```php
use Hariadi\Siapa;
echo Siapa::name('Hariadi Hinta', 'UTF-8')->first();  // Hariadi
```

## Methods

*Note: If `$encoding` is not given, it defaults to `mb_internal_encoding()`.*

#### salutation

`$siapa->salutation()`

`Siapa::salutation()`

Returns salutation from full name.

```php
Siapa::name('Datuk Dr. Ir. Hariadi Hinta', 'UTF-8')->salutation(); // Datuk Dr. Ir.
```

#### givenName

`Siapa::givenName()`

Returns the combine of first and last name without salutation and optional with or witout middle name.

```php
Siapa::name('Dato\' Hariadi Bin Hinta', 'UTF-8')->givenName(false); // Hariadi Bin Hinta
```

#### first

`Siapa::first()`

Returns the first name.

```php
Siapa::name('Hariadi Hinta', 'UTF-8')->first(); // Hariadi
```

#### last

`Siapa::last()`

Returns the last name.

```php
Siapa::name('Hariadi Hinta', 'UTF-8')->last(); // Hinta
```

#### gender

`Siapa::gender(boolean $short)`

Returns the gender of name. Default param is `true` for short gender (M for Male and F for Female).

```php
Siapa::name('Hariadi Hinta', 'UTF-8')->gender(false); // Male
```

Algorithm to detect malay name gender:
- Default gender is Male
- Check if `Binti`, `Bte.`, `Bte`, `Puan`, `Puan`, `Pn.`, `Bt.`, `Bt`, `A/P` exist in first name
- If not found then we check for salutation if `Hajah`, `Hajjah`, `Hjh.`, `Puan`, `Pn.`, `Cik` exist.
- If not found then we check for common female malay name in [`female.txt`](https://github.com/hariadi/Siapa/blob/master/src/data/female.txt) library

## Tests

1. Clone the repository: git clone https://github.com/hariadi/Siapa.git
2. From the project directory, tests can be ran using `phpunit`

## License

Released under the MIT License - see `LICENSE.txt` for details.


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

import java.util.List;
import java.util.UUID;

import org.jdbi.v3.core.Handle;
import org.jdbi.v3.core.Jdbi;
import org.jdbi.v3.core.statement.UnableToCreateStatementException;
import org.jdbi.v3.sqlobject.customizer.BindList;
import org.jdbi.v3.sqlobject.statement.SqlQuery;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.google.common.collect.Lists;

public class TestBindListParameter {

    private Jdbi db;
    private Handle handle;
    private MyDAO dao;

    @Before
    public void setUp() {
        db = Jdbi.create("jdbc:h2:mem:" + UUID.randomUUID());
        db.installPlugin(new SqlObjectPlugin());
        handle = db.open();
        handle.createUpdate(
                "create table foo (id int, bar varchar(100) default null);")
                .execute();
        dao = db.onDemand(MyDAO.class);
    }

    @After
    public void tearDown() throws Exception {
        handle.execute("drop table foo");
        handle.close();
    }

    @Test(expected = UnableToCreateStatementException.class)
    public void testBrokenSyntax() {
        dao.broken();
    }

    @Test
    public void testWorks() {
        dao.works(Lists.newArrayList(1L, 2L));
    }

    @Test
    public void testIds() {
        dao.ids(Lists.newArrayList(1, 2));
    }

    public interface MyDAO {
        @SqlQuery("select count(*) from foo where bar < 12 and id in (<ids>)")
        int broken();

        @SqlQuery("select count(*) from foo where bar \\< 12 and id in (<ids>)")
        int works(@BindList List<Long> ids);

        @SqlQuery("select count(*) from foo where id in (<ids>)")
        int ids(@BindList List<Integer> ids);
    }
}


text:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib

def make_scatter(dpp_y, dpp_err, rand_y, rand_err, dpp_num_samples, rand_num_samples, dpp_num_iters, space):

    x = range(1,len(dpp_y)+1)
    dpp_x = [i-.1 for i in x]
    rand_x = [i+.1 for i in x]

    # First illustrate basic pyplot interface, using defaults where possible.
    plt.figure()
    plt.errorbar(dpp_x, dpp_y, yerr=dpp_err, fmt='o',elinewidth=.5,markersize=2)
    plt.errorbar(rand_x, rand_y, yerr=rand_err, fmt='s',elinewidth=.5, markersize=2)
    plt.title("Mean best dev acc after K iterations, with 95% CI")
    plt.legend(["DPP","Random"],loc='lower right')

    plt.savefig('plot_drafts/cnn_iter={}_dppRestarts={}_randRestarts={}_space={}.pdf'.format(dpp_num_iters, dpp_num_samples, rand_num_samples, space))

def add_scatter(data, order, names, space, cur_ax, ylim_lower=None, ylim_upper=None, last_few=None):
    x = range(1,len(data['dpp']['avg_best'])+1)
    if last_few is not None:
        x = [xi + last_few for xi in x]
    diff_x = {}
    counter = 0
    width = .3
    for algo in order:
        counter += 1
        #diff_x[algo] = [(width*1.0/len(data)) * counter + x_i for x_i in x]
        diff_x[algo] = x
    #dpp_x = [i-.15 for i in x]
    #ham_x = x
    #rand_x = [i+.15 for i in x]

    if space != 'arch':
        cur_ax.set_ylim([.545,.83])
    if ylim_lower is not None:
        cur_ax.set_ylim([ylim_lower,ylim_upper])

    #cur_ax.errorbar(rand_x, rand_info['avg_best'], yerr=rand_info['ci'], fmt=',',elinewidth=.5, markersize=2)
    #cur_ax.errorbar(dpp_x, dpp_info['avg_best'], yerr=dpp_info['ci'], fmt=',',elinewidth=.5,markersize=2)
    #cur_ax.errorbar(ham_x, ham_info['avg_best'], yerr=ham_info['ci'], fmt=',',elinewidth=.5, markersize=2)
    for algo in order:
        if algo in data:
            cur_ax.plot(diff_x[algo], data[algo]['avg_best'], dashes=data[algo]['dash'], linewidth=1)
    #cur_ax.plot(rand_x, rand_info['avg_best'], '-', linewidth=1)
    #if ham_info is not None:
    #    cur_ax.plot(ham_x, ham_info['avg_best'], '--', linewidth=1)
    #cur_ax.plot(dpp_x, dpp_info['avg_best'],':', linewidth=1)

    if space == 'reg_bad_lr':
        cur_ax.set_title("Hard learning rate".format(space))
    elif space == 'reg_half_bad_lr':
        cur_ax.set_title("Medium learning rate".format(space))
    elif space == 'reg':
        cur_ax.set_title("Easy learning rate".format(space))

    cur_ax.legend([names[name] for name in order if name in data], loc='lower right')
    #if ham_info is not None:
    #    cur_ax.legend(["Uniform", "k-DPP-Hamm", "k-DPP-Cos"],loc='lower right')
    #else:
    #    cur_ax.legend(["Uniform", "k-DPP-Cos"],loc='lower right')

    cur_ax.xaxis.set_major_locator(matplotlib.ticker.MaxNLocator(integer=True))

    #cur_ax.locator_params(axis='x', nticks=11)

    #num_vals = len(x)
    #pos = np.arange(num_vals)
    #ticks = []
    #for i in range(10):
    #    ticks.append(str(i*2 + 1))
    #    ticks.append('')
    #print ticks
    #cur_ax.set_xticks(ticks)


text:
from azure.template import template_main

def simple_sample():
    print("Running simple sample")
    template_main()
    print("Completed running simple sample")

if __name__ == "__main__":
    simple_sample()


text:
<?php

// IntroHelloBundle:secure:sucess.html.twig
return array (
);


text:
<?php

namespace Gerrie\Tests\Check;

use Gerrie\Check\DatabaseConnectionCheck;

class DatabaseConnectionCheckTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @var \Gerrie\Check\CheckInterface
     */
    protected $checkInstance;

    public function setUp()
    {
        $databaseMock = $this->getDatabaseMock();
        $this->checkInstance = new DatabaseConnectionCheck($databaseMock);
    }

    protected function getDatabaseMock($connectWillThrowException = false)
    {
        $database = $this->getMock('Gerrie\Component\Database\Database', [], [[]]);

        if ($connectWillThrowException === true) {
            $database->expects($this->any())
                     ->method('connect')
                     ->will($this->throwException(new \Exception()));
        }

        return $database;
    }

    public function tearDown()
    {
        $this->checkInstance = null;
    }

    public function testCheckWithDatabaseConnection()
    {
        $this->assertTrue($this->checkInstance->check());
    }

    public function testCheckWithoutDatabaseConnection()
    {
        $databaseMock = $this->getDatabaseMock(true);
        $checkInstance = new DatabaseConnectionCheck($databaseMock);

        $this->assertFalse($checkInstance->check());
    }

    public function testGetFailureMessage()
    {
        $this->checkInstance->check();
        $this->assertInternalType('string', $this->checkInstance->getFailureMessage());
    }

    public function testGetSuccessMessage()
    {
        $this->assertInternalType('string', $this->checkInstance->getSuccessMessage());
    }

    public function testIsOptional()
    {
        $this->assertInternalType('bool', $this->checkInstance->isOptional());
    }
}


text:
package com.intellij.psi;

import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.DocumentRunnable;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.Nullable;

public interface ExternalChangeAction extends Runnable,IgnorePsiEventsMarker {
  abstract class ExternalDocumentChange extends DocumentRunnable implements ExternalChangeAction {
    protected ExternalDocumentChange(@Nullable Document document, Project project) {
      super(document, project);
    }
  }
}


text:
/**
 * Dashboard routes.
 */
define(['angular', './controllers', 'common'], function(angular, controllers) {
  'use strict';

  var mod = angular.module('services.routes', ['yourprefix.common']);
  mod.config(['$routeProvider', function($routeProvider) {
    $routeProvider
      .when('/services',  {templateUrl: '/assets/partials/services/index.html',  controller:controllers.ServicesCtrl})
      .when('/services/factorial',  {templateUrl: '/assets/partials/services/factorial.html',  controller:controllers.FactorialCtrl});
  }]);
  return mod;
});


text:
package org.soitoolkit.tools.generator.model.enums;

public interface ILabeledEnum {
	String getLabel();
}


text:
Create your own collaborative radio for your live streams, working spaces, partys or events

## TODO:

[Trello](https://trello.com/b/CFYHFEDK)


text:
import { getCurrentTimestamp } from '@stylebot/utils';

const StylesModifiedTimeUpdate = async (): Promise<void> => {
  return new Promise(resolve => {
    chrome.storage.local.get(items => {
      if (items['styles']) {
        const styles = items['styles'];

        for (const url in styles) {
          const style = styles[url];

          if (!style.modifiedTime) {
            styles[url].modifiedTime = getCurrentTimestamp();
          }
        }

        chrome.storage.local.set({ styles }, () => {
          resolve();
        });
      } else {
        resolve();
      }
    });
  });
};

export default StylesModifiedTimeUpdate;


text:
var should = require('chai').should()
var fs = require('fs');

var formatter = require('../../lib/index');

describe('Formatters - Attributes', function() {
  it('should split multiple attributes in to own lines in self closing tag if tag length is more than 50 characters', function () {
    var test = '
';

    formatter.setOptions({});
    var result = formatter.format(test);
    var lines = result.split('\n');

    lines[0].trim().should.equal('
');
  });

  it('should split multiple attributes in to own lines in opening tag if tag length is more than 50 characters', function () {
    var test = '

';

    formatter.setOptions({});
    var result = formatter.format(test);
    var lines = result.split('\n');

    lines[0].trim().should.equal('
');
  });

  it('should split multiple attributes in to own lines if one attribute already is splitted', function () {
    var test = '

';

    formatter.setOptions({});
    var result = formatter.format(test);
    var lines = result.split('\n');

    lines[0].trim().should.equal('
');
  });
});


text:
/**
 * Program comment
 */

// L first statement
type T = any;


text:
module Ledger
  class Event
    attr_accessor :actor, :action, :object, :data, :created_at

    def initialize opts
      opts.each do |attr, value|
        self.send("#{attr}=", value) if respond_to?("#{attr}=")
      end
    end

    class << self
      def from_json json
        require 'json'
        self.new JSON.parse json
      end
    end
  end
end


text:
class SyobocalMailer < ActionMailer::Base
  default from: 'Annict <no-reply@annict.com>'

  def episode_created_notification(episode_id)
    @episode = Episode.find(episode_id)

    mail(to: 'anannict@gmail.com', subject: t('episodes.created_notification'))
  end

  def special_program_notification(alert_id)
    alert = Syobocal::Alert.find(alert_id)
    @work = alert.work
    @sub_title = alert.sc_sub_title
    @prog_comment = alert.sc_prog_comment

    mail(to: 'anannict@gmail.com', subject: t('syobocal.special_program_notification'))
  end
end


text:
import renderer from 'react-test-renderer'
import React from 'react'

import {mockModification} from '../../../utils/mock-data'
import EditAlignment from '../edit-alignment'

describe('Component > Modification > Edit Alignment', function () {
  it('renders correctly', function () {
    const props = {
      disabled: false,
      extendFromEnd: false,
      mapState: {
        modificationId: mockModification._id,
        state: null
      },
      modification: mockModification,
      allStops: [],
      numberOfStops: 16,
      segmentDistances: [45.22],
      setMapState: jest.fn(),
      update: jest.fn()
    }

    const tree = renderer.create(<EditAlignment {...props} />).toJSON()

    expect(tree).toMatchSnapshot()
  })
})


text:
import React from 'react';
import Icon from '../Icon';

export default class SkipPreviousIcon extends Icon {
  getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M12 12h4v24h-4zm7 12l17 12V12z"/></svg>;}
};


text:
package io.crate.planner.fetch;

import com.google.common.collect.ImmutableList;
import io.crate.analyze.OrderBy;
import io.crate.analyze.QuerySpec;
import io.crate.analyze.WhereClause;
import io.crate.metadata.ReferenceIdent;
import io.crate.metadata.ReferenceInfo;
import io.crate.metadata.TableIdent;
import io.crate.planner.RowGranularity;
import io.crate.planner.symbol.Reference;
import io.crate.planner.symbol.Symbol;
import io.crate.types.DataTypes;
import org.junit.Test;

import static io.crate.testing.TestingHelpers.isReference;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;

public class FetchPushDownTest {

    private static final TableIdent TABLE_IDENT = new TableIdent("s", "t");
    private static final Reference REF_I = new Reference(
            new ReferenceInfo(
                    new ReferenceIdent(new TableIdent("s", "t"), "i"),
                    RowGranularity.DOC,
                    DataTypes.INTEGER
            )
    );

    private static final Reference REF_A = new Reference(
            new ReferenceInfo(
                    new ReferenceIdent(new TableIdent("s", "t"), "a"),
                    RowGranularity.DOC,
                    DataTypes.STRING
            )
    );

    @Test
    public void testLimitIsPushedDown() throws Exception {
        QuerySpec qs = new QuerySpec();
        qs.outputs(ImmutableList.<Symbol>of(REF_I, REF_A));
        qs.limit(10);
        qs.offset(100);

        QuerySpec sub = FetchPushDown.pushDown(qs, TABLE_IDENT);
        assertThat(sub.limit(), is(110));
        assertThat(sub.offset(), is(0));

        assertThat(qs.limit(), is(10));
        assertThat(qs.offset(), is(100));
    }

    @Test
    public void testWhereIsPushedDown() throws Exception {
        QuerySpec qs = new QuerySpec();
        qs.outputs(ImmutableList.<Symbol>of(REF_I, REF_A));
        qs.where(WhereClause.NO_MATCH);

        QuerySpec sub = FetchPushDown.pushDown(qs, TABLE_IDENT);

        assertThat(sub.where(), is(WhereClause.NO_MATCH));
        assertThat(qs.where(), is(WhereClause.MATCH_ALL));
    }

    @Test
    public void testPushDownWithoutOrder() throws Exception {
        QuerySpec qs = new QuerySpec();
        qs.outputs(ImmutableList.<Symbol>of(REF_A, REF_I));
        QuerySpec sub = FetchPushDown.pushDown(qs, TABLE_IDENT);
        assertThat(qs.outputs(), hasSize(2));

        assertThat(qs.outputs().get(0), isReference("a"));
        assertThat(qs.outputs().get(1), isReference("i"));

        assertThat(sub.outputs(), hasSize(1));
        assertThat(sub.outputs().get(0), isReference("_docid"));
    }

    @Test
    public void testPushDownWithOrder() throws Exception {
        QuerySpec qs = new QuerySpec();
        qs.outputs(ImmutableList.<Symbol>of(REF_A, REF_I));
        qs.orderBy(new OrderBy(ImmutableList.<Symbol>of(REF_I), new boolean[]{true}, new Boolean[]{false}));
        QuerySpec sub = FetchPushDown.pushDown(qs, TABLE_IDENT);
        assertThat(qs.outputs(), hasSize(2));

        assertThat(qs.outputs().get(0), isReference("a"));
        assertThat(qs.outputs().get(1), isReference("i"));

        assertThat(sub.outputs(), hasSize(2));
        assertThat(sub.outputs().get(0), isReference("_docid"));
        assertThat(sub.outputs().get(1), isReference("i"));
    }

    @Test
    public void testNoPushDownWithOrder() throws Exception {
        QuerySpec qs = new QuerySpec();
        qs.outputs(ImmutableList.<Symbol>of(REF_I));
        qs.orderBy(new OrderBy(ImmutableList.<Symbol>of(REF_I), new boolean[]{true}, new Boolean[]{false}));

        assertNull(FetchPushDown.pushDown(qs, TABLE_IDENT));
        assertThat(qs.outputs(), contains(isReference("i")));
    }
}