text:
/*
 *  compile:

 g++-5 -std=c++11 -O2 -o multi-thread-regex-numa.bin multi-thread-regex-numa-6t.cpp -lpthread \
 -lre2 -lboost_date_time -lpcre -lnuma

 */

/*
 * This is used to test NUMA-aware threads
 * 1.k2 configuration:
 *	node 0 cpus: 0 2 4 6 8 10 12 14 16 18 20 22
 *      node 1 cpus: 1 3 5 7 9 11 13 15 17 19 21 23
 * In this code, we only allocate memory from Node 0
 *
 * 2.Have to define one of there types:
 * 	-- LOCAL_ONLY:  use core 0, 2, 4...
 *      -- REMOTE_ONLY: use core 1, 3, 5...
 *	-- LOCAL_REMOTE: use core 0, 1, 2, 3...
 *
 * 3.Here the NUM_THREADS has to be : 2, 4, 6, 8, 10, or 12.
 */

/*
 * this is used to test the scalability of regular expression libraries
 * Before running:
 * 1. modify input file name
 * 2. set NUM_THREADS, which is the max # of threads you want to use.
 */

/*
 * ref: https://www.tutorialspoint.com/cplusplus/cpp_multithreading.htm
 */

/*
 * 1. For std::regex, using -O2 can achive 10X faster performance than using -O0
 * 2. Both std::regex and re2:regex can scall well in multi-thread, but re2::regex is much faster than std::regex
 * 3. If we using 96 cores, the re2 throughput can reach around 20GB/s.
 * 4. Performance numbers:
 *	Uing 1 core
 *		-- re2: 0.59 GB/s
 *		-- std::regex: 0.003 GB/s (using -O0)
 *		-- std::regex: 0.03 GB/s (using -O2)
 *	Using 5 cores
 *		-- re2: 2.2 GB/s
 *		-- std::regex: 0.014 GB/s (using -O0)
 *		-- std::regex: 0.14 GB/s (using -O2)
 *	Using 10 cores
 *		-- re2: 3.5 GB/s
 *		-- std::regex: 0.028 GB/s (using -O0)
 *		-- std::regex: 0.28 GB/s (using -O2)
 */

#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h>
#include <fstream>
//#include <boost/regex.hpp>
#include <re2/re2.h>
#include "boost/date_time/posix_time/posix_time.hpp"
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <ctype.h>
#include <string>
#include <regex>
//#include <boost/regex.hpp>
#include <pcre.h>
#include <numa.h>
#include <thread>
#include <atomic>

using namespace std;
using namespace boost::posix_time;

#define NUM_THREADS     12

//#define REMOTE 1 //using core: 0,1,2,3,4,5,6,7,8,9,10,11
		 // else useing core: 0,2,4,6,8,10.12,14,16,18,20,22
/*
#ifdef REMOTE
static atomic<int> thread_num (-1);
#else
static atomic<int> thread_num (-2);
#endif
*/

//XXX Have to chose one of them
//#define LOCAL_ONLY
//#define REMOTE_ONLY
#define LOCAL_REMOTE

#ifdef LOCAL_ONLY // 0, 2, 4 ...
	static atomic<int> thread_num (-2);
#endif

#ifdef REMOTE_ONLY //1,3,5...
	static atomic<int> thread_num (-1);
#endif

#ifdef LOCAL_REMOTE // 0,1,2,3..
	static atomic<int> thread_num (-1);
#endif

int size = 0;

void *wait_on_core(void *t)
{
	int i, s;
	long tid;

	cpu_set_t cpuset;
	pthread_t thread;

	thread = pthread_self();
	CPU_ZERO(&cpuset);
	//core 0, 2, 4, 8... 22 are on node 0
	//thread_num ++;
#ifdef REMOTE
	thread_num.fetch_add(1);
#else
	thread_num.fetch_add(2);
#endif

	CPU_SET(thread_num, &cpuset);
	s = pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset);
	if(s != 0){
		std::cout << "setaffinity faile!!!" << std::endl;
		exit(0);
	}

	sleep(3);
	std::thread::id this_id = std::this_thread::get_id();
	std::cout << "On core: " << sched_getcpu() << std::endl;

	pthread_exit(NULL);
}

void bind_to_core(){
	cpu_set_t cpuset;
	pthread_t thread;

	thread = pthread_self();
	CPU_ZERO(&cpuset);

#ifdef LOCAL_ONLY
	thread_num.fetch_add(2);
#endif

#ifdef REMOTE_ONLY
	thread_num.fetch_add(2);
#endif

#ifdef LOCAL_REMOTE
	thread_num.fetch_add(1);
#endif

	CPU_SET(thread_num, &cpuset);
	int s = pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset);
	if(s != 0){
		std::cout << "setaffinity faile!!!" << std::endl;
		exit(0);
	}
//	std::cout << "On core: " << sched_getcpu() << std::endl;
//	std::cout << sched_getcpu() << std::endl;
}

void *wait(void *t)
{
	int i;
	long tid;

	tid = (long)t;

	sleep(1);
	cout << "Sleeping in thread " << endl;
	cout << "Thread with id : " << tid << "  ...exiting " << endl;
	pthread_exit(NULL);
}

void * pcre_regex(void * t){

	bind_to_core();

	pcre *reCompiled;
	pcre_extra *pcreExtra;
	int pcreExecRet;
	int subStrVec[30];
	const char *pcreErrorStr;
	int pcreErrorOffset;
	char *aStrRegex;
	const char *psubStrMatchStr;
	int j;
	int count = 0;
	char * testStrings = (char *)t;

	//aStrRegex = "\\d\\d\\d\\d";
	aStrRegex = (char *)"\\d\\d\\d\\d";
	//std::cout << "Regex to use: " << aStrRegex << std::endl;

	// First, the regex string must be compiled.
	reCompiled = pcre_compile(aStrRegex, 0, &pcreErrorStr, &pcreErrorOffset, NULL);

	// pcre_compile returns NULL on error, and sets pcreErrorOffset & pcreErrorStr
	if(reCompiled == NULL) {
		std::cout << "ERROR: Could not compile " << aStrRegex << " " << pcreErrorStr << std::endl;
		exit(1);
	}

	// Optimize the regex
	pcreExtra = pcre_study(reCompiled, 0, &pcreErrorStr);

	/* pcre_study() returns NULL for both errors and when it can not optimize the regex.  The last argument is how one checks for
	   errors (it is NULL if everything works, and points to an error string otherwise. */
	if(pcreErrorStr != NULL) {
		std::cout << "ERROR: Could not study " << aStrRegex << " " << pcreErrorStr << std::endl;
		exit(1);
	}

	int subject_length = strlen(testStrings);
	int start_offset = 0;

	/* find all matched substring*/
	while (1) {
		//std::cout << "string " << testStrings << std::endl;

		pcreExecRet = pcre_exec(reCompiled,
				pcreExtra,
				testStrings,
				subject_length,
				start_offset,                      // Start looking at this point
				0,                      // OPTIONS
				subStrVec,              //subStrVec[0] is the position of the first matched substring
				30);                    // Length of subStrVec
		//std::cout << "pcreExecRet is:" << pcreExecRet << std::endl;

		/* no matched string*/
		if(pcreExecRet < 0) {
			//std::cout << "NO match" << std::endl;
			//return 0;
			goto out;
		} else {
			//printf("Result: We have a match!\n");
			//std::cout << "Result: We have a match!" << std::endl;
			count += pcreExecRet;
//			printf("submatches %d. len %d \n", pcreExecRet, subStrVec[1] -subStrVec[0]);

#if 1
			// PCRE contains a handy function to do the above for you:
			for(int i=0; i<pcreExecRet; i++) {
/*
				char *substring_start = testStrings + subStrVec[2*i];
				int substring_length = subStrVec[2*i+1] - subStrVec[2*i];
*/

//				printf("%2d: %.*s\n", i, substring_length, substring_start);

				//pcre_get_substring(testStrings, subStrVec, pcreExecRet, i, &(psubStrMatchStr));
				//std::cout << "matched string: " << psubStrMatchStr << std::endl;
			}
#endif

			//subStrVec[0] is the position of matched substring
//			std::cout << "subStrVec: " << (testStrings + subStrVec[0]) << std::endl;

//			testStrings += subStrVec[0];
			start_offset = subStrVec[1];
//			testStrings += strlen(psubStrMatchStr);

			// Free up the substring
//			pcre_free_substring(psubStrMatchStr);
		}
		//std::cout << std::endl;
	}
out:
	//printf("done. count =%d\n", count);

	// Free up the regular expression.
	pcre_free(reCompiled);

	// Free up the EXTRA PCRE value (may be NULL at this point)
	if(pcreExtra != NULL) {
#ifdef PCRE_CONFIG_JIT
		pcre_free_study(pcreExtra);
#else
		pcre_free(pcreExtra);
#endif
	}
        //std::cout << "cout is " << count << std::endl;
	pthread_exit(NULL);
}

void * re2_regex(void * t){
	char *buff = (char *)t;
	std::string matched;
	RE2 re("(\\d\\d\\d\\d)");
	//RE2 re("(((http[s]{0,1}|ftp)://)[a-zA-Z0-9\\.\\-]+\\.([a-z]|[A-Z]|[0-9]|[/.]|[~]|[-])*)");
	int count = 0;
	re2::StringPiece input(buff);
	while(RE2::FindAndConsume(&input, re, &matched)) {
		count ++;
	}
	//std::cout << "one re2_regex thread finished, count is" << count << std::endl;
	pthread_exit(NULL);
}

void * std_regex(void * t){
	char * buff = (char *)t;
	std::string str(buff);
	std::regex ex("(\\d\\d\\d\\d)");
	std::smatch res;
	int count = 0;
	std::string::const_iterator searchStart(str.cbegin());
	while( std::regex_search(searchStart, str.cend(), res, ex)){
		count ++;
		searchStart += res.position() + res.length();
	}
	//std::cout << "one std_regex thread finished, count is" << count << std::endl;
	pthread_exit(NULL);
}

void * std_regex_2(void * t){
	char * buff = (char *)t;
	std::string str(buff);
	std::regex ex("(\\d\\d\\d\\d)");

	std::sregex_iterator it(str.begin(), str.end(), ex);
	std::sregex_iterator reg_end;
	int count = 0;
	for (; it != reg_end; ++it) {
		count ++;
	}
	std::cout << "one std_regex thread finished, count is" << count << std::endl;
	pthread_exit(NULL);
}

/*
void * str_str(void *t){
	bind_to_core();
	char *buff = (char *)t;
	char p;
	int cnt = 0;
	for(int i = 0; i < size; i++){
		buff[i] = 'a';
		cnt ++;
	}

	//std::cout << "count is " << cnt << std::endl;
	pthread_exit(NULL);
}
*/

/*
void * str_str(void * t){
	const char *buff = (char *)t;
	const char *target = "very";
	const char *result = buff;
	int count = 0;
	while((result = std::strstr(result, target)) != NULL){
		++result;
		count ++;
	}
	//std::cout << "count is " << count << std::endl;
	pthread_exit(NULL);
}
*/

void * str_str(void * t){
	bind_to_core();
	char * buff = (char *)t;
	//std::cout << "buffer size" <<  strlen(buff) << std::endl;
	char * p = strstr(buff, "very");
	volatile int count = 0;

	while(p != NULL){
		//p = p + 4;
		p++;
		count ++;
		p = strstr(p, "very");
	}

	//std::cout << "one str_str thread finished, count is" << count << std::endl;
	pthread_exit(NULL);
}

