<commit_before>#include "Others.pp.hpp"
#include <algorithm>
#include <prophy/detail/encoder.hpp>
#include <prophy/detail/decoder.hpp>
#include <prophy/detail/printer.hpp>
#include <prophy/detail/align.hpp>

namespace prophy
{
namespace detail
{

template <>
struct print_traits<Enum>
{
    static const char* to_literal(Enum x)
    {
        switch(x)
        {
            case Enum_One: return "Enum_One";
            case Enum_Two: return "Enum_Two";
            default: return 0;
        }
    }
};

template <>
template <endianness E>
uint8_t* message_impl<ConstantTypedefEnum>::encode(const ConstantTypedefEnum& x, uint8_t* pos)
{
    pos = do_encode<E>(pos, x.a, 3);
    pos = do_encode<E>(pos, x.b);
    pos = do_encode<E>(pos, x.c);
    return pos;
}
template uint8_t* message_impl<ConstantTypedefEnum>::encode<native>(const ConstantTypedefEnum& x, uint8_t* pos);
template uint8_t* message_impl<ConstantTypedefEnum>::encode<little>(const ConstantTypedefEnum& x, uint8_t* pos);
template uint8_t* message_impl<ConstantTypedefEnum>::encode<big>(const ConstantTypedefEnum& x, uint8_t* pos);

template <>
template <endianness E>
bool message_impl<ConstantTypedefEnum>::decode(ConstantTypedefEnum& x, const uint8_t*& pos, const uint8_t* end)
{
    return (
        do_decode<E>(x.a, 3, pos, end) &&
        do_decode<E>(x.b, pos, end) &&
        do_decode<E>(x.c, pos, end)
    );
}
template bool message_impl<ConstantTypedefEnum>::decode<native>(ConstantTypedefEnum& x, const uint8_t*& pos, const uint8_t* end);
template bool message_impl<ConstantTypedefEnum>::decode<little>(ConstantTypedefEnum& x, const uint8_t*& pos, const uint8_t* end);
template bool message_impl<ConstantTypedefEnum>::decode<big>(ConstantTypedefEnum& x, const uint8_t*& pos, const uint8_t* end);

template <>
void message_impl<ConstantTypedefEnum>::print(const ConstantTypedefEnum& x, std::ostream& out, size_t indent)
{
    do_print(out, indent, "a", x.a, 3);
    do_print(out, indent, "b", x.b);
    do_print(out, indent, "c", x.c);
}
template void message_impl<ConstantTypedefEnum>::print(const ConstantTypedefEnum& x, std::ostream& out, size_t indent);

template <>
template <endianness E>
uint8_t* message_impl<DynEnum>::encode(const DynEnum& x, uint8_t* pos)
{
    pos = do_encode<E>(pos, uint32_t(x.x.size()));
    pos = do_encode<E>(pos, x.x.data(), x.x.size());
    return pos;
}
template uint8_t* message_impl<DynEnum>::encode<native>(const DynEnum& x, uint8_t* pos);
template uint8_t* message_impl<DynEnum>::encode<little>(const DynEnum& x, uint8_t* pos);
template uint8_t* message_impl<DynEnum>::encode<big>(const DynEnum& x, uint8_t* pos);

template <>
template <endianness E>
bool message_impl<DynEnum>::decode(DynEnum& x, const uint8_t*& pos, const uint8_t* end)
{
    return (
        do_decode_resize<E, uint32_t>(x.x, pos, end) &&
        do_decode<E>(x.x.data(), x.x.size(), pos, end)
    );
}
template bool message_impl<DynEnum>::decode<native>(DynEnum& x, const uint8_t*& pos, const uint8_t* end);
template bool message_impl<DynEnum>::decode<little>(DynEnum& x, const uint8_t*& pos, const uint8_t* end);
template bool message_impl<DynEnum>::decode<big>(DynEnum& x, const uint8_t*& pos, const uint8_t* end);

template <>
void message_impl<DynEnum>::print(const DynEnum& x, std::ostream& out, size_t indent)
{
    do_print(out, indent, "x", x.x.data(), x.x.size());
}
template void message_impl<DynEnum>::print(const DynEnum& x, std::ostream& out, size_t indent);

template <>
template <endianness E>
uint8_t* message_impl<Floats>::encode(const Floats& x, uint8_t* pos)
{
    pos = do_encode<E>(pos, x.a);
    pos = pos + 4;
    pos = do_encode<E>(pos, x.b);
    return pos;
}
template uint8_t* message_impl<Floats>::encode<native>(const Floats& x, uint8_t* pos);
template uint8_t* message_impl<Floats>::encode<little>(const Floats& x, uint8_t* pos);
template uint8_t* message_impl<Floats>::encode<big>(const Floats& x, uint8_t* pos);

template <>
template <endianness E>
bool message_impl<Floats>::decode(Floats& x, const uint8_t*& pos, const uint8_t* end)
{
    return (
        do_decode<E>(x.a, pos, end) &&
        do_decode_advance(4, pos, end) &&
        do_decode<E>(x.b, pos, end)
    );
}
template bool message_impl<Floats>::decode<native>(Floats& x, const uint8_t*& pos, const uint8_t* end);
template bool message_impl<Floats>::decode<little>(Floats& x, const uint8_t*& pos, const uint8_t* end);
template bool message_impl<Floats>::decode<big>(Floats& x, const uint8_t*& pos, const uint8_t* end);

template <>
template <endianness E>
uint8_t* message_impl<BytesFixed>::encode(const BytesFixed& x, uint8_t* pos)
{
    pos = do_encode<E>(pos, x.x, 3);
    return pos;
}
template uint8_t* message_impl<BytesFixed>::encode<native>(const BytesFixed& x, uint8_t* pos);
template uint8_t* message_impl<BytesFixed>::encode<little>(const BytesFixed& x, uint8_t* pos);
template uint8_t* message_impl<BytesFixed>::encode<big>(const BytesFixed& x, uint8_t* pos);

template <>
template <endianness E>
bool message_impl<BytesFixed>::decode(BytesFixed& x, const uint8_t*& pos, const uint8_t* end)
{
    return (
        do_decode<E>(x.x, 3, pos, end)
    );
}
template bool message_impl<BytesFixed>::decode<native>(BytesFixed& x, const uint8_t*& pos, const uint8_t* end);
template bool message_impl<BytesFixed>::decode<little>(BytesFixed& x, const uint8_t*& pos, const uint8_t* end);
template bool message_impl<BytesFixed>::decode<big>(BytesFixed& x, const uint8_t*& pos, const uint8_t* end);

template <>
template <endianness E>
uint8_t* message_impl<BytesDynamic>::encode(const BytesDynamic& x, uint8_t* pos)
{
    pos = do_encode<E>(pos, uint32_t(x.x.size()));
    pos = do_encode<E>(pos, x.x.data(), uint32_t(x.x.size()));
    pos = align<4>(pos);
    return pos;
}
template uint8_t* message_impl<BytesDynamic>::encode<native>(const BytesDynamic& x, uint8_t* pos);
template uint8_t* message_impl<BytesDynamic>::encode<little>(const BytesDynamic& x, uint8_t* pos);
template uint8_t* message_impl<BytesDynamic>::encode<big>(const BytesDynamic& x, uint8_t* pos);

template <>
template <endianness E>
bool message_impl<BytesDynamic>::decode(BytesDynamic& x, const uint8_t*& pos, const uint8_t* end)
{
    return (
        do_decode_resize<E, uint32_t>(x.x, pos, end) &&
        do_decode<E>(x.x.data(), x.x.size(), pos, end) &&
        do_decode_align<4>(pos, end)
    );
}
template bool message_impl<BytesDynamic>::decode<native>(BytesDynamic& x, const uint8_t*& pos, const uint8_t* end);
template bool message_impl<BytesDynamic>::decode<little>(BytesDynamic& x, const uint8_t*& pos, const uint8_t* end);
template bool message_impl<BytesDynamic>::decode<big>(BytesDynamic& x, const uint8_t*& pos, const uint8_t* end);

template <>
template <endianness E>
uint8_t* message_impl<BytesLimited>::encode(const BytesLimited& x, uint8_t* pos)
{
    pos = do_encode<E>(pos, uint32_t(std::min(x.x.size(), size_t(4))));
    do_encode<E>(pos, x.x.data(), std::min(x.x.size(), size_t(4)));
    pos = pos + 4;
    return pos;
}
template uint8_t* message_impl<BytesLimited>::encode<native>(const BytesLimited& x, uint8_t* pos);
template uint8_t* message_impl<BytesLimited>::encode<little>(const BytesLimited& x, uint8_t* pos);
template uint8_t* message_impl<BytesLimited>::encode<big>(const BytesLimited& x, uint8_t* pos);

template <>
template <endianness E>
bool message_impl<BytesLimited>::decode(BytesLimited& x, const uint8_t*& pos, const uint8_t* end)
{
    return (
        do_decode_resize<E, uint32_t>(x.x, pos, end, 4) &&
        do_decode_in_place<E>(x.x.data(), x.x.size(), pos, end) &&
        do_decode_advance(4, pos, end)
    );
}
template bool message_impl<BytesLimited>::decode<native>(BytesLimited& x, const uint8_t*& pos, const uint8_t* end);
template bool message_impl<BytesLimited>::decode<little>(BytesLimited& x, const uint8_t*& pos, const uint8_t* end);
template bool message_impl<BytesLimited>::decode<big>(BytesLimited& x, const uint8_t*& pos, const uint8_t* end);

template <>
template <endianness E>
uint8_t* message_impl<BytesGreedy>::encode(const BytesGreedy& x, uint8_t* pos)
{
    pos = do_encode<E>(pos, x.x.data(), x.x.size());
    return pos;
}
template uint8_t* message_impl<BytesGreedy>::encode<native>(const BytesGreedy& x, uint8_t* pos);
template uint8_t* message_impl<BytesGreedy>::encode<little>(const BytesGreedy& x, uint8_t* pos);
template uint8_t* message_impl<BytesGreedy>::encode<big>(const BytesGreedy& x, uint8_t* pos);

template <>
template <endianness E>
bool message_impl<BytesGreedy>::decode(BytesGreedy& x, const uint8_t*& pos, const uint8_t* end)
{
    return (
        do_decode_greedy<E>(x.x, pos, end)
    );
}
template bool message_impl<BytesGreedy>::decode<native>(BytesGreedy& x, const uint8_t*& pos, const uint8_t* end);
template bool message_impl<BytesGreedy>::decode<little>(BytesGreedy& x, const uint8_t*& pos, const uint8_t* end);
template bool message_impl<BytesGreedy>::decode<big>(BytesGreedy& x, const uint8_t*& pos, const uint8_t* end);

} // namespace detail
} // namespace prophy
<commit_msg>to_literal function defined with exteral linkage, not inlined<commit_after>#include "Others.pp.hpp"
#include <algorithm>
#include <prophy/detail/encoder.hpp>
#include <prophy/detail/decoder.hpp>
#include <prophy/detail/printer.hpp>
#include <prophy/detail/align.hpp>

