text:
#include "stdafx.h"
#include "LogListModel.h"

#include <QDate>

#include <boost/format.hpp>

#include <autom8/util/utility.hpp>
#include <autom8/util/debug.hpp>

using namespace autom8;

#define u2q(x) QString::fromUtf8(x.c_str())

static std::map<int, QVariant> sColumnHeaders;
static bool sInitialized = false;

#define DB_TABLE_NAME "log"
#define DB_ID_COLUMN "id"
#define DB_TIME_COLUMN "time"
#define DB_MESSAGE_COLUMN "message"
#define MAX_LOG_SIZE 2000

static int sLastDayOfYear = -1;
static bool sInTransaction = false;

static const std::string TAG = "LogListModel";

static void init() {
	sColumnHeaders[TIME_COLUMN] = QVariant("Time");
	sColumnHeaders[MESSAGE_COLUMN] = QVariant("Message");
}

#define EXEC_SQL(connection, str)				\
	{											\
		sqlite3_stmt* stmt = NULL;				\
		std::string query(str);					\
												\
		int result = sqlite3_prepare_v2(		\
			connection,							\
			query.c_str(),						\
			(int) query.size(),					\
			&stmt,								\
			NULL);								\
												\
		if (result == SQLITE_OK) {				\
			result = sqlite3_step(stmt);		\
		}										\
												\
		sqlite3_finalize(stmt);					\
	}											\

static void beginTransaction(sqlite3* connection) {
	if ( ! sInTransaction) {
		EXEC_SQL(connection, "BEGIN TRANSACTION;");
		sInTransaction = true;
	}
}

static void endTransaction(sqlite3* connection) {
	if (sInTransaction) {
		EXEC_SQL(connection, "COMMIT TRANSACTION;");
		sInTransaction = false;
	}
}

LogListModel::LogListModel(QObject *parent)
: QAbstractItemModel(parent)
{
	if ( ! sInitialized) {
		init();
		sInitialized = true;
	}

    debug::string_logged.connect(this, &LogListModel::onDebugStringLogged);

	connect(&mUpdateTimer, SIGNAL(timeout()), this, SLOT(onTimerTick()));
	mUpdateTimer.setInterval(2500);
	mUpdateTimer.start();

	initDbConnection();
	beginTransaction(mConnection);
}

LogListModel::~LogListModel() {
	debug::string_logged.disconnect(this);
	sqlite3_close(mConnection);
}

void LogListModel::initDbConnection() {
    // connect to the db.
    std::string filename = utility::settings_directory() + "access_logs.db";
    if (sqlite3_open(filename.c_str(), &mConnection) != SQLITE_OK) {
        debug::log(debug::error, TAG, "unable to open log database");
        throw std::exception();
    }

    // create the table
    std::string create_table = (boost::format(
        " CREATE TABLE IF NOT EXISTS %1% ("
        " %2% INTEGER PRIMARY KEY AUTOINCREMENT, "
        " %3% INTEGER, "
        " %4% STRING); ")
        % DB_TABLE_NAME
        % DB_ID_COLUMN
        % DB_TIME_COLUMN
        % DB_MESSAGE_COLUMN).str();

    sqlite3_stmt* stmt = NULL;

    int result = sqlite3_prepare_v2(
        mConnection,
        create_table.c_str(),
        (int) create_table.size(),
        &stmt,
        NULL);

    if (result == SQLITE_OK) {
        result = sqlite3_step(stmt);
    }

    sqlite3_finalize(stmt);

    if (result != SQLITE_DONE) {
        debug::log(debug::error, TAG, "unable to create devices table");
        throw std::exception();
    }

	// will clear, then implicitly load entries
    clearOldEntries();
}

void LogListModel::clearOldEntries() {
	std::string delete_older_than_a_week =
		(boost::format(
			"DELETE FROM %1% WHERE %2% < strftime('%%J', 'now', '-2 days');")
			% DB_TABLE_NAME
			% DB_TIME_COLUMN).str();

    sqlite3_stmt* stmt = NULL;

    int result = sqlite3_prepare(
        mConnection,
        delete_older_than_a_week.c_str(),
        (int) delete_older_than_a_week.size(),
        &stmt,
        NULL);

    if (result == SQLITE_OK) {
        result = sqlite3_step(stmt);
        sqlite3_finalize(stmt);
    }

	sLastDayOfYear = QDate::currentDate().dayOfYear();

	loadEntries();
}

void LogListModel::clear() {
    bool success = false;

    std::string delete_all =
        (boost::format("DELETE FROM %1%;") % DB_TABLE_NAME).str();

    {
        sqlite3_stmt* stmt = NULL;

        int result = sqlite3_prepare(
            mConnection,
            delete_all.c_str(),
            (int) delete_all.size(),
            &stmt,
            NULL);

		{
			if (result == SQLITE_OK) {
				result = sqlite3_step(stmt);
				sqlite3_finalize(stmt);
			}

			success = (result == SQLITE_DONE);

			if (success) {
				std::string vacuum = "VACUUM";

				result = sqlite3_prepare(
					mConnection,
					vacuum.c_str(),
					(int) vacuum.size(),
					&stmt,
					NULL);

				if (result == SQLITE_OK) {
					result = sqlite3_step(stmt);
					sqlite3_finalize(stmt);
				}
			}
		}
    }

    if (success) {
        beginResetModel();
        mEntries.clear();
		mPending.clear();
        endResetModel();
    }
}

void LogListModel::loadEntries() {
    beginResetModel();

    mEntries.clear();
	mPending.clear();

    std::string query = (boost::format(
        " SELECT %1%"
        " FROM %2%"
        " ORDER BY %3% ASC"
		" LIMIT %4%;")
        % DB_ID_COLUMN
        % DB_TABLE_NAME
        % DB_TIME_COLUMN
		% MAX_LOG_SIZE).str();

    sqlite3_stmt* stmt = NULL;

    int result = sqlite3_prepare(
        mConnection,
        query.c_str(),
        (int) query.size(),
        &stmt,
        NULL);

    if (result == SQLITE_OK) {
        while ((result = sqlite3_step(stmt)) == SQLITE_ROW) {
            ID id = (ID) sqlite3_column_int64(stmt, 0);
            mEntries.insert(mEntries.begin(), LogEntry(id, mConnection));
        }
    }

    sqlite3_finalize(stmt);

    endResetModel();
}

void LogListModel::onDebugStringLogged(autom8::debug::debug_level level, std::string tag, std::string message) {
	// if the day has changed since the last cleared old entries, go
	// ahead and clear them now. this isn't bullet proof, but will work
	// most of the time.
	if (QDate::currentDate().dayOfYear() != sLastDayOfYear) {
		clearOldEntries();
	}

	std::string levelStr = "[W]";
	switch (level) {
	case autom8::debug::info: levelStr = "[I]"; break;
	case autom8::debug::warning: levelStr = "[W]"; break;
	case autom8::debug::error: levelStr = "[E]"; break;
	}

	message = levelStr + " [" + tag + "] " + message;

    std::string insert_row = (boost::format(
		" INSERT INTO %1% (%2%, %3%, %4%)"
		" VALUES(NULL, julianday('now'), ?);")
		% DB_TABLE_NAME
		% DB_ID_COLUMN
		% DB_TIME_COLUMN
		% DB_MESSAGE_COLUMN).str();

    sqlite3_stmt* stmt = NULL;

    int result = sqlite3_prepare(
        mConnection,
        insert_row.c_str(),
        (int) insert_row.size(),
        &stmt,
        NULL);

    if (result == SQLITE_OK) {
        sqlite3_bind_text(stmt, 1, message.c_str(), -1, SQLITE_STATIC);
        result = sqlite3_step(stmt);

		if (result == SQLITE_DONE) {
			boost::mutex::scoped_lock lock(mPendingMutex);

			ID id = sqlite3_last_insert_rowid(mConnection);
            mPending.push_back(LogEntry(id, mConnection));
		}
    }

    if (stmt) {
        sqlite3_finalize(stmt);
    }
}

void LogListModel::onTimerTick() {
	if (mPending.size() > 0) {
        beginResetModel();

		{
			boost::mutex::scoped_lock lock(mPendingMutex);

			for (size_t i = 0; i < mPending.size(); i++) {
				mEntries.insert(mEntries.begin(), mPending[i]);
			}

			const int toRemove = ((int) mEntries.size() - MAX_LOG_SIZE);
			for (int i = toRemove; i > 0; i--) {
				mEntries.pop_back();
			}

			mPending.clear();
		}

		endTransaction(mConnection);
        endResetModel();

		beginTransaction(mConnection);
	}
}

int	LogListModel::columnCount(const QModelIndex & parent) const {
	return (int) sColumnHeaders.size();
}

QVariant LogListModel::data(const QModelIndex & index, int role) const {
	if (role == Qt::DisplayRole) {
		switch (index.column())
		{
		case TIME_COLUMN:
			return QVariant(mEntries[index.row()].time());

		case MESSAGE_COLUMN:
			return QVariant(mEntries[index.row()].message());
		}
	}

	return QVariant();
}

QModelIndex	LogListModel::index(int row, int column, const QModelIndex & parent) const {
	return createIndex(row, column);
}

QModelIndex	LogListModel::parent(const QModelIndex & index) const {
	return QModelIndex();
}

int	LogListModel::rowCount(const QModelIndex & parent) const {
	if (parent == QModelIndex())
	{
		return (int) mEntries.size();
	}

	return 0;
}

QVariant LogListModel::headerData(int section, Qt::Orientation orientation, int role) const {
	if (role == Qt::DisplayRole)
	{
		return sColumnHeaders.find(section)->second;
	}

	return QVariant();
}

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

inline QString QueryColumnString(sqlite3* connection, long long id, const char* column) {
    QString value;

    std::string query = (boost::format(
        " SELECT %1%"
        " FROM %2%"
        " WHERE id=%3%;")
        % column
        % DB_TABLE_NAME
        % id).str();

    sqlite3_stmt* stmt = NULL;

    int result = sqlite3_prepare(
        connection,
        query.c_str(),
        (int) query.size(),
        &stmt,
        NULL);

    if (result == SQLITE_OK) {
        result = sqlite3_step(stmt);

        if (result == SQLITE_ROW) {
			value = QString::fromUtf8((const char *) sqlite3_column_text(stmt, 0));
        }
    }

    sqlite3_finalize(stmt);

    return value;
}

inline QString QueryColumnTime(sqlite3* connection, long long id, const char* column) {
    QString value;

    std::string query = (boost::format(
        " SELECT datetime(%1%, 'localtime')"
        " FROM %2%"
        " WHERE id=%3%;")
        % column
        % DB_TABLE_NAME
        % id).str();

    sqlite3_stmt* stmt = NULL;

    int result = sqlite3_prepare(
        connection,
        query.c_str(),
        (int) query.size(),
        &stmt,
        NULL);

    if (result == SQLITE_OK) {
        result = sqlite3_step(stmt);

        if (result == SQLITE_ROW) {
			value = QString::fromUtf8((const char *) sqlite3_column_text(stmt, 0));
        }
    }

    sqlite3_finalize(stmt);

    return value;
}

LogListModel::LogEntry::LogEntry(ID id, sqlite3* connection)
: mId(id)
, mConnection(connection)
{
}

QString LogListModel::LogEntry::time() const {
    return QueryColumnTime(mConnection, mId, DB_TIME_COLUMN);
}

QString LogListModel::LogEntry::message() const {
    return QueryColumnString(mConnection, mId, DB_MESSAGE_COLUMN);
}


text:
#pragma once

#include <string>
#include <fstream>

#include <boost/algorithm/string/case_conv.hpp>

#include <msw/throw_runtime_error.hpp>

#include <rubetek/essence/unique_id/controller.hpp>

namespace rubetek    {
namespace controller {

    inline unique_controller_id::type read_unique_id(std::string const& filename)
    {
        std::ifstream unique_id_file(filename);
        if (!unique_id_file.good()) msw::throw_runtime_error("can't open file with unique id: '", filename, "'");
        unique_controller_id::type unique_id;
        unique_id_file >> unique_id;
        boost::to_lower(unique_id);
        return std::move(unique_id);
    }

}}

ext: hpp