int main ()
{
	int rc;
	int i,j,k;
	//pthread_t threads[NUM_THREADS];
	pthread_t threads[100];
	//char *buff[100];
	//char *buff;
	//int size;
	pthread_attr_t attr;
	void *status;

//	int fd = open("/tmp/large1.txt", O_RDONLY); //100MB
//	int fd = open("/shared/stream_data_set/movies.txt", O_RDONLY);
//	int fd = open("/tmp/1g.txt.part00", O_RDONLY);
//	int fd = open("/tmp/movies.txt.part00.part00.part00.part00.part00.part00", O_RDONLY);

//	int fd = open("/tmp/1gb-2.txt", O_RDONLY);
//	int fd = open("/tmp/10mb.txt", O_RDONLY);
//	int fd = open("/ssd/word_10MB.txt", O_RDONLY);
		int fd = open("/ssd/1g.txt", O_RDONLY);
//	int fd = open("/home/xzl/tmp/word_10MB.txt", O_RDONLY);

	struct stat finfo;
	if(fd < 0)
		std::cout << "open fail!" << std::endl;
	fstat(fd, &finfo);
	//char *buff = (char *) malloc(finfo.st_size);

	char *buff = (char *) numa_alloc_onnode(finfo.st_size, 0); //only allocate memory from node 0
	size = pread(fd, buff, finfo.st_size, 0);
	std::cout << "Input size: "<< size/1024/1024 << "MB" << std::endl;

	// Initialize and set thread joinable
	pthread_attr_init(&attr);
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

	for(int j = 2; j <= NUM_THREADS; j = j + 2) {
#ifdef LOCAL_ONLY
		std::cout << "using LOCAL_ONLY cores: ";
		for(int m = 0; m < j; m++){
			std::cout << 2 * m << " ";
		}
		std::cout << std::endl;
#endif

#ifdef REMOTE_ONLY
		std::cout << "using REMOTE_ONLY cores: ";
		for(int m = 0; m < j; m++){
			std::cout << 2*m +1 << " ";
		}
		std::cout << std::endl;
#endif

#ifdef LOCAL_REMOTE
		std::cout << "using LOCAL_REMOTE cores: ";
		for(int m = 0; m < j; m++){
			std::cout << m << " ";
		}
		std::cout << std::endl;
#endif
/*
		for(i = 0; i < j; i++){
			buff[i] = (char *) numa_alloc_onnode(finfo.st_size, 0); //only allocate memory from node 0
			size = pread(fd, buff[i], finfo.st_size, 0);
		}
		std::cout << "Input size: "<< size/1024/1024 << "MB" << std::endl;
*/
		j = 6;
		//for(k = 0; k < 20; k++){
		while(1){
#ifdef LOCAL_ONLY //0,2,4,6,
			thread_num.store(-2);
#endif

#ifdef REMOTE_ONLY //1,3,5
			thread_num.store(-1);
#endif

#ifdef LOCAL_REMOTE //0,1,2,3
			thread_num.store(-1);
#endif
			ptime begin = boost::posix_time::microsec_clock::local_time();
			//std::cout << "begin is: " << to_simple_string(begin) << std::endl;
			//for( i=0; i < NUM_THREADS; i++ ){
			for(i = 0; i < j; i++){
				//cout << "main() : creating thread, " << i << endl;
				//rc = pthread_create(&threads[i], &attr, wait, (void *)buff );
				//rc = pthread_create(&threads[i], &attr, re2_regex, (void *)buff );
				//rc = pthread_create(&threads[i], &attr, std_regex, (void *)buff );
				rc = pthread_create(&threads[i], &attr, str_str, (void *)buff);
				//rc = pthread_create(&threads[i], &attr, std_regex_2, (void *)buff );
				//rc = pthread_create(&threads[i], &attr, pcre_regex, (void *)buff[i] );
				if (rc){
					cout << "Error:unable to create thread," << rc << endl;
					exit(-1);
				}
			}

			// free attribute and wait for the other threads
			pthread_attr_destroy(&attr);
			for(i = 0; i < j; i++){
				//for( i=0; i < NUM_THREADS; i++ ){
				rc = pthread_join(threads[i], &status);
				if (rc){
					cout << "Error:unable to join," << rc << endl;
					exit(-1);
				}
				//cout << "Main: completed thread id :" << i ;
				//cout << "  exiting with status :" << status << endl;
			}

			//end time
			ptime end  = boost::posix_time::microsec_clock::local_time();
			//std::cout << "end is: " << to_simple_string(end) << std::endl;
			boost::posix_time::time_duration diff = end - begin;
		/*	double interval_sec = (double) diff.total_milliseconds() / 1000;
			std::cout << "interval_sec = " << interval_sec << std::endl;
			//std::cout << "Throughput is: " << NUM_THREADS * (size / interval_sec / (1024*1024*1024))<< "GB/s" << std::endl;
			std::cout << "Bandwidth is: " << j * (size / interval_sec / (1024*1024*1024))<< "GB/s" << std::endl;
		*/
			//double interval_msec = (double) diff.total_milliseconds();
			double interval_microsec = (double) diff.total_microseconds();
			//std::cout << "interval_microsec: " << interval_microsec << std::endl;
			//std::cout << "Throughput is: " << (j * (size / interval_microsec / (1024*1024*1024))) / (1000 * 1000) << "GB/s" << std::endl;
			//std::cout << "size is: " << size << "; interval_microsec is: " << interval_microsec << std::endl;
			std::cout << "Throughput is: " << j * (size/interval_microsec) * (1000*1000) / (1024*1024*1024) << "GB/s" << std::endl;

		}//end of for(k)
		std::cout << "--------" << std::endl;

/*
		for(i = 0; i < j; i++){
			if(buff[i]){
				numa_free(buff[i], size);
			}
		}
*/
	}//for(j)

	cout << "Main: program exiting." << endl;

	if(buff){
		numa_free(buff, finfo.st_size);
	}

	pthread_exit(NULL);
}

max_stars_repo_name: chenzongxiong/streambox

max_issues_repo_name: chenzongxiong/streambox

max_forks_repo_name: chenzongxiong/streambox


text:
/*
@copyright Louis Dionne 2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
 */

#include <boost/hana/assert.hpp>
#include <boost/hana/config.hpp>

//! [main]
#include <boost/hana/set.hpp>
using namespace boost::hana;

int main() {
    BOOST_HANA_CONSTEXPR_LAMBDA auto xs = set(1, 2.2, 'x');
    BOOST_HANA_CONSTEXPR_CHECK(elem(xs, 'x'));
}
//! [main]

ext: cpp

max_stars_repo_name: josephwinston/hana

max_issues_repo_name: josephwinston/hana

max_forks_repo_name: josephwinston/hana


text:
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/// @project        Open Space Toolkit ▸ Physics
/// @file           OpenSpaceToolkit/Physics/Time/Interval.cpp
/// @author         Lucas Brémond <lucas@loftorbital.com>
/// @license        Apache License 2.0

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

#include <OpenSpaceToolkit/Physics/Time/Interval.hpp>

#include <OpenSpaceToolkit/Core/Error.hpp>
#include <OpenSpaceToolkit/Core/Utilities.hpp>

#include <boost/regex.hpp>

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

namespace ostk
{
namespace physics
{
namespace time
{

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

                                Interval::Interval                          (   const   Instant&                    aLowerBound,
                                                                                const   Instant&                    anUpperBound,
                                                                                const   Interval::Type&             anIntervalType                              )
                                :   math::obj::Interval<Instant>(aLowerBound, anUpperBound, anIntervalType)
{

}

std::ostream&                   operator <<                                 (           std::ostream&               anOutputStream,
                                                                                const   Interval&                   anInterval                                  )
{

    ostk::core::utils::Print::Header(anOutputStream, "Interval") ;

    ostk::core::utils::Print::Line(anOutputStream) << "Start:" << (anInterval.isDefined() ? anInterval.accessStart().toString(Scale::UTC) : "Undefined") ;
    ostk::core::utils::Print::Line(anOutputStream) << "End:" << (anInterval.isDefined() ? anInterval.accessEnd().toString(Scale::UTC) : "Undefined") ;

    ostk::core::utils::Print::Footer(anOutputStream) ;

    return anOutputStream ;

}

bool                            Interval::isDefined                         ( ) const
{
    return math::obj::Interval<Instant>::isDefined() && (this->getType() != Interval::Type::Undefined) ;
}

const Instant&                  Interval::accessStart                       ( ) const
{

    if (!this->isDefined())
    {
        throw ostk::core::error::runtime::Undefined("Interval") ;
    }

    return this->accessLowerBound() ;

}

const Instant&                  Interval::accessEnd                         ( ) const
{

    if (!this->isDefined())
    {
        throw ostk::core::error::runtime::Undefined("Interval") ;
    }

    return this->accessUpperBound() ;

}

Instant                         Interval::getStart                          ( ) const
{

    if (!this->isDefined())
    {
        throw ostk::core::error::runtime::Undefined("Interval") ;
    }

    return this->accessLowerBound() ;

}

Instant                         Interval::getEnd                            ( ) const
{

    if (!this->isDefined())
    {
        throw ostk::core::error::runtime::Undefined("Interval") ;
    }

    return this->accessUpperBound() ;

}

Duration                        Interval::getDuration                       ( ) const
{

    if (!this->isDefined())
    {
        throw ostk::core::error::runtime::Undefined("Interval") ;
    }

    return Duration::Between(this->accessLowerBound(), this->accessUpperBound()) ;

}

Instant                         Interval::getCenter                         ( ) const
{

    if (!this->isDefined())
    {
        throw ostk::core::error::runtime::Undefined("Interval") ;
    }

    return this->accessLowerBound() + this->getDuration() / 2.0 ;

}

String                          Interval::toString                         (   const   Scale&                      aTimeScale                                  ) const
{

    using ostk::physics::time::DateTime ;

    if (!this->isDefined())
    {
        throw ostk::core::error::runtime::Undefined("Interval") ;
    }

    switch (this->getType())
    {

        case Interval::Type::Closed:
            return String::Format("[{0} - {1}] [{2}]", this->accessLowerBound().getDateTime(aTimeScale).toString(DateTime::Format::Standard), this->accessUpperBound().getDateTime(aTimeScale).toString(DateTime::Format::Standard), StringFromScale(aTimeScale)) ;

        case Interval::Type::Open:
            return String::Format("]{0} - {1}[ [{2}]", this->accessLowerBound().getDateTime(aTimeScale).toString(DateTime::Format::Standard), this->accessUpperBound().getDateTime(aTimeScale).toString(DateTime::Format::Standard), StringFromScale(aTimeScale)) ;

        case Interval::Type::HalfOpenLeft:
            return String::Format("]{0} - {1}] [{2}]", this->accessLowerBound().getDateTime(aTimeScale).toString(DateTime::Format::Standard), this->accessUpperBound().getDateTime(aTimeScale).toString(DateTime::Format::Standard), StringFromScale(aTimeScale)) ;

        case Interval::Type::HalfOpenRight:
            return String::Format("[{0} - {1}[ [{2}]", this->accessLowerBound().getDateTime(aTimeScale).toString(DateTime::Format::Standard), this->accessUpperBound().getDateTime(aTimeScale).toString(DateTime::Format::Standard), StringFromScale(aTimeScale)) ;

        default:
            break ;

    }

    throw ostk::core::error::runtime::Wrong("Interval type") ;

    return String::Empty() ;

}

Array<Instant>                  Interval::generateGrid                      (   const   Duration&                   aTimeStep                                   ) const
{

    return this->generateArrayWithStep(aTimeStep) ;

    // using ostk::core::types::Index ;
    // using ostk::core::types::Size ;

    // if (!this->isDefined())
    // {
    //     throw ostk::core::error::runtime::Undefined("Interval") ;
    // }

    // if (!aTimeStep.isDefined())
    // {
    //     throw ostk::core::error::runtime::Undefined("Time step") ;
    // }

    // if (aTimeStep.isZero())
    // {
    //     throw ostk::core::error::RuntimeError("Time step is zero.") ;
    // }

    // Array<Instant> grid = Array<Instant>::Empty() ;

    // if (aTimeStep.isPositive())
    // {

    //     Instant instant = this->accessLowerBound() ;

    //     while (instant <= this->accessUpperBound())
    //     {

    //         grid.add(instant) ;

    //         instant += aTimeStep ;

    //     }

    //     if (grid.accessLast() < this->accessUpperBound())
    //     {
    //         grid.add(this->accessUpperBound()) ;
    //     }

    // }
    // else
    // {

    //     Instant instant = this->accessUpperBound() ;

    //     while (instant >= this->accessLowerBound())
    //     {

    //         grid.add(instant) ;

    //         instant += aTimeStep ;

    //     }

    //     if (grid.accessLast() > this->accessLowerBound())
    //     {
    //         grid.add(this->accessLowerBound()) ;
    //     }

    // }

    // return grid ;

}

Interval                        Interval::Undefined                         ( )
{
    return Interval(Instant::Undefined(), Instant::Undefined(), Interval::Type::Undefined) ;
}

Interval                        Interval::Closed                            (   const   Instant&                    aLowerBound,
                                                                                const   Instant&                    anUpperBound                                )
{

    if (!aLowerBound.isDefined())
    {
        throw ostk::core::error::runtime::Undefined("Lower bound") ;
    }

    if (!anUpperBound.isDefined())
    {
        throw ostk::core::error::runtime::Undefined("Upper bound") ;
    }

    return Interval(aLowerBound, anUpperBound, Interval::Type::Closed) ;

}

Interval                        Interval::Centered                          (   const   Instant&                    aCentralInstant,
                                                                                const   Duration&                   aDuration,
                                                                                const   Interval::Type&             anIntervalType                              )
{

    if (!aCentralInstant.isDefined())
    {
        throw ostk::core::error::runtime::Undefined("Central instant") ;
    }

    if (!aDuration.isDefined())
    {
        throw ostk::core::error::runtime::Undefined("Duration") ;
    }

    if (!aDuration.isPositive())
    {
        throw ostk::core::error::RuntimeError("Duration is negative.") ;
    }

    if (anIntervalType == Interval::Type::Undefined)
    {
        throw ostk::core::error::runtime::Undefined("Interval type") ;
    }

    return Interval((aCentralInstant - aDuration / 2.0), (aCentralInstant + aDuration / 2.0), anIntervalType) ;

}

Interval                        Interval::Parse                             (   const   String&                     aString                                     )
{

    using ostk::physics::time::DateTime ;

    if (aString.isEmpty())
    {
        throw ostk::core::error::runtime::Undefined("String") ;
    }

    boost::smatch match ;

    if (boost::regex_match(aString, match, boost::regex("^([\\[\\]])([\\d]{4}-[\\d]{2}-[\\d]{2} [\\d]{2}:[\\d]{2}:[\\d]{2}) - ([\\d]{4}-[\\d]{2}-[\\d]{2} [\\d]{2}:[\\d]{2}:[\\d]{2})([\\[\\]]) \\[([\\w]+)\\]$")))
    {

        const String openingBracket = String(match[1]) ;
        const String startInstantString = String(match[2]) ;
        const String endInstantString = String(match[3]) ;
        const String closingBracket = String(match[4]) ;
        const String timeScaleString = String(match[5]) ;

        const Scale timeScale = ScaleFromString(timeScaleString) ;

        const Instant startInstant = Instant::DateTime(DateTime::Parse(startInstantString, DateTime::Format::Standard), timeScale) ;
        const Instant endInstant = Instant::DateTime(DateTime::Parse(endInstantString, DateTime::Format::Standard), timeScale) ;

        Interval::Type type = Interval::Type::Undefined ;

        if ((openingBracket == "[") && (closingBracket == "]"))
        {
            type = Interval::Type::Closed ;
        }
        else if ((openingBracket == "]") && (closingBracket == "["))
        {
            type = Interval::Type::Open ;
        }
        else if ((openingBracket == "]") && (closingBracket == "]"))
        {
            type = Interval::Type::HalfOpenLeft ;
        }
        else if ((openingBracket == "[") && (closingBracket == "["))
        {
            type = Interval::Type::HalfOpenRight ;
        }
        else
        {
            throw ostk::core::error::runtime::Wrong("Brackets") ;
        }

        return Interval(startInstant, endInstant, type) ;

    }
    else
    {
        throw ostk::core::error::RuntimeError("Cannot parse interval string [{}].", aString) ;
    }

    return Interval::Undefined() ;

}

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

}
}
}

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

