text:
typedef struct ComputeReferenceInfoF_
{
    float *x;
    cl_ushort *r;
    f2h f;
    cl_ulong i;
    cl_uint lim;
    cl_uint count;
} ComputeReferenceInfoF;

typedef struct ComputeReferenceInfoD_
{
    double *x;
    cl_ushort *r;
    d2h f;
    cl_ulong i;
    cl_uint lim;
    cl_uint count;
} ComputeReferenceInfoD;

typedef struct CheckResultInfoF_
{
    const float *x;
    const cl_ushort *r;
    const cl_ushort *s;
    f2h f;
    const char *aspace;
    cl_uint lim;
    cl_uint count;
    int vsz;
} CheckResultInfoF;

typedef struct CheckResultInfoD_
{
    const double *x;
    const cl_ushort *r;
    const cl_ushort *s;
    d2h f;
    const char *aspace;
    cl_uint lim;
    cl_uint count;
    int vsz;
} CheckResultInfoD;

static cl_int
ReferenceF(cl_uint jid, cl_uint tid, void *userInfo)
{
    ComputeReferenceInfoF *cri = (ComputeReferenceInfoF *)userInfo;
    cl_uint lim = cri->lim;
    cl_uint count = cri->count;
    cl_uint off = jid * count;
    float *x = cri->x + off;
    cl_ushort *r = cri->r + off;
    f2h f = cri->f;
    cl_ulong i = cri->i + off;
    cl_uint j;

    if (off + count > lim)
        count = lim - off;

    for (j = 0; j < count; ++j) {
        x[j] = as_float((cl_uint)(i + j));
        r[j] = f(x[j]);
    }

    return 0;
}

static cl_int
CheckF(cl_uint jid, cl_uint tid, void *userInfo)
{
    CheckResultInfoF *cri = (CheckResultInfoF *)userInfo;
    cl_uint lim = cri->lim;
    cl_uint count = cri->count;
    cl_uint off = jid * count;
    const float *x = cri->x + off;
    const cl_ushort *r = cri->r + off;
    const cl_ushort *s = cri->s + off;
    f2h f = cri->f;
    cl_uint j;
    cl_ushort correct2 = f( 0.0f);
    cl_ushort correct3 = f(-0.0f);
    cl_int ret = 0;

    if (off + count > lim)
        count = lim - off;

    if (!memcmp(r, s, count*sizeof(cl_ushort)))
        return 0;

    for (j = 0; j < count; j++) {
        if (s[j] == r[j]) continue;

        // Pass any NaNs
        if ((s[j] & 0x7fff) > 0x7c00 && (r[j] & 0x7fff) > 0x7c00 )
            continue;

        // retry per section 6.5.3.3
        if (IsFloatSubnormal(x[j]) && (s[j] == correct2 || s[j] == correct3))
            continue;

        // if reference result is subnormal, pass any zero
        if (gIsEmbedded && IsHalfSubnormal(r[j]) && (s[j] == 0x0000 || s[j] == 0x8000))
            continue;

        vlog_error("\nFailure at [%u] with %.6a: *0x%04x vs 0x%04x,  vector_size = %d, address_space = %s\n",
                   j+off, x[j], r[j], s[j], cri->vsz, cri->aspace);

        ret = 1;
        break;
    }

    return ret;
}

static cl_int
ReferenceD(cl_uint jid, cl_uint tid, void *userInfo)
{
    ComputeReferenceInfoD *cri = (ComputeReferenceInfoD *)userInfo;
    cl_uint lim = cri->lim;
    cl_uint count = cri->count;
    cl_uint off = jid * count;
    double *x = cri->x + off;
    cl_ushort *r = cri->r + off;
    d2h f = cri->f;
    cl_uint j;
    cl_ulong i = cri->i + off;

    if (off + count > lim)
        count = lim - off;

    for (j = 0; j < count; ++j) {
        x[j] = as_double(DoubleFromUInt((cl_uint)(i + j)));
        r[j] = f(x[j]);
    }

    return 0;
}

static cl_int
CheckD(cl_uint jid, cl_uint tid, void *userInfo)
{
    CheckResultInfoD *cri = (CheckResultInfoD *)userInfo;
    cl_uint lim = cri->lim;
    cl_uint count = cri->count;
    cl_uint off = jid * count;
    const double *x = cri->x + off;
    const cl_ushort *r = cri->r + off;
    const cl_ushort *s = cri->s + off;
    d2h f = cri->f;
    cl_uint j;
    cl_ushort correct2 = f( 0.0);
    cl_ushort correct3 = f(-0.0);
    cl_int ret = 0;

    if (off + count > lim)
        count = lim - off;

    if (!memcmp(r, s, count*sizeof(cl_ushort)))
        return 0;

    for (j = 0; j < count; j++) {
        if (s[j] == r[j]) continue;

        // Pass any NaNs
        if ((s[j] & 0x7fff) > 0x7c00 && (r[j] & 0x7fff) > 0x7c00)
            continue;

        if (IsDoubleSubnormal(x[j]) && (s[j] == correct2 || s[j] == correct3))
            continue;

        // if reference result is subnormal, pass any zero result
        if (gIsEmbedded && IsHalfSubnormal(r[j]) && (s[j] == 0x0000 || s[j] == 0x8000))
            continue;

        vlog_error("\nFailure at [%u] with %.13la: *0x%04x vs 0x%04x, vector_size = %d, address space = %s (double precision)\n",
                   j+off, x[j], r[j], s[j], cri->vsz, cri->aspace);

        ret = 1;
    break;
    }

    return ret;
}

static cl_half float2half_rte(float f)
{
    return cl_half_from_float(f, CL_HALF_RTE);
}

static cl_half float2half_rtz(float f)
{
    return cl_half_from_float(f, CL_HALF_RTZ);
}

static cl_half float2half_rtp(float f)
{
    return cl_half_from_float(f, CL_HALF_RTP);
}

static cl_half float2half_rtn(float f)
{
    return cl_half_from_float(f, CL_HALF_RTN);
}

static cl_half double2half_rte(double f)
{
    return cl_half_from_double(f, CL_HALF_RTE);
}

static cl_half double2half_rtz(double f)
{
    return cl_half_from_double(f, CL_HALF_RTZ);
}

static cl_half double2half_rtp(double f)
{
    return cl_half_from_double(f, CL_HALF_RTP);
}

static cl_half double2half_rtn(double f)
{
    return cl_half_from_double(f, CL_HALF_RTN);
}

int test_vstore_half( cl_device_id deviceID, cl_context context, cl_command_queue queue, int num_elements )
{
    switch (get_default_rounding_mode(deviceID))
    {
        case CL_FP_ROUND_TO_ZERO:
            return Test_vStoreHalf_private(deviceID, float2half_rtz, double2half_rte, "");
        case 0:
            return -1;
        default:
            return Test_vStoreHalf_private(deviceID, float2half_rte, double2half_rte, "");
    }
}

int test_vstore_half_rte( cl_device_id deviceID, cl_context context, cl_command_queue queue, int num_elements )
{
    return Test_vStoreHalf_private(deviceID, float2half_rte, double2half_rte, "_rte");
}

int test_vstore_half_rtz( cl_device_id deviceID, cl_context context, cl_command_queue queue, int num_elements )
{
    return Test_vStoreHalf_private(deviceID, float2half_rtz, double2half_rtz, "_rtz");
}

int test_vstore_half_rtp( cl_device_id deviceID, cl_context context, cl_command_queue queue, int num_elements )
{
    return Test_vStoreHalf_private(deviceID, float2half_rtp, double2half_rtp, "_rtp");
}

int test_vstore_half_rtn( cl_device_id deviceID, cl_context context, cl_command_queue queue, int num_elements )
{
    return Test_vStoreHalf_private(deviceID, float2half_rtn, double2half_rtn, "_rtn");
}

int test_vstorea_half( cl_device_id deviceID, cl_context context, cl_command_queue queue, int num_elements )
{
    switch (get_default_rounding_mode(deviceID))
    {
        case CL_FP_ROUND_TO_ZERO:
            return Test_vStoreaHalf_private(deviceID,float2half_rtz, double2half_rte, "");
        case 0:
            return -1;
        default:
            return Test_vStoreaHalf_private(deviceID, float2half_rte, double2half_rte, "");
    }
}

int test_vstorea_half_rte( cl_device_id deviceID, cl_context context, cl_command_queue queue, int num_elements )
{
    return Test_vStoreaHalf_private(deviceID, float2half_rte, double2half_rte, "_rte");
}

int test_vstorea_half_rtz( cl_device_id deviceID, cl_context context, cl_command_queue queue, int num_elements )
{
    return Test_vStoreaHalf_private(deviceID, float2half_rtz, double2half_rtz, "_rtz");
}

int test_vstorea_half_rtp( cl_device_id deviceID, cl_context context, cl_command_queue queue, int num_elements )
{
    return Test_vStoreaHalf_private(deviceID, float2half_rtp, double2half_rtp, "_rtp");
}

int test_vstorea_half_rtn( cl_device_id deviceID, cl_context context, cl_command_queue queue, int num_elements )
{
    return Test_vStoreaHalf_private(deviceID, float2half_rtn, double2half_rtn, "_rtn");
}

#pragma mark -