max_stars_repo_name: yklishevich/RubetekIOS-CPP-releases

max_issues_repo_name: yklishevich/RubetekIOS-CPP-releases

max_forks_repo_name: yklishevich/RubetekIOS-CPP-releases


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

#include <boost/assign/list_of.hpp>

#include <sstream>

#include "bgp/bgp_factory.h"
#include "bgp/bgp_session_manager.h"
#include "bgp/bgp_xmpp_channel.h"
#include "bgp/test/bgp_server_test_util.h"
#include "bgp/xmpp_message_builder.h"
#include "control-node/control_node.h"
#include "control-node/test/network_agent_mock.h"
#include "io/test/event_manager_test.h"

static const char *config_template_21 = "\
<config>\
    <bgp-router name=\'X\'>\
        <autonomous-system>1</autonomous-system>\
        <identifier>192.168.0.1</identifier>\
        <address>127.0.0.1</address>\
        <port>%d</port>\
        <session to=\'Y\'>\
            <address-families>\
                <family>e-vpn</family>\
                <family>route-target</family>\
                <family>inet-vpn</family>\
                <family>erm-vpn</family>\
            </address-families>\
        </session>\
        <sub-cluster name='subcluster1'/>\
    </bgp-router>\
    <bgp-router name=\'Y\'>\
        <autonomous-system>1</autonomous-system>\
        <identifier>192.168.0.2</identifier>\
        <address>127.0.0.2</address>\
        <port>%d</port>\
        <session to=\'X\'>\
            <address-families>\
                <family>e-vpn</family>\
                <family>route-target</family>\
                <family>inet-vpn</family>\
                <family>erm-vpn</family>\
            </address-families>\
        </session>\
        <sub-cluster name='subcluster2'/>\
    </bgp-router>\
    <sub-cluster name='subcluster1'>\
        <sub-cluster-asn>199</sub-cluster-asn>\
    </sub-cluster>\
    <sub-cluster name='subcluster2'>\
        <sub-cluster-asn>299</sub-cluster-asn>\
    </sub-cluster>\
</config>\
";

//
// Control Nodes X and Y.
// Agents A and B.
//
class BgpSubClusterIntegrationTest : public ::testing::Test {
protected:
    BgpSubClusterIntegrationTest() :
            thread_(&evm_), xs_x_(NULL), xs_y_(NULL) {
    }

    virtual void SetUp() {
        bs_x_.reset(new BgpServerTest(&evm_, "X"));
        bs_x_->session_manager()->Initialize(0);
        LOG(DEBUG, "Created BGP server at port: " <<
            bs_x_->session_manager()->GetPort());
        xs_x_ = new XmppServer(&evm_, test::XmppDocumentMock::kControlNodeJID);
        xs_x_->Initialize(0, false);
        LOG(DEBUG, "Created XMPP server at port: " <<
            xs_x_->GetPort());
        cm_x_.reset(
            new BgpXmppChannelManager(xs_x_, bs_x_.get()));

        bs_y_.reset(new BgpServerTest(&evm_, "Y"));
        bs_y_->session_manager()->Initialize(0);
        LOG(DEBUG, "Created BGP server at port: " <<
            bs_y_->session_manager()->GetPort());
        xs_y_ = new XmppServer(&evm_, test::XmppDocumentMock::kControlNodeJID);
        xs_y_->Initialize(0, false);
        LOG(DEBUG, "Created XMPP server at port: " <<
            xs_y_->GetPort());
        cm_y_.reset(
            new BgpXmppChannelManager(xs_y_, bs_y_.get()));

        thread_.Start();
    }

    virtual void TearDown() {
        xs_x_->Shutdown();
        task_util::WaitForIdle();
        bs_x_->Shutdown();
        task_util::WaitForIdle();
        cm_x_.reset();

        xs_y_->Shutdown();
        task_util::WaitForIdle();
        bs_y_->Shutdown();
        task_util::WaitForIdle();
        cm_y_.reset();

        TcpServerManager::DeleteServer(xs_x_);
        xs_x_ = NULL;
        TcpServerManager::DeleteServer(xs_y_);
        xs_y_ = NULL;

        if (agent_a_)
            agent_a_->Delete();
        if (agent_b_)
            agent_b_->Delete();
        if (agent_c_)
            agent_c_->Delete();
        if (agent_d_)
            agent_d_->Delete();

        evm_.Shutdown();
        thread_.Join();
        task_util::WaitForIdle();
    }

    void Configure(BgpServerTestPtr server, const char *cfg_template) {
        char config[4096];
        snprintf(config, sizeof(config), cfg_template,
                 server->session_manager()->GetPort());
        server->Configure(config);
    }

    void Configure(const char *cfg_template = config_template_21) {
        char config[4096];
        snprintf(config, sizeof(config), cfg_template,
                 bs_x_->session_manager()->GetPort(),
                 bs_y_->session_manager()->GetPort());
        bs_x_->Configure(config);
        bs_y_->Configure(config);
    }

    EventManager evm_;
    ServerThread thread_;
    BgpServerTestPtr bs_x_;
    BgpServerTestPtr bs_y_;
    XmppServer *xs_x_;
    XmppServer *xs_y_;
    test::NetworkAgentMockPtr agent_a_;
    test::NetworkAgentMockPtr agent_b_;
    test::NetworkAgentMockPtr agent_c_;
    test::NetworkAgentMockPtr agent_d_;
    boost::scoped_ptr<BgpXmppChannelManager> cm_x_;
    boost::scoped_ptr<BgpXmppChannelManager> cm_y_;
};

// Bring up agents with matching subcluster names.
TEST_F(BgpSubClusterIntegrationTest, ClusterNameMatch1) {
    Configure();
    task_util::WaitForIdle();

    // Create XMPP Agent A connected to XMPP server X.
    agent_a_.reset(
        new test::NetworkAgentMock(&evm_, "agent-a", xs_x_->GetPort(),
            "127.0.0.1", "127.0.0.1", false, "subcluster1"));

    // Create XMPP Agent B connected to XMPP server Y.
    agent_b_.reset(
        new test::NetworkAgentMock(&evm_, "agent-b", xs_y_->GetPort(),
            "127.0.0.2", "127.0.0.2", false, "subcluster2"));

    task_util::WaitForIdle();
    TASK_UTIL_EXPECT_TRUE(agent_a_->IsEstablished());
    TASK_UTIL_EXPECT_TRUE(agent_b_->IsEstablished());

    // Close the sessions.
    agent_a_->SessionDown();
    agent_b_->SessionDown();
}

// Bring up agents with matching subcluster names. Then send a new connection
// request with mis-matching subcluster names. This new connection request
// should be ignored.
TEST_F(BgpSubClusterIntegrationTest, ClusterNameMatch2) {
    Configure();
    task_util::WaitForIdle();

    // Create XMPP Agent A connected to XMPP server X.
    agent_a_.reset(
        new test::NetworkAgentMock(&evm_, "agent-a", xs_x_->GetPort(),
            "127.0.0.1", "127.0.0.1", false, "subcluster1"));

    // Create XMPP Agent B connected to XMPP server Y.
    agent_b_.reset(
        new test::NetworkAgentMock(&evm_, "agent-b", xs_y_->GetPort(),
            "127.0.0.2", "127.0.0.2", false, "subcluster2"));

    task_util::WaitForIdle();
    TASK_UTIL_EXPECT_TRUE(agent_a_->IsEstablished());
    TASK_UTIL_EXPECT_TRUE(agent_b_->IsEstablished());

    // Try a new connection with mismatch in subcluster name.
    agent_c_.reset(
        new test::NetworkAgentMock(&evm_, "agent-a", xs_x_->GetPort(),
            "127.0.0.1", "127.0.0.1", false, "subcluster11"));
    agent_d_.reset(
        new test::NetworkAgentMock(&evm_, "agent-b", xs_y_->GetPort(),
            "127.0.0.2", "127.0.0.2", false, "subcluster21"));

    task_util::WaitForIdle();
    TASK_UTIL_EXPECT_TRUE(agent_a_->IsEstablished());
    TASK_UTIL_EXPECT_TRUE(agent_b_->IsEstablished());
    TASK_UTIL_EXPECT_FALSE(agent_c_->IsEstablished());
    TASK_UTIL_EXPECT_FALSE(agent_d_->IsEstablished());

    // Close the sessions.
    agent_a_->SessionDown();
    agent_b_->SessionDown();
    agent_c_->SessionDown();
    agent_d_->SessionDown();
}

// Bring up agents with mis-matching subcluster names.
TEST_F(BgpSubClusterIntegrationTest, ClusterNameMisMatch1) {
    Configure();
    task_util::WaitForIdle();

    // Create XMPP Agent A connected to XMPP server X.
    agent_a_.reset(
        new test::NetworkAgentMock(&evm_, "agent-a", xs_x_->GetPort(),
            "127.0.0.1", "127.0.0.1", false, "subcluster11"));

    // Create XMPP Agent B connected to XMPP server Y.
    agent_b_.reset(
        new test::NetworkAgentMock(&evm_, "agent-b", xs_y_->GetPort(),
            "127.0.0.2", "127.0.0.2", false, "subcluster21"));

    task_util::WaitForIdle();
    TASK_UTIL_EXPECT_FALSE(agent_a_->IsEstablished());
    TASK_UTIL_EXPECT_FALSE(agent_b_->IsEstablished());

    // Close the sessions.
    agent_a_->SessionDown();
    agent_b_->SessionDown();
}

// Start with sub-cluster name mismatch and then update to match.
TEST_F(BgpSubClusterIntegrationTest, ClusterNameMisMatch2) {
    Configure();
    task_util::WaitForIdle();

    // Create XMPP Agent A connected to XMPP server X.
    agent_a_.reset(
        new test::NetworkAgentMock(&evm_, "agent-a", xs_x_->GetPort(),
            "127.0.0.1", "127.0.0.1", false, "subcluster11"));

    // Create XMPP Agent B connected to XMPP server Y.
    agent_b_.reset(
        new test::NetworkAgentMock(&evm_, "agent-b", xs_y_->GetPort(),
            "127.0.0.2", "127.0.0.2", false, "subcluster21"));

    task_util::WaitForIdle();
    TASK_UTIL_EXPECT_FALSE(agent_a_->IsEstablished());
    TASK_UTIL_EXPECT_FALSE(agent_b_->IsEstablished());

    agent_c_.reset(
        new test::NetworkAgentMock(&evm_, "agent-a", xs_x_->GetPort(),
            "127.0.0.1", "127.0.0.1", false, "subcluster1"));

    // Create XMPP Agent B connected to XMPP server Y.
    agent_d_.reset(
        new test::NetworkAgentMock(&evm_, "agent-b", xs_y_->GetPort(),
            "127.0.0.2", "127.0.0.2", false, "subcluster2"));

    task_util::WaitForIdle();
    TASK_UTIL_EXPECT_FALSE(agent_a_->IsEstablished());
    TASK_UTIL_EXPECT_FALSE(agent_b_->IsEstablished());
    TASK_UTIL_EXPECT_TRUE(agent_c_->IsEstablished());
    TASK_UTIL_EXPECT_TRUE(agent_d_->IsEstablished());

    // Close the sessions.
    agent_a_->SessionDown();
    agent_b_->SessionDown();
    agent_c_->SessionDown();
    agent_d_->SessionDown();
}

class TestEnvironment : public ::testing::Environment {
    virtual ~TestEnvironment() { }
    virtual void SetUp() {
    }
    virtual void TearDown() {
    }
};

static void SetUp() {
    BgpServer::Initialize();
    ControlNode::SetDefaultSchedulingPolicy();
    BgpServerTest::GlobalSetUp();
    BgpObjectFactory::Register<StateMachine>(
        boost::factory<StateMachineTest *>());
    BgpObjectFactory::Register<BgpXmppMessageBuilder>(
        boost::factory<BgpXmppMessageBuilder *>());
}
static void TearDown() {
    BgpServer::Terminate();
    TaskScheduler *scheduler = TaskScheduler::GetInstance();
    scheduler->Terminate();
}

int main(int argc, char **argv) {
    bgp_log_test::init();
    ::testing::InitGoogleTest(&argc, argv);
    ::testing::AddGlobalTestEnvironment(new TestEnvironment());
    SetUp();
    int result = RUN_ALL_TESTS();
    TearDown();

    return result;
}

