text:
#include "naive_implementations.h"
#include <cassert>
#include <cstring>
#include <algorithm>
#include <cfloat>
#include <iostream>

//cpu_layer_merge_convolution_int16_fixedpoint_avx2_compilation.cpp #1
//cpu_layer_normalization_response_across_maps_fixedpoint.cpp
//cpu_layer_pooling_int16_fixedpoint_avx2.cpp
//cpu_layer_pooling_int16_fixedpoint_avx2_compilation.cpp
//cpu_layer_convolution_int16_fixedpoint_avx2.cpp
//cpu_layer_convolution_int16_fixedpoint_avx2_compilation.cpp
//cpu_layer_convolution_pooling_int16_fixedpoint_avx2.cpp
//cpu_layer_convolution_pooling_int16_fixedpoint_avx2_compilation.cpp
void ult_nn_merge_convolution_fixedpoint_naive_set_input_value(
    int16_t* input_ref,
    uint_least32_t input_feature_map_width,
    uint_least32_t input_feature_map_height,
    uint_least32_t input_column,
    uint_least32_t input_row,
    uint_least32_t input_map,
    int16_t value,
    uint_least32_t& offset)
{
    offset = input_column + input_row*input_feature_map_width + input_map*input_feature_map_width*input_feature_map_height;

    input_ref[offset] = value;
}

//cpu_layer_merge_convolution_int16_fixedpoint_avx2_compilation.cpp #2
//cpu_layer_convolution_int16_fixedpoint_avx2.cpp
//cpu_layer_convolution_int16_fixedpoint_avx2_compilation.cpp
//cpu_layer_convolution_pooling_int16_fixedpoint_avx2.cpp
//cpu_layer_convolution_pooling_int16_fixedpoint_avx2_compilation.cpp
void ult_nn_merge_convolution_fixedpoint_naive_set_kernel_value(
    int16_t* kernel_ref,
    uint_least32_t kernel_width,
    uint_least32_t kernel_height,
    uint_least32_t num_input_feature_maps,
    uint_least32_t kernel_column,
    uint_least32_t kernel_row,
    uint_least32_t kernel_input_map,
    uint_least32_t kernel_output_map,
    int16_t value,
    uint_least32_t& offset)
{
    offset = kernel_column + kernel_row*kernel_width + kernel_input_map*kernel_width*kernel_height + kernel_output_map*kernel_width*kernel_height*num_input_feature_maps;
    kernel_ref[offset] = value;
}

//cpu_layer_merge_convolution_int16_fixedpoint_avx2_compilation.cpp #3
void ult_nn_merge_convolution_fixedpoint_both_initialize_matrices(
    int16_t* input,
    int16_t* output,
    int32_t* biases,
    int16_t* kernel,
    int16_t* input_ref,
    int16_t* output_ref,
    int32_t* biases_ref,
    int16_t* kernel_ref,
    uint_least32_t num_output_feature_maps,
    uint_least32_t num_input_feature_maps,
    uint_least32_t output_feature_map_width,
    uint_least32_t output_feature_map_height,
    uint_least32_t input_feature_map_width,
    uint_least32_t input_feature_map_height,
    uint_least32_t kernel_width,
    uint_least32_t kernel_height,
    uint_least32_t center_x,
    uint_least32_t center_y
    )
{
    uint_least32_t input_size = input_feature_map_width * input_feature_map_height * num_input_feature_maps * sizeof(int16_t);
    int16_t * inputT = (int16_t*)_mm_malloc(input_size, 4096);
    uint_least32_t kernel_size = num_input_feature_maps * num_output_feature_maps * kernel_width * kernel_height * sizeof(int16_t);
    int16_t * weightT = (int16_t*)_mm_malloc(kernel_size, 4096);

    uint32_t IFMBlock = 8;
    if (num_input_feature_maps == 4) IFMBlock = 4;
    uint32_t OFMBlock = 32;
    uint32_t OFMpBlock = 2;
    if (num_output_feature_maps == 3072 && num_input_feature_maps == 1024)
    {
        IFMBlock = 8;
        OFMBlock = 384;
    }

    for (uint_least32_t input_map = 0; input_map < num_input_feature_maps; input_map++)
    {
        uint_least32_t element = 0;
        int16_t value = input_map * 0x0100;
        for (uint_least32_t row = 0; row < input_feature_map_height; row++)
        {
            for (uint_least32_t column = 0; column < input_feature_map_width; column++)
            {
                uint_least32_t offset;
                //ult_nn_convolution_optimized_set_input_value(inputT, input_feature_map_width, num_input_feature_maps, column, row, input_map, value, offset);
                ult_nn_merge_convolution_fixedpoint_naive_set_input_value(inputT, input_feature_map_width, input_feature_map_height, column, row, input_map, value, offset);
                ult_nn_merge_convolution_fixedpoint_naive_set_input_value(input_ref, input_feature_map_width, input_feature_map_height, column, row, input_map, value, offset);
                value++;
            }
        }
    }

    int16_t value = 0;
    for (uint_least32_t outmapa = 0; outmapa < num_output_feature_maps; outmapa++)
    {
        for (uint_least32_t input_map = 0; input_map < num_input_feature_maps; input_map++)
        {
            for (uint_least32_t row = 0; row < kernel_height; row++)
            {
                for (uint_least32_t column = 0; column < kernel_width; column++)
                {
                    uint_least32_t offset;
                    //ult_nn_convolution_optimized_set_kernel_value
                    ult_nn_merge_convolution_fixedpoint_naive_set_kernel_value(kernel, kernel_width, kernel_height, num_input_feature_maps, column, row, input_map, outmapa, value, offset);
                    ult_nn_merge_convolution_fixedpoint_naive_set_kernel_value(kernel_ref, kernel_width, kernel_height, num_input_feature_maps, column, row, input_map, outmapa, value, offset);
                    value++;
                }
            }
        }
    }

    for (uint_least32_t outmapa = 0; outmapa < num_output_feature_maps; outmapa++)
    {
        for (uint_least32_t row = 0; row < output_feature_map_height + 2 * center_y; row++)
        {
            for (uint_least32_t column = 0; column < output_feature_map_width + 2 * center_x; column++)
            {
                uint32_t index = column + row * (output_feature_map_width + 2 * center_x) + outmapa * (output_feature_map_width + 2 * center_x) * (output_feature_map_height + 2 * center_y);
                output[index] = 0;
                output_ref[index] = 0;
            }
        }
    }

    for (uint_least32_t outmapa = 0; outmapa < num_output_feature_maps; outmapa++)
    {
        biases[outmapa] = outmapa;
        biases_ref[outmapa] = outmapa;

    }

    //prepare right input layout for zxy
    for (size_t y = 0; y < input_feature_map_height; y++)
    {
        for (size_t x = 0; x < input_feature_map_width; x++)
        {
            for (size_t z = 0; z < num_input_feature_maps; z++)
            {
                input[z + x * num_input_feature_maps + y * num_input_feature_maps * input_feature_map_width]
                    = inputT[z * input_feature_map_width * input_feature_map_height + y * input_feature_map_height + x];
            }
        }
    }

    _mm_free(inputT);
    _mm_free(weightT);
}

//cpu_layer_merge_convolution_int16_fixedpoint_avx2_compilation.cpp #4
bool ult_nn_merge_convolution_fixedpoint_check_outputs(
    nn::data<int16_t, 3>* output,
    int16_t* output_ref,
    uint_least32_t num_output_feature_maps,
    uint_least32_t output_feature_map_width,
    uint_least32_t output_feature_map_height,
    uint_least32_t center_x,
    uint_least32_t center_y,
    int8_t merge_axis
    )
{
    size_t num_output_feature_maps_merge = merge_axis == 2 ? NUM_MERGED_CONVOLUTIONS * num_output_feature_maps : num_output_feature_maps;
    size_t output_feature_map_height_merge = merge_axis == 1 ? NUM_MERGED_CONVOLUTIONS * output_feature_map_height : output_feature_map_height;
    size_t output_feature_map_width_merge = merge_axis == 0 ? NUM_MERGED_CONVOLUTIONS * output_feature_map_width : output_feature_map_width;

    // zxy -> xyz
    uint_least32_t output_size = (output_feature_map_width_merge + 2 * center_x) * (output_feature_map_height_merge + 2 * center_y) * num_output_feature_maps_merge * sizeof(int16_t);
    int16_t* outputT = (int16_t*)_mm_malloc(output_size, 64);
    int16_t* outputT2 = (int16_t*)_mm_malloc(output_size, 64);
    int16_t * outputOpt = (int16_t *)output->buffer;
    uint32_t OFMOutBlock = 8;

    for (size_t y = 0; y < output_feature_map_height_merge; y++)
    {
        for (size_t x = 0; x < output_feature_map_width_merge; x++)
        {
            for (size_t z = 0; z < num_output_feature_maps_merge; z++)
            {
                outputT[z * output_feature_map_width_merge * output_feature_map_height_merge + y * output_feature_map_width_merge + x]
                    = outputOpt[z + x * num_output_feature_maps_merge + y * num_output_feature_maps_merge * output_feature_map_width_merge];
            }
        }
    }

    // xyz -> pxyznq  - TODO: replace these 2 conversions with 1
    for (uint32_t i = 0; i < num_output_feature_maps_merge / OFMOutBlock; i++)
    for (uint32_t j = 0; j < output_feature_map_width_merge * output_feature_map_height_merge; j++)
    for (uint32_t n = 0; n < OFMOutBlock; n++)
        outputT2[n + j * OFMOutBlock + i * output_feature_map_width_merge * output_feature_map_height_merge * OFMOutBlock]
        = outputT[n * output_feature_map_width_merge * output_feature_map_height_merge + j + i * output_feature_map_width_merge * output_feature_map_height_merge * OFMOutBlock];

    outputOpt = outputT2;

    bool passed = true;
    int32_t count = 0;
    int16_t *comparePtr;
    if (merge_axis == 0)
        comparePtr = outputOpt + output_feature_map_width * OFMOutBlock;
    if (merge_axis == 1)
        comparePtr = outputOpt + output_feature_map_height * output_feature_map_width * OFMOutBlock;
    if (merge_axis == 2)
        comparePtr = outputOpt + num_output_feature_maps * output_feature_map_height * output_feature_map_width;

    for (uint32_t z = 0; z < num_output_feature_maps / OFMOutBlock; z++)
    {
        for (uint32_t y = 0; y < (output_feature_map_height + 2 * center_y); y++)
        {
            for (uint32_t x = 0; x < (output_feature_map_width + 2 * center_x); x++)
            {
                for (uint32_t n = 0; n < OFMOutBlock; n++)
                {
                    if (comparePtr[n + x * OFMOutBlock] != outputOpt[n + x * OFMOutBlock])
                        passed = false;
                }
            }

            if (merge_axis == 0)
            {
                outputOpt += output_feature_map_width * OFMOutBlock * NUM_MERGED_CONVOLUTIONS;
                comparePtr += output_feature_map_width * OFMOutBlock * NUM_MERGED_CONVOLUTIONS;
            }
        }

        if (merge_axis == 1)
        {
            outputOpt += output_feature_map_height * output_feature_map_width * OFMOutBlock * NUM_MERGED_CONVOLUTIONS;
            comparePtr += output_feature_map_height * output_feature_map_width * OFMOutBlock * NUM_MERGED_CONVOLUTIONS;
        }
    }

    _mm_free(outputT);
    _mm_free(outputT2);

    return passed;
}