int Test_vStoreHalf_private( cl_device_id device, f2h referenceFunc, d2h doubleReferenceFunc, const char *roundName )
{
    int vectorSize, error;
    cl_program  programs[kVectorSizeCount+kStrangeVectorSizeCount][3];
    cl_kernel   kernels[kVectorSizeCount+kStrangeVectorSizeCount][3];

    uint64_t time[kVectorSizeCount+kStrangeVectorSizeCount] = {0};
    uint64_t min_time[kVectorSizeCount+kStrangeVectorSizeCount] = {0};
    memset( min_time, -1, sizeof( min_time ) );
    cl_program  doublePrograms[kVectorSizeCount+kStrangeVectorSizeCount][3];
    cl_kernel   doubleKernels[kVectorSizeCount+kStrangeVectorSizeCount][3];
    uint64_t doubleTime[kVectorSizeCount+kStrangeVectorSizeCount] = {0};
    uint64_t min_double_time[kVectorSizeCount+kStrangeVectorSizeCount] = {0};
    memset( min_double_time, -1, sizeof( min_double_time ) );

    bool aligned= false;

    for( vectorSize = kMinVectorSize; vectorSize < kLastVectorSizeToTest; vectorSize++)
    {
        const char *source[] = {
            "__kernel void test( __global float", vector_size_name_extensions[vectorSize]," *p, __global half *f )\n"
            "{\n"
            "   size_t i = get_global_id(0);\n"
            "   vstore_half",vector_size_name_extensions[vectorSize],roundName,"( p[i], i, f );\n"
            "}\n"
        };

        const char *source_v3[] = {
            "__kernel void test( __global float *p, __global half *f,\n"
            "                   uint extra_last_thread)\n"
            "{\n"
            "   size_t i = get_global_id(0);\n"
            "   size_t last_i = get_global_size(0)-1;\n"
            "   size_t adjust = 0;\n"
            "   if(last_i == i && extra_last_thread != 0) {\n"
            "     adjust = 3-extra_last_thread;\n"
            "   } "
            "   vstore_half3",roundName,"( vload3(i, p-adjust), i, f-adjust );\n"
            "}\n"
        };

        const char *source_private_store[] = {
            "__kernel void test( __global float", vector_size_name_extensions[vectorSize]," *p, __global half *f )\n"
            "{\n"
            "   __private ushort data[16];\n"
            "   size_t i = get_global_id(0);\n"
            "   size_t offset = 0;\n"
            "   size_t vecsize = vec_step(p[i]);\n"
            "   vstore_half",vector_size_name_extensions[vectorSize],roundName,"( p[i], 0, (__private half *)(&data[0]) );\n"
            "   for(offset = 0; offset < vecsize; offset++)\n"
            "   {\n"
            "       vstore_half(vload_half(offset, (__private half *)data), 0, &f[vecsize*i+offset]);\n"
            "   }\n"
            "}\n"
        };

        const char *source_private_store_v3[] = {
            "__kernel void test( __global float *p, __global half *f,\n"
            "                   uint extra_last_thread )\n"
            "{\n"
            "   __private ushort data[4];\n"
            "   size_t i = get_global_id(0);\n"
            "   size_t last_i = get_global_size(0)-1;\n"
            "   size_t adjust = 0;\n"
            "   size_t offset = 0;\n"
            "   if(last_i == i && extra_last_thread != 0) {\n"
            "     adjust = 3-extra_last_thread;\n"
            "   } "
            "   vstore_half3",roundName,"( vload3(i, p-adjust), 0, (__private half *)(&data[0]) );\n"
            "   for(offset = 0; offset < 3; offset++)\n"
            "   {\n"
            "       vstore_half(vload_half(offset, (__private half *) data), 0, &f[3*i+offset-adjust]);\n"
            "   }\n"
            "}\n"
        };

        char local_buf_size[10];
        sprintf(local_buf_size, "%lld", (uint64_t)gWorkGroupSize);

        const char *source_local_store[] = {
            "__kernel void test( __global float", vector_size_name_extensions[vectorSize]," *p, __global half *f )\n"
            "{\n"
            "   __local ushort data[16*", local_buf_size, "];\n"
            "   size_t i = get_global_id(0);\n"
            "   size_t lid = get_local_id(0);\n"
            "   size_t lsize = get_local_size(0);\n"
            "   size_t vecsize = vec_step(p[0]);\n"
            "   event_t async_event;\n"
            "   vstore_half",vector_size_name_extensions[vectorSize],roundName,"( p[i], lid, (__local half *)(&data[0]) );\n"
            "   barrier( CLK_LOCAL_MEM_FENCE ); \n"
            "   async_event = async_work_group_copy((__global ushort *)f+vecsize*(i-lid), (__local ushort *)(&data[0]), vecsize*lsize, 0);\n" // investigate later
            "   wait_group_events(1, &async_event);\n"
            "}\n"
        };

        const char *source_local_store_v3[] = {
            "__kernel void test( __global float *p, __global half *f,\n"
            "                   uint extra_last_thread )\n"
            "{\n"
            "   __local ushort data[3*(",
            local_buf_size,
            "+1)];\n"
            "   size_t i = get_global_id(0);\n"
            "   size_t lid = get_local_id(0);\n"
            "   size_t last_i = get_global_size(0)-1;\n"
            "   size_t adjust = 0;\n"
            "   size_t lsize = get_local_size(0);\n"
            "   event_t async_event;\n"
            "   if(last_i == i && extra_last_thread != 0) {\n"
            "     adjust = 3-extra_last_thread;\n"
            "   } "
            "   vstore_half3",
            roundName,
            "( vload3(i,p-adjust), lid, (__local half *)(&data[0]) );\n"
            "   barrier( CLK_LOCAL_MEM_FENCE ); \n"
            "   if (get_group_id(0) == (get_num_groups(0) - 1) &&\n"
            "       extra_last_thread != 0) {\n"
            "     adjust = 3-extra_last_thread;\n"
            "   }\n"
            "   async_event = async_work_group_copy(\n"
            "       (__global ushort*)(f+3*(i-lid)),\n"
            "       (__local ushort *)(&data[adjust]),\n"
            "       lsize*3-adjust, 0);\n" // investigate later
            "   wait_group_events(1, &async_event);\n"
            "}\n"
        };

        const char *double_source[] = {
            "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n"
            "__kernel void test( __global double", vector_size_name_extensions[vectorSize]," *p, __global half *f )\n"
            "{\n"
            "   size_t i = get_global_id(0);\n"
            "   vstore_half",vector_size_name_extensions[vectorSize],roundName,"( p[i], i, f );\n"
            "}\n"
        };

        const char *double_source_private_store[] = {
            "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n"
            "__kernel void test( __global double", vector_size_name_extensions[vectorSize]," *p, __global half *f )\n"
            "{\n"
            "   __private ushort data[16];\n"
            "   size_t i = get_global_id(0);\n"
            "   size_t offset = 0;\n"
            "   size_t vecsize = vec_step(p[i]);\n"
            "   vstore_half",vector_size_name_extensions[vectorSize],roundName,"( p[i], 0, (__private half *)(&data[0]) );\n"
            "   for(offset = 0; offset < vecsize; offset++)\n"
            "   {\n"
            "       vstore_half(vload_half(offset, (__private half *)data), 0, &f[vecsize*i+offset]);\n"
            "   }\n"
            "}\n"
        };

        const char *double_source_local_store[] = {
            "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n"
            "__kernel void test( __global double", vector_size_name_extensions[vectorSize]," *p, __global half *f )\n"
            "{\n"
            "   __local ushort data[16*", local_buf_size, "];\n"
            "   size_t i = get_global_id(0);\n"
            "   size_t lid = get_local_id(0);\n"
            "   size_t vecsize = vec_step(p[0]);\n"
            "   size_t lsize = get_local_size(0);\n"
            "   event_t async_event;\n"
            "   vstore_half",vector_size_name_extensions[vectorSize],roundName,"( p[i], lid, (__local half *)(&data[0]) );\n"
            "   barrier( CLK_LOCAL_MEM_FENCE ); \n"
            "   async_event = async_work_group_copy((__global ushort *)(f+vecsize*(i-lid)), (__local ushort *)(&data[0]), vecsize*lsize, 0);\n" // investigate later
            "   wait_group_events(1, &async_event);\n"
            "}\n"
        };

        const char *double_source_v3[] = {
            "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n"
            "__kernel void test( __global double *p, __global half *f ,\n"
            "                   uint extra_last_thread)\n"
            "{\n"
            "   size_t i = get_global_id(0);\n"
            "   size_t last_i = get_global_size(0)-1;\n"
            "   size_t adjust = 0;\n"
            "   if(last_i == i && extra_last_thread != 0) {\n"
            "     adjust = 3-extra_last_thread;\n"
            "   } "
            "   vstore_half3",roundName,"( vload3(i,p-adjust), i, f -adjust);\n"
            "}\n"
        };

        const char *double_source_private_store_v3[] = {
            "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n"
            "__kernel void test( __global double *p, __global half *f,\n"
            "                   uint extra_last_thread )\n"
            "{\n"
            "   __private ushort data[4];\n"
            "   size_t i = get_global_id(0);\n"
            "   size_t last_i = get_global_size(0)-1;\n"
            "   size_t adjust = 0;\n"
            "   size_t offset = 0;\n"
            "   if(last_i == i && extra_last_thread != 0) {\n"
            "     adjust = 3-extra_last_thread;\n"
            "   } "
            "   vstore_half3",roundName,"( vload3(i, p-adjust), 0, (__private half *)(&data[0]) );\n"
            "   for(offset = 0; offset < 3; offset++)\n"
            "   {\n"
            "       vstore_half(vload_half(offset, (__private half *)data), 0, &f[3*i+offset-adjust]);\n"
            "   }\n"
            "}\n"
        };

        const char *double_source_local_store_v3[] = {
            "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n"
            "__kernel void test( __global double *p, __global half *f,\n"
            "                   uint extra_last_thread )\n"
            "{\n"
            "   __local ushort data[3*(",
            local_buf_size,
            "+1)];\n"
            "   size_t i = get_global_id(0);\n"
            "   size_t lid = get_local_id(0);\n"
            "   size_t last_i = get_global_size(0)-1;\n"
            "   size_t adjust = 0;\n"
            "   size_t lsize = get_local_size(0);\n"
            "   event_t async_event;\n"
            "   if(last_i == i && extra_last_thread != 0) {\n"
            "     adjust = 3-extra_last_thread;\n"
            "   }\n "
            "   vstore_half3",
            roundName,
            "( vload3(i,p-adjust), lid, (__local half *)(&data[0]) );\n"
            "   barrier( CLK_LOCAL_MEM_FENCE ); \n"
            "   if (get_group_id(0) == (get_num_groups(0) - 1) &&\n"
            "       extra_last_thread != 0) {\n"
            "     adjust = 3-extra_last_thread;\n"
            "   }\n"
            "   async_event = async_work_group_copy(\n"
            "       (__global ushort *)(f+3*(i-lid)),\n"
            "       (__local ushort *)(&data[adjust]),\n"
            "       lsize*3-adjust, 0);\n" // investigate later
            "   wait_group_events(1, &async_event);\n"
            "}\n"
        };

        if(g_arrVecSizes[vectorSize] == 3) {
            programs[vectorSize][0] = MakeProgram( device, source_v3, sizeof(source_v3) / sizeof( source_v3[0]) );
        } else {
            programs[vectorSize][0] = MakeProgram( device, source, sizeof(source) / sizeof( source[0]) );
        }
        if( NULL == programs[ vectorSize ][0] )
        {
            gFailCount++;
            return -1;
        }

        kernels[ vectorSize ][0] = clCreateKernel( programs[ vectorSize ][0], "test", &error );
        if( NULL == kernels[vectorSize][0] )
        {
            gFailCount++;
            vlog_error( "\t\tFAILED -- Failed to create kernel. (%d)\n", error );
            return error;
        }

        if(g_arrVecSizes[vectorSize] == 3) {
            programs[vectorSize][1] = MakeProgram( device, source_private_store_v3, sizeof(source_private_store_v3) / sizeof( source_private_store_v3[0]) );
        } else {
            programs[vectorSize][1] = MakeProgram( device, source_private_store, sizeof(source_private_store) / sizeof( source_private_store[0]) );
        }
        if( NULL == programs[ vectorSize ][1] )
        {
            gFailCount++;
            return -1;
        }

        kernels[ vectorSize ][1] = clCreateKernel( programs[ vectorSize ][1], "test", &error );
        if( NULL == kernels[vectorSize][1] )
        {
            gFailCount++;
            vlog_error( "\t\tFAILED -- Failed to create private kernel. (%d)\n", error );
            return error;
        }

        if(g_arrVecSizes[vectorSize] == 3) {
            programs[vectorSize][2] = MakeProgram( device, source_local_store_v3, sizeof(source_local_store_v3) / sizeof( source_local_store_v3[0]) );
            if(  NULL == programs[ vectorSize ][2] )
            {
                unsigned q;
                for ( q= 0; q < sizeof( source_local_store_v3) / sizeof( source_local_store_v3[0]); q++)
                    vlog_error("%s", source_local_store_v3[q]);

                gFailCount++;
                return -1;

            }
        } else {
            programs[vectorSize][2] = MakeProgram( device, source_local_store, sizeof(source_local_store) / sizeof( source_local_store[0]) );
            if( NULL == programs[ vectorSize ][2] )
            {
                unsigned q;
                for ( q= 0; q < sizeof( source_local_store) / sizeof( source_local_store[0]); q++)
                    vlog_error("%s", source_local_store[q]);

                gFailCount++;
                return -1;

            }
        }

        kernels[ vectorSize ][2] = clCreateKernel( programs[ vectorSize ][2], "test", &error );
        if( NULL == kernels[vectorSize][2] )
        {
            gFailCount++;
            vlog_error( "\t\tFAILED -- Failed to create local kernel. (%d)\n", error );
            return error;
        }

        if( gTestDouble )
        {
            if(g_arrVecSizes[vectorSize] == 3) {
                doublePrograms[vectorSize][0] = MakeProgram( device, double_source_v3, sizeof(double_source_v3) / sizeof( double_source_v3[0]) );
            } else {
                doublePrograms[vectorSize][0] = MakeProgram( device, double_source, sizeof(double_source) / sizeof( double_source[0]) );
            }
            if( NULL == doublePrograms[ vectorSize ][0] )
            {
                gFailCount++;
                return -1;
            }

            doubleKernels[ vectorSize ][0] = clCreateKernel( doublePrograms[ vectorSize ][0], "test", &error );
            if( NULL == kernels[vectorSize][0] )
            {
                gFailCount++;
                vlog_error( "\t\tFAILED -- Failed to create double kernel. (%d)\n", error );
                return error;
            }

            if(g_arrVecSizes[vectorSize] == 3)
                doublePrograms[vectorSize][1] = MakeProgram( device, double_source_private_store_v3, sizeof(double_source_private_store_v3) / sizeof( double_source_private_store_v3[0]) );
            else
                doublePrograms[vectorSize][1] = MakeProgram( device, double_source_private_store, sizeof(double_source_private_store) / sizeof( double_source_private_store[0]) );

            if( NULL == doublePrograms[ vectorSize ][1] )
            {
                gFailCount++;
                return -1;
            }

            doubleKernels[ vectorSize ][1] = clCreateKernel( doublePrograms[ vectorSize ][1], "test", &error );
            if( NULL == kernels[vectorSize][1] )
            {
                gFailCount++;
                vlog_error( "\t\tFAILED -- Failed to create double private kernel. (%d)\n", error );
                return error;
            }

            if(g_arrVecSizes[vectorSize] == 3) {
                doublePrograms[vectorSize][2] = MakeProgram( device, double_source_local_store_v3, sizeof(double_source_local_store_v3) / sizeof( double_source_local_store_v3[0]) );
            } else {
                doublePrograms[vectorSize][2] = MakeProgram( device, double_source_local_store, sizeof(double_source_local_store) / sizeof( double_source_local_store[0]) );
            }
            if( NULL == doublePrograms[ vectorSize ][2] )
            {
                gFailCount++;
                return -1;
            }

            doubleKernels[ vectorSize ][2] = clCreateKernel( doublePrograms[ vectorSize ][2], "test", &error );
            if( NULL == kernels[vectorSize][2] )
            {
                gFailCount++;
                vlog_error( "\t\tFAILED -- Failed to create double local kernel. (%d)\n", error );
                return error;
            }
        }
    } // end for vector size

    // Figure out how many elements are in a work block
    size_t elementSize = std::max(sizeof(cl_ushort), sizeof(float));
    size_t blockCount = BUFFER_SIZE / elementSize; // elementSize is power of 2
    uint64_t lastCase = 1ULL << (8*sizeof(float)); // number of floats.
    size_t stride = blockCount;

    if (gWimpyMode)
        stride = (uint64_t)blockCount * (uint64_t)gWimpyReductionFactor;

    // we handle 64-bit types a bit differently.
    if( lastCase == 0 )
        lastCase = 0x100000000ULL;

    uint64_t i, j;
    error = 0;
    uint64_t printMask = (lastCase >> 4) - 1;
    cl_uint count = 0;
    int addressSpace;
    size_t loopCount;
    cl_uint threadCount = GetThreadCount();

    ComputeReferenceInfoF fref;
    fref.x = (float *)gIn_single;
    fref.r = (cl_half *)gOut_half_reference;
    fref.f = referenceFunc;
    fref.lim = blockCount;
    fref.count = (blockCount + threadCount - 1) / threadCount;

    CheckResultInfoF fchk;
    fchk.x = (const float *)gIn_single;
    fchk.r = (const cl_half *)gOut_half_reference;
    fchk.s = (const cl_half *)gOut_half;
    fchk.f = referenceFunc;
    fchk.lim = blockCount;
    fchk.count = (blockCount + threadCount - 1) / threadCount;

    ComputeReferenceInfoD dref;
    dref.x = (double *)gIn_double;
    dref.r = (cl_half *)gOut_half_reference_double;
    dref.f = doubleReferenceFunc;
    dref.lim = blockCount;
    dref.count = (blockCount + threadCount - 1) / threadCount;

    CheckResultInfoD dchk;
    dchk.x = (const double *)gIn_double;
    dchk.r = (const cl_half *)gOut_half_reference_double;
    dchk.s = (const cl_half *)gOut_half;
    dchk.f = doubleReferenceFunc;
    dchk.lim = blockCount;
    dchk.count = (blockCount + threadCount - 1) / threadCount;

    for( i = 0; i < lastCase; i += stride )
    {
        count = (cl_uint)std::min((uint64_t)blockCount, lastCase - i);
        fref.i = i;
        dref.i = i;

        // Compute the input and reference
        ThreadPool_Do(ReferenceF, threadCount, &fref);

        error = clEnqueueWriteBuffer(gQueue, gInBuffer_single, CL_FALSE, 0, count * sizeof(float ), gIn_single, 0, NULL, NULL);
        if (error) {
            vlog_error( "Failure in clWriteBuffer\n" );
            gFailCount++;
            goto exit;
        }

        if (gTestDouble) {
            ThreadPool_Do(ReferenceD, threadCount, &dref);

            error = clEnqueueWriteBuffer(gQueue, gInBuffer_double, CL_FALSE, 0, count * sizeof(double ), gIn_double, 0, NULL, NULL);
            if (error) {
                vlog_error( "Failure in clWriteBuffer\n" );
                gFailCount++;
                goto exit;
            }
        }

        for (vectorSize = kMinVectorSize; vectorSize < kLastVectorSizeToTest; vectorSize++) {
            // Loop through vector sizes
            fchk.vsz = g_arrVecSizes[vectorSize];
            dchk.vsz = g_arrVecSizes[vectorSize];

            for ( addressSpace = 0; addressSpace < 3; addressSpace++) {
                // Loop over address spaces
                fchk.aspace = addressSpaceNames[addressSpace];
                dchk.aspace = addressSpaceNames[addressSpace];

                cl_uint pattern = 0xdeaddead;
                memset_pattern4( gOut_half, &pattern, BUFFER_SIZE/2);

                error = clEnqueueWriteBuffer(gQueue, gOutBuffer_half, CL_FALSE,
                                             0, count * sizeof(cl_half),
                                             gOut_half, 0, NULL, NULL);
                if (error) {
                    vlog_error( "Failure in clWriteArray\n" );
                    gFailCount++;
                    goto exit;
                }

                error = RunKernel(device, kernels[vectorSize][addressSpace], gInBuffer_single, gOutBuffer_half,
                                       numVecs(count, vectorSize, aligned) ,
                                  runsOverBy(count, vectorSize, aligned));
                if (error) {
                    gFailCount++;
                    goto exit;
                }

                error = clEnqueueReadBuffer(gQueue, gOutBuffer_half, CL_TRUE, 0,
                                            count * sizeof(cl_half), gOut_half,
                                            0, NULL, NULL);
                if (error) {
                    vlog_error( "Failure in clReadArray\n" );
                    gFailCount++;
                    goto exit;
                }

                error = ThreadPool_Do(CheckF, threadCount, &fchk);
                if (error) {
                            gFailCount++;
                            goto exit;
                        }

                if (gTestDouble) {
                    memset_pattern4( gOut_half, &pattern, BUFFER_SIZE/2);

                    error = clEnqueueWriteBuffer(
                        gQueue, gOutBuffer_half, CL_FALSE, 0,
                        count * sizeof(cl_half), gOut_half, 0, NULL, NULL);
                    if (error) {
                        vlog_error( "Failure in clWriteArray\n" );
                        gFailCount++;
                        goto exit;
                    }

                    error = RunKernel(device, doubleKernels[vectorSize][addressSpace], gInBuffer_double, gOutBuffer_half,
                                      numVecs(count, vectorSize, aligned),
                                      runsOverBy(count, vectorSize, aligned));
                    if (error) {
                        gFailCount++;
                        goto exit;
                    }

                    error = clEnqueueReadBuffer(
                        gQueue, gOutBuffer_half, CL_TRUE, 0,
                        count * sizeof(cl_half), gOut_half, 0, NULL, NULL);
                    if (error) {
                        vlog_error( "Failure in clReadArray\n" );
                        gFailCount++;
                        goto exit;
                    }

                    error = ThreadPool_Do(CheckD, threadCount, &dchk);
                    if (error) {
                                gFailCount++;
                                goto exit;
                            }
                        }
                    }
                }

        if( ((i+blockCount) & ~printMask) == (i+blockCount) )
        {
            vlog( "." );
            fflush( stdout );
        }
    }  // end last case

    loopCount = count == blockCount ? 1 : 100;
    if( gReportTimes )
    {
        //Init the input stream
        cl_float *p = (cl_float *)gIn_single;
        for( j = 0; j < count; j++ )
            p[j] = (float)((double) (rand() - RAND_MAX/2) / (RAND_MAX/2));

        if( (error = clEnqueueWriteBuffer(gQueue, gInBuffer_single, CL_TRUE, 0, count * sizeof( float ), gIn_single, 0, NULL, NULL)) )
        {
            vlog_error( "Failure in clWriteArray\n" );
            gFailCount++;
            goto exit;
        }

        if( gTestDouble )
        {
            //Init the input stream
            cl_double *q = (cl_double *)gIn_double;
            for( j = 0; j < count; j++ )
                q[j] = ((double) (rand() - RAND_MAX/2) / (RAND_MAX/2));

            if( (error = clEnqueueWriteBuffer(gQueue, gInBuffer_double, CL_TRUE, 0, count * sizeof( double ), gIn_double, 0, NULL, NULL)) )
            {
                vlog_error( "Failure in clWriteArray\n" );
                gFailCount++;
                goto exit;
            }
        }

        //Run again for timing
        for( vectorSize = kMinVectorSize; vectorSize < kLastVectorSizeToTest; vectorSize++)
        {
            uint64_t bestTime = -1ULL;
            for( j = 0; j < loopCount; j++ )
            {
                uint64_t startTime = ReadTime();

                if( (error = RunKernel(device, kernels[vectorSize][0], gInBuffer_single, gOutBuffer_half, numVecs(count, vectorSize, aligned) ,
                                       runsOverBy(count, vectorSize, aligned)) ) )
                {
                    gFailCount++;
                    goto exit;
                }

                if( (error = clFinish(gQueue)) )
                {
                    vlog_error( "Failure in clFinish\n" );
                    gFailCount++;
                    goto exit;
                }
                uint64_t currentTime = ReadTime() - startTime;
                if( currentTime < bestTime )
                    bestTime = currentTime;
                time[ vectorSize ] += currentTime;
            }
            if( bestTime < min_time[ vectorSize ] )
                min_time[ vectorSize ] = bestTime ;

            if( gTestDouble )
            {
                bestTime = -1ULL;
                for( j = 0; j < loopCount; j++ )
                {
                    uint64_t startTime = ReadTime();
                    if( (error = RunKernel(device, doubleKernels[vectorSize][0], gInBuffer_double, gOutBuffer_half, numVecs(count, vectorSize, aligned) ,
                                           runsOverBy(count, vectorSize, aligned)) ) )
                    {
                        gFailCount++;
                        goto exit;
                    }

                    if( (error = clFinish(gQueue)) )
                    {
                        vlog_error( "Failure in clFinish\n" );
                        gFailCount++;
                        goto exit;
                    }
                    uint64_t currentTime = ReadTime() - startTime;
                    if( currentTime < bestTime )
                        bestTime = currentTime;
                    doubleTime[ vectorSize ] += currentTime;
                }
                if( bestTime < min_double_time[ vectorSize ] )
                    min_double_time[ vectorSize ] = bestTime;
            }
        }
    }

    if( gReportTimes )
    {
        for( vectorSize = kMinVectorSize; vectorSize < kLastVectorSizeToTest; vectorSize++)
            vlog_perf( SubtractTime( time[ vectorSize ], 0 ) * 1e6 * gDeviceFrequency * gComputeDevices / (double) (count * loopCount), 0,
                      "average us/elem", "vStoreHalf%s avg. (%s vector size: %d)", roundName, addressSpaceNames[0], (g_arrVecSizes[vectorSize]) );
        for( vectorSize = kMinVectorSize; vectorSize < kLastVectorSizeToTest; vectorSize++)
            vlog_perf( SubtractTime( min_time[ vectorSize ], 0 ) * 1e6 * gDeviceFrequency * gComputeDevices / (double) count, 0,
                      "best us/elem", "vStoreHalf%s best (%s vector size: %d)", roundName, addressSpaceNames[0], (g_arrVecSizes[vectorSize])  );
        if( gTestDouble )
        {
            for( vectorSize = kMinVectorSize; vectorSize < kLastVectorSizeToTest; vectorSize++)
                vlog_perf( SubtractTime( doubleTime[ vectorSize ], 0 ) * 1e6 * gDeviceFrequency * gComputeDevices / (double) (count * loopCount), 0,
                          "average us/elem (double)", "vStoreHalf%s avg. d (%s vector size: %d)", roundName, addressSpaceNames[0],  (g_arrVecSizes[vectorSize])  );
            for( vectorSize = kMinVectorSize; vectorSize < kLastVectorSizeToTest; vectorSize++)
                vlog_perf( SubtractTime( min_double_time[ vectorSize ], 0 ) * 1e6 * gDeviceFrequency * gComputeDevices / (double) count, 0,
                          "best us/elem (double)", "vStoreHalf%s best d (%s vector size: %d)", roundName, addressSpaceNames[0], (g_arrVecSizes[vectorSize]) );
        }
    }

exit:
    //clean up
    for( vectorSize = kMinVectorSize; vectorSize < kLastVectorSizeToTest; vectorSize++)
    {
        for ( addressSpace = 0; addressSpace < 3; addressSpace++) {
            clReleaseKernel( kernels[ vectorSize ][ addressSpace ] );
            clReleaseProgram( programs[ vectorSize ][ addressSpace ] );
            if( gTestDouble )
            {
                clReleaseKernel( doubleKernels[ vectorSize ][addressSpace] );
                clReleaseProgram( doublePrograms[ vectorSize ][addressSpace] );
            }
        }
    }

    return error;
}