namespace prophy
{
namespace detail
{

template <>
const char* print_traits<Enum>::to_literal(Enum x)
{
    switch(x)
    {
        case Enum_One: return "Enum_One";
        case Enum_Two: return "Enum_Two";
        default: return 0;
    }
}

template <>
template <endianness E>
uint8_t* message_impl<ConstantTypedefEnum>::encode(const ConstantTypedefEnum& x, uint8_t* pos)
{
    pos = do_encode<E>(pos, x.a, 3);
    pos = do_encode<E>(pos, x.b);
    pos = do_encode<E>(pos, x.c);
    return pos;
}
template uint8_t* message_impl<ConstantTypedefEnum>::encode<native>(const ConstantTypedefEnum& x, uint8_t* pos);
template uint8_t* message_impl<ConstantTypedefEnum>::encode<little>(const ConstantTypedefEnum& x, uint8_t* pos);
template uint8_t* message_impl<ConstantTypedefEnum>::encode<big>(const ConstantTypedefEnum& x, uint8_t* pos);

template <>
template <endianness E>
bool message_impl<ConstantTypedefEnum>::decode(ConstantTypedefEnum& x, const uint8_t*& pos, const uint8_t* end)
{
    return (
        do_decode<E>(x.a, 3, pos, end) &&
        do_decode<E>(x.b, pos, end) &&
        do_decode<E>(x.c, pos, end)
    );
}
template bool message_impl<ConstantTypedefEnum>::decode<native>(ConstantTypedefEnum& x, const uint8_t*& pos, const uint8_t* end);
template bool message_impl<ConstantTypedefEnum>::decode<little>(ConstantTypedefEnum& x, const uint8_t*& pos, const uint8_t* end);
template bool message_impl<ConstantTypedefEnum>::decode<big>(ConstantTypedefEnum& x, const uint8_t*& pos, const uint8_t* end);

template <>
void message_impl<ConstantTypedefEnum>::print(const ConstantTypedefEnum& x, std::ostream& out, size_t indent)
{
    do_print(out, indent, "a", x.a, 3);
    do_print(out, indent, "b", x.b);
    do_print(out, indent, "c", x.c);
}
template void message_impl<ConstantTypedefEnum>::print(const ConstantTypedefEnum& x, std::ostream& out, size_t indent);

template <>
template <endianness E>
uint8_t* message_impl<DynEnum>::encode(const DynEnum& x, uint8_t* pos)
{
    pos = do_encode<E>(pos, uint32_t(x.x.size()));
    pos = do_encode<E>(pos, x.x.data(), x.x.size());
    return pos;
}
template uint8_t* message_impl<DynEnum>::encode<native>(const DynEnum& x, uint8_t* pos);
template uint8_t* message_impl<DynEnum>::encode<little>(const DynEnum& x, uint8_t* pos);
template uint8_t* message_impl<DynEnum>::encode<big>(const DynEnum& x, uint8_t* pos);

template <>
template <endianness E>
bool message_impl<DynEnum>::decode(DynEnum& x, const uint8_t*& pos, const uint8_t* end)
{
    return (
        do_decode_resize<E, uint32_t>(x.x, pos, end) &&
        do_decode<E>(x.x.data(), x.x.size(), pos, end)
    );
}
template bool message_impl<DynEnum>::decode<native>(DynEnum& x, const uint8_t*& pos, const uint8_t* end);
template bool message_impl<DynEnum>::decode<little>(DynEnum& x, const uint8_t*& pos, const uint8_t* end);
template bool message_impl<DynEnum>::decode<big>(DynEnum& x, const uint8_t*& pos, const uint8_t* end);

template <>
void message_impl<DynEnum>::print(const DynEnum& x, std::ostream& out, size_t indent)
{
    do_print(out, indent, "x", x.x.data(), x.x.size());
}
template void message_impl<DynEnum>::print(const DynEnum& x, std::ostream& out, size_t indent);

template <>
template <endianness E>
uint8_t* message_impl<Floats>::encode(const Floats& x, uint8_t* pos)
{
    pos = do_encode<E>(pos, x.a);
    pos = pos + 4;
    pos = do_encode<E>(pos, x.b);
    return pos;
}
template uint8_t* message_impl<Floats>::encode<native>(const Floats& x, uint8_t* pos);
template uint8_t* message_impl<Floats>::encode<little>(const Floats& x, uint8_t* pos);
template uint8_t* message_impl<Floats>::encode<big>(const Floats& x, uint8_t* pos);

template <>
template <endianness E>
bool message_impl<Floats>::decode(Floats& x, const uint8_t*& pos, const uint8_t* end)
{
    return (
        do_decode<E>(x.a, pos, end) &&
        do_decode_advance(4, pos, end) &&
        do_decode<E>(x.b, pos, end)
    );
}
template bool message_impl<Floats>::decode<native>(Floats& x, const uint8_t*& pos, const uint8_t* end);
template bool message_impl<Floats>::decode<little>(Floats& x, const uint8_t*& pos, const uint8_t* end);
template bool message_impl<Floats>::decode<big>(Floats& x, const uint8_t*& pos, const uint8_t* end);

template <>
template <endianness E>
uint8_t* message_impl<BytesFixed>::encode(const BytesFixed& x, uint8_t* pos)
{
    pos = do_encode<E>(pos, x.x, 3);
    return pos;
}
template uint8_t* message_impl<BytesFixed>::encode<native>(const BytesFixed& x, uint8_t* pos);
template uint8_t* message_impl<BytesFixed>::encode<little>(const BytesFixed& x, uint8_t* pos);
template uint8_t* message_impl<BytesFixed>::encode<big>(const BytesFixed& x, uint8_t* pos);

template <>
template <endianness E>
bool message_impl<BytesFixed>::decode(BytesFixed& x, const uint8_t*& pos, const uint8_t* end)
{
    return (
        do_decode<E>(x.x, 3, pos, end)
    );
}
template bool message_impl<BytesFixed>::decode<native>(BytesFixed& x, const uint8_t*& pos, const uint8_t* end);
template bool message_impl<BytesFixed>::decode<little>(BytesFixed& x, const uint8_t*& pos, const uint8_t* end);
template bool message_impl<BytesFixed>::decode<big>(BytesFixed& x, const uint8_t*& pos, const uint8_t* end);

template <>
template <endianness E>
uint8_t* message_impl<BytesDynamic>::encode(const BytesDynamic& x, uint8_t* pos)
{
    pos = do_encode<E>(pos, uint32_t(x.x.size()));
    pos = do_encode<E>(pos, x.x.data(), uint32_t(x.x.size()));
    pos = align<4>(pos);
    return pos;
}
template uint8_t* message_impl<BytesDynamic>::encode<native>(const BytesDynamic& x, uint8_t* pos);
template uint8_t* message_impl<BytesDynamic>::encode<little>(const BytesDynamic& x, uint8_t* pos);
template uint8_t* message_impl<BytesDynamic>::encode<big>(const BytesDynamic& x, uint8_t* pos);

template <>
template <endianness E>
bool message_impl<BytesDynamic>::decode(BytesDynamic& x, const uint8_t*& pos, const uint8_t* end)
{
    return (
        do_decode_resize<E, uint32_t>(x.x, pos, end) &&
        do_decode<E>(x.x.data(), x.x.size(), pos, end) &&
        do_decode_align<4>(pos, end)
    );
}
template bool message_impl<BytesDynamic>::decode<native>(BytesDynamic& x, const uint8_t*& pos, const uint8_t* end);
template bool message_impl<BytesDynamic>::decode<little>(BytesDynamic& x, const uint8_t*& pos, const uint8_t* end);
template bool message_impl<BytesDynamic>::decode<big>(BytesDynamic& x, const uint8_t*& pos, const uint8_t* end);

template <>
template <endianness E>
uint8_t* message_impl<BytesLimited>::encode(const BytesLimited& x, uint8_t* pos)
{
    pos = do_encode<E>(pos, uint32_t(std::min(x.x.size(), size_t(4))));
    do_encode<E>(pos, x.x.data(), std::min(x.x.size(), size_t(4)));
    pos = pos + 4;
    return pos;
}
template uint8_t* message_impl<BytesLimited>::encode<native>(const BytesLimited& x, uint8_t* pos);
template uint8_t* message_impl<BytesLimited>::encode<little>(const BytesLimited& x, uint8_t* pos);
template uint8_t* message_impl<BytesLimited>::encode<big>(const BytesLimited& x, uint8_t* pos);

template <>
template <endianness E>
bool message_impl<BytesLimited>::decode(BytesLimited& x, const uint8_t*& pos, const uint8_t* end)
{
    return (
        do_decode_resize<E, uint32_t>(x.x, pos, end, 4) &&
        do_decode_in_place<E>(x.x.data(), x.x.size(), pos, end) &&
        do_decode_advance(4, pos, end)
    );
}
template bool message_impl<BytesLimited>::decode<native>(BytesLimited& x, const uint8_t*& pos, const uint8_t* end);
template bool message_impl<BytesLimited>::decode<little>(BytesLimited& x, const uint8_t*& pos, const uint8_t* end);
template bool message_impl<BytesLimited>::decode<big>(BytesLimited& x, const uint8_t*& pos, const uint8_t* end);

template <>
template <endianness E>
uint8_t* message_impl<BytesGreedy>::encode(const BytesGreedy& x, uint8_t* pos)
{
    pos = do_encode<E>(pos, x.x.data(), x.x.size());
    return pos;
}
template uint8_t* message_impl<BytesGreedy>::encode<native>(const BytesGreedy& x, uint8_t* pos);
template uint8_t* message_impl<BytesGreedy>::encode<little>(const BytesGreedy& x, uint8_t* pos);
template uint8_t* message_impl<BytesGreedy>::encode<big>(const BytesGreedy& x, uint8_t* pos);

template <>
template <endianness E>
bool message_impl<BytesGreedy>::decode(BytesGreedy& x, const uint8_t*& pos, const uint8_t* end)
{
    return (
        do_decode_greedy<E>(x.x, pos, end)
    );
}
template bool message_impl<BytesGreedy>::decode<native>(BytesGreedy& x, const uint8_t*& pos, const uint8_t* end);
template bool message_impl<BytesGreedy>::decode<little>(BytesGreedy& x, const uint8_t*& pos, const uint8_t* end);
template bool message_impl<BytesGreedy>::decode<big>(BytesGreedy& x, const uint8_t*& pos, const uint8_t* end);

} // namespace detail
} // namespace prophy
<|endoftext|>


<commit_before>#include "authdialog.h"

#include <qconnman/manager.h>
#include <qconnman/agent.h>

#include <QDebug>

AuthDialog::AuthDialog(Manager *manager, QWidget *parent):
    QDialog(parent),
    m_manager(manager)
{
    ui.setupUi(this);

    connect(ui.showPassword, SIGNAL(toggled(bool)), SLOT(showPassword(bool)));
}

int AuthDialog::exec()
{
    Agent *agent = qobject_cast<Agent *>(QObject::sender());
    Agent::InputRequest *request = agent->currentInputRequest();

    ui.label->setText(trUtf8("This network requires a %1 password to connect. Please enter the password bellow.")
                      .arg(m_manager->service(request->service)->security().join("").toUpper()));

    int result = QDialog::exec();
    if (result == QDialog::Accepted)
        request->response.passphrase = ui.password->text();
    else
        request->cancel = true;

    return result;
}

void AuthDialog::showPassword(bool checked)
{
    if (!checked)
        ui.password->setEchoMode(QLineEdit::Password);
    else
        ui.password->setEchoMode(QLineEdit::Normal);
}
<commit_msg>AuthDialog: Set focus on password field<commit_after>#include "authdialog.h"

#include <qconnman/manager.h>
#include <qconnman/agent.h>

#include <QDebug>

AuthDialog::AuthDialog(Manager *manager, QWidget *parent):
    QDialog(parent),
    m_manager(manager)
{
    ui.setupUi(this);

    connect(ui.showPassword, SIGNAL(toggled(bool)), SLOT(showPassword(bool)));
}

int AuthDialog::exec()
{
    Agent *agent = qobject_cast<Agent *>(QObject::sender());
    Agent::InputRequest *request = agent->currentInputRequest();

    ui.password->clear();
    ui.password->setFocus();
    ui.label->setText(trUtf8("This network requires a %1 password to connect. Please enter the password bellow.")
                      .arg(m_manager->service(request->service)->security().join("").toUpper()));

    int result = QDialog::exec();
    if (result == QDialog::Accepted)
        request->response.passphrase = ui.password->text();
    else
        request->cancel = true;

    return result;
}

void AuthDialog::showPassword(bool checked)
{
    if (!checked)
        ui.password->setEchoMode(QLineEdit::Password);
    else
        ui.password->setEchoMode(QLineEdit::Normal);
}
<|endoftext|>


<commit_before>// Copyright (c) 2011-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <qt/transactionfilterproxy.h>

#include <qt/transactiontablemodel.h>
#include <qt/transactionrecord.h>

#include <cstdlib>

// Earliest date that can be represented (far in the past)
const QDateTime TransactionFilterProxy::MIN_DATE = QDateTime::fromTime_t(0);
// Last date that can be represented (far in the future)
const QDateTime TransactionFilterProxy::MAX_DATE = QDateTime::fromTime_t(0xFFFFFFFF);

TransactionFilterProxy::TransactionFilterProxy(QObject *parent) :
    QSortFilterProxyModel(parent),
    dateFrom(MIN_DATE),
    dateTo(MAX_DATE),
    m_search_string(),
    typeFilter(ALL_TYPES),
    watchOnlyFilter(WatchOnlyFilter_All),
    minAmount(0),
    limitRows(-1),
    showInactive(true)
{
}

bool TransactionFilterProxy::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
    QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);

    int type = index.data(TransactionTableModel::TypeRole).toInt();
    QDateTime datetime = index.data(TransactionTableModel::DateRole).toDateTime();
    bool involvesWatchAddress = index.data(TransactionTableModel::WatchonlyRole).toBool();
    QString address = index.data(TransactionTableModel::AddressRole).toString();
    QString label = index.data(TransactionTableModel::LabelRole).toString();
    QString txid = index.data(TransactionTableModel::TxHashRole).toString();
    qint64 amount = llabs(index.data(TransactionTableModel::AmountRole).toLongLong());
    int status = index.data(TransactionTableModel::StatusRole).toInt();

    if(!showInactive && status == TransactionStatus::Conflicted)
        return false;
    if(!(TYPE(type) & typeFilter))
        return false;
    if (involvesWatchAddress && watchOnlyFilter == WatchOnlyFilter_No)
        return false;
    if (!involvesWatchAddress && watchOnlyFilter == WatchOnlyFilter_Yes)
        return false;
    if(datetime < dateFrom || datetime > dateTo)
        return false;
    if (!address.contains(m_search_string, Qt::CaseInsensitive) &&
        !  label.contains(m_search_string, Qt::CaseInsensitive) &&
        !   txid.contains(m_search_string, Qt::CaseInsensitive)) {
        return false;
    }
    if(amount < minAmount)
        return false;

    return true;
}

void TransactionFilterProxy::setDateRange(const QDateTime &from, const QDateTime &to)
{
    this->dateFrom = from;
    this->dateTo = to;
    invalidateFilter();
}

