<commit_before>#ifndef units_hh_INCLUDED
#define units_hh_INCLUDED

namespace Kakoune
{

template<typename RealType, typename ValueType = int>
class StronglyTypedInteger
{
public:
    explicit constexpr StronglyTypedInteger(ValueType value)
        : m_value(value) {}

    constexpr RealType operator+(const RealType& other) const
    { return RealType(m_value + other.m_value); }

    constexpr RealType operator-(const RealType& other) const
    { return RealType(m_value - other.m_value); }

    constexpr RealType operator*(const RealType& other) const
    { return RealType(m_value * other.m_value); }

    constexpr RealType operator/(const RealType& other) const
    { return RealType(m_value / other.m_value); }

    RealType& operator+=(const RealType& other)
    { m_value += other.m_value; return static_cast<RealType&>(*this); }

    RealType& operator-=(const RealType& other)
    { m_value -= other.m_value; return static_cast<RealType&>(*this); }

    RealType& operator*=(const RealType& other)
    { m_value *= other.m_value; return static_cast<RealType&>(*this); }

    RealType& operator/=(const RealType& other)
    { m_value /= other.m_value; return static_cast<RealType&>(*this); }

    RealType& operator++()
    { ++m_value; return static_cast<RealType&>(*this); }

    RealType& operator--()
    { --m_value; return static_cast<RealType&>(*this); }

    RealType operator++(int)
    { RealType backup(static_cast<RealType&>(*this)); ++m_value; return backup; }

    RealType operator--(int)
    { RealType backup(static_cast<RealType&>(*this)); --m_value; return backup; }

    constexpr RealType operator-() { return RealType(-m_value); }

    constexpr bool operator==(const RealType& other) const
    { return m_value == other.m_value; }

    constexpr bool operator!=(const RealType& other) const
    { return m_value != other.m_value; }

    constexpr bool operator<(const RealType& other) const
    { return m_value < other.m_value; }

    constexpr bool operator<=(const RealType& other) const
    { return m_value <= other.m_value; }

    constexpr bool operator>(const RealType& other) const
    { return m_value > other.m_value; }

    constexpr bool operator>=(const RealType& other) const
    { return m_value >= other.m_value; }

    constexpr bool operator!() const
    { return !m_value; }

    explicit constexpr operator ValueType() const { return m_value; }
    explicit constexpr operator bool() const { return m_value; }
private:
   ValueType m_value;
};

struct LineCount : public StronglyTypedInteger<LineCount, int>
{
    constexpr LineCount(int value) : StronglyTypedInteger<LineCount>(value) {}
};

inline constexpr LineCount operator"" _line(unsigned long long int value)
{
    return LineCount(value);
}

struct ByteCount : public StronglyTypedInteger<ByteCount, int>
{
    constexpr ByteCount(int value) : StronglyTypedInteger<ByteCount>(value) {}
};

inline constexpr ByteCount operator"" _byte(unsigned long long int value)
{
    return ByteCount(value);
}

struct CharCount : public StronglyTypedInteger<CharCount, int>
{
    constexpr CharCount(int value) : StronglyTypedInteger<CharCount>(value) {}
};

inline constexpr CharCount operator"" _char(unsigned long long int value)
{
    return CharCount(value);
}

}

#endif // units_hh_INCLUDED

<commit_msg>rename StronglyTypedInteger to more accurate StronglyTypedNumber<commit_after>#ifndef units_hh_INCLUDED
#define units_hh_INCLUDED

#include <type_traits>

namespace Kakoune
{

template<typename RealType, typename ValueType = int>
class StronglyTypedNumber
{
public:
    explicit constexpr StronglyTypedNumber(ValueType value)
        : m_value(value)
    {
        static_assert(std::is_base_of<StronglyTypedNumber, RealType>::value,
                     "RealType is not derived from StronglyTypedNumber");
    }

    constexpr RealType operator+(const RealType& other) const
    { return RealType(m_value + other.m_value); }

    constexpr RealType operator-(const RealType& other) const
    { return RealType(m_value - other.m_value); }

    constexpr RealType operator*(const RealType& other) const
    { return RealType(m_value * other.m_value); }

    constexpr RealType operator/(const RealType& other) const
    { return RealType(m_value / other.m_value); }

    RealType& operator+=(const RealType& other)
    { m_value += other.m_value; return static_cast<RealType&>(*this); }

    RealType& operator-=(const RealType& other)
    { m_value -= other.m_value; return static_cast<RealType&>(*this); }

    RealType& operator*=(const RealType& other)
    { m_value *= other.m_value; return static_cast<RealType&>(*this); }

    RealType& operator/=(const RealType& other)
    { m_value /= other.m_value; return static_cast<RealType&>(*this); }

    RealType& operator++()
    { ++m_value; return static_cast<RealType&>(*this); }

    RealType& operator--()
    { --m_value; return static_cast<RealType&>(*this); }

    RealType operator++(int)
    { RealType backup(static_cast<RealType&>(*this)); ++m_value; return backup; }

    RealType operator--(int)
    { RealType backup(static_cast<RealType&>(*this)); --m_value; return backup; }

    constexpr RealType operator-() { return RealType(-m_value); }

    constexpr bool operator==(const RealType& other) const
    { return m_value == other.m_value; }

    constexpr bool operator!=(const RealType& other) const
    { return m_value != other.m_value; }

    constexpr bool operator<(const RealType& other) const
    { return m_value < other.m_value; }

    constexpr bool operator<=(const RealType& other) const
    { return m_value <= other.m_value; }

    constexpr bool operator>(const RealType& other) const
    { return m_value > other.m_value; }

    constexpr bool operator>=(const RealType& other) const
    { return m_value >= other.m_value; }

    constexpr bool operator!() const
    { return !m_value; }

    explicit constexpr operator ValueType() const { return m_value; }
    explicit constexpr operator bool() const { return m_value; }
private:
   ValueType m_value;
};

struct LineCount : public StronglyTypedNumber<LineCount, int>
{
    constexpr LineCount(int value) : StronglyTypedNumber<LineCount>(value) {}
};

inline constexpr LineCount operator"" _line(unsigned long long int value)
{
    return LineCount(value);
}

struct ByteCount : public StronglyTypedNumber<ByteCount, int>
{
    constexpr ByteCount(int value) : StronglyTypedNumber<ByteCount>(value) {}
};

inline constexpr ByteCount operator"" _byte(unsigned long long int value)
{
    return ByteCount(value);
}

struct CharCount : public StronglyTypedNumber<CharCount, int>
{
    constexpr CharCount(int value) : StronglyTypedNumber<CharCount>(value) {}
};

inline constexpr CharCount operator"" _char(unsigned long long int value)
{
    return CharCount(value);
}

}

#endif // units_hh_INCLUDED

<|endoftext|>


<commit_before>/**
 * @file user.cpp
 * @brief Class for manipulating user / contact data
 *
 * (c) 2013-2014 by Mega Limited, Auckland, New Zealand
 *
 * This file is part of the MEGA SDK - Client Access Engine.
 *
 * Applications using the MEGA API must present a valid application key
 * and comply with the the rules set forth in the Terms of Service.
 *
 * The MEGA SDK 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.
 *
 * @copyright Simplified (2-clause) BSD License.
 *
 * You should have received a copy of the license along with this
 * program.
 */

#include "mega/user.h"
#include "mega/megaclient.h"

namespace mega {
User::User(const char* cemail)
{
    userhandle = UNDEF;
    show = VISIBILITY_UNKNOWN;
    ctime = 0;
    pubkrequested = 0;

    if (cemail)
    {
        email = cemail;
    }
}

bool User::serialize(string* d)
{
    unsigned char l;
    unsigned short ll;
    time_t ts;
    AttrMap attrmap;
    char attrVersion = '1';

    d->reserve(d->size() + 100 + attrmap.storagesize(10));

    d->append((char*)&userhandle, sizeof userhandle);

    // FIXME: use m_time_t & Serialize64 instead
    ts = ctime;
    d->append((char*)&ts, sizeof ts);
    d->append((char*)&show, sizeof show);

    l = (unsigned char)email.size();
    d->append((char*)&l, sizeof l);
    d->append(email.c_str(), l);

    d->append((char*)&attrVersion, 1);
    d->append("\0\0\0\0\0\0", 7);

    // serialization of attributes
    for (string_map::iterator it = attrs.begin(); it != attrs.end(); it++)
    {
        l = it->first.size();
        d->append((char*)&l, sizeof l);
        d->append(it->first.data(), l);

        ll = it->second.size();
        d->append((char*)&ll, sizeof ll);
        d->append(it->second.data(), ll);

        if (attrsv.find(it->first) != attrsv.end())
        {
            ll = attrsv[it->first].size();
            d->append((char*)&ll, sizeof ll);
            d->append(attrsv[it->first].data(), ll);
        }
        else
        {
            ll = 0;
            d->append((char*)&ll, sizeof ll);
        }
    }

    d->append("", 1);

    if (pubk.isvalid())
    {
        pubk.serializekey(d, AsymmCipher::PUBKEY);
    }

    return true;
}

User* User::unserialize(MegaClient* client, string* d)
{
    handle uh;
    time_t ts;
    visibility_t v;
    unsigned char l;
    unsigned short ll;
    string m;
    User* u;
    const char* ptr = d->data();
    const char* end = ptr + d->size();
    int i;
    char attrVersion;

    if (ptr + sizeof(handle) + sizeof(time_t) + sizeof(visibility_t) + 2 > end)
    {
        return NULL;
    }

    uh = MemAccess::get<handle>(ptr);
    ptr += sizeof uh;

    // FIXME: use m_time_t & Serialize64
    ts = MemAccess::get<time_t>(ptr);
    ptr += sizeof ts;

    v = MemAccess::get<visibility_t>(ptr);
    ptr += sizeof v;

    l = *ptr++;
    if (l)
    {
        if (ptr + l > end)
        {
            return NULL;
        }
        m.assign(ptr, l);
    }
    ptr += l;

    if (ptr + sizeof(char) > end)
    {
        return NULL;
    }

    attrVersion = MemAccess::get<char>(ptr);
    ptr += sizeof(attrVersion);

    for (i = 7; i--;)
    {
        if (ptr + MemAccess::get<unsigned char>(ptr) < end)
        {
            ptr += MemAccess::get<unsigned char>(ptr) + 1;
        }
    }

    if ((i >= 0) || !(u = client->finduser(uh, 1)))
    {
        return NULL;
    }

    client->mapuser(uh, m.c_str());
    u->set(v, ts);

    if (attrVersion == '\0')
    {
        AttrMap attrmap;
        if ((ptr < end) && !(ptr = attrmap.unserialize(ptr, end)))
        {
            client->users.erase(client->uhindex[uh]);
            return NULL;
        }
    }
    else if (attrVersion == '1')
    {
        string key;
        while ((ptr < end) && (l = *ptr++))
        {
            if (ptr + l + sizeof(ll) > end)
            {
                client->users.erase(client->uhindex[uh]);
                return NULL;
            }
            key.assign(ptr, l);
            ptr += l;

            ll = MemAccess::get<short>(ptr);
            ptr += sizeof ll;

            if (ptr + ll + sizeof(ll) > end)
            {
                client->users.erase(client->uhindex[uh]);
                return NULL;
            }

            u->attrs[key].assign(ptr, ll);
            ptr += ll;

            ll = MemAccess::get<short>(ptr);
            ptr += sizeof ll;

            if (ll)
            {
                if (ptr + ll > end)
                {
                    client->users.erase(client->uhindex[uh]);
                    return NULL;
                }
                u->attrsv[key].assign(ptr,ll);
                ptr += ll;
            }
        }
    }

#ifdef ENABLE_CHAT
    const string *av = (u->isattrvalid("*keyring")) ? u->getattr("*keyring") : NULL;
    if (av)
    {
        TLVstore *tlvRecords = TLVstore::containerToTLVrecords(av, &client->key);

        if (tlvRecords->find(EdDSA::TLV_KEY))
        {
            client->signkey = new EdDSA((unsigned char *) tlvRecords->get(EdDSA::TLV_KEY).data());
        }

        if (tlvRecords->find(ECDH::TLV_KEY))
        {
            client->chatkey = new ECDH((unsigned char *) tlvRecords->get(ECDH::TLV_KEY).data());
        }

        delete tlvRecords;
    }
#endif

    if ((ptr < end) && !u->pubk.setkey(AsymmCipher::PUBKEY, (byte*)ptr, end - ptr))
    {
        client->users.erase(client->uhindex[uh]);
        return NULL;
    }

    return u;
}

void User::setattr(string *an, string *av, string *v)
{
    setChanged(an->c_str());

    if (*an != "+a") // avatar is saved to disc
    {
        attrs[*an] = *av;
    }

    attrsv[*an] = *v;
}

void User::invalidateattr(string an)
{
    setChanged(an.c_str());
    attrsv.erase(an);
}

// returns the value if there is value (even if it's invalid by now)
const string * User::getattr(string an)
{
    string_map::const_iterator it = attrs.find(an);
    if (it != attrs.end())
    {
        return &attrs[an];
    }

    return NULL;
}

bool User::isattrvalid(string an)
{
    return (attrsv.find(an) != attrsv.end());
}

const string *User::getattrversion(string an)
{
    string_map::iterator it = attrsv.find(an);
    if (it != attrsv.end())
    {
        return &attrsv[an];
    }

    return NULL;
}

bool User::setChanged(const char *an)
{
    if (!strcmp(an, "*keyring"))
    {
        changed.keyring = true;
    }
    else if (!strcmp(an, "*!authring"))
    {
        changed.authring = true;
    }
    else if (!strcmp(an, "*!lstint"))
    {
        changed.lstint = true;
    }
    else if (!strcmp(an, "+puCu255"))
    {
        changed.puCu255 = true;
    }
    else if (!strcmp(an, "+puEd255"))
    {
        changed.puEd255 = true;
    }
    else if (!strcmp(an, "+sigPubk"))
    {
        changed.sigPubk = true;
    }
    else if (!strcmp(an, "+sigCu255"))
    {
        changed.sigCu255 = true;
    }
    else if (!strcmp(an, "+a"))
    {
        changed.avatar = true;
    }
    else if (!strcmp(an, "firstname"))
    {
        changed.firstname = true;
    }
    else if (!strcmp(an, "lastname"))
    {
        changed.lastname = true;
    }
    else if (!strcmp(an, "country"))
    {
        changed.country = true;
    }
    else if (!strcmp(an, "birthday")   ||
             !strcmp(an, "birthmonth") ||
             !strcmp(an, "birthyear"))
    {
        changed.birthday = true;
    }
    else
    {
        return false;   // attribute not recognized
    }

    return true;
}

// update user attributes
void User::set(visibility_t v, m_time_t ct)
{
    show = v;
    ctime = ct;
}
} // namespace
<commit_msg>Improve access to user attributes<commit_after>/**
 * @file user.cpp
 * @brief Class for manipulating user / contact data
 *
 * (c) 2013-2014 by Mega Limited, Auckland, New Zealand
 *
 * This file is part of the MEGA SDK - Client Access Engine.
 *
 * Applications using the MEGA API must present a valid application key
 * and comply with the the rules set forth in the Terms of Service.
 *
 * The MEGA SDK 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.
 *
 * @copyright Simplified (2-clause) BSD License.
 *
 * You should have received a copy of the license along with this
 * program.
 */