//cpu_layer_merge_convolution_int16_fixedpoint_avx2_compilation.cpp #5
void ult_nn_convolve_fp_naive(
    int16_t* input_ref,
    int16_t* output_ref,
    int32_t* biases_ref,
    int16_t* kernel_ref,
    uint_least32_t num_output_feature_maps,
    uint_least32_t num_input_feature_maps,
    uint_least32_t output_feature_map_width,
    uint_least32_t output_feature_map_height,
    uint_least32_t input_feature_map_width,
    uint_least32_t input_feature_map_height,
    uint_least32_t kernel_width,
    uint_least32_t kernel_height,
    uint_least32_t kernel_stride_x,
    uint_least32_t kernel_stride_y,
    uint8_t accumulator_fraction,
    uint8_t output_fraction,
    uint_least32_t center_x,
    uint_least32_t center_y,
    NN_ACTIVATION_FUNCTION activation)
{
    bool BiasEn = 1;

    int32_t * output_ref_temp = (int32_t*)_mm_malloc((output_feature_map_width + 2 * center_x) * (output_feature_map_height + 2 * center_y) * num_output_feature_maps * sizeof(int32_t), 64);
    memset(output_ref_temp, 0, (output_feature_map_width + 2 * center_x) * (output_feature_map_height + 2 * center_y) * num_output_feature_maps * sizeof(int32_t));

    for (unsigned int ofmItr = 0; ofmItr < num_output_feature_maps; ofmItr++)
    { // For each output feature map
        for (unsigned int ifmItr = 0; ifmItr < num_input_feature_maps; ifmItr++)
        { // Go over all input feature maps

            for (unsigned int hItr = 0; hItr < (input_feature_map_height - kernel_height + 1); hItr += kernel_stride_y)
            { // For each input feature map, go over all locations where the kernel-sized stencil would fit - in both dimensions, y...
                for (unsigned int wItr = 0; wItr < (input_feature_map_width - kernel_width + 1); wItr += kernel_stride_x)
                { // and x...
                    for (unsigned int kH = 0; kH < kernel_height; kH++)
                    {
                        for (unsigned int kW = 0; kW < kernel_width; kW++)
                        { // For each stencil placement, compute 2D convolution at the placement
                            short kernel_pixel = kernel_ref[ofmItr * num_input_feature_maps * kernel_height * kernel_width + ifmItr * kernel_width * kernel_height + kernel_width*kH + kW];
                            short ifm_pixel = input_ref[(ifmItr * input_feature_map_width * input_feature_map_height + (input_feature_map_width*hItr + wItr) + kH*input_feature_map_width + kW)];
                            output_ref_temp[
                                (ofmItr * (output_feature_map_width + 2 * center_x) * (output_feature_map_height + 2 * center_y)
                                    + (center_y + hItr / kernel_stride_y) * (output_feature_map_width + 2 * center_x)
                                    + (center_x + wItr / kernel_stride_x))]
                                    += ifm_pixel*kernel_pixel;
                        }
                    }
                    // Also add bias, but only once for each output feature map - when going over input feature map 0
                    output_ref_temp[(ofmItr * (output_feature_map_width + 2 * center_x) * (output_feature_map_height + 2 * center_y)
                        + (center_y + hItr / kernel_stride_y) * (output_feature_map_width + 2 * center_x)
                        + (center_x + wItr / kernel_stride_x))]
                        += (((ifmItr == 0) && BiasEn) ? 1 : 0) * biases_ref[ofmItr];
                }
            }
        }
    }

    const auto acc_shift = accumulator_fraction - output_fraction;

    for (uint32_t ofmItr = 0; ofmItr < num_output_feature_maps; ++ofmItr)
    { // For each output feature map
        for (uint32_t hItr = 0; hItr < (output_feature_map_height + 2 * center_y); ++hItr)
        {
            for (uint32_t wItr = 0; wItr < (output_feature_map_width + 2 * center_x); ++wItr)
            {
                auto indx = wItr + hItr * (output_feature_map_width + 2 * center_x) + ofmItr * (output_feature_map_width + 2 * center_x) * (output_feature_map_height + 2 * center_y);

                switch (activation)
                {
                case NN_ACTIVATION_FUNCTION_RELU:
                    output_ref_temp[indx] = std::max(0, output_ref_temp[indx]);
                    break;
                case NN_ACTIVATION_FUNCTION_NONE:
                    break;
                default:
                    break;
                }

                if (acc_shift > 0)
                {
                    output_ref_temp[indx] = output_ref_temp[indx] >> acc_shift;
                }
                else
                {
                    output_ref_temp[indx] = output_ref_temp[indx] << -acc_shift;
                }

                output_ref_temp[indx] = std::min(output_ref_temp[indx], 32767);
                output_ref_temp[indx] = std::max(output_ref_temp[indx], -32768);
                output_ref[indx] = (int16_t)(output_ref_temp[indx]);

            }
        }
    }

    _mm_free(output_ref_temp);
}

//cpu_layer_normalization.cpp
bool compare_results(nn_workload_item *&work_item, nn::data<float, 4> &output_ref) {
    for (uint32_t batch = 0; batch < output_ref.size[3]; ++batch) {
        for (uint32_t output_element_y = 0; output_element_y < output_ref.size[2]; ++output_element_y) {
            for (uint32_t output_element_x = 0; output_element_x < output_ref.size[1]; ++output_element_x) {
                for (uint32_t output_element_z = 0; output_element_z < output_ref.size[0]; ++output_element_z) {
                    float value = nn_workload_data_get<float>(
                        work_item->output[0], batch, output_element_x, output_element_y, output_element_z, 0, 0);
                    float value_ref = output_ref.at(output_element_z, output_element_x, output_element_y, batch);

                    float diff = fabs(value_ref - value);

                    if (value_ref == 0.0f || value == 0.0f || diff < FLT_MIN)
                    {
                        if (diff > FLT_MIN)
                        {
                            return false;
                        }
                    }
                    else
                    {
                        if (diff / value_ref > 5.2e-04F)
                        {
                            return false;
                        }
                    }
                }
            }
        }
    }

    return true;
}

//cpu_layer_normalization.cpp
template <class T_primitive>
bool run_naive_layer_normalization(
    float alpha, float beta, uint32_t k, uint32_t n, const nn::data<float, 4> &input, nn::data<float, 4> &output) {
    assert(0);
    return false;
}

/* data ordering is Z,X,Y,N */
template <>
bool run_naive_layer_normalization<layer::normalization_elementwise_linear_f32>(
    float alpha, float beta, uint32_t k, uint32_t n, const nn::data<float, 4> &input, nn::data<float, 4> &output) {
    float coeff_a = alpha;
    float coeff_b = beta;
    for (uint32_t batch = 0; batch < input.size[3]; ++batch)
    {
        for (uint32_t output_element_y = 0; output_element_y < input.size[2]; ++output_element_y)
        {
            for (uint32_t output_element_x = 0; output_element_x < input.size[1]; ++output_element_x)
            {
                for (uint32_t output_element_z = 0; output_element_z < input.size[0]; ++output_element_z)
                {
                    float value = input.at(output_element_z, output_element_x, output_element_y, batch);

                    value = value * coeff_a + coeff_b;

                    output.at(output_element_z, output_element_x, output_element_y, batch) = value;
                }
            }
        }
    }
    return true;
}

/* data ordering is Z,X,Y,N */
template <>
bool run_naive_layer_normalization<layer::normalization_response_across_maps_f32>(
    float alpha, float beta, uint32_t k, uint32_t n, const nn::data<float, 4> &input, nn::data<float, 4> &output) {
    float coeff_a = alpha;
    float coeff_b = beta;
    uint32_t coeff_n = n;
    uint32_t coeff_k = k;

    for (uint32_t batch = 0; batch < input.size[3]; ++batch)
    {
        for (uint32_t output_element_y = 0; output_element_y < input.size[2]; ++output_element_y)
        {
            for (uint32_t output_element_x = 0; output_element_x < input.size[1]; ++output_element_x)
            {
                for (uint32_t output_element_z = 0; output_element_z < input.size[0]; ++output_element_z)
                {
                    float acc = 0.0f;
                    float raw_input = input.at(output_element_z, output_element_x, output_element_y, batch);

                    for (int32_t input_element = (int32_t)output_element_z - (int32_t)(coeff_n / 2);
                        input_element <= (int32_t)output_element_z + (int32_t)(coeff_n / 2);
                        ++input_element) {
                        float value = 0.0f;
                        if (input_element >= 0 && input_element < input.size[0])
                            value = input.at(input_element, output_element_x, output_element_y, batch);

                        acc += value*value;
                    }

                    acc = acc * coeff_a + (int32_t)coeff_k;
                    acc = std::pow(acc, -coeff_b);

                    acc = raw_input * acc;

                    output.at(output_element_z, output_element_x, output_element_y, batch) = acc;
                }
            }
        }
    }

    return true;
}

//cpu_layer_normalization_response_across_maps_fixedpoint.cpp
void ult_nn_lrn_fp_naive(
    int16_t * input_ref,
    int16_t * output_ref,
    int32_t num_feature_maps,
    int32_t feature_map_width,
    int32_t feature_map_height,
    int32_t batch_size,
    int32_t input_fraction,
    int32_t output_fraction,
    float coeff_alpha,
    float coeff_beta,
    float coeff_k
    )
{
    const int32_t coeff_N = 5;
    float scale_in = 1.0f / (float)(1 << input_fraction);

    auto MapSizeXY = feature_map_width * feature_map_height;
    auto MapSizeXYZ = feature_map_width * feature_map_height * num_feature_maps;

    for (auto itrBatch = 0; itrBatch < batch_size; ++itrBatch)
    for (auto itrMapY = 0; itrMapY < feature_map_height; ++itrMapY)
    for (auto itrMapX = 0; itrMapX < feature_map_width; ++itrMapX)
    for (auto itrMapZ = 0; itrMapZ < num_feature_maps; ++itrMapZ)
    {
        int32_t sum = 0;
        int16_t v_int = 0;
        float v_float = 0;
        int16_t v_int0 = input_ref[itrMapX + itrMapY * feature_map_width + (itrMapZ + 0) * MapSizeXY + itrBatch * MapSizeXYZ];
        for (int32_t itrN = -coeff_N / 2; itrN < coeff_N / 2 + 1; ++itrN)
        {

            if ((itrMapZ + itrN < 0) || (itrMapZ + itrN >= num_feature_maps))
                v_int = 0;
            else
                v_int = input_ref[itrMapX + itrMapY * feature_map_width + (itrMapZ + itrN) * MapSizeXY + itrBatch * MapSizeXYZ];

            sum += v_int * v_int;
        }
        v_float = (float)sum * scale_in * scale_in;
        v_float = (v_float * coeff_alpha + coeff_k);
        v_float = pow(v_float, coeff_beta);

        v_float = (float)v_int0 * scale_in / v_float;

        auto float2int16 = [&output_fraction](float in) {
            auto scaled = in * (1 << output_fraction);
            if (scaled < INT16_MIN)
                scaled = INT16_MIN;
            if (scaled > INT16_MAX)
                scaled = INT16_MAX;
            return static_cast<std::int16_t>(round(scaled));
        };
        output_ref[itrMapX + itrMapY * feature_map_width + (itrMapZ + 0) * MapSizeXY + itrBatch * MapSizeXYZ] = float2int16(v_float);
    }
}