ext: cc

max_stars_repo_name: jnpr-pranav/contrail-controller

max_issues_repo_name: jnpr-pranav/contrail-controller

max_forks_repo_name: jnpr-pranav/contrail-controller


text:
// Copyright (c) 2017 Daniel Cooke
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.

#define BOOST_TEST_DYN_LINK

#include <boost/test/unit_test.hpp>

#include <vector>

#include "mappable/contig_region.hpp"
#include "mappable/mappable.hpp"
#include "mappable/mappable_algorithms.hpp"

namespace mappable { namespace test {

BOOST_AUTO_TEST_SUITE(mappable_algorithms)

BOOST_AUTO_TEST_SUITE_END()

} // namespace test
} // namespace mappable

ext: cpp

max_stars_repo_name: dancooke/mappable

max_issues_repo_name: dancooke/mappable

max_forks_repo_name: dancooke/mappable


text:
/*  Sirikata
 *  asyncCraqSet.cpp
 *
 *  Copyright (c) 2010, Behram Mistree
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are
 *  met:
 *  * Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *  * Neither the name of Sirikata nor the names of its contributors may
 *    be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "asyncCraqSet.hpp"
#include <iostream>
#include <boost/bind.hpp>
#include <string.h>
#include <sstream>
#include <boost/regex.hpp>
#include <boost/asio.hpp>

#include "../asyncCraqUtil.hpp"
#include "asyncConnectionSet.hpp"
#include <sirikata/core/network/IOStrandImpl.hpp>
#include "../../CraqObjectSegmentation.hpp"
#include <functional>
#include <sirikata/core/network/Asio.hpp>

#define CRAQ_MAX_PUSH_SET 5

namespace Sirikata
{

  void AsyncCraqSet::stop()
  {
#ifdef ASYNC_CRAQ_SET_DEBUG
    std::cout<<"\n\nReceived a stop in async craq set\n";
#endif
    for (int s=0; s < (int) mConnections.size(); ++s)
      mConnectionsStrands[s]->post(std::tr1::bind(&AsyncConnectionSet::stop,mConnections[s]));
  }

  AsyncCraqSet::~AsyncCraqSet()
  {
    for (int s= 0;s < (int) mConnections.size(); ++s)
    {
      delete mConnectionsStrands[s];
      delete mConnections[s];
    }
    mConnections.clear();
    mConnectionsStrands.clear();
  }

  AsyncCraqSet::AsyncCraqSet(SpaceContext* con, Network::IOStrand* strand_this_runs_on, Network::IOStrand* strand_to_post_results_to, CraqObjectSegmentation* parent_oseg_called)
   : ctx(con),
      mStrand(strand_this_runs_on),
      mResultsStrand(strand_to_post_results_to),
      mOSeg(parent_oseg_called)
  {
  }

  void AsyncCraqSet::initialize(std::vector<CraqInitializeArgs> ipAddPort)
  {
#ifdef ASYNC_CRAQ_SET_DEBUG
    std::cout<<"\n\nbftm debug: asynccraqset initialize\n\n";
#endif
    mIpAddPort = ipAddPort;

    Sirikata::Network::TCPResolver resolver(*ctx->ioService);   //a resolver can resolve a query into a series of endpoints.

    for (int s=0; s < STREAM_CRAQ_NUM_CONNECTIONS_SET; ++s)
    {
      Network::IOStrand* tmpStrand = ctx->ioService->createStrand();
      mConnectionsStrands.push_back(tmpStrand);

      AsyncConnectionSet* tmpConn = new AsyncConnectionSet(ctx,                     //space context
                                                           mConnectionsStrands[s],  //strand for this connection to run on.
                                                           mStrand,                 //strand that the connection will return errors on
                                                           mResultsStrand,          //strand that the connection will return results on.
                                                           this,                    //will return errors to this master
                                                           mOSeg,
                                                           std::tr1::bind(&AsyncCraqSet::readyStateChanged,this,s));                   //will return results to this oseg

      mConnections.push_back(tmpConn);
    }

    Sirikata::Network::TCPSocket* passSocket;

    if (((int)ipAddPort.size()) >= STREAM_CRAQ_NUM_CONNECTIONS_SET)
    {
      //just assign each connection a separate router (in order that they were provided).
      for (int s = 0; s < STREAM_CRAQ_NUM_CONNECTIONS_SET; ++s)
      {
        boost::asio::ip::tcp::resolver::query query(boost::asio::ip::tcp::v4(), ipAddPort[s].ipAdd.c_str(), ipAddPort[s].port.c_str());
        boost::asio::ip::tcp::resolver::iterator iterator = resolver.resolve(query);  //creates a list of endpoints that we can try to connect to.
        passSocket   =  new Sirikata::Network::TCPSocket(*ctx->ioService);
        mConnectionsStrands[s]->post(std::tr1::bind(&AsyncConnectionSet::initialize, mConnections[s],passSocket,iterator));

      }
    }
    else
    {
      int whichRouterServingPrevious = -1;
      int whichRouterServing;
      double percentageConnectionsServed;

      boost::asio::ip::tcp::resolver::iterator iterator;

      for (int s=0; s < STREAM_CRAQ_NUM_CONNECTIONS_SET; ++s)
      {
        percentageConnectionsServed = ((double)s)/((double) STREAM_CRAQ_NUM_CONNECTIONS_SET);
        whichRouterServing = (int)(percentageConnectionsServed*((double)ipAddPort.size()));

        if (whichRouterServing  != whichRouterServingPrevious)
        {
          boost::asio::ip::tcp::resolver::query query(boost::asio::ip::tcp::v4(), ipAddPort[whichRouterServing].ipAdd.c_str(), ipAddPort[whichRouterServing].port.c_str());

          iterator = resolver.resolve(query);  //creates a list of endpoints that we can try to connect to.

          whichRouterServingPrevious = whichRouterServing;
        }

        passSocket   =  new Sirikata::Network::TCPSocket (*ctx->ioService);
        mConnectionsStrands[s]->post(std::tr1::bind(&AsyncConnectionSet::initialize, mConnections[s],passSocket,iterator));

      }
    }
  }

  void AsyncCraqSet::set(CraqDataSetGet dataToSet, uint64 track_num)
  {
    //force this to be a set message.
    dataToSet.messageType = CraqDataSetGet::SET;

    if (dataToSet.trackMessage)
    {
      dataToSet.trackingID = track_num;
    }
    pushQueue(dataToSet);

    int numTries = 0;
    while((mQueue.size() != 0) && (numTries < CRAQ_MAX_PUSH_SET))
    {
      ++numTries;
      int rand_connection = rand() % STREAM_CRAQ_NUM_CONNECTIONS_SET;
      checkConnections(rand_connection);
    }
  }

  /*
    Returns the size of the queue of operations to be processed
  */
  int AsyncCraqSet::queueSize()
  {
    return mQueue.size();
  }

  int AsyncCraqSet::numStillProcessing()
  {
    int returner = 0;

    for (int s=0; s < (int)mConnections.size(); ++s)
    {
      returner = returner + ((int)mConnections[s]->numStillProcessing());
    }
    return returner;
  }

  void AsyncCraqSet::erroredGetValue(CraqOperationResult* cor)
  {
#ifdef ASYNC_CRAQ_SET_DEBUG
    std::cout<<"\n\n\nError: should not receive an errored get value call in asyncCraqSet.cpp\n\n";
#endif
    assert(false);
  }

  void AsyncCraqSet::erroredSetValue(CraqOperationResult* errorRes)
  {
    if (errorRes->whichOperation == CraqOperationResult::GET)
    {
#ifdef ASYNC_CRAQ_SET_DEBUG
      std::cout<<"\n\nFailure: trying to perform a get operation from within asynccraqset\n\n";
#endif
      assert(false);
    }
    else
    {
      CraqDataSetGet cdSG(errorRes->objID,errorRes->servID,errorRes->tracking, CraqDataSetGet::SET);
      pushQueue(cdSG);
    }

    delete errorRes;
  }

  void AsyncCraqSet::readyStateChanged(int s) {
      mReadyConnections.push_back(s);
      while (checkConnections(s)) {
          if (mQueue.empty()) {
              break;
          }
      }
  }
  void AsyncCraqSet::pushQueue(const CraqDataSetGet&dataToSet){
      mQueue.push(dataToSet);//push and try to empty the queue
      while (!mReadyConnections.empty()) {
          unsigned int rnd=rand()%mReadyConnections.size();
          if (checkConnections(mReadyConnections[rnd])) {
              if (mQueue.empty()) {
                  break;
              }
          }else {
              mReadyConnections[rnd]=mReadyConnections.back();
              mReadyConnections.pop_back();
          }
      }
  }
  /*
    This function checks connection s to see if it needs a new socket or if it's ready to accept another query.
  */
  bool AsyncCraqSet::checkConnections(int s)
  {
    if (s>=(int)mConnections.size()) {
        return false;
    }
    assert (s<(int)mConnections.size());

    int numOperations = 0;

    if (mConnections[s]->ready() == AsyncConnectionSet::READY)
    {
      if (mQueue.size() != 0)
      {
        //need to put in another
        CraqDataSetGet cdSG = mQueue.front();
        mQueue.pop();

        ++numOperations;

        if (cdSG.messageType == CraqDataSetGet::GET)
        {
#ifdef ASYNC_CRAQ_SET_DEBUG
          std::cout<<"\n\nTrying to deal with get message in async craq set.cpp\n\n";
#endif
          assert(false);
        }
        else if (cdSG.messageType == CraqDataSetGet::SET)
        {
          //performing a set in connections.
          CraqObjectID tmpCraqID;
          memcpy(tmpCraqID.cdk, cdSG.dataKey, CRAQ_DATA_KEY_SIZE);
          mConnections[s]->setProcessing();
          mConnectionsStrands[s]->post(std::tr1::bind(&AsyncConnectionSet::setBound, mConnections[s], tmpCraqID, cdSG.dataKeyValue, cdSG.trackMessage, cdSG.trackingID));
        }
      }
    }
    else if (mConnections[s]->ready() == AsyncConnectionSet::NEED_NEW_SOCKET)
    {
      //need to create a new socket for the other
      reInitializeNode(s);
#ifdef ASYNC_CRAQ_SET_DEBUG
      std::cout<<"\n\nbftm debug: needed new connection.  How long will this take? \n\n";
#endif
    }
    else
    {
        return false;
    }
    return true;
  }

//means that we need to connect a new socket to the service.
void AsyncCraqSet::reInitializeNode(int s)
{
  if (s >= (int)mConnections.size())
    return;

  Sirikata::Network::TCPSocket* passSocket;

  Sirikata::Network::TCPResolver resolver(*ctx->ioService);   //a resolver can resolve a query into a series of endpoints.

  if ( ((int)mIpAddPort.size()) >= STREAM_CRAQ_NUM_CONNECTIONS_SET)
  {
    boost::asio::ip::tcp::resolver::query query(boost::asio::ip::tcp::v4(), mIpAddPort[s].ipAdd.c_str(), mIpAddPort[s].port.c_str());
    boost::asio::ip::tcp::resolver::iterator iterator = resolver.resolve(query);  //creates a list of endpoints that we can try to connect to.
    passSocket   =  new Sirikata::Network::TCPSocket(*ctx->ioService);

    mConnectionsStrands[s]->post(std::tr1::bind(&AsyncConnectionSet::initialize, mConnections[s],passSocket,iterator));
  }
  else
  {

    boost::asio::ip::tcp::resolver::iterator iterator;

    double percentageConnectionsServed = ((double)s)/((double) STREAM_CRAQ_NUM_CONNECTIONS_SET);
    int whichRouterServing = (int)(percentageConnectionsServed*((double)mIpAddPort.size()));

    boost::asio::ip::tcp::resolver::query query(boost::asio::ip::tcp::v4(), mIpAddPort[whichRouterServing].ipAdd.c_str(), mIpAddPort[whichRouterServing].port.c_str());
    iterator = resolver.resolve(query);  //creates a list of endpoints that we can try to connect to.

    passSocket   =  new Sirikata::Network::TCPSocket(*ctx->ioService);
    mConnectionsStrands[s]->post(std::tr1::bind(&AsyncConnectionSet::initialize, mConnections[s],passSocket,iterator));
  }
}

}//end namespace