void TransactionFilterProxy::setSearchString(const QString &search_string)
{
    if (m_search_string == search_string) return;
    m_search_string = search_string;
    invalidateFilter();
}

void TransactionFilterProxy::setTypeFilter(quint32 modes)
{
    this->typeFilter = modes;
    invalidateFilter();
}

void TransactionFilterProxy::setMinAmount(const CAmount& minimum)
{
    this->minAmount = minimum;
    invalidateFilter();
}

void TransactionFilterProxy::setWatchOnlyFilter(WatchOnlyFilter filter)
{
    this->watchOnlyFilter = filter;
    invalidateFilter();
}

void TransactionFilterProxy::setLimit(int limit)
{
    this->limitRows = limit;
}

void TransactionFilterProxy::setShowInactive(bool _showInactive)
{
    this->showInactive = _showInactive;
    invalidateFilter();
}

int TransactionFilterProxy::rowCount(const QModelIndex &parent) const
{
    if(limitRows != -1)
    {
        return std::min(QSortFilterProxyModel::rowCount(parent), limitRows);
    }
    else
    {
        return QSortFilterProxyModel::rowCount(parent);
    }
}
<commit_msg>qt: Avoid querying unnecessary model data when filtering transactions<commit_after>// Copyright (c) 2011-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <qt/transactionfilterproxy.h>

#include <qt/transactiontablemodel.h>
#include <qt/transactionrecord.h>

#include <cstdlib>

// Earliest date that can be represented (far in the past)
const QDateTime TransactionFilterProxy::MIN_DATE = QDateTime::fromTime_t(0);
// Last date that can be represented (far in the future)
const QDateTime TransactionFilterProxy::MAX_DATE = QDateTime::fromTime_t(0xFFFFFFFF);

TransactionFilterProxy::TransactionFilterProxy(QObject *parent) :
    QSortFilterProxyModel(parent),
    dateFrom(MIN_DATE),
    dateTo(MAX_DATE),
    m_search_string(),
    typeFilter(ALL_TYPES),
    watchOnlyFilter(WatchOnlyFilter_All),
    minAmount(0),
    limitRows(-1),
    showInactive(true)
{
}

bool TransactionFilterProxy::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
    QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);

    int status = index.data(TransactionTableModel::StatusRole).toInt();
    if (!showInactive && status == TransactionStatus::Conflicted)
        return false;

    int type = index.data(TransactionTableModel::TypeRole).toInt();
    if (!(TYPE(type) & typeFilter))
        return false;

    bool involvesWatchAddress = index.data(TransactionTableModel::WatchonlyRole).toBool();
    if (involvesWatchAddress && watchOnlyFilter == WatchOnlyFilter_No)
        return false;
    if (!involvesWatchAddress && watchOnlyFilter == WatchOnlyFilter_Yes)
        return false;

    QDateTime datetime = index.data(TransactionTableModel::DateRole).toDateTime();
    if (datetime < dateFrom || datetime > dateTo)
        return false;

    QString address = index.data(TransactionTableModel::AddressRole).toString();
    QString label = index.data(TransactionTableModel::LabelRole).toString();
    QString txid = index.data(TransactionTableModel::TxHashRole).toString();
    if (!address.contains(m_search_string, Qt::CaseInsensitive) &&
        !  label.contains(m_search_string, Qt::CaseInsensitive) &&
        !   txid.contains(m_search_string, Qt::CaseInsensitive)) {
        return false;
    }

    qint64 amount = llabs(index.data(TransactionTableModel::AmountRole).toLongLong());
    if (amount < minAmount)
        return false;

    return true;
}

void TransactionFilterProxy::setDateRange(const QDateTime &from, const QDateTime &to)
{
    this->dateFrom = from;
    this->dateTo = to;
    invalidateFilter();
}

void TransactionFilterProxy::setSearchString(const QString &search_string)
{
    if (m_search_string == search_string) return;
    m_search_string = search_string;
    invalidateFilter();
}

void TransactionFilterProxy::setTypeFilter(quint32 modes)
{
    this->typeFilter = modes;
    invalidateFilter();
}

void TransactionFilterProxy::setMinAmount(const CAmount& minimum)
{
    this->minAmount = minimum;
    invalidateFilter();
}

void TransactionFilterProxy::setWatchOnlyFilter(WatchOnlyFilter filter)
{
    this->watchOnlyFilter = filter;
    invalidateFilter();
}

void TransactionFilterProxy::setLimit(int limit)
{
    this->limitRows = limit;
}

void TransactionFilterProxy::setShowInactive(bool _showInactive)
{
    this->showInactive = _showInactive;
    invalidateFilter();
}

int TransactionFilterProxy::rowCount(const QModelIndex &parent) const
{
    if(limitRows != -1)
    {
        return std::min(QSortFilterProxyModel::rowCount(parent), limitRows);
    }
    else
    {
        return QSortFilterProxyModel::rowCount(parent);
    }
}
<|endoftext|>


<commit_before>
#include <gloperate/rendering/Box.h>

#include <glm/glm.hpp>

#include <cppassist/memory/make_unique.h>

#include <glbinding/gl/enum.h>

#include <globjects/Buffer.h>

namespace gloperate
{

Box::Box(float size, cppassist::Flags<ShapeOption> options)
: Box(size, size, size, options)
{
}

Box::Box(float width, float height, float depth, cppassist::Flags<ShapeOption> options)
: Shape(ShapeType::Box, options)
{
    // Box geometry
    static const std::array<glm::vec3, 36> vertices { {
          glm::vec3(-0.5f, -0.5f,  0.5f)
        , glm::vec3( 0.5f, -0.5f,  0.5f)
        , glm::vec3(-0.5f,  0.5f,  0.5f)

        , glm::vec3( 0.5f, -0.5f,  0.5f)
        , glm::vec3(-0.5f,  0.5f,  0.5f)
        , glm::vec3( 0.5f,  0.5f,  0.5f)

        , glm::vec3(-0.5f, -0.5f, -0.5f)
        , glm::vec3(-0.5f,  0.5f, -0.5f)
        , glm::vec3( 0.5f, -0.5f, -0.5f)

        , glm::vec3(-0.5f,  0.5f, -0.5f)
        , glm::vec3( 0.5f, -0.5f, -0.5f)
        , glm::vec3( 0.5f,  0.5f, -0.5f)

        , glm::vec3(-0.5f, -0.5f,  0.5f)
        , glm::vec3(-0.5f,  0.5f,  0.5f)
        , glm::vec3(-0.5f, -0.5f, -0.5f)

        , glm::vec3(-0.5f,  0.5f,  0.5f)
        , glm::vec3(-0.5f, -0.5f, -0.5f)
        , glm::vec3(-0.5f,  0.5f, -0.5f)

        , glm::vec3( 0.5f, -0.5f, -0.5f)
        , glm::vec3( 0.5f,  0.5f, -0.5f)
        , glm::vec3( 0.5f, -0.5f,  0.5f)

        , glm::vec3( 0.5f,  0.5f, -0.5f)
        , glm::vec3( 0.5f, -0.5f,  0.5f)
        , glm::vec3( 0.5f,  0.5f,  0.5f)

        , glm::vec3(-0.5f,  0.5f,  0.5f)
        , glm::vec3( 0.5f,  0.5f,  0.5f)
        , glm::vec3(-0.5f,  0.5f, -0.5f)

        , glm::vec3( 0.5f,  0.5f,  0.5f)
        , glm::vec3(-0.5f,  0.5f, -0.5f)
        , glm::vec3( 0.5f,  0.5f, -0.5f)

        , glm::vec3(-0.5f, -0.5f,  0.5f)
        , glm::vec3(-0.5f, -0.5f, -0.5f)
        , glm::vec3( 0.5f, -0.5f,  0.5f)

        , glm::vec3(-0.5f, -0.5f, -0.5f)
        , glm::vec3( 0.5f, -0.5f,  0.5f)
        , glm::vec3( 0.5f, -0.5f, -0.5f)
    } };

    static const std::array<glm::vec2, 36> texcoords { {
          glm::vec2(0.0f, 0.0f)
        , glm::vec2(1.0f, 0.0f)
        , glm::vec2(0.0f, 1.0f)

        , glm::vec2(1.0f, 0.0f)
        , glm::vec2(0.0f, 1.0f)
        , glm::vec2(1.0f, 1.0f)

        , glm::vec2(1.0f, 0.0f)
        , glm::vec2(1.0f, 1.0f)
        , glm::vec2(0.0f, 0.0f)

        , glm::vec2(1.0f, 1.0f)
        , glm::vec2(0.0f, 0.0f)
        , glm::vec2(0.0f, 1.0f)

        , glm::vec2(1.0f, 0.0f)
        , glm::vec2(1.0f, 1.0f)
        , glm::vec2(0.0f, 0.0f)

        , glm::vec2(1.0f, 1.0f)
        , glm::vec2(0.0f, 0.0f)
        , glm::vec2(0.0f, 1.0f)

        , glm::vec2(1.0f, 0.0f)
        , glm::vec2(1.0f, 1.0f)
        , glm::vec2(0.0f, 0.0f)

        , glm::vec2(1.0f, 1.0f)
        , glm::vec2(0.0f, 0.0f)
        , glm::vec2(0.0f, 1.0f)

        , glm::vec2(0.0f, 0.0f)
        , glm::vec2(1.0f, 0.0f)
        , glm::vec2(0.0f, 1.0f)

        , glm::vec2(1.0f, 0.0f)
        , glm::vec2(0.0f, 1.0f)
        , glm::vec2(1.0f, 1.0f)

        , glm::vec2(0.0f, 1.0f)
        , glm::vec2(0.0f, 0.0f)
        , glm::vec2(1.0f, 1.0f)

        , glm::vec2(0.0f, 0.0f)
        , glm::vec2(1.0f, 1.0f)
        , glm::vec2(1.0f, 0.0f)
    } };

    // Create drawable
    m_drawable = cppassist::make_unique<Drawable>();
    m_drawable->setPrimitiveMode(gl::GL_TRIANGLES);
    m_drawable->setDrawMode(DrawMode::Arrays);
    m_drawable->setSize(36);

    // Create vertex buffer
    auto v = vertices;

    for (auto & vertex : v) {
        vertex *= glm::vec3(width, height, depth);
    }

    m_vertices = cppassist::make_unique<globjects::Buffer>();
    m_vertices->setData(v, gl::GL_STATIC_DRAW);

    m_drawable->bindAttribute(0, 0);
    m_drawable->setBuffer(0, m_vertices.get());
    m_drawable->setAttributeBindingBuffer(0, 0, 0, sizeof(glm::vec3));
    m_drawable->setAttributeBindingFormat(0, 3, gl::GL_FLOAT, gl::GL_FALSE, 0);
    m_drawable->enableAttributeBinding(0);

    // Create texture coordinate buffer
    if (options & ShapeOption::IncludeTexCoords)
    {
        m_texCoords = cppassist::make_unique<globjects::Buffer>();
        m_texCoords->setData(texcoords, gl::GL_STATIC_DRAW);

        m_drawable->bindAttribute(1, 1);
        m_drawable->setBuffer(1, m_texCoords.get());
        m_drawable->setAttributeBindingBuffer(1, 1, 0, sizeof(glm::vec2));
        m_drawable->setAttributeBindingFormat(1, 2, gl::GL_FLOAT, gl::GL_FALSE, 0);
        m_drawable->enableAttributeBinding(1);
    }
}

Box::~Box()
{
}

void Box::draw() const
{
    m_drawable->draw();
}

} // namespace gloperate
<commit_msg>Fix Box winding to have all front faces on the outside<commit_after>
#include <gloperate/rendering/Box.h>

#include <glm/glm.hpp>

#include <cppassist/memory/make_unique.h>

#include <glbinding/gl/enum.h>

#include <globjects/Buffer.h>

