text:
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 1998-2011, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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 "PyIlmBaseConfigInternal.h"

#include "PyImathFun.h"
#include "PyImathDecorators.h"
#include "PyImathExport.h"
#include "PyImathAutovectorize.h"
#include <Python.h>
#include <boost/python.hpp>
#include <boost/python/make_constructor.hpp>
#include <boost/format.hpp>
#include <ImathVec.h>
#include <ImathMatrixAlgo.h>
#include <ImathFun.h>

namespace PyImath {

using namespace boost::python;
using namespace PyImath;

namespace {

template <class T>
struct rotationXYZWithUpDir_op
{
    static IMATH_NAMESPACE::Vec3<T>
    apply(const IMATH_NAMESPACE::Vec3<T> &from, const IMATH_NAMESPACE::Vec3<T> &to,
          const IMATH_NAMESPACE::Vec3<T> &up)
    {
        IMATH_NAMESPACE::Vec3<T> retval;
        IMATH_NAMESPACE::extractEulerXYZ(IMATH_NAMESPACE::rotationMatrixWithUpDir(from,to,up),retval);
        return retval;
    }
};

template <class T>
struct abs_op
{
    static T
    apply(T value)
    {
        return IMATH_NAMESPACE::abs<T>(value);
    }
};

template <class T>
struct sign_op
{
    static T
    apply(T value)
    {
        return IMATH_NAMESPACE::sign<T>(value);
    }
};

template <class T>
struct log_op
{
    static T
    apply(T value)
    {
        return ::log(value);
    }
};

template <class T>
struct log10_op
{
    static T
    apply(T value)
    {
        return ::log10(value);
    }
};

template <class T>
struct lerp_op
{
    static T
    apply(T a, T b, T t)
    {
        return IMATH_NAMESPACE::lerp<T>(a,b,t);
    }
};

template <class T>
struct ulerp_op
{
    static T
    apply(T a, T b, T t)
    {
        return IMATH_NAMESPACE::ulerp<T>(a,b,t);
    }
};

template <class T>
struct lerpfactor_op
{
    static T
    apply(T a, T b, T t)
    {
        return IMATH_NAMESPACE::lerpfactor<T>(a,b,t);
    }
};

template <class T>
struct clamp_op
{
    static T
    apply(T value, T low, T high)
    {
        return IMATH_NAMESPACE::clamp<T>(value,low,high);
    }
};

template <class T>
struct cmp_op
{
    static T
    apply(T value)
    {
        return IMATH_NAMESPACE::cmp<T>(value);
    }
};

template <class T>
struct cmpt_op
{
    static T
    apply(T value)
    {
        return IMATH_NAMESPACE::cmpt<T>(value);
    }
};

template <class T>
struct iszero_op
{
    static T
    apply(T value)
    {
        return IMATH_NAMESPACE::iszero<T>(value);
    }
};

template <class T>
struct equal_op
{
    static T
    apply(T value)
    {
        return IMATH_NAMESPACE::equal<T>(value);
    }
};

template <class T>
struct floor_op
{
    static int
    apply(T value)
    {
        return IMATH_NAMESPACE::floor<T>(value);
    }
};

template <class T>
struct ceil_op
{
    static int
    apply(T value)
    {
        return IMATH_NAMESPACE::ceil<T>(value);
    }
};

template <class T>
struct trunc_op
{
    static int
    apply(T value)
    {
        return IMATH_NAMESPACE::trunc<T>(value);
    }
};

struct divs_op
{
    static int
    apply(int x, int y)
    {
        return IMATH_NAMESPACE::divs(x,y);
    }
};

struct mods_op
{
    static int
    apply(int x, int y)
    {
        return IMATH_NAMESPACE::mods(x,y);
    }
};

struct divp_op
{
    static int
    apply(int x, int y)
    {
        return IMATH_NAMESPACE::divp(x,y);
    }
};

struct modp_op
{
    static int
    apply(int x, int y)
    {
        return IMATH_NAMESPACE::modp(x,y);
    }
};

struct bias_op
{
    static inline float
    apply(float x, float b)
    {
        if (b != 0.5f)
        {
            static const float inverse_log_half = 1.0f / std::log(0.5f);
            const float biasPow = std::log(b)*inverse_log_half;
            return std::pow(x, biasPow);
        }
        return x;
    }
};

struct gain_op
{
    static inline float
    apply(float x, float g)
    {
        if (x < 0.5f)
            return 0.5f*bias_op::apply(2.0f*x, 1.0f - g);
        else
            return 1.0f - 0.5f*bias_op::apply(2.0f - 2.0f*x, 1.0f - g);
    }
};

} // namespace

void register_functions()
{
    //
    // Utility Functions
    //

    // nb: MSVC gets confused about which arg we want (it thinks it
    // might be boost::arg), so telling it which one explicitly here.
    typedef boost::python::arg arg;

    PyImath::generate_bindings<abs_op<int>,boost::mpl::true_>(
        "abs",
        "return the absolute value of 'value'",
        (arg("value")));
    PyImath::generate_bindings<abs_op<float>,boost::mpl::true_>(
        "abs",
        "return the absolute value of 'value'",
        (arg("value")));
    PyImath::generate_bindings<abs_op<double>,boost::mpl::true_>(
        "abs",
        "return the absolute value of 'value'",
        (arg("value")));

    PyImath::generate_bindings<sign_op<int>,boost::mpl::true_>(
        "sign",
        "return 1 or -1 based on the sign of 'value'",
        (arg("value")));
    PyImath::generate_bindings<sign_op<float>,boost::mpl::true_>(
        "sign",
        "return 1 or -1 based on the sign of 'value'",
        (arg("value")));
    PyImath::generate_bindings<sign_op<double>,boost::mpl::true_>(
        "sign",
        "return 1 or -1 based on the sign of 'value'",
        (arg("value")));

    PyImath::generate_bindings<log_op<float>,boost::mpl::true_>(
        "log",
        "return the natural log of 'value'",
        (arg("value")));
    PyImath::generate_bindings<log_op<double>,boost::mpl::true_>(
        "log",
        "return the natural log of 'value'",
        (arg("value")));

    PyImath::generate_bindings<log10_op<float>,boost::mpl::true_>(
        "log10",
        "return the base 10 log of 'value'",
        (arg("value")));
    PyImath::generate_bindings<log10_op<double>,boost::mpl::true_>(
        "log10",
        "return the base 10 log of 'value'",
        (arg("value")));

    PyImath::generate_bindings<lerp_op<float>,boost::mpl::true_,boost::mpl::true_,boost::mpl::true_>(
        "lerp",
        "return the linear interpolation of 'a' to 'b' using parameter 't'",
        (arg("a"),arg("b"),arg("t")));
    PyImath::generate_bindings<lerp_op<double>,boost::mpl::true_,boost::mpl::true_,boost::mpl::true_>(
        "lerp",
        "return the linear interpolation of 'a' to 'b' using parameter 't'",
        (arg("a"),arg("b"),arg("t")));

    PyImath::generate_bindings<lerpfactor_op<float>,boost::mpl::true_,boost::mpl::true_,boost::mpl::true_>(
        "lerpfactor",
        "return how far m is between a and b, that is return t such that\n"
        "if:\n"
        "    t = lerpfactor(m, a, b);\n"
        "then:\n"
        "    m = lerp(a, b, t);\n"
        "\n"
        "If a==b, return 0.\n",
        (arg("m"),arg("a"),arg("b")));
    PyImath::generate_bindings<lerpfactor_op<double>,boost::mpl::true_,boost::mpl::true_,boost::mpl::true_>(
        "lerpfactor",
        "return how far m is between a and b, that is return t such that\n"
        "    if:\n"
        "        t = lerpfactor(m, a, b);\n"
        "    then:\n"
        "        m = lerp(a, b, t);\n"
        "    if a==b, return 0.\n",
        (arg("m"),arg("a"),arg("b")));

    PyImath::generate_bindings<clamp_op<int>,boost::mpl::true_,boost::mpl::true_,boost::mpl::true_>(
        "clamp",
        "return the value clamped to the range [low,high]",
        (arg("value"),arg("low"),arg("high")));
    PyImath::generate_bindings<clamp_op<float>,boost::mpl::true_,boost::mpl::true_,boost::mpl::true_>(
        "clamp",
        "return the value clamped to the range [low,high]",
        (arg("value"),arg("low"),arg("high")));
    PyImath::generate_bindings<clamp_op<double>,boost::mpl::true_,boost::mpl::true_,boost::mpl::true_>(
        "clamp",
        "return the value clamped to the range [low,high]",
        (arg("value"),arg("low"),arg("high")));

    def("cmp", IMATH_NAMESPACE::cmp<float>);
    def("cmp", IMATH_NAMESPACE::cmp<double>);

    def("cmpt", IMATH_NAMESPACE::cmpt<float>);
    def("cmpt", IMATH_NAMESPACE::cmpt<double>);

    def("iszero", IMATH_NAMESPACE::iszero<float>);
    def("iszero", IMATH_NAMESPACE::iszero<double>);

    def("equal", IMATH_NAMESPACE::equal<float, float, float>);
    def("equal", IMATH_NAMESPACE::equal<double, double, double>);

    PyImath::generate_bindings<floor_op<float>,boost::mpl::true_>(
        "floor",
        "return the closest integer less than or equal to 'value'",
        (arg("value")));
    PyImath::generate_bindings<floor_op<double>,boost::mpl::true_>(
        "floor",
        "return the closest integer less than or equal to 'value'",
        (arg("value")));

    PyImath::generate_bindings<ceil_op<float>,boost::mpl::true_>(
        "ceil",
        "return the closest integer greater than or equal to 'value'",
        (arg("value")));
    PyImath::generate_bindings<ceil_op<double>,boost::mpl::true_>(
        "ceil",
        "return the closest integer greater than or equal to 'value'",
        (arg("value")));

    PyImath::generate_bindings<trunc_op<float>,boost::mpl::true_>(
        "trunc",
        "return the closest integer with magnitude less than or equal to 'value'",
        (arg("value")));
    PyImath::generate_bindings<trunc_op<double>,boost::mpl::true_>(
        "trunc",
        "return the closest integer with magnitude less than or equal to 'value'",
        (arg("value")));

    PyImath::generate_bindings<divs_op,boost::mpl::true_,boost::mpl::true_>(
        "divs",
        "return x/y where the remainder has the same sign as x:\n"
        "    divs(x,y) == (abs(x) / abs(y)) * (sign(x) * sign(y))\n",
        (arg("x"),arg("y")));
    PyImath::generate_bindings<mods_op,boost::mpl::true_,boost::mpl::true_>(
        "mods",
        "return x%y where the remainder has the same sign as x:\n"
        "    mods(x,y) == x - y * divs(x,y)\n",
        (arg("x"),arg("y")));

    PyImath::generate_bindings<divp_op,boost::mpl::true_,boost::mpl::true_>(
        "divp",
        "return x/y where the remainder is always positive:\n"
        "    divp(x,y) == floor (double(x) / double (y))\n",
        (arg("x"),arg("y")));
    PyImath::generate_bindings<modp_op,boost::mpl::true_,boost::mpl::true_>(
        "modp",
        "return x%y where the remainder is always positive:\n"
        "    modp(x,y) == x - y * divp(x,y)\n",
        (arg("x"),arg("y")));

    PyImath::generate_bindings<bias_op,boost::mpl::true_,boost::mpl::true_>(
         "bias",
         "bias(x,b) is a gamma correction that remaps the unit interval such that bias(0.5, b) = b.",
         (arg("x"),arg("b")));

    PyImath::generate_bindings<gain_op,boost::mpl::true_,boost::mpl::true_>(
         "gain",
         "gain(x,g) is a gamma correction that remaps the unit interval with the property that gain(0.5, g) = 0.5.\n"
         "The gain function can be thought of as two scaled bias curves forming an 'S' shape in the unit interval.",
         (arg("x"),arg("g")));

    //
    // Vectorized utility functions
    //
    PyImath::generate_bindings<rotationXYZWithUpDir_op<float>,boost::mpl::true_,boost::mpl::true_,boost::mpl::true_>(
        "rotationXYZWithUpDir",
        "return the XYZ rotation vector that rotates 'fromDir' to 'toDir'"
        "using the up vector 'upDir'",
        args("fromDir","toDir","upDir"));
}

} // namespace PyImath