max_stars_repo_name: robinpdm/open-space-toolkit-physics

max_issues_repo_name: robinpdm/open-space-toolkit-physics

max_forks_repo_name: robinpdm/open-space-toolkit-physics


text:
/*
 * File:   JsonList.h
 * Author: Joshua Johannson
 *
 */
#include "ApiJsonObject.h"
#include "JsonList.h"
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;

template<class T>
JsonList<T>::JsonList(): JsonList(defaultIdAutoIncrement)
{}
template<class T>
JsonList<T>::JsonList(int &idAutoIncrement)
    : ApiJsonObject(),
      idAutoIncrement(idAutoIncrement)
{
  setLogName("JsonList");
}
template<class T>
ApiRespond* JsonList<T>::processApi(ApiRequest request)
{
  ApiRespond *respond = nullptr;

  // action to one entity
  bool destEntity = !request.route.isEmpty();

  // entity id
  string entityIdString = request.route.pop();
  int entityId = -1;

  //info("at " + component + "/" + entityIdString);

  // if for list item
  if (destEntity)
  {
    // to int
    try
    {
      entityId = stoi(entityIdString);
    } catch (invalid_argument e)
    {
      err("entity's id is not a number", e.what());
      destEntity = false;
      return new ApiRespondError("entity's id is not a number '" +string(e.what())+"'", request);
    }
  }
  else // for me
  {
    // processed by ApiJsonObject part
    respond = ApiJsonObject::processApi(request);
    if (respond != nullptr)
      return respond;
  }

  // call process api of subRoute
  function<ApiRespond*()> callProcessApiOfItem = [&](){
    auto el = items.find(entityId);
    if (el == items.end())
      return (ApiRespond*) new ApiRespondError("entity '" + entityIdString + "'  not found", request, route.get_value_or(ApiMessageRoute()));

    ApiProcessible *processible = dynamic_cast<ApiProcessible*>(el->second);
    if (!processible)
      return (ApiRespond*) new ApiRespondError("entity '" + entityIdString + "' cant process any api command because"
                                                   + ((is_fundamental<T>::value) ? "it is a primitive type " : "") + "(Type: "+ typeid(T).name()+")", request);

    return processible->processApi(request);
  };

  // test constexpr
  //if constexpr (is_fundamental<T>::value) {
  //  info("progressApi of fundamental T type: " + string(typeid(T).name()));
  //}

  // we ar not target if there are still route parts left
  if (!request.route.isEmpty()) {
    return callProcessApiOfItem();
  }

  if (!destEntity)
  {
    /*
     * Destination: whole list
     */
    // getAll
    if (request.what == "getAll")
    {
      Json res{};
      for (auto el : items)
        res.push_back(el.second->toJson());

      return new ApiRespondOk(res, request);
    }

    // add
    if (request.what == "add")
    {
      info("at "+route.get_value_or(ApiMessageRoute()).toString()+" add " + to_string(idAutoIncrement));

      Json j = request.data;
      j.update(Json{{"id", idAutoIncrement}}); // insert id key into data json
      T* n = createItemFunc(j);
      if (n != nullptr)
      {
        n->fromJson(j, true /*catch param assignment errors*/);
        items.insert({idAutoIncrement, n});
        if (route.is_initialized() && is_base_of<ApiJsonObject, T>::value)
        {
          ApiMessageRoute nRoute = this->route.get_value_or(ApiMessageRoute());
          nRoute.push(to_string(idAutoIncrement)); // set entity id in its route
          n->setRoute(nRoute);
          n->store();
        }

        // subscriber update
        ApiMessageRoute removedRoute = route.is_initialized() ? route.get() : ApiMessageRoute("");
        removedRoute.push(to_string(idAutoIncrement));
        sendToSubscribers(ApiRequest(removedRoute, "add", n->toJson()),
                          *request.client);

        idAutoIncrement++;
        return new ApiRespondOk(n->toJson(), request);
      }
      else
        return new ApiRespondError("can’t create item by given data", request, route.get_value_or(ApiMessageRoute()));
    }
  }

  if (destEntity)
  {
    /*
     * Destination: single entity
     */
    auto item = items.find(entityId);
    if (item == items.end())
    {
      return new ApiRespondError("entity '" + entityIdString + "' not found", request, route.get_value_or(ApiMessageRoute()));
    }

    // get item
    if (request.what == "get")
    {
      return new ApiRespondOk((*item).second->toJson(), request);
    }

    // remove item
    if (request.what == "remove")
    {
      if (route.is_initialized())
      {
        info("at " + route.get().toString() + " remove " + to_string(item->first));
        item->second->remove();
        boost::filesystem::remove_all(route.get().toStringStorePath() + entityIdString);
        info("removed item " + route.get().toStringStorePath());
        items.erase(item);
        delete item->second;

        // subscriber update
        ApiMessageRoute removedRoute = route.is_initialized() ? route.get() : ApiMessageRoute("");
        removedRoute.push(entityIdString);
        sendToSubscribers(ApiRequest(removedRoute, "remove"),
                          *request.client);

        return new ApiRespondOk(request);
      }
    }
  }

  // the what commands goal is item
  if (destEntity)
    return callProcessApiOfItem();
  return respond; // is nullptr
}

template<class T>
T &JsonList<T>::get(int id)
{
  return *(*items.find(id)).second;
}

template<class T>
void JsonList<T>::set(int id, T element)
{
  T *n = new T(element);
  n->fromJson(Json{{"id", id}});
  items.insert({id, n});
  if (route.is_initialized() && is_base_of<ApiJsonObject, T>::value)
  {
    ApiMessageRoute nRoute = this->route.get_value_or(ApiMessageRoute());
    nRoute.push(to_string(idAutoIncrement)); // set entity id in its route
    n->setRoute(nRoute);
    n->store();
  }
  idAutoIncrement++;
}

template<class T>
void JsonList<T>::add(T element)
{
  T *n = new T(element);
  n->fromJson(Json{{"id", idAutoIncrement}});
  items.insert({idAutoIncrement, n});
  if (route.is_initialized() && is_base_of<ApiJsonObject, T>::value)
  {
    ApiMessageRoute nRoute = this->route.get_value_or(ApiMessageRoute());
    nRoute.push(to_string(idAutoIncrement)); // set entity id in its route
    n->setRoute(nRoute);
    n->store();
  }

  // subscriber update
  ApiMessageRoute removedRoute = route.is_initialized() ? route.get() : ApiMessageRoute("");
  removedRoute.push(to_string(idAutoIncrement));
  sendToSubscribers(ApiRequest(removedRoute, "add", n->toJson()));

  idAutoIncrement++;
}

template<class T>
bool JsonList<T>::remove(int id)
{
  auto it = items.find(id);
  if (it != items.end()) {
    items.erase(it);

    // subscriber update
    ApiMessageRoute removedRoute = route.is_initialized() ? route.get() : ApiMessageRoute("");
    removedRoute.push(to_string(id));
    sendToSubscribers(ApiRequest(removedRoute, "remove"));

    return true;
  }
  return false;
}

template<class T>
int JsonList<T>::length()
{
  return items.size();
}

template<class T>
void JsonList<T>::setCreateItemFunction(function<T *(Json params)> createItemFunc)
{
  this->createItemFunc = createItemFunc;
}

template<class T>
void JsonList<T>::restore()
{
  ApiProcessible::restore();
  if (!route.is_initialized())
    return;

  // foreach dir
  try
  {
    fs::directory_iterator directory_iterator(fs::path(this->route.get().toStringStorePath()));
    while (directory_iterator != fs::directory_iterator{})
    {
      /*
       * get id by directory name */
      string id = directory_iterator->path().filename().string();
      try
      {

        int idNum;
        try
        {
          idNum = stoi(id);
        } catch (invalid_argument &e)
        {
          err("entity's id (in directoryName '" + directory_iterator->path().string() + "') is not a number", e.what());
          continue;
        }
        //info("... restore: " + storePath.get() + "/" + id);

        /*
         * read item.json */
        Json params;
        try
        {
          ifstream item{this->route.get().toStringStorePath() + id + "/item.json"};
          stringstream sItem;
          sItem << item.rdbuf();
          params = Json::parse(sItem.str());
        }
        catch (exception &e)
        {
          err("read item '" + this->route.get().toStringStorePath() + id + "/item.json" + "' : " + string(e.what()));
          directory_iterator++;
          continue;
        }

        /*
         * add item */
        T *n = createItemFunc(params);
        ApiMessageRoute nRoute = route.get();
        nRoute.push(id); // set entity id
        n->setRoute(nRoute);
        items.insert({idNum, n});
        n->restore();

        // next
        if (idNum >= idAutoIncrement)
          idAutoIncrement = idNum + 1;
        directory_iterator++;
      }
      catch (exception &e)
      {
        err("restore (" + this->route.get().toStringStorePath() + " id(" + id + ")): " + string(e.what()));
        directory_iterator++;
      }
    }
  }
  catch (exception &e){
    err("restore ("+this->route.get().toStringStorePath()+" all list items): " + string(e.what()));
  }
}