namespace gloperate
{

Box::Box(float size, cppassist::Flags<ShapeOption> options)
: Box(size, size, size, options)
{
}

Box::Box(float width, float height, float depth, cppassist::Flags<ShapeOption> options)
: Shape(ShapeType::Box, options)
{
    // Box geometry
    static const std::array<glm::vec3, 36> vertices { {
          glm::vec3(-0.5f, -0.5f,  0.5f)
        , glm::vec3( 0.5f, -0.5f,  0.5f)
        , glm::vec3(-0.5f,  0.5f,  0.5f)

        , glm::vec3( 0.5f, -0.5f,  0.5f)
        , glm::vec3( 0.5f,  0.5f,  0.5f)
        , glm::vec3(-0.5f,  0.5f,  0.5f)

        , glm::vec3(-0.5f, -0.5f, -0.5f)
        , glm::vec3(-0.5f,  0.5f, -0.5f)
        , glm::vec3( 0.5f, -0.5f, -0.5f)

        , glm::vec3(-0.5f,  0.5f, -0.5f)
        , glm::vec3( 0.5f,  0.5f, -0.5f)
        , glm::vec3( 0.5f, -0.5f, -0.5f)

        , glm::vec3(-0.5f, -0.5f,  0.5f)
        , glm::vec3(-0.5f,  0.5f,  0.5f)
        , glm::vec3(-0.5f, -0.5f, -0.5f)

        , glm::vec3(-0.5f,  0.5f,  0.5f)
        , glm::vec3(-0.5f,  0.5f, -0.5f)
        , glm::vec3(-0.5f, -0.5f, -0.5f)

        , glm::vec3( 0.5f, -0.5f, -0.5f)
        , glm::vec3( 0.5f,  0.5f, -0.5f)
        , glm::vec3( 0.5f, -0.5f,  0.5f)

        , glm::vec3( 0.5f,  0.5f, -0.5f)
        , glm::vec3( 0.5f,  0.5f,  0.5f)
        , glm::vec3( 0.5f, -0.5f,  0.5f)

        , glm::vec3(-0.5f,  0.5f,  0.5f)
        , glm::vec3( 0.5f,  0.5f,  0.5f)
        , glm::vec3(-0.5f,  0.5f, -0.5f)

        , glm::vec3( 0.5f,  0.5f,  0.5f)
        , glm::vec3( 0.5f,  0.5f, -0.5f)
        , glm::vec3(-0.5f,  0.5f, -0.5f)

        , glm::vec3(-0.5f, -0.5f,  0.5f)
        , glm::vec3(-0.5f, -0.5f, -0.5f)
        , glm::vec3( 0.5f, -0.5f,  0.5f)

        , glm::vec3(-0.5f, -0.5f, -0.5f)
        , glm::vec3( 0.5f, -0.5f, -0.5f)
        , glm::vec3( 0.5f, -0.5f,  0.5f)
    } };

    static const std::array<glm::vec2, 36> texcoords { {
          glm::vec2(0.0f, 0.0f)
        , glm::vec2(1.0f, 0.0f)
        , glm::vec2(0.0f, 1.0f)

        , glm::vec2(1.0f, 0.0f)
        , glm::vec2(1.0f, 1.0f)
        , glm::vec2(0.0f, 1.0f)

        , glm::vec2(1.0f, 0.0f)
        , glm::vec2(1.0f, 1.0f)
        , glm::vec2(0.0f, 0.0f)

        , glm::vec2(1.0f, 1.0f)
        , glm::vec2(0.0f, 1.0f)
        , glm::vec2(0.0f, 0.0f)

        , glm::vec2(1.0f, 0.0f)
        , glm::vec2(1.0f, 1.0f)
        , glm::vec2(0.0f, 0.0f)

        , glm::vec2(1.0f, 1.0f)
        , glm::vec2(0.0f, 1.0f)
        , glm::vec2(0.0f, 0.0f)

        , glm::vec2(1.0f, 0.0f)
        , glm::vec2(1.0f, 1.0f)
        , glm::vec2(0.0f, 0.0f)

        , glm::vec2(1.0f, 1.0f)
        , glm::vec2(0.0f, 1.0f)
        , glm::vec2(0.0f, 0.0f)

        , glm::vec2(0.0f, 0.0f)
        , glm::vec2(1.0f, 0.0f)
        , glm::vec2(0.0f, 1.0f)

        , glm::vec2(1.0f, 0.0f)
        , glm::vec2(1.0f, 1.0f)
        , glm::vec2(0.0f, 1.0f)

        , glm::vec2(0.0f, 1.0f)
        , glm::vec2(0.0f, 0.0f)
        , glm::vec2(1.0f, 1.0f)

        , glm::vec2(0.0f, 0.0f)
        , glm::vec2(1.0f, 0.0f)
        , glm::vec2(1.0f, 1.0f)
    } };

    // Create drawable
    m_drawable = cppassist::make_unique<Drawable>();
    m_drawable->setPrimitiveMode(gl::GL_TRIANGLES);
    m_drawable->setDrawMode(DrawMode::Arrays);
    m_drawable->setSize(36);

    // Create vertex buffer
    auto v = vertices;

    for (auto & vertex : v) {
        vertex *= glm::vec3(width, height, depth);
    }

    m_vertices = cppassist::make_unique<globjects::Buffer>();
    m_vertices->setData(v, gl::GL_STATIC_DRAW);

    m_drawable->bindAttribute(0, 0);
    m_drawable->setBuffer(0, m_vertices.get());
    m_drawable->setAttributeBindingBuffer(0, 0, 0, sizeof(glm::vec3));
    m_drawable->setAttributeBindingFormat(0, 3, gl::GL_FLOAT, gl::GL_FALSE, 0);
    m_drawable->enableAttributeBinding(0);

    // Create texture coordinate buffer
    if (options & ShapeOption::IncludeTexCoords)
    {
        m_texCoords = cppassist::make_unique<globjects::Buffer>();
        m_texCoords->setData(texcoords, gl::GL_STATIC_DRAW);

        m_drawable->bindAttribute(1, 1);
        m_drawable->setBuffer(1, m_texCoords.get());
        m_drawable->setAttributeBindingBuffer(1, 1, 0, sizeof(glm::vec2));
        m_drawable->setAttributeBindingFormat(1, 2, gl::GL_FLOAT, gl::GL_FALSE, 0);
        m_drawable->enableAttributeBinding(1);
    }
}

Box::~Box()
{
}

void Box::draw() const
{
    m_drawable->draw();
}

} // namespace gloperate
<|endoftext|>


<commit_before>//
// Created by david on 2019-08-07.
//

#include <complex.h>
#undef I

#ifdef MKL_AVAILABLE
//#ifndef MKL_Complex8
//#define MKL_Complex8 std::complex<float>
//#endif
//#ifndef MKL_Complex16
//#define MKL_Complex16 std::complex<double>
//#endif
#ifndef ComplexFloat_
#define ComplexFloat_  lapack_complex_float
#endif
#ifndef ComplexDouble_
#define ComplexDouble_ lapack_complex_double
#endif
#include <mkl_lapacke.h>
#else
#define ComplexFloat_  __complex__ float
#define ComplexDouble_ __complex__ double
#include <lapacke.h>
#endif

#include <math/class_svd_wrapper.h>
#include <Eigen/Core>
//
//template<typename Scalar>
//
//std::tuple<class_SVD::MatrixType<Scalar>, class_SVD::VectorType<Scalar>,class_SVD::MatrixType<Scalar> , long>
//do_svd_dgesvd(const Scalar *matrix, int rows, int cols){
//
//}

template<typename Scalar>
std::tuple<class_SVD::MatrixType<Scalar>, class_SVD::VectorType<Scalar>,class_SVD::MatrixType<Scalar> , long>
class_SVD::do_svd_lapacke(const Scalar * mat_ptr, long rows, long cols, long rank_max){
    MatrixType<Scalar> A = Eigen::Map<const MatrixType<Scalar>> (mat_ptr,rows,cols);

    if (rows <= 0)              throw std::runtime_error("SVD error: rows() == 0");
    if (cols <= 0)              throw std::runtime_error("SVD error: cols() == 0");
    if (not A.allFinite())      throw std::runtime_error("SVD error: matrix has inf's or nan's");
    if (A.isZero(0))            throw std::runtime_error("SVD error: matrix is all zeros");

    int info   = 0;
    int rowsU  = (int) rows;
    int colsU  = (int) std::min(rows,cols);
    int rowsVT = (int) std::min(rows,cols);
    int colsVT = (int) cols;
    int sizeS  = (int) std::min(rows,cols);
    int lda    = (int) rows;
    int ldu    = (int) rowsU;
    int ldvt   = (int) rowsVT;

    MatrixType<Scalar> U(rowsU,colsU);
    VectorType<double> S(sizeS);
    MatrixType<Scalar> VT(rowsVT,colsVT);
    VectorType<Scalar> work(1);

    if constexpr (std::is_same<Scalar,double>::value){
        info = LAPACKE_dgesvd_work(LAPACK_COL_MAJOR, 'S', 'S', rows,cols, A.data(), lda, S.data(), U.data(), ldu, VT.data(), ldvt, work.data(), -1);
        int lwork  = (int) work(0);
        work.resize(lwork);
        info = LAPACKE_dgesvd_work(LAPACK_COL_MAJOR, 'S', 'S', rows,cols, A.data(), lda, S.data(), U.data(), ldu, VT.data(), ldvt, work.data(), lwork);
    }
    if constexpr (std::is_same<Scalar,std::complex<double>>::value){
        int lrwork = (int) (5 * std::min(rows,cols));
        VectorType<double> rwork(lrwork);
        auto Ap  =  reinterpret_cast< ComplexDouble_ *>(A.data());
        auto Up  =  reinterpret_cast< ComplexDouble_ *>(U.data());
        auto VTp =  reinterpret_cast< ComplexDouble_ *>(VT.data());
        auto Wp  =  reinterpret_cast< ComplexDouble_ *>(work.data());
        info = LAPACKE_zgesvd_work(LAPACK_COL_MAJOR, 'S', 'S', rows,cols, Ap, lda, S.data(), Up, ldu, VTp, ldvt, Wp, -1,rwork.data());
        int lwork  = (int) std::real(work(0));
        work.resize(lwork);
        info = LAPACKE_zgesvd_work(LAPACK_COL_MAJOR, 'S', 'S', rows,cols, Ap, lda, S.data(), Up, ldu, VTp, ldvt, Wp, lwork,rwork.data());
    }

    long max_size    =  std::min(S.size(),rank_max);
    long rank        = (S.head(max_size).array() >= SVDThreshold).count();
    if(rank == S.size()){
        truncation_error = 0;
    }else{
        truncation_error = S.tail(S.size()-rank).squaredNorm();
    }

    if (rank <= 0
        or not U.leftCols(rank).allFinite()
        or not S.head(rank).allFinite()
        or not VT.topRows(rank).allFinite() )
    {
        std::cerr   << "SVD error \n"
                    << "  svd_threshold     = " << SVDThreshold << '\n'
                    << "  Truncation Error = " << truncation_error << '\n'
                    << "  Rank             = " << rank << '\n'
                    << "  U all finite     : " << std::boolalpha << U.leftCols(rank).allFinite() << '\n'
                    << "  S all finite     : " << std::boolalpha << S.head(rank).allFinite() << '\n'
                    << "  V all finite     : " << std::boolalpha << VT.topRows(rank).allFinite() << '\n';
//        return do_svd_lapacke(mat_ptr, rows,cols,rank_max);
        throw std::runtime_error("SVD lapacke error:  Erroneous results");
    }

    return std::make_tuple(
            U.leftCols(rank),
            S.head(rank),
            VT.topRows(rank),
            rank
    );
}

//! \relates class_SVD
//! \brief force instantiation of do_svd_lapacke for type 'double'
template std::tuple<class_SVD::MatrixType<double>, class_SVD::VectorType<double>,class_SVD::MatrixType<double> , long>
class_SVD::do_svd_lapacke(const double *, long, long, long);

using cplx = std::complex<double>;
//! \relates class_SVD
//! \brief force instantiation of do_svd_lapacke for type 'std::complex<double>'
template std::tuple<class_SVD::MatrixType<cplx>, class_SVD::VectorType<cplx>,class_SVD::MatrixType<cplx> , long>
class_SVD::do_svd_lapacke(const cplx *, long, long, long);

<commit_msg>Debugging lapack svd segfault<commit_after>//
// Created by david on 2019-08-07.
//

#include <complex.h>
#undef I

#ifdef MKL_AVAILABLE
//#ifndef MKL_Complex8
//#define MKL_Complex8 std::complex<float>
//#endif
//#ifndef MKL_Complex16
//#define MKL_Complex16 std::complex<double>
//#endif
#include <mkl_lapacke.h>
#ifndef ComplexFloat_
#define ComplexFloat_  lapack_complex_float
#endif
#ifndef ComplexDouble_
#define ComplexDouble_ lapack_complex_double
#endif
#else
#define ComplexFloat_  __complex__ float
#define ComplexDouble_ __complex__ double
#include <lapacke.h>
#endif

#include <math/class_svd_wrapper.h>
#include <Eigen/Core>
//
//template<typename Scalar>
//
//std::tuple<class_SVD::MatrixType<Scalar>, class_SVD::VectorType<Scalar>,class_SVD::MatrixType<Scalar> , long>
//do_svd_dgesvd(const Scalar *matrix, int rows, int cols){
//
//}