max_stars_repo_name: FnGyula/openexr

max_issues_repo_name: FnGyula/openexr

max_forks_repo_name: FnGyula/openexr


text:
#include "pch.h"
#include "sqlite3.h"
#include <iostream>
#include <xxhash.h>
#include <fstream>
#include <chrono>
#include <boost/filesystem.hpp>
#include <Sqlite3IncrementalBackup/api.h>

#define TIMER_START(timer_name) auto _##timer_name = std::chrono::high_resolution_clock::now();
#define TIMER_GET(timer_name, measure) std::chrono::duration_cast<std::chrono::##measure>(std::chrono::high_resolution_clock::now() - _##timer_name).count()

#define IN_MEMORY_CACHE

#ifdef IN_MEMORY_CACHE
	static const int g_flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
#else
	static const int g_flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_SHAREDCACHE | SQLITE_OPEN_NOMUTEX;
#endif

#ifdef IN_MEMORY_CACHE
	static const char* dbPath = "test";
#else
	static const char* dbPath = ".\\test.sqlite";
#endif
static const char* dbBackupPath = ".\\test_backup.sqlite";

static const int loadParameter = 1000;

sqlite3* openDb() {
	sqlite3* db = nullptr;
#ifdef IN_MEMORY_CACHE
	if (boost::filesystem::exists(dbBackupPath)) {
		sqlite3* bckp = nullptr;
		sqlite3_open_v2(dbBackupPath, &bckp, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_SHAREDCACHE | SQLITE_OPEN_NOMUTEX, nullptr);
		sqlite3_open_v2(dbPath, &db, g_flags, nullptr);
		auto loadFromBackup = sqlite3_backup_init(
			db, "main",
			bckp, "main");

		sqlite3_backup_step(loadFromBackup, -1);
		sqlite3_backup_finish(loadFromBackup);
	}
	else
#endif
	sqlite3_open_v2(dbPath, &db, g_flags, nullptr);
	return db;
}

void backupNative(sqlite3* db) {
	sqlite3* bck = nullptr;
	sqlite3_open_v2("testnative.sqlite", &bck, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_SHAREDCACHE | SQLITE_OPEN_NOMUTEX, nullptr);
	sqlite3_backup* pBckHandle = sqlite3_backup_init(bck, "main", db, "main");
	sqlite3_backup_step(pBckHandle, -1);
	sqlite3_backup_finish(pBckHandle);
}

sqlite3* createDb() {
	sqlite3* db = openDb();
	int rc = sqlite3_exec(db, "DROP TABLE IF EXISTS test", NULL, NULL, NULL);
	rc |= sqlite3_exec(db, "CREATE TABLE test (col1 NUM PRIMARY KEY, col2 TEXT)", NULL, NULL, NULL);
	if (rc != SQLITE_OK)
		std::cerr << "error query\n";
	return db;
}

void fillDb(sqlite3* db, int rowCount, std::function<std::string()> f) {

	sqlite3_exec(db, "BEGIN TRANSACTION", NULL, NULL, NULL);
	sqlite3_stmt* stmt = nullptr;
	if (SQLITE_OK != sqlite3_prepare_v2(db, "INSERT INTO test (col1, col2) VALUES (@col1, @col2)", -1, &stmt, NULL)) {
		std::cerr << "error query\n";
	}

	for (int i = 0; i < rowCount; ++i) {
		std::string str = f();
		sqlite3_bind_int64(stmt, sqlite3_bind_parameter_index(stmt, "@col1"), i + 1);
		sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, "@col2"), str.c_str(), str.size(), nullptr);
		sqlite3_step(stmt);
		sqlite3_clear_bindings(stmt);
		sqlite3_reset(stmt);
	}
	sqlite3_finalize(stmt);
	sqlite3_exec(db, "END TRANSACTION", NULL, NULL, NULL);
}

void updateDb(sqlite3* db, int from, int rowCount, std::function<std::string()> f) {
	sqlite3_exec(db, "BEGIN TRANSACTION", NULL, NULL, NULL);
	sqlite3_stmt* stmt = nullptr;
	sqlite3_prepare_v2(db, "UPDATE test SET col2=@col2 WHERE col1=@col1", -1, &stmt, NULL);

	for (int i = from; i < rowCount + from; ++i) {
		std::string str = f();
		sqlite3_bind_text(stmt, sqlite3_bind_parameter_index(stmt, "@col2"), str.c_str(), str.size(), nullptr);
		sqlite3_bind_int64(stmt, sqlite3_bind_parameter_index(stmt, "@col1"), i + 1);
		sqlite3_step(stmt);
		sqlite3_clear_bindings(stmt);
		sqlite3_reset(stmt);
	}
	sqlite3_finalize(stmt);
	sqlite3_exec(db, "END TRANSACTION", NULL, NULL, NULL);
}

std::string genWord() {
	switch (rand() % 5) {
	case 0: return "it";
	case 1: return "is";
	case 2: return "wednesday";
	case 3: return "my";
	case 4: return "dudes";
	}
}

bool compareDb() {
#ifdef IN_MEMORY_CACHE
	return true;
#endif

	std::ifstream fsrc(dbPath, std::ios::binary);
	std::ifstream f1(dbPath, std::ifstream::binary | std::ifstream::ate);
	std::ifstream f2(dbBackupPath, std::ifstream::binary | std::ifstream::ate);

	if (f1.fail() || f2.fail()) {
		std::cerr << "File problem";
		return false;
	}

	if (f1.tellg() != f2.tellg()) {
		std::cerr << "Size mismatch";
		return false;
	}

	//seek back to beginning and use std::equal to compare contents
	f1.seekg(0, std::ifstream::beg);
	f2.seekg(0, std::ifstream::beg);
	return std::equal(std::istreambuf_iterator<char>(f1.rdbuf()),
		std::istreambuf_iterator<char>(),
		std::istreambuf_iterator<char>(f2.rdbuf()));
}

bool backup(sqlite3 *db) {
	char* msg = nullptr;
	bool status = 0 == sqlite3_inc_bkp::backup(db, ".\\", "test", &msg, [](const void* data, std::size_t size) { return XXH64(data, size, 0); });
	/*if (!status)
		std::cerr << msg << std::endl;*/
	return status;
}

void clear() {
	std::remove(".\\.test.manifest");
	std::remove(dbPath);
	std::remove(dbBackupPath);
	std::remove(".\\testnative.sqlite");
}

sqlite3* openBackup() {
	sqlite3* db = nullptr;
	if (boost::filesystem::exists(dbBackupPath)) {
		sqlite3_open_v2(dbBackupPath, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_SHAREDCACHE | SQLITE_OPEN_NOMUTEX, nullptr);
	}
	return db;
}

TEST(InitBackup, BackupTest) {
	clear();

	sqlite3* db = createDb();
	fillDb(db, 100 * loadParameter, []{ return std::string("test"); });
	std::cout << "Backup started...\n";
	TIMER_START(backupTimer);
	EXPECT_TRUE(backup(db));
	auto time = TIMER_GET(backupTimer, milliseconds);
	TIMER_START(nativeTimer);
	backupNative(db);
	auto timeNative = TIMER_GET(nativeTimer, milliseconds);
	std::cout << "Backup time [" << time << "]ms" << " VS Native backup time["<< timeNative <<"]ms"<<std::endl;

	EXPECT_TRUE(compareDb());
}

TEST(UpdateAndBackup, BackupTest) {
	sqlite3* db = openDb();
	updateDb(db, 0, 100 * loadParameter, genWord);
	std::cout << "Backup started...\n";
	TIMER_START(backupTimer);
	EXPECT_TRUE(backup(db));
	auto time = TIMER_GET(backupTimer, milliseconds);
	TIMER_START(nativeTimer);
	backupNative(db);
	auto timeNative = TIMER_GET(nativeTimer, milliseconds);
	std::cout << "Backup time [" << time << "]ms" << " VS Native backup time[" << timeNative << "]ms" << std::endl;
	EXPECT_TRUE(compareDb());
}

TEST(WriteMoreAndBackup, BackupTest) {
	sqlite3* db = openDb();
	fillDb(db, 4000 * loadParameter, [] { return std::string("test"); });
	std::cout << "Backup started...\n";
	TIMER_START(backupTimer);
	EXPECT_TRUE(backup(db));
	auto time = TIMER_GET(backupTimer, milliseconds);
	TIMER_START(nativeTimer);
	backupNative(db);
	auto timeNative = TIMER_GET(nativeTimer, milliseconds);
	std::cout << "Backup time [" << time << "]ms" << " VS Native backup time[" << timeNative << "]ms" << std::endl;
	EXPECT_TRUE(compareDb());
}

TEST(UpdatePartAndBackup, BackupTest) {
	sqlite3* db = openDb();
	updateDb(db, 200 * loadParameter, loadParameter, genWord);
	std::cout << "Backup started...\n";
	TIMER_START(backupTimer);
	EXPECT_TRUE(backup(db));
	auto time = TIMER_GET(backupTimer, milliseconds);
	TIMER_START(nativeTimer);
	backupNative(db);
	auto timeNative = TIMER_GET(nativeTimer, milliseconds);
	std::cout << "Backup time [" << time << "]ms" << " VS Native backup time[" << timeNative << "]ms" << std::endl;
	EXPECT_TRUE(compareDb());
}

TEST(CorruptCheck, BackupTest) {
	//Check integrity true
	char* msg;
	sqlite3* bckp = openBackup();
	sqlite3* dst = nullptr;
	sqlite3_open_v2(dbPath, &dst, g_flags, nullptr);
	int rc = sqlite3_inc_bkp::read_backup(dst, ".\\", "test", &msg, [](const void* data, std::size_t size) { return XXH64(data, size, 0); });
	if (rc != 0) {
		std::cout << "Corrupt message: " << msg << std::endl;
	}
	sqlite3_close_v2(dst);
	EXPECT_TRUE(rc == 0);

	//Corrupt manifest file
	boost::filesystem::copy(".\\.test.manifest", ".\\test.manifest.bcp");
	std::ofstream file(".\\.test.manifest", std::ios::binary);
	file.write("it is wednesday my dudes", 333);
	file.close();
	rc = sqlite3_inc_bkp::read_backup(bckp, ".\\", "test", &msg, [](const void* data, std::size_t size) { return XXH64(data, size, 0); });
	EXPECT_TRUE(rc == 5);
	std::remove(".\\.test.manifest");
	std::rename(".\\test.manifest.bcp", ".\\.test.manifest");

	//Corrupt database file
	updateDb(bckp, 200 * loadParameter, loadParameter, genWord);
	sqlite3* db = nullptr;
	rc = sqlite3_inc_bkp::read_backup(bckp, ".\\", "test", &msg, [](const void* data, std::size_t size) { return XXH64(data, size, 0); });
	EXPECT_TRUE(rc == 5);
	clear();
}

