text:
/*
 * unit_test_feature.cpp
 *
 *  Created on: Mar 7, 2013
 *      Author: root
 */

#include "gtest/gtest.h"
#include <iostream>
#include <strings.h>

#include "xtreme/common/TcpEngine/ITcpMeasure.h"
#include "xtreme/common/internal/TcpEngine/Ccb_variables.h"
#include "xtreme/common/internal/TcpEngine/Ccb_buffer.h"
#include "xtreme/common/internal/TcpEngine/Ip_addr.h"
#include "xtreme/common/internal/TcpEngine/Connection.h"
#include "xtreme/common/internal/TcpEngine/ConnControlBlock.h"
#include "xtreme/common/counter/counter_types.h"
#include "xtreme/common/timestamp.h"
#include "xtreme/common/ipaddress.h"

#include <boost/foreach.hpp>
#include <boost/any.hpp>
#include <tbb/tick_count.h>
#include <tbb/compat/thread>
#include <ctime>
#include <sys/time.h>

using namespace xtreme::TcpEngine;
using namespace xtreme;

TEST(TcpEngine_size_object, max_min_datatypes) {
  std::cout << "max of uint32_t:" << std::numeric_limits<uint32_t>::max() << "\n";
  std::cout << "min of uint32_t:" << std::numeric_limits<uint32_t>::min() << "\n";
  std::cout << "min of float:" << std::numeric_limits<float>::min() << "\n";
  std::cout << "max of float: " << std::numeric_limits<float>::max() << "\n";
  float n6Gps = 6123456789.1234567;
/*  std::cout.setf( std::ios::fixed, std::ios::floatfield );
  std::cout.precision(1);*/
  std::cout << "6Gps of float: " <<  n6Gps << "\n";
}

class A {
private:
  float  v1;
  uint16_t v2;
  uint32_t v3;
};

TEST(TcpEngine_size_object, sizeof_Class_A) {
  std::cout << "size of A = " << sizeof(A) << "\n";
}

TEST(TcpEngine_size_object, sizeof_WindowFullVariables) {
  std::cout << "size of timestamp = " << sizeof(xtreme::Timestamp) << "\n";
  std::cout << "size of DupInFast_ccbv = " << sizeof(DupInFast_ccbv) << "\n";

  std::cout << "ccb_var_attempt:" << "\n";
  std::cout << (boost::format("sizeof(at) =%d;")% sizeof(Attempt_ccbv) ) << "\n";

  std::cout << "ccb_var_retries:" << "\n";
  std::cout << (boost::format("sizeof(at) =%d;")% sizeof(Retry_ccbv) ) << "\n";

  std::cout << "ccb_var_errocause:" << "\n";
  std::cout << (boost::format("sizeof(at) =%d;")% sizeof(ErrorCause_ccbv) ) << "\n";

  std::cout << "ccb_var_window_size:" << "\n";
  std::cout << (boost::format("sizeof(at) =%d;")% sizeof(WindowSet_ccbv) ) << "\n";

  std::cout << "ccb_var_window_usage:" << "\n";
  std::cout << (boost::format("sizeof(at) =%d;")% sizeof(WindowUsage_ccbv) ) << "\n";

  std::cout << "ccb_var_window_headroom:" << "\n";
  std::cout << (boost::format("sizeof(at) =%d;")% sizeof(WindowHeadroom_ccbv) ) << "\n";

  std::cout << "ccb_var_window_zero:" << "\n";
  std::cout << (boost::format("sizeof(at) =%d;")% sizeof(WindowZero_ccbv) ) << "\n";

  std::cout << "ccb_var_window_full:" << "\n";
  std::cout << (boost::format("sizeof(at) =%d;")% sizeof(WindowFull_ccbv) ) << "\n";

  std::cout << "ccb_var_transaction_time:" << "\n";
  std::cout << (boost::format("sizeof(at) =%d;")% sizeof(TransactionTime_ccbv) ) << "\n";

  std::cout << "ccb_var_rto:" << "\n";
  std::cout << (boost::format("sizeof(at) =%d;")% sizeof(RTO_ccbv) ) << "\n";

  std::cout << "ccb_var_rtt:" << "\n";
  std::cout << (boost::format("sizeof(at) =%d;")% sizeof(RTT_ccbv) ) << "\n";

  std::cout << "ccb_var_actual_thruput:" << "\n";
  std::cout << (boost::format("sizeof(at) =%d;")% sizeof(ActualThruput_ccbv) ) << "\n";

  std::cout << "ccb_var_connection:" << "\n";
  std::cout << (boost::format("sizeof(at) =%d;")% sizeof(Connection_ccbv) ) << "\n";

  std::cout << "ccb_var_rtx_thruput:" << "\n";
  std::cout << (boost::format("sizeof(at) =%d;")% sizeof(Rtx_ccbv) ) << "\n";

  std::cout << "ccb_var_fast_rtx:" << "\n";
  std::cout << (boost::format("sizeof(at) =%d;")% sizeof(FastRtx_ccbv) ) << "\n";

  std::cout << "ccb_var_flow_ccbv:" << "\n";
  std::cout << (boost::format("sizeof(at) =%d;")% sizeof(Flow_ccbv) ) << "\n";

  std::cout << "ccb_var_ack_ccbv:" << "\n";
  std::cout << (boost::format("sizeof(at) =%d;")% sizeof(AckedTable_ccbv) ) << "\n";

  std::cout << "ccb_var_total:" << "\n";
  std::cout << (boost::format("sizeof(at) =%d;")% sizeof(Total_ccbv) ) << "\n";

  std::cout << "ccb_var_fast_dup:" << "\n";
  std::cout << (boost::format("sizeof(at) =%d;")% sizeof(DupInFast_ccbv) ) << "\n";

  std::cout << "AckedTableVariable:" << "\n";
  std::cout << (boost::format("sizeof(at) =%d;")% sizeof(AckedTableVariable) ) << "\n";

  std::cout << "FlowVariable:" << "\n";
  std::cout << (boost::format("sizeof(at) =%d;")% sizeof(FlowVariable) ) << "\n";
  {
    std::cout << (boost::format("sizeof(SessionPair) =%d; sizeof(Connection)= %d; sizeof(ConnControlBlock)=%d; sizeof(TCP_unacked)=%d; sizeof(KeyOfAcked)=%d; sizeof(TCP_acked)=%d; ccbv bufer=%d")
    % sizeof(SessionPair) % sizeof(Connection)) % sizeof(ConnControlBlock) % sizeof(TCP_unacked) % sizeof(KeyOfAcked) % sizeof(TCP_acked) % sizeof_ccbvs << "\n";
  }
}

TEST(TcpEngine_IP_address, IPv4_parsing)
{
    Ip_addr ipv4("10.120.38.35");
    ASSERT_TRUE(ipv4.ToString() == "10.120.38.35");
    ASSERT_FALSE(ipv4.ipv6_version());
}

TEST(TcpEngine_IP_address, IPv6_parsing)
{
    Ip_addr ipv6("100:120:38:35:1258:a12:c00:88E4");
    std::string strRet = ipv6.ToString();
    std::cout << (boost::format("ip string is %s")% strRet.c_str()) << "\n";
    ASSERT_TRUE(strncasecmp(strRet.c_str(), "100:120:38:35:1258:a12:c00:88E4", strRet.length()) == 0);
    ASSERT_TRUE(ipv6.ipv6_version());
}

TEST(TcpEngine_IP_address, IPv6_abbr_parsing)
{
    Ip_addr ipv6("2001:db8::ff00:42:8239");
    std::string strRet = ipv6.ToString();
    std::cout << (boost::format("ip string is %s") % strRet.c_str())<< "\n";
    ASSERT_TRUE(strncasecmp(strRet.c_str(), "2001:db8::ff00:42:8239", strRet.length()) == 0);
    ASSERT_TRUE(ipv6.ipv6_version());
}

void cleanSessionContainer(SessionConnectionMap & conn_map){

    BOOST_FOREACH(SessionConnectionMap::right_reference rcl, conn_map.right){
        ConnectionInfoPtr cl = rcl.first;
        delete cl;
    }
    conn_map.clear();
}

TEST(TcpEngine_Session, Hashing_session_ipv4)
{
    SessionConnectionMap conn_map_;
    Ip_addr _src_addr("192.168.120.2");
    Ip_addr _dest_addr("192.168.120.6");
    IPAddress src_addr(*(uint32_t*)&(_src_addr.ip().ip6.s6_addr[12]));
    IPAddress dest_addr(*(uint32_t*)&(_dest_addr.ip().ip6.s6_addr[12]));

    std::cout << (boost::format("src:%s, dest:%s") % src_addr.ToString() %dest_addr.ToString() )<< "\n";
#ifdef COMMON_IP_ADDRESS
    SessionPairPtr sp = SessionPairPtr(
            new SessionPair(src_addr, dest_addr, 8080, 157,
                            (src_addr.type() == kIPV6)? SessionPair::ipv6 : SessionPair::ipv4));
#else
    SessionPairPtr sp = SessionPairPtr(
            new SessionPair(_src_addr, _dest_addr, 8080, 157,
                            _src_addr.ipv6_version()? SessionPair::ipv6 : SessionPair::ipv4));

#endif
    ITcpMeasure *ss = NULL;
    ConnectionInfoPtr current_connection_ = 0;
    SetCounterType countertypes_;
    //to find the session from the container
    SessionConnectionMap::left_map & maptype = conn_map_.left;
    std::cout << (boost::format("Find: src:%s, dest:%s") % sp->src_ip().ToString().c_str() % sp->dest_ip().ToString().c_str() )<< "\n";
    SessionConnectionMap::left_map::iterator iter = maptype.find(sp);
    if (iter != maptype.end()) {//find,
        current_connection_ = iter->second;
        ASSERT_FALSE(false);
    } else {
        /*
         * not find, and then create one
         */
        ss = ITcpMeasure::createTcpMeasure(10);
        current_connection_ = new Connection();
        current_connection_->createCCB(countertypes_);
        current_connection_->initFlow();
        std::cout << (boost::format("Insert: src:%s, dest:%s") % sp->src_ip().ToString().c_str() % sp->dest_ip().ToString().c_str() )<< "\n";
        conn_map_.insert(SessionConnectionMap::value_type(sp, current_connection_));
    }
    ASSERT_TRUE(conn_map_.size() == 1);

    Ip_addr _src_addr1("192.168.120.6");
    Ip_addr _dest_addr1("192.168.120.2");
    IPAddress src_addr1(*(uint32_t*)&(_src_addr1.ip().ip6.s6_addr[12]));
    IPAddress dest_addr1(*(uint32_t*)&(_dest_addr1.ip().ip6.s6_addr[12]));
#ifdef COMMON_IP_ADDRESS
    SessionPairPtr sp1 = SessionPairPtr(
            new SessionPair(src_addr1, dest_addr1, 157, 8080,
                            (src_addr1.type() == kIPV6)? SessionPair::ipv6 : SessionPair::ipv4));
#else
    SessionPairPtr sp1 = SessionPairPtr(
            new SessionPair(_src_addr1, _dest_addr1, 157, 8080,
                            (_src_addr1.ipv6_version())? SessionPair::ipv6 : SessionPair::ipv4));
#endif
    std::cout << (boost::format("Find: src:%s, dest:%s") % sp1->src_ip().ToString().c_str() % sp1->dest_ip().ToString().c_str() )<< "\n";
    iter = maptype.find(sp1);
    if (iter != maptype.end()) {//no find,
        ASSERT_TRUE(false);
    }

    //clean them all.
    delete ss;
    cleanSessionContainer(conn_map_);
}

