text:
#include <bluetoe/attribute_handle.hpp>
#include <bluetoe/server.hpp>

#define BOOST_TEST_MODULE
#include <boost/test/included/unit_test.hpp>

#include <bluetoe/server.hpp>
#include <bluetoe/service.hpp>
#include <bluetoe/characteristic.hpp>

#include "test_servers.hpp"
#include "test_attribute_access.hpp"
#include "attribute_io.hpp"

template < typename Server >
struct fixture
{
    std::uint16_t handle_by_index( std::size_t index )
    {
        return bluetoe::details::handle_index_mapping< Server >::handle_by_index( index );
    }

    std::size_t index_by_handle( std::uint16_t handle )
    {
        return bluetoe::details::handle_index_mapping< Server >::index_by_handle( handle );
    }

    static std::size_t first_index_by_handle( std::uint16_t handle )
    {
        return bluetoe::details::handle_index_mapping< Server >::first_index_by_handle( handle );
    }

    void check_attribute( std::size_t index, std::initializer_list< std::uint8_t > value )
    {
        std::uint8_t value_buffer[ 100 ];
        std::uint8_t cccd_data[ 10 ] = { 0 };
        bluetoe::details::client_characteristic_configuration config( cccd_data, sizeof( cccd_data ) );
        Server srv;
        auto access = bluetoe::details::attribute_access_arguments::read( value_buffer, 0, config );

        const auto result = srv.attribute_at( index ).access( access, index );
        BOOST_CHECK_EQUAL( result, bluetoe::details::attribute_access_result::success );

        BOOST_CHECK_EQUAL_COLLECTIONS(
            value.begin(), value.end(),
            &value_buffer[ 0 ], &value_buffer[ access.buffer_size ] );
    }
};

using server_with_single_fixed_service = bluetoe::server<
    bluetoe::no_gap_service_for_gatt_servers,
    bluetoe::service<
        bluetoe::attribute_handle< 0x0100 >,
        bluetoe::service_uuid16< 0x0815 >,
        bluetoe::characteristic<
            bluetoe::characteristic_uuid16< 0x0816 >,
            bluetoe::fixed_uint8_value< 0x42 >
        >
    >
>;

BOOST_FIXTURE_TEST_SUITE( mapping_single_fixed_service, fixture< server_with_single_fixed_service > )

    BOOST_AUTO_TEST_CASE( service_handle )
    {
        BOOST_CHECK_EQUAL( handle_by_index( 0 ), 0x0100u );
        BOOST_CHECK_EQUAL( handle_by_index( 1 ), 0x0101u );
        BOOST_CHECK_EQUAL( handle_by_index( 2 ), 0x0102u );
        BOOST_CHECK_EQUAL( handle_by_index( 3 ), bluetoe::details::invalid_attribute_handle );
    }

    BOOST_AUTO_TEST_CASE( attribute_values )
    {
        check_attribute( 0, {
            0x15, 0x08              // 0x0815 service UUID
        } );
        check_attribute( 1, {
            0x02,                   // Properties: Read
            0x02, 0x01,             // Characteristic Value Attribute Handle: 0x0102
            0x16, 0x08              // Characteristic UUID
        } );
    }

    BOOST_AUTO_TEST_CASE( handle_to_first_index )
    {
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x010 ), 0u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x100 ), 0u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x101 ), 1u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x102 ), 2u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x103 ), bluetoe::details::invalid_attribute_index );
    }

    BOOST_AUTO_TEST_CASE( handle_to_index )
    {
        BOOST_CHECK_EQUAL( index_by_handle( 0x010 ), bluetoe::details::invalid_attribute_index );
        BOOST_CHECK_EQUAL( index_by_handle( 0x100 ), 0u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x101 ), 1u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x102 ), 2u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x103 ), bluetoe::details::invalid_attribute_index );
    }

    BOOST_AUTO_TEST_CASE( invalid_handles )
    {
        BOOST_CHECK_EQUAL( index_by_handle( 1 ), bluetoe::details::invalid_attribute_index );
    }

BOOST_AUTO_TEST_SUITE_END()

using server_with_single_not_fixed_service = bluetoe::server<
    bluetoe::no_gap_service_for_gatt_servers,
    bluetoe::service<
        bluetoe::service_uuid16< 0x0815 >,
        bluetoe::characteristic<
            bluetoe::characteristic_uuid16< 0x0816 >,
            bluetoe::fixed_uint8_value< 0x42 >
        >
    >
>;

BOOST_FIXTURE_TEST_SUITE( mapping_single_service, fixture< server_with_single_not_fixed_service > )

    BOOST_AUTO_TEST_CASE( service_handle )
    {
        BOOST_CHECK_EQUAL( handle_by_index( 0 ), 1u );
    }

    BOOST_AUTO_TEST_CASE( attribute_values )
    {
        check_attribute( 0, {
            0x15, 0x08              // 0x0815 service UUID
        } );
        check_attribute( 1, {
            0x02,                   // Properties: Read
            0x03, 0x00,             // Characteristic Value Attribute Handle: 0x0003
            0x16, 0x08              // Characteristic UUID
        } );
    }

    BOOST_AUTO_TEST_CASE( handle_to_first_index )
    {
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x00 ), 0u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x01 ), 0u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x02 ), 1u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x03 ), 2u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x04 ), bluetoe::details::invalid_attribute_index );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x05 ), bluetoe::details::invalid_attribute_index );
    }

    BOOST_AUTO_TEST_CASE( handle_to_index )
    {
        BOOST_CHECK_EQUAL( index_by_handle( 0x00 ), bluetoe::details::invalid_attribute_index );
        BOOST_CHECK_EQUAL( index_by_handle( 0x01 ), 0u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x02 ), 1u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x03 ), 2u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x04 ), bluetoe::details::invalid_attribute_index );
        BOOST_CHECK_EQUAL( index_by_handle( 0x05 ), bluetoe::details::invalid_attribute_index );
    }

BOOST_AUTO_TEST_SUITE_END()

using server_with_gap_service_service = bluetoe::server<
    bluetoe::service<
        bluetoe::service_uuid16< 0x0815 >,
        bluetoe::characteristic<
            bluetoe::fixed_uint8_value< 0x42 >
        >
    >
>;

BOOST_FIXTURE_TEST_SUITE( mapping_single_service_with_gap, fixture< server_with_gap_service_service > )

    BOOST_AUTO_TEST_CASE( all_handles )
    {
        // service with single characteristic == 3 handles
        // GAP Service contains 2 characteristics  == 5 handles
        BOOST_CHECK_EQUAL( handle_by_index( 0 ), 1u );
        BOOST_CHECK_EQUAL( handle_by_index( 1 ), 2u );
        BOOST_CHECK_EQUAL( handle_by_index( 2 ), 3u );
        BOOST_CHECK_EQUAL( handle_by_index( 3 ), 4u );
        BOOST_CHECK_EQUAL( handle_by_index( 4 ), 5u );
        BOOST_CHECK_EQUAL( handle_by_index( 5 ), 6u );
        BOOST_CHECK_EQUAL( handle_by_index( 6 ), 7u );
        BOOST_CHECK_EQUAL( handle_by_index( 7 ), 8u );
        BOOST_CHECK_EQUAL( handle_by_index( 8 ), bluetoe::details::invalid_attribute_handle );
    }

    BOOST_AUTO_TEST_CASE( handle_to_first_index )
    {
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x00 ), 0u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x01 ), 0u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x02 ), 1u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x03 ), 2u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x04 ), 3u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x05 ), 4u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x06 ), 5u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x07 ), 6u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x08 ), 7u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x09 ), bluetoe::details::invalid_attribute_index );
    }

    BOOST_AUTO_TEST_CASE( handle_to_index )
    {
        BOOST_CHECK_EQUAL( index_by_handle( 0x00 ), bluetoe::details::invalid_attribute_index );
        BOOST_CHECK_EQUAL( index_by_handle( 0x01 ), 0u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x02 ), 1u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x03 ), 2u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x04 ), 3u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x05 ), 4u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x06 ), 5u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x07 ), 6u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x08 ), 7u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x09 ), bluetoe::details::invalid_attribute_index );
    }

BOOST_AUTO_TEST_SUITE_END()

using server_with_gap_and_one_fixed_service = bluetoe::server<
    bluetoe::service<
        bluetoe::attribute_handle< 0x010 >,
        bluetoe::service_uuid16< 0x0815 >,
        bluetoe::characteristic<
            bluetoe::fixed_uint8_value< 0x42 >
        >
    >
>;

BOOST_FIXTURE_TEST_SUITE( mapping_with_gap_and_one_fixed_service, bluetoe::details::handle_index_mapping< server_with_gap_and_one_fixed_service > )

    BOOST_AUTO_TEST_CASE( all_handles )
    {
        // service with single characteristic == 3 handles
        // GAP Service contains 2 characteristics  == 5 handles
        BOOST_CHECK_EQUAL( handle_by_index( 0 ), 0x010u );
        BOOST_CHECK_EQUAL( handle_by_index( 1 ), 0x011u );
        BOOST_CHECK_EQUAL( handle_by_index( 2 ), 0x012u );
        BOOST_CHECK_EQUAL( handle_by_index( 3 ), 0x013u );
        BOOST_CHECK_EQUAL( handle_by_index( 4 ), 0x014u );
        BOOST_CHECK_EQUAL( handle_by_index( 5 ), 0x015u );
        BOOST_CHECK_EQUAL( handle_by_index( 6 ), 0x016u );
        BOOST_CHECK_EQUAL( handle_by_index( 7 ), 0x017u );
        BOOST_CHECK_EQUAL( handle_by_index( 8 ), bluetoe::details::invalid_attribute_handle );
    }

    BOOST_AUTO_TEST_CASE( handle_to_first_index )
    {
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x0F ), 0u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x10 ), 0u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x11 ), 1u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x12 ), 2u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x13 ), 3u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x14 ), 4u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x15 ), 5u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x16 ), 6u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x17 ), 7u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x18 ), bluetoe::details::invalid_attribute_index );
    }

    BOOST_AUTO_TEST_CASE( handle_to_index )
    {
        BOOST_CHECK_EQUAL( index_by_handle( 0x0F ), bluetoe::details::invalid_attribute_index );
        BOOST_CHECK_EQUAL( index_by_handle( 0x10 ), 0u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x11 ), 1u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x12 ), 2u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x13 ), 3u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x14 ), 4u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x15 ), 5u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x16 ), 6u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x17 ), 7u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x18 ), bluetoe::details::invalid_attribute_index );
    }

BOOST_AUTO_TEST_SUITE_END()

using server_with_partial_fixed_services = bluetoe::server<
    bluetoe::service<
        bluetoe::service_uuid16< 0x0816 >,
        bluetoe::characteristic<
            bluetoe::fixed_uint8_value< 0x42 >
        >
    >,
    bluetoe::service<
        bluetoe::attribute_handle< 0x010 >,
        bluetoe::service_uuid16< 0x0815 >,
        bluetoe::characteristic<
            bluetoe::fixed_uint8_value< 0x42 >
        >
    >
>;