template<typename Scalar>
std::tuple<class_SVD::MatrixType<Scalar>, class_SVD::VectorType<Scalar>,class_SVD::MatrixType<Scalar> , long>
class_SVD::do_svd_lapacke(const Scalar * mat_ptr, long rows, long cols, long rank_max){
    MatrixType<Scalar> A = Eigen::Map<const MatrixType<Scalar>> (mat_ptr,rows,cols);

    if (rows <= 0)              throw std::runtime_error("SVD error: rows() == 0");
    if (cols <= 0)              throw std::runtime_error("SVD error: cols() == 0");
    if (not A.allFinite())      throw std::runtime_error("SVD error: matrix has inf's or nan's");
    if (A.isZero(0))            throw std::runtime_error("SVD error: matrix is all zeros");

    int info   = 0;
    int rowsU  = (int) rows;
    int colsU  = (int) std::min(rows,cols);
    int rowsVT = (int) std::min(rows,cols);
    int colsVT = (int) cols;
    int sizeS  = (int) std::min(rows,cols);
    int lda    = (int) rows;
    int ldu    = (int) rowsU;
    int ldvt   = (int) rowsVT;

    MatrixType<Scalar> U(rowsU,colsU);
    VectorType<double> S(sizeS);
    MatrixType<Scalar> VT(rowsVT,colsVT);
    VectorType<Scalar> work(1);

    if constexpr (std::is_same<Scalar,double>::value){
        info = LAPACKE_dgesvd_work(LAPACK_COL_MAJOR, 'S', 'S', rows,cols, A.data(), lda, S.data(), U.data(), ldu, VT.data(), ldvt, work.data(), -1);
        int lwork  = (int) work(0);
        work.resize(lwork);
        info = LAPACKE_dgesvd_work(LAPACK_COL_MAJOR, 'S', 'S', rows,cols, A.data(), lda, S.data(), U.data(), ldu, VT.data(), ldvt, work.data(), lwork);
    }
    if constexpr (std::is_same<Scalar,std::complex<double>>::value){
        int lrwork = (int) (5 * std::min(rows,cols));
        VectorType<double> rwork(lrwork);
        auto Ap  =  reinterpret_cast< ComplexDouble_ *>(A.data());
        auto Up  =  reinterpret_cast< ComplexDouble_ *>(U.data());
        auto VTp =  reinterpret_cast< ComplexDouble_ *>(VT.data());
        auto Wp  =  reinterpret_cast< ComplexDouble_ *>(work.data());
        info = LAPACKE_zgesvd_work(LAPACK_COL_MAJOR, 'S', 'S', rows,cols, Ap, lda, S.data(), Up, ldu, VTp, ldvt, Wp, -1,rwork.data());
        int lwork  = (int) std::real(work(0));
        work.resize(lwork);
        info = LAPACKE_zgesvd_work(LAPACK_COL_MAJOR, 'S', 'S', rows,cols, Ap, lda, S.data(), Up, ldu, VTp, ldvt, Wp, lwork,rwork.data());
    }

    long max_size    =  std::min(S.size(),rank_max);
    long rank        = (S.head(max_size).array() >= SVDThreshold).count();
    if(rank == S.size()){
        truncation_error = 0;
    }else{
        truncation_error = S.tail(S.size()-rank).squaredNorm();
    }

    if (rank <= 0
        or not U.leftCols(rank).allFinite()
        or not S.head(rank).allFinite()
        or not VT.topRows(rank).allFinite() )
    {
        std::cerr   << "SVD error \n"
                    << "  svd_threshold     = " << SVDThreshold << '\n'
                    << "  Truncation Error = " << truncation_error << '\n'
                    << "  Rank             = " << rank << '\n'
                    << "  U all finite     : " << std::boolalpha << U.leftCols(rank).allFinite() << '\n'
                    << "  S all finite     : " << std::boolalpha << S.head(rank).allFinite() << '\n'
                    << "  V all finite     : " << std::boolalpha << VT.topRows(rank).allFinite() << '\n';
//        return do_svd_lapacke(mat_ptr, rows,cols,rank_max);
        throw std::runtime_error("SVD lapacke error:  Erroneous results");
    }

    return std::make_tuple(
            U.leftCols(rank),
            S.head(rank),
            VT.topRows(rank),
            rank
    );
}

//! \relates class_SVD
//! \brief force instantiation of do_svd_lapacke for type 'double'
template std::tuple<class_SVD::MatrixType<double>, class_SVD::VectorType<double>,class_SVD::MatrixType<double> , long>
class_SVD::do_svd_lapacke(const double *, long, long, long);

using cplx = std::complex<double>;
//! \relates class_SVD
//! \brief force instantiation of do_svd_lapacke for type 'std::complex<double>'
template std::tuple<class_SVD::MatrixType<cplx>, class_SVD::VectorType<cplx>,class_SVD::MatrixType<cplx> , long>
class_SVD::do_svd_lapacke(const cplx *, long, long, long);

<|endoftext|>


<commit_before>//
//  JdCircularAllocator.hpp
//  Tape
//
//  Created by Steven Massey on 6/10/20.
//  Copyright © 2020 Massey Plugins Inc. All rights reserved.
//

#ifndef JdCircularAllocator_hpp
#define JdCircularAllocator_hpp

#include "JdCore.cpp"
#include <condition_variable>
#include <mutex>

/*
 	This is a thread-safe fixed-size circular buffer allocator.  It's used in the JdModule system for message-passing and assumes that
 	all allocations are short-lived and allocated and deallocated in a roughly first-out, first-back-in manner.
 */

class JdCircularAllocator
{
	public:					JdCircularAllocator					(u32 i_maxAllocationSize, u32 i_bufferSize = 0)
							:
							m_maxAllocationSize					(i_maxAllocationSize)
	{
		if (i_bufferSize)
			Resize (i_bufferSize);														d_jdAssert (i_maxAllocationSize, "must be >=1");
	}

	void					Resize								(u32 i_numBytes, u32 i_maxAllocationSize = 0 /* 0= don't modify */)
	{
		std::unique_lock <std::mutex> lock (m_mutex);

		while (m_claimedIndex != m_releaseIndex)				// can only resize if nothing allocated
			m_condition.wait (lock);

		if (i_maxAllocationSize)
			m_maxAllocationSize = i_maxAllocationSize;

		m_bufferSize = Jd::RoundUpToAPowerOf2 (i_numBytes);
		m_bytes.resize (m_bufferSize + m_maxAllocationSize);	// pad the buffer so that m_maxAllocationSize bytes can always be safelyused when m_claimedIndex is near the end of the buffer
		m_data = m_bytes.data ();								// in worst case situation, size word is last word within the nominal buffer size and the overflow is equal to the size of the alloc.

		m_indexMask = m_bufferSize - 1;
	}

	template <typename T>
	T *							Allocate						(u32 i_numBytes = sizeof (T))
	{
		T * allocated = nullptr;

		u32 numBytes = Jd::Align64 (i_numBytes);						d_jdAssert (numBytes <= m_maxAllocationSize, "allocation too large");

		if (numBytes <= m_maxAllocationSize)
		{
			numBytes += sizeof (u64);			// size word

			std::unique_lock <std::mutex> lock (m_mutex);

			while (GetNumAvailableBytesUnlocked () < numBytes)
			{
				m_hasOverflowed = true;
				m_condition.wait (lock);
			}

			u32 index = m_claimedIndex & m_indexMask;
			m_claimedIndex += numBytes;

			u64 * data = (u64 *) & m_data [index];
			* data = numBytes | 1;	// 1 = allocated signal bit

			allocated = (T *) ++data;
		}

		return allocated;
	}

	void					Release								(void * i_data)
	{
		u32 numBytesToRelease = 0;

		m_mutex.lock ();

		u64 * word = (u64 *) i_data;
		(* --word) &= ~1;	// erase allocation bit flag

		u32 index = (u8 *) word - m_data;

		if (index == m_releaseIndex)
		{
			// if the release index is pointing to this chunk, then free it by advancing the release index.
			// also, free any further contiguous chunks that have been deallocated prior.
			do
			{
				u64 numBytes = * word;
				numBytesToRelease += numBytes;
				m_releaseIndex += numBytes;

				if (m_releaseIndex == m_claimedIndex)
					break;

				word = (u64 *) & m_data [m_releaseIndex & m_indexMask];
			}
			while (not (* word & 1)); // check allocated bit flag
		}

		m_mutex.unlock ();

		if (numBytesToRelease)
			m_condition.notify_all ();
	}

	u32						GetNumAvailableBytes				()
	{
		std::unique_lock <std::mutex> lock (m_mutex);

		return GetNumAvailableBytesUnlocked ();
	}

	bool					HasOverflowed						()
	{
		std::unique_lock <std::mutex> lock (m_mutex);

		bool hasOverflowed = m_hasOverflowed;
		m_hasOverflowed = false;

		return hasOverflowed;
	}

	protected:

	u32						GetNumAvailableBytesUnlocked		()
	{
		return m_bufferSize - (m_claimedIndex - m_releaseIndex);
	}

	mutex					m_mutex;
	condition_variable		m_condition;

	vector <u8>				m_bytes;
	u8 *					m_data								= nullptr;

	u32						m_maxAllocationSize					= 0;
	u32						m_bufferSize						= 0;

	u32						m_claimedIndex						= 0;
	u32						m_releaseIndex						= 0;

	u32						m_indexMask							= 0;

	bool					m_hasOverflowed						= false;
};

#endif /* JdCircularAllocator_hpp */
<commit_msg>no message<commit_after>//
//  JdCircularAllocator.hpp
//  Tape
//
//  Created by Steven Massey on 6/10/20.
//  Copyright © 2020 Massey Plugins Inc. All rights reserved.
//

#ifndef JdCircularAllocator_hpp
#define JdCircularAllocator_hpp

#include "JdCore.hpp"
#include "JdAssert.hpp"
#include <condition_variable>
#include <mutex>

/*
 	This is a thread-safe fixed-size circular buffer allocator.  It's used in the JdModule system for message-passing and assumes that
 	all allocations are short-lived and allocated and deallocated in a roughly first-out, first-back-in manner.
 */

class JdCircularAllocator
{
	public:					JdCircularAllocator					(u32 i_maxAllocationSize, u32 i_bufferSize = 0)
							:
							m_maxAllocationSize					(i_maxAllocationSize)
	{
		if (i_bufferSize)
			Resize (i_bufferSize);														d_jdAssert (i_maxAllocationSize, "must be >=1");
	}

	void					Resize								(u32 i_numBytes, u32 i_maxAllocationSize = 0 /* 0= don't modify */)
	{
		std::unique_lock <std::mutex> lock (m_mutex);

		while (m_claimedIndex != m_releaseIndex)				// can only resize if nothing allocated
			m_condition.wait (lock);

		if (i_maxAllocationSize)
			m_maxAllocationSize = i_maxAllocationSize;

		m_bufferSize = Jd::RoundUpToAPowerOf2 (i_numBytes);
		m_bytes.resize (m_bufferSize + m_maxAllocationSize);	// pad the buffer so that m_maxAllocationSize bytes can always be safelyused when m_claimedIndex is near the end of the buffer
		m_data = m_bytes.data ();								// in worst case situation, size word is last word within the nominal buffer size and the overflow is equal to the size of the alloc.

		m_indexMask = m_bufferSize - 1;
	}

	template <typename T>
	T *							Allocate						(u32 i_numBytes = sizeof (T))
	{
		T * allocated = nullptr;

		u32 numBytes = Jd::Align64 (i_numBytes);						d_jdAssert (numBytes <= m_maxAllocationSize, "allocation too large");

		if (numBytes <= m_maxAllocationSize)
		{
			numBytes += sizeof (u64);			// size word

			std::unique_lock <std::mutex> lock (m_mutex);

			while (GetNumAvailableBytesUnlocked () < numBytes)
			{
				m_hasOverflowed = true;
				m_condition.wait (lock);
			}

			u32 index = m_claimedIndex & m_indexMask;
			m_claimedIndex += numBytes;

			u64 * data = (u64 *) & m_data [index];
			* data = numBytes | 1;	// 1 = allocated signal bit

			allocated = (T *) ++data;
		}

		return allocated;
	}

	void					Release								(void * i_data)
	{
		u32 numBytesToRelease = 0;

		m_mutex.lock ();

		u64 * word = (u64 *) i_data;
		(* --word) &= ~1;	// erase allocation bit flag

		u32 index = (u8 *) word - m_data;

		if (index == m_releaseIndex)
		{
			// if the release index is pointing to this chunk, then free it by advancing the release index.
			// also, free any further contiguous chunks that have been deallocated prior.
			do
			{
				u64 numBytes = * word;
				numBytesToRelease += numBytes;
				m_releaseIndex += numBytes;

				if (m_releaseIndex == m_claimedIndex)
					break;

				word = (u64 *) & m_data [m_releaseIndex & m_indexMask];
			}
			while (not (* word & 1)); // check allocated bit flag
		}

		m_mutex.unlock ();

		if (numBytesToRelease)
			m_condition.notify_all ();
	}

	u32						GetNumAvailableBytes				()
	{
		std::unique_lock <std::mutex> lock (m_mutex);

		return GetNumAvailableBytesUnlocked ();
	}

	bool					HasOverflowed						()
	{
		std::unique_lock <std::mutex> lock (m_mutex);

		bool hasOverflowed = m_hasOverflowed;
		m_hasOverflowed = false;

		return hasOverflowed;
	}

	protected:

	u32						GetNumAvailableBytesUnlocked		()
	{
		return m_bufferSize - (m_claimedIndex - m_releaseIndex);
	}

	mutex					m_mutex;
	condition_variable		m_condition;

	vector <u8>				m_bytes;
	u8 *					m_data								= nullptr;

	u32						m_maxAllocationSize					= 0;
	u32						m_bufferSize						= 0;

	u32						m_claimedIndex						= 0;
	u32						m_releaseIndex						= 0;

	u32						m_indexMask							= 0;

	bool					m_hasOverflowed						= false;
};

#endif /* JdCircularAllocator_hpp */
<|endoftext|>