TEST(TcpEngine_Session, Hashing_session_ipv6)
{
    SessionConnectionMap conn_map_;
    Ip_addr _src_addr("100:120:38:35:1258:a12:c00:88E4");
    Ip_addr _dest_addr("100:120:38:35:1258:a12:c00:88EE");
    IPAddress src_addr(_src_addr.ip().ip6.s6_addr);
    IPAddress dest_addr(_dest_addr.ip().ip6.s6_addr);
    std::cout << (boost::format("src:%s, dest:%s") % src_addr.ToString() %dest_addr.ToString() )<< "\n";
#ifdef COMMON_IP_ADDRESS
    SessionPairPtr sp = SessionPairPtr(
            new SessionPair(src_addr, dest_addr, 8080, 157,
                            (src_addr.type() == kIPV6)? SessionPair::ipv6 : SessionPair::ipv4));
#else
    SessionPairPtr sp = SessionPairPtr(
            new SessionPair(_src_addr, _dest_addr, 8080, 157,
                            (_src_addr.ipv6_version())? SessionPair::ipv6 : SessionPair::ipv4));

#endif
    ITcpMeasure *ss = NULL;
    ConnectionInfoPtr current_connection_ = 0;
    SetCounterType countertypes_;
    //to find the session from the container
    SessionConnectionMap::left_map & maptype = conn_map_.left;
    std::cout << (boost::format("Find: src:%s, dest:%s") % sp->src_ip().ToString().c_str() % sp->dest_ip().ToString().c_str() )<< "\n";
    SessionConnectionMap::left_map::iterator iter = maptype.find(sp);
    if (iter != maptype.end()) {//find,
        current_connection_ = iter->second;
        ASSERT_FALSE(false);
    } else {
        /*
         * not find, and then create one
         */
        ss = ITcpMeasure::createTcpMeasure(10); //todo..., to delete this ss.
        current_connection_ = new Connection();
        current_connection_->createCCB(countertypes_);
        current_connection_->initFlow();
        std::cout << (boost::format("Insert: src:%s, dest:%s") % sp->src_ip().ToString().c_str() % sp->dest_ip().ToString().c_str() )<< "\n";
        conn_map_.insert(SessionConnectionMap::value_type(sp, current_connection_));
    }
    ASSERT_TRUE(conn_map_.size() == 1);

    Ip_addr _src_addr1("100:120:38:35:1258:a12:c00:88E4");
    Ip_addr _dest_addr1("100:120:38:35:1258:a12:c00:88EE");
    IPAddress src_addr1(_src_addr1.ip().ip6.s6_addr);
    IPAddress dest_addr1(_dest_addr1.ip().ip6.s6_addr);
#ifdef COMMON_IP_ADDRESS
    SessionPairPtr sp1 = SessionPairPtr(
            new SessionPair(src_addr1, dest_addr1, 8080, 157,
                            (src_addr1.type() == kIPV6)? SessionPair::ipv6 : SessionPair::ipv4));
#else
    SessionPairPtr sp1 = SessionPairPtr(
            new SessionPair(_src_addr1, _dest_addr1, 8080, 157,
                            (_src_addr1.ipv6_version())? SessionPair::ipv6 : SessionPair::ipv4));
#endif
    std::cout << (boost::format("Find: src:%s, dest:%s") % sp1->src_ip().ToString().c_str() % sp1->dest_ip().ToString().c_str() )<< "\n";
    iter = maptype.find(sp1);
    if (iter == maptype.end()) {//no find,
        ASSERT_TRUE(false);
    }

    //clean them all.
    delete ss;
    cleanSessionContainer(conn_map_);
}

TEST(TcpEngine_Session, SessionMap_unique_relation_1toMany){
    SessionConnectionMap conn_map_;
    Ip_addr _src_addr("192.168.120.2");
    Ip_addr _dest_addr("192.168.120.6");
    IPAddress src_addr(*(uint32_t*)&(_src_addr.ip().ip6.s6_addr[12]));
    IPAddress dest_addr(*(uint32_t*)&(_dest_addr.ip().ip6.s6_addr[12]));
#ifdef COMMON_IP_ADDRESS
    SessionPairPtr sp = SessionPairPtr(
            new SessionPair(src_addr, dest_addr, 8080, 157,
                            (src_addr.type() == kIPV6)? SessionPair::ipv6 : SessionPair::ipv4));
#else
    SessionPairPtr sp = SessionPairPtr(
            new SessionPair(_src_addr, _dest_addr, 8080, 157,
                            _src_addr.ipv6_version()? SessionPair::ipv6 : SessionPair::ipv4));
#endif
    ConnectionInfoPtr current_connection_ = 0;
    SetCounterType countertypes_;
    ITcpMeasure *ss = ITcpMeasure::createTcpMeasure(10); //todo... to clean this ss
    for (int i = 0; i < 2 ; i++){

        current_connection_ = new Connection();
        current_connection_->createCCB(countertypes_);
        current_connection_->initFlow();
        std::cout << (boost::format("Insert: src:%s, dest:%s") % sp->src_ip().ToString().c_str() % sp->dest_ip().ToString().c_str() )<< "\n";
        conn_map_.insert(SessionConnectionMap::value_type(sp, current_connection_));
    }
    ASSERT_TRUE(conn_map_.size() == 1);

    cleanSessionContainer(conn_map_);
    delete ss;
}

TEST(TcpEngine_Session, SessionMap_unique_relation_manytoMany) {
    SessionConnectionMap conn_map_;
    static size_t nSessionSize = 3;
    ITcpMeasure *ss = ITcpMeasure::createTcpMeasure(10); //todo... to clean this ss
    for (size_t i = 0; i < nSessionSize; i++) {
        std::string src("192.168.120.");
        std::stringstream sstemp;
        sstemp << i;
        src += sstemp.str();
        Ip_addr _src_addr(src);
        Ip_addr _dest_addr("192.168.120.6");
        IPAddress src_addr(*(uint32_t*)&(_src_addr.ip().ip6.s6_addr[12]));
        IPAddress dest_addr(*(uint32_t*)&(_dest_addr.ip().ip6.s6_addr[12]));
#ifdef COMMON_IP_ADDRESS
        SessionPairPtr sp = SessionPairPtr(
                new SessionPair(src_addr, dest_addr, 8080, 157,
                                (src_addr.type() == kIPV6)? SessionPair::ipv6 : SessionPair::ipv4));
#else
        SessionPairPtr sp = SessionPairPtr(
                new SessionPair(_src_addr, _dest_addr, 8080, 157,
                                _src_addr.ipv6_version()? SessionPair::ipv6 : SessionPair::ipv4));
#endif

        ConnectionInfoPtr current_connection_ = 0;
        SetCounterType countertypes_;

        current_connection_ = new Connection();
        current_connection_->createCCB(countertypes_);
        current_connection_->initFlow();
        std::cout << (boost::format("Insert: src:%s, dest:%s") % sp->src_ip().ToString().c_str() % sp->dest_ip().ToString().c_str() )<< "\n";
        conn_map_.insert(SessionConnectionMap::value_type(sp, current_connection_));
    }
    ASSERT_TRUE(conn_map_.size() == nSessionSize);

    cleanSessionContainer(conn_map_);
    delete ss;
}

#ifndef LIMIT_ON_ACK_TABLE
//testing for Acked_table
TEST(TcpEngine_Acked_table, Acked_table_Hash_insert){
    Acked_table at;
    static size_t nSize = 3;
    TCP_acked  ta;
    for (size_t i = 0; i < nSize ; i++){
        KeyOfAcked ka = boost::make_tuple<>(i, 5+i, 5-i);
        at.insert(Acked_table::value_type(ka, &ta));
    }
    ASSERT_TRUE(at.size() == nSize);
}

TEST(TcpEngine_Acked_table, Acked_table_Hash_find){
    Acked_table at;
    static size_t nSize = 3;
    TCP_acked  ta;
    for (size_t i = 0; i < nSize ; i++){
        KeyOfAcked ka = boost::make_tuple<>(i, 5+i, 5-i);
        at.insert(Acked_table::value_type(ka, &ta));
    }

    Acked_table::iterator it = at.begin();
    it = at.find(boost::make_tuple<>(1, 6, 4));
    ASSERT_TRUE(it != at.end());

    it = at.find(boost::make_tuple<>(0, 6, 5));
    ASSERT_FALSE(it != at.end());
}
//end of testing to Acked_table;
#endif

#define nMaxLoop    50
static unsigned char buffer[nMaxLoop];

int compare (const void * a, const void * b) {
    return ( *(unsigned char*)a - *(unsigned char*)b );
}

TEST(test_performance, which_is_fast_tbb){
    //initialize array with random number
    for(int nindex=0; nindex<nMaxLoop; ++nindex)
        buffer[nindex] = rand() % 255;

    tbb::tick_count start, stop;
    //do the checksum count on array data
    //------------------------------------------------------------------------------------
    int64_t sum = 0;
    start = tbb::tick_count::now();
    for(int nindex=0; nindex<nMaxLoop; ++nindex) {
        if (buffer[nindex] > 0)
            sum += buffer[nindex];
    }
    stop = tbb::tick_count::now();
    std::cout << "sum:" << sum << "  Total unsort: " << (stop-start).seconds() << std::endl;

    //sort the array then do checksum
    //------------------------------------------------------------------------------------
    sum = 0;
    qsort (buffer, nMaxLoop, sizeof(char), compare);
    start = tbb::tick_count::now();
    for(int nindex=0; nindex<nMaxLoop; ++nindex) {
        if (buffer[nindex] > 0)
            sum += buffer[nindex];
    }
    stop = tbb::tick_count::now();
    std::cout << "sum:" << sum << "  Total sorted: " << (stop-start).seconds() << std::endl;
}

TEST(test_performance, which_is_fast_clock){
    //initialize array with random number
    for(int nindex=0; nindex<nMaxLoop; ++nindex)
        buffer[nindex] = rand() % 255;

    clock_t start, stop;
    //do the checksum count on array data
    //------------------------------------------------------------------------------------
    int64_t sum = 0;
    start = clock();
    for(int nindex=0; nindex<nMaxLoop; ++nindex) {
        if (buffer[nindex] > 0)
            sum += buffer[nindex];
    }
    stop = clock();
    std::cout << "sum:" << sum << "  Total unsort: " << ((double)(stop-start))/CLOCKS_PER_SEC << std::endl;

    //sort the array then do checksum
    //------------------------------------------------------------------------------------
    sum = 0;
    qsort (buffer, nMaxLoop, sizeof(char), compare);
    start = clock();
    for(int nindex=0; nindex<nMaxLoop; ++nindex) {
        if (buffer[nindex] > 0)
            sum += buffer[nindex];
    }
    stop = clock();
    std::cout << "sum:" << sum << "  Total sorted: " << ((double)(stop-start))/CLOCKS_PER_SEC << std::endl;
}
#include "xtreme/common/utils.h"
TEST(TcpEngine, test_kama_convert_sting) {
  std::string value0 = xtreme::convert_to_string<double>(0);
  std::cout << "convert_to_string<double>(0) = " << value0 << "\n";
  std::string value1 = xtreme::convert_to_string<int>(0.1);
  std::cout << "convert_to_string<int>(0.1) = " << value1 << "\n";
  std::string value2 = xtreme::convert_to_string<float>(10);
  ASSERT_EQ(value2.compare("10.0"), 0);
  std::cout << "convert_to_string<float>(10) = " << value2 << "\n";
  std::string value3 = xtreme::convert_to_string<bool>(true);
  std::cout << "convert_to_string<bool>(false) = " << value3 << "\n";

}

const uint32_t g_max_random_value = 10000;
#include <boost/random.hpp>
#include <boost/generator_iterator.hpp>

TEST(TCPEngine, test_sessionpair_hash_exisiting)
{
  std::set<size_t> set_of_hashresult;
  typedef boost::mt19937 RNGType;
  RNGType rng;
  boost::uniform_int<> zero_to_n( 0, g_max_random_value );
  boost::variate_generator< RNGType, boost::uniform_int<> > dice(rng, zero_to_n);

  tbb::tick_count start, stop;
  start = tbb::tick_count::now();
  for (uint32_t i = 0 ; i < g_max_random_value; i++ ){
    int n  = dice();
    Ip_addr _src_ip((in_addr_t) n), _dest_ip((in_addr_t) n + i);
    IPAddress src_ip(*(uint32_t*)&(_src_ip.ip().ip6.s6_addr[12]));
    IPAddress dest_ip(*(uint32_t*)&(_dest_ip.ip().ip6.s6_addr[12]));
#ifdef COMMON_IP_ADDRESS
    SessionPair sp(src_ip, dest_ip, 8080 + i, 157 + i,
                   (src_ip.type() == kIPV6)? SessionPair::ipv6 : SessionPair::ipv4);
#else
    SessionPair sp(_src_ip, _dest_ip, 8080 + i, 157 + i,
                   _src_ip.ipv6_version()? SessionPair::ipv6 : SessionPair::ipv4);
#endif
    size_t hash_rsult = sp.hash_1();
    set_of_hashresult.insert(hash_rsult);
  }
  stop = tbb::tick_count::now();
  std::cout << "hash_exisiting time consuming(secs): " << (stop-start).seconds() << std::endl;

  ASSERT_GT(set_of_hashresult.size(), g_max_random_value-300);
}

TEST(TCPEngine, test_sessionpair_hash_hj)
{
  std::set<size_t> set_of_hashresult;
  std::set<size_t> set_of_seeds;
  typedef boost::mt19937 RNGType;
  RNGType rng;
  boost::uniform_int<> zero_to_n( 0, g_max_random_value );
  boost::variate_generator< RNGType, boost::uniform_int<> > dice(rng, zero_to_n);

  tbb::tick_count start, stop;
  start = tbb::tick_count::now();
  for (uint32_t i = 0 ; i < g_max_random_value; i++ ){
    int n  = dice();
    set_of_seeds.insert(n);
    Ip_addr _src_ip((in_addr_t) n), _dest_ip((in_addr_t) n + i);
    IPAddress src_ip(*(uint32_t*)&(_src_ip.ip().ip6.s6_addr[12]));
    IPAddress dest_ip(*(uint32_t*)&(_dest_ip.ip().ip6.s6_addr[12]));
#ifdef COMMON_IP_ADDRESS
    SessionPair sp(src_ip, dest_ip, n + i, 157 + i,
                   (src_ip.type() == kIPV6)? SessionPair::ipv6 : SessionPair::ipv4);
#else
    SessionPair sp(_src_ip, _dest_ip, n + i, 157 + i,
                   _src_ip.ipv6_version()? SessionPair::ipv6 : SessionPair::ipv4);
#endif
    size_t hash_rsult = sp.hash_2();
    set_of_hashresult.insert(hash_rsult);
  }
  stop = tbb::tick_count::now();
  std::cout << "hash_hj time consuming(secs): " << (stop-start).seconds() << std::endl;

  ASSERT_GT(set_of_hashresult.size(), g_max_random_value-10);
}