BOOST_FIXTURE_TEST_SUITE( mapping_with_partial_fixed_services, bluetoe::details::handle_index_mapping< server_with_partial_fixed_services > )

    BOOST_AUTO_TEST_CASE( all_handles )
    {
        // 2 service with single characteristic == 6 handles
        // GAP Service contains 2 characteristics  == 5 handles
        BOOST_CHECK_EQUAL( handle_by_index( 0 ), 0x001u );
        BOOST_CHECK_EQUAL( handle_by_index( 1 ), 0x002u );
        BOOST_CHECK_EQUAL( handle_by_index( 2 ), 0x003u );
        BOOST_CHECK_EQUAL( handle_by_index( 3 ), 0x010u );
        BOOST_CHECK_EQUAL( handle_by_index( 4 ), 0x011u );
        BOOST_CHECK_EQUAL( handle_by_index( 5 ), 0x012u );
        BOOST_CHECK_EQUAL( handle_by_index( 6 ), 0x013u );
        BOOST_CHECK_EQUAL( handle_by_index( 7 ), 0x014u );
        BOOST_CHECK_EQUAL( handle_by_index( 8 ), 0x015u );
        BOOST_CHECK_EQUAL( handle_by_index( 9 ), 0x016u );
        BOOST_CHECK_EQUAL( handle_by_index( 10 ), 0x017u );
        BOOST_CHECK_EQUAL( handle_by_index( 11 ), bluetoe::details::invalid_attribute_handle );
    }

    BOOST_AUTO_TEST_CASE( handle_to_first_index )
    {
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x000 ), 0u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x001 ), 0u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x002 ), 1u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x003 ), 2u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x004 ), 3u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x010 ), 3u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x011 ), 4u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x012 ), 5u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x013 ), 6u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x014 ), 7u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x015 ), 8u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x016 ), 9u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x017 ), 10u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x018 ), bluetoe::details::invalid_attribute_index );
    }

    BOOST_AUTO_TEST_CASE( handle_to_index )
    {
        BOOST_CHECK_EQUAL( index_by_handle( 0x000 ), bluetoe::details::invalid_attribute_index );
        BOOST_CHECK_EQUAL( index_by_handle( 0x001 ), 0u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x002 ), 1u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x003 ), 2u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x004 ), bluetoe::details::invalid_attribute_index );
        BOOST_CHECK_EQUAL( index_by_handle( 0x010 ), 3u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x011 ), 4u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x012 ), 5u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x013 ), 6u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x014 ), 7u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x015 ), 8u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x016 ), 9u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x017 ), 10u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x018 ), bluetoe::details::invalid_attribute_index );
    }

BOOST_AUTO_TEST_SUITE_END()

using server_with_multiple_fixed_services = bluetoe::server<
    bluetoe::service<
        bluetoe::attribute_handle< 0x020 >,
        bluetoe::service_uuid16< 0x0816 >,
        bluetoe::characteristic<
            bluetoe::fixed_uint8_value< 0x42 >
        >
    >,
    bluetoe::service<
        bluetoe::attribute_handle< 0x100 >,
        bluetoe::service_uuid16< 0x0815 >,
        bluetoe::characteristic<
            bluetoe::fixed_uint8_value< 0x42 >
        >
    >
>;

BOOST_FIXTURE_TEST_SUITE( mapping_with_multiple_fixed_services, bluetoe::details::handle_index_mapping< server_with_multiple_fixed_services > )

    BOOST_AUTO_TEST_CASE( all_handles )
    {
        // 2 service with single characteristic == 6 handles
        // GAP Service contains 2 characteristics  == 5 handles
        BOOST_CHECK_EQUAL( handle_by_index( 0 ), 0x020u );
        BOOST_CHECK_EQUAL( handle_by_index( 1 ), 0x021u );
        BOOST_CHECK_EQUAL( handle_by_index( 2 ), 0x022u );
        BOOST_CHECK_EQUAL( handle_by_index( 3 ), 0x100u );
        BOOST_CHECK_EQUAL( handle_by_index( 4 ), 0x101u );
        BOOST_CHECK_EQUAL( handle_by_index( 5 ), 0x102u );
        BOOST_CHECK_EQUAL( handle_by_index( 6 ), 0x103u );
        BOOST_CHECK_EQUAL( handle_by_index( 7 ), 0x104u );
        BOOST_CHECK_EQUAL( handle_by_index( 8 ), 0x105u );
        BOOST_CHECK_EQUAL( handle_by_index( 9 ), 0x106u );
        BOOST_CHECK_EQUAL( handle_by_index( 10 ), 0x107u );
        BOOST_CHECK_EQUAL( handle_by_index( 11 ), bluetoe::details::invalid_attribute_handle );
    }

    BOOST_AUTO_TEST_CASE( handle_to_first_index )
    {
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x000 ), 0u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x020 ), 0u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x021 ), 1u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x022 ), 2u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x023 ), 3u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x100 ), 3u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x101 ), 4u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x102 ), 5u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x103 ), 6u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x104 ), 7u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x105 ), 8u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x106 ), 9u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x107 ), 10u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x108 ), bluetoe::details::invalid_attribute_index );
    }

    BOOST_AUTO_TEST_CASE( handle_to_index )
    {
        BOOST_CHECK_EQUAL( index_by_handle( 0x000 ), bluetoe::details::invalid_attribute_index );
        BOOST_CHECK_EQUAL( index_by_handle( 0x020 ), 0u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x021 ), 1u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x022 ), 2u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x023 ), bluetoe::details::invalid_attribute_index );
        BOOST_CHECK_EQUAL( index_by_handle( 0x100 ), 3u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x101 ), 4u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x102 ), 5u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x103 ), 6u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x104 ), 7u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x105 ), 8u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x106 ), 9u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x107 ), 10u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x108 ), bluetoe::details::invalid_attribute_index );
    }

BOOST_AUTO_TEST_SUITE_END()

using server_with_multiple_fixed_services_and_characteristics = bluetoe::server<
    bluetoe::service<
        bluetoe::attribute_handle< 0x020 >,
        bluetoe::service_uuid16< 0x0816 >,
        bluetoe::characteristic<
            bluetoe::fixed_uint8_value< 0x42 >
        >,
        bluetoe::characteristic<
            bluetoe::attribute_handle< 0x100 >,
            bluetoe::fixed_uint8_value< 0x42 >,
            bluetoe::notify
        >
    >,
    bluetoe::service<
        bluetoe::service_uuid16< 0x0815 >,
        bluetoe::characteristic<
            bluetoe::attribute_handle< 0x200 >,
            bluetoe::fixed_uint8_value< 0x42 >,
            bluetoe::notify
        >,
        bluetoe::characteristic<
            bluetoe::fixed_uint8_value< 0x42 >
        >
    >
>;

BOOST_FIXTURE_TEST_SUITE( mapping_with_multiple_fixed_services_and_characteristics, bluetoe::details::handle_index_mapping< server_with_multiple_fixed_services_and_characteristics > )

    BOOST_AUTO_TEST_CASE( all_handles )
    {
        // first service
        BOOST_CHECK_EQUAL( handle_by_index( 0 ), 0x020u );
            // 2 Characteristics
            BOOST_CHECK_EQUAL( handle_by_index( 1 ), 0x021u );
            BOOST_CHECK_EQUAL( handle_by_index( 2 ), 0x022u );

            BOOST_CHECK_EQUAL( handle_by_index( 3 ), 0x100u );
            BOOST_CHECK_EQUAL( handle_by_index( 4 ), 0x101u );
            BOOST_CHECK_EQUAL( handle_by_index( 5 ), 0x102u );

        // second service
        BOOST_CHECK_EQUAL( handle_by_index( 6 ), 0x103u );
            // 2 Characteristics
            BOOST_CHECK_EQUAL( handle_by_index( 7 ), 0x200u );
            BOOST_CHECK_EQUAL( handle_by_index( 8 ), 0x201u );
            BOOST_CHECK_EQUAL( handle_by_index( 9 ), 0x202u );

            BOOST_CHECK_EQUAL( handle_by_index( 10 ), 0x203u );
            BOOST_CHECK_EQUAL( handle_by_index( 11 ), 0x204u );

        // GAP Service
        BOOST_CHECK_EQUAL( handle_by_index( 12 ), 0x205u );
            // 2 Characteristics
            BOOST_CHECK_EQUAL( handle_by_index( 13 ), 0x206u );
            BOOST_CHECK_EQUAL( handle_by_index( 14 ), 0x207u );

            BOOST_CHECK_EQUAL( handle_by_index( 15 ), 0x208u );
            BOOST_CHECK_EQUAL( handle_by_index( 16 ), 0x209u );

        BOOST_CHECK_EQUAL( handle_by_index( 17 ), bluetoe::details::invalid_attribute_handle );
    }

    BOOST_AUTO_TEST_CASE( handle_to_first_index )
    {
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x01f ), 0u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x020 ), 0u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x021 ), 1u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x022 ), 2u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x023 ), 3u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x100 ), 3u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x101 ), 4u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x102 ), 5u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x103 ), 6u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x104 ), 7u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x200 ), 7u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x201 ), 8u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x202 ), 9u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x203 ), 10u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x204 ), 11u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x205 ), 12u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x206 ), 13u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x207 ), 14u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x208 ), 15u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x209 ), 16u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x20a ), bluetoe::details::invalid_attribute_index );
    }

    BOOST_AUTO_TEST_CASE( handle_to_index )
    {
        BOOST_CHECK_EQUAL( index_by_handle( 0x01f ), bluetoe::details::invalid_attribute_index );
        BOOST_CHECK_EQUAL( index_by_handle( 0x020 ), 0u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x021 ), 1u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x022 ), 2u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x023 ), bluetoe::details::invalid_attribute_index );
        BOOST_CHECK_EQUAL( index_by_handle( 0x100 ), 3u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x101 ), 4u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x102 ), 5u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x103 ), 6u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x104 ), bluetoe::details::invalid_attribute_index );
        BOOST_CHECK_EQUAL( index_by_handle( 0x200 ), 7u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x201 ), 8u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x202 ), 9u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x203 ), 10u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x204 ), 11u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x205 ), 12u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x206 ), 13u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x207 ), 14u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x208 ), 15u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x209 ), 16u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x20a ), bluetoe::details::invalid_attribute_index );
    }

BOOST_AUTO_TEST_SUITE_END()

using server_with_multiple_fixed_attributes_handles = bluetoe::server<
    bluetoe::no_gap_service_for_gatt_servers,
    bluetoe::service<
        bluetoe::attribute_handle< 0x020 >,
        bluetoe::service_uuid16< 0x0816 >,

        bluetoe::characteristic<
            bluetoe::characteristic_uuid16< 0x0816 >,
            bluetoe::attribute_handles< 0x50, 0x52 >,
            bluetoe::fixed_uint8_value< 0x42 >
        >,
        bluetoe::characteristic<
            bluetoe::characteristic_uuid16< 0x0817 >,
            bluetoe::attribute_handles< 0x60, 0x62, 0x64 >,
            bluetoe::fixed_uint8_value< 0x43 >,
            bluetoe::notify
        >
    >,
    bluetoe::service<
        bluetoe::service_uuid16< 0x0815 >,
        bluetoe::characteristic<
            bluetoe::characteristic_uuid16< 0x0816 >,
            bluetoe::fixed_uint8_value< 0x44 >,
            bluetoe::notify
        >,
        bluetoe::characteristic<
            bluetoe::characteristic_uuid16< 0x0818 >,
            bluetoe::attribute_handles< 0x100, 0x101 >,
            bluetoe::fixed_uint8_value< 0x45 >
        >
    >
>;