ext: cpp


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

#include <boost/bind.hpp>

#include "gazebo/gazebo_config.h"
#include "gazebo/common/Console.hh"

#include "gazebo/physics/Model.hh"
#include "gazebo/physics/Link.hh"
#include "gazebo/physics/ode/ODELink.hh"
#include "gazebo/physics/ode/ODEGearboxJoint.hh"

using namespace gazebo;
using namespace physics;

//////////////////////////////////////////////////
ODEGearboxJoint::ODEGearboxJoint(dWorldID _worldId, BasePtr _parent)
    : GearboxJoint<ODEJoint>(_parent)
{
  this->jointId = dJointCreateGearbox(_worldId, NULL);
}

//////////////////////////////////////////////////
ODEGearboxJoint::~ODEGearboxJoint()
{
}

//////////////////////////////////////////////////
void ODEGearboxJoint::Init()
{
  Joint::Init();
  LinkPtr link = this->model->GetLink(this->referenceBody);
  this->SetReferenceBody(link);
}

//////////////////////////////////////////////////
void ODEGearboxJoint::Load(sdf::ElementPtr _sdf)
{
  GearboxJoint<ODEJoint>::Load(_sdf);

  this->SetGearboxRatio(this->gearRatio);
}

//////////////////////////////////////////////////
void ODEGearboxJoint::SetReferenceBody(LinkPtr _body)
{
  ODELinkPtr odelink = boost::dynamic_pointer_cast<ODELink>(_body);
  dBodyID refId;
  if (odelink == NULL)
  {
    gzwarn << "Reference body not valid, using inertial frame.\n";
    refId = 0;
  }
  else
  {
    refId = odelink->GetODEId();
  }

  dJointSetGearboxReferenceBody(this->jointId, refId);
}

//////////////////////////////////////////////////
void ODEGearboxJoint::SetGearboxRatio(double _gearRatio)
{
  this->gearRatio = _gearRatio;
  dJointSetGearboxRatio(this->jointId, _gearRatio);
}

//////////////////////////////////////////////////
math::Vector3 ODEGearboxJoint::GetGlobalAxis(unsigned int _index) const
{
  dVector3 result;

  if (_index == 0)
    dJointGetGearboxAxis1(this->jointId, result);
  else if (_index == 1)
    dJointGetGearboxAxis2(this->jointId, result);
  else
    gzerr << "index [" << _index << "] out of range\n";

  return math::Vector3(result[0], result[1], result[2]);
}

//////////////////////////////////////////////////
void ODEGearboxJoint::SetAxis(unsigned int _index, const math::Vector3 &_axis)
{
  ODEJoint::SetAxis(_index, _axis);

  if (this->childLink)
    this->childLink->SetEnabled(true);
  if (this->parentLink)
    this->parentLink->SetEnabled(true);

  /// ODE needs global axis
  math::Quaternion axisFrame = this->GetAxisFrame(_index);
  math::Vector3 globalAxis = axisFrame.RotateVector(_axis);

  if (_index == 0)
  {
    dJointSetGearboxAxis1(this->jointId, globalAxis.x, globalAxis.y,
      globalAxis.z);
  }
  else if (_index == 1)
  {
    dJointSetGearboxAxis2(this->jointId, globalAxis.x, globalAxis.y,
      globalAxis.z);
  }
  else
    gzerr << "index [" << _index << "] out of range\n";
}

//////////////////////////////////////////////////
math::Angle ODEGearboxJoint::GetAngleImpl(unsigned int /*index*/) const
{
  gzlog << "GetAngle not implemented for gearbox\n";
  return math::Angle(0);
}

//////////////////////////////////////////////////
double ODEGearboxJoint::GetVelocity(unsigned int /*index*/) const
{
  gzlog << "GetVelocity not implemented for gearbox\n";
  return 0;
}

//////////////////////////////////////////////////
void ODEGearboxJoint::SetVelocity(unsigned int /*index*/, double /*_angle*/)
{
  gzlog << "SetVelocity not implemented for gearbox\n";
  return;
}

//////////////////////////////////////////////////
void ODEGearboxJoint::SetMaxForce(unsigned int /*index*/, double /*_t*/)
{
  gzlog << "SetMaxForce not implemented for gearbox\n";
  return;
}

//////////////////////////////////////////////////
double ODEGearboxJoint::GetMaxForce(unsigned int /*index*/)
{
  gzlog << "GetMaxForce not implemented for gearbox\n";
  return 0;
}

//////////////////////////////////////////////////
void ODEGearboxJoint::SetForceImpl(unsigned int /*_index*/, double /*_effort*/)
{
  if (this->jointId)
    gzlog << "SetForce not implemented for gearbox\n";
  else
    gzerr << "ODE Joint ID is invalid\n";
}

//////////////////////////////////////////////////
double ODEGearboxJoint::GetParam(unsigned int /*_parameter*/) const
{
  gzlog << "GetParam not implemented for gearbox\n";
  return 0;
}

//////////////////////////////////////////////////
void ODEGearboxJoint::SetParam(unsigned int /*_parameter*/, double /*_value*/)
{
  gzlog << "SetParam not implemented for gearbox\n";
  return;
}

//////////////////////////////////////////////////
math::Vector3 ODEGearboxJoint::GetAnchor(unsigned int /*_index*/) const
{
  dVector3 result;
  gzlog << "ODEGearboxJoint::GetAnchor not implemented.\n";
  return math::Vector3(result[0], result[1], result[2]);
}

//////////////////////////////////////////////////
void ODEGearboxJoint::SetAnchor(unsigned int /*_index*/,
  const math::Vector3 &/*_anchor*/)
{
  gzlog << "ODEGearboxJoint::SetAnchor not implemented.\n";
}

ext: cc

max_stars_repo_name: horikawahorikawa/gazebo-PR

max_issues_repo_name: shyamalschandra/gazebo-official

max_forks_repo_name: shyamalschandra/gazebo-official


text:
/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu>
 * Licensed under the MIT license. See the license file LICENSE.
 */

#pragma once

#include <Eigen/Dense>
#include <time.h>
#include <memory>

//#include <boost/random/uniform_int_distribution.hpp>
//#include <boost/random/uniform_int.hpp>
#include <boost/random/uniform_01.hpp>

#include <dpMM/distribution.hpp>
#include <dpMM/sampler.hpp>

using namespace Eigen;
using std::cout;
using std::endl;

template<typename T>
class Cat : public Distribution<T>
{
public:
  uint32_t K_;
  Matrix<T,Dynamic,1> pdf_;
  Matrix<T,Dynamic,1> cdf_;

  /* constructor from pdf */
  Cat(const Matrix<T,Dynamic,1>& pdf, boost::mt19937 *pRndGen);
  /* constructor from indicators - estimates from counts */
  Cat(const VectorXu& z, boost::mt19937 *pRndGen);
  /* copy constructor */
  Cat(const Cat& other);
  virtual ~Cat();

  uint32_t sample();
  void sample(VectorXu& z);

  T logPdf(const Matrix<T,Dynamic,1>& x) const
  {
    //assuming x is all zeros except one element
    assert(x.rows()==K_); //data dimmension should agree with # categories
    for(uint32_t d=0; d<K_; ++d) {
      if(x(d)==1) {
        return(log(pdf_(d)));
      }
    }
    assert(false); //invalid data (at least one element must be one) [this should never happen]
    return(-1);
  };

  T logPdf(uint32_t x) const
  {
    assert(x < K_);
    return(log(pdf_(x)));
  };

  T logPdfOfSS(const Matrix<T,Dynamic,1>& x) const
  {

    assert(x.rows()==K_); //data dimmension should agree with # categories
    T logPdf = 0;
    for(uint32_t d=0; d<K_; ++d) {
      logPdf += x(d) * log(pdf_(d));
    }
    return logPdf;
  };

  const Matrix<T,Dynamic,1>& pdf() const {return pdf_;};
  void pdf(const Matrix<T,Dynamic,1>& pdf){
    pdf_ = pdf;
    updateCdf();
  };
  const Matrix<T,Dynamic,1>& cdf() const {return cdf_;};

  void print() const;

private:
  boost::uniform_01<T> unif_;
  void updateCdf();
};

typedef Cat<float> Catf;
typedef Cat<double> Catd;

template<typename T>
inline T logSumExpRow(const Matrix<T,Dynamic,Dynamic>& pdf, uint32_t i)
{
  T max = pdf.row(i).maxCoeff();
  return log((pdf.row(i).array()-max).exp().matrix().sum()) + max;
}

template<typename T>
inline T logSumExpCol(const Matrix<T,Dynamic,Dynamic>& pdf, uint32_t i)
{
  T max = pdf.col(i).maxCoeff();
  return log((pdf.col(i).array()-max).exp().matrix().sum()) + max;
}

template<typename T>
inline T logSumExp(const Matrix<T,Dynamic,1>& pdf)
{
  T max = pdf.maxCoeff();
  return log((pdf.array()-max).exp().matrix().sum()) + max;
}

//template<typename T>
//inline T logSumExp(const Matrix<T,1,Dynamic>& pdf)
//{
//  T max = pdf.maxCoeff();
//  return log((pdf.array()-max).exp().matrix().sum()) + max;
//}

ext: hpp

max_stars_repo_name: jstraub/dpMM

max_issues_repo_name: jstraub/dpMM

max_forks_repo_name: jstraub/dpMM


text:
#include "EglAttribMap.h"
#include "EglDisplay.h"
#include "EglException.h"
#include <rocket/Log.h>
#include <boost/format.hpp>