max_stars_repo_name: pathorn/sirikata

max_issues_repo_name: pathorn/sirikata

max_forks_repo_name: pathorn/sirikata


text: #include <boost/spirit/home/karma/directive/as.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include <KLocalizedString>
#include <KConfigCore/KConfig>
#include <KConfigCore/KConfigGroup>

#include <QApplication>
#include <QClipboard>

#include <boost/asio/io_service.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/write.hpp>
#include <boost/algorithm/string.hpp>

#include <iostream>
#include <QtCore/QtCore>

#include "konohazku.hpp"

#define MAIN_PORT 3329
#define BACKUP_PORT 5829

using namespace std;
using namespace boost::asio;

io_service ioservice;
ip::tcp::socket tcp_socket {ioservice};
array<char, 4096> bytes;

string sendString;
string recvString;

void boost::throw_exception(std::exception const &exception) {
    // TODO: Do exception handling
}

KonohaZku::KonohaZku(QObject *parent, const QVariantList &args)
    : Plasma::AbstractRunner(parent, args) {
    Q_UNUSED(args);

    // General runner configuration
    setObjectName(QLatin1String("KonohaZku"));
    setHasRunOptions(true);
    setIgnoredTypes(Plasma::RunnerContext::Directory |
                    Plasma::RunnerContext::File |
                    Plasma::RunnerContext::NetworkLocation);
    setSpeed(Plasma::AbstractRunner::NormalSpeed);
    setPriority(HighestPriority);
    setDefaultSyntax(
        Plasma::RunnerSyntax(
            QString::fromLatin1(":q:"),
            i18n("Sends :q: query to Zku, and retrieves data.")
        )
    );
}

KonohaZku::~KonohaZku() {
}

void KonohaZku::match(Plasma::RunnerContext &context) {
    if (!context.isValid())
        return;

    // Cancel if there is any ongoing request
    if (tcp_socket.is_open()) {
        tcp_socket.close();
    }

    const QString enteredKey = context.query();
    sendString = enteredKey.toStdString();
    recvString = string("");

    ip::tcp::endpoint server_endpoint(ip::address::from_string("127.0.0.1"), MAIN_PORT);
    boost::system::error_code ec;
    tcp_socket.connect(server_endpoint, ec);
    if (ec) {
        return;
    }
    write(tcp_socket, buffer(sendString));

    tcp_socket.receive(buffer(bytes));
    recvString.append(bytes.data());

    // Process response
    vector<std::string> responseVector;
    boost::split(responseVector, recvString, boost::is_any_of("\n"));
    std::string sender("");

    for (int i = 0; i < responseVector.size(); i++) {
        if (boost::starts_with(responseVector[i], "sender")) {
            string::size_type equalPosition = responseVector[i].find("=", 0);
            if (equalPosition == string::npos) {
                // Cannot do anything
                return;
            }
            sender = responseVector[i].substr(equalPosition + 1, string::npos);
        }
        else if (boost::starts_with(responseVector[i], "response")) {
            string::size_type equalPosition = responseVector[i].find("=", 0);
            if (equalPosition == string::npos) {
                // Cannot do anything
                return;
            }
            std::string actualContent = responseVector[i].substr(equalPosition + 1, string::npos);
            string::size_type colonPosition = actualContent.find(":", 0);
            if (colonPosition == string::npos) {
                // No numbering in response, possible old response protocol? (<=ZSMP 0.4)
                Plasma::QueryMatch match(this);
                match.setType(Plasma::QueryMatch::ExactMatch);
                match.setData("zku");
                match.setText(actualContent.data());
                match.setSubtext(sender.data());
                match.setIcon(QIcon::fromTheme("preferences-desktop-font"));

                context.addMatch(match);
            }
            else {
                std::string responseNumber = actualContent.substr(0, colonPosition);

                Plasma::QueryMatch match(this);
                match.setType(Plasma::QueryMatch::ExactMatch);
                match.setData("zku");
                match.setText(actualContent.data());
                match.setSubtext(sender.append(":").append(responseNumber).data());
                match.setIcon(QIcon::fromTheme("preferences-desktop-font"));

                context.addMatch(match);
            }
        }
    }

    tcp_socket.close();
}

/**
 * Perform an action when a user chooses one of the previously found matches.
 * Either some string gets copied to the clipboard, a file/path/URL is being opened,
 * or a command is being executed.
 */
void KonohaZku::run(const Plasma::RunnerContext &context, const Plasma::QueryMatch &match) {
    Q_UNUSED(context);

    if (match.data().toString().compare("open") == 0) {
        // Open a file or a URL in a (file/web) browser
        // (in a new process, so that krunner doesn't get stuck while opening the path)
        string command = "kde-open " + match.text().remove("→ ").toStdString() + " &";
        system(command.c_str());
    }
    else if (match.data().toString().compare("execute") == 0) {
        // Execute a command
        // (in a new process, so that krunner doesn't get stuck while opening the path)
        string command = match.text().remove(">_ ").toStdString() + " &";
        system(command.c_str());
    }
    else {
        // Copy the result to clipboard
        QApplication::clipboard()->setText(match.text());
    }
}

K_EXPORT_PLASMA_RUNNER(konohazku, KonohaZku)

#include "konohazku.moc"

max_stars_repo_name: Mnkai/KonohaZku

max_issues_repo_name: Mnkai/KonohaZku

max_forks_repo_name: Mnkai/KonohaZku


text:
/*
 * Copyright (C) 2019 by AutoSense Organization. All rights reserved.
 * Gary Chan <chenshj35@mail2.sysu.edu.cn>
 */

#ifndef COMMON_INCLUDE_COMMON_TRANSFORM_HPP_
#define COMMON_INCLUDE_COMMON_TRANSFORM_HPP_

#include <geometry_msgs/Point.h>  // geometry_msgs::Point
#include <ros/ros.h>
#include <tf/transform_listener.h>    // tf::TransformListener
#include <tf_conversions/tf_eigen.h>  // tf::transformTFToEigen

#include <Eigen/Core>
#include <string>
#include <vector>

#include "common/types/object.hpp"  // ObjectPtr

namespace autosense {
namespace common {
namespace transform {

static bool getVelodynePose(const tf::TransformListener& tf_buffer,
                            const std::string& source_frame,
                            const std::string& target_frame,
                            const double& query_time,
                            Eigen::Matrix4d* trans) {
    if (trans == nullptr) {
        ROS_ERROR("Failed to get trans, the trans ptr can not be NULL.");
        return false;
    }

    ros::Time query_stamp(query_time);
    tf::StampedTransform transform_stamped;
    try {
        tf_buffer.lookupTransform(target_frame, source_frame, query_stamp,
                                  transform_stamped);
    } catch (tf2::TransformException& ex) {
        ROS_WARN(
            "Failed to query pose at %lf, use latest available pose instead.",
            query_time);
        try {
            tf_buffer.lookupTransform(target_frame, source_frame, ros::Time(0),
                                      transform_stamped);
        } catch (tf2::TransformException& ex) {
            ROS_ERROR_STREAM("Exception: " << ex.what());
            return false;
        }
    }
    Eigen::Affine3d affine_3d;
    tf::transformTFToEigen(transform_stamped, affine_3d);
    *trans = affine_3d.matrix();

    ROS_INFO_STREAM("Get " << source_frame << " to " << target_frame
                           << " trans: \n"
                           << *trans);

    return true;
}

static void transformGroundBox(const Eigen::Matrix4d& trans,
                               Eigen::Vector3d* position) {
    Eigen::Vector3d& center = *position;
    center =
        (trans * Eigen::Vector4d(center[0], center[1], center[2], 1)).head(3);
}

template <typename PointT>
static void transformPoint(const Eigen::Matrix4d& trans, PointT* position) {
    Eigen::Vector3d center =
        (trans *
         Eigen::Vector4d((*position).x, (*position).y, (*position).z, 1))
            .head(3);
    (*position).x = center(0);
    (*position).y = center(1);
    (*position).z = center(2);
}

static void transformDirection(const Eigen::Matrix4d& trans,
                               Eigen::Vector3d* position) {
    Eigen::Vector3d& center = *position;
    center =
        (trans * Eigen::Vector4d(center[0], center[1], center[2], 0)).head(3);
}

static void transformVelocity(const Eigen::Matrix4d& trans,
                              Eigen::Vector3d* position) {
    transformDirection(trans, position);
}

template <typename PointT>
static void transformPointCloud(
    const Eigen::Matrix4d& trans_mat,
    typename pcl::PointCloud<PointT>::Ptr cloud_in_out) {
    assert(cloud_in_out.get() != nullptr);

    for (size_t i = 0u; i < cloud_in_out->size(); ++i) {
        PointT& p = cloud_in_out->at(i);
        // ROS_WARN("Original: (%lf, %lf, %lf)", p.x, p.y, p.z);
        Eigen::Vector4d v(p.x, p.y, p.z, 1.);
        v = trans_mat * v;
        p.x = v(0);
        p.y = v(1);
        p.z = v(2);
        // ROS_INFO("Transformed: (%lf, %lf, %lf)", p.x, p.y, p.z);
    }
}

/**
 * @brief
 *  needed for PointICloud-converted tyoe, can't use Ptr
 *  common::geometry::transformPointCloud<PointD>
 * @tparam PointT
 * @param trans_mat
 * @param cloud_in_out
 */
template <typename PointT>
static void transformPointCloud(
    const Eigen::Matrix4d& trans_mat,
    typename pcl::PointCloud<PointT>& cloud_in_out) {  // NOLINT
    for (size_t i = 0u; i < cloud_in_out.size(); ++i) {
        PointT& p = cloud_in_out.at(i);
        Eigen::Vector4d v(p.x, p.y, p.z, 1.);
        v = trans_mat * v;
        p.x = v(0);
        p.y = v(1);
        p.z = v(2);
    }
}

/**
 * @brief transform object with given pose
 * @params[IN] pose: pose using for coordinate transformation
 * @params[OUT] obj: object for transfromation
 * @return nothing
 */
static void transformBuiltObject(const Eigen::Matrix4d& pose, ObjectPtr obj) {
    /*Eigen::Vector3d& dir = obj->direction;
    dir = (pose * Eigen::Vector4d(dir[0], dir[1], dir[2], 0)).head(3);*/
    transformDirection(pose, &(obj->direction));
    // transform center
    transformGroundBox(pose, &(obj->ground_center));
    /*Eigen::Vector3d& center = obj->ground_center;
    center = (pose * Eigen::Vector4d(center[0], center[1], center[2],
    1)).head(3);*/
    // transform cloud & polygon
    transformPointCloud<PointI>(pose, obj->cloud);
    // PointDCloudPtr polygon(&((*obj)->polygon));
    transformPointCloud<PointD>(pose, obj->polygon);
}

static void transformBuiltObjects(const Eigen::Matrix4d& transform_to_mat,
                                  std::vector<ObjectPtr>* objects) {
    for (size_t i = 0u; i < (*objects).size(); ++i) {
        transformBuiltObject(transform_to_mat, (*objects)[i]);
    }
}

}  // namespace transform
}  // namespace common
}  // namespace autosense

#endif  // COMMON_INCLUDE_COMMON_TRANSFORM_HPP_


text:
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE UIIDPicker
#include <boost/test/unit_test.hpp>

#define ALLEGRO_UNSTABLE

#include <allegro_flare/ui_picking_buffer.h>

using namespace allegro_flare;

struct Setup
{
   Setup()
   {
      BOOST_REQUIRE_EQUAL(false, al_is_system_installed());
      BOOST_REQUIRE_EQUAL(true, al_init());
   }
   ~Setup()
   {
      al_uninstall_system();
   }
};

struct SetupWithDisplay
{
   ALLEGRO_DISPLAY *display;
   SetupWithDisplay()
      : display(NULL)
   {
      BOOST_REQUIRE_EQUAL(false, al_is_system_installed());
      BOOST_REQUIRE_EQUAL(true, al_init());

      display = al_create_display(800, 600);
      BOOST_REQUIRE_NE((void *)0, display);
   }
   ~SetupWithDisplay()
   {
      al_uninstall_system();
   }
};