TEST(TCPEngine, test_sessionpair_hash_wireshark)
{
  std::set<size_t> set_of_hashresult;
  std::set<size_t> set_of_seeds;
  typedef boost::mt19937 RNGType;
  RNGType rng;
  boost::uniform_int<> zero_to_n( 0, g_max_random_value );
  boost::variate_generator< RNGType, boost::uniform_int<> > dice(rng, zero_to_n);

  tbb::tick_count start, stop;
  start = tbb::tick_count::now();
  for (uint32_t i = 0 ; i < g_max_random_value; i++ ){
    int n  = dice();
    set_of_seeds.insert(n);
    Ip_addr _src_ip((in_addr_t) n), _dest_ip((in_addr_t) n + i);
    IPAddress src_ip(*(uint32_t*)&(_src_ip.ip().ip6.s6_addr[12]));
    IPAddress dest_ip(*(uint32_t*)&(_dest_ip.ip().ip6.s6_addr[12]));
#ifdef COMMON_IP_ADDRESS
    SessionPair sp(src_ip, dest_ip, n + i, 157 + i,
                   (src_ip.type() == kIPV6)? SessionPair::ipv6 : SessionPair::ipv4);
#else
    SessionPair sp(_src_ip, _dest_ip, n + i, 157 + i,
                   _src_ip.ipv6_version()? SessionPair::ipv6 : SessionPair::ipv4);
#endif
    size_t hash_rsult = sp.hash_3();
    set_of_hashresult.insert(hash_rsult);
  }
  stop = tbb::tick_count::now();
  std::cout << "hash_wireshark time consuming(secs): " << (stop-start).seconds() << std::endl;

  //conflict is about 1%
  ASSERT_GT(set_of_hashresult.size(), g_max_random_value-100);
}

TEST(TCPEngine, test_sessionpair_hash_iphash)
{
  std::set<size_t> set_of_hashresult;
  std::set<size_t> set_of_seeds;
  typedef boost::mt19937 RNGType;
  RNGType rng;
  boost::uniform_int<> zero_to_n( 0, g_max_random_value );
  boost::variate_generator< RNGType, boost::uniform_int<> > dice(rng, zero_to_n);

  tbb::tick_count start, stop;
  start = tbb::tick_count::now();
  for (uint32_t i = 0 ; i < g_max_random_value; i++ ){
    int n  = dice();
    set_of_seeds.insert(n);
    Ip_addr _src_ip((in_addr_t) n), _dest_ip((in_addr_t) n + i);
    IPAddress src_ip(*(uint32_t*)&(_src_ip.ip().ip6.s6_addr[12]));
    IPAddress dest_ip(*(uint32_t*)&(_dest_ip.ip().ip6.s6_addr[12]));
#ifdef COMMON_IP_ADDRESS
    SessionPair sp(src_ip, dest_ip, n + i, 157 + i,
                   (src_ip.type() == kIPV6)? SessionPair::ipv6 : SessionPair::ipv4);
#else
    SessionPair sp(_src_ip, _dest_ip, n + i, 157 + i,
                   _src_ip.ipv6_version()? SessionPair::ipv6 : SessionPair::ipv4);
#endif
    size_t hash_rsult = sp.hash_4();
    set_of_hashresult.insert(hash_rsult);
  }
  stop = tbb::tick_count::now();
  std::cout << "hash_iphash time consuming(secs): " << (stop-start).seconds() << std::endl;

  // the conflict ratio is about 0.5%
  ASSERT_GT(set_of_hashresult.size(), g_max_random_value-50);
}

TEST(TCPEngine, ack_table_time_eviction_KeyOfAcked_Hash){
  uint32_t num, seq, ack;
  uint32_t MAX_LOOP = 10000;
  std::set<size_t> setof_result;
  for (uint32_t i = 0 ; i < MAX_LOOP; i++) {
    num = i;
    seq = i + 1;
    ack = i+ 2;
    KeyOfAcked acke_key = boost::tuples::make_tuple<uint32_t, seqno, ackno>(num, seq, ack);
    KeyOfAcked_Hash kh;
    setof_result.insert(kh(acke_key));
  }
  ASSERT_EQ(MAX_LOOP, setof_result.size());
}

static uint32_t g_timeout = 5;

#ifdef LIMIT_ON_ACK_TABLE

#define acked_table_batch_aging_size  10

Acked_table * get_ack_table(uint32_t max_Loop, uint32_t act_table_size) {
  Acked_table *acked_table = new Acked_table(create_tcp_ack, delete_tcp_ack, compare_tcp_ack, g_timeout, act_table_size, acked_table_batch_aging_size);
  TCP_acked *pTa = NULL;
  uint32_t num, seq, ack;
  for (uint32_t i = 0 ; i < max_Loop; i++) {
    num = i;
    seq = i + 1;
    ack = i+ 2;
    KeyOfAcked acke_key = boost::tuples::make_tuple<uint32_t, seqno, ackno>(num, seq, ack);
    struct timespec time_now;
    clock_gettime(CLOCK_REALTIME, &time_now);
    if ((*acked_table)(acke_key, pTa, time_now)) {
    }
  }
  return acked_table;
}

class KeyArrays:public std::vector<KeyOfAcked>{
};
bool operator==(const KeyArrays &s1, const KeyArrays &s2) {
  if (s2.size() != s1.size()) {
    return false;
  }
  for (size_t i = 0; i < s1.size(); i++) {
    KeyOfAcked_Equal ss;
    if (!ss(s1[i], s2[i])) {
      return false;
    }
  }
  return true;
}
TEST(TCPEngine, ack_table_time_eviction_size)
{
  uint32_t MAX_LOOP = 100;
  Acked_table * acked_table = get_ack_table(MAX_LOOP, MAX_LOOP);

  ASSERT_EQ(acked_table->size(), MAX_LOOP);
  acked_table->Clear();
  delete acked_table;
}

TEST(TCPEngine, ack_table_time_eviction_perforance_insert)
{
  uint32_t MAX_LOOP = 10000;
  uint32_t num, seq, ack;
  Acked_table * acked_table = get_ack_table(MAX_LOOP, MAX_LOOP);
  ASSERT_EQ(MAX_LOOP, acked_table->size());
  TCP_acked *pTa = NULL;
  tbb::tick_count start, stop;
  start = tbb::tick_count::now();
  for (uint32_t i = 0 ;i < MAX_LOOP; i++) {
    pTa = NULL;
    num = i;
    seq = i + 1;
    ack = i+ 2;
    KeyOfAcked acke_key = boost::tuples::make_tuple<uint32_t, seqno, ackno>(num, seq, ack);
    if (false == acked_table->find(acke_key, pTa)) {
      ASSERT_TRUE(false);
    }
  }
  stop = tbb::tick_count::now();
  std::cout << "LRU time_eviction search " <<  MAX_LOOP << " times, consuming(secs): " << (stop-start).seconds() << std::endl;

  start = tbb::tick_count::now();
  acked_table->Clear();
  stop = tbb::tick_count::now();
  std::cout << "LRU time_eviction delete " <<  MAX_LOOP << " times, consuming(secs): " << (stop-start).seconds() << std::endl;
  delete acked_table;
}
TEST(TCPEngine, ack_table_time_eviction_insert)
{
  uint32_t MAX_LOOP = 3;
  uint32_t num, seq, ack;
  Acked_table * acked_table = get_ack_table(MAX_LOOP, 100);
  ASSERT_EQ(MAX_LOOP, acked_table->size());
  TCP_acked *pTa = NULL;
  tbb::tick_count start, stop;
  for (uint32_t i = 0 ;i < MAX_LOOP; i++) {
    pTa = NULL;
    num = i;
    seq = i + 1;
    ack = i+ 2;
    KeyOfAcked acke_key = boost::tuples::make_tuple<uint32_t, seqno, ackno>(num, seq, ack);
    if (false == acked_table->find(acke_key, pTa)) {
      ASSERT_TRUE(false);
    }
  }

  ASSERT_TRUE(acked_table->find(boost::tuples::make_tuple<uint32_t, seqno, ackno>(2, 3, 4), pTa) );
  if (pTa) {
    pTa->frame_timestamp_.tv_sec -= 31;

  }
  ASSERT_TRUE(acked_table->find(boost::tuples::make_tuple<uint32_t, seqno, ackno>(1, 2, 3), pTa) );
  if (pTa) {
    pTa->frame_timestamp_.tv_sec -= 2;

  }
  {
    KeyArrays expected;
    expected.push_back(boost::tuples::make_tuple<uint32_t, seqno, ackno>(1, 2, 3));
    expected.push_back(boost::tuples::make_tuple<uint32_t, seqno, ackno>(2, 3, 4));
    expected.push_back(boost::tuples::make_tuple<uint32_t, seqno, ackno>(0, 1, 2));
    KeyArrays actual;
    acked_table->get_keys(std::back_inserter(actual));
    ASSERT_TRUE(actual == expected);
  }
  acked_table->Clear();
  delete acked_table;
}
TEST(TCPEngine, ack_table_time_eviction_search)
{
  uint32_t MAX_LOOP = 10000;
  uint32_t num, seq, ack;
  Acked_table * acked_table = get_ack_table(MAX_LOOP, MAX_LOOP);
  ASSERT_EQ(MAX_LOOP, acked_table->size());
  TCP_acked *pTa = NULL;
  tbb::tick_count start, stop;
  start = tbb::tick_count::now();
  for (uint32_t i = 0 ;i < MAX_LOOP; i++) {
    pTa = NULL;
    num = i;
    seq = i + 1;
    ack = i+ 2;
    KeyOfAcked acke_key = boost::tuples::make_tuple<uint32_t, seqno, ackno>(num, seq, ack);
    if (false == acked_table->find(acke_key, pTa)) {
      ASSERT_TRUE(false);
    }
  }
  stop = tbb::tick_count::now();
  std::cout << "LRU time_eviction search " <<  MAX_LOOP << " times, consuming(secs): " << (stop-start).seconds() << std::endl;

  start = tbb::tick_count::now();
  acked_table->Clear();
  stop = tbb::tick_count::now();
  std::cout << "LRU time_eviction delete " <<  MAX_LOOP << " times, consuming(secs): " << (stop-start).seconds() << std::endl;
  delete acked_table;
}

TEST(TCPEngine, ack_table_time_eviction_aging_out_by_timeout)
{
  uint32_t MAX_LOOP = 3;
  uint32_t num, seq, ack;
  Acked_table * acked_table = get_ack_table(MAX_LOOP, 100);
  ASSERT_EQ(MAX_LOOP, acked_table->size());
  TCP_acked *pTa = NULL;
  tbb::tick_count start, stop;
  for (uint32_t i = 0 ;i < MAX_LOOP; i++) {
    pTa = NULL;
    num = i;
    seq = i + 1;
    ack = i+ 2;
    KeyOfAcked acke_key = boost::tuples::make_tuple<uint32_t, seqno, ackno>(num, seq, ack);
    if (false == acked_table->find(acke_key, pTa)) {
      ASSERT_TRUE(false);
    }
  }

  /*
   * after g_timeout sec, insert a new one, the first one will be removed.
   */
  //std::this_thread::sleep_for( tbb::tick_count::interval_t(30) );
  sleep(g_timeout+1);
  struct timespec time_now;
  clock_gettime(CLOCK_REALTIME, &time_now);
  KeyOfAcked acke_key = boost::tuples::make_tuple<uint32_t, seqno, ackno>(100, 111, 222);
  if (!(*acked_table)(acke_key, pTa, time_now)) {
    ASSERT_TRUE(false);
  }

  /*
   * check whether the first one is deleted or not.
   */
  ASSERT_FALSE(acked_table->find(boost::tuples::make_tuple<uint32_t, seqno, ackno>(0, 1, 2), pTa) );

  /*
   * check the list in the container by keys
   */
  {
    KeyArrays expected;
    expected.push_back(boost::tuples::make_tuple<uint32_t, seqno, ackno>(100, 111, 222));
    expected.push_back(boost::tuples::make_tuple<uint32_t, seqno, ackno>(2, 3, 4));
    expected.push_back(boost::tuples::make_tuple<uint32_t, seqno, ackno>(1, 2, 3));
    KeyArrays actual;
    acked_table->get_keys(std::back_inserter(actual));
    ASSERT_TRUE(actual == expected);
  }

  start = tbb::tick_count::now();
  acked_table->Clear();
  stop = tbb::tick_count::now();
  std::cout << "LRU time_eviction delete " <<  MAX_LOOP << " times, consuming(secs): " << (stop-start).seconds() << std::endl;
  delete acked_table;
}

TEST(TCPEngine, ack_table_time_eviction_batch_ageing_out)
{
  uint32_t MAX_LOOP = 16;
  Acked_table * acked_table = get_ack_table(MAX_LOOP, 4);
  ASSERT_EQ((unsigned long)(MAX_LOOP - acked_table_batch_aging_size), (unsigned long)acked_table->size());
}