int Test_vStoreaHalf_private( cl_device_id device, f2h referenceFunc, d2h doubleReferenceFunc, const char *roundName )
{
    int vectorSize, error;
    cl_program  programs[kVectorSizeCount+kStrangeVectorSizeCount][3];
    cl_kernel   kernels[kVectorSizeCount+kStrangeVectorSizeCount][3];

    uint64_t time[kVectorSizeCount+kStrangeVectorSizeCount] = {0};
    uint64_t min_time[kVectorSizeCount+kStrangeVectorSizeCount] = {0};
    memset( min_time, -1, sizeof( min_time ) );
    cl_program  doublePrograms[kVectorSizeCount+kStrangeVectorSizeCount][3];
    cl_kernel   doubleKernels[kVectorSizeCount+kStrangeVectorSizeCount][3];
    uint64_t doubleTime[kVectorSizeCount+kStrangeVectorSizeCount] = {0};
    uint64_t min_double_time[kVectorSizeCount+kStrangeVectorSizeCount] = {0};
    memset( min_double_time, -1, sizeof( min_double_time ) );

    bool aligned = true;

    int minVectorSize = kMinVectorSize;
    // There is no aligned scalar vstorea_half
    if( 0 == minVectorSize )
        minVectorSize = 1;

    //Loop over vector sizes
    for( vectorSize = minVectorSize; vectorSize < kLastVectorSizeToTest; vectorSize++)
    {
        const char *source[] = {
            "__kernel void test( __global float", vector_size_name_extensions[vectorSize]," *p, __global half *f )\n"
            "{\n"
            "   size_t i = get_global_id(0);\n"
            "   vstorea_half",vector_size_name_extensions[vectorSize],roundName,"( p[i], i, f );\n"
            "}\n"
        };

        const char *source_v3[] = {
            "__kernel void test( __global float3 *p, __global half *f )\n"
            "{\n"
            "   size_t i = get_global_id(0);\n"
            "   vstorea_half3",roundName,"( p[i], i, f );\n"
            "   vstore_half",roundName,"( ((__global  float *)p)[4*i+3], 4*i+3, f);\n"
            "}\n"
        };

        const char *source_private[] = {
            "__kernel void test( __global float", vector_size_name_extensions[vectorSize]," *p, __global half *f )\n"
            "{\n"
            "   __private float", vector_size_name_extensions[vectorSize], " data;\n"
            "   size_t i = get_global_id(0);\n"
            "   data = p[i];\n"
            "   vstorea_half",vector_size_name_extensions[vectorSize],roundName,"( data, i, f );\n"
            "}\n"
        };

        const char *source_private_v3[] = {
            "__kernel void test( __global float3 *p, __global half *f )\n"
            "{\n"
            "   __private float", vector_size_name_extensions[vectorSize], " data;\n"
            "   size_t i = get_global_id(0);\n"
            "   data = p[i];\n"
            "   vstorea_half3",roundName,"( data, i, f );\n"
            "   vstore_half",roundName,"( ((__global  float *)p)[4*i+3], 4*i+3, f);\n"
            "}\n"
        };

        char local_buf_size[10];
        sprintf(local_buf_size, "%lld", (uint64_t)gWorkGroupSize);
        const char *source_local[] = {
            "__kernel void test( __global float", vector_size_name_extensions[vectorSize]," *p, __global half *f )\n"
            "{\n"
            "   __local float", vector_size_name_extensions[vectorSize], " data[", local_buf_size, "];\n"
            "   size_t i = get_global_id(0);\n"
            "   size_t lid = get_local_id(0);\n"
            "   data[lid] = p[i];\n"
            "   vstorea_half",vector_size_name_extensions[vectorSize],roundName,"( data[lid], i, f );\n"
            "}\n"
        };

        const char *source_local_v3[] = {
            "__kernel void test( __global float", vector_size_name_extensions[vectorSize]," *p, __global half *f )\n"
            "{\n"
            "   __local float", vector_size_name_extensions[vectorSize], " data[", local_buf_size, "];\n"
            "   size_t i = get_global_id(0);\n"
            "   size_t lid = get_local_id(0);\n"
            "   data[lid] = p[i];\n"
            "   vstorea_half",vector_size_name_extensions[vectorSize],roundName,"( data[lid], i, f );\n"
            "   vstore_half",roundName,"( ((__global float *)p)[4*i+3], 4*i+3, f);\n"
            "}\n"
        };

        const char *double_source[] = {
            "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n"
            "__kernel void test( __global double", vector_size_name_extensions[vectorSize]," *p, __global half *f )\n"
            "{\n"
            "   size_t i = get_global_id(0);\n"
            "   vstorea_half",vector_size_name_extensions[vectorSize],roundName,"( p[i], i, f );\n"
            "}\n"
        };

        const char *double_source_v3[] = {
            "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n"
            "__kernel void test( __global double", vector_size_name_extensions[vectorSize]," *p, __global half *f )\n"
            "{\n"
            "   size_t i = get_global_id(0);\n"
            "   vstorea_half",vector_size_name_extensions[vectorSize],roundName,"( p[i], i, f );\n"
            "   vstore_half",roundName,"( ((__global double *)p)[4*i+3], 4*i+3, f);\n"
            "}\n"
        };

        const char *double_source_private[] = {
            "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n"
            "__kernel void test( __global double", vector_size_name_extensions[vectorSize]," *p, __global half *f )\n"
            "{\n"
            "   __private double", vector_size_name_extensions[vectorSize], " data;\n"
            "   size_t i = get_global_id(0);\n"
            "   data = p[i];\n"
            "   vstorea_half",vector_size_name_extensions[vectorSize],roundName,"( data, i, f );\n"
            "}\n"
        };

        const char *double_source_private_v3[] = {
            "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n"
            "__kernel void test( __global double", vector_size_name_extensions[vectorSize]," *p, __global half *f )\n"
            "{\n"
            "   __private double", vector_size_name_extensions[vectorSize], " data;\n"
            "   size_t i = get_global_id(0);\n"
            "   data = p[i];\n"
            "   vstorea_half",vector_size_name_extensions[vectorSize],roundName,"( data, i, f );\n"
            "   vstore_half",roundName,"( ((__global  double *)p)[4*i+3], 4*i+3, f);\n"
            "}\n"
        };

        const char *double_source_local[] = {
            "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n"
            "__kernel void test( __global double", vector_size_name_extensions[vectorSize]," *p, __global half *f )\n"
            "{\n"
            "   __local double", vector_size_name_extensions[vectorSize], " data[", local_buf_size, "];\n"
            "   size_t i = get_global_id(0);\n"
            "   size_t lid = get_local_id(0);\n"
            "   data[lid] = p[i];\n"
            "   vstorea_half",vector_size_name_extensions[vectorSize],roundName,"( data[lid], i, f );\n"
            "}\n"
        };

        const char *double_source_local_v3[] = {
            "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n"
            "__kernel void test( __global double", vector_size_name_extensions[vectorSize]," *p, __global half *f )\n"
            "{\n"
            "   __local double", vector_size_name_extensions[vectorSize], " data[", local_buf_size, "];\n"
            "   size_t i = get_global_id(0);\n"
            "   size_t lid = get_local_id(0);\n"
            "   data[lid] = p[i];\n"
            "   vstorea_half",vector_size_name_extensions[vectorSize],roundName,"( data[lid], i, f );\n"
            "   vstore_half",roundName,"( ((__global double *)p)[4*i+3], 4*i+3, f);\n"
            "}\n"
        };

        if(g_arrVecSizes[vectorSize] == 3) {
            programs[vectorSize][0] = MakeProgram( device, source_v3, sizeof(source_v3) / sizeof( source_v3[0]) );
            if( NULL == programs[ vectorSize ][0] )
            {
                gFailCount++;
                return -1;
            }
        } else {
            programs[vectorSize][0] = MakeProgram( device, source, sizeof(source) / sizeof( source[0]) );
            if( NULL == programs[ vectorSize ][0] )
            {
                gFailCount++;
                return -1;
            }
        }

        kernels[ vectorSize ][0] = clCreateKernel( programs[ vectorSize ][0], "test", &error );
        if( NULL == kernels[vectorSize][0] )
        {
            gFailCount++;
            vlog_error( "\t\tFAILED -- Failed to create kernel. (%d)\n", error );
            return error;
        }

        if(g_arrVecSizes[vectorSize] == 3) {
            programs[vectorSize][1] = MakeProgram( device, source_private_v3, sizeof(source_private_v3) / sizeof( source_private_v3[0]) );
            if( NULL == programs[ vectorSize ][1] )
            {
                gFailCount++;
                return -1;
            }
        } else {
            programs[vectorSize][1] = MakeProgram( device, source_private, sizeof(source_private) / sizeof( source_private[0]) );
            if( NULL == programs[ vectorSize ][1] )
            {
                gFailCount++;
                return -1;
            }
        }

        kernels[ vectorSize ][1] = clCreateKernel( programs[ vectorSize ][1], "test", &error );
        if( NULL == kernels[vectorSize][1] )
        {
            gFailCount++;
            vlog_error( "\t\tFAILED -- Failed to create private kernel. (%d)\n", error );
            return error;
        }

        if(g_arrVecSizes[vectorSize] == 3) {
            programs[vectorSize][2] = MakeProgram( device, source_local_v3, sizeof(source_local_v3) / sizeof( source_local_v3[0]) );
            if( NULL == programs[ vectorSize ][2] )
            {
                gFailCount++;
                return -1;
            }
        } else {
            programs[vectorSize][2] = MakeProgram( device, source_local, sizeof(source_local) / sizeof( source_local[0]) );
            if( NULL == programs[ vectorSize ][2] )
            {
                gFailCount++;
                return -1;
            }
        }

        kernels[ vectorSize ][2] = clCreateKernel( programs[ vectorSize ][2], "test", &error );
        if( NULL == kernels[vectorSize][2] )
        {
            gFailCount++;
            vlog_error( "\t\tFAILED -- Failed to create local kernel. (%d)\n", error );
            return error;
        }

        if( gTestDouble )
        {
            if(g_arrVecSizes[vectorSize] == 3) {
                doublePrograms[vectorSize][0] = MakeProgram( device, double_source_v3, sizeof(double_source_v3) / sizeof( double_source_v3[0]) );
                if( NULL == doublePrograms[ vectorSize ][0] )
                {
                    gFailCount++;
                    return -1;
                }
            } else {
                doublePrograms[vectorSize][0] = MakeProgram( device, double_source, sizeof(double_source) / sizeof( double_source[0]) );
                if( NULL == doublePrograms[ vectorSize ][0] )
                {
                    gFailCount++;
                    return -1;
                }
            }

            doubleKernels[ vectorSize ][0] = clCreateKernel( doublePrograms[ vectorSize ][0], "test", &error );
            if( NULL == kernels[vectorSize][0] )
            {
                gFailCount++;
                vlog_error( "\t\tFAILED -- Failed to create double kernel. (%d)\n", error );
                return error;
            }

            if(g_arrVecSizes[vectorSize] == 3) {
                doublePrograms[vectorSize][1] = MakeProgram( device, double_source_private_v3, sizeof(double_source_private_v3) / sizeof( double_source_private_v3[0]) );
                if( NULL == doublePrograms[ vectorSize ][1] )
                {
                    gFailCount++;
                    return -1;
                }
            } else {
                doublePrograms[vectorSize][1] = MakeProgram( device, double_source_private, sizeof(double_source_private) / sizeof( double_source_private[0]) );
                if( NULL == doublePrograms[ vectorSize ][1] )
                {
                    gFailCount++;
                    return -1;
                }
            }

            doubleKernels[ vectorSize ][1] = clCreateKernel( doublePrograms[ vectorSize ][1], "test", &error );
            if( NULL == kernels[vectorSize][1] )
            {
                gFailCount++;
                vlog_error( "\t\tFAILED -- Failed to create double private kernel. (%d)\n", error );
                return error;
            }

            if(g_arrVecSizes[vectorSize] == 3) {
                doublePrograms[vectorSize][2] = MakeProgram( device, double_source_local_v3, sizeof(double_source_local_v3) / sizeof( double_source_local_v3[0]) );
                if( NULL == doublePrograms[ vectorSize ][2] )
                {
                    gFailCount++;
                    return -1;
                }
            } else {
                doublePrograms[vectorSize][2] = MakeProgram( device, double_source_local, sizeof(double_source_local) / sizeof( double_source_local[0]) );
                if( NULL == doublePrograms[ vectorSize ][2] )
                {
                    gFailCount++;
                    return -1;
                }
            }

            doubleKernels[ vectorSize ][2] = clCreateKernel( doublePrograms[ vectorSize ][2], "test", &error );
            if( NULL == kernels[vectorSize][2] )
            {
                gFailCount++;
                vlog_error( "\t\tFAILED -- Failed to create double local kernel. (%d)\n", error );
                return error;
            }
        }
    }

    // Figure out how many elements are in a work block
    size_t elementSize = std::max(sizeof(cl_ushort), sizeof(float));
    size_t blockCount = BUFFER_SIZE / elementSize;
    uint64_t lastCase = 1ULL << (8*sizeof(float));
    size_t stride = blockCount;

    if (gWimpyMode)
        stride = (uint64_t)blockCount * (uint64_t)gWimpyReductionFactor;

    // we handle 64-bit types a bit differently.
    if( lastCase == 0 )
        lastCase = 0x100000000ULL;
    uint64_t i, j;
    error = 0;
    uint64_t printMask = (lastCase >> 4) - 1;
    cl_uint count = 0;
    int addressSpace;
    size_t loopCount;
    cl_uint threadCount = GetThreadCount();

    ComputeReferenceInfoF fref;
    fref.x = (float *)gIn_single;
    fref.r = (cl_half *)gOut_half_reference;
    fref.f = referenceFunc;
    fref.lim = blockCount;
    fref.count = (blockCount + threadCount - 1) / threadCount;

    CheckResultInfoF fchk;
    fchk.x = (const float *)gIn_single;
    fchk.r = (const cl_half *)gOut_half_reference;
    fchk.s = (const cl_half *)gOut_half;
    fchk.f = referenceFunc;
    fchk.lim = blockCount;
    fchk.count = (blockCount + threadCount - 1) / threadCount;

    ComputeReferenceInfoD dref;
    dref.x = (double *)gIn_double;
    dref.r = (cl_half *)gOut_half_reference_double;
    dref.f = doubleReferenceFunc;
    dref.lim = blockCount;
    dref.count = (blockCount + threadCount - 1) / threadCount;

    CheckResultInfoD dchk;
    dchk.x = (const double *)gIn_double;
    dchk.r = (const cl_half *)gOut_half_reference_double;
    dchk.s = (const cl_half *)gOut_half;
    dchk.f = doubleReferenceFunc;
    dchk.lim = blockCount;
    dchk.count = (blockCount + threadCount - 1) / threadCount;

    for( i = 0; i < (uint64_t)lastCase; i += stride )
    {
        count = (cl_uint)std::min((uint64_t)blockCount, lastCase - i);
        fref.i = i;
        dref.i = i;

        // Create the input and reference
        ThreadPool_Do(ReferenceF, threadCount, &fref);

        error = clEnqueueWriteBuffer(gQueue, gInBuffer_single, CL_FALSE, 0, count * sizeof(float ), gIn_single, 0, NULL, NULL);
        if (error) {
            vlog_error( "Failure in clWriteArray\n" );
            gFailCount++;
            goto exit;
        }

        if (gTestDouble) {
            ThreadPool_Do(ReferenceD, threadCount, &dref);

            error = clEnqueueWriteBuffer(gQueue, gInBuffer_double, CL_FALSE, 0, count * sizeof(double ), gIn_double, 0, NULL, NULL);
            if (error) {
                vlog_error( "Failure in clWriteArray\n" );
                gFailCount++;
                goto exit;
            }
        }

        for (vectorSize = minVectorSize; vectorSize < kLastVectorSizeToTest; vectorSize++) {
            // Loop over vector legths
            fchk.vsz = g_arrVecSizes[vectorSize];
            dchk.vsz = g_arrVecSizes[vectorSize];

            for ( addressSpace = 0; addressSpace < 3; addressSpace++) {
                // Loop over address spaces
                fchk.aspace = addressSpaceNames[addressSpace];
                dchk.aspace = addressSpaceNames[addressSpace];

                cl_uint pattern = 0xdeaddead;
                memset_pattern4(gOut_half, &pattern, BUFFER_SIZE/2);

                error = clEnqueueWriteBuffer(gQueue, gOutBuffer_half, CL_FALSE,
                                             0, count * sizeof(cl_half),
                                             gOut_half, 0, NULL, NULL);
                if (error) {
                    vlog_error( "Failure in clWriteArray\n" );
                    gFailCount++;
                    goto exit;
                }

                error = RunKernel(device, kernels[vectorSize][addressSpace], gInBuffer_single, gOutBuffer_half,
                                  numVecs(count, vectorSize, aligned),
                                  runsOverBy(count, vectorSize, aligned));
                if (error) {
                    gFailCount++;
                    goto exit;
                }

                error = clEnqueueReadBuffer(gQueue, gOutBuffer_half, CL_TRUE, 0,
                                            count * sizeof(cl_half), gOut_half,
                                            0, NULL, NULL);
                if (error) {
                    vlog_error( "Failure in clReadArray\n" );
                    gFailCount++;
                    goto exit;
                }

                error = ThreadPool_Do(CheckF, threadCount, &fchk);
                if (error) {
                            gFailCount++;
                            goto exit;
                        }

                if (gTestDouble) {
                    memset_pattern4(gOut_half, &pattern, BUFFER_SIZE/2);

                    error = clEnqueueWriteBuffer(
                        gQueue, gOutBuffer_half, CL_FALSE, 0,
                        count * sizeof(cl_half), gOut_half, 0, NULL, NULL);
                    if (error) {
                        vlog_error( "Failure in clWriteArray\n" );
                        gFailCount++;
                        goto exit;
                    }

                    error = RunKernel(device, doubleKernels[vectorSize][addressSpace], gInBuffer_double, gOutBuffer_half,
                                      numVecs(count, vectorSize, aligned),
                                      runsOverBy(count, vectorSize, aligned));
                    if (error) {
                        gFailCount++;
                        goto exit;
                    }

                    error = clEnqueueReadBuffer(
                        gQueue, gOutBuffer_half, CL_TRUE, 0,
                        count * sizeof(cl_half), gOut_half, 0, NULL, NULL);
                    if (error) {
                        vlog_error( "Failure in clReadArray\n" );
                        gFailCount++;
                        goto exit;
                    }

                    error = ThreadPool_Do(CheckD, threadCount, &dchk);
                    if (error) {
                                gFailCount++;
                                goto exit;
                            }
                        }
                    }
        }  // end for vector size

        if( ((i+blockCount) & ~printMask) == (i+blockCount) ) {
            vlog( "." );
            fflush( stdout );
        }
    }  // for end lastcase

    loopCount = count == blockCount ? 1 : 100;
    if( gReportTimes )
    {
        //Init the input stream
        cl_float *p = (cl_float *)gIn_single;
        for( j = 0; j < count; j++ )
            p[j] = (float)((double) (rand() - RAND_MAX/2) / (RAND_MAX/2));

        if( (error = clEnqueueWriteBuffer(gQueue, gInBuffer_single, CL_TRUE, 0, count * sizeof( float ), gIn_single, 0, NULL, NULL)) )
        {
            vlog_error( "Failure in clWriteArray\n" );
            gFailCount++;
            goto exit;
        }

        if( gTestDouble )
        {
            //Init the input stream
            cl_double *q = (cl_double *)gIn_double;
            for( j = 0; j < count; j++ )
                q[j] = ((double) (rand() - RAND_MAX/2) / (RAND_MAX/2));

            if( (error = clEnqueueWriteBuffer(gQueue, gInBuffer_double, CL_TRUE, 0, count * sizeof( double ), gIn_double, 0, NULL, NULL)) )
            {
                vlog_error( "Failure in clWriteArray\n" );
                gFailCount++;
                goto exit;
            }
        }

        //Run again for timing
        for( vectorSize = minVectorSize; vectorSize < kLastVectorSizeToTest; vectorSize++)
        {
            uint64_t bestTime = -1ULL;
            for( j = 0; j < loopCount; j++ )
            {
                uint64_t startTime = ReadTime();
                if( (error = RunKernel(device, kernels[vectorSize][0], gInBuffer_single, gOutBuffer_half, numVecs(count, vectorSize, aligned) ,
                                       runsOverBy(count, vectorSize, aligned)) ) )
                {
                    gFailCount++;
                    goto exit;
                }

                if( (error = clFinish(gQueue)) )
                {
                    vlog_error( "Failure in clFinish\n" );
                    gFailCount++;
                    goto exit;
                }
                uint64_t currentTime = ReadTime() - startTime;
                if( currentTime < bestTime )
                    bestTime = currentTime;
                time[ vectorSize ] += currentTime;
            }
            if( bestTime < min_time[ vectorSize ] )
                min_time[ vectorSize ] = bestTime ;

            if( gTestDouble )
            {
                bestTime = -1ULL;
                for( j = 0; j < loopCount; j++ )
                {
                    uint64_t startTime = ReadTime();
                    if( (error = RunKernel(device, doubleKernels[vectorSize][0], gInBuffer_double, gOutBuffer_half, numVecs(count, vectorSize, aligned) ,
                                           runsOverBy(count, vectorSize, aligned)) ) )
                    {
                        gFailCount++;
                        goto exit;
                    }

                    if( (error = clFinish(gQueue)) )
                    {
                        vlog_error( "Failure in clFinish\n" );
                        gFailCount++;
                        goto exit;
                    }
                    uint64_t currentTime = ReadTime() - startTime;
                    if( currentTime < bestTime )
                        bestTime = currentTime;
                    doubleTime[ vectorSize ] += currentTime;
                }
                if( bestTime < min_double_time[ vectorSize ] )
                    min_double_time[ vectorSize ] = bestTime;
            }
        }
    }

    if( gReportTimes )
    {
        for( vectorSize = minVectorSize; vectorSize < kLastVectorSizeToTest; vectorSize++)
            vlog_perf( SubtractTime( time[ vectorSize ], 0 ) * 1e6 * gDeviceFrequency * gComputeDevices / (double) (count * loopCount), 0,
                      "average us/elem", "vStoreaHalf%s avg. (%s vector size: %d)", roundName, addressSpaceNames[0], (g_arrVecSizes[vectorSize]) );
        for( vectorSize = minVectorSize; vectorSize < kLastVectorSizeToTest; vectorSize++)
            vlog_perf( SubtractTime( min_time[ vectorSize ], 0 ) * 1e6 * gDeviceFrequency * gComputeDevices / (double) count, 0,
                      "best us/elem", "vStoreaHalf%s best (%s vector size: %d)", roundName, addressSpaceNames[0], (g_arrVecSizes[vectorSize])  );
        if( gTestDouble )
        {
            for( vectorSize = minVectorSize; vectorSize < kLastVectorSizeToTest; vectorSize++)
                vlog_perf( SubtractTime( doubleTime[ vectorSize ], 0 ) * 1e6 * gDeviceFrequency * gComputeDevices / (double) (count * loopCount), 0,
                          "average us/elem (double)", "vStoreaHalf%s avg. d (%s vector size: %d)", roundName, addressSpaceNames[0], (g_arrVecSizes[vectorSize])  );
            for( vectorSize = minVectorSize; vectorSize < kLastVectorSizeToTest; vectorSize++)
                vlog_perf( SubtractTime( min_double_time[ vectorSize ], 0 ) * 1e6 * gDeviceFrequency * gComputeDevices / (double) count, 0,
                          "best us/elem (double)", "vStoreaHalf%s best d (%s vector size: %d)", roundName, addressSpaceNames[0], (g_arrVecSizes[vectorSize]) );
        }
    }

exit:
    //clean up
    for( vectorSize = minVectorSize; vectorSize < kLastVectorSizeToTest; vectorSize++)
    {
        for ( addressSpace = 0; addressSpace < 3; addressSpace++) {
            clReleaseKernel( kernels[ vectorSize ][addressSpace] );
            clReleaseProgram( programs[ vectorSize ][addressSpace] );
            if( gTestDouble )
            {
                clReleaseKernel( doubleKernels[ vectorSize ][addressSpace] );
                clReleaseProgram( doublePrograms[ vectorSize ][addressSpace] );
            }
        }
    }

    return error;
}