//cpu_layer_normalization_response_across_maps_fixedpoint_compilation.cpp
// Naive normalization_lrn
void ult_nn_lrn_fp_comp_naive(
    int16_t * input_ref,
    int16_t * output_ref,
    int32_t num_feature_maps,
    int32_t feature_map_width,
    int32_t feature_map_height,
    int32_t batch_size,
    int32_t input_fraction,
    int32_t output_fraction,
    float coeff_alpha,
    float coeff_beta,
    float coeff_k
    )
{
    const int32_t coeff_N = 5;
    float scale_in = 1.0f / (float)(1 << input_fraction);

    auto MapSizeXY = feature_map_width * feature_map_height;
    auto MapSizeXYZ = feature_map_width * feature_map_height * num_feature_maps;

    for (auto itrBatch = 0; itrBatch < batch_size; ++itrBatch)
    for (auto itrMapY = 0; itrMapY < feature_map_height; ++itrMapY)
    for (auto itrMapX = 0; itrMapX < feature_map_width; ++itrMapX)
    for (auto itrMapZ = 0; itrMapZ < num_feature_maps; ++itrMapZ)
    {
        float sum = 0;
        int16_t v_int = 0;
        float v_float = 0;
        int16_t v_int0 = input_ref[itrMapX + itrMapY * feature_map_width + (itrMapZ + 0) * MapSizeXY + itrBatch * MapSizeXYZ];
        for (int32_t itrN = -coeff_N / 2; itrN < coeff_N / 2 + 1; ++itrN)
        {

            if ((itrMapZ + itrN < 0) || (itrMapZ + itrN >= num_feature_maps))
                v_int = 0;
            else
                v_int = input_ref[itrMapX + itrMapY * feature_map_width + (itrMapZ + itrN) * MapSizeXY + itrBatch * MapSizeXYZ];

            sum += v_int * v_int;
        }
        v_float = (float)sum * scale_in * scale_in;
        v_float = (v_float * coeff_alpha + coeff_k);
        v_float = pow(v_float, coeff_beta);

        v_float = (float)v_int0 * scale_in / v_float;

        auto float2int16 = [&output_fraction](float in) {
            auto scaled = in * (1 << output_fraction);
            if (scaled < INT16_MIN)
                scaled = INT16_MIN;
            if (scaled > INT16_MAX)
                scaled = INT16_MAX;
            return static_cast<std::int16_t>(round(scaled));
        };
        output_ref[itrMapX + itrMapY * feature_map_width + (itrMapZ + 0) * MapSizeXY + itrBatch * MapSizeXYZ] = float2int16(v_float);
    }
}

//cpu_layer_pooling_avx2.cpp
void run_reference(nn::workload_data<> *input,
    nn::data<float, 4> &output,
    size_t pool_size_x,
    size_t pool_size_y,
    size_t pool_stride_x,
    size_t pool_stride_y) {
    for (uint32_t batch = 0; batch < output.size[3]; ++batch)
    {
        for (uint32_t output_element_y = 0; output_element_y < output.size[2]; ++output_element_y)
        {
            for (uint32_t output_element_x = 0; output_element_x < output.size[1]; ++output_element_x)
            {
                for (uint32_t output_element_z = 0; output_element_z < output.size[0]; ++output_element_z)
                {
                    bool first_value = true;
                    float acc = 0.0f;

                    for (uint32_t input_element_y = 0; input_element_y < pool_size_y; ++input_element_y)
                    {
                        for (uint32_t input_element_x = 0; input_element_x < pool_size_x; ++input_element_x)
                        {
                            float value = nn_workload_data_get<float>(
                                input,
                                batch,
                                output_element_x * pool_stride_x + input_element_x,
                                output_element_y * pool_stride_y + input_element_y,
                                output_element_z,
                                0,
                                0);

                            acc = (first_value) ? value : std::max(acc, value);
                            first_value = false;
                        }
                    }

                    output.at(output_element_z, output_element_x, output_element_y, batch) = acc;
                }
            }
        }
    }
}

//cpu_layer_pooling_int16_fixedpoint_avx2.cpp
/*static*/ void ult_nn_maxpooling_naive(
    int16_t* input_ref,
    int16_t* output_ref,
    uint_least32_t num_output_feature_maps,
    uint_least32_t num_input_feature_maps,
    uint_least32_t output_feature_map_width,
    uint_least32_t output_feature_map_height,
    uint_least32_t output_feature_map_width_int,
    uint_least32_t output_feature_map_height_int,
    uint_least32_t input_feature_map_width,
    uint_least32_t input_feature_map_height,
    uint_least32_t pool_width,
    uint_least32_t pool_height,
    uint_least32_t pool_stride_x,
    uint_least32_t pool_stride_y,
    uint_least32_t center_x,
    uint_least32_t center_y)
{
    uint_least32_t output_int_size = output_feature_map_width_int * output_feature_map_height_int * num_output_feature_maps * sizeof(int32_t);
    int32_t * output_int = (int32_t*)_mm_malloc(output_int_size, 64);
    memset(output_int, 0, output_int_size);
    uint_least32_t output_ref_size = (output_feature_map_width + 2 * center_x) * (output_feature_map_height + 2 * center_y) * num_output_feature_maps * sizeof(int16_t);
    memset(output_ref, 0, output_ref_size);

    for (unsigned int ofmItr = 0; ofmItr < num_output_feature_maps; ofmItr++)
    {
        for (uint32_t y = 0; y < output_feature_map_height; y++)
        {
            for (uint32_t x = 0; x < output_feature_map_width; x++)
            {
                int coord = ofmItr * output_feature_map_height_int * output_feature_map_width_int + y * pool_stride_y * output_feature_map_height_int + x * pool_stride_x;
                int32_t max_t = input_ref[coord];
                for (uint32_t maxY = 0; maxY < pool_height; maxY++)
                {
                    for (uint32_t maxX = 0; maxX < pool_width; maxX++)
                    {
                        int coord2 = ofmItr * output_feature_map_height_int * output_feature_map_width_int + (y * pool_stride_y + maxY) * output_feature_map_height_int + x * pool_stride_x + maxX;
                        int32_t next_val = input_ref[coord2];
                        max_t = std::max(max_t, next_val);
                    }
                }

                int coord3 = ofmItr * (output_feature_map_height + 2 * center_y) * (output_feature_map_width + 2 * center_x) + (y + center_y) * (output_feature_map_width + 2 * center_x) + x + center_x;
                output_ref[coord3] = max_t;
            }
        }
    }

    _mm_free(output_int);
}

//cpu_layer_softmax.cpp
void cpu_layer_softmax(
    nn_workload_item* &work_item,
    bool is_ref,
    nn_device_t *device)
{
    for (uint32_t batch = 0;
        batch < work_item->output[0]->parent->lengths.t[NN_DATA_COORD_n];
        ++batch)
    {
        {
            float max_value;
            uint32_t output_element = 0;
            max_value = nn_workload_data_get<float>(work_item->input[0].get_data_view(), batch, output_element++, 0, 0, 0, 0);
            while(output_element < work_item->output[0]->parent->lengths.t[NN_DATA_COORD_x])
                max_value = std::max(max_value, nn_workload_data_get<float>(work_item->input[0].get_data_view(), batch, output_element++, 0, 0, 0, 0));

            for(uint32_t output = 0; output < work_item->output[0]->parent->lengths.t[NN_DATA_COORD_x]; ++output)
                nn_workload_data_get<float>(work_item->output[0], batch, output, 0, 0, 0, 0) =
                    nn_workload_data_get<float>(work_item->input[0].get_data_view(), batch, output, 0, 0, 0, 0) - max_value;
        }

        float sum = 0.0f;
        for (uint32_t output_element = 0;
            output_element < work_item->output[0]->parent->lengths.t[NN_DATA_COORD_x];
            ++output_element)
        {
            float value = exp(nn_workload_data_get<float>(work_item->output[0], batch, output_element, 0, 0, 0, 0));
            sum += value;

            nn_workload_data_get<float>(work_item->output[0], batch, output_element, 0, 0, 0, 0) = value;
        }

        sum = 1.0f / sum;

        for (uint32_t output_element = 0;
            output_element < work_item->output[0]->parent->lengths.t[NN_DATA_COORD_x];
            ++output_element)
        {
            float value = nn_workload_data_get<float>(work_item->output[0], batch, output_element, 0, 0, 0, 0);
            value *= sum;

            nn_workload_data_get<float>(work_item->output[0], batch, output_element, 0, 0, 0, 0) = value;
        }

    }
}

//cpu_fully_connected_int16_avx2.cpp
static int16_t& get_input(int16_t * in, int32_t NumBatch, int32_t batch, int32_t idx)//needed for ult_nn_fc_naive to work
{
    return in[idx / 2 * NumBatch * 2 + batch * 2 + idx % 2];
}

static int32_t& get_output(int32_t * out, int32_t NumBatch, int32_t batch, int32_t idx)//needed for ult_nn_fc_naive to work
{
    return out[idx / 2 * NumBatch * 2 + batch * 2 + idx % 2];
}

static int16_t& get_weight(int16_t * weights, int32_t numInputNeurons, int32_t in, int32_t out)//needed for ult_nn_fc_naive to work
{
    return weights[out / 8 * 8 * numInputNeurons + in / 2 * 2 * 8 + (out % 8) * 2 + in % 2];
}

/*static*/ void ult_nn_fc_naive(
    int16_t* input,
    int32_t* output,
    int32_t* biases,
    int16_t* kernel,
    uint_least32_t num_input_neurons,
    uint_least32_t num_output_neurons,
    uint_least32_t batch_size,
    NN_ACTIVATION_FUNCTION activation)
{
    bool BiasEn = 1;

    for (int batchItr = 0; batchItr < batch_size; ++batchItr)
    {
        for (unsigned int outputNeuronsItr = 0; outputNeuronsItr < num_output_neurons; outputNeuronsItr++)
        {
            if (BiasEn)
                get_output(output, batch_size, batchItr, outputNeuronsItr) = biases[outputNeuronsItr];
            else
                get_output(output, batch_size, batchItr, outputNeuronsItr) = 0;

            for (unsigned int inputNeuronsItr = 0; inputNeuronsItr < num_input_neurons; inputNeuronsItr++)
            {
                get_output(output, batch_size, batchItr, outputNeuronsItr) +=
                    get_input(input, batch_size, batchItr, inputNeuronsItr) * get_weight(kernel, num_input_neurons, inputNeuronsItr, outputNeuronsItr);
            }
            switch (activation)
            {
            case NN_ACTIVATION_FUNCTION_RELU:
                get_output(output, batch_size, batchItr, outputNeuronsItr) = std::max(0, get_output(output, batch_size, batchItr, outputNeuronsItr));
                break;
            case NN_ACTIVATION_FUNCTION_NONE:
                break;
            default:
                break;
            }
        }
    }
}

