text:
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "netbase.h"
#include "util.h"
#include "hash.h"

#ifndef WIN32
#ifdef ANDROID
#include <fcntl.h>
#else
#include <sys/fcntl.h>
#endif
#endif

#ifdef _MSC_VER
#include <BaseTsd.h>
typedef SSIZE_T ssize_t;
#endif

#include <boost/algorithm/string/case_conv.hpp> // for to_lower()
#include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()

CCriticalSection netbase::manage::cs_proxyInfos;
netbase::proxyType netbase::manage::proxyInfo[netbase::NET_MAX];
netbase::proxyType netbase::manage::nameproxyInfo;
const unsigned char CNetAddr::pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
const unsigned char CNetAddr::pchOnionCat[6] = { 0xFD, 0x87, 0xD8, 0x7E, 0xEB, 0x43 };
const unsigned char CNetAddr::pchGarliCat[6] = { 0xFD, 0x60, 0xDB, 0x4D, 0xDD, 0xB5 };
const int CNetAddr::NET_UNKNOWN = netbase::NET_MAX + 0;
const int CNetAddr::NET_TEREDO = netbase::NET_MAX + 1;
int netbase::nConnectTimeout = 5000;
bool netbase::fNameLookup = false;

enum netbase::Network netbase::manage::ParseNetwork(std::string net)
{
    boost::to_lower(net);
    if (net == "ipv4") {return netbase::NET_IPV4;}
    if (net == "ipv6") {return netbase::NET_IPV6;}
    if (net == "tor" || net == "onion") {return netbase::NET_TOR;}
    if (net == "i2p") {return netbase::NET_I2P;}
    return netbase::NET_UNROUTABLE;
}

void netbase::manage::SplitHostPort(std::string in, uint16_t &portOut, std::string &hostOut)
{
    const size_t colon = in.find_last_of(':');

    // if a : is found, and it either follows a [...], or no other : is in the string, treat it as port separator
    bool fHaveColon = (colon != in.npos);
    bool fBracketed = (fHaveColon && (in[0]=='[' && in[colon - 1]==']'));    // if there is a colon, and in[0]=='[', colon is not 0, so in[colon-1] is safe
    bool fMultiColon = (fHaveColon && (in.find_last_of(':',colon - 1) != in.npos));

    if (fHaveColon && (colon==0 || fBracketed || !fMultiColon)) {
        char *endp = NULL;
        int n = ::strtol(in.c_str() + colon + 1, &endp, 10);
        if (endp && *endp == 0 && n >= 0) {
            in = in.substr(0, colon);
            if (n > 0 && n < 0x10000) {
                portOut = n;
            }
        }
    }
    if (in.size()>0 && in[0] == '[' && in[in.size() - 1] == ']') {
        hostOut = in.substr(1, in.size() - 2);
    } else {
        hostOut = in;
    }
}

bool netbase::manage::LookupIntern(const char *pszName, std::vector<CNetAddr> &vIP, unsigned int nMaxSolutions, bool fAllowLookup)
{
    vIP.clear();

    {
        CNetAddr addr;
        if (addr.SetSpecial(std::string(pszName))) {
            vIP.push_back(addr);
            return true;
        }
    }

    struct addrinfo aiHint = { 0 };

    aiHint.ai_socktype = SOCK_STREAM;
    aiHint.ai_protocol = IPPROTO_TCP;
#ifdef USE_IPV6
    aiHint.ai_family = AF_UNSPEC;
#else
    aiHint.ai_family = AF_INET;
#endif

#ifdef WIN32
    aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
#else
    aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
#endif

    struct addrinfo *aiRes = NULL;
    int nErr = ::getaddrinfo(pszName, NULL, &aiHint, &aiRes);
    if (nErr) {
        return false;
    }

    struct addrinfo *aiTrav = aiRes;
    while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions))
    {
        switch (aiTrav->ai_family)
        {
        case (AF_INET):
            assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in));
            vIP.push_back(CNetAddr(((struct sockaddr_in *)(aiTrav->ai_addr))->sin_addr));
            break;

#ifdef USE_IPV6
        case (AF_INET6):
            assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6));
            vIP.push_back(CNetAddr(((struct sockaddr_in6 *)(aiTrav->ai_addr))->sin6_addr));
            break;
#endif
        }

        aiTrav = aiTrav->ai_next;
    }

    ::freeaddrinfo(aiRes);
    return (vIP.size() > 0);
}

bool netbase::manage::LookupHost(const char *pszName, std::vector<CNetAddr> &vIP, unsigned int nMaxSolutions /* = 0 */, bool fAllowLookup /* = true */)
{
    std::string strHost(pszName);
    if (strHost.empty()) {
        return false;
    }
    if (boost::algorithm::starts_with(strHost, "[") && boost::algorithm::ends_with(strHost, "]")) {
        strHost = strHost.substr(1, strHost.size() - 2);
    }

    return netbase::manage::LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
}

bool netbase::manage::Lookup(const char *pszName, std::vector<CService> &vAddr, uint16_t portDefault /* = 0 */, bool fAllowLookup /* = true */, unsigned int nMaxSolutions /* = 0 */)
{
    if (pszName[0] == 0) {
        return false;
    }

    uint16_t port = portDefault;
    std::string hostname = "";
    SplitHostPort(std::string(pszName), port, hostname);

    std::vector<CNetAddr> vIP;
    bool fRet = netbase::manage::LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
    if (! fRet) {
        return false;
    }

    vAddr.resize(vIP.size());
    for (unsigned int i = 0; i < vIP.size(); ++i)
    {
        vAddr[i] = CService(vIP[i], port);
    }
    return true;
}

bool netbase::manage::Lookup(const char *pszName, CService &addr, uint16_t portDefault /* = 0 */, bool fAllowLookup /* = true */)
{
    std::vector<CService> vService;
    bool fRet = netbase::manage::Lookup(pszName, vService, portDefault, fAllowLookup, 1);
    if (! fRet) {
        return false;
    }

    addr = vService[0];
    return true;
}

bool netbase::manage::LookupNumeric(const char *pszName, CService &addr, uint16_t portDefault /* = 0 */)
{
    return netbase::manage::Lookup(pszName, addr, portDefault, false);
}

bool netbase::manage::Socks4(const CService &addrDest, SOCKET &hSocket)
{
    printf("SOCKS4 connecting %s\n", addrDest.ToString().c_str());
    if (! addrDest.IsIPv4()) {
        netbase::manage::CloseSocket(hSocket);
        return print::error("Proxy destination is not IPv4");
    }

    char pszSocks4IP[] = "\4\1\0\0\0\0\0\0user";
    struct sockaddr_in addr;
    socklen_t len = sizeof(addr);
    if (!addrDest.GetSockAddr((struct sockaddr *)&addr, &len) || addr.sin_family != AF_INET) {
        netbase::manage::CloseSocket(hSocket);
        return print::error("Cannot get proxy destination address");
    }

    ::memcpy(pszSocks4IP + 2, &addr.sin_port, 2);
    ::memcpy(pszSocks4IP + 4, &addr.sin_addr, 4);
    char *pszSocks4 = pszSocks4IP;
    int nSize = sizeof(pszSocks4IP);

    int ret = ::send(hSocket, pszSocks4, nSize, MSG_NOSIGNAL);
    if (ret != nSize) {
        netbase::manage::CloseSocket(hSocket);
        return print::error("Error sending to proxy");
    }

    char pchRet[8];
    if (::recv(hSocket, pchRet, 8, 0) != 8) {
        netbase::manage::CloseSocket(hSocket);
        return print::error("Error reading proxy response");
    }
    if (pchRet[1] != 0x5a) {
        netbase::manage::CloseSocket(hSocket);
        if (pchRet[1] != 0x5b) {
            printf("ERROR: Proxy returned error %d\n", pchRet[1]);
        }
        return false;
    }

    printf("SOCKS4 connected %s\n", addrDest.ToString().c_str());
    return true;
}

bool netbase::manage::Socks5(std::string strDest, uint16_t port, SOCKET &hSocket)
{
    printf("SOCKS5 connecting %s\n", strDest.c_str());
    if (strDest.size() > 255) {
        netbase::manage::CloseSocket(hSocket);
        return print::error("Hostname too long");
    }

    const char pszSocks5Init[] = "\5\1\0";
    ssize_t ret = ::send(hSocket, pszSocks5Init, 3, MSG_NOSIGNAL);
    if (ret != 3) {
        netbase::manage::CloseSocket(hSocket);
        return print::error("Error sending to proxy");
    }

    char pchRet1[2];
    if (recv(hSocket, pchRet1, 2, 0) != 2) {
        netbase::manage::CloseSocket(hSocket);
        return print::error("Error reading proxy response");
    }
    if (pchRet1[0] != 0x05 || pchRet1[1] != 0x00) {
        netbase::manage::CloseSocket(hSocket);
        return print::error("Proxy failed to initialize");
    }

    std::string strSocks5("\5\1");
    strSocks5 += '\000'; strSocks5 += '\003';
    strSocks5 += static_cast<char>(std::min((int)strDest.size(), 255));
    strSocks5 += strDest;
    strSocks5 += static_cast<char>((port >> 8) & 0xFF);
    strSocks5 += static_cast<char>((port >> 0) & 0xFF);
    ret = ::send(hSocket, strSocks5.data(), strSocks5.size(), MSG_NOSIGNAL);
    if (ret != (ssize_t)strSocks5.size()) {
        netbase::manage::CloseSocket(hSocket);
        return print::error("Error sending to proxy");
    }

    char pchRet2[4];
    if (::recv(hSocket, pchRet2, 4, 0) != 4) {
        netbase::manage::CloseSocket(hSocket);
        return print::error("Error reading proxy response");
    }
    if (pchRet2[0] != 0x05) {
        netbase::manage::CloseSocket(hSocket);
        return print::error("Proxy failed to accept request");
    }
    if (pchRet2[1] != 0x00) {
        netbase::manage::CloseSocket(hSocket);
        switch (pchRet2[1])
        {
        case 0x01: return print::error("Proxy error: general failure");
        case 0x02: return print::error("Proxy error: connection not allowed");
        case 0x03: return print::error("Proxy error: network unreachable");
        case 0x04: return print::error("Proxy error: host unreachable");
        case 0x05: return print::error("Proxy error: connection refused");
        case 0x06: return print::error("Proxy error: TTL expired");
        case 0x07: return print::error("Proxy error: protocol error");
        case 0x08: return print::error("Proxy error: address type not supported");
        default:   return print::error("Proxy error: unknown");
        }
        /// return;
    }

    if (pchRet2[2] != 0x00) {
        netbase::manage::CloseSocket(hSocket);
        return print::error("Error: malformed proxy response");
    }

    char pchRet3[256];
    switch (pchRet2[3])
    {
    case 0x01: ret = ::recv(hSocket, pchRet3, 4, 0) != 4; break;
    case 0x04: ret = ::recv(hSocket, pchRet3, 16, 0) != 16; break;
    case 0x03:
        {
            ret = ::recv(hSocket, pchRet3, 1, 0) != 1;
            if (ret) {
                netbase::manage::CloseSocket(hSocket);
                return print::error("Error reading from proxy");
            }
            int nRecv = pchRet3[0];
            ret = ::recv(hSocket, pchRet3, nRecv, 0) != nRecv;
            break;
        }
    default: netbase::manage::CloseSocket(hSocket); return print::error("Error: malformed proxy response");
    }

    if (ret) {
        netbase::manage::CloseSocket(hSocket);
        return print::error("Error reading from proxy");
    }
    if (::recv(hSocket, pchRet3, 2, 0) != 2) {
        netbase::manage::CloseSocket(hSocket);
        return print::error("Error reading from proxy");
    }

    printf("SOCKS5 connected %s\n", strDest.c_str());
    return true;
}