namespace rocket { namespace egl {

EglDisplay::EglDisplay(EGLNativeDisplayType displayId) {
	// Fetching display
	EGLDisplay displayHandle = eglGetDisplay(displayId);
	if (displayHandle != EGL_NO_DISPLAY) {
		LOGD("Got valid display");
	} else {
		LOGE("Failed to acquire display");
		throw EglException("Failed to acquire display");
	}

	// Initialize display
	EGLint major;
	EGLint minor;
	auto result = eglInitialize(displayHandle, &major, &minor); // EGL_VERSION_1_0, EGL_VERSION_1_4);
	if (result == EGL_TRUE) {
		LOGD("Successfully initialized display, major=" << major << ", minor=" << minor);
	} else {
		LOGE("Failed to initialize display");
		throw EglException("Failed to initialize display");
	}

	display = unique_deleter_ptr<void>(displayHandle, [displayHandle](void *ptr) {
		LOGD("Destructing");
		if (ptr == nullptr) {
			return;
		}

		auto result = eglTerminate(displayHandle);
		if (result == EGL_TRUE) {
			LOGD("Terminated display");
		} else {
			LOGE("Failed to terminate display, invalid display... something is really fishy");
#ifndef NDEBUG
			std::abort(); // Let's abort in debug build to find what happened.
#endif
		}
		LOGD("Destructed");
	});
}

std::string EglDisplay::queryString(EGLint name) {
	return eglQueryString(display.get(), name);
}

std::vector<EGLConfig> EglDisplay::getConfigs() {
	EGLint numConfigs;

	auto result = eglGetConfigs(display.get(), nullptr, 0, &numConfigs);
	if (result == EGL_FALSE) {
		throw EglException("Unable to fetch config count");
	}

	std::vector<EGLConfig> configs(static_cast<std::size_t>(numConfigs));
	result = eglGetConfigs(display.get(), &configs[0], numConfigs, &numConfigs);
	if (result == EGL_FALSE) {
		throw EglException("Unable to fetch configs");
	}

	return configs;
}

std::vector<EGLConfig> EglDisplay::getConfigs(EglAttribMap const& attribs) {
	EGLint numConfigs;

	auto result = eglChooseConfig(display.get(), attribs.getAttribs(), nullptr, 0, &numConfigs);
	if (result == EGL_FALSE) {
		throw EglException("Unable to fetch config count");
	}

	std::vector<EGLConfig> configs(static_cast<std::size_t>(numConfigs));
	result = eglChooseConfig(display.get(), attribs.getAttribs(), &configs[0], numConfigs, &numConfigs);
	if (result == EGL_FALSE) {
		throw EglException("Unable to choose configs");
	}

	return configs;
}

EGLConfig EglDisplay::pickConfig(EglAttribMap const& attribs) {
	EGLint numConfigs;
	EGLConfig config;

	auto result = eglChooseConfig(display.get(), attribs.getAttribs(), &config, 1, &numConfigs);
	if (result == EGL_FALSE || numConfigs == 0) {
		std::string msg = (boost::format("Unable to pick config from %d available configurations.")
				% numConfigs).str();
		throw EglException(msg);
	}

	return config;
}

static void getAttribValue(EGLDisplay display, EGLConfig config, EglAttribMap &attribMap, EGLint attribName) {
	EGLint tmp;
	auto result = eglGetConfigAttrib(display, config, attribName, &tmp);
	if (result == EGL_TRUE) {
		attribMap[attribName] = tmp;
	} else {
		LOGD("Attribute " << eglAttribToString(attribName) << " not present in configuration");
	}
}

EglAttribMap EglDisplay::getConfigAttribs(EGLConfig config) const {
	EglAttribMap eglAttribs;

	getAttribValue(display.get(), config, eglAttribs, EGL_BUFFER_SIZE);
	getAttribValue(display.get(), config, eglAttribs, EGL_ALPHA_SIZE);
	getAttribValue(display.get(), config, eglAttribs, EGL_BLUE_SIZE);
	getAttribValue(display.get(), config, eglAttribs, EGL_GREEN_SIZE);
	getAttribValue(display.get(), config, eglAttribs, EGL_RED_SIZE);
	getAttribValue(display.get(), config, eglAttribs, EGL_DEPTH_SIZE);
	getAttribValue(display.get(), config, eglAttribs, EGL_STENCIL_SIZE);
	getAttribValue(display.get(), config, eglAttribs, EGL_CONFIG_CAVEAT);
	getAttribValue(display.get(), config, eglAttribs, EGL_CONFIG_ID);
	getAttribValue(display.get(), config, eglAttribs, EGL_LEVEL);
	getAttribValue(display.get(), config, eglAttribs, EGL_MAX_PBUFFER_HEIGHT);
	getAttribValue(display.get(), config, eglAttribs, EGL_MAX_PBUFFER_PIXELS);
	getAttribValue(display.get(), config, eglAttribs, EGL_MAX_PBUFFER_WIDTH);
	getAttribValue(display.get(), config, eglAttribs, EGL_NATIVE_RENDERABLE);
	getAttribValue(display.get(), config, eglAttribs, EGL_NATIVE_VISUAL_ID);
	getAttribValue(display.get(), config, eglAttribs, EGL_NATIVE_VISUAL_TYPE);
	getAttribValue(display.get(), config, eglAttribs, EGL_SAMPLES);
	getAttribValue(display.get(), config, eglAttribs, EGL_SAMPLE_BUFFERS);
	getAttribValue(display.get(), config, eglAttribs, EGL_SURFACE_TYPE);
	getAttribValue(display.get(), config, eglAttribs, EGL_TRANSPARENT_TYPE);
	getAttribValue(display.get(), config, eglAttribs, EGL_TRANSPARENT_BLUE_VALUE);
	getAttribValue(display.get(), config, eglAttribs, EGL_TRANSPARENT_GREEN_VALUE);
	getAttribValue(display.get(), config, eglAttribs, EGL_TRANSPARENT_RED_VALUE);
	getAttribValue(display.get(), config, eglAttribs, EGL_BIND_TO_TEXTURE_RGB);
	getAttribValue(display.get(), config, eglAttribs, EGL_BIND_TO_TEXTURE_RGBA);
	getAttribValue(display.get(), config, eglAttribs, EGL_MIN_SWAP_INTERVAL);
	getAttribValue(display.get(), config, eglAttribs, EGL_MAX_SWAP_INTERVAL);
	getAttribValue(display.get(), config, eglAttribs, EGL_LUMINANCE_SIZE);
	getAttribValue(display.get(), config, eglAttribs, EGL_ALPHA_MASK_SIZE);
	getAttribValue(display.get(), config, eglAttribs, EGL_COLOR_BUFFER_TYPE);
	getAttribValue(display.get(), config, eglAttribs, EGL_RENDERABLE_TYPE);
	getAttribValue(display.get(), config, eglAttribs, EGL_CONFORMANT);

	return eglAttribs;
}

std::unique_ptr<EglSurface> EglDisplay::createSurface(EGLConfig config, EGLNativeWindowType win) {
	return createSurface(config, win, EglAttribMap());
}

std::unique_ptr<EglSurface> EglDisplay::createSurface(EGLConfig config, EGLNativeWindowType win, EglAttribMap const& attribs) {
	return std::unique_ptr<EglSurface>(new EglSurface(display.get(), config, win, attribs));
}

std::unique_ptr<EglContext> EglDisplay::createContext(EGLConfig config, EglAttribMap const& attribs) {
	return createContext(config, EGL_NO_CONTEXT, attribs);
}

std::unique_ptr<EglContext> EglDisplay::createContext(EGLConfig config, EGLContext shared, EglAttribMap const& attribs) {
	return std::unique_ptr<EglContext>(new EglContext(display.get(), config, shared, attribs));
}

}}


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)

// Copyright (c) 2014-2015, Oracle and/or its affiliates.

// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_SIGNED_SIZE_TYPE_HPP
#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_SIGNED_SIZE_TYPE_HPP

#include <cstddef>
#include <boost/type_traits/make_signed.hpp>

namespace boost { namespace geometry
{

typedef boost::make_signed<std::size_t>::type signed_size_type;

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_SIGNED_SIZE_TYPE_HPP

max_stars_repo_name: cpp-pm/boost


text:
// -*- mode: c++; -*-

#include <functional>
#include <iostream>
#include <utility>

#include <boost/type_index.hpp>
namespace ti = boost::typeindex;

#define TI(x) ti::type_id_with_cvr< x > ().pretty_name ()
#define TV(x) ti::type_id_with_cvr< decltype (x) > ().pretty_name ()

static int a, b, c, d;

namespace X {

template< typename T >
struct box {
    explicit box (const T& t) noexcept (noexcept (T (t)))
        : value (t) {
        std::cout << " --> box< " << TI (T)
                  << " >::box (" << TI (decltype (t))
                  << ")\n";
        ++a;
    }

    explicit box (T&& t) noexcept (noexcept (T (std::move_if_noexcept (t))))
        : value (std::move_if_noexcept (t)) {
        std::cout << " --> box< " << TI (T) << " >::box ("
                  << TI (decltype (t)) << ")\n";
        ++b;
    }

private:
    template< typename U >
    using enable_construction_from = std::enable_if_t<
        std::is_constructible< T, U >::value >;

public:
    template< typename U, typename = enable_construction_from< U > >
    explicit box (U&& u) noexcept (noexcept (T (std::forward< U > (u))))
        : value (std::forward< U > (u)) {
        std::cout << " --> box< " << TI (T) << " >::box (" << TI (decltype (u))
                  << ")\n";
        ++c;
    }

    T value;
};

template< typename T >
struct box< T& > {
private:
    template< typename U >
    using enable_construction_from = std::enable_if_t<
        std::is_convertible< U, T& >::value >;

public:
    template< typename U, typename = enable_construction_from< U > >
    box (U&& u) noexcept (noexcept (static_cast< T& > (u)))
        : value (static_cast< T& > (u)) {
        std::cout << " --> box< " << TI (T&) << " >::box ("
                  << TI (decltype (u)) << ")\n";
        ++d;
    }

    std::reference_wrapper< T > value;
};

template< typename T >
struct gift {
private:
    template< typename U >
    static constexpr auto is_boxable_resource_v =
        std::is_constructible< box< T >, U >::value;

    template< typename U >
    using enable_construction_from = std::enable_if_t<
        is_boxable_resource_v< U > >;

public:
    template< typename U, typename = enable_construction_from< U > >
    explicit gift (U&& u) noexcept (
        noexcept (box< T > (std::forward< U > (u))))
        : value (std::forward< U > (u))
        { }