#include "mega/user.h"
#include "mega/megaclient.h"

namespace mega {
User::User(const char* cemail)
{
    userhandle = UNDEF;
    show = VISIBILITY_UNKNOWN;
    ctime = 0;
    pubkrequested = 0;

    if (cemail)
    {
        email = cemail;
    }
}

bool User::serialize(string* d)
{
    unsigned char l;
    unsigned short ll;
    time_t ts;
    AttrMap attrmap;
    char attrVersion = '1';

    d->reserve(d->size() + 100 + attrmap.storagesize(10));

    d->append((char*)&userhandle, sizeof userhandle);

    // FIXME: use m_time_t & Serialize64 instead
    ts = ctime;
    d->append((char*)&ts, sizeof ts);
    d->append((char*)&show, sizeof show);

    l = (unsigned char)email.size();
    d->append((char*)&l, sizeof l);
    d->append(email.c_str(), l);

    d->append((char*)&attrVersion, 1);
    d->append("\0\0\0\0\0\0", 7);

    // serialization of attributes
    for (string_map::iterator it = attrs.begin(); it != attrs.end(); it++)
    {
        l = it->first.size();
        d->append((char*)&l, sizeof l);
        d->append(it->first.data(), l);

        ll = it->second.size();
        d->append((char*)&ll, sizeof ll);
        d->append(it->second.data(), ll);

        if (attrsv.find(it->first) != attrsv.end())
        {
            ll = attrsv[it->first].size();
            d->append((char*)&ll, sizeof ll);
            d->append(attrsv[it->first].data(), ll);
        }
        else
        {
            ll = 0;
            d->append((char*)&ll, sizeof ll);
        }
    }

    d->append("", 1);

    if (pubk.isvalid())
    {
        pubk.serializekey(d, AsymmCipher::PUBKEY);
    }

    return true;
}

User* User::unserialize(MegaClient* client, string* d)
{
    handle uh;
    time_t ts;
    visibility_t v;
    unsigned char l;
    unsigned short ll;
    string m;
    User* u;
    const char* ptr = d->data();
    const char* end = ptr + d->size();
    int i;
    char attrVersion;

    if (ptr + sizeof(handle) + sizeof(time_t) + sizeof(visibility_t) + 2 > end)
    {
        return NULL;
    }

    uh = MemAccess::get<handle>(ptr);
    ptr += sizeof uh;

    // FIXME: use m_time_t & Serialize64
    ts = MemAccess::get<time_t>(ptr);
    ptr += sizeof ts;

    v = MemAccess::get<visibility_t>(ptr);
    ptr += sizeof v;

    l = *ptr++;
    if (l)
    {
        if (ptr + l > end)
        {
            return NULL;
        }
        m.assign(ptr, l);
    }
    ptr += l;

    if (ptr + sizeof(char) > end)
    {
        return NULL;
    }

    attrVersion = MemAccess::get<char>(ptr);
    ptr += sizeof(attrVersion);

    for (i = 7; i--;)
    {
        if (ptr + MemAccess::get<unsigned char>(ptr) < end)
        {
            ptr += MemAccess::get<unsigned char>(ptr) + 1;
        }
    }

    if ((i >= 0) || !(u = client->finduser(uh, 1)))
    {
        return NULL;
    }

    client->mapuser(uh, m.c_str());
    u->set(v, ts);

    if (attrVersion == '\0')
    {
        AttrMap attrmap;
        if ((ptr < end) && !(ptr = attrmap.unserialize(ptr, end)))
        {
            client->users.erase(client->uhindex[uh]);
            return NULL;
        }
    }
    else if (attrVersion == '1')
    {
        string key;
        while ((ptr < end) && (l = *ptr++))
        {
            if (ptr + l + sizeof(ll) > end)
            {
                client->users.erase(client->uhindex[uh]);
                return NULL;
            }
            key.assign(ptr, l);
            ptr += l;

            ll = MemAccess::get<short>(ptr);
            ptr += sizeof ll;

            if (ptr + ll + sizeof(ll) > end)
            {
                client->users.erase(client->uhindex[uh]);
                return NULL;
            }

            u->attrs[key].assign(ptr, ll);
            ptr += ll;

            ll = MemAccess::get<short>(ptr);
            ptr += sizeof ll;

            if (ll)
            {
                if (ptr + ll > end)
                {
                    client->users.erase(client->uhindex[uh]);
                    return NULL;
                }
                u->attrsv[key].assign(ptr,ll);
                ptr += ll;
            }
        }
    }

#ifdef ENABLE_CHAT
    const string *av = (u->isattrvalid("*keyring")) ? u->getattr("*keyring") : NULL;
    if (av)
    {
        TLVstore *tlvRecords = TLVstore::containerToTLVrecords(av, &client->key);

        if (tlvRecords->find(EdDSA::TLV_KEY))
        {
            client->signkey = new EdDSA((unsigned char *) tlvRecords->get(EdDSA::TLV_KEY).data());
        }

        if (tlvRecords->find(ECDH::TLV_KEY))
        {
            client->chatkey = new ECDH((unsigned char *) tlvRecords->get(ECDH::TLV_KEY).data());
        }

        delete tlvRecords;
    }
#endif

    if ((ptr < end) && !u->pubk.setkey(AsymmCipher::PUBKEY, (byte*)ptr, end - ptr))
    {
        client->users.erase(client->uhindex[uh]);
        return NULL;
    }

    return u;
}

void User::setattr(string *an, string *av, string *v)
{
    setChanged(an->c_str());

    if (*an != "+a") // avatar is saved to disc
    {
        attrs[*an] = *av;
    }

    attrsv[*an] = *v;
}

void User::invalidateattr(string an)
{
    setChanged(an.c_str());
    attrsv.erase(an);
}

// returns the value if there is value (even if it's invalid by now)
const string * User::getattr(string an)
{
    string_map::const_iterator it = attrs.find(an);
    if (it != attrs.end())
    {
        return &(it->second);
    }

    return NULL;
}

bool User::isattrvalid(string an)
{
    return attrsv.count(an);
}

const string *User::getattrversion(string an)
{
    string_map::iterator it = attrsv.find(an);
    if (it != attrsv.end())
    {
        return &(it->second);
    }

    return NULL;
}

bool User::setChanged(const char *an)
{
    if (!strcmp(an, "*keyring"))
    {
        changed.keyring = true;
    }
    else if (!strcmp(an, "*!authring"))
    {
        changed.authring = true;
    }
    else if (!strcmp(an, "*!lstint"))
    {
        changed.lstint = true;
    }
    else if (!strcmp(an, "+puCu255"))
    {
        changed.puCu255 = true;
    }
    else if (!strcmp(an, "+puEd255"))
    {
        changed.puEd255 = true;
    }
    else if (!strcmp(an, "+sigPubk"))
    {
        changed.sigPubk = true;
    }
    else if (!strcmp(an, "+sigCu255"))
    {
        changed.sigCu255 = true;
    }
    else if (!strcmp(an, "+a"))
    {
        changed.avatar = true;
    }
    else if (!strcmp(an, "firstname"))
    {
        changed.firstname = true;
    }
    else if (!strcmp(an, "lastname"))
    {
        changed.lastname = true;
    }
    else if (!strcmp(an, "country"))
    {
        changed.country = true;
    }
    else if (!strcmp(an, "birthday")   ||
             !strcmp(an, "birthmonth") ||
             !strcmp(an, "birthyear"))
    {
        changed.birthday = true;
    }
    else
    {
        return false;   // attribute not recognized
    }

    return true;
}

// update user attributes
void User::set(visibility_t v, m_time_t ct)
{
    show = v;
    ctime = ct;
}
} // namespace
<|endoftext|>


<commit_before>#ifndef utils_hh_INCLUDED
#define utils_hh_INCLUDED

#include "exception.hh"

#include <memory>

namespace Kakoune
{

struct LineAndColumn
{
    int line;
    int column;

    LineAndColumn(int line = 0, int column = 0)
        : line(line), column(column) {}
};

template<typename Container>
struct ReversedContainer
{
    ReversedContainer(Container& container) : container(container) {}
    Container& container;

    decltype(container.rbegin()) begin() { return container.rbegin(); }
    decltype(container.rend())   end()   { return container.rend(); }
};

template<typename Container>
ReversedContainer<Container> reversed(Container& container)
{
    return ReversedContainer<Container>(container);
}

template<typename T>
bool operator== (const std::unique_ptr<T>& lhs, T* rhs)
{
    return lhs.get() == rhs;
}

}

#endif // utils_hh_INCLUDED
<commit_msg>utils: add auto_raii helper function<commit_after>#ifndef utils_hh_INCLUDED
#define utils_hh_INCLUDED

#include "exception.hh"

#include <memory>

namespace Kakoune
{

struct LineAndColumn
{
    int line;
    int column;

    LineAndColumn(int line = 0, int column = 0)
        : line(line), column(column) {}
};

template<typename Container>
struct ReversedContainer
{
    ReversedContainer(Container& container) : container(container) {}
    Container& container;

    decltype(container.rbegin()) begin() { return container.rbegin(); }
    decltype(container.rend())   end()   { return container.rend(); }
};

template<typename Container>
ReversedContainer<Container> reversed(Container& container)
{
    return ReversedContainer<Container>(container);
}

template<typename T>
bool operator== (const std::unique_ptr<T>& lhs, T* rhs)
{
    return lhs.get() == rhs;
}

template<typename T, typename F>
class AutoRaii
{
public:
    AutoRaii(T* resource, F cleanup)
        : m_resource(resource), m_cleanup(cleanup) {}

    AutoRaii(AutoRaii&& other) : m_resource(other.m_resource),
                                 m_cleanup(other.m_cleanup)
    { other.m_resource = nullptr; }

    AutoRaii(const AutoRaii&) = delete;
    AutoRaii& operator=(const AutoRaii&) = delete;

    ~AutoRaii() { if (m_resource) m_cleanup(m_resource); }

    operator T*() { return m_resource; }

private:
    T* m_resource;
    F  m_cleanup;
};

template<typename T, typename F>
AutoRaii<T, F> auto_raii(T* resource, F cleanup)
{
    return AutoRaii<T, F>(resource, cleanup);
}

}

#endif // utils_hh_INCLUDED
<|endoftext|>


<commit_before>// @(#)root/test:$Name$:$Id$
// Author: Valeriy Onuchin & Fons Rademakers   04/10/98

///////////////////////////////////////////////////////////////////
//  ROOT implementation of the X11 xclock.
//
//  To run this example do the following:
//  $ root
//  root [0] gSystem.Load("Aclock")
//  root [1] Aclock a
//  <enjoy>
//  root [2] .q
//
//  Other ROOT fun examples: Tetris, Hello ...
//
//  Begin_Html
//
//  End_Html
//
///////////////////////////////////////////////////////////////////

#include <TROOT.h>
#include <TSystem.h>
#include "Aclock.h"

ClassImp(Aclock)

Float_t MinuteHand::fgMinuteHandX[] = { -0.05, 0, 0.05 };
Float_t MinuteHand::fgMinuteHandY[] = { -0.04, 0.625, -0.04 };

Float_t HourHand::fgHourHandX[] = { -0.05, 0, 0.05 };
Float_t HourHand::fgHourHandY[] = { -0.04, 0.4, -0.04 };

Float_t SecondHand::fgSecondHandX[] = { 0., 0.035, 0., -0.035 };
Float_t SecondHand::fgSecondHandY[] = { 0.78, 0.73, 0.68, 0.73 };

TDatime *ClockHand::fgTime = new TDatime;

TPolygon::TPolygon(Int_t n, Float_t *x, Float_t *y) : TPolyLine(n+1,x,y)
{
   // Create filled polygon. Polygon will be added to current pad.

   if (!TVirtualPad::Pad()) { Error("Constructor","Create TPad first!"); return; }

   fPad  = (TPad*)TVirtualPad::Pad();
   fX[n] = x[0];             // create an extra point to connect polyline ends
   fY[n] = y[0];
   Draw();                   // append to fPad
}

void TPolygon::Paint(Option_t *)
{
   // Paint filled polygon.

   TAttLine::Modify();
   TAttFill::Modify();
   fPad->PaintFillArea(fN-1, fX, fY);
   fPad->PaintPolyLine(fN, fX, fY, "");
}

ClockHand::ClockHand(Int_t n, Float_t *x, Float_t *y) : TPolygon(n,x,y)
{
   // Create clockhand

   fX0 = new Float_t[GetN()];   // initial shape and position
   fY0 = new Float_t[GetN()];   // initial shape and position

   for (int i = 0; i < GetN(); i++) {
     fX0[i] = fX[i];
     fY0[i] = fY[i];
   }
   SetFillColor(9);            // default fill color
}