bool netbase::manage::ConnectSocketDirectly(const CService &addrConnect, SOCKET &hSocketRet, int nTimeout)
{
    hSocketRet = INVALID_SOCKET;

#ifdef USE_IPV6
    struct sockaddr_storage sockaddr;
#else
    struct sockaddr sockaddr;
#endif

    socklen_t len = sizeof(sockaddr);
    if (! addrConnect.GetSockAddr((struct sockaddr *)&sockaddr, &len)) {
        printf("Cannot connect to %s: unsupported network\n", addrConnect.ToString().c_str());
        return false;
    }

    SOCKET hSocket = ::socket(((struct sockaddr *)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
    if (hSocket == INVALID_SOCKET) {
        return false;
    }

#ifdef SO_NOSIGPIPE
    int set = 1;
    ::setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void *)&set, sizeof(int));
#endif

#ifdef WIN32
    u_long fNonblock = 1;
    if (::ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
#else
    int fFlags = ::fcntl(hSocket, F_GETFL, 0);
    if (::fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == -1)
#endif
    {
        netbase::manage::CloseSocket(hSocket);
        return false;
    }

    if (::connect(hSocket, (struct sockaddr *)&sockaddr, len) == SOCKET_ERROR) {
        int nErr = WSAGetLastError();

        // WSAEINVAL is here because some legacy version of winsock uses it
        if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
            struct timeval timeout;
            timeout.tv_sec  = nTimeout / 1000;
            timeout.tv_usec = (nTimeout % 1000) * 1000;

            fd_set fdset;
            FD_ZERO(&fdset);
            FD_SET(hSocket, &fdset);
            int nRet = ::select(hSocket + 1, NULL, &fdset, NULL, &timeout);
            if (nRet == 0) {
                printf("connection timeout\n");
                netbase::manage::CloseSocket(hSocket);
                return false;
            }
            if (nRet == SOCKET_ERROR) {
                printf("select() for connection failed: %i\n",WSAGetLastError());
                netbase::manage::CloseSocket(hSocket);
                return false;
            }

            socklen_t nRetSize = sizeof(nRet);
#ifdef WIN32
            if (::getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
#else
            if (::getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
#endif
            {
                printf("getsockopt() for connection failed: %i\n",WSAGetLastError());
                netbase::manage::CloseSocket(hSocket);
                return false;
            }
            if (nRet != 0) {
                printf("connect() failed after select(): %s\n",strerror(nRet));
                netbase::manage::CloseSocket(hSocket);
                return false;
            }
        }
#ifdef WIN32
        else if (::WSAGetLastError() != WSAEISCONN)
#else
        else
#endif
        {
            printf("connect() failed: %i\n",WSAGetLastError());
            netbase::manage::CloseSocket(hSocket);
            return false;
        }
    }

    // this isn't even strictly necessary
    // ConnectNode immediately turns the socket back to non-blocking
    // but we'll turn it back to blocking just in case
#ifdef WIN32
    fNonblock = 0;
    if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
#else
    fFlags = fcntl(hSocket, F_GETFL, 0);
    if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR)
#endif
    {
        netbase::manage::CloseSocket(hSocket);
        return false;
    }

    hSocketRet = hSocket;
    return true;
}

bool netbase::manage::SetProxy(enum netbase::Network net, CService addrProxy, int nSocksVersion /* = 5 */) {
    assert(net >= 0 && net < NET_MAX);
    if (nSocksVersion != 0 && nSocksVersion != 4 && nSocksVersion != 5) {
        return false;
    }
    if (nSocksVersion != 0 && !addrProxy.IsValid()) {
        return false;
    }

    LOCK(manage::cs_proxyInfos);
    manage::proxyInfo[net] = std::make_pair(addrProxy, nSocksVersion);
    return true;
}

bool netbase::manage::GetProxy(enum netbase::Network net, netbase::proxyType &proxyInfoOut) {
    assert(net >= 0 && net < NET_MAX);
    LOCK(manage::cs_proxyInfos);
    if (! proxyInfo[net].second) {
        return false;
    }

    proxyInfoOut = manage::proxyInfo[net];
    return true;
}

bool netbase::manage::SetNameProxy(CService addrProxy, int nSocksVersion /* = 5 */) {
    if (nSocksVersion != 0 && nSocksVersion != 5) {
        return false;
    }
    if (nSocksVersion != 0 && !addrProxy.IsValid()) {
        return false;
    }

    LOCK(manage::cs_proxyInfos);
    manage::nameproxyInfo = std::make_pair(addrProxy, nSocksVersion);
    return true;
}

bool netbase::manage::GetNameProxy(proxyType &nameproxyInfoOut) {
    LOCK(manage::cs_proxyInfos);
    if (! nameproxyInfo.second) {
        return false;
    }

    nameproxyInfoOut = manage::nameproxyInfo;
    return true;
}

bool netbase::manage::HaveNameProxy() {
    LOCK(manage::cs_proxyInfos);
    return nameproxyInfo.second != 0;
}

bool netbase::manage::IsProxy(const CNetAddr &addr) {
    LOCK(manage::cs_proxyInfos);
    for (int i = 0; i < netbase::NET_MAX; ++i)
    {
        if (manage::proxyInfo[i].second && (addr == (CNetAddr)manage::proxyInfo[i].first)) {
            return true;
        }
    }
    return false;
}

bool netbase::manage::ConnectSocket(const CService &addrDest, SOCKET &hSocketRet, int nTimeout /* = netbase::nConnectTimeout */)
{
    proxyType proxy;

    // no proxy needed
    if (! manage::GetProxy(addrDest.GetNetwork(), proxy)) {
        return manage::ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);
    }

    SOCKET hSocket = INVALID_SOCKET;

    // first connect to proxy server
    if (! manage::ConnectSocketDirectly(proxy.first, hSocket, nTimeout)) {
        return false;
    }

    // do socks negotiation
    switch (proxy.second)
    {
    case 4:
        if (! manage::Socks4(addrDest, hSocket)) {
            return false;
        }
        break;
    case 5:
        if (! manage::Socks5(addrDest.ToStringIP(), addrDest.GetPort(), hSocket)) {
            return false;
        }
        break;
    default:
        netbase::manage::CloseSocket(hSocket);
        return false;
    }

    hSocketRet = hSocket;
    return true;
}

bool netbase::manage::ConnectSocketByName(CService &addr, SOCKET &hSocketRet, const char *pszDest, uint16_t portDefault /* = 0 */, int nTimeout /* = netbase::nConnectTimeout */)
{
    std::string strDest;
    uint16_t port = portDefault;
    manage::SplitHostPort(std::string(pszDest), port, strDest);

    SOCKET hSocket = INVALID_SOCKET;

    proxyType nameproxy;
    manage::GetNameProxy(nameproxy);

    CService addrResolved(CNetAddr(strDest, netbase::fNameLookup && !nameproxy.second), port);
    if (addrResolved.IsValid()) {
        addr = addrResolved;
        return ConnectSocket(addr, hSocketRet, nTimeout);
    }

    addr = CService("0.0.0.0:0");
    if (! nameproxy.second) {
        return false;
    }
    if (! manage::ConnectSocketDirectly(nameproxy.first, hSocket, nTimeout)) {
        return false;
    }

    switch(nameproxy.second)
    {
    default:
    case 4:
        netbase::manage::CloseSocket(hSocket);
        return false;
    case 5:
        if (! manage::Socks5(strDest, port, hSocket)) {
            return false;
        }
        break;
    }

    hSocketRet = hSocket;
    return true;
}

bool netbase::manage::CloseSocket(SOCKET &hSocket)
{
    if (hSocket == INVALID_SOCKET) {
        return false;
    }

#ifdef WIN32
    int ret = ::closesocket(hSocket);
#else
    int ret = ::close(hSocket);
#endif

    hSocket = INVALID_SOCKET;
    return ret != SOCKET_ERROR;
}

///////////////////////////////////////////////////////////////////////////////////////////////////

void CNetAddr::Init()
{
    ::memset(ip, 0, sizeof(ip));
}

void CNetAddr::SetIP(const CNetAddr &ipIn)
{
    ::memcpy(ip, ipIn.ip, sizeof(ip));
}

bool CNetAddr::SetSpecial(const std::string &strName)
{
    if (strName.size() > 6 && strName.substr(strName.size() - 6, 6) == ".onion") {
        std::vector<unsigned char> vchAddr = base32::DecodeBase32(strName.substr(0, strName.size() - 6).c_str());
        if (vchAddr.size() != 16 - sizeof(pchOnionCat)) {
            return false;
        }

        ::memcpy(ip, pchOnionCat, sizeof(pchOnionCat));
        for (unsigned int i=0; i < 16 - sizeof(pchOnionCat); ++i)
        {
            ip[i + sizeof(pchOnionCat)] = vchAddr[i];
        }
        return true;
    }

    if (strName.size() > 11 && strName.substr(strName.size() - 11, 11) == ".oc.b32.i2p") {
        std::vector<unsigned char> vchAddr = base32::DecodeBase32(strName.substr(0, strName.size() - 11).c_str());
        if (vchAddr.size() != 16 - sizeof(pchGarliCat)) {
            return false;
        }

        ::memcpy(ip, pchOnionCat, sizeof(pchGarliCat));
        for (unsigned int i=0; i<16-sizeof(pchGarliCat); ++i)
        {
            ip[i + sizeof(pchGarliCat)] = vchAddr[i];
        }
        return true;
    }
    return false;
}

CNetAddr::CNetAddr()
{
    Init();
}

CNetAddr::CNetAddr(const struct in_addr &ipv4Addr)
{
    ::memcpy(ip, CNetAddr::pchIPv4, 12);
    ::memcpy(ip + 12, &ipv4Addr, 4);
}

#ifdef USE_IPV6
CNetAddr::CNetAddr(const struct in6_addr &ipv6Addr)
{
    ::memcpy(ip, &ipv6Addr, 16);
}
#endif