<commit_before>/*
** Copyright 2011-2013 Merethis
**
** This file is part of Centreon Clib.
**
** Centreon Clib is free software: you can redistribute it
** and/or modify it under the terms of the GNU Affero General Public
** License as published by the Free Software Foundation, either version
** 3 of the License, or (at your option) any later version.
**
** Centreon Clib is distributed in the hope that it will be
** useful, but WITHOUT ANY WARRANTY; without even the implied warranty
** of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Affero General Public License for more details.
**
** You should have received a copy of the GNU Affero General Public
** License along with Centreon Clib. If not, see
** <http://www.gnu.org/licenses/>.
*/

#include <exception>
#include <iostream>
#include "com/centreon/concurrency/thread.hh"
#include "com/centreon/exceptions/basic.hh"
#include "com/centreon/timestamp.hh"

using namespace com::centreon;

/**
 *  Check the sleep methode.
 *
 *  @return 0 on success.
 */
int main() {
  try {
    unsigned long waiting(4000000000l);
    timestamp start(timestamp::now());
    concurrency::thread::nsleep(waiting);
    timestamp end(timestamp::now());
    timestamp diff(end - start);
    waiting /= 1000;
    if (diff.to_useconds() > waiting * 1.20)
      throw (basic_error()
             << "waiting more than necessary: "
             << diff.to_useconds() << "/" << waiting);
    if (diff.to_useconds() < waiting * 0.90)
      throw (basic_error()
             << "waiting less than necessary: "
             << diff.to_useconds() << "/" << waiting);
  }
  catch (std::exception const& e) {
    std::cerr << "error: " << e.what() << std::endl;
    return (1);
  }
  return (0);
}
<commit_msg>Fix unit test.<commit_after>/*
** Copyright 2011-2013 Merethis
**
** This file is part of Centreon Clib.
**
** Centreon Clib is free software: you can redistribute it
** and/or modify it under the terms of the GNU Affero General Public
** License as published by the Free Software Foundation, either version
** 3 of the License, or (at your option) any later version.
**
** Centreon Clib is distributed in the hope that it will be
** useful, but WITHOUT ANY WARRANTY; without even the implied warranty
** of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Affero General Public License for more details.
**
** You should have received a copy of the GNU Affero General Public
** License along with Centreon Clib. If not, see
** <http://www.gnu.org/licenses/>.
*/

#include <exception>
#include <iostream>
#include "com/centreon/concurrency/thread.hh"
#include "com/centreon/exceptions/basic.hh"
#include "com/centreon/timestamp.hh"

using namespace com::centreon;

/**
 *  Check the sleep methode.
 *
 *  @return 0 on success.
 */
int main() {
  try {
    unsigned long waiting(4000000000ul);
    timestamp start(timestamp::now());
    concurrency::thread::nsleep(waiting);
    timestamp end(timestamp::now());
    timestamp diff(end - start);
    waiting /= 1000;
    if (diff.to_useconds() > waiting * 1.20)
      throw (basic_error()
             << "waiting more than necessary: "
             << diff.to_useconds() << "/" << waiting);
    if (diff.to_useconds() < waiting * 0.90)
      throw (basic_error()
             << "waiting less than necessary: "
             << diff.to_useconds() << "/" << waiting);
  }
  catch (std::exception const& e) {
    std::cerr << "error: " << e.what() << std::endl;
    return (1);
  }
  return (0);
}
<|endoftext|>


<commit_before>/*
 * Copyright 2014 Blistud:io
 */

#include "blieng/point.h"

#include <boost/format.hpp>
#include <math.h>

#include <string>

using blieng::Point;

Point::~Point()
{
    x = 0;
    y = 0;
}

std::string Point::toString() const
{
    return (boost::format("%f,%f") % x % y).str();
}

bool Point::operator==(const Point &other) const
{
    return (x == other.x && y == other.y);
}

bool Point::operator!=(const Point &other) const
{
    return (x != other.x || y != other.y);
}

Point Point::operator+(const Point &other)
{
    Point res(x + other.x, y + other.y);
    return res;
}

Point Point::operator-(const Point &other)
{
    Point res(x - other.x, y - other.y);
    return res;
}

Point &Point::operator+=(const Point &other)
{
    x += other.x;
    y += other.y;
    return *this;
}

Point &Point::operator-=(const Point &other)
{
    x -= other.x;
    y -= other.y;
    return *this;
}

void Point::update(Point another)
{
    x = another.x;
    y = another.y;
}

Point Point::semiPoint(Point target, double pos) const
{
    if (pos < 0) return *this;
    if (pos >= 1.0) return target;

    double nposx = target.x - x;
    double nposy = target.y - y;

    nposx *= pos;
    nposy *= pos;

    nposx += x;
    nposy += y;

    return Point(nposx, nposy);
}

Point Point::traverse(Point target, double now, double time) const
{
    // Travel to another point, in specific time, specify now as current time
    if (now <= 0) return *this;
    if (now > time) return target;

    double nposx, nposy;
    nposx = target.x - x;
    nposy = target.y - y;
    nposx = (nposx * now / time) + x;
    nposy = (nposy * now / time) + y;

    return Point(nposx, nposy);
}

double Point::length(Point another)
{
    double dx = x - another.x;
    double dy = y - another.y;
    if (dx < 0) dx *= -1;
    if (dy < 0) dy *= -1;

    // return sqrt(dx*dx + dy*dy);
    return dx+dy;
}

double Point::lengthGeo(Point another)
{
    static const double PI = 3.14159;
    static const double R = 6378.137;

    double dlat = (x - another.x) * PI / 180.0;
    double dlon = (y - another.y) * PI / 180.0;

    double a = sin(dlat / 2) * sin(dlat / 2) +
        cos(another.x * PI / 180.0) * cos(x * PI / 180.0) +
        sin(dlon / 2) * sin(dlon / 2);
    double c = 2 * atan2(sqrt(a), sqrt(1 - a));
    double d = R * c;

    // Meters
    return d * 1000;

    /*
    if (dx < 0) dx *= -1;
    if (dy < 0) dy *= -1;

    // return sqrt(dx*dx + dy*dy);
    return dx+dy;
    */
}
<commit_msg>Fix plus with multiply<commit_after>/*
 * Copyright 2014 Blistud:io
 */

#include "blieng/point.h"

#include <boost/format.hpp>
#include <math.h>

#include <string>

using blieng::Point;

Point::~Point()
{
    x = 0;
    y = 0;
}

std::string Point::toString() const
{
    return (boost::format("%f,%f") % x % y).str();
}

bool Point::operator==(const Point &other) const
{
    return (x == other.x && y == other.y);
}

bool Point::operator!=(const Point &other) const
{
    return (x != other.x || y != other.y);
}

Point Point::operator+(const Point &other)
{
    Point res(x + other.x, y + other.y);
    return res;
}

Point Point::operator-(const Point &other)
{
    Point res(x - other.x, y - other.y);
    return res;
}

Point &Point::operator+=(const Point &other)
{
    x += other.x;
    y += other.y;
    return *this;
}

Point &Point::operator-=(const Point &other)
{
    x -= other.x;
    y -= other.y;
    return *this;
}

void Point::update(Point another)
{
    x = another.x;
    y = another.y;
}

Point Point::semiPoint(Point target, double pos) const
{
    if (pos < 0) return *this;
    if (pos >= 1.0) return target;

    double nposx = target.x - x;
    double nposy = target.y - y;

    nposx *= pos;
    nposy *= pos;

    nposx += x;
    nposy += y;

    return Point(nposx, nposy);
}

Point Point::traverse(Point target, double now, double time) const
{
    // Travel to another point, in specific time, specify now as current time
    if (now <= 0) return *this;
    if (now > time) return target;

    double nposx, nposy;
    nposx = target.x - x;
    nposy = target.y - y;
    nposx = (nposx * now / time) + x;
    nposy = (nposy * now / time) + y;

    return Point(nposx, nposy);
}

double Point::length(Point another)
{
    double dx = x - another.x;
    double dy = y - another.y;
    if (dx < 0) dx *= -1;
    if (dy < 0) dy *= -1;

    // return sqrt(dx*dx + dy*dy);
    return dx+dy;
}

double Point::lengthGeo(Point another)
{
    static const double PI = 3.14159;
    static const double R = 6378.137;

    double dlat = (x - another.x) * PI / 180.0;
    double dlon = (y - another.y) * PI / 180.0;

    double a = sin(dlat / 2) * sin(dlat / 2) +
        cos(another.x * PI / 180.0) * cos(x * PI / 180.0) *
        sin(dlon / 2) * sin(dlon / 2);
    double c = 2 * atan2(sqrt(a), sqrt(1 - a));
    double d = R * c;

    // Meters
    return d * 1000;

    /*
    if (dx < 0) dx *= -1;
    if (dy < 0) dy *= -1;

    // return sqrt(dx*dx + dy*dy);
    return dx+dy;
    */
}
<|endoftext|>


<commit_before>#include "raiden.h"
#include "reflection.h"
//#include "transform.h"
#include "gtest.h"

TEST(FrConductor,Au){
   float air_ior[3]={1,1,1};
//    float au_ior[3]={0.15557,0.42415,1.3831};
//    float au_k[3] = {3.5024,2.4721,1.9155};
    float au_ior[3]={0.18299,0.42108,1.3734};
   float au_k[3] = {3.4242,2.3459,1.7704};

   Spectrum air=Spectrum::FromRGB(air_ior);
   Spectrum ior=Spectrum::FromRGB(au_ior);
   Spectrum k=Spectrum::FromRGB(au_k);

   Spectrum r=FrConductor(1,air,ior,k);
   float au[3];
   r.ToRGB(au);
//    EXPECT_FLOAT_EQ(au[0],1.000);
//    EXPECT_FLOAT_EQ(au[1],0.766);
//    EXPECT_FLOAT_EQ(au[2],0.336);

   EXPECT_GE(au[0],0.9);
   EXPECT_GE(au[1],0.7);
   EXPECT_GE(au[2],0.3);
}<commit_msg>修正一个单元测试内的类型问题<commit_after>#include "raiden.h"
#include "reflection.h"
//#include "transform.h"
#include "gtest.h"

TEST(FrConductor,Au){
   Float air_ior[3]={1,1,1};
//    float au_ior[3]={0.15557,0.42415,1.3831};
//    float au_k[3] = {3.5024,2.4721,1.9155};
    Float au_ior[3]={0.18299,0.42108,1.3734};
   Float au_k[3] = {3.4242,2.3459,1.7704};

   Spectrum air=Spectrum::FromRGB(air_ior);
   Spectrum ior=Spectrum::FromRGB(au_ior);
   Spectrum k=Spectrum::FromRGB(au_k);

   Spectrum r=FrConductor(1,air,ior,k);
   Float au[3];
   r.ToRGB(au);
//    EXPECT_FLOAT_EQ(au[0],1.000);
//    EXPECT_FLOAT_EQ(au[1],0.766);
//    EXPECT_FLOAT_EQ(au[2],0.336);

   EXPECT_GE(au[0],0.9);
   EXPECT_GE(au[1],0.7);
   EXPECT_GE(au[2],0.3);
}<|endoftext|>


<commit_before>// Copyright 2016 Jonathan Buchanan.
// This file is part of Sunglasses, which is licensed under the MIT License.
// See LICENSE.md for details.
#include <gtest/gtest.h>
#include <gmock/gmock.h>

#include <Sunglasses/Sunglasses.hpp>

struct SunScriptTest : ::testing::Test {
    SunScript script;
    SunScriptTest() {
        script.loadFile("src/test_SunScript_0.lua");
        script.loadFile("src/test_SunScript_1.lua");
    }

    ~SunScriptTest() {

    }
};

TEST_F(SunScriptTest, LuaVariables) {
    int x = script.getVariable("x");
    EXPECT_EQ(x, 2);

    double pi = script["pi"];
    EXPECT_DOUBLE_EQ(pi, 3.14);

    bool yes = script.getVariable("yes");
    EXPECT_EQ(yes, true);

    bool no = script.getVariable("no");
    EXPECT_EQ(no, false);

    std::string str = script.getVariable("str");
    EXPECT_EQ(str, "Hello, World!");

    int a = script["table"]["a"];
    EXPECT_EQ(a, 7);

    double b = script.getVariable("table")["b"];
    EXPECT_DOUBLE_EQ(b, 1.23);

    bool c = script.getVariable("table")["c"];
    EXPECT_EQ(c, true);

    bool d = script.getVariable("table")["d"];
    EXPECT_EQ(d, false);

    SunLuaValue e_ = script.getVariable("table");
    EXPECT_EQ((std::string)e_["e"], "Test");

    int r = script["table"]["f"]["r"];
    EXPECT_EQ(r, 1);

    double g = script["table"]["f"]["g"];
    EXPECT_DOUBLE_EQ(g, 0.2);

    double b_ = script["table"]["f"]["b"];
    EXPECT_DOUBLE_EQ(b_, 0.5);

    script["a"] = 23;
    EXPECT_EQ((int)script["a"], 23);

    script["b"] = 3.21;
    EXPECT_DOUBLE_EQ((double)script["b"], 3.21);

    script["c"] = true;
    EXPECT_EQ((bool)script["c"], true);

    script["d"] = false;
    EXPECT_EQ((bool)script["d"], false);

    script["e"] = "Testing";
    EXPECT_EQ((std::string)script["e"], "Testing");

    script["o"].newTable();

    script["o"][1] = -3;
    EXPECT_EQ((int)script["o"][1], -3);

    script["o"][2] = true;
    EXPECT_EQ((bool)script["o"][2], true);

    script["o"][3] = 7.89;
    EXPECT_DOUBLE_EQ((double)script["o"][3], 7.89);

    /*script["o"][4] = "abc";
    EXPECT_EQ((std::string)script["o"][4], "abc");*/
}

