<commit_before>/* descriptor.cpp

Copyright (c) 2015, Nikolaj Schlej. All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution.  The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php

THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHWARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
*/

#include "descriptor.h"

// Calculate address of data structure addressed by descriptor address format
// 8 bit base or limit
const UINT8* calculateAddress8(const UINT8* baseAddress, const UINT8 baseOrLimit)
{
    return baseAddress + baseOrLimit * 0x10;
}

// 16 bit base or limit
const UINT8* calculateAddress16(const UINT8* baseAddress, const UINT16 baseOrLimit)
{
    return baseAddress + baseOrLimit * 0x1000;
}

// Calculate offset of region using its base
UINT32 calculateRegionOffset(const UINT16 base)
{
    return base * 0x1000;
}

//Calculate size of region using its base and limit
UINT32 calculateRegionSize(const UINT16 base, const UINT16 limit)
{
    if (limit)
        return (limit + 1 - base) * 0x1000;
    return 0;
}

// Return human-readable chip name for given JEDEC ID
UString jedecIdToUString(UINT8 vendorId, UINT8 deviceId0, UINT8 deviceId1)
{
    UINT32 jedecId = (UINT32)deviceId1 + ((UINT32)deviceId0 << 8) + ((UINT32)vendorId << 16);
    switch (jedecId) {
    // Winbond
    case 0xEF3013: return UString("Winbond W25X40");
    case 0xEF3014: return UString("Winbond W25X80");
    case 0xEF3015: return UString("Winbond W25X16");
    case 0xEF3016: return UString("Winbond W25X32");
    case 0xEF3017: return UString("Winbond W25X64");
    case 0xEF4013: return UString("Winbond W25Q40");
    case 0xEF4014: return UString("Winbond W25Q80");
    case 0xEF4015: return UString("Winbond W25Q16");
    case 0xEF4016: return UString("Winbond W25Q32");
    case 0xEF4017: return UString("Winbond W25Q64");
    case 0xEF4018: return UString("Winbond W25Q128");
    case 0xEF4019: return UString("Winbond W25Q256");
    case 0xEF6015: return UString("Winbond W25Q16");
    case 0xEF6016: return UString("Winbond W25Q32");
    case 0xEF6017: return UString("Winbond W25Q64");
    case 0xEF6018: return UString("Winbond W25Q128");

    // Macronix
    case 0xC22013: return UString("Macronix MX25L40");
    case 0xC22014: return UString("Macronix MX25L80");
    case 0xC22015:
    case 0xC22415:
    case 0xC22515: return UString("Macronix MX25L16");
    case 0xC22016:
    case 0xC22535: return UString("Macronix MX25U16");
    case 0xC22536: return UString("Macronix MX25U32");
    case 0xC22537: return UString("Macronix MX25U64");
    case 0xC22538: return UString("Macronix MX25U128");
    case 0xC22539: return UString("Macronix MX25U256");
    case 0xC25E16: return UString("Macronix MX25L32");
    case 0xC22017:
    case 0xC29517: return UString("Macronix MX25L64");
    case 0xC22018: return UString("Macronix MX25L128");
    case 0xC22019: return UString("Macronix MX25L256");

    // Micron
    case 0x202014: return UString("Micron M25P80");
    case 0x202015: return UString("Micron M25P16");
    case 0x202016: return UString("Micron M25P32");
    case 0x202017: return UString("Micron M25P64");
    case 0x202018: return UString("Micron M25P128");
    case 0x204011: return UString("Micron M45PE10");
    case 0x204012: return UString("Micron M45PE20");
    case 0x204013: return UString("Micron M45PE40");
    case 0x204014: return UString("Micron M45PE80");
    case 0x204015: return UString("Micron M45PE16");
    case 0x207114: return UString("Micron M25PX80");
    case 0x207115: return UString("Micron M25PX16");
    case 0x207116: return UString("Micron M25PX32");
    case 0x207117: return UString("Micron M25PX64");
    case 0x208011: return UString("Micron M25PE10");
    case 0x208012: return UString("Micron M25PE20");
    case 0x208013: return UString("Micron M25PE40");
    case 0x208014: return UString("Micron M25PE80");
    case 0x208015: return UString("Micron M25PE16");
    case 0x20BA15: return UString("Micron N25Q016");
    case 0x20BA16: return UString("Micron N25Q032");
    case 0x20BA17: return UString("Micron N25Q064");
    case 0x20BA18: return UString("Micron N25Q128");
    case 0x20BA19: return UString("Micron N25Q256");
    case 0x20BA20: return UString("Micron N25Q512");
    case 0x20BA21: return UString("Micron N25Q00A");
    case 0x20BB15: return UString("Micron N25Q016");
    case 0x20BB16: return UString("Micron N25Q032");
    case 0x20BB17: return UString("Micron N25Q064");
    case 0x20BB18: return UString("Micron MT25Q128");
    case 0x20BB19: return UString("Micron MT25Q256");
    case 0x20BB20: return UString("Micron MT25Q512");

    // Intel
    case 0x898911: return UString("Intel 25F160S33B8");
    case 0x898912: return UString("Intel 25F320S33B8");
    case 0x898913: return UString("Intel 25F640S33B8");
    case 0x898915: return UString("Intel 25F160S33T8");
    case 0x898916: return UString("Intel 25F320S33T8");
    case 0x898917: return UString("Intel 25F640S33T8");

    // Atmel
    case 0x1F4500: return UString("Atmel AT26DF081");
    case 0x1F4501: return UString("Atmel AT26DF081A");
    case 0x1F4502: return UString("Atmel AT25DF081");
    case 0x1F4600: return UString("Atmel AT26DF161");
    case 0x1F4601: return UString("Atmel AT26DF161A");
    case 0x1F4602: return UString("Atmel AT25DF161");
    case 0x1F8600: return UString("Atmel AT25DQ161");
    case 0x1F4700: return UString("Atmel AT25DF321");
    case 0x1F4701: return UString("Atmel AT25DF321A");
    case 0x1F4800: return UString("Atmel AT25DF641");
    case 0x1F8800: return UString("Atmel AT25DQ641");

    // Microchip
    case 0xBF2541: return UString("Microchip SST25VF016B");
    case 0xBF254A: return UString("Microchip SST25VF032B");
    case 0xBF258D: return UString("Microchip SST25VF040B");
    case 0xBF258E: return UString("Microchip SST25VF080B");
    case 0xBF254B: return UString("Microchip SST25VF064C");

    // EON
    case 0x1C3013: return UString("EON EN25Q40");
    case 0x1C3014: return UString("EON EN25Q80");
    case 0x1C3015: return UString("EON EN25Q16");
    case 0x1C3016: return UString("EON EN25Q32");
    case 0x1C3017: return UString("EON EN25Q64");
    case 0x1C3018: return UString("EON EN25Q128");
    case 0x1C3114: return UString("EON EN25F80");
    case 0x1C3115: return UString("EON EN25F16");
    case 0x1C3116: return UString("EON EN25F32");
    case 0x1C3117: return UString("EON EN25F64");
    case 0x1C7015: return UString("EON EN25QH16");
    case 0x1C7016: return UString("EON EN25QH32");
    case 0x1C7017: return UString("EON EN25QH64");
    case 0x1C7018: return UString("EON EN25QH128");
    case 0x1C7019: return UString("EON EN25QH256");

    // GigaDevice
    case 0xC84014: return UString("GigaDevice GD25x80");
    case 0xC84015: return UString("GigaDevice GD25x16");
    case 0xC84016: return UString("GigaDevice GD25x32");
    case 0xC84017: return UString("GigaDevice GD25x64");
    case 0xC84018: return UString("GigaDevice GD25x128");
    case 0xC86017: return UString("GigaDevice GD25Lx64");
    case 0xC86018: return UString("GigaDevice GD25Lx128");

    // Fidelix
    case 0xF83215: return UString("Fidelix FM25Q16");
    case 0xF83216: return UString("Fidelix FM25Q32");
    case 0xF83217: return UString("Fidelix FM25Q64");
    case 0xF83218: return UString("Fidelix FM25Q128");

    // Spansion
    case 0x014015: return UString("Spansion S25FL116K");
    case 0x014016: return UString("Spansion S25FL132K");
    case 0x014017: return UString("Spansion S25FL164K");

    // Amic
    case 0x373015: return UString("Amic A25L016");
    case 0x373016: return UString("Amic A25L032");
    case 0x374016: return UString("Amic A25L032A");

    // PMC
    case 0x9DF713: return UString("PMC Pm25LV080B");
    case 0x9DF714: return UString("PMC Pm25LV016B");
    case 0x9DF744: return UString("PMC Pm25LQ080C");
    case 0x9DF745: return UString("PMC Pm25LQ016C");
    case 0x9DF746: return UString("PMC Pm25LQ032C");
    case 0x9DF77B: return UString("PMC Pm25LV512A");
    case 0x9DF77C: return UString("PMC Pm25LV010A");
    case 0x9DF77D: return UString("PMC Pm25LV020");
    case 0x9DF77E: return UString("PMC Pm25LV040");

    // ISSI
    case 0x9D6017: return UString("ISSI Ix25LP064");
    case 0x9D6018: return UString("ISSI Ix25LP128");
    case 0x9D7018: return UString("ISSI Ix25WP128");
    }

    return UString("Unknown");
}
<commit_msg>Add more chip IDs, thank you Google<commit_after>/* descriptor.cpp

Copyright (c) 2015, Nikolaj Schlej. All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution.  The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php

THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHWARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
*/

#include "descriptor.h"

// Calculate address of data structure addressed by descriptor address format
// 8 bit base or limit
const UINT8* calculateAddress8(const UINT8* baseAddress, const UINT8 baseOrLimit)
{
    return baseAddress + baseOrLimit * 0x10;
}

// 16 bit base or limit
const UINT8* calculateAddress16(const UINT8* baseAddress, const UINT16 baseOrLimit)
{
    return baseAddress + baseOrLimit * 0x1000;
}

// Calculate offset of region using its base
UINT32 calculateRegionOffset(const UINT16 base)
{
    return base * 0x1000;
}

//Calculate size of region using its base and limit
UINT32 calculateRegionSize(const UINT16 base, const UINT16 limit)
{
    if (limit)
        return (limit + 1 - base) * 0x1000;
    return 0;
}