CNetAddr::CNetAddr(const char *pszIp, bool fAllowLookup)
{
    Init();
    std::vector<CNetAddr> vIP;
    if (netbase::manage::LookupHost(pszIp, vIP, 1, fAllowLookup)) {
        *this = vIP[0];
    }
}

CNetAddr::CNetAddr(const std::string &strIp, bool fAllowLookup)
{
    Init();
    std::vector<CNetAddr> vIP;
    if (netbase::manage::LookupHost(strIp.c_str(), vIP, 1, fAllowLookup)) {
        *this = vIP[0];
    }
}

uint8_t CNetAddr::GetByte(int n) const
{
    return ip[15 - n];
}

bool CNetAddr::IsIPv4() const
{
    return (::memcmp(ip, CNetAddr::pchIPv4, sizeof(pchIPv4)) == 0);
}

bool CNetAddr::IsIPv6() const
{
    return (!IsIPv4() && !IsTor() && !IsI2P());
}

bool CNetAddr::IsRFC1918() const
{
    return  IsIPv4() && (
            GetByte(3) == 10 ||
            (GetByte(3) == 192 && GetByte(2) == 168) ||
            (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
}

bool CNetAddr::IsRFC3927() const
{
    return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
}

bool CNetAddr::IsRFC3849() const
{
    return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
}

bool CNetAddr::IsRFC3964() const
{
    return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
}

bool CNetAddr::IsRFC6052() const
{
    static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
    return (::memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0);
}

bool CNetAddr::IsRFC4380() const
{
    return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
}

bool CNetAddr::IsRFC4862() const
{
    static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0};
    return (::memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);
}

bool CNetAddr::IsRFC4193() const
{
    return ((GetByte(15) & 0xFE) == 0xFC);
}

bool CNetAddr::IsRFC6145() const
{
    static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
    return (::memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0);
}

bool CNetAddr::IsRFC4843() const
{
    return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10);
}

bool CNetAddr::IsTor() const
{
    return (memcmp(ip, pchOnionCat, sizeof(pchOnionCat)) == 0);
}

bool CNetAddr::IsI2P() const
{
    return (::memcmp(ip, pchGarliCat, sizeof(pchGarliCat)) == 0);
}

bool CNetAddr::IsLocal() const
{
    // IPv4 loopback
    if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0)) {
       return true;
    }

    // IPv6 loopback (::1/128)
    static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
    if (::memcmp(ip, pchLocal, 16) == 0) {
        return true;
    }

    return false;
}

bool CNetAddr::IsMulticast() const
{
    return    (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0)
           || (GetByte(15) == 0xFF);
}

bool CNetAddr::IsValid() const
{
    //
    // Cleanup 3-byte shifted addresses caused by garbage in size field
    // of addr messages from versions before 0.2.9 checksum.
    // Two consecutive addr messages look like this:
    // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
    // so if the first length field is garbled, it reads the second batch
    // of addr misaligned by 3 bytes.
    //
    if (::memcmp(ip, CNetAddr::pchIPv4 + 3, sizeof(pchIPv4) - 3) == 0) {
        return false;
    }

    // unspecified IPv6 address (::/128)
    unsigned char ipNone[16] = {};
    if (::memcmp(ip, ipNone, 16) == 0) {
        return false;
    }

    // documentation IPv6 address
    if (IsRFC3849()) {
        return false;
    }

    if (IsIPv4()) {
        // INADDR_NONE
        uint32_t ipNone = INADDR_NONE;
        if (::memcmp(ip + 12, &ipNone, 4) == 0) {
            return false;
        }

        // 0
        ipNone = 0;
        if (::memcmp(ip + 12, &ipNone, 4) == 0) {
            return false;
        }
    }

    return true;
}

bool CNetAddr::IsRoutable() const
{
    return IsValid() && !(IsRFC1918() || IsRFC3927() || IsRFC4862() || (IsRFC4193() && !IsTor() && !IsI2P()) || IsRFC4843() || IsLocal());
}

enum netbase::Network CNetAddr::GetNetwork() const
{
    if (! IsRoutable()) {
        return netbase::NET_UNROUTABLE;
    }

    if (IsIPv4()) {
        return netbase::NET_IPV4;
    }

    if (IsTor()) {
        return netbase::NET_TOR;
    }

    if (IsI2P()) {
        return netbase::NET_I2P;
    }

    return netbase::NET_IPV6;
}

std::string CNetAddr::ToStringIP() const
{
    if (IsTor()) {
        return base32::EncodeBase32(&ip[6], 10) + ".onion";
    }
    if (IsI2P()) {
        return base32::EncodeBase32(&ip[6], 10) + ".oc.b32.i2p";
    }

    CService serv(*this, (uint16_t)0);
#ifdef USE_IPV6
    struct sockaddr_storage sockaddr;
#else
    struct sockaddr sockaddr;
#endif
    socklen_t socklen = sizeof(sockaddr);
    if (serv.GetSockAddr((struct sockaddr *)&sockaddr, &socklen)) {
        char name[1025] = "";
        if (! getnameinfo((const struct sockaddr *)&sockaddr, socklen, name, sizeof(name), NULL, 0, NI_NUMERICHOST)) {
            return std::string(name);
        }
    }

    if (IsIPv4()) {
        return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
    } else {
        return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
                         GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
                         GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
                         GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
                         GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
    }
}

std::string CNetAddr::ToString() const
{
    return ToStringIP();
}

bool CNetAddr::GetInAddr(struct in_addr *pipv4Addr) const
{
    if (! IsIPv4()) {
        return false;
    }

    ::memcpy(pipv4Addr, ip + 12, 4);
    return true;
}

#ifdef USE_IPV6
bool CNetAddr::GetIn6Addr(struct in6_addr *pipv6Addr) const
{
    ::memcpy(pipv6Addr, ip, 16);
    return true;
}
#endif

// get canonical identifier of an address' group
// no two connections will be attempted to addresses with the same group
std::vector<unsigned char> CNetAddr::GetGroup() const
{
    std::vector<unsigned char> vchRet;
    uint8_t nClass = netbase::NET_IPV6;
    int nStartByte = 0;
    int nBits = 16;

    // all local addresses belong to the same group
    if (IsLocal()) {
        nClass = 255;
        nBits = 0;
    }

    if (! IsRoutable()) {
        // all unroutable addresses belong to the same group
        nClass = netbase::NET_UNROUTABLE;
        nBits = 0;
    } else if (IsIPv4() || IsRFC6145() || IsRFC6052()) {
        // for IPv4 addresses, '1' + the 16 higher-order bits of the IP
        // includes mapped IPv4, SIIT translated IPv4, and the well-known prefix
        nClass = netbase::NET_IPV4;
        nStartByte = 12;
    } else if (IsRFC3964()) {
        // for 6to4 tunnelled addresses, use the encapsulated IPv4 address
        nClass = netbase::NET_IPV4;
        nStartByte = 2;
    } else if (IsRFC4380()) {
        // for Teredo-tunnelled IPv6 addresses, use the encapsulated IPv4 address
        vchRet.push_back(netbase::NET_IPV4);
        vchRet.push_back(GetByte(3) ^ 0xFF);
        vchRet.push_back(GetByte(2) ^ 0xFF);
        return vchRet;
    } else if (IsTor()) {
        nClass = netbase::NET_TOR;
        nStartByte = 6;
        nBits = 4;
    } else if (IsI2P()) {
        nClass = netbase::NET_I2P;
        nStartByte = 6;
        nBits = 4;
    } else if (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && GetByte(12) == 0x70) {
        // for he.net, use /36 groups
        nBits = 36;
    } else {
        // for the rest of the IPv6 network, use /32 groups
        nBits = 32;
    }

    vchRet.push_back(nClass);
    while (nBits >= 8)
    {
        vchRet.push_back(GetByte(15 - nStartByte));
        nStartByte++;
        nBits -= 8;
    }
    if (nBits > 0) {
        vchRet.push_back(GetByte(15 - nStartByte) | ((1 << nBits) - 1));
    }

    return vchRet;
}

uint64_t CNetAddr::GetHash() const
{
    uint256 hash = hash_basis::Hash(&ip[0], &ip[16]);
    uint64_t nRet;
    ::memcpy(&nRet, &hash, sizeof(nRet));
    return nRet;
}

/** Calculates a metric for how reachable (*this) is from a given partner */
int CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const
{
    enum Reachability
    {
        REACH_UNREACHABLE,
        REACH_DEFAULT,
        REACH_TEREDO,
        REACH_IPV6_WEAK,
        REACH_IPV4,
        REACH_IPV6_STRONG,
        REACH_PRIVATE
    };

    if (! IsRoutable()) {
        return REACH_UNREACHABLE;
    }

    int ourNet = GetExtNetwork(this);
    int theirNet = GetExtNetwork(paddrPartner);
    bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145();

    switch(theirNet)
    {
    case netbase::NET_IPV4:
        switch(ourNet)
        {
        default:
            return REACH_DEFAULT;
        case netbase::NET_IPV4:
            return REACH_IPV4;
        }
    case netbase::NET_IPV6:
        switch(ourNet)
        {
        default:
            return REACH_DEFAULT;
        case NET_TEREDO:
            return REACH_TEREDO;
        case netbase::NET_IPV4:
            return REACH_IPV4;
        case netbase::NET_IPV6:
            return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; // only prefer giving our IPv6 address if it's not tunnelled
        }
    case netbase::NET_TOR:
        switch(ourNet)
        {
        default:
            return REACH_DEFAULT;
        case netbase::NET_IPV4:
            return REACH_IPV4; // Tor users can connect to IPv4 as well
        case netbase::NET_TOR:
            return REACH_PRIVATE;
        }
    case netbase::NET_I2P:
        switch(ourNet)
        {
        default:
            return REACH_DEFAULT;
        case netbase::NET_I2P:
            return REACH_PRIVATE;
        }
    case NET_TEREDO:
        switch(ourNet)
        {
        default:
            return REACH_DEFAULT;
        case NET_TEREDO:
            return REACH_TEREDO;
        case netbase::NET_IPV6:
            return REACH_IPV6_WEAK;
        case netbase::NET_IPV4:
            return REACH_IPV4;
        }
    case NET_UNKNOWN:
    case netbase::NET_UNROUTABLE:
    default:
        switch(ourNet)
        {
        default:
            return REACH_DEFAULT;
        case NET_TEREDO:
            return REACH_TEREDO;
        case netbase::NET_IPV6:
            return REACH_IPV6_WEAK;
        case netbase::NET_IPV4:
            return REACH_IPV4;
        case netbase::NET_I2P:
            return REACH_PRIVATE; // assume connections from unroutable addresses are
        case netbase::NET_TOR:
            return REACH_PRIVATE; // either from Tor/I2P, or don't care about our address
        }
    }
}

///////////////////////////////////////////////////////////////////////////////////////////////////

void CService::Init()
{
    port = 0;
}

CService::CService()
{
    Init();
}

