<commit_before>// Copyright (c) 2016-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 <amount.h>
#include <policy/feerate.h>
#include <test/test_bitcoin.h>

#include <boost/test/unit_test.hpp>

BOOST_FIXTURE_TEST_SUITE(amount_tests, BasicTestingSetup)

BOOST_AUTO_TEST_CASE(MoneyRangeTest)
{
    BOOST_CHECK_EQUAL(MoneyRange(CAmount(-1)), false);
    BOOST_CHECK_EQUAL(MoneyRange(MAX_MONEY + CAmount(1)), false);
    BOOST_CHECK_EQUAL(MoneyRange(CAmount(1)), true);
}

BOOST_AUTO_TEST_CASE(GetFeeTest)
{
    CFeeRate feeRate, altFeeRate;

    feeRate = CFeeRate(0);
    // Must always return 0
    BOOST_CHECK_EQUAL(feeRate.GetFee(0), 0);
    BOOST_CHECK_EQUAL(feeRate.GetFee(1e5), 0);

    feeRate = CFeeRate(1000);
    // Must always just return the arg
    BOOST_CHECK_EQUAL(feeRate.GetFee(0), 0);
    BOOST_CHECK_EQUAL(feeRate.GetFee(1), 1);
    BOOST_CHECK_EQUAL(feeRate.GetFee(121), 121);
    BOOST_CHECK_EQUAL(feeRate.GetFee(999), 999);
    BOOST_CHECK_EQUAL(feeRate.GetFee(1e3), 1e3);
    BOOST_CHECK_EQUAL(feeRate.GetFee(9e3), 9e3);

    feeRate = CFeeRate(-1000);
    // Must always just return -1 * arg
    BOOST_CHECK_EQUAL(feeRate.GetFee(0), 0);
    BOOST_CHECK_EQUAL(feeRate.GetFee(1), -1);
    BOOST_CHECK_EQUAL(feeRate.GetFee(121), -121);
    BOOST_CHECK_EQUAL(feeRate.GetFee(999), -999);
    BOOST_CHECK_EQUAL(feeRate.GetFee(1e3), -1e3);
    BOOST_CHECK_EQUAL(feeRate.GetFee(9e3), -9e3);

    feeRate = CFeeRate(123);
    // Truncates the result, if not integer
    BOOST_CHECK_EQUAL(feeRate.GetFee(0), 0);
    BOOST_CHECK_EQUAL(feeRate.GetFee(8), 1); // Special case: returns 1 instead of 0
    BOOST_CHECK_EQUAL(feeRate.GetFee(9), 1);
    BOOST_CHECK_EQUAL(feeRate.GetFee(121), 14);
    BOOST_CHECK_EQUAL(feeRate.GetFee(122), 15);
    BOOST_CHECK_EQUAL(feeRate.GetFee(999), 122);
    BOOST_CHECK_EQUAL(feeRate.GetFee(1e3), 123);
    BOOST_CHECK_EQUAL(feeRate.GetFee(9e3), 1107);

    feeRate = CFeeRate(-123);
    // Truncates the result, if not integer
    BOOST_CHECK_EQUAL(feeRate.GetFee(0), 0);
    BOOST_CHECK_EQUAL(feeRate.GetFee(8), -1); // Special case: returns -1 instead of 0
    BOOST_CHECK_EQUAL(feeRate.GetFee(9), -1);

    // check alternate constructor
    feeRate = CFeeRate(1000);
    altFeeRate = CFeeRate(feeRate);
    BOOST_CHECK_EQUAL(feeRate.GetFee(100), altFeeRate.GetFee(100));

    // Check full constructor
    // default value
    BOOST_CHECK(CFeeRate(CAmount(-1), 1000) == CFeeRate(-1));
    BOOST_CHECK(CFeeRate(CAmount(0), 1000) == CFeeRate(0));
    BOOST_CHECK(CFeeRate(CAmount(1), 1000) == CFeeRate(1));
    // lost precision (can only resolve satoshis per kB)
    BOOST_CHECK(CFeeRate(CAmount(1), 1001) == CFeeRate(0));
    BOOST_CHECK(CFeeRate(CAmount(2), 1001) == CFeeRate(1));
    // some more integer checks
    BOOST_CHECK(CFeeRate(CAmount(26), 789) == CFeeRate(32));
    BOOST_CHECK(CFeeRate(CAmount(27), 789) == CFeeRate(34));
    // Maximum size in bytes, should not crash
    CFeeRate(MAX_MONEY, std::numeric_limits<size_t>::max() >> 1).GetFeePerK();
}

BOOST_AUTO_TEST_CASE(BinaryOperatorTest)
{
    CFeeRate a, b;
    a = CFeeRate(1);
    b = CFeeRate(2);
    BOOST_CHECK(a < b);
    BOOST_CHECK(b > a);
    BOOST_CHECK(a == a);
    BOOST_CHECK(a <= b);
    BOOST_CHECK(a <= a);
    BOOST_CHECK(b >= a);
    BOOST_CHECK(b >= b);
    // a should be 0.00000002 BTC/kB now
    a += a;
    BOOST_CHECK(a == b);
}