    box< T > value;
};

template< typename T >
inline auto
wrap (T&& t) {
    std::cout << "wrap(1)<" << TI (T) << "> (" << TI (T&&) << ")\n";
    return gift< T > (std::forward< T > (t));
}

template< typename T >
inline auto
wrap (T& t) {
    std::cout << "wrap(2)<" << TI (T) << "> (" << TI (T&) << ")\n";
    return gift< T& > (t);
}

} // namespace X

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

template< typename T, typename U >
inline void do_box (U&& u) {
    auto x = X::box< T > (std::forward< U > (u));
    std::cout << "   : " << TV (x) << "\n\n";
}

template< typename T, typename U >
using enable_if_convertible_t = std::enable_if_t<
    std::is_convertible< U&, T& >::value >;

template< typename T, typename U >
using enable_if_not_convertible_t = std::enable_if_t<
    !std::is_convertible< U&, T& >::value >;

template< typename T, typename U = T >
inline enable_if_convertible_t< T, U >
box () {
    do_box< T, U > (U{ });

    {
        U u;
        do_box< T > (u);
        do_box< T& > (u);
    }

    {
        const U u{ };
        do_box< T > (u);
        do_box< const T& > (u);
    }
}

template< typename T, typename U = T >
inline enable_if_not_convertible_t< T, U >
box () {
    do_box< T, U > (U{ });

    {
        U u;
        do_box< T > (u);
    }

    {
        const U u{ };
        do_box< T > (u);
        do_box< const T& > (u);
    }
}

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

int f () { return 0; }

struct V { };
struct W : V { };

static void
direct_construction () {
    box< int > ();
    box< int, unsigned > ();
    box< V, W > ();

    {
        auto x = X::box< int(&)() > (f);
        std::cout << "   : " << TV (x) << "\n\n";

        auto y = X::box< int(*)() > (&f);
        std::cout << "   : " << TV (y) << "\n\n";
    }

    {
        auto lambda = [&]{ return 0; };
        auto x = X::box< decltype (lambda) > (std::move (lambda));
        std::cout << "   : " << TV (x) << "\n\n";
    }

    {
        auto lambda = [&]{ return 0; };
        auto x = X::box< decltype (lambda)& > (lambda);
        std::cout << "   : " << TV (x) << "\n\n";
    }
}

static void
indirect_construction () {
    using namespace X;

    {
        auto x = wrap (0);
        std::cout << "   : " << TV (x) << "\n\n";
    }

    {
        int i{ };
        auto x = wrap (i);
        std::cout << "   : " << TV (x) << "\n\n";
    }

    {
        const int i{ };
        auto x = wrap (i);
        std::cout << "   : " << TV (x) << "\n\n";
    }

    {
        auto x = wrap< unsigned > (int{ });
        std::cout << "   : " << TV (x) << "\n\n";
    }

    {
        int i{ };
        auto x = wrap< unsigned > (i);
        std::cout << "   : " << TV (x) << "\n\n";
    }

    {
        W w;
        auto x = wrap< V > (w);
        std::cout << "   : " << TV (x) << "\n\n";
    }

    {
        const W w{ };
        auto x = wrap< const V > (w);
        std::cout << "   : " << TV (x) << "\n\n";
    }

    {
        auto x = wrap (f);
        std::cout << "   : " << TV (x) << "\n\n";
    }

    {
        auto x = wrap< int(*)() > (&f);
        std::cout << "   : " << TV (x) << "\n\n";
    }

    {
        auto x = wrap ([&]{ return 0; });
        std::cout << "   : " << TV (x) << "\n\n";
    }
}

int main () {
    a = b = c = d = 0;
    direct_construction ();
    std::cout << a << ", " << b << ", " << c << ", " << d << "\n\n";

    a = b = c = d = 0;
    indirect_construction ();
    std::cout << a << ", " << b << ", " << c << ", " << d << "\n";

    return 0;
}


text:
#include <iostream> //std::cout
#include <chrono> //std::chrono::high_resolution_clock, std::chrono::duration_cast
#include <fstream> // std::ofstream
#include <filesystem> //fs::is_directory, fs::create_directory
#include <boost/progress.hpp> //boost::progress_display, boost::progress_timer
#include <numeric> //std::accumulate

#include "histogram.h"
#include "init.h"
#include "vars.h"
#include "evolve.h"

namespace fs = std::filesystem;
void print_parameters();

//three function declarations below are no longer in use
std::vector<std::vector<double>> evolve_and_hist(float time, std::vector <std::vector<double>> init_vel_matrix, std::vector <std::vector<double>> init_pos_matrix, std::list<double> bin_list);
void sample_xv_in_csv(std::string folder, std::string file, float time, std::vector <std::vector<double>> init_vel_matrix, std::vector <std::vector<double>> init_pos_matrix, bool exporting_vel);
void old_main();
/*
 * Runs hard rod gas simulation a number of times given by no_samples for each sampling_time, up until max_time. Set ALL parameters in vars.h
 * Saves the averaged density and current distribution time_series of each simulation run in two csv files.
 */
int main() {

    print_parameters();

    //Create a directory if there isn't one
    if (fs::is_directory(folder_name)) { std::cout << "N.B. Directory with this name already exists.\n\n"; }
    else { fs::create_directory(folder_name); }

    //Initialise csv files for exporting
    //Set file names
    std::string file_name = "T" + std::to_string(int(max_time)) + "_ST" + std::to_string(int(sampling_time)) + \
        "_V" + std::to_string(float(V)) + "_kickW" + std::to_string(kick_width) + "_temp" + std::to_string(float(T)) + \
        "_samples" + std::to_string(no_samples) \
        + "_rods" + std::to_string(N) + "_sys_length" + std::to_string(int(L)) + "_rodlength" + std::to_string(float(rod_length));

    std::ofstream rho_bar_csvfile;
    rho_bar_csvfile.open(".\\" + folder_name + "\\D_" + file_name + ".csv"); //Create csv file in which density data is stored

    std::ofstream j_bar_csvfile;
    j_bar_csvfile.open(".\\" + folder_name + "\\J_" + file_name + ".csv"); //Create csv file in which current data is stored

    if (fs::exists(".\\" + folder_name + "\\" + file_name)) {
        std::cout << "File name already exists - please rename. exiting";
        return 0;
    }
    else {

        //Initialise matrices of density + current data for reading to csv

        int no_time_samples = std::round(max_time / sampling_time + 1);
        int no_cells = std::round(L / cell_length);

        std::vector<std::vector<double>> rho_accumulator(no_time_samples, std::vector<double>(no_cells)); //density matrix size no_time_samples x no_cells
        std::vector<std::vector<double>> j_accumulator(no_time_samples, std::vector<double>(no_cells)); //current matrix size no_time_samples x no_cells

        //Initialise histogram bins

        std::list<double> bins_list = init_bins(std::round(L / cell_length));

        //Initalise progress bar
        std::cout << "Running simulation:" << "\n";
        unsigned int sample_size = no_samples;
        boost::progress_display show_progress(sample_size);

        //Start timing

        boost::progress_timer t;

        for (unsigned int i = 0; i < sample_size; i++) {

            //initialise sample positions + velocities from init.cpp

            std::vector<double> x_0 = init_uniform_positions();

            std::vector<double> v_0 = init_velocities();

            if (implementing_v_kick) { v_0 = velocity_kick(kick_centre, V, kick_width, v_0, x_0); }

            for (int j = 0; j < static_cast<int> (max_time / sampling_time) + 1; j++) {

                std::vector<std::vector<double>> xv_evolved = evolve_to(sampling_time * j, x_0, v_0); // call evolve.cpp function

                std::vector<std::vector<double>> rho_j_dist_matrix = rho_j_dist(xv_evolved[0], xv_evolved[1], bins_list); // call histogram.cpp function

                //std::cout << std::accumulate(rho_j_dist_matrix[0].begin(), rho_j_dist_matrix[0].end(), 0); //print out sum of the bins

                //add to density and current containers
                std::transform(rho_accumulator[j].begin(), rho_accumulator[j].end(), rho_j_dist_matrix[0].begin(), rho_accumulator[j].begin(), std::plus<double>());
                std::transform(j_accumulator[j].begin(), j_accumulator[j].end(), rho_j_dist_matrix[1].begin(), j_accumulator[j].begin(), std::plus<double>());

            }

            ++show_progress;

        }
        int sample_no = no_samples; //no_samples is a const so can't be used in a lambda

        for (int i = 0; i < no_time_samples; i++) {
            //normalise rho and j by sample_no
            std::transform(rho_accumulator[i].begin(), rho_accumulator[i].end(), rho_accumulator[i].begin(), [&sample_no](auto& c) {return c / sample_no;});
            std::transform(j_accumulator[i].begin(), j_accumulator[i].end(), j_accumulator[i].begin(), [&sample_no](auto& c) {return c / sample_no;});
        }
        //write rho_accumulator and j_accumulator matrices to csv files

        if (rho_bar_csvfile.is_open()) {

            for (unsigned i = 0; i < rho_accumulator.size(); i++) {
                for (unsigned j = 0; j < rho_accumulator[i].size() - 1; j++) {
                    rho_bar_csvfile << rho_accumulator[i][j] << ",";
                }
                rho_bar_csvfile << rho_accumulator[i].back() << "\n"; //last entry on row doesn't require a comma
            }
        }
        else {
            std::cout << "\nError opening file.";
        }

        if (j_bar_csvfile.is_open()) {

            for (unsigned i = 0; i < j_accumulator.size(); i++) {
                for (unsigned j = 0; j < j_accumulator[i].size() - 1; j++) {
                    j_bar_csvfile << j_accumulator[i][j] << ",";
                }
                j_bar_csvfile << j_accumulator[i].back() << "\n"; //last entry on row doesn't require a comma
            }
        }
        else {
            std::cout << "\nError opening file.";
        }
        //End of simulation
        std::cout << "\n\nHard rod simulation has completed with runtime of ";
    }
}

/*
 * Prints parameters in vars.h
 */
void print_parameters() {
    std::cout << "Parameters chosen:\n";
    std::cout << "Max_Time: " << max_time << " Sampling_Time: " << sampling_time << " No_Samples: " << no_samples << "\n";
    std::cout << "No_Rods: " << N << " Temp: " << T << " Sys_Length: " << L << " Rod_Length: " << std::to_string(rod_length) << " Cell_Length: " << std::to_string(cell_length) << "\n\n";
    std::cout << "Position sampling method: " << posn_init_method << "\n";

    if (posn_init_method == "init_densityjump") {
        std::cout << "Left_weight: " << l_weight << " Right_weight: " << r_weight << "\n";
    }

    if (implementing_v_kick) {
        std::cout << "Implementing_v_kick: Yes" << "\n";
        std:: cout << "Kick_Centre: " << kick_centre << " Kick_Width: " << kick_width << " Kick_Strength: " << V << "\n\n";
    }
    else {
        std::cout << "Implementing_v_kick: No" << "\n";
    }
}

/*
* Calls evolve.cpp and hist.cpp functions - returns averaged density and current distributions for each time.
*/
std::vector<std::vector<double>> evolve_and_hist(float time, std::vector <std::vector<double>> init_vel_matrix, std::vector <std::vector<double>> init_pos_matrix, std::list<double> bin_list) {

    std::vector<double> rho_accumulator(std::round(L / cell_length)); //initialise vector which adds the density distributions for each sample
    std::vector<double> j_accumulator(std::round(L / cell_length)); //initialise vector which adds the current distributions for each sample

    for (size_t i = 0; i < init_vel_matrix.size(); i++) {

        auto start = std::chrono::high_resolution_clock::now();

        //std::cout << "\nRun " << i << " is in progress...";
        auto iter_start = std::chrono::high_resolution_clock::now();

        //Call evolve.cpp function
        auto xv_matrix = evolve_to(time, init_pos_matrix[i], init_vel_matrix[i]); // x_evolved = xv_matrix[0]; v_evolved = xv_matrix[1]

        //histogram call
        auto rho_j_dist_matrix = rho_j_dist(xv_matrix[0], xv_matrix[1],bin_list);

        //add to density and current containers
        std::transform(rho_accumulator.begin(), rho_accumulator.end(), rho_j_dist_matrix[0].begin(), rho_accumulator.begin(), std::plus<double>());
        std::transform(j_accumulator.begin(), j_accumulator.end(), rho_j_dist_matrix[1].begin(), j_accumulator.begin(), std::plus<double>());

        // Print time data
        auto iter_stop = std::chrono::high_resolution_clock::now();
        auto iter_duration = std::chrono::duration_cast<std::chrono::microseconds>(iter_stop - iter_start);
        auto time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(iter_stop - start);
    }
    //normalise density and current containers by no_samples
    int sample_no = no_samples;
    std::transform(rho_accumulator.begin(), rho_accumulator.end(), rho_accumulator.begin(), [&sample_no](auto& c) {return c / sample_no;});
    std::transform(j_accumulator.begin(), j_accumulator.end(), j_accumulator.begin(), [& sample_no](auto& c) {return c / sample_no;});

    return { rho_accumulator, j_accumulator };
}

/*
 * Creates a .csv file for both x[N] and v[N] after the system is evolved to a particular time. Both .csv files have 'no_rods' columns and 'no_samples' rows.
 *
 * @param std::string folder is the existing/new folder in which you want to store the .csv file
 * @param std::string file contains the simulation parameter data of the .csv file
 * @param float time is the duration for which evolve_to runs (evolve_to takes 'time' as an argument)
 * @param init_vel_matrix and init_pos_matrix are the matrices containing 'no_samples' intial velocity and position vectors respectively
 * @param bool export_vel exports velocities to a csv file, default value is False.
 */
void sample_xv_in_csv(std::string folder, std::string file, float time, std::vector <std::vector<double>> init_vel_matrix, std::vector <std::vector<double>> init_pos_matrix, bool exporting_vel) {

    std::ofstream positions_csv_file;
    positions_csv_file.open(".\\" + folder + "\\P_" + file + ".csv"); //Create csv file in which position data is stored

    std::ofstream velocities_csv_file;
    velocities_csv_file.open(".\\" + folder + "\\V_" + file + ".csv"); //Create csv file in which velocity data is stored

    //std::cout << "Beginning sample_run:" << "\n";

    auto start = std::chrono::high_resolution_clock::now();

    //Call evolve functions 'sample_no' times

    for (size_t i = 0; i < init_vel_matrix.size(); i++) {

        //std::cout << "\nRun " << i << " is in progress...";
        auto iter_start = std::chrono::high_resolution_clock::now();

        //Call evolve.cpp function
        auto xv_matrix = evolve_to(time, init_pos_matrix[i], init_vel_matrix[i]); // x_evolved = xv_matrix[0]; v_evolved = xv_matrix[1]

        //HISTOGRAM CALL

        // Print time data
        auto iter_stop = std::chrono::high_resolution_clock::now();
        auto iter_duration = std::chrono::duration_cast<std::chrono::microseconds>(iter_stop - iter_start);
        auto time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(iter_stop - start);

        //std::cout << " and has completed after " << iter_duration.count() << "mu_s. Total runtime is " << time_elapsed.count() << "ms.";

        //Entering position data to csv file
        if (positions_csv_file.is_open()) {

            for (int j = 0; j < N - 1; j++) {
                //positions_csv_file << xv_matrix[0][j] << ",";
            }
            //positions_csv_file << xv_matrix[0][N - 1] << "\n"; //last entry on row doesn't require a comma
        }
        else {
            std::cout << "\nError opening file.";
        }

        if (exporting_vel) {
            if (velocities_csv_file.is_open()) {

                for (int j = 0; j < N - 1; j++) {
                    //velocities_csv_file << xv_matrix[1][j] << ",";
                }
                //velocities_csv_file << xv_matrix[1][N - 1] << "\n"; //last entry on row doesn't require a comma
            }
            else {
                std::cout << "\nError opening file.";
            }
        }

    }
    //Close csv files
    positions_csv_file.close();
    if (exporting_vel) {
        velocities_csv_file.close();
    }
    else {
        velocities_csv_file.close();
        fs::remove(".\\" + folder + "\\V_" + file + ".csv");
    }
}

void old_main() {
    print_parameters();

    //Run initialisation
    //Create a directory if there isn't one
    if (fs::is_directory(folder_name)) { std::cout << "N.B. Directory with this name already exists.\n\n"; }
    else { fs::create_directory(folder_name); }

    //Start clock
    std::cout << "Beginning simulation:" << "\n";

    auto start = std::chrono::high_resolution_clock::now();

    //Call init.cpp functions
    std::cout << "Initialisation in progress...";
    std::vector <std::vector<double>> init_vel_matrix = init_velocities_matrix();
    std::vector <std::vector<double>> init_posn_matrix = init_positions_matrix(posn_init_method);

    if (implementing_v_kick) { init_vel_matrix = kick_velocity_matrix(init_vel_matrix, init_posn_matrix); }

    auto init_stop = std::chrono::high_resolution_clock::now();
    auto init_duration = std::chrono::duration_cast<std::chrono::milliseconds>(init_stop - start);
    std::cout << " and has completed after " << init_duration.count() << "ms. total runtime is " << init_duration.count() / 1000 << "s.";

    std::cout << "\nBegin evolving + sampling:" << "\n";

    //set file_name
    std::string file_name = "T" + std::to_string(std::round(max_time)) + "ST" + std::to_string(std::round(sampling_time)) + \
        "_temp" + std::to_string(std::round(T)) + "_samples" + std::to_string(no_samples) \
        + "_rods" + std::to_string(N) + "_sys_length" + std::to_string(std::round(L)) + "_rodlength" + std::to_string(rod_length);

    //check if file_name doesn't already exist inside folder_name
    if (fs::exists(".\\" + folder_name + "\\" + file_name)) {
        std::cout << "File name already exists - please rename. exiting";
        //return 0;
    }
    else {
        std::ofstream rho_bar_csvfile;
        rho_bar_csvfile.open(".\\" + folder_name + "\\D_" + file_name + ".csv"); //Create csv file in which density data is stored

        std::ofstream j_bar_csvfile;
        j_bar_csvfile.open(".\\" + folder_name + "\\J_" + file_name + ".csv"); //Create csv file in which current data is stored

        int no_time_samples = std::round(max_time / sampling_time) + 1;

        std::vector<std::vector<double>> rho_t_series(no_time_samples);
        std::vector<std::vector<double>> j_t_series(no_time_samples);

        std::list<double> bins_list = init_bins(std::round(L / cell_length));

        //for loop to run evolve_and_hist every 'sampling_time' up until 'max_time'
        for (int i = 0; i < static_cast<int> (max_time / sampling_time) + 1; i++) {

            std::cout << "\nSampling at time t = " << std::to_string(sampling_time * i) << " is in progress...";
            auto iter_start = std::chrono::high_resolution_clock::now();

            //call evolve_and_hist

            std::vector<std::vector<double>> averaged_rho_j_dists = evolve_and_hist(sampling_time * i, init_vel_matrix, init_posn_matrix, bins_list);
            rho_t_series[i] = averaged_rho_j_dists[0];
            j_t_series[i] = averaged_rho_j_dists[1];

            auto iter_stop = std::chrono::high_resolution_clock::now();
            auto iter_duration = std::chrono::duration_cast<std::chrono::milliseconds>(iter_stop - iter_start);
            auto time_elapsed = std::chrono::duration_cast<std::chrono::seconds>(iter_stop - start);
            std::cout << " and has completed after " << iter_duration.count() << "ms. Total runtime is " << time_elapsed.count() << "s.";
        }
        //exporting to csv

        if (rho_bar_csvfile.is_open()) {

            for (unsigned i = 0; i < rho_t_series.size(); i++) {
                for (unsigned j = 0; j < rho_t_series[i].size() - 1; j++) {
                    rho_bar_csvfile << rho_t_series[i][j] << ",";
                }
                rho_bar_csvfile << rho_t_series[i].back() << "\n"; //last entry on row doesn't require a comma
            }
        }
        else {
            std::cout << "\nError opening file.";
        }

        if (j_bar_csvfile.is_open()) {

            for (unsigned i = 0; i < j_t_series.size(); i++) {
                for (unsigned j = 0; j < j_t_series[i].size() - 1; j++) {
                    j_bar_csvfile << j_t_series[i][j] << ",";
                }
                j_bar_csvfile << j_t_series[i].back() << "\n"; //last entry on row doesn't require a comma
            }
        }
        else {
            std::cout << "\nError opening file.";
        }

    }
}

max_stars_repo_name: IraPelidae/Classical-Nonlinear-Response

max_issues_repo_name: IraPelidae/Classical-Nonlinear-Response

max_forks_repo_name: IraPelidae/Classical-Nonlinear-Response


text:
// Copyright 2005 The Trustees of Indiana University.

// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

//  Authors: Jeremiah Willcock
//           Douglas Gregor
//           Andrew Lumsdaine

// The libstdc++ debug mode makes this test run for hours...
#ifdef _GLIBCXX_DEBUG
#  undef _GLIBCXX_DEBUG
#endif

// Test for the compressed sparse row graph type
#include <boost/graph/compressed_sparse_row_graph.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/erdos_renyi_generator.hpp>
#include <boost/graph/graph_utility.hpp>
#include <boost/random/linear_congruential.hpp>
#include <boost/concept_check.hpp> // for ignore_unused_variable_warning
#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
#include <boost/lexical_cast.hpp>
#include <boost/iterator/transform_iterator.hpp>
#include <boost/limits.hpp>
#include <string>
#include <boost/graph/iteration_macros.hpp>
#include <boost/test/minimal.hpp>

// Algorithms to test against
#include <boost/graph/betweenness_centrality.hpp>
#include <boost/graph/kruskal_min_spanning_tree.hpp>

typedef boost::adjacency_list<> GraphT;
typedef boost::erdos_renyi_iterator<boost::minstd_rand, GraphT> ERGen;

struct VertexData
{
  int index;
};

struct EdgeData
{
  int index_e;
};

typedef boost::compressed_sparse_row_graph<boost::directedS, VertexData, EdgeData>
  CSRGraphT;

typedef boost::compressed_sparse_row_graph<boost::bidirectionalS, VertexData, EdgeData>
  BidirCSRGraphT;

template <class G1, class VI1, class G2, class VI2, class IsomorphismMap>
void assert_graphs_equal(const G1& g1, const VI1& vi1,
                         const G2& g2, const VI2& vi2,
                         const IsomorphismMap& iso) {
  using boost::out_degree;

  BOOST_CHECK (num_vertices(g1) == num_vertices(g2));
  BOOST_CHECK (num_edges(g1) == num_edges(g2));

  typedef typename boost::graph_traits<G1>::vertex_iterator vertiter1;
  {
    vertiter1 i, iend;
    for (boost::tie(i, iend) = vertices(g1); i != iend; ++i) {
      typename boost::graph_traits<G1>::vertex_descriptor v1 = *i;
      typename boost::graph_traits<G2>::vertex_descriptor v2 = iso[v1];

      BOOST_CHECK (vi1[v1] == vi2[v2]);

      BOOST_CHECK (out_degree(v1, g1) == out_degree(v2, g2));
      std::vector<std::size_t> edges1(out_degree(v1, g1));
      typename boost::graph_traits<G1>::out_edge_iterator oe1, oe1end;
      for (boost::tie(oe1, oe1end) = out_edges(v1, g1); oe1 != oe1end; ++oe1) {
        BOOST_CHECK (source(*oe1, g1) == v1);
        edges1.push_back(vi1[target(*oe1, g1)]);
      }
      std::vector<std::size_t> edges2(out_degree(v2, g2));
      typename boost::graph_traits<G2>::out_edge_iterator oe2, oe2end;
      for (boost::tie(oe2, oe2end) = out_edges(v2, g2); oe2 != oe2end; ++oe2) {
        BOOST_CHECK (source(*oe2, g2) == v2);
        edges2.push_back(vi2[target(*oe2, g2)]);
      }

      std::sort(edges1.begin(), edges1.end());
      std::sort(edges2.begin(), edges2.end());
      if (edges1 != edges2) {
        std::cerr << "For vertex " << v1 << std::endl;
        std::cerr << "edges1:";
        for (size_t i = 0; i < edges1.size(); ++i) std::cerr << " " << edges1[i];
        std::cerr << std::endl;
        std::cerr << "edges2:";
        for (size_t i = 0; i < edges2.size(); ++i) std::cerr << " " << edges2[i];
        std::cerr << std::endl;
      }
      BOOST_CHECK (edges1 == edges2);
    }
  }

  {
    std::vector<std::pair<std::size_t, std::size_t> > all_edges1;
    std::vector<std::pair<std::size_t, std::size_t> > all_edges2;
    typename boost::graph_traits<G1>::edge_iterator ei1, ei1end;
    for (boost::tie(ei1, ei1end) = edges(g1); ei1 != ei1end; ++ei1)
      all_edges1.push_back(std::make_pair(vi1[source(*ei1, g1)],
                                          vi1[target(*ei1, g1)]));
    typename boost::graph_traits<G2>::edge_iterator ei2, ei2end;
    for (boost::tie(ei2, ei2end) = edges(g2); ei2 != ei2end; ++ei2)
      all_edges2.push_back(std::make_pair(vi2[source(*ei2, g2)],
                                          vi2[target(*ei2, g2)]));
    std::sort(all_edges1.begin(), all_edges1.end());
    std::sort(all_edges2.begin(), all_edges2.end());
    BOOST_CHECK (all_edges1 == all_edges2);
  }
}

template <typename Structure>
void check_consistency_one(const Structure& g) {
  // Do a bunch of tests on the graph internal data
  // Check that m_rowstart entries are valid, and that entries after
  // m_last_source + 1 are all zero
  BOOST_CHECK(g.m_rowstart[0] == 0);
  for (size_t i = 0;
       i < g.m_rowstart.size() - 1;
       ++i) {
    BOOST_CHECK(g.m_rowstart[i + 1] >= g.m_rowstart[i]);
    BOOST_CHECK(g.m_rowstart[i + 1] <= g.m_rowstart.back());
  }
  // Check that m_column entries are within range
  for (size_t i = 0; i < g.m_rowstart.back(); ++i) {
    BOOST_CHECK(g.m_column[i] < g.m_rowstart.size() - 1);
  }
}

template <typename Graph>
void check_consistency_dispatch(const Graph& g,
                                boost::incidence_graph_tag) {
  check_consistency_one(g.m_forward);
}

template <class G>
void assert_bidir_equal_in_both_dirs(const G& g) {
  BOOST_CHECK (g.m_forward.m_rowstart.size() == g.m_backward.m_rowstart.size());
  BOOST_CHECK (g.m_forward.m_column.size() == g.m_backward.m_column.size());
  typedef typename boost::graph_traits<G>::vertex_descriptor Vertex;
  typedef typename boost::graph_traits<G>::edges_size_type EdgeIndex;
  std::vector<boost::tuple<EdgeIndex, Vertex, Vertex> > edges_forward, edges_backward;
  for (Vertex i = 0; i < g.m_forward.m_rowstart.size() - 1; ++i) {
    for (EdgeIndex j = g.m_forward.m_rowstart[i];
         j < g.m_forward.m_rowstart[i + 1]; ++j) {
      edges_forward.push_back(boost::make_tuple(j, i, g.m_forward.m_column[j]));
    }
  }
  for (Vertex i = 0; i < g.m_backward.m_rowstart.size() - 1; ++i) {
    for (EdgeIndex j = g.m_backward.m_rowstart[i];
         j < g.m_backward.m_rowstart[i + 1]; ++j) {
      edges_backward.push_back(boost::make_tuple(g.m_backward.m_edge_properties[j], g.m_backward.m_column[j], i));
    }
  }
  std::sort(edges_forward.begin(), edges_forward.end());
  std::sort(edges_backward.begin(), edges_backward.end());
  BOOST_CHECK (edges_forward == edges_backward);
}

template <typename Graph>
void check_consistency_dispatch(const Graph& g,
                                boost::bidirectional_graph_tag) {
  check_consistency_one(g.m_forward);
  check_consistency_one(g.m_backward);
  assert_bidir_equal_in_both_dirs(g);
}

template <typename Graph>
void check_consistency(const Graph& g) {
  check_consistency_dispatch(g, typename boost::graph_traits<Graph>::traversal_category());
}

template<typename OrigGraph>
void graph_test(const OrigGraph& g)
{
  // Check copying of a graph
  CSRGraphT g2(g);
  check_consistency(g2);
  BOOST_CHECK((std::size_t)std::distance(edges(g2).first, edges(g2).second)
              == num_edges(g2));
  assert_graphs_equal(g, boost::identity_property_map(),
                      g2, boost::identity_property_map(),
                      boost::identity_property_map());

  // Check constructing a graph from iterators
  CSRGraphT g3(boost::edges_are_sorted,
              boost::make_transform_iterator(edges(g2).first,
                                              boost::detail::make_edge_to_index_pair(g2)),
               boost::make_transform_iterator(edges(g2).second,
                                              boost::detail::make_edge_to_index_pair(g2)),
               num_vertices(g));
  check_consistency(g3);
  BOOST_CHECK((std::size_t)std::distance(edges(g3).first, edges(g3).second)
              == num_edges(g3));
  assert_graphs_equal(g2, boost::identity_property_map(),
                      g3, boost::identity_property_map(),
                      boost::identity_property_map());

  // Check constructing a graph using in-place modification of vectors
  {
    std::vector<std::size_t> sources(num_edges(g2));
    std::vector<std::size_t> targets(num_edges(g2));
    std::size_t idx = 0;
    // Edges actually sorted
    BGL_FORALL_EDGES(e, g2, CSRGraphT) {
      sources[idx] = source(e, g2);
      targets[idx] = target(e, g2);
      ++idx;
    }
    CSRGraphT g3a(boost::construct_inplace_from_sources_and_targets,
                  sources,
                  targets,
                  num_vertices(g2));
    check_consistency(g3a);
    assert_graphs_equal(g2, boost::identity_property_map(),
                        g3a, boost::identity_property_map(),
                        boost::identity_property_map());
  }
  {
    std::vector<std::size_t> sources(num_edges(g2));
    std::vector<std::size_t> targets(num_edges(g2));
    std::size_t idx = 0;
    // Edges reverse-sorted
    BGL_FORALL_EDGES(e, g2, CSRGraphT) {
      sources[num_edges(g2) - 1 - idx] = source(e, g2);
      targets[num_edges(g2) - 1 - idx] = target(e, g2);
      ++idx;
    }
    CSRGraphT g3a(boost::construct_inplace_from_sources_and_targets,
                  sources,
                  targets,
                  num_vertices(g2));
    check_consistency(g3a);
    assert_graphs_equal(g2, boost::identity_property_map(),
                        g3a, boost::identity_property_map(),
                        boost::identity_property_map());
  }
  {
    std::vector<std::size_t> sources(num_edges(g2));
    std::vector<std::size_t> targets(num_edges(g2));
    std::size_t idx = 0;
    // Edges scrambled using Fisher-Yates shuffle (Durstenfeld variant) from
    // Wikipedia
    BGL_FORALL_EDGES(e, g2, CSRGraphT) {
      sources[idx] = source(e, g2);
      targets[idx] = target(e, g2);
      ++idx;
    }
    boost::minstd_rand gen(1);
    if (num_edges(g) != 0) {
      for (std::size_t i = num_edges(g) - 1; i > 0; --i) {
        std::size_t scrambled = boost::uniform_int<>(0, i)(gen);
        if (scrambled == i) continue;
        using std::swap;
        swap(sources[i], sources[scrambled]);
        swap(targets[i], targets[scrambled]);
      }
    }
    CSRGraphT g3a(boost::construct_inplace_from_sources_and_targets,
                  sources,
                  targets,
                  num_vertices(g2));
    check_consistency(g3a);
    assert_graphs_equal(g2, boost::identity_property_map(),
                        g3a, boost::identity_property_map(),
                        boost::identity_property_map());
  }

  CSRGraphT::edge_iterator ei, ei_end;

  // Check edge_from_index (and implicitly the edge_index property map) for
  // each edge in g2
  std::size_t last_src = 0;
  for (boost::tie(ei, ei_end) = edges(g2); ei != ei_end; ++ei) {
    BOOST_CHECK(edge_from_index(get(boost::edge_index, g2, *ei), g2) == *ei);
    std::size_t src = get(boost::vertex_index, g2, source(*ei, g2));
    (void)(std::size_t)get(boost::vertex_index, g2, target(*ei, g2));
    BOOST_CHECK(src >= last_src);
    last_src = src;
  }

  // Check out edge iteration and vertex iteration for sortedness
  CSRGraphT::vertex_iterator vi, vi_end;
  std::size_t last_vertex = 0;
  bool first_iter = true;
  for (boost::tie(vi, vi_end) = vertices(g2); vi != vi_end; ++vi) {
    std::size_t v = get(boost::vertex_index, g2, *vi);
    BOOST_CHECK(first_iter || v > last_vertex);
    last_vertex = v;
    first_iter = false;

    CSRGraphT::out_edge_iterator oei, oei_end;
    for (boost::tie(oei, oei_end) = out_edges(*vi, g2); oei != oei_end; ++oei) {
      BOOST_CHECK(source(*oei, g2) == *vi);
    }

    // Find a vertex for testing
    CSRGraphT::vertex_descriptor test_vertex = vertex(num_vertices(g2) / 2, g2);
    int edge_count = 0;
    CSRGraphT::out_edge_iterator oei2, oei2_end;
    for (boost::tie(oei2, oei_end) = out_edges(*vi, g2); oei2 != oei_end; ++oei2) {
      if (target(*oei2, g2) == test_vertex)
        ++edge_count;
    }
  }

  // Run brandes_betweenness_centrality, which touches on a whole lot
  // of things, including VertexListGraph and IncidenceGraph
  using namespace boost;
  std::vector<double> vertex_centralities(num_vertices(g3));
  std::vector<double> edge_centralities(num_edges(g3));
  brandes_betweenness_centrality
    (g3,
     make_iterator_property_map(vertex_centralities.begin(),
                                get(boost::vertex_index, g3)),
     make_iterator_property_map(edge_centralities.begin(),
                                get(boost::edge_index, g3)));
    // Extra qualifications for aCC

  // Invert the edge centralities and use these as weights to
  // Kruskal's MST algorithm, which will test the EdgeListGraph
  // capabilities.
  double max_val = (std::numeric_limits<double>::max)();
  for (std::size_t i = 0; i < num_edges(g3); ++i)
    edge_centralities[i] =
      edge_centralities[i] == 0.0? max_val : 1.0 / edge_centralities[i];

  typedef boost::graph_traits<CSRGraphT>::edge_descriptor edge_descriptor;
  std::vector<edge_descriptor> mst_edges;
  mst_edges.reserve(num_vertices(g3));
  kruskal_minimum_spanning_tree
    (g3, std::back_inserter(mst_edges),
     weight_map(make_iterator_property_map(edge_centralities.begin(),
                                           get(boost::edge_index, g3))));
}

void graph_test(int nnodes, double density, int seed)
{
  boost::minstd_rand gen(seed);
  std::cout << "Testing " << nnodes << " density " << density << std::endl;
  GraphT g(ERGen(gen, nnodes, density), ERGen(), nnodes);
  graph_test(g);
}

void test_graph_properties()
{
  using namespace boost;

  typedef compressed_sparse_row_graph<directedS,
                                      no_property,
                                      no_property,
                                      property<graph_name_t, std::string> >
    CSRGraphT;

  CSRGraphT g;
  BOOST_CHECK(get_property(g, graph_name) == "");
  set_property(g, graph_name, "beep");
  BOOST_CHECK(get_property(g, graph_name) == "beep");
}

struct Vertex
{
  double centrality;
};

struct Edge
{
  Edge(double weight) : weight(weight), centrality(0.0) { }