CService::CService(const CNetAddr& cip, uint16_t portIn) : CNetAddr(cip), port(portIn) {}

CService::CService(const struct in_addr& ipv4Addr, uint16_t portIn) : CNetAddr(ipv4Addr), port(portIn) {}

#ifdef USE_IPV6
CService::CService(const struct in6_addr& ipv6Addr, uint16_t portIn) : CNetAddr(ipv6Addr), port(portIn){}
#endif

CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))
{
    assert(addr.sin_family == AF_INET);
}

#ifdef USE_IPV6
CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr), port(ntohs(addr.sin6_port))
{
    assert(addr.sin6_family == AF_INET6);
}
#endif

bool CService::SetSockAddr(const struct sockaddr *paddr)
{
    switch (paddr->sa_family)
    {
    case AF_INET:
        *this = CService(*(const struct sockaddr_in *)paddr);
        return true;
#ifdef USE_IPV6
    case AF_INET6:
        *this = CService(*(const struct sockaddr_in6 *)paddr);
        return true;
#endif
    default:
        return false;
    }
}

CService::CService(const char *pszIpPort, bool fAllowLookup)
{
    Init();
    CService ip;
    if (netbase::manage::Lookup(pszIpPort, ip, 0, fAllowLookup)) {
        *this = ip;
    }
}

CService::CService(const char *pszIpPort, uint16_t portDefault, bool fAllowLookup)
{
    Init();
    CService ip;
    if (netbase::manage::Lookup(pszIpPort, ip, portDefault, fAllowLookup)) {
        *this = ip;
    }
}

CService::CService(const std::string &strIpPort, bool fAllowLookup)
{
    Init();
    CService ip;
    if (netbase::manage::Lookup(strIpPort.c_str(), ip, 0, fAllowLookup)) {
        *this = ip;
    }
}

CService::CService(const std::string &strIpPort, uint16_t portDefault, bool fAllowLookup)
{
    Init();
    CService ip;
    if (netbase::manage::Lookup(strIpPort.c_str(), ip, portDefault, fAllowLookup)) {
        *this = ip;
    }
}

unsigned short CService::GetPort() const
{
    return port;
}

bool CService::GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
{
    if (IsIPv4()) {
        if (*addrlen < (socklen_t)sizeof(struct sockaddr_in)) {
            return false;
        }

        *addrlen = sizeof(struct sockaddr_in);
        struct sockaddr_in *paddrin = (struct sockaddr_in *)paddr;
        ::memset(paddrin, 0, *addrlen);
        if (! GetInAddr(&paddrin->sin_addr)) {
            return false;
        }

        paddrin->sin_family = AF_INET;
        paddrin->sin_port = htons(port);
        return true;
    }
#ifdef USE_IPV6
    if (IsIPv6()) {
        if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6)) {
            return false;
        }

        *addrlen = sizeof(struct sockaddr_in6);
        struct sockaddr_in6 *paddrin6 = (struct sockaddr_in6 *)paddr;
        ::memset(paddrin6, 0, *addrlen);
        if (! GetIn6Addr(&paddrin6->sin6_addr)) {
            return false;
        }

        paddrin6->sin6_family = AF_INET6;
        paddrin6->sin6_port = htons(port);
        return true;
    }
#endif
    return false;
}

std::vector<unsigned char> CService::GetKey() const
{
     std::vector<unsigned char> vKey;
     vKey.resize(18);
     ::memcpy(&vKey[0], ip, 16);
     vKey[16] = port / 0x100;
     vKey[17] = port & 0x0FF;
     return vKey;
}

std::string CService::ToStringPort() const
{
    return strprintf("%u", port);
}

std::string CService::ToStringIPPort() const
{
    if (IsIPv4() || IsTor() || IsI2P()) {
        return ToStringIP() + ":" + ToStringPort();
    } else {
        return "[" + ToStringIP() + "]:" + ToStringPort();
    }
}

std::string CService::ToString() const
{
    return ToStringIPPort();
}

void CService::SetPort(unsigned short portIn)
{
    port = portIn;
}

max_stars_repo_name: SorachanCoin/SorachanCoin-qt

max_issues_repo_name: SorachanCoin/SorachanCoin-qt

max_forks_repo_name: SorachanCoin/SorachanCoin-qt


text: #include <boost/units/physical_dimensions/angular_velocity.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include <boost/iostreams/stream.hpp>
#include <ShlObj.h>

#include "skse/PluginAPI.h"
#include "skse/skse_version.h"
#include "skse/GameData.h"
//#include "skse/PapyrusVM.h"
#include "skse/GameForms.h"
#include "skse/GameData.h"

//#include "gtest.h"
#include "skse.h"
#include "util/util.h"
#include "jc_interface.h"
#include "reflection.h"
#include "jcontainers_constants.h"
#include "tes_context.h"

class VMClassRegistry;

namespace jc {
    extern root_interface root;
}

SKSESerializationInterface	* g_serialization = nullptr;

namespace {

    using namespace collections;

    static PluginHandle					g_pluginHandle = kPluginHandle_Invalid;

    static SKSEPapyrusInterface			* g_papyrus = nullptr;
    static SKSEMessagingInterface       * g_messaging = nullptr;

    void revert(SKSESerializationInterface * intfc) {
        util::do_with_timing("Revert", []() {
            collections::tes_context::instance().clearState();
        });
    }

    void save(SKSESerializationInterface * intfc) {

        namespace io = boost::iostreams;

        struct skse_data_sink {
            typedef char      char_type;
            typedef io::sink_tag  category;

            std::streamsize write(const char* s, std::streamsize n) const {
                (void)_sink->WriteRecordData(s, n); // always returns true
                return n;
            }

            SKSESerializationInterface* _sink;
        };

        util::do_with_timing("Save", [intfc]() {
            if (intfc->OpenRecord((UInt32)consts::storage_chunk, (UInt32)serialization_version::current)) {
                io::stream<skse_data_sink> stream(skse_data_sink{ intfc });
                collections::tes_context::instance().write_to_stream(stream);
                //_DMESSAGE("%lu bytes saved", stream.tellp());
            }
            else {
                _DMESSAGE("Unable open JC record");
            }
        });
    }

    void load(SKSESerializationInterface * intfc) {

        namespace io = boost::iostreams;

        class skse_data_source {
        public:
            typedef char char_type;
            typedef io::source_tag  category;

            explicit skse_data_source(SKSESerializationInterface* src = nullptr) : _source(src){}

            std::streamsize read(char* buffer, std::streamsize n) const {
                return _source ? _source->ReadRecordData(buffer, n) : 0;
            }

        private:
            SKSESerializationInterface* _source;
        };

        util::do_with_timing("Load", [intfc]() {

            UInt32 type = 0;
            UInt32 version = 0;
            UInt32 length = 0;

            while (intfc->GetNextRecordInfo(&type, &version, &length)) {
                if (static_cast<consts>(type) == consts::storage_chunk) {
                    break;
                }
            }

            io::stream<skse_data_source> stream(skse_data_source(static_cast<consts>(type) == consts::storage_chunk ? intfc : nullptr));
            collections::tes_context::instance().read_from_stream(stream);
        });
    }

    extern "C" {

        __declspec(dllexport) bool SKSEPlugin_Query(const SKSEInterface * skse, PluginInfo * info) {
            gLog.OpenRelative(CSIDL_MYDOCUMENTS, "\\My Games\\Skyrim\\SKSE\\" JC_PLUGIN_NAME ".log");
            gLog.SetPrintLevel(IDebugLog::kLevel_Error);
            gLog.SetLogLevel(IDebugLog::kLevel_DebugMessage);

            // populate info structure
            info->infoVersion = PluginInfo::kInfoVersion;
            info->name = JC_PLUGIN_NAME;
            info->version = JC_API_VERSION;

            // store plugin handle so we can identify ourselves later
            g_pluginHandle = skse->GetPluginHandle();

            _MESSAGE(JC_PLUGIN_NAME " " JC_VERSION_STR);

            if (skse->isEditor) {
                _MESSAGE("loaded in editor, marking as incompatible");
                return false;
            }
            else if (skse->runtimeVersion != RUNTIME_VERSION_1_9_32_0) {
                _MESSAGE("unsupported runtime version %08X", skse->runtimeVersion);
                return false;
            }

            // get the serialization interface and query its version
            g_serialization = (SKSESerializationInterface *)skse->QueryInterface(kInterface_Serialization);
            if (!g_serialization) {
                _MESSAGE("couldn't get serialization interface");
                return false;
            }

            if (g_serialization->version < SKSESerializationInterface::kVersion) {
                _MESSAGE("serialization interface too old (%d expected %d)", g_serialization->version, SKSESerializationInterface::kVersion);
                return false;
            }

            g_papyrus = (SKSEPapyrusInterface *)skse->QueryInterface(kInterface_Papyrus);

            if (!g_papyrus) {
                _MESSAGE("couldn't get papyrus interface");
                return false;
            }

            auto messaging = (SKSEMessagingInterface *)skse->QueryInterface(kInterface_Messaging);
            if (messaging && messaging->interfaceVersion >= SKSEMessagingInterface::kInterfaceVersion) {
                g_messaging = messaging;
            }

            skse::set_no_fake();

            return true;
        }

        bool registerAllFunctions(VMClassRegistry *registry) {

            _MESSAGE("registering functions");

            reflection::foreach_metaInfo_do([=](const reflection::class_info& info) {
                info.bind(registry);
            });

            return true;
        }

        __declspec(dllexport) bool SKSEPlugin_Load(const SKSEInterface * skse) {

            g_serialization->SetUniqueID(g_pluginHandle, (UInt32)consts::storage_chunk);

            g_serialization->SetRevertCallback(g_pluginHandle, revert);
            g_serialization->SetSaveCallback(g_pluginHandle, save);
            g_serialization->SetLoadCallback(g_pluginHandle, load);

            g_papyrus->Register(registerAllFunctions);

            if (g_messaging) {
                g_messaging->RegisterListener(g_pluginHandle, "SKSE", [](SKSEMessagingInterface::Message* msg) {
                    if (msg && msg->type == SKSEMessagingInterface::kMessage_PostPostLoad) {
                        g_messaging->Dispatch(g_pluginHandle, jc::message_root_interface, (void *)&jc::root, sizeof(void*), nullptr);
                    }
                });
            }

            _MESSAGE("plugin loaded");

            return true;
        }
    };

}

ext: cpp

max_stars_repo_name: SilverIce/JContainers

max_issues_repo_name: SilverIce/JContainers

max_forks_repo_name: SilverIce/JContainers


text:
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

#include "stdafx.h"

#include <boost/test/unit_test.hpp>
#include "Common/boost-taef.h"

using namespace std;
using namespace Common;
using namespace ::Query;
using namespace ServiceModel;

class TestQueryRequestParameterParserUtility
{
protected:
    void Insert(
        wstring key,
        wstring value)
    {
        queryArgumentMap_.Insert(key, value);
    }