template<class T>
void JsonList<T>::setRoute(ApiMessageRoute route)
{
  ApiProcessible::setRoute(route);
  for (auto i: items) {
    ApiMessageRoute n = route;
    n.push(to_string(i.first)); // set entity id
    i.second->setRoute(n);
  }
}

template<class T>
void JsonList<T>::store()
{
  ApiProcessible::store();
  for (auto i: items) {
    i.second->store();
  }
}

template<class T>
void JsonList<T>::remove()
{
  ApiProcessible::remove();
  for (auto item : items) {
    item.second->remove();
    delete item.second;
  }
  items.clear();
  boost::filesystem::remove_all(route.get().toStringStorePath());
  info("removed " + route.get().toStringStorePath());
}

template<class T>
JsonList<T>::~JsonList()
{
  info("at "+route.get_value_or(ApiMessageRoute()).toString()+" will delete all items ...");
  for (auto item : items)
    delete item.second;
  items.clear();
}

ext: tpp

max_stars_repo_name: PancakeSoftware/openHabAI

max_issues_repo_name: PancakeSoftware/openHabAI

max_forks_repo_name: PancakeSoftware/openHabAI


text:
#include "catch.hpp"

#include "tntn/Raster.h"
#include "tntn/RasterIO.h"
#include "tntn/RasterOverviews.h"

#include "test_common.h"

#include <memory>
#include <cstdlib>
#include <boost/filesystem.hpp>

namespace tntn {
namespace unittests {

TEST_CASE("raster_overviews_tests_1", "[tntn]")
{
    auto raster = std::make_unique<RasterDouble>();
    bool load_result;

    fs::path valid_raster_file = fixture_path("valid_raster.tif");

    load_result = load_raster_file(valid_raster_file.string(), *raster);
    REQUIRE(load_result == true);

    int min_zoom = 0;
    int max_zoom = 20;
    RasterOverviews overviews(std::move(raster), min_zoom, max_zoom);

    RasterOverview overview;

    int zooms[1] = {15};
    double resolutions[1] = {3.916942};

    int counter = 0;

    while(overviews.next(overview))
    {
       REQUIRE(counter < 1);
       REQUIRE(overview.zoom_level == zooms[counter]);
       REQUIRE(double_eq(overview.resolution, resolutions[counter], 0.01));

       counter++;
    }
}

TEST_CASE("raster_overviews_tests_2", "[tntn]")
{
    auto raster = std::make_unique<RasterDouble>();
    bool load_result;

    fs::path valid_raster_file = fixture_path("egm84-epsg3857.tif");

    load_result = load_raster_file(valid_raster_file.string(), *raster);
    REQUIRE(load_result == true);

    int min_zoom = 0;
    int max_zoom = 20;
    RasterOverviews overviews(std::move(raster), min_zoom, max_zoom);

    RasterOverview overview;

    int zooms[2] = {1, 0};
    double resolutions[2] = {64187.510960, 128375.021920};

    int counter = 0;

    while(overviews.next(overview))
    {
       REQUIRE(counter < 2);
       REQUIRE(overview.zoom_level == zooms[counter]);
       REQUIRE(double_eq(overview.resolution, resolutions[counter], 0.01));

       counter++;
    }
}

} // namespace unittests
} // namespace tntn

max_stars_repo_name: znly/tin-terrain

max_issues_repo_name: sotex/tin-terrain

max_forks_repo_name: sotex/tin-terrain


text:
OBSOLETE

// Boost.Geometry (aka GGL, Generic Geometry Library)
//
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
// 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)
//
// Doxygen Examples, for e.g. email formal review

#include <boost/foreach.hpp>

#include <boost/geometry/geometry.hpp>

void example_distance()
{
    int a[2] = {1,2};
    int b[2] = {3,4};
    double d = boost::geometry::distance(a, b);
    std::cout << d << std::endl;
}

void example_length1()
{
    std::vector<boost::tuple<double, double, double> > line;
    line.push_back(boost::make_tuple(1, 2, 3));
    line.push_back(boost::make_tuple(4, 5, 6));
    line.push_back(boost::make_tuple(7, 8, 9));
    double length = boost::geometry::length(line);
    std::cout << length << std::endl;
}

void example_length2()
{
    std::vector<boost::tuple<double, double> > line;
    line.push_back(boost::make_tuple(1.1, 2.2));
    line.push_back(boost::make_tuple(3.3, 4.4));
    line.push_back(boost::make_tuple(5.5, 6.6));
    std::cout << boost::geometry::length(
                std::make_pair(boost::begin(line), boost::end(line) + -1)
            )
        << std::endl;
}

void example_less()
{
    typedef boost::tuple<double, double> P;
    std::vector<P> line;
    line.push_back(boost::make_tuple(8.1, 1.9));
    line.push_back(boost::make_tuple(4.2, 7.5));
    line.push_back(boost::make_tuple(2.3, 3.6));
    std::sort(line.begin(), line.end(), boost::geometry::less<P>());

    // Display ordered points
    BOOST_FOREACH(P const& p, line)
    {
        std::cout << boost::geometry::dsv(p) << std::endl;
    }
}

int main(void)
{
    example_distance();
    example_length1();
    example_length2();
    example_less();
    return 0;
}


text:
/*
Copyright 2017 InitialDLab

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/*
 * Rtree Experiements
 *
 * by Lu Wang 2014
 */

#include <iostream>
#include <vector>
#include <string>
#include <memory>
#include <cstdlib>

#include <boost/geometry/geometries/box.hpp>
#include <boost/timer/timer.hpp>
#include <boost/lexical_cast.hpp>

#include "rtree/rtree.h"
#include "rtree/tests/integrity_checker.h"

#include "level_sampling/level_sampling.h"

#include "mongo_types.h"
#include "hilbert/hilbert.h"

//#define USE_OSM

#ifdef USE_OSM
// osm
std::string const DATASET = "osm";
int const LEVEL_SAMPLING_MIN_MEM_LEVEL = 12;
#else
// geo
std::string const DATASET = "geo";
int const LEVEL_SAMPLING_MIN_MEM_LEVEL = 4;
#endif

/*
 * cache system disk cache
 */
const char * clear_cache_cmd = "/uusoc/scratch/magpie17/robertc/clearCache > /dev/null";
void clear_cache()
{
    auto unused = system(clear_cache_cmd);
    // TODO clear block manager cache when implemented
}

namespace bg = boost::geometry;
namespace bt = boost::timer;

struct Exp
{
    // how many sample queries to perform
    using entry = mongo_types::entry;
    using sample_entry = mongo_types::sample_entry;
    using point = mongo_types::point3d;
    using box = mongo_types::box3d;

    using rtree_t = rtree::rtree<
        entry,
        sample_entry,
        box,
        256, // node sample count
        16  // max fanout
    >;

    using ls_t = level_sampling::level_sampling<
        entry,
        sample_entry,
        box,
        16 // max fanout
    >;

    Exp(std::string const& rtree_name, std::string const& ls_name)
        : rtree_name(rtree_name)
        , ls_name(ls_name)
    { }

    void build_rtree (bool load_mem_nodes = false) {
        bt::cpu_timer timer;
        rtree_ptr.reset(new rtree_t(rtree_name, false, load_mem_nodes));
        std::cout << "tree size: " << rtree_ptr->size() << std::endl;

        auto stats = rtree_ptr->get_stats();
        std::cout << "leaf node count: " << stats.leaf_nodes << std::endl;
        std::cout << "internal node count: " << stats.internal_nodes << std::endl;
        std::cout << "tree building time(ms): " << ' ' << timer.elapsed().wall/1000000.0 << std::endl;

        std::cout << "bbox: ";
        dump_box(std::cout, rtree_ptr->bbox());
        std::cout << std::endl;
    }

    void build_ls (void) {
        bt::cpu_timer timer;
        ls_ptr.reset(new ls_t(ls_name, LEVEL_SAMPLING_MIN_MEM_LEVEL));
        std::cout << "min mem level: " << ls_ptr->min_mem_level << std::endl;
        std::cout << "max level: " << ls_ptr->max_level << std::endl;
    }

    void run() {
        build_rtree(true);
        auto stats = rtree_ptr->count_nodes();
        std::cerr << "internal nodes: " << stats.internal_nodes << std::endl;
        std::cerr << "leaf nodes: " << stats.leaf_nodes << std::endl;
        std::cerr << "io internal nodes: " << stats.io_internal_nodes << std::endl;
        std::cerr << "io leaf nodes: " << stats.io_leaf_nodes << std::endl;
    }

    std::unique_ptr<rtree_t> rtree_ptr;
    std::unique_ptr<ls_t> ls_ptr;
    std::string rtree_name, ls_name;

    std::vector<box> queries;
};

int main(int argc, char ** argv)
{
    //std::string filename = argv[1];
    std::string path = "/uusoc/scratch/magpie21/luwang/data/built/" + DATASET;

    //Exp(filename+"-rtree", filename+"-ls").run();
    Exp(path + "_tree", path + "_level").run();

    return 0;
}

max_stars_repo_name: InitialDLab/SampleIndex

max_issues_repo_name: InitialDLab/SONAR-SamplingIndex

max_forks_repo_name: InitialDLab/SONAR-SamplingIndex


text:
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 "hbase/utils/bytes-util.h"

#include <boost/predef.h>
#include <glog/logging.h>

#include <memory>
#include <string>

namespace hbase {

constexpr char BytesUtil::kHexChars[];

std::string BytesUtil::ToString(int64_t val) {
  std::string res;
#if BOOST_ENDIAN_BIG_BYTE || BOOST_ENDIAN_BIG_WORD
  for (int i = 7; i > 0; i--) {
    res += (int8_t)(val & 0xffu);
    val = val >> 8;
  }
  res += (int8_t)val;
#else
  int64_t mask = 0xff00000000000000u;
  for (int i = 56; i >= 1; i -= 8) {
    auto num = ((val & mask) >> i);
    res += num;
    mask = mask >> 8;
  }
  res += (val & 0xff);
#endif
  return res;
}

int64_t BytesUtil::ToInt64(std::string str) {
  if (str.length() < 8) {
    throw std::runtime_error("There are not enough bytes. Expected: 8, actual: " + str.length());
  }
  const unsigned char *bytes = reinterpret_cast<unsigned char *>(const_cast<char *>(str.c_str()));
  int64_t l = 0;
  for (int i = 0; i < 8; i++) {
    l <<= 8;
    l ^= bytes[i];
  }
  return l;
}

std::string BytesUtil::ToStringBinary(const std::string &b, size_t off, size_t len) {
  std::string result;
  // Just in case we are passed a 'len' that is > buffer length...
  if (off >= b.size()) {
    return result;
  }
  if (off + len > b.size()) {
    len = b.size() - off;
  }
  for (size_t i = off; i < off + len; ++i) {
    int32_t ch = b[i] & 0xFF;
    if (ch >= ' ' && ch <= '~' && ch != '\\') {
      result += ch;
    } else {
      result += "\\x";
      result += kHexChars[ch / 0x10];
      result += kHexChars[ch % 0x10];
    }
  }
  return result;
}

} /* namespace hbase */

ext: cc


text:
//==============================================================================
//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#define NT2_UNIT_MODULE "boost::dispatch::meta::as_signed"

#include <boost/simd/sdk/config/types.hpp>
#include <boost/dispatch/meta/as_signed.hpp>
#include <boost/type_traits/is_same.hpp>

#include <nt2/sdk/unit/module.hpp>
#include <nt2/sdk/unit/tests/basic.hpp>