TEST_F(SunScriptTest, LuaFunctions) {
    int result = script["add"](1, 2);
    EXPECT_EQ(result, 3);

    int add;
    int multiply;
    script["addAndMultiply"](4, 5).assign(add, multiply);
    EXPECT_EQ(add, 9);
    EXPECT_EQ(multiply, 20);
}

TEST_F(SunScriptTest, RunLua) {
    script.run("z = 5");
    EXPECT_EQ((int)script["z"], 5);

    script.run("z = z + 2");
    EXPECT_EQ((int)script["z"], 7);

    script("z = (z * 2) - 1");
    EXPECT_EQ((int)script["z"], 13);
}

int divide(int a, int b) {
    return a / b;
}

int add(int a, int b, int c) {
    return a + b + c;
}

int zaz = 0;

void sum(int a, int b) {
    zaz = a + b;
}

TEST_F(SunScriptTest, CFunctions) {
    // Test Lambda
    auto cat = [](const char *a, const char *b) -> char * {
        char *result = (char *)malloc(strlen(a) + strlen(b) + 1);
        strcpy(result, a);
        strcat(result, b);
        return result;
    };
    std::function<char *(const char *, const char *)> _cat = cat;
    script.registerFunction("cat", _cat);
    std::string x = (std::string)script["cat"]("1 + 2", " = 3");
    EXPECT_EQ(x, "1 + 2 = 3");

    // Test std::function
    std::function<int(int, int, int)> _add = add;
    script.registerFunction("add3", _add);
    script("abs = add3(1, 2, 3)");
    int y = script["abs"];
    EXPECT_EQ(y, 6);

    // Test C Function
    script.registerFunction("divide", &divide);
    int z = script["divide"](30, 5);
    EXPECT_EQ(z, 6);

    // Test Void Function
    script.registerFunction("sum", &sum);
    script["sum"](5, 7);
    EXPECT_EQ(zaz, 12);
}

struct TestClass {
    int x;
    TestClass(int _x) { x = _x; }

    void add(int a) {
        x = x + a;
    }

    void multiply(int a) {
        x = x * a;
    }
};

TEST_F(SunScriptTest, Objects) {
    TestClass test(6);
    script.registerObject("test", &test, "add", &TestClass::add, "multiply", &TestClass::multiply, "x", &TestClass::x);
    EXPECT_EQ((int)script["test"]["x"](), 6);
    EXPECT_EQ(test.x, 6);

    script("test.add(4)");
    EXPECT_EQ((int)script["test"]["x"](), 10);
    EXPECT_EQ(test.x, 10);

    test.multiply(3);
    EXPECT_EQ((int)script["test"]["x"](), 30);
    EXPECT_EQ(test.x, 30);

    script("test.set_x(-6)");
    EXPECT_EQ(test.x, -6);
}

/*TEST_F(SunScriptedNodeTest, Classes) {
    node.registerClass<TestClass, int>("TestClass", "multiply", &TestClass::multiply, "add", &TestClass::add, "x", &TestClass::x);
    node("test = TestClass.new(5)");
    node("z = test:x()");
    int z = node["z"];
    EXPECT_EQ(z, 5);

    node("test:multiply(2)");
    node("z = test:x()");
    z = node["z"];
    EXPECT_EQ(z, 10);

    node("test:add(4)");
    node("z = test:x()");
    z = node["z"];
    EXPECT_EQ(z, 14);
}*/
<commit_msg>Removed debugging stuff<commit_after>// Copyright 2016 Jonathan Buchanan.
// This file is part of Sunglasses, which is licensed under the MIT License.
// See LICENSE.md for details.
#include <gtest/gtest.h>
#include <gmock/gmock.h>

#include <Sunglasses/Sunglasses.hpp>

struct SunScriptTest : ::testing::Test {
    SunScript script;
    SunScriptTest() {
        script.loadFile("src/test_SunScript_0.lua");
        script.loadFile("src/test_SunScript_1.lua");
    }

    ~SunScriptTest() {

    }
};

TEST_F(SunScriptTest, LuaVariables) {
    int x = script.getVariable("x");
    EXPECT_EQ(x, 2);

    double pi = script["pi"];
    EXPECT_DOUBLE_EQ(pi, 3.14);

    bool yes = script.getVariable("yes");
    EXPECT_EQ(yes, true);

    bool no = script.getVariable("no");
    EXPECT_EQ(no, false);

    std::string str = script.getVariable("str");
    EXPECT_EQ(str, "Hello, World!");

    int a = script["table"]["a"];
    EXPECT_EQ(a, 7);

    double b = script.getVariable("table")["b"];
    EXPECT_DOUBLE_EQ(b, 1.23);

    bool c = script.getVariable("table")["c"];
    EXPECT_EQ(c, true);

    bool d = script.getVariable("table")["d"];
    EXPECT_EQ(d, false);

    SunLuaValue e_ = script.getVariable("table");
    EXPECT_EQ((std::string)e_["e"], "Test");

    int r = script["table"]["f"]["r"];
    EXPECT_EQ(r, 1);

    double g = script["table"]["f"]["g"];
    EXPECT_DOUBLE_EQ(g, 0.2);

    double b_ = script["table"]["f"]["b"];
    EXPECT_DOUBLE_EQ(b_, 0.5);

    script["a"] = 23;
    EXPECT_EQ((int)script["a"], 23);

    script["b"] = 3.21;
    EXPECT_DOUBLE_EQ((double)script["b"], 3.21);

    script["c"] = true;
    EXPECT_EQ((bool)script["c"], true);

    script["d"] = false;
    EXPECT_EQ((bool)script["d"], false);

    script["e"] = "Testing";
    EXPECT_EQ((std::string)script["e"], "Testing");

    script["o"].newTable();

    script["o"][1] = -3;
    EXPECT_EQ((int)script["o"][1], -3);

    script["o"][2] = true;
    EXPECT_EQ((bool)script["o"][2], true);

    script["o"][3] = 7.89;
    EXPECT_DOUBLE_EQ((double)script["o"][3], 7.89);

    script["o"][4] = "abc";
    EXPECT_EQ((std::string)script["o"][4], "abc");
}

TEST_F(SunScriptTest, LuaFunctions) {
    int result = script["add"](1, 2);
    EXPECT_EQ(result, 3);

    int add;
    int multiply;
    script["addAndMultiply"](4, 5).assign(add, multiply);
    EXPECT_EQ(add, 9);
    EXPECT_EQ(multiply, 20);
}

TEST_F(SunScriptTest, RunLua) {
    script.run("z = 5");
    EXPECT_EQ((int)script["z"], 5);

    script.run("z = z + 2");
    EXPECT_EQ((int)script["z"], 7);

    script("z = (z * 2) - 1");
    EXPECT_EQ((int)script["z"], 13);
}

int divide(int a, int b) {
    return a / b;
}

int add(int a, int b, int c) {
    return a + b + c;
}

int zaz = 0;

void sum(int a, int b) {
    zaz = a + b;
}

TEST_F(SunScriptTest, CFunctions) {
    // Test Lambda
    auto cat = [](const char *a, const char *b) -> char * {
        char *result = (char *)malloc(strlen(a) + strlen(b) + 1);
        strcpy(result, a);
        strcat(result, b);
        return result;
    };
    std::function<char *(const char *, const char *)> _cat = cat;
    script.registerFunction("cat", _cat);
    std::string x = (std::string)script["cat"]("1 + 2", " = 3");
    EXPECT_EQ(x, "1 + 2 = 3");

    // Test std::function
    std::function<int(int, int, int)> _add = add;
    script.registerFunction("add3", _add);
    script("abs = add3(1, 2, 3)");
    int y = script["abs"];
    EXPECT_EQ(y, 6);

    // Test C Function
    script.registerFunction("divide", &divide);
    int z = script["divide"](30, 5);
    EXPECT_EQ(z, 6);

    // Test Void Function
    script.registerFunction("sum", &sum);
    script["sum"](5, 7);
    EXPECT_EQ(zaz, 12);
}

struct TestClass {
    int x;
    TestClass(int _x) { x = _x; }

    void add(int a) {
        x = x + a;
    }

    void multiply(int a) {
        x = x * a;
    }
};

TEST_F(SunScriptTest, Objects) {
    TestClass test(6);
    script.registerObject("test", &test, "add", &TestClass::add, "multiply", &TestClass::multiply, "x", &TestClass::x);
    EXPECT_EQ((int)script["test"]["x"](), 6);
    EXPECT_EQ(test.x, 6);

    script("test.add(4)");
    EXPECT_EQ((int)script["test"]["x"](), 10);
    EXPECT_EQ(test.x, 10);

    test.multiply(3);
    EXPECT_EQ((int)script["test"]["x"](), 30);
    EXPECT_EQ(test.x, 30);

    script("test.set_x(-6)");
    EXPECT_EQ(test.x, -6);
}

/*TEST_F(SunScriptedNodeTest, Classes) {
    node.registerClass<TestClass, int>("TestClass", "multiply", &TestClass::multiply, "add", &TestClass::add, "x", &TestClass::x);
    node("test = TestClass.new(5)");
    node("z = test:x()");
    int z = node["z"];
    EXPECT_EQ(z, 5);

    node("test:multiply(2)");
    node("z = test:x()");
    z = node["z"];
    EXPECT_EQ(z, 10);

    node("test:add(4)");
    node("z = test:x()");
    z = node["z"];
    EXPECT_EQ(z, 14);
}*/
<|endoftext|>


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

/* This benchmark exists to ensure that the benchmark integration is
 * working */

#include <benchmark/benchmark.h>
#include <grpc/grpc.h>
#include <grpc/support/log.h>
#include <grpcpp/completion_queue.h>
#include <grpcpp/impl/grpc_library.h>
#include "test/cpp/microbenchmarks/helpers.h"
#include "test/cpp/util/test_config.h"

#include "src/core/lib/surface/completion_queue.h"

namespace grpc {
namespace testing {

static void BM_CreateDestroyCpp(benchmark::State& state) {
  TrackCounters track_counters;
  while (state.KeepRunning()) {
    CompletionQueue cq;
  }
  track_counters.Finish(state);
}
BENCHMARK(BM_CreateDestroyCpp);

/* Create cq using a different constructor */
static void BM_CreateDestroyCpp2(benchmark::State& state) {
  TrackCounters track_counters;
  while (state.KeepRunning()) {
    grpc_completion_queue* core_cq =
        grpc_completion_queue_create_for_next(nullptr);
    CompletionQueue cq(core_cq);
  }
  track_counters.Finish(state);
}
BENCHMARK(BM_CreateDestroyCpp2);

static void BM_CreateDestroyCore(benchmark::State& state) {
  TrackCounters track_counters;
  while (state.KeepRunning()) {
    // TODO: sreek Templatize this benchmark and pass completion type and
    // polling type as parameters
    grpc_completion_queue_destroy(
        grpc_completion_queue_create_for_next(nullptr));
  }
  track_counters.Finish(state);
}
BENCHMARK(BM_CreateDestroyCore);

static void DoneWithCompletionOnStack(void* arg,
                                      grpc_cq_completion* completion) {}

class DummyTag final : public internal::CompletionQueueTag {
 public:
  bool FinalizeResult(void** tag, bool* status) override { return true; }
};

static void BM_Pass1Cpp(benchmark::State& state) {
  TrackCounters track_counters;
  CompletionQueue cq;
  grpc_completion_queue* c_cq = cq.cq();
  while (state.KeepRunning()) {
    grpc_cq_completion completion;
    DummyTag dummy_tag;
    grpc_core::ExecCtx exec_ctx;
    GPR_ASSERT(grpc_cq_begin_op(c_cq, &dummy_tag));
    grpc_cq_end_op(c_cq, &dummy_tag, GRPC_ERROR_NONE, DoneWithCompletionOnStack,
                   nullptr, &completion);

    void* tag;
    bool ok;
    cq.Next(&tag, &ok);
  }
  track_counters.Finish(state);
}
BENCHMARK(BM_Pass1Cpp);

static void BM_Pass1Core(benchmark::State& state) {
  TrackCounters track_counters;
  // TODO: sreek Templatize this benchmark and pass polling_type as a param
  grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr);
  gpr_timespec deadline = gpr_inf_future(GPR_CLOCK_MONOTONIC);
  while (state.KeepRunning()) {
    grpc_cq_completion completion;
    grpc_core::ExecCtx exec_ctx;
    GPR_ASSERT(grpc_cq_begin_op(cq, nullptr));
    grpc_cq_end_op(cq, nullptr, GRPC_ERROR_NONE, DoneWithCompletionOnStack,
                   nullptr, &completion);

    grpc_completion_queue_next(cq, deadline, nullptr);
  }
  grpc_completion_queue_destroy(cq);
  track_counters.Finish(state);
}
BENCHMARK(BM_Pass1Core);

static void BM_Pluck1Core(benchmark::State& state) {
  TrackCounters track_counters;
  // TODO: sreek Templatize this benchmark and pass polling_type as a param
  grpc_completion_queue* cq = grpc_completion_queue_create_for_pluck(nullptr);
  gpr_timespec deadline = gpr_inf_future(GPR_CLOCK_MONOTONIC);
  while (state.KeepRunning()) {
    grpc_cq_completion completion;
    grpc_core::ExecCtx exec_ctx;
    GPR_ASSERT(grpc_cq_begin_op(cq, nullptr));
    grpc_cq_end_op(cq, nullptr, GRPC_ERROR_NONE, DoneWithCompletionOnStack,
                   nullptr, &completion);

    grpc_completion_queue_pluck(cq, nullptr, deadline, nullptr);
  }
  grpc_completion_queue_destroy(cq);
  track_counters.Finish(state);
}
BENCHMARK(BM_Pluck1Core);

static void BM_EmptyCore(benchmark::State& state) {
  TrackCounters track_counters;
  // TODO: sreek Templatize this benchmark and pass polling_type as a param
  grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr);
  gpr_timespec deadline = gpr_inf_past(GPR_CLOCK_MONOTONIC);
  while (state.KeepRunning()) {
    grpc_completion_queue_next(cq, deadline, nullptr);
  }
  grpc_completion_queue_destroy(cq);
  track_counters.Finish(state);
}
BENCHMARK(BM_EmptyCore);