void ClockHand::Update()
{
   // Update hand position

   if (!IsModified()) return;

   fPrevTimeValue = GetTimeValue();
   Move(GetHandAngle());
}

void ClockHand::Move(Float_t clock_angle)
{
   // Move clockhand.

  Int_t n = GetN();

  // ClockPoints used to rotate,scale and shift initial points
  static ClockPoints *points = new ClockPoints();

  Float_t wh = (Float_t)fPad->XtoPixel(fPad->GetX2());
  Float_t hh = (Float_t)fPad->YtoPixel(fPad->GetY1());

  for (int i = 0; i < n; i++) {
     points->SetXY(fX0[i],fY0[i]);
     points->Rotate(clock_angle);

     if (wh < hh) points->Scale(0.5,0.5*wh/hh);    //  scale to have a circular clock
     else         points->Scale(0.5*hh/wh,0.5);

     points->Shift(0.5,0.5);                      // move to the center of pad
     fX[i] = points->GetX();
     fY[i] = points->GetY();
   }
}

Aclock::Aclock(Int_t csize) : TTimer(500, kTRUE)
{
   // Create a clock. Clock will be drawn in the current pad. If there
   // is no pad it will create a new canvas.

   if (!gPad || gPad->InheritsFrom("TCanvas"))
      fPad = new TCanvas("Aclock:canvas","xclock",-csize,csize);
   else
      fPad = (TPad*)gPad;

   fPad->SetFillColor(14);     // grey

   fMinuteHand = new MinuteHand();
   fSecondHand = new SecondHand();
   fHourHand   = new HourHand();

   SetBit(kCanDelete);
   Draw();                         // append this Aclock to fPad
   Animate();
   gSystem->AddTimer(this);        // start timer = start animation
}

Aclock::~Aclock()
{
   // Clean up the clock.

   delete fMinuteHand;
   delete fSecondHand;
   delete fHourHand;
}

void Aclock::Paint(Option_t *)
{
   // Just draw clock scale (time and minutes ticks)

   static ClockPoints *point1 = new ClockPoints();
   static ClockPoints *point2 = new ClockPoints();

   Float_t wh = (Float_t)fPad->XtoPixel(fPad->GetX2());
   Float_t hh = (Float_t)fPad->YtoPixel(fPad->GetY1());

   for (int i = 0; i < 60; i++ ) {             // draw minute/hour ticks
      point1->SetXY(0.,0.9);

      if (!(i%5)) point2->SetXY(0.,0.8);       // hour  ticks  are longer
      else        point2->SetXY(0.,0.87);

      Float_t angle = 6.*i;
      point1->Rotate(angle);
      point2->Rotate(angle);

      if (wh < hh) {                   // scale in oder to draw circle scale
         point1->Scale(0.5,0.5*wh/hh);
         point2->Scale(0.5,0.5*wh/hh);
      } else {
         point1->Scale(0.5*hh/wh,0.5);
         point2->Scale(0.5*hh/wh,0.5);
      }

      point1->Shift(0.5,0.5);              // move to center of pad
      point2->Shift(0.5,0.5);

      fPad->DrawLine(point1->GetX(),point1->GetY(),point2->GetX(),point2->GetY());
   }
}

void Aclock::Animate()
{
   // Update clock hand positions and redraw the fPad

   if (!fSecondHand->IsModified()) return;

   fHourHand->Update();            //  update position every minute
   fMinuteHand->Update();          //  update position every minute
   fSecondHand->Update();          //  update position every second
   fPad->Modified();               //  drawing ...
   fPad->Update();
}

Bool_t Aclock::Notify()
{
   // Actions after timer's time-out

   Animate();
   TTimer::Reset();
   return kFALSE;
}
<commit_msg>Replace call to TPad::DrawLine (obsolete) by TPad::PaintLine Initialize member fPrevTimeValue in ClockHand constructor<commit_after>// @(#)root/test:$Name:  $:$Id: Aclock.cxx,v 1.2 2000/07/11 18:05:26 rdm Exp $
// Author: Valeriy Onuchin & Fons Rademakers   04/10/98

///////////////////////////////////////////////////////////////////
//  ROOT implementation of the X11 xclock.
//
//  To run this example do the following:
//  $ root
//  root [0] gSystem.Load("Aclock")
//  root [1] Aclock a
//  <enjoy>
//  root [2] .q
//
//  Other ROOT fun examples: Tetris, Hello ...
//
//  Begin_Html
//
//  End_Html
//
///////////////////////////////////////////////////////////////////

#include <TROOT.h>
#include <TSystem.h>
#include "Aclock.h"

ClassImp(Aclock)

Float_t MinuteHand::fgMinuteHandX[] = { -0.05, 0, 0.05 };
Float_t MinuteHand::fgMinuteHandY[] = { -0.04, 0.625, -0.04 };

Float_t HourHand::fgHourHandX[] = { -0.05, 0, 0.05 };
Float_t HourHand::fgHourHandY[] = { -0.04, 0.4, -0.04 };

Float_t SecondHand::fgSecondHandX[] = { 0., 0.035, 0., -0.035 };
Float_t SecondHand::fgSecondHandY[] = { 0.78, 0.73, 0.68, 0.73 };

TDatime *ClockHand::fgTime = new TDatime;

TPolygon::TPolygon(Int_t n, Float_t *x, Float_t *y) : TPolyLine(n+1,x,y)
{
   // Create filled polygon. Polygon will be added to current pad.

   if (!TVirtualPad::Pad()) { Error("Constructor","Create TPad first!"); return; }

   fPad  = (TPad*)TVirtualPad::Pad();
   fX[n] = x[0];             // create an extra point to connect polyline ends
   fY[n] = y[0];
   Draw();                   // append to fPad
}

void TPolygon::Paint(Option_t *)
{
   // Paint filled polygon.

   TAttLine::Modify();
   TAttFill::Modify();
   fPad->PaintFillArea(fN-1, fX, fY);
   fPad->PaintPolyLine(fN, fX, fY, "");
}

ClockHand::ClockHand(Int_t n, Float_t *x, Float_t *y) : TPolygon(n,x,y)
{
   // Create clockhand

   fPrevTimeValue = 0;
   fX0 = new Float_t[GetN()];   // initial shape and position
   fY0 = new Float_t[GetN()];   // initial shape and position

   for (int i = 0; i < GetN(); i++) {
     fX0[i] = fX[i];
     fY0[i] = fY[i];
   }
   SetFillColor(9);            // default fill color
}

void ClockHand::Update()
{
   // Update hand position

   if (!IsModified()) return;

   fPrevTimeValue = GetTimeValue();
   Move(GetHandAngle());
}

void ClockHand::Move(Float_t clock_angle)
{
   // Move clockhand.

  Int_t n = GetN();

  // ClockPoints used to rotate,scale and shift initial points
  static ClockPoints *points = new ClockPoints();

  Float_t wh = (Float_t)fPad->XtoPixel(fPad->GetX2());
  Float_t hh = (Float_t)fPad->YtoPixel(fPad->GetY1());

  for (int i = 0; i < n; i++) {
     points->SetXY(fX0[i],fY0[i]);
     points->Rotate(clock_angle);

     if (wh < hh) points->Scale(0.5,0.5*wh/hh);    //  scale to have a circular clock
     else         points->Scale(0.5*hh/wh,0.5);

     points->Shift(0.5,0.5);                      // move to the center of pad
     fX[i] = points->GetX();
     fY[i] = points->GetY();
   }
}

Aclock::Aclock(Int_t csize) : TTimer(500, kTRUE)
{
   // Create a clock in a new canvas.

   fPad = new TCanvas("Aclock:canvas","xclock",-csize,csize);

   fPad->SetFillColor(14);     // grey

   fMinuteHand = new MinuteHand();
   fSecondHand = new SecondHand();
   fHourHand   = new HourHand();

   SetBit(kCanDelete);
   Draw();                         // append this Aclock to fPad
   Animate();
   gSystem->AddTimer(this);        // start timer = start animation
}

Aclock::~Aclock()
{
   // Clean up the clock.

   delete fMinuteHand;
   delete fSecondHand;
   delete fHourHand;
}

void Aclock::Paint(Option_t *)
{
   // Just draw clock scale (time and minutes ticks)

   static ClockPoints *point1 = new ClockPoints();
   static ClockPoints *point2 = new ClockPoints();

   Float_t wh = (Float_t)fPad->XtoPixel(fPad->GetX2());
   Float_t hh = (Float_t)fPad->YtoPixel(fPad->GetY1());

   for (int i = 0; i < 60; i++ ) {             // draw minute/hour ticks
      point1->SetXY(0.,0.9);

      if (!(i%5)) point2->SetXY(0.,0.8);       // hour  ticks  are longer
      else        point2->SetXY(0.,0.87);

      Float_t angle = 6.*i;
      point1->Rotate(angle);
      point2->Rotate(angle);

      if (wh < hh) {                   // scale in oder to draw circle scale
         point1->Scale(0.5,0.5*wh/hh);
         point2->Scale(0.5,0.5*wh/hh);
      } else {
         point1->Scale(0.5*hh/wh,0.5);
         point2->Scale(0.5*hh/wh,0.5);
      }

      point1->Shift(0.5,0.5);              // move to center of pad
      point2->Shift(0.5,0.5);

      fPad->PaintLine(point1->GetX(),point1->GetY(),point2->GetX(),point2->GetY());
   }
}

void Aclock::Animate()
{
   // Update clock hand positions and redraw the fPad

   if (!fSecondHand->IsModified()) return;

   fHourHand->Update();            //  update position every minute
   fMinuteHand->Update();          //  update position every minute
   fSecondHand->Update();          //  update position every second
   fPad->Modified();               //  drawing ...
   fPad->Update();
}

Bool_t Aclock::Notify()
{
   // Actions after timer's time-out

   Animate();
   TTimer::Reset();
   return kFALSE;
}
<|endoftext|>


<commit_before>#include "ChatServer.h"

#include <iostream>
#include <thread>
#include <fstream>

ChatServer::ChatServer()
	: TCPSocketServer()
{
	config.loadConfigFile( "config.ini" );
}

void ChatServer::addLogLine( std::string msg )
{
	// save to message queue (10 messages capacity)
	msgLog.push_back( msg );
	if( msgLog.size() > 10 )
	{
		msgLog.pop_front();
	}

	// also write to logfile
	std::ofstream file;
	file.open( config.getStringParameter( "msgLogFile" ),
			std::ofstream::app );
	if( file.good() )
	{
		file << msg << std::endl;
	}
	file.close();
}

bool ChatServer::connect()
{
	if( TCPSocketServer::connect(config.getIntParameter("wsServerPort")) )
	{
		if( ircConnection.connectChannel(
					config.getStringParameter( "ircServerIP" ),
					config.getIntParameter( "ircServerPort" ),
					config.getStringParameter( "ircChannel" ),
					config.getStringParameter( "ircBotNick" ) ))
		{
			return true;
		}
		else close();
	}
	return false;
}

void ChatServer::ircLoop()
{
	while( ircConnection.isGood() )
	{
		std::string msg = ircConnection.getLine();
		if( ! msg.empty() )
		{
			notifyParticipants( msg );
		}
	}
}

void ChatServer::listeningLoop()
{
	std::cout << "started loops" << std::endl;

	std::thread t0 ( &ChatServer::ircLoop, this );
	t0.detach();

	while( good() )
	{
		int connection_fd = listenForIncoming();
		std::cout << "incoming" << std::endl;
		std::thread t1 (
				&ChatServer::participantLoop, this, connection_fd );
		t1.detach();
		std::cout << "detached" << std::endl;
		// TODO thread pool
	}
	close();
}

void ChatServer::participantLoop( int connection_fd )
{
	std::cout << "participant loop" << std::endl;

	WebSocketConnection newConnection (connection_fd);
	if( newConnection.open() )
	{
		std::string partName = "";
		while( newConnection.isGood() && partName.empty() )
		{
			// query name as long as no name is provided
			partName = newConnection.getWebsocketMsg();
		}
		if( newConnection.isGood() ) // => partName is not empty
		{
			// get message history
			for( auto it = msgLog.begin(); it != msgLog.end(); it++ )
			{
				// TODO thread safety
				newConnection.putLine( *it );
			}
			participants.push_back(&newConnection);
			notifyParticipants( partName, 1 );
			while( newConnection.isGood() ) {
				std::string incoming = newConnection.getWebsocketMsg();
				if( !incoming.empty() ) // only accept non-empty messages
				{
					notifyParticipants( partName, incoming );
					notifyIRC( partName, incoming );
				}
				incoming = "";
			}
			participants.remove(&newConnection);
			// TODO: scope-bound destruction of pointer using subscriber-pattern (-> stack-unwinding)
			notifyParticipants( partName, 0 );
		}
	}
}

void ChatServer::notifyParticipants( std::string name, unsigned int status )
{
	time_t rawtime;
	time( &rawtime);
	struct tm* timeinfo = localtime(&rawtime);
	char buff[9];
	strftime( buff, 9, "(%R) ", timeinfo);

	std::string statusMsg = status == 1
		? " joined conversation."
		: " left conversation.";
	// TODO mutexify
	for( auto it = participants.begin(); it != participants.end(); it++ )
	{
		(*it)->putLine( buff + name + statusMsg );
	}
	std::cout << buff << name << statusMsg << std::endl;
}

void ChatServer::notifyParticipants( std::string msg )
{
	time_t rawtime;
	time( &rawtime);
	struct tm* timeinfo = localtime(&rawtime);
	char buff[9];
	strftime( buff, 9, "(%R) ", timeinfo);

	addLogLine( buff + msg );

	// TODO mutexify
	for( auto it = participants.begin(); it != participants.end(); it++ )
	{
		(*it)->putLine( buff + msg );
	}
	std::cout << buff << msg << std::endl;
}