//cpu_layer_convolution_avx2 #1
//cpu_layer_convolution_pooling_avx2.cpp #1
float ult_nn_convolution_naive_get_output_value(
    float* output_ref,
    uint_least32_t output_feature_map_width,
    uint_least32_t output_feature_map_height,
    uint_least32_t num_output_feature_maps,
    uint_least32_t output_column,
    uint_least32_t output_row,
    uint_least32_t output_map,
    uint_least32_t batch,
    uint_least32_t& offset)
{
    offset = batch*output_feature_map_width*output_feature_map_height*num_output_feature_maps + output_column + output_row*output_feature_map_width + output_map*output_feature_map_width*output_feature_map_height;
    return output_ref[offset];
}

//cpu_layer_convolution_avx2 #2
//cpu_layer_convolution_pooling_avx2.cpp #2
void ult_nn_convolution_naive_set_output_value(
    float* output_ref,
    uint_least32_t output_feature_map_width,
    uint_least32_t output_feature_map_height,
    uint_least32_t num_output_feature_maps,
    uint_least32_t output_column,
    uint_least32_t output_row,
    uint_least32_t output_map,
    uint_least32_t batch,
    float value,
    uint_least32_t& offset)
{
    offset = batch*output_feature_map_width*output_feature_map_height*num_output_feature_maps + output_column + output_row*output_feature_map_width + output_map*output_feature_map_width*output_feature_map_height;
    output_ref[offset] = value;
}

//cpu_layer_convolution_avx2 #3
//cpu_layer_convolution_pooling_avx2.cpp #3
void ult_nn_convolution_naive_set_input_value(
    float* input_ref,
    uint_least32_t input_feature_map_width,
    uint_least32_t input_feature_map_height,
    uint_least32_t num_input_feature_maps,
    uint_least32_t input_column,
    uint_least32_t input_row,
    uint_least32_t input_map,
    uint_least32_t batch,
    float value,
    uint_least32_t& offset)
{
    offset = batch*num_input_feature_maps*input_feature_map_width*input_feature_map_height + input_column + input_row*input_feature_map_width + input_map*input_feature_map_width*input_feature_map_height;
    input_ref[offset] = value;
}

//cpu_layer_convolution_avx2 #4
//cpu_layer_convolution_pooling_avx2.cpp #4
void ult_nn_convolution_naive_set_kernel_value(
    float* kernel_ref,
    uint_least32_t kernel_width,
    uint_least32_t kernel_height,
    uint_least32_t num_input_feature_maps,
    uint_least32_t kernel_column,
    uint_least32_t kernel_row,
    uint_least32_t kernel_input_map,
    uint_least32_t kernel_output_map,
    float value,
    uint_least32_t& offset)
{
    offset = kernel_column + kernel_row*kernel_width + kernel_input_map*kernel_width*kernel_height + kernel_output_map*kernel_width*kernel_height*num_input_feature_maps;
    kernel_ref[offset] = value;
}

//cpu_layer_convolution_avx2 #5
//cpu_layer_convolution_pooling_avx2.cpp #5
void ult_nn_convolve_naive(
    float* input_ref,
    float* output_ref,
    float* biases_ref,
    float* kernel_ref,
    uint_least32_t batch_size,
    uint_least32_t num_output_feature_maps,
    uint_least32_t num_input_feature_maps,
    uint_least32_t output_feature_map_width,
    uint_least32_t output_feature_map_height,
    uint_least32_t input_feature_map_width,
    uint_least32_t input_feature_map_height,
    uint_least32_t kernel_width,
    uint_least32_t kernel_height,
    uint_least32_t kernel_stride_x,
    uint_least32_t kernel_stride_y,
    NN_ACTIVATION_FUNCTION activation)
{
    for (uint_least32_t batch = 0; batch < batch_size; batch++)
    {
        for (uint_least32_t output_feature_map = 0; output_feature_map < num_output_feature_maps; output_feature_map += 8)
        {
            for (uint_least32_t input_row = 0, output_row = 0; output_row < output_feature_map_height; input_row += kernel_stride_y, output_row++)
            {
                for (uint_least32_t input_column = 0, output_column = 0; output_column < output_feature_map_width; input_column += kernel_stride_x, output_column++)
                {
                    const uint_least32_t out_ofss = output_feature_map_width*output_feature_map_height;
                    const uint_least32_t out_base =
                        ((batch * num_output_feature_maps + output_feature_map)
                            * output_feature_map_height + output_row)
                                * output_feature_map_width + output_column;
                    float accumulator0 = 0.0f;
                    float accumulator1 = 0.0f;
                    float accumulator2 = 0.0f;
                    float accumulator3 = 0.0f;
                    float accumulator4 = 0.0f;
                    float accumulator5 = 0.0f;
                    float accumulator6 = 0.0f;
                    float accumulator7 = 0.0f;

                    for (uint_least32_t input_feature_map = 0; input_feature_map < num_input_feature_maps; input_feature_map++)
                    {
                        for (uint_least32_t kernel_row = 0; kernel_row < kernel_height; kernel_row++)
                        {
                            const uint_least32_t kern_ofss = kernel_width*kernel_height*num_input_feature_maps;
                            uint_least32_t kern_base = kernel_row*kernel_width + input_feature_map*kernel_width*kernel_height + output_feature_map*kernel_width*kernel_height*num_input_feature_maps;

                            for (uint_least32_t kernel_column = 0; kernel_column < kernel_width; kernel_column++)
                            {
                                float weight0 = kernel_ref[kern_base + 0 * kern_ofss];
                                float weight1 = kernel_ref[kern_base + 1 * kern_ofss];
                                float weight2 = kernel_ref[kern_base + 2 * kern_ofss];
                                float weight3 = kernel_ref[kern_base + 3 * kern_ofss];
                                float weight4 = kernel_ref[kern_base + 4 * kern_ofss];
                                float weight5 = kernel_ref[kern_base + 5 * kern_ofss];
                                float weight6 = kernel_ref[kern_base + 6 * kern_ofss];
                                float weight7 = kernel_ref[kern_base + 7 * kern_ofss];

                                ++kern_base;

                                float input = input_ref[batch*num_input_feature_maps*input_feature_map_width*input_feature_map_height + kernel_column + kernel_row*input_feature_map_width + input_column + input_row*input_feature_map_width + input_feature_map*input_feature_map_width*input_feature_map_height];

                                accumulator0 += weight0 * input;
                                accumulator1 += weight1 * input;
                                accumulator2 += weight2 * input;
                                accumulator3 += weight3 * input;
                                accumulator4 += weight4 * input;
                                accumulator5 += weight5 * input;
                                accumulator6 += weight6 * input;
                                accumulator7 += weight7 * input;
                            }
                        }
                    }

                    switch (activation)
                    {
                    case NN_ACTIVATION_FUNCTION_RELU:
                        accumulator0 = std::max(0.0f, accumulator0 + biases_ref[output_feature_map + 0]);
                        accumulator1 = std::max(0.0f, accumulator1 + biases_ref[output_feature_map + 1]);
                        accumulator2 = std::max(0.0f, accumulator2 + biases_ref[output_feature_map + 2]);
                        accumulator3 = std::max(0.0f, accumulator3 + biases_ref[output_feature_map + 3]);
                        accumulator4 = std::max(0.0f, accumulator4 + biases_ref[output_feature_map + 4]);
                        accumulator5 = std::max(0.0f, accumulator5 + biases_ref[output_feature_map + 5]);
                        accumulator6 = std::max(0.0f, accumulator6 + biases_ref[output_feature_map + 6]);
                        accumulator7 = std::max(0.0f, accumulator7 + biases_ref[output_feature_map + 7]);
                        break;

                    case NN_ACTIVATION_FUNCTION_NONE:
                        accumulator0 = accumulator0 + biases_ref[output_feature_map + 0];
                        accumulator1 = accumulator1 + biases_ref[output_feature_map + 1];
                        accumulator2 = accumulator2 + biases_ref[output_feature_map + 2];
                        accumulator3 = accumulator3 + biases_ref[output_feature_map + 3];
                        accumulator4 = accumulator4 + biases_ref[output_feature_map + 4];
                        accumulator5 = accumulator5 + biases_ref[output_feature_map + 5];
                        accumulator6 = accumulator6 + biases_ref[output_feature_map + 6];
                        accumulator7 = accumulator7 + biases_ref[output_feature_map + 7];
                        break;

                    default:
                        break;
                    }

                    output_ref[out_base + 0 * out_ofss] = accumulator0;
                    output_ref[out_base + 1 * out_ofss] = accumulator1;
                    output_ref[out_base + 2 * out_ofss] = accumulator2;
                    output_ref[out_base + 3 * out_ofss] = accumulator3;
                    output_ref[out_base + 4 * out_ofss] = accumulator4;
                    output_ref[out_base + 5 * out_ofss] = accumulator5;
                    output_ref[out_base + 6 * out_ofss] = accumulator6;
                    output_ref[out_base + 7 * out_ofss] = accumulator7;
                }
            }
        }
    }
}

//cpu_layer_convolution_pooling_avx2.cpp #6
void ult_nn_maxpooling_naive_convolution_pooling(
    float* input_ref,
    float* output_ref,
    uint_least32_t batch_size,
    uint_least32_t num_output_feature_maps,
    uint_least32_t num_input_feature_maps,
    uint_least32_t output_feature_map_width,
    uint_least32_t output_feature_map_height,
    uint_least32_t input_feature_map_width,
    uint_least32_t input_feature_map_height,
    uint_least32_t pool_width,
    uint_least32_t pool_height,
    uint_least32_t pool_stride_x,
    uint_least32_t pool_stride_y,
    NN_ACTIVATION_FUNCTION activation)
{
    for (uint_least32_t batch = 0; batch < batch_size; batch++)
    {
        for (uint_least32_t output_feature_map = 0; output_feature_map < num_output_feature_maps; output_feature_map++)
        {
            for (uint_least32_t input_row = 0, output_row = 0; output_row < output_feature_map_height; input_row += pool_stride_y, output_row++)
            {
                for (uint_least32_t input_column = 0, output_column = 0; output_column < output_feature_map_width; input_column += pool_stride_x, output_column++)
                {
                    const uint_least32_t out_base = batch*output_feature_map_width*output_feature_map_height*num_output_feature_maps + output_column + output_row*output_feature_map_width + output_feature_map*output_feature_map_width*output_feature_map_height;
                    float accumulator0 = output_ref[out_base];

                    for (uint_least32_t kernel_row = 0; kernel_row < pool_height; kernel_row++)
                    {
                        for (uint_least32_t kernel_column = 0; kernel_column < pool_width; kernel_column++)
                        {
                            float input = input_ref[batch*num_output_feature_maps*input_feature_map_width*input_feature_map_height + kernel_column + kernel_row*input_feature_map_width + input_column + input_row*input_feature_map_width + output_feature_map*input_feature_map_width*input_feature_map_height];

                            accumulator0 = std::max(accumulator0, input);
                        }
                    }

                    output_ref[out_base] = accumulator0;
                }
            }
        }
    }
}

//cpu_layer_convolution_int16_fixedpoint_avx2.cpp #1
int16_t ult_nn_convolution_fp_naive_get_output_value(
    int16_t* output_ref,
    uint_least32_t output_feature_map_width,
    uint_least32_t output_feature_map_height,
    uint_least32_t num_output_feature_maps,
    uint_least32_t output_column,
    uint_least32_t output_row,
    uint_least32_t output_map,
    uint_least32_t& offset)
{
    offset = output_column + output_row*output_feature_map_width + output_map*output_feature_map_width*output_feature_map_height;
    return output_ref[offset];
}