// Return human-readable chip name for given JEDEC ID
UString jedecIdToUString(UINT8 vendorId, UINT8 deviceId0, UINT8 deviceId1)
{
    UINT32 jedecId = (UINT32)deviceId1 + ((UINT32)deviceId0 << 8) + ((UINT32)vendorId << 16);
    switch (jedecId) {
    // Winbond
    case 0xEF3013: return UString("Winbond W25X40");
    case 0xEF3014: return UString("Winbond W25X80");
    case 0xEF3015: return UString("Winbond W25X16");
    case 0xEF3016: return UString("Winbond W25X32");
    case 0xEF3017: return UString("Winbond W25X64");
    case 0xEF4013: return UString("Winbond W25Q40");
    case 0xEF4014: return UString("Winbond W25Q80");
    case 0xEF4015: return UString("Winbond W25Q16");
    case 0xEF4016: return UString("Winbond W25Q32");
    case 0xEF4017: return UString("Winbond W25Q64");
    case 0xEF4018: return UString("Winbond W25Q128");
    case 0xEF4019: return UString("Winbond W25Q256");
    case 0xEF6011: return UString("Winbond W25Q10");
    case 0xEF6012: return UString("Winbond W25Q20");
    case 0xEF6013: return UString("Winbond W25Q40");
    case 0xEF6014: return UString("Winbond W25Q80");
    case 0xEF6015: return UString("Winbond W25Q16");
    case 0xEF6016: return UString("Winbond W25Q32");
    case 0xEF6017: return UString("Winbond W25Q64");
    case 0xEF6018: return UString("Winbond W25Q128");

    // Macronix
    case 0xC22013: return UString("Macronix MX25L40");
    case 0xC22014: return UString("Macronix MX25L80");
    case 0xC22015:
    case 0xC22415:
    case 0xC22515: return UString("Macronix MX25L16");
    case 0xC22016:
    case 0xC22535: return UString("Macronix MX25U16");
    case 0xC2201A: return UString("Macronix MX66L512");
    case 0xC22536: return UString("Macronix MX25U32");
    case 0xC22537: return UString("Macronix MX25U64");
    case 0xC22538: return UString("Macronix MX25U128");
    case 0xC22539: return UString("Macronix MX25U256");
    case 0xC25E16: return UString("Macronix MX25L32");
    case 0xC22017:
    case 0xC29517:
    case 0xC22617: return UString("Macronix MX25L64");
    case 0xC22018:
    case 0xC22618: return UString("Macronix MX25L128");
    case 0xC22019: return UString("Macronix MX25L256");

    // Micron
    case 0x202014: return UString("Micron M25P80");
    case 0x202015: return UString("Micron M25P16");
    case 0x202016: return UString("Micron M25P32");
    case 0x202017: return UString("Micron M25P64");
    case 0x202018: return UString("Micron M25P128");
    case 0x204011: return UString("Micron M45PE10");
    case 0x204012: return UString("Micron M45PE20");
    case 0x204013: return UString("Micron M45PE40");
    case 0x204014: return UString("Micron M45PE80");
    case 0x204015: return UString("Micron M45PE16");
    case 0x207114: return UString("Micron M25PX80");
    case 0x207115: return UString("Micron M25PX16");
    case 0x207116: return UString("Micron M25PX32");
    case 0x207117: return UString("Micron M25PX64");
    case 0x208011: return UString("Micron M25PE10");
    case 0x208012: return UString("Micron M25PE20");
    case 0x208013: return UString("Micron M25PE40");
    case 0x208014: return UString("Micron M25PE80");
    case 0x208015: return UString("Micron M25PE16");
    case 0x20BA15: return UString("Micron N25Q016");
    case 0x20BA16: return UString("Micron N25Q032");
    case 0x20BA17: return UString("Micron N25Q064");
    case 0x20BA18: return UString("Micron N25Q128");
    case 0x20BA19: return UString("Micron N25Q256");
    case 0x20BA20: return UString("Micron N25Q512");
    case 0x20BA21: return UString("Micron N25Q00A");
    case 0x20BB15: return UString("Micron N25Q016");
    case 0x20BB16: return UString("Micron N25Q032");
    case 0x20BB17: return UString("Micron N25Q064");
    case 0x20BB18: return UString("Micron MT25Q128");
    case 0x20BB19: return UString("Micron MT25Q256");
    case 0x20BB20: return UString("Micron MT25Q512");

    // Intel
    case 0x898911: return UString("Intel 25F160S33B8");
    case 0x898912: return UString("Intel 25F320S33B8");
    case 0x898913: return UString("Intel 25F640S33B8");
    case 0x898915: return UString("Intel 25F160S33T8");
    case 0x898916: return UString("Intel 25F320S33T8");
    case 0x898917: return UString("Intel 25F640S33T8");

    // Atmel
    case 0x1F3217: return UString("Atmel AT25SF641");
    case 0x1F4216: return UString("Atmel AT25SL321");
    case 0x1F4218: return UString("Atmel AT25SL128A");
    case 0x1F4317: return UString("Atmel AT25SL641");
    case 0x1F4500: return UString("Atmel AT26DF081");
    case 0x1F4501: return UString("Atmel AT26DF081A");
    case 0x1F4502: return UString("Atmel AT25DF081");
    case 0x1F4600: return UString("Atmel AT26DF161");
    case 0x1F4601: return UString("Atmel AT26DF161A");
    case 0x1F4602: return UString("Atmel AT25DF161");
    case 0x1F8600: return UString("Atmel AT25DQ161");
    case 0x1F4700: return UString("Atmel AT25DF321");
    case 0x1F4701: return UString("Atmel AT25DF321A");
    case 0x1F4800: return UString("Atmel AT25DF641");
    case 0x1F8800: return UString("Atmel AT25DQ641");

    // Microchip
    case 0xBF2541: return UString("Microchip SST25VF016B");
    case 0xBF254A: return UString("Microchip SST25VF032B");
    case 0xBF258D: return UString("Microchip SST25VF040B");
    case 0xBF258E: return UString("Microchip SST25VF080B");
    case 0xBF254B: return UString("Microchip SST25VF064C");

    // EON
    case 0x1C3013: return UString("EON EN25Q40");
    case 0x1C3014: return UString("EON EN25Q80");
    case 0x1C3015: return UString("EON EN25Q16");
    case 0x1C3016: return UString("EON EN25Q32");
    case 0x1C3017: return UString("EON EN25Q64");
    case 0x1C3018: return UString("EON EN25Q128");
    case 0x1C3114: return UString("EON EN25F80");
    case 0x1C3115: return UString("EON EN25F16");
    case 0x1C3116: return UString("EON EN25F32");
    case 0x1C3117: return UString("EON EN25F64");
    case 0x1C7014: return UString("EON EN25QH80");
    case 0x1C7015: return UString("EON EN25QH16");
    case 0x1C7016: return UString("EON EN25QH32");
    case 0x1C7017: return UString("EON EN25QH64");
    case 0x1C7018: return UString("EON EN25QH128");
    case 0x1C7019: return UString("EON EN25QH256");

    // GigaDevice
    case 0xC84014: return UString("GigaDevice GD25x80");
    case 0xC84015: return UString("GigaDevice GD25x16");
    case 0xC84016: return UString("GigaDevice GD25x32");
    case 0xC84017: return UString("GigaDevice GD25x64");
    case 0xC84018: return UString("GigaDevice GD25x128");
    case 0xC84019: return UString("GigaDevice GD25x256C");
    case 0xC86017: return UString("GigaDevice GD25Lx64");
    case 0xC86018: return UString("GigaDevice GD25Lx128");
    case 0xC86019: return UString("GigaDevice GD25LQ256C");

    // Fidelix
    case 0xF83215: return UString("Fidelix FM25Q16");
    case 0xF83216: return UString("Fidelix FM25Q32");
    case 0xF83217: return UString("Fidelix FM25Q64");
    case 0xF83218: return UString("Fidelix FM25Q128");

    // Spansion
    case 0x014015: return UString("Spansion S25FL116K");
    case 0x014016: return UString("Spansion S25FL132K");
    case 0x014017: return UString("Spansion S25FL164K");

    // Amic
    case 0x373015: return UString("Amic A25L016");
    case 0x373016: return UString("Amic A25L032");
    case 0x374016: return UString("Amic A25L032A");

    // PMC
    case 0x9DF713: return UString("PMC Pm25LV080B");
    case 0x9DF714: return UString("PMC Pm25LV016B");
    case 0x9DF744: return UString("PMC Pm25LQ080C");
    case 0x9DF745: return UString("PMC Pm25LQ016C");
    case 0x9DF746: return UString("PMC Pm25LQ032C");
    case 0x9DF77B: return UString("PMC Pm25LV512A");
    case 0x9DF77C: return UString("PMC Pm25LV010A");
    case 0x9DF77D: return UString("PMC Pm25LV020");
    case 0x9DF77E: return UString("PMC Pm25LV040");

    // ISSI
    case 0x9D6017: return UString("ISSI Ix25LP064");
    case 0x9D6018: return UString("ISSI Ix25LP128");
    case 0x9D6019: return UString("ISSI Ix25LP256");
    case 0x9D7017: return UString("ISSI Ix25WP064");
    case 0x9D7018: return UString("ISSI Ix25WP128");
    case 0x9D7019: return UString("ISSI Ix25WP256");
    }

    return UString("Unknown");
}
<|endoftext|>


<commit_before>#include <fstream>
#include <regex>

#include "logging/logger.h"
#include "sequence/io/ptb_parser.h"

namespace meta
{
namespace sequence
{

std::vector<sequence> extract_sequences(const std::string& filename)
{
    std::regex regex{"=====+\\s*$"};

    std::vector<sequence> results;
    std::ifstream file{filename};
    std::string line;
    sequence seq;
    while (std::getline(file, line))
    {
        if (seq.size() > 0)
        {
            if (std::regex_match(line, regex))
            {
                results.emplace_back(std::move(seq));
                continue;
            }

            if (line.length() == 0)
            {
                if (seq[seq.size() - 1].tag() == tag_t{"."})
                    results.emplace_back(std::move(seq));
                continue;
            }
        }

        std::stringstream ss{line};
        std::string word;
        while (ss >> word)
        {
            if (word == "]" || word == "[")
                continue;
            auto pos = word.rfind('/');
            if (pos == word.npos)
            {
                LOG(warning) << "could not find '/' in word/tag pair" << ENDLG;
                continue;
            }
            auto sym = symbol_t{word.substr(0, pos)};
            auto tag = tag_t{word.substr(pos + 1)};
            seq.add_observation({sym, tag});
        }
    }
    if (seq.size() > 0)
        results.emplace_back(std::move(seq));

    return results;
}

}
}
<commit_msg>Fix bug where the regex was unused in extract_sequences.<commit_after>#include <fstream>
#include <regex>

#include "logging/logger.h"
#include "sequence/io/ptb_parser.h"

namespace meta
{
namespace sequence
{

std::vector<sequence> extract_sequences(const std::string& filename)
{
    std::regex regex{"=====+\\s*$"};

    std::vector<sequence> results;
    std::ifstream file{filename};
    std::string line;
    sequence seq;
    while (std::getline(file, line))
    {
        // blank line
        if (line.length() == 0)
        {
            if (seq.size() > 0)
            {
                if (seq[seq.size() - 1].tag() == tag_t{"."})
                    results.emplace_back(std::move(seq));
            }
            continue;
        }

        // paragraph divider
        if (std::regex_match(line, regex))
        {
            if (seq.size() > 0)
                results.emplace_back(std::move(seq));
            continue;
        }

        std::stringstream ss{line};
        std::string word;
        while (ss >> word)
        {
            if (word == "]" || word == "[")
                continue;
            auto pos = word.rfind('/');
            if (pos == word.npos)
            {
                LOG(warning) << "could not find '/' in word/tag pair" << ENDLG;
                LOG(warning) << "word/tag pair is: " << word << ENDLG;
                continue;
            }
            auto sym = symbol_t{word.substr(0, pos)};
            auto tag = tag_t{word.substr(pos + 1)};
            seq.add_observation({sym, tag});
        }
    }
    if (seq.size() > 0)
        results.emplace_back(std::move(seq));

    return results;
}

}
}
<|endoftext|>


<commit_before>//
// shared_statement.cc for saw
// Made by nicuveo <crucuny@gmail.com>
//

//HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
// Includes

#include <iostream>
#include "shared/shared_statement.hh"
#include "error.hh"

//HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
// Implementation

namespace saw
{

  // -tors

  SharedStatement::SharedStatement(Database db, const char* statement)
    : row_index_(-1)
  {
    check(db, sqlite3_prepare_v2(db.raw_data(), statement, -1, &data_, 0));
    resize(sqlite3_column_count(data_));
  }

  SharedStatement::~SharedStatement()
  {
    sqlite3_finalize(data_);
  }

  // mutators

  bool
  SharedStatement::step(const Statement& parent)
  {
    Database db = parent.database();

    row_invalidity_.raise();
    switch (sqlite3_step(data()))
    {
      case SQLITE_DONE:
        reset();
        return false;

      case SQLITE_ROW:
        row_ = Row(parent, ++row_index_, row_invalidity_);
        return true;

      default:
        check(db, reset());
    }

    return false;

  }

  int
  SharedStatement::reset()
  {
    row_ = Row();
    row_index_ = -1;
    return sqlite3_reset(data_);
  }

  // helpers

  std::string
  SharedStatement::fetch(int i) const
  {
    return sqlite3_column_name(data(), i);
  }

}
<commit_msg>Removed useless include.<commit_after>//
// shared_statement.cc for saw
// Made by nicuveo <crucuny@gmail.com>
//

//HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
// Includes

#include "shared/shared_statement.hh"
#include "error.hh"

//HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
// Implementation

namespace saw
{

  // -tors

  SharedStatement::SharedStatement(Database db, const char* statement)
    : row_index_(-1)
  {
    check(db, sqlite3_prepare_v2(db.raw_data(), statement, -1, &data_, 0));
    resize(sqlite3_column_count(data_));
  }

  SharedStatement::~SharedStatement()
  {
    sqlite3_finalize(data_);
  }

  // mutators

  bool
  SharedStatement::step(const Statement& parent)
  {
    Database db = parent.database();

    row_invalidity_.raise();
    switch (sqlite3_step(data()))
    {
      case SQLITE_DONE:
        reset();
        return false;

      case SQLITE_ROW:
        row_ = Row(parent, ++row_index_, row_invalidity_);
        return true;

      default:
        check(db, reset());
    }

    return false;

  }

  int
  SharedStatement::reset()
  {
    row_ = Row();
    row_index_ = -1;
    return sqlite3_reset(data_);
  }

  // helpers

  std::string
  SharedStatement::fetch(int i) const
  {
    return sqlite3_column_name(data(), i);
  }

}
<|endoftext|>