void ChatServer::notifyParticipants( std::string name, std::string msg )
{
	time_t rawtime;
	time( &rawtime);
	struct tm* timeinfo = localtime(&rawtime);
	char buff[9];
	strftime( buff, 9, "(%R) ", timeinfo);

	addLogLine( buff + name + ": " + msg );

	// TODO mutexify
	for( auto it = participants.begin(); it != participants.end(); it++ )
	{
		(*it)->putLine( buff + name + ": " + msg );
	}
	std::cout << buff << name << ": " << msg << std::endl;
}

void ChatServer::notifyIRC( std::string name, std::string msg )
{
	if( !ircConnection.isGood() ) return;
	ircConnection.putLine( name + ": " + msg );
}
<commit_msg>No IRC channel connection possible (config.ini).<commit_after>#include "ChatServer.h"

#include <iostream>
#include <thread>
#include <fstream>

ChatServer::ChatServer()
	: TCPSocketServer()
{
	config.loadConfigFile( "config.ini" );
}

void ChatServer::addLogLine( std::string msg )
{
	// save to message queue (10 messages capacity)
	msgLog.push_back( msg );
	if( msgLog.size() > 10 )
	{
		msgLog.pop_front();
	}

	// also write to logfile
	std::ofstream file;
	file.open( config.getStringParameter( "msgLogFile" ),
			std::ofstream::app );
	if( file.good() )
	{
		file << msg << std::endl;
	}
	file.close();
}

bool ChatServer::connect()
{
	if( TCPSocketServer::connect(config.getIntParameter("wsServerPort")) )
	{
		if( ! config.getIntParameter("useIrc") ) {
			std::cout << "No IRC channel connection." << std::endl;
			return true;
		}
		if( ircConnection.connectChannel(
					config.getStringParameter( "ircServerIP" ),
					config.getIntParameter( "ircServerPort" ),
					config.getStringParameter( "ircChannel" ),
					config.getStringParameter( "ircBotNick" ) ))
		{
			return true;
		}
		else close();
	}
	return false;
}

void ChatServer::ircLoop()
{
	while( ircConnection.isGood() )
	{
		std::string msg = ircConnection.getLine();
		if( ! msg.empty() )
		{
			notifyParticipants( msg );
		}
	}
}

void ChatServer::listeningLoop()
{
	std::cout << "started loops" << std::endl;

	std::thread t0 ( &ChatServer::ircLoop, this );
	t0.detach();

	while( good() )
	{
		int connection_fd = listenForIncoming();
		std::cout << "incoming" << std::endl;
		std::thread t1 (
				&ChatServer::participantLoop, this, connection_fd );
		t1.detach();
		std::cout << "detached" << std::endl;
		// TODO thread pool
	}
	close();
}

void ChatServer::participantLoop( int connection_fd )
{
	std::cout << "participant loop" << std::endl;

	WebSocketConnection newConnection (connection_fd);
	if( newConnection.open() )
	{
		std::string partName = "";
		while( newConnection.isGood() && partName.empty() )
		{
			// query name as long as no name is provided
			partName = newConnection.getWebsocketMsg();
		}
		if( newConnection.isGood() ) // => partName is not empty
		{
			// get message history
			for( auto it = msgLog.begin(); it != msgLog.end(); it++ )
			{
				// TODO thread safety
				newConnection.putLine( *it );
			}
			participants.push_back(&newConnection);
			notifyParticipants( partName, 1 );
			while( newConnection.isGood() ) {
				std::string incoming = newConnection.getWebsocketMsg();
				if( !incoming.empty() ) // only accept non-empty messages
				{
					notifyParticipants( partName, incoming );
					notifyIRC( partName, incoming );
				}
				incoming = "";
			}
			participants.remove(&newConnection);
			// TODO: scope-bound destruction of pointer using subscriber-pattern (-> stack-unwinding)
			notifyParticipants( partName, 0 );
		}
	}
}

void ChatServer::notifyParticipants( std::string name, unsigned int status )
{
	time_t rawtime;
	time( &rawtime);
	struct tm* timeinfo = localtime(&rawtime);
	char buff[9];
	strftime( buff, 9, "(%R) ", timeinfo);

	std::string statusMsg = status == 1
		? " joined conversation."
		: " left conversation.";
	// TODO mutexify
	for( auto it = participants.begin(); it != participants.end(); it++ )
	{
		(*it)->putLine( buff + name + statusMsg );
	}
	std::cout << buff << name << statusMsg << std::endl;
}

void ChatServer::notifyParticipants( std::string msg )
{
	time_t rawtime;
	time( &rawtime);
	struct tm* timeinfo = localtime(&rawtime);
	char buff[9];
	strftime( buff, 9, "(%R) ", timeinfo);

	addLogLine( buff + msg );

	// TODO mutexify
	for( auto it = participants.begin(); it != participants.end(); it++ )
	{
		(*it)->putLine( buff + msg );
	}
	std::cout << buff << msg << std::endl;
}

void ChatServer::notifyParticipants( std::string name, std::string msg )
{
	time_t rawtime;
	time( &rawtime);
	struct tm* timeinfo = localtime(&rawtime);
	char buff[9];
	strftime( buff, 9, "(%R) ", timeinfo);

	addLogLine( buff + name + ": " + msg );

	// TODO mutexify
	for( auto it = participants.begin(); it != participants.end(); it++ )
	{
		(*it)->putLine( buff + name + ": " + msg );
	}
	std::cout << buff << name << ": " << msg << std::endl;
}

void ChatServer::notifyIRC( std::string name, std::string msg )
{
	if( !ircConnection.isGood() ) return;
	ircConnection.putLine( name + ": " + msg );
}
<|endoftext|>


<commit_before>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN all_of any_of none_of tests

#include <boost/test/unit_test.hpp>

#include <algorithm>
#include <vector>

#include "operators.h"
#include "rectangle.h"

using rectangle = rectangle_t<int>;

BOOST_AUTO_TEST_SUITE( all_of_test_suite )

BOOST_AUTO_TEST_CASE( empty_container_all_of )
{
    std::vector<rectangle> rects;

    /*! True regardless of the predicate, as all elements in the container
     * satisfy the predicate trivially. */
    BOOST_CHECK(std::all_of(std::begin(rects), std::end(rects), true_no_op()));
    BOOST_CHECK(std::all_of(std::begin(rects), std::end(rects), false_no_op()));
}

BOOST_AUTO_TEST_CASE( empty_container_any_of )
{
    std::vector<rectangle> rects;

    /*! True regardless of the predicate, as none of the elements in the
     * container make the predicate return false. */
    BOOST_CHECK(std::none_of(std::begin(rects), std::end(rects), true_no_op()));
    BOOST_CHECK(std::none_of(std::begin(rects), std::end(rects), false_no_op()));
}

BOOST_AUTO_TEST_CASE( empty_container_none_of )
{
    std::vector<rectangle> rects;

    /*! Note the definition for any_of: "returns true if the predicate returns
     * true for *at least one* element in the range. Since the range has no
     * elements, if must return false for any predicate, as there is no
     * 'witness'. */
    BOOST_CHECK(not std::any_of(std::begin(rects), std::end(rects), true_no_op()));
    BOOST_CHECK(not std::any_of(std::begin(rects), std::end(rects), false_no_op()));
}

BOOST_AUTO_TEST_CASE( no_op_all_of )
{
    const rects_variety_fixture f;

    BOOST_CHECK(std::all_of(std::begin(f.rects), std::end(f.rects), true_no_op()));
    BOOST_CHECK(not std::all_of(std::begin(f.rects), std::end(f.rects), false_no_op()));
    BOOST_CHECK(not std::all_of(std::begin(f.rects), std::end(f.rects), alternating_no_op()));
}

BOOST_AUTO_TEST_CASE( no_op_any_of )
{
    const rects_variety_fixture f;

    BOOST_CHECK(std::any_of(std::begin(f.rects), std::end(f.rects), true_no_op()));
    BOOST_CHECK(not std::any_of(std::begin(f.rects), std::end(f.rects), false_no_op()));

    /*! True, as the container has at least 2 elements. */
    BOOST_CHECK(std::any_of(std::begin(f.rects), std::end(f.rects), alternating_no_op()));
}

BOOST_AUTO_TEST_CASE( no_op_none_of )
{
    const rects_variety_fixture f;

    BOOST_CHECK(not std::none_of(std::begin(f.rects), std::end(f.rects), true_no_op()));
    BOOST_CHECK(std::none_of(std::begin(f.rects), std::end(f.rects), false_no_op()));
    BOOST_CHECK(not std::none_of(std::begin(f.rects), std::end(f.rects), alternating_no_op()));
}

BOOST_AUTO_TEST_SUITE_END( /* STL_Algorithm_all_of_Test_Suite */ )
<commit_msg>Consistent naming.<commit_after>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN all_of any_of none_of tests

#include <boost/test/unit_test.hpp>

#include <algorithm>
#include <vector>

#include "operators.h"
#include "rectangle.h"

using rectangle = rectangle_t<int>;

BOOST_AUTO_TEST_SUITE( all_of_test_suite )

BOOST_AUTO_TEST_CASE( empty_container_all_of )
{
    std::vector<rectangle> rects;

    /*! True regardless of the predicate, as all elements in the container
     * satisfy the predicate trivially. */
    BOOST_CHECK(std::all_of(std::begin(rects), std::end(rects), true_no_op()));
    BOOST_CHECK(std::all_of(std::begin(rects), std::end(rects), false_no_op()));
}

BOOST_AUTO_TEST_CASE( empty_container_any_of )
{
    std::vector<rectangle> rects;

    /*! True regardless of the predicate, as none of the elements in the
     * container make the predicate return false. */
    BOOST_CHECK(std::none_of(std::begin(rects), std::end(rects), true_no_op()));
    BOOST_CHECK(std::none_of(std::begin(rects), std::end(rects), false_no_op()));
}

BOOST_AUTO_TEST_CASE( empty_container_none_of )
{
    std::vector<rectangle> rects;

    /*! Note the definition for any_of: "returns true if the predicate returns
     * true for *at least one* element in the range. Since the range has no
     * elements, if must return false for any predicate, as there is no
     * 'witness'. */
    BOOST_CHECK(not std::any_of(std::begin(rects), std::end(rects), true_no_op()));
    BOOST_CHECK(not std::any_of(std::begin(rects), std::end(rects), false_no_op()));
}

BOOST_AUTO_TEST_CASE( no_op_all_of )
{
    const rects_variety_fixture f;

    BOOST_CHECK(std::all_of(std::begin(f.rects), std::end(f.rects), true_no_op()));
    BOOST_CHECK(not std::all_of(std::begin(f.rects), std::end(f.rects), false_no_op()));
    BOOST_CHECK(not std::all_of(std::begin(f.rects), std::end(f.rects), alternating_no_op()));
}

BOOST_AUTO_TEST_CASE( no_op_any_of )
{
    const rects_variety_fixture f;

    BOOST_CHECK(std::any_of(std::begin(f.rects), std::end(f.rects), true_no_op()));
    BOOST_CHECK(not std::any_of(std::begin(f.rects), std::end(f.rects), false_no_op()));

    /*! True, as the container has at least 2 elements. */
    BOOST_CHECK(std::any_of(std::begin(f.rects), std::end(f.rects), alternating_no_op()));
}

BOOST_AUTO_TEST_CASE( no_op_none_of )
{
    const rects_variety_fixture f;

    BOOST_CHECK(not std::none_of(std::begin(f.rects), std::end(f.rects), true_no_op()));
    BOOST_CHECK(std::none_of(std::begin(f.rects), std::end(f.rects), false_no_op()));
    BOOST_CHECK(not std::none_of(std::begin(f.rects), std::end(f.rects), alternating_no_op()));
}

BOOST_AUTO_TEST_SUITE_END( /* all_of_test_suite */ )
<|endoftext|>


<commit_before>/*
 * v8cgi main file. Loosely based on V8's "shell" sample app.
 */

#include <v8.h>
#include "js_system.h"
#include "js_io.h"
#include "js_mysql.h"
#include "js_gd.h"
#include "js_common.h"

#include <sstream>

#define _STRING(x) #x
#define STRING(x) _STRING(x)

// chdir()
#ifndef HAVE_CHDIR
#	include <direct.h>
#       define chdir(name) _chdir(name)
#endif

// getcwd()
#ifndef HAVE_GETCWD
#	include <direct.h>
#       define getcwd(name) _getcwd(name)
#endif

v8::Handle<v8::Array> __onexit;

void die(int code) {
	uint32_t max = __onexit->Length();
	v8::Handle<v8::Function> fun;
	for (unsigned int i=0;i<max;i++) {
		fun = v8::Handle<v8::Function>::Cast(__onexit->Get(JS_INT(i)));
		fun->Call(v8::Context::GetCurrent()->Global(), 0, NULL);
	}
	exit(code);
}

v8::Handle<v8::String> read_file(const char* name) {
	printf("%s",name);
	FILE* file = fopen(name, "rb");
	if (file == NULL) return v8::Handle<v8::String>();

	fseek(file, 0, SEEK_END);
	size_t size = ftell(file);
	rewind(file);

	char* chars = new char[size + 1];
	chars[size] = '\0';
	for (unsigned int i = 0; i < size;) {
		size_t read = fread(&chars[i], 1, size - i, file);
		i += read;
	}
	fclose(file);

	/* remove shebang line */
	std::string str = chars;
	if ( str.find('#',0) == 0 && str.find('!',1) == 1 ) {
		unsigned int pfix = str.find('\n',0);
		str.erase(0,pfix);
	};

	v8::Handle<v8::String> result = JS_STR(str.c_str());
	delete[] chars;
	return result;
}