text:
<?php

namespace Oro\Bundle\EntityExtendBundle\Tests\Unit\Migration;

use Oro\Bundle\EntityExtendBundle\EntityConfig\ExtendScope;
use Oro\Bundle\EntityExtendBundle\Migration\RefreshExtendCacheMigrationQuery;
use Oro\Bundle\EntityExtendBundle\Migration\RefreshExtendConfigMigrationQuery;
use Oro\Bundle\EntityExtendBundle\Migration\UpdateExtendConfigMigration;
use Oro\Bundle\EntityExtendBundle\Migration\UpdateExtendConfigMigrationQuery;

class UpdateExtendConfigMigrationTest extends \PHPUnit\Framework\TestCase
{
    public function testUp()
    {
        $extendOptions = ['test'];

        $initialState = ['entities' => ['Test\Entity' => ExtendScope::STATE_UPDATE]];

        $optionsPath = realpath(__DIR__ . '/../Fixtures') . '/test_options.yml';
        $initialStatePath = realpath(__DIR__ . '/../Fixtures') . '/initial_state.yml';
        $commandExecutor = $this->getMockBuilder('Oro\Bundle\EntityConfigBundle\Tools\CommandExecutor')
            ->disableOriginalConstructor()
            ->getMock();

        $migration = new UpdateExtendConfigMigration(
            $commandExecutor,
            $optionsPath,
            $initialStatePath
        );

        $schema = $this->getMockBuilder('Oro\Bundle\EntityExtendBundle\Migration\Schema\ExtendSchema')
            ->disableOriginalConstructor()
            ->getMock();
        $queries = $this->getMockBuilder('Oro\Bundle\MigrationBundle\Migration\QueryBag')
            ->disableOriginalConstructor()
            ->getMock();

        $dataStorageExtension = $this
            ->getMockBuilder('Oro\Bundle\MigrationBundle\Migration\Extension\DataStorageExtension')
            ->disableOriginalConstructor()
            ->getMock();
        $dataStorageExtension->expects($this->once())
            ->method('get')
            ->with('initial_entity_config_state', [])
            ->willReturn($initialState);
        $migration->setDataStorageExtension($dataStorageExtension);

        $schema->expects($this->once())
            ->method('getExtendOptions')
            ->will($this->returnValue($extendOptions));

        $queries->expects($this->at(0))
            ->method('addQuery')
            ->with(
                new UpdateExtendConfigMigrationQuery(
                    $extendOptions,
                    $commandExecutor,
                    $optionsPath
                )
            );
        $queries->expects($this->at(1))
            ->method('addQuery')
            ->with(
                new RefreshExtendConfigMigrationQuery(
                    $commandExecutor,
                    $initialState,
                    $initialStatePath
                )
            );
        $queries->expects($this->at(2))
            ->method('addQuery')
            ->with(
                new RefreshExtendCacheMigrationQuery(
                    $commandExecutor
                )
            );

        $migration->up($schema, $queries);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package package_deleter

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"

	aptly_model "github.com/seibert-media/aptly-utils/model"
	http_requestbuilder "github.com/bborbe/http/requestbuilder"
	aptly_version "github.com/bborbe/version"
	"github.com/golang/glog"
)

type ExecuteRequest func(req *http.Request) (resp *http.Response, err error)

type NewHTTPRequestBuilder func(url string) http_requestbuilder.HttpRequestBuilder

type PublishRepo func(api aptly_model.API, repository aptly_model.Repository, distribution aptly_model.Distribution) error

type PackageDeleter interface {
	DeletePackageByNameAndVersion(api aptly_model.API, repository aptly_model.Repository, distribution aptly_model.Distribution, name aptly_model.Package, version aptly_version.Version) error
	DeletePackagesByKey(api aptly_model.API, repository aptly_model.Repository, distribution aptly_model.Distribution, keys []aptly_model.Key) error
}

type packageDeleter struct {
	executeRequest        ExecuteRequest
	newHTTPRequestBuilder NewHTTPRequestBuilder
	publishRepo           PublishRepo
}

func New(executeRequest ExecuteRequest, newHTTPRequestBuilder NewHTTPRequestBuilder, publishRepo PublishRepo) *packageDeleter {
	p := new(packageDeleter)
	p.executeRequest = executeRequest
	p.newHTTPRequestBuilder = newHTTPRequestBuilder
	p.publishRepo = publishRepo
	return p
}

type JSONStruct []map[string]string

func (p *packageDeleter) DeletePackageByNameAndVersion(api aptly_model.API, repository aptly_model.Repository, distribution aptly_model.Distribution, name aptly_model.Package, version aptly_version.Version) error {
	keys, err := p.findKeys(api, repository, name, version)
	if err != nil {
		return err
	}
	if len(keys) == 0 {
		return fmt.Errorf("no package found")
	}
	return p.DeletePackagesByKey(api, repository, distribution, keys)
}

func (p *packageDeleter) DeletePackagesByKey(api aptly_model.API, repository aptly_model.Repository, distribution aptly_model.Distribution, keys []aptly_model.Key) error {
	if err := p.deletePackagesByKey(api, repository, keys); err != nil {
		return err
	}
	return p.publishRepo(api, repository, distribution)
}

func (p *packageDeleter) findKeys(api aptly_model.API, repository aptly_model.Repository, packageName aptly_model.Package, version aptly_version.Version) ([]aptly_model.Key, error) {
	glog.V(2).Infof("PackageVersions - repo: %s package: %s", repository, packageName)
	url := fmt.Sprintf("%s/api/repos/%s/packages?format=details", api.APIUrl, repository)
	requestbuilder := p.newHTTPRequestBuilder(url)
	requestbuilder.AddBasicAuth(string(api.APIUsername), string(api.APIPassword))
	requestbuilder.SetMethod("GET")
	requestbuilder.AddContentType("application/json")
	req, err := requestbuilder.Build()
	if err != nil {
		return nil, err
	}
	resp, err := p.executeRequest(req)
	if err != nil {
		return nil, err
	}
	content, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	if resp.StatusCode/100 != 2 {
		return nil, fmt.Errorf("request to %s failed with status %d", url, resp.StatusCode)
	}

	var jsonStruct JSONStruct
	err = json.Unmarshal(content, &jsonStruct)
	if err != nil {
		return nil, err
	}
	var keys []aptly_model.Key
	for _, info := range jsonStruct {
		if info["Package"] == string(packageName) && info["Version"] == string(version) {
			key := info["Key"]
			glog.V(2).Infof("found key: %s", key)
			keys = append(keys, aptly_model.Key(key))
		}
	}
	return keys, nil
}

func (p *packageDeleter) deletePackagesByKey(api aptly_model.API, repository aptly_model.Repository, keys []aptly_model.Key) error {
	glog.V(2).Infof("delete package with keys: %v", keys)
	url := fmt.Sprintf("%s/api/repos/%s/packages?format=details", api.APIUrl, repository)
	requestbuilder := p.newHTTPRequestBuilder(url)
	requestbuilder.AddBasicAuth(string(api.APIUsername), string(api.APIPassword))
	requestbuilder.SetMethod("DELETE")
	requestbuilder.AddContentType("application/json")
	requestContent, err := json.Marshal(map[string][]aptly_model.Key{"PackageRefs": keys})
	if err != nil {
		return err
	}
	requestbuilder.SetBody(bytes.NewBuffer(requestContent))
	req, err := requestbuilder.Build()
	if err != nil {
		return err
	}
	resp, err := p.executeRequest(req)
	if err != nil {
		return err
	}
	if resp.StatusCode/100 != 2 {
		return fmt.Errorf("request to %s failed with status %d", url, resp.StatusCode)
	}
	return nil
}


text:
package org.kie.workbench.common.stunner.bpmn.backend.converters.tostunner.events;

import java.util.List;

import org.eclipse.bpmn2.BoundaryEvent;
import org.eclipse.bpmn2.CatchEvent;
import org.eclipse.bpmn2.CompensateEventDefinition;
import org.eclipse.bpmn2.ConditionalEventDefinition;
import org.eclipse.bpmn2.ErrorEventDefinition;
import org.eclipse.bpmn2.EscalationEventDefinition;
import org.eclipse.bpmn2.EventDefinition;
import org.eclipse.bpmn2.IntermediateCatchEvent;
import org.eclipse.bpmn2.MessageEventDefinition;
import org.eclipse.bpmn2.SignalEventDefinition;
import org.eclipse.bpmn2.TimerEventDefinition;
import org.kie.workbench.common.stunner.bpmn.backend.converters.Match;
import org.kie.workbench.common.stunner.bpmn.backend.converters.TypedFactoryManager;
import org.kie.workbench.common.stunner.bpmn.backend.converters.tostunner.BpmnNode;
import org.kie.workbench.common.stunner.bpmn.backend.converters.tostunner.properties.CatchEventPropertyReader;
import org.kie.workbench.common.stunner.bpmn.backend.converters.tostunner.properties.EventDefinitionReader;
import org.kie.workbench.common.stunner.bpmn.backend.converters.tostunner.properties.PropertyReaderFactory;
import org.kie.workbench.common.stunner.bpmn.definition.IntermediateCompensationEvent;
import org.kie.workbench.common.stunner.bpmn.definition.IntermediateConditionalEvent;
import org.kie.workbench.common.stunner.bpmn.definition.IntermediateErrorEventCatching;
import org.kie.workbench.common.stunner.bpmn.definition.IntermediateEscalationEvent;
import org.kie.workbench.common.stunner.bpmn.definition.IntermediateMessageEventCatching;
import org.kie.workbench.common.stunner.bpmn.definition.IntermediateSignalEventCatching;
import org.kie.workbench.common.stunner.bpmn.definition.IntermediateTimerEvent;
import org.kie.workbench.common.stunner.bpmn.definition.property.dataio.DataIOSet;
import org.kie.workbench.common.stunner.bpmn.definition.property.event.CancelActivity;
import org.kie.workbench.common.stunner.bpmn.definition.property.event.conditional.CancellingConditionalEventExecutionSet;
import org.kie.workbench.common.stunner.bpmn.definition.property.event.error.CancellingErrorEventExecutionSet;
import org.kie.workbench.common.stunner.bpmn.definition.property.event.error.ErrorRef;
import org.kie.workbench.common.stunner.bpmn.definition.property.event.escalation.CancellingEscalationEventExecutionSet;
import org.kie.workbench.common.stunner.bpmn.definition.property.event.escalation.EscalationRef;
import org.kie.workbench.common.stunner.bpmn.definition.property.event.message.CancellingMessageEventExecutionSet;
import org.kie.workbench.common.stunner.bpmn.definition.property.event.message.MessageRef;
import org.kie.workbench.common.stunner.bpmn.definition.property.event.signal.CancellingSignalEventExecutionSet;
import org.kie.workbench.common.stunner.bpmn.definition.property.event.signal.SignalRef;
import org.kie.workbench.common.stunner.bpmn.definition.property.event.timer.CancellingTimerEventExecutionSet;
import org.kie.workbench.common.stunner.bpmn.definition.property.event.timer.TimerSettings;
import org.kie.workbench.common.stunner.bpmn.definition.property.general.BPMNGeneralSet;
import org.kie.workbench.common.stunner.bpmn.definition.property.general.Documentation;
import org.kie.workbench.common.stunner.bpmn.definition.property.general.Name;
import org.kie.workbench.common.stunner.core.graph.Edge;
import org.kie.workbench.common.stunner.core.graph.Node;
import org.kie.workbench.common.stunner.core.graph.content.view.View;

public class IntermediateCatchEventConverter {