TEST(TCPEngine, ack_table_time_eviction_ageing_out_by_number)
{
  uint32_t MAX_LOOP = 16;
  uint32_t num, seq, ack;
  Acked_table * acked_table = get_ack_table(MAX_LOOP, 5);

  TCP_acked *pTa = NULL;
  tbb::tick_count start, stop;
  for (uint32_t i = 10 ;i < MAX_LOOP; i++) {
    pTa = NULL;
    num = i;
    seq = i + 1;
    ack = i+ 2;
    KeyOfAcked acke_key = boost::tuples::make_tuple<uint32_t, seqno, ackno>(num, seq, ack);
    if (false == acked_table->find(acke_key, pTa)) {
      ASSERT_TRUE(false);
    }
  }

  /*
   * check whether the first one is deleted or not.
   */
  ASSERT_FALSE(acked_table->find(boost::tuples::make_tuple<uint32_t, seqno, ackno>(0, 1, 2), pTa) );

  /*
   * check the list in the container by keys, the old ones are removed, only left the from 10~16
   */
  {
    KeyArrays expected;
    expected.push_back(boost::tuples::make_tuple<uint32_t, seqno, ackno>(4, 5, 6));
    expected.push_back(boost::tuples::make_tuple<uint32_t, seqno, ackno>(3, 4, 5));
    expected.push_back(boost::tuples::make_tuple<uint32_t, seqno, ackno>(2, 3, 4));
    expected.push_back(boost::tuples::make_tuple<uint32_t, seqno, ackno>(1, 2, 3));
    KeyArrays actual;
    acked_table->get_keys(std::back_inserter(actual));
    ASSERT_FALSE(actual == expected);
  }

  start = tbb::tick_count::now();
  acked_table->Clear();
  stop = tbb::tick_count::now();
  std::cout << "LRU time_eviction delete " <<  MAX_LOOP << " times, consuming(secs): " << (stop-start).seconds() << std::endl;
  delete acked_table;
}

#endif

int main(int argc, char **argv)
{
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}


text:
#include <boost/property_tree/exceptions.hpp>
#include <boost/property_tree/id_translator.hpp>
#include <boost/property_tree/info_parser.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree_fwd.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ptree_serialization.hpp>
#include <boost/property_tree/stream_translator.hpp>
#include <boost/property_tree/string_path.hpp>
#include <boost/property_tree/xml_parser.hpp>

int
main ()
{
  return 0;
}

ext: cpp


text:
//==============================================================================
//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011 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
//==============================================================================
#ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_SCALAR_DIVFIX_HPP_INCLUDED
#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SCALAR_DIVFIX_HPP_INCLUDED

#include <boost/simd/arithmetic/functions/divfix.hpp>
#include <boost/simd/include/functions/scalar/trunc.hpp>
#include <boost/simd/include/constants/zero.hpp>
#include <boost/simd/include/constants/valmin.hpp>
#include <boost/simd/include/constants/valmax.hpp>
#include <boost/dispatch/attributes.hpp>

namespace boost { namespace simd { namespace ext
{
  BOOST_DISPATCH_IMPLEMENT         ( divfix_, tag::cpu_
                                   , (A0)
                                   , (scalar_< signed_<A0> >)
                                     (scalar_< signed_<A0> >)
                                   )
  {
    typedef A0 result_type;

    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)
    {
      if (!a0) return  Zero<result_type>();
      if(a1)
      {
        return a0/a1;
      }
      else
        return ((a0>0) ? Valmax<result_type>() : Valmin<result_type>());

    }
  };

  BOOST_DISPATCH_IMPLEMENT         ( divfix_, tag::cpu_
                                   , (A0)
                                   , (scalar_< unsigned_<A0> >)
                                     (scalar_< unsigned_<A0> >)
                                   )
  {
    typedef A0 result_type;
    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)
    {
      if (!a0) return  Zero<result_type>();
      if(a1)
      {
        return a0/a1;
      }
      else
        return Valmax<result_type>();

    }
  };

#ifdef BOOST_MSVC
  #pragma warning(push)
  #pragma warning(disable: 4723) // potential divide by 0
#endif

  BOOST_DISPATCH_IMPLEMENT         ( divfix_, tag::cpu_
                                   , (A0)
                                   , (scalar_< floating_<A0> >)
                                     (scalar_< floating_<A0> >)
                                   )
  {
    typedef A0 result_type;
    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)
    {
      return trunc(a0/a1);
    }
  };

#ifdef BOOST_MSVC
  #pragma warning(pop)
#endif

} } }

#endif

ext: hpp


text:
#include <boost/test/unit_test.hpp>

#include "logs.h"
#include "route.h"
#include "track.h"

using namespace GPS;

BOOST_AUTO_TEST_SUITE( Track_TravellingTime )

const bool isFileName = true;

//This checks the travel time is correct when the time duration is set to 1 seconds
//with route A1B2C
BOOST_AUTO_TEST_CASE ( duration_1_sec )
{
    Track track = Track(LogFiles::GPXTracksDir + "TrackDuration1.gpx", isFileName);
    BOOST_CHECK_EQUAL(track.travellingTime(), 3);
}

//This checks the travel time is correct when the time duration is set to 10 seconds
//with route A3B1C
BOOST_AUTO_TEST_CASE ( duration_10_sec )
{
    Track track = Track(LogFiles::GPXTracksDir + "TrackDuration10.gpx", isFileName);
    BOOST_CHECK_EQUAL(track.travellingTime(), 40);
}

//this checks the travel time is correct when the time duration is set to an even number, 2 in this case
//with route A4B2C
BOOST_AUTO_TEST_CASE( duration_2_sec)
{
    Track track = Track(LogFiles::GPXTracksDir + "TrackDurationEven.gpx", isFileName);
    BOOST_CHECK_EQUAL(track.travellingTime(), 12);
}

//this checks the travel time is correct when the time duration is set to an odd number, 7 in this case
//with route M3A2G
BOOST_AUTO_TEST_CASE ( duration_7_sec)
{
    Track track = Track(LogFiles::GPXTracksDir + "TrackDurationOdd.gpx", isFileName);
    BOOST_CHECK_EQUAL(track.travellingTime(), 35);
}

//This test checks the travel time when the time unit duration and interval is 1
BOOST_AUTO_TEST_CASE ( duration_interval_1 )
{
    Track track = Track(LogFiles::GPXTracksDir + "TrackI&D1.gpx", isFileName);
    BOOST_CHECK_EQUAL(track.travellingTime(), 6);
}

//This test checks the travel time when the Log interval is set to 10
BOOST_AUTO_TEST_CASE ( interval_10 )
{
    Track track = Track(LogFiles::GPXTracksDir + "TrackInterval10.gpx", isFileName);
    BOOST_CHECK_EQUAL(track.travellingTime(), 60);
}

/*This test checks that an error is thrown when the log interval is a negative number
because if the log interval is set a negative number then the GPX log becomes corrupted
and doesn't show the correct track*/
BOOST_AUTO_TEST_CASE ( interval_negative )
{
    Track track = Track(LogFiles::GPXTracksDir + "TrackIntervalNegative.gpx", isFileName);
    BOOST_CHECK_THROW(track.travellingTime(), std::invalid_argument);
}

/*This test checks that the correct travel time is produced when log interval is a multiple
 *of the duration and they're both odd numbers*/
BOOST_AUTO_TEST_CASE ( interval_multiple_of_duration )
{
    Track track = Track(LogFiles::GPXTracksDir + "TrackI&DMultiples.gpx", isFileName);
    BOOST_CHECK_EQUAL(track.travellingTime(), 45);
}

/*This test checks if an error is thrown when
 *the log interval and the duration are odd numbers and if they're not multiples.
  The logs produced don't produce the correct number of logs to calculate the travelling time*/
BOOST_AUTO_TEST_CASE( interval_not_multiple_of_duration_odd )
{
    Track track = Track(LogFiles::GPXTracksDir + "TrackI&DNotMultiples.gpx", isFileName);
    BOOST_CHECK_THROW(track.travellingTime(), std::invalid_argument);
}

/*the purpose of this test is to check that the duration is an even number and that
 * the log interval is a factor of the duration while remaining to be equal to
 * or less than half of the duration. This is because if the log interval is more than half
 * of the duration it'll produce incorrect logs and if it is not a factor it also produces incorrect
 * logs
 */
BOOST_AUTO_TEST_CASE( interval_factor_of_duration_and_less_than_half_of_duration )
{
    Track track = Track(LogFiles::GPXTracksDir + "TrackIntervalEvenlessthanhalf.gpx", isFileName);
    BOOST_CHECK_EQUAL(track.travellingTime(), 100);
}

/*This test checks the travel time when the absolute start time is a number beyond 1
as the absolute start time can be a positive value*/
BOOST_AUTO_TEST_CASE ( absolute_1 )
{
    Track track = Track(LogFiles::GPXTracksDir + "TrackAbsoluteTime1.gpx", isFileName);
    BOOST_CHECK_EQUAL(track.travellingTime(), 40);
}

/*This test checks the travel time when the absolute start time is a negative number
because if the absolute start time is set to a negative number then the GPX log becomes corrupted
and doesn't show the correct path*/
BOOST_AUTO_TEST_CASE ( absolute_negative )
{
    Track track = Track(LogFiles::GPXTracksDir + "TrackAbsoluteTimeNegative.gpx", isFileName);
    BOOST_CHECK_THROW(track.travellingTime(), std::invalid_argument);
}

//This tests checks that is can produce the correct results when handling a large track
BOOST_AUTO_TEST_CASE ( multiple_tracks )
{
    Track track = Track(LogFiles::GPXTracksDir + "TrackMultiplePoints.gpx", isFileName);
    BOOST_CHECK_EQUAL(track.travellingTime(), 21000);
}

//This test checks if the correct travel time is returned while the track includes points of no movement
BOOST_AUTO_TEST_CASE ( track_has_rests )
{
    Track track = Track(LogFiles::GPXTracksDir + "TrackHasRests.gpx", isFileName);
    BOOST_CHECK_EQUAL(track.travellingTime(), 30);
}