void report_exception(v8::TryCatch* try_catch) {
	v8::HandleScope handle_scope;
	v8::String::Utf8Value exception(try_catch->Exception());
	v8::Handle<v8::Message> message = try_catch->Message();
	std::string msgstring = "";
	std::stringstream ss;
	std::string tmp;

	if (message.IsEmpty()) {
		msgstring += *exception;
		msgstring += "\n";
	} else {
		v8::String::Utf8Value filename(message->GetScriptResourceName());
		int linenum = message->GetLineNumber();
		msgstring += *filename;
		msgstring += ":";

		ss << linenum;
		ss >> tmp;

		msgstring += tmp;
		msgstring += ": ";
		msgstring += *exception;
		msgstring += "\n";
		v8::String::Utf8Value sourceline(message->GetSourceLine());
		msgstring += *sourceline;
		msgstring += "\n";

		// Print wavy underline (GetUnderline is deprecated).
		int start = message->GetStartColumn();
		for (int i = 0; i < start; i++) {
			msgstring += " ";
		}
		int end = message->GetEndColumn();
		for (int i = start; i < end; i++) {
			msgstring += "^";
		}
		msgstring += "\n";
	}

	int cgi = 0;
	v8::Local<v8::Function> fun;
	v8::Local<v8::Value> context = v8::Context::GetCurrent()->Global()->Get(JS_STR("response"));
	if (context->IsObject()) {
		v8::Local<v8::Value> print = context->ToObject()->Get(JS_STR("error"));
		if (print->IsObject()) {
			fun = v8::Local<v8::Function>::Cast(print);
			cgi = 1;
		}
	}
	if (!cgi) {
		context = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
		fun = v8::Local<v8::Function>::Cast(context->ToObject()->Get(JS_STR("stdout")));
	}

	v8::Handle<v8::Value> data[1];
	data[0] = JS_STR(msgstring.c_str());
	fun->Call(context->ToObject(), 1, data);
}

int execute_file(const char * str) {
	v8::HandleScope handle_scope;
	v8::TryCatch try_catch;
	v8::Handle<v8::String> name = JS_STR(str);
	v8::Handle<v8::String> source = read_file(str);

	if (source.IsEmpty()) {
		printf("Error reading '%s'\n", str);
		return 1;
	}

	v8::Handle<v8::Script> script = v8::Script::Compile(source, name);
	if (script.IsEmpty()) {
		report_exception(&try_catch);
		return 1;
	} else {

		char * old = getcwd(NULL, 0);
		char * end = strrchr(str, '/');
		if (end == NULL) {
			end = strrchr(str, '\\');
		}

		if (end != NULL) {
			int len = end-str;
			char * base = (char *) malloc(len+1);
			strncpy(base, str, len);
    			base[len] = '\0';
    			chdir(base);
		}
		v8::Handle<v8::Value> result = script->Run();
		chdir(old);
		if (result.IsEmpty()) {
			report_exception(&try_catch);
			return 1;
		}
	}
	return 0;
}

int library(char * name) {
	v8::HandleScope handle_scope;
	v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
	v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
	v8::String::Utf8Value pfx(prefix);
	std::string path = "";

	path += *pfx;
	path += "/";
	path += name;
	return execute_file(path.c_str());
}

v8::Handle<v8::Value> _include(const v8::Arguments& args) {
	bool ok = true;
	int result;
	for (int i = 0; i < args.Length(); i++) {
		v8::HandleScope handle_scope;
		v8::String::Utf8Value file(args[i]);
		result = execute_file(*file);
		if (result != 0) { ok = false; }
	}
	return JS_BOOL(ok);
}

v8::Handle<v8::Value> _library(const v8::Arguments & args) {
	bool ok = true;
	int result;

	v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
	v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
	v8::String::Utf8Value pfx(prefix);

	for (int i = 0; i < args.Length(); i++) {
		v8::HandleScope handle_scope;
		v8::String::Utf8Value file(args[i]);
		result = library(*file);
		if (result != 0) { ok = false; }
	}
	return JS_BOOL(ok);
}

v8::Handle<v8::Value> _exit(const v8::Arguments& args) {
	die(args[0]->Int32Value());
	return v8::Undefined();
}

v8::Handle<v8::Value> _onexit(const v8::Arguments& args) {
	__onexit->Set(JS_INT(__onexit->Length()), args[0]);
	return v8::Undefined();
}

int library_autoload() {
	v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
	v8::Handle<v8::Array> list = v8::Handle<v8::Array>::Cast(config->ToObject()->Get(JS_STR("libraryAutoload")));
	int cnt = list->Length();
	for (int i=0;i<cnt;i++) {
		v8::Handle<v8::Value> item = list->Get(JS_INT(i));
		v8::String::Utf8Value name(item);
		if (library(*name)) { return 1; }
	}
	return 0;
}

void init(char * cfg) {
	int result = execute_file(cfg);
	if (result) {
		printf("Cannot load configuration, quitting...\n");
		die(1);
	}
	result = library_autoload();
	if (result) {
		printf("Cannot load default libraries, quitting...\n");
		die(1);
	}
}

int main(int argc, char ** argv, char ** envp) {
	v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
	v8::HandleScope handle_scope;

	v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
	v8::Handle<v8::Context> context = v8::Context::New(NULL, global);
	v8::Context::Scope context_scope(context);

	__onexit = v8::Array::New();
	context->Global()->Set(JS_STR("library"), v8::FunctionTemplate::New(_library)->GetFunction());
	context->Global()->Set(JS_STR("include"), v8::FunctionTemplate::New(_include)->GetFunction());
	context->Global()->Set(JS_STR("exit"), v8::FunctionTemplate::New(_exit)->GetFunction());
	context->Global()->Set(JS_STR("onexit"), v8::FunctionTemplate::New(_onexit)->GetFunction());
	context->Global()->Set(JS_STR("global"), context->Global());
	context->Global()->Set(JS_STR("Config"), v8::Object::New());

	setup_system(envp, context->Global());
	setup_io(context->Global());

	#ifdef HAVE_MYSQL
	setup_mysql(context->Global());
	#endif

	#ifdef HAVE_GD
	setup_gd(context->Global());
	#endif

	char * cfg = STRING(CONFIG_PATH);
	int argptr = 0;
	for (int i = 1; i < argc; i++) {
		const char* str = argv[i];
		argptr = i;
		if (strcmp(str, "-c") == 0 && i + 1 < argc) {
			cfg = argv[i+1];
			argptr = 0;
			i++;
		}
	}

	init(cfg);

	if (!argptr) {
		// try the PATH_TRANSLATED env var
		v8::Handle<v8::Value> sys = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
		v8::Handle<v8::Value> env = sys->ToObject()->Get(JS_STR("env"));
		v8::Handle<v8::Value> pt = env->ToObject()->Get(JS_STR("PATH_TRANSLATED"));
		if (pt->IsString()) {
			v8::String::Utf8Value name(pt);
			int result = execute_file(*name);
			if (result) { die(result); }
		} else {
			printf("Nothing to do.\n");
		}
	} else {
		int result = execute_file(argv[argptr]);
		if (result) { die(result); }
	}
	die(0);
}
<commit_msg>chdir, getcwd for msve<commit_after>/*
 * v8cgi main file. Loosely based on V8's "shell" sample app.
 */

#include <v8.h>
#include "js_system.h"
#include "js_io.h"
#include "js_mysql.h"
#include "js_gd.h"
#include "js_common.h"

#include <sstream>

#define _STRING(x) #x
#define STRING(x) _STRING(x)

// chdir()
#ifndef HAVE_CHDIR
#	include <direct.h>
#       define chdir(name) _chdir(name)
#endif

// getcwd()
#ifndef HAVE_GETCWD
#	include <direct.h>
#       define getcwd(name, bytes) _getcwd(name, bytes)
#endif

v8::Handle<v8::Array> __onexit;

void die(int code) {
	uint32_t max = __onexit->Length();
	v8::Handle<v8::Function> fun;
	for (unsigned int i=0;i<max;i++) {
		fun = v8::Handle<v8::Function>::Cast(__onexit->Get(JS_INT(i)));
		fun->Call(v8::Context::GetCurrent()->Global(), 0, NULL);
	}
	exit(code);
}

v8::Handle<v8::String> read_file(const char* name) {
	printf("%s",name);
	FILE* file = fopen(name, "rb");
	if (file == NULL) return v8::Handle<v8::String>();

	fseek(file, 0, SEEK_END);
	size_t size = ftell(file);
	rewind(file);

	char* chars = new char[size + 1];
	chars[size] = '\0';
	for (unsigned int i = 0; i < size;) {
		size_t read = fread(&chars[i], 1, size - i, file);
		i += read;
	}
	fclose(file);

	/* remove shebang line */
	std::string str = chars;
	if ( str.find('#',0) == 0 && str.find('!',1) == 1 ) {
		unsigned int pfix = str.find('\n',0);
		str.erase(0,pfix);
	};

	v8::Handle<v8::String> result = JS_STR(str.c_str());
	delete[] chars;
	return result;
}

void report_exception(v8::TryCatch* try_catch) {
	v8::HandleScope handle_scope;
	v8::String::Utf8Value exception(try_catch->Exception());
	v8::Handle<v8::Message> message = try_catch->Message();
	std::string msgstring = "";
	std::stringstream ss;
	std::string tmp;

	if (message.IsEmpty()) {
		msgstring += *exception;
		msgstring += "\n";
	} else {
		v8::String::Utf8Value filename(message->GetScriptResourceName());
		int linenum = message->GetLineNumber();
		msgstring += *filename;
		msgstring += ":";

		ss << linenum;
		ss >> tmp;

		msgstring += tmp;
		msgstring += ": ";
		msgstring += *exception;
		msgstring += "\n";
		v8::String::Utf8Value sourceline(message->GetSourceLine());
		msgstring += *sourceline;
		msgstring += "\n";

		// Print wavy underline (GetUnderline is deprecated).
		int start = message->GetStartColumn();
		for (int i = 0; i < start; i++) {
			msgstring += " ";
		}
		int end = message->GetEndColumn();
		for (int i = start; i < end; i++) {
			msgstring += "^";
		}
		msgstring += "\n";
	}

	int cgi = 0;
	v8::Local<v8::Function> fun;
	v8::Local<v8::Value> context = v8::Context::GetCurrent()->Global()->Get(JS_STR("response"));
	if (context->IsObject()) {
		v8::Local<v8::Value> print = context->ToObject()->Get(JS_STR("error"));
		if (print->IsObject()) {
			fun = v8::Local<v8::Function>::Cast(print);
			cgi = 1;
		}
	}
	if (!cgi) {
		context = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
		fun = v8::Local<v8::Function>::Cast(context->ToObject()->Get(JS_STR("stdout")));
	}

	v8::Handle<v8::Value> data[1];
	data[0] = JS_STR(msgstring.c_str());
	fun->Call(context->ToObject(), 1, data);
}

int execute_file(const char * str) {
	v8::HandleScope handle_scope;
	v8::TryCatch try_catch;
	v8::Handle<v8::String> name = JS_STR(str);
	v8::Handle<v8::String> source = read_file(str);

	if (source.IsEmpty()) {
		printf("Error reading '%s'\n", str);
		return 1;
	}

	v8::Handle<v8::Script> script = v8::Script::Compile(source, name);
	if (script.IsEmpty()) {
		report_exception(&try_catch);
		return 1;
	} else {

		char * old = getcwd(NULL, 0);
		char * end = strrchr(str, '/');
		if (end == NULL) {
			end = strrchr(str, '\\');
		}

		if (end != NULL) {
			int len = end-str;
			char * base = (char *) malloc(len+1);
			strncpy(base, str, len);
    			base[len] = '\0';
    			chdir(base);
		}
		v8::Handle<v8::Value> result = script->Run();
		chdir(old);
		if (result.IsEmpty()) {
			report_exception(&try_catch);
			return 1;
		}
	}
	return 0;
}

int library(char * name) {
	v8::HandleScope handle_scope;
	v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
	v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
	v8::String::Utf8Value pfx(prefix);
	std::string path = "";

	path += *pfx;
	path += "/";
	path += name;
	return execute_file(path.c_str());
}

v8::Handle<v8::Value> _include(const v8::Arguments& args) {
	bool ok = true;
	int result;
	for (int i = 0; i < args.Length(); i++) {
		v8::HandleScope handle_scope;
		v8::String::Utf8Value file(args[i]);
		result = execute_file(*file);
		if (result != 0) { ok = false; }
	}
	return JS_BOOL(ok);
}

v8::Handle<v8::Value> _library(const v8::Arguments & args) {
	bool ok = true;
	int result;

	v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
	v8::Handle<v8::Value> prefix = config->ToObject()->Get(JS_STR("libraryPath"));
	v8::String::Utf8Value pfx(prefix);

	for (int i = 0; i < args.Length(); i++) {
		v8::HandleScope handle_scope;
		v8::String::Utf8Value file(args[i]);
		result = library(*file);
		if (result != 0) { ok = false; }
	}
	return JS_BOOL(ok);
}

v8::Handle<v8::Value> _exit(const v8::Arguments& args) {
	die(args[0]->Int32Value());
	return v8::Undefined();
}

v8::Handle<v8::Value> _onexit(const v8::Arguments& args) {
	__onexit->Set(JS_INT(__onexit->Length()), args[0]);
	return v8::Undefined();
}

int library_autoload() {
	v8::Handle<v8::Value> config = v8::Context::GetCurrent()->Global()->Get(JS_STR("Config"));
	v8::Handle<v8::Array> list = v8::Handle<v8::Array>::Cast(config->ToObject()->Get(JS_STR("libraryAutoload")));
	int cnt = list->Length();
	for (int i=0;i<cnt;i++) {
		v8::Handle<v8::Value> item = list->Get(JS_INT(i));
		v8::String::Utf8Value name(item);
		if (library(*name)) { return 1; }
	}
	return 0;
}

void init(char * cfg) {
	int result = execute_file(cfg);
	if (result) {
		printf("Cannot load configuration, quitting...\n");
		die(1);
	}
	result = library_autoload();
	if (result) {
		printf("Cannot load default libraries, quitting...\n");
		die(1);
	}
}