////////////////////////////////////////////////////////////////////////////////
// Test that as_integer is correct w/r to original sign
////////////////////////////////////////////////////////////////////////////////
NT2_TEST_CASE(as_signed)
{
  using boost::dispatch::meta::as_signed;
  using boost::is_same;

  NT2_TEST( (is_same<as_signed<double        >::type,double     >::value ));
  NT2_TEST( (is_same<as_signed<float         >::type,float      >::value ));
  NT2_TEST( (is_same<as_signed<boost::simd::int64_t >::type,boost::simd::int64_t>::value ));
  NT2_TEST( (is_same<as_signed<boost::simd::int32_t >::type,boost::simd::int32_t>::value ));
  NT2_TEST( (is_same<as_signed<boost::simd::int16_t >::type,boost::simd::int16_t>::value ));
  NT2_TEST( (is_same<as_signed<boost::simd::int8_t  >::type,boost::simd::int8_t >::value ));
  NT2_TEST( (is_same<as_signed<boost::simd::uint64_t>::type,boost::simd::int64_t>::value ));
  NT2_TEST( (is_same<as_signed<boost::simd::uint32_t>::type,boost::simd::int32_t>::value ));
  NT2_TEST( (is_same<as_signed<boost::simd::uint16_t>::type,boost::simd::int16_t>::value ));
  NT2_TEST( (is_same<as_signed<boost::simd::uint8_t >::type,boost::simd::int8_t >::value ));
  NT2_TEST( (is_same<as_signed<bool         >::type,bool        >::value ));
}


text:
//
// Created by lei on 4/21/19.
//

#ifndef TGO1D_CXX_TGO_HPP
#define TGO1D_CXX_TGO_HPP

#include <vector>
#include <functional>
#include <armadillo>

struct OptimizeResult {
    OptimizeResult(const arma::vec &xl,
                   const arma::vec &fl,
                   double x, double f);

    // copy and move
    arma::vec xl;
    arma::vec funl;
    double x;
    double f;
};

class TGO {
public:
    TGO(std::function<double(double)> functor, int nsample, int nk,
        double xmin, double xmax, double xtol);

    OptimizeResult optimize();

private:
    static double func_nlopt(const std::vector<double> &x,
                             std::vector<double> &grad,
                             void *f_data);
    static double approx_grad(double x, double f, double epsilon);
    std::function<double(double)> functor_;
    int nsample_;
    int nk_;
    double xmin_;
    double xmax_;
    double xtol_;
    static constexpr double epsilon_ = 1.0e-9;

    static TGO *pThis;
};
// so many `static` due to the requirement of static function in nlopt.

#endif //TGO1D_CXX_TGO_HPP

ext: hpp


text:
/**
 * \ file AttackReleaseHysteresisFilter.cpp
 */

#include <ATK/Dynamic/AttackReleaseHysteresisFilter.h>

#include <ATK/Core/InPointerFilter.h>
#include <ATK/Core/OutPointerFilter.h>
#include <ATK/Core/Utilities.h>

#include <gtest/gtest.h>

#include <boost/math/constants/constants.hpp>

constexpr gsl::index PROCESSSIZE = 1024*64;

TEST(AttackReleaseHysteresis, attack_test)
{
  ATK::AttackReleaseHysteresisFilter<double> filter;
  filter.set_attack(0.5);
  ASSERT_EQ(filter.get_attack(), 0.5);
}

TEST(AttackReleaseHysteresis, attack_range_test)
{
  ATK::AttackReleaseHysteresisFilter<double> filter;
  ASSERT_THROW(filter.set_attack(-0.000001), ATK::RuntimeError);
}

TEST(AttackReleaseHysteresis, attack_range2_test)
{
  ATK::AttackReleaseHysteresisFilter<double> filter;
  ASSERT_THROW(filter.set_attack(1.000001), ATK::RuntimeError);
}

TEST(AttackReleaseHysteresis, release_test)
{
  ATK::AttackReleaseHysteresisFilter<double> filter;
  filter.set_release(0.5);
  ASSERT_EQ(filter.get_release(), 0.5);
}

TEST(AttackReleaseHysteresis, release_range_test)
{
  ATK::AttackReleaseHysteresisFilter<double> filter;
  ASSERT_THROW(filter.set_release(-0.000001), ATK::RuntimeError);
}

TEST(AttackReleaseHysteresis, release_range2_test)
{
  ATK::AttackReleaseHysteresisFilter<double> filter;
  ASSERT_THROW(filter.set_release(1.000001), ATK::RuntimeError);
}

TEST(AttackReleaseHysteresis, attack_hysteresis_test)
{
  ATK::AttackReleaseHysteresisFilter<double> filter;
  filter.set_release_hysteresis(0.1);
  filter.set_attack_hysteresis(0.5);
  ASSERT_EQ(filter.get_attack_hysteresis(), 0.5);
}

TEST(AttackReleaseHysteresis, attack_hysteresis_db_test)
{
  ATK::AttackReleaseHysteresisFilter<double> filter;
  filter.set_release_hysteresis(0.001);
  filter.set_attack_hysteresis_db(-20);
  ASSERT_NEAR(filter.get_attack_hysteresis(), 0.1, 0.1);
}

TEST(AttackReleaseHysteresis, attack_hysteresis_range_test)
{
  ATK::AttackReleaseHysteresisFilter<double> filter;
  filter.set_release_hysteresis(.5);
  ASSERT_THROW(filter.set_attack_hysteresis(.5 - 0.000001), ATK::RuntimeError);
}

TEST(AttackReleaseHysteresis, attack_hysteresis_range2_test)
{
  ATK::AttackReleaseHysteresisFilter<double> filter;
  ASSERT_THROW(filter.set_attack_hysteresis(1.000001), ATK::RuntimeError);
}

TEST(AttackReleaseHysteresis, hysteresis_release_test)
{
  ATK::AttackReleaseHysteresisFilter<double> filter;
  filter.set_release_hysteresis(0.5);
  ASSERT_EQ(filter.get_release_hysteresis(), 0.5);
}

TEST(AttackReleaseHysteresis, release_hysteresis_db_test)
{
  ATK::AttackReleaseHysteresisFilter<double> filter;
  filter.set_release_hysteresis_db(-20);
  ASSERT_NEAR(filter.get_release_hysteresis(), 0.1, 0.1);
}

TEST(AttackReleaseHysteresis, release_hysteresis_range_test)
{
  ATK::AttackReleaseHysteresisFilter<double> filter;
  ASSERT_THROW(filter.set_release_hysteresis(-0.000001), ATK::RuntimeError);
}

TEST(AttackReleaseHysteresis, release_hysteresis_range2_test)
{
  ATK::AttackReleaseHysteresisFilter<double> filter;
  ASSERT_THROW(filter.set_release_hysteresis(1.000001), ATK::RuntimeError);
}

TEST(AttackReleaseHysteresisFilter, triangle_test)
{
  std::vector<double> data(PROCESSSIZE);
  for(gsl::index i = 0; i < PROCESSSIZE/2; ++i)
  {
    data[i] = i / 48000;
  }
  for(gsl::index i = 0; i < PROCESSSIZE/2; ++i)
  {
    data[PROCESSSIZE/2 + i] = (PROCESSSIZE/2 - i) / 48000;
  }

  ATK::InPointerFilter<double> generator(data.data(), 1, PROCESSSIZE, false);
  generator.set_output_sampling_rate(48000);

  std::vector<double> outdata(PROCESSSIZE);

  ATK::AttackReleaseHysteresisFilter<double> filter(1);
  filter.set_attack(std::exp(-1./(48000 * 1e-3)));
  filter.set_release(std::exp(-1./(48000 * 100e-3)));
  filter.set_input_sampling_rate(48000);
  filter.set_input_port(0, &generator, 0);

  ATK::OutPointerFilter<double> output(outdata.data(), 1, PROCESSSIZE, false);
  output.set_input_sampling_rate(48000);
  output.set_input_port(0, &filter, 0);

  output.process(PROCESSSIZE);

  for(gsl::index i = 0; i < PROCESSSIZE/2; ++i)
  {
    ASSERT_GE(data[i], outdata[i]);
  }
  for(gsl::index i = 0; i < PROCESSSIZE/2; ++i)
  {
    ASSERT_GE(outdata[PROCESSSIZE / 2 + i], outdata[PROCESSSIZE / 2 + i - 1]);
  }
}

#define CUSTOMPROCESSSIZE 7

TEST(AttackReleaseHysteresisFilter, release_custom_test)
{
  double data[] = {0., 1., .5, .4, .3, .2, .1};
  double target[] = {0., 1., 1., .46, .46, .226, .1126};

  ATK::InPointerFilter<double> generator(data, 1, CUSTOMPROCESSSIZE, false);
  generator.set_output_sampling_rate(48000);

  std::array<double, CUSTOMPROCESSSIZE> outdata;

  ATK::AttackReleaseHysteresisFilter<double> filter(1);
  filter.set_attack(0);
  filter.set_release(.1);
  filter.set_release_hysteresis(.5);
  filter.set_input_sampling_rate(48000);
  filter.set_input_port(0, &generator, 0);

  ATK::OutPointerFilter<double> output(outdata.data(), 1, CUSTOMPROCESSSIZE, false);
  output.set_input_sampling_rate(48000);
  output.set_input_port(0, &filter, 0);

  output.process(CUSTOMPROCESSSIZE);

  for(gsl::index i = 0; i < CUSTOMPROCESSSIZE; ++i)
  {
    ASSERT_NEAR(target[i], outdata[i], .001);
  }
}

max_stars_repo_name: AudioTK/AudioTK

max_issues_repo_name: AudioTK/AudioTK

max_forks_repo_name: AudioTK/AudioTK


text:
/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  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.
 */
/*
 * Copyright (C) 2014 Cloudius Systems, Ltd.
 */

#ifndef SHARED_PTR_HH_
#define SHARED_PTR_HH_

#include "shared_ptr_debug_helper.hh"
#include <utility>
#include <type_traits>
#include <functional>
#include <iostream>
#include "util/is_smart_ptr.hh"
#include "util/indirect.hh"

#include <boost/intrusive/parent_from_member.hpp>

namespace seastar {

// This header defines two shared pointer facilities, lw_shared_ptr<> and
// shared_ptr<>, both modeled after std::shared_ptr<>.
//
// Unlike std::shared_ptr<>, neither of these implementations are thread
// safe, and two pointers sharing the same object must not be used in
// different threads.
//
// lw_shared_ptr<> is the more lightweight variant, with a lw_shared_ptr<>
// occupying just one machine word, and adding just one word to the shared
// object.  However, it does not support polymorphism.
//
// shared_ptr<> is more expensive, with a pointer occupying two machine
// words, and with two words of overhead in the shared object.  In return,
// it does support polymorphism.
//
// Both variants support shared_from_this() via enable_shared_from_this<>
// and lw_enable_shared_from_this<>().
//

#ifndef SEASTAR_DEBUG_SHARED_PTR
using shared_ptr_counter_type = long;
#else
using shared_ptr_counter_type = debug_shared_ptr_counter_type;
#endif

template <typename T>
class lw_shared_ptr;

template <typename T>
class shared_ptr;

template <typename T>
class enable_lw_shared_from_this;

template <typename T>
class enable_shared_from_this;

template <typename T, typename... A>
lw_shared_ptr<T> make_lw_shared(A&&... a);

template <typename T>
lw_shared_ptr<T> make_lw_shared(T&& a);

template <typename T>
lw_shared_ptr<T> make_lw_shared(T& a);

template <typename T, typename... A>
shared_ptr<T> make_shared(A&&... a);

template <typename T>
shared_ptr<T> make_shared(T&& a);

template <typename T, typename U>
shared_ptr<T> static_pointer_cast(const shared_ptr<U>& p);

template <typename T, typename U>
shared_ptr<T> dynamic_pointer_cast(const shared_ptr<U>& p);

template <typename T, typename U>
shared_ptr<T> const_pointer_cast(const shared_ptr<U>& p);

struct lw_shared_ptr_counter_base {
    shared_ptr_counter_type _count = 0;
};

namespace internal {

template <class T, class U>
struct lw_shared_ptr_accessors;

template <class T>
struct lw_shared_ptr_accessors_esft;

template <class T>
struct lw_shared_ptr_accessors_no_esft;

}

// We want to support two use cases for shared_ptr<T>:
//
//   1. T is any type (primitive or class type)
//
//   2. T is a class type that inherits from enable_shared_from_this<T>.
//
// In the first case, we must wrap T in an object containing the counter,
// since T may be a primitive type and cannot be a base class.
//
// In the second case, we want T to reach the counter through its
// enable_shared_from_this<> base class, so that we can implement
// shared_from_this().
//
// To implement those two conflicting requirements (T alongside its counter;
// T inherits from an object containing the counter) we use std::conditional<>
// and some accessor functions to select between two implementations.

// CRTP from this to enable shared_from_this:
template <typename T>
class enable_lw_shared_from_this : private lw_shared_ptr_counter_base {
    using ctor = T;
protected:
    enable_lw_shared_from_this() noexcept {}
    enable_lw_shared_from_this(enable_lw_shared_from_this&&) noexcept {}
    enable_lw_shared_from_this(const enable_lw_shared_from_this&) noexcept {}
    enable_lw_shared_from_this& operator=(const enable_lw_shared_from_this&) noexcept { return *this; }
    enable_lw_shared_from_this& operator=(enable_lw_shared_from_this&&) noexcept { return *this; }
public:
    lw_shared_ptr<T> shared_from_this();
    lw_shared_ptr<const T> shared_from_this() const;