    private final TypedFactoryManager factoryManager;
    private final PropertyReaderFactory propertyReaderFactory;

    public IntermediateCatchEventConverter(TypedFactoryManager factoryManager, PropertyReaderFactory propertyReaderFactory) {
        this.factoryManager = factoryManager;
        this.propertyReaderFactory = propertyReaderFactory;
    }

    public BpmnNode convertIntermediateCatchEvent(IntermediateCatchEvent event) {
        CatchEventPropertyReader p = propertyReaderFactory.of(event);
        List<EventDefinition> eventDefinitions = p.getEventDefinitions();
        switch (eventDefinitions.size()) {
            case 0:
                throw new UnsupportedOperationException("An intermediate catch event should contain exactly one definition");
            case 1:
                return Match.of(EventDefinition.class, BpmnNode.class)
                        .when(TimerEventDefinition.class, e -> timerEvent(event, e))
                        .when(SignalEventDefinition.class, e -> signalEvent(event, e))
                        .when(MessageEventDefinition.class, e -> messageEvent(event, e))
                        .when(ErrorEventDefinition.class, e -> errorEvent(event, e))
                        .when(ConditionalEventDefinition.class, e -> conditionalEvent(event, e))
                        .when(EscalationEventDefinition.class, e -> escalationEvent(event, e))
                        .when(CompensateEventDefinition.class, e -> compensationEvent(event, e))
                        .apply(eventDefinitions.get(0)).value();
            default:
                throw new UnsupportedOperationException("Multiple definitions not supported for intermediate catch event");
        }
    }