    void Insert(
        wstring fieldName,
        int64 value)
    {
        auto stringValue = wformatString(value);
        queryArgumentMap_.Insert(fieldName, stringValue);
    }

    void Insert(
        wstring fieldName,
        Guid value)
    {
        auto stringValue = wformatString(value);
        queryArgumentMap_.Insert(fieldName, stringValue);
    }

    bool TryGetValue(wstring key, wstring & outVal) const
    {
        return queryArgumentMap_.TryGetValue(key, outVal);
    }

    bool TryGetValue(wstring key, int64 & outVal) const
    {
        return queryArgumentMap_.TryGetValue(key, outVal);
    }

    bool TryGetValue(wstring key, Guid & outVal) const
    {
        return queryArgumentMap_.TryGetValue(key, outVal);
    }

    bool TryGetPartitionId(Guid & outVal) const
    {
        return queryArgumentMap_.TryGetPartitionId(outVal);
    }

    bool TryGetReplicaId(int64 & outVal) const
    {
        return queryArgumentMap_.TryGetReplicaId(outVal);
    }

protected:
    QueryArgumentMap queryArgumentMap_;
};

BOOST_AUTO_TEST_SUITE(Unit)

BOOST_FIXTURE_TEST_SUITE(TestQueryRequestParameterParserUtilitySuite, TestQueryRequestParameterParserUtility)

BOOST_AUTO_TEST_CASE(WithStringValue)
{
    auto key = L"key";
    auto inputVal = L"applicationName";
    Insert(key, inputVal);

    wstring outVal;
    VERIFY_IS_TRUE(TryGetValue(key, outVal));
    VERIFY_ARE_EQUAL(inputVal, outVal);
}

BOOST_AUTO_TEST_CASE(WithMissingStringValue)
{
    auto key = L"key";
    wstring outVal;

    VERIFY_IS_FALSE(TryGetValue(key, outVal));
    VERIFY_IS_TRUE(outVal.empty());
}

BOOST_AUTO_TEST_CASE(WithInt64Value)
{
    auto key = L"key";
    int64 inputVal = 123456789;
    Insert(key, inputVal);
    int64 outVal;

    VERIFY_IS_TRUE(TryGetValue(key, outVal));
    VERIFY_ARE_EQUAL(inputVal, outVal);
}

BOOST_AUTO_TEST_CASE(WithMissingInt64Value)
{
    auto key = L"key";
    int64 outVal;

    VERIFY_IS_TRUE(!TryGetValue(key, outVal));
}

BOOST_AUTO_TEST_CASE(WithInvalidInt64FormatValue)
{
    auto key = L"key";
    wstring inputVal = L"invalidFormatValue";
    Insert(key, inputVal);
    int64 outVal;

    VERIFY_IS_TRUE(!TryGetValue(key, outVal));
}

BOOST_AUTO_TEST_CASE(WithGuidValue)
{
    auto key = L"key";
    auto inputVal = Guid::NewGuid();
    Insert(key, inputVal);
    Guid outVal;

    VERIFY_IS_TRUE(TryGetValue(key, outVal));
    VERIFY_ARE_EQUAL(inputVal, outVal);
}

BOOST_AUTO_TEST_CASE(WithMissingGuidValue)
{
    auto key = L"key";
    Guid outVal;

    VERIFY_IS_FALSE(TryGetValue(key, outVal));
}

BOOST_AUTO_TEST_CASE(WithEmptyStringGuidValue)
{
    auto key = L"key";
    wstring inputVal = L"";
    Insert(key, inputVal);
    Guid outVal;

    VERIFY_IS_FALSE(TryGetValue(key, outVal));
}

BOOST_AUTO_TEST_CASE(WithInvalidGuidStringValue)
{
    auto key = L"key";
    auto inputVal = L"invalidFormatValue";
    Insert(key, inputVal);
    Guid outVal;

    VERIFY_IS_FALSE(TryGetValue(key, outVal));
}

BOOST_AUTO_TEST_CASE(WithPartitionId)
{
    auto inputVal = Guid::NewGuid();
    Insert(QueryResourceProperties::Partition::PartitionId, inputVal);
    Guid outVal;

    VERIFY_IS_TRUE(TryGetPartitionId(outVal));
    VERIFY_ARE_EQUAL(inputVal, outVal);
}