    template <typename X>
    friend class lw_shared_ptr;
    template <typename X>
    friend class internal::lw_shared_ptr_accessors_esft;
    template <typename X, class Y>
    friend class internal::lw_shared_ptr_accessors;
};

template <typename T>
struct shared_ptr_no_esft : private lw_shared_ptr_counter_base {
    T _value;

    shared_ptr_no_esft() = default;
    shared_ptr_no_esft(const T& x) : _value(x) {}
    shared_ptr_no_esft(T&& x) : _value(std::move(x)) {}
    template <typename... A>
    shared_ptr_no_esft(A&&... a) : _value(std::forward<A>(a)...) {}

    template <typename X>
    friend class lw_shared_ptr;
    template <typename X>
    friend class internal::lw_shared_ptr_accessors_no_esft;
    template <typename X, class Y>
    friend class internal::lw_shared_ptr_accessors;
};

/// Extension point: the user may override this to change how \ref lw_shared_ptr objects are destroyed,
/// primarily so that incomplete classes can be used.
///
/// Customizing the deleter requires that \c T be derived from \c enable_lw_shared_from_this<T>.
/// The specialization must be visible for all uses of \c lw_shared_ptr<T>.
///
/// To customize, the template must have a `static void dispose(T*)` operator that disposes of
/// the object.
template <typename T>
struct lw_shared_ptr_deleter;  // No generic implementation

namespace internal {

template <typename T>
struct lw_shared_ptr_accessors_esft {
    using concrete_type = std::remove_const_t<T>;
    static T* to_value(lw_shared_ptr_counter_base* counter) {
        return static_cast<T*>(counter);
    }
    static void dispose(lw_shared_ptr_counter_base* counter) {
        dispose(static_cast<T*>(counter));
    }
    static void dispose(T* value_ptr) {
        delete value_ptr;
    }
    static void instantiate_to_value(lw_shared_ptr_counter_base* p) {
        // since to_value() is defined above, we don't need to do anything special
        // to force-instantiate it
    }
};

template <typename T>
struct lw_shared_ptr_accessors_no_esft {
    using concrete_type = shared_ptr_no_esft<T>;
    static T* to_value(lw_shared_ptr_counter_base* counter) {
        return &static_cast<concrete_type*>(counter)->_value;
    }
    static void dispose(lw_shared_ptr_counter_base* counter) {
        delete static_cast<concrete_type*>(counter);
    }
    static void dispose(T* value_ptr) {
        delete boost::intrusive::get_parent_from_member(value_ptr, &concrete_type::_value);
    }
    static void instantiate_to_value(lw_shared_ptr_counter_base* p) {
        // since to_value() is defined above, we don't need to do anything special
        // to force-instantiate it
    }
};

// Generic case: lw_shared_ptr_deleter<T> is not specialized, select
// implementation based on whether T inherits from enable_lw_shared_from_this<T>.
template <typename T, typename U = void>
struct lw_shared_ptr_accessors : std::conditional_t<
         std::is_base_of<enable_lw_shared_from_this<T>, T>::value,
         lw_shared_ptr_accessors_esft<T>,
         lw_shared_ptr_accessors_no_esft<T>> {
};

// void_t is C++17, use this temporarily
template <typename... T>
using void_t = void;

// Overload when lw_shared_ptr_deleter<T> specialized
template <typename T>
struct lw_shared_ptr_accessors<T, void_t<decltype(lw_shared_ptr_deleter<T>{})>> {
    using concrete_type = T;
    static T* to_value(lw_shared_ptr_counter_base* counter);
    static void dispose(lw_shared_ptr_counter_base* counter) {
        lw_shared_ptr_deleter<T>::dispose(to_value(counter));
    }
    static void instantiate_to_value(lw_shared_ptr_counter_base* p) {
        // instantiate to_value(); must be defined by shared_ptr_incomplete.hh
        to_value(p);
    }
};

}

template <typename T>
class lw_shared_ptr {
    using accessors = internal::lw_shared_ptr_accessors<std::remove_const_t<T>>;
    using concrete_type = typename accessors::concrete_type;
    mutable lw_shared_ptr_counter_base* _p = nullptr;
private:
    lw_shared_ptr(lw_shared_ptr_counter_base* p) noexcept : _p(p) {
        if (_p) {
            ++_p->_count;
        }
    }
    template <typename... A>
    static lw_shared_ptr make(A&&... a) {
        auto p = new concrete_type(std::forward<A>(a)...);
        accessors::instantiate_to_value(p);
        return lw_shared_ptr(p);
    }
public:
    using element_type = T;

    // Destroys the object pointed to by p and disposes of its storage.
    // The pointer to the object must have been obtained through release().
    static void dispose(T* p) noexcept {
        accessors::dispose(p);
    }

    // A functor which calls dispose().
    class disposer {
    public:
        void operator()(T* p) const noexcept {
            dispose(p);
        }
    };

    lw_shared_ptr() noexcept = default;
    lw_shared_ptr(std::nullptr_t) noexcept : lw_shared_ptr() {}
    lw_shared_ptr(const lw_shared_ptr& x) noexcept : _p(x._p) {
        if (_p) {
            ++_p->_count;
        }
    }
    lw_shared_ptr(lw_shared_ptr&& x) noexcept  : _p(x._p) {
        x._p = nullptr;
    }
    [[gnu::always_inline]]
    ~lw_shared_ptr() {
        if (_p && !--_p->_count) {
            accessors::dispose(_p);
        }
    }
    lw_shared_ptr& operator=(const lw_shared_ptr& x) noexcept {
        if (_p != x._p) {
            this->~lw_shared_ptr();
            new (this) lw_shared_ptr(x);
        }
        return *this;
    }
    lw_shared_ptr& operator=(lw_shared_ptr&& x) noexcept {
        if (_p != x._p) {
            this->~lw_shared_ptr();
            new (this) lw_shared_ptr(std::move(x));
        }
        return *this;
    }
    lw_shared_ptr& operator=(std::nullptr_t) noexcept {
        return *this = lw_shared_ptr();
    }
    lw_shared_ptr& operator=(T&& x) noexcept {
        this->~lw_shared_ptr();
        new (this) lw_shared_ptr(make_lw_shared<T>(std::move(x)));
        return *this;
    }

    T& operator*() const noexcept { return *accessors::to_value(_p); }
    T* operator->() const noexcept { return accessors::to_value(_p); }
    T* get() const noexcept {
        if (_p) {
            return accessors::to_value(_p);
        } else {
            return nullptr;
        }
    }

    // Releases ownership of the object without destroying it.
    // If this was the last owner then returns an engaged unique_ptr
    // which is now the sole owner of the object.
    // Returns a disengaged pointer if there are still some owners.
    //
    // Note that in case the raw pointer is extracted from the unique_ptr
    // using unique_ptr::release(), it must be still destroyed using
    // lw_shared_ptr::disposer or lw_shared_ptr::dispose().
    std::unique_ptr<T, disposer> release() noexcept {
        auto p = std::exchange(_p, nullptr);
        if (--p->_count) {
            return nullptr;
        } else {
            return std::unique_ptr<T, disposer>(accessors::to_value(p));
        }
    }

    long int use_count() const noexcept {
        if (_p) {
            return _p->_count;
        } else {
            return 0;
        }
    }

    operator lw_shared_ptr<const T>() const noexcept {
        return lw_shared_ptr<const T>(_p);
    }

    explicit operator bool() const noexcept {
        return _p;
    }

    bool owned() const noexcept {
        return _p->_count == 1;
    }

    bool operator==(const lw_shared_ptr<const T>& x) const {
        return _p == x._p;
    }

    bool operator!=(const lw_shared_ptr<const T>& x) const {
        return !operator==(x);
    }

    bool operator==(const lw_shared_ptr<std::remove_const_t<T>>& x) const {
        return _p == x._p;
    }

    bool operator!=(const lw_shared_ptr<std::remove_const_t<T>>& x) const {
        return !operator==(x);
    }

    bool operator<(const lw_shared_ptr<const T>& x) const {
        return _p < x._p;
    }

    bool operator<(const lw_shared_ptr<std::remove_const_t<T>>& x) const {
        return _p < x._p;
    }

    template <typename U>
    friend class lw_shared_ptr;

    template <typename X, typename... A>
    friend lw_shared_ptr<X> make_lw_shared(A&&...);

    template <typename U>
    friend lw_shared_ptr<U> make_lw_shared(U&&);

    template <typename U>
    friend lw_shared_ptr<U> make_lw_shared(U&);

    template <typename U>
    friend class enable_lw_shared_from_this;
};

template <typename T, typename... A>
inline
lw_shared_ptr<T> make_lw_shared(A&&... a) {
    return lw_shared_ptr<T>::make(std::forward<A>(a)...);
}

template <typename T>
inline
lw_shared_ptr<T> make_lw_shared(T&& a) {
    return lw_shared_ptr<T>::make(std::move(a));
}

template <typename T>
inline
lw_shared_ptr<T> make_lw_shared(T& a) {
    return lw_shared_ptr<T>::make(a);
}

template <typename T>
inline
lw_shared_ptr<T>
enable_lw_shared_from_this<T>::shared_from_this() {
    return lw_shared_ptr<T>(this);
}

template <typename T>
inline
lw_shared_ptr<const T>
enable_lw_shared_from_this<T>::shared_from_this() const {
    return lw_shared_ptr<const T>(const_cast<enable_lw_shared_from_this*>(this));
}

template <typename T>
static inline
std::ostream& operator<<(std::ostream& out, const lw_shared_ptr<T>& p) {
    if (!p) {
        return out << "null";
    }
    return out << *p;
}

// Polymorphic shared pointer class

struct shared_ptr_count_base {
    // destructor is responsible for fully-typed deletion
    virtual ~shared_ptr_count_base() {}
    shared_ptr_counter_type count = 0;
};

template <typename T>
struct shared_ptr_count_for : shared_ptr_count_base {
    T data;
    template <typename... A>
    shared_ptr_count_for(A&&... a) : data(std::forward<A>(a)...) {}
};

template <typename T>
class enable_shared_from_this : private shared_ptr_count_base {
public:
    shared_ptr<T> shared_from_this();
    shared_ptr<const T> shared_from_this() const;

    template <typename U>
    friend class shared_ptr;

    template <typename U, bool esft>
    friend struct shared_ptr_make_helper;
};

template <typename T>
class shared_ptr {
    mutable shared_ptr_count_base* _b = nullptr;
    mutable T* _p = nullptr;
private:
    explicit shared_ptr(shared_ptr_count_for<T>* b) noexcept : _b(b), _p(&b->data) {
        ++_b->count;
    }
    shared_ptr(shared_ptr_count_base* b, T* p) noexcept : _b(b), _p(p) {
        if (_b) {
            ++_b->count;
        }
    }
    explicit shared_ptr(enable_shared_from_this<std::remove_const_t<T>>* p) noexcept : _b(p), _p(static_cast<T*>(p)) {
        if (_b) {
            ++_b->count;
        }
    }
public:
    using element_type = T;