    public BpmnNode convertBoundaryEvent(BoundaryEvent event) {
        CatchEventPropertyReader p = propertyReaderFactory.of(event);
        List<EventDefinition> eventDefinitions = p.getEventDefinitions();
        switch (eventDefinitions.size()) {
            case 0:
                throw new UnsupportedOperationException("A boundary event should contain exactly one definition");
            case 1:
                return Match.of(EventDefinition.class, BpmnNode.class)
                        .when(SignalEventDefinition.class, e -> signalEvent(event, e))
                        .when(TimerEventDefinition.class, e -> timerEvent(event, e))
                        .when(MessageEventDefinition.class, e -> messageEvent(event, e))
                        .when(ErrorEventDefinition.class, e -> errorEvent(event, e))
                        .when(ConditionalEventDefinition.class, e -> conditionalEvent(event, e))
                        .when(EscalationEventDefinition.class, e -> escalationEvent(event, e))
                        .when(CompensateEventDefinition.class, e -> compensationEvent(event, e))
                        .apply(eventDefinitions.get(0)).value()
                        .docked();
            default:
                throw new UnsupportedOperationException("Multiple definitions not supported for boundary event");
        }
    }

    private BpmnNode errorEvent(CatchEvent event, ErrorEventDefinition e) {
        String nodeId = event.getId();
        Node<View<IntermediateErrorEventCatching>, Edge> node = factoryManager.newNode(nodeId, IntermediateErrorEventCatching.class);

        IntermediateErrorEventCatching definition = node.getContent().getDefinition();
        CatchEventPropertyReader p = propertyReaderFactory.of(event);

        definition.setGeneral(new BPMNGeneralSet(
                new Name(p.getName()),
                new Documentation(p.getDocumentation())
        ));

        definition.setDataIOSet(
                new DataIOSet(
                        p.getAssignmentsInfo()));

        definition.setExecutionSet(new CancellingErrorEventExecutionSet(
                new CancelActivity(p.isCancelActivity()),
                new ErrorRef(EventDefinitionReader.errorRefOf(e))
        ));

        node.getContent().setBounds(p.getBounds());

        definition.setDimensionsSet(p.getCircleDimensionSet());
        definition.setFontSet(p.getFontSet());
        definition.setBackgroundSet(p.getBackgroundSet());

        return BpmnNode.of(node);
    }