int main(int argc, char ** argv, char ** envp) {
	v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
	v8::HandleScope handle_scope;

	v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
	v8::Handle<v8::Context> context = v8::Context::New(NULL, global);
	v8::Context::Scope context_scope(context);

	__onexit = v8::Array::New();
	context->Global()->Set(JS_STR("library"), v8::FunctionTemplate::New(_library)->GetFunction());
	context->Global()->Set(JS_STR("include"), v8::FunctionTemplate::New(_include)->GetFunction());
	context->Global()->Set(JS_STR("exit"), v8::FunctionTemplate::New(_exit)->GetFunction());
	context->Global()->Set(JS_STR("onexit"), v8::FunctionTemplate::New(_onexit)->GetFunction());
	context->Global()->Set(JS_STR("global"), context->Global());
	context->Global()->Set(JS_STR("Config"), v8::Object::New());

	setup_system(envp, context->Global());
	setup_io(context->Global());

	#ifdef HAVE_MYSQL
	setup_mysql(context->Global());
	#endif

	#ifdef HAVE_GD
	setup_gd(context->Global());
	#endif

	char * cfg = STRING(CONFIG_PATH);
	int argptr = 0;
	for (int i = 1; i < argc; i++) {
		const char* str = argv[i];
		argptr = i;
		if (strcmp(str, "-c") == 0 && i + 1 < argc) {
			cfg = argv[i+1];
			argptr = 0;
			i++;
		}
	}

	init(cfg);

	if (!argptr) {
		// try the PATH_TRANSLATED env var
		v8::Handle<v8::Value> sys = v8::Context::GetCurrent()->Global()->Get(JS_STR("System"));
		v8::Handle<v8::Value> env = sys->ToObject()->Get(JS_STR("env"));
		v8::Handle<v8::Value> pt = env->ToObject()->Get(JS_STR("PATH_TRANSLATED"));
		if (pt->IsString()) {
			v8::String::Utf8Value name(pt);
			int result = execute_file(*name);
			if (result) { die(result); }
		} else {
			printf("Nothing to do.\n");
		}
	} else {
		int result = execute_file(argv[argptr]);
		if (result) { die(result); }
	}
	die(0);
}
<|endoftext|>


<commit_before>/* rest_proxy.cc
   Jeremy Barnes, 14 November 2012
   Copyright (c) 2012 Datacratic Inc.  All rights reserved.

*/

#include "rest_proxy.h"

using namespace std;
using namespace ML;

namespace Datacratic {

/*****************************************************************************/
/* REST PROXY                                                                */
/*****************************************************************************/

RestProxy::
RestProxy()
    : operationQueue(1024),
      numMessagesOutstanding_(0),
      currentOpId(1)
{
    // What to do when we get a new entry in the queue?
    operationQueue.onEvent = std::bind(&RestProxy::handleOperation,
                                       this, std::placeholders::_1);

}

RestProxy::
RestProxy(const std::shared_ptr<zmq::context_t> & context)
    : operationQueue(1024),
      connection(context),
      numMessagesOutstanding_(0),
      currentOpId(1)
{
    // What to do when we get a new entry in the queue?
    operationQueue.onEvent = std::bind(&RestProxy::handleOperation,
                                       this, std::placeholders::_1);

}

RestProxy::
~RestProxy()
{
    shutdown();
}

void
RestProxy::
sleepUntilIdle()
{
    for (;;) {
        int o = numMessagesOutstanding_;
        //cerr << "numMessagesOustanding = " << o << endl;
        if (!o)
            return;
        ML::futex_wait(numMessagesOutstanding_, o, 0.01);
    }
}

void
RestProxy::
shutdown()
{
    // Stop processing messages
    MessageLoop::shutdown();

    connection.shutdown();
}

void
RestProxy::
init(std::shared_ptr<ConfigurationService> config,
     const std::string & serviceName)
{
    serviceName_ = serviceName;

    connection.init(config, ZMQ_XREQ);
    connection.connect(serviceName + "/zeromq");

    addSource("RestProxy::operationQueue", operationQueue);

    // What to do when we get something back from zeromq?
    addSource("RestProxy::handleZmqResponse",
              std::make_shared<ZmqEventSource>
              (connection.socket(),
               std::bind(&RestProxy::handleZmqResponse,
                         this,
                         std::placeholders::_1)));
}

void
RestProxy::
initServiceClass(std::shared_ptr<ConfigurationService> config,
                 const std::string & serviceClass,
                 const std::string & serviceEndpoint)
{
    connection.init(config, ZMQ_XREQ);
    connection.connectToServiceClass(serviceClass, serviceEndpoint);

    addSource("RestProxy::operationQueue", operationQueue);

    // What to do when we get something back from zeromq?
    addSource("RestProxy::handleZmqResponse",
              std::make_shared<ZmqEventSource>
              (connection.socket(),
               std::bind(&RestProxy::handleZmqResponse,
                         this,
                         std::placeholders::_1)));
}

void
RestProxy::
push(const RestRequest & request, const OnDone & onDone)
{
    Operation op;
    op.request = request;
    op.onDone = onDone;
    if (operationQueue.tryPush(std::move(op)))
        ML::atomic_inc(numMessagesOutstanding_);
    else
        throw ML::Exception("queue is full");
}

void
RestProxy::
push(const OnDone & onDone,
     const std::string & method,
     const std::string & resource,
     const RestParams & params,
     const std::string & payload)
{
    RestRequest request(method, resource, params, payload);
    push(request, onDone);
}

void
RestProxy::
handleOperation(const Operation & op)
{
    // Gets called when someone calls our API to make something happen;
    // this is run by the main worker thread to actually do the work.
    // It forwards the request off to the master banker.
    uint64_t opId = 0;
    if (op.onDone)
        opId = currentOpId++;

    //cerr << "sending with payload " << op.request.payload
    //     << " and response id " << opId << endl;

    if (trySendMessage(connection.socket(),
                       std::to_string(opId),
                       op.request.verb,
                       op.request.resource,
                       op.request.params.toBinary(),
                       op.request.payload)) {
        if (opId)
            outstanding[opId] = op.onDone;
        else {
            int no = __sync_add_and_fetch(&numMessagesOutstanding_, -1);
            if (no == 0)
                futex_wake(numMessagesOutstanding_);
        }
    }
    else {
        if (op.onDone) {
            string exc_msg = ("connection to '" + serviceName_
                              + "' is unavailable");
            op.onDone(make_exception_ptr<ML::Exception>(exc_msg), 0, "");
        }
    }
}

void
RestProxy::
handleZmqResponse(const std::vector<std::string> & message)
{
    // Gets called when we get a response back from the master banker in
    // response to one of our calls.

    // We call the callback associated with this code.

    //cerr << "response is " << message << endl;

    uint64_t opId = boost::lexical_cast<uint64_t>(message.at(0));
    int responseCode = boost::lexical_cast<int>(message.at(1));
    std::string body = message.at(2);

    ExcAssert(opId);

    auto it = outstanding.find(opId);
    if (it == outstanding.end()) {
        cerr << "unknown op ID " << endl;
        return;
    }
    try {
        if (responseCode >= 200 && responseCode < 300)
            it->second(nullptr, responseCode, body);
        else
            it->second(std::make_exception_ptr(ML::Exception(body)),
                       responseCode, "");
    } catch (const std::exception & exc) {
        cerr << "warning: exception handling banker result: "
             << exc.what() << endl;
    } catch (...) {
        cerr << "warning: unknown exception handling banker result"
             << endl;
    }

    outstanding.erase(it);

    ML::atomic_dec(numMessagesOutstanding_);
}

} // namespace Datacratic
<commit_msg>numMessagesOutstanding_ must be decreased whenever a send operation fails<commit_after>/* rest_proxy.cc
   Jeremy Barnes, 14 November 2012
   Copyright (c) 2012 Datacratic Inc.  All rights reserved.

*/

#include "rest_proxy.h"

using namespace std;
using namespace ML;

namespace Datacratic {

/*****************************************************************************/
/* REST PROXY                                                                */
/*****************************************************************************/

RestProxy::
RestProxy()
    : operationQueue(1024),
      numMessagesOutstanding_(0),
      currentOpId(1)
{
    // What to do when we get a new entry in the queue?
    operationQueue.onEvent = std::bind(&RestProxy::handleOperation,
                                       this, std::placeholders::_1);

}

RestProxy::
RestProxy(const std::shared_ptr<zmq::context_t> & context)
    : operationQueue(1024),
      connection(context),
      numMessagesOutstanding_(0),
      currentOpId(1)
{
    // What to do when we get a new entry in the queue?
    operationQueue.onEvent = std::bind(&RestProxy::handleOperation,
                                       this, std::placeholders::_1);

}

RestProxy::
~RestProxy()
{
    shutdown();
}

void
RestProxy::
sleepUntilIdle()
{
    for (;;) {
        int o = numMessagesOutstanding_;
        //cerr << "numMessagesOustanding = " << o << endl;
        if (!o)
            return;
        ML::futex_wait(numMessagesOutstanding_, o, 0.01);
    }
}

void
RestProxy::
shutdown()
{
    // Stop processing messages
    MessageLoop::shutdown();

    connection.shutdown();
}

void
RestProxy::
init(std::shared_ptr<ConfigurationService> config,
     const std::string & serviceName)
{
    serviceName_ = serviceName;

    connection.init(config, ZMQ_XREQ);
    connection.connect(serviceName + "/zeromq");

    addSource("RestProxy::operationQueue", operationQueue);

    // What to do when we get something back from zeromq?
    addSource("RestProxy::handleZmqResponse",
              std::make_shared<ZmqEventSource>
              (connection.socket(),
               std::bind(&RestProxy::handleZmqResponse,
                         this,
                         std::placeholders::_1)));
}

void
RestProxy::
initServiceClass(std::shared_ptr<ConfigurationService> config,
                 const std::string & serviceClass,
                 const std::string & serviceEndpoint)
{
    connection.init(config, ZMQ_XREQ);
    connection.connectToServiceClass(serviceClass, serviceEndpoint);

    addSource("RestProxy::operationQueue", operationQueue);

    // What to do when we get something back from zeromq?
    addSource("RestProxy::handleZmqResponse",
              std::make_shared<ZmqEventSource>
              (connection.socket(),
               std::bind(&RestProxy::handleZmqResponse,
                         this,
                         std::placeholders::_1)));
}

void
RestProxy::
push(const RestRequest & request, const OnDone & onDone)
{
    Operation op;
    op.request = request;
    op.onDone = onDone;
    if (operationQueue.tryPush(std::move(op)))
        ML::atomic_inc(numMessagesOutstanding_);
    else
        throw ML::Exception("queue is full");
}

void
RestProxy::
push(const OnDone & onDone,
     const std::string & method,
     const std::string & resource,
     const RestParams & params,
     const std::string & payload)
{
    RestRequest request(method, resource, params, payload);
    push(request, onDone);
}

void
RestProxy::
handleOperation(const Operation & op)
{
    // Gets called when someone calls our API to make something happen;
    // this is run by the main worker thread to actually do the work.
    // It forwards the request off to the master banker.
    uint64_t opId = 0;
    if (op.onDone)
        opId = currentOpId++;

    //cerr << "sending with payload " << op.request.payload
    //     << " and response id " << opId << endl;

    if (trySendMessage(connection.socket(),
                       std::to_string(opId),
                       op.request.verb,
                       op.request.resource,
                       op.request.params.toBinary(),
                       op.request.payload)) {
        if (opId)
            outstanding[opId] = op.onDone;
        else {
            int no = __sync_add_and_fetch(&numMessagesOutstanding_, -1);
            if (no == 0)
                futex_wake(numMessagesOutstanding_);
        }
    }
    else {
        if (op.onDone) {
            string exc_msg = ("connection to '" + serviceName_
                              + "' is unavailable");
            op.onDone(make_exception_ptr<ML::Exception>(exc_msg), 0, "");
        }
        int no = __sync_add_and_fetch(&numMessagesOutstanding_, -1);
        if (no == 0)
            futex_wake(numMessagesOutstanding_);
    }
}

void
RestProxy::
handleZmqResponse(const std::vector<std::string> & message)
{
    // Gets called when we get a response back from the master banker in
    // response to one of our calls.

    // We call the callback associated with this code.

    //cerr << "response is " << message << endl;

    uint64_t opId = boost::lexical_cast<uint64_t>(message.at(0));
    int responseCode = boost::lexical_cast<int>(message.at(1));
    std::string body = message.at(2);

    ExcAssert(opId);

    auto it = outstanding.find(opId);
    if (it == outstanding.end()) {
        cerr << "unknown op ID " << endl;
        return;
    }
    try {
        if (responseCode >= 200 && responseCode < 300)
            it->second(nullptr, responseCode, body);
        else
            it->second(std::make_exception_ptr(ML::Exception(body)),
                       responseCode, "");
    } catch (const std::exception & exc) {
        cerr << "warning: exception handling banker result: "
             << exc.what() << endl;
    } catch (...) {
        cerr << "warning: unknown exception handling banker result"
             << endl;
    }

    outstanding.erase(it);

    ML::atomic_dec(numMessagesOutstanding_);
}

} // namespace Datacratic
<|endoftext|>


<commit_before>/******************************************************************************
*
* Modified version for SYCL of Kevin Beason smallpt
* http://www.kevinbeason.com/smallpt/
*
******************************************************************************/

#define float_type float
#define sqrt_f cl::sycl::sqrt
#define modify_sample_rate 100
#include <smallpt.h>
#include <sycl_gtx.h>

using namespace cl;
using namespace sycl;

class RNG {
public:
	unsigned int x;
	const uint32_t fmask = (1 << 23) - 1;
	RNG(const unsigned int seed) { x = seed; }
	uint32_t next() {
		x ^= x >> 6;
		x ^= x << 17;
		x ^= x >> 9;
		return uint32_t(x);
	}
	float operator()(void) {
		union {
			float f;
			uint32_t i;
		} u;
		u.i = (next() & fmask) | 0x3f800000;
		return u.f - 1.f;
	}
};