    shared_ptr() noexcept = default;
    shared_ptr(std::nullptr_t) noexcept : shared_ptr() {}
    shared_ptr(const shared_ptr& x) noexcept
            : _b(x._b)
            , _p(x._p) {
        if (_b) {
            ++_b->count;
        }
    }
    shared_ptr(shared_ptr&& x) noexcept
            : _b(x._b)
            , _p(x._p) {
        x._b = nullptr;
        x._p = nullptr;
    }
    template <typename U, typename = std::enable_if_t<std::is_base_of<T, U>::value>>
    shared_ptr(const shared_ptr<U>& x) noexcept
            : _b(x._b)
            , _p(x._p) {
        if (_b) {
            ++_b->count;
        }
    }
    template <typename U, typename = std::enable_if_t<std::is_base_of<T, U>::value>>
    shared_ptr(shared_ptr<U>&& x) noexcept
            : _b(x._b)
            , _p(x._p) {
        x._b = nullptr;
        x._p = nullptr;
    }
    ~shared_ptr() {
        if (_b && !--_b->count) {
            delete _b;
        }
    }
    shared_ptr& operator=(const shared_ptr& x) noexcept {
        if (this != &x) {
            this->~shared_ptr();
            new (this) shared_ptr(x);
        }
        return *this;
    }
    shared_ptr& operator=(shared_ptr&& x) noexcept {
        if (this != &x) {
            this->~shared_ptr();
            new (this) shared_ptr(std::move(x));
        }
        return *this;
    }
    shared_ptr& operator=(std::nullptr_t) noexcept {
        return *this = shared_ptr();
    }
    template <typename U, typename = std::enable_if_t<std::is_base_of<T, U>::value>>
    shared_ptr& operator=(const shared_ptr<U>& x) noexcept {
        if (*this != x) {
            this->~shared_ptr();
            new (this) shared_ptr(x);
        }
        return *this;
    }
    template <typename U, typename = std::enable_if_t<std::is_base_of<T, U>::value>>
    shared_ptr& operator=(shared_ptr<U>&& x) noexcept {
        if (*this != x) {
            this->~shared_ptr();
            new (this) shared_ptr(std::move(x));
        }
        return *this;
    }
    explicit operator bool() const noexcept {
        return _p;
    }
    T& operator*() const noexcept {
        return *_p;
    }
    T* operator->() const noexcept {
        return _p;
    }
    T* get() const noexcept {
        return _p;
    }
    long use_count() const noexcept {
        if (_b) {
            return _b->count;
        } else {
            return 0;
        }
    }

    template <bool esft>
    struct make_helper;

    template <typename U, typename... A>
    friend shared_ptr<U> make_shared(A&&... a);

    template <typename U>
    friend shared_ptr<U> make_shared(U&& a);

    template <typename V, typename U>
    friend shared_ptr<V> static_pointer_cast(const shared_ptr<U>& p);

    template <typename V, typename U>
    friend shared_ptr<V> dynamic_pointer_cast(const shared_ptr<U>& p);

    template <typename V, typename U>
    friend shared_ptr<V> const_pointer_cast(const shared_ptr<U>& p);

    template <bool esft, typename... A>
    static shared_ptr make(A&&... a);

    template <typename U>
    friend class enable_shared_from_this;

    template <typename U, bool esft>
    friend struct shared_ptr_make_helper;

    template <typename U>
    friend class shared_ptr;
};

template <typename U, bool esft>
struct shared_ptr_make_helper;

template <typename T>
struct shared_ptr_make_helper<T, false> {
    template <typename... A>
    static shared_ptr<T> make(A&&... a) {
        return shared_ptr<T>(new shared_ptr_count_for<T>(std::forward<A>(a)...));
    }
};

template <typename T>
struct shared_ptr_make_helper<T, true> {
    template <typename... A>
    static shared_ptr<T> make(A&&... a) {
        auto p = new T(std::forward<A>(a)...);
        return shared_ptr<T>(p, p);
    }
};

template <typename T, typename... A>
inline
shared_ptr<T>
make_shared(A&&... a) {
    using helper = shared_ptr_make_helper<T, std::is_base_of<shared_ptr_count_base, T>::value>;
    return helper::make(std::forward<A>(a)...);
}

template <typename T>
inline
shared_ptr<T>
make_shared(T&& a) {
    using helper = shared_ptr_make_helper<T, std::is_base_of<shared_ptr_count_base, T>::value>;
    return helper::make(std::forward<T>(a));
}

template <typename T, typename U>
inline
shared_ptr<T>
static_pointer_cast(const shared_ptr<U>& p) {
    return shared_ptr<T>(p._b, static_cast<T*>(p._p));
}

template <typename T, typename U>
inline
shared_ptr<T>
dynamic_pointer_cast(const shared_ptr<U>& p) {
    auto q = dynamic_cast<T*>(p._p);
    return shared_ptr<T>(q ? p._b : nullptr, q);
}

template <typename T, typename U>
inline
shared_ptr<T>
const_pointer_cast(const shared_ptr<U>& p) {
    return shared_ptr<T>(p._b, const_cast<T*>(p._p));
}

template <typename T>
inline
shared_ptr<T>
enable_shared_from_this<T>::shared_from_this() {
    auto unconst = reinterpret_cast<enable_shared_from_this<std::remove_const_t<T>>*>(this);
    return shared_ptr<T>(unconst);
}

template <typename T>
inline
shared_ptr<const T>
enable_shared_from_this<T>::shared_from_this() const {
    auto esft = const_cast<enable_shared_from_this*>(this);
    auto unconst = reinterpret_cast<enable_shared_from_this<std::remove_const_t<T>>*>(esft);
    return shared_ptr<const T>(unconst);
}

template <typename T, typename U>
inline
bool
operator==(const shared_ptr<T>& x, const shared_ptr<U>& y) {
    return x.get() == y.get();
}

template <typename T>
inline
bool
operator==(const shared_ptr<T>& x, std::nullptr_t) {
    return x.get() == nullptr;
}

template <typename T>
inline
bool
operator==(std::nullptr_t, const shared_ptr<T>& y) {
    return nullptr == y.get();
}

template <typename T, typename U>
inline
bool
operator!=(const shared_ptr<T>& x, const shared_ptr<U>& y) {
    return x.get() != y.get();
}

template <typename T>
inline
bool
operator!=(const shared_ptr<T>& x, std::nullptr_t) {
    return x.get() != nullptr;
}

template <typename T>
inline
bool
operator!=(std::nullptr_t, const shared_ptr<T>& y) {
    return nullptr != y.get();
}

template <typename T, typename U>
inline
bool
operator<(const shared_ptr<T>& x, const shared_ptr<U>& y) {
    return x.get() < y.get();
}

template <typename T>
inline
bool
operator<(const shared_ptr<T>& x, std::nullptr_t) {
    return x.get() < nullptr;
}

template <typename T>
inline
bool
operator<(std::nullptr_t, const shared_ptr<T>& y) {
    return nullptr < y.get();
}

template <typename T, typename U>
inline
bool
operator<=(const shared_ptr<T>& x, const shared_ptr<U>& y) {
    return x.get() <= y.get();
}

template <typename T>
inline
bool
operator<=(const shared_ptr<T>& x, std::nullptr_t) {
    return x.get() <= nullptr;
}

template <typename T>
inline
bool
operator<=(std::nullptr_t, const shared_ptr<T>& y) {
    return nullptr <= y.get();
}

template <typename T, typename U>
inline
bool
operator>(const shared_ptr<T>& x, const shared_ptr<U>& y) {
    return x.get() > y.get();
}

template <typename T>
inline
bool
operator>(const shared_ptr<T>& x, std::nullptr_t) {
    return x.get() > nullptr;
}

template <typename T>
inline
bool
operator>(std::nullptr_t, const shared_ptr<T>& y) {
    return nullptr > y.get();
}

template <typename T, typename U>
inline
bool
operator>=(const shared_ptr<T>& x, const shared_ptr<U>& y) {
    return x.get() >= y.get();
}

template <typename T>
inline
bool
operator>=(const shared_ptr<T>& x, std::nullptr_t) {
    return x.get() >= nullptr;
}

template <typename T>
inline
bool
operator>=(std::nullptr_t, const shared_ptr<T>& y) {
    return nullptr >= y.get();
}

template <typename T>
static inline
std::ostream& operator<<(std::ostream& out, const shared_ptr<T>& p) {
    if (!p) {
        return out << "null";
    }
    return out << *p;
}

template<typename T>
using shared_ptr_equal_by_value = indirect_equal_to<shared_ptr<T>>;

template<typename T>
using shared_ptr_value_hash = indirect_hash<shared_ptr<T>>;

}

namespace std {

template <typename T>
struct hash<seastar::lw_shared_ptr<T>> : private hash<T*> {
    size_t operator()(const seastar::lw_shared_ptr<T>& p) const {
        return hash<T*>::operator()(p.get());
    }
};

template <typename T>
struct hash<seastar::shared_ptr<T>> : private hash<T*> {
    size_t operator()(const seastar::shared_ptr<T>& p) const {
        return hash<T*>::operator()(p.get());
    }
};

}

namespace seastar {

template<typename T>
struct is_smart_ptr<shared_ptr<T>> : std::true_type {};

template<typename T>
struct is_smart_ptr<lw_shared_ptr<T>> : std::true_type {};

}

#endif /* SHARED_PTR_HH_ */

ext: hh


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

// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.

// This file was modified by Oracle on 2017.
// Modifications copyright (c) 2017, 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_EXTENSIONS_MULTI_ALGORITHMS_DISSOLVE_HPP
#define BOOST_GEOMETRY_EXTENSIONS_MULTI_ALGORITHMS_DISSOLVE_HPP

#include <vector>

#include <boost/range.hpp>

#include <boost/geometry/core/point_type.hpp>
#include <boost/geometry/core/tags.hpp>

#include <boost/geometry/algorithms/union.hpp>

#include <boost/geometry/extensions/algorithms/dissolve.hpp>
#include <boost/geometry/extensions/algorithms/detail/overlay/dissolver.hpp>