    private BpmnNode signalEvent(CatchEvent event, SignalEventDefinition e) {
        String nodeId = event.getId();
        Node<View<IntermediateSignalEventCatching>, Edge> node = factoryManager.newNode(nodeId, IntermediateSignalEventCatching.class);

        IntermediateSignalEventCatching definition = node.getContent().getDefinition();
        CatchEventPropertyReader p = propertyReaderFactory.of(event);

        definition.setGeneral(new BPMNGeneralSet(
                new Name(p.getName()),
                new Documentation(p.getDocumentation())
        ));

        definition.setDataIOSet(new DataIOSet(
                p.getAssignmentsInfo()
        ));

        definition.setExecutionSet(new CancellingSignalEventExecutionSet(
                new CancelActivity(p.isCancelActivity()),
                new SignalRef(p.getSignalRef())
        ));

        node.getContent().setBounds(p.getBounds());

        definition.setDimensionsSet(p.getCircleDimensionSet());
        definition.setFontSet(p.getFontSet());
        definition.setBackgroundSet(p.getBackgroundSet());

        return BpmnNode.of(node);
    }

    private BpmnNode timerEvent(CatchEvent event, TimerEventDefinition e) {
        String nodeId = event.getId();
        Node<View<IntermediateTimerEvent>, Edge> node = factoryManager.newNode(nodeId, IntermediateTimerEvent.class);

        IntermediateTimerEvent definition = node.getContent().getDefinition();
        CatchEventPropertyReader p = propertyReaderFactory.of(event);

        definition.setGeneral(new BPMNGeneralSet(
                new Name(p.getName()),
                new Documentation(p.getDocumentation())
        ));

        definition.setExecutionSet(new CancellingTimerEventExecutionSet(
                new CancelActivity(p.isCancelActivity()),
                new TimerSettings(p.getTimerSettings(e))
        ));

        node.getContent().setBounds(p.getBounds());

        definition.setDimensionsSet(p.getCircleDimensionSet());
        definition.setFontSet(p.getFontSet());
        definition.setBackgroundSet(p.getBackgroundSet());

        return BpmnNode.of(node);
    }

    private BpmnNode messageEvent(CatchEvent event, MessageEventDefinition e) {
        String nodeId = event.getId();
        Node<View<IntermediateMessageEventCatching>, Edge> node = factoryManager.newNode(nodeId, IntermediateMessageEventCatching.class);

        IntermediateMessageEventCatching definition = node.getContent().getDefinition();
        CatchEventPropertyReader p = propertyReaderFactory.of(event);

        definition.setGeneral(new BPMNGeneralSet(
                new Name(p.getName()),
                new Documentation(p.getDocumentation())
        ));

        definition.setDataIOSet(new DataIOSet(
                p.getAssignmentsInfo()
        ));

        definition.setExecutionSet(new CancellingMessageEventExecutionSet(
                new CancelActivity(p.isCancelActivity()),
                new MessageRef(EventDefinitionReader.messageRefOf(e))
        ));

        node.getContent().setBounds(p.getBounds());

        definition.setDimensionsSet(p.getCircleDimensionSet());
        definition.setFontSet(p.getFontSet());
        definition.setBackgroundSet(p.getBackgroundSet());

        return BpmnNode.of(node);
    }

    private BpmnNode conditionalEvent(CatchEvent event, ConditionalEventDefinition e) {
        String nodeId = event.getId();
        Node<View<IntermediateConditionalEvent>, Edge> node = factoryManager.newNode(nodeId, IntermediateConditionalEvent.class);

        IntermediateConditionalEvent definition = node.getContent().getDefinition();
        CatchEventPropertyReader p = propertyReaderFactory.of(event);

        definition.setGeneral(new BPMNGeneralSet(
                new Name(p.getName()),
                new Documentation(p.getDocumentation())
        ));

        definition.setExecutionSet(new CancellingConditionalEventExecutionSet(
                new CancelActivity(p.isCancelActivity()),
                p.getConditionExpression(e)
        ));

        node.getContent().setBounds(p.getBounds());

        definition.setDimensionsSet(p.getCircleDimensionSet());
        definition.setFontSet(p.getFontSet());
        definition.setBackgroundSet(p.getBackgroundSet());

        return BpmnNode.of(node);
    }

    private BpmnNode escalationEvent(CatchEvent event,
                                     EscalationEventDefinition e) {
        String nodeId = event.getId();
        Node<View<IntermediateEscalationEvent>, Edge> node = factoryManager.newNode(nodeId,
                                                                                IntermediateEscalationEvent.class);

        IntermediateEscalationEvent definition = node.getContent().getDefinition();
        CatchEventPropertyReader p = propertyReaderFactory.of(event);

        definition.setGeneral(new BPMNGeneralSet(
                new Name(p.getName()),
                new Documentation(p.getDocumentation())
        ));

        definition.setDataIOSet(
                new DataIOSet(p.getAssignmentsInfo()));

        definition.setExecutionSet(new CancellingEscalationEventExecutionSet(
                new CancelActivity(p.isCancelActivity()),
                new EscalationRef(EventDefinitionReader.escalationRefOf(e))
        ));

        node.getContent().setBounds(p.getBounds());

        definition.setDimensionsSet(p.getCircleDimensionSet());
        definition.setFontSet(p.getFontSet());
        definition.setBackgroundSet(p.getBackgroundSet());

        return BpmnNode.of(node);
    }

    private BpmnNode compensationEvent(CatchEvent event,
                                       CompensateEventDefinition e) {
        String nodeId = event.getId();
        Node<View<IntermediateCompensationEvent>, Edge> node = factoryManager.newNode(nodeId,
                                                                                IntermediateCompensationEvent.class);

        IntermediateCompensationEvent definition = node.getContent().getDefinition();
        CatchEventPropertyReader p = propertyReaderFactory.of(event);

        definition.setGeneral(new BPMNGeneralSet(
                new Name(p.getName()),
                new Documentation(p.getDocumentation())
        ));

        node.getContent().setBounds(p.getBounds());

        definition.setDimensionsSet(p.getCircleDimensionSet());
        definition.setFontSet(p.getFontSet());
        definition.setBackgroundSet(p.getBackgroundSet());

        return BpmnNode.of(node);
    }

}


text:
package org.apache.flink.graph.pregel;

import org.apache.flink.api.common.aggregators.Aggregator;
import org.apache.flink.api.common.functions.IterationRuntimeContext;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.graph.Edge;
import org.apache.flink.graph.Vertex;
import org.apache.flink.types.Either;
import org.apache.flink.types.Value;
import org.apache.flink.util.Collector;

import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;

/**
 * The base class for the message-passing functions between vertices as a part of a {@link VertexCentricIteration}.
 *
 * @param <K> The type of the vertex key (the vertex identifier).
 * @param <VV> The type of the vertex value (the state of the vertex).
 * @param <EV> The type of the values that are associated with the edges.
 * @param <Message> The type of the message sent between vertices along the edges.
 */
public abstract class ComputeFunction<K, VV, EV, Message> implements Serializable {

	private static final long serialVersionUID = 1L;

	// --------------------------------------------------------------------------------------------
	//  Public API Methods
	// --------------------------------------------------------------------------------------------