BOOST_FIXTURE_TEST_SUITE( mapping_with_multiple_fixed_attributes_handles, fixture< server_with_multiple_fixed_attributes_handles > )

    BOOST_AUTO_TEST_CASE( all_handles )
    {
        // first service
        BOOST_CHECK_EQUAL( handle_by_index( 0 ), 0x020u );
            // 2 Characteristics
            BOOST_CHECK_EQUAL( handle_by_index( 1 ), 0x050u );
            BOOST_CHECK_EQUAL( handle_by_index( 2 ), 0x052u );

            BOOST_CHECK_EQUAL( handle_by_index( 3 ), 0x060u );
            BOOST_CHECK_EQUAL( handle_by_index( 4 ), 0x062u );
            BOOST_CHECK_EQUAL( handle_by_index( 5 ), 0x064u );

        // second service
        BOOST_CHECK_EQUAL( handle_by_index( 6 ), 0x065u );
            // 2 Characteristics
            BOOST_CHECK_EQUAL( handle_by_index( 7 ), 0x066u );
            BOOST_CHECK_EQUAL( handle_by_index( 8 ), 0x067u );
            BOOST_CHECK_EQUAL( handle_by_index( 9 ), 0x068u );

            BOOST_CHECK_EQUAL( handle_by_index( 10 ), 0x100u );
            BOOST_CHECK_EQUAL( handle_by_index( 11 ), 0x101u );

        BOOST_CHECK_EQUAL( handle_by_index( 12 ), bluetoe::details::invalid_attribute_handle );
    }

    BOOST_AUTO_TEST_CASE( handle_to_first_index )
    {
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x01f ), 0u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x020 ), 0u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x021 ), 1u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x050 ), 1u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x051 ), 2u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x052 ), 2u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x053 ), 3u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x060 ), 3u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x061 ), 4u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x062 ), 4u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x063 ), 5u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x064 ), 5u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x065 ), 6u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x066 ), 7u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x067 ), 8u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x068 ), 9u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x069 ), 10u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x100 ), 10u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x101 ), 11u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x102 ), bluetoe::details::invalid_attribute_index );
    }

    BOOST_AUTO_TEST_CASE( handle_to_index )
    {
        BOOST_CHECK_EQUAL( index_by_handle( 0x01f ), bluetoe::details::invalid_attribute_index );
        BOOST_CHECK_EQUAL( index_by_handle( 0x020 ), 0u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x021 ), bluetoe::details::invalid_attribute_index );
        BOOST_CHECK_EQUAL( index_by_handle( 0x050 ), 1u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x051 ), bluetoe::details::invalid_attribute_index );
        BOOST_CHECK_EQUAL( index_by_handle( 0x052 ), 2u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x053 ), bluetoe::details::invalid_attribute_index );
        BOOST_CHECK_EQUAL( index_by_handle( 0x060 ), 3u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x061 ), bluetoe::details::invalid_attribute_index );
        BOOST_CHECK_EQUAL( index_by_handle( 0x062 ), 4u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x063 ), bluetoe::details::invalid_attribute_index );
        BOOST_CHECK_EQUAL( index_by_handle( 0x064 ), 5u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x065 ), 6u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x066 ), 7u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x067 ), 8u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x068 ), 9u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x069 ), bluetoe::details::invalid_attribute_index );
        BOOST_CHECK_EQUAL( index_by_handle( 0x100 ), 10u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x101 ), 11u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x102 ), bluetoe::details::invalid_attribute_index );
    }

    BOOST_AUTO_TEST_CASE( attribute_values )
    {
        // first service
        check_attribute( 0, {
            0x16, 0x08              // 0x0815 service UUID
        } );

        // first characteristic
        check_attribute( 1, {
            0x02,                   // Properties: Read
            0x52, 0x00,             // Characteristic Value Attribute Handle: 0x0052
            0x16, 0x08              // Characteristic UUID
        } );
        check_attribute( 2, { 0x42 } ); // Value

        // second characteristic
        check_attribute( 3, {
            0x12,                   // Properties: Read, Notify
            0x62, 0x00,             // Characteristic Value Attribute Handle: 0x0062
            0x17, 0x08              // Characteristic UUID
        } );
        check_attribute( 4, { 0x43 } ); // Value
        check_attribute( 5, { 0x00, 0x00 } ); // CCCD configuration

        // second service
        check_attribute( 6, {
            0x15, 0x08              // 0x0815 service UUID
        } );

        // first characteristic
        check_attribute( 7, {
            0x12,                   // Properties: Read, Notify
            0x67, 0x00,             // Characteristic Value Attribute Handle: 0x0067
            0x16, 0x08              // Characteristic UUID
        } );
        check_attribute( 8, { 0x44 } ); // Value
        check_attribute( 9, { 0x00, 0x00 } ); // CCCD configuration

        // second characteristic
        check_attribute( 10, {
            0x02,                   // Properties: Read
            0x01, 0x01,             // Characteristic Value Attribute Handle: 0x0101
            0x18, 0x08              // Characteristic UUID
        } );
        check_attribute( 11, { 0x45 } ); // Value
    }

BOOST_AUTO_TEST_SUITE_END()

static const char char_name_foo[] = "Foo";
static const char char_name_bar[] = "Bar";
static const char char_name_baz[] = "Baz";
static const std::uint8_t descriptor_data[] = { 0x08, 0x15 };

using server_with_additional_descriptors = bluetoe::server<
    bluetoe::no_gap_service_for_gatt_servers,
    bluetoe::service<
        bluetoe::attribute_handle< 0x020 >,
        bluetoe::service_uuid16< 0x0815 >,

        // Characteristic with CCCD and Characteristic User Description without fixed CCCD
        bluetoe::characteristic<
            bluetoe::characteristic_uuid16< 0x1516 >,
            bluetoe::attribute_handles< 0x50, 0x52 >,
            bluetoe::fixed_uint8_value< 0x42 >,
            bluetoe::characteristic_name< char_name_foo >,
            bluetoe::notify
        >,
        // Characteristic with CCCD and Characteristic User Description and user descriptor with fixed CCCD
        bluetoe::characteristic<
            bluetoe::characteristic_uuid16< 0x1517 >,
            bluetoe::attribute_handles< 0x60, 0x62, 0x64 >,
            bluetoe::fixed_uint8_value< 0x43 >,
            bluetoe::characteristic_name< char_name_bar >,
            bluetoe::descriptor< 0x1722, descriptor_data, sizeof( descriptor_data ) >,
            bluetoe::notify
        >,
        // No descriptors, no fixup
        bluetoe::characteristic<
            bluetoe::characteristic_uuid16< 0x1518 >,
            bluetoe::fixed_uint8_value< 0x44 >
        >,
        // Characteristic Characteristic User Description without fixed CCCD
        bluetoe::characteristic<
            bluetoe::characteristic_uuid16< 0x1519 >,
            bluetoe::attribute_handles< 0x70, 0x80 >,
            bluetoe::fixed_uint8_value< 0x45 >,
            bluetoe::characteristic_name< char_name_baz >
        >
    >
>;

BOOST_FIXTURE_TEST_SUITE( mapping_server_with_additional_descriptors, fixture< server_with_additional_descriptors > )

    BOOST_AUTO_TEST_CASE( all_handles )
    {
        // first service
        BOOST_CHECK_EQUAL( handle_by_index( 0 ), 0x020u );
            // Declaration, Value, CCCD, User Description
            BOOST_CHECK_EQUAL( handle_by_index( 1 ), 0x050u );
            BOOST_CHECK_EQUAL( handle_by_index( 2 ), 0x052u );
            BOOST_CHECK_EQUAL( handle_by_index( 3 ), 0x053u );
            BOOST_CHECK_EQUAL( handle_by_index( 4 ), 0x054u );

            // Declaration, Value, CCCD, User Description
            BOOST_CHECK_EQUAL( handle_by_index( 5 ), 0x060u );
            BOOST_CHECK_EQUAL( handle_by_index( 6 ), 0x062u );
            BOOST_CHECK_EQUAL( handle_by_index( 7 ), 0x064u );
            BOOST_CHECK_EQUAL( handle_by_index( 8 ), 0x065u );
            BOOST_CHECK_EQUAL( handle_by_index( 9 ), 0x066u );

            // Declaration, Value without fixup
            BOOST_CHECK_EQUAL( handle_by_index( 10 ), 0x067u );
            BOOST_CHECK_EQUAL( handle_by_index( 11 ), 0x068u );

            // Declaration, Value, User Description
            BOOST_CHECK_EQUAL( handle_by_index( 12 ), 0x070u );
            BOOST_CHECK_EQUAL( handle_by_index( 13 ), 0x080u );
            BOOST_CHECK_EQUAL( handle_by_index( 14 ), 0x081u );

        BOOST_CHECK_EQUAL( handle_by_index( 15 ), bluetoe::details::invalid_attribute_handle );
    }

    BOOST_AUTO_TEST_CASE( handle_to_first_index )
    {
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x01f ), 0u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x020 ), 0u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x021 ), 1u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x050 ), 1u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x051 ), 2u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x052 ), 2u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x053 ), 3u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x054 ), 4u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x055 ), 5u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x060 ), 5u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x061 ), 6u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x062 ), 6u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x063 ), 7u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x064 ), 7u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x065 ), 8u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x066 ), 9u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x067 ), 10u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x068 ), 11u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x069 ), 12u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x070 ), 12u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x071 ), 13u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x07F ), 13u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x080 ), 13u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x081 ), 14u );
        BOOST_CHECK_EQUAL( first_index_by_handle( 0x082 ), bluetoe::details::invalid_attribute_index );
    }

    BOOST_AUTO_TEST_CASE( handle_to_index )
    {
        BOOST_CHECK_EQUAL( index_by_handle( 0x01f ), bluetoe::details::invalid_attribute_index );
        BOOST_CHECK_EQUAL( index_by_handle( 0x020 ), 0u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x021 ), bluetoe::details::invalid_attribute_index );
        BOOST_CHECK_EQUAL( index_by_handle( 0x050 ), 1u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x051 ), bluetoe::details::invalid_attribute_index );
        BOOST_CHECK_EQUAL( index_by_handle( 0x052 ), 2u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x053 ), 3u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x054 ), 4u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x055 ), bluetoe::details::invalid_attribute_index );
        BOOST_CHECK_EQUAL( index_by_handle( 0x060 ), 5u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x061 ), bluetoe::details::invalid_attribute_index );
        BOOST_CHECK_EQUAL( index_by_handle( 0x062 ), 6u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x063 ), bluetoe::details::invalid_attribute_index );
        BOOST_CHECK_EQUAL( index_by_handle( 0x064 ), 7u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x065 ), 8u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x066 ), 9u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x067 ), 10u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x068 ), 11u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x069 ), bluetoe::details::invalid_attribute_index );
        BOOST_CHECK_EQUAL( index_by_handle( 0x070 ), 12u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x071 ), bluetoe::details::invalid_attribute_index );
        BOOST_CHECK_EQUAL( index_by_handle( 0x07F ), bluetoe::details::invalid_attribute_index );
        BOOST_CHECK_EQUAL( index_by_handle( 0x080 ), 13u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x081 ), 14u );
        BOOST_CHECK_EQUAL( index_by_handle( 0x082 ), bluetoe::details::invalid_attribute_index );
    }

    /*
     * This test tests, that the descriptors are in the expected order within the characteristic
     */
    BOOST_AUTO_TEST_CASE( attribute_values )
    {
        // first service
        check_attribute( 0, {
            0x15, 0x08              // 0x0815 service UUID
        } );

        // first characteristic
        check_attribute( 1, {
            0x12,                   // Properties: Read, Notify
            0x52, 0x00,             // Characteristic Value Attribute Handle: 0x0052
            0x16, 0x15              // UUID
        } );
        check_attribute( 2, {
            0x42                    // Value
        } );
        check_attribute( 3, {
            0x00, 0x00              // CCCD
        } );
        check_attribute( 4, {
            'F', 'o', 'o'           // Characteristic User Description
        } );

        // second characteristic
        check_attribute( 5, {
            0x12,                   // Properties: Read, Notify
            0x62, 0x00,             // Characteristic Value Attribute Handle: 0x0062
            0x17, 0x15              // UUID
        } );
        check_attribute( 6, {
            0x43                    // Value
        } );
        check_attribute( 7, {
            0x00, 0x00              // CCCD
        } );
        check_attribute( 8, {
            'B', 'a', 'r'           // Characteristic User Description
        } );
        check_attribute( 9, {
            0x08, 0x15              // User defined descriptor
        } );

        // third characteristic
        check_attribute( 10, {
            0x02,                   // Properties: Read
            0x68, 0x00,             // Characteristic Value Attribute Handle: 0x0068
            0x18, 0x15              // UUID
        } );
        check_attribute( 11, {
            0x44                    // Value
        } );

        // forth characteristic
        check_attribute( 12, {
            0x02,                   // Properties: Read
            0x80, 0x00,             // Characteristic Value Attribute Handle: 0x0070
            0x19, 0x15              // UUID
        } );
        check_attribute( 13, {
            0x45                    // Value
        } );
        check_attribute( 14, {
            'B', 'a', 'z'           // Characteristic User Description
        } );
   }