const Sphere spheres_glob[] = {//Scene: radius, position, emission, color, material
	Sphere(1e4, Vec(1e4 + 1, 40.8, 81.6), Vec(), Vec(.75, .25, .25), DIFF),//Left
	Sphere(1e4, Vec(-1e4 + 99, 40.8, 81.6), Vec(), Vec(.25, .25, .75), DIFF),//Rght
	Sphere(1e4, Vec(50, 40.8, 1e4), Vec(), Vec(.75, .75, .75), DIFF),//Back
	Sphere(1e4, Vec(50, 40.8, -1e4 + 170), Vec(), Vec(), DIFF),//Frnt
	Sphere(1e4, Vec(50, 1e4, 81.6), Vec(), Vec(.75, .75, .75), DIFF),//Botm
	Sphere(1e4, Vec(50, -1e4 + 81.6, 81.6), Vec(), Vec(.75, .75, .75), DIFF),//Top
	Sphere(16.5, Vec(27, 16.5, 47), Vec(), Vec(1, 1, 1)*.999, SPEC),//Mirr
	Sphere(16.5, Vec(73, 16.5, 78), Vec(), Vec(1, 1, 1)*.999, REFR),//Glas
	Sphere(600, Vec(50, 681.6 - .27, 81.6), Vec(12, 12, 12), Vec(), DIFF) //Lite
};
inline int toInt(float x) {
	return int(sycl::pow(clamp(x), 1 / 2.2f) * 255 + .5f);
}

template<typename T>
inline bool intersect(const Ray &r, float &t, int &id,
	T spheres) {
	float d, inf = t = 1e20f;
	for(int i = 9; i--;)
		if((d = spheres[i].intersect(r)) && d < t) {
			t = d;
			id = i;
		}
	return t < inf;
}

template<typename T>
Vec radiance(const Ray &r_, int depth_, T spheres,
	RNG &rng) {
	float t;
	int id = 0;
	Ray r = r_;
	int depth = depth_;
	Vec cl(0, 0, 0); // accumulated color
	Vec cf(1, 1, 1); // accumulated reflectance
	while(1) {
		if(!intersect(r, t, id, spheres))
			return cl;                     // if miss, return black
		const Sphere &obj = spheres[id]; // the hit object
		Vec x = r.o + r.d * t, n = (x - obj.p).norm(),
			nl = n.dot(r.d) < 0 ? n : n * -1, f = obj.c;
		float p = f.x > f.y && f.x > f.z ? f.x : f.y > f.z ? f.y : f.z; // max refl
		cl = cl + cf.mult(obj.e);
		if(++depth > 5) {
			if(rng() < p) {
				f = f * (1 / p);
			}
			else {
				return cl;
			}
		} // R.R.
		cf = cf.mult(f);
		if(obj.refl == DIFF) { // Ideal DIFFUSE reflection
			float r1 = 2 * M_PI * rng(), r2 = rng(), r2s = sycl::sqrt(r2);
			Vec w = nl,
				u = ((sycl::fabs(w.x) > .1 ? Vec(0, 1) : Vec(1)) % w).norm(),
				v = w % u;
			Vec d = (u * sycl::cos(r1) * r2s + v * sycl::sin(r1) * r2s +
				w * sycl::sqrt(1 - r2)).norm();
			r = Ray(x, d);
			continue;
		}
		else if(obj.refl == SPEC) { // Ideal SPECULAR reflection
			r = Ray(x, r.d - n * 2 * n.dot(r.d));
			continue;
		}
		Ray reflRay(x, r.d - n * 2 * n.dot(r.d)); // Ideal dielectric REFRACTION
		bool into = n.dot(nl) > 0;                // Ray from outside going in?
		float nc = 1, nt = 1.5, nnt = into ? nc / nt : nt / nc, ddn = r.d.dot(nl),
			cos2t;
		if((cos2t = 1 - nnt * nnt * (1 - ddn * ddn)) <
			0) { // Total internal reflection
			r = reflRay;
			continue;
		}
		Vec tdir =
			(r.d * nnt -
			n * ((into ? 1 : -1) * (ddn * nnt + sycl::sqrt(cos2t)))).norm();
		float a = nt - nc, b = nt + nc, R0 = a * a / (b * b),
			c = 1 - (into ? -ddn : tdir.dot(n));
		float Re = R0 + (1 - R0) * c * c * c * c * c, Tr = 1 - Re,
			P = .25 + .5 * Re, RP = Re / P, TP = Tr / (1 - P);
		if(rng() < P) {
			cf = cf * RP;
			r = reflRay;
		}
		else {
			cf = cf * TP;
			r = Ray(x, tdir);
		}
		continue;
	}
}

// creating SYCL accessor types used by the command group.
typedef accessor<Vec, 1, access::mode::write, access::target::global_buffer>
vec_access;
typedef accessor<Sphere, 1, access::mode::read, access::target::constant_buffer>
spheres_access;

class kernel_r {
public:
	vec_access c;            // framebuffer
	spheres_access spheres_; // spheres
	int w, h, samps;

	Ray cam;
	Vec cx, cy, r;

	void operator()(item<2> item_) {
		const Sphere *spheres = &spheres_[0];
		const int x = item_[0];
		const int y = item_[1];
		RNG rng(1 + (y * w) + x); // initialise our own rng with rand() seed
		for(int sy = 0, i = (h - y - 1) * w + x; sy < 2; sy++) // 2x2 subpixel rows
			for(int sx = 0; sx < 2; sx++, r = Vec()) {           // 2x2 subpixel cols
				for(int s = 0; s < samps; s++) {
					float r1 = 2 * rng(), dx = r1 < 1 ? sycl::sqrt(r1) - 1
						: 1 - sycl::sqrt(2 - r1);
					float r2 = 2 * rng(), dy = r2 < 1 ? sycl::sqrt(r2) - 1
						: 1 - sycl::sqrt(2 - r2);
					Vec d = cx * (((sx + .5 + dx) / 2 + x) / w - .5) +
						cy * (((sy + .5 + dy) / 2 + y) / h - .5) + cam.d;
					r = r +
						radiance(Ray(cam.o + d * 140, d.norm()), 0, spheres, rng) *
						(1. / samps);
				} // Camera rays are pushed ^^^^^ forward to start in interior
				c[i] = c[i] + Vec(clamp(r.x), clamp(r.y), clamp(r.z)) * .25;
			}
	}
};

void compute_sycl(void* dev, int w, int h, int samps, Ray cam_, Vec cx_, Vec cy_, Vec r_, Vec* c) {
	queue q(*(device*)dev);
	{
		// data is wrapped in SYCL buffers.
		buffer<Vec, 1> color_buffer(c, range<1>(w * h));
		buffer<Sphere, 1> spheres_buffer(&spheres_glob[0], range<1>(9));
		auto cg = [&](handler &ch) {
			kernel_r ray_ = {
				// enabling access of the data on the device for SYCL.
				color_buffer.get_access<access::mode::write>(ch),
				spheres_buffer.get_access<access::mode::read,
				access::target::constant_buffer>(ch),
				w, h, samps,
				cam_, cx_, cy_, r_
			};
			nd_range<2> ndr(range<2>(w, h), range<2>(8, 8));
			ch.parallel_for(ndr, ray_);
		};
		// submitting the command group to the SYCL command queue for execution.
		q.submit(cg);
	}
}

int main(int argc, char** argv) {
	using namespace std;
	vector<testInfo> tests;

	// TODO: compute_sycl_gtx does not work with ComputeCpp yet
	getDevices(tests, { compute_sycl, /*compute_sycl_gtx*/ });

	return mainTester(argc, argv, tests, "ComputeCpp");
}
<commit_msg>smallpt-ccpp - host fallback<commit_after>/******************************************************************************
*
* Modified version for SYCL of Kevin Beason smallpt
* http://www.kevinbeason.com/smallpt/
*
******************************************************************************/

#define float_type float
#define sqrt_f cl::sycl::sqrt
#define modify_sample_rate 100
#include <smallpt.h>
#include <sycl_gtx.h>

using namespace cl;
using namespace sycl;

class RNG {
public:
	unsigned int x;
	const uint32_t fmask = (1 << 23) - 1;
	RNG(const unsigned int seed) { x = seed; }
	uint32_t next() {
		x ^= x >> 6;
		x ^= x << 17;
		x ^= x >> 9;
		return uint32_t(x);
	}
	float operator()(void) {
		union {
			float f;
			uint32_t i;
		} u;
		u.i = (next() & fmask) | 0x3f800000;
		return u.f - 1.f;
	}
};

const Sphere spheres_glob[] = {//Scene: radius, position, emission, color, material
	Sphere(1e4, Vec(1e4 + 1, 40.8, 81.6), Vec(), Vec(.75, .25, .25), DIFF),//Left
	Sphere(1e4, Vec(-1e4 + 99, 40.8, 81.6), Vec(), Vec(.25, .25, .75), DIFF),//Rght
	Sphere(1e4, Vec(50, 40.8, 1e4), Vec(), Vec(.75, .75, .75), DIFF),//Back
	Sphere(1e4, Vec(50, 40.8, -1e4 + 170), Vec(), Vec(), DIFF),//Frnt
	Sphere(1e4, Vec(50, 1e4, 81.6), Vec(), Vec(.75, .75, .75), DIFF),//Botm
	Sphere(1e4, Vec(50, -1e4 + 81.6, 81.6), Vec(), Vec(.75, .75, .75), DIFF),//Top
	Sphere(16.5, Vec(27, 16.5, 47), Vec(), Vec(1, 1, 1)*.999, SPEC),//Mirr
	Sphere(16.5, Vec(73, 16.5, 78), Vec(), Vec(1, 1, 1)*.999, REFR),//Glas
	Sphere(600, Vec(50, 681.6 - .27, 81.6), Vec(12, 12, 12), Vec(), DIFF) //Lite
};
inline int toInt(float x) {
	return int(sycl::pow(clamp(x), 1 / 2.2f) * 255 + .5f);
}

template<typename T>
inline bool intersect(const Ray &r, float &t, int &id,
	T spheres) {
	float d, inf = t = 1e20f;
	for(int i = 9; i--;)
		if((d = spheres[i].intersect(r)) && d < t) {
			t = d;
			id = i;
		}
	return t < inf;
}

template<typename T>
Vec radiance(const Ray &r_, int depth_, T spheres,
	RNG &rng) {
	float t;
	int id = 0;
	Ray r = r_;
	int depth = depth_;
	Vec cl(0, 0, 0); // accumulated color
	Vec cf(1, 1, 1); // accumulated reflectance
	while(1) {
		if(!intersect(r, t, id, spheres))
			return cl;                     // if miss, return black
		const Sphere &obj = spheres[id]; // the hit object
		Vec x = r.o + r.d * t, n = (x - obj.p).norm(),
			nl = n.dot(r.d) < 0 ? n : n * -1, f = obj.c;
		float p = f.x > f.y && f.x > f.z ? f.x : f.y > f.z ? f.y : f.z; // max refl
		cl = cl + cf.mult(obj.e);
		if(++depth > 5) {
			if(rng() < p) {
				f = f * (1 / p);
			}
			else {
				return cl;
			}
		} // R.R.
		cf = cf.mult(f);
		if(obj.refl == DIFF) { // Ideal DIFFUSE reflection
			float r1 = 2 * M_PI * rng(), r2 = rng(), r2s = sycl::sqrt(r2);
			Vec w = nl,
				u = ((sycl::fabs(w.x) > .1 ? Vec(0, 1) : Vec(1)) % w).norm(),
				v = w % u;
			Vec d = (u * sycl::cos(r1) * r2s + v * sycl::sin(r1) * r2s +
				w * sycl::sqrt(1 - r2)).norm();
			r = Ray(x, d);
			continue;
		}
		else if(obj.refl == SPEC) { // Ideal SPECULAR reflection
			r = Ray(x, r.d - n * 2 * n.dot(r.d));
			continue;
		}
		Ray reflRay(x, r.d - n * 2 * n.dot(r.d)); // Ideal dielectric REFRACTION
		bool into = n.dot(nl) > 0;                // Ray from outside going in?
		float nc = 1, nt = 1.5, nnt = into ? nc / nt : nt / nc, ddn = r.d.dot(nl),
			cos2t;
		if((cos2t = 1 - nnt * nnt * (1 - ddn * ddn)) <
			0) { // Total internal reflection
			r = reflRay;
			continue;
		}
		Vec tdir =
			(r.d * nnt -
			n * ((into ? 1 : -1) * (ddn * nnt + sycl::sqrt(cos2t)))).norm();
		float a = nt - nc, b = nt + nc, R0 = a * a / (b * b),
			c = 1 - (into ? -ddn : tdir.dot(n));
		float Re = R0 + (1 - R0) * c * c * c * c * c, Tr = 1 - Re,
			P = .25 + .5 * Re, RP = Re / P, TP = Tr / (1 - P);
		if(rng() < P) {
			cf = cf * RP;
			r = reflRay;
		}
		else {
			cf = cf * TP;
			r = Ray(x, tdir);
		}
		continue;
	}
}

// creating SYCL accessor types used by the command group.
typedef accessor<Vec, 1, access::mode::write, access::target::global_buffer>
vec_access;
typedef accessor<Sphere, 1, access::mode::read, access::target::constant_buffer>
spheres_access;

class kernel_r {
public:
	vec_access c;            // framebuffer
	spheres_access spheres_; // spheres
	int w, h, samps;

	Ray cam;
	Vec cx, cy, r;

	void operator()(item<2> item_) {
		const Sphere *spheres = &spheres_[0];
		const int x = item_[0];
		const int y = item_[1];
		RNG rng(1 + (y * w) + x); // initialise our own rng with rand() seed
		for(int sy = 0, i = (h - y - 1) * w + x; sy < 2; sy++) // 2x2 subpixel rows
			for(int sx = 0; sx < 2; sx++, r = Vec()) {           // 2x2 subpixel cols
				for(int s = 0; s < samps; s++) {
					float r1 = 2 * rng(), dx = r1 < 1 ? sycl::sqrt(r1) - 1
						: 1 - sycl::sqrt(2 - r1);
					float r2 = 2 * rng(), dy = r2 < 1 ? sycl::sqrt(r2) - 1
						: 1 - sycl::sqrt(2 - r2);
					Vec d = cx * (((sx + .5 + dx) / 2 + x) / w - .5) +
						cy * (((sy + .5 + dy) / 2 + y) / h - .5) + cam.d;
					r = r +
						radiance(Ray(cam.o + d * 140, d.norm()), 0, spheres, rng) *
						(1. / samps);
				} // Camera rays are pushed ^^^^^ forward to start in interior
				c[i] = c[i] + Vec(clamp(r.x), clamp(r.y), clamp(r.z)) * .25;
			}
	}
};