  double weight;
  double centrality;
};

void test_vertex_and_edge_properties()
{
  using namespace boost;
  typedef compressed_sparse_row_graph<directedS, Vertex, Edge>
    CSRGraphWithPropsT;

  typedef std::pair<int, int> E;
  E edges_init[6] = { E(0, 1), E(0, 3), E(1, 2), E(3, 1), E(3, 4), E(4, 2) };
  double weights[6] = { 1.0, 1.0, 0.5, 1.0, 1.0, 0.5 };
  double centrality[5] = { 0.0, 1.5, 0.0, 1.0, 0.5 };

  CSRGraphWithPropsT g(boost::edges_are_sorted, &edges_init[0], &edges_init[0] + 6, &weights[0], 5, 6);
  brandes_betweenness_centrality
    (g,
     centrality_map(get(&Vertex::centrality, g)).
     weight_map(get(&Edge::weight, g)).
     edge_centrality_map(get(&Edge::centrality, g)));

  BGL_FORALL_VERTICES(v, g, CSRGraphWithPropsT)
    BOOST_CHECK(g[v].centrality == centrality[v]);
}

int test_main(int argc, char* argv[])
{
  // Optionally accept a seed value
  int seed = int(std::time(0));
  if (argc > 1) seed = boost::lexical_cast<int>(argv[1]);

  std::cout << "Seed = " << seed << std::endl;
  {
    std::cout << "Testing empty graph" << std::endl;
    CSRGraphT g;
    graph_test(g);
  }
  //  graph_test(1000, 0.05, seed);
  //  graph_test(1000, 0.0, seed);
  //  graph_test(1000, 0.1, seed);
  graph_test(1000, 0.001, seed);
  graph_test(1000, 0.0005, seed);

  test_graph_properties();
  test_vertex_and_edge_properties();

  {
    std::cout << "Testing CSR graph built from unsorted edges" << std::endl;
    std::pair<int, int> unsorted_edges[] = {std::make_pair(5, 0), std::make_pair(3, 2), std::make_pair(4, 1), std::make_pair(4, 0), std::make_pair(0, 2), std::make_pair(5, 2)};
    CSRGraphT g(boost::edges_are_unsorted, unsorted_edges, unsorted_edges + sizeof(unsorted_edges) / sizeof(*unsorted_edges), 6);

    // Test vertex and edge bundle access
    boost::ignore_unused_variable_warning(
      (VertexData&)get(get(boost::vertex_bundle, g), vertex(0, g)));
    boost::ignore_unused_variable_warning(
      (const VertexData&)get(get(boost::vertex_bundle, (const CSRGraphT&)g), vertex(0, g)));
    boost::ignore_unused_variable_warning(
      (VertexData&)get(boost::vertex_bundle, g, vertex(0, g)));
    boost::ignore_unused_variable_warning(
      (const VertexData&)get(boost::vertex_bundle, (const CSRGraphT&)g, vertex(0, g)));
    put(boost::vertex_bundle, g, vertex(0, g), VertexData());
    boost::ignore_unused_variable_warning(
      (EdgeData&)get(get(boost::edge_bundle, g), *edges(g).first));
    boost::ignore_unused_variable_warning(
      (const EdgeData&)get(get(boost::edge_bundle, (const CSRGraphT&)g), *edges(g).first));
    boost::ignore_unused_variable_warning(
      (EdgeData&)get(boost::edge_bundle, g, *edges(g).first));
    boost::ignore_unused_variable_warning(
      (const EdgeData&)get(boost::edge_bundle, (const CSRGraphT&)g, *edges(g).first));
    put(boost::edge_bundle, g, *edges(g).first, EdgeData());

    CSRGraphT g2(boost::edges_are_unsorted_multi_pass, unsorted_edges, unsorted_edges + sizeof(unsorted_edges) / sizeof(*unsorted_edges), 6);
    graph_test(g);
    graph_test(g2);
    assert_graphs_equal(g, boost::identity_property_map(),
                        g2, boost::identity_property_map(),
                        boost::identity_property_map());
    std::cout << "Testing bidir CSR graph built from unsorted edges" << std::endl;
    BidirCSRGraphT g2b(boost::edges_are_unsorted_multi_pass, unsorted_edges, unsorted_edges + sizeof(unsorted_edges) / sizeof(*unsorted_edges), 6);
    graph_test(g2b);
    assert_graphs_equal(g, boost::identity_property_map(),
                        g2b, boost::identity_property_map(),
                        boost::identity_property_map());
    // Check in edge access
    typedef boost::graph_traits<BidirCSRGraphT>::in_edge_iterator in_edge_iterator;
    std::pair<in_edge_iterator, in_edge_iterator> ie(in_edges(vertex(0, g2b), g2b));
    // quiet unused variable warning
    ie.first = ie.second;

    std::cout << "Testing CSR graph built using add_edges" << std::endl;
    // Test building a graph using add_edges on unsorted lists
    CSRGraphT g3(boost::edges_are_unsorted, unsorted_edges, unsorted_edges, 6); // Empty range
    add_edges(unsorted_edges, unsorted_edges + 3, g3);
    EdgeData edge_data[3];
    add_edges(unsorted_edges + 3, unsorted_edges + 6, edge_data, edge_data + 3, g3);
    graph_test(g3);
    assert_graphs_equal(g, boost::identity_property_map(),
                        g3, boost::identity_property_map(),
                        boost::identity_property_map());
  }

  return 0;
}


text:
// (C) 2016 Marvin Sielenkemper

#include "db.hpp"

#include "Config.hpp"
#include "db/MySql.hpp"
#include "db/Statement.hpp"
#include "db/ResultSet.hpp"
#include "db/Bindings.hpp"

#include <boost/any.hpp>
#include <boost/range/iterator_range_core.hpp>
#include <boost/iterator/iterator_facade.hpp>
#include <boost/foreach.hpp>

#include <sstream>
#include <vector>

struct Db::Impl : boost::noncopyable {
  db::MySql mysql;
  db::Statement insert;
  db::Statement query;