BOOST_AUTO_TEST_SUITE_END()


text:
package tonius.neiintegration.mods.mcforge;

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

import net.minecraft.item.Item;
import net.minecraft.tileentity.TileEntityFurnace;
import net.minecraft.util.EnumChatFormatting;
import net.minecraftforge.event.entity.player.ItemTooltipEvent;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.oredict.OreDictionary;
import tonius.neiintegration.Utils;
import tonius.neiintegration.config.Config;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;

public class MCForgeTooltipHandler {

    @SubscribeEvent
    public void onItemTooltip(ItemTooltipEvent evt) {
        if (Config.tooltip_unlocalizedName && (!Config.tooltip_unlocalizedNameShift || Utils.isShiftKeyDown()) && (!Config.tooltip_unlocalizedNameAdvanced || evt.showAdvancedItemTooltips)) {
            evt.toolTip.add(EnumChatFormatting.DARK_GRAY + Utils.translate("tooltip.unlocalizedName") + " " + evt.itemStack.getUnlocalizedName());
        }

        if (Config.tooltip_internalName && (!Config.tooltip_internalNameShift || Utils.isShiftKeyDown()) && (!Config.tooltip_internalNameAdvanced || evt.showAdvancedItemTooltips)) {
            evt.toolTip.add(EnumChatFormatting.DARK_GRAY + Utils.translate("tooltip.internalName") + " " + Item.itemRegistry.getNameForObject(evt.itemStack.getItem()));
        }

        if (Config.tooltip_maxStack && (!Config.tooltip_maxStackShift || Utils.isShiftKeyDown()) && (!Config.tooltip_maxStackAdvanced || evt.showAdvancedItemTooltips)) {
            evt.toolTip.add(EnumChatFormatting.DARK_GRAY + Utils.translate("tooltip.maxstack") + " " + String.valueOf(evt.itemStack.getMaxStackSize()));
        }

        if (Config.tooltip_burnTime && (!Config.tooltip_burnTimeShift || Utils.isShiftKeyDown()) && (!Config.tooltip_burnTimeAdvanced || evt.showAdvancedItemTooltips)) {
            int burnTime = TileEntityFurnace.getItemBurnTime(evt.itemStack);
            if (burnTime > 0) {
                evt.toolTip.add(Utils.translate("tooltip.burntime") + " " + burnTime + " " + Utils.translate("ticks"));
            }
        }

        if (Config.tooltip_oreDictNames && (!Config.tooltip_oreDictNamesShift || Utils.isShiftKeyDown()) && (!Config.tooltip_oreDictNamesAdvanced || evt.showAdvancedItemTooltips)) {
            List<String> names = new ArrayList<String>();
            for (int id : OreDictionary.getOreIDs(evt.itemStack)) {
                String name = OreDictionary.getOreName(id);
                if (!names.contains(name)) {
                    names.add("  " + name);
                } else {
                    names.add("  " + EnumChatFormatting.DARK_GRAY + name);
                }
            }
            Collections.sort(names);
            if (!names.isEmpty()) {
                evt.toolTip.add(Utils.translate("tooltip.oredict"));
                evt.toolTip.addAll(names);
            }
        }

        if (Config.tooltip_fluidRegInfo && (!Config.tooltip_fluidRegInfoShift || Utils.isShiftKeyDown()) && (!Config.tooltip_fluidRegInfoAdvanced || evt.showAdvancedItemTooltips)) {
            List<String> names = new ArrayList<String>();
            if (FluidContainerRegistry.isEmptyContainer(evt.itemStack)) {
                names.add("  " + Utils.translate("tooltip.fluidreg.empty"));
            } else {
                FluidStack fluid = Utils.getFluidStack(evt.itemStack);
                if (fluid != null) {
                    names.add("  " + fluid.getLocalizedName());
                    names.add("  " + fluid.amount + " mB");
                }
            }
            if (!names.isEmpty()) {
                evt.toolTip.add(Utils.translate("tooltip.fluidreg"));
                evt.toolTip.addAll(names);
            }
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
<?php

class RESTCommandTvArchiveRecorder extends RESTCommand
{
    private $manager;

    public function __construct(){
        $this->manager = new TvArchiveRecorder();
    }

    /**
     * Create recording task
     *
     * @param RESTRequest $request
     * @return bool
     * @throws ErrorException
     */
    public function create(RESTRequest $request){

        $task = $request->getData('task');

        if (empty($task)){
            throw new ErrorException('Empty task');
        }

        return $this->manager->start($task);
    }

    /**
     * Delete recording task
     *
     * @param RESTRequest $request
     * @return bool
     * @throws ErrorException
     */
    public function delete(RESTRequest $request){

        $ch_ids = $request->getIdentifiers();

        if (empty($ch_ids[0])){
            throw new ErrorException('Empty ch_id');
        }

        return $this->manager->stop($ch_ids[0]);
    }
}


text:
namespace Ops {
  template<typename T> struct Assign {
    __host__ __device__ __forceinline__
    const T operator() (T & lhs, const T & rhs) const {
      return lhs = rhs;
    }
  };
  template<typename T> struct Add {
    __host__ __device__ __forceinline__
    const T operator() (T & lhs, const T & rhs) const {
      return lhs += rhs;
    }
  };
  template<typename T> struct Sub {
    __host__ __device__ __forceinline__
    const T operator() (T & lhs, const T & rhs) const {
      return lhs -= rhs;
    }
  };
  template<typename T> struct Mul {
    __host__ __device__ __forceinline__
    const T operator() (T & lhs, const T & rhs) const {
      return lhs *= rhs;
    }
  };
  template<typename T> struct Div {
    __host__ __device__ __forceinline__
    const T operator() (T & lhs, const T & rhs) const {
      return lhs /= rhs;
    }
  };
  template<typename T> struct Gt {
    __host__ __device__ __forceinline__
    bool operator() (T & lhs, const T & rhs) const {
      return lhs >= rhs;
    }
  };
  template<typename T> struct Lt {
    __host__ __device__ __forceinline__
    bool operator() (T & lhs, const T & rhs) const {
      return lhs <= rhs;
    }
  };
  template<typename T> struct And {
    __host__ __device__ __forceinline__
    int operator() (int & lhs, const int & rhs) const {
      return lhs &= rhs;
    }
  };
  template<typename T> struct Or {
    __host__ __device__ __forceinline__
    int operator() (int & lhs, const int & rhs) const {
      return lhs |= rhs;
    }
  };
  template<typename T> struct Negate {
    __host__ __device__ __forceinline__
    T operator() (T & lhs, const T & rhs) const {
      return lhs = -rhs;
    }
  };
  template<typename T> struct Min {
    __host__ __device__ __forceinline__
    T operator() (T & lhs, const T & rhs) const {
      return lhs < rhs ? lhs : rhs;
    }
  };
  template<typename T> struct Max {
    __host__ __device__ __forceinline__
    T operator() (T & lhs, const T & rhs) const {
      return lhs > rhs ? lhs : rhs;
    }
  };
  template<typename T> struct Abs {
    __host__ __device__ __forceinline__
    T operator() (T & lhs, const T & rhs) const {
      return lhs = fabsf(rhs);
    }
  };
  template<typename T> struct Rsqrt {
    __host__ __device__ __forceinline__
    T operator() (T & lhs, const T & rhs) const {
      return lhs = rsqrtf(rhs);
    }
  };
}

template<typename Op, typename T, int N>
struct Unroll {
  __host__ __device__ __forceinline__
  static void loop(T * lhs, const T * rhs) {
    Op operation;
    Unroll<Op,T,N-1>::loop(lhs, rhs);
    operation(lhs[N-1], rhs[N-1]);
  }
  __host__ __device__ __forceinline__
  static void loop(T * lhs, const T rhs) {
    Op operation;
    Unroll<Op,T,N-1>::loop(lhs, rhs);
    operation(lhs[N-1], rhs);
  }
  __host__ __device__ __forceinline__
  static const T reduce(const T * val) {
    Op operation;
    return operation(const_cast<T*>(val)[N-1], Unroll<Op,T,N-1>::reduce(val));
  }
};

template<typename Op, typename T>
struct Unroll<Op,T,1> {
  __host__ __device__ __forceinline__
  static void loop(T * lhs, const T * rhs) {
    Op operation;
    operation(lhs[0], rhs[0]);
  }
  __host__ __device__ __forceinline__
  static void loop(T * lhs, const T rhs) {
    Op operation;
    operation(lhs[0], rhs);
  }
  __host__ __device__ __forceinline__
  static const T reduce(const T * val) {
    return val[0];
  }
};

#endif


text:
package org.jtrim2.swing.component;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.util.StringTokenizer;

final class RenderHelper {
    public static int drawOutlinedStringSimple(Graphics2D g, String str, int x, int y) {
        Rectangle2D textArea = g.getFont().getStringBounds(str, g.getFontRenderContext());

        Color textColor = g.getColor();
        g.setColor(g.getBackground());

        g.drawString(str, x + 1, y + 1);
        g.drawString(str, x + 1, y - 1);
        g.drawString(str, x - 1, y + 1);
        g.drawString(str, x - 1, y - 1);

        g.drawString(str, x + 1, y);
        g.drawString(str, x - 1, y);
        g.drawString(str, x, y - 1);
        g.drawString(str, x, y + 1);

        g.setColor(textColor);
        g.drawString(str, x, y);

        return (int) textArea.getWidth() + 1;
    }

    public static void drawOutlinedString(Graphics2D g, String str, int x, int y, int extraSpace) {
        int currentX = x;

        for (int i = 0; i < str.length(); i++) {
            currentX += drawOutlinedStringSimple(g, str.substring(i, i + 1), currentX, y);
            currentX += extraSpace;
        }
    }

    public static void drawMessage(Graphics2D g, String message) {
        final int gap = 5;

        Rectangle2D textArea = g.getFont().getStringBounds(message, g.getFontRenderContext());

        int x = gap - (int) textArea.getMinX();
        int y = gap - (int) textArea.getMinY();

        StringTokenizer messageTokenizer = new StringTokenizer(message, "\n");

        while (messageTokenizer.hasMoreTokens()) {
            String currentLine = messageTokenizer.nextToken();
            drawOutlinedString(g, currentLine, x, y, 0);

            y = y + (int) textArea.getHeight();
        }
    }

    private RenderHelper() {
        throw new AssertionError();
    }
}


text:
// Type definitions for @storybook/addon-viewport 4.1
// Project: https://github.com/storybooks/storybook/tree/master/addons/viewport
// Definitions by: Vincent Tunru <https://github.com/Vinnl>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8

import { StoryDecorator } from '@storybook/react';

export type ViewportName = string;

export interface ViewportProperties {
    name: ViewportName;
    styles: {
        width?: string,
        height?: string,
        [styleName: string]: any,
    };
    type?: 'desktop' | 'tablet' | 'mobile' | string;
}
export interface ViewportDecoratorOptions {
    /**
     * Default viewport
     */
    name?: ViewportName;
    /**
     * Called whenever different viewport is selected from the dropdown
     */
    onViewportChange: (change: { viewport: ViewportProperties }) => void;
}
export interface ViewportDefinitions {
    [viewportKey: string]: ViewportProperties;
}
export type Viewport = ViewportName | ViewportDecoratorOptions;

export interface ViewportConfiguration {
    viewports?: ViewportDefinitions;
    defaultViewport?: ViewportName;
}

export const INITIAL_VIEWPORTS: ViewportDefinitions;
export function configureViewport(configuration: ViewportConfiguration): void;
export function withViewport(viewport?: Viewport): StoryDecorator;


text:
#include <aws/sagemaker/model/DataSource.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace SageMaker
{
namespace Model
{

DataSource::DataSource() :
    m_s3DataSourceHasBeenSet(false),
    m_fileSystemDataSourceHasBeenSet(false)
{
}

DataSource::DataSource(JsonView jsonValue) :
    m_s3DataSourceHasBeenSet(false),
    m_fileSystemDataSourceHasBeenSet(false)
{
  *this = jsonValue;
}

DataSource& DataSource::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("S3DataSource"))
  {
    m_s3DataSource = jsonValue.GetObject("S3DataSource");

    m_s3DataSourceHasBeenSet = true;
  }

  if(jsonValue.ValueExists("FileSystemDataSource"))
  {
    m_fileSystemDataSource = jsonValue.GetObject("FileSystemDataSource");

    m_fileSystemDataSourceHasBeenSet = true;
  }

  return *this;
}

JsonValue DataSource::Jsonize() const
{
  JsonValue payload;

  if(m_s3DataSourceHasBeenSet)
  {
   payload.WithObject("S3DataSource", m_s3DataSource.Jsonize());

  }

  if(m_fileSystemDataSourceHasBeenSet)
  {
   payload.WithObject("FileSystemDataSource", m_fileSystemDataSource.Jsonize());

  }

  return payload;
}

} // namespace Model
} // namespace SageMaker
} // namespace Aws