namespace boost { namespace geometry
{

#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace dissolve
{

template <typename Multi, typename GeometryOut, bool Reverse>
struct dissolve_multi
{
    template
    <
        typename RescalePolicy, typename OutputIterator,
        typename Strategy, typename Visitor
    >
    static inline OutputIterator apply(Multi const& multi,
            RescalePolicy const& rescale_policy, OutputIterator out,
            Strategy const& strategy, Visitor& visitor)
    {
        typedef typename boost::range_value<Multi>::type polygon_type;
        typedef typename boost::range_iterator<Multi const>::type iterator_type;

        // Step 1: dissolve all polygons in the multi-polygon, independantly
        std::vector<GeometryOut> step1;
        for (iterator_type it = boost::begin(multi);
            it != boost::end(multi);
            ++it)
        {
            dissolve_polygon
                <
                    polygon_type,
                    GeometryOut,
                    Reverse
                >::apply(*it, rescale_policy, std::back_inserter(step1),
                         strategy, visitor);
        }

        // Step 2: remove mutual overlap
        {
            std::vector<GeometryOut> step2; // TODO avoid this, output to "out", if possible
            detail::dissolver::dissolver_generic
                <
                    detail::dissolver::plusmin_policy
                >::apply(step1, rescale_policy, step2, strategy);
            for (typename std::vector<GeometryOut>::const_iterator it = step2.begin();
                it != step2.end(); ++it)
            {
                *out++ = *it;
            }
        }

        return out;
    }
};

// Dissolving multi-linestring is currently moved to extensions/algorithms/connect,
// because it is actually different from dissolving of polygons.
// To be decided what the final behaviour/name is.

}} // namespace detail::dissolve
#endif

#ifndef DOXYGEN_NO_DISPATCH
namespace dispatch
{

template<typename Multi, typename GeometryOut, bool Reverse>
struct dissolve<Multi, GeometryOut, Reverse, multi_polygon_tag, polygon_tag>
    : detail::dissolve::dissolve_multi<Multi, GeometryOut, Reverse>
{};

} // namespace dispatch
#endif // DOXYGEN_NO_DISPATCH

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_EXTENSIONS_MULTI_ALGORITHMS_DISSOLVE_HPP


text:
#include <math.h>
#include "inertiatest.hpp"
#include <frames_io.hpp>
#include <rotationalinertia.hpp>
#include <rigidbodyinertia.hpp>
#include <articulatedbodyinertia.hpp>

#include <Eigen/Core>
CPPUNIT_TEST_SUITE_REGISTRATION( InertiaTest );

using namespace KDL;
using namespace Eigen;

void InertiaTest::setUp()
{
}

void InertiaTest::tearDown()
{
}

void InertiaTest::TestRotationalInertia() {
    //Check if construction works fine
    RotationalInertia I0=RotationalInertia::Zero();
    CPPUNIT_ASSERT(Map<Matrix3d>(I0.data).isZero());
    RotationalInertia I1;
    CPPUNIT_ASSERT(Map<Matrix3d>(I1.data).isZero());
    CPPUNIT_ASSERT(Map<Matrix3d>(I0.data).isApprox(Map<Matrix3d>(I1.data)));
    RotationalInertia I2(1,2,3,4,5,6);

    //Check if copying works fine
    RotationalInertia I3=I2;
    CPPUNIT_ASSERT(Map<Matrix3d>(I3.data).isApprox(Map<Matrix3d>(I2.data)));
    I2.data[0]=0.0;
    CPPUNIT_ASSERT(!Map<Matrix3d>(I3.data).isApprox(Map<Matrix3d>(I2.data)));

    //Check if addition and multiplication works fine
    Map<Matrix3d>(I0.data).setRandom();
    I1=-2*I0;
    CPPUNIT_ASSERT(!Map<Matrix3d>(I1.data).isZero());
    I1=I1+I0+I0;
    CPPUNIT_ASSERT(Map<Matrix3d>(I1.data).isZero());

    //Check if matrix is symmetric
    CPPUNIT_ASSERT(Map<Matrix3d>(I2.data).isApprox(Map<Matrix3d>(I2.data).transpose()));

    //Check if angular momentum is correctly calculated:
    Vector omega;
    random(omega);
    Vector momentum=I2*omega;

    CPPUNIT_ASSERT(Map<Vector3d>(momentum.data).isApprox(Map<Matrix3d>(I2.data)*Map<Vector3d>(omega.data)));

}

void InertiaTest::TestRigidBodyInertia() {
    RigidBodyInertia I1(0.0);
    double mass;
    Vector c;
    RotationalInertia Ic;
    random(mass);
    random(c);
    Matrix3d Ic_eig = Matrix3d::Random();
    //make it symmetric:
    Map<Matrix3d>(Ic.data)=Ic_eig+Ic_eig.transpose();
    RigidBodyInertia I2(mass,c,Ic);
    //Check if construction works fine
    CPPUNIT_ASSERT_EQUAL(I2.getMass(),mass);
    CPPUNIT_ASSERT(!Map<Matrix3d>(I2.getRotationalInertia().data).isZero());
    CPPUNIT_ASSERT_EQUAL(I2.getCOG(),c);
    CPPUNIT_ASSERT(Map<Matrix3d>(I2.getRotationalInertia().data).isApprox(Map<Matrix3d>(Ic.data)-mass*(Map<Vector3d>(c.data)*Map<Vector3d>(c.data).transpose()-(Map<Vector3d>(c.data).dot(Map<Vector3d>(c.data))*Matrix3d::Identity()))));

    RigidBodyInertia I3=I2;
    //check if copying works fine
    CPPUNIT_ASSERT_EQUAL(I2.getMass(),I3.getMass());
    CPPUNIT_ASSERT_EQUAL(I2.getCOG(),I3.getCOG());
    CPPUNIT_ASSERT(Map<Matrix3d>(I2.getRotationalInertia().data).isApprox(Map<Matrix3d>(I3.getRotationalInertia().data)));
    //Check if multiplication and addition works fine
    RigidBodyInertia I4=-2*I2 +I3+I3;
    CPPUNIT_ASSERT_EQUAL(I4.getMass(),0.0);
    CPPUNIT_ASSERT_EQUAL(I4.getCOG(),Vector::Zero());
    CPPUNIT_ASSERT(Map<Matrix3d>(I4.getRotationalInertia().data).isZero());

    //Check if transformations work fine
    //Check only rotation transformation
    //back and forward
    Rotation R;
    random(R);
    I3 = R*I2;
    I4 = R.Inverse()*I3;
    CPPUNIT_ASSERT_EQUAL(I2.getMass(),I4.getMass());
    CPPUNIT_ASSERT_EQUAL(I2.getCOG(),I4.getCOG());
    CPPUNIT_ASSERT(Map<Matrix3d>(I2.getRotationalInertia().data).isApprox(Map<Matrix3d>(I4.getRotationalInertia().data)));
    //rotation and total with p=0
    Frame T(R);
    I4 = T*I2;
    CPPUNIT_ASSERT_EQUAL(I3.getMass(),I4.getMass());
    CPPUNIT_ASSERT_EQUAL(I3.getCOG(),I4.getCOG());
    CPPUNIT_ASSERT(Map<Matrix3d>(I3.getRotationalInertia().data).isApprox(Map<Matrix3d>(I4.getRotationalInertia().data)));

    //Check only transformation
    Vector p;
    random(p);
    I3 = I2.RefPoint(p);
    I4 = I3.RefPoint(-p);
    CPPUNIT_ASSERT_EQUAL(I2.getMass(),I4.getMass());
    CPPUNIT_ASSERT_EQUAL(I2.getCOG(),I4.getCOG());
    CPPUNIT_ASSERT(Map<Matrix3d>(I2.getRotationalInertia().data).isApprox(Map<Matrix3d>(I4.getRotationalInertia().data)));
    T=Frame(-p);
    I4 = T*I2;
    CPPUNIT_ASSERT_EQUAL(I3.getMass(),I4.getMass());
    CPPUNIT_ASSERT_EQUAL(I3.getCOG(),I4.getCOG());
    CPPUNIT_ASSERT(Map<Matrix3d>(I3.getRotationalInertia().data).isApprox(Map<Matrix3d>(I4.getRotationalInertia().data)));

    random(T);
    I3=T*I2;
    I4=T.Inverse()*I3;

    Twist a;
    random(a);
    Wrench f=I2*a;
    CPPUNIT_ASSERT_EQUAL(T*f,(T*I2)*(T*a));

    random(T);
    I3 = T*I2;
    I4 = T.Inverse()*I3;
    CPPUNIT_ASSERT_EQUAL(I2.getMass(),I4.getMass());
    CPPUNIT_ASSERT_EQUAL(I2.getCOG(),I4.getCOG());
    CPPUNIT_ASSERT(Map<Matrix3d>(I2.getRotationalInertia().data).isApprox(Map<Matrix3d>(I4.getRotationalInertia().data)));

}
void InertiaTest::TestArticulatedBodyInertia() {
    double mass;
    Vector c;
    RotationalInertia Ic;
    random(mass);
    random(c);
    Matrix3d::Map(Ic.data).triangularView<Lower>()= Matrix3d::Random().triangularView<Lower>();
    RigidBodyInertia RBI2(mass,c,Ic);
    ArticulatedBodyInertia I2(RBI2);
    ArticulatedBodyInertia I1(mass,c,Ic);
    //Check if construction works fine
    CPPUNIT_ASSERT_EQUAL(I2.M,I1.M);
    CPPUNIT_ASSERT_EQUAL(I2.H,I1.H);
    CPPUNIT_ASSERT_EQUAL(I2.I,I1.I);
    I1 = ArticulatedBodyInertia(I2);
    CPPUNIT_ASSERT_EQUAL(I2.M,I1.M);
    CPPUNIT_ASSERT_EQUAL(I2.H,I1.H);
    CPPUNIT_ASSERT_EQUAL(I2.I,I1.I);

    CPPUNIT_ASSERT_EQUAL(I2.M,(Matrix3d::Identity()*mass).eval());
    CPPUNIT_ASSERT(!I2.I.isZero());
    //CPPUNIT_ASSERT(I2.I.isApprox(Map<Matrix3d>(Ic.data)-mass*(Map<Vector3d>(c.data)*Map<Vector3d>(c.data).transpose()-(Map<Vector3d>(c.data).dot(Map<Vector3d>(c.data))*Matrix3d::Identity()))));
    //CPPUNIT_ASSERT(I2.H.isApprox(Map<Vector3d>(c.data)*Map<Vector3d>(c.data).transpose()-(Map<Vector3d>(c.data).dot(Map<Vector3d>(c.data))*Matrix3d::Identity())));
    ArticulatedBodyInertia I3=I2;
    //check if copying works fine
    CPPUNIT_ASSERT_EQUAL(I2.M,I3.M);
    CPPUNIT_ASSERT_EQUAL(I2.H,I3.H);
    CPPUNIT_ASSERT_EQUAL(I2.I,I3.I);
    //Check if multiplication and addition works fine
    ArticulatedBodyInertia I4=-2*I2 +I3+I3;
    CPPUNIT_ASSERT_EQUAL(I4.M,Matrix3d::Zero().eval());
    CPPUNIT_ASSERT_EQUAL(I4.H,Matrix3d::Zero().eval());
    CPPUNIT_ASSERT_EQUAL(I4.I,Matrix3d::Zero().eval());

    //Check if transformations work fine
    //Check only rotation transformation
    //back and forward
    Rotation R;
    random(R);
    I3 = R*I2;
    Map<Matrix3d> E(R.data);
    Matrix3d tmp = E.transpose()*I2.M*E;
    CPPUNIT_ASSERT(I3.M.isApprox(tmp));
    tmp = E.transpose()*I2.H*E;
    CPPUNIT_ASSERT_EQUAL(I3.H,tmp);
    tmp = E.transpose()*I2.I*E;
    CPPUNIT_ASSERT(I3.I.isApprox(tmp));

    I4 = R.Inverse()*I3;
    CPPUNIT_ASSERT(I2.M.isApprox(I4.M));
    CPPUNIT_ASSERT(I2.H.isApprox(I4.H));
    CPPUNIT_ASSERT(I2.I.isApprox(I4.I));
    //rotation and total with p=0
    Frame T(R);
    I4 = T*I2;
    CPPUNIT_ASSERT_EQUAL(I3.M,I4.M);
    CPPUNIT_ASSERT_EQUAL(I3.H,I4.H);
    CPPUNIT_ASSERT_EQUAL(I3.I,I4.I);

    //Check only transformation
    Vector p;
    random(p);
    I3 = I2.RefPoint(p);
    I4 = I3.RefPoint(-p);
    CPPUNIT_ASSERT_EQUAL(I2.M,I4.M);
    CPPUNIT_ASSERT(I2.H.isApprox(I4.H));
    CPPUNIT_ASSERT(I2.I.isApprox(I4.I));
    T=Frame(-p);
    I4 = T*I2;
    CPPUNIT_ASSERT_EQUAL(I3.M,I4.M);
    CPPUNIT_ASSERT_EQUAL(I3.H,I4.H);
    CPPUNIT_ASSERT_EQUAL(I3.I,I4.I);

    random(T);
    I3=T*I2;
    I4=T.Inverse()*I3;

    Twist a;
    random(a);
    Wrench f=I2*a;
    CPPUNIT_ASSERT_EQUAL(T*f,(T*I2)*(T*a));

    random(T);
    I3 = T*I2;
    I4 = T.Inverse()*I3;
    CPPUNIT_ASSERT(I2.M.isApprox(I4.M));
    CPPUNIT_ASSERT(I2.H.isApprox(I4.H));
    CPPUNIT_ASSERT(I2.I.isApprox(I4.I));
}

max_stars_repo_name: numberen/apollo-platform

max_issues_repo_name: numberen/apollo-platform

max_forks_repo_name: numberen/apollo-platform