BOOST_AUTO_TEST_CASE(ToStringTest)
{
    CFeeRate feeRate;
    feeRate = CFeeRate(1);
    BOOST_CHECK_EQUAL(feeRate.ToString(), "0.00000001 LTC/kB");
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Fix fee amount test. Adapt to change feerate policy according to: https://github.com/deeponion/deeponion/commit/fb6899cbc9aa5e6d6ccb5a6c3fe65dcfeecfc4a1#diff-51f643b7317a098f9241456eb3873fce<commit_after>// Copyright (c) 2016-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 <amount.h>
#include <policy/feerate.h>
#include <test/test_bitcoin.h>

#include <boost/test/unit_test.hpp>

BOOST_FIXTURE_TEST_SUITE(amount_tests, BasicTestingSetup)

BOOST_AUTO_TEST_CASE(MoneyRangeTest)
{
    BOOST_CHECK_EQUAL(MoneyRange(CAmount(-1)), false);
    BOOST_CHECK_EQUAL(MoneyRange(CAmount(0)), true);
    BOOST_CHECK_EQUAL(MoneyRange(CAmount(1)), true);
    BOOST_CHECK_EQUAL(MoneyRange(MAX_MONEY), true);
    BOOST_CHECK_EQUAL(MoneyRange(MAX_MONEY + CAmount(1)), false);
}

BOOST_AUTO_TEST_CASE(GetFeeTest)
{
    CFeeRate feeRate, altFeeRate;

    feeRate = CFeeRate(0);
    // Must always return 0
    BOOST_CHECK_EQUAL(feeRate.GetFee(0), CAmount(0));
    BOOST_CHECK_EQUAL(feeRate.GetFee(1e5), CAmount(0));

    feeRate = CFeeRate(1000);
    // Must always just return the arg
    BOOST_CHECK_EQUAL(feeRate.GetFee(0), CAmount(0));
    BOOST_CHECK_EQUAL(feeRate.GetFee(1), CAmount(1000));
    BOOST_CHECK_EQUAL(feeRate.GetFee(121), CAmount(1000));
    BOOST_CHECK_EQUAL(feeRate.GetFee(999), CAmount(1000));
    BOOST_CHECK_EQUAL(feeRate.GetFee(1e3), CAmount(2000));
    BOOST_CHECK_EQUAL(feeRate.GetFee(9e3), CAmount(10000));

    feeRate = CFeeRate(-1000);
    // Must always just return -1 * arg
    BOOST_CHECK_EQUAL(feeRate.GetFee(0), CAmount(0));
    BOOST_CHECK_EQUAL(feeRate.GetFee(1), CAmount(-1000));
    BOOST_CHECK_EQUAL(feeRate.GetFee(121), CAmount(-1000));
    BOOST_CHECK_EQUAL(feeRate.GetFee(999), CAmount(-1000));
    BOOST_CHECK_EQUAL(feeRate.GetFee(1e3), CAmount(-2000));
    BOOST_CHECK_EQUAL(feeRate.GetFee(9e3), CAmount(-10000));

    feeRate = CFeeRate(123);
    // Truncates the result, if not integer
    BOOST_CHECK_EQUAL(feeRate.GetFee(0), CAmount(0));
    BOOST_CHECK_EQUAL(feeRate.GetFee(8), CAmount(123)); // Special case: returns 1 instead of 0
    BOOST_CHECK_EQUAL(feeRate.GetFee(9), CAmount(123));
    BOOST_CHECK_EQUAL(feeRate.GetFee(121), CAmount(123));
    BOOST_CHECK_EQUAL(feeRate.GetFee(122), CAmount(123));
    BOOST_CHECK_EQUAL(feeRate.GetFee(999), CAmount(123));
    BOOST_CHECK_EQUAL(feeRate.GetFee(1e3), CAmount(246));
    BOOST_CHECK_EQUAL(feeRate.GetFee(9e3), CAmount(1230));

    feeRate = CFeeRate(-123);
    // Truncates the result, if not integer
    BOOST_CHECK_EQUAL(feeRate.GetFee(0), CAmount(0));
    BOOST_CHECK_EQUAL(feeRate.GetFee(8), CAmount(-123)); // Special case: returns -1 instead of 0
    BOOST_CHECK_EQUAL(feeRate.GetFee(9), CAmount(-123));

    // check alternate constructor
    feeRate = CFeeRate(1000);
    altFeeRate = CFeeRate(feeRate);
    BOOST_CHECK_EQUAL(feeRate.GetFee(100), altFeeRate.GetFee(100));

    // Check full constructor
    BOOST_CHECK(CFeeRate(CAmount(-1), 0) == CFeeRate(0));
    BOOST_CHECK(CFeeRate(CAmount(0), 0) == CFeeRate(0));
    BOOST_CHECK(CFeeRate(CAmount(1), 0) == CFeeRate(0));
    // default value
    BOOST_CHECK(CFeeRate(CAmount(-1), 1000) == CFeeRate(-1));
    BOOST_CHECK(CFeeRate(CAmount(0), 1000) == CFeeRate(0));
    BOOST_CHECK(CFeeRate(CAmount(1), 1000) == CFeeRate(1));
    // lost precision (can only resolve satoshis per kB)
    BOOST_CHECK(CFeeRate(CAmount(1), 1001) == CFeeRate(0));
    BOOST_CHECK(CFeeRate(CAmount(2), 1001) == CFeeRate(1));
    // some more integer checks
    BOOST_CHECK(CFeeRate(CAmount(26), 789) == CFeeRate(32));
    BOOST_CHECK(CFeeRate(CAmount(27), 789) == CFeeRate(34));
    // Maximum size in bytes, should not crash
    CFeeRate(MAX_MONEY, std::numeric_limits<size_t>::max() >> 1).GetFeePerK();
}

BOOST_AUTO_TEST_CASE(BinaryOperatorTest)
{
    CFeeRate a, b;
    a = CFeeRate(1);
    b = CFeeRate(2);
    BOOST_CHECK(a < b);
    BOOST_CHECK(b > a);
    BOOST_CHECK(a == a);
    BOOST_CHECK(a <= b);
    BOOST_CHECK(a <= a);
    BOOST_CHECK(b >= a);
    BOOST_CHECK(b >= b);
    // a should be 0.00000002 BTC/kB now
    a += a;
    BOOST_CHECK(a == b);
}

BOOST_AUTO_TEST_CASE(ToStringTest)
{
    CFeeRate feeRate;
    feeRate = CFeeRate(1);
    BOOST_CHECK_EQUAL(feeRate.ToString(), "0.00000001 ONION/kB");
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>/* This file is part of Zanshin Todo.

   Copyright 2008-2011 Mario Bensi <nef@ipsquad.net>

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 of
   the License or (at your option) version 3 or any later version
   accepted by the membership of KDE e.V. (or its successor approved
   by the membership of KDE e.V.), which shall act as a proxy
   defined in Section 14 of version 3 of the license.

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

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
   USA.
*/

#include "todometadatamodel.h"

#include <KDE/KCalCore/Todo>

#include <KDebug>
#include <KIcon>
#include <KLocale>

#include "globaldefs.h"

TodoMetadataModel::TodoMetadataModel(QObject *parent)
    : KIdentityProxyModel(parent)
{
    connect(this, SIGNAL(rowsInserted(QModelIndex,int,int)),
            this, SLOT(onSourceInsertRows(QModelIndex,int,int)));
    connect(this, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
            this, SLOT(onSourceRemoveRows(QModelIndex,int,int)));
    connect(this, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
            this, SLOT(onSourceDataChanged(QModelIndex,QModelIndex)));

    onSourceInsertRows(QModelIndex(), 0, rowCount()-1);
}

TodoMetadataModel::~TodoMetadataModel()
{
}

Qt::ItemFlags TodoMetadataModel::flags(const QModelIndex &index) const
{
    if (!sourceModel()) {
        return Qt::NoItemFlags;
    }

    Qt::ItemFlags flags = sourceModel()->flags(mapToSource(index));

    if (index.isValid()) {
        Zanshin::ItemType type = (Zanshin::ItemType)index.data(Zanshin::ItemTypeRole).toInt();
        if (index.column()==0) {
            Akonadi::Item item = index.data(Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>();
            if (item.isValid() && type==Zanshin::StandardTodo) {
                flags|= Qt::ItemIsUserCheckable;
            }
        } else if (index.column()==4) {
            flags&= ~Qt::ItemIsEditable;
        }

        if (type==Zanshin::Collection) {
            flags&= ~Qt::ItemIsEditable;
            flags&= ~Qt::ItemIsDragEnabled;
        }
    }

    return flags;
}

QVariant TodoMetadataModel::data(const QModelIndex &index, int role) const
{
    if (!sourceModel()) {
        return QVariant();
    }

    Akonadi::Item item = sourceModel()->data(mapToSource(index), Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>();

    if (!item.isValid() || !item.hasPayload<KCalCore::Todo::Ptr>()) {
        if (role==Zanshin::ItemTypeRole) {
            Akonadi::Collection collection = sourceModel()->data(mapToSource(index), Akonadi::EntityTreeModel::CollectionRole).value<Akonadi::Collection>();
            if (collection.isValid()) {
                return Zanshin::Collection;
            }
        }
        return KIdentityProxyModel::data(index, role);
    }

    switch (role) {
    case Qt::CheckStateRole:
        if (index.column()==0 && itemTypeFromItem(item)==Zanshin::StandardTodo) {
            return todoFromItem(item)->isCompleted() ? Qt::Checked : Qt::Unchecked;
        } else {
            return QVariant();
        }
    case Qt::DecorationRole:
        if (index.column()==0 && itemTypeFromItem(item)==Zanshin::ProjectTodo) {
            return KIcon("view-pim-tasks");
        } else {
            return KIdentityProxyModel::data(index, role);
        }
    case Zanshin::UidRole:
        return uidFromItem(item);
    case Zanshin::ParentUidRole:
        return relatedUidFromItem(item);
    case Zanshin::AncestorsUidRole:
        return ancestorsUidFromItem(item);
    case Zanshin::ItemTypeRole:
        return itemTypeFromItem(item);
    case Zanshin::CategoriesRole:
        return categoriesFromItem(item);
    case Zanshin::AncestorsCategoriesRole:
        return ancestorsCategoriesFromItem(item);
    case Zanshin::DataTypeRole:
        switch (index.column()) {
            case 1 :
                return Zanshin::ProjectType;
            case 2 :
                return Zanshin::CategoryType;
            default:
                return Zanshin::StandardType;
        }
    case Zanshin::ChildUidsRole:
        return childUidsFromItem(item);
    case Zanshin::ChildIndexesRole:
        return QVariant::fromValue(childIndexesFromIndex(index));
    default:
        return KIdentityProxyModel::data(index, role);
    }
    return KIdentityProxyModel::data(index, role);
}

void TodoMetadataModel::onSourceInsertRows(const QModelIndex &parent, int begin, int end)
{
    for (int i = begin; i <= end; i++) {
        QModelIndex child = index(i, 0, parent);
        onSourceInsertRows(child, 0, rowCount(child)-1);

        KCalCore::Todo::Ptr todo = todoFromIndex(child);

        if (!todo) {
            continue;
        }

        QString uid = todo->uid();

        m_indexMap[uid] = child;

        QString relatedUid = todo->relatedTo();

        if (relatedUid.isEmpty()) {
            continue;
        }

        m_parentMap[uid] = relatedUid;
        m_childrenMap[relatedUid] << uid;

        // Emit dataChanged to notify that the todo is a project todo
        QModelIndex parentIndex = m_indexMap[relatedUid];
        if (parentIndex.data(Zanshin::ItemTypeRole).toInt()==Zanshin::ProjectTodo
         && m_childrenMap[relatedUid].size() == 1) {
            emit dataChanged(parentIndex, parentIndex);
        }

    }
}

void TodoMetadataModel::onSourceRemoveRows(const QModelIndex &parent, int begin, int end)
{
    for (int i = begin; i <= end; ++i) {
        QModelIndex child = index(i, 0, parent);

        cleanupDataForSourceIndex(child);
    }
}

void TodoMetadataModel::onSourceDataChanged(const QModelIndex &begin, const QModelIndex &end)
{
    for (int row = begin.row(); row <= end.row(); ++row) {
        for (int column = begin.column(); column <= end.column(); ++column) {
            QModelIndex child = index(row, column, begin.parent());
            KCalCore::Todo::Ptr todo = todoFromIndex(child);

            if (!todo) {
                continue;
            }

            QString uid = todo->uid();

            QString newRelatedUid = todo->relatedTo();
            QString oldRelatedUid;
            if (m_parentMap.contains(uid)) {
                oldRelatedUid = m_parentMap[uid];
            }

            if (newRelatedUid!=oldRelatedUid) {
                if (newRelatedUid.isEmpty()) {
                    m_parentMap.remove(uid);
                } else {
                    m_parentMap[uid] = newRelatedUid;
                    m_childrenMap[newRelatedUid] << uid;
                }
                m_childrenMap[oldRelatedUid].removeAll(uid);
            }

            if (child.data(Zanshin::ItemTypeRole).toInt()==Zanshin::ProjectTodo) {
                foreach (const QModelIndex &index, childIndexesFromIndex(child)) {
                    emit dataChanged(index, index);
                }
            }
        }
    }
}

void TodoMetadataModel::cleanupDataForSourceIndex(const QModelIndex &index)
{
    for (int row=0; row<rowCount(index); row++) {
        QModelIndex child = this->index(row, 0, index);
        cleanupDataForSourceIndex(child);
    }

    KCalCore::Todo::Ptr todo = todoFromIndex(index);

    if (!todo) {
        return;
    }

    QString uid = todo->uid();

    QString relatedUid = todo->relatedTo();

    QModelIndex parentIndex = m_indexMap[relatedUid];
    Zanshin::ItemType parentType = (Zanshin::ItemType)parentIndex.data(Zanshin::ItemTypeRole).toInt();

    m_parentMap.remove(uid);
    m_childrenMap[relatedUid].removeAll(uid);
    m_indexMap.remove(uid);

    if (parentType==Zanshin::ProjectTodo
     && parentIndex.data(Zanshin::ItemTypeRole).toInt()!=parentType) {
        emit dataChanged(parentIndex, parentIndex);
    }
}

KCalCore::Todo::Ptr TodoMetadataModel::todoFromIndex(const QModelIndex &index) const
{
    Akonadi::Item item = sourceModel()->data(mapToSource(index), Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>();
    return todoFromItem(item);
}

KCalCore::Todo::Ptr TodoMetadataModel::todoFromItem(const Akonadi::Item &item) const
{
    if (!item.isValid() || !item.hasPayload<KCalCore::Todo::Ptr>()) {
        return KCalCore::Todo::Ptr();
    } else {
        return item.payload<KCalCore::Todo::Ptr>();
    }
}

Zanshin::ItemType TodoMetadataModel::itemTypeFromItem(const Akonadi::Item &item) const
{
    KCalCore::Todo::Ptr todo = todoFromItem(item);

    QStringList comments = todo->comments();
    if (comments.contains("X-Zanshin-Project")
     || m_childrenMap[todo->uid()].count()>0) {
        return Zanshin::ProjectTodo;
    } else {
        return Zanshin::StandardTodo;
    }
}

QString TodoMetadataModel::uidFromItem(const Akonadi::Item &item) const
{
    KCalCore::Todo::Ptr todo = todoFromItem(item);
    if (todo) {
        return todo->uid();
    } else {
        return QString();
    }
}

QString TodoMetadataModel::relatedUidFromItem(const Akonadi::Item &item) const
{
    KCalCore::Todo::Ptr todo = todoFromItem(item);
    if (todo) {
        return todo->relatedTo();
    } else {
        return QString();
    }
}

QStringList TodoMetadataModel::ancestorsUidFromItem(const Akonadi::Item &item) const
{
    QStringList result;
    KCalCore::Todo::Ptr todo = todoFromItem(item);

    if (todo) {
        QString id = todo->uid();
        while (m_parentMap.contains(id)) {
            const QString parentId = m_parentMap[id];
            Q_ASSERT(!parentId.isEmpty());
            result << parentId;
            id = parentId;
        }
    }

    return result;
}

QStringList TodoMetadataModel::ancestorsCategoriesFromItem(const Akonadi::Item &item) const
{
    QStringList ancestors = ancestorsUidFromItem(item);
    QStringList categories;
    foreach (QString uid, ancestors) {
        const QModelIndex &index = m_indexMap[uid];
        KCalCore::Todo::Ptr todo = todoFromIndex(index);
        if (todo) {
            categories << todo->categories();
        }
    }
    categories.removeDuplicates();
    return categories;
}

QStringList TodoMetadataModel::categoriesFromItem(const Akonadi::Item &item) const
{
    QStringList categories = ancestorsCategoriesFromItem(item);
    KCalCore::Todo::Ptr todo = todoFromItem(item);
    if (todo) {
        categories << todo->categories();
    }
    categories.removeDuplicates();
    return categories;
}

QStringList TodoMetadataModel::childUidsFromItem(const Akonadi::Item &item) const
{
    KCalCore::Todo::Ptr todo = todoFromItem(item);
    if (todo) {
        return m_childrenMap[todo->uid()];
    } else {
        return QStringList();
    }
}

QModelIndexList TodoMetadataModel::childIndexesFromIndex(const QModelIndex &idx) const
{
    QModelIndexList indexes;
    KCalCore::Todo::Ptr todo = todoFromIndex(idx);
    if (!todo) {
        return indexes;
    }
    QString parent = todo->uid();
    for (int i = 0; i < rowCount(idx.parent()); ++i) {
        QModelIndex child = index(i, idx.column(), idx.parent());
        todo = todoFromIndex(child);
        if (!todo) {
            continue;
        }
        if (m_parentMap[todo->uid()] == parent) {
            indexes << child;
        }
    }
    return indexes;
}

void TodoMetadataModel::setSourceModel(QAbstractItemModel *model)
{
    KIdentityProxyModel::setSourceModel(model);

    onSourceInsertRows(QModelIndex(), 0, rowCount() - 1);
}
<commit_msg>Prevent the default insertion with a default value in hashMap<commit_after>/* This file is part of Zanshin Todo.

   Copyright 2008-2011 Mario Bensi <nef@ipsquad.net>

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 of
   the License or (at your option) version 3 or any later version
   accepted by the membership of KDE e.V. (or its successor approved
   by the membership of KDE e.V.), which shall act as a proxy
   defined in Section 14 of version 3 of the license.

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

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
   USA.
*/

#include "todometadatamodel.h"

#include <KDE/KCalCore/Todo>

#include <KDebug>
#include <KIcon>
#include <KLocale>

#include "globaldefs.h"

TodoMetadataModel::TodoMetadataModel(QObject *parent)
    : KIdentityProxyModel(parent)
{
    connect(this, SIGNAL(rowsInserted(QModelIndex,int,int)),
            this, SLOT(onSourceInsertRows(QModelIndex,int,int)));
    connect(this, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
            this, SLOT(onSourceRemoveRows(QModelIndex,int,int)));
    connect(this, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
            this, SLOT(onSourceDataChanged(QModelIndex,QModelIndex)));

    onSourceInsertRows(QModelIndex(), 0, rowCount()-1);
}

TodoMetadataModel::~TodoMetadataModel()
{
}

Qt::ItemFlags TodoMetadataModel::flags(const QModelIndex &index) const
{
    if (!sourceModel()) {
        return Qt::NoItemFlags;
    }

    Qt::ItemFlags flags = sourceModel()->flags(mapToSource(index));

    if (index.isValid()) {
        Zanshin::ItemType type = (Zanshin::ItemType)index.data(Zanshin::ItemTypeRole).toInt();
        if (index.column()==0) {
            Akonadi::Item item = index.data(Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>();
            if (item.isValid() && type==Zanshin::StandardTodo) {
                flags|= Qt::ItemIsUserCheckable;
            }
        } else if (index.column()==4) {
            flags&= ~Qt::ItemIsEditable;
        }

        if (type==Zanshin::Collection) {
            flags&= ~Qt::ItemIsEditable;
            flags&= ~Qt::ItemIsDragEnabled;
        }
    }

    return flags;
}

QVariant TodoMetadataModel::data(const QModelIndex &index, int role) const
{
    if (!sourceModel()) {
        return QVariant();
    }

    Akonadi::Item item = sourceModel()->data(mapToSource(index), Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>();

    if (!item.isValid() || !item.hasPayload<KCalCore::Todo::Ptr>()) {
        if (role==Zanshin::ItemTypeRole) {
            Akonadi::Collection collection = sourceModel()->data(mapToSource(index), Akonadi::EntityTreeModel::CollectionRole).value<Akonadi::Collection>();
            if (collection.isValid()) {
                return Zanshin::Collection;
            }
        }
        return KIdentityProxyModel::data(index, role);
    }

    switch (role) {
    case Qt::CheckStateRole:
        if (index.column()==0 && itemTypeFromItem(item)==Zanshin::StandardTodo) {
            return todoFromItem(item)->isCompleted() ? Qt::Checked : Qt::Unchecked;
        } else {
            return QVariant();
        }
    case Qt::DecorationRole:
        if (index.column()==0 && itemTypeFromItem(item)==Zanshin::ProjectTodo) {
            return KIcon("view-pim-tasks");
        } else {
            return KIdentityProxyModel::data(index, role);
        }
    case Zanshin::UidRole:
        return uidFromItem(item);
    case Zanshin::ParentUidRole:
        return relatedUidFromItem(item);
    case Zanshin::AncestorsUidRole:
        return ancestorsUidFromItem(item);
    case Zanshin::ItemTypeRole:
        return itemTypeFromItem(item);
    case Zanshin::CategoriesRole:
        return categoriesFromItem(item);
    case Zanshin::AncestorsCategoriesRole:
        return ancestorsCategoriesFromItem(item);
    case Zanshin::DataTypeRole:
        switch (index.column()) {
            case 1 :
                return Zanshin::ProjectType;
            case 2 :
                return Zanshin::CategoryType;
            default:
                return Zanshin::StandardType;
        }
    case Zanshin::ChildUidsRole:
        return childUidsFromItem(item);
    case Zanshin::ChildIndexesRole:
        return QVariant::fromValue(childIndexesFromIndex(index));
    default:
        return KIdentityProxyModel::data(index, role);
    }
    return KIdentityProxyModel::data(index, role);
}

void TodoMetadataModel::onSourceInsertRows(const QModelIndex &parent, int begin, int end)
{
    for (int i = begin; i <= end; i++) {
        QModelIndex child = index(i, 0, parent);
        onSourceInsertRows(child, 0, rowCount(child)-1);

        KCalCore::Todo::Ptr todo = todoFromIndex(child);

        if (!todo) {
            continue;
        }

        QString uid = todo->uid();

        m_indexMap[uid] = child;

        QString relatedUid = todo->relatedTo();

        if (relatedUid.isEmpty()) {
            continue;
        }

        m_parentMap[uid] = relatedUid;
        m_childrenMap[relatedUid] << uid;

        if (!m_indexMap.contains(relatedUid)) {
            continue;
        }

        // Emit dataChanged to notify that the todo is a project todo
        QModelIndex parentIndex = m_indexMap[relatedUid];
        if (parentIndex.data(Zanshin::ItemTypeRole).toInt()==Zanshin::ProjectTodo
         && m_childrenMap[relatedUid].size() == 1) {
            emit dataChanged(parentIndex, parentIndex);
        }

    }
}

void TodoMetadataModel::onSourceRemoveRows(const QModelIndex &parent, int begin, int end)
{
    for (int i = begin; i <= end; ++i) {
        QModelIndex child = index(i, 0, parent);

        cleanupDataForSourceIndex(child);
    }
}

void TodoMetadataModel::onSourceDataChanged(const QModelIndex &begin, const QModelIndex &end)
{
    for (int row = begin.row(); row <= end.row(); ++row) {
        for (int column = begin.column(); column <= end.column(); ++column) {
            QModelIndex child = index(row, column, begin.parent());
            KCalCore::Todo::Ptr todo = todoFromIndex(child);

            if (!todo) {
                continue;
            }

            QString uid = todo->uid();

            QString newRelatedUid = todo->relatedTo();
            QString oldRelatedUid;
            if (m_parentMap.contains(uid)) {
                oldRelatedUid = m_parentMap[uid];
            }

            if (newRelatedUid!=oldRelatedUid) {
                if (newRelatedUid.isEmpty()) {
                    m_parentMap.remove(uid);
                } else {
                    m_parentMap[uid] = newRelatedUid;
                    m_childrenMap[newRelatedUid] << uid;
                }
                m_childrenMap[oldRelatedUid].removeAll(uid);
            }

            if (child.data(Zanshin::ItemTypeRole).toInt()==Zanshin::ProjectTodo) {
                foreach (const QModelIndex &index, childIndexesFromIndex(child)) {
                    emit dataChanged(index, index);
                }
            }
        }
    }
}

void TodoMetadataModel::cleanupDataForSourceIndex(const QModelIndex &index)
{
    for (int row=0; row<rowCount(index); row++) {
        QModelIndex child = this->index(row, 0, index);
        cleanupDataForSourceIndex(child);
    }

    KCalCore::Todo::Ptr todo = todoFromIndex(index);

    if (!todo) {
        return;
    }

    QString uid = todo->uid();

    QString relatedUid = todo->relatedTo();

    QModelIndex parentIndex = m_indexMap[relatedUid];
    Zanshin::ItemType parentType = (Zanshin::ItemType)parentIndex.data(Zanshin::ItemTypeRole).toInt();

    m_parentMap.remove(uid);
    m_childrenMap[relatedUid].removeAll(uid);
    m_indexMap.remove(uid);

    if (parentType==Zanshin::ProjectTodo
     && parentIndex.data(Zanshin::ItemTypeRole).toInt()!=parentType) {
        emit dataChanged(parentIndex, parentIndex);
    }
}

KCalCore::Todo::Ptr TodoMetadataModel::todoFromIndex(const QModelIndex &index) const
{
    Akonadi::Item item = sourceModel()->data(mapToSource(index), Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>();
    return todoFromItem(item);
}

KCalCore::Todo::Ptr TodoMetadataModel::todoFromItem(const Akonadi::Item &item) const
{
    if (!item.isValid() || !item.hasPayload<KCalCore::Todo::Ptr>()) {
        return KCalCore::Todo::Ptr();
    } else {
        return item.payload<KCalCore::Todo::Ptr>();
    }
}

Zanshin::ItemType TodoMetadataModel::itemTypeFromItem(const Akonadi::Item &item) const
{
    KCalCore::Todo::Ptr todo = todoFromItem(item);

    QStringList comments = todo->comments();
    const int childCount = m_childrenMap.contains(todo->uid()) ? m_childrenMap[todo->uid()].count() : 0;
    if (comments.contains("X-Zanshin-Project")
     || childCount>0) {
        return Zanshin::ProjectTodo;
    } else {
        return Zanshin::StandardTodo;
    }
}

QString TodoMetadataModel::uidFromItem(const Akonadi::Item &item) const
{
    KCalCore::Todo::Ptr todo = todoFromItem(item);
    if (todo) {
        return todo->uid();
    } else {
        return QString();
    }
}

QString TodoMetadataModel::relatedUidFromItem(const Akonadi::Item &item) const
{
    KCalCore::Todo::Ptr todo = todoFromItem(item);
    if (todo) {
        return todo->relatedTo();
    } else {
        return QString();
    }
}

QStringList TodoMetadataModel::ancestorsUidFromItem(const Akonadi::Item &item) const
{
    QStringList result;
    KCalCore::Todo::Ptr todo = todoFromItem(item);

    if (todo) {
        QString id = todo->uid();
        while (m_parentMap.contains(id)) {
            const QString parentId = m_parentMap[id];
            Q_ASSERT(!parentId.isEmpty());
            result << parentId;
            id = parentId;
        }
    }

    return result;
}

QStringList TodoMetadataModel::ancestorsCategoriesFromItem(const Akonadi::Item &item) const
{
    QStringList ancestors = ancestorsUidFromItem(item);
    QStringList categories;
    foreach (QString uid, ancestors) {
        if (!m_indexMap.contains(uid)) {
            continue;
        }
        const QModelIndex &index = m_indexMap[uid];
        KCalCore::Todo::Ptr todo = todoFromIndex(index);
        if (todo) {
            categories << todo->categories();
        }
    }
    categories.removeDuplicates();
    return categories;
}

QStringList TodoMetadataModel::categoriesFromItem(const Akonadi::Item &item) const
{
    QStringList categories = ancestorsCategoriesFromItem(item);
    KCalCore::Todo::Ptr todo = todoFromItem(item);
    if (todo) {
        categories << todo->categories();
    }
    categories.removeDuplicates();
    return categories;
}

QStringList TodoMetadataModel::childUidsFromItem(const Akonadi::Item &item) const
{
    KCalCore::Todo::Ptr todo = todoFromItem(item);
    if (todo) {
        return m_childrenMap[todo->uid()];
    } else {
        return QStringList();
    }
}

QModelIndexList TodoMetadataModel::childIndexesFromIndex(const QModelIndex &idx) const
{
    QModelIndexList indexes;
    KCalCore::Todo::Ptr todo = todoFromIndex(idx);
    if (!todo) {
        return indexes;
    }
    QString parent = todo->uid();
    for (int i = 0; i < rowCount(idx.parent()); ++i) {
        QModelIndex child = index(i, idx.column(), idx.parent());
        todo = todoFromIndex(child);
        if (!todo) {
            continue;
        }
        if (m_parentMap[todo->uid()] == parent) {
            indexes << child;
        }
    }
    return indexes;
}

void TodoMetadataModel::setSourceModel(QAbstractItemModel *model)
{
    KIdentityProxyModel::setSourceModel(model);

    onSourceInsertRows(QModelIndex(), 0, rowCount() - 1);
}
<|endoftext|>


<commit_before>#include "unittest/gtest.hpp"
#include "unittest/server_test_helper.hpp"
#include "unittest/unittest_utils.hpp"
#include "buffer_cache/blob.hpp"

namespace unittest {

struct blob_tester_t : public server_test_helper_t {
protected:
    void run_tests(cache_t *cache) {
        small_value_test(cache);
    }

private:
    void small_value_test(cache_t *cache) {
        block_size_t block_size = cache->get_block_size();

        transaction_t txn(cache, rwi_write, 0, repli_timestamp_t::distant_past);

        char buf[251] = { 0 };

        blob_t blob(block_size, buf, 251);
        {
            ASSERT_EQ(0, blob.valuesize());
            ASSERT_EQ(1, blob.refsize(block_size));

            buffer_group_t bg;
            blob_acq_t bacq;
            blob.expose_region(&txn, rwi_write, 0, 0, &bg, &bacq);

            ASSERT_EQ(0, bg.get_size());
            ASSERT_EQ(0, bg.num_buffers());
        }

        blob.append_region(&txn, 1);
        {
            ASSERT_EQ(1, blob.valuesize());
            ASSERT_EQ(2, blob.refsize(block_size));

            buffer_group_t bg;
            blob_acq_t bacq;
            blob.expose_region(&txn, rwi_write, 0, 1, &bg, &bacq);

            ASSERT_EQ(1, bg.get_size());
            ASSERT_EQ(1, bg.num_buffers());
            ASSERT_EQ(1, bg.get_size());
        }
    }
};

TEST(BlobTest, all_tests) {
    blob_tester_t().run();
}

}  // namespace unittest
<commit_msg>Added blob_tracker_t for unit testing purposes.<commit_after>#include "unittest/gtest.hpp"
#include "unittest/server_test_helper.hpp"
#include "unittest/unittest_utils.hpp"
#include "buffer_cache/blob.hpp"

namespace unittest {

class blob_tracker_t {
public:
    blob_tracker_t(block_size_t block_size, size_t maxreflen)
        : expected_("\0"), blob_(block_size, expected_.c_str(), maxreflen) {
        // That's a bit of a hack, because blob_ will only read the
        // first byte or first two bytes if they are zero.
        expected_.clear();
    }

    void check_region(transaction_t *txn, int64_t offset, int64_t size) {
        ASSERT_LE(0, offset);
        ASSERT_LE(offset, expected_.size());
        ASSERT_LE(0, size);
        ASSERT_LE(offset + size, expected_.size());

        ASSERT_EQ(expected_.size(), blob_.valuesize());

        buffer_group_t bg;
        blob_acq_t bacq;
        blob_.expose_region(txn, rwi_read, offset, size, &bg, &bacq);

        ASSERT_EQ(size, bg.get_size());

        std::string::iterator p_orig = expected_.begin() + offset, p = p_orig, e = p + size;
        for (size_t i = 0, n = bg.num_buffers(); i < n; ++i) {
            buffer_group_t::buffer_t buffer = bg.get_buffer(i);
            ASSERT_LE(buffer.size, e - p);
            char *data = reinterpret_cast<char *>(buffer.data);
            ASSERT_TRUE(std::equal(data, data + buffer.size, p));
            p += buffer.size;
        }

        ASSERT_EQ(e - p_orig, p - p_orig);
    }

    void check(transaction_t *txn) {
        check_region(txn, 0, expected_.size());
    }

    void append(transaction_t *txn, const std::string& x) {
        int64_t n = x.size();

        blob_.append_region(txn, n);

        ASSERT_EQ(expected_.size() + n, blob_.valuesize());

        {
            buffer_group_t bg;
            blob_acq_t bacq;
            blob_.expose_region(txn, rwi_write, expected_.size(), n, &bg, &bacq);

            ASSERT_EQ(n, bg.get_size());

            const_buffer_group_t copyee;
            copyee.add_buffer(x.size(), x.data());

            buffer_group_copy_data(&bg, &copyee);

            expected_ += x;
        }

        check(txn);
    }

    void prepend(transaction_t *txn, const std::string& x) {
        int64_t n = x.size();

        blob_.prepend_region(txn, n);

        ASSERT_EQ(n + expected_.size(), blob_.valuesize());

        {
            buffer_group_t bg;
            blob_acq_t bacq;
            blob_.expose_region(txn, rwi_write, expected_.size(), n, &bg, &bacq);

            ASSERT_EQ(n, bg.get_size());

            const_buffer_group_t copyee;
            copyee.add_buffer(x.size(), x.data());

            buffer_group_copy_data(&bg, &copyee);

            expected_ = x + expected_;
        }

        check(txn);
    }

    void unprepend(transaction_t *txn, int64_t n) {
        ASSERT_LE(n, expected_.size());

        blob_.unprepend_region(txn, n);
        expected_.erase(0, n);

        check(txn);
    }

    void unappend(transaction_t *txn, int64_t n) {
        ASSERT_LE(n, expected_.size());

        blob_.unappend_region(txn, n);
        expected_.erase(expected_.size() - n);

        check(txn);
    }

private:
    std::string expected_;
    blob_t blob_;
};

struct blob_tester_t : public server_test_helper_t {
protected:
    void run_tests(cache_t *cache) {
        small_value_test(cache);
    }

private:
    void small_value_test(cache_t *cache) {
        block_size_t block_size = cache->get_block_size();

        transaction_t txn(cache, rwi_write, 0, repli_timestamp_t::distant_past);

        blob_tracker_t tk(block_size, 251);

        tk.append(&txn, "a");
        tk.append(&txn, "b");
        tk.prepend(&txn, "c");
    }
};

TEST(BlobTest, all_tests) {
    blob_tester_t().run();
}

}  // namespace unittest
<|endoftext|>


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

#include "util/util_logging.h"

#include "util/util_math.h"
#include "util/util_string.h"

#include <stdio.h>
#ifdef _MSC_VER
#  define snprintf _snprintf
#endif

CCL_NAMESPACE_BEGIN

static bool is_verbosity_set()
{
  using CYCLES_GFLAGS_NAMESPACE::GetCommandLineOption;

  std::string verbosity;
  if (!GetCommandLineOption("v", &verbosity)) {
    return false;
  }
  return verbosity != "0";
}

void util_logging_init(const char *argv0)
{
#ifdef WITH_CYCLES_LOGGING
  using CYCLES_GFLAGS_NAMESPACE::SetCommandLineOption;

  /* Make it so ERROR messages are always print into console. */
  char severity_fatal[32];
  snprintf(severity_fatal, sizeof(severity_fatal), "%d", google::GLOG_ERROR);

  google::InitGoogleLogging(argv0);
  SetCommandLineOption("logtostderr", "1");
  if (!is_verbosity_set()) {
    SetCommandLineOption("v", "0");
  }
  SetCommandLineOption("stderrthreshold", severity_fatal);
  SetCommandLineOption("minloglevel", severity_fatal);
#else
  (void)argv0;
#endif
}

void util_logging_start()
{
#ifdef WITH_CYCLES_LOGGING
  using CYCLES_GFLAGS_NAMESPACE::SetCommandLineOption;
  SetCommandLineOption("logtostderr", "1");
  if (!is_verbosity_set()) {
    SetCommandLineOption("v", "2");
  }
  SetCommandLineOption("stderrthreshold", "1");
  SetCommandLineOption("minloglevel", "0");
#endif
}

void util_logging_verbosity_set(int verbosity)
{
#ifdef WITH_CYCLES_LOGGING
  using CYCLES_GFLAGS_NAMESPACE::SetCommandLineOption;
  char val[10];
  snprintf(val, sizeof(val), "%d", verbosity);
  SetCommandLineOption("v", val);
#else
  (void)verbosity;
#endif
}

std::ostream &operator<<(std::ostream &os, const int2 &value)
{
  os << "(" << value.x << ", " << value.y << ")";
  return os;
}

std::ostream &operator<<(std::ostream &os, const float3 &value)
{
  os << "(" << value.x << ", " << value.y << ", " << value.z << ")";
  return os;
}

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

#include "util/util_logging.h"

#include "util/util_math.h"
#include "util/util_string.h"

#include <stdio.h>
#ifdef _MSC_VER
#  define snprintf _snprintf
#endif

CCL_NAMESPACE_BEGIN

static bool is_verbosity_set()
{
#ifdef WITH_CYCLES_LOGGING
using CYCLES_GFLAGS_NAMESPACE::GetCommandLineOption;

  std::string verbosity;
  if (!GetCommandLineOption("v", &verbosity)) {
    return false;
  }
  return verbosity != "0";
#else
	return false;
#endif
}

void util_logging_init(const char *argv0)
{
#ifdef WITH_CYCLES_LOGGING
  using CYCLES_GFLAGS_NAMESPACE::SetCommandLineOption;

  /* Make it so ERROR messages are always print into console. */
  char severity_fatal[32];
  snprintf(severity_fatal, sizeof(severity_fatal), "%d", google::GLOG_ERROR);

  google::InitGoogleLogging(argv0);
  SetCommandLineOption("logtostderr", "1");
  if (!is_verbosity_set()) {
    SetCommandLineOption("v", "0");
  }
  SetCommandLineOption("stderrthreshold", severity_fatal);
  SetCommandLineOption("minloglevel", severity_fatal);
#else
  (void)argv0;
#endif
}

void util_logging_start()
{
#ifdef WITH_CYCLES_LOGGING
  using CYCLES_GFLAGS_NAMESPACE::SetCommandLineOption;
  SetCommandLineOption("logtostderr", "1");
  if (!is_verbosity_set()) {
    SetCommandLineOption("v", "2");
  }
  SetCommandLineOption("stderrthreshold", "1");
  SetCommandLineOption("minloglevel", "0");
#endif
}

void util_logging_verbosity_set(int verbosity)
{
#ifdef WITH_CYCLES_LOGGING
  using CYCLES_GFLAGS_NAMESPACE::SetCommandLineOption;
  char val[10];
  snprintf(val, sizeof(val), "%d", verbosity);
  SetCommandLineOption("v", val);
#else
  (void)verbosity;
#endif
}

std::ostream &operator<<(std::ostream &os, const int2 &value)
{
  os << "(" << value.x << ", " << value.y << ")";
  return os;
}

std::ostream &operator<<(std::ostream &os, const float3 &value)
{
  os << "(" << value.x << ", " << value.y << ", " << value.z << ")";
  return os;
}

CCL_NAMESPACE_END
<|endoftext|>


<commit_before>//Copyright (c) 2019 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.

#include "linearAlg2D.h"

#include <cmath> // atan2
#include <cassert>
#include <algorithm> // swap

#include "IntPoint.h" // dot

namespace cura
{

float LinearAlg2D::getAngleLeft(const Point& a, const Point& b, const Point& c)
{
    const Point ba = a - b;
    const Point bc = c - b;
    const coord_t dott = dot(ba, bc); // dot product
    const coord_t det = ba.X * bc.Y - ba.Y * bc.X; // determinant
    if (det == 0)
    {
        if (
            (ba.X != 0 && (ba.X > 0) == (bc.X > 0))
            || (ba.X == 0 && (ba.Y > 0) == (bc.Y > 0))
            )
        {
            return 0; // pointy bit
        }
        else
        {
            return M_PI; // straight bit
        }
    }
    const float angle = -atan2(det, dott); // from -pi to pi
    if (angle >= 0)
    {
        return angle;
    }
    else
    {
        return M_PI * 2 + angle;
    }
}

bool LinearAlg2D::getPointOnLineWithDist(const Point& p, const Point& a, const Point& b, const coord_t dist, Point& result)
{
    //         result
    //         v
    //   b<----r---a.......x
    //          '-.        :
    //              '-.    :
    //                  '-.p
    const Point ab = b - a;
    const coord_t ab_size = vSize(ab);
    const Point ap = p - a;
    const coord_t ax_size = (ab_size < 50)? dot(normal(ab, 1000), ap) / 1000 : dot(ab, ap) / ab_size;
    const coord_t ap_size2 = vSize2(ap);
    const coord_t px_size = sqrt(std::max(coord_t(0), ap_size2 - ax_size * ax_size));
    if (px_size > dist)
    {
        return false;
    }
    const coord_t xr_size = sqrt(dist * dist - px_size * px_size);
    if (ax_size <= 0)
    { // x lies before ab
        const coord_t ar_size = xr_size + ax_size;
        if (ar_size < 0 || ar_size > ab_size)
        { // r lies outisde of ab
            return false;
        }
        else
        {
            result = a + normal(ab, ar_size);
            return true;
        }
    }
    else if (ax_size >= ab_size)
    { // x lies after ab
        //         result
        //         v
        //   a-----r-->b.......x
        //          '-.        :
        //              '-.    :
        //                  '-.p
        const coord_t ar_size = ax_size - xr_size;
        if (ar_size < 0 || ar_size > ab_size)
        { // r lies outisde of ab
            return false;
        }
        else
        {
            result = a + normal(ab, ar_size);
            return true;
        }
    }
    else // ax_size > 0 && ax_size < ab_size
    { // x lies on ab
        //            result is either or
        //         v                       v
        //   a-----r-----------x-----------r----->b
        //          '-.        :        .-'
        //              '-.    :    .-'
        //                  '-.p.-'
        //           or there is not result:
        //         v                       v
        //         r   a-------x---->b     r
        //          '-.        :        .-'
        //              '-.    :    .-'
        //                  '-.p.-'
        // try r in both directions
        const coord_t ar1_size = ax_size - xr_size;
        if (ar1_size >= 0)
        {
            result = a + normal(ab, ar1_size);
            return true;
        }
        const coord_t ar2_size = ax_size + xr_size;
        if (ar2_size < ab_size)
        {
            result = a + normal(ab, ar2_size);
            return true;
        }
        return false;
    }
}

std::pair<Point, Point> LinearAlg2D::getClosestConnection(Point a1, Point a2, Point b1, Point b2)
{
    Point b1_on_a = getClosestOnLineSegment(b1, a1, a2);
    coord_t b1_on_a_dist2 = vSize2(b1_on_a - b1);
    Point b2_on_a = getClosestOnLineSegment(b2, a1, a2);
    coord_t b2_on_a_dist2 = vSize2(b2_on_a - b2);
    Point a1_on_b = getClosestOnLineSegment(a1, b1, b2);
    coord_t a1_on_b_dist2 = vSize2(a1_on_b - a1);
    Point a2_on_b = getClosestOnLineSegment(a1, b1, b2);
    coord_t a2_on_b_dist2 = vSize2(a2_on_b - a2);
    if (b1_on_a_dist2 < b2_on_a_dist2 && b1_on_a_dist2 < a1_on_b_dist2 && b1_on_a_dist2 < a2_on_b_dist2)
    {
        return std::make_pair(b1_on_a, b1);
    }
    else if (b2_on_a_dist2 < a1_on_b_dist2 && b2_on_a_dist2 < a2_on_b_dist2)
    {
        return std::make_pair(b2_on_a, b2);
    }
    else if (a1_on_b_dist2 < a2_on_b_dist2)
    {
        return std::make_pair(a1, a1_on_b);
    }
    else
    {
        return std::make_pair(a2, a2_on_b);
    }
}

bool LinearAlg2D::lineSegmentsCollide(const Point& a_from_transformed, const Point& a_to_transformed, Point b_from_transformed, Point b_to_transformed)
{
    assert(std::abs(a_from_transformed.Y - a_to_transformed.Y) < 2 && "line a is supposed to be transformed to be aligned with the X axis!");
    assert(a_from_transformed.X - 2 <= a_to_transformed.X && "line a is supposed to be aligned with X axis in positive direction!");
    if ((b_from_transformed.Y >= a_from_transformed.Y && b_to_transformed.Y <= a_from_transformed.Y) || (b_to_transformed.Y >= a_from_transformed.Y && b_from_transformed.Y <= a_from_transformed.Y))
    {
        if(b_to_transformed.Y == b_from_transformed.Y)
        {
            if (b_to_transformed.X < b_from_transformed.X)
            {
                std::swap(b_to_transformed.X, b_from_transformed.X);
            }
            if (b_from_transformed.X > a_to_transformed.X)
            {
                return false;
            }
            if (b_to_transformed.X < a_from_transformed.X)
            {
                return false;
            }
            return true;
        }
        else
        {
            const coord_t x = b_from_transformed.X + (b_to_transformed.X - b_from_transformed.X) * (a_from_transformed.Y - b_from_transformed.Y) / (b_to_transformed.Y - b_from_transformed.Y);
            if (x >= a_from_transformed.X && x <= a_to_transformed.X)
            {
                return true;
            }
        }
    }
    return false;
}

coord_t LinearAlg2D::getDist2FromLine(const Point& p, const Point& a, const Point& b)
{
    //  x.......a------------b
    //  :
    //  :
    //  p
    // return px_size
    const Point vab = b - a;
    const Point vap = p - a;
    const coord_t ab_size2 = vSize2(vab);
    const coord_t ap_size2 = vSize2(vap);
    if(ab_size2 == 0) //Line of 0 length. Assume it's a line perpendicular to the direction to p.
    {
        return ap_size2;
    }
    const coord_t dott = dot(vab, vap);
    const coord_t ax_size2 = dott * dott / vSize2(vab);
    const coord_t px_size2 = std::max(coord_t(0), ap_size2 - ax_size2);
    return px_size2;
}

bool LinearAlg2D::isInsideCorner(const Point a, const Point b, const Point c, const Point q)
{
    constexpr coord_t normal_length = 10000;
    Point ba = normal(a - b, normal_length);
    Point bc = normal(c - b, normal_length);
    Point bq = q - b;
    Point n = turn90CCW(bq);
    coord_t anx = dot(ba, n);
    coord_t cnx = dot(bc, n);
    if ((anx > 0) != (cnx > 0))
    {
        return anx > 0;
    }
    else
    {
        coord_t ax = dot(ba, bq);
        coord_t cx = dot(bc, bq);
        return (cx < ax) == (anx > 0);
    }
}

} // namespace cura
<commit_msg>Better variable names, visualisation and documentation<commit_after>//Copyright (c) 2020 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.

#include "linearAlg2D.h"

#include <cmath> // atan2
#include <cassert>
#include <algorithm> // swap

#include "IntPoint.h" // dot

namespace cura
{

float LinearAlg2D::getAngleLeft(const Point& a, const Point& b, const Point& c)
{
    const Point ba = a - b;
    const Point bc = c - b;
    const coord_t dott = dot(ba, bc); // dot product
    const coord_t det = ba.X * bc.Y - ba.Y * bc.X; // determinant
    if (det == 0)
    {
        if (
            (ba.X != 0 && (ba.X > 0) == (bc.X > 0))
            || (ba.X == 0 && (ba.Y > 0) == (bc.Y > 0))
            )
        {
            return 0; // pointy bit
        }
        else
        {
            return M_PI; // straight bit
        }
    }
    const float angle = -atan2(det, dott); // from -pi to pi
    if (angle >= 0)
    {
        return angle;
    }
    else
    {
        return M_PI * 2 + angle;
    }
}

bool LinearAlg2D::getPointOnLineWithDist(const Point& p, const Point& a, const Point& b, const coord_t dist, Point& result)
{
    //         result
    //         v
    //   b<----r---a.......x
    //          '-.        :
    //              '-.    :
    //                  '-.p
    const Point ab = b - a;
    const coord_t ab_size = vSize(ab);
    const Point ap = p - a;
    const coord_t ax_size = (ab_size < 50)? dot(normal(ab, 1000), ap) / 1000 : dot(ab, ap) / ab_size;
    const coord_t ap_size2 = vSize2(ap);
    const coord_t px_size = sqrt(std::max(coord_t(0), ap_size2 - ax_size * ax_size));
    if (px_size > dist)
    {
        return false;
    }
    const coord_t xr_size = sqrt(dist * dist - px_size * px_size);
    if (ax_size <= 0)
    { // x lies before ab
        const coord_t ar_size = xr_size + ax_size;
        if (ar_size < 0 || ar_size > ab_size)
        { // r lies outisde of ab
            return false;
        }
        else
        {
            result = a + normal(ab, ar_size);
            return true;
        }
    }
    else if (ax_size >= ab_size)
    { // x lies after ab
        //         result
        //         v
        //   a-----r-->b.......x
        //          '-.        :
        //              '-.    :
        //                  '-.p
        const coord_t ar_size = ax_size - xr_size;
        if (ar_size < 0 || ar_size > ab_size)
        { // r lies outisde of ab
            return false;
        }
        else
        {
            result = a + normal(ab, ar_size);
            return true;
        }
    }
    else // ax_size > 0 && ax_size < ab_size
    { // x lies on ab
        //            result is either or
        //         v                       v
        //   a-----r-----------x-----------r----->b
        //          '-.        :        .-'
        //              '-.    :    .-'
        //                  '-.p.-'
        //           or there is not result:
        //         v                       v
        //         r   a-------x---->b     r
        //          '-.        :        .-'
        //              '-.    :    .-'
        //                  '-.p.-'
        // try r in both directions
        const coord_t ar1_size = ax_size - xr_size;
        if (ar1_size >= 0)
        {
            result = a + normal(ab, ar1_size);
            return true;
        }
        const coord_t ar2_size = ax_size + xr_size;
        if (ar2_size < ab_size)
        {
            result = a + normal(ab, ar2_size);
            return true;
        }
        return false;
    }
}

std::pair<Point, Point> LinearAlg2D::getClosestConnection(Point a1, Point a2, Point b1, Point b2)
{
    Point b1_on_a = getClosestOnLineSegment(b1, a1, a2);
    coord_t b1_on_a_dist2 = vSize2(b1_on_a - b1);
    Point b2_on_a = getClosestOnLineSegment(b2, a1, a2);
    coord_t b2_on_a_dist2 = vSize2(b2_on_a - b2);
    Point a1_on_b = getClosestOnLineSegment(a1, b1, b2);
    coord_t a1_on_b_dist2 = vSize2(a1_on_b - a1);
    Point a2_on_b = getClosestOnLineSegment(a1, b1, b2);
    coord_t a2_on_b_dist2 = vSize2(a2_on_b - a2);
    if (b1_on_a_dist2 < b2_on_a_dist2 && b1_on_a_dist2 < a1_on_b_dist2 && b1_on_a_dist2 < a2_on_b_dist2)
    {
        return std::make_pair(b1_on_a, b1);
    }
    else if (b2_on_a_dist2 < a1_on_b_dist2 && b2_on_a_dist2 < a2_on_b_dist2)
    {
        return std::make_pair(b2_on_a, b2);
    }
    else if (a1_on_b_dist2 < a2_on_b_dist2)
    {
        return std::make_pair(a1, a1_on_b);
    }
    else
    {
        return std::make_pair(a2, a2_on_b);
    }
}

bool LinearAlg2D::lineSegmentsCollide(const Point& a_from_transformed, const Point& a_to_transformed, Point b_from_transformed, Point b_to_transformed)
{
    assert(std::abs(a_from_transformed.Y - a_to_transformed.Y) < 2 && "line a is supposed to be transformed to be aligned with the X axis!");
    assert(a_from_transformed.X - 2 <= a_to_transformed.X && "line a is supposed to be aligned with X axis in positive direction!");
    if ((b_from_transformed.Y >= a_from_transformed.Y && b_to_transformed.Y <= a_from_transformed.Y) || (b_to_transformed.Y >= a_from_transformed.Y && b_from_transformed.Y <= a_from_transformed.Y))
    {
        if(b_to_transformed.Y == b_from_transformed.Y)
        {
            if (b_to_transformed.X < b_from_transformed.X)
            {
                std::swap(b_to_transformed.X, b_from_transformed.X);
            }
            if (b_from_transformed.X > a_to_transformed.X)
            {
                return false;
            }
            if (b_to_transformed.X < a_from_transformed.X)
            {
                return false;
            }
            return true;
        }
        else
        {
            const coord_t x = b_from_transformed.X + (b_to_transformed.X - b_from_transformed.X) * (a_from_transformed.Y - b_from_transformed.Y) / (b_to_transformed.Y - b_from_transformed.Y);
            if (x >= a_from_transformed.X && x <= a_to_transformed.X)
            {
                return true;
            }
        }
    }
    return false;
}

coord_t LinearAlg2D::getDist2FromLine(const Point& p, const Point& a, const Point& b)
{
    //  x.......a------------b
    //  :
    //  :
    //  p
    // return px_size
    const Point vab = b - a;
    const Point vap = p - a;
    const coord_t ab_size2 = vSize2(vab);
    const coord_t ap_size2 = vSize2(vap);
    if(ab_size2 == 0) //Line of 0 length. Assume it's a line perpendicular to the direction to p.
    {
        return ap_size2;
    }
    const coord_t dott = dot(vab, vap);
    const coord_t ax_size2 = dott * dott / vSize2(vab);
    const coord_t px_size2 = std::max(coord_t(0), ap_size2 - ax_size2);
    return px_size2;
}

bool LinearAlg2D::isInsideCorner(const Point a, const Point b, const Point c, const Point query_point)
{
    /*
     Visualisation for the algorithm below:

                 query
                   |
                   |
                   |
    perp-----------b
                  / \       (note that the lines
                 /   \      AB and AC are normalized
                /     \     to 10000 units length)
               a       c
     */

    constexpr coord_t normal_length = 10000; //Create a normal vector of reasonable length in order to reduce rounding error.
    const Point ba = normal(a - b, normal_length);
    const Point bc = normal(c - b, normal_length);
    const Point bq = query_point - b;
    const Point perpendicular = turn90CCW(bq); //The query projects to this perpendicular to coordinate 0.
    const coord_t project_a_perpendicular = dot(ba, perpendicular); //Project vertex A on the perpendicular line.
    const coord_t project_c_perpendicular = dot(bc, perpendicular); //Project vertex C on the perpendicular line.
    if ((project_a_perpendicular > 0) != (project_c_perpendicular > 0)) //Query is between A and C on the projection.
    {
        return project_a_perpendicular > 0; //Due to the winding order of corner ABC, this means that the query is inside.
    }
    else //Beyond either A or C, but it could still be inside of the polygon.
    {
        const coord_t project_a_parallel = dot(ba, bq); //Project not on the perpendicular, but on the original.
        const coord_t project_c_parallel = dot(bc, bq);

        //Either:
        // * A is to the right of B (project_a_perpendicular > 0) and C is below A (project_c_parallel < project_a_parallel), or
        // * A is to the left of B (project_a_perpendicular < 0) and C is above A (project_c_parallel > project_a_parallel).
        return (project_c_parallel < project_a_parallel) == (project_a_perpendicular > 0);
    }
}

} // namespace cura
<|endoftext|>


<commit_before>#include "asts.h"

namespace ICM
{
	AST* createAST(Match &match, const KeyWordMap &KeyWords)
	{
		AST *ast = new AST();
		MatchResult mr;

		bool firstMatchBraket = false;
		bool emptybreak = false;

		mr = match.matchNext();
		while (mr.begin() != mr.end()) {
			if (mr.getString()[0] != '\n') {
				//println(&mr);
			}
			if (mr.getType() == T_LBracket) {
				ast->pushNode(AST_FUNC);
				firstMatchBraket = true;
				emptybreak = true;
			}
			else if (mr.getType() == T_RBracket) {
				ast->retNode();
			}
			else if (mr.getType() == T_Identifier) {
				if (firstMatchBraket) {
					auto i = KeyWords.find(mr.getString());
					if (i == KeyWords.end()) {
						// TODO
						ast->setfunc(FUNC_ADD, 0);
					}
					else {
						ast->setfunc(FUNC_DEF, i->second);
					}
				}
				else {
					ast->pushNode(AST_DATA)->setdata(mr.getString());
				}
				firstMatchBraket = false;
			}
			else if (mr.getType() == T_Number) {
				ast->pushNode(AST_DATA)->setdata(atoi(mr.getString().c_str()))->settype(T_Number);
			}
			else if (mr.getType() == T_String) {
				ast->pushNode(AST_DATA)->setdata<std::string>(mr.getString())->settype(T_String);
			}
			if (emptybreak && ast->isend()) {
				break;
			}
			mr = match.matchNext();
		}
		return ast;
	}
}
<commit_msg>Delete asts.cpp<commit_after><|endoftext|>


<commit_before>/*! \file */

#include <sim_parameters/nmspc_sim_settings.h>
#include <sim_parameters/nmspc_model.h>
#include <algorithms/class_algorithm_launcher.h>
#include <gitversion.h>
#include <io/class_settings_reader.h>
#include <io/class_hdf5_file.h>
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
//#include <El.hpp>

#ifdef OpenBLAS_AVAILABLE
#include <cblas.h>
#endif

#ifdef OpenMP_AVAILABLE
#include <omp.h>
#endif

#ifdef MKL_AVAILABLE
#define MKL_Complex8 std::complex<float>
#define MKL_Complex16 std::complex<double>
#include <mkl_service.h>
#include <mkl.h>
#endif

/*!
    \brief  Main function. Sets simulation parameters and excecutes the desired algorithms.
    \return an integer 0 upon exit success
*/

int main(int argc, char* argv[]) {

    auto logger = spdlog::stderr_color_mt("DMRG");
    logger->set_pattern("[%Y-%m-%d %H:%M:%S][%n]%^[%=8l]%$ %v");
    spdlog::set_default_logger(logger);
    spdlog::set_level(spdlog::level::trace);

    int openblas_num_threads = 1;
    #ifdef OpenBLAS_AVAILABLE
        openblas_set_num_threads(openblas_num_threads);
    std::cout << "OpenBLAS compiled with mode " << openblas_get_parallel()
              << " for target " << openblas_get_corename()
              << " with config " << openblas_get_config()
              << ". Running with " << openblas_get_num_threads() << " thread(s)" << std::endl;
    #endif

    #ifdef OpenMP_AVAILABLE
        Eigen::initParallel();
//        omp_set_num_threads(OpenMP_NUM_THREADS);
//        omp_set_dynamic(0);
//        Eigen::setNbThreads(OpenMP_NUM_THREADS);
//        Eigen::setNbThreads(0);
        spdlog::info("Using Eigen  with {} threads",Eigen::nbThreads( )  );
        spdlog::info("Using OpenMP with {} threads",omp_get_max_threads());
        #ifdef MKL_AVAILABLE
//            mkl_set_num_threads(OpenMP_NUM_THREADS);
            spdlog::info("Using Intel MKL with {} threads", mkl_get_max_threads());
        #endif
    #endif

    // Print current Git status
    spdlog::info("Git branch      : {}",GIT::BRANCH);
    spdlog::info("    commit hash : {}",GIT::COMMIT_HASH);
    spdlog::info("    revision    : {}",GIT::REVISION);

    //Print all given parameters
    //Load input and output files from command line. If none were given use defaults.
    //Normally an output filename is given in the input file. But it can also be given from command line.
    std::string inputfile  = "input.cfg";
    std::string outputfile = "output.h5";
    for (int i=0; i < argc; i++){
        std::string arg_string = std::string(argv[i]);
        spdlog::info("Input argument {} : {}",i,arg_string);
        if (arg_string.find(".cfg") != std::string::npos) {inputfile  = arg_string;}
        if (arg_string.find(".h5")  != std::string::npos) {outputfile = arg_string;}
    }
    class_settings_reader indata(inputfile);
    if(indata.found_file){
        settings::load_from_file(indata);
    }else{
        auto hdf5 = std::make_shared<class_hdf5_file> (outputfile,"",false,false,true);
        if (hdf5->fileMode == class_hdf5_file::FileMode::OPEN) {
            spdlog::info("The output file existed already: {}", hdf5->get_file_name());
            spdlog::info("Loading settings from existing file.");
            settings::load_from_hdf5(*hdf5);
        }else{
            spdlog::warn("Couldn't find an inputfile or previous outputfile to load settings. Running defaults.");
        }

    }

    if (settings::console::verbosity < 0 or settings::console::verbosity > 6){
        std::cerr << "ERROR: Expected verbosity level integer in [0-6]. Got: " << settings::console::verbosity << std::endl;
        exit(2);
    }else{
        spdlog::level::level_enum lvl = static_cast<spdlog::level::level_enum>(settings::console::verbosity);
        logger->set_level(lvl);
        logger->debug("Verbosity level: {}", spdlog::level::to_string_view(lvl));
    }

//
//
//
//    spdlog = spdlog::get("DMRG++");
//
//    spdlog->warn("TESTING MY LOGGER");
    //Initialize the algorithm class
    //This class stores simulation data_struct automatically to a file specified in the input file
    class_algorithm_launcher launcher;

    //Run the algorithms
    launcher.run_algorithms();

    return 0;
}

<commit_msg>Resuming works, logger works<commit_after>/*! \file */

#include <sim_parameters/nmspc_sim_settings.h>
#include <sim_parameters/nmspc_model.h>
#include <algorithms/class_algorithm_launcher.h>
#include <gitversion.h>
#include <io/class_settings_reader.h>
#include <io/class_hdf5_file.h>
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
//#include <El.hpp>

#ifdef OpenBLAS_AVAILABLE
#include <cblas.h>
#endif

#ifdef OpenMP_AVAILABLE
#include <omp.h>
#endif

#ifdef MKL_AVAILABLE
#define MKL_Complex8 std::complex<float>
#define MKL_Complex16 std::complex<double>
#include <mkl_service.h>
#include <mkl.h>
#endif

/*!
    \brief  Main function. Sets simulation parameters and excecutes the desired algorithms.
    \return an integer 0 upon exit success
*/

int main(int argc, char* argv[]) {

    auto logger = spdlog::stdout_color_mt("DMRG");
    logger->set_pattern("[%Y-%m-%d %H:%M:%S][%n]%^[%=8l]%$ %v");
    spdlog::set_default_logger(logger);
    spdlog::set_level(spdlog::level::trace);

    int openblas_num_threads = 1;
    #ifdef OpenBLAS_AVAILABLE
        openblas_set_num_threads(openblas_num_threads);
    std::cout << "OpenBLAS compiled with mode " << openblas_get_parallel()
              << " for target " << openblas_get_corename()
              << " with config " << openblas_get_config()
              << ". Running with " << openblas_get_num_threads() << " thread(s)" << std::endl;
    #endif

    #ifdef OpenMP_AVAILABLE
        Eigen::initParallel();
//        omp_set_num_threads(OpenMP_NUM_THREADS);
//        omp_set_dynamic(0);
//        Eigen::setNbThreads(OpenMP_NUM_THREADS);
//        Eigen::setNbThreads(0);
        spdlog::info("Using Eigen  with {} threads",Eigen::nbThreads( )  );
        spdlog::info("Using OpenMP with {} threads",omp_get_max_threads());
        #ifdef MKL_AVAILABLE
//            mkl_set_num_threads(OpenMP_NUM_THREADS);
            spdlog::info("Using Intel MKL with {} threads", mkl_get_max_threads());
        #endif
    #endif

    // Print current Git status
    spdlog::info("Git branch      : {}",GIT::BRANCH);
    spdlog::info("    commit hash : {}",GIT::COMMIT_HASH);
    spdlog::info("    revision    : {}",GIT::REVISION);

    //Print all given parameters
    //Load input and output files from command line. If none were given use defaults.
    //Normally an output filename is given in the input file. But it can also be given from command line.
    std::string inputfile  = "input.cfg";
    std::string outputfile = "output.h5";
    for (int i=0; i < argc; i++){
        std::string arg_string = std::string(argv[i]);
        spdlog::info("Input argument {} : {}",i,arg_string);
        if (arg_string.find(".cfg") != std::string::npos) {inputfile  = arg_string;}
        if (arg_string.find(".h5")  != std::string::npos) {outputfile = arg_string;}
    }
    class_settings_reader indata(inputfile);
    if(indata.found_file){
        settings::load_from_file(indata);
    }else{
        auto hdf5 = std::make_shared<class_hdf5_file> (outputfile,"",false,false,true);
        if (hdf5->fileMode == class_hdf5_file::FileMode::OPEN) {
            spdlog::info("The output file existed already: {}", hdf5->get_file_name());
            spdlog::info("Loading settings from existing file.");
            settings::load_from_hdf5(*hdf5);
        }else{
            spdlog::warn("Couldn't find an inputfile or previous outputfile to load settings. Running defaults.");
        }

    }

    if (settings::console::verbosity < 0 or settings::console::verbosity > 6){
        std::cerr << "ERROR: Expected verbosity level integer in [0-6]. Got: " << settings::console::verbosity << std::endl;
        exit(2);
    }else{
        spdlog::level::level_enum lvl = static_cast<spdlog::level::level_enum>(settings::console::verbosity);
        logger->set_level(lvl);
        logger->debug("Verbosity level: {}", spdlog::level::to_string_view(lvl));
    }

//
//
//
//    spdlog = spdlog::get("DMRG++");
//
//    spdlog->warn("TESTING MY LOGGER");
    //Initialize the algorithm class
    //This class stores simulation data_struct automatically to a file specified in the input file
    class_algorithm_launcher launcher;

    //Run the algorithms
    launcher.run_algorithms();

    return 0;
}

<|endoftext|>


<commit_before>#include "logxx/logxx.h"
#include "dicom/dicom.h"
#include "dirent.h"

static logxx::Log cLog("extractor");

int main(int argc, char **argv){
	S_LOG("main");
        logxx::GlobalLogLevel(logxx::warning);
        if (argc < 2){
                log(logxx::error) << "A path with dicom files should be specified" << logxx::endl;
                return 1;
        } else {
                std::string path(argv[1]);
                if (path[path.length()-1] != '/')
                        path += '/';
                DIR *dir;
                if ((dir = opendir (path.c_str())) != nullptr) {
                        dirent *ent;
                        while ((ent = readdir (dir)) != NULL) {
                                if (ent->d_type == DT_REG){
                                        std::string fName = ent->d_name;
                                        log(logxx::debug) << "{" << fName << "}" << logxx::endl;
                                        Dicom dicom(path + fName);
                                        if (dicom.Parse()){
                                                log(logxx::notice) << "{" << fName << "} Parsed" << logxx::endl;
                                        } else {
                                                log(logxx::notice) << "{" << fName << "} Not parsed" << logxx::endl;
                                        }
                                }
                        }
                        closedir (dir);
                } else {
                        log(logxx::error) << "Can't open path {" << path << "}" << logxx::endl;
                        return 1;
                }

                return 0;
        }
}
<commit_msg>Output to a CSV file<commit_after>#include "logxx/logxx.h"
#include "dicom/dicom.h"
#include "dirent.h"
#include <fstream>

static logxx::Log cLog("extractor");

std::ostream& operator<<(std::ostream& s, const Dicom & d){
        s << d.GetId() << "," << d.GetDate() << "," << d.GetName() << "," << d.GetPet();
        return s;
}

int main(int argc, char **argv){
	S_LOG("main");
        logxx::GlobalLogLevel(logxx::warning);
        if (argc < 2){
                log(logxx::error) << "A path with dicom files should be specified" << logxx::endl;
                return 1;
        } else {
                std::string path(argv[1]);
                if (path[path.length()-1] != '/')
                        path += '/';
                DIR *dir;

                std::string csvFile = path + "out.csv";
                std::ofstream out(csvFile);
                if (out.good()){
                        if ((dir = opendir (path.c_str())) != nullptr) {
                                dirent *ent;
                                while ((ent = readdir (dir)) != NULL) {
                                        if (ent->d_type == DT_REG){
                                                std::string fName = ent->d_name;
                                                log(logxx::debug) << "{" << fName << "}" << logxx::endl;
                                                Dicom dicom(path + fName);
                                                if (dicom.Parse()){
                                                        log(logxx::notice) << "{" << fName << "} Parsed" << logxx::endl;
                                                        out << fName << "," << dicom << std::endl;

                                                } else {
                                                        log(logxx::notice) << "{" << fName << "} Not parsed" << logxx::endl;
                                                }
                                        }
                                }
                                closedir (dir);
                        } else {
                                log(logxx::error) << "Can't open path {" << path << "}" << logxx::endl;
                                return 1;
                        }
                        return 0;
                } else {
                        log(logxx::error) << "Can't open file {" << csvFile <<  "} for writing"  << logxx::endl;
                        return 1;
                }
        }
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <cstdlib>
#include <cmath>

using namespace std;

int GCD(int x, int y) {
	if (y > 0)
		return GCD(y, x%y);
	else
		return x;
}

void FermatVsPythagoras(int n) {
	int total, others, sqrt_n;
	vector<int> num(n+1);
	sqrt_n = sqrt(static_cast<double>(n));
	total = 0;
	int c = 0;
	for (int r = 1; r <= sqrt_n; r++) {
		for (int s = r+1; s <= sqrt_n; s++) {
			c++;
			int x = abs(r*r-s*s);
			int y = 2*r*s;
			int z = r*r+s*s;
			if (z > n)
				continue;
			for(int k = 1; k*z<=n; k++) {
				num[k*x] = 1;
				num[k*y] = 1;
				num[k*z] = 1;
			}
			if (GCD(x,y)==1)
				total++;
		}
	}
	others = 0;
	for (int i = 1; i <= n; i++)
		if (!num[i])
			others++;
	cout << total << " " << others << endl;
}

int main() {
	int n;
	while (cin >> n)
		FermatVsPythagoras(n);
	return 0;
}
<commit_msg>removing tabs...<commit_after>#include <iostream>
#include <vector>
#include <cstdlib>
#include <cmath>

using namespace std;

int GCD(int x, int y) {
  if (y > 0)
    return GCD(y, x%y);
  else
    return x;
}

void FermatVsPythagoras(int n) {
  int total, others, sqrt_n;
  vector<int> num(n+1);
  sqrt_n = sqrt(static_cast<double>(n));
  total = 0;
  int c = 0;
  for (int r = 1; r <= sqrt_n; r++) {
    for (int s = r+1; s <= sqrt_n; s++) {
      c++;
      int x = abs(r*r-s*s);
      int y = 2*r*s;
      int z = r*r+s*s;
      if (z > n)
        continue;
      for(int k = 1; k*z<=n; k++) {
        num[k*x] = 1;
        num[k*y] = 1;
        num[k*z] = 1;
      }
      if (GCD(x,y)==1)
        total++;
    }
  }
  others = 0;
  for (int i = 1; i <= n; i++)
    if (!num[i])
      others++;
  cout << total << " " << others << endl;
}

int main() {
  int n;
  while (cin >> n)
    FermatVsPythagoras(n);
  return 0;
}
<|endoftext|>


<commit_before>#include <ncurses.h>
#include <utility>

#include "board.hpp"
#include "print.hpp"
#include "reversi.hpp"

namespace roadagain
{

Reversi::Reversi() : black_(DEFAULT_STONE / 2), white_(DEFAULT_STONE / 2),
    now_(BLACK), next_(WHITE)
{
}

Reversi::~Reversi()
{
}

void Reversi::start()
{
    print();
}

void Reversi::play()
{
    std::pair<int, int> point;

    for (int i = 0; i < MAX_PUT; i++){
        std::pair<int, int> point = move();
        put(point);
        change();
    }
}

bool Reversi::can_put(const std::pair<int, int>& point)
{
    static const int* dxy = { -1, 0, 1 };
    for (int i = 0; i < 3; i++){
        for (int j = 0; j < 3; j++){
            if (dxy[i] == 0 && dxy[j] == 0){
                continue;
            }
            if (can_put(point, dxy[i], dxy[j]) == true){
                return (true);
            }
        }
    }

    return (false);
}

bool Reversi::can_put(const std::pair<int, int>& point, int dy, int dx)
{
    int y = point.first + dy;
    int x = point.second + dx;

    if (matrix_[y][x] != EMPTY){
        return (false);
    }

    while (in_board(y, x) == true && matrix_[y][x] == next_){
        can_reverse = true;
        y += dy;
        x += dx;
    }

    return (in_board(y, x) == true && can_reverse == true && matrix_[y][x] == now_);
}

std::pair<int, int> Reversi::move()
{
    int y = 0;
    int x = 0;
    char c;

    if (matrix_[y][x] == EMPTY){
        print_stone(y, x, now_);
    }

    c = getch();
    while (c != '\n'){
        print_stone(y, x, matrix_[y][x]);
        switch (c){
          case 'h':
            x = (x + Board::COL - 1) % Board::COL;
            break;
          case 'j':
            y = (y + 1) % Board::ROW;
            break;
          case 'k':
            y = (y + Board::ROW - 1) % Board::ROW;
            break;
          case 'l':
            x = (x + 1) % Board::COL;
            break;
        }
        if (matrix_[y][x] == EMPTY){
            print_stone(y, x, now_);
        }
        c = getch();
    }

    return (std::pair<int, int>(y, x));
}

void Reversi::put(const std::pair<int, int>& point)
{
    int y = point.first;
    int x = point.second;

    matrix_[y][x] = now_;
    print_stone(y, x, now_);
    reverse(point);
}

bool Reversi::reverse(const std::pair<int, int>& point)
{
    bool success = false;

    static const int dxy[] = { -1, 0, 1 };
    for (int i = 0; i < 3; i++){
        for (int j = 0; j < 3; j++){
            if (dxy[i] == 0 && dxy[j] == 0){
                continue;
            }
            bool flag = reverse(point, dxy[i], dxy[j]);
            if (success == false){
                success = flag;
            }
        }
    }

    return (success);
}

bool Reversi::reverse(const std::pair<int, int>& point, int dy, int dx)
{
    int y = point.first + dy;
    int x = point.second + dx;
    int cnt = 0;
    bool can_reverse = false;

    while (in_board(y, x) == true && matrix_[y][x] == next_){
        cnt++;
        can_reverse = true;
        y += dy;
        x += dx;
    }
    if (in_board(y, x) == false || can_reverse == false){
        return (false);
    }

    while (cnt-- > 0){
        y -= dy;
        x -= dx;
        matrix_[y][x] = now_;
        print_stone(y, x, now_);
    }
    return (true);
}

void Reversi::change()
{
    now_ = next_;
    next_ = (next_ == BLACK ? WHITE : BLACK);
}

}
<commit_msg>Added available check when putting stone<commit_after>#include <ncurses.h>
#include <utility>

#include "board.hpp"
#include "print.hpp"
#include "reversi.hpp"

namespace roadagain
{

Reversi::Reversi() : black_(DEFAULT_STONE / 2), white_(DEFAULT_STONE / 2),
    now_(BLACK), next_(WHITE)
{
}

Reversi::~Reversi()
{
}

void Reversi::start()
{
    print();
}

void Reversi::play()
{
    std::pair<int, int> point;

    for (int i = 0; i < MAX_PUT; i++){
        std::pair<int, int> point = move();
        put(point);
        change();
    }
}

bool Reversi::can_put(const std::pair<int, int>& point)
{
    static const int* dxy = { -1, 0, 1 };
    for (int i = 0; i < 3; i++){
        for (int j = 0; j < 3; j++){
            if (dxy[i] == 0 && dxy[j] == 0){
                continue;
            }
            if (can_put(point, dxy[i], dxy[j]) == true){
                return (true);
            }
        }
    }

    return (false);
}

bool Reversi::can_put(const std::pair<int, int>& point, int dy, int dx)
{
    int y = point.first + dy;
    int x = point.second + dx;

    if (matrix_[y][x] != EMPTY){
        return (false);
    }

    while (in_board(y, x) == true && matrix_[y][x] == next_){
        can_reverse = true;
        y += dy;
        x += dx;
    }

    return (in_board(y, x) == true && can_reverse == true && matrix_[y][x] == now_);
}

std::pair<int, int> Reversi::move()
{
    int y = 0;
    int x = 0;
    char c;

    if (matrix_[y][x] == EMPTY){
        print_stone(y, x, now_);
    }

    c = getch();
    while (c != '\n' || can_put(std::pair<int, int>(y, x)) == false){
        print_stone(y, x, matrix_[y][x]);
        switch (c){
          case 'h':
            x = (x + Board::COL - 1) % Board::COL;
            break;
          case 'j':
            y = (y + 1) % Board::ROW;
            break;
          case 'k':
            y = (y + Board::ROW - 1) % Board::ROW;
            break;
          case 'l':
            x = (x + 1) % Board::COL;
            break;
        }
        if (matrix_[y][x] == EMPTY){
            print_stone(y, x, now_);
        }
        c = getch();
    }

    return (std::pair<int, int>(y, x));
}

void Reversi::put(const std::pair<int, int>& point)
{
    int y = point.first;
    int x = point.second;

    matrix_[y][x] = now_;
    print_stone(y, x, now_);
    reverse(point);
}

bool Reversi::reverse(const std::pair<int, int>& point)
{
    bool success = false;

    static const int dxy[] = { -1, 0, 1 };
    for (int i = 0; i < 3; i++){
        for (int j = 0; j < 3; j++){
            if (dxy[i] == 0 && dxy[j] == 0){
                continue;
            }
            bool flag = reverse(point, dxy[i], dxy[j]);
            if (success == false){
                success = flag;
            }
        }
    }

    return (success);
}

bool Reversi::reverse(const std::pair<int, int>& point, int dy, int dx)
{
    int y = point.first + dy;
    int x = point.second + dx;
    int cnt = 0;
    bool can_reverse = false;

    while (in_board(y, x) == true && matrix_[y][x] == next_){
        cnt++;
        can_reverse = true;
        y += dy;
        x += dx;
    }
    if (in_board(y, x) == false || can_reverse == false){
        return (false);
    }

    while (cnt-- > 0){
        y -= dy;
        x -= dx;
        matrix_[y][x] = now_;
        print_stone(y, x, now_);
    }
    return (true);
}

void Reversi::change()
{
    now_ = next_;
    next_ = (next_ == BLACK ? WHITE : BLACK);
}

}
<|endoftext|>


<commit_before>#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/imgcodecs.hpp>
#include <iostream>
#include <math.h>
#include <stdio.h>

using namespace cv;
using namespace std;

int main()
{

	//char dir[100]={"/home/sedrica/Desktop/images.jpg"};

	Mat img;
	img=imread("images.jpg", CV_LOAD_IMAGE_COLOR); // reading the rgb image in Mat data struct

	Mat img_bw;
	cvtColor(img, img_bw,COLOR_RGB2GRAY);  // conversion to greayscale
/*

note: we may have to either pre process the image or not work with the custom bgr to greyscale or both
	  as they might not be able to detect edge very well
*/

	Mat grad_x, grad_y;    // derivative along x and y direction respectively
    Mat square_grad_x, square_grad_y;   // absoute value of derivative

    /// Gradient  along X direction
	Sobel( img_bw, grad_x,CV_16S, 1, 0, 3, 1,0, BORDER_DEFAULT );
	/// Gradient  along y direction
	Sobel( img_bw, grad_y,CV_16S, 0, 1, 3, 1, 0, BORDER_DEFAULT );

	square_grad_y=grad_y.mul(grad_y);
	square_grad_x=grad_x.mul(grad_x);

	Mat img_edge;

    addWeighted( square_grad_x,1, square_grad_y, 0.5, 0,img_edge);    // more weight is provided in the horizontal direction for more importance to lane detection

    Mat img_edge_dilated;
    Point anchor=Point(-1,-1);
    Size str_elem_dim_11;
    str_elem_dim_11=Size(11,11);

    Mat rect_str_elem=getStructuringElement(MORPH_RECT,str_elem_dim_11,anchor);

    dilate(img_edge,img_edge_dilated,rect_str_elem);

    //Mat img_eroded;
    Mat circ_str_elem=getStructuringElement(MORPH_ELLIPSE,str_elem_dim_11,anchor);
    //erode( img_edge_dilated,img_eroded,circ_str_elem);

    Mat img_flood_fill;
    Point origin=Point(0,0);  // is this have to be origin or (-1,-1) ?

    floodFill(img_edge_dilated,img_flood_fill,origin,Scalar(255),0,Scalar(),Scalar(),4);   /// got an issue with arguments SCALAR

    Mat img_openloops_removed;

    morphologyEx(img_flood_fill,img_openloops_removed,MORPH_OPEN,rect_str_elem);  // <------ confirm it

    Mat img_small_closedloops_removed;
	morphologyEx(img_openloops_removed,img_small_closedloops_removed,MORPH_CLOSED,rect_str_elem);  // comfirm it

	Mat img_erode_post_fill1,img_erode_post_erode;

	erode(img_small_closedloops_removed,img_erode_post_fill1,circ_str_elem);
	erode(img_erode_post_fill1,img_erode_post_erode,circ_str_elem);

	Mat img_final_filled;
	floodFill(img_erode_post_fill1,img_final_filled,origin,Scalar(255),0,Scalar(),Scalar(),4);   /// got an issue with arguments SCALAR

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

	int connected_components_count;

	Mat img_label;
	connected_components_count=connectedComponents(img_final_filled,img_label,8,int ltype=cv_32s);

	Mat label;
	label = // add matlab labelmatrix function equivalent of opencv

	Mat final_color_segmented;
	applyColorMap(label,final_color_segmented, COLORMAP_JET);

	return 0;
}
<commit_msg>flood<commit_after>#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/imgcodecs.hpp>
#include <iostream>
#include <math.h>
#include <stdio.h>

using namespace cv;
using namespace std;

int main()
{

	//char dir[100]={"/home/sedrica/Desktop/images.jpg"};

	Mat img;
	img=imread("images.jpg", CV_LOAD_IMAGE_COLOR); // reading the rgb image in Mat data struct

	Mat img_bw;
	cvtColor(img, img_bw,COLOR_RGB2GRAY);  // conversion to greayscale
/*

note: we may have to either pre process the image or not work with the custom bgr to greyscale or both
	  as they might not be able to detect edge very well
*/

	Mat grad_x, grad_y;    // derivative along x and y direction respectively
    Mat square_grad_x, square_grad_y;   // absoute value of derivative

    /// Gradient  along X direction
	Sobel( img_bw, grad_x,CV_16S, 1, 0, 3, 1,0, BORDER_DEFAULT );
	/// Gradient  along y direction
	Sobel( img_bw, grad_y,CV_16S, 0, 1, 3, 1, 0, BORDER_DEFAULT );

	square_grad_y=grad_y.mul(grad_y);
	square_grad_x=grad_x.mul(grad_x);

	Mat img_edge;

    addWeighted( square_grad_x,1, square_grad_y, 0.5, 0,img_edge);    // more weight is provided in the horizontal direction for more importance to lane detection

    Mat img_edge_dilated;
    Point anchor=Point(-1,-1);
    Size str_elem_dim_11;
    str_elem_dim_11=Size(11,11);

    Mat rect_str_elem=getStructuringElement(MORPH_RECT,str_elem_dim_11,anchor);

    dilate(img_edge,img_edge_dilated,rect_str_elem);

    //Mat img_eroded;
    Mat circ_str_elem=getStructuringElement(MORPH_ELLIPSE,str_elem_dim_11,anchor);
    //erode( img_edge_dilated,img_eroded,circ_str_elem);

    Mat img_flood_fill;
    Point origin=Point(0,0);  // is this have to be origin or (-1,-1) ?

    floodFill(img_edge_dilated,img_flood_fill,origin,Scalar(255),0,Scalar(),Scalar(),4);   /// got an issue with arguments SCALAR

    Mat img_openloops_removed;

    morphologyEx(img_flood_fill,img_openloops_removed,MORPH_OPEN,rect_str_elem);  // <------ confirm it

    Mat img_small_closedloops_removed;
	morphologyEx(img_openloops_removed,img_small_closedloops_removed,MORPH_CLOSED,rect_str_elem);  // comfirm it

	Mat img_erode_post_fill1,img_erode_post_erode;

	erode(img_small_closedloops_removed,img_erode_post_fill1,circ_str_elem);
	erode(img_erode_post_fill1,img_erode_post_erode,circ_str_elem);

	Mat img_final_filled;
	floodFill(img_erode_post_fill1,img_final_filled,origin,Scalar(255),0,Scalar(),Scalar(),4);   /// got an issue with arguments SCALAR

////////////////////////////////////////////////////////////////////////////
/*
	int connected_components_count;

	Mat img_label;
	connected_components_count=connectedComponents(img_final_filled,img_label,8,int ltype=cv_32s);

	Mat label;
	label = // add matlab labelmatrix function equivalent of opencv

	Mat final_color_segmented;
	applyColorMap(label,final_color_segmented, COLORMAP_JET);
 */
	return 0;
}
<|endoftext|>


<commit_before>/*
 * Distributed under the OSI-approved Apache License, Version 2.0.  See
 * accompanying file Copyright.txt for details.
 *
 * ExampleEnginePlugin.cpp This plugin does nothing but write API calls out to a
 * log file.
 *
 *  Created on: Jul 31, 2017
 *      Author: Chuck Atkins <chuck.atkins@kitware.com>
 */

#include "ExampleEnginePlugin.h"

#include <cstdio>
#include <cstring>
#include <ctime>

#ifndef _WIN32_
#include <sys/time.h>
#endif

namespace
{
std::string now()
{
    tm *timeInfo;
#ifdef _WIN32
    time_t rawTime;
    std::time(&rawTime);
    timeInfo = std::localtime(&rawtime);
#else
    timeval curTime;
    gettimeofday(&curTime, nullptr);
    timeInfo = std::localtime(&curTime.tv_sec);
#endif

    char timeBuf[80];
    std::memset(timeBuf, 0, sizeof(timeBuf));
    std::strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%dT%H:%M:%S", timeInfo);

#ifdef _WIN32
    return std::string(timeBuf);
#else
    double subSec = curTime.tv_usec / 1e6;
    char subSecBuf[9];
    std::memset(subSecBuf, 0, sizeof(subSecBuf));
    std::sprintf(subSecBuf, "%1.6f", subSec);
    return std::string(timeBuf) + std::string(&subSecBuf[1]);
#endif
}
}

namespace adios2
{

ExampleEnginePlugin::ExampleEnginePlugin(IO &io, const std::string &name,
                                         const OpenMode openMode,
                                         MPI_Comm mpiComm)
: adios2::PluginEngineInterface(io, name, openMode, mpiComm)
{
    Init();
}

ExampleEnginePlugin::~ExampleEnginePlugin() { m_Log.close(); }

void ExampleEnginePlugin::Close(const int transportIndex)
{
    m_Log << now() << " Close with transportIndex " << transportIndex
          << std::endl;
}

void ExampleEnginePlugin::Init()
{
    std::string logName = "ExamplePlugin.log";
    auto paramLogNameIt = m_IO.m_Parameters.find("LogName");
    if (paramLogNameIt != m_IO.m_Parameters.end())
    {
        logName = paramLogNameIt->second;
    }

    m_Log.open(logName);
    if (!m_Log)
    {
        throw std::ios_base::failure(
            "ExampleEnginePlugin: Failed to open log file " + logName);
    }

    m_Log << now() << " Init" << std::endl;
}

#define define(T)                                                              \
    void ExampleEnginePlugin::DoWrite(Variable<T> &variable, const T *values)  \
    {                                                                          \
        m_Log << now() << " Writing variable \"" << variable.m_Name << "\""    \
              << std::endl;                                                    \
    }
ADIOS2_FOREACH_TYPE_1ARG(define)
#undef define
void ExampleEnginePlugin::DoWrite(VariableCompound &variable,
                                  const void *values)
{
    m_Log << now() << " Writing variable \"" << variable.m_Name << "\""
          << std::endl;
}

} // end namespace adios2
<commit_msg>Fix bad WIN32 ifdef check<commit_after>/*
 * Distributed under the OSI-approved Apache License, Version 2.0.  See
 * accompanying file Copyright.txt for details.
 *
 * ExampleEnginePlugin.cpp This plugin does nothing but write API calls out to a
 * log file.
 *
 *  Created on: Jul 31, 2017
 *      Author: Chuck Atkins <chuck.atkins@kitware.com>
 */

#include "ExampleEnginePlugin.h"

#include <cstdio>
#include <cstring>
#include <ctime>

#ifndef _WIN32
#include <sys/time.h>
#endif

namespace
{
std::string now()
{
    tm *timeInfo;
#ifdef _WIN32
    time_t rawTime;
    std::time(&rawTime);
    timeInfo = std::localtime(&rawTime);
#else
    timeval curTime;
    gettimeofday(&curTime, nullptr);
    timeInfo = std::localtime(&curTime.tv_sec);
#endif

    char timeBuf[80];
    std::memset(timeBuf, 0, sizeof(timeBuf));
    std::strftime(timeBuf, sizeof(timeBuf), "%Y-%m-%dT%H:%M:%S", timeInfo);

#ifdef _WIN32
    return std::string(timeBuf);
#else
    double subSec = curTime.tv_usec / 1e6;
    char subSecBuf[9];
    std::memset(subSecBuf, 0, sizeof(subSecBuf));
    std::sprintf(subSecBuf, "%1.6f", subSec);
    return std::string(timeBuf) + std::string(&subSecBuf[1]);
#endif
}
}

namespace adios2
{

ExampleEnginePlugin::ExampleEnginePlugin(IO &io, const std::string &name,
                                         const OpenMode openMode,
                                         MPI_Comm mpiComm)
: adios2::PluginEngineInterface(io, name, openMode, mpiComm)
{
    Init();
}

ExampleEnginePlugin::~ExampleEnginePlugin() { m_Log.close(); }

void ExampleEnginePlugin::Close(const int transportIndex)
{
    m_Log << now() << " Close with transportIndex " << transportIndex
          << std::endl;
}

void ExampleEnginePlugin::Init()
{
    std::string logName = "ExamplePlugin.log";
    auto paramLogNameIt = m_IO.m_Parameters.find("LogName");
    if (paramLogNameIt != m_IO.m_Parameters.end())
    {
        logName = paramLogNameIt->second;
    }

    m_Log.open(logName);
    if (!m_Log)
    {
        throw std::ios_base::failure(
            "ExampleEnginePlugin: Failed to open log file " + logName);
    }

    m_Log << now() << " Init" << std::endl;
}

#define define(T)                                                              \
    void ExampleEnginePlugin::DoWrite(Variable<T> &variable, const T *values)  \
    {                                                                          \
        m_Log << now() << " Writing variable \"" << variable.m_Name << "\""    \
              << std::endl;                                                    \
    }
ADIOS2_FOREACH_TYPE_1ARG(define)
#undef define
void ExampleEnginePlugin::DoWrite(VariableCompound &variable,
                                  const void *values)
{
    m_Log << now() << " Writing variable \"" << variable.m_Name << "\""
          << std::endl;
}

} // end namespace adios2
<|endoftext|>


<commit_before>
#include "ofxSimpleGuiQuadWarp.h"

#define MOUSE_DISTANCE		10.0f

//---------------------------------------------------------------------
ofxSimpleGuiQuadWarp::ofxSimpleGuiQuadWarp(string name, ofBaseDraws &baseDraw, ofPoint *pts) : ofxSimpleGuiControl(name) {
	this->baseDraw = &baseDraw;

	setPosition(0, 0);
	setSize(baseDraw.getWidth(), baseDraw.getHeight());

	curPoint	= NULL;
	this->pts = pts;

	for(int i=0; i<4; i++) pts[i].z = i;		// z axis stores the index

	controlType = "QuadWarp";
	setup();
}

void ofxSimpleGuiQuadWarp::setup() {

}

#ifndef OFXMSAGUI_DONT_USE_XML
void ofxSimpleGuiQuadWarp::loadFromXML(ofxXmlSettings &XML) {
	for(int i=0; i<4; i++) {
		pts[i].x = XML.getValue(controlType + "_" + key + ":values_" + ofToString(i) + "_x", 0.0f);
		pts[i].y = XML.getValue(controlType + "_" + key + ":values_" + ofToString(i) + "_y", 0.0f);
	}
}

void ofxSimpleGuiQuadWarp::saveToXML(ofxXmlSettings &XML) {
	XML.addTag(controlType + "_" + key);
	XML.pushTag(controlType + "_" + key);
	XML.addValue("name", name);
	for(int i=0; i<4; i++) {
		XML.addValue("values_" + ofToString(i) + "_x", pts[i].x);
		XML.addValue("values_" + ofToString(i) + "_y", pts[i].y);
	}
	XML.popTag();
}
#endif

//---------------------------------------------------------------------
void ofxSimpleGuiQuadWarp::onPress(int x, int y, int button) {
	curPoint = NULL;
	for(int i=0; i<4; i++) {
		if(ofDistSquared(x - this->x, y - this->y, pts[i].x, pts[i].y) < MOUSE_DISTANCE * MOUSE_DISTANCE) {
			curPoint = pts + i;
		}
	}

	// if doubleclick, reset
	if(ofDistSquared(x, y, lastPressPlace.x, lastPressPlace.y) < MOUSE_DISTANCE * MOUSE_DISTANCE && ofGetElapsedTimef() - lastPressTime < 0.25f) {
//		pts[0].set(0, 0);
//		pts[1].set(width, 0);
//		pts[2].set(width, height);
//		pts[3].set(0, height);
		if(curPoint) {
			switch((int)curPoint->z) {		// stores index of point
				case 0: pts[0].set(0, 0); break;
				case 1:	pts[1].set(width, 0); break;
				case 2:	pts[2].set(width, height); break;
				case 3:	pts[3].set(0, height); break;
			}
		}
	}

	lastPressPlace.set(x, y);
	lastPressTime = ofGetElapsedTimef();
}

void ofxSimpleGuiQuadWarp::onPressOutside(int x, int y, int button) {
	onPress(x, y, button);
}

void ofxSimpleGuiQuadWarp::onDragOver(int x, int y, int button) {
	if(curPoint) {
		curPoint->set(x - this->x, y - this->y);
	}

}

//---------------------------------------------------------------------
void ofxSimpleGuiQuadWarp::onDragOutside(int x, int y, int button) {
	onDragOver(x, y, button);
}

//---------------------------------------------------------------------
void ofxSimpleGuiQuadWarp::draw(float x, float y) {
	setPosition(x, y);
	glPushMatrix();
	glTranslatef(x, y, 0);
	glColor3f(1, 1, 1);
	baseDraw->draw(0, 0);

	ofEnableAlphaBlending();
	ofFill();

	for(int i=0; i<4; i++) {
		if(curPoint == &pts[i]) {
			ofSetColor(255, 0, 0);
			ofCircle(pts[i].x, pts[i].y, 4);
		} else {
			ofSetColor(0, 255, 0);
			ofCircle(pts[i].x, pts[i].y, 2);
		}

	}

	ofBeginShape();
	ofNoFill();
	ofSetColor(255, 255, 255);
	for(int i=0; i<4; i++) {
		ofVertex(pts[i].x, pts[i].y);
	}
	ofEndShape(TRUE);
	ofDisableAlphaBlending();

	glPopMatrix();
}
<commit_msg>quadwarp mod<commit_after>
#include "ofxSimpleGuiQuadWarp.h"

#define MOUSE_DISTANCE		10.0f

//---------------------------------------------------------------------
ofxSimpleGuiQuadWarp::ofxSimpleGuiQuadWarp(string name, ofBaseDraws &baseDraw, ofPoint *pts) : ofxSimpleGuiControl(name) {
	this->baseDraw = &baseDraw;

	setPosition(0, 0);
//	setSize(baseDraw.getWidth(), baseDraw.getHeight());

	curPoint	= NULL;
	this->pts = pts;

	for(int i=0; i<4; i++) pts[i].z = i;		// z axis stores the index

	controlType = "QuadWarp";
	setup();
}

void ofxSimpleGuiQuadWarp::setup() {

}

#ifndef OFXMSAGUI_DONT_USE_XML
void ofxSimpleGuiQuadWarp::loadFromXML(ofxXmlSettings &XML) {
	for(int i=0; i<4; i++) {
		pts[i].x = XML.getValue(controlType + "_" + key + ":values_" + ofToString(i) + "_x", 0.0f);
		pts[i].y = XML.getValue(controlType + "_" + key + ":values_" + ofToString(i) + "_y", 0.0f);
	}
}

void ofxSimpleGuiQuadWarp::saveToXML(ofxXmlSettings &XML) {
	XML.addTag(controlType + "_" + key);
	XML.pushTag(controlType + "_" + key);
	XML.addValue("name", name);
	for(int i=0; i<4; i++) {
		XML.addValue("values_" + ofToString(i) + "_x", pts[i].x);
		XML.addValue("values_" + ofToString(i) + "_y", pts[i].y);
	}
	XML.popTag();
}
#endif

//---------------------------------------------------------------------
void ofxSimpleGuiQuadWarp::onPress(int x, int y, int button) {
	curPoint = NULL;
	for(int i=0; i<4; i++) {
		if(ofDistSquared(x - this->x, y - this->y, pts[i].x, pts[i].y) < MOUSE_DISTANCE * MOUSE_DISTANCE) {
			curPoint = pts + i;
		}
	}

	// if doubleclick, reset
	if(ofDistSquared(x, y, lastPressPlace.x, lastPressPlace.y) < MOUSE_DISTANCE * MOUSE_DISTANCE && ofGetElapsedTimef() - lastPressTime < 0.25f) {
//		pts[0].set(0, 0);
//		pts[1].set(width, 0);
//		pts[2].set(width, height);
//		pts[3].set(0, height);
		if(curPoint) {
			switch((int)curPoint->z) {		// stores index of point
				case 0: pts[0].set(0, 0); break;
				case 1:	pts[1].set(width, 0); break;
				case 2:	pts[2].set(width, height); break;
				case 3:	pts[3].set(0, height); break;
			}
		}
	}

	lastPressPlace.set(x, y);
	lastPressTime = ofGetElapsedTimef();
}

void ofxSimpleGuiQuadWarp::onPressOutside(int x, int y, int button) {
	onPress(x, y, button);
}

void ofxSimpleGuiQuadWarp::onDragOver(int x, int y, int button) {
	if(curPoint) {
		curPoint->set(x - this->x, y - this->y);
	}

}

//---------------------------------------------------------------------
void ofxSimpleGuiQuadWarp::onDragOutside(int x, int y, int button) {
	onDragOver(x, y, button);
}

//---------------------------------------------------------------------
void ofxSimpleGuiQuadWarp::draw(float x, float y) {
	setPosition(x, y);
	glPushMatrix();
	glTranslatef(x, y, 0);
	glColor3f(1, 1, 1);
	baseDraw->draw(0, 0);

	ofEnableAlphaBlending();
	ofFill();

	for(int i=0; i<4; i++) {
		if(curPoint == &pts[i]) {
			ofSetColor(255, 0, 0);
			ofCircle(pts[i].x, pts[i].y, 4);
		} else {
			ofSetColor(0, 255, 0);
			ofCircle(pts[i].x, pts[i].y, 2);
		}

	}

	ofBeginShape();
	ofNoFill();
	ofSetColor(255, 255, 255);
	for(int i=0; i<4; i++) {
		ofVertex(pts[i].x, pts[i].y);
	}
	ofEndShape(TRUE);
	ofDisableAlphaBlending();

	glPopMatrix();
}
<|endoftext|>