text:
<!DOCTYPE html>

        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>A11Y First Workshop - A Web Accessibility Workshop</title>
        <link rel="stylesheet" href="https://ir.ebaystatic.com/cr/v/c1/skin/v7.0.2/ds4/skin.min.css"/>
        <link rel="stylesheet" href="index.css"/>

A11Y First Workshop - A Web Accessibility Workshop

Refer to the README for instructions.

Table of Contents

Structure & Semantics

Links

Buttons

Flyouts

Forms

Form Validation

ARIA Widgets

Data Tables

Chapter 1: Introduces Structure & Semantics

Also introduces the concepts of screenreader-only text and ARIA roles

Blank Page

Meta

Paragraphs

Lists

Definition Lists

Headings

Landmarks

Images

Background Images

Table Layout

Grid System

Cards

Inline Frames

Chapter 2: Introduces Links

Also introduces concept of focus management.

Text Links

Tiles

Ambiguous Links

Fake Buttons

New Window Links

Navigation Landmarks

Skip-To Main

Enhanced Skip-To

Custom Focus Indicator

Fake Tabs

Chapter 3: Introduces Buttons

Also introduces concept of ARIA labels.

Button Text

Critical Icon

Access Key

Chapter 4: Introduces Flyouts

Button Flyout

Link Flyout

Fake Menu

Infotip

Tooltip

Chapter 5: Introduces Form Controls

Also introduces concept of ARIA descriptions and ARIA hidden elements.

Textbox

Radio Buttons

Customised Radio Buttons

Select

Customised Select

Form Reset

Form Submit

Textbox Icons

Floating Labels

Checkbox

Customised Checkbox

Field Description

Chapter 6: Introduces Form Validation

Also introduces concept of ARIA live regions and client-side rendering.

Required Field

Page Error

Field Error

Dynamic Field Error

Dynamic Page Error

Chapter 7: Introduces ARIA Widgets

Also introduces concept of widget keyboard navigation.

Menu

Dialog

Tabs

Combobox

Date Picker

Chapter 8: Introduces Data Tables

Data Tables

Interactive Data Tables

Row Select/Actions

Bulk Select

            Copyright © 1995-2017 eBay Inc. All Rights Reserved.


text:
layout: page
title: Ho Industries Party
date: 2016-05-24
author: Deborah Waller
tags: weekly links, java
status: published
summary: Integer cursus ac mauris suscipit tempor.
banner: images/banner/leisure-01.jpg
booking:
  startDate: 05/21/2017
  endDate: 05/26/2017
  ctyhocn: AUSRKHX
  groupCode: HIP
published: true
---
Nunc lectus nisi, ornare sit amet sapien nec, blandit rutrum orci. Suspendisse id ex varius, efficitur urna et, scelerisque massa. Sed nunc tellus, pretium quis orci at, convallis feugiat eros. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. In posuere nulla non quam faucibus ullamcorper. Phasellus sodales non ligula vitae interdum. Donec nec lectus sed nisl blandit posuere. Phasellus sit amet tellus orci. Maecenas rutrum sodales augue, nec finibus justo. Nunc condimentum venenatis viverra. Curabitur semper consequat sapien, id posuere neque.

* Vestibulum gravida nisl quis cursus fermentum
* Praesent sed orci et enim ullamcorper feugiat id a odio
* Cras quis tellus varius, congue risus sit amet, pretium diam
* Aliquam a quam a tortor sodales ultrices eget et leo
* Praesent at nibh consequat, interdum ex quis, tempor ex.

Morbi maximus auctor felis id molestie. Proin laoreet rutrum egestas. Pellentesque luctus lorem vitae porta euismod. Maecenas eleifend magna non elit eleifend porttitor. Aenean volutpat lobortis elit. Pellentesque rutrum suscipit iaculis. Integer auctor pulvinar dapibus. Curabitur commodo sollicitudin facilisis. Nulla euismod sapien a lacus blandit bibendum. Nunc et rhoncus purus, eget semper dolor. Duis eget blandit odio. Duis dictum massa quis metus luctus, non ornare mauris vehicula. Etiam tempus ullamcorper nulla eget vulputate. Fusce interdum erat vel dolor consectetur, aliquam scelerisque arcu pulvinar. Cras hendrerit efficitur sagittis. Fusce porttitor mauris eget erat imperdiet volutpat et at sem.


text:
'use strict';

import type EmitterSubscription from 'EmitterSubscription';
import type EventEmitter from 'EventEmitter';
import type EventHolder from 'EventHolder';

/**
 * @class EventEmitterWithHolding
 * @description
 * An EventEmitterWithHolding decorates an event emitter and enables one to
 * "hold" or cache events and then have a handler register later to actually
 * handle them.
 *
 * This is separated into its own decorator so that only those who want to use
 * the holding functionality have to and others can just use an emitter. Since
 * it implements the emitter interface it can also be combined with anything
 * that uses an emitter.
 */
class EventEmitterWithHolding {

  _emitter: EventEmitter;
  _eventHolder: EventHolder;
  _currentEventToken: ?Object;
  _emittingHeldEvents: boolean;

  /**
   * @constructor
   * @param {object} emitter - The object responsible for emitting the actual
   *   events.
   * @param {object} holder - The event holder that is responsible for holding
   *   and then emitting held events.
   */
  constructor(emitter: EventEmitter, holder: EventHolder) {
    this._emitter = emitter;
    this._eventHolder = holder;
    this._currentEventToken = null;
    this._emittingHeldEvents = false;
  }

  /**
   * @see EventEmitter#addListener
   */
  addListener(eventType: string, listener: Function, context: ?Object) {
    return this._emitter.addListener(eventType, listener, context);
  }

  /**
   * @see EventEmitter#once
   */
  once(eventType: string, listener: Function, context: ?Object) {
    return this._emitter.once(eventType, listener, context);
  }

  /**
   * Adds a listener to be invoked when events of the specified type are
   * emitted. An optional calling context may be provided. The data arguments
   * emitted will be passed to the listener function. In addition to subscribing
   * to all subsequent events, this method will also handle any events that have
   * already been emitted, held, and not released.
   *
   * @param {string} eventType - Name of the event to listen to
   * @param {function} listener - Function to invoke when the specified event is
   *   emitted
   * @param {*} context - Optional context object to use when invoking the
   *   listener
   *
   * @example
   *   emitter.emitAndHold('someEvent', 'abc');
   *
   *   emitter.addRetroactiveListener('someEvent', function(message) {
   *     console.log(message);
   *   }); // logs 'abc'
   */
  addRetroactiveListener(
    eventType: string, listener: Function, context: ?Object): EmitterSubscription {
    const subscription = this._emitter.addListener(eventType, listener, context);

    this._emittingHeldEvents = true;
    this._eventHolder.emitToListener(eventType, listener, context);
    this._emittingHeldEvents = false;

    return subscription;
  }

  /**
   * @see EventEmitter#removeAllListeners
   */
  removeAllListeners(eventType: string) {
    this._emitter.removeAllListeners(eventType);
  }

  /**
   * @see EventEmitter#removeCurrentListener
   */
  removeCurrentListener() {
    this._emitter.removeCurrentListener();
  }

  /**
   * @see EventEmitter#listeners
   */
  listeners(eventType: string) /* TODO: Annotate return type here */ {
    return this._emitter.listeners(eventType);
  }

  /**
   * @see EventEmitter#emit
   */
  emit(eventType: string, ...args: any) {
    this._emitter.emit(eventType, ...args);
  }

  /**
   * Emits an event of the given type with the given data, and holds that event
   * in order to be able to dispatch it to a later subscriber when they say they
   * want to handle held events.
   *
   * @param {string} eventType - Name of the event to emit
   * @param {...*} Arbitrary arguments to be passed to each registered listener
   *
   * @example
   *   emitter.emitAndHold('someEvent', 'abc');
   *
   *   emitter.addRetroactiveListener('someEvent', function(message) {
   *     console.log(message);
   *   }); // logs 'abc'
   */
  emitAndHold(eventType: string, ...args: any) {
    this._currentEventToken = this._eventHolder.holdEvent(eventType, ...args);
    this._emitter.emit(eventType, ...args);
    this._currentEventToken = null;
  }

  /**
   * @see EventHolder#releaseCurrentEvent
   */
  releaseCurrentEvent() {
    if (this._currentEventToken) {
      this._eventHolder.releaseEvent(this._currentEventToken);
    } else if (this._emittingHeldEvents) {
      this._eventHolder.releaseCurrentEvent();
    }
  }