<commit_before>#include "ys_sockdata.h"
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <poll.h>
#include <fcntl.h>
#include <string.h>

namespace ys {

sock_module::sock_module(char* host, int port) {
    struct sockaddr_in local;
    bzero(&local, sizeof(local));
    local.sin_family = AF_INET;
    local.sin_port = htons(port);
    inet_pton(AF_INET, host, &local.sin_addr);
    if ((listen.sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        return -1;
    }
    if (-1 == bind(lsock, (struct sockaddr*)&local, sizeof(local))) {
        return -1;
    }
    if (-1 == listen(lsock, LISTEN_NUM)) {
        return -1;
    }
    listen.sock = lsock;
    listen.pos = -1;
    listen.close = 0;
    connList = 0;
}

sock_module::~sock_module() {

}

void sock_module::prepare(struct pollfd *psock, int& nsock) {
    connect_meta* p = connList;
    int pos = nsock;
    if (!listen.close) {
        psock[pos].fd = listen.sock;
        listen.pos = pos;
        psock[pos++].events = POLLIN;
    }
    while (p) {
        if (p->close) {
			p = p->link;
			continue;
		}
		psock[pos].fd = p->sock;
        p->pos = pos;
        psock[pos].events = POLLERR | POLLHUP;
		pthread_mutex_lock(&p->lock);
		if (p->getStateCanRead()) {
			psock[pos].events |= POLLIN;
		}
		if (p->getStateCanWrite()) {
			psock[pos].events |= POLLOUT;
		}
		pos ++;
        p = p->link;
    }
    nsock = pos;
}

void sock_module::process(struct pollfd *psock) {
	processL(psock);
	processC(psock);
}

void sock_module::processL(struct pollfd * psock) {
	if (listen.pos < 0 || !(psock[listen.pos] & POLLIN)) {
		return;
	}
    int dsock = accept(listen.sock, (struct sockaddr*)0, 0);
    if (dsock < 0) {
        printf ("error!\n");
    }
    else {
        connect_meta* tmp = new connect_meta();
        tmp->sock = dsock;
        tmp->pos = -1;
		tmp->close = 0;
		tmp->state = 0;
		tmp->setStateCanRead();
		tmp->setStateCanWrite();
        tmp->link = connList;
        connList->link = tmp;
    }
}

void sock_module::processC(struct pollfd * psodk) {
	connect_meta *cusor = connList;
	while (cusor) {
		if (cusor->pos < 0) {
			cusor = cusor->link;
			continue;
		}
		if (psodk[cusor->pos].revents & POLLERR ||
			psodk[cusor->pos].revents & POLLHUP) {
			close (cusor->sock);
			cusor->close = 1;
		}
		if (psodk[cusor->pos].revents
		if (psodk[cusor->pos].revents & POLLIN) {
			cusor->setStateNoRead();
			readEvent event = new readEvent();
			event->args = (void*)cusor;
			// TODO
		}
		if (psodk[cusor->pos].revents & POLLOUT) {
			cusor->setStateNoWrite();
			writeEvent event = new writeEvent();
			event->args = (void*)cusor;
			// TODO
		}
		cusor = cusor->link;
	}

	connect_meta **delcusor = connList;
	while (*delcusor) {
		if (1 == (*delcusor)->close) {
			connect_meta *tmp = *delcusor;
			*delcusor = (*delcusor)->link;
			delete tmp;
		}
		else {
			delcusor = &(*delcusor)->link;
		}
	}
}

}

<commit_msg>format<commit_after>#include "ys_sockdata.h"
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <poll.h>
#include <fcntl.h>
#include <string.h>

namespace ys {

sock_module::sock_module(char* host, int port) {
    struct sockaddr_in local;
    bzero(&local, sizeof(local));
    local.sin_family = AF_INET;
    local.sin_port = htons(port);
    inet_pton(AF_INET, host, &local.sin_addr);
    if ((listen.sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        return -1;
    }
    if (-1 == bind(lsock, (struct sockaddr*)&local, sizeof(local))) {
        return -1;
    }
    if (-1 == listen(lsock, LISTEN_NUM)) {
        return -1;
    }
    listen.sock = lsock;
    listen.pos = -1;
    listen.close = 0;
    connList = 0;
}

sock_module::~sock_module() {

}

void sock_module::prepare(struct pollfd *psock, int& nsock) {
    connect_meta* p = connList;
    int pos = nsock;
    if (!listen.close) {
        psock[pos].fd = listen.sock;
        listen.pos = pos;
        psock[pos++].events = POLLIN;
    }
    while (p) {
        if (p->close) {
            p = p->link;
            continue;
		}
        psock[pos].fd = p->sock;
        p->pos = pos;
        psock[pos].events = POLLERR | POLLHUP;
        pthread_mutex_lock(&p->lock);
        if (p->getStateCanRead()) {
            psock[pos].events |= POLLIN;
        }
        if (p->getStateCanWrite()) {
            psock[pos].events |= POLLOUT;
        }
        pos ++;
        p = p->link;
    }
    nsock = pos;
}

void sock_module::process(struct pollfd *psock) {
    processL(psock);
    processC(psock);
}

void sock_module::processL(struct pollfd * psock) {
    if (listen.pos < 0 || !(psock[listen.pos] & POLLIN)) {
        return;
    }
    int dsock = accept(listen.sock, (struct sockaddr*)0, 0);
    if (dsock < 0) {
        printf ("error!\n");
    }
    else {
        connect_meta* tmp = new connect_meta();
        tmp->sock = dsock;
        tmp->pos = -1;
        tmp->close = 0;
        tmp->state = 0;
        tmp->setStateCanRead();
        tmp->setStateCanWrite();
        tmp->link = connList;
        connList->link = tmp;
    }
}

void sock_module::processC(struct pollfd * psodk) {
    connect_meta *cusor = connList;
    while (cusor) {
        if (cusor->pos < 0) {
            cusor = cusor->link;
            continue;
        }
        if (psodk[cusor->pos].revents & POLLERR ||
                psodk[cusor->pos].revents & POLLHUP) {
            close (cusor->sock);
            cusor->close = 1;
		}
        if (psodk[cusor->pos].revents & POLLIN) {
            cusor->setStateNoRead();
            readEvent event = new readEvent();
            event->args = (void*)cusor;
            // TODO
		}
        if (psodk[cusor->pos].revents & POLLOUT) {
            cusor->setStateNoWrite();
            writeEvent event = new writeEvent();
            event->args = (void*)cusor;
            // TODO
            }
        cusor = cusor->link;
    }

    connect_meta **delcusor = connList;
    while (*delcusor) {
        if (1 == (*delcusor)->close) {
            connect_meta *tmp = *delcusor;
            *delcusor = (*delcusor)->link;
            delete tmp;
        }
        else {
            delcusor = &(*delcusor)->link;
        }
    }
}

}

<|endoftext|>


<commit_before>#include "start_game_state.hpp"

#include "game_state.hpp"
#include "main_menu_state.hpp"
#include "logger.hpp"
#include "exception.hpp"

static boost::log::sources::severity_logger<boost::log::trivial::severity_level> lg;

namespace Quoridor {

std::string StartGameState::name_("Start Game");

StartGameState::StartGameState(std::shared_ptr<StateManager> stm)
    : stm_(stm), player_types_(), player_num_(2)
{
    win_ = std::shared_ptr<CEGUI::Window>(
            CEGUI::WindowManager::getSingleton().
                    loadLayoutFromFile("start_game.layout"),
            [=](CEGUI::Window *w) {
                BOOST_LOG_SEV(lg, boost::log::trivial::debug) << "removing window " << w;
                CEGUI::WindowManager::getSingleton().destroyWindow(w);
            }
    );

    init_player_num_();

    subscribe_for_events_();

    player_types_.push_back("fake");
    player_types_.push_back("fake");
}

StartGameState::~StartGameState()
{
    BOOST_LOG_SEV(lg, boost::log::trivial::debug) << "destroying state " << name_;
}

std::shared_ptr<CEGUI::Window> StartGameState::window() const
{
    return win_;
}

const std::string &StartGameState::name() const
{
    return name_;
}

void StartGameState::init_player_num_()
{
    CEGUI::Combobox *cbpn = static_cast<CEGUI::Combobox*>(win_->getChild("playerNum"));

    std::vector<std::pair<int, std::string>> num_str_list = {
        {2, "two players"},
        {4, "four players"}
    };
    for (auto num : num_str_list) {
        auto item = new CEGUI::ListboxTextItem(num.second);
        item->setUserData(reinterpret_cast<void*>(num.first));
        cbpn->addItem(item);
    }

    if (auto item = cbpn->getListboxItemFromIndex(0)) {
        cbpn->setItemSelectState(item, true);
        update_player_num_();
    }
    else {
        throw Exception("failed to set player number");
    }
}

int StartGameState::update_player_num_()
{
    CEGUI::Combobox *cbpn = static_cast<CEGUI::Combobox*>(win_->getChild("playerNum"));
    if (auto item = cbpn->getSelectedItem()) {
        player_num_ = reinterpret_cast<uintptr_t>(item->getUserData());
        BOOST_LOG_SEV(lg, boost::log::trivial::info)
            << "set player number to " << player_num_;
        set_player_list_();
        return 0;
    }
    return -1;
}

void StartGameState::set_player_list_()
{
    CEGUI::DefaultWindow *plist_win = static_cast<CEGUI::DefaultWindow*>(
            win_->getChild("playerList"));
    for (size_t i = 0; i < player_num_; ++i) {
        auto ptype_win = CEGUI::WindowManager::getSingleton().createWindow("GlossySerpent/Combobox");
        ptype_win->setPosition(CEGUI::UVector2(
                    CEGUI::UDim(0, 20),
                    CEGUI::UDim(0.1 * i, 0)));
        ptype_win->setSize(CEGUI::USize(
                    CEGUI::UDim(0.5, 20),
                    CEGUI::UDim(0.8, 0)));
        plist_win->addChild(ptype_win);
    }
}

void StartGameState::subscribe_for_events_()
{
    win_->getChild("startGame")->subscribeEvent(
            CEGUI::Window::EventMouseClick,
            CEGUI::Event::Subscriber(
                    &StartGameState::handle_start_game_, this
            )
    );
    win_->getChild("returnToMainMenu")->subscribeEvent(
            CEGUI::Window::EventMouseClick,
            CEGUI::Event::Subscriber(
                    &StartGameState::handle_return_, this
            )
    );
    win_->getChild("playerNum")->subscribeEvent(
            CEGUI::Combobox::EventListSelectionAccepted,
            CEGUI::Event::Subscriber(
                    &StartGameState::handle_player_num_, this
            )
    );
}

bool StartGameState::handle_start_game_(const CEGUI::EventArgs &/* e */)
{
    BOOST_LOG_SEV(lg, boost::log::trivial::info) << "starting game";
    stm_->change_state(std::shared_ptr<IState>(new GameState(stm_, player_types_)));
    return true;
}

bool StartGameState::handle_return_(const CEGUI::EventArgs &/* e */)
{
    BOOST_LOG_SEV(lg, boost::log::trivial::info) << "returning to main menu";
    stm_->change_state(std::shared_ptr<IState>(new MainMenuState(stm_)));
    return true;
}

bool StartGameState::handle_player_num_(const CEGUI::EventArgs &/* e */)
{
    BOOST_LOG_SEV(lg, boost::log::trivial::info) << "changing player number";
    if (update_player_num_() == 0) {
        return true;
    }
    return false;
}

}  /* namespace Quoridor */
<commit_msg>Set player types empty on init<commit_after>#include "start_game_state.hpp"

#include "game_state.hpp"
#include "main_menu_state.hpp"
#include "logger.hpp"
#include "exception.hpp"

static boost::log::sources::severity_logger<boost::log::trivial::severity_level> lg;

namespace Quoridor {

std::string StartGameState::name_("Start Game");

StartGameState::StartGameState(std::shared_ptr<StateManager> stm)
    : stm_(stm), player_types_(), player_num_(0)
{
    win_ = std::shared_ptr<CEGUI::Window>(
            CEGUI::WindowManager::getSingleton().
                    loadLayoutFromFile("start_game.layout"),
            [=](CEGUI::Window *w) {
                BOOST_LOG_SEV(lg, boost::log::trivial::debug) << "removing window " << w;
                CEGUI::WindowManager::getSingleton().destroyWindow(w);
            }
    );

    init_player_num_();

    subscribe_for_events_();
}

StartGameState::~StartGameState()
{
    BOOST_LOG_SEV(lg, boost::log::trivial::debug) << "destroying state " << name_;
}

std::shared_ptr<CEGUI::Window> StartGameState::window() const
{
    return win_;
}

const std::string &StartGameState::name() const
{
    return name_;
}

void StartGameState::init_player_num_()
{
    CEGUI::Combobox *cbpn = static_cast<CEGUI::Combobox*>(win_->getChild("playerNum"));

    std::vector<std::pair<int, std::string>> num_str_list = {
        {2, "two players"},
        {4, "four players"}
    };
    for (auto num : num_str_list) {
        auto item = new CEGUI::ListboxTextItem(num.second);
        item->setUserData(reinterpret_cast<void*>(num.first));
        cbpn->addItem(item);
    }

    if (auto item = cbpn->getListboxItemFromIndex(0)) {
        cbpn->setItemSelectState(item, true);
        update_player_num_();
    }
    else {
        throw Exception("failed to set player number");
    }
}

int StartGameState::update_player_num_()
{
    CEGUI::Combobox *cbpn = static_cast<CEGUI::Combobox*>(win_->getChild("playerNum"));
    if (auto item = cbpn->getSelectedItem()) {
        player_num_ = reinterpret_cast<uintptr_t>(item->getUserData());
        BOOST_LOG_SEV(lg, boost::log::trivial::info)
            << "set player number to " << player_num_;
        set_player_list_();
        return 0;
    }
    return -1;
}

void StartGameState::set_player_list_()
{
    CEGUI::DefaultWindow *plist_win = static_cast<CEGUI::DefaultWindow*>(
            win_->getChild("playerList"));
    for (size_t i = 0; i < player_num_; ++i) {
        auto ptype_win = CEGUI::WindowManager::getSingleton().createWindow("GlossySerpent/Combobox");
        ptype_win->setPosition(CEGUI::UVector2(
                    CEGUI::UDim(0, 20),
                    CEGUI::UDim(0.1 * i, 0)));
        ptype_win->setSize(CEGUI::USize(
                    CEGUI::UDim(0.5, 20),
                    CEGUI::UDim(0.8, 0)));
        plist_win->addChild(ptype_win);
    }
}

void StartGameState::subscribe_for_events_()
{
    win_->getChild("startGame")->subscribeEvent(
            CEGUI::Window::EventMouseClick,
            CEGUI::Event::Subscriber(
                    &StartGameState::handle_start_game_, this
            )
    );
    win_->getChild("returnToMainMenu")->subscribeEvent(
            CEGUI::Window::EventMouseClick,
            CEGUI::Event::Subscriber(
                    &StartGameState::handle_return_, this
            )
    );
    win_->getChild("playerNum")->subscribeEvent(
            CEGUI::Combobox::EventListSelectionAccepted,
            CEGUI::Event::Subscriber(
                    &StartGameState::handle_player_num_, this
            )
    );
}

bool StartGameState::handle_start_game_(const CEGUI::EventArgs &/* e */)
{
    BOOST_LOG_SEV(lg, boost::log::trivial::info) << "starting game";
    stm_->change_state(std::shared_ptr<IState>(new GameState(stm_, player_types_)));
    return true;
}

bool StartGameState::handle_return_(const CEGUI::EventArgs &/* e */)
{
    BOOST_LOG_SEV(lg, boost::log::trivial::info) << "returning to main menu";
    stm_->change_state(std::shared_ptr<IState>(new MainMenuState(stm_)));
    return true;
}

bool StartGameState::handle_player_num_(const CEGUI::EventArgs &/* e */)
{
    BOOST_LOG_SEV(lg, boost::log::trivial::info) << "changing player number";
    if (update_player_num_() == 0) {
        return true;
    }
    return false;
}

}  /* namespace Quoridor */
<|endoftext|>


<commit_before>/*
===========================================================================

Daemon GPL Source Code
Copyright (C) 2012 Unvanquished Developers

This file is part of the Daemon GPL Source Code (Daemon Source Code).

Daemon Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Daemon Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Daemon Source Code.  If not, see <http://www.gnu.org/licenses/>.

In addition, the Daemon Source Code is also subject to certain additional terms.
You should have received a copy of these additional terms immediately following the
terms and conditions of the GNU General Public License which accompanied the Daemon
Source Code.  If not, please request a copy in writing from id Software at the address
below.

If you have questions concerning this license or the applicable additional terms, you
may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville,
Maryland 20850 USA.

===========================================================================
*/
#include <Rocket/Core.h>
#include "client.h"
#include "rocket.h"
#include "../qcommon/q_unicode.h"

using namespace Rocket::Core::Input;

static std::map< int, int > keyMap;
static bool init = false;

void Rocket_InitKeys( void )
{
	keyMap[ K_TAB ] = KI_TAB;
	keyMap[ K_ENTER ] = KI_RETURN;
	keyMap[ K_ESCAPE ] = KI_ESCAPE;
	keyMap[ K_SPACE ] = KI_SPACE;

	keyMap[ K_BACKSPACE ] = KI_BACK;

	keyMap[ K_COMMAND ] = KI_LWIN;
	keyMap[ K_CAPSLOCK ] = KI_CAPITAL;
	keyMap[ K_POWER ] = KI_POWER;
	keyMap[ K_PAUSE ] = KI_PAUSE;

	keyMap[ K_UPARROW ] = KI_UP;
	keyMap[ K_DOWNARROW ] = KI_DOWN;
	keyMap[ K_LEFTARROW ] = KI_LEFT;
	keyMap[ K_RIGHTARROW ] = KI_RIGHT;

	keyMap[ K_ALT ] = KI_LMETA;
	keyMap[ K_CTRL ] = KI_LCONTROL;
	keyMap[ K_SHIFT ] = KI_LSHIFT;
	keyMap[ K_INS ] = KI_INSERT;
	keyMap[ K_DEL ] = KI_DELETE;
	keyMap[ K_PGDN ] = KI_NEXT;
	keyMap[ K_PGUP ] = KI_PRIOR;
	keyMap[ K_HOME ] = KI_HOME;
	keyMap[ K_END ] = KI_END;

	keyMap[ K_F1 ] = KI_F1;
	keyMap[ K_F2 ] = KI_F2;
	keyMap[ K_F3 ] = KI_F3;
	keyMap[ K_F4 ] = KI_F4;
	keyMap[ K_F5 ] = KI_F5;
	keyMap[ K_F6 ] = KI_F6;
	keyMap[ K_F7 ] = KI_F7;
	keyMap[ K_F8 ] = KI_F8;
	keyMap[ K_F9 ] = KI_F9;
	keyMap[ K_F10 ] = KI_F10;
	keyMap[ K_F11 ] = KI_F11;
	keyMap[ K_F12 ] = KI_F12;
	keyMap[ K_F13 ] = KI_F13;
	keyMap[ K_F14 ] = KI_F14;
	keyMap[ K_F15 ] = KI_F15;

	keyMap[ K_KP_HOME ] = KI_NUMPAD7;
	keyMap[ K_KP_UPARROW ] = KI_NUMPAD8;
	keyMap[ K_KP_PGUP ] = KI_NUMPAD9;
	keyMap[ K_KP_LEFTARROW ] = KI_NUMPAD4;
	keyMap[ K_KP_5 ] = KI_NUMPAD5;
	keyMap[ K_KP_RIGHTARROW ] = KI_NUMPAD6;
	keyMap[ K_KP_END ] = KI_NUMPAD1;
	keyMap[ K_KP_DOWNARROW ] = KI_NUMPAD2;
	keyMap[ K_KP_PGDN ] = KI_NUMPAD3;
	keyMap[ K_KP_ENTER ] = KI_NUMPADENTER;
	keyMap[ K_KP_INS ] = KI_NUMPAD0;
	keyMap[ K_KP_DEL ] = KI_DECIMAL;
	keyMap[ K_KP_SLASH ] = KI_DIVIDE;
	keyMap[ K_KP_MINUS ] = KI_SUBTRACT;
	keyMap[ K_KP_PLUS ] = KI_ADD;
	keyMap[ K_KP_NUMLOCK ] = KI_NUMLOCK;
	keyMap[ K_KP_STAR ] = KI_MULTIPLY;
// 	keyMap[ K_KP_EQUALS ] = KI_KP_EQUALS;

	keyMap[ K_SUPER ] = KI_LWIN;
// 	keyMap[ K_COMPOSE ] = KI_COMPOSE;
// 	keyMap[ K_MODE ] = KI_MODE;
	keyMap[ K_HELP ] = KI_HELP;
	keyMap[ K_PRINT ] = KI_PRINT;
// 	keyMap[ K_SYSREQ ] = KI_SYSREQ;
	keyMap[ K_SCROLLOCK ] = KI_SCROLL;
// 	keyMap[ K_BREAK ] = KI_BREAK;
	keyMap[ K_MENU ] = KI_APPS;
// 	keyMap[ K_EURO ] = KI_EURO;
// 	keyMap[ K_UNDO ] = KI_UNDO;

	// Corresponds to 0 - 9
	for ( int i = '0'; i < '9' + 1; ++i )
	{
		keyMap[ i ] = KI_0 + ( i - '0' );
	}

	// Corresponds to a - z
	for ( int i = 'a'; i < 'z' + 1; ++i )
	{
		keyMap[ i ] = KI_A + ( i - 'a' );
	}

	// Other keyMap that out of ascii order and are handled separately
	keyMap[ ';' ] = KI_OEM_1;      // US standard keyboard; the ';:' key.
	keyMap[ '=' ] = KI_OEM_PLUS;   // Any region; the '=+' key.
	keyMap[ ',' ] = KI_OEM_COMMA;  // Any region; the ',<' key.
	keyMap[ '-' ] = KI_OEM_MINUS;  // Any region; the '-_' key.
	keyMap[ '.' ] = KI_OEM_PERIOD; // Any region; the '.>' key.
	keyMap[ '/' ] = KI_OEM_2;      // Any region; the '/?' key.
	keyMap[ '`' ] = KI_OEM_3;      // Any region; the '`~' key.
	keyMap[ K_CONSOLE ] = KI_OEM_3;

	keyMap[ '[' ] = KI_OEM_4;      // US standard keyboard; the '[{' key.
	keyMap[ '\\' ] = KI_OEM_5;     // US standard keyboard; the '\|' key.
	keyMap[ ']' ] = KI_OEM_6;      // US standard keyboard; the ']}' key.
	keyMap[ '\'' ] = KI_OEM_7;     // US standard keyboard; the ''"' key.

	init = true;
}

KeyIdentifier Rocket_FromQuake( int key )
{
	if ( !init )
	{
		Com_Log( LOG_WARN, "Tried to convert keyMap before key array initialized." );
		return KI_UNKNOWN;
	}
	std::map< int, int >::iterator it;
	it = keyMap.find( key );
	if ( it != keyMap.end() )
	{
		return static_cast< KeyIdentifier >( it->second );
	}

	Com_Logf( LOG_WARN, "Rocket_FromQuake: Could not find keynum %d", key );
	return KI_UNKNOWN;
}

keyNum_t Rocket_ToQuake( int key )
{
	if ( !init )
	{
		Com_Log( LOG_WARN, "Tried to convert keyMap before key array initialized." );
		return K_NONE;
	}
	std::map< int, int >::iterator it;
	for ( it = keyMap.begin(); it != keyMap.end(); ++it )
	{
		if ( it->second == key )
		{
			return static_cast< keyNum_t>( it->first );
		}
	}

	Com_Logf( LOG_WARN, "Rocket_ToQuake: Could not find keynum %d", key );
	return K_NONE;
}

KeyModifier Rocket_GetKeyModifiers( void )
{
	int mod = 0;

	if ( Key_IsDown( K_CTRL ) )
	{
		mod |= KM_CTRL;
	}
	if ( Key_IsDown( K_SHIFT ) )
	{
		mod |= KM_SHIFT;
	}
	if ( Key_IsDown( K_ALT ) )
	{
		mod |= KM_ALT;
	}
	if ( Key_IsDown( K_SUPER ) )
	{
		mod |= KM_META;
	}
	if ( Key_IsDown( K_CAPSLOCK ) )
	{
		mod |= KM_CAPSLOCK;
	}
	if ( Sys_IsNumLockDown() )
	{
		mod |= KM_NUMLOCK;
	}

	return static_cast< KeyModifier >( mod );
}

void Rocket_ProcessMouseClick( int button, qboolean down )
{
	if ( !menuContext || cls.keyCatchers & KEYCATCH_CONSOLE )
	{
		return;
	}

	int idx = 0;
	if ( button <= K_MOUSE5 )
	{
		idx = button - K_MOUSE1;
	}
	else
	{
		idx = button - K_AUX1 + 5; // Start at 5 because of K_MOUSE5
	}

	if ( down )
	{
		menuContext->ProcessMouseButtonDown( idx, Rocket_GetKeyModifiers() );
	}
	else
	{
		menuContext->ProcessMouseButtonUp( idx, Rocket_GetKeyModifiers() );
	}
}

#define MOUSEWHEEL_DELTA 5
void Rocket_ProcessKeyInput( int key, qboolean down )
{
	if ( !menuContext || cls.keyCatchers & KEYCATCH_CONSOLE )
	{
		return;
	}

	// Our input system sends mouse events as key presses.
	if ( ( key >= K_MOUSE1 && key <= K_MOUSE5 ) || ( key >= K_AUX1 && key <= K_AUX16 ) )
	{
		Rocket_ProcessMouseClick( key, down );
		return;
	}

	if ( ( key == K_MWHEELDOWN || key == K_MWHEELUP ) )
	{
		// Our input system sends an up event right after a down event
		// We only want to catch one of these.
		if ( !down )
		{
			return;
		}

		menuContext->ProcessMouseWheel( key == K_MWHEELDOWN ? MOUSEWHEEL_DELTA : -MOUSEWHEEL_DELTA, Rocket_GetKeyModifiers() );
		return;
	}
	if ( down )
	{
		menuContext->ProcessKeyDown( Rocket_FromQuake( key ), Rocket_GetKeyModifiers() );
	}
	else
	{
		menuContext->ProcessKeyUp( Rocket_FromQuake( key ), Rocket_GetKeyModifiers() );
	}
}

int utf8_to_ucs2( const unsigned char *input )
{
	if ( input[0] == 0 )
		return -1;

	if ( input[0] < 0x80 )
	{
		return input[0];
	}

	if ( ( input[0] & 0xE0 ) == 0xE0 )
	{
		if ( input[1] == 0 || input[2] == 0 )
			return -1;

		return
		    ( input[0] & 0x0F ) << 12 |
		    ( input[1] & 0x3F ) << 6  |
		    ( input[2] & 0x3F );
	}

	if ( ( input[0] & 0xC0 ) == 0xC0 )
	{
		if ( input[1] == 0 )
			return -1;

		return
		    ( input[0] & 0x1F ) << 6  |
		    ( input[1] & 0x3F );
	}

	return -1;
}

void Rocket_ProcessTextInput( int key )
{
	if ( !menuContext || cls.keyCatchers & KEYCATCH_CONSOLE )
	{
		return;
	}

	//
	// ignore any non printable chars
	//
	const char *s =  Q_UTF8_Unstore( key );
	if ( ( unsigned char )*s < 32 || ( unsigned char )*s == 0x7f )
	{
		return;
	}

	menuContext->ProcessTextInput( utf8_to_ucs2( ( unsigned char* )s ) );
}

void Rocket_MouseMove( int x, int y )
{
	if ( !menuContext || cls.keyCatchers & KEYCATCH_CONSOLE )
	{
		return;
	}

	menuContext->ProcessMouseMove( x, y, Rocket_GetKeyModifiers() );
}
<commit_msg>Don't inject input to rocket when it doesn't have focus<commit_after>/*
===========================================================================

Daemon GPL Source Code
Copyright (C) 2012 Unvanquished Developers

This file is part of the Daemon GPL Source Code (Daemon Source Code).

Daemon Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Daemon Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Daemon Source Code.  If not, see <http://www.gnu.org/licenses/>.

In addition, the Daemon Source Code is also subject to certain additional terms.
You should have received a copy of these additional terms immediately following the
terms and conditions of the GNU General Public License which accompanied the Daemon
Source Code.  If not, please request a copy in writing from id Software at the address
below.

If you have questions concerning this license or the applicable additional terms, you
may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville,
Maryland 20850 USA.

===========================================================================
*/
#include <Rocket/Core.h>
#include "client.h"
#include "rocket.h"
#include "../qcommon/q_unicode.h"

using namespace Rocket::Core::Input;

static std::map< int, int > keyMap;
static bool init = false;

void Rocket_InitKeys( void )
{
	keyMap[ K_TAB ] = KI_TAB;
	keyMap[ K_ENTER ] = KI_RETURN;
	keyMap[ K_ESCAPE ] = KI_ESCAPE;
	keyMap[ K_SPACE ] = KI_SPACE;

	keyMap[ K_BACKSPACE ] = KI_BACK;

	keyMap[ K_COMMAND ] = KI_LWIN;
	keyMap[ K_CAPSLOCK ] = KI_CAPITAL;
	keyMap[ K_POWER ] = KI_POWER;
	keyMap[ K_PAUSE ] = KI_PAUSE;

	keyMap[ K_UPARROW ] = KI_UP;
	keyMap[ K_DOWNARROW ] = KI_DOWN;
	keyMap[ K_LEFTARROW ] = KI_LEFT;
	keyMap[ K_RIGHTARROW ] = KI_RIGHT;

	keyMap[ K_ALT ] = KI_LMETA;
	keyMap[ K_CTRL ] = KI_LCONTROL;
	keyMap[ K_SHIFT ] = KI_LSHIFT;
	keyMap[ K_INS ] = KI_INSERT;
	keyMap[ K_DEL ] = KI_DELETE;
	keyMap[ K_PGDN ] = KI_NEXT;
	keyMap[ K_PGUP ] = KI_PRIOR;
	keyMap[ K_HOME ] = KI_HOME;
	keyMap[ K_END ] = KI_END;

	keyMap[ K_F1 ] = KI_F1;
	keyMap[ K_F2 ] = KI_F2;
	keyMap[ K_F3 ] = KI_F3;
	keyMap[ K_F4 ] = KI_F4;
	keyMap[ K_F5 ] = KI_F5;
	keyMap[ K_F6 ] = KI_F6;
	keyMap[ K_F7 ] = KI_F7;
	keyMap[ K_F8 ] = KI_F8;
	keyMap[ K_F9 ] = KI_F9;
	keyMap[ K_F10 ] = KI_F10;
	keyMap[ K_F11 ] = KI_F11;
	keyMap[ K_F12 ] = KI_F12;
	keyMap[ K_F13 ] = KI_F13;
	keyMap[ K_F14 ] = KI_F14;
	keyMap[ K_F15 ] = KI_F15;

	keyMap[ K_KP_HOME ] = KI_NUMPAD7;
	keyMap[ K_KP_UPARROW ] = KI_NUMPAD8;
	keyMap[ K_KP_PGUP ] = KI_NUMPAD9;
	keyMap[ K_KP_LEFTARROW ] = KI_NUMPAD4;
	keyMap[ K_KP_5 ] = KI_NUMPAD5;
	keyMap[ K_KP_RIGHTARROW ] = KI_NUMPAD6;
	keyMap[ K_KP_END ] = KI_NUMPAD1;
	keyMap[ K_KP_DOWNARROW ] = KI_NUMPAD2;
	keyMap[ K_KP_PGDN ] = KI_NUMPAD3;
	keyMap[ K_KP_ENTER ] = KI_NUMPADENTER;
	keyMap[ K_KP_INS ] = KI_NUMPAD0;
	keyMap[ K_KP_DEL ] = KI_DECIMAL;
	keyMap[ K_KP_SLASH ] = KI_DIVIDE;
	keyMap[ K_KP_MINUS ] = KI_SUBTRACT;
	keyMap[ K_KP_PLUS ] = KI_ADD;
	keyMap[ K_KP_NUMLOCK ] = KI_NUMLOCK;
	keyMap[ K_KP_STAR ] = KI_MULTIPLY;
// 	keyMap[ K_KP_EQUALS ] = KI_KP_EQUALS;

	keyMap[ K_SUPER ] = KI_LWIN;
// 	keyMap[ K_COMPOSE ] = KI_COMPOSE;
// 	keyMap[ K_MODE ] = KI_MODE;
	keyMap[ K_HELP ] = KI_HELP;
	keyMap[ K_PRINT ] = KI_PRINT;
// 	keyMap[ K_SYSREQ ] = KI_SYSREQ;
	keyMap[ K_SCROLLOCK ] = KI_SCROLL;
// 	keyMap[ K_BREAK ] = KI_BREAK;
	keyMap[ K_MENU ] = KI_APPS;
// 	keyMap[ K_EURO ] = KI_EURO;
// 	keyMap[ K_UNDO ] = KI_UNDO;

	// Corresponds to 0 - 9
	for ( int i = '0'; i < '9' + 1; ++i )
	{
		keyMap[ i ] = KI_0 + ( i - '0' );
	}

	// Corresponds to a - z
	for ( int i = 'a'; i < 'z' + 1; ++i )
	{
		keyMap[ i ] = KI_A + ( i - 'a' );
	}

	// Other keyMap that out of ascii order and are handled separately
	keyMap[ ';' ] = KI_OEM_1;      // US standard keyboard; the ';:' key.
	keyMap[ '=' ] = KI_OEM_PLUS;   // Any region; the '=+' key.
	keyMap[ ',' ] = KI_OEM_COMMA;  // Any region; the ',<' key.
	keyMap[ '-' ] = KI_OEM_MINUS;  // Any region; the '-_' key.
	keyMap[ '.' ] = KI_OEM_PERIOD; // Any region; the '.>' key.
	keyMap[ '/' ] = KI_OEM_2;      // Any region; the '/?' key.
	keyMap[ '`' ] = KI_OEM_3;      // Any region; the '`~' key.
	keyMap[ K_CONSOLE ] = KI_OEM_3;

	keyMap[ '[' ] = KI_OEM_4;      // US standard keyboard; the '[{' key.
	keyMap[ '\\' ] = KI_OEM_5;     // US standard keyboard; the '\|' key.
	keyMap[ ']' ] = KI_OEM_6;      // US standard keyboard; the ']}' key.
	keyMap[ '\'' ] = KI_OEM_7;     // US standard keyboard; the ''"' key.

	init = true;
}

KeyIdentifier Rocket_FromQuake( int key )
{
	if ( !init )
	{
		Com_Log( LOG_WARN, "Tried to convert keyMap before key array initialized." );
		return KI_UNKNOWN;
	}
	std::map< int, int >::iterator it;
	it = keyMap.find( key );
	if ( it != keyMap.end() )
	{
		return static_cast< KeyIdentifier >( it->second );
	}

	Com_Logf( LOG_WARN, "Rocket_FromQuake: Could not find keynum %d", key );
	return KI_UNKNOWN;
}

keyNum_t Rocket_ToQuake( int key )
{
	if ( !init )
	{
		Com_Log( LOG_WARN, "Tried to convert keyMap before key array initialized." );
		return K_NONE;
	}
	std::map< int, int >::iterator it;
	for ( it = keyMap.begin(); it != keyMap.end(); ++it )
	{
		if ( it->second == key )
		{
			return static_cast< keyNum_t>( it->first );
		}
	}

	Com_Logf( LOG_WARN, "Rocket_ToQuake: Could not find keynum %d", key );
	return K_NONE;
}

KeyModifier Rocket_GetKeyModifiers( void )
{
	int mod = 0;

	if ( Key_IsDown( K_CTRL ) )
	{
		mod |= KM_CTRL;
	}
	if ( Key_IsDown( K_SHIFT ) )
	{
		mod |= KM_SHIFT;
	}
	if ( Key_IsDown( K_ALT ) )
	{
		mod |= KM_ALT;
	}
	if ( Key_IsDown( K_SUPER ) )
	{
		mod |= KM_META;
	}
	if ( Key_IsDown( K_CAPSLOCK ) )
	{
		mod |= KM_CAPSLOCK;
	}
	if ( Sys_IsNumLockDown() )
	{
		mod |= KM_NUMLOCK;
	}

	return static_cast< KeyModifier >( mod );
}

void Rocket_ProcessMouseClick( int button, qboolean down )
{
	if ( !menuContext || cls.keyCatchers & KEYCATCH_CONSOLE || !cls.keyCatchers )
	{
		return;
	}

	int idx = 0;
	if ( button <= K_MOUSE5 )
	{
		idx = button - K_MOUSE1;
	}
	else
	{
		idx = button - K_AUX1 + 5; // Start at 5 because of K_MOUSE5
	}

	if ( down )
	{
		menuContext->ProcessMouseButtonDown( idx, Rocket_GetKeyModifiers() );
	}
	else
	{
		menuContext->ProcessMouseButtonUp( idx, Rocket_GetKeyModifiers() );
	}
}

#define MOUSEWHEEL_DELTA 5
void Rocket_ProcessKeyInput( int key, qboolean down )
{
	if ( !menuContext || cls.keyCatchers & KEYCATCH_CONSOLE || !cls.keyCatchers )
	{
		return;
	}

	// Our input system sends mouse events as key presses.
	if ( ( key >= K_MOUSE1 && key <= K_MOUSE5 ) || ( key >= K_AUX1 && key <= K_AUX16 ) )
	{
		Rocket_ProcessMouseClick( key, down );
		return;
	}

	if ( ( key == K_MWHEELDOWN || key == K_MWHEELUP ) )
	{
		// Our input system sends an up event right after a down event
		// We only want to catch one of these.
		if ( !down )
		{
			return;
		}

		menuContext->ProcessMouseWheel( key == K_MWHEELDOWN ? MOUSEWHEEL_DELTA : -MOUSEWHEEL_DELTA, Rocket_GetKeyModifiers() );
		return;
	}
	if ( down )
	{
		menuContext->ProcessKeyDown( Rocket_FromQuake( key ), Rocket_GetKeyModifiers() );
	}
	else
	{
		menuContext->ProcessKeyUp( Rocket_FromQuake( key ), Rocket_GetKeyModifiers() );
	}
}

int utf8_to_ucs2( const unsigned char *input )
{
	if ( input[0] == 0 )
		return -1;

	if ( input[0] < 0x80 )
	{
		return input[0];
	}

	if ( ( input[0] & 0xE0 ) == 0xE0 )
	{
		if ( input[1] == 0 || input[2] == 0 )
			return -1;

		return
		    ( input[0] & 0x0F ) << 12 |
		    ( input[1] & 0x3F ) << 6  |
		    ( input[2] & 0x3F );
	}

	if ( ( input[0] & 0xC0 ) == 0xC0 )
	{
		if ( input[1] == 0 )
			return -1;

		return
		    ( input[0] & 0x1F ) << 6  |
		    ( input[1] & 0x3F );
	}

	return -1;
}

void Rocket_ProcessTextInput( int key )
{
	if ( !menuContext || cls.keyCatchers & KEYCATCH_CONSOLE || !cls.keyCatchers )
	{
		return;
	}

	//
	// ignore any non printable chars
	//
	const char *s =  Q_UTF8_Unstore( key );
	if ( ( unsigned char )*s < 32 || ( unsigned char )*s == 0x7f )
	{
		return;
	}

	menuContext->ProcessTextInput( utf8_to_ucs2( ( unsigned char* )s ) );
}

void Rocket_MouseMove( int x, int y )
{
	if ( !menuContext || cls.keyCatchers & KEYCATCH_CONSOLE || !cls.keyCatchers )
	{
		return;
	}

	menuContext->ProcessMouseMove( x, y, Rocket_GetKeyModifiers() );
}
<|endoftext|>


<commit_before>//
//  Copyright Silvin Lubecki 2010
//
//  Distributed under the Boost Software License, Version 1.0. (See
//  accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef OPENCLAM_FOR_EACH_HPP_INCLUDED
#define OPENCLAM_FOR_EACH_HPP_INCLUDED

#include "kernel.hpp"
#include <memory>

namespace openclam
{
namespace detail
{
    template< class RandomAccessIterator, class Kernel >
    void for_each_dispatch( RandomAccessIterator& first, RandomAccessIterator& last, Kernel& k, std::random_access_iterator_tag )
    {
        k( &*first, std::distance( first, last ) );
    }

    template< class InputIterator, class Kernel >
    void for_each_dispatch( InputIterator& first, InputIterator& last, Kernel& k, std::input_iterator_tag )
    {
        std::vector< InputIterator::value_type* > data_references;
        std::vector< InputIterator::value_type > data;
        for( ; first != last; ++first )
        {
            data.push_back( *first );
            data_references.push_back( &*first );
        }
        k( &data[ 0 ], data.size() );
        for( unsigned int i = 0; i < data.size(); ++i )
            *data_references[ i ] = data[ i ];
    }
}

    template< class InputIterator, class Kernel >
    void for_each( InputIterator first, InputIterator last, Kernel& k )
    {
        typename std::iterator_traits< InputIterator >::iterator_category category;
        detail::for_each_dispatch( first, last, k, category );
    }
}

#endif // #ifndef OPENCLAM_CONTEXT_HPP_INCLUDED
<commit_msg>clean up<commit_after>//
//  Copyright Silvin Lubecki 2010
//
//  Distributed under the Boost Software License, Version 1.0. (See
//  accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef OPENCLAM_FOR_EACH_HPP_INCLUDED
#define OPENCLAM_FOR_EACH_HPP_INCLUDED

#include <memory>

namespace openclam
{
namespace detail
{
    template< class RandomAccessIterator, class Kernel >
    void for_each_dispatch( RandomAccessIterator& first, RandomAccessIterator& last, Kernel& k, std::random_access_iterator_tag )
    {
        k( &*first, std::distance( first, last ) );
    }

    template< class InputIterator, class Kernel >
    void for_each_dispatch( InputIterator& first, InputIterator& last, Kernel& k, std::input_iterator_tag )
    {
        std::vector< InputIterator::value_type* > data_references;
        std::vector< InputIterator::value_type > data;
        for( ; first != last; ++first )
        {
            data.push_back( *first );
            data_references.push_back( &*first );
        }
        k( &data[ 0 ], data.size() );
        for( unsigned int i = 0; i < data.size(); ++i )
            *data_references[ i ] = data[ i ];
    }
}

    template< class InputIterator, class Kernel >
    void for_each( InputIterator first, InputIterator last, Kernel& k )
    {
        typename std::iterator_traits< InputIterator >::iterator_category category;
        detail::for_each_dispatch( first, last, k, category );
    }
}

#endif // #ifndef OPENCLAM_CONTEXT_HPP_INCLUDED
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io>
 * Authors:
 *   - Paul Asmuth <paul@eventql.io>
 *   - Laura Schlimmer <laura@eventql.io>
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License ("the license") as
 * published by the Free Software Foundation, either version 3 of the License,
 * or any later version.
 *
 * In accordance with Section 7(e) of the license, the licensing of the Program
 * under the license does not imply a trademark license. Therefore any rights,
 * title and interest in our trademarks remain entirely with us.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the license for more details.
 *
 * You can be released from the requirements of the license by purchasing a
 * commercial license. Buying such a license is mandatory as soon as you develop
 * commercial activities involving this program without disclosing the source
 * code of your own applications
 */
#include <eventql/sql/qtree/JoinNode.h>
#include <eventql/sql/qtree/ColumnReferenceNode.h>
#include <eventql/sql/qtree/QueryTreeUtil.h>

#include "eventql/eventql.h"

namespace csql {

JoinNode::JoinNode(
    JoinType join_type,
    RefPtr<QueryTreeNode> base_table,
    RefPtr<QueryTreeNode> joined_table) :
    join_type_(join_type),
    base_table_(base_table),
    joined_table_(joined_table) {
  addChild(&base_table_);
  addChild(&joined_table_);
}

JoinNode::JoinNode(
    JoinType join_type,
    RefPtr<QueryTreeNode> base_table,
    RefPtr<QueryTreeNode> joined_table,
    Vector<RefPtr<SelectListNode>> select_list,
    Option<RefPtr<ValueExpressionNode>> where_expr,
    Option<RefPtr<ValueExpressionNode>> join_cond) :
    join_type_(join_type),
    base_table_(base_table),
    joined_table_(joined_table),
    select_list_(select_list),
    where_expr_(where_expr),
    join_cond_(join_cond) {
  for (const auto& sl : select_list_) {
    column_names_.emplace_back(sl->columnName());
  }

  addChild(&base_table_);
  addChild(&joined_table_);
}

JoinNode::JoinNode(
    const JoinNode& other) :
    join_type_(other.join_type_),
    base_table_(other.base_table_->deepCopy()),
    joined_table_(other.joined_table_->deepCopy()),
    input_map_(other.input_map_),
    column_names_(other.column_names_),
    join_cond_(other.join_cond_) {
  for (const auto& e : other.select_list_) {
    select_list_.emplace_back(e->deepCopyAs<SelectListNode>());
  }

  if (!other.where_expr_.isEmpty()) {
    where_expr_ = Some(
        other.where_expr_.get()->deepCopyAs<ValueExpressionNode>());
  }

  addChild(&base_table_);
  addChild(&joined_table_);
}

JoinType JoinNode::joinType() const {
  return join_type_;
}

RefPtr<QueryTreeNode> JoinNode::baseTable() const {
  return base_table_;
}

RefPtr<QueryTreeNode> JoinNode::joinedTable() const {
  return joined_table_;
}

Vector<RefPtr<SelectListNode>> JoinNode::selectList() const {
  return select_list_;
}

Vector<String> JoinNode::getResultColumns() const {
  return column_names_;
}

Vector<QualifiedColumn> JoinNode::getAvailableColumns() const {
  Vector<QualifiedColumn> cols;

  for (const auto& c :
      base_table_.asInstanceOf<TableExpressionNode>()->getAvailableColumns()) {
    cols.emplace_back(c);
  }

  for (const auto& c :
      joined_table_.asInstanceOf<TableExpressionNode>()->getAvailableColumns()) {
    cols.emplace_back(c);
  }

  return cols;
}

size_t JoinNode::getComputedColumnIndex(
    const String& column_name,
    bool allow_add /* = false */) {
  for (int i = 0; i < column_names_.size(); ++i) {
    if (column_names_[i] == column_name) {
      return i;
    }
  }

  auto input_idx = getInputColumnIndex(column_name);
  if (input_idx != size_t(-1)) {
    auto slnode = new SelectListNode(
        new ColumnReferenceNode(input_idx, getInputColumnType(input_idx)));
    slnode->setAlias(column_name);
    select_list_.emplace_back(slnode);
    return select_list_.size() - 1;
  }

  return -1; // FIXME
}

size_t JoinNode::getNumComputedColumns() const {
  return select_list_.size();
}

SType JoinNode::getColumnType(size_t idx) const {
  assert(idx < select_list_.size());
  return select_list_[idx]->expression()->getReturnType();
}

size_t JoinNode::getInputColumnIndex(
    const String& column_name,
    bool allow_add /* = false */) {
  for (int i = 0; i < input_map_.size(); ++i) {
    if (input_map_[i].column == column_name) {
      return i;
    }
  }

  auto base_table_idx = base_table_
      .asInstanceOf<TableExpressionNode>()
      ->getComputedColumnIndex(column_name, allow_add);

  auto joined_table_idx = joined_table_
      .asInstanceOf<TableExpressionNode>()
      ->getComputedColumnIndex(column_name, allow_add);

  if (base_table_idx != size_t(-1) && joined_table_idx != size_t(-1)) {
    RAISEF(
        kRuntimeError,
        "ambiguous column reference: '$0'",
        column_name);
  }

  if (base_table_idx != size_t(-1)) {
    input_map_.emplace_back(InputColumnRef{
      .column = column_name,
      .table_idx = 0,
      .column_idx = base_table_idx
    });

    return input_map_.size() - 1;
  }

  if (joined_table_idx != size_t(-1)) {
    input_map_.emplace_back(InputColumnRef{
      .column = column_name,
      .table_idx = 1,
      .column_idx = joined_table_idx
    });

    return input_map_.size() - 1;
  }

  return -1;
}

Option<RefPtr<ValueExpressionNode>> JoinNode::whereExpression() const {
  return where_expr_;
}

Option<RefPtr<ValueExpressionNode>> JoinNode::joinCondition() const {
  return join_cond_;
}

RefPtr<QueryTreeNode> JoinNode::deepCopy() const {
  return new JoinNode(*this);
}

const Vector<JoinNode::InputColumnRef>& JoinNode::inputColumnMap() const {
  return input_map_;
}

String JoinNode::toString() const {
  auto str = StringUtil::format(
      "(join (base-table $0) (joined-table $0) (select-list",
      base_table_->toString(),
      joined_table_->toString());

  for (const auto& e : select_list_) {
    str += " " + e->toString();
  }
  str += ")";

  if (!where_expr_.isEmpty()) {
    str += StringUtil::format(" (where $0)", where_expr_.get()->toString());
  }

  if (!join_cond_.isEmpty()) {
    str += StringUtil::format(" (join-cond $0)", join_cond_.get()->toString());
  }

  str += ")";
  return str;
};

void JoinNode::encode(
    QueryTreeCoder* coder,
    const JoinNode& node,
    OutputStream* os) {
  os->appendUInt8((uint8_t) node.join_type_);

  os->appendVarUInt(node.select_list_.size());
  for (const auto& e : node.select_list_) {
    coder->encode(e.get(), os);
  }

  uint8_t flags = 0;
  if (!node.where_expr_.isEmpty()) {
    flags |= kHasWhereExprFlag;
  }
  if (!node.join_cond_.isEmpty()) {
    flags |= kHasJoinExprFlag;
  }

  os->appendUInt8(flags);

  if (!node.where_expr_.isEmpty()) {
    coder->encode(node.where_expr_.get().get(), os);
  }

  if (!node.join_cond_.isEmpty()) {
    coder->encode(node.join_cond_.get().get(), os);
  }

  coder->encode(node.base_table_.get(), os);
  coder->encode(node.joined_table_.get(), os);
}

RefPtr<QueryTreeNode> JoinNode::decode (
    QueryTreeCoder* coder,
    InputStream* is) {
  auto join_type = (JoinType) is->readUInt8();

  Vector<RefPtr<SelectListNode>> select_list;
  auto select_list_size = is->readVarUInt();
  for (auto i = 0; i < select_list_size; ++i) {
    select_list.emplace_back(coder->decode(is).asInstanceOf<SelectListNode>());
  }

  Option<RefPtr<ValueExpressionNode>> where_expr;
  Option<RefPtr<ValueExpressionNode>> join_cond;
  auto flags = is->readUInt8();

  if ((flags & kHasWhereExprFlag) > 0) {
    where_expr = coder->decode(is).asInstanceOf<ValueExpressionNode>();
  }

  if ((flags & kHasJoinExprFlag) > 0) {
    join_cond = coder->decode(is).asInstanceOf<ValueExpressionNode>();
  }

  auto base_tbl = coder->decode(is);
  auto joined_tbl = coder->decode(is);

  return new JoinNode(
      join_type,
      base_tbl,
      joined_tbl,
      select_list,
      where_expr,
      join_cond);
}

} // namespace csql

<commit_msg>implement new JoinNode methods<commit_after>/**
 * Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io>
 * Authors:
 *   - Paul Asmuth <paul@eventql.io>
 *   - Laura Schlimmer <laura@eventql.io>
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License ("the license") as
 * published by the Free Software Foundation, either version 3 of the License,
 * or any later version.
 *
 * In accordance with Section 7(e) of the license, the licensing of the Program
 * under the license does not imply a trademark license. Therefore any rights,
 * title and interest in our trademarks remain entirely with us.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the license for more details.
 *
 * You can be released from the requirements of the license by purchasing a
 * commercial license. Buying such a license is mandatory as soon as you develop
 * commercial activities involving this program without disclosing the source
 * code of your own applications
 */
#include <eventql/sql/qtree/JoinNode.h>
#include <eventql/sql/qtree/ColumnReferenceNode.h>
#include <eventql/sql/qtree/QueryTreeUtil.h>

#include "eventql/eventql.h"

namespace csql {

JoinNode::JoinNode(
    JoinType join_type,
    RefPtr<QueryTreeNode> base_table,
    RefPtr<QueryTreeNode> joined_table) :
    join_type_(join_type),
    base_table_(base_table),
    joined_table_(joined_table) {
  addChild(&base_table_);
  addChild(&joined_table_);
}

JoinNode::JoinNode(
    JoinType join_type,
    RefPtr<QueryTreeNode> base_table,
    RefPtr<QueryTreeNode> joined_table,
    Vector<RefPtr<SelectListNode>> select_list,
    Option<RefPtr<ValueExpressionNode>> where_expr,
    Option<RefPtr<ValueExpressionNode>> join_cond) :
    join_type_(join_type),
    base_table_(base_table),
    joined_table_(joined_table),
    select_list_(select_list),
    where_expr_(where_expr),
    join_cond_(join_cond) {
  for (const auto& sl : select_list_) {
    column_names_.emplace_back(sl->columnName());
  }

  addChild(&base_table_);
  addChild(&joined_table_);
}

JoinNode::JoinNode(
    const JoinNode& other) :
    join_type_(other.join_type_),
    base_table_(other.base_table_->deepCopy()),
    joined_table_(other.joined_table_->deepCopy()),
    input_map_(other.input_map_),
    column_names_(other.column_names_),
    join_cond_(other.join_cond_) {
  for (const auto& e : other.select_list_) {
    select_list_.emplace_back(e->deepCopyAs<SelectListNode>());
  }

  if (!other.where_expr_.isEmpty()) {
    where_expr_ = Some(
        other.where_expr_.get()->deepCopyAs<ValueExpressionNode>());
  }

  addChild(&base_table_);
  addChild(&joined_table_);
}

JoinType JoinNode::joinType() const {
  return join_type_;
}

void JoinNode::setJoinType(JoinType type) {
  join_type_ = type;
}

RefPtr<QueryTreeNode> JoinNode::baseTable() const {
  return base_table_;
}

RefPtr<QueryTreeNode> JoinNode::joinedTable() const {
  return joined_table_;
}

Vector<RefPtr<SelectListNode>> JoinNode::selectList() const {
  return select_list_;
}

void JoinNode::addSelectList(RefPtr<SelectListNode> sl) {
  column_names_.emplace_back(sl->columnName());
  select_list_.emplace_back(sl);
}

Vector<String> JoinNode::getResultColumns() const {
  return column_names_;
}

Vector<QualifiedColumn> JoinNode::getAvailableColumns() const {
  Vector<QualifiedColumn> cols;

  for (const auto& c :
      base_table_.asInstanceOf<TableExpressionNode>()->getAvailableColumns()) {
    cols.emplace_back(c);
  }

  for (const auto& c :
      joined_table_.asInstanceOf<TableExpressionNode>()->getAvailableColumns()) {
    cols.emplace_back(c);
  }

  return cols;
}

size_t JoinNode::getComputedColumnIndex(
    const String& column_name,
    bool allow_add /* = false */) {
  for (int i = 0; i < column_names_.size(); ++i) {
    if (column_names_[i] == column_name) {
      return i;
    }
  }

  auto input_idx = getInputColumnIndex(column_name);
  if (input_idx != size_t(-1)) {
    auto slnode = new SelectListNode(
        new ColumnReferenceNode(input_idx, getInputColumnType(input_idx)));
    slnode->setAlias(column_name);
    select_list_.emplace_back(slnode);
    return select_list_.size() - 1;
  }

  return -1; // FIXME
}

size_t JoinNode::getNumComputedColumns() const {
  return select_list_.size();
}

SType JoinNode::getColumnType(size_t idx) const {
  assert(idx < select_list_.size());
  return select_list_[idx]->expression()->getReturnType();
}

size_t JoinNode::getInputColumnIndex(
    const String& column_name,
    bool allow_add /* = false */) {
  for (int i = 0; i < input_map_.size(); ++i) {
    if (input_map_[i].column == column_name) {
      return i;
    }
  }

  auto base_table_idx = base_table_
      .asInstanceOf<TableExpressionNode>()
      ->getComputedColumnIndex(column_name, allow_add);

  auto joined_table_idx = joined_table_
      .asInstanceOf<TableExpressionNode>()
      ->getComputedColumnIndex(column_name, allow_add);

  if (base_table_idx != size_t(-1) && joined_table_idx != size_t(-1)) {
    RAISEF(
        kRuntimeError,
        "ambiguous column reference: '$0'",
        column_name);
  }

  if (base_table_idx != size_t(-1)) {
    input_map_.emplace_back(InputColumnRef{
      .column = column_name,
      .table_idx = 0,
      .column_idx = base_table_idx
    });

    return input_map_.size() - 1;
  }

  if (joined_table_idx != size_t(-1)) {
    input_map_.emplace_back(InputColumnRef{
      .column = column_name,
      .table_idx = 1,
      .column_idx = joined_table_idx
    });

    return input_map_.size() - 1;
  }

  return -1;
}

SType JoinNode::getInputColumnType(size_t idx) const {
  if (idx >= input_map_.size()) {
    RAISEF(
        kRuntimeError,
        "invalid column index: '$0'",
        idx);
  }

  switch (input_map_[idx].table_idx) {
    case 0:
      return base_table_.asInstanceOf<TableExpressionNode>()->getColumnType(
          input_map_[idx].column_idx);
    case 1:
      return joined_table_.asInstanceOf<TableExpressionNode>()->getColumnType(
          input_map_[idx].column_idx);
    default:
      return SType::NIL;
  }
}

std::pair<size_t, SType> JoinNode::getInputColumnInfo(
    const String& column_name,
    bool allow_add) {
  auto idx = getInputColumnIndex(column_name, allow_add);
  if (idx == size_t(-1)) {
    return std::make_pair(idx, SType::NIL);
  } else {
    return std::make_pair(idx, getInputColumnType(idx));
  }
}

Option<RefPtr<ValueExpressionNode>> JoinNode::whereExpression() const {
  return where_expr_;
}

void JoinNode::setWhereExpression(RefPtr<ValueExpressionNode> expr) {
  where_expr_ = Some(expr);
}

Option<RefPtr<ValueExpressionNode>> JoinNode::joinCondition() const {
  return join_cond_;
}

void JoinNode::setJoinCondition(RefPtr<ValueExpressionNode> expr) {
  join_cond_ = Some(expr);
}

RefPtr<QueryTreeNode> JoinNode::deepCopy() const {
  return new JoinNode(*this);
}

const Vector<JoinNode::InputColumnRef>& JoinNode::inputColumnMap() const {
  return input_map_;
}

String JoinNode::toString() const {
  auto str = StringUtil::format(
      "(join (base-table $0) (joined-table $0) (select-list",
      base_table_->toString(),
      joined_table_->toString());

  for (const auto& e : select_list_) {
    str += " " + e->toString();
  }
  str += ")";

  if (!where_expr_.isEmpty()) {
    str += StringUtil::format(" (where $0)", where_expr_.get()->toString());
  }

  if (!join_cond_.isEmpty()) {
    str += StringUtil::format(" (join-cond $0)", join_cond_.get()->toString());
  }

  str += ")";
  return str;
};

void JoinNode::encode(
    QueryTreeCoder* coder,
    const JoinNode& node,
    OutputStream* os) {
  os->appendUInt8((uint8_t) node.join_type_);

  os->appendVarUInt(node.select_list_.size());
  for (const auto& e : node.select_list_) {
    coder->encode(e.get(), os);
  }

  uint8_t flags = 0;
  if (!node.where_expr_.isEmpty()) {
    flags |= kHasWhereExprFlag;
  }
  if (!node.join_cond_.isEmpty()) {
    flags |= kHasJoinExprFlag;
  }

  os->appendUInt8(flags);

  if (!node.where_expr_.isEmpty()) {
    coder->encode(node.where_expr_.get().get(), os);
  }

  if (!node.join_cond_.isEmpty()) {
    coder->encode(node.join_cond_.get().get(), os);
  }

  coder->encode(node.base_table_.get(), os);
  coder->encode(node.joined_table_.get(), os);
}

RefPtr<QueryTreeNode> JoinNode::decode (
    QueryTreeCoder* coder,
    InputStream* is) {
  auto join_type = (JoinType) is->readUInt8();

  Vector<RefPtr<SelectListNode>> select_list;
  auto select_list_size = is->readVarUInt();
  for (auto i = 0; i < select_list_size; ++i) {
    select_list.emplace_back(coder->decode(is).asInstanceOf<SelectListNode>());
  }

  Option<RefPtr<ValueExpressionNode>> where_expr;
  Option<RefPtr<ValueExpressionNode>> join_cond;
  auto flags = is->readUInt8();

  if ((flags & kHasWhereExprFlag) > 0) {
    where_expr = coder->decode(is).asInstanceOf<ValueExpressionNode>();
  }

  if ((flags & kHasJoinExprFlag) > 0) {
    join_cond = coder->decode(is).asInstanceOf<ValueExpressionNode>();
  }

  auto base_tbl = coder->decode(is);
  auto joined_tbl = coder->decode(is);

  return new JoinNode(
      join_type,
      base_tbl,
      joined_tbl,
      select_list,
      where_expr,
      join_cond);
}

} // namespace csql

<|endoftext|>


<commit_before>#include <unistd.h>
#include <cassert>
#include <boost/shared_ptr.hpp>

#include "gen-cpp/DataHub.h"
#include <thrift/transport/THttpClient.h>
#include <thrift/transport/TBufferTransports.h>
#include <thrift/protocol/TBinaryProtocol.h>

/**
 * Sample DataHub C++ Client
 *
 * @author anantb
 * @author stephentu
 * @date 11/07/2013
 *
 */

using namespace std;
using namespace boost;
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;

using namespace datahub;

int main () {
  try {
    shared_ptr<THttpClient> transport(new THttpClient("datahub.csail.mit.edu", 80, "/service"));
    shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
    DataHubClient client(protocol);

    transport->open();
    double version = client.get_version();
    cout << version << endl;

    ConnectionParams params = ConnectionParams();
    params.__set_user("anantb");
    params.__set_password("anant");

    Connection conn;
    client.open_connection(conn, params);

    ResultSet res;
    client.execute_sql(
      res, conn, "select * from anantb.test.demo", vector<string>());
    for(vector<Tuple>::const_iterator tuple_it = res.tuples.begin();
        tuple_it != res.tuples.end();
        ++tuple_it) {
      for(vector<string>::const_iterator cell_it = (*tuple_it).cells.begin();
          cell_it != (*tuple_it).cells.end();
          ++cell_it) {
        cout << *cell_it << "\t";
      }
      cout << std::endl;
    }

    transport->close();
  } catch (TException &tx) {
    cout << "ERROR: " << tx.what();
  }

  return 0;
}
<commit_msg>cpp sample<commit_after>#include <unistd.h>
#include <cassert>
#include <boost/shared_ptr.hpp>

#include "gen-cpp/DataHub.h"
#include <thrift/transport/THttpClient.h>
#include <thrift/transport/TBufferTransports.h>
#include <thrift/protocol/TBinaryProtocol.h>

/**
 * Sample DataHub C++ Client
 *
 * @author anantb
 * @author stephentu
 * @date 11/07/2013
 *
 */

using namespace std;
using namespace boost;
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;

using namespace datahub;

int main () {
  try {
    shared_ptr<THttpClient> transport(
        new THttpClient("datahub.csail.mit.edu", 80, "/service"));
    shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
    DataHubClient client(protocol);

    transport->open();
    double version = client.get_version();
    cout << "Version: " << version << endl;

    ConnectionParams params = ConnectionParams();
    params.__set_user("anantb");
    params.__set_password("anant");

    Connection conn;
    client.open_connection(conn, params);

    ResultSet res;
    client.execute_sql(
      res, conn, "select * from anantb.test.demo", vector<string>());

    // print field names
    for(vector<string>::const_iterator field_it = res.field_names.begin();
        field_it != res.field_names.end();
        ++field_it) {
      cout << *field_it << "\t";
    }

    // print tuple values
    for(vector<Tuple>::const_iterator tuple_it = res.tuples.begin();
        tuple_it != res.tuples.end();
        ++tuple_it) {
      for(vector<string>::const_iterator cell_it = (*tuple_it).cells.begin();
          cell_it != (*tuple_it).cells.end();
          ++cell_it) {
        cout << *cell_it << "\t";
      }
      cout << std::endl;
    }

    transport->close();
  } catch (TException &tx) {
    cout << "ERROR: " << tx.what();
  }

  return 0;
}
<|endoftext|>


<commit_before>#include "MatrixSlicingTest.h"
#include <matrix/Matrix.h>
#include <matrix/MatrixHelper.h>
#include <matrix/MatrixSlice.h>
#include <algorithm>
#include <cstddef>

const size_t ROWS = 910;
const size_t COLS = 735;
const size_t NODE_COUNTS[] = { 3, 1, 2, 3, 5, 7, 12, 25, 80, 110 };

typedef Matrix<float> TestGrid;

using namespace std;
typedef MatrixSlicer::SliceList SliceList;

ostream& operator<<(ostream& stream, const MatrixSlice& slice)
{
    return stream
        << "("
        << slice.getStartX() << ", "
        << slice.getStartY() << ", "
        << slice.getColumns() << ", "
        << slice.getRows() << ")";
}

ostream& operator<<(ostream& stream, const SliceList& slices)
{
    stream << "[";
    bool first = true;
    for (const auto& slice : slices)
    {
        if (!first)
            stream << ", ";
        stream << slice;
        first = false;
    }
    stream << "]";

    return stream;
}

BenchmarkResult makeUniformRatings(size_t number)
{
    BenchmarkResult ratings;
    for (size_t i=0; i<number; ++i)
    {
        ratings[i] = 100/number;
    }
    return ratings;
}

TestGrid setupTestGrid(size_t rows, size_t cols)
{
    TestGrid testGrid(rows, cols);
    MatrixHelper::fill(testGrid, [](){ return 0.0f; });
    return testGrid;
}

string makeErrorMsg(size_t nodeCount, const MatrixSlice& slice)
{
    stringstream errorMsg;
    errorMsg
        << " out of bounds. Nodes: "
        << nodeCount << ", Slice: " << slice;
    return errorMsg.str();
}

void applySliceToTestGrid(const MatrixSlice& slice, TestGrid* grid, size_t nodeCount)
{
    for (size_t i=0; i<slice.getRows(); ++i)
    {
        for (size_t j=0; j<slice.getColumns(); ++j)
        {
            auto row = i + slice.getStartY();
            auto col = j + slice.getStartX();
            ASSERT_LT(row, grid->rows()) << "Row" << makeErrorMsg(nodeCount, slice);
            ASSERT_LT(col, grid->columns()) << "Column" << makeErrorMsg(nodeCount, slice);
            (*grid)(row, col) += 1.0f;
        }
    }
}

TestGrid fillTestGrid(size_t rows, size_t cols, const SliceList& slices, const BenchmarkResult& ratings)
{
    TestGrid testGrid = setupTestGrid(rows, cols);
    for (const MatrixSlice& slice : slices)
    {
        applySliceToTestGrid(slice, &testGrid, ratings.size());
        if (testing::Test::HasFatalFailure()) break;
    }

    return testGrid;
}

TestGrid makeTestGrid(size_t nodeCount, const MatrixSlicer& slicer)
{
    auto ratings = makeUniformRatings(nodeCount);
    auto slices = slicer.sliceAndDice(ratings, ROWS, COLS);
    return fillTestGrid(ROWS, COLS, slices, ratings);
}

void checkTestGrid(const TestGrid& testGrid, const SliceList& slices)
{
    for(size_t i=0; i<ROWS; ++i)
    {
        for (size_t j=0; j<COLS; ++j)
        {
            ASSERT_GT(testGrid(i, j), 0.0f)
                << "Slices incomplete at (" << i
                << ", " << j << "). Slices: " << slices;

            ASSERT_LT(testGrid(i, j), 2.0f)
                << "Slices overlap at (" << i
                << ", " << j << "). Slices: " << slices;
        }
    }
}

TEST_F(MatrixSlicingTest, SingleNodeKeepsWholeMatrixTest)
{
    auto slices = slicer.sliceAndDice({{0, 0}}, ROWS, COLS);
    ASSERT_EQ(slices.size(), (size_t)1);

    auto slice = slices[0];
    EXPECT_EQ(slice.getStartX(), (size_t)0);
    EXPECT_EQ(slice.getStartY(), (size_t)0);
    EXPECT_EQ(slice.getRows(), ROWS);
    EXPECT_EQ(slice.getColumns(), COLS);
}

TEST_F(MatrixSlicingTest, OneSlicePerNodeTest)
{
    for (size_t count : NODE_COUNTS)
    {
        auto slices = slicer.sliceAndDice(makeUniformRatings(count), ROWS, COLS);
        EXPECT_EQ(slices.size(), count);
    }
}

TEST_F(MatrixSlicingTest, ValidSlicesTest)
{
    for (size_t count : NODE_COUNTS)
    {
        auto ratings = makeUniformRatings(count);
        auto slices = slicer.sliceAndDice(ratings, ROWS, COLS);
        TestGrid testGrid = fillTestGrid(ROWS, COLS, slices, ratings);
        if (HasFatalFailure()) return;

        checkTestGrid(testGrid, slices);
        if (HasFatalFailure()) return;
    }
}
<commit_msg>Removed bogus node count from NODE_COUNTS<commit_after>#include "MatrixSlicingTest.h"
#include <matrix/Matrix.h>
#include <matrix/MatrixHelper.h>
#include <matrix/MatrixSlice.h>
#include <algorithm>
#include <cstddef>

const size_t ROWS = 910;
const size_t COLS = 735;
const size_t NODE_COUNTS[] = { 1, 2, 3, 5, 7, 12, 25, 80, 110, 127 };

typedef Matrix<float> TestGrid;

using namespace std;
typedef MatrixSlicer::SliceList SliceList;

ostream& operator<<(ostream& stream, const MatrixSlice& slice)
{
    return stream
        << "("
        << slice.getStartX() << ", "
        << slice.getStartY() << ", "
        << slice.getColumns() << ", "
        << slice.getRows() << ")";
}

ostream& operator<<(ostream& stream, const SliceList& slices)
{
    stream << "[";
    bool first = true;
    for (const auto& slice : slices)
    {
        if (!first)
            stream << ", ";
        stream << slice;
        first = false;
    }
    stream << "]";

    return stream;
}

BenchmarkResult makeUniformRatings(size_t number)
{
    BenchmarkResult ratings;
    for (size_t i=0; i<number; ++i)
    {
        ratings[i] = 100/number;
    }
    return ratings;
}

TestGrid setupTestGrid(size_t rows, size_t cols)
{
    TestGrid testGrid(rows, cols);
    MatrixHelper::fill(testGrid, [](){ return 0.0f; });
    return testGrid;
}

string makeErrorMsg(size_t nodeCount, const MatrixSlice& slice)
{
    stringstream errorMsg;
    errorMsg
        << " out of bounds. Nodes: "
        << nodeCount << ", Slice: " << slice;
    return errorMsg.str();
}

void applySliceToTestGrid(const MatrixSlice& slice, TestGrid* grid, size_t nodeCount)
{
    for (size_t i=0; i<slice.getRows(); ++i)
    {
        for (size_t j=0; j<slice.getColumns(); ++j)
        {
            auto row = i + slice.getStartY();
            auto col = j + slice.getStartX();
            ASSERT_LT(row, grid->rows()) << "Row" << makeErrorMsg(nodeCount, slice);
            ASSERT_LT(col, grid->columns()) << "Column" << makeErrorMsg(nodeCount, slice);
            (*grid)(row, col) += 1.0f;
        }
    }
}

TestGrid fillTestGrid(size_t rows, size_t cols, const SliceList& slices, const BenchmarkResult& ratings)
{
    TestGrid testGrid = setupTestGrid(rows, cols);
    for (const MatrixSlice& slice : slices)
    {
        applySliceToTestGrid(slice, &testGrid, ratings.size());
        if (testing::Test::HasFatalFailure()) break;
    }

    return testGrid;
}

TestGrid makeTestGrid(size_t nodeCount, const MatrixSlicer& slicer)
{
    auto ratings = makeUniformRatings(nodeCount);
    auto slices = slicer.sliceAndDice(ratings, ROWS, COLS);
    return fillTestGrid(ROWS, COLS, slices, ratings);
}

void checkTestGrid(const TestGrid& testGrid, const SliceList& slices)
{
    for(size_t i=0; i<ROWS; ++i)
    {
        for (size_t j=0; j<COLS; ++j)
        {
            ASSERT_GT(testGrid(i, j), 0.0f)
                << "Slices incomplete at (" << i
                << ", " << j << "). Slices: " << slices;

            ASSERT_LT(testGrid(i, j), 2.0f)
                << "Slices overlap at (" << i
                << ", " << j << "). Slices: " << slices;
        }
    }
}

TEST_F(MatrixSlicingTest, SingleNodeKeepsWholeMatrixTest)
{
    auto slices = slicer.sliceAndDice({{0, 0}}, ROWS, COLS);
    ASSERT_EQ(slices.size(), (size_t)1);

    auto slice = slices[0];
    EXPECT_EQ(slice.getStartX(), (size_t)0);
    EXPECT_EQ(slice.getStartY(), (size_t)0);
    EXPECT_EQ(slice.getRows(), ROWS);
    EXPECT_EQ(slice.getColumns(), COLS);
}

TEST_F(MatrixSlicingTest, OneSlicePerNodeTest)
{
    for (size_t count : NODE_COUNTS)
    {
        auto slices = slicer.sliceAndDice(makeUniformRatings(count), ROWS, COLS);
        EXPECT_EQ(slices.size(), count);
    }
}

TEST_F(MatrixSlicingTest, ValidSlicesTest)
{
    for (size_t count : NODE_COUNTS)
    {
        auto ratings = makeUniformRatings(count);
        auto slices = slicer.sliceAndDice(ratings, ROWS, COLS);
        TestGrid testGrid = fillTestGrid(ROWS, COLS, slices, ratings);
        if (HasFatalFailure()) return;

        checkTestGrid(testGrid, slices);
        if (HasFatalFailure()) return;
    }
}
<|endoftext|>