//cpu_layer_convolution_int16_fixedpoint_avx2.cpp #2
/*static*/ void ult_nn_convolution_fp_naive_set_output_value(
    int16_t* output_ref,
    uint_least32_t output_feature_map_width,
    uint_least32_t output_feature_map_height,
    uint_least32_t num_output_feature_maps,
    uint_least32_t output_column,
    uint_least32_t output_row,
    uint_least32_t output_map,
    int16_t value,
    uint_least32_t& offset)
{
    offset = output_column + output_row*output_feature_map_width + output_map*output_feature_map_width*output_feature_map_height;
    output_ref[offset] = value;
}

//cpu_layer_convolution_pooling_int16_fixedpoint_avx2.cpp
//cpu_layer_convolution_pooling_int16_fixedpoint_avx2_compilation.cpp
void ult_nn_maxpooling_naive_pooling_int16_fixedpoint(
    int16_t* input_ref,
    int16_t* output_ref,
    int32_t* biases_ref,
    int16_t* kernel_ref,
    uint_least32_t num_output_feature_maps,
    uint_least32_t num_input_feature_maps,
    uint_least32_t output_feature_map_width,
    uint_least32_t output_feature_map_height,
    uint_least32_t output_feature_map_width_int,
    uint_least32_t output_feature_map_height_int,
    uint_least32_t input_feature_map_width,
    uint_least32_t input_feature_map_height,
    uint_least32_t kernel_width,
    uint_least32_t kernel_height,
    uint_least32_t kernel_stride_x,
    uint_least32_t kernel_stride_y,
    uint_least32_t pool_width,
    uint_least32_t pool_height,
    uint_least32_t pool_stride_x,
    uint_least32_t pool_stride_y,
    uint8_t accumulator_fraction,
    uint8_t output_fraction,
    uint_least32_t center_x,
    uint_least32_t center_y,
    NN_ACTIVATION_FUNCTION activation)
{
    bool BiasEn = 1;

    uint_least32_t output_int_size = output_feature_map_width_int * output_feature_map_height_int * num_output_feature_maps * sizeof(int32_t);
    int32_t * output_int = (int32_t*)_mm_malloc(output_int_size, 64);
    memset(output_int, 0, output_int_size);
    uint_least32_t output_ref_size = (output_feature_map_width + 2 * center_x) * (output_feature_map_height + 2 * center_y) * num_output_feature_maps * sizeof(int16_t);
    memset(output_ref, 0, output_ref_size);

    for (unsigned int ofmItr = 0; ofmItr < num_output_feature_maps; ofmItr++)
    { // For each output feature map
        for (unsigned int ifmItr = 0; ifmItr < num_input_feature_maps; ifmItr++)
        { // Go over all input feature maps
            for (unsigned int hItr = 0; hItr < (input_feature_map_height - kernel_height + 1); hItr += kernel_stride_y)
            { // For each input feature map, go over all locations where the kernel-sized stencil would fit - in both dimensions, y...
                for (unsigned int wItr = 0; wItr < (input_feature_map_width - kernel_width + 1); wItr += kernel_stride_x)
                { // and x...
                    for (unsigned int kH = 0; kH < kernel_height; kH++)
                    {
                        for (unsigned int kW = 0; kW < kernel_width; kW++)
                        { // For each stencil placement, compute 2D convolution at the placement
                            short kernel_pixel = kernel_ref[ofmItr * num_input_feature_maps * kernel_height * kernel_width + ifmItr * kernel_width * kernel_height + kernel_width*kH + kW];
                            short ifm_pixel = input_ref[(ifmItr * input_feature_map_width * input_feature_map_height + (input_feature_map_width*hItr + wItr) + kH*input_feature_map_width + kW)];
                            output_int[(ofmItr * output_feature_map_width_int * output_feature_map_height_int + (hItr / kernel_stride_y) * output_feature_map_height_int + (wItr / kernel_stride_x))] += ifm_pixel*kernel_pixel;
                        }
                    }
                    // Also add bias, but only once for each output feature map - when going over input feature map 0
                    output_int[(ofmItr * output_feature_map_width_int * output_feature_map_height_int + (hItr / kernel_stride_y) * output_feature_map_width_int + (wItr / kernel_stride_x))] += ((ifmItr == 0 && BiasEn) ? 1 : 0) * biases_ref[ofmItr];
                }
            }
        }
    }

    const auto acc_shift = accumulator_fraction - output_fraction;

    for (unsigned int ofmItr = 0; ofmItr < num_output_feature_maps; ofmItr++)
    for (uint32_t y = 0; y < output_feature_map_height; y++)
    for (uint32_t x = 0; x < output_feature_map_width; x++)
    {
        int32_t max_t = output_int[ofmItr * output_feature_map_height_int * output_feature_map_width_int + y * pool_stride_y * output_feature_map_height_int + x * pool_stride_x];
        for (uint32_t maxY = 0; maxY < pool_stride_y; maxY++)
        for (uint32_t maxX = 0; maxX < pool_stride_x; maxX++)
        {
            int32_t max_t1 = output_int[ofmItr * output_feature_map_height_int * output_feature_map_width_int + (y * pool_stride_y + maxY) * output_feature_map_height_int + x * pool_stride_x + maxX];
            max_t = std::max(max_t, max_t1);
        }

        switch (activation)
        {
        case NN_ACTIVATION_FUNCTION_RELU:
            max_t = std::max(0, max_t);
            break;
        case NN_ACTIVATION_FUNCTION_NONE:
            break;
        default:
            break;
        }

        if (acc_shift > 0)
        {
            max_t = max_t >> acc_shift;
        }
        else
        {
            max_t = max_t << -acc_shift;
        }

        max_t = std::min(max_t, 32767);
        max_t = std::max(max_t, -32768);
        output_ref[ofmItr * (output_feature_map_height + 2 * center_y) * (output_feature_map_width + 2 * center_x) + (y + center_y) * (output_feature_map_width + 2 * center_x) + x + center_x] = max_t;
    }

    _mm_free(output_int);

}

//cpu_layer_fullyconnected.cpp
void cpu_layer_fullyconnected(
    nn_workload_item* &work_item,
    NN_ACTIVATION_FUNCTION activation_function)
    {
    auto &arguments = work_item->parameters;
    for (uint32_t batch = 0;
        batch < work_item->output[0]->parent->lengths.t[NN_DATA_COORD_n];
        ++batch)
    {
        for (uint32_t output_element = 0;
            output_element < work_item->output[0]->parent->lengths.t[NN_DATA_COORD_x];
            ++output_element)
        {
            float accumulator = 0.0f;
            for (uint32_t input_element = 0;
                input_element < work_item->input[0].get_data_view()->parent->lengths.t[NN_DATA_COORD_x];
                ++input_element)
            {
                accumulator +=
                    nn_workload_data_get<float>(work_item->input[0].get_data_view(), batch, input_element, 0, 0, 0, 0) *
                    nn_workload_data_get<float>(arguments[0], 0, input_element, output_element, 0, 0, 0);
            }

            accumulator += nn_workload_data_get<float>(arguments[1], 0, output_element, 0, 0, 0, 0);

            if (activation_function == NN_ACTIVATION_FUNCTION_RELU)
            {
                accumulator = std::max(0.0f, accumulator);
            }

            nn_workload_data_get<float>(work_item->output[0], batch, output_element, 0, 0, 0, 0) = accumulator;
        }
    }
}

namespace
{

void calculateSingleOutputFeature(
    float* in_ref,
    float* out_ref,
    float* kernel_ref,
    float bias,
    uint64_t num_input_features,
    uint64_t out_width,
    uint64_t out_height,
    uint64_t in_width,
    uint64_t in_height,
    uint64_t kernel_width,
    uint64_t kernel_height,
    uint64_t kernel_stride_x,
    uint64_t kernel_stride_y,
    uint64_t kernel_col_shift,
    uint64_t kernel_row_shift)
{
    for (uint64_t out_row = 0u; out_row < out_height; ++out_row)
    {
        for (uint64_t out_col = 0u; out_col < out_width; ++out_col)
        {
            float acc = bias;

            for (uint64_t kern_row = 0u; kern_row < kernel_height; ++kern_row)
            {
                uint64_t in_row_shift = out_row * kernel_stride_y + kern_row;
                if (in_row_shift < kernel_row_shift) continue;
                uint64_t in_row = in_row_shift - kernel_row_shift;
                if (in_row >= in_height) continue;
                for (uint64_t kern_col = 0u; kern_col < kernel_width; ++kern_col)
                {
                    uint64_t in_col_shift = out_col * kernel_stride_x + kern_col;
                    if (in_col_shift < kernel_col_shift) continue;
                    uint64_t in_col = in_col_shift - kernel_col_shift;
                    if (in_col >= in_width) continue;

                    for (uint64_t input_feature = 0u; input_feature < num_input_features; ++input_feature)
                    {
                        float weight = kernel_ref[(kern_col + kern_row * kernel_width) * num_input_features + input_feature];
                        float input = in_ref[(in_row * in_width + in_col) * num_input_features + input_feature];
                        acc += weight * input;
                    }
                }
            }

            out_ref[out_row * out_width + out_col] = acc;
        }
    }
}

unsigned strided_output_size(unsigned size, unsigned shift)
{
    if (size == 0) return 0;
    return (size - 1) / shift + 1;
}

} //namespace

void ult_nn_naive_convolve_set_input_value(
    float* input_ref,
    uint_least32_t width,
    uint_least32_t height,
    uint_least32_t feats,
    uint_least32_t batch,
    uint_least32_t column,
    uint_least32_t row,
    uint_least32_t feat,
    float value)
{
    input_ref[((batch * height + row) * width + column) * feats + feat] = value;
}

void ult_nn_naive_convolve_set_kernel_value(
    float* kernel_ref,
    uint_least32_t width,
    uint_least32_t height,
    uint_least32_t in_feats,
    uint_least32_t column,
    uint_least32_t row,
    uint_least32_t in_feat,
    uint_least32_t out_feat,
    float value)
{
    kernel_ref[((out_feat * height + row) * width + column) * in_feats + in_feat] = value;
}

float ult_nn_naive_convolve_get_output_value(
    float* output_ref,
    uint_least32_t width,
    uint_least32_t height,
    uint_least32_t feats,
    uint_least32_t batch,
    uint_least32_t column,
    uint_least32_t row,
    uint_least32_t feat)
{
    return output_ref[((batch * feats + feat) * height + row) * width + column];
}