void compute_sycl(void* dev, int w, int h, int samps, Ray cam_, Vec cx_, Vec cy_, Vec r_, Vec* c) {
	queue q(*(device*)dev);
	{
		// data is wrapped in SYCL buffers.
		buffer<Vec, 1> color_buffer(c, range<1>(w * h));
		buffer<Sphere, 1> spheres_buffer(&spheres_glob[0], range<1>(9));
		auto cg = [&](handler &ch) {
			kernel_r ray_ = {
				// enabling access of the data on the device for SYCL.
				color_buffer.get_access<access::mode::write>(ch),
				spheres_buffer.get_access<access::mode::read,
				access::target::constant_buffer>(ch),
				w, h, samps,
				cam_, cx_, cy_, r_
			};
			nd_range<2> ndr(range<2>(w, h), range<2>(8, 8));
			ch.parallel_for(ndr, ray_);
		};
		// submitting the command group to the SYCL command queue for execution.
		q.submit(cg);
	}
}

int main(int argc, char** argv) {
	using namespace std;
	vector<testInfo> tests;

	// Host fallback
	host_selector hs;
	tests.emplace_back(string("T0") + ' ' + "ComputeCpp", compute_sycl, std::shared_ptr<device>(new device(hs)));
	string fakeName;
	version deviceVersion("");
	displayDevice(*tests.back().dev, -1, fakeName, deviceVersion, 1);

	// TODO: compute_sycl_gtx does not work with ComputeCpp yet
	getDevices(tests, { compute_sycl, /*compute_sycl_gtx*/ });

	return mainTester(argc, argv, tests, "ComputeCpp");
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include "TrelScript.h"
#include "Script.h"

TrelScript::TrelScript()
{
	m_filepath	= "{{use default}}";
	setInfo();
}

TrelScript::TrelScript(std::string a_filepath)
{
	m_filepath	= a_filepath;
	setInfo();
}

TrelScript::~TrelScript()
{
	std::cout << "Execution complete.\n";
}

void TrelScript::setInfo()
{
	m_name		= "Trel Script";
	m_version	= "0.3.1";
}

void TrelScript::runScript()
{
	std::cout << "~~ " + m_name + " v" + m_version + " ~~" << std::endl;

	Script *thisScript	= new Script(m_filepath);
	thisScript->executeScript();
}<commit_msg>update version<commit_after>#include <iostream>
#include <string>
#include "TrelScript.h"
#include "Script.h"

TrelScript::TrelScript()
{
	m_filepath	= "{{use default}}";
	setInfo();
}

TrelScript::TrelScript(std::string a_filepath)
{
	m_filepath	= a_filepath;
	setInfo();
}

TrelScript::~TrelScript()
{
	std::cout << "Execution complete.\n";
}

void TrelScript::setInfo()
{
	m_name		= "Trel Script";
	m_version	= "0.3.3";
}

void TrelScript::runScript()
{
	std::cout << "~~ " + m_name + " v" + m_version + " ~~" << std::endl;

	Script *thisScript	= new Script(m_filepath);
	thisScript->executeScript();
}<|endoftext|>


<commit_before>/*******************************************************************************
GPU OPTIMIZED MONTE CARLO (GOMC) 2.1
Copyright (C) 2016  GOMC Group
A copy of the GNU General Public License can be found in the COPYRIGHT.txt
along with this program, also can be found at <http://www.gnu.org/licenses/>.
********************************************************************************/
#include "BoxDimensions.h"
#include "MoveConst.h" //For cutoff-related fail condition

void BoxDimensions::Init(config_setup::RestartSettings const& restart,
                         config_setup::Volume const& confVolume,
                         pdb_setup::Cryst1 const& cryst,
                         double rc, double rcSq)
{
  const double TENTH_ANGSTROM = 0.1;
  rCut = rc;
  rCutSq = rcSq;
  minBoxSize = rc * rcSq * 8 + TENTH_ANGSTROM;
  if (restart.enable && cryst.hasVolume)
    axis = cryst.axis;
  else if (confVolume.hasVolume)
    axis = confVolume.axis;
  else
  {
    fprintf(stderr,
            "Error: Box Volume(s) not specified in PDB or in.dat files.\n");
    exit(EXIT_FAILURE);
  }
  halfAx.Init(BOX_TOTAL);
  axis.CopyRange(halfAx, 0, 0, BOX_TOTAL);
  halfAx.ScaleRange(0, BOX_TOTAL, 0.5);
  //Init volume/inverse volume.
  for (uint b = 0; b < BOX_TOTAL; b++)
  {
    volume[b] = axis.x[b] * axis.y[b] * axis.z[b];
    volInv[b] = 1.0 / volume[b];
    //check to see if initial box size is cubic or not
    cubic[b] = ((axis.x[b] == axis.y[b]) && (axis.y[b] == axis.z[b]));
  }
  constArea = confVolume.cstArea;
}

uint BoxDimensions::ShiftVolume
(BoxDimensions & newDim, XYZ & scale, const uint b, const double delta) const
{
  uint rejectState = mv::fail_state::NO_FAIL;
  double newVolume = volume[b] + delta;

  newDim.SetVolume(b, newVolume);

  //If move would shrink any box axis to be less than 2 * rcut, then
  //automatically reject to prevent errors.
  if ((newDim.axis.x[b] < rCut || newDim.axis.y[b] < rCut || newDim.axis.z[b] < rCut))
  {
    std::cout << "WARNING!!! box shrunk below 2*rc! Auto-rejecting!"
	      << std::endl;
    rejectState = mv::fail_state::VOL_TRANS_WOULD_SHRINK_BOX_BELOW_CUTOFF;
  }
  scale = newDim.axis.Get(b) / axis.Get(b);

  return rejectState;
}

uint BoxDimensions::ExchangeVolume
(BoxDimensions & newDim, XYZ * scale, const double transfer) const
{
  uint state = mv::fail_state::NO_FAIL;
  double vTot = volume[0] + volume[1];
  newDim = *this;

  newDim.SetVolume(0, volume[0] + transfer);
  newDim.SetVolume(1, vTot - newDim.volume[0]);

  //If move would shrink any box axis to be less than 2 * rcut, then
  //automatically reject to prevent errors.
  for (uint b = 0; b < BOX_TOTAL && state == mv::fail_state::NO_FAIL; b++)
  {
    scale[b] = newDim.axis.Get(b) / axis.Get(b);
    if ((newDim.axis.x[b] < rCut || newDim.axis.y[b] < rCut || newDim.axis.z[b] < rCut))
    {
      std::cout << "WARNING!!! box shrunk below 2*rc! Auto-rejecting!"
	      << std::endl;
      state = state && mv::fail_state::VOL_TRANS_WOULD_SHRINK_BOX_BELOW_CUTOFF;
    }
  }
  return state;
}
<commit_msg>Fix to volume move to reject any move that decrease the box size below 2Rc<commit_after>/*******************************************************************************
GPU OPTIMIZED MONTE CARLO (GOMC) 2.1
Copyright (C) 2016  GOMC Group
A copy of the GNU General Public License can be found in the COPYRIGHT.txt
along with this program, also can be found at <http://www.gnu.org/licenses/>.
********************************************************************************/
#include "BoxDimensions.h"
#include "MoveConst.h" //For cutoff-related fail condition

void BoxDimensions::Init(config_setup::RestartSettings const& restart,
                         config_setup::Volume const& confVolume,
                         pdb_setup::Cryst1 const& cryst,
                         double rc, double rcSq)
{
  const double TENTH_ANGSTROM = 0.1;
  rCut = rc;
  rCutSq = rcSq;
  minBoxSize = rc * rcSq * 8 + TENTH_ANGSTROM;
  if (restart.enable && cryst.hasVolume)
    axis = cryst.axis;
  else if (confVolume.hasVolume)
    axis = confVolume.axis;
  else
  {
    fprintf(stderr,
            "Error: Box Volume(s) not specified in PDB or in.dat files.\n");
    exit(EXIT_FAILURE);
  }
  halfAx.Init(BOX_TOTAL);
  axis.CopyRange(halfAx, 0, 0, BOX_TOTAL);
  halfAx.ScaleRange(0, BOX_TOTAL, 0.5);
  //Init volume/inverse volume.
  for (uint b = 0; b < BOX_TOTAL; b++)
  {
    volume[b] = axis.x[b] * axis.y[b] * axis.z[b];
    volInv[b] = 1.0 / volume[b];
    //check to see if initial box size is cubic or not
    cubic[b] = ((axis.x[b] == axis.y[b]) && (axis.y[b] == axis.z[b]));
  }
  constArea = confVolume.cstArea;
}

uint BoxDimensions::ShiftVolume
(BoxDimensions & newDim, XYZ & scale, const uint b, const double delta) const
{
  uint rejectState = mv::fail_state::NO_FAIL;
  double newVolume = volume[b] + delta;

  newDim.SetVolume(b, newVolume);

  //If move would shrink any box axis to be less than 2 * rcut, then
  //automatically reject to prevent errors.
  if ((newDim.axis.x[b] < rCut || newDim.axis.y[b] < rCut || newDim.axis.z[b] < rCut))
  {
    std::cout << "WARNING!!! box shrunk below 2*rc! Auto-rejecting!"
	      << std::endl;
    rejectState = mv::fail_state::VOL_TRANS_WOULD_SHRINK_BOX_BELOW_CUTOFF;
  }
  scale = newDim.axis.Get(b) / axis.Get(b);

  return rejectState;
}

uint BoxDimensions::ExchangeVolume
(BoxDimensions & newDim, XYZ * scale, const double transfer) const
{
  uint state = mv::fail_state::NO_FAIL;
  double vTot = volume[0] + volume[1];
  newDim = *this;

  newDim.SetVolume(0, volume[0] + transfer);
  newDim.SetVolume(1, vTot - newDim.volume[0]);

  //If move would shrink any box axis to be less than 2 * rcut, then
  //automatically reject to prevent errors.
  for (uint b = 0; b < BOX_TOTAL && state == mv::fail_state::NO_FAIL; b++)
  {
    scale[b] = newDim.axis.Get(b) / axis.Get(b);
    if ((newDim.halfAx.x[b] < rCut || newDim.halfAx.y[b] < rCut ||
	 newDim.halfAx.z[b] < rCut))
    {
      std::cout << "WARNING!!! box shrunk below 2*Rcut! Auto-rejecting!"
	      << std::endl;
      state = state && mv::fail_state::VOL_TRANS_WOULD_SHRINK_BOX_BELOW_CUTOFF;
    }
  }
  return state;
}
<|endoftext|>


<commit_before>#include <boost/thread.hpp>
#include <boost/chrono.hpp>
#include <C5G/C5G.h>

namespace C5G{
  void C5G::moveCartesian(const Pose& p){
    std::cout << "Relative movement to (" << p.x << ", " << p.y << ", " << p.z << ")\nOrientation: (" << p.alpha << ", " << p.beta << ", " << p.gamma << "\n";
  }

  const Pose C5G::safePose={0.3, 0, 0.7, 0, 0, 0};
  void C5G::moveCartesianGlobal(const Pose& p){
    std::cout << "Global movement to (" << p.x << ", " << p.y << ", " << p.z << ")\nOrientation: (" << p.alpha << ", " << p.beta << ", " << p.gamma << "\n";
  }

  void C5G::init(){
    std::cout << "Initing the system..\n";
    boost::this_thread::sleep_for(boost::chrono::seconds(3));
    std::cout << "Done.\n";
  }

  void C5G::standby(){
    std::cout << "Goodbye, cruel world..\n";
    boost::this_thread::sleep_for(boost::chrono::seconds(1));
    std::cout << "I'm leaving you today..\n";
    boost::this_thread::sleep_for(boost::chrono::seconds(1));
    std::cout << "Goodbye..\n";
    boost::this_thread::sleep_for(boost::chrono::seconds(1));
    std::cout << "Goodbye..\n";
    boost::this_thread::sleep_for(boost::chrono::seconds(1));
    std::cout << "Goodbye.\n";
  }
}
<commit_msg>Add times to C5G_dummy :)<commit_after>#include <boost/thread.hpp>
#include <boost/chrono.hpp>
#include <C5G/C5G.h>

namespace C5G{
  void C5G::moveCartesian(const Pose& p){
    std::cout << "Relative movement to (" << p.x << ", " << p.y << ", " << p.z << ")\nOrientation: (" << p.alpha << ", " << p.beta << ", " << p.gamma << "\n";
    boost::this_thread::sleep_for(boost::chrono::seconds(1));
  }

  const Pose C5G::safePose={0.3, 0, 0.7, 0, 0, 0};
  void C5G::moveCartesianGlobal(const Pose& p){
    std::cout << "Global movement to (" << p.x << ", " << p.y << ", " << p.z << ")\nOrientation: (" << p.alpha << ", " << p.beta << ", " << p.gamma << "\n";
    boost::this_thread::sleep_for(boost::chrono::seconds(1));
  }

  void C5G::init(){
    std::cout << "Initing the system..\n";
    boost::this_thread::sleep_for(boost::chrono::seconds(3));
    std::cout << "Done.\n";
  }

  void C5G::standby(){
    std::cout << "Goodbye, cruel world..\n";
    boost::this_thread::sleep_for(boost::chrono::seconds(1));
    std::cout << "I'm leaving you today..\n";
    boost::this_thread::sleep_for(boost::chrono::seconds(1));
    std::cout << "Goodbye..\n";
    boost::this_thread::sleep_for(boost::chrono::seconds(1));
    std::cout << "Goodbye..\n";
    boost::this_thread::sleep_for(boost::chrono::seconds(1));
    std::cout << "Goodbye.\n";
  }
}
<|endoftext|>