BOOST_FIXTURE_TEST_CASE(decodes_transparent_to_ID_0, Setup)
{
   ALLEGRO_COLOR color = al_map_rgba(0, 0, 0, 0);
   int decoded_id = UIPickingBuffer::decode_id(color);

   BOOST_CHECK_EQUAL(0, decoded_id);
}

BOOST_FIXTURE_TEST_CASE(encodes_ID_0_to_transparent, Setup)
{
   ALLEGRO_COLOR color = UIPickingBuffer::encode_id(0);

   unsigned char r, g, b, a;
   al_unmap_rgba(color, &r, &g, &b, &a);

   BOOST_CHECK_EQUAL(0, r);
   BOOST_CHECK_EQUAL(0, g);
   BOOST_CHECK_EQUAL(0, b);
   BOOST_CHECK_EQUAL(0, a);
}

BOOST_FIXTURE_TEST_CASE(encodes_IDs_greater_than_0_with_an_alpha_of_255__test_1, Setup)
{
   ALLEGRO_COLOR color = UIPickingBuffer::encode_id(1);

   unsigned char r, g, b, a;
   al_unmap_rgba(color, &r, &g, &b, &a);

   BOOST_CHECK_EQUAL(255, a);
}

BOOST_FIXTURE_TEST_CASE(encodes_IDs_greater_than_0_with_an_alpha_of_255__test_2, Setup)
{
   for (unsigned i=1; i<1000; i++)
   {
      ALLEGRO_COLOR color = UIPickingBuffer::encode_id(i);
      unsigned char r, g, b, a;
      al_unmap_rgba(color, &r, &g, &b, &a);

      BOOST_CHECK_EQUAL(255, a);
   }
}

BOOST_FIXTURE_TEST_CASE(encodes_all_numbers_less_than_UIPickingBuffer_ID_MAX, Setup)
{
   for (int i=0; i<UIPickingBuffer::ID_MAX; i++)
   {
      int encoded_num = UIPickingBuffer::decode_id(UIPickingBuffer::encode_id(i));
      BOOST_CHECK_EQUAL(i, encoded_num);
   }
}

BOOST_FIXTURE_TEST_CASE(does_not_encode_numbers_greater_than_or_equal_to_UIPickingBuffer_ID_MAX, Setup)
{
   int encoded_num = 0;
   int expected_num = 0;

   encoded_num = UIPickingBuffer::decode_id(UIPickingBuffer::encode_id(UIPickingBuffer::ID_MAX));
   expected_num = UIPickingBuffer::ID_MAX;
   BOOST_CHECK_NE(expected_num, encoded_num);

   encoded_num = UIPickingBuffer::decode_id(UIPickingBuffer::encode_id(UIPickingBuffer::ID_MAX+1));
   expected_num = UIPickingBuffer::ID_MAX+1;
   BOOST_CHECK_NE(expected_num, encoded_num);
}

BOOST_FIXTURE_TEST_CASE(does_not_encode_negative_numbers, Setup)
{
   int encoded_num = UIPickingBuffer::decode_id(UIPickingBuffer::encode_id(-1));
   BOOST_CHECK_NE(-1, encoded_num);
}

BOOST_AUTO_TEST_CASE(builds_an_on_click_id_message)
{
   BOOST_CHECK_EQUAL("on_click_id 42", UIPickingBuffer::compose_on_click_id_message(42));
   BOOST_CHECK_EQUAL("on_click_id 64", UIPickingBuffer::compose_on_click_id_message(64));
   BOOST_CHECK_EQUAL("on_click_id 3", UIPickingBuffer::compose_on_click_id_message(3));
}

BOOST_AUTO_TEST_CASE(extracts_an_id_from_an_on_click_id_message)
{
   BOOST_CHECK_EQUAL(42, UIPickingBuffer::extract_on_click_id("on_click_id 42"));
   BOOST_CHECK_EQUAL(64, UIPickingBuffer::extract_on_click_id("on_click_id 64"));
   BOOST_CHECK_EQUAL(3, UIPickingBuffer::extract_on_click_id("on_click_id 3"));
}

BOOST_AUTO_TEST_CASE(identifies_a_properly_formatted_on_click_id_message)
{
   BOOST_CHECK_EQUAL(true, UIPickingBuffer::is_on_click_id_message("on_click_id 9"));
   BOOST_CHECK_EQUAL(true, UIPickingBuffer::is_on_click_id_message("on_click_id 345678"));
   BOOST_CHECK_EQUAL(true, UIPickingBuffer::is_on_click_id_message("on_click_id 42"));

   BOOST_CHECK_EQUAL(false, UIPickingBuffer::is_on_click_id_message(""));
   BOOST_CHECK_EQUAL(false, UIPickingBuffer::is_on_click_id_message("foo bar"));
   BOOST_CHECK_EQUAL(false, UIPickingBuffer::is_on_click_id_message("on_click_id"));
   BOOST_CHECK_EQUAL(false, UIPickingBuffer::is_on_click_id_message("on_click_id9"));
}

BOOST_FIXTURE_TEST_CASE(creates_a_render_surface_with_or_without_a_depth_buffer, SetupWithDisplay)
{
   UIPickingBuffer *id_picker_1 = new UIPickingBuffer(NULL, 0, 0, 300, 200, 0);
   BOOST_CHECK_EQUAL(0, al_get_bitmap_depth(id_picker_1->surface_render));

   UIPickingBuffer *id_picker_2 = new UIPickingBuffer(NULL, 0, 0, 300, 200, 32);
   BOOST_CHECK_EQUAL(32, al_get_bitmap_depth(id_picker_2->surface_render));
}

BOOST_FIXTURE_TEST_CASE(creates_a_render_surface_without_multisampling, SetupWithDisplay)
{
   al_set_new_bitmap_samples(32);

   UIPickingBuffer *id_picker = new UIPickingBuffer(NULL, 0, 0, 200, 200, 0);
   BOOST_CHECK_EQUAL(0, al_get_bitmap_samples(id_picker->surface_render));

   BOOST_CHECK_EQUAL(32, al_get_new_bitmap_samples());
}

BOOST_FIXTURE_TEST_CASE(recreates_a_render_surface, SetupWithDisplay)
{
   UIPickingBuffer *id_picker = new UIPickingBuffer(NULL, 0, 0, 300, 200, 0);
   BOOST_CHECK_EQUAL(300, al_get_bitmap_width(id_picker->surface_render));
   BOOST_CHECK_EQUAL(200, al_get_bitmap_height(id_picker->surface_render));
   BOOST_CHECK_EQUAL(0, al_get_bitmap_depth(id_picker->surface_render));

   id_picker->create_new_surface(800, 600, 32);
   BOOST_CHECK_EQUAL(800, al_get_bitmap_width(id_picker->surface_render));
   BOOST_CHECK_EQUAL(600, al_get_bitmap_height(id_picker->surface_render));
   BOOST_CHECK_EQUAL(32, al_get_bitmap_depth(id_picker->surface_render));
}


text:
// -*- mode:c++; c-style:k&r; c-basic-offset:4; indent-tabs-mode: nil; -*-
// vi:set et cin sw=4 cino=>se0n0f0{0}0^0\:0=sl1g0hspst0+sc3C0/0(0u0U0w0m0:

#include "cache.hpp"
#include "stdio.h"
#include <boost/function.hpp>
#include <boost/bind.hpp>

#define DEBUG

#define DEBUG
#undef DEBUG

#ifdef DEBUG
#define mh_log(X) cout
#define mh_assert(X) assert(X)
#else
#define mh_assert(X)
#define mh_log(X) LOG(log,X)
#endif

cacheRequest::cacheRequest(maddr_t maddr, cacheReqType_t request_type, uint32_t word_count,
                           shared_array<uint32_t> data_to_write, std::shared_ptr<void> coherence_info_to_write) :
    m_request_type(request_type),
    m_maddr(maddr),
    m_word_count(word_count),
    m_status(CACHE_REQ_NEW),
    m_line_copy(std::shared_ptr<cacheLine>()),
    m_line_to_evict_copy(std::shared_ptr<cacheLine>()),
    m_coherence_info_to_write(coherence_info_to_write),
    m_data_to_write(data_to_write),
    m_aux_info_for_coherence(std::shared_ptr<void>()),
    m_do_unset_dirty_on_write(false),
    m_do_claim(true),
    m_do_evict(true)
{}

cacheRequest::~cacheRequest() {}

cache::cache(uint32_t level, uint32_t id, const uint64_t &t, std::shared_ptr<tile_statistics> st, logger &l, std::shared_ptr<random_gen> r,
             uint32_t words_per_line, uint32_t total_lines, uint32_t associativity, replacementPolicy_t replacement_policy,
             uint32_t hit_test_latency, uint32_t num_read_ports,  uint32_t num_write_ports) :
    m_level(level),
    m_id(id),
    system_time(t),
    stats(st),
    log(l),
    ran(r),
    m_words_per_line(words_per_line),
    m_total_lines(total_lines),
    m_associativity(associativity),
    m_replacement_policy(replacement_policy),
    m_hit_test_latency(hit_test_latency),
    m_available_read_ports(num_read_ports),
    m_available_write_ports(num_write_ports),
    m_helper_copy_coherence_info(NULL),
    m_helper_is_coherence_hit(NULL),
    m_helper_can_evict_line(NULL),
    m_helper_evict_need_action(NULL),
    m_helper_replacement_policy(NULL),
    m_claim_hook(NULL),
    m_invalidate_hook(NULL),
    m_read_hook(NULL),
    m_write_hook(NULL),
    m_update_hook(NULL)
{
    mh_assert(m_associativity > 0);
    mh_assert(m_words_per_line > 0);
    mh_assert(m_available_read_ports > 0);
    mh_assert(m_available_write_ports > 0);
    int log2 = 0;
    for (uint32_t i = m_words_per_line * 4; i > 1; i = i/2) {
        mh_assert(i%2 == 0); /*  must be a power of 2 */
        ++log2;
    }
    m_offset_mask = m_words_per_line * 4 - 1;
    m_index_pos = log2;
    m_index_mask = (m_total_lines / m_associativity - 1) << m_index_pos;

}

cache::~cache() {
    for (cacheTable::iterator it = m_cache.begin(); it != m_cache.end(); ++it) {
        delete[] m_cache[it->first];
    }
}

void cache::print_contents() {
    cout << "[cache " << m_id << " - L" << m_level << " ] printing cache contents" << endl;
    for (cacheTable::iterator it = m_cache.begin(); it != m_cache.end(); ++it) {
        uint32_t index = it->first;
        for (uint32_t it_way = 0; it_way < m_associativity; ++it_way) {
            cout << "  (idx=" << index << ", way=" << it_way << ") : ";
            if (m_cache[index][it_way].claimed) {
                cout << "[" << m_cache[index][it_way].start_maddr << "] " << endl;
                cout << hex;
                for (uint32_t o = 0; o < m_words_per_line; o++) {
                    cout << m_cache[index][it_way].data[o] << " ";
                }
                cout << dec << endl;
            } else {
                cout << "empty" << endl;
            }
        }
    }
    cout << endl;
}

std::shared_ptr<cacheLine> cache::copy_cache_line(const cacheLine &line) {

    /* the cache always returns copies of data, not pointers */
    /* For coherence information, shmem systems decide what to do */
    /* For example, it may do shallow copy to implement some magic hardware, or concurrent snoopy mechanisms */

    std::shared_ptr<cacheLine> copy(new cacheLine);
    (*copy) = line;

    /* deep copy data */
    if (line.data) {
        copy->data = shared_array<uint32_t>(new uint32_t[m_words_per_line]);
        for (uint32_t i = 0; i < m_words_per_line; ++i) {
            copy->data[i] = line.data[i];
        }
    }

    /* let the helper function deal with coherence information */
    if (line.coherence_info) {
        mh_assert(m_helper_copy_coherence_info);
        copy->coherence_info = m_helper_copy_coherence_info(line.coherence_info);
    }

    return copy;
}