  Impl(Config const& config)
      : mysql(config.dbConfig())
      , insert(mysql, "INSERT INTO serial_log(line) VALUES(?)")
      , query(mysql, "SELECT id, time, line FROM serial_log") {
  }
};

Db::Db(Config const& config) : m_implPtr(new Impl(config)) {
}

Db::~Db() {
}

void Db::addSerialLine(std::string const& line) {
  auto& insert(m_implPtr->insert);
  db::Bindings bindings(line);

  insert.execute(bindings);
}

void Db::getLines(
    std::function<void(int, int, std::string const&)> const&
        callback) {
  auto& query(m_implPtr->query);
  auto const resultSet(query.execute());

  BOOST_FOREACH (auto const& row, resultSet) {
    callback(row.get<int>("id"), row.get<int>("time"),
             row.get<std::string>("line"));
  }
}

max_stars_repo_name: sielenk/furnace

max_issues_repo_name: sielenk/furnace

max_forks_repo_name: sielenk/furnace


text:
//
// Created by Alex Beccaro on 18/01/18.
//

#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#include "../../src/problems/1-50/38/problem38.hpp"

BOOST_AUTO_TEST_SUITE( Problem38 )

    BOOST_AUTO_TEST_CASE( Solution ) {
        auto res = problems::problem38::solve();
        BOOST_CHECK_EQUAL(res, 932718654);
    }

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: abeccaro/project-euler

max_issues_repo_name: abeccaro/project-euler

max_forks_repo_name: abeccaro/project-euler


text:
#include <iostream>
#include <Eigen/Core>
#include <Eigen/Geometry>

using namespace std;

int main(int argc, char** argv)
{
    // 机器人B在坐标系O中的坐标：
    Eigen::Vector3d B(3, 4, M_PI);

    // 坐标系B到坐标O的转换矩阵：
    Eigen::Matrix3d TOB;
    TOB << cos(B(2)), -sin(B(2)), B(0),
           sin(B(2)),  cos(B(2)), B(1),
              0,          0,        1;

    // 坐标系O到坐标B的转换矩阵:
    Eigen::Matrix3d TBO = TOB.inverse();

    // 机器人A在坐标系O中的坐标：
    Eigen::Vector3d A(1, 3, -M_PI / 2);

    // 求机器人A在机器人B中的坐标：
    Eigen::Vector3d BA;
    // TODO 参照第一课PPT
    // start your code here (5~10 lines)
    Eigen::Matrix3d TOA;

    // end your code here

    cout << "The right answer is BA: 2 1 1.5708" << endl;
    cout << "Your answer is BA: " << BA.transpose() << endl;

    return 0;
}


text:
#include "io.h"

#include <Eigen/Geometry>

#define STBI_FAILURE_USERMSG
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>

using namespace std;
using namespace gr;

////////////////////////////////////////////////////////////////////////////////
/// Write
////////////////////////////////////////////////////////////////////////////////

bool IOManager::WriteMatrix(
        const string &name,
        const Eigen::Ref<const Eigen::Matrix<double, 4, 4> >& mat,
        IOManager::MATRIX_MODE mode)
{
    std::ofstream sstr;
    sstr.open(name, std::ofstream::out | std::ofstream::trunc);

    bool status = false;

    switch (mode) {
    case POLYWORKS:
        formatPolyworksMatrix(mat, sstr);
        status = true;
        break;
    default:
        break;
    }

    sstr.close();

    return status;
}

std::ofstream &
IOManager::formatPolyworksMatrix(
        const Eigen::Ref<const Eigen::Matrix<double, 4, 4> > &mat,
        std::ofstream &sstr) {

    auto formatValue = [](const double& v){
        return (v >= 0.
                ? std::string(" ") + std::to_string(v)
                : std::to_string(v));
    };

    sstr << "VERSION\t=\t1\n";
    sstr << "MATRIX\t=\n";
    for (int j = 0; j!= 4; ++j){
        sstr << formatValue(mat(j, 0)) << "  "
             << formatValue(mat(j, 1)) << "  "
             << formatValue(mat(j, 2)) << "  "
             << formatValue(mat(j, 3)) << "\n";
    }

    return sstr;
}

////////////////////////////////////////////////////////////////////////////////
/// Wrapped STBI functions to be used inside template methods
/// Limits dependency on stb just to compilation of the library
////////////////////////////////////////////////////////////////////////////////
unsigned char*
IOManager::stbi_load_(char const *filename, int *x, int *y, int *comp, int req_comp)
{
    return stbi_load(filename, x, y, comp, req_comp);
}

void
IOManager::stbi_image_free_(void *retval_from_stbi_load)
{
    return stbi_image_free(retval_from_stbi_load);
}

const char *
IOManager::stbi_failure_reason_(void)
{
    return stbi_failure_reason();
}

max_stars_repo_name: sgiraudot/OpenGR

max_issues_repo_name: sgiraudot/OpenGR

max_forks_repo_name: sgiraudot/OpenGR