  /**
   * @see EventHolder#releaseEventType
   * @param {string} eventType
   */
  releaseHeldEventType(eventType: string) {
    this._eventHolder.releaseEventType(eventType);
  }
}

module.exports = EventEmitterWithHolding;


text:
<?php

declare(strict_types=1);

/*
 * This file is part of PHP CS Fixer.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace PhpCsFixer\Tests\AutoReview;

use PhpCsFixer\Documentation\DocumentationLocator;
use PhpCsFixer\Documentation\FixerDocumentGenerator;
use PhpCsFixer\Documentation\ListDocumentGenerator;
use PhpCsFixer\Documentation\RuleSetDocumentationGenerator;
use PhpCsFixer\Fixer\FixerInterface;
use PhpCsFixer\FixerFactory;
use PhpCsFixer\RuleSet\RuleSets;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Finder\Finder;

/**
 * @internal
 *
 * @covers \PhpCsFixer\Documentation\DocumentationLocator
 * @covers \PhpCsFixer\Documentation\FixerDocumentGenerator
 * @covers \PhpCsFixer\Documentation\ListDocumentGenerator
 * @covers \PhpCsFixer\Documentation\RstUtils
 * @covers \PhpCsFixer\Documentation\RuleSetDocumentationGenerator
 *
 * @group auto-review
 * @requires PHP 7.3
 */
final class DocumentationTest extends TestCase
{
    /**
     * @dataProvider provideFixerCases
     */
    public function testFixerDocumentationFileIsUpToDate(FixerInterface $fixer): void
    {
        $locator = new DocumentationLocator();
        $generator = new FixerDocumentGenerator($locator);

        $path = $locator->getFixerDocumentationFilePath($fixer);

        static::assertFileExists($path);

        $expected = $generator->generateFixerDocumentation($fixer);
        $actual = file_get_contents($path);

        $expected = preg_replace_callback(
            '/
                # an example
                (?<before>
                    Example\ \#\d\n
                    ~+\n
                    \n
                    (?:\*Default\*\ configuration\.\n\n)?
                    (?:With\ configuration:.*?\n\n)?
                )
                # with a diff that could not be generated
                \.\.\ error::\n
                \ \ \ Cannot\ generate\ diff\ for\ code\ sample\ \#\d\ of\ rule\ .+?:\n
                \ \ \ the\ sample\ is\ not\ suitable\ for\ current\ version\ of\ PHP\ \(.+?\).\n
                # followed by another title or end of file
                (?<after>
                    \n
                    [^ \n].*?
                    \n
                    |$
                )
            /x',
            static function (array $matches) use ($actual): string {
                $before = preg_quote($matches['before'], '/');
                $after = preg_quote($matches['after'], '/');

                $replacement = '[UNAVAILABLE EXAMPLE DIFF]';

                if (1 === preg_match("/{$before}(\\.\\. code-block:: diff.*?){$after}/s", $actual, $actualMatches)) {
                    $replacement = $actualMatches[1];
                }

                return $matches[1].$replacement.$matches[2];
            },
            $expected
        );

        static::assertSame($expected, $actual);
    }

    public function provideFixerCases(): \Generator
    {
        foreach ($this->getFixers() as $fixer) {
            yield $fixer->getName() => [$fixer];
        }
    }

    public function testFixersDocumentationIndexFileIsUpToDate(): void
    {
        $locator = new DocumentationLocator();
        $generator = new FixerDocumentGenerator($locator);

        self::assertFileEqualsString(
            $generator->generateFixersDocumentationIndex($this->getFixers()),
            $locator->getFixersDocumentationIndexFilePath()
        );
    }

    public function testFixersDocumentationDirectoryHasNoExtraFiles(): void
    {
        $generator = new DocumentationLocator();

        static::assertCount(
            \count($this->getFixers()) + 1,
            (new Finder())->files()->in($generator->getFixersDocumentationDirectoryPath())
        );
    }

    /**
     * @requires PHP 7.4
     */
    public function testRuleSetsDocumentationIsUpToDate(): void
    {
        $locator = new DocumentationLocator();
        $generator = new RuleSetDocumentationGenerator($locator);

        $fixers = $this->getFixers();
        $paths = [];

        foreach (RuleSets::getSetDefinitions() as $name => $definition) {
            $paths[$name] = $path = $locator->getRuleSetsDocumentationFilePath($name);

            static::assertFileEqualsString(
                $generator->generateRuleSetsDocumentation($definition, $fixers),
                $path,
                sprintf('RuleSet documentation is generated (please see CONTRIBUTING.md), file "%s".', $path)
            );
        }

        $indexFilePath = $locator->getRuleSetsDocumentationIndexFilePath();

        static::assertFileEqualsString(
            $generator->generateRuleSetsDocumentationIndex($paths),
            $indexFilePath,
            sprintf('RuleSet documentation is generated (please CONTRIBUTING.md), file "%s".', $indexFilePath)
        );
    }

    /**
     * @requires PHP 7.4
     */
    public function testRuleSetsDocumentationDirectoryHasNoExtraFiles(): void
    {
        $generator = new DocumentationLocator();

        static::assertCount(
            \count(RuleSets::getSetDefinitions()) + 1,
            (new Finder())->files()->in($generator->getRuleSetsDocumentationDirectoryPath())
        );
    }

    public function testInstallationDocHasCorrectMinimumVersion(): void
    {
        $composerJsonContent = file_get_contents(__DIR__.'/../../composer.json');
        $composerJson = json_decode($composerJsonContent, true);
        $phpVersion = $composerJson['require']['php'];
        $minimumVersion = ltrim(substr($phpVersion, 0, strpos($phpVersion, ' ')), '^');

        $minimumVersionInformation = sprintf('PHP needs to be a minimum version of PHP %s.', $minimumVersion);
        $installationDocPath = realpath(__DIR__.'/../../doc/installation.rst');

        static::assertStringContainsString(
            $minimumVersionInformation,
            file_get_contents($installationDocPath),
            sprintf('Files %s needs to contain information "%s"', $installationDocPath, $minimumVersionInformation)
        );
    }

    /**
     * @requires PHP 7.4
     */
    public function testListingDocumentationIsUpToDate(): void
    {
        $locator = new DocumentationLocator();
        $generator = new ListDocumentGenerator($locator);

        $fixers = $this->getFixers();
        $listingFilePath = $locator->getListingFilePath();

        static::assertFileEqualsString(
            $generator->generateListingDocumentation($fixers),
            $listingFilePath,
            sprintf('Listing documentation is generated (please CONTRIBUTING.md), file "%s".', $listingFilePath)
        );
    }

    private static function assertFileEqualsString(string $expectedString, string $actualFilePath, string $message = ''): void
    {
        static::assertFileExists($actualFilePath, $message);
        static::assertSame($expectedString, file_get_contents($actualFilePath), $message);
    }

    private function getFixers(): array
    {
        $factory = new FixerFactory();
        $factory->registerBuiltInFixers();

        return $factory->getFixers();
    }
}


text:
require 'test_helper'

class PlatronNotificationTest < Test::Unit::TestCase
  include ActiveMerchant::Billing::Integrations

  def setup
    @correct_notification = Platron::Notification.new(http_raw_data_with_correct_signature,:secret=>'secret',:path=>'result')
    @notification_with_wrong_signature= Platron::Notification.new(http_raw_data_with_wrong_signature,:secret=>'secret',:path=>'result')
  end

  def test_accessors
    assert_equal '111', @correct_notification.order_id
    assert_equal '1023', @correct_notification.platron_payment_id
    assert_equal 'USD', @correct_notification.currency
    assert_equal '2013-01-02 10:14:20', @correct_notification.payment_date
    assert_equal '1', @correct_notification.complete?
    assert_equal 'Visa', @correct_notification.payment_system
    assert_equal 'VI', @correct_notification.card_brand
    assert_equal '990',@correct_notification.amount
  end

  def test_acknowledgement
    assert_equal @correct_notification.acknowledge,true
    assert_equal @notification_with_wrong_signature.acknowledge,false
  end

  def test_respond_to_acknowledge
    assert @correct_notification.respond_to?(:acknowledge)
  end

  def test_success_response
    xml_response=@correct_notification.success_response('result','secret')

    assert_nothing_raised do
       hash= Hash.from_xml(xml_response)
       assert_equal hash['response']['pg_status'],'ok'
       sign=Digest::MD5.hexdigest(['result',{:pg_status=>'ok',:pg_salt=>hash['response']['pg_salt']}.with_indifferent_access.sort.map{|ar|ar[1]},'secret'].join(';'))
       assert_equal hash['response']['pg_sig'],sign
    end

  end

  private

  def test_response_params
    {
       :pg_result=>'1',:pg_order_id=>'111',:pg_payment_id=>'1023',:pg_amount=>'990',:pg_ps_currency=>'USD',
       :pg_payment_system=>'Visa',:pg_payment_date=>'2013-01-02 10:14:20',:pg_card_brand=>'VI',:pg_overpayment=>'0',
       :pg_salt=>'vfw87rb2vwevhj'
    }
  end

  def http_raw_data_with_correct_signature
    pg_sig= Digest::MD5.hexdigest(['result',test_response_params.with_indifferent_access.sort.map{|ar|ar[1]},'secret'].join(';'))
    test_response_params.merge({:pg_sig=>pg_sig}).to_param
  end

  def http_raw_data_with_wrong_signature
    pg_sig= 'wrong signature'
    test_response_params.merge({:pg_sig=>pg_sig}).to_param
  end

end


text:
namespace v8 {
namespace internal {
namespace compiler {

// Macro for outputting trace information from representation inference.
#define TRACE(...)                                  \
  do {                                              \
    if (FLAG_trace_turbo_loop) PrintF(__VA_ARGS__); \
  } while (false)

LoopVariableOptimizer::LoopVariableOptimizer(Graph* graph,
                                             CommonOperatorBuilder* common,
                                             Zone* zone)
    : graph_(graph),
      common_(common),
      zone_(zone),
      limits_(graph->NodeCount(), zone),
      induction_vars_(zone) {}

void LoopVariableOptimizer::Run() {
  ZoneQueue<Node*> queue(zone());
  queue.push(graph()->start());
  NodeMarker<bool> queued(graph(), 2);
  while (!queue.empty()) {
    Node* node = queue.front();
    queue.pop();
    queued.Set(node, false);

    DCHECK_NULL(limits_[node->id()]);
    bool all_inputs_visited = true;
    int inputs_end = (node->opcode() == IrOpcode::kLoop)
                         ? kFirstBackedge
                         : node->op()->ControlInputCount();
    for (int i = 0; i < inputs_end; i++) {
      if (limits_[NodeProperties::GetControlInput(node, i)->id()] == nullptr) {
        all_inputs_visited = false;
        break;
      }
    }
    if (!all_inputs_visited) continue;

    VisitNode(node);
    DCHECK_NOT_NULL(limits_[node->id()]);

    // Queue control outputs.
    for (Edge edge : node->use_edges()) {
      if (NodeProperties::IsControlEdge(edge) &&
          edge.from()->op()->ControlOutputCount() > 0) {
        Node* use = edge.from();
        if (use->opcode() == IrOpcode::kLoop &&
            edge.index() != kAssumedLoopEntryIndex) {
          VisitBackedge(node, use);
        } else if (!queued.Get(use)) {
          queue.push(use);
          queued.Set(use, true);
        }
      }
    }
  }
}

class LoopVariableOptimizer::Constraint : public ZoneObject {
 public:
  InductionVariable::ConstraintKind kind() const { return kind_; }
  Node* left() const { return left_; }
  Node* right() const { return right_; }