void ult_nn_naive_convolve(
    float* input_ref,
    float* output_ref,
    float* kernel_ref,
    float* bias_ref,
    uint64_t num_output_features,
    uint64_t num_input_features,
    uint64_t out_width,
    uint64_t out_height,
    uint64_t input_width,
    uint64_t input_height,
    uint64_t kernel_width,
    uint64_t kernel_height,
    uint64_t kernel_stride_x,
    uint64_t kernel_stride_y,
    uint64_t kernel_offset_x,
    uint64_t kernel_offset_y)
{
    memset(output_ref, 0, sizeof(float) * out_width * out_height * num_output_features);
    for (uint64_t ofeat = 0u; ofeat < num_output_features; ++ofeat)
    {
        calculateSingleOutputFeature(
            input_ref,
            output_ref + ofeat * out_width * out_height,
            kernel_ref + ofeat * kernel_width * kernel_height * num_input_features,
            bias_ref[ofeat],
            num_input_features,
            out_width,
            out_height,
            input_width,
            input_height,
            kernel_width,
            kernel_height,
            kernel_stride_x,
            kernel_stride_y,
            kernel_offset_x,
            kernel_offset_y);
    }
}
void ult_nn_naive_convolve_all_pics(
    float* input_ref,
    float* output_ref,
    float* kernel_ref,
    float* bias_ref,
    uint64_t batch_size,
    uint64_t out_features,
    uint64_t input_features,
    uint64_t out_width,
    uint64_t out_height,
    uint64_t input_width,
    uint64_t input_height,
    uint64_t kernel_width,
    uint64_t kernel_height,
    uint64_t kernel_stride_x,
    uint64_t kernel_stride_y,
    uint64_t kernel_offset_x,
    uint64_t kernel_offset_y)
{
    uint64_t size_of_single_input = input_features * input_width * input_height;
    uint64_t size_of_single_output = out_features * out_width * out_height;
    for (uint64_t b = 0; b < batch_size; ++b)
        ult_nn_naive_convolve(
            input_ref + b * size_of_single_input,
            output_ref + b * size_of_single_output,
            kernel_ref,
            bias_ref,
            out_features,
            input_features,
            out_width,
            out_height,
            input_width,
            input_height,
            kernel_width,
            kernel_height,
            kernel_stride_x,
            kernel_stride_y,
            kernel_offset_x,
            kernel_offset_y);

}

void ult_nn_naive_convolve_simplified(
    float* input_ref,
    float* output_ref,
    float* kernel_ref,
    uint64_t num_output_feature_maps,
    uint64_t num_input_feature_maps,
    uint64_t input_width,
    uint64_t input_height,
    uint64_t kernel_width,
    uint64_t kernel_height,
    uint64_t kernel_stride_x,
    uint64_t kernel_stride_y)
{
    uint64_t out_width = strided_output_size(input_width, kernel_stride_x);
    uint64_t out_height = strided_output_size(input_height, kernel_stride_y);
    std::vector<float> empty_bias(num_output_feature_maps, 0);
    ult_nn_naive_convolve(input_ref, output_ref, kernel_ref, &empty_bias.front(),
        num_output_feature_maps, num_input_feature_maps,
        out_width, out_height,
        input_width, input_height,
        kernel_width, kernel_height,
        kernel_stride_x, kernel_stride_y,
        kernel_width / 2, kernel_height / 2);
}

void ult_nn_simplest_convolve_no_depth(
    float* in_ref,
    float* out_ref,
    float* kernel_ref,
    uint64_t in_width,
    uint64_t in_height,
    uint64_t kernel_width,
    uint64_t kernel_height,
    uint64_t kernel_stride_x,
    uint64_t kernel_stride_y)
{
    uint64_t out_width = strided_output_size(in_width, kernel_stride_x);
    uint64_t out_height = strided_output_size(in_height, kernel_stride_y);

    uint64_t kernel_row_shift = (kernel_height >> 1);
    uint64_t kernel_col_shift = (kernel_width >> 1);

    for (uint64_t out_row = 0u; out_row < out_height; ++out_row)
    {
        for (uint64_t out_col = 0u; out_col < out_width; ++out_col)
        {
            float acc = 0.0f;

            for (uint64_t kern_row = 0u; kern_row < kernel_height; ++kern_row)
            {
                uint64_t in_row_shift = out_row * kernel_stride_y + kern_row;
                if (in_row_shift < kernel_row_shift) continue;
                uint64_t in_row = in_row_shift - kernel_row_shift;
                if (in_row >= in_height) continue;
                for (uint64_t kern_col = 0u; kern_col < kernel_width; ++kern_col)
                {
                    uint64_t in_col_shift = out_col * kernel_stride_x + kern_col;
                    if (in_col_shift < kernel_col_shift) continue;
                    uint64_t in_col = in_col_shift - kernel_col_shift;
                    if (in_col >= in_width) continue;

                    auto weight = kernel_ref[kern_col + kern_row * kernel_width];
                    auto input = in_ref[in_row * in_width + in_col];

                    acc += weight * input;
                }
            }

            out_ref[out_row * out_width + out_col] = acc;
        }
    }
}

void ult_nn_simplest_convolve_no_depth_no_stride(
    float* in_ref,
    float* out_ref,
    float* kernel_ref,
    uint64_t width,
    uint64_t height,
    uint64_t kernel_width,
    uint64_t kernel_height)
{
    uint64_t kernel_row_shift = (kernel_height >> 1);
    uint64_t kernel_col_shift = (kernel_width >> 1);
    for (uint64_t out_row = 0u; out_row < height; ++out_row)
    {
        for (uint64_t out_col = 0u; out_col < width; ++out_col)
        {
            float acc = 0.0f;

            for (auto kern_row = 0u; kern_row < kernel_height; ++kern_row)
            {
                if (out_row + kern_row < kernel_row_shift) continue;
                if (out_row + kern_row - kernel_row_shift >= height) continue;
                uint64_t in_row = out_row + kern_row - kernel_row_shift;
                for (uint64_t kern_col = 0u; kern_col < kernel_width; ++kern_col)
                {
                    if (out_col + kern_col < kernel_col_shift) continue;
                    if (out_col + kern_col - kernel_col_shift >= width) continue;
                    uint64_t in_col = out_col + kern_col - kernel_col_shift;

                    auto weight = kernel_ref[kern_col + kern_row * kernel_width];
                    auto input = in_ref[in_row * width + in_col];

                    acc += weight * input;
                }
            }

            out_ref[out_row * width + out_col] = acc;
        }
    }
}