	/**
	 * This method is invoked once per superstep, for each active vertex.
	 * A vertex is active during a superstep, if at least one message was produced for it,
	 * in the previous superstep. During the first superstep, all vertices are active.
	 *
	 *
This method can iterate over all received messages, set the new vertex value, and
	 * send messages to other vertices (which will be delivered in the next superstep).
	 *
	 * @param vertex The vertex executing this function
	 * @param messages The messages that were sent to this vertex in the previous superstep
	 * @throws Exception
	 */
	public abstract void compute(Vertex<K, VV> vertex, MessageIterator<Message> messages) throws Exception;

	/**
	 * This method is executed once per superstep before the vertex update function is invoked for each vertex.
	 *
	 * @throws Exception Exceptions in the pre-superstep phase cause the superstep to fail.
	 */
	public void preSuperstep() throws Exception {}

	/**
	 * This method is executed once per superstep after the vertex update function has been invoked for each vertex.
	 *
	 * @throws Exception Exceptions in the post-superstep phase cause the superstep to fail.
	 */
	public void postSuperstep() throws Exception {}

	/**
	 * Gets an {@link java.lang.Iterable} with all out-going edges. This method is mutually exclusive with
	 * {@link #sendMessageToAllNeighbors(Object)} and may be called only once.
	 *
	 * @return An iterator with all edges.
	 */
	public final Iterable<Edge<K, EV>> getEdges() {
		verifyEdgeUsage();
		this.edgeIterator.set(edges);
		return this.edgeIterator;
	}

	/**
	 * Sends the given message to all vertices that adjacent to the changed vertex.
	 * This method is mutually exclusive to the method {@link #getEdges()} and may be called only once.
	 *
	 * @param m The message to send.
	 */
	public final void sendMessageToAllNeighbors(Message m) {
		verifyEdgeUsage();
		outMsg.f1 = m;
		while (edges.hasNext()) {
			Tuple next = edges.next();
			outMsg.f0 = next.getField(1);
			out.collect(Either.Right(outMsg));
		}
	}

	/**
	 * Sends the given message to the vertex identified by the given key. If the target vertex does not exist,
	 * the next superstep will cause an exception due to a non-deliverable message.
	 *
	 * @param target The key (id) of the target vertex to message.
	 * @param m The message.
	 */
	public final void sendMessageTo(K target, Message m) {

		outMsg.f0 = target;
		outMsg.f1 = m;

		out.collect(Either.Right(outMsg));
	}

	/**
	 * Sets the new value of this vertex.
	 *
	 *
This should be called at most once per ComputeFunction.
	 *
	 * @param newValue The new vertex value.
	 */
	public final void setNewVertexValue(VV newValue) {
		if (setNewVertexValueCalled) {
			throw new IllegalStateException("setNewVertexValue should only be called at most once per updateVertex");
		}
		setNewVertexValueCalled = true;

		outVertex.f1 = newValue;

		out.collect(Either.Left(outVertex));
	}

	// --------------------------------------------------------------------------------------------

	/**
	 * Gets the number of the superstep, starting at <tt>1</tt>.
	 *
	 * @return The number of the current superstep.
	 */
	public final int getSuperstepNumber() {
		return this.runtimeContext.getSuperstepNumber();
	}

	/**
	 * Gets the iteration aggregator registered under the given name. The iteration aggregator combines
	 * all aggregates globally once per superstep and makes them available in the next superstep.
	 *
	 * @param name The name of the aggregator.
	 * @return The aggregator registered under this name, or {@code null}, if no aggregator was registered.
	 */
	public final <T extends Aggregator<?>> T getIterationAggregator(String name) {
		return this.runtimeContext.getIterationAggregator(name);
	}

	/**
	 * Get the aggregated value that an aggregator computed in the previous iteration.
	 *
	 * @param name The name of the aggregator.
	 * @return The aggregated value of the previous iteration.
	 */
	public final <T extends Value> T getPreviousIterationAggregate(String name) {
		return this.runtimeContext.getPreviousIterationAggregate(name);
	}

	/**
	 * Gets the broadcast data set registered under the given name. Broadcast data sets
	 * are available on all parallel instances of a function. They can be registered via
	 * {@link org.apache.flink.graph.pregel.VertexCentricConfiguration#addBroadcastSet(String, DataSet)}.
	 *
	 * @param name The name under which the broadcast set is registered.
	 * @return The broadcast data set.
	 */
	public final <T> Collection<T> getBroadcastSet(String name) {
		return this.runtimeContext.getBroadcastVariable(name);
	}

	// --------------------------------------------------------------------------------------------
	//  internal methods and state
	// --------------------------------------------------------------------------------------------

	private Vertex<K, VV> outVertex;

	private Tuple2<K, Message> outMsg;

	private IterationRuntimeContext runtimeContext;

	private Iterator<Edge<K, EV>> edges;

	private Collector<Either<?, ?>> out;

	private EdgesIterator<K, EV> edgeIterator;

	private boolean edgesUsed;

	private boolean setNewVertexValueCalled;

	void init(IterationRuntimeContext context) {
		this.runtimeContext = context;
		this.outVertex = new Vertex<>();
		this.outMsg = new Tuple2<>();
		this.edgeIterator = new EdgesIterator<>();
	}

	@SuppressWarnings("unchecked")
	void set(K vertexId, Iterator<Edge<K, EV>> edges,
			Collector<Either<Vertex<K, VV>, Tuple2<K, Message>>> out) {

		this.outVertex.f0 = vertexId;
		this.edges = edges;
		this.out = (Collector<Either<?, ?>>) (Collector<?>) out;
		this.edgesUsed = false;
		setNewVertexValueCalled = false;
	}

	private void verifyEdgeUsage() throws IllegalStateException {
		if (edgesUsed) {
			throw new IllegalStateException(
					"Can use either 'getEdges()' or 'sendMessageToAllNeighbors()' exactly once.");
		}
		edgesUsed = true;
	}

	private static final class EdgesIterator<K, EV>
		implements Iterator<Edge<K, EV>>, Iterable<Edge<K, EV>> {

		private Iterator<Edge<K, EV>> input;

		private Edge<K, EV> edge = new Edge<>();

		void set(Iterator<Edge<K, EV>> input) {
			this.input = input;
		}

		@Override
		public boolean hasNext() {
			return input.hasNext();
		}

		@Override
		public Edge<K, EV> next() {
			Edge<K, EV> next = input.next();
			edge.setSource(next.f0);
			edge.setTarget(next.f1);
			edge.setValue(next.f2);
			return edge;
		}

		@Override
		public void remove() {
			throw new UnsupportedOperationException();
		}

		@Override
		public Iterator<Edge<K, EV>> iterator() {
			return this;
		}
	}
}


text:
namespace Microsoft.Graph
{
    using System;
    using System.Collections.Generic;

    /// <summary>
    /// The interface IUserCreatedObjectsCollectionReferencesRequestBuilder.
    /// </summary>
    public partial interface IUserCreatedObjectsCollectionReferencesRequestBuilder
    {
        /// <summary>
        /// Builds the request.
        /// </summary>
        /// <returns>The built request.</returns>
        IUserCreatedObjectsCollectionReferencesRequest Request();

        /// <summary>
        /// Builds the request.
        /// </summary>
        /// <param name="options">The query and header options for the request.</param>
        /// <returns>The built request.</returns>
        IUserCreatedObjectsCollectionReferencesRequest Request(IEnumerable<Option> options);
    }
}


text:
<?php

namespace Zend\EventManager;

/**
 * Provides logic to easily create aggregate listeners, without worrying about
 * manually detaching events
 */
trait ListenerAggregateTrait
{
    /**
     * @var \Zend\Stdlib\CallbackHandler[]
     */
    protected $listeners = array();

    /**
     * {@inheritDoc}
     */
    public function detach(EventManagerInterface $events)
    {
        foreach ($this->listeners as $index => $callback) {
            if ($events->detach($callback)) {
                unset($this->listeners[$index]);
            }
        }
    }
}


text:
package utils;

/**
 * Created by Maxim Tarasov on 14.08.2016.
 */
public class Gravitation {

//    public static List<Double> force(double mu, List<Double> r, List<Double> r_sigma) {
//        List<Double> r_diff = VectorAlgebra.difference(r_sigma, r);
//        return VectorAlgebra.constMult(mu, VectorAlgebra.difference(
//                VectorAlgebra.constMult(Math.pow(VectorAlgebra.absoluteValue(r_diff), -2), VectorAlgebra.normalize(r_diff)),
//                VectorAlgebra.constMult(Math.pow(VectorAlgebra.absoluteValue(r_sigma), -2), VectorAlgebra.normalize(r_sigma))));
//    }

    public static double[] force(double mu, double[] r, double[] r_sigma) {
        double[] r_diff = VectorAlgebra.difference(r_sigma, r);
        return VectorAlgebra.constMult(mu, VectorAlgebra.difference(
                VectorAlgebra.constMult(Math.pow(VectorAlgebra.absoluteValue(r_diff), -2), VectorAlgebra.normalize(r_diff)),
                VectorAlgebra.constMult(Math.pow(VectorAlgebra.absoluteValue(r_sigma), -2), VectorAlgebra.normalize(r_sigma))));
    }

    public static double[] force(double mu, double r_x, double r_y, double r_z, double r_sigma_x, double r_sigma_y, double r_sigma_z) {
        double[] r = new double[]{r_x, r_y, r_z};
        double[] rSigma = new double[]{r_sigma_x, r_sigma_y, r_sigma_z};
//        ArrayList<Double> r = new ArrayList<Double>() {{
//            add(r_x);
//            add(r_y);
//            add(r_z);
//        }};
//        ArrayList<Double> r_sigma = new ArrayList<Double>() {{
//            add(r_sigma_x);
//            add(r_sigma_y);
//            add(r_sigma_z);
//        }};
//        List<Double> r_diff = VectorAlgebra.difference(r_sigma, r);
//        return VectorAlgebra.constMult(mu, VectorAlgebra.difference(VectorAlgebra.normalize(r_diff), VectorAlgebra.normalize(r_sigma)));
        return force(mu, r, rSigma);
    }
}


text:
package com.platform.interfaces;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import okhttp3.Request;
import okhttp3.Response;

public interface Middleware {

    boolean handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response);

}


text:
using System;

namespace SchoolSystem.MVP.Student.Views.EventArguments
{
    public class GetStudentMarksEventArgs : EventArgs
    {
        public string StudentName { get; set; }
    }
}


text:
package com.dianping.zebra.util;

import com.dianping.zebra.exception.ZebraConfigException;
import com.dianping.zebra.exception.ZebraException;
import com.dianping.zebra.log.Logger;
import com.dianping.zebra.log.LoggerFactory;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.ByteArrayOutputStream;
import java.io.StringReader;

public class JaxbUtils {
	private static Logger LOGGER = LoggerFactory.getLogger(JaxbUtils.class);

	public static <T> T fromXml(String xmlString, Class<T> clazz) {
		if (StringUtils.isBlank(xmlString)) {
			throw new ZebraException("xmlString won't be blank");
		}

		try {
			StringReader reader = new StringReader(xmlString);
			JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
			return (T) jaxbContext.createUnmarshaller().unmarshal(reader);
		} catch (JAXBException e) {
			LOGGER.error("convert xml to Java failed", e);
			throw new ZebraConfigException("convert xml to Java failed", e);
		}
	}

	public static <T> byte[] toXml(Class<T> clazz, T object) {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

		try {
			JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
			Marshaller marshaller = jaxbContext.createMarshaller();
			// 编码格式
			marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
			// 是否格式化生成的xml串
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			// 是否省略xml头信息
			marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);
			marshaller.marshal(object, outputStream);

			return outputStream.toByteArray();
		} catch (Exception e) {
			LOGGER.error("convert Java to xml fail!", e);
			throw new ZebraConfigException("convert xml to Java failed", e);
		}
	}
}


text:
export const SET_PREFERENCES = 'preferences/set';

export function setPreferences(preferences) {
  return {
    type: SET_PREFERENCES,
    preferences,
  };
}