/*This test checks if the correct travel time appears when one of the point
 * sequence is equal to 0. Eg. A0A2B
*/
BOOST_AUTO_TEST_CASE ( Track_zero_sequence )
{
    Track track = Track(LogFiles::GPXTracksDir + "TrackHas0andRests.gpx", isFileName);
    BOOST_CHECK_EQUAL(track.travellingTime(), 20);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: EdwinLangley/GPX-Route-and-Track

max_issues_repo_name: EdwinLangley/GPX-Route-and-Track

max_forks_repo_name: EdwinLangley/GPX-Route-and-Track


text:
#pragma once
#include <eosio/eosio.hpp>
#include <eosio/asset.hpp>
#include <eosio/system.hpp>
// #include <eosio/crypto.hpp>
#include <string>
#include <vector>
#include <map>
#include <cstdlib> 		// M-1: for strtoull
// #include <boost/lexical_cast.hpp>		// M-2: for string to uint64_t (Using Boost lib)		compile using `$ eosio-cpp tippertipper.cpp -I /mnt/f/Coding/github_repos -o tippertipper.wasm`

using eosio::contract;
using eosio::print;
using eosio::name;
using eosio::multi_index;
using eosio::const_mem_fun;
using eosio::indexed_by;
using eosio::asset;
using eosio::check;
using eosio::permission_level;
using eosio::datastream;
// using eosio::current_time_point;
using eosio::action;
using eosio::same_payer;
using eosio::symbol;
using eosio::extended_symbol;
// using eosio::require_recipient;
// using eosio::checksum256;
// using eosio::action_wrapper;

using std::string;
using std::vector;
using std::map;
using std::make_pair;
// using boost::lexical_cast;

CONTRACT tippertipper : public contract
{
private:
	// const symbol fund_token_symbol;
	// const symbol native_token_symbol;

public:
	using contract::contract;

	tippertipper(name receiver, name code, datastream<const char*> ds) :
				contract(receiver, code, ds)
				// fund_token_symbol("EOS", 4),
				// native_token_symbol("FUTBOL", 4)
				{}

	/**
	 * @brief - deposit money to the contract ac
	 * @details - deposit money to the contract ac with memo - telegram user_id e.g. 452435325
	 * 			- accepts any token i.e. EOSIO token e.g. "EOS", "TOE", "FUTBOL" created on a chain
	 * @param from - user account
	 * @param contract_ac - contract ac
	 * @param quantity - in eosio tokens - EOS, TOE, etc.
	 * @param memo - purpose which should include telegram user_id
	 */
	[[eosio::on_notify("*::transfer")]]
	void deposit( const name& from_ac,
					const name& contract_ac,
					const asset& quantity,
					const string& memo );

	/**
	 * @brief - withdraw amount
	 * @details - withdraw amount from_id to to_ac
	 *
	 * @param from_id - from telegram_id
	 * @param from_username - from telegram username
	 * @param to_ac - to eosio account
	 * @param quantity - qty
	 * @param memo - memo
	 */
	ACTION withdraw( uint64_t from_id,
					 const string& from_username,
					 const name& to_ac,
					 const asset& quantity,
					 const string& memo
					);

	/**
	 * @brief - tip money to a person via just telegram_id
	 * @details - no eosio account needed for both from & to users
	 *
	 * @param from_id - from telegram_id
	 * @param to_id - to telegram_id
	 * @param from_username - from telegram username
	 * @param to_username - to telegram username
	 * @param quantity - qty
	 * @param memo - memo
	 */
	ACTION tip( uint64_t from_id,
				uint64_t to_id,
				const string& from_username,
				const string& to_username,
				const asset& quantity,
				const string& memo );

	ACTION testdlacbyid( uint64_t tg_id ) {
		require_auth(get_self());

		// instantiate the `account` table
		account_index account_table(get_self(), get_self().value);
		auto account_it = account_table.find(tg_id);

		check(account_it != account_table.end(), "there is no account available for the parsed tg_id.");

		account_table.erase(account_it);
	}

	ACTION testmdqtyusr(uint64_t from_id, const asset& quantity, bool arithmetic_op) {
		require_auth(get_self());

		// instantiate the `account` table
		account_index account_table(get_self(), get_self().value);
		auto frm_account_it = account_table.find(from_id);

		check(frm_account_it != account_table.end(), "there is no account available for the given from_id.");

		// update (substract) the balances' value in from_id accounts table
		account_table.modify(frm_account_it, get_self(), [&](auto& row) {

			// NOTE: below is not used as map was not allowed to be used as const like this: `const map<extended_symbol, uint64_t>& m`
			creatify_map(row.balances, quantity, arithmetic_op, "captract"_n);		// arithmetic_op for add/sub - (1/0) balance

/*			// ----------------------------------------------------------------------------
			// code snippet for modifying the value in place of creatify_map() func
			// ----------------------------------------------------------------------------
			// bool arithmetic_op = 1;		// 1 for add balance
			auto s_it = std::find_if(row.balances.begin(), row.balances.end(),
								[&](auto& ms) {return ms.first.get_symbol() == quantity.symbol;});

			if(s_it != row.balances.end()) {		// key found
				if (arithmetic_op == 1)
					s_it->second += quantity.amount;
				else if (arithmetic_op == 0)
					s_it->second -= quantity.amount;
			}
			else {						// key NOT found
				row.balances.insert( make_pair(extended_symbol(quantity.symbol, get_first_receiver()), quantity.amount) );
			}
			// ----------------------------------------------------------------------------
			// ----------------------------------------------------------------------------
*/
		});
	}

	// static void check_quantity( const asset& quantity, const symbol& token1_sym, const symbol& token2_sym ) {
	// 	check(quantity.is_valid(), "invalid quantity");
	// 	check(quantity.amount > 0, "must withdraw positive quantity");
	// 	check( (quantity.symbol == token1_sym) || (quantity.symbol == token2_sym) , "symbol precision mismatch. Also, could be bcoz of sending unaccepted tokens to this contract.");
	// }
	// -----------------------------------------------------------------------------------------------------------------------
	TABLE account
	{
		uint64_t owner;		// telegram_id, e.g. 452435325.

		/*
			[
				{ "key": { "symbol": "4,SOV", "contract": "sovmintofeos" }, "value": 30000 },
				{ "key": { "symbol": "4,FROG", "contract": "frogfrogcoin" }, "value": 3500000 },
				{ "key": { "symbol": "4,PEOS", "contract": "thepeostoken" }, "value": 100000 },
				{ "key": { "symbol": "4,KROWN", "contract": "krowndactokn" }, "value": 7169 }
			]

			Here, quantity amount is 30000/10^4 = 3 i.e. asset is "3.0000 SOV"
		*/
		map<extended_symbol, uint64_t> balances; // map with extended_symbol, uint64_t

		auto primary_key() const { return owner; }
	};

	using account_index = multi_index<"accounts"_n, account>;

	// -----------------------------------------------------------------------------------------------------------------------
	// UTILITY functions
	// -----------------------------------------------------------------------------------------------------------------------
	// count no. of alphabets in a string
	inline uint64_t count_alpha( const string& str ) {
		uint64_t count = 0;		// no. of alphabet chars

	    for (int i=0; i<=str.size(); ++i) {
	        if (isalpha(str[i]))
	            ++count;
	    }

	    return count;
	}

	// string to uint64_t
	inline uint64_t str_to_uint64t(const string& s) {
		// M-1
		// char* end;
		uint64_t num = strtoull(s.c_str(), NULL, 10);

		//----------------------------------------------
		// M-2
		// uint64_t num = lexical_cast<uint64_t>(s);

		return num;
	}

	/*
		Here, 2 cases are covered in which the balances map is modified when the row with (owner, balances) exist:
			- case-1: if the row exists & key is found. i.e. the parsed quantity symbol is found
				- add/sub quantity amount is done by an arithmetic_op (0/1) => (-/+)
			- case-2: if the row exists & key is NOT found. i.e. the parsed quantity symbol is NOT found
	*/
	inline void creatify_map( map<extended_symbol, uint64_t>& m, const asset& qty,
								bool arithmetic_op, 			// add/sub balance from existing quantity
								const name& token_contract_name ) {
		auto s_it = std::find_if(m.begin(), m.end(),
							[&](auto& ms) {return ms.first.get_symbol() == qty.symbol;});

		if(s_it != m.end()) {		// key found
			if (arithmetic_op == 1)
				s_it->second += qty.amount;
			else if (arithmetic_op == 0)
				s_it->second -= qty.amount;
		}
		else {						// key NOT found
			if (token_contract_name == ""_n)
				m.insert( make_pair(extended_symbol(qty.symbol, get_first_receiver()), qty.amount) );
			else
				m.insert( make_pair(extended_symbol(qty.symbol, capture_contract_in_map(m, qty)), qty.amount) );
		}
	}

	/*
		Here, 2 cases are covered in which the balances map is checked for <>= than the given quantity, when the row with (owner, balances) exist:
			- case-1: if the row exists & key is found. i.e. the parsed quantity symbol is found
				- check for >= , else throw message
			- case-2: if the row exists & key is NOT found. i.e. the parsed quantity symbol is NOT found
				- throw message saying that there is no balances available
	*/
	inline void compare_amount_in_map( map<extended_symbol, uint64_t> m, const asset& qty ) {
		auto s_it = std::find_if(m.begin(), m.end(),
							[&](auto& ms) {return ms.first.get_symbol() == qty.symbol;});

		if(s_it != m.end()) {		// key found
			check( s_it->second >= qty.amount, "Insufficient balance in from\'s account." );
		}
		else {						// key NOT found
			check( false, "there is no balances available corresponding to the parsed quantity symbol for the given from_id." );
		}
	}

	/*
		Here, capture the token contract name in which the balances map exists in the row with (owner, balances) exist:
			- case-1: if the row exists & key is found. i.e. the parsed quantity symbol is found
				- capture the contract ac name from the key
	*/
	inline name capture_contract_in_map( map<extended_symbol, uint64_t> m, const asset& qty ) {
		name token_contract_ac = ""_n;

		auto s_it = std::find_if(m.begin(), m.end(),
							[&](auto& ms) {return ms.first.get_symbol() == qty.symbol;});

		if(s_it != m.end()) {		// key found
			token_contract_ac = s_it->first.get_contract();
		}
		else {
			check(false, "there is no contract account found with this quantity");
		}

		return token_contract_ac;
	}

};


text:
#ifndef TRISYCL_SYCL_CONTEXT_DETAIL_OPENCL_CONTEXT_HPP
#define TRISYCL_SYCL_CONTEXT_DETAIL_OPENCL_CONTEXT_HPP

/** \file The SYCL OpenCL context implementation

    a-doumoulakis at gmail dot com (Anastasios Doumoulakis)

    This file is distributed under the University of Illinois Open Source
    License. See LICENSE.TXT for details.
*/

#include <boost/compute.hpp>

#include "CL/sycl/detail/default_classes.hpp"
#include "CL/sycl/detail/unimplemented.hpp"
#include "CL/sycl/detail/cache.hpp"

#include "CL/sycl/context/detail/context.hpp"
#include "CL/sycl/platform.hpp"
#include "CL/sycl/info/param_traits.hpp"
#include "CL/sycl/exception.hpp"

namespace cl {
namespace sycl {
namespace detail {

/// SYCL OpenCL context
class opencl_context : public detail::context {

  /// User the Boost Compute abstraction of the OpenCL context
  boost::compute::context c;

  /** A boost \c command_queue associated to an OpenCL context for
      when we need to transfer data but no queue is given
      (eg. When an buffer accessor is created)
  */
  boost::compute::command_queue q;

  /** A cache to always return the same alive context for a given OpenCL
      context

      C++11 guaranties the static construction is thread-safe
  */
  static detail::cache<cl_context, detail::opencl_context> cache;

public:

  /// Return the underlying \c cl_context of the \c cl::sycl::context
  cl_context get() const override {
    return c.get();
  }

  /** Return the underlying \c boost::compute::context
      of the \c cl::sycl::context
  */
  boost::compute::context &get_boost_compute() override {
    return c;
  }

  /// Return the queue that is associated to the context
  boost::compute::command_queue &get_boost_queue() override {
    return q;
  }

  /// Return false because the context is not a SYCL host context
  bool is_host() const override {
    return false;
  }

#if 0
  /** Query the context for OpenCL \c info::context info

      Return synchronous errors via the SYCL exception class.

      \todo To be implemented
  */
  template <info::context Param>
  typename info::param_traits<info::context, Param>::type
  get_info() const override{
    detail::unimplemented();
    return {};
  }
#endif

  /** Return the platform of the context

      Return synchronous errors via the SYCL exception class.

      \todo To be implemented
  */
  cl::sycl::platform get_platform() const override {
    detail::unimplemented();
    return {};
  }

  /** Returns the set of devices that are part of this context.

      \todo To be implemented
  */
  vector_class<cl::sycl::device> get_devices() const override {
    detail::unimplemented();
    return {};
  }

  /// Get a singleton instance of the \c opencl_context
  static std::shared_ptr<opencl_context>
  instance(const boost::compute::context &c) {
    return cache.get_or_register(c.get(),
                                 [&] { return new opencl_context { c }; });
  }

private:

  /// Only the instance factory can build it
  opencl_context(const boost::compute::context &c) :
    c { c },
    q { boost::compute::command_queue { c, c.get_device() } } {}

public:
  /// Unregister from the cache on destruction
  ~opencl_context() override {
    cache.remove(c.get());
  }

};

/* Allocate the cache here but since this is a pure-header library,
   use a weak symbol so that only one remains when SYCL headers are
   used in different compilation units of a program
*/
TRISYCL_WEAK_ATTRIB_PREFIX
detail::cache<cl_context, detail::opencl_context> opencl_context::cache
TRISYCL_WEAK_ATTRIB_SUFFIX;

}
}
}

/*
    # Some Emacs stuff:
    ### Local Variables:
    ### ispell-local-dictionary: "american"
    ### eval: (flyspell-prog-mode)
    ### End:
*/

#endif //TRISYCL_SYCL_CONTEXT_DETAIL_OPENCL_CONTEXT_HPP

max_stars_repo_name: infinitesnow/InceptionCL

max_issues_repo_name: infinitesnow/InceptionCL

max_forks_repo_name: infinitesnow/InceptionCL


text:
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// test_registered.cpp

// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
// 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)

// should pass compilation and execution

#include "io_fixture.hpp"
#include "polymorphic_derived1.hpp"
#include "polymorphic_derived2.hpp"
#include <boost/archive/archive_exception.hpp>
#include <boost/serialization/base_object.hpp>
#include <boost/serialization/type_info_implementation.hpp>
#include <boost/test/unit_test.hpp>

BOOST_FIXTURE_TEST_CASE(registered1, io_fixture)
{
    polymorphic_derived1* rd1 = new polymorphic_derived1;
    polymorphic_derived2* rd2 = new polymorphic_derived2;
    polymorphic_base*     rb1 = rd1;
    polymorphic_base*     rb2 = rd2;

    {
        test_ostream  os(get_filename().c_str(), STREAM_FLAGS);
        test_oarchive oa(os, ARCHIVE_FLAGS);

        // registration IS necessary when serializing pointers of
        // polymorphic classes
        oa.register_type(static_cast<polymorphic_derived1*>(NULL));
        oa.register_type(static_cast<polymorphic_derived2*>(NULL));
        oa << BOOST_SERIALIZATION_NVP(rd1);
        oa << BOOST_SERIALIZATION_NVP(rd2);

        oa << BOOST_SERIALIZATION_NVP(rb1);
        oa << BOOST_SERIALIZATION_NVP(rb2);
    }

    delete rd1;
    delete rd2;
    rd1 = nullptr;
    rd2 = nullptr;
    {
        test_istream  is(get_filename().c_str(), STREAM_FLAGS);
        test_iarchive ia(is, ARCHIVE_FLAGS);
        // registration IS necessary when serializing pointers of
        // polymorphic classes
        ia.register_type(static_cast<polymorphic_derived1*>(nullptr));
        ia.register_type(static_cast<polymorphic_derived2*>(nullptr));

        ia >> BOOST_SERIALIZATION_NVP(rd1);
        ia >> BOOST_SERIALIZATION_NVP(rd2);

        // the above opereration registers the derived classes as a side
        // effect.  Hence, instances can now be correctly serialized through
        // a base class pointer.
        ia >> BOOST_SERIALIZATION_NVP(rb1);
        ia >> BOOST_SERIALIZATION_NVP(rb2);
    }

    const boost::serialization::extended_type_info* p1;
    p1 = &boost::serialization::type_info_implementation<
        polymorphic_derived1>::type::get_const_instance();

    BOOST_CHECK(nullptr != p1);

    const boost::serialization::extended_type_info* p2;
    p2 = boost::serialization::type_info_implementation<
             polymorphic_derived1>::type::get_const_instance()
             .get_derived_extended_type_info(*rd1);

    BOOST_CHECK(nullptr != p2);

    BOOST_CHECK_MESSAGE(p1 == p2, "restored pointer d1 not of correct type");

    BOOST_CHECK_MESSAGE(
        &boost::serialization::type_info_implementation<
            polymorphic_derived2>::type::get_const_instance() ==
            boost::serialization::type_info_implementation<
                polymorphic_derived2>::type::get_const_instance()
                .get_derived_extended_type_info(*rd2),
        "restored pointer d2 not of correct type");

    BOOST_CHECK_MESSAGE(rb1 == dynamic_cast<polymorphic_base*>(rd1),
                        "serialized pointers not correctly restored");

    p1 = &boost::serialization::type_info_implementation<
        polymorphic_derived1>::type::get_const_instance();

    BOOST_CHECK(nullptr != p1);

    p2 = boost::serialization::type_info_implementation<
             polymorphic_base>::type::get_const_instance()
             .get_derived_extended_type_info(*rb1);

    BOOST_CHECK(nullptr != p2);

    BOOST_CHECK_MESSAGE(p1 == p2, "restored pointer b1 not of correct type");

    BOOST_CHECK_MESSAGE(rb2 == dynamic_cast<polymorphic_base*>(rd2),
                        "serialized pointers not correctly restored");

    BOOST_CHECK_MESSAGE(&boost::serialization::type_info_implementation<
                            polymorphic_derived2>::type::get_const_instance() ==
                            boost::serialization::type_info_implementation<
                                polymorphic_base>::type::get_const_instance()
                                .get_derived_extended_type_info(*rb2),
                        "restored pointer b2 not of correct type");

    delete rb1;
    delete rb2;
}

BOOST_FIXTURE_TEST_CASE(registered2, io_fixture)
{

    polymorphic_base* rb1 = new polymorphic_derived1;
    polymorphic_base* rb2 = new polymorphic_derived2;

    {
        test_ostream  os(get_filename().c_str(), STREAM_FLAGS);
        test_oarchive oa(os, ARCHIVE_FLAGS);

        // registration (forward declaration) will permit correct serialization
        // through a pointer to a base class
        oa.register_type(static_cast<polymorphic_derived1*>(nullptr));
        oa.register_type(static_cast<polymorphic_derived2*>(nullptr));
        oa << BOOST_SERIALIZATION_NVP(rb1) << BOOST_SERIALIZATION_NVP(rb2);
    }

    delete rb1;
    delete rb2;

    rb1 = nullptr;
    rb2 = nullptr;

    {
        test_istream  is(get_filename().c_str(), STREAM_FLAGS);
        test_iarchive ia(is, ARCHIVE_FLAGS);

        // registration (forward declaration) will permit correct serialization
        // through a pointer to a base class
        ia.register_type(static_cast<polymorphic_derived1*>(nullptr));
        ia.register_type(static_cast<polymorphic_derived2*>(nullptr));
        ia >> BOOST_SERIALIZATION_NVP(rb1) >> BOOST_SERIALIZATION_NVP(rb2);
    }

    BOOST_CHECK_MESSAGE(&boost::serialization::type_info_implementation<
                            polymorphic_derived1>::type::get_const_instance() ==
                            boost::serialization::type_info_implementation<
                                polymorphic_base>::type::get_const_instance()
                                .get_derived_extended_type_info(*rb1),
                        "restored pointer b1 not of correct type");

    BOOST_CHECK_MESSAGE(&boost::serialization::type_info_implementation<
                            polymorphic_derived2>::type::get_const_instance() ==
                            boost::serialization::type_info_implementation<
                                polymorphic_base>::type::get_const_instance()
                                .get_derived_extended_type_info(*rb2),
                        "restored pointer b2 not of correct type");

    delete rb1;
    delete rb2;
}

// EOF

max_stars_repo_name: rwols/yaml-archive

max_issues_repo_name: rwols/yaml-archive

max_forks_repo_name: rwols/yaml-archive


text:
#define ljsonrpclib_cpp

#include "glua/lauxlib.h"
#include "glua/lprefix.h"
#include "glua/lua.h"
#include "glua/lua_api.h"
#include "glua/lualib.h"

#include <boost/asio.hpp>
#include <boost/asio/ip/tcp.hpp>

#include <errno.h>
#include <locale.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <memory>
#include <mutex>

#undef LUA_JSONRPC_VERSION
#define LUA_JSONRPC_VERSION "1.0"

// TODO

static const luaL_Reg jsonrpclib[] = {
	// { "listen", lualib_http_listen },
	{ "version", nullptr },
	{ nullptr, nullptr }
};

LUAMOD_API int luaopen_jsonrpc(lua_State *L) {
	luaL_newlib(L, jsonrpclib);
	lua_pushstring(L, LUA_JSONRPC_VERSION);
	lua_setfield(L, -2, "version");
	return 1;
}

max_stars_repo_name: WillAchain/lvm

max_issues_repo_name: WillAchain/lvm

max_forks_repo_name: WillAchain/lvm


text:
#include <CCA/Components/Wasatch/Expressions/DensityCalculator.h>

#include <sci_defs/uintah_defs.h>

#include <boost/foreach.hpp>

#define DGESV FIX_NAME(dgesv)

extern "C"{
  void DGESV( const int    * n,    // # of equations
              const int    * nrhs, // # of rhs to solve
                    double   A[],  // lhs matrix
              const int    * lda,  // leading dim of A (#eqn for us)
                    int    * ipiv, // integer work array
                    double   rhs[],// rhs array
              const int    * ldb,  // dimension of rhs (#eqn for us)
                    int    * info );
}

//-------------------------------------------------------------------

DensityCalculatorBase::
DensityCalculatorBase( const int neq,
                       const double rtol,
                       const size_t maxIter )
: rtol_   ( rtol    ),
  maxIter_( maxIter ),
  neq_    ( neq     )
{
  jac_ .resize( neq_*neq_ );
  res_ .resize( neq_      );
  ipiv_.resize( neq_      );
}

DensityCalculatorBase::~DensityCalculatorBase(){}

bool DensityCalculatorBase::solve( const DoubleVec& passThrough,
                                   DoubleVec& soln,
                                   double& relError)
{
  unsigned niter = 0;
  double relErr = 0.0;
  if (maxIter_ == 0) return true;
  do{
    calc_jacobian_and_res( passThrough, soln, jac_, res_ );
    switch( neq_ ){
      case 1: // avoid the overhead of the general equation solver for this trivial case.
        res_[0] /= jac_[0];  // put the displacement from Newton's method in the residual.
        break;
      default:
        // Solving J * delta = rhs  (note the missing minus sign, which is handled in the update below)
        // note that on entry, res_ is the rhs and on exit, it is the solution (delta).
        const int one=1; int info;
        DGESV( &neq_, &one, &jac_[0], &neq_, &ipiv_[0], &res_[0], &neq_, &info );
        if( info != 0 ){
          std::cout << "\nSOLVER FAILED: "<< info << "  " << soln[0] << ", " << soln[1] << std::endl;
        }
        assert( info==0 );
        break;
    } // switch
    relErr = 0.0;
    for( int i=0; i<neq_; ++i ){
      soln[i] -= res_[i];
      relErr += std::abs( res_[i]/get_normalization_factor(i) );
      // clip the solution to the valid range
      const std::pair<double,double>& bounds = get_bounds(i);
      soln[i] = std::max( std::min( bounds.second, soln[i] ), bounds.first );
    }
    ++niter;
  } while( relErr > rtol_ && niter < maxIter_ );
  relError = relErr;
  return niter < maxIter_;
}

//===================================================================

template< typename FieldT >
DensFromMixfrac<FieldT>::
DensFromMixfrac( const InterpT& rhoEval,
                 const Expr::Tag& rhoOldTag,
                 const Expr::Tag& rhoFTag, //rhoFTag will NOT be used if weakform is true.
                 const Expr::Tag& fTag,
                 const bool weakForm,
                 const double rtol,
                 const unsigned maxIter)
  : Expr::Expression<FieldT>(),
    DensityCalculatorBase( 1, rtol, maxIter ),
    rhoEval_( rhoEval ),
    bounds_ ( rhoEval.get_bounds()[0] ),
    weak_   ( weakForm )
{
  this->set_gpu_runnable(false);
  if (weak_) {
    f_ = this->template create_field_request<FieldT>(fTag);
  } else {
    rhoF_ = this->template create_field_request<FieldT>(rhoFTag);
    rhoOld_ = this->template create_field_request<FieldT>(rhoOldTag);
  }
}

//--------------------------------------------------------------------

template< typename FieldT >
DensFromMixfrac<FieldT>::
~DensFromMixfrac()
{}

//--------------------------------------------------------------------

template< typename FieldT >
void
DensFromMixfrac<FieldT>::
evaluate()
{
  typedef typename Expr::Expression<FieldT>::ValVec SVolFieldVec;
  SVolFieldVec& results = this->get_value_vec();

  // jcs: can we do the linear solve in place? We probably can. If so,
  // we would only need one field, not two...
  FieldT& rho = *results[0];
  if (!weak_) rho <<= rhoOld_->field_ref();

  FieldT& badPts = *results[1];
  FieldT& drhodf = *results[2];
  badPts <<= 0.0;

  typename FieldT::iterator irho = rho.begin();
  typename FieldT::iterator ibad = badPts.begin();
  typename FieldT::iterator idrhodf = drhodf.begin();
  const typename FieldT::iterator irhoe = rho.end();
  size_t nbad = 0;
  DoubleVec soln(1), vals(1);
  double relError = 0.0;

  if(weak_) {
    const FieldT& f = f_->field_ref();
    typename FieldT::const_iterator iF = f.begin();
    for( ; irho!=irhoe; ++irho, ++iF, ++ibad, ++idrhodf){
      vals[0] = *iF;
      soln[0] = *iF;   // initial guess for the mixture fraction
      const double& f = soln[0];
      *irho = rhoEval_.value(&f);
      *idrhodf = rhoEval_.derivative(&f, 0);
    }
  } else {
    const FieldT& rhoF = rhoF_->field_ref();
    typename FieldT::const_iterator irhoF = rhoF.begin();

    for( ; irho!=irhoe; ++irho, ++irhoF, ++ibad, ++idrhodf){
      vals[0] = *irhoF;
      soln[0] = *irhoF / *irho;   // initial guess for the mixture fraction
      if (maxIter_ == 0) {
        const double& f = soln[0];
        *irho = rhoEval_.value(&f);
        *idrhodf = rhoEval_.derivative(&f, 0);
      } else {
        const bool converged = this->solve( vals, soln, relError );  // soln contains the mixture fraction
        if( !converged ) {
          ++nbad;
          *ibad = relError;
        }

        *irho = *irhoF / soln[0];

        const double& f = soln[0];
        if (f == 0) {
          *irho = rhoEval_.value(&soln[0]);
        }

        *idrhodf = rhoEval_.derivative(&f, 0);

      }
    }
  }

  if( nbad>0 && maxIter_ != 0){
    std::cout << "\tConvergence failed at " << nbad << " points.\n";
  }
}

//--------------------------------------------------------------------

template<typename FieldT>
void
DensFromMixfrac<FieldT>::
calc_jacobian_and_res( const DensityCalculatorBase::DoubleVec& passThrough,
                       const DensityCalculatorBase::DoubleVec& soln,
                       DensityCalculatorBase::DoubleVec& jac,
                       DensityCalculatorBase::DoubleVec& res )
{
  const double rhoF = passThrough[0];
  const double& f = soln[0];
  const double rhoCalc = rhoEval_.value( &f );
  jac[0] = rhoCalc + f * rhoEval_.derivative( &f, 0 );
  res[0] = f * rhoCalc - rhoF;
}

//--------------------------------------------------------------------

template< typename FieldT >
DensFromMixfrac<FieldT>::
Builder::Builder( const InterpT& rhoEval,
                  const Expr::TagList& resultsTag,
                  const Expr::Tag& rhoOldTag,
                  const Expr::Tag& rhoFTag,
                  const Expr::Tag& fTag,
                  const bool weakForm,
                  const double rtol,
                  const unsigned maxIter)
  : ExpressionBuilder( resultsTag ),
    rhoEval_  (rhoEval.clone() ),
    rhoOldTag_(rhoOldTag       ),
    rhoFTag_  (rhoFTag         ),
    fTag_     (fTag            ),
    weakForm_ (weakForm        ),
    rtol_     (rtol            ),
    maxIter_  (maxIter         )
{}

//===================================================================

template< typename FieldT >
DensHeatLossMixfrac<FieldT>::
DensHeatLossMixfrac( const Expr::Tag& rhoOldTag,
                     const Expr::Tag& gammaOldTag,
                     const Expr::Tag& rhofTag,
                     const Expr::Tag& rhohTag,
                     const InterpT& densEvaluator,
                     const InterpT& enthEvaluator )
  : Expr::Expression<FieldT>(),
    DensityCalculatorBase( 2, 1e-6, 5 ),
    densEval_( densEvaluator ),
    enthEval_( enthEvaluator ),
    bounds_( densEvaluator.get_bounds() )
{
  rhoOld_ = this->template create_field_request<FieldT>(rhoOldTag);
  gammaOld_ = this->template create_field_request<FieldT>(gammaOldTag);
  rhof_ = this->template create_field_request<FieldT>(rhofTag);
  rhoh_ = this->template create_field_request<FieldT>(rhohTag);
}

//--------------------------------------------------------------------

template< typename FieldT >
DensHeatLossMixfrac<FieldT>::
~DensHeatLossMixfrac()
{}

//--------------------------------------------------------------------

template< typename FieldT >
void
DensHeatLossMixfrac<FieldT>::
evaluate()
{
  typename Expr::Expression<FieldT>::ValVec& result  = this->get_value_vec();
  FieldT& density = *result[0];
  FieldT& gamma   = *result[1];

  density <<= rhoOld_->field_ref();
  gamma   <<= gammaOld_->field_ref();

  const FieldT& rhof = rhof_->field_ref();
  const FieldT& rhoh = rhoh_->field_ref();

  typename FieldT::const_iterator irhof = rhof.begin();
  typename FieldT::const_iterator irhoh = rhoh.begin();
  typename FieldT::iterator irho = density.begin();
  typename FieldT::iterator igam = gamma.begin();
  const typename FieldT::iterator irhoe = density.end();

  size_t nbad=0;
  DoubleVec soln(2), vals(2);
  double relError = 0.0;
  for( ; irho!=irhoe; ++irho, ++igam, ++irhof, ++irhoh ){
    vals[0] = *irhof;
    vals[1] = *irhoh;
    soln[0] = *irhof / *irho; // mixture fraction
    soln[1] = *igam;          // heat loss
    const bool converged = this->solve( vals, soln, relError );
    if( !converged ) ++nbad;
    *irho = *irhof / soln[0]; // set solution for density
    *igam = soln[1];          // heat loss
  }
  if( nbad>0 ){
    std::cout << "\tConvergence failed at " << nbad << " of " << density.window_with_ghost().local_npts() << " points.\n";
  }
}

//--------------------------------------------------------------------

template< typename FieldT >
void
DensHeatLossMixfrac<FieldT>::
calc_jacobian_and_res( const DensityCalculatorBase::DoubleVec& passThrough,
                       const DensityCalculatorBase::DoubleVec& soln,
                       DensityCalculatorBase::DoubleVec& jac,
                       DensityCalculatorBase::DoubleVec& res )
{
  const double& rhof = passThrough[0];
  const double& rhoh = passThrough[1];
  const double& f    = soln[0];
  //const double& gam  = soln[1];

  // if we hit the bounds on mixture fraction, we have a degenerate case,
  // so don't solve for heat loss in that situation.
  const double tol = 1e-4;
  const bool atBounds = ( std::abs(f-bounds_[0].first ) < tol ||
                          std::abs(f-bounds_[0].second) < tol );

  // evaluate density and enthalpy given the current guess for f and gamma.
  const double rho =                       densEval_.value( soln );
  const double h   = atBounds ? rhoh/rho : enthEval_.value( soln );
  // evaluate the residual function
  res[0] = f * rho - rhof;
  res[1] = atBounds ? 0 : rho * h - rhoh;

  // evaluate derivative for use in the jacobian matrix
  const double drhodf   =                densEval_.derivative( soln, 0 );
  const double drhodgam = atBounds ? 0 : densEval_.derivative( soln, 1 );
  const double dhdf     = atBounds ? 0 : enthEval_.derivative( soln, 0 );
  const double dhdgam   = atBounds ? 0 : enthEval_.derivative( soln, 1 );

  // strange ordering because of fortran/c conventions.
  jac[0] = rho + f * drhodf;
  jac[2] = atBounds ? 0 : f * drhodgam;
  jac[1] = atBounds ? 0 : rho*dhdf   + h*drhodf;
  jac[3] = atBounds ? 1 : rho*dhdgam + h*drhodgam;
}

//--------------------------------------------------------------------

template< typename FieldT >
DensHeatLossMixfrac<FieldT>::
Builder::Builder( const Expr::Tag& rhoOldTag,
                  const Expr::Tag& rhoTag,
                  const Expr::Tag& gammaOldTag,
                  const Expr::Tag& gammaTag,
                  const Expr::Tag& rhofTag,
                  const Expr::Tag& rhohTag,
                  const InterpT& densEvaluator,
                  const InterpT& enthEvaluator )
  : ExpressionBuilder( tag_list(rhoTag,gammaTag) ),
    rhoOldTag_   ( rhoOldTag             ),
    gammaOldTag_ ( gammaOldTag           ),
    densEval_    ( densEvaluator.clone() ),
    enthEval_    ( enthEvaluator.clone() )
{}

//====================================================================

template< typename FieldT >
TwoStreamMixingDensity<FieldT>::
TwoStreamMixingDensity( const Expr::Tag& rhofTag,
                        const double rho0,
                        const double rho1 )
  : Expr::Expression<FieldT>(),
    rho0_(rho0), rho1_(rho1),
    rhoMin_( rho0_ < rho1_ ? rho0_ : rho1),
    rhoMax_( rho0_ > rho1_ ? rho0_ : rho1)
{
  this->set_gpu_runnable(true);
  rhof_ = this->template create_field_request<FieldT>(rhofTag);
}

//--------------------------------------------------------------------

template< typename FieldT >
void
TwoStreamMixingDensity<FieldT>::
evaluate()
{
  using namespace SpatialOps;
  typename Expr::Expression<FieldT>::ValVec& results  = this->get_value_vec();
  FieldT& rho    = *results[0];
  FieldT& drhodf = *results[1];

  const FieldT& rf = rhof_->field_ref();

  // compute the density in one shot from rhof
  rho <<= rho0_ + (1 - rho0_/rho1_)*rf;

  // repair bounds
  rho <<= max( min(rho, rhoMax_), rhoMin_ );

  drhodf <<= (1/rho0_ - 1/rho1_)*rho*rho;
}

//--------------------------------------------------------------------

template< typename FieldT >
TwoStreamMixingDensity<FieldT>::
Builder::Builder( const Expr::TagList& resultsTagList,
                  const Expr::Tag& rhofTag,
                  const double rho0,
                  const double rho1 )
  : ExpressionBuilder( resultsTagList ),
    rho0_(rho0), rho1_(rho1),
    rhofTag_( rhofTag )
{}

//====================================================================

template< typename FieldT >
TwoStreamDensFromMixfr<FieldT>::
TwoStreamDensFromMixfr( const Expr::Tag& mixfrTag,
                        const double rho0,
                        const double rho1 )
  : Expr::Expression<FieldT>(),
    rho0_(rho0), rho1_(rho1),
    rhoMin_( rho0_ < rho1_ ? rho0_ : rho1),
    rhoMax_( rho0_ > rho1_ ? rho0_ : rho1)
{
  this->set_gpu_runnable(true);
  mixfr_ = this->template create_field_request<FieldT>(mixfrTag);
}

//--------------------------------------------------------------------

template< typename FieldT >
void
TwoStreamDensFromMixfr<FieldT>::
evaluate()
{
  using namespace SpatialOps;

  typename Expr::Expression<FieldT>::ValVec& results  = this->get_value_vec();
  FieldT& rho    = *results[0];
  FieldT& drhodf = *results[1];

  const FieldT& f = mixfr_->field_ref();

  rho <<= 1.0 / ( f/rho1_ + (1.0-f)/rho0_ );
  // repair bounds
  rho <<= max ( min(rho, rhoMax_), rhoMin_);

  drhodf <<= -rho0_*rho1_*(rho0_-rho1_)/( (rho0_ - rho1_)*f - rho1_ )/( (rho0_ - rho1_)*f - rho1_ );
}

//--------------------------------------------------------------------

template< typename FieldT >
TwoStreamDensFromMixfr<FieldT>::
Builder::Builder( const Expr::TagList& resultsTagList,
                  const Expr::Tag& mixfrTag,
                  const double rho0,
                  const double rho1 )
  : ExpressionBuilder( resultsTagList ),
    rho0_(rho0), rho1_(rho1),
    mixfrTag_( mixfrTag )
{}

//====================================================================

// explicit template instantiation
#include <spatialops/structured/FVStaggeredFieldTypes.h>
template class DensFromMixfrac       <SpatialOps::SVolField>;
template class DensHeatLossMixfrac   <SpatialOps::SVolField>;
template class TwoStreamDensFromMixfr<SpatialOps::SVolField>;
template class TwoStreamMixingDensity<SpatialOps::SVolField>;

ext: cc


text:
/**TODO:  Add copyright*/

#define BOOST_TEST_MODULE TensorShard1 test suite
#include <boost/test/included/unit_test.hpp>
#include <TensorBase/ml/TensorShard.h>
#include <TensorBase/ml/TensorDataDefaultDevice.h>

using namespace TensorBase;
using namespace std;

BOOST_AUTO_TEST_SUITE(TensorShard1)

/*TensorShard DefaultDevice Tests*/
BOOST_AUTO_TEST_CASE(constructorTensorShardDefaultDevice)
{
  TensorShard* ptr = nullptr;
  TensorShard* nullPointer = nullptr;
	ptr = new TensorShard();
  BOOST_CHECK_NE(ptr, nullPointer);
}

BOOST_AUTO_TEST_CASE(destructorTensorShardDefaultDevice)
{
  TensorShard* ptr = nullptr;
	ptr = new TensorShard();
  delete ptr;
}

BOOST_AUTO_TEST_CASE(getNMaxShardsDefaultDevice)
{
  Eigen::array<Eigen::Index, 3> dims_small = { 1,2,3 };
  BOOST_CHECK_EQUAL(TensorShard::getNMaxShards(dims_small), 1);

  Eigen::array<Eigen::Index, 4> dims_medium = { 1000,1000,1000,1000 };
  BOOST_CHECK_EQUAL(TensorShard::getNMaxShards(dims_medium), 1001);

  Eigen::array<Eigen::Index, 7> dims_large = { 1000,1000,1000,1000,1000,1000,1000 };
  BOOST_CHECK_EQUAL(TensorShard::getNMaxShards(dims_large), -1);
}

BOOST_AUTO_TEST_CASE(checkShardSpansDefaultDevice)
{
  Eigen::array<Eigen::Index, 4> dimensions_medium = { 0, 1000, 3, 0 };
  std::map<std::string, int> axes_to_dims_medium = { {"1", 0}, {"2", 1}, {"3", 2}, {"4", 3} };
  std::map<std::string, int> shard_span_medium = { {"1", 10}, {"2", 2e9}, {"3", -1}, {"4", 0} };
  TensorShard::checkShardSpans<4>(axes_to_dims_medium, dimensions_medium, shard_span_medium);
  BOOST_CHECK_EQUAL(shard_span_medium.at("1"), 10);
  BOOST_CHECK_EQUAL(shard_span_medium.at("2"), 1000);
  BOOST_CHECK_EQUAL(shard_span_medium.at("3"), 3);
  BOOST_CHECK_EQUAL(shard_span_medium.at("4"), 1e9);
}

BOOST_AUTO_TEST_CASE(getDefaultMaxDimensionsDefaultDevice)
{
  std::map<std::string, int> axes_to_dims_small = { {"1", 0}, {"2", 1}, {"3", 2} };
  std::map<std::string, int> shard_span_small = { {"1", 1}, {"2", 2}, {"3", 3} };
  auto dims_small = TensorShard::getDefaultMaxDimensions<3>(axes_to_dims_small, shard_span_small);
  BOOST_CHECK_EQUAL(dims_small.at(0), 18);
  BOOST_CHECK_EQUAL(dims_small.at(1), 36);
  BOOST_CHECK_EQUAL(dims_small.at(2), 54);

  std::map<std::string, int> axes_to_dims_medium = { {"1", 0}, {"2", 1}, {"3", 2}, {"4", 3} };
  std::map<std::string, int> shard_span_medium = { {"1", 10}, {"2", 20}, {"3", 30}, {"4", 40} };
  auto dims_medium = TensorShard::getDefaultMaxDimensions<4>(axes_to_dims_medium, shard_span_medium);
  BOOST_CHECK_EQUAL(dims_medium.at(0), 140);
  BOOST_CHECK_EQUAL(dims_medium.at(1), 280);
  BOOST_CHECK_EQUAL(dims_medium.at(2), 420);
  BOOST_CHECK_EQUAL(dims_medium.at(3), 560);
}

BOOST_AUTO_TEST_CASE(makeShardIndicesFromShardIDsDefaultDevice)
{
  Eigen::DefaultDevice device;

  // Setup the input data
  int nlabels = 6, maxlabels = 1000;
  Eigen::array<Eigen::Index, 3> dimensions = { nlabels,nlabels,nlabels };
  Eigen::array<Eigen::Index, 3> dimensions_max = { maxlabels,maxlabels,maxlabels };
  std::map<std::string, int> axes_to_dims = {{"1", 0}, {"2", 1}, {"3", 2}};
  std::map<std::string, int> shard_span = { {"1", nlabels}, {"2", nlabels}, {"3", nlabels} };
  std::map<std::string, std::shared_ptr<TensorData<int, Eigen::DefaultDevice, 1>>> shard_ids;
  Eigen::Tensor<int, 1> shard_ids_values(nlabels);
  shard_ids_values.setConstant(1);
  for (const auto& axis_to_dim : axes_to_dims) {
    TensorDataDefaultDevice<int, 1> shard_ids_tmp(Eigen::array<Eigen::Index, 1>({ nlabels }));
    shard_ids_tmp.setData(shard_ids_values);
    shard_ids_tmp.syncHAndDData(device);
    shard_ids.emplace(axis_to_dim.first, std::make_shared<TensorDataDefaultDevice<int,1>>(shard_ids_tmp));
  }

  // Test for the shard indices
  TensorDataDefaultDevice<int, 3> indices_shard(dimensions);
  std::shared_ptr<TensorData<int, Eigen::DefaultDevice, 3>> indices_shard_ptr = std::make_shared<TensorDataDefaultDevice<int,3>>(indices_shard);
  indices_shard_ptr->setData();
  indices_shard_ptr->syncHAndDData(device);
  TensorShard::makeShardIndicesFromShardIDs(axes_to_dims, shard_span, dimensions, dimensions_max, shard_ids, indices_shard_ptr, device);
  indices_shard_ptr->syncHAndDData(device);
  for (int i = 0; i < nlabels; ++i) {
    for (int j = 0; j < nlabels; ++j) {
      for (int k = 0; k < nlabels; ++k) {
        BOOST_CHECK_EQUAL(indices_shard_ptr->getData()(i, j, k), 1);
      }
    }
  }

  // make the expected tensor indices
  std::map<std::string, int> shard_span_new = { {"1", 2}, {"2", 2}, {"3", 2} };
  int shard_n_indices = maxlabels/2;
  std::vector<int> shard_id_indices = { 0, 0, 1, 1, 2, 2 };
  Eigen::Tensor<int, 3> indices_test(nlabels, nlabels, nlabels);
  for (int i = 0; i < nlabels; ++i) {
    shard_ids_values(i) = shard_id_indices.at(i) + 1;
    for (int j = 0; j < nlabels; ++j) {
      for (int k = 0; k < nlabels; ++k) {
        indices_test(i, j, k) = shard_id_indices.at(i) + shard_id_indices.at(j) * shard_n_indices + shard_id_indices.at(k) * shard_n_indices * shard_n_indices + 1;
      }
    }
  }

  // Remake the shard_ids
  for (const auto& axis_to_dim : axes_to_dims) {
    TensorDataDefaultDevice<int, 1> shard_ids_tmp(Eigen::array<Eigen::Index, 1>({ nlabels }));
    shard_ids_tmp.setData(shard_ids_values);
    shard_ids_tmp.syncHAndDData(device);
    shard_ids.at(axis_to_dim.first) = std::make_shared<TensorDataDefaultDevice<int, 1>>(shard_ids_tmp);
  }

  // Test for the shard indices
  indices_shard_ptr->setData();
  indices_shard_ptr->syncHAndDData(device);
  TensorShard::makeShardIndicesFromShardIDs(axes_to_dims, shard_span_new, dimensions, dimensions_max, shard_ids, indices_shard_ptr, device);
  indices_shard_ptr->syncHAndDData(device);
  for (int i = 0; i < nlabels; ++i) {
    for (int j = 0; j < nlabels; ++j) {
      for (int k = 0; k < nlabels; ++k) {
        BOOST_CHECK_EQUAL(indices_shard_ptr->getData()(i, j, k), indices_test(i, j, k));
      }
    }
  }
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: dmccloskey/TensorBase

max_issues_repo_name: dmccloskey/TensorBase

max_forks_repo_name: dmccloskey/TensorBase


text:
#include "pairbrowse.h"
#include <iostream>
#include <boost/filesystem.hpp>
#include <algorithm>

OptionsPanel::OptionsPanel(MyFrame* parent) : wxPanel(parent), boss(parent) {
	btn = new wxButton(this, wxID_ANY, "Moi", wxPoint(20, 20));
	slider = new wxSlider(this, wxID_ANY, 1, 1, 10); // TODO: style

	wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL);

	sizer->Add(btn, 1, wxEXPAND);
	sizer->Add(slider, 1, wxEXPAND);
	SetSizer(sizer);
	Bind(wxEVT_SLIDER, &OptionsPanel::OnSlider, this, wxID_ANY);
}

bool MyApp::OnInit()
{
	wxInitAllImageHandlers();
	loadImages("img/left", images[0]);
	loadImages("img/right", images[1]);
	wxFrame *mainframe = new MyFrame("Hello World", images);
	mainframe->Show(true);
	return true;
}

MyFrame::MyFrame(const wxString& title, std::vector<std::string> (&images)[2]) : wxFrame(NULL, wxID_ANY, title, wxDefaultPosition, wxSize(1024, 768)) , images(images) {
	doMenus();
	doPanels();
}
void MyApp::loadImages(const std::string& pathname, std::vector<std::string>& vec) {
	namespace fs = boost::filesystem;
	fs::path path(pathname);
	if (is_directory(path)) {
		std::vector<fs::directory_entry> entries;
		std::copy(fs::directory_iterator(path), fs::directory_iterator(),
				std::back_inserter(entries));
		std::transform(entries.begin(), entries.end(), std::back_inserter(vec),
				[](fs::directory_entry& e) { return e.path().string(); });
		std::sort(vec.begin(), vec.end());
	}
}

void MyFrame::doPanels() {
	wxGridSizer* sizer = new wxGridSizer(2, wxSize(3, 3));

	leftpic = new ImagePanel(this, images[0][0]);
	sizer->Add(leftpic, 1, wxEXPAND);
	rightpic = new ImagePanel(this, images[1][0]);
	sizer->Add(rightpic, 1, wxEXPAND);

	OptionsPanel * op = new OptionsPanel(this);
	sizer->Add(op, 1, wxEXPAND);

	disppic = new ImagePanel(this);
	sizer->Add(disppic);

	SetSizer(sizer);
}

void MyFrame::doMenus() {
	Bind(wxEVT_COMMAND_MENU_SELECTED, &MyFrame::OnExit, this, wxID_EXIT);

	wxMenu *menuFile = new wxMenu;
	menuFile->AppendSeparator();
	menuFile->Append(wxID_EXIT);
	wxMenuBar *menuBar = new wxMenuBar;
	menuBar->Append(menuFile, "&File");
	SetMenuBar(menuBar);

	CreateStatusBar();
	SetStatusText("Hello world");
}

void MyFrame::selectImage(int n) {
	std::cout << "image " << n << std::endl;
	leftpic->setImage(images[0][n]);
	rightpic->setImage(images[1][n]);
}

void OptionsPanel::OnSlider(wxCommandEvent& event) {
	boss->selectImage(slider->GetValue());
}

void MyFrame::OnExit(wxCommandEvent& event) {
	Close(true);
}

wxIMPLEMENT_APP(MyApp);

max_stars_repo_name: sooda/thesis

max_issues_repo_name: sooda/thesis

max_forks_repo_name: sooda/thesis


text:
//
// Created by alex on 2/2/19.
//

#include <gie/Program.h>

#include <boost/python.hpp>

#include <cassert>
#include <vector>

#include <iostream>

int main()
{

    Program program;

    program.context().module("builtins", false);

    auto sys = program.context().module("sys", false);
    auto os = program.context().module("os", false);

    sys.attr("path").attr("insert")(1, os.attr("getcwd")());

    program.context().module("test_modules.basic", "test_modules/basic");

    for(const auto& symbol: program.context().importedSymbols())
    {
        std::cout << symbol.name.qualifiedName << std::endl;
    }

    program.addNode("test_modules.basic.to_int", {});
    program.addNode("test_modules.basic.to_int", {});
    program.addNode("test_modules.basic.to_int", {});
    program.addNode("test_modules.basic.to_int", {});
    program.addNode("test_modules.basic.to_int", {});
    program.addNode("test_modules.basic.to_int", {});
    program.addNode("test_modules.basic.to_int", {});
    program.addNode("test_modules.basic.to_int", {});
    program.removeNode(NodeId{7}).discard();
    program.addNode("test_modules.basic.to_int", {});
}

max_stars_repo_name: Kerdek/gie

max_issues_repo_name: Kerdek/gie

max_forks_repo_name: Kerdek/gie


text:
//
// ip/dccp.hpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2012 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef BOOST_ASIO_IP_DCCP_HPP
#define BOOST_ASIO_IP_DCCP_HPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)

#include <boost/asio/detail/config.hpp>
#include <boost/asio/basic_socket_acceptor.hpp>
#include <boost/asio/basic_socket_iostream.hpp>
#include <boost/asio/basic_stream_socket.hpp>
// RG
// #include <boost/asio/basic_packetstream_socket.hpp>
#include "packetstream_socket_service.hpp"

#include <boost/asio/detail/socket_option.hpp>
#include <boost/asio/detail/socket_types.hpp>
#include <boost/asio/ip/basic_endpoint.hpp>
#include <boost/asio/ip/basic_resolver.hpp>
#include <boost/asio/ip/basic_resolver_iterator.hpp>
#include <boost/asio/ip/basic_resolver_query.hpp>

#include <boost/asio/detail/push_options.hpp>

namespace boost {
namespace asio {
namespace ip {

/// Encapsulates the flags needed for DCCP.
/**
 * The boost::asio::ip::dccp class contains flags necessary for DCCP sockets.
 *
 * @par Thread Safety
 * @e Distinct @e objects: Safe.@n
 * @e Shared @e objects: Safe.
 *
 * @par Concepts:
 * Protocol, InternetProtocol.
 */
class dccp
{
public:
  /// The type of a DCCP endpoint.
  typedef basic_endpoint<dccp> endpoint;

  /// Construct to represent the IPv4 DCCP protocol.
  static dccp v4()
  {
    return dccp(PF_INET);
  }

  /// Construct to represent the IPv6 DCCP protocol.
  static dccp v6()
  {
    return dccp(PF_INET6);
  }

  /// Obtain an identifier for the type of the protocol.
  int type() const
  {
    return SOCK_DCCP;
  }

  /// Obtain an identifier for the protocol.
  int protocol() const
  {
    return IPPROTO_DCCP;
  }

  /// Obtain an identifier for the protocol family.
  int family() const
  {
    return family_;
  }

  // RG: TODO?
  /// The DCCP socket type.
  //typedef basic_stream_socket<dccp> socket;

#if 0
  typedef basic_stream_socket<dccp, packetstream_socket_service<dccp> > socket;
#else
  typedef basic_datagram_socket<dccp, packetstream_socket_service<dccp> > socket;
#endif

//typedef basic_packetstream_socket<dccp> socket;

  //typedef basic_seq_packet_socket<dccp> socket;
  /// The UDP socket type.
  //typedef basic_datagram_socket<dccp> socket;

  /// The DCCP acceptor type.
  typedef basic_socket_acceptor<dccp> acceptor;

  /// The DCCP resolver type.
  typedef basic_resolver<dccp> resolver;

#if !defined(BOOST_NO_IOSTREAM)
  /// The DCCP iostream type.
  typedef basic_socket_iostream<dccp> iostream;
#endif // !defined(BOOST_NO_IOSTREAM)

  /// Socket option for disabling the Nagle algorithm.
  /**
   * Implements the IPPROTO_TCP/TCP_NODELAY socket option.
   *
   * @par Examples
   * Setting the option:
   * @code
   * boost::asio::ip::tcp::socket socket(io_service);
   * ...
   * boost::asio::ip::tcp::no_delay option(true);
   * socket.set_option(option);
   * @endcode
   *
   * @par
   * Getting the current option value:
   * @code
   * boost::asio::ip::tcp::socket socket(io_service);
   * ...
   * boost::asio::ip::tcp::no_delay option;
   * socket.get_option(option);
   * bool is_set = option.value();
   * @endcode
   *
   * @par Concepts:
   * Socket_Option, Boolean_Socket_Option.
   */
/* RG
#if defined(GENERATING_DOCUMENTATION)
  typedef implementation_defined no_delay;
#else
  typedef boost::asio::detail::socket_option::boolean<
    IPPROTO_TCP, TCP_NODELAY> no_delay;
#endif
*/

  /// Compare two protocols for equality.
  friend bool operator==(const dccp& p1, const dccp& p2)
  {
    return p1.family_ == p2.family_;
  }

  /// Compare two protocols for inequality.
  friend bool operator!=(const dccp& p1, const dccp& p2)
  {
    return p1.family_ != p2.family_;
  }

private:
  // Construct with a specific family.
  explicit dccp(int protocol_family)
    : family_(protocol_family)
  {
  }

  int family_;
};

} // namespace ip
} // namespace asio
} // namespace boost

#include <boost/asio/detail/pop_options.hpp>

#endif // BOOST_ASIO_IP_DCCP_HPP