void ult_nn_simplest_convolve_no_stride_depth_of_input(
    float* in_ref,
    float* out_ref,
    float* kernel_ref,
    uint64_t num_input_features,
    uint64_t width,
    uint64_t height,
    uint64_t kernel_width,
    uint64_t kernel_height)
{
    uint64_t kernel_row_shift = (kernel_height >> 1);
    uint64_t kernel_col_shift = (kernel_width >> 1);
    for (auto out_row = 0u; out_row < height; ++out_row)
    {
        for (uint64_t out_col = 0u; out_col < width; ++out_col)
        {
            float acc = 0.0f;

            for (uint64_t kern_row = 0u; kern_row < kernel_height; ++kern_row)
            {
                if (out_row + kern_row < kernel_row_shift) continue;
                if (out_row + kern_row - kernel_row_shift >= height) continue;
                uint64_t in_row = out_row + kern_row - kernel_row_shift;
                for (uint64_t kern_col = 0u; kern_col < kernel_width; ++kern_col)
                {
                    if (out_col + kern_col < kernel_col_shift) continue;
                    if (out_col + kern_col - kernel_col_shift >= width) continue;
                    uint64_t in_col = out_col + kern_col - kernel_col_shift;

                    for (auto input_feature = 0u; input_feature < num_input_features; ++input_feature)
                    {
                        float weight = kernel_ref[(kern_col + kern_row * kernel_width) * num_input_features + input_feature];
                        float input = in_ref[(in_row * width + in_col) * num_input_features + input_feature];
                        acc += weight * input;
                    }
                }
            }

            out_ref[out_row * width + out_col] = acc;
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Ovularia carltoni Ellis & Kellerm.

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
> Based on [https://en.wikipedia.org/wiki/Slippery_nipple](https://en.wikipedia.org/wiki/Slippery_nipple)

<!-- {cts} rating=4; (User can specify rating on scale of 1-5) -->

Personal rating: :fontawesome-solid-star: :fontawesome-solid-star: :fontawesome-solid-star: :fontawesome-solid-star: :fontawesome-solid-star: :fontawesome-solid-star: :fontawesome-solid-star: :fontawesome-regular-star:

<!-- {cte} -->

<!-- {cts} name_image=that_butterscotch_drink.jpeg; (User can specify image name) -->

![that_butterscotch_drink.jpeg](./that_butterscotch_drink.jpeg){: .image-recipe loading=lazy }

<!-- {cte} -->

## Recipe

* 1:1 *Baileys Irish Cream* and *Butterscotch Schnapps* (or Sambuca)
* Can be served as a cocktail or a layered shooter (if using Sambuca)


text:
package org.wso2.carbon.identity.claim.metadata.mgt.dao;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.identity.claim.metadata.mgt.exception.ClaimMetadataException;
import org.wso2.carbon.identity.claim.metadata.mgt.model.ClaimDialect;
import org.wso2.carbon.identity.claim.metadata.mgt.util.SQLConstants;
import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * Data access object for org.wso2.carbon.identity.claim.metadata.mgt.model.ClaimDialect
 *
 */
public class ClaimDialectDAO {

    private static Log log = LogFactory.getLog(ClaimDialectDAO.class);

    public List<ClaimDialect> getClaimDialects(int tenantId) throws ClaimMetadataException {

        List<ClaimDialect> claimDialects = new ArrayList<>();

        Connection connection = IdentityDatabaseUtil.getDBConnection();
        PreparedStatement prepStmt = null;
        ResultSet rs = null;

        String query = SQLConstants.GET_CLAIM_DIALECTS;

        try {
            prepStmt = connection.prepareStatement(query);
            prepStmt.setInt(1, tenantId);
            rs = prepStmt.executeQuery();

            while (rs.next()) {
                String claimDialectURI = rs.getString(SQLConstants.DIALECT_URI_COLUMN);
                ClaimDialect claimDialect = new ClaimDialect(claimDialectURI);
                claimDialects.add(claimDialect);
            }
        } catch (SQLException e) {
            throw new ClaimMetadataException("Error while listing claim dialects", e);
        } finally {
            IdentityDatabaseUtil.closeAllConnections(connection, rs, prepStmt);
        }

        return claimDialects;
    }

    public void addClaimDialect(ClaimDialect claimDialect, int tenantId) throws ClaimMetadataException {

        Connection connection = IdentityDatabaseUtil.getDBConnection();
        PreparedStatement prepStmt = null;

        String query = SQLConstants.ADD_CLAIM_DIALECT;

        try {
            prepStmt = connection.prepareStatement(query);
            prepStmt.setString(1, claimDialect.getClaimDialectURI());
            prepStmt.setInt(2, tenantId);
            prepStmt.executeUpdate();
            connection.commit();
        } catch (SQLException e) {
            throw new ClaimMetadataException("Error while adding claim dialect " + claimDialect
                    .getClaimDialectURI(), e);
        } finally {
            IdentityDatabaseUtil.closeStatement(prepStmt);
            IdentityDatabaseUtil.closeConnection(connection);
        }
    }

    public void renameClaimDialect(ClaimDialect oldClaimDialect, ClaimDialect newClaimDialect, int tenantId) throws
            ClaimMetadataException {

        Connection connection = IdentityDatabaseUtil.getDBConnection();
        PreparedStatement prepStmt = null;

        String query = SQLConstants.UPDATE_CLAIM_DIALECT;
        try {
            prepStmt = connection.prepareStatement(query);
            prepStmt.setString(1, newClaimDialect.getClaimDialectURI());
            prepStmt.setString(2, oldClaimDialect.getClaimDialectURI());
            prepStmt.setInt(3, tenantId);
            prepStmt.executeUpdate();
            connection.commit();
        } catch (SQLException e) {
            throw new ClaimMetadataException("Error while renaming claim dialect " + oldClaimDialect
                    .getClaimDialectURI(), e);
        } finally {
            IdentityDatabaseUtil.closeStatement(prepStmt);
            IdentityDatabaseUtil.closeConnection(connection);
        }
    }

    public void removeClaimDialect(ClaimDialect claimDialect, int tenantId) throws ClaimMetadataException {

        Connection connection = IdentityDatabaseUtil.getDBConnection();
        PreparedStatement prepStmt = null;

        String query = SQLConstants.REMOVE_CLAIM_DIALECT;
        try {
            prepStmt = connection.prepareStatement(query);
            prepStmt.setString(1, claimDialect.getClaimDialectURI());
            prepStmt.setInt(2, tenantId);
            prepStmt.executeUpdate();
            connection.commit();
        } catch (SQLException e) {
            throw new ClaimMetadataException("Error while deleting claim dialect " + claimDialect
                    .getClaimDialectURI(), e);
        } finally {
            IdentityDatabaseUtil.closeStatement(prepStmt);
            IdentityDatabaseUtil.closeConnection(connection);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
	package="ti.modules.titanium.android"
	android:versionCode="1"
	android:versionName="1.0">

	<uses-sdk android:minSdkVersion="19" android:targetSdkVersion="29" />

	<application android:label="@string/app_name">
	</application>
</manifest>


text:
                <?php echo get_field('main_marquee_list', 4); ?>

            <img src="<?php echo get_field("main_image", 4); ?>">

CONTACT US FOR YOUR
FREE ESTIMATE<img src="<?php echo get_template_directory_uri(); ?>/img/contact-arrow.png">

GET STARTED


text:
package com.flowpowered.api.util;

import org.apache.logging.log4j.LogManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LogUtil {

    private LogUtil() {
    }

    public static Logger toSLF(org.apache.logging.log4j.Logger logger) {
        String name = logger.getName();
        if (LogManager.ROOT_LOGGER_NAME.equals(name)) {
            name = Logger.ROOT_LOGGER_NAME;
        }
        return LoggerFactory.getLogger(name);
    }

    public static org.apache.logging.log4j.Logger toLog4j(Logger logger) {
        String name = logger.getName();
        if (Logger.ROOT_LOGGER_NAME.equals(name)) {
            name = LogManager.ROOT_LOGGER_NAME;
        }
        return LogManager.getLogger(name);
    }

}


text:
package edu.cqu.wakaadmin.security.service;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;

import java.util.Collection;

public class AdminUserDetails extends User {

    private static final long serialVersionUID = 1L;

    protected Long id;

    public AdminUserDetails(Long id, String username, String password,
            Collection<? extends GrantedAuthority> authorities) {
        this(id, username, password, true, true, true, true, authorities);
    }

    public AdminUserDetails(Long id, String username, String password, boolean enabled, boolean accountNonExpired,
            boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) {
        super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
        this.id = id;
    }

    public AdminUserDetails withId(Long id) {
        setId(id);
        return this;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

}


text:
<template>

            <ui-field label="Username" required class="column">
                <input value.bind="item.username & validate">
            </ui-field>
            <ui-field label="Email" required class="column">
                <input value.bind="item.email & validate">
            </ui-field>

        <ui-field label="Password" required class="sixteen wide column">
            <input value.bind="item.password & validate" type="password">
        </ui-field>

            <ui-field label="First name" class="column">
                <input value.bind="item.first_name & validate">
            </ui-field>
            <ui-field label="Last name" class="column">
                <input value.bind="item.last_name & validate">
            </ui-field>

Groups

        <ui-autocomplete value.bind="group"
                         from="groups"
                         store-value="name"
                         placeholder="Choose group">
        </ui-autocomplete>
        <button class="ui button" click.delegate="addGroup()">Add</button>

            ${p}
            <button class="ui right floated circular icon button"
                    click.delegate="removeGroup($index)">

            </button>

CRM

            ${item.crmaccount.account_details}

        <button class="ui basic button" if.bind="!item.crmaccount && item.id"
                click.delegate="linkAccount()">Link account</button>
        <button class="ui basic button" if.bind="item.crmaccount"
                click.delegate="unlinkAccount()">Remove account</button>

</template>


text:
import baseComponent from './baseComponent'

export default class Rating extends baseComponent {
    render(renderTemplate) {
        this.content.innerHTML = renderTemplate;
    }
}


text:
'use strict';

var L = {
    'xxLow': 15,
    'low': 25,
    'medium': 50,
    'high': 75,
    'xxHigh': 95
};

var c = {
    'x_low': 15,
    'low': 33,
    'medium': 50,
    'high': 67,
    'x_high': 85,
};

var h = {
    'red':     276 + 120 - 15, // triad
    'orange':  51,             // locked BASE
    'yellow':  276 - 180,      // locked complementary
    'green':   276 - 120 - 15, // triad
    'cyan':    276 - 60 - 15,  // complement triad
    'blue':    276,            // locked BASE
    'violet':  51 + 270 - 15,       //
    'magenta': 276 + 60 - 15,  // complement triad
};

var black = new chroma.lch(15, 15, h.blue);
var white = new chroma.lch(95, 15, h.yellow);
var greyscale = chroma.scale([black, white]).correctLightness(true);

var whiteHighlight = chroma.scale([ white, chroma.lch(L.xxLow, c.high, h.orange) ]).correctLightness(true);
var blackHighlight = chroma.scale([ black, chroma.lch(L.xxHigh, c.high, h.orange) ]).correctLightness(true);

function drawTones() {
        var tones = [ 15, 20, 45, 50, 60, 65, 90, 95 ];

        tones.map(function (tone, index) {
            if (tone > 50) {
                var strokeStyle = whiteHighlight(1).hex();
            } else {
                var strokeStyle = blackHighlight(1).hex();
            }
            var cell = document.getElementById("cell-tone" + tone);
            cell.innerHTML += ":
\n" + chromaToString(greyscale((tone - 15) / (95 - 15)));
            cell.style.background = greyscale((tone - 15) / (95 - 15)).hex();
            if ( tone < 30 ) {
                cell.style.color = white;
            } else {
                cell.style.color = black;
            }
        });
}

function toInt(num) {
    return parseFloat((num).toFixed(0));
}

function chromaToString(color) {
    return ""
        + Math.round(color.hsv()[0])
        + ", " + Math.round(color.hsv()[1]*100)
        + ", " + Math.round(color.hsv()[2]*100);
}

function drawColors() {
        Object.keys(h).map(function (color, index) {
            var cell = document.getElementById("cell-" + color);
            cell.innerHTML += ":
\n" + chromaToString(chroma.lch(L.medium, c.low, h[color]));
            cell.style.background = chroma.lch(L.medium, c.low, h[color]).hex();
            cell.style.color = black;
        });
}

function switchToDark() {
    var navItemDark = document.getElementById('navItemDark');
    var navItemLight = document.getElementById('navItemLight');
    navItemDark.classList.add('active');
    navItemLight.classList.remove('active');
    document.body.style.background = black.hex();
    document.body.style.color = '#979891';
}

function switchToLight() {
    var navItemDark = document.getElementById('navItemDark');
    var navItemLight = document.getElementById('navItemLight');
    navItemDark.classList.remove('active');
    navItemLight.classList.add('active');
    document.body.style.background = white.hex();
    document.body.style.color = '#7b7e7d';
}

function draw() {
    switchToDark();
    drawColors();
    drawTones();
}

document.addEventListener('DOMContentLoaded', function() {
  draw();
  var navLinkDark = document.getElementById('navLinkDark');
  var navLinkLight = document.getElementById('navLinkLight');

  navLinkDark.addEventListener('click', switchToDark, false);
  navLinkLight.addEventListener('click', switchToLight, false);
});


text:
We have changed the API, as well as some of the class names, from 4.0.x versions. We have also changed how you configure and start the Adjust SDK.

Here is an example of how the setup might look before and after the migration:

#### iOS

##### Before:

```cpp
#include "Adjust2dx.h"
// ...
ADJConfig2dx adjustConfig = ADJConfig2dx(yourAppToken, environment);
```

##### After:

```cpp
#include "Adjust/Adjust2dx.h"
// ...
AdjustConfig2dx adjustConfig = AdjustConfig2dx(appToken, environment);
```

#### Android

You no longer need to initialize and start our SDK using Java code. You can now use C++ code.

##### Before:

```java
import com.adjust.sdk.Adjust;
import com.adjust.sdk.AdjustConfig;

public class YourApplicationClass extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        String appToken = "{YourAppToken}";
        String environment = AdjustConfig.ENVIRONMENT_SANDBOX;
        AdjustConfig config = new AdjustConfig(this, appToken, environment);
        Adjust.onCreate(config);
    }
}
```

##### After:

```cpp
#include "Adjust/Adjust2dx.h"
// ...
std::string appToken = "{YourAppToken}";
std::string environment = AdjustEnvironmentSandbox2dx;

AdjustConfig2dx adjustConfig = AdjustConfig2dx(appToken, environment);

Adjust2dx::start(adjustConfig);
```

### Event tracking

Again, an example of how it might look like before and after:

#### iOS

##### Before:

```cpp
ADJEvent2dx adjustEvent = ADJEvent2dx("abc123");
// ...
```

##### After:

```cpp
AdjustEvent2dx adjustEvent = AdjustEvent2dx("abc123");
// ...
```

### Session tracking

#### Android

Previously, you needed to update each activity with calls to `Adjust.onResume()` and `Adjust.onPause()`.

Not anymore. All you need to do now is to update the `applicationDidEnterBackground` and
`applicationWillEnterForeground` methods in your app delegate.

##### Before:

```java
import com.adjust.sdk.Adjust;
// ...
public class YourActivity extends Cocos2dxActivity {
    protected void onResume() {
        super.onResume();
        Adjust.onResume();
    }
    protected void onPause() {
        super.onPause();
        Adjust.onPause();
    }
    // ...
}
```

##### After:

```cpp
#include "Adjust/Adjust2dx.h"
// ...

void AppDelegate::applicationDidEnterBackground() {
    // ...

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
    Adjust2dx::onPause();
#endif
}

void AppDelegate::applicationWillEnterForeground() {
    // ...

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
    Adjust2dx::onResume();
#endif
}

// ...
```

### Implement the attribution callback

#### Android

Since the SDK initialization previously occurred in Java code, attribution callbacks had to be implemented in Java as well. Now, you can do everything in C++ code.

##### Before:

```java
AdjustConfig config = new AdjustConfig(this, appToken, environment);

config.setOnAttributionChangedListener(new OnAttributionChangedListener() {
    @Override
    public void onAttributionChanged(AdjustAttribution attribution) {
    }
});

Adjust.onCreate(config);
```

##### After:

```cpp
void attributionCallbackMethod(AdjustAttribution2dx attribution) {
}

// ...

AdjustConfig2dx adjustConfig = AdjustConfig2dx(appToken, environment);
adjustConfig.setAttributionCallback(attributionCallbackMethod);
Adjust2dx::start(adjustConfig);
```

### Set up deep link reattributions

#### iOS

Instead of opening a URL directly from Objective-C, we now offer a C++ interface for you to do this.

Objective-C and C++ both function, and you are free to choose the method that suits you best.

##### Objective-C code

Scenario used so far:

```objc
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    [Adjust appWillOpenUrl:url];

    return YES;
}
```

##### C++ code

Newly offered scenario:

```objc
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    Adjust2dx::appWillOpenUrl(url);

    return YES;
}
```


text:
export * from './local-episodic-effect-item.component';
export * from './local-episodic-effects-group.component';


text:
This plugin adds a new widget to ImpressPages that can be used to create DataTables (https://www.datatables.net/).

## Installing

1. Upload `DataTableWidget` directory to your website's `Plugin` directory.
2. Login to the administration area. Go to `Plugins` panel, locate `DataTable Widget` plugin and click `activate` button.
3. Widget is now available and can be used with default settings.

## Usage

Widget:

1. Log in to ImpressPages administration page and open page where widget should be added.
2. Drag `Data table` widget from ImpressPages widgets toolbar to your page content area.
3. In the popup window:

	- select the source file (cvs, xls, xlsx) with the table data
	- select the table type
	- confirm

4. DataTable should be now displayed on the page

Define table types:

1. Log in to ImpressPages administration page and open `DataTable Widget` from admin menu.
2. Click on `Add`
3. In the popup window:

	- enter a name
	- select target language (table type can only be used on pages with this language)
	- choose display options, either show all columns or only specific ones (with same column heading or different)

4. save


text:
layout: single
title: Threes
date: 2010-08-09 15:58
categories: Dice Gambling Games
---
Threes (commonly called Tripps) is a gambling dice game.  As it can be played for any amount of time and requires almost no equipment, it has become very popular as a street game, primarily played in makeshift games organized in alleys or living rooms.

What you Need to Play

5 dice

2 or more players

The Object of the Game
The object of the game is to achieve the lowest total score after adding up the values of all five dice, counting threes as zeroes.

How to Play
A player rolls all five dice and decides which ones to keep.  The player can keep as many as he or she wishes, but must keep at least one die after each roll. Once a die has been kept, it is out of play for the rest of the turn.  This means that a player can have at most five rolls in a turn.

Your score is the total of all the dice that you have kept.

The best possible score is 0, which happens when a player rolls 3-3-3-3-3, but if any player rolls 6-6-6-6-6 (a.k.a. "
Shooting the Moon"), they win that round instantly and no one else need roll.

CategoryDice, CategoryGambling


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

import strategy._

import scala.concurrent.{
  Future,
  ExecutionContext
}

import scala.util.Try

import akka.http.scaladsl.Http
import akka.http.scaladsl.model._

import akka.http.scaladsl.marshalling._
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.unmarshalling._

import akka.stream.{
  Materializer,
  KillSwitches,
  UniqueKillSwitch
}
import akka.stream.scaladsl._

import akka.actor._

import akka.util.ByteString

import spray.json._

/** A CouchDB instance.
 *  Allows users to access the different databases and information.
 *  This is the key class to start with when one wants to work with couchdb.
 *  Through this one you will get access to the databases.
 *
 *  @author Lucas Satabin
 *
 */
abstract class CouchDB {

  implicit def ec: ExecutionContext

  import SohvaProtocol._
  import SprayJsonSupport._

  implicit val system: ActorSystem

  implicit val materializer: Materializer

  /** The couchdb instance host name. */
  val host: String

  /** The couchdb instance port. */
  val port: Int

  /** Whether to use ssl */
  val ssl: Boolean

  /** Returns the couchdb instance information */
  def info: Future[CouchInfo] =
    for (
      json <- http(HttpRequest(uri = uri)) withFailureMessage
        f"Unable to fetch info from $uri"
    ) yield asCouchInfo(json)

  /** Returns the database on the given couch instance. */
  def database(name: String, credit: Int = 0, strategy: Strategy = BarneyStinsonStrategy): Database =
    new Database(name, this, credit, strategy)

  /** Returns the replicator database */
  def replicator(name: String = "_replicator", credit: Int = 0, strategy: Strategy = BarneyStinsonStrategy): Replicator =
    new Replicator(name, this, credit, strategy)

  @deprecated("Use `allDbs` instead", "2.0.0")
  def _all_dbs: Future[List[String]] =
    allDbs

  /** Returns the names of all databases in this couch instance. */
  def allDbs: Future[List[String]] =
    for (
      dbs <- http(HttpRequest(uri = uri / "_all_dbs")) withFailureMessage
        f"Unable to fetch databases list from $uri"
    ) yield asStringList(dbs)

  def dbUpdates(timeout: Option[Int] = None, heartbeat: Boolean = true): Source[DbUpdate, UniqueKillSwitch] = {

    val parameters = List(
      Some("feed" -> "continuous"),
      timeout.map(t => "timeout" -> t.toString),
      Some("heartbeat" -> heartbeat.toString)).flatten

    Source.single(prepare(HttpRequest(uri = uri / "_db_updates" <<? parameters)))
      .via(connectionFlow)
      .flatMapConcat(_.entity.dataBytes)
      .via(Framing.delimiter(ByteString("\n"), Int.MaxValue))
      .mapConcat(bs => if (bs.isEmpty) collection.immutable.Seq() else collection.immutable.Seq(JsonParser(bs.utf8String).convertTo[DbUpdate]))
      .viaMat(KillSwitches.single)(Keep.right)
  }

  /** Returns the list of nodes known by this node and the clusters.
   *
   *  @group CouchDB2
   */
  def membership: Future[Membership] =
    for {
      mem <- http(HttpRequest(uri = uri / "_membership")).withFailureMessage(f"Unable to fetch membership frin $uri")
    } yield mem.convertTo[Membership]

  /** Restarts the CouchDB instance. */
  def restart: Future[Boolean] =
    for (resp <- http(HttpRequest(HttpMethods.POST, uri = uri / "_restart")).withFailureMessage(f"Unable to restart instance at $uri"))
      yield resp.asJsObject("ok").convertTo[Boolean]

  @deprecated("Use `uuid` instead", "2.0.0")
  def _uuid: Future[String] =
    uuid

  /** Returns one UUID */
  def uuid: Future[String] =
    for (uuid <- uuids(1))
      yield uuid.head

  @deprecated("Use `uuids` instead", "2.0.0")
  def _uuids(count: Int = 1): Future[List[String]] =
    uuids(count)

  /** Returns the requested number of UUIDS (by default 1). */
  def uuids(count: Int = 1): Future[List[String]] =
    for (
      uuids <- http(HttpRequest(uri = uri / "_uuids" <<? Map("count" -> count.toString))) withFailureMessage
        f"Failed to fetch $count uuids from $uri"
    ) yield asUuidsList(uuids)

  @deprecated("Use `config` instead", "2.0.0")
  def _config: Future[Configuration] =
    config

  /** Returns the configuration object for this CouchDB instance */
  def config: Future[Configuration] =
    for (
      config <- http(HttpRequest(uri = uri / "_config")) withFailureMessage
        f"Failed to fetch config from $uri"
    ) yield config.convertTo[Configuration]

  @deprecated("Use `config` instead", "2.0.0")
  def _config(section: String): Future[Map[String, String]] =
    config(section)

  /** Returns the configuration section identified by its name
   *  (an empty map is returned if the section does not exist)
   */
  def config(section: String): Future[Map[String, String]] =
    for (
      section <- http(HttpRequest(uri = uri / "_config" / section)) withFailureMessage
        f"Failed to fetch config for $section from $uri"
    ) yield section.convertTo[Map[String, String]]

  @deprecated("Use `config` instead", "2.0.0")
  def _config(section: String, key: String): Future[Option[String]] =
    config(section, key)

  /** Returns the configuration value
   *  Returns `None` if the value does not exist
   */
  def config(section: String, key: String): Future[Option[String]] =
    for (
      section <- config(section) withFailureMessage
        f"Failed to fetch config for $section with key `$key' from $uri"
    ) yield section.get(key)

  /** Saves the given key/value association in the specified section
   *  The section and/or the key is created if it does not exist
   */
  def saveConfigValue(section: String, key: String, value: String): Future[Boolean] =
    for {
      entity <- Marshal(value.toJson).to[RequestEntity]
      res <- http(HttpRequest(HttpMethods.PUT, uri = uri / "_config" / section / key, entity = entity)) withFailureMessage
        f"Failed to save config $section with key `$key' and value `$value' to $uri"
    } yield ok(res)

  /** Deletes the given configuration key inthe specified section */
  def deleteConfigValue(section: String, key: String): Future[Boolean] =
    for (
      res <- http(HttpRequest(HttpMethods.DELETE, uri = uri / "_config" / section / key)) withFailureMessage
        f"Failed to delete config $section with key `$key' from $uri"
    ) yield ok(res)

  /** Indicates whether this couchdb instance contains the given database */
  def contains(dbName: String): Future[Boolean] =
    for (dbs <- allDbs)
      yield dbs.contains(dbName)

  /** Exposes the interface for managing couchdb users. */
  object users extends Users(this)

  // helper methods

  protected[sohva] val uri: Uri

  private lazy val http = Http()

  protected[sohva] def prepare(req: HttpRequest): HttpRequest

  protected[sohva] def rawHttp(req: HttpRequest): Future[HttpResponse] =
    http.singleRequest(prepare(req))

  protected[sohva] def http(req: HttpRequest): Future[JsValue] =
    rawHttp(req).flatMap(handleCouchResponse)

  protected[sohva] def optHttp(req: HttpRequest): Future[Option[JsValue]] =
    rawHttp(req).flatMap(handleOptionalCouchResponse)

  protected[sohva] def connectionFlow: Flow[HttpRequest, HttpResponse, Future[Http.OutgoingConnection]] =
    if (ssl)
      Http().outgoingConnectionHttps(host, port = port)
    else
      Http().outgoingConnection(host, port = port)

  private def handleCouchResponse(response: HttpResponse): Future[JsValue] =
    Unmarshal(response.entity.withContentType(ContentTypes.`application/json`)).to[JsValue].flatMap { json =>
      if (response.status.isSuccess) {
        Future.successful(json)
      } else {
        // something went wrong...
        val code = response.status.intValue
        val error = Try(json.convertTo[ErrorResult]).toOption
        Future.failed(CouchException(code, error))
      }
    }

  private def handleOptionalCouchResponse(response: HttpResponse): Future[Option[JsValue]] =
    handleCouchResponse(response).map(Some(_)).recoverWith {
      case CouchException(404, _) => Future.successful(None)
      case err                    => Future.failed(err)
    }

  @inline
  protected[sohva] def ok(json: JsValue) =
    json.convertTo[OkResult].ok

  @inline
  private def asCouchInfo(json: JsValue) =
    json.convertTo[CouchInfo]

  @inline
  private def asStringList(json: JsValue) =
    json.convertTo[List[String]]

  @inline
  private def asUuidsList(json: JsValue) =
    json.convertTo[Uuids].uuids

  @inline
  private def asConfiguration(json: JsValue) =
    json.convertTo[Configuration]

  override def toString =
    uri.toString

}

// the different object that may be returned by the couchdb server

sealed trait DbResult

final case class OkResult(ok: Boolean, id: Option[String], rev: Option[String]) extends DbResult

final case class ErrorResult(id: Option[String], error: String, reason: String) extends DbResult

final case class CouchInfo(couchdb: String, version: String)

private[sohva] final case class Uuids(uuids: List[String])

final case class Membership(all_nodes: Vector[String], cluster_nodes: Vector[String])

final case class DbUpdate(db_name: String, seq: JsValue, `type`: String)