void cache::request(std::shared_ptr<cacheRequest> req) {

    req->m_status = CACHE_REQ_WAIT;

    std::shared_ptr<reqEntry> new_entry(new reqEntry);
    new_entry->status = (m_hit_test_latency > 0) ? ENTRY_HIT_TEST : ENTRY_DONE;
    new_entry->request = req;
    new_entry->start_maddr = get_start_maddr_in_line(req->m_maddr);
    new_entry->idx = get_index(req->m_maddr);
    new_entry->remaining_hit_test_cycles = m_hit_test_latency;

    m_req_table[new_entry->start_maddr].push_back(new_entry);

    mh_log(4) << "[cache " << m_id << " L" << m_level << " @ " << system_time << " ] "
              << " a request " << req->m_request_type << " on " << req->m_maddr << " arrived "  << endl;

    if (m_req_table[new_entry->start_maddr].front() == new_entry && new_entry->status == ENTRY_DONE) {
        mh_log(4) << "[cache " << m_id << " L" << m_level << " @ " << system_time << " ] "
                  << " a request " << req->m_request_type << " on " << req->m_maddr << " is in the ready queue "
                  << "(queue size " << m_ready_requests.size() << " )." << endl;
        m_ready_requests.push_back(new_entry);
    }

    if (req->use_read_ports()) {
        mh_assert(read_port_available());
        --m_available_read_ports;
    } else {
        mh_assert(write_port_available());
        --m_available_write_ports;
    }

    return;

}

void cache::tick_positive_edge() {

    static boost::function<int(int)> rr_fn = bind(&random_gen::random_range, ran, _1);
    random_shuffle(m_ready_requests.begin(), m_ready_requests.end(), rr_fn);

    for (vector<std::shared_ptr<reqEntry> >::iterator it_req = m_ready_requests.begin(); it_req != m_ready_requests.end(); ) {

        std::shared_ptr<reqEntry> entry = *it_req;
        std::shared_ptr<cacheRequest> req = entry->request;
        uint32_t idx = entry->idx;
        maddr_t& start_maddr = entry->start_maddr;

        mh_log(5) << "[cache " << m_id << " L" << m_level << " @ " << system_time << " ] "
                  << " is working on a request " << req->m_request_type
                  << " on " << req->m_maddr << endl;

        /* allocate memory for this index if not exist */
        if (m_cache.count(idx) == 0) {
            m_cache[idx] = new cacheLine[m_associativity];
            for (uint32_t it_way = 0; it_way < m_associativity; ++it_way) {
                m_cache[idx][it_way].claimed = false;
                m_cache[idx][it_way].data = shared_array<uint32_t>(new uint32_t[m_words_per_line]);
                m_cache[idx][it_way].coherence_info = std::shared_ptr<void>();
            }
        }

        /* find a matching way and/or empty ways */
        bool matched = false;
        uint32_t matching_way = 0;
        bool has_empty_way = false;
        uint32_t empty_way = 0;
        for (uint32_t it_way = 0; it_way < m_associativity; ++it_way) {
            cacheLine &line = m_cache[idx][it_way];
            if (line.claimed && start_maddr == line.start_maddr) {
                /* found */
                matched = true;
                matching_way = it_way;
                break;
            } else if (!line.claimed) {
                has_empty_way = true;
                empty_way = it_way;
            }
        }

        if (matched) {
            cacheLine &line = m_cache[idx][matching_way];
            line.last_access_time = system_time;

            if (req->m_request_type == CACHE_REQ_READ || req->m_request_type == CACHE_REQ_WRITE) {
                bool coherence_hit = line.ready && (!m_helper_is_coherence_hit
                                                    || !line.coherence_info
                                                    || (*m_helper_is_coherence_hit)(req, line, system_time));
                if (coherence_hit) {
                    mh_log(4) << "[cache " << m_id << " L" << m_level << " @ " << system_time << " ] "
                              << " a request " << req->m_request_type
                              << " on " << req->m_maddr << " gets a HIT." << endl;
                    req->m_status = CACHE_REQ_HIT;
                    if (req->m_request_type == CACHE_REQ_WRITE) {
                        if (req->m_word_count) {
                            uint32_t offset = get_offset(req->m_maddr) / 4;
                            for (uint32_t i = 0; i < req->m_word_count; ++i) {
                                line.data[offset + i] = req->m_data_to_write[i];
                            }
                            if (req->m_do_unset_dirty_on_write) {
                                line.data_dirty = false;
                            } else {
                                line.data_dirty = true;
                            }
                        }
                        if (req->m_coherence_info_to_write) {
                            line.coherence_info = req->m_coherence_info_to_write;
                            if (req->m_do_unset_dirty_on_write) {
                                line.coherence_info_dirty = false;
                            } else {
                                line.coherence_info_dirty = true;
                            }
                        }
                        if (m_write_hook) { (*m_write_hook)(req, line, system_time); }
                    } else {
                        if (m_read_hook) { (*m_read_hook)(req, line, system_time); }
                    }
                } else {
                    mh_log(4) << "[cache " << m_id << " L" << m_level << " @ " << system_time << " ] "
                              << " a request " << req->m_request_type
                              << " on " << req->m_maddr << " gets a coherence or not-ready MISS." << endl;
                    req->m_status = CACHE_REQ_MISS;
                }

                req->m_line_copy = copy_cache_line(line);

            } else if (req->m_request_type == CACHE_REQ_UPDATE) {

                bool coherence_hit = line.ready && (!m_helper_is_coherence_hit
                                                    || !line.coherence_info
                                                    || (*m_helper_is_coherence_hit)(req, line, system_time));

                if (!line.ready || coherence_hit) {

                    mh_log(4) << "[cache " << m_id << " L" << m_level << " @ " << system_time << " ] "
                              << " a request UPDATE "
                              << " on " << req->m_maddr << " gets a HIT." << endl;

                    line.ready = true;

                    req->m_status = CACHE_REQ_HIT;
                    if (req->m_word_count > 0) {
                        uint32_t offset = get_offset(req->m_maddr) / 4;
                        for (uint32_t i = 0; i < req->m_word_count; ++i) {
                            line.data[offset + i] = req->m_data_to_write[i];
                        }
                        if (req->m_do_unset_dirty_on_write) {
                            line.data_dirty = false;
                        } else {
                            line.data_dirty = true;
                        }
                    }
                    if (req->m_coherence_info_to_write) {
                        line.coherence_info = req->m_coherence_info_to_write;
                        if (req->m_do_unset_dirty_on_write) {
                            line.coherence_info_dirty = false;
                        } else {
                            line.coherence_info_dirty = true;
                        }
                    }
                    if (m_update_hook) { (*m_update_hook)(req, line, system_time); }
                } else {

                    mh_log(4) << "[cache " << m_id << " L" << m_level << " @ " << system_time << " ] "
                              << " a request UPDATE "
                              << " on " << req->m_maddr << " gets a coherence MISS." << endl;

                    req->m_status = CACHE_REQ_MISS;
                }

                req->m_line_copy = copy_cache_line(line);

            } else if (req->m_request_type == CACHE_REQ_INVALIDATE) {

                bool coherence_hit = line.ready && (!m_helper_is_coherence_hit
                                                || !line.coherence_info
                                                || (*m_helper_is_coherence_hit)(req, line, system_time));
                if (!line.ready || coherence_hit) {
                    req->m_status = CACHE_REQ_HIT;

                    mh_log(4) << "[cache " << m_id << " L" << m_level << " @ " << system_time << " ] "
                              << " a request INVALIDATE "
                              << " on " << req->m_maddr << " gets a HIT." << endl;

                    /* must act at the negative edge */
                    m_lines_to_invalidate.push_back(make_tuple(idx, matching_way, entry));

                } else {

                    mh_log(4) << "[cache " << m_id << " L" << m_level << " @ " << system_time << " ] "
                              << " a request INVALIDATE "
                              << " on " << req->m_maddr << " gets a coherence MISS." << endl;

                    req->m_status = CACHE_REQ_MISS;
                    req->m_line_copy = copy_cache_line(line);
                }
            }

            if (req->use_read_ports()) {
                ++m_available_read_ports;
            } else {
                ++m_available_write_ports;
            }

            m_ready_requests.erase(it_req);
            m_req_table[start_maddr].erase(m_req_table[start_maddr].begin());
            if (m_req_table[start_maddr].size() == 0) {
                m_req_table.erase(start_maddr);
            }
            continue;

        } else {
            /* no matching cache block */

            if (req->m_do_evict && !has_empty_way) {
                mh_log(4) << "[cache " << m_id << " L" << m_level << " @ " << system_time << " ] "
                          << " a request " << req->m_request_type
                          << " on " << req->m_maddr << " need to evict a line." << endl;
                ++it_req;
                continue;
            }

            if (req->m_do_claim && has_empty_way) {
                cacheLine &line = m_cache[idx][empty_way];
                line.claimed = true;
                line.start_maddr = start_maddr;

                if (m_claim_hook) {
                    (*m_claim_hook)(req, line, system_time);
                }

                if (req->m_request_type == CACHE_REQ_UPDATE) {
                    line.ready = true;
                    line.data_dirty = false;
                    line.coherence_info_dirty = false;
                    line.last_access_time = system_time;
                    if (req->m_word_count > 0) {
                        uint32_t offset = get_offset(req->m_maddr) / 4;
                        for (uint32_t i = 0; i < req->m_word_count; ++i) {
                            line.data[offset + i] = req->m_data_to_write[i];
                        }
                        if (req->m_do_unset_dirty_on_write) {
                            line.data_dirty = false;
                        } else {
                            line.data_dirty = true;
                        }
                    }
                    if (req->m_coherence_info_to_write) {
                        line.coherence_info = req->m_coherence_info_to_write;
                        if (req->m_do_unset_dirty_on_write) {
                            line.coherence_info_dirty = false;
                        } else {
                            line.coherence_info_dirty = true;
                        }
                    }

                    if (m_update_hook) {
                        (*m_update_hook)(req, line, system_time);
                    }

                    req->m_status = CACHE_REQ_HIT;

                    mh_log(4) << "[cache " << m_id << " L" << m_level << " @ " << system_time << " ] "
                              << " a request UPDATE "
                              << " on " << req->m_maddr << " gets a HIT on an empty block." << endl;

                } else {

                    mh_log(4) << "[cache " << m_id << " L" << m_level << " @ " << system_time << " ] "
                              << " a request " << req->m_request_type
                              << " on " << req->m_maddr << " gets a MISS but claimed a line." << endl;

                    line.ready = false;
                    req->m_status = CACHE_REQ_MISS;
                }
                req->m_line_copy = copy_cache_line(line);

            } else {

                mh_log(4) << "[cache " << m_id << " L" << m_level << " @ " << system_time << " ] "
                          << " a request " << req->m_request_type
                          << " on " << req->m_maddr << " gets a MISS." << endl;

                req->m_status = CACHE_REQ_MISS;
            }

            if (req->use_read_ports()) {
                ++m_available_read_ports;
            } else {
                ++m_available_write_ports;
            }
            m_ready_requests.erase(it_req);
            m_req_table[start_maddr].erase(m_req_table[start_maddr].begin());
            if (m_req_table[start_maddr].size() == 0) {
                m_req_table.erase(start_maddr);
            }
            continue;
        }
        /* never reach here */
    }

}