  const Constraint* next() const { return next_; }

  Constraint(Node* left, InductionVariable::ConstraintKind kind, Node* right,
             const Constraint* next)
      : left_(left), right_(right), kind_(kind), next_(next) {}

 private:
  Node* left_;
  Node* right_;
  InductionVariable::ConstraintKind kind_;
  const Constraint* next_;
};

class LoopVariableOptimizer::VariableLimits : public ZoneObject {
 public:
  static VariableLimits* Empty(Zone* zone) {
    return new (zone) VariableLimits();
  }

  VariableLimits* Copy(Zone* zone) const {
    return new (zone) VariableLimits(this);
  }

  void Add(Node* left, InductionVariable::ConstraintKind kind, Node* right,
           Zone* zone) {
    head_ = new (zone) Constraint(left, kind, right, head_);
    limit_count_++;
  }

  void Merge(const VariableLimits* other) {
    // Change the current condition list to a longest common tail
    // of this condition list and the other list. (The common tail
    // should correspond to the list from the common dominator.)

    // First, we throw away the prefix of the longer list, so that
    // we have lists of the same length.
    size_t other_size = other->limit_count_;
    const Constraint* other_limit = other->head_;
    while (other_size > limit_count_) {
      other_limit = other_limit->next();
      other_size--;
    }
    while (limit_count_ > other_size) {
      head_ = head_->next();
      limit_count_--;
    }

    // Then we go through both lists in lock-step until we find
    // the common tail.
    while (head_ != other_limit) {
      DCHECK(limit_count_ > 0);
      limit_count_--;
      other_limit = other_limit->next();
      head_ = head_->next();
    }
  }

  const Constraint* head() const { return head_; }

 private:
  VariableLimits() {}
  explicit VariableLimits(const VariableLimits* other)
      : head_(other->head_), limit_count_(other->limit_count_) {}

  const Constraint* head_ = nullptr;
  size_t limit_count_ = 0;
};

void InductionVariable::AddUpperBound(Node* bound,
                                      InductionVariable::ConstraintKind kind) {
  if (FLAG_trace_turbo_loop) {
    OFStream os(stdout);
    os << "New upper bound for " << phi()->id() << " (loop "
       << NodeProperties::GetControlInput(phi())->id() << "): " << *bound
       << std::endl;
  }
  upper_bounds_.push_back(Bound(bound, kind));
}

void InductionVariable::AddLowerBound(Node* bound,
                                      InductionVariable::ConstraintKind kind) {
  if (FLAG_trace_turbo_loop) {
    OFStream os(stdout);
    os << "New lower bound for " << phi()->id() << " (loop "
       << NodeProperties::GetControlInput(phi())->id() << "): " << *bound;
  }
  lower_bounds_.push_back(Bound(bound, kind));
}

void LoopVariableOptimizer::VisitBackedge(Node* from, Node* loop) {
  if (loop->op()->ControlInputCount() != 2) return;

  // Go through the constraints, and update the induction variables in
  // this loop if they are involved in the constraint.
  const VariableLimits* limits = limits_[from->id()];
  for (const Constraint* constraint = limits->head(); constraint != nullptr;
       constraint = constraint->next()) {
    if (constraint->left()->opcode() == IrOpcode::kPhi &&
        NodeProperties::GetControlInput(constraint->left()) == loop) {
      auto var = induction_vars_.find(constraint->left()->id());
      if (var != induction_vars_.end()) {
        var->second->AddUpperBound(constraint->right(), constraint->kind());
      }
    }
    if (constraint->right()->opcode() == IrOpcode::kPhi &&
        NodeProperties::GetControlInput(constraint->right()) == loop) {
      auto var = induction_vars_.find(constraint->right()->id());
      if (var != induction_vars_.end()) {
        var->second->AddLowerBound(constraint->left(), constraint->kind());
      }
    }
  }
}

void LoopVariableOptimizer::VisitNode(Node* node) {
  switch (node->opcode()) {
    case IrOpcode::kMerge:
      return VisitMerge(node);
    case IrOpcode::kLoop:
      return VisitLoop(node);
    case IrOpcode::kIfFalse:
      return VisitIf(node, false);
    case IrOpcode::kIfTrue:
      return VisitIf(node, true);
    case IrOpcode::kStart:
      return VisitStart(node);
    case IrOpcode::kLoopExit:
      return VisitLoopExit(node);
    default:
      return VisitOtherControl(node);
  }
}

void LoopVariableOptimizer::VisitMerge(Node* node) {
  // Merge the limits of all incoming edges.
  VariableLimits* merged = limits_[node->InputAt(0)->id()]->Copy(zone());
  for (int i = 1; i < node->InputCount(); i++) {
    merged->Merge(limits_[node->InputAt(i)->id()]);
  }
  limits_[node->id()] = merged;
}

void LoopVariableOptimizer::VisitLoop(Node* node) {
  DetectInductionVariables(node);
  // Conservatively take the limits from the loop entry here.
  return TakeConditionsFromFirstControl(node);
}

void LoopVariableOptimizer::VisitIf(Node* node, bool polarity) {
  Node* branch = node->InputAt(0);
  Node* cond = branch->InputAt(0);
  VariableLimits* limits = limits_[branch->id()]->Copy(zone());
  // Normalize to less than comparison.
  switch (cond->opcode()) {
    case IrOpcode::kJSLessThan:
    case IrOpcode::kSpeculativeNumberLessThan:
      AddCmpToLimits(limits, cond, InductionVariable::kStrict, polarity);
      break;
    case IrOpcode::kJSGreaterThan:
      AddCmpToLimits(limits, cond, InductionVariable::kNonStrict, !polarity);
      break;
    case IrOpcode::kJSLessThanOrEqual:
    case IrOpcode::kSpeculativeNumberLessThanOrEqual:
      AddCmpToLimits(limits, cond, InductionVariable::kNonStrict, polarity);
      break;
    case IrOpcode::kJSGreaterThanOrEqual:
      AddCmpToLimits(limits, cond, InductionVariable::kStrict, !polarity);
      break;
    default:
      break;
  }
  limits_[node->id()] = limits;
}

void LoopVariableOptimizer::AddCmpToLimits(
    VariableLimits* limits, Node* node, InductionVariable::ConstraintKind kind,
    bool polarity) {
  Node* left = node->InputAt(0);
  Node* right = node->InputAt(1);
  if (FindInductionVariable(left) || FindInductionVariable(right)) {
    if (polarity) {
      limits->Add(left, kind, right, zone());
    } else {
      kind = (kind == InductionVariable::kStrict)
                 ? InductionVariable::kNonStrict
                 : InductionVariable::kStrict;
      limits->Add(right, kind, left, zone());
    }
  }
}

void LoopVariableOptimizer::VisitStart(Node* node) {
  limits_[node->id()] = VariableLimits::Empty(zone());
}

void LoopVariableOptimizer::VisitLoopExit(Node* node) {
  return TakeConditionsFromFirstControl(node);
}

void LoopVariableOptimizer::VisitOtherControl(Node* node) {
  DCHECK_EQ(1, node->op()->ControlInputCount());
  return TakeConditionsFromFirstControl(node);
}

void LoopVariableOptimizer::TakeConditionsFromFirstControl(Node* node) {
  const VariableLimits* limits =
      limits_[NodeProperties::GetControlInput(node, 0)->id()];
  DCHECK_NOT_NULL(limits);
  limits_[node->id()] = limits;
}

const InductionVariable* LoopVariableOptimizer::FindInductionVariable(
    Node* node) {
  auto var = induction_vars_.find(node->id());
  if (var != induction_vars_.end()) {
    return var->second;
  }
  return nullptr;
}

InductionVariable* LoopVariableOptimizer::TryGetInductionVariable(Node* phi) {
  DCHECK_EQ(2, phi->op()->ValueInputCount());
  DCHECK_EQ(IrOpcode::kLoop, NodeProperties::GetControlInput(phi)->opcode());
  Node* initial = phi->InputAt(0);
  Node* arith = phi->InputAt(1);
  InductionVariable::ArithmeticType arithmeticType;
  if (arith->opcode() == IrOpcode::kJSAdd ||
      arith->opcode() == IrOpcode::kSpeculativeNumberAdd) {
    arithmeticType = InductionVariable::ArithmeticType::kAddition;
  } else if (arith->opcode() == IrOpcode::kJSSubtract ||
             arith->opcode() == IrOpcode::kSpeculativeNumberSubtract) {
    arithmeticType = InductionVariable::ArithmeticType::kSubtraction;
  } else {
    return nullptr;
  }

  // TODO(jarin) Support both sides.
  if (arith->InputAt(0) != phi) {
    if ((arith->InputAt(0)->opcode() != IrOpcode::kJSToNumber &&
         arith->InputAt(0)->opcode() != IrOpcode::kSpeculativeToNumber) ||
        arith->InputAt(0)->InputAt(0) != phi) {
      return nullptr;
    }
  }
  Node* incr = arith->InputAt(1);
  return new (zone())
      InductionVariable(phi, arith, incr, initial, zone(), arithmeticType);
}

void LoopVariableOptimizer::DetectInductionVariables(Node* loop) {
  if (loop->op()->ControlInputCount() != 2) return;
  TRACE("Loop variables for loop %i:", loop->id());
  for (Edge edge : loop->use_edges()) {
    if (NodeProperties::IsControlEdge(edge) &&
        edge.from()->opcode() == IrOpcode::kPhi) {
      Node* phi = edge.from();
      InductionVariable* induction_var = TryGetInductionVariable(phi);
      if (induction_var) {
        induction_vars_[phi->id()] = induction_var;
        TRACE(" %i", induction_var->phi()->id());
      }
    }
  }
  TRACE("\n");
}

void LoopVariableOptimizer::ChangeToInductionVariablePhis() {
  for (auto entry : induction_vars_) {
    // It only make sense to analyze the induction variables if
    // there is a bound.
    InductionVariable* induction_var = entry.second;
    DCHECK_EQ(MachineRepresentation::kTagged,
              PhiRepresentationOf(induction_var->phi()->op()));
    if (induction_var->upper_bounds().size() == 0 &&
        induction_var->lower_bounds().size() == 0) {
      continue;
    }
    // Insert the increment value to the value inputs.
    induction_var->phi()->InsertInput(graph()->zone(),
                                      induction_var->phi()->InputCount() - 1,
                                      induction_var->increment());
    // Insert the bound inputs to the value inputs.
    for (auto bound : induction_var->lower_bounds()) {
      induction_var->phi()->InsertInput(
          graph()->zone(), induction_var->phi()->InputCount() - 1, bound.bound);
    }
    for (auto bound : induction_var->upper_bounds()) {
      induction_var->phi()->InsertInput(
          graph()->zone(), induction_var->phi()->InputCount() - 1, bound.bound);
    }
    NodeProperties::ChangeOp(
        induction_var->phi(),
        common()->InductionVariablePhi(induction_var->phi()->InputCount() - 1));
  }
}

void LoopVariableOptimizer::ChangeToPhisAndInsertGuards() {
  for (auto entry : induction_vars_) {
    InductionVariable* induction_var = entry.second;
    if (induction_var->phi()->opcode() == IrOpcode::kInductionVariablePhi) {
      // Turn the induction variable phi back to normal phi.
      int value_count = 2;
      Node* control = NodeProperties::GetControlInput(induction_var->phi());
      DCHECK_EQ(value_count, control->op()->ControlInputCount());
      induction_var->phi()->TrimInputCount(value_count + 1);
      induction_var->phi()->ReplaceInput(value_count, control);
      NodeProperties::ChangeOp(
          induction_var->phi(),
          common()->Phi(MachineRepresentation::kTagged, value_count));

      // If the backedge is not a subtype of the phi's type, we insert a sigma
      // to get the typing right.
      Node* backedge_value = induction_var->phi()->InputAt(1);
      Type* backedge_type = NodeProperties::GetType(backedge_value);
      Type* phi_type = NodeProperties::GetType(induction_var->phi());
      if (!backedge_type->Is(phi_type)) {
        Node* backedge_control =
            NodeProperties::GetControlInput(induction_var->phi())->InputAt(1);
        Node* rename = graph()->NewNode(common()->TypeGuard(phi_type),
                                        backedge_value, backedge_control);
        induction_var->phi()->ReplaceInput(1, rename);
      }
    }
  }
}

}  // namespace compiler
}  // namespace internal
}  // namespace v8