BOOST_AUTO_TEST_CASE(WithReplicaId)
{
    int64 inputVal = 123456789;
    Insert(QueryResourceProperties::Replica::ReplicaId, inputVal);
    int64 outVal;

    VERIFY_IS_TRUE(TryGetReplicaId(outVal));
    VERIFY_ARE_EQUAL(inputVal, outVal);
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE_END()


text:
//
// Copyright (c) 2019 Vinnie Falco (vinnie.falco@gmail.com)
//
// 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)
//
// Official repository: https://github.com/CPPAlliance/url
//

#ifndef BOOST_URL_HOST_TYPE_HPP
#define BOOST_URL_HOST_TYPE_HPP

#include <boost/url/detail/config.hpp>

namespace boost {
namespace urls {

/** Identifies the type of host in a URL.

    Values of this type are returned by URL views
    and containers to indicate the type of host
    present in a URL.

    @see url_view::host, url_base::host
*/
enum class host_type
{
    /** No host is specified.
    */
    none,

    /** A host is specified by reg-name.
    */
    name,

    /** A host is specified by IPv4address.

        @see ipv4_address
    */
    ipv4,

    /** A host is specified by IPv6address.

        @see ipv6_address
    */
    ipv6,

    /** A host is specified by IPvFuture.
    */
    ipvfuture
};

} // urls
} // boost

#endif


text:
#include <stan/math/rev.hpp>
#include <boost/mp11.hpp>
#include <gtest/gtest.h>
#include <test/unit/math/rev/functor/test_fixture_ode.hpp>
#include <test/unit/math/rev/functor/test_fixture_dae_chem.hpp>
#include <test/unit/math/rev/functor/dae_test_functors.hpp>

/**
 *
 * Use same solver functor type for both w & w/o tolerance control
 */
template <typename solve_type, typename... Ts>
using ode_test_tuple = std::tuple<solve_type, solve_type, Ts...>;

/**
 * Outer product of test types
 */
using chemical_kinetics_test_types
    = boost::mp11::mp_product<ode_test_tuple, ::testing::Types<dae_functor>,
                              ::testing::Types<double>,  // t
                              ::testing::Types<double>,  // yy0
                              ::testing::Types<double>,  // yp0
                              ::testing::Types<double>   // theta
                              >;

TYPED_TEST_SUITE_P(chemical_kinetics_test);
TYPED_TEST_P(chemical_kinetics_test, param_and_data_finite_diff) {
  // params that gives extreme gradients
  this->test_fd_dv(1.e-3, 2e-3);

  // params that gives moderate gradients
  this->theta = {0.4, 0.5, 0.5};
  this->test_fd_dv(1.e-3, 5e-6);
}
TYPED_TEST_P(chemical_kinetics_test, value) {
  this->test_value(0.0);
  this->test_value(1.0);
  this->test_value(-1.0);
}

TYPED_TEST_P(chemical_kinetics_test, error) { this->test_bad(); }

REGISTER_TYPED_TEST_SUITE_P(chemical_kinetics_test, value, error,
                            param_and_data_finite_diff);
INSTANTIATE_TYPED_TEST_SUITE_P(StanOde, chemical_kinetics_test,
                               chemical_kinetics_test_types);

TYPED_TEST_SUITE_P(chemical_kinetics_data_test);
TYPED_TEST_P(chemical_kinetics_data_test, value) {
  this->test_value(0.0);
  this->test_value(1.0);
  this->test_value(-1.0);
}
TYPED_TEST_P(chemical_kinetics_data_test, param_and_data_finite_diff) {
  // params that gives extreme gradients
  this->test_fd_dv(1.e-3, 2e-3);

  // params that gives moderate gradients
  this->theta = {0.4, 0.5, 0.5};
  this->x_r = {0.5, 0.5};
  this->test_fd_dv(1.e-3, 2e-6);
}
REGISTER_TYPED_TEST_SUITE_P(chemical_kinetics_data_test, value,
                            param_and_data_finite_diff);
INSTANTIATE_TYPED_TEST_SUITE_P(StanDAE, chemical_kinetics_data_test,
                               chemical_kinetics_test_types);


text:
/*
 * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
 */

#include "base/os.h"
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include "testing/gunit.h"
#include "test_cmn_util.h"
#include "vr_types.h"
#include "oper/vn.h"
#include "oper/tunnel_nh.h"

#include <boost/assign/list_of.hpp>

#define BUF_SIZE (12 * 1024)

using namespace std;
using namespace boost::assign;

void RouterIdDepInit(Agent *agent) {
}

class MulticastTest : public ::testing::Test {
public:
    MulticastTest() : agent_(Agent::GetInstance()) {}
    virtual void SetUp() {
        peer_ = CreateBgpPeer(Ip4Address(1), "BGP Peer1");
    }

    virtual void TearDown() {
        WAIT_FOR(1000, 10000, (agent_->vn_table()->Size() == 0));
        WAIT_FOR(1000, 10000, (agent_->vrf_table()->Size() == 2));
        DeleteBgpPeer(peer_);
    }
    Agent *agent_;
    Peer *peer_;
};

// Basic BUM route creation.
// Happens when VMs are added to a VRF.
// Two VMs added to VRF resulting in broadcast route being added
// with the two VMs as the members of the nexthop.
TEST_F(MulticastTest, Mcast_vm_add_basic) {
    struct PortInfo input[] = {
        {"vnet1", 1, "11.1.1.3", "00:00:11:01:01:03", 1, 1},
        {"vnet2", 2, "11.1.1.4", "00:00:11:01:01:04", 1, 1},
    };

    CreateVmportEnv(input, 2, 0);
    client->WaitForIdle();
    WAIT_FOR(1000, 1000, (VmPortActive(input, 0) == true));

    MacAddress mac = MacAddress::kBroadcastMac;
    BridgeRouteEntry *rt = L2RouteGet("vrf1", mac);
    EXPECT_TRUE((rt != NULL));

    const NextHop *nh;
    const CompositeNH *cnh, *cnh1;
    const ComponentNH *component_nh;

    nh = L2RouteToNextHop("vrf1", mac);

    cnh = dynamic_cast<const CompositeNH *>(nh);
    EXPECT_EQ(1, cnh->ActiveComponentNHCount());

    component_nh = cnh->Get(0);
    nh = component_nh->nh();
    EXPECT_TRUE((nh != NULL));
    cnh1 = dynamic_cast<const CompositeNH *>(nh);
    // 2 indicates number of VMs in the VN/VRF.
    EXPECT_EQ(2, cnh1->ActiveComponentNHCount());

    DeleteVmportEnv(input, 2, 1, 0);
    client->WaitForIdle();
}

// BUM route creation with neighbor compute.
// Happens when VMs are added to a VRF.
// Two VMs added to VRF resulting in broadcast route being added
// with the two VMs as the members of the nexthop.
// Also, a dummy compute is added to the Nexthop - 8.8.8.8.
// Fabric composite nexthop contains a tunnel nexthop to 8.8.8.8.
TEST_F(MulticastTest, Mcast_fabric_nexthop_1) {
    struct PortInfo input[] = {
        {"vnet1", 1, "11.1.1.3", "00:00:11:01:01:03", 1, 1},
        {"vnet2", 2, "11.1.1.4", "00:00:11:01:01:04", 1, 1},
    };

    CreateVmportEnv(input, 2, 0);
    client->WaitForIdle();

    WAIT_FOR(1000, 1000, (VmPortActive(input, 0) == true));
    WAIT_FOR(1000, 1000, (VmPortActive(input, 1) == true));

    MacAddress mac = MacAddress::kBroadcastMac;
    BridgeRouteEntry *rt = L2RouteGet("vrf1", mac);
    EXPECT_TRUE((rt != NULL));

    TunnelOlist olist_map;
    olist_map.push_back(OlistTunnelEntry(boost::uuids::nil_uuid(), 2000,
                            IpAddress::from_string("8.8.8.8").to_v4(),
                            TunnelType::AllType()));
    agent_->oper_db()->multicast()->
        ModifyFabricMembers(agent_->multicast_tree_builder_peer(), "vrf1",
                            IpAddress::from_string("255.255.255.255").to_v4(),
                            IpAddress::from_string("0.0.0.0").to_v4(),
                            1112, olist_map,
                            agent_->controller()->multicast_sequence_number());
    client->WaitForIdle();

    const NextHop *nh;
    const CompositeNH *cnh, *cnh1;
    const ComponentNH *component_nh;

    nh = L2RouteToNextHop("vrf1", mac);

    cnh = dynamic_cast<const CompositeNH *>(nh);
    EXPECT_EQ(2, cnh->ActiveComponentNHCount());

    component_nh = cnh->Get(0);
    nh = component_nh->nh();
    EXPECT_TRUE((nh != NULL));
    cnh1 = dynamic_cast<const CompositeNH *>(nh);
    EXPECT_EQ(1, cnh1->ActiveComponentNHCount());

    component_nh = cnh->Get(1);
    nh = component_nh->nh();
    EXPECT_TRUE((nh != NULL));
    cnh1 = dynamic_cast<const CompositeNH *>(nh);
    EXPECT_EQ(2, cnh1->ActiveComponentNHCount());

    DeleteVmportEnv(input, 2, 1, 0);
    client->WaitForIdle();
}

// BUM route creation with neighbor compute.
// Happens when VMs are added to a VRF.
// Two VMs added to VRF resulting in broadcast route being added
// with the two VMs as the members of the nexthop.
// Also, dummy computes is added to the Nexthop - 8.8.8.8 and 8.8.8.9.
// Fabric composite nexthop contains tunnel nexthops to 8.8.8.8 and 8.8.8.9.
// second half of test consist of having only one tunnel as an update to the
// route.
TEST_F(MulticastTest, Mcast_fabric_nexthop_2) {
    struct PortInfo input[] = {
        {"vnet1", 1, "11.1.1.3", "00:00:11:01:01:03", 1, 1},
        {"vnet2", 2, "11.1.1.4", "00:00:11:01:01:04", 1, 1},
    };

    CreateVmportEnv(input, 2, 0);
    client->WaitForIdle();

    WAIT_FOR(1000, 1000, (VmPortActive(input, 0) == true));
    WAIT_FOR(1000, 1000, (VmPortActive(input, 1) == true));

    MacAddress mac = MacAddress::kBroadcastMac;
    BridgeRouteEntry *rt = L2RouteGet("vrf1", mac);
    EXPECT_TRUE((rt != NULL));

    TunnelOlist olist_map;
    const NextHop *nh;
    const CompositeNH *cnh, *cnh1;
    const ComponentNH *component_nh;

    olist_map.push_back(OlistTunnelEntry(boost::uuids::nil_uuid(), 2000,
                            IpAddress::from_string("8.8.8.8").to_v4(),
                            TunnelType::AllType()));
    olist_map.push_back(OlistTunnelEntry(boost::uuids::nil_uuid(), 2000,
                            IpAddress::from_string("8.8.8.9").to_v4(),
                            TunnelType::AllType()));
    agent_->oper_db()->multicast()->
        ModifyFabricMembers(agent_->multicast_tree_builder_peer(), "vrf1",
                            IpAddress::from_string("255.255.255.255").to_v4(),
                            IpAddress::from_string("0.0.0.0").to_v4(),
                            1112, olist_map,
                            agent_->controller()->multicast_sequence_number());
    client->WaitForIdle();

    nh = L2RouteToNextHop("vrf1", mac);

    cnh = dynamic_cast<const CompositeNH *>(nh);
    EXPECT_EQ(2, cnh->ActiveComponentNHCount());

    component_nh = cnh->Get(0);
    nh = component_nh->nh();
    EXPECT_TRUE((nh != NULL));
    cnh1 = dynamic_cast<const CompositeNH *>(nh);
    EXPECT_EQ(2, cnh1->ActiveComponentNHCount());

    component_nh = cnh->Get(1);
    nh = component_nh->nh();
    EXPECT_TRUE((nh != NULL));
    cnh1 = dynamic_cast<const CompositeNH *>(nh);
    EXPECT_EQ(2, cnh1->ActiveComponentNHCount());

    olist_map.clear();
    olist_map.push_back(OlistTunnelEntry(boost::uuids::nil_uuid(), 2000,
                            IpAddress::from_string("8.8.8.8").to_v4(),
                            TunnelType::AllType()));
    agent_->oper_db()->multicast()->
        ModifyFabricMembers(agent_->multicast_tree_builder_peer(), "vrf1",
                            IpAddress::from_string("255.255.255.255").to_v4(),
                            IpAddress::from_string("0.0.0.0").to_v4(),
                            1112, olist_map,
                            agent_->controller()->multicast_sequence_number());
    client->WaitForIdle();

    nh = L2RouteToNextHop("vrf1", mac);

    cnh = dynamic_cast<const CompositeNH *>(nh);
    EXPECT_EQ(2, cnh->ActiveComponentNHCount());

    component_nh = cnh->Get(0);
    nh = component_nh->nh();
    EXPECT_TRUE((nh != NULL));
    cnh1 = dynamic_cast<const CompositeNH *>(nh);
    EXPECT_EQ(1, cnh1->ActiveComponentNHCount());

    component_nh = cnh->Get(1);
    nh = component_nh->nh();
    EXPECT_TRUE((nh != NULL));
    cnh1 = dynamic_cast<const CompositeNH *>(nh);
    EXPECT_EQ(2, cnh1->ActiveComponentNHCount());

    DeleteVmportEnv(input, 2, 1, 0);
    client->WaitForIdle();
}

int main(int argc, char **argv) {
    GETUSERARGS();
    client = TestInit(init_file, ksync_init);

    int ret = RUN_ALL_TESTS();
    client->WaitForIdle();
    TestShutdown();
    delete client;
    return ret;
}

ext: cc

max_stars_repo_name: jnpr-pranav/contrail-controller

max_issues_repo_name: jnpr-pranav/contrail-controller

max_forks_repo_name: jnpr-pranav/contrail-controller


text:
//
// Copyright 2011-2013 Ettus Research LLC
//
// This program 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.
//
// 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
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

#ifndef INCLUDED_UHD_STREAM_HPP
#define INCLUDED_UHD_STREAM_HPP

#include <uhd/config.hpp>
#include <uhd/types/metadata.hpp>
#include <uhd/types/device_addr.hpp>
#include <uhd/types/stream_cmd.hpp>
#include <uhd/types/ref_vector.hpp>
#include <boost/utility.hpp>
#include <boost/shared_ptr.hpp>
#include <vector>
#include <string>

namespace uhd{

/*!
 * A struct of parameters to construct a streamer.
 *
 * Note:
 * Not all combinations of CPU and OTW format have conversion support.
 * You may however write and register your own conversion routines.
 */
struct UHD_API stream_args_t{

    //! Convenience constructor for streamer args
    stream_args_t(
        const std::string &cpu = "",
        const std::string &otw = ""
    ){
        cpu_format = cpu;
        otw_format = otw;
    }

    /*!
     * The CPU format is a string that describes the format of host memory.
     * Conversions for the following CPU formats have been implemented:
     *  - fc64 - complex<double>
     *  - fc32 - complex<float>
     *  - sc16 - complex<int16_t>
     *  - sc8 - complex<int8_t>
     *
     * The following are not implemented, but are listed to demonstrate naming convention:
     *  - f32 - float
     *  - f64 - double
     *  - s16 - int16_t
     *  - s8 - int8_t
     */
    std::string cpu_format;

    /*!
     * The OTW format is a string that describes the format over-the-wire.
     * The following over-the-wire formats have been implemented:
     *  - sc16 - Q16 I16
     *  - sc8 - Q8_1 I8_1 Q8_0 I8_0
     *
     * The following are not implemented, but are listed to demonstrate naming convention:
     *  - s16 - R16_1 R16_0
     *  - s8 - R8_3 R8_2 R8_1 R8_0
     */
    std::string otw_format;

    /*!
     * The args parameter is used to pass arbitrary key/value pairs.
     * Possible keys used by args (depends on implementation):
     *
     * - fullscale: specifies the full-scale amplitude when using floats.
     * By default, the fullscale amplitude under floating point is 1.0.
     * Set the "fullscale" to scale the samples in the host to the
     * expected input range and/or output range of your application.
     *
     * - peak: specifies a fractional sample level to calculate scaling with the sc8 wire format.
     * When using sc8 samples over the wire, the device must scale samples
     * (both on the host and in the device) to satisfy the dynamic range needs.
     * The peak value specifies a fraction of the maximum sample level (1.0 = 100%).
     * Set peak to max_sample_level/full_scale_level to ensure optimum dynamic range.
     *
     * - underflow_policy: how the TX DSP should recover from underflow.
     * Possible options are "next_burst" or "next_packet".
     * In the "next_burst" mode, the DSP drops incoming packets until a new burst is started.
     * In the "next_packet" mode, the DSP starts transmitting again at the next packet.
     *
     * - spp: (samples per packet) controls the size of RX packets.
     * When not specified, the packets are always maximum frame size.
     * Users should specify this option to request smaller than default
     * packets, probably with the intention of reducing packet latency.
     *
     * The following are not implemented, but are listed for conceptual purposes:
     * - function: magnitude or phase/magnitude
     * - units: numeric units like counts or dBm
     */
    device_addr_t args;

    /*!
     * The channels is a list of channel numbers.
     * Leave this blank to default to channel 0.
     * Set channels for a multi-channel application.
     * Channel mapping depends on the front-end selection.
     */
    std::vector<size_t> channels;
};

/*!
 * The RX streamer is the host interface to receiving samples.
 * It represents the layer between the samples on the host
 * and samples inside the device's receive DSP processing.
 */
class UHD_API rx_streamer : boost::noncopyable{
public:
    typedef boost::shared_ptr<rx_streamer> sptr;

    virtual ~rx_streamer(void);

    //! Get the number of channels associated with this streamer
    virtual size_t get_num_channels(void) const = 0;

    //! Get the max number of samples per buffer per packet
    virtual size_t get_max_num_samps(void) const = 0;

    //! Typedef for a pointer to a single, or a collection of recv buffers
    typedef ref_vector<void *> buffs_type;

    /*!
     * Receive buffers containing samples described by the metadata.
     *
     * Receive handles fragmentation as follows:
     * If the buffer has insufficient space to hold all samples
     * that were received in a single packet over-the-wire,
     * then the buffer will be completely filled and the implementation
     * will hold a pointer into the remaining portion of the packet.
     * Subsequent calls will load from the remainder of the packet,
     * and will flag the metadata to show that this is a fragment.
     * The next call to receive, after the remainder becomes exahausted,
     * will perform an over-the-wire receive as usual.
     * See the rx metadata fragment flags and offset fields for details.
     *
     * This is a blocking call and will not return until the number
     * of samples returned have been written into each buffer.
     * Under a timeout condition, the number of samples returned
     * may be less than the number of samples specified.
     *
     * The one_packet option allows the user to guarantee that
     * the call will return after a single packet has been processed.
     * This may be useful to maintain packet boundaries in some cases.
     *
     * \param buffs a vector of writable memory to fill with samples
     * \param nsamps_per_buff the size of each buffer in number of samples
     * \param metadata data to fill describing the buffer
     * \param timeout the timeout in seconds to wait for a packet
     * \param one_packet return after the first packet is received
     * \return the number of samples received or 0 on error
     */
    virtual size_t recv(
        const buffs_type &buffs,
        const size_t nsamps_per_buff,
        rx_metadata_t &metadata,
        const double timeout = 0.1,
        const bool one_packet = false
    ) = 0;

    /*!
     * Issue a stream command to the usrp device.
     * This tells the usrp to send samples into the host.
     * See the documentation for stream_cmd_t for more info.
     *
     * With multiple devices, the first stream command in a chain of commands
     * should have a time spec in the near future and stream_now = false;
     * to ensure that the packets can be aligned by their time specs.
     *
     * \param stream_cmd the stream command to issue
     */
    virtual void issue_stream_cmd(const stream_cmd_t &stream_cmd) = 0;
};

/*!
 * The TX streamer is the host interface to transmitting samples.
 * It represents the layer between the samples on the host
 * and samples inside the device's transmit DSP processing.
 */
class UHD_API tx_streamer : boost::noncopyable{
public:
    typedef boost::shared_ptr<tx_streamer> sptr;

    virtual ~tx_streamer(void);

    //! Get the number of channels associated with this streamer
    virtual size_t get_num_channels(void) const = 0;

    //! Get the max number of samples per buffer per packet
    virtual size_t get_max_num_samps(void) const = 0;

    //! Typedef for a pointer to a single, or a collection of send buffers
    typedef ref_vector<const void *> buffs_type;

    /*!
     * Send buffers containing samples described by the metadata.
     *
     * Send handles fragmentation as follows:
     * If the buffer has more items than the maximum per packet,
     * the send method will fragment the samples across several packets.
     * Send will respect the burst flags when fragmenting to ensure
     * that start of burst can only be set on the first fragment and
     * that end of burst can only be set on the final fragment.
     *
     * This is a blocking call and will not return until the number
     * of samples returned have been read out of each buffer.
     * Under a timeout condition, the number of samples returned
     * may be less than the number of samples specified.
     *
     * \param buffs a vector of read-only memory containing samples
     * \param nsamps_per_buff the number of samples to send, per buffer
     * \param metadata data describing the buffer's contents
     * \param timeout the timeout in seconds to wait on a packet
     * \return the number of samples sent
     */
    virtual size_t send(
        const buffs_type &buffs,
        const size_t nsamps_per_buff,
        const tx_metadata_t &metadata,
        const double timeout = 0.1
    ) = 0;

    /*!
     * Receive and asynchronous message from this TX stream.
     * \param async_metadata the metadata to be filled in
     * \param timeout the timeout in seconds to wait for a message
     * \return true when the async_metadata is valid, false for timeout
     */
    virtual bool recv_async_msg(
        async_metadata_t &async_metadata, double timeout = 0.1
    ) = 0;
};

} //namespace uhd

#endif /* INCLUDED_UHD_STREAM_HPP */

max_stars_repo_name: cityscapesc/specobs

max_issues_repo_name: cityscapesc/specobs

max_forks_repo_name: cityscapesc/specobs


text:
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <boost/math/special_functions/beta.hpp>

using namespace std;
using namespace boost::math;

inline double calcindex(double beta, const double a, const double nn)
{
  double p = double(a)/double(nn);
  const double b = nn - a;
  const double r = ((double)a/(double)nn);
  const double rup = ((double)a+1.0)/((double)nn+1.0);
  const double rdn = ((double)a)/((double)nn+1.0);

  for(int k = 0; k < 10; ++k)
  {
    if(p > 1 || p < r || p != p)
    {
      cerr << "Warning! returning approximation for a = " << a << " and b = " << b << endl;
      return r;
    }
    const double safe = p/(1-beta);

    const double lhs = r*(1-ibeta(a+1,b,p));
    const double expmax = lhs + p*ibeta((double)a,b,p);
    //cout << expmax << ". lhs = " << lhs << ". rhs = " << p*ibeta((double)a,b,p) << endl;
    const double risky = r+ beta/(1-beta)*expmax;

    const double orig = risky - safe;
    const double deriv = beta/(1-beta)*ibeta(a,b,p) - 1/(1-beta);
    p -= orig/deriv;
  }
  return p;
}

void computeIndices(const int n, const double beta, vector<vector<double> >& indices)
{
  for(int nn = n-1; nn >= 2; --nn)
  {
    for(int a = 1; a <= nn-1; ++a)
    {
      double p = calcindex(beta, a, nn);
      indices[a-1][nn-a-1] = p;
    }
  }
}

int main(int argc, const char** args)
{
  if(argc != 3)
  {
    cerr << "need 2 arguments [n] [beta]" << endl;
    exit(1);
  }
  int n;
  string strnum = args[1];
  stringstream ss(strnum);
  ss >> n;

  double beta;
  string betastr = args[2];
  stringstream ssbeta(betastr);
  ssbeta >> beta;

  //cout << calcindex(beta,292,292+1170) << endl;
  //cout << "finding indices for size limit [" << n << "] and step size [" << step << "]" << endl;
  vector<vector<double> > indices(n-1, vector<double>(n-1, 0));
  computeIndices(n, beta, indices);

  for(int i = 0; i < n-1; ++i)
  {
    for(int j=0; j < n-2; ++j)
    {
      cout << indices[i][j] << ", ";
    }
    cout << indices[i][n-2] << endl;
  }
}

max_stars_repo_name: gutin/FastGittins

max_issues_repo_name: gutin/FastGittins

max_forks_repo_name: gutin/FastGittins


text:
/*=============================================================================
    Copyright (c) 2006 Eric Niebler

    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)
==============================================================================*/
#if !defined(BOOST_FUSION_SEGMENTS_04052005_1141)
#define BOOST_FUSION_SEGMENTS_04052005_1141

#include <boost/fusion/support/config.hpp>
#include <boost/type_traits/is_const.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/fusion/sequence/intrinsic_fwd.hpp>
#include <boost/fusion/support/tag_of.hpp>

namespace boost { namespace fusion
{
    // Special tags:
    struct sequence_facade_tag;
    struct iterator_range_tag;

    // segments: returns a sequence of sequences
    namespace extension
    {
        template <typename Tag>
        struct segments_impl
        {
            template <typename Sequence>
            struct apply {};
        };

        template <>
        struct segments_impl<sequence_facade_tag>
        {
            template <typename Sequence>
            struct apply : Sequence::template segments<Sequence> {};
        };

        template <>
        struct segments_impl<iterator_range_tag>;
    }

    namespace result_of
    {
        template <typename Sequence>
        struct segments
        {
            typedef typename traits::tag_of<Sequence>::type tag_type;

            typedef typename
                extension::segments_impl<tag_type>::template apply<Sequence>::type
            type;
        };
    }

    template <typename Sequence>
    BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
    inline typename
        lazy_disable_if<
            is_const<Sequence>
          , result_of::segments<Sequence>
        >::type
    segments(Sequence& seq)
    {
        typedef typename traits::tag_of<Sequence>::type tag_type;
        return extension::segments_impl<tag_type>::template apply<Sequence>::call(seq);
    }

    template <typename Sequence>
    BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED
    inline typename result_of::segments<Sequence const>::type
    segments(Sequence const& seq)
    {
        typedef typename traits::tag_of<Sequence const>::type tag_type;
        return extension::segments_impl<tag_type>::template apply<Sequence const>::call(seq);
    }
}}

#endif

max_stars_repo_name: sbrown-uhd/hazelcast-cpp-client

max_issues_repo_name: sbrown-uhd/hazelcast-cpp-client

max_forks_repo_name: sbrown-uhd/hazelcast-cpp-client


text:
/* Boost.Flyweight test of set_factory.
 *
 * Copyright 2006-2013 Joaquin M Lopez Munoz.
 * 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)
 *
 * See http://www.boost.org/libs/flyweight for library home page.
 */

#include "test_set_factory.hpp"

#include <boost/config.hpp> /* keep it first to prevent nasty warns in MSVC */
#include <boost/flyweight/flyweight.hpp>
#include <boost/flyweight/refcounted.hpp>
#include <boost/flyweight/set_factory.hpp>
#include <boost/flyweight/simple_locking.hpp>
#include <boost/flyweight/static_holder.hpp>
#include <functional>
#include "test_basic_template.hpp"

using namespace boost::flyweights;

struct set_factory_flyweight_specifier1
{
  template<typename T>
  struct apply
  {
    typedef flyweight<T,set_factory<> > type;
  };
};

struct set_factory_flyweight_specifier2
{
  template<typename T>
  struct apply
  {
    typedef flyweight<
      T,
      static_holder_class<boost::mpl::_1>,
      set_factory_class<
        boost::mpl::_1,boost::mpl::_2,
        std::greater<boost::mpl::_2>,
        std::allocator<boost::mpl::_1>
      >
    > type;
  };
};

struct set_factory_flyweight_specifier3
{
  template<typename T>
  struct apply
  {
    typedef flyweight<
      T,
      set_factory<
        std::greater<boost::mpl::_2>,
        std::allocator<boost::mpl::_1>
      >,
      static_holder_class<boost::mpl::_1>,
      tag<char>
    > type;
  };
};

void test_set_factory()
{
  test_basic_template<set_factory_flyweight_specifier1>();
  test_basic_template<set_factory_flyweight_specifier2>();
  test_basic_template<set_factory_flyweight_specifier3>();
}


text:
// Boost.Range library
//
//  Copyright Thorsten Ottosen 2003-2004. Use, modification and
//  distribution is subject to 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)
//
// For more information, see http://www.boost.org/libs/range/
//
#include <boost/range/adaptor/replaced_if.hpp>
#include <boost/range/algorithm/copy.hpp>
#include <boost/assign.hpp>
#include <algorithm>
#include <iostream>
#include <vector>

struct is_even
{
    bool operator()(int x) const { return x % 2 == 0; }
};

int main(int argc, const char* argv[])
{
    using namespace boost::adaptors;
    using namespace boost::assign;

    std::vector<int> input;
    input += 1,2,3,4,5,6,7,8,9;

    boost::copy(
        input | replaced_if(is_even(), 10),
        std::ostream_iterator<int>(std::cout, ","));

    return 0;
}


text:
/*
 * TestBinaryWord.cpp
 *
 *  Created on: Nov 25, 2016
 *      Author: victor
 */

#include <string>
#include <vector>

using namespace std;

#define BOOST_TEST_DYN_LINK

#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE "Secure Remote Password Protocol Tests"
#include <boost/test/included/unit_test.hpp>


text:
#ifndef STATIC_LINK_VW
#  define BOOST_TEST_DYN_LINK
#endif

#include <boost/test/unit_test.hpp>
#include <boost/test/test_tools.hpp>

#include "test_common.h"

#include "namespaced_features.h"

BOOST_AUTO_TEST_CASE(namespaced_features_test)
{
  VW::namespaced_features feature_groups;
  BOOST_CHECK(feature_groups.empty());

  auto begin_end = feature_groups.get_namespace_index_groups('a');
  BOOST_CHECK(begin_end.second - begin_end.first == 0);

  feature_groups.get_or_create_feature_group(123, 'a');
  feature_groups.get_or_create_feature_group(1234, 'a');

  begin_end = feature_groups.get_namespace_index_groups('a');
  BOOST_CHECK(begin_end.second - begin_end.first == 2);

  BOOST_REQUIRE_THROW(feature_groups[1], VW::vw_exception);
  BOOST_REQUIRE_NO_THROW(feature_groups[123]);

  check_collections_exact(feature_groups.get_indices(), std::set<namespace_index>{'a'});

  feature_groups.remove_feature_group(123);
  begin_end = feature_groups.get_namespace_index_groups('a');
  BOOST_CHECK(begin_end.second - begin_end.first == 1);

  check_collections_exact(feature_groups.get_indices(), std::set<namespace_index>{'a'});
  feature_groups.remove_feature_group(1234);
  check_collections_exact(feature_groups.get_indices(), std::set<namespace_index>{});
}


text:
/*
 *      Copyright (C) 2013 DataStax Inc.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
#include <boost/date_time/gregorian/gregorian.hpp>
#include "cql/cql_host.hpp"
#include "cql/internal/cql_util.hpp"

cql::cql_host_t::cql_host_t(
	const cql_endpoint_t& endpoint,
	const boost::shared_ptr<cql_reconnection_policy_t>& reconnection_policy)
	: _endpoint(endpoint),
	  _datacenter("unknown"),
	  _rack("unknown"),
	  _is_up(false),
	  _next_up_time(boost::posix_time::min_date_time),
	  _reconnection_policy(reconnection_policy),
	  _reconnection_schedule(reconnection_policy->new_schedule())
{ }

::boost::shared_ptr<cql::cql_host_t>
cql::cql_host_t::create(
	const cql_endpoint_t&                               endpoint,
	const boost::shared_ptr<cql_reconnection_policy_t>& reconnection_policy)
{
	// if (endpoint.is_unspecified()) {
	// 	throw std::invalid_argument("unspecified IP address.");
    // }

	if (!reconnection_policy) {
		throw std::invalid_argument("reconnection policy cannot be null.");
    }

	return ::boost::shared_ptr<cql::cql_host_t>(
        new cql_host_t(endpoint, reconnection_policy));
}

void
cql::cql_host_t::set_location_info(
	const std::string& datacenter,
	const std::string& rack )
{
	_datacenter = datacenter;
	_rack = rack;
}

bool
cql::cql_host_t::is_considerably_up() const
{
	if(is_up())
		return true;

	boost::posix_time::ptime utc_time = utc_now();
	return (_next_up_time <= utc_time);
}

bool
cql::cql_host_t::set_down()
{
	if (is_considerably_up()) {
		boost::posix_time::time_duration delay =
					_reconnection_schedule->get_delay();

		boost::posix_time::ptime now = utc_now();

		_next_up_time = now + delay;
	}

	if (_is_up) {
		_is_up = false;
		return true;
	}

	return false;
}

bool
cql::cql_host_t::bring_up()
{
	_reconnection_schedule = _reconnection_policy->new_schedule();

	if (!_is_up) {
		_is_up = true;
		return true;
	}

	return false;
}

cql::cql_host_distance_enum
cql::cql_host_t::distance(const cql_policies_t& policies) const {
    cql_host_distance_enum distance = policies
                                     .load_balancing_policy()
                                    ->distance(*this);
    return distance;
}

max_stars_repo_name: ncbi/cassandra-cpp-driver

max_issues_repo_name: ncbi/cassandra-cpp-driver

max_forks_repo_name: ncbi/cassandra-cpp-driver


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

#include <boost/assign/list_of.hpp>
#include <gtest/gtest.h>

#include "kudu/common/partial_row.h"
#include "kudu/common/row.h"
#include "kudu/common/row_key-util.h"
#include "kudu/common/schema.h"
#include "kudu/gutil/mathlimits.h"
#include "kudu/util/test_util.h"

namespace kudu {

class RowKeyUtilTest : public KuduTest {
 public:
  RowKeyUtilTest()
    : arena_(1024, 4096) {}

 protected:
  uint8_t* row_data(KuduPartialRow* row) {
    return row->row_data_;
  }

  Arena arena_;
};

TEST_F(RowKeyUtilTest, TestIncrementNonCompositeKey) {
  Schema schema(boost::assign::list_of
                (ColumnSchema("key", INT32))
                (ColumnSchema("other_col", INT32))
                (ColumnSchema("other_col2", STRING, true)),
                1);
  KuduPartialRow p_row(&schema);
  ContiguousRow row(&schema, row_data(&p_row));

  // Normal increment.
  EXPECT_OK(p_row.SetInt32(0, 1000));
  EXPECT_TRUE(row_key_util::IncrementKey(&row, &arena_));
  EXPECT_EQ("int32 key=1001", p_row.ToString());

  // Overflow increment.
  EXPECT_OK(p_row.SetInt32(0, MathLimits<int32_t>::kMax));
  EXPECT_FALSE(row_key_util::IncrementKey(&row, &arena_));
  EXPECT_EQ("int32 key=-2147483648", p_row.ToString());
}

TEST_F(RowKeyUtilTest, TestIncrementCompositeKey) {
  Schema schema(boost::assign::list_of
                   (ColumnSchema("k1", INT32))
                   (ColumnSchema("k2", INT32))
                   (ColumnSchema("other_col", STRING, true)),
                   2);

  KuduPartialRow p_row(&schema);
  ContiguousRow row(&schema, row_data(&p_row));

  // Normal increment.
  EXPECT_OK(p_row.SetInt32(0, 1000));
  EXPECT_OK(p_row.SetInt32(1, 1000));
  EXPECT_TRUE(row_key_util::IncrementKey(&row, &arena_));
  EXPECT_EQ("int32 k1=1000, int32 k2=1001", p_row.ToString());

  // Overflow a later part of the key, carrying into the earlier
  // part..
  EXPECT_OK(p_row.SetInt32(1, MathLimits<int32_t>::kMax));
  EXPECT_TRUE(row_key_util::IncrementKey(&row, &arena_));
  EXPECT_EQ("int32 k1=1001, int32 k2=-2147483648", p_row.ToString());

  // Overflow the whole key.
  EXPECT_OK(p_row.SetInt32(0, MathLimits<int32_t>::kMax));
  EXPECT_OK(p_row.SetInt32(1, MathLimits<int32_t>::kMax));
  EXPECT_FALSE(row_key_util::IncrementKey(&row, &arena_));
  EXPECT_EQ("int32 k1=-2147483648, int32 k2=-2147483648", p_row.ToString());
}

TEST_F(RowKeyUtilTest, TestIncrementCompositeIntStringKey) {
  Schema schema(boost::assign::list_of
                   (ColumnSchema("k1", INT32))
                   (ColumnSchema("k2", STRING))
                   (ColumnSchema("other_col", STRING, true)),
                   2);

  KuduPartialRow p_row(&schema);
  ContiguousRow row(&schema, row_data(&p_row));

  // Normal increment.
  EXPECT_OK(p_row.SetInt32(0, 1000));
  EXPECT_OK(p_row.SetString(1, "hello"));
  EXPECT_TRUE(row_key_util::IncrementKey(&row, &arena_));
  EXPECT_EQ("int32 k1=1000, string k2=hello\\000", p_row.ToString());

  // There's no way to overflow a string key - you can always make it higher
  // by tacking on more \x00.
  EXPECT_TRUE(row_key_util::IncrementKey(&row, &arena_));
  EXPECT_EQ("int32 k1=1000, string k2=hello\\000\\000", p_row.ToString());
}

TEST_F(RowKeyUtilTest, TestIncrementCompositeStringIntKey) {
  Schema schema(boost::assign::list_of
                   (ColumnSchema("k1", STRING))
                   (ColumnSchema("k2", INT32))
                   (ColumnSchema("other_col", STRING, true)),
                   2);

  KuduPartialRow p_row(&schema);
  ContiguousRow row(&schema, row_data(&p_row));

  // Normal increment.
  EXPECT_OK(p_row.SetString(0, "hello"));
  EXPECT_OK(p_row.SetInt32(1, 1000));
  EXPECT_TRUE(row_key_util::IncrementKey(&row, &arena_));
  EXPECT_EQ("string k1=hello, int32 k2=1001", p_row.ToString());

  // Overflowing the int32 portion should tack \x00 onto the
  // string portion.
  EXPECT_OK(p_row.SetInt32(1, MathLimits<int32_t>::kMax));
  EXPECT_TRUE(row_key_util::IncrementKey(&row, &arena_));
  EXPECT_EQ("string k1=hello\\000, int32 k2=-2147483648", p_row.ToString());
}

} // namespace kudu

max_stars_repo_name: kv-zuiwanyuan/kudu

max_issues_repo_name: kv-zuiwanyuan/kudu

max_forks_repo_name: kv-zuiwanyuan/kudu