void cache::tick_negative_edge() {

    while (m_ready_requests.size()) {
        std::shared_ptr<reqEntry> entry = m_ready_requests.front();
        std::shared_ptr<cacheRequest> req = entry->request;
        uint32_t idx = entry->idx;
        maddr_t& start_maddr = entry->start_maddr;

        mh_log(4) << "[cache " << m_id << " L" << m_level << " @ " << system_time << " ] "
                  << " a request " << req->m_request_type
                  << " on " << req->m_maddr << " tries to evict a line." << endl;

        /* no matter what, they will finish here */
        if (req->use_read_ports()) {
            ++m_available_read_ports;
        } else {
            ++m_available_write_ports;
        }
        m_req_table[start_maddr].erase(m_req_table[start_maddr].begin());
        if (m_req_table[start_maddr].size() == 0) {
            m_req_table.erase(start_maddr);
        }
        m_ready_requests.erase(m_ready_requests.begin());

        /* find a matching way and/or empty ways */
        vector<uint32_t> evictables;
        uint64_t lru_time = UINT64_MAX;
        uint32_t lru_way = 0;
        for (uint32_t it_way = 0; it_way < m_associativity; ++it_way) {
            cacheLine &line = m_cache[idx][it_way];
            if (line.ready && line.last_access_time < system_time
                && (!m_helper_can_evict_line || (*m_helper_can_evict_line)(line, system_time)) )
            {
                evictables.push_back(it_way);
                if (line.last_access_time < lru_time) {
                    lru_way = it_way;
                    lru_time = line.last_access_time;
                }
            }
        }

        if (evictables.empty()) {
            mh_log(4) << "[cache " << m_id << " L" << m_level << " @ " << system_time << " ] "
                      << " a request " << req->m_request_type
                      << " on " << req->m_maddr << " found no evictable lines." << endl;
            req->m_status = CACHE_REQ_MISS;
            continue;
        }

        uint32_t victim_way = 0;
        switch (m_replacement_policy) {
        case REPLACE_RANDOM:
            victim_way = evictables[ran->random_range(evictables.size())];
            break;
        case REPLACE_LRU:
            victim_way = lru_way;
            break;
        case REPLACE_CUSTOM:
            mh_assert(m_helper_replacement_policy);
            victim_way = (*m_helper_replacement_policy)(evictables, m_cache[idx], system_time, ran);
            break;
        default:
            break;
        }

        cacheLine &line = m_cache[idx][victim_way];

        if (!m_helper_evict_need_action || !line.coherence_info || !(*m_helper_evict_need_action)(line, system_time)) {
            line.last_access_time = system_time; /* prevent this line to be considered again */
            m_lines_to_evict.push_back(make_tuple(idx, victim_way, entry));
        } else {
            req->m_status = CACHE_REQ_MISS;
            req->m_line_to_evict_copy = copy_cache_line(line);
            mh_log(4) << "[cache " << m_id << " L" << m_level << " @ " << system_time << " ] "
                      << " a request " << req->m_request_type
                      << " on " << req->m_maddr << " could not evict a line (coherence protocol)" << endl;
        }
    }

    while (m_lines_to_invalidate.size()) {
        uint32_t idx = get<0>(m_lines_to_invalidate.front());
        uint32_t way = get<1>(m_lines_to_invalidate.front());
        std::shared_ptr<reqEntry>& entry = get<2>(m_lines_to_invalidate.front());
        std::shared_ptr<cacheRequest>& req = entry->request;

        /* evict line and return a copy */
        cacheLine &line = m_cache[idx][way];
        line.claimed = false;
        if (m_invalidate_hook) {
            (*m_invalidate_hook)(req, line, system_time);
        }

        if (req->m_do_claim) {
            line.claimed = true;
            line.ready = false;
            line.start_maddr = entry->start_maddr;
            if (m_claim_hook) {
                (*m_claim_hook)(req, line, system_time);
            }
        }

        req->m_status = CACHE_REQ_HIT;
        req->m_line_copy = copy_cache_line(line);

        m_lines_to_invalidate.erase(m_lines_to_invalidate.begin());
    }

    while (m_lines_to_evict.size()) {
        uint32_t idx = get<0>(m_lines_to_evict.front());
        uint32_t way = get<1>(m_lines_to_evict.front());
        std::shared_ptr<reqEntry>& entry = get<2>(m_lines_to_evict.front());
        std::shared_ptr<cacheRequest>& req = entry->request;

        /* evict line and return a copy */
        cacheLine &line = m_cache[idx][way];
        line.claimed = false;
        if (m_invalidate_hook) {
            (*m_invalidate_hook)(req, line, system_time);
        }
        req->m_line_to_evict_copy = copy_cache_line(line);

        if (req->m_do_claim) {
            line.claimed = true;
            line.ready = false;
            line.start_maddr = entry->start_maddr;
            if (m_claim_hook) {
                (*m_claim_hook)(req, line, system_time);
            }

            if (req->m_request_type == CACHE_REQ_UPDATE) {
                line.ready = true;
                line.data_dirty = false;
                line.coherence_info_dirty = false;
                line.last_access_time = system_time;
                if (req->m_word_count > 0) {
                    uint32_t offset = get_offset(req->m_maddr) / 4;
                    for (uint32_t i = 0; i < req->m_word_count; ++i) {
                        line.data[offset + i] = req->m_data_to_write[i];
                    }
                    if (req->m_do_unset_dirty_on_write) {
                        line.data_dirty = false;
                    } else {
                        line.data_dirty = true;
                    }
                }
                if (req->m_coherence_info_to_write) {
                    line.coherence_info = req->m_coherence_info_to_write;
                    if (req->m_do_unset_dirty_on_write) {
                        line.coherence_info_dirty = false;
                    } else {
                        line.coherence_info_dirty = true;
                    }
                }

                if (m_update_hook) { (*m_update_hook)(req, line, system_time); }

                req->m_status = CACHE_REQ_HIT;
            } else {
                req->m_status = CACHE_REQ_MISS;
            }

            req->m_line_copy = copy_cache_line(line);
        } else {
            req->m_status = CACHE_REQ_MISS;
        }
        m_lines_to_evict.erase(m_lines_to_evict.begin());
    }

    /* advance hit testing */
    for (reqTable::iterator it_q = m_req_table.begin(); it_q != m_req_table.end(); ++it_q) {
        std::shared_ptr<reqEntry> &head = it_q->second.front();
        if (head->status == ENTRY_HIT_TEST) {
            if (--(head->remaining_hit_test_cycles) == 0) {
                head->status = ENTRY_DONE;
                m_ready_requests.push_back(head);
                mh_log(4) << "[cache " << m_id << " L" << m_level << " @ " << system_time << " ] "
                          << " a request " << head->request->m_request_type
                          << " on " << head->request->m_maddr << " is in the ready queue "
                          << "(queue size " << m_ready_requests.size() << " )." << endl;
            }
        }
    }

}

max_stars_repo_name: compstruct/hornet

max_issues_repo_name: compstruct/hornet

max_forks_repo_name: compstruct/hornet


text:
/**
 * Copyright (c) 2011, 2012
 * Claudio Kopper <claudio.kopper@icecube.wisc.edu>
 * and the IceCube Collaboration <http://www.icecube.wisc.edu>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 *
 * $Id$
 *
 * @file I3ShadowedPhotonRemover.cxx
 * @version $Revision$
 * @date $Date$
 * @author Claudio Kopper
 */

#include <sstream>

#include <clsim/shadow/I3ShadowedPhotonRemover.h>

#include <boost/preprocessor/seq.hpp>

#include "simclasses/I3CylinderMap.h"

using namespace boost::python;
namespace bp = boost::python;

void register_I3ShadowedPhotonRemover()
{
    {
        bp::scope I3ShadowedPhotonRemover_scope =
        bp::class_<I3ShadowedPhotonRemover, boost::shared_ptr<I3ShadowedPhotonRemover>, boost::noncopyable>
        ("I3ShadowedPhotonRemover",
         bp::init<
	 const I3CylinderMap & ,
	 const double &
	 >( (bp::arg("cylinder_map") , bp::arg("distance")) )
	 )
	  .def("IsPhotonShadowed", &I3ShadowedPhotonRemover::IsPhotonShadowed);
    }

    bp::implicitly_convertible<boost::shared_ptr<I3ShadowedPhotonRemover>, boost::shared_ptr<const I3ShadowedPhotonRemover> >();
}

ext: cxx

max_stars_repo_name: claudiok/clsim

max_issues_repo_name: claudiok/clsim

max_forks_repo_name: claudiok/clsim


text: #include <boost/units/quantity.hpp>


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

#include "txdb.h"

#include "chainparams.h"
#include "hash.h"
#include "main.h"
#include "pow.h"
#include "uint256.h"

#include <stdint.h>

#include <boost/thread.hpp>

using namespace std;

static const char DB_ANCHOR = 'A';
static const char DB_NULLIFIER = 's';
static const char DB_COINS = 'c';
static const char DB_BLOCK_FILES = 'f';
static const char DB_TXINDEX = 't';
static const char DB_BLOCK_INDEX = 'b';

static const char DB_BEST_BLOCK = 'B';
static const char DB_BEST_ANCHOR = 'a';
static const char DB_FLAG = 'F';
static const char DB_REINDEX_FLAG = 'R';
static const char DB_LAST_BLOCK = 'l';

CCoinsViewDB::CCoinsViewDB(std::string dbName, size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / dbName, nCacheSize, fMemory, fWipe) {
}

CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe, true) {
}

bool CCoinsViewDB::GetAnchorAt(const uint256 &rt, ZCIncrementalMerkleTree &tree) const {
    if (rt == ZCIncrementalMerkleTree::empty_root()) {
        ZCIncrementalMerkleTree new_tree;
        tree = new_tree;
        return true;
    }

    bool read = db.Read(make_pair(DB_ANCHOR, rt), tree);

    return read;
}

bool CCoinsViewDB::GetNullifier(const uint256 &nf) const {
    bool spent = false;
    bool read = db.Read(make_pair(DB_NULLIFIER, nf), spent);

    return read;
}

bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) const {
    return db.Read(make_pair(DB_COINS, txid), coins);
}

bool CCoinsViewDB::HaveCoins(const uint256 &txid) const {
    return db.Exists(make_pair(DB_COINS, txid));
}

uint256 CCoinsViewDB::GetBestBlock() const {
    uint256 hashBestChain;
    if (!db.Read(DB_BEST_BLOCK, hashBestChain))
        return uint256();
    return hashBestChain;
}

uint256 CCoinsViewDB::GetBestAnchor() const {
    uint256 hashBestAnchor;
    if (!db.Read(DB_BEST_ANCHOR, hashBestAnchor))
        return ZCIncrementalMerkleTree::empty_root();
    return hashBestAnchor;
}

bool CCoinsViewDB::BatchWrite(CCoinsMap &mapCoins,
                              const uint256 &hashBlock,
                              const uint256 &hashAnchor,
                              CAnchorsMap &mapAnchors,
                              CNullifiersMap &mapNullifiers) {
    CDBBatch batch(db);
    size_t count = 0;
    size_t changed = 0;
    for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
        if (it->second.flags & CCoinsCacheEntry::DIRTY) {
            if (it->second.coins.IsPruned())
                batch.Erase(make_pair(DB_COINS, it->first));
            else
                batch.Write(make_pair(DB_COINS, it->first), it->second.coins);
            changed++;
        }
        count++;
        CCoinsMap::iterator itOld = it++;
        mapCoins.erase(itOld);
    }

    for (CAnchorsMap::iterator it = mapAnchors.begin(); it != mapAnchors.end();) {
        if (it->second.flags & CAnchorsCacheEntry::DIRTY) {
            if (!it->second.entered)
                batch.Erase(make_pair(DB_ANCHOR, it->first));
            else {
                batch.Write(make_pair(DB_ANCHOR, it->first), it->second.tree);
            }
            // TODO: changed++?
        }
        CAnchorsMap::iterator itOld = it++;
        mapAnchors.erase(itOld);
    }

    for (CNullifiersMap::iterator it = mapNullifiers.begin(); it != mapNullifiers.end();) {
        if (it->second.flags & CNullifiersCacheEntry::DIRTY) {
            if (!it->second.entered)
                batch.Erase(make_pair(DB_NULLIFIER, it->first));
            else
                batch.Write(make_pair(DB_NULLIFIER, it->first), true);
            // TODO: changed++?
        }
        CNullifiersMap::iterator itOld = it++;
        mapNullifiers.erase(itOld);
    }

    if (!hashBlock.IsNull())
        batch.Write(DB_BEST_BLOCK, hashBlock);
    if (!hashAnchor.IsNull())
        batch.Write(DB_BEST_ANCHOR, hashAnchor);

    LogPrint("coindb", "Committing %u changed transactions (out of %u) to coin database...\n", (unsigned int)changed, (unsigned int)count);
    return db.WriteBatch(batch);
}

CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) {
}

bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {
    return Read(make_pair(DB_BLOCK_FILES, nFile), info);
}

bool CBlockTreeDB::WriteReindexing(bool fReindexing) {
    if (fReindexing)
        return Write(DB_REINDEX_FLAG, '1');
    else
        return Erase(DB_REINDEX_FLAG);
}