text:
Meteor.methods({
  /*
   * Updates a Song
   *
   * @param {Song} song Song object to update (Astronomy class)
   * @return {Song} the saved song
   */
  '/songs/upvote': function(song) {
    check(song, Song)

    if(song.validate()) {
      var newVotes = song.votes + 1;
      Song.update({ _id: song._id }, {$set: {votes: newVotes}});
    } else {
      // Send errors back to the client
      song.throwValidationException();
    }
  },

  '/songs/downvote': function(song) {
    check(song, Song)

    if(song.validate()) {
      var newVotes = song.votes - 1;
      Song.update({ _id: song._id }, {$set: {votes: newVotes}});
    } else {
      // Send errors back to the client
      song.throwValidationException();
    }
  },

  '/songs/playnow': function(song) {
    check(song, Song)

    if(song.validate()) {
      Song.update({ _id: song._id }, {$set: {votes: 999}});
    } else {
      // Send errors back to the client
      song.throwValidationException();
    }
  } ,

  '/songs/currentlyPlaying': function(song) {
    check(song, Song);

    if (song.validate()) {
      Song.update({ _id: song._id }, {$set: {currentlyPlaying: true}})
    }
  }
});


text:
/* Function label symbol */

package ir.symboltable.symbols;

import ir.symboltable.*;
import ir.types.*;
import ir.types.c.Function;
import ir.types.c.IntegerScalar;
import ir.symboltable.ocl.KernelPrototype;

public class FunctionLabel extends Symbol implements CommonFunctionLabelInterface {

  //------------------------------
  // Private data
  //------------------------------

  // Function prototype or definition
  boolean is_function_definition = false;

  // Builtin information
  private boolean is_compiler_builtin_function = false;
  private boolean is_external_builtin_function = false;

  // Symbol to be mangled
  private boolean is_mangled_function = false;

  //------------------------------
  // OpenCL data
  //------------------------------
  private boolean is_kernel=false;
  private KernelPrototype kernel_prototype=null;
  // Attributes
  Type vec_type_hint=IntegerScalar.Tsint;
  int[] work_group_size_hint = new int[]{-1,-1,-1};
  int[] reqd_work_group_size = new int[]{-1,-1,-1};
  // Stack size management
  long stack_size=-1;

  //==================================================================
  // Constructors
  //==================================================================

  public FunctionLabel() {
    super();
  }

  public FunctionLabel(StorageClass sc) {
    super(sc);
  }

  public FunctionLabel(String name) {
    super(name);
  }

  public FunctionLabel(Symbol symb) {
    super(symb);
  }

  public FunctionLabel(FunctionLabel symb) {

    is_kernel		 = symb.is_kernel;

    // Builtin information
    is_compiler_builtin_function = symb.is_compiler_builtin_function;
    is_external_builtin_function = symb.is_external_builtin_function;

    // Mangling information
    is_mangled_function	 = symb.is_mangled_function;
  }

  //==================================================================
  // Def/proto management
  //==================================================================

  // Setting
  public void setDefinition() {
     is_function_definition=true;
  }
  public void setPrototype() {
     is_function_definition=false;
  }

  // Query
  public boolean isDefinition() {
    return is_function_definition;
  }
  public boolean isPrototype() {
    return !is_function_definition;
  }

  //------------------------------------------------------------------
  // isCompileTimeKnown
  //
  // The address of a function definition/prototype is always known
  //
  // whose address is compile time known
  // Note: concerns only data objects and functions
  //------------------------------------------------------------------
  public boolean referencesCompileTimeAllocatedEntity() {
    return true;
  }

  //==================================================================
  // Symbol regeneration
  //==================================================================

  //------------------------------------------------------------------
  // getOutputName
  //
  // Returns the symbol name for the output source file. It performs
  // mangling if necessary
  //------------------------------------------------------------------
  public String getOutputName() {
    String output=getName();
    if (isMangledFunction()) {
      // Only functions are mangled
      return "_Z"+output.length()+output+((Function)getType()).getSignatureForMangling();
    }
    else {
      return output;
    }
  }

  //==================================================================
  // Builtin management
  //==================================================================

  // Setting
  public void setCompilerBuiltinFunction() {
     is_compiler_builtin_function=true;
  }
  public void setExternalBuiltinFunction() {
     is_external_builtin_function=true;
  }

  // Query
  public boolean isCompilerBuiltinFunction() {
    return is_compiler_builtin_function;
  }
  public boolean isExternalBuiltinFunction() {
    return is_external_builtin_function;
  }

  //==================================================================
  // Mangling management
  //==================================================================

  // Set a symbol as mangled
  public void setMangledFunction() {
     is_mangled_function=true;
  }

  // Query if the symbol is mangled
  public boolean isMangledFunction() {
    return is_mangled_function;
  }

  //==================================================================
  // Kernel management: OCL specific
  //==================================================================

  // Setting
  public void setKernel() {
     is_kernel=true;
  }
  public void setKernelPrototype(KernelPrototype kp) {
    kernel_prototype=kp;
  }

  // Query
  public boolean isKernel() {
    return is_kernel;
  }
  public KernelPrototype getKernelPrototype() {
    return kernel_prototype;
  }

  // Attribute setters
  public void setAttribute_vec_type_hint(Type t) {
    vec_type_hint=t;
  }
  public void setAttribute_work_group_size_hint(int d0, int d1, int d2) {
    work_group_size_hint[0]=d0;
    work_group_size_hint[1]=d1;
    work_group_size_hint[2]=d2;
  }
  public void setAttribute_reqd_work_group_size(int d0, int d1, int d2) {
    reqd_work_group_size[0]=d0;
    reqd_work_group_size[1]=d1;
    reqd_work_group_size[2]=d2;
  }
//   public void setAttribute_reqd_max_work_group_elements(int n) {
//       reqd_max_work_group_elements=n;
//   }
  public void setAttribute_stack_size(long s) {
      stack_size=s;
  }

  // Attribute getters
  public Type getAttribute_vec_type_hint() {
    return vec_type_hint;
  }
  public int getAttribute_work_group_size_hint(int dim) {
    return work_group_size_hint[dim];
  }
  public int getAttribute_reqd_work_group_size(int dim) {
    return reqd_work_group_size[dim];
  }
//   public long getAttribute_reqd_max_work_group_elements() {
//       return reqd_max_work_group_elements;
//   }
  public long getAttribute_stack_size() {
      return stack_size;
  }

  //==================================================================
  // Verbosing
  //==================================================================

  //------------------------------------------------------------------
  // getMessageName:
  //
  // Return the symbol reference name as i should appear in a message
  // or error
  //------------------------------------------------------------------
  public String getMessageName() {
    return "function '"+ getName() +"'";
  }

  //------------------------------------------------------------------
  // toString:
  //
  // Dump the symbol to a string
  //------------------------------------------------------------------
  public String toString() {
    StringBuffer buff = new StringBuffer();

    buff.append(super.toString());

    // Standard symbol
    if (isCompilerBuiltinFunction()) {
      buff.append("[builtin]");
    }
    if (isExternalBuiltinFunction()) {
      buff.append("[ext builtin]");
    }
    if (isMangledFunction()) {
      buff.append("[mangled]");
    }

    // Return the final string
    return buff.toString();
  }
}


text:
<?php

namespace Moss\Storage\Query;

use Moss\Storage\GetTypeTrait;
use Moss\Storage\Model\Definition\FieldInterface;

/**
 * Query used to read data from table
 *
 * @author  Michal Wachowski <wachowski.michal@gmail.com>
 * @package Moss\Storage
 */
class WriteQuery extends AbstractEntityValueQuery implements WriteQueryInterface
{
    const EVENT_BEFORE = 'write.before';
    const EVENT_AFTER = 'write.after';

    use GetTypeTrait;

    protected $instance;

    protected $values = [];

    /**
     * Sets field names which values will be written
     *
     * @param array $fields
     *
     * @return $this
     */
    public function values($fields = [])
    {
        $this->values = [];

        if (empty($fields)) {
            foreach ($this->model->fields() as $field) {
                $this->assignValue($field);
            }

            return $this;
        }

        foreach ($fields as $field) {
            $this->assignValue($this->model->field($field));
        }

        return $this;
    }

    /**
     * Adds field which value will be written
     *
     * @param string $field
     *
     * @return $this
     */
    public function value($field)
    {
        $this->assignValue($this->model->field($field));

        return $this;
    }

    /**
     * Assigns value to query
     *
     * @param FieldInterface $field
     */
    protected function assignValue(FieldInterface $field)
    {
        $this->values[] = $field->name();
    }

    /**
     * Executes query
     * After execution query is reset
     *
     * @return mixed
     */
    public function execute()
    {
        $this->dispatcher->fire(self::EVENT_BEFORE, $this->instance);

        $this->buildQuery()
            ->execute();

        $this->dispatcher->fire(self::EVENT_AFTER, $this->instance);

        foreach ($this->relations as $relation) {
            $relation->write($this->instance);
        }

        return $this->instance;
    }

    /**
     * Returns current query string
     *
     * @return string
     */
    public function getSQL()
    {
        return $this->buildQuery()->getSQL();
    }

    /**
     * @return InsertQuery|UpdateQuery
     */
    protected function buildQuery()
    {
        if ($this->checkIfEntityExists()) {
            $query = new UpdateQuery($this->connection, $this->instance, $this->model, $this->factory, $this->accessor, $this->dispatcher);
        } else {
            $query = new InsertQuery($this->connection, $this->instance, $this->model, $this->factory, $this->accessor, $this->dispatcher);
        }

        $query->values($this->values);

        return $query;
    }

    /**
     * Returns true if entity exists database
     *
     * @return int
     */
    protected function checkIfEntityExists()
    {
        $query = new ReadQuery($this->connection, $this->model, $this->factory, $this->accessor, $this->dispatcher);

        foreach ($this->model->primaryFields() as $field) {
            $value = $this->accessor->getPropertyValue($this->instance, $field->name());

            if ($value === null) {
                return false;
            }

            $query->where($field->name(), $value, '=', 'and');
        }

        return $query->count() > 0;
    }

    /**
     * Returns array with bound values and their placeholders as keys
     *
     * @return array
     */
    public function binds()
    {
        return [];
    }

    /**
     * Resets adapter
     *
     * @return $this
     */
    public function reset()
    {
        $this->values = [];
        $this->relations = [];

        return $this;
    }
}