// Helper for tests to shutdown correctly and tersely
static void shutdown_and_destroy(grpc_completion_queue* cc) {
  grpc_completion_queue_shutdown(cc);
  grpc_completion_queue_destroy(cc);
}

// Tag completion queue iterate times
class TagCallback : public grpc_experimental_completion_queue_functor {
 public:
  explicit TagCallback(int* iter) : iter_(iter) {
    functor_run = &TagCallback::Run;
  }
  ~TagCallback() {}
  static void Run(grpc_experimental_completion_queue_functor* cb, int ok) {
    GPR_ASSERT(static_cast<bool>(ok));
    *static_cast<TagCallback*>(cb)->iter_ += 1;
  };

 private:
  int* iter_;
};

// Check if completion queue is shut down
class ShutdownCallback : public grpc_experimental_completion_queue_functor {
 public:
  explicit ShutdownCallback(bool* done) : done_(done) {
    functor_run = &ShutdownCallback::Run;
  }
  ~ShutdownCallback() {}
  static void Run(grpc_experimental_completion_queue_functor* cb, int ok) {
    *static_cast<ShutdownCallback*>(cb)->done_ = static_cast<bool>(ok);
  }

 private:
  bool* done_;
};

static void BM_Callback_CQ_Pass1Core(benchmark::State& state) {
  TrackCounters track_counters;
  int iteration = 0;
  TagCallback tag_cb(&iteration);
  bool got_shutdown = false;
  ShutdownCallback shutdown_cb(&got_shutdown);
  grpc_completion_queue* cc =
      grpc_completion_queue_create_for_callback(&shutdown_cb, nullptr);
  while (state.KeepRunning()) {
    grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
    grpc_core::ExecCtx exec_ctx;
    grpc_cq_completion completion;
    GPR_ASSERT(grpc_cq_begin_op(cc, &tag_cb));
    grpc_cq_end_op(cc, &tag_cb, GRPC_ERROR_NONE, DoneWithCompletionOnStack,
                   nullptr, &completion);
  }
  shutdown_and_destroy(cc);
  GPR_ASSERT(got_shutdown);
  GPR_ASSERT(iteration == static_cast<int>(state.iterations()));
  track_counters.Finish(state);
}
BENCHMARK(BM_Callback_CQ_Pass1Core);

}  // namespace testing
}  // namespace grpc

// Some distros have RunSpecifiedBenchmarks under the benchmark namespace,
// and others do not. This allows us to support both modes.
namespace benchmark {
void RunTheBenchmarksNamespaced() { RunSpecifiedBenchmarks(); }
}  // namespace benchmark

int main(int argc, char** argv) {
  LibraryInitializer libInit;
  ::benchmark::Initialize(&argc, argv);
  ::grpc::testing::InitTest(&argc, &argv, false);
  benchmark::RunTheBenchmarksNamespaced();
  return 0;
}
<commit_msg>Add synchronization to bm test<commit_after>/*
 *
 * Copyright 2015 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

/* This benchmark exists to ensure that the benchmark integration is
 * working */

#include <benchmark/benchmark.h>
#include <grpc/grpc.h>
#include <grpc/support/log.h>
#include <grpcpp/completion_queue.h>
#include <grpcpp/impl/grpc_library.h>
#include "test/cpp/microbenchmarks/helpers.h"
#include "test/cpp/util/test_config.h"

#include "src/core/lib/surface/completion_queue.h"

namespace grpc {
namespace testing {

static void BM_CreateDestroyCpp(benchmark::State& state) {
  TrackCounters track_counters;
  while (state.KeepRunning()) {
    CompletionQueue cq;
  }
  track_counters.Finish(state);
}
BENCHMARK(BM_CreateDestroyCpp);

/* Create cq using a different constructor */
static void BM_CreateDestroyCpp2(benchmark::State& state) {
  TrackCounters track_counters;
  while (state.KeepRunning()) {
    grpc_completion_queue* core_cq =
        grpc_completion_queue_create_for_next(nullptr);
    CompletionQueue cq(core_cq);
  }
  track_counters.Finish(state);
}
BENCHMARK(BM_CreateDestroyCpp2);

static void BM_CreateDestroyCore(benchmark::State& state) {
  TrackCounters track_counters;
  while (state.KeepRunning()) {
    // TODO: sreek Templatize this benchmark and pass completion type and
    // polling type as parameters
    grpc_completion_queue_destroy(
        grpc_completion_queue_create_for_next(nullptr));
  }
  track_counters.Finish(state);
}
BENCHMARK(BM_CreateDestroyCore);

static void DoneWithCompletionOnStack(void* arg,
                                      grpc_cq_completion* completion) {}

class DummyTag final : public internal::CompletionQueueTag {
 public:
  bool FinalizeResult(void** tag, bool* status) override { return true; }
};

static void BM_Pass1Cpp(benchmark::State& state) {
  TrackCounters track_counters;
  CompletionQueue cq;
  grpc_completion_queue* c_cq = cq.cq();
  while (state.KeepRunning()) {
    grpc_cq_completion completion;
    DummyTag dummy_tag;
    grpc_core::ExecCtx exec_ctx;
    GPR_ASSERT(grpc_cq_begin_op(c_cq, &dummy_tag));
    grpc_cq_end_op(c_cq, &dummy_tag, GRPC_ERROR_NONE, DoneWithCompletionOnStack,
                   nullptr, &completion);

    void* tag;
    bool ok;
    cq.Next(&tag, &ok);
  }
  track_counters.Finish(state);
}
BENCHMARK(BM_Pass1Cpp);

static void BM_Pass1Core(benchmark::State& state) {
  TrackCounters track_counters;
  // TODO: sreek Templatize this benchmark and pass polling_type as a param
  grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr);
  gpr_timespec deadline = gpr_inf_future(GPR_CLOCK_MONOTONIC);
  while (state.KeepRunning()) {
    grpc_cq_completion completion;
    grpc_core::ExecCtx exec_ctx;
    GPR_ASSERT(grpc_cq_begin_op(cq, nullptr));
    grpc_cq_end_op(cq, nullptr, GRPC_ERROR_NONE, DoneWithCompletionOnStack,
                   nullptr, &completion);

    grpc_completion_queue_next(cq, deadline, nullptr);
  }
  grpc_completion_queue_destroy(cq);
  track_counters.Finish(state);
}
BENCHMARK(BM_Pass1Core);

static void BM_Pluck1Core(benchmark::State& state) {
  TrackCounters track_counters;
  // TODO: sreek Templatize this benchmark and pass polling_type as a param
  grpc_completion_queue* cq = grpc_completion_queue_create_for_pluck(nullptr);
  gpr_timespec deadline = gpr_inf_future(GPR_CLOCK_MONOTONIC);
  while (state.KeepRunning()) {
    grpc_cq_completion completion;
    grpc_core::ExecCtx exec_ctx;
    GPR_ASSERT(grpc_cq_begin_op(cq, nullptr));
    grpc_cq_end_op(cq, nullptr, GRPC_ERROR_NONE, DoneWithCompletionOnStack,
                   nullptr, &completion);

    grpc_completion_queue_pluck(cq, nullptr, deadline, nullptr);
  }
  grpc_completion_queue_destroy(cq);
  track_counters.Finish(state);
}
BENCHMARK(BM_Pluck1Core);

static void BM_EmptyCore(benchmark::State& state) {
  TrackCounters track_counters;
  // TODO: sreek Templatize this benchmark and pass polling_type as a param
  grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr);
  gpr_timespec deadline = gpr_inf_past(GPR_CLOCK_MONOTONIC);
  while (state.KeepRunning()) {
    grpc_completion_queue_next(cq, deadline, nullptr);
  }
  grpc_completion_queue_destroy(cq);
  track_counters.Finish(state);
}
BENCHMARK(BM_EmptyCore);

// Helper for tests to shutdown correctly and tersely
static void shutdown_and_destroy(grpc_completion_queue* cc) {
  grpc_completion_queue_shutdown(cc);
  grpc_completion_queue_destroy(cc);
}

// Tag completion queue iterate times
class TagCallback : public grpc_experimental_completion_queue_functor {
 public:
  explicit TagCallback(int* iter) : iter_(iter) {
    functor_run = &TagCallback::Run;
  }
  ~TagCallback() {}
  static void Run(grpc_experimental_completion_queue_functor* cb, int ok) {
    GPR_ASSERT(static_cast<bool>(ok));
    *static_cast<TagCallback*>(cb)->iter_ += 1;
  };

 private:
  int* iter_;
};

static gpr_mu shutdown_mu;
static gpr_cv shutdown_cv;

// Check if completion queue is shut down
class ShutdownCallback : public grpc_experimental_completion_queue_functor {
 public:
  explicit ShutdownCallback(bool* done) : done_(done) {
    functor_run = &ShutdownCallback::Run;
  }
  ~ShutdownCallback() {}
  static void Run(grpc_experimental_completion_queue_functor* cb, int ok) {
    gpr_mu_lock(&shutdown_mu);
    *static_cast<ShutdownCallback*>(cb)->done_ = static_cast<bool>(ok);
    gpr_cv_signal(&shutdown_cv);
    gpr_mu_unlock(&shutdown_mu);
  }

 private:
  bool* done_;
};

static void BM_Callback_CQ_Pass1Core(benchmark::State& state) {
  TrackCounters track_counters;
  int iteration = 0;
  TagCallback tag_cb(&iteration);
  gpr_mu_init(&shutdown_mu);
  gpr_cv_init(&shutdown_cv);
  bool got_shutdown = false;
  ShutdownCallback shutdown_cb(&got_shutdown);
  grpc_completion_queue* cc =
      grpc_completion_queue_create_for_callback(&shutdown_cb, nullptr);
  while (state.KeepRunning()) {
    grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
    grpc_core::ExecCtx exec_ctx;
    grpc_cq_completion completion;
    GPR_ASSERT(grpc_cq_begin_op(cc, &tag_cb));
    grpc_cq_end_op(cc, &tag_cb, GRPC_ERROR_NONE, DoneWithCompletionOnStack,
                   nullptr, &completion);
  }
  shutdown_and_destroy(cc);

  gpr_mu_lock(&shutdown_mu);
  while (!got_shutdown) {
    // Wait for the shutdown callback to complete.
    gpr_cv_wait(&shutdown_cv, &shutdown_mu,
                gpr_inf_future(GPR_CLOCK_REALTIME));
  }
  gpr_mu_unlock(&shutdown_mu);
  GPR_ASSERT(got_shutdown);
  GPR_ASSERT(iteration == static_cast<int>(state.iterations()));
  track_counters.Finish(state);
  gpr_cv_destroy(&shutdown_cv);
  gpr_mu_destroy(&shutdown_mu);
}
BENCHMARK(BM_Callback_CQ_Pass1Core);

}  // namespace testing
}  // namespace grpc

// Some distros have RunSpecifiedBenchmarks under the benchmark namespace,
// and others do not. This allows us to support both modes.
namespace benchmark {
void RunTheBenchmarksNamespaced() { RunSpecifiedBenchmarks(); }
}  // namespace benchmark

int main(int argc, char** argv) {
  LibraryInitializer libInit;
  ::benchmark::Initialize(&argc, argv);
  ::grpc::testing::InitTest(&argc, &argv, false);
  benchmark::RunTheBenchmarksNamespaced();
  return 0;
}
<|endoftext|>