bool CBlockTreeDB::ReadReindexing(bool &fReindexing) {
    fReindexing = Exists(DB_REINDEX_FLAG);
    return true;
}

bool CBlockTreeDB::ReadLastBlockFile(int &nFile) {
    return Read(DB_LAST_BLOCK, nFile);
}

bool CCoinsViewDB::GetStats(CCoinsStats &stats) const {
    /* It seems that there are no "const iterators" for LevelDB.  Since we
       only need read operations on it, use a const-cast to get around
       that restriction.  */
    boost::scoped_ptr<CDBIterator> pcursor(const_cast<CDBWrapper*>(&db)->NewIterator());
    pcursor->Seek(DB_COINS);

    CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
    stats.hashBlock = GetBestBlock();
    ss << stats.hashBlock;
    CAmount nTotalAmount = 0;
    while (pcursor->Valid()) {
        boost::this_thread::interruption_point();
        std::pair<char, uint256> key;
        CCoins coins;
        if (pcursor->GetKey(key) && key.first == DB_COINS) {
            if (pcursor->GetValue(coins)) {
                stats.nTransactions++;
                for (unsigned int i=0; i<coins.vout.size(); i++) {
                    const CTxOut &out = coins.vout[i];
                    if (!out.IsNull()) {
                        stats.nTransactionOutputs++;
                        ss << VARINT(i+1);
                        ss << out;
                        nTotalAmount += out.nValue;
                    }
                }
                stats.nSerializedSize += 32 + pcursor->GetValueSize();
                ss << VARINT(0);
            } else {
                return error("CCoinsViewDB::GetStats() : unable to read value");
            }
        } else {
            break;
        }
        pcursor->Next();
    }
    {
        LOCK(cs_main);
        stats.nHeight = mapBlockIndex.find(stats.hashBlock)->second->nHeight;
    }
    stats.hashSerialized = ss.GetHash();
    stats.nTotalAmount = nTotalAmount;
    return true;
}

bool CBlockTreeDB::WriteBatchSync(const std::vector<std::pair<int, const CBlockFileInfo*> >& fileInfo, int nLastFile, const std::vector<const CBlockIndex*>& blockinfo) {
    CDBBatch batch(*this);
    for (std::vector<std::pair<int, const CBlockFileInfo*> >::const_iterator it=fileInfo.begin(); it != fileInfo.end(); it++) {
        batch.Write(make_pair(DB_BLOCK_FILES, it->first), *it->second);
    }
    batch.Write(DB_LAST_BLOCK, nLastFile);
    for (std::vector<const CBlockIndex*>::const_iterator it=blockinfo.begin(); it != blockinfo.end(); it++) {
        batch.Write(make_pair(DB_BLOCK_INDEX, (*it)->GetBlockHash()), CDiskBlockIndex(*it));
    }
    return WriteBatch(batch, true);
}

bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) {
    return Read(make_pair(DB_TXINDEX, txid), pos);
}

bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) {
    CDBBatch batch(*this);
    for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++)
        batch.Write(make_pair(DB_TXINDEX, it->first), it->second);
    return WriteBatch(batch);
}

bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) {
    return Write(std::make_pair(DB_FLAG, name), fValue ? '1' : '0');
}

bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) {
    char ch;
    if (!Read(std::make_pair(DB_FLAG, name), ch))
        return false;
    fValue = ch == '1';
    return true;
}

bool CBlockTreeDB::LoadBlockIndexGuts()
{
    boost::scoped_ptr<CDBIterator> pcursor(NewIterator());

    pcursor->Seek(make_pair(DB_BLOCK_INDEX, uint256()));

    // Load mapBlockIndex
    while (pcursor->Valid()) {
        boost::this_thread::interruption_point();
        std::pair<char, uint256> key;
        if (pcursor->GetKey(key) && key.first == DB_BLOCK_INDEX) {
            CDiskBlockIndex diskindex;
            if (pcursor->GetValue(diskindex)) {
                // Construct block index object
                CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
                pindexNew->pprev          = InsertBlockIndex(diskindex.hashPrev);
                pindexNew->nHeight        = diskindex.nHeight;
                pindexNew->nFile          = diskindex.nFile;
                pindexNew->nDataPos       = diskindex.nDataPos;
                pindexNew->nUndoPos       = diskindex.nUndoPos;
                pindexNew->hashAnchor     = diskindex.hashAnchor;
                pindexNew->nVersion       = diskindex.nVersion;
                pindexNew->hashReserved   = diskindex.hashReserved;
                pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
                pindexNew->nTime          = diskindex.nTime;
                pindexNew->nBits          = diskindex.nBits;
                pindexNew->nNonce         = diskindex.nNonce;
                pindexNew->nArrivalTime   = diskindex.nArrivalTime;
                pindexNew->nSolution      = diskindex.nSolution;
                pindexNew->nStatus        = diskindex.nStatus;
                pindexNew->nTx            = diskindex.nTx;
                pindexNew->nSproutValue   = diskindex.nSproutValue;

                // Consistency checks
                auto header = pindexNew->GetBlockHeader();
                if (header.GetHash() != pindexNew->GetBlockHash())
                    return error("LoadBlockIndex(): block header inconsistency detected: on-disk = %s, in-memory = %s",
                       diskindex.ToString(),  pindexNew->ToString());

                if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits, Params().GetConsensus()))
                    return error("LoadBlockIndex(): CheckProofOfWork failed: %s", pindexNew->ToString());

                pcursor->Next();
            } else {
                return error("LoadBlockIndex() : failed to read value");
            }
        } else {
            break;
        }
    }

    return true;
}

max_stars_repo_name: conbinicoin/conbinicoin

max_issues_repo_name: phabulu/litecoinz

max_forks_repo_name: phabulu/litecoinz


text:
//
// Copyright 2005-2007 Adobe Systems Incorporated
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
#ifndef BOOST_GIL_PIXEL_ITERATOR_HPP
#define BOOST_GIL_PIXEL_ITERATOR_HPP

#include <boost/gil/concepts.hpp>
#include <boost/gil/dynamic_step.hpp>
#include <boost/gil/utilities.hpp>
#include <boost/gil/pixel.hpp>

#include <iterator>
#include <type_traits>

namespace boost { namespace gil {

//forwarded declaration (as this file is included in step_iterator.hpp)
template <typename Iterator>
class memory_based_step_iterator;

/// \brief metafunction predicate determining whether the given iterator is a plain one or an adaptor over another iterator.
/// Examples of adaptors are the step iterator and the dereference iterator adaptor.
template <typename It>
struct is_iterator_adaptor : public std::false_type {};

/// \brief returns the base iterator for a given iterator adaptor. Provide an specialization when introducing new iterator adaptors
template <typename It>
struct iterator_adaptor_get_base;

/// \brief Changes the base iterator of an iterator adaptor. Provide an specialization when introducing new iterator adaptors
template <typename It, typename NewBaseIt>
struct iterator_adaptor_rebind;

/// \brief Returns the type of an iterator just like the input iterator, except operating over immutable values
template <typename It>
struct const_iterator_type;

// The default implementation when the iterator is a C pointer is to use the standard constness semantics
template <typename T> struct const_iterator_type<T*>       { using type = T const*; };
template <typename T> struct const_iterator_type<T const*> { using type = T const*; };

/// \brief Metafunction predicate returning whether the given iterator allows for changing its values
/// \ingroup GILIsMutable
template <typename It>
struct iterator_is_mutable{};

// The default implementation when the iterator is a C pointer is to use the standard constness semantics
template <typename T>
struct iterator_is_mutable<T*> : std::true_type {};

template <typename T>
struct iterator_is_mutable<T const*> : std::false_type {};

/// \defgroup PixelIteratorModelInterleavedPtr C pointer to a pixel
/// \ingroup PixelIteratorModel
/// \brief Iterators over interleaved pixels.
/// A C pointer to a model of PixelValueConcept is used as an iterator over interleaved pixels. Models PixelIteratorConcept, HomogeneousPixelBasedConcept, HasDynamicXStepTypeConcept, MemoryBasedIteratorConcept

/////////////////////////////
//  HasDynamicXStepTypeConcept
/////////////////////////////

/// \ingroup PixelIteratorModelInterleavedPtr
template <typename Pixel>
struct dynamic_x_step_type<Pixel*> {
    using type = memory_based_step_iterator<Pixel *>;
};

/// \ingroup PixelIteratorModelInterleavedPtr
template <typename Pixel>
struct dynamic_x_step_type<const Pixel*> {
    using type = memory_based_step_iterator<const Pixel *>;
};

/////////////////////////////
//  PixelBasedConcept
/////////////////////////////

template <typename Pixel>
struct color_space_type<Pixel*> : color_space_type<Pixel> {};

template <typename Pixel>
struct color_space_type<Pixel const*> : color_space_type<Pixel> {};

template <typename Pixel>
struct channel_mapping_type<Pixel*> : channel_mapping_type<Pixel> {};

template <typename Pixel>
struct channel_mapping_type<Pixel const*> : channel_mapping_type<Pixel> {};

template <typename Pixel>
struct is_planar<Pixel*> : is_planar<Pixel> {};

template <typename Pixel>
struct is_planar<Pixel const*> : is_planar<Pixel> {};

/////////////////////////////
//  HomogeneousPixelBasedConcept
/////////////////////////////

template <typename Pixel>
struct channel_type<Pixel*> : channel_type<Pixel> {};

template <typename Pixel>
struct channel_type<Pixel const*> : channel_type<Pixel> {};

////////////////////////////////////////////////////////////////////////////////////////
/// Support for pixel iterator movement measured in memory units (bytes or bits) as opposed to pixel type.
/// Necessary to handle image row alignment and channel plane alignment.
////////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////
//  MemoryBasedIteratorConcept
/////////////////////////////

template <typename T>
struct byte_to_memunit : std::integral_constant<int, 1> {};

template <typename P>
inline std::ptrdiff_t memunit_step(P const*) { return sizeof(P); }

template <typename P>
inline std::ptrdiff_t memunit_distance(P const* p1, P const* p2)
{
    return (
        gil_reinterpret_cast_c<unsigned char const*>(p2) -
        gil_reinterpret_cast_c<unsigned char const*>(p1));
}

template <typename P>
inline void memunit_advance(P* &p, std::ptrdiff_t diff)
{
    p = (P*)((unsigned char*)(p)+diff);
}

template <typename P>
inline P* memunit_advanced(const P* p, std::ptrdiff_t diff)
{
    return (P*)((char*)(p)+diff);
}

//  memunit_advanced_ref
//  (shortcut to advancing a pointer by a given number of memunits and taking the reference in case the compiler is not smart enough)

template <typename P>
inline P& memunit_advanced_ref(P* p, std::ptrdiff_t diff) {
    return *memunit_advanced(p,diff);
}

} }  // namespace boost::gil

#endif


text:
//  Copyright John Maddock 2006.
//  Use, modification and distribution are subject to the
//  Boost Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Basic sanity check that header <boost/math/special_functions/modf.hpp>
// #includes all the files that it needs to.
//
#include <boost/math/special_functions/modf.hpp>
//
// Note this header includes no other headers, this is
// important if this test is to be meaningful:
//
#include "test_compile_result.hpp"

float ff;
double dd;
long double lldd;

int ii;
long ll;
#ifdef BOOST_HAS_LONG_LONG
boost::long_long_type llll;
#endif

void check()
{
   check_result<float>(boost::math::modf(f, &ff));
   check_result<double>(boost::math::modf(d, &dd));
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
   check_result<long double>(boost::math::modf(l, &lldd));
#endif
   check_result<float>(boost::math::modf(f, &ii));
   check_result<double>(boost::math::modf(d, &ii));
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
   check_result<long double>(boost::math::modf(l, &ii));
#endif
   check_result<float>(boost::math::modf(f, &ll));
   check_result<double>(boost::math::modf(d, &ll));
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
   check_result<long double>(boost::math::modf(l, &ll));
#endif
#ifdef BOOST_HAS_LONG_LONG
   check_result<float>(boost::math::modf(f, &llll));
   check_result<double>(boost::math::modf(d, &llll));
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
   check_result<long double>(boost::math::modf(l, &llll));
#endif
#endif
}

max_issues_repo_name: boost-cmake/vintage

max_forks_repo_name: boost-cmake/vintage