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

#include <iostream>
#include <stdlib.h>
#include <signal.h>

#include <opencv2/highgui/highgui.hpp>
#include <shmfw/allocator.h>
#include <shmfw/variable.h>
#include <shmfw/objects/grid_map.h>
#include <shmfw/objects/opencv.h>
#include <boost/program_options.hpp>

struct Prarmeters {
    int reload;
    bool on_change;
    bool normalize;
    bool flip;
    std::string shm_memory_name;
    unsigned int shm_memory_size;
    std::string variable_name;
};

Prarmeters readArgs ( int argc, char **argv ) {
    namespace po = boost::program_options;

    Prarmeters params;
    po::options_description desc ( "Allowed Parameters" );
    desc.add_options()
    ( "help", "get this help message" )
    ( "on_change,c", "updates only on change" )
    ( "normalize", "normalize the entries between [0 1] to the maximum entry" )
    ( "reload,r", po::value< int > ( &params.reload )->default_value ( 100 ), "reload time in ms, 0 means reload on signal, -1 means relaod owns to load image into shm" )
    ( "shm_memory_name,m", po::value<std::string> ( &params.shm_memory_name )->default_value ( ShmFw::DEFAULT_SEGMENT_NAME() ), "shared memory segment name" )
    ( "shm_memory_size,s", po::value<unsigned int> ( &params.shm_memory_size )->default_value ( ShmFw::DEFAULT_SEGMENT_SIZE() ), "shared memory segment size" )
    ( "variable_name,v", po::value<std::string> ( &params.variable_name )->default_value ( "image_grid" ), "shared variable name" );

    po::variables_map vm;
    try {
        po::store ( po::parse_command_line ( argc, argv, desc ), vm );
    } catch ( const std::exception &ex ) {
        std::cout << desc << std::endl;;
        exit ( 1 );
    }
    po::notify ( vm );

    if ( vm.count ( "help" ) )  {
        std::cout << desc << std::endl;
        exit ( 1 );
    }
    params.on_change = ( vm.count ( "on_change" ) > 0 );
    params.normalize = ( vm.count ( "normalize" ) > 0 );

    return params;
}

bool loop_program = true;

void terminate ( int param ) {
    std::cout << "Program was trying to abort or terminate." << std::endl;
    loop_program = false;
}

void view_image ( const Prarmeters &params, ShmFw::HandlerPtr &shmHdl ) {
    ShmFw::Var<ShmFw::GridMapInterprocess<uchar > > grid ( params.variable_name, shmHdl );
    std::cout << *grid << " --> ";
    cv::Mat img;
    if ( grid->isType<double> () ) {
        std::cout << " CV_64F";
        img = grid->cvMat ( CV_64F );
    } else if ( grid->isType<float> () ) {
        std::cout << " CV_32F";
        img = grid->cvMat ( CV_32F );
    } else if ( grid->isType<int8_t> () ) {
        std::cout << " CV_8S";
        img = grid->cvMat ( CV_8S );
    } else if ( grid->isType<uint8_t> () ) {
        std::cout << " CV_8U";
        img = grid->cvMat ( CV_8U );
    } else {
        if ( grid->cvtype() != -1 ) {
            std::cout << " CV by depth";
            img = grid->cvMat ( grid->cvtype() );
        } else {
            std::cout << "no matching type!" << std::endl;
            return;
        }
    }
    std::cout << std::endl;

    cv::namedWindow ( params.variable_name.c_str() );
    int key;
    double min, max;
    do {
        cv::Mat tmp = img;
        if ( params.normalize ) {
            tmp = img.clone();
            cv::minMaxLoc ( img, &min, &max );
            tmp = img / max;
            std::cout << "[" << min << ", " << max << " ]" << std::endl;
        }
        cv::imshow ( params.variable_name.c_str(), tmp );
        if ( params.on_change ) {
            key = cv::waitKey ( params.reload );
            while ( grid.timed_wait ( 10000 ) == false ) {
                boost::posix_time::time_duration d = ShmFw::now() - grid.timestampShm();
                std::cout << "Last change " << d.total_milliseconds() << " ms ago!" << std::endl;
            }
        } else {
            key = cv::waitKey ( params.reload );
        }
    } while ( loop_program && ( key < 0 ) );
    cv::destroyWindow ( params.variable_name.c_str() );
}
int main ( int argc, char **argv ) {

    signal ( SIGABRT,	terminate );
    signal ( SIGTERM,	terminate );
    Prarmeters params = readArgs ( argc, argv );
    ShmFw::HandlerPtr shmHdl = ShmFw::Handler::create ( params.shm_memory_name, params.shm_memory_size );
    ShmFw::Header *header = ( ShmFw::Header * ) shmHdl->findName ( params.variable_name );
    if ( header ) {
        view_image ( params, shmHdl );
    }

    exit ( 0 );
}

max_stars_repo_name: ShmFw/shmfw

max_issues_repo_name: ShmFw/shmfw

max_forks_repo_name: ShmFw/shmfw


text:
#include "miningpage.h"
#include "ui_miningpage.h"
#include "main.h"
#include "util.h"
#include "bitcoinrpc.h"
#include "walletmodel.h"

#include <boost/thread.hpp>
#include <stdio.h>

extern json_spirit::Value GetNetworkHashPS(int lookup, int height);

MiningPage::MiningPage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MiningPage),
    hasMiningprivkey(false)
{
    ui->setupUi(this);

    int nThreads = boost::thread::hardware_concurrency();

    int nUseThreads = GetArg("-genproclimit", -1);
    if (nUseThreads < 0)
         nUseThreads = nThreads;

    std::string PrivAddress = GetArg("-miningprivkey", "");
    if (!PrivAddress.empty())
    {
        CBitcoinSecret Secret;
        Secret.SetString(PrivAddress);
        if (Secret.IsValid())
        {
            CBitcoinAddress Address;
            Address.Set(Secret.GetKey().GetPubKey().GetID());
            ui->labelAddress->setText(QString("All mined coins will go to to %1").arg(Address.ToString().c_str()));
            hasMiningprivkey = true;
        }
    }

    ui->sliderCores->setMinimum(0);
    ui->sliderCores->setMaximum(nThreads);
    ui->sliderCores->setValue(nUseThreads);
    ui->labelNCores->setText(QString("%1").arg(nUseThreads));

    connect(ui->sliderCores, SIGNAL(valueChanged(int)), this, SLOT(changeNumberOfCores(int)));
    connect(ui->pushSwitchMining, SIGNAL(clicked()), this, SLOT(switchMining()));

    updateUI();
    startTimer(1500);
}

MiningPage::~MiningPage()
{
    delete ui;
}

void MiningPage::setModel(WalletModel *model)
{
    this->model = model;
}

void MiningPage::updateUI()
{
    int nThreads = boost::thread::hardware_concurrency();

    int nUseThreads = GetArg("-genproclimit", -1);
    if (nUseThreads < 0)
        nUseThreads = nThreads;

    ui->labelNCores->setText(QString("%1").arg(nUseThreads));
    ui->pushSwitchMining->setText(GetBoolArg("-gen", false)? tr("Stop mining") : tr("Start mining"));
}

void MiningPage::restartMining(bool fGenerate)
{
    int nThreads = ui->sliderCores->value();

    mapArgs["-genproclimit"] = QString("%1").arg(nThreads).toUtf8().data();

    // unlock wallet before mining
    if (fGenerate && !hasMiningprivkey && !unlockContext.get())
    {
        this->unlockContext.reset(new WalletModel::UnlockContext(model->requestUnlock()));
        if (!unlockContext->isValid())
        {
            unlockContext.reset(NULL);
            return;
        }
    }

    json_spirit::Array Args;
    Args.push_back(fGenerate);
    Args.push_back(nThreads);
    setgenerate(Args, false);

    // lock wallet after mining
    if (!fGenerate && !hasMiningprivkey)
        unlockContext.reset(NULL);

    updateUI();
}

void MiningPage::changeNumberOfCores(int i)
{
    restartMining(GetBoolArg("-gen"));
}

void MiningPage::switchMining()
{
    restartMining(!GetBoolArg("-gen"));
}

static QString formatTimeInterval(CBigNum t)
{
    enum  EUnit { YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, NUM_UNITS };

    const int SecondsPerUnit[NUM_UNITS] =
    {
        31556952, // average number of seconds in gregorian year
        31556952/12, // average number of seconds in gregorian month
        24*60*60, // number of seconds in a day
        60*60, // number of seconds in an hour
        60, // number of seconds in a minute
        1
    };

    const char* UnitNames[NUM_UNITS] =
    {
        "year",
        "month",
        "day",
        "hour",
        "minute",
        "second"
    };

    if (t > 0xFFFFFFFF)
    {
        t /= SecondsPerUnit[YEAR];
        return QString("%1 years").arg(t.ToString(10).c_str());
    }
    else
    {
        unsigned int t32 = t.getuint();

        int Values[NUM_UNITS];
        for (int i = 0; i < NUM_UNITS; i++)
        {
            Values[i] = t32/SecondsPerUnit[i];
            t32 %= SecondsPerUnit[i];
        }

        int FirstNonZero = 0;
        while (FirstNonZero < NUM_UNITS && Values[FirstNonZero] == 0)
            FirstNonZero++;

        QString TimeStr;
        for (int i = FirstNonZero; i < std::min(FirstNonZero + 3, (int)NUM_UNITS); i++)
        {
            int Value = Values[i];
            TimeStr += QString("%1 %2%3 ").arg(Value).arg(UnitNames[i]).arg((Value == 1)? "" : "s"); // FIXME: this is English specific
        }
        return TimeStr;
    }
}

static QString formatHashrate(int64 n)
{
    if (n == 0)
        return "0 H/s";

    int i = (int)floor(log(n)/log(1000));
    float v = n*pow(1000.0f, -i);

    QString prefix = "";
    if (i >= 1 && i < 9)
        prefix = " kMGTPEZY"[i];

    return QString("%1 %2H/s").arg(v, 0, 'f', 2).arg(prefix);
}

void MiningPage::timerEvent(QTimerEvent *)
{
    int64 NetworkHashrate = GetNetworkHashPS(120, -1).get_int64();
    int64 Hashrate = GetBoolArg("-gen")? gethashespersec(json_spirit::Array(), false).get_int64() : 0;

    QString NextBlockTime;
    if (Hashrate == 0)
        NextBlockTime = QChar(L'∞');
    else
    {
        CBigNum Target;
        Target.SetCompact(pindexBest->nBits);
        CBigNum ExpectedTime = (CBigNum(1) << 256)/(Target*Hashrate);
        NextBlockTime = formatTimeInterval(ExpectedTime);
    }

    ui->labelNethashrate->setText(formatHashrate(NetworkHashrate));
    ui->labelYourHashrate->setText(formatHashrate(Hashrate));
    ui->labelNextBlock->setText(NextBlockTime);
}

ext: cpp


text:
// SPDX-License-Identifier: MIT
// Copyright (c) 2019-2021 Thomas Vanderbruggen <th.vanderbruggen@gmail.com>

#ifndef SCICPP_CORE_META
#define SCICPP_CORE_META

#include <Eigen/Dense>
#include <array>
#include <complex>
#include <ratio>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>

namespace scicpp::meta {

//---------------------------------------------------------------------------------
// is_complex
//---------------------------------------------------------------------------------

namespace detail {

template <class T>
struct is_complex : std::false_type {};
template <class T>
struct is_complex<std::complex<T>> : std::true_type {};

} // namespace detail

template <class T>
constexpr bool is_complex_v = detail::is_complex<T>::value;

template <typename T>
using enable_if_complex = std::enable_if_t<is_complex_v<T>, int>;

template <typename T>
using disable_if_complex = std::enable_if_t<!is_complex_v<T>, int>;

//---------------------------------------------------------------------------------
// is_iterable
//---------------------------------------------------------------------------------

// https://stackoverflow.com/questions/13830158/check-if-a-variable-is-iterable

namespace detail {

// To allow ADL with custom begin/end
using std::begin;
using std::end;

template <typename T>
auto is_iterable_impl(int) -> decltype(
    begin(std::declval<T &>()) !=
        end(std::declval<T &>()), // begin/end and operator !=
    void(),                       // Handle evil operator ,
    ++std::declval<decltype(begin(std::declval<T &>())) &>(), // operator ++
    void(*begin(std::declval<T &>())),                        // operator*
    std::true_type{});

template <typename T>
std::false_type is_iterable_impl(...);

template <typename T>
using is_iterable = decltype(detail::is_iterable_impl<T>(0));

} // namespace detail

template <typename T>
constexpr bool is_iterable_v = detail::is_iterable<T>::value;

template <typename T>
using enable_if_iterable = std::enable_if_t<is_iterable_v<T>, int>;

template <typename T>
using disable_if_iterable = std::enable_if_t<!is_iterable_v<T>, int>;

//---------------------------------------------------------------------------------
// std::vector traits
//---------------------------------------------------------------------------------

namespace detail {

template <class T>
struct is_std_vector : std::false_type {};
template <typename Scalar>
struct is_std_vector<std::vector<Scalar>> : std::true_type {};

} // namespace detail

template <class T>
constexpr bool is_std_vector_v = detail::is_std_vector<T>::value;

//---------------------------------------------------------------------------------
// std::array traits
//---------------------------------------------------------------------------------

namespace detail {

template <class T>
struct is_std_array : std::false_type {};
template <typename Scalar, std::size_t N>
struct is_std_array<std::array<Scalar, N>> : std::true_type {};

} // namespace detail

template <class T>
constexpr bool is_std_array_v = detail::is_std_array<T>::value;

//---------------------------------------------------------------------------------
// std::tuple traits
//---------------------------------------------------------------------------------

namespace detail {

template <class T>
struct is_std_tuple : std::false_type {};
template <typename... Args>
struct is_std_tuple<std::tuple<Args...>> : std::true_type {};

} // namespace detail

template <class T>
constexpr bool is_std_tuple_v = detail::is_std_tuple<T>::value;

//---------------------------------------------------------------------------------
// std::pair traits
//---------------------------------------------------------------------------------

namespace detail {

template <class T>
struct is_std_pair : std::false_type {};
template <typename T1, typename T2>
struct is_std_pair<std::pair<T1, T2>> : std::true_type {};

} // namespace detail

template <class T>
constexpr bool is_std_pair_v = detail::is_std_pair<T>::value;

//---------------------------------------------------------------------------------
// subtuple
// https://stackoverflow.com/questions/17854219/creating-a-sub-tuple-starting-from-a-stdtuplesome-types
//---------------------------------------------------------------------------------

namespace detail {

template <typename... T, std::size_t... I>
constexpr auto subtuple_(const std::tuple<T...> &t,
                         std::index_sequence<I...> /*unused*/) {
    return std::make_tuple(std::get<I>(t)...);
}

} // namespace detail

template <int Trim, typename... T>
constexpr auto subtuple(const std::tuple<T...> &t) {
    return detail::subtuple_(t,
                             std::make_index_sequence<sizeof...(T) - Trim>());
}

template <int Trim = 1, typename T1, typename T2>
constexpr auto subtuple(const std::pair<T1, T2> &t) {
    return std::make_tuple(t.first);
}

//---------------------------------------------------------------------------------
// is_ratio
//---------------------------------------------------------------------------------

namespace detail {

template <class T>
struct is_ratio : std::false_type {};

template <intmax_t num, intmax_t den>
struct is_ratio<std::ratio<num, den>> : std::true_type {};

} // namespace detail

template <class T>
constexpr bool is_ratio_v = detail::is_ratio<T>::value;

//---------------------------------------------------------------------------------
// Eigen type traits
//---------------------------------------------------------------------------------

namespace detail {

template <class T>
struct is_eigen_matrix : std::false_type {};
template <typename Scalar, int RowsAtCompileTime, int ColsAtCompileTime>
struct is_eigen_matrix<
    Eigen::Matrix<Scalar, RowsAtCompileTime, ColsAtCompileTime>>
    : std::true_type {};

template <class T>
struct is_eigen_array : std::false_type {};
template <typename Scalar, int RowsAtCompileTime, int ColsAtCompileTime>
struct is_eigen_array<
    Eigen::Array<Scalar, RowsAtCompileTime, ColsAtCompileTime>>
    : std::true_type {};

} // namespace detail

template <class T>
constexpr bool is_eigen_matrix_v = detail::is_eigen_matrix<T>::value;

template <class T>
constexpr bool is_eigen_array_v = detail::is_eigen_array<T>::value;

template <class T>
constexpr bool is_eigen_container_v =
    is_eigen_matrix_v<T> || is_eigen_array_v<T>;

//---------------------------------------------------------------------------------
// is_predicate
//---------------------------------------------------------------------------------

template <class Predicate, class... Args>
constexpr bool is_predicate =
    std::is_integral_v<std::invoke_result_t<Predicate, Args...>>;

//---------------------------------------------------------------------------------
// is_string
//---------------------------------------------------------------------------------

template <class T>
constexpr bool is_string_v =
    std::is_same_v<const char *, typename std::decay_t<T>> ||
    std::is_same_v<char *, typename std::decay_t<T>> ||
    std::is_same_v<std::string, typename std::decay_t<T>>;

} // namespace scicpp::meta

#endif // SCICPP_CORE_META

ext: hpp

max_stars_repo_name: tvanderbruggen/SciCpp

max_issues_repo_name: tvanderbruggen/SciCpp

max_forks_repo_name: tvanderbruggen/SciCpp


text:
/*! \file versioning_omit_pointers.cpp
    \brief Check if omit is working with derived class registration
    \ingroup tests */
/*
  Copyright (c) 2016, Randolph Voorhies, Shane Grant, Michal Breiter
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:
      * Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
      * Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in the
        documentation and/or other materials provided with the distribution.
      * Neither the name of cereal nor the
        names of its contributors may be used to endorse or promote products
        derived from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES AND SHANE GRANT AND MICHAL BREITER BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "common.hpp"
#include <boost/test/unit_test.hpp>

class A;
class B;
class AA;
class BB;
class AAA;
class BBB;
static const bool WRITE_TO_CONSOLE=false;

static uint8_t A_VERSION_WRITE = 0;
static uint8_t A_VERSION_READ = 0;

class AAA {
  public:
  int aaa;
  virtual ~AAA() {}
  virtual void init() {
    aaa = 123456789;
  }
  bool check() {
    BOOST_CHECK(aaa == 123456789);
    return aaa == 123456789;
  }
  template<class Archive>
  void serialize(Archive & ar, const unsigned int /*version*/) {
    ar & CEREAL_NVP(aaa);
  }
};

class BBB : public AAA {
  public:
  int bbb;
  virtual ~BBB() {}
  virtual void init() {
    AAA::init();
    bbb = 213456789;
  }
  virtual bool check() {
    BOOST_CHECK(bbb == 213456789);
    return AAA::check() && bbb == 213456789;
  }
  template<class Archive>
  void serialize(Archive & ar, const unsigned int /*version*/) {
    ar & cereal::virtual_base_class<AAA>(this);
    ar & CEREAL_NVP(bbb);
  }
};

class AAAA {
  public:
  int aaaa;
  virtual ~AAAA() {}
  virtual void init() {
    aaaa = 123456789;
  }
  bool check() {
    BOOST_CHECK(aaaa == 123456789);
    return aaaa == 123456789;
  }
  template<class Archive>
  void serialize(Archive & ar, const unsigned int /*version*/) {
    ar & CEREAL_NVP(aaaa);
  }
};

class BBBB : public AAAA {
  public:
  int bbbb;
  virtual ~BBBB() {}
  virtual void init() {
    AAAA::init();
    bbbb = 213456788;
  }
  virtual bool check() {
    BOOST_CHECK(bbbb == 213456788);
    return AAAA::check() && bbbb == 213456788;
  }
  template<class Archive>
  void serialize(Archive & ar, const unsigned int /*version*/) {
    ar & cereal::virtual_base_class<AAAA>(this);
    ar & CEREAL_NVP(bbbb);
  }
};

class AA {
  public:
  int aa;
  virtual ~AA() {}

  virtual bool check() {
    BOOST_CHECK(aa == 7892);
    return aa == 7892;
  }

  virtual void init() {
    aa = 7892;
  }
  template<class Archive>
  void serialize(Archive & ar, const unsigned int /*version*/) {
    ar & CEREAL_NVP(aa);
  }
};

class BB : public AA {
  public:
  int bb;
  virtual bool check() {
    BOOST_CHECK(bb == 7891);
    return AA::check() && bb == 7891;
  }

  virtual void init() {
    AA::init();
    bb = 7891;
  }
  template<class Archive>
  void serialize(Archive & ar, const unsigned int /*version*/) {
    ar & cereal::virtual_base_class<AA>(this);
    ar & CEREAL_NVP(bb);
  }
};

class A {
  public:
  enum OmitFields {
    OMIT_NONE = 0,
    OMIT1_FROM_A= 1,
    OMIT2_FROM_A = 2,
    OMIT3_FROM_A = 4,
    SKIP1_FROM_A = 8,
    SKIP2_FROM_A = 16,
    SKIP3_FROM_A = 32,
  };

  std::unique_ptr<AA> AAtoBB1;
  std::unique_ptr<AA> AAtoBB2;
  std::unique_ptr<AAA> AAAtoBBB;

  A() :AAtoBB1(nullptr), AAtoBB2(nullptr), AAAtoBBB(nullptr) {}

  virtual ~A() {}

  void init() {
    AAtoBB1 = std::unique_ptr<AA>(new BB());
    AAtoBB2 = std::unique_ptr<AA>(new BB());
    AAAtoBBB = std::unique_ptr<AAA>(new BBB());

    AAtoBB1->init();
    AAtoBB2->init();
    AAAtoBBB->init();
  }

  template<class Archive>
  void serialize(Archive & ar, const unsigned int /*version*/) {
    uint8_t version = Archive::is_saving::value ? A_VERSION_WRITE : A_VERSION_READ;
    if(WRITE_TO_CONSOLE) std::cout << "\t\tserialize A archive saving?" << Archive::is_saving::value << " version:" << std::bitset<8>(version) << std::endl;
    if(version & OMIT1_FROM_A) {
      ar(cereal::make_nvp("AAtoBB1", cereal::OmittedFieldTag())); // AA*
    } else if(version & SKIP1_FROM_A) {
      return;
      // do nothing
    } else {
      ar & CEREAL_NVP(AAtoBB1);
    }
    if(Archive::is_loading::value) {
      BOOST_CHECK_EQUAL(ar.wasSerialized(), false == (A_VERSION_WRITE & OMIT1_FROM_A));
    }
    if(version & OMIT2_FROM_A) {
      ar(cereal::make_nvp("AAtoBB2", cereal::OmittedFieldTag())); // AA*
    } else if(version & SKIP2_FROM_A) {
      return;
      // do nothing
    } else {
      ar & CEREAL_NVP(AAtoBB2);
    }
    if(Archive::is_loading::value) {
      BOOST_CHECK_EQUAL(ar.wasSerialized(), false == (A_VERSION_WRITE & OMIT2_FROM_A));
    }
    if(version & OMIT3_FROM_A) {
      ar(cereal::make_nvp("AAAtoBBB", cereal::OmittedFieldTag())); // AAA*
    } else if(version & SKIP3_FROM_A) {
      return;
    } else {
      ar & CEREAL_NVP(AAAtoBBB);
    }
    if(Archive::is_loading::value) {
      BOOST_CHECK_EQUAL(ar.wasSerialized(), false == (A_VERSION_WRITE & OMIT3_FROM_A));
    }
  }

  bool check() {
    if(WRITE_TO_CONSOLE) std::cout << "\t\tcheck A archive version write:" << std::bitset<8>(A_VERSION_WRITE) << " version read:" << std::bitset<8>(A_VERSION_WRITE) << std::endl;

    if((A_VERSION_WRITE & SKIP1_FROM_A) || (A_VERSION_READ & SKIP1_FROM_A)) {
      BOOST_CHECK(AAtoBB1 == nullptr);
      BOOST_CHECK(AAtoBB2 ==  nullptr);
      BOOST_CHECK(AAAtoBBB == nullptr);
      return true; // skip next checks
    }
    if((A_VERSION_WRITE & OMIT1_FROM_A) || (A_VERSION_READ & OMIT1_FROM_A)) {
      BOOST_CHECK(AAtoBB1 == nullptr);
    } else {
      BOOST_ASSERT(dynamic_cast<BB*>(AAtoBB1.get()) != nullptr);
      BOOST_CHECK(dynamic_cast<BB*>(AAtoBB1.get())->check());
    }

    if((A_VERSION_WRITE & SKIP2_FROM_A) || (A_VERSION_READ & SKIP2_FROM_A)) {
      BOOST_CHECK(AAtoBB2 == nullptr);
      BOOST_CHECK(AAAtoBBB == nullptr);
      return true;
    }
    if((A_VERSION_WRITE & OMIT2_FROM_A) || (A_VERSION_READ & OMIT2_FROM_A)) {
      BOOST_CHECK(AAtoBB2 == nullptr);
    } else {
      BOOST_ASSERT(dynamic_cast<BB*>(AAtoBB2.get()) != nullptr);
      BOOST_CHECK(dynamic_cast<BB*>(AAtoBB2.get())->check());
    }

    if((A_VERSION_WRITE & SKIP3_FROM_A) || (A_VERSION_READ & SKIP3_FROM_A)) {
      BOOST_CHECK(AAAtoBBB == nullptr);
      return true;
    }
    if((A_VERSION_WRITE & OMIT3_FROM_A) || (A_VERSION_READ & OMIT3_FROM_A)) {
      BOOST_CHECK(AAAtoBBB == nullptr);
    } else {
      BOOST_ASSERT(AAAtoBBB != nullptr);
      BOOST_CHECK(AAAtoBBB->check());
    }
    return true;
  }

};

class B {
  public:
  std::unique_ptr<A> a;

  std::unique_ptr<AAAA> AAAAtoBBBB;
  std::unique_ptr<AA> AAtoBB;
  int o;

  B() :a(nullptr), AAAAtoBBBB(nullptr), o(0) {}

  virtual ~B() {}

  void init() {
    a = std::unique_ptr<A>(new A());
    AAAAtoBBBB = std::unique_ptr<AAAA>(new BBBB());
    o = 12468546;

    AAAAtoBBBB->init();
    a->init();

    AAtoBB = std::unique_ptr<AA>(new BB());
    AAtoBB->init();
  }

  template<class Archive>
  void serialize(Archive & ar, const unsigned int /*version*/) {
    if(WRITE_TO_CONSOLE) std::cout << "\tserialize B archive saving?" << Archive::is_saving::value << std::endl;
    ar & CEREAL_NVP(a);
    ar & CEREAL_NVP(o);
    ar & CEREAL_NVP(AAAAtoBBBB);
    ar & CEREAL_NVP(AAtoBB);
  }
  bool check() {
    if(WRITE_TO_CONSOLE) std::cout << "\tcheck B" << std::endl;
    BOOST_CHECK(a != nullptr);
    BOOST_CHECK(o == 12468546);
    BOOST_CHECK(AAAAtoBBBB != nullptr);
    BOOST_ASSERT(dynamic_cast<BBBB*>(AAAAtoBBBB.get()) != nullptr);
    BOOST_ASSERT(AAtoBB != nullptr);
    BOOST_ASSERT(dynamic_cast<BB*>(AAtoBB.get()) != nullptr);
    return a != nullptr && AAAAtoBBBB != nullptr && a->check() && AAAAtoBBBB->check() && AAtoBB->check();
  }

};

/* added mostly to use shared static objects for function coverage */
struct AllShared
{
  std::shared_ptr<AA> aa;
  std::shared_ptr<AAA> aaa;
  std::shared_ptr<AAAA> aaaa;

  void init() {
    aa = std::make_shared<BB>();
    aaa = std::make_shared<BBB>();
    aaaa = std::make_shared<BBBB>();
  }

  bool check() {
    BOOST_CHECK(aa != nullptr);
    BOOST_CHECK(aaa != nullptr);
    BOOST_CHECK(aaaa != nullptr);
    return aa != nullptr && aaa != nullptr && aaaa != nullptr;
  }

  template<class Archive>
  void serialize(Archive & ar) {
    ar(CEREAL_NVP(aa));
    ar(CEREAL_NVP(aaa));
    ar(CEREAL_NVP(aaaa));
  }

};

CEREAL_REGISTER_TYPE(BB)
CEREAL_REGISTER_TYPE(BBB)
CEREAL_REGISTER_TYPE(BBBB)

template <class Main, class IArchive, class OArchive>
static bool check_both(uint8_t write, uint8_t read) {
  A_VERSION_WRITE = write;
  A_VERSION_READ = read;
  if (WRITE_TO_CONSOLE) std::cout << "check_both write:" << std::bitset<8>(write) << " read: " << std::bitset<8>(read) << std::endl;

  bool ok = false;
  std::ostringstream os(std::ios_base::binary | std::ios_base::out);
  {
    Main b;
    b.init();
    OArchive ar(os);
    ar(b);
  }
  try {
    Main b;
    std::istringstream is(os.str(), std::ios_base::binary | std::ios_base::in);
    IArchive ar(is);
    ar(b);
    ok = b.check();
  } catch (const std::exception & e) {
    std::cerr << "exception: " << e.what() << "\n";
    BOOST_CHECK(false);
  }
  if (WRITE_TO_CONSOLE) std::cout << std::endl;
  BOOST_CHECK(ok);
  return ok;
}

template <class IArchive, class OArchive>
static bool check_first_none(uint8_t two) {
  return check_both<IArchive, OArchive>(A::OMIT_NONE, two);
}

namespace cereal {
  template <class Archive> inline
  typename std::enable_if<!cereal::traits::is_same_archive<Archive, cereal::ExtendableBinaryInputArchive>::value
                          && !cereal::traits::is_same_archive<Archive, cereal::ExtendableBinaryOutputArchive>::value, void>::type
  CEREAL_SERIALIZE_FUNCTION_NAME( Archive &, OmittedFieldTag & )
  {
    throw std::runtime_error("Should not be called, not implemented");
  }

} // namespace cereal

// comma cannot be in BOOST_CHECK macro
static bool check_both_json(uint8_t write, uint8_t read) {
  return check_both<B, cereal::JSONInputArchive, cereal::JSONOutputArchive>(write, read);
}

static bool check_both_xml(uint8_t write, uint8_t read) {
  return check_both<B, cereal::XMLInputArchive, cereal::XMLOutputArchive>(write, read);
}

static bool check_both_binary(uint8_t write, uint8_t read) {
  return check_both<B, cereal::PortableBinaryInputArchive, cereal::PortableBinaryOutputArchive>(write, read)
         && check_both<B, cereal::BinaryInputArchive, cereal::BinaryOutputArchive>(write, read);
}

static bool check_both_extendable_binary(uint8_t write, uint8_t read) {
  return check_both<B, cereal::ExtendableBinaryInputArchive, cereal::ExtendableBinaryOutputArchive>(write, read);
}

static bool check_first_none_json(uint8_t two) {
  return check_both<B, cereal::JSONInputArchive, cereal::JSONOutputArchive>(A::OMIT_NONE, two);
}

static bool check_first_none_extendable_binary(uint8_t two) {
  return check_both<B, cereal::ExtendableBinaryInputArchive, cereal::ExtendableBinaryOutputArchive>(A::OMIT_NONE, two);
}

BOOST_AUTO_TEST_SUITE(OmitClassRegistration)

  BOOST_AUTO_TEST_CASE(AllShared)
  {
    bool json = check_both<::AllShared, cereal::JSONInputArchive,
        cereal::JSONOutputArchive>(A::OMIT_NONE, A::OMIT_NONE);
    BOOST_CHECK(json);
    bool xml = check_both<::AllShared, cereal::XMLInputArchive,
        cereal::XMLOutputArchive>(A::OMIT_NONE, A::OMIT_NONE);
    BOOST_CHECK(xml);
    bool pbinary = check_both<::AllShared, cereal::PortableBinaryInputArchive,
        cereal::PortableBinaryOutputArchive>(A::OMIT_NONE, A::OMIT_NONE);
    BOOST_CHECK(pbinary);
    bool binary = check_both<::AllShared, cereal::BinaryInputArchive,
        cereal::BinaryOutputArchive>(A::OMIT_NONE, A::OMIT_NONE);

    BOOST_CHECK(binary);
    bool ebinary = check_both<::AllShared, cereal::ExtendableBinaryInputArchive,
        cereal::ExtendableBinaryOutputArchive>(A::OMIT_NONE, A::OMIT_NONE);
    BOOST_CHECK(ebinary);

    auto json_omit = []() {
      return check_both<::B, cereal::JSONInputArchive,
          cereal::JSONOutputArchive>(A::OMIT1_FROM_A, A::OMIT1_FROM_A);
    };
    BOOST_CHECK_THROW(json_omit(), std::runtime_error);
    auto xml_omit = []() {
      return check_both<::B, cereal::XMLInputArchive,
          cereal::XMLOutputArchive>(A::OMIT1_FROM_A, A::OMIT1_FROM_A);
    };
    BOOST_CHECK_THROW(xml_omit(), std::runtime_error);
    auto pbinary_omit = []() {
      return check_both<::B, cereal::PortableBinaryInputArchive,
          cereal::PortableBinaryOutputArchive>(A::OMIT1_FROM_A, A::OMIT1_FROM_A);
    };
    BOOST_CHECK_THROW(pbinary_omit(), std::runtime_error);
    auto binary_omit = []() {
      return check_both<::B, cereal::BinaryInputArchive,
          cereal::BinaryOutputArchive>(A::OMIT1_FROM_A, A::OMIT1_FROM_A);

    };
    BOOST_CHECK_THROW(binary_omit(), std::runtime_error);
//    auto ebinary_omit = []() {
//      return check_both<::AllShared, cereal::ExtendableBinaryInputArchive,
//          cereal::ExtendableBinaryOutputArchive>(A::OMIT1_FROM_A, A::OMIT1_FROM_A);
//    };
//    BOOST_CHECK_THROW(ebinary_omit(), std::runtime_error);
  }

/* both are reading and saving same fields */
  BOOST_AUTO_TEST_CASE(OmitNone)
  {
    BOOST_CHECK(check_both_json(A::OMIT_NONE, A::OMIT_NONE));
    BOOST_CHECK(check_both_xml(A::OMIT_NONE, A::OMIT_NONE));
    BOOST_CHECK(check_both_extendable_binary(A::OMIT_NONE, A::OMIT_NONE));
    BOOST_CHECK(check_both_binary(A::OMIT_NONE, A::OMIT_NONE));
  }

  BOOST_AUTO_TEST_CASE(BothSkip1)
  {
    BOOST_CHECK(check_both_json(A::SKIP1_FROM_A, A::SKIP1_FROM_A));
    BOOST_CHECK(check_both_xml(A::SKIP1_FROM_A, A::SKIP1_FROM_A));
    BOOST_CHECK(check_both_extendable_binary(A::SKIP1_FROM_A, A::SKIP1_FROM_A));
    BOOST_CHECK(check_both_binary(A::SKIP1_FROM_A, A::SKIP1_FROM_A));
  }

  BOOST_AUTO_TEST_CASE(BothSkip2)
  {
    BOOST_CHECK(check_both_json(A::SKIP2_FROM_A, A::SKIP2_FROM_A));
    BOOST_CHECK(check_both_xml(A::SKIP2_FROM_A, A::SKIP2_FROM_A));
    BOOST_CHECK(check_both_extendable_binary(A::SKIP2_FROM_A, A::SKIP2_FROM_A));
    BOOST_CHECK(check_both_binary(A::SKIP2_FROM_A, A::SKIP2_FROM_A));
  }

  BOOST_AUTO_TEST_CASE(BothSkip3)
  {
    BOOST_CHECK(check_both_json(A::SKIP3_FROM_A, A::SKIP3_FROM_A));
    BOOST_CHECK(check_both_xml(A::SKIP3_FROM_A, A::SKIP3_FROM_A));
    BOOST_CHECK(check_both_extendable_binary(A::SKIP3_FROM_A, A::SKIP3_FROM_A));
    BOOST_CHECK(check_both_binary(A::SKIP3_FROM_A, A::SKIP3_FROM_A));
  }

  BOOST_AUTO_TEST_CASE(OmitBoth1)
  {
    BOOST_CHECK(check_both_extendable_binary(A::OMIT1_FROM_A, A::OMIT1_FROM_A));
  }

  BOOST_AUTO_TEST_CASE(OmitBoth2)
  {
    BOOST_CHECK(check_both_extendable_binary(A::OMIT2_FROM_A, A::OMIT2_FROM_A));
  }

  BOOST_AUTO_TEST_CASE(OmitBoth3)
  {
    BOOST_CHECK(check_both_extendable_binary(A::OMIT3_FROM_A, A::OMIT3_FROM_A));
  }

  BOOST_AUTO_TEST_CASE(OmitBoth1a2)
  {
    BOOST_CHECK(check_both_extendable_binary(A::OMIT1_FROM_A | A::OMIT2_FROM_A, A::OMIT1_FROM_A | A::OMIT2_FROM_A));
  }

  BOOST_AUTO_TEST_CASE(OmitBoth1a3)
  {
    BOOST_CHECK(check_both_extendable_binary(A::OMIT1_FROM_A | A::OMIT3_FROM_A, A::OMIT1_FROM_A | A::OMIT3_FROM_A));
  }

  BOOST_AUTO_TEST_CASE(OmitBoth2a3)
  {
    BOOST_CHECK(check_both_extendable_binary(A::OMIT2_FROM_A | A::OMIT3_FROM_A, A::OMIT2_FROM_A | A::OMIT3_FROM_A));
  }

  BOOST_AUTO_TEST_CASE(OmitBoth1a2a3)
  {
    BOOST_CHECK(check_both_extendable_binary(A::OMIT1_FROM_A | A::OMIT2_FROM_A | A::OMIT3_FROM_A,
                                             A::OMIT1_FROM_A | A::OMIT2_FROM_A | A::OMIT3_FROM_A));
  }

/* reading side is omitting fields */

  BOOST_AUTO_TEST_CASE(OmitSec1)
  {
    BOOST_CHECK(check_first_none_extendable_binary(A::OMIT1_FROM_A));
  }

  BOOST_AUTO_TEST_CASE(OmitSec2)
  {
    BOOST_CHECK(check_first_none_extendable_binary(A::OMIT2_FROM_A));
  }

  BOOST_AUTO_TEST_CASE(OmitSec3)
  {
    BOOST_CHECK(check_first_none_extendable_binary(A::OMIT3_FROM_A));
  }

  BOOST_AUTO_TEST_CASE(OmitSec1a2)
  {
    BOOST_CHECK(check_first_none_extendable_binary(A::OMIT1_FROM_A | A::OMIT2_FROM_A));
  }

  BOOST_AUTO_TEST_CASE(OmitSec2a3)
  {
    BOOST_CHECK(check_first_none_extendable_binary(A::OMIT2_FROM_A | A::OMIT3_FROM_A));
  }

  BOOST_AUTO_TEST_CASE(OmitSec1a3)
  {
    BOOST_CHECK(check_first_none_extendable_binary(A::OMIT1_FROM_A | A::OMIT3_FROM_A));
  }

  BOOST_AUTO_TEST_CASE(OmitSec1a2a3)
  {
    BOOST_CHECK(check_first_none_extendable_binary(A::OMIT1_FROM_A | A::OMIT2_FROM_A | A::OMIT3_FROM_A));
  }

/* reading side is skipping fields */

  BOOST_AUTO_TEST_CASE(SkipSec1)
  {
    BOOST_CHECK(check_first_none_extendable_binary(A::SKIP1_FROM_A));
    // BOOST_CHECK(check_first_none_json(A::SKIP1_FROM_A)); not working
  }

  BOOST_AUTO_TEST_CASE(SkipSec2)
  {
    BOOST_CHECK(check_first_none_extendable_binary(A::SKIP2_FROM_A));
    BOOST_CHECK(check_first_none_json(A::SKIP2_FROM_A));
  }

  BOOST_AUTO_TEST_CASE(SkipSec3)
  {
    BOOST_CHECK(check_first_none_extendable_binary(A::SKIP3_FROM_A));
    BOOST_CHECK(check_first_none_json(A::SKIP3_FROM_A));
  }

/* writing side is skipping fields */
  BOOST_AUTO_TEST_CASE(OmitFirst1)
  {
    BOOST_CHECK(check_both_extendable_binary(A::OMIT1_FROM_A, A::OMIT_NONE));
  }

  BOOST_AUTO_TEST_CASE(OmitFirst2)
  {
    BOOST_CHECK(check_both_extendable_binary(A::OMIT2_FROM_A, A::OMIT_NONE));
  }

  BOOST_AUTO_TEST_CASE(OmitFirst3)
  {
    BOOST_CHECK(check_both_extendable_binary(A::OMIT3_FROM_A, A::OMIT_NONE));
  }

  BOOST_AUTO_TEST_CASE(OmitFirst1a2)
  {
    BOOST_CHECK(check_both_extendable_binary(A::OMIT1_FROM_A | A::OMIT2_FROM_A, A::OMIT_NONE));
  }

  BOOST_AUTO_TEST_CASE(OmitFirst2a3)
  {
    BOOST_CHECK(check_both_extendable_binary(A::OMIT1_FROM_A | A::OMIT3_FROM_A, A::OMIT_NONE));
  }

  BOOST_AUTO_TEST_CASE(OmitNone1a2a3)
  {
    BOOST_CHECK(check_both_extendable_binary(A::OMIT1_FROM_A | A::OMIT2_FROM_A | A::OMIT3_FROM_A, A::OMIT_NONE));
  }

#if 0
  /* Optional loading of all fields, not only omitted field would be required to pass this tests */
/* skip first */
  BOOST_AUTO_TEST_CASE( SkipFirst1 ) {
    BOOST_CHECK(check_both_extendable_binary(A::SKIP1_FROM_A, A::OMIT_NONE));
  }
  BOOST_AUTO_TEST_CASE( SkipFirst2 ) {
    BOOST_CHECK(check_both_extendable_binary(A::SKIP2_FROM_A, A::OMIT_NONE));
  }
  BOOST_AUTO_TEST_CASE( SkipFirst3 ) {
    BOOST_CHECK(check_both_extendable_binary(A::SKIP3_FROM_A, A::OMIT_NONE));
  }

/* mixed skip */
  BOOST_AUTO_TEST_CASE( SkipFirst1Sec2 ) {
    BOOST_CHECK(check_both(A::SKIP1_FROM_A, A::SKIP2_FROM_A));
  }
  BOOST_AUTO_TEST_CASE( SkipFirst1Sec3 ) {
    BOOST_CHECK(check_both(A::SKIP1_FROM_A, A::SKIP3_FROM_A));
  }

  BOOST_AUTO_TEST_CASE( SkipFirst2Sec1 ) {
    BOOST_CHECK(check_both(A::SKIP2_FROM_A, A::SKIP1_FROM_A));
  }
  BOOST_AUTO_TEST_CASE( SkipFirst2Sec3 ) {
    BOOST_CHECK(check_both(A::SKIP2_FROM_A, A::SKIP3_FROM_A));
  }

  BOOST_AUTO_TEST_CASE( SkipFirst3Sec1 ) {
    BOOST_CHECK(check_both(A::SKIP3_FROM_A, A::SKIP1_FROM_A));
  }
  BOOST_AUTO_TEST_CASE( SkipFirst3Sec2 ) {
    BOOST_CHECK(check_both(A::SKIP3_FROM_A, A::SKIP2_FROM_A));
  }
#endif

BOOST_AUTO_TEST_SUITE_END()


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 <array>
#include <boost/test/unit_test.hpp>
#include <climits>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <numeric>
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/transport/TBufferTransports.h>
#include <vector>

#include "gen-cpp/ThriftTest_types.h"

BOOST_AUTO_TEST_SUITE(TMemoryBufferTest)

using apache::thrift::protocol::TBinaryProtocol;
using apache::thrift::transport::TMemoryBuffer;
using apache::thrift::transport::TTransportException;
using std::shared_ptr;
using std::cout;
using std::endl;
using std::string;

BOOST_AUTO_TEST_CASE(test_read_write_grow) {
  // Added to test the fix for THRIFT-1248
  TMemoryBuffer uut;
  const int maxSize = 65536;
  uint8_t verify[maxSize];
  std::vector<uint8_t> buf;
  buf.resize(maxSize);

  for (uint32_t i = 0; i < maxSize; ++i) {
    buf[i] = static_cast<uint8_t>(i);
  }

  for (uint32_t i = 1; i < maxSize; i *= 2) {
    uut.write(&buf[0], i);
  }

  for (uint32_t i = 1; i < maxSize; i *= 2) {
    uut.read(verify, i);
    BOOST_CHECK_EQUAL(0, ::memcmp(verify, &buf[0], i));
  }
}

BOOST_AUTO_TEST_CASE(test_roundtrip) {
  shared_ptr<TMemoryBuffer> strBuffer(new TMemoryBuffer());
  shared_ptr<TBinaryProtocol> binaryProtcol(new TBinaryProtocol(strBuffer));

  thrift::test::Xtruct a;
  a.i32_thing = 10;
  a.i64_thing = 30;
  a.string_thing = "holla back a";

  a.write(binaryProtcol.get());
  std::string serialized = strBuffer->getBufferAsString();

  shared_ptr<TMemoryBuffer> strBuffer2(new TMemoryBuffer());
  shared_ptr<TBinaryProtocol> binaryProtcol2(new TBinaryProtocol(strBuffer2));

  strBuffer2->resetBuffer((uint8_t*)serialized.data(), static_cast<uint32_t>(serialized.length()));
  thrift::test::Xtruct a2;
  a2.read(binaryProtcol2.get());

  BOOST_CHECK(a == a2);
}

BOOST_AUTO_TEST_CASE(test_readAppendToString) {
  string str1 = "abcd1234";
  TMemoryBuffer buf((uint8_t*)str1.data(),
                    static_cast<uint32_t>(str1.length()),
                    TMemoryBuffer::COPY);

  string str3 = "wxyz", str4 = "6789";
  buf.readAppendToString(str3, 4);
  buf.readAppendToString(str4, INT_MAX);

  BOOST_CHECK(str3 == "wxyzabcd");
  BOOST_CHECK(str4 == "67891234");
}

BOOST_AUTO_TEST_CASE(test_exceptions) {
  char data[] = "foo\0bar";

  TMemoryBuffer buf1((uint8_t*)data, 7, TMemoryBuffer::OBSERVE);
  string str = buf1.getBufferAsString();
  BOOST_CHECK(str.length() == 7);

  buf1.resetBuffer();

  BOOST_CHECK_THROW(buf1.write((const uint8_t*)"foo", 3), TTransportException);

  TMemoryBuffer buf2((uint8_t*)data, 7, TMemoryBuffer::COPY);
  BOOST_CHECK_NO_THROW(buf2.write((const uint8_t*)"bar", 3));
}

BOOST_AUTO_TEST_CASE(test_default_maximum_buffer_size)
{
  BOOST_CHECK_EQUAL((std::numeric_limits<uint32_t>::max)(), TMemoryBuffer().getMaxBufferSize());
}

BOOST_AUTO_TEST_CASE(test_default_buffer_size)
{
  BOOST_CHECK_EQUAL(1024, TMemoryBuffer().getBufferSize());
}

BOOST_AUTO_TEST_CASE(test_error_set_max_buffer_size_too_small)
{
  TMemoryBuffer buf;
  BOOST_CHECK_THROW(buf.setMaxBufferSize(buf.getBufferSize() - 1), TTransportException);
}

BOOST_AUTO_TEST_CASE(test_observe) {
#ifdef _MSC_VER
  #define N 73
#else
  constexpr size_t N = 73;
#endif
  constexpr size_t M = 42;
  uint8_t one_byte = 42;
  std::vector<uint8_t> scratch;
  auto filler = [=]() {
    std::array<uint8_t, N> x;
    // Fill buf_mem with a sequence from 0 to N - 1
    std::iota(x.begin(), x.end(), 0);
    return x;
  };
  static const std::array<uint8_t, N> buf_mem = filler();

  BOOST_STATIC_ASSERT(M < N);

  TMemoryBuffer buf((uint8_t*)&buf_mem.front(), N, TMemoryBuffer::MemoryPolicy::OBSERVE);

  // Readable
  BOOST_CHECK_EQUAL(N, buf.available_read());
  // No available write space
  BOOST_CHECK_EQUAL(0, buf.available_write());
  // Not writeable
  BOOST_CHECK_THROW(buf.write(&one_byte, 1), TTransportException);

  // Read some but not all
  scratch.resize(M);
  BOOST_CHECK_EQUAL(M, buf.read(&scratch[0], M));
  // Check remaining
  BOOST_CHECK_EQUAL(N - M, buf.available_read());
  // No available write space
  BOOST_CHECK_EQUAL(0, buf.available_write());
  // Not writeable
  BOOST_CHECK_THROW(buf.write(&one_byte, 1), TTransportException);
  // Contents
  BOOST_CHECK_EQUAL_COLLECTIONS(scratch.begin(), scratch.end(), buf_mem.begin(),
                                buf_mem.begin() + M);

  // Readable (drain remaining)
  scratch.resize(N);
  BOOST_CHECK_EQUAL(N - M, buf.read(&scratch[M], N - M));
  // No available write space
  BOOST_CHECK_EQUAL(0, buf.available_write());
  // Not writeable
  BOOST_CHECK_THROW(buf.write(&one_byte, 1), TTransportException);
  // Contents
  BOOST_CHECK_EQUAL_COLLECTIONS(scratch.begin(), scratch.end(), buf_mem.begin(), buf_mem.end());

  // Not readable
  BOOST_CHECK_EQUAL(0, buf.read(&one_byte, 1));
  BOOST_CHECK_EQUAL(0, buf.available_read());
  // No available write space
  BOOST_CHECK_EQUAL(0, buf.available_write());
  // Not writeable
  BOOST_CHECK_THROW(buf.write(&one_byte, 1), TTransportException);

  /* OBSERVE buffer cannot be reread with the default reset */

  buf.resetBuffer();
  // Not Readable
  BOOST_CHECK_EQUAL(0, buf.available_read());
  // No available write space
  BOOST_CHECK_EQUAL(0, buf.available_write());
  // Not writeable
  BOOST_CHECK_THROW(buf.write(&one_byte, 1), TTransportException);

  /* OBSERVE buffers do not auto-resize when written to (implicit) */
  /* OBSERVE buffers can be appended-to (implicit) */
}

BOOST_AUTO_TEST_CASE(test_copy) {
#ifdef _MSC_VER
  #define N 73
#else
  constexpr size_t N = 73;
#endif
  constexpr size_t M = 42;
  uint8_t one_byte = 42;
  std::vector<uint8_t> scratch;
  auto filler = [&]() {
    std::array<uint8_t, N> x;
    // Fill buf_mem with a sequence from 0 to N - 1
    std::iota(x.begin(), x.end(), 0);
    return x;
  };
  static const std::array<uint8_t, N> buf_mem = filler();

  BOOST_STATIC_ASSERT(M < N);

  TMemoryBuffer buf((uint8_t*)&buf_mem.front(), N, TMemoryBuffer::MemoryPolicy::COPY);

  // Readable
  BOOST_CHECK_EQUAL(N, buf.available_read());
  // No available write space
  BOOST_CHECK_EQUAL(0, buf.available_write());

  // Read some but not all
  scratch.resize(M);
  BOOST_CHECK_EQUAL(M, buf.read(&scratch[0], M));
  // Check remaining
  BOOST_CHECK_EQUAL(N - M, buf.available_read());
  // No available write space
  BOOST_CHECK_EQUAL(0, buf.available_write());
  // Contents
  BOOST_CHECK_EQUAL_COLLECTIONS(scratch.begin(), scratch.end(), buf_mem.begin(),
                                buf_mem.begin() + M);

  // Readable (drain remaining)
  scratch.resize(N);
  BOOST_CHECK_EQUAL(N - M, buf.read(&scratch[M], N - M));
  // No available write space
  BOOST_CHECK_EQUAL(0, buf.available_write());
  // Contents
  BOOST_CHECK_EQUAL_COLLECTIONS(scratch.begin(), scratch.end(), buf_mem.begin(), buf_mem.end());

  // Not readable
  BOOST_CHECK_EQUAL(0, buf.read(&one_byte, 1));
  BOOST_CHECK_EQUAL(0, buf.available_read());
  // No available write space
  BOOST_CHECK_EQUAL(0, buf.available_write());

  /* COPY buffer cannot be reread with the default reset */

  buf.resetBuffer();
  // Not readable
  BOOST_CHECK_EQUAL(0, buf.available_read());
  // Has available write space
  BOOST_CHECK_EQUAL(N, buf.available_write());

  /* COPY buffers auto-resize when written to */

  // Not readable
  BOOST_CHECK_EQUAL(0, buf.read(&one_byte, 1));
  BOOST_CHECK_EQUAL(0, buf.available_read());
  // No available write space
  BOOST_CHECK_GT(buf.available_write(), 0);
  // Writeable
  one_byte = M;
  BOOST_CHECK_NO_THROW(buf.write(&one_byte, 1));
  // Readable
  one_byte = 0xff;
  BOOST_CHECK_EQUAL(1, buf.read(&one_byte, 1));
  BOOST_CHECK_EQUAL(one_byte, M);

  /* COPY buffers can be appended-to (and auto-resize) */

  buf.resetBuffer((uint8_t*)&buf_mem.front(), N, TMemoryBuffer::MemoryPolicy::COPY);
  // Appendable
  one_byte = N + 1;
  BOOST_CHECK_NO_THROW(buf.write(&one_byte, 1));
  BOOST_CHECK_EQUAL(N, buf.read(&scratch[0], N));
  BOOST_CHECK_EQUAL_COLLECTIONS(scratch.begin(), scratch.end(), buf_mem.begin(),
                                buf_mem.begin() + N);
  one_byte = 0xff;
  BOOST_CHECK_EQUAL(1, buf.read(&one_byte, 1));
  BOOST_CHECK_EQUAL(one_byte, N + 1);
}

BOOST_AUTO_TEST_CASE(test_take_ownership)
{
#ifdef _MSC_VER
  #define N 73
#else
  constexpr size_t N = 73;
#endif
  constexpr size_t M = 42;
  uint8_t one_byte = 42;
  std::vector<uint8_t> scratch;
  auto filler = [&]() {
    /* TAKE_OWNERSHIP buffers MUST be malloc'ed */
    uint8_t* x = static_cast<uint8_t*>(malloc(N));
    // Fill buf_mem with a sequence from 0 to N - 1
    std::iota(&x[0], &x[N], 0);
    return x;
  };
  uint8_t* buf_mem = filler();

  BOOST_STATIC_ASSERT(M < N);

  TMemoryBuffer buf(buf_mem, N, TMemoryBuffer::MemoryPolicy::TAKE_OWNERSHIP);

  // Readable
  BOOST_CHECK_EQUAL(N, buf.available_read());
  // No available write space
  BOOST_CHECK_EQUAL(0, buf.available_write());

  // Read some but not all
  scratch.resize(M);
  BOOST_CHECK_EQUAL(M, buf.read(&scratch[0], M));
  // Check remaining
  BOOST_CHECK_EQUAL(N - M, buf.available_read());
  // No available write space
  BOOST_CHECK_EQUAL(0, buf.available_write());
  // Contents
  BOOST_CHECK_EQUAL_COLLECTIONS(scratch.begin(), scratch.end(), &buf_mem[0], &buf_mem[M]);

  // Readable (drain remaining)
  scratch.resize(N);
  BOOST_CHECK_EQUAL(N - M, buf.read(&scratch[M], N - M));
  // No available write space
  BOOST_CHECK_EQUAL(0, buf.available_write());
  // Contents
  BOOST_CHECK_EQUAL_COLLECTIONS(scratch.begin(), scratch.end(), &buf_mem[0], &buf_mem[N]);

  // Not readable
  BOOST_CHECK_EQUAL(0, buf.read(&one_byte, 1));
  BOOST_CHECK_EQUAL(0, buf.available_read());
  // No available write space
  BOOST_CHECK_EQUAL(0, buf.available_write());

  /* TAKE_OWNERSHIP buffers auto-resize when written to */

  // Not readable
  BOOST_CHECK_EQUAL(0, buf.read(&one_byte, 1));
  BOOST_CHECK_EQUAL(0, buf.available_read());
  // No available write space
  BOOST_CHECK_EQUAL(buf.available_write(), 0);
  // Writeable
  one_byte = M;
  BOOST_CHECK_NO_THROW(buf.write(&one_byte, 1));
  // Readable
  one_byte = 0xff;
  BOOST_CHECK_EQUAL(1, buf.read(&one_byte, 1));
  BOOST_CHECK_EQUAL(one_byte, M);

  /* TAKE_OWNERSHIP buffers can be appended-to (and auto-resize) */

  buf_mem = filler();
  buf.resetBuffer(buf_mem, N, TMemoryBuffer::MemoryPolicy::COPY);
  // Appendable
  one_byte = N + 1;
  BOOST_CHECK_NO_THROW(buf.write(&one_byte, 1));
  BOOST_CHECK_EQUAL(N, buf.read(&scratch[0], N));
  BOOST_CHECK_EQUAL_COLLECTIONS(scratch.begin(), scratch.end(), &buf_mem[0], &buf_mem[N]);
  one_byte = 0xff;
  BOOST_CHECK_EQUAL(1, buf.read(&one_byte, 1));
  BOOST_CHECK_EQUAL(one_byte, N + 1);
}

BOOST_AUTO_TEST_CASE(test_maximum_buffer_size)
{
  TMemoryBuffer buf;
  buf.setMaxBufferSize(8192);
  std::vector<uint8_t> small_buff(1);

  for (size_t i = 0; i < 8192; ++i)
  {
    buf.write(&small_buff[0], 1);
  }

  BOOST_CHECK_THROW(buf.write(&small_buff[0], 1), TTransportException);
}

BOOST_AUTO_TEST_CASE(test_memory_buffer_to_get_sizeof_objects)
{
  // This is a demonstration of how to use TMemoryBuffer to determine
  // the serialized size of a thrift object in the Binary protocol.
  // See THRIFT-3480

  shared_ptr<TMemoryBuffer> memBuffer(new TMemoryBuffer());
  shared_ptr<TBinaryProtocol> binaryProtcol(new TBinaryProtocol(memBuffer));

  thrift::test::Xtruct object;
  object.i32_thing = 10;
  object.i64_thing = 30;
  object.string_thing = "who's your daddy?";

  uint32_t size = object.write(binaryProtcol.get());
  BOOST_CHECK_EQUAL(47, size);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: Jimexist/thrift

max_issues_repo_name: Jimexist/thrift

max_forks_repo_name: Jimexist/thrift


text:
/*!
@file
Forward declares `boost::hana::length`.

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

#ifndef BOOST_HANA_FWD_LENGTH_HPP
#define BOOST_HANA_FWD_LENGTH_HPP

#include <boost/hana/config.hpp>
#include <boost/hana/core/when.hpp>

BOOST_HANA_NAMESPACE_BEGIN
    //! Return the number of elements in a foldable structure.
    //! @ingroup group-Foldable
    //!
    //! Given a `Foldable` `xs`, `length(xs)` must return an object of an
    //! unsigned integral type, or an `IntegralConstant` holding such an
    //! object, which represents the number of elements in the structure.
    //!
    //! @note
    //! Since only compile-time `Foldable`s are supported in the library
    //! right now, `length` must always return an `IntegralConstant`.
    //!
    //!
    //! Example
    //! -------
    //! @include example/length.cpp
#ifdef BOOST_HANA_DOXYGEN_INVOKED
    constexpr auto length = [](auto const& xs) {
        return tag-dispatched;
    };
#else
    template <typename T, typename = void>
    struct length_impl : length_impl<T, when<true>> { };

    struct length_t {
        template <typename Xs>
        constexpr auto operator()(Xs const& xs) const;
    };

    BOOST_HANA_INLINE_VARIABLE constexpr length_t length{};
#endif
BOOST_HANA_NAMESPACE_END

#endif // !BOOST_HANA_FWD_LENGTH_HPP


text:
#include <iostream>
#include <armadillo>

using namespace std;
using namespace arma;

int main()
{

    int sx = 200;
    int nx= 400;
    int offset = 100;

    arma::Col<float> geo_line_all(nx,fill::zeros);
    arma::Col<float> geo_line(offset*2,fill::zeros);

    geo_line_all.load("./surface_all.dat",raw_binary);

for(int ix=0; ix<offset; ix++)
{
    geo_line(ix*2) = ix;
    geo_line(ix*2+1) = geo_line_all(sx-offset/2+ix);
}

    geo_line.save("./surface_singal_ASCII.dat",raw_ascii);

    return 0;
}


text:
/*
 * Copyright (c) 2016 Juniper Networks, Inc. All rights reserved.
 */
#include "config_client_manager.h"

#include <boost/assign/list_of.hpp>
#include <sandesh/sandesh_types.h>
#include <sandesh/sandesh.h>
#include <sandesh/request_pipeline.h>

#include "base/connection_info.h"
#include "base/task.h"
#include "config_amqp_client.h"
#include "config_db_client.h"
#include "config_cassandra_client.h"
#include "config_json_parser.h"
#include "ifmap/ifmap_config_options.h"
#include "ifmap/ifmap_factory.h"
#include "ifmap/ifmap_log.h"
#include "ifmap/ifmap_log_types.h"
#include "ifmap/ifmap_server.h"
#include "ifmap/ifmap_sandesh_context.h"
#include "ifmap/ifmap_server_show_types.h"
#include "ifmap/ifmap_server_table.h"
#include "io/event_manager.h"
#include "schema/bgp_schema_types.h"
#include "schema/vnc_cfg_types.h"

using namespace boost::assign;
using namespace std;

const set<string> ConfigClientManager::skip_properties = list_of("perms2");

int ConfigClientManager::GetNumConfigReader() {
    static bool init_ = false;
    static int num_config_readers = 0;

    if (!init_) {
        // XXX To be used for testing purposes only.
        char *count_str = getenv("CONFIG_NUM_WORKERS");
        if (count_str) {
            num_config_readers = strtol(count_str, NULL, 0);
        } else {
            num_config_readers = kNumConfigReaderTasks;
        }
        init_ = true;
    }
    return num_config_readers;
}

ConfigClientManager::ConfigClientManager(EventManager *evm,
        IFMapServer *ifmap_server, string hostname, string module_name,
        const IFMapConfigOptions& config_options)
        : evm_(evm), ifmap_server_(ifmap_server) {
    config_json_parser_.reset(new ConfigJsonParser(this));
    thread_count_ = GetNumConfigReader();
    end_of_rib_computed_ = false;
    end_of_rib_computed_at_ = UTCTimestampUsec();
    config_db_client_.reset(
            IFMapFactory::Create<ConfigCassandraClient>(this, evm,
                config_options, config_json_parser_.get(), thread_count_));
    config_amqp_client_.reset(new ConfigAmqpClient(this, hostname, module_name,
                                                   config_options));
    vnc_cfg_FilterInfo vnc_filter_info;
    bgp_schema_FilterInfo bgp_schema_filter_info;

    bgp_schema_Server_GenerateGraphFilter(&bgp_schema_filter_info);
    vnc_cfg_Server_GenerateGraphFilter(&vnc_filter_info);

    for (vnc_cfg_FilterInfo::iterator it = vnc_filter_info.begin();
         it != vnc_filter_info.end(); it++) {
        link_name_map_.insert(make_pair(make_pair(it->left_, it->right_),
                                    make_pair(it->metadata_, it->linkattr_)));
    }

    for (bgp_schema_FilterInfo::iterator it = bgp_schema_filter_info.begin();
         it != bgp_schema_filter_info.end(); it++) {
        link_name_map_.insert(make_pair(make_pair(it->left_, it->right_),
                                    make_pair(it->metadata_, it->linkattr_)));
    }

    bgp_schema_Server_GenerateWrapperPropertyInfo(&wrapper_field_map_);
    vnc_cfg_Server_GenerateWrapperPropertyInfo(&wrapper_field_map_);

    bgp_schema_Server_GenerateObjectTypeList(&obj_type_to_read_);
    vnc_cfg_Server_GenerateObjectTypeList(&obj_type_to_read_);
}

void ConfigClientManager::Initialize() {
    config_db_client_->InitDatabase();
}

ConfigJsonParser *ConfigClientManager::config_json_parser() const {
    return config_json_parser_.get();
}

ConfigDbClient *ConfigClientManager::config_db_client() const {
    return config_db_client_.get();
}

ConfigAmqpClient *ConfigClientManager::config_amqp_client() const {
    return config_amqp_client_.get();
}

bool ConfigClientManager::GetEndOfRibComputed() const {
    tbb::mutex::scoped_lock lock(end_of_rib_sync_mutex_);
    return end_of_rib_computed_;
}

void ConfigClientManager::EnqueueUUIDRequest(string oper, string obj_type,
                                             string uuid_str) {
    config_db_client_->EnqueueUUIDRequest(oper, obj_type, uuid_str);
}

void ConfigClientManager::InsertRequestIntoQ(IFMapOrigin::Origin origin,
        const string &neigh_type, const string &neigh_name,
        const string &metaname, auto_ptr<AutogenProperty > pvalue,
        const IFMapTable::RequestKey &key, bool add_change,
        RequestList *req_list) const {

    IFMapServerTable::RequestData *data =
        new IFMapServerTable::RequestData(origin, neigh_type, neigh_name);
    data->metadata = metaname;
    data->content.reset(pvalue.release());

    DBRequest *db_request = new DBRequest();
    db_request->oper = (add_change ? DBRequest::DB_ENTRY_ADD_CHANGE :
                        DBRequest::DB_ENTRY_DELETE);
    db_request->key.reset(CloneKey(key));
    db_request->data.reset(data);

    req_list->push_back(db_request);
}

void ConfigClientManager::EnqueueListToTables(RequestList *req_list) const {
    while (!req_list->empty()) {
        auto_ptr<DBRequest> req(req_list->front());
        req_list->pop_front();
        IFMapTable::RequestKey *key =
            static_cast<IFMapTable::RequestKey *>(req->key.get());

        IFMapTable *table = IFMapTable::FindTable(ifmap_server_->database(),
                                                  key->id_type);
        if (table != NULL) {
            table->Enqueue(req.get());
        } else {
            IFMAP_TRACE(IFMapTblNotFoundTrace, "Cant find table", key->id_type);
        }
    }
}

IFMapTable::RequestKey *ConfigClientManager::CloneKey(
        const IFMapTable::RequestKey &src) const {
    IFMapTable::RequestKey *retkey = new IFMapTable::RequestKey();
    retkey->id_type = src.id_type;
    retkey->id_name = src.id_name;
    // TODO
    //retkey->id_seq_num = what?
    return retkey;
}

string ConfigClientManager::GetLinkName(const string &left,
                                        const string &right) const {
    LinkNameMap::const_iterator it =
        link_name_map_.find(make_pair(left, right));
    if (it == link_name_map_.end())
        return "";
    return it->second.first;
}

bool ConfigClientManager::IsLinkWithAttr(const string &left,
                                         const string &right) const {
    LinkNameMap::const_iterator it =
        link_name_map_.find(make_pair(left, right));
    if (it == link_name_map_.end())
        return false;
    return it->second.second;
}

string ConfigClientManager::GetWrapperFieldName(const string &type_name,
                                          const string &property_name) const {
    WrapperFieldMap::const_iterator it =
        wrapper_field_map_.find(type_name+':'+property_name);
    if (it == wrapper_field_map_.end()) {
        return "";
    } else {
        // TODO: Fix the autogen to have _ instead of -
        string temp_str = it->second;
        std::replace(temp_str.begin(), temp_str.end(), '-', '_');
        return temp_str;
    }
}

void ConfigClientManager::EndOfConfig() {
    {
        // Notify waiting caller with the resultcjjjkkkk
        tbb::mutex::scoped_lock lock(end_of_rib_sync_mutex_);
        assert(!end_of_rib_computed_);
        end_of_rib_computed_ = true;
        cond_var_.notify_all();
        end_of_rib_computed_at_ = UTCTimestampUsec();
    }

    process::ConnectionState::GetInstance()->Update();
}

void ConfigClientManager::WaitForEndOfConfig() {
    tbb::interface5::unique_lock<tbb::mutex> lock(end_of_rib_sync_mutex_);
    // Wait for End of config
    if (!end_of_rib_computed_)
        cond_var_.wait(lock);
}

void ConfigClientManager::GetPeerServerInfo(
                                        IFMapPeerServerInfoUI *server_info) {
    ConfigDBConnInfo status;

    config_db_client()->GetConnectionInfo(status);
    server_info->set_url(status.cluster);
    server_info->set_connection_status(
                       (status.connection_status ? "Up" : "Down"));
    server_info->set_connection_status_change_at(
                       status.connection_status_change_at);
}

void ConfigClientManager::GetClientManagerInfo(
                                   ConfigClientManagerInfo &info) const {
    tbb::mutex::scoped_lock lock(end_of_rib_sync_mutex_);
    info.end_of_rib_computed = end_of_rib_computed_;
    info.end_of_rib_computed_at = end_of_rib_computed_at_;
}

static bool ConfigClientInfoHandleRequest(const Sandesh *sr,
                                         const RequestPipeline::PipeSpec ps,
                                         int stage, int instNum,
                                         RequestPipeline::InstData *data) {
    const ConfigClientInfoReq *request =
        static_cast<const ConfigClientInfoReq *>(ps.snhRequest_.get());
    ConfigClientInfoResp *response = new ConfigClientInfoResp();
    IFMapSandeshContext *sctx =
        static_cast<IFMapSandeshContext *>(request->module_context("IFMap"));

    ConfigClientManager *config_mgr =
        sctx->ifmap_server()->get_config_manager();

    ConfigAmqpConnInfo amqp_conn_info;
    config_mgr->config_amqp_client()->GetConnectionInfo(amqp_conn_info);

    ConfigDBConnInfo db_conn_info;
    config_mgr->config_db_client()->GetConnectionInfo(db_conn_info);

    ConfigClientManagerInfo client_mgr_info;
    config_mgr->GetClientManagerInfo(client_mgr_info);

    response->set_client_manager_info(client_mgr_info);
    response->set_db_conn_info(db_conn_info);
    response->set_amqp_conn_info(amqp_conn_info);
    response->set_context(request->context());
    response->set_more(false);
    response->Response();
    return true;
}

void ConfigClientInfoReq::HandleRequest() const {
    RequestPipeline::StageSpec s0;
    TaskScheduler *scheduler = TaskScheduler::GetInstance();

    s0.taskId_ = scheduler->GetTaskId("config::SandeshCmd");
    s0.cbFn_ = ConfigClientInfoHandleRequest;
    s0.instances_.push_back(0);

    RequestPipeline::PipeSpec ps(this);
    ps.stages_= list_of(s0);
    RequestPipeline rp(ps);
}

ext: cc

max_stars_repo_name: sagarc-contrail/contrail-controller

max_issues_repo_name: sagarc-contrail/contrail-controller

max_forks_repo_name: sagarc-contrail/contrail-controller


text:
#ifndef NT2_TOOLBOX_MATLAB_DETAILS_ARRAY_CONTAINER_TUPLE_HPP_INCLUDED
#define NT2_TOOLBOX_MATLAB_DETAILS_ARRAY_CONTAINER_TUPLE_HPP_INCLUDED

#include <nt2/toolbox/matlab/details/array/container.hpp>
#include <boost/fusion/include/at_c.hpp>
#include <boost/fusion/include/size.hpp>
#include <boost/fusion/include/boost_array.hpp>

namespace nt2 { namespace matlab
{
    namespace details
    {
        template<typename T, typename Dummy = void>
        struct is_container_tuple
          : boost::mpl::false_
        {
        };

        template<typename T, typename Dummy = void>
        struct primitive_of_container
        {
            typedef T type;
        };

        template<typename T>
        struct primitive_of_container<T, typename boost::enable_if< is_container<T> >::type>
          : primitive_of_container<typename boost::range_value<T>::type>
        {
        };

        template<typename T>
        struct is_container_tuple<
            T,
            typename boost::enable_if<
                boost::mpl::and_<
                    meta::is_fundamental<
                        //typename meta::primitive_of<
                            typename meta::strip<
                                typename boost::mpl::eval_if<
                                    is_container<T>,
                                    primitive_of_container<T>,
                                    dummy
                                >::type
                            >::type
                        //>::type
                    >,
                    boost::fusion::traits::is_sequence<T>
                >
            >::type
        >
          : boost::mpl::true_
        {
        };

        template<typename In, typename Out>
        typename boost::disable_if<
            is_container<typename std::iterator_traits<In>::value_type>,
            Out
        >::type
        copy(In const& begin, In const& end, Out& out)
        {
            return std::copy(begin, end, out);
        }

        template<typename In, typename Out>
        typename boost::enable_if<
            is_container<typename std::iterator_traits<In>::value_type>,
            Out
        >::type
        copy(In const& begin, In const& end, Out& out)
        {
            for(In it = begin; it != end; ++it)
                out = details::copy(boost::begin(*it), boost::end(*it), out);
            return out;
        }

        template<typename T>
        typename boost::disable_if<
            is_container_tuple<T>,
            T&
        >::type
        primitive_of_container_access(T& t)
        {
            return t;
        }

        template<typename T>
        typename boost::enable_if<
            is_container_tuple<T>,
            typename primitive_of_container<T>::type&
        >::type
        primitive_of_container_access(T& t)
        {
            return primitive_of_container_access(*boost::begin(t));
        }

        template<typename T, typename Dummy = void>
        struct container_nesting_level
        {
            static const std::size_t value = 0;
        };

        template<typename T>
        struct container_nesting_level<T, typename boost::enable_if< is_container_tuple<T> >::type>
        {
            static const std::size_t value =
                container_nesting_level<typename boost::range_value<T>::type>::value
                + 1
            ;
        };

        template<typename T, std::size_t I, std::size_t N>
        typename boost::enable_if_c<I == N>::type
        container_dimensions_fill(boost::array<std::size_t, N>& a)
        {
        }

        template<typename T, std::size_t I, std::size_t N>
        typename boost::disable_if_c<I == N>::type
        container_dimensions_fill(boost::array<std::size_t, N>& a)
        {
            a[I] = boost::fusion::result_of::size<T>::value;
            container_dimensions_fill<typename boost::range_value<T>::type, I+1>(a);
        }
    }

}
namespace meta
{
    template<typename T, std::size_t N>
    struct primitive_of<boost::array<T, N> >
    {
        typedef T type;
    };

    template<typename T, std::size_t N, std::size_t M>
    struct primitive_of<boost::array<boost::array<T, N>, M > >
    {
        typedef T type;
    };
}
namespace matlab {
namespace traits
{
    template<typename T, typename Out>
    struct linearize_impl<T, Out, typename boost::enable_if< details::is_container_tuple<T> >::type>
    {
        static Out call(const T& t, Out out)
        {
            return details::copy(boost::begin(t), boost::end(t), out);
        }
    };

    template<typename T, typename Iterator>
    struct assign_from_iterators_impl<T, Iterator, typename boost::enable_if< details::is_container_tuple<T> >::type>
    {
        static void call(Iterator const& begin, Iterator const& end, T& t)
        {
            std::copy(begin, end, &details::primitive_of_container_access(t));
        }
    };

    namespace result_of
    {
        template<typename T>
        struct size<T, typename boost::enable_if< details::is_container_tuple<T> >::type>
        {
            typedef boost::array<std::size_t, details::container_nesting_level<T>::value> type;
        };
    }

    template<typename T>
    struct size_impl<T, typename boost::enable_if< details::is_container_tuple<T> >::type>
    {
        static typename result_of::size<T>::type call(const T& t)
        {
            typename result_of::size<T>::type a;
            details::container_dimensions_fill<T, 0>(a);
            return a;
        }
    };
}
}}

#endif


text:
///////////////////////////////////////////////////////////////////////////////
// predicate_matcher.hpp
//
//  Copyright 2008 Eric Niebler. 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_XPRESSIVE_DETAIL_CORE_MATCHER_PREDICATE_MATCHER_HPP_EAN_03_22_2007
#define BOOST_XPRESSIVE_DETAIL_CORE_MATCHER_PREDICATE_MATCHER_HPP_EAN_03_22_2007

// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif

#include <boost/mpl/not.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/xpressive/detail/detail_fwd.hpp>
#include <boost/xpressive/detail/core/quant_style.hpp>
#include <boost/xpressive/detail/core/matcher/action_matcher.hpp>
#include <boost/xpressive/detail/core/state.hpp>
#include <boost/proto/core.hpp>

namespace boost { namespace xpressive { namespace detail
{
    ///////////////////////////////////////////////////////////////////////////////
    // predicate_context
    //
    template<typename BidiIter>
    struct predicate_context
    {
        explicit predicate_context(int sub, sub_match_impl<BidiIter> const *sub_matches, action_args_type *action_args)
          : sub_(sub)
          , sub_matches_(sub_matches)
          , action_args_(action_args)
        {}

        action_args_type const &args() const
        {
            return *this->action_args_;
        }

        // eval_terminal
        template<typename Expr, typename Arg>
        struct eval_terminal
          : proto::default_eval<Expr, predicate_context const>
        {};

        template<typename Expr, typename Arg>
        struct eval_terminal<Expr, reference_wrapper<Arg> >
        {
            typedef Arg &result_type;
            result_type operator()(Expr &expr, predicate_context const &) const
            {
                return proto::value(expr).get();
            }
        };

        template<typename Expr>
        struct eval_terminal<Expr, any_matcher>
        {
            typedef sub_match<BidiIter> const &result_type;
            result_type operator()(Expr &, predicate_context const &ctx) const
            {
                return ctx.sub_matches_[ctx.sub_];
            }
        };

        template<typename Expr>
        struct eval_terminal<Expr, mark_placeholder>
        {
            typedef sub_match<BidiIter> const &result_type;
            result_type operator()(Expr &expr, predicate_context const &ctx) const
            {
                return ctx.sub_matches_[proto::value(expr).mark_number_];
            }
        };

        template<typename Expr, typename Type, typename Int>
        struct eval_terminal<Expr, action_arg<Type, Int> >
        {
            typedef typename action_arg<Type, Int>::reference result_type;
            result_type operator()(Expr &expr, predicate_context const &ctx) const
            {
                action_args_type::const_iterator where_ = ctx.args().find(&typeid(proto::value(expr)));
                if(where_ == ctx.args().end())
                {
                    BOOST_THROW_EXCEPTION(
                        regex_error(
                            regex_constants::error_badarg
                          , "An argument to an action was unspecified"
                        )
                    );
                }
                return proto::value(expr).cast(where_->second);
            }
        };

        // eval
        template<typename Expr, typename Tag = typename Expr::proto_tag>
        struct eval
          : proto::default_eval<Expr, predicate_context const>
        {};

        template<typename Expr>
        struct eval<Expr, proto::tag::terminal>
          : eval_terminal<Expr, typename proto::result_of::value<Expr>::type>
        {};

        #if BOOST_VERSION >= 103500
        template<typename Expr>
        struct eval<Expr, proto::tag::mem_ptr>
          : mem_ptr_eval<Expr, predicate_context const>
        {};
        #endif

        int sub_;
        sub_match_impl<BidiIter> const *sub_matches_;
        action_args_type *action_args_;
    };

    ///////////////////////////////////////////////////////////////////////////////
    // AssertionFunctor
    //
    struct AssertionFunctor
      : proto::function<
            proto::terminal<check_tag>
          , proto::terminal<proto::_>
        >
    {};

    ///////////////////////////////////////////////////////////////////////////////
    // predicate_matcher
    //
    template<typename Predicate>
    struct predicate_matcher
      : quant_style_assertion
    {
        int sub_;
        Predicate predicate_;

        predicate_matcher(Predicate const &pred, int sub)
          : sub_(sub)
          , predicate_(pred)
        {
        }

        template<typename BidiIter, typename Next>
        bool match(match_state<BidiIter> &state, Next const &next) const
        {
            // Predicate is check(assertion), where assertion can be
            // a lambda or a function object.
            return this->match_(state, next, proto::matches<Predicate, AssertionFunctor>());
        }

    private:
        template<typename BidiIter, typename Next>
        bool match_(match_state<BidiIter> &state, Next const &next, mpl::true_) const
        {
            sub_match<BidiIter> const &sub = state.sub_match(this->sub_);
            return proto::value(proto::child_c<1>(this->predicate_))(sub) && next.match(state);
        }

        template<typename BidiIter, typename Next>
        bool match_(match_state<BidiIter> &state, Next const &next, mpl::false_) const
        {
            predicate_context<BidiIter> ctx(this->sub_, state.sub_matches_, state.action_args_);
            return proto::eval(proto::child_c<1>(this->predicate_), ctx) && next.match(state);
        }
    };

}}}

#endif // BOOST_XPRESSIVE_DETAIL_CORE_MATCHER_PREDICATE_MATCHER_HPP_EAN_03_22_2007

max_stars_repo_name: importlib/klib

max_issues_repo_name: isuhao/klib

max_forks_repo_name: isuhao/klib


text:
// Part of the apollo library -- Copyright (c) Christian Neumüller 2015
// This file is subject to the terms of the BSD 2-Clause License.
// See LICENSE.txt or http://opensource.org/licenses/BSD-2-Clause

#ifndef APOLLO_TYPEID_HPP_INCLUDED
#define APOLLO_TYPEID_HPP_INCLUDED TYPEID_HPP_INCLUDED

#include <apollo/config.hpp>

#include <apollo/lua_include.hpp>

#include <boost/type_index.hpp>

namespace apollo {

APOLLO_API boost::typeindex::type_info const& lbuiltin_typeid(int id);

APOLLO_API boost::typeindex::type_info const& ltypeid(lua_State* L, int idx);

} // namespace apollo

#endif // APOLLO_TYPEID_HPP_INCLUDED


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

// Third party includes
#include <boost/format.hpp>

// VOTCA includes
#include <votca/tools/elements.h>
#include <votca/tools/tokenizer.h>

// Local VOTCA includes
#include "votca/xtp/atomcontainer.h"
#include "votca/xtp/classicalsegment.h"

namespace votca {
namespace xtp {

// MPS files have a weird format positions can be in bohr or angstroem,
// multipoles are in q*bohr^k, with k rank of multipole and polarisabilities are
// in angstroem^3
template <class T>
void ClassicalSegment<T>::LoadFromFile(std::string filename) {

  std::string line;
  std::ifstream intt;
  intt.open(filename);
  double unit_conversion = tools::conv::ang2bohr;

  Index readinmultipoles = 0;
  Index numberofmultipoles = 0;
  Vector9d multipoles = Vector9d::Zero();
  Index rank = 0;

  if (!intt.is_open()) {
    throw std::runtime_error("File:" + filename + " could not be opened");
  }
  while (intt.good()) {

    std::getline(intt, line);
    tools::Tokenizer toker(line, " \t");
    std::vector<std::string> split = toker.ToVector();

    if (!split.size() || split[0] == "!" || split[0].substr(0, 1) == "!") {
      continue;
    }

    // ! Interesting information here, e.g.
    // ! DCV2T opt
    // ! SP        RB3LYP          6-311+G(d,p)
    // Units bohr
    //
    // C          -4.2414603400   -3.8124751600    0.0017575736    Rank  2
    //  -0.3853409355
    //  -0.0002321905   0.2401559510   0.6602334308
    //  -0.7220625314   0.0004894995  -0.0003833545   0.4526409813  -0.50937399
    //  P 1.75

    // Units used
    if (split[0] == "Units") {
      std::string units = split[1];
      if (units != "bohr" && units != "angstrom") {
        throw std::runtime_error("Unit " + units + " in file " + filename +
                                 " not supported.");
      }
      if (units == "bohr") {
        unit_conversion = 1.0;
      }
    } else if (split.size() == 6) {
      // element,  position,  rank limit convert to bohr
      std::string name = split[0];
      Eigen::Vector3d pos;
      Index id = Index(this->_atomlist.size());
      pos[0] = boost::lexical_cast<double>(split[1]);
      pos[1] = boost::lexical_cast<double>(split[2]);
      pos[2] = boost::lexical_cast<double>(split[3]);
      rank = boost::lexical_cast<Index>(split[5]);
      numberofmultipoles = (rank + 1) * (rank + 1);
      multipoles = Vector9d::Zero();
      pos *= unit_conversion;
      this->_atomlist.push_back(T(id, name, pos));
    }
    // 'P', dipole polarizability
    else if (split[0] == "P") {
      Eigen::Matrix3d p1;
      if (split.size() == 7) {
        double pxx = boost::lexical_cast<double>(split[1]);
        double pxy = boost::lexical_cast<double>(split[2]);
        double pxz = boost::lexical_cast<double>(split[3]);
        double pyy = boost::lexical_cast<double>(split[4]);
        double pyz = boost::lexical_cast<double>(split[5]);
        double pzz = boost::lexical_cast<double>(split[6]);
        p1 << pxx, pxy, pxz, pxy, pyy, pyz, pxz, pyz, pzz;
      } else if (split.size() == 2) {
        double pxx = boost::lexical_cast<double>(split[1]);
        p1 = pxx * Eigen::Matrix3d::Identity();
      } else {
        throw std::runtime_error("Invalid line in " + filename + ": " + line);
      }
      double unit_conversion_3 = std::pow(tools::conv::ang2bohr, 3);
      p1 = p1 * unit_conversion_3;
      this->_atomlist.back().setpolarization(p1);
    }
    // Multipole lines
    else {
      // stay in bohr
      for (const std::string& entry : split) {
        double qXYZ = boost::lexical_cast<double>(entry);
        if (multipoles.size() < readinmultipoles) {
          throw std::runtime_error("ReadMpsFile: File" + filename +
                                   "is not properly formatted");
        }
        multipoles(readinmultipoles) = qXYZ;
        readinmultipoles++;
      }
      if (readinmultipoles == numberofmultipoles) {
        Eigen::Vector3d temp_dipoles = multipoles.segment<3>(1);
        // mps format for dipoles is z x y
        // we need x y z
        multipoles(1) = temp_dipoles(1);
        multipoles(2) = temp_dipoles(2);
        multipoles(3) = temp_dipoles(0);
        this->_atomlist.back().setMultipole(multipoles, rank);
        readinmultipoles = 0;
      }
    }
  }
  this->calcPos();
}

template <class T>
double ClassicalSegment<T>::CalcTotalQ() const {
  double Q = 0;
  for (const T& site : this->_atomlist) {
    Q += site.getCharge();
  }
  return Q;
}

template <class T>
Eigen::Vector3d ClassicalSegment<T>::CalcDipole() const {
  Eigen::Vector3d dipole = Eigen::Vector3d::Zero();

  Eigen::Vector3d CoM = this->getPos();
  for (const T& site : this->_atomlist) {
    dipole += (site.getPos() - CoM) * site.getCharge();
    dipole += site.getDipole();
  }
  return dipole;
}

template <class T>
void ClassicalSegment<T>::WriteMPS(std::string filename,
                                   std::string header) const {

  std::ofstream ofs;
  ofs.open(filename, std::ofstream::out);
  if (!ofs.is_open()) {
    throw std::runtime_error("Bad file handle: " + filename);
  }

  ofs << (boost::format("! GENERATED BY VOTCA::XTP::%1$s\n") % header);
  ofs << (boost::format("! N=%2$d Q[e]=%1$+1.7f\n") % CalcTotalQ() %
          this->size());
  ofs << boost::format("Units angstrom\n");

  for (const T& site : this->_atomlist) {
    ofs << site.WriteMpsLine("angstrom");
  }
  ofs.close();
}

template <class T>
std::string ClassicalSegment<T>::identify() const {
  return "";
}

template <>
std::string ClassicalSegment<PolarSite>::identify() const {
  return "PolarSegment";
}
template <>
std::string ClassicalSegment<StaticSite>::identify() const {
  return "StaticSegment";
}

template class ClassicalSegment<PolarSite>;
template class ClassicalSegment<StaticSite>;

}  // namespace xtp
}  // namespace votca

max_stars_repo_name: fossabot/xtp

max_issues_repo_name: fossabot/xtp

max_forks_repo_name: fossabot/xtp


text:
/////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2021 Andreas Milton Maniotis.
//
// Email: andreas.maniotis@gmail.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)
/////////////////////////////////////////////////////////////////////////////////////////////

//#pragma once

#include "../object.hpp"
#include "../logic.hpp"

namespace aml::adt
{
    template< typename Number >
    struct function_argument;

    template<>
    struct function_argument< num<1> >
    {
        template<  typename    Head
                ,  typename... Tail
                >
        static consteval Head&& from_header( Head&& h, Tail&&...t )
        {
            return static_cast<Head&&>(h);
        }
    };

    template<typename Number>
    struct function_argument
    {
        template<  typename    Head
                ,  typename... Tail
                >
        static consteval decltype(auto) from_header( Head&& h, Tail&&... t )
        {
            return function_argument< typename Number::down >::from_header( static_cast<Tail&&>(t)... );
        }
    };

    template<typename N, typename... Args>
    consteval decltype(auto) get_argument(Args&&... args)
    {
        return function_argument<N>::from_header( static_cast<Args&&>(args)... );
    };
}

template<auto n> struct foo {};

#include <iostream>
#include <boost/core/demangle.hpp>
#include <vector>

template<typename T>
struct keeper
{
    template<typename S>
    keeper(S&& t) : t_(std::forward<S>(t) )
    { }

    T t_;
};

template<typename Value>
struct Vector : public std::vector<Value>
{
    Vector(std::initializer_list<double> l )
    : std::vector<double>(l)
    { }

    Vector(Vector const& other)
    :    std::vector<double>(other)
    {
        std::cout << "copy constructing! " << std::endl;
    }

    Vector(Vector && other)
    :    std::vector<double>(std::move(other))
    {
        std::cout << "move constructing! " << std::endl;
    }

};

int main()
{
    foo<  aml::adt::get_argument<aml::num<3> >( 1, 2, 3 ) > f;

    std::cout << boost::core::demangle( typeid(f).name() ) << std::endl;

    keeper< Vector<double> > k1( aml::adt::get_argument<aml::num<2> >( Vector<double>{1, 1.11, 2.22 },
                                                                            Vector<double>{-2, -3.3, -4.44 } ));;

    std::cout << boost::core::demangle( typeid(k1).name() ) << std::endl;
    auto const& v = k1.t_;

    for (auto const& el : v )
        std::cout << el << " : ";
    std::cout << std::endl;
}

max_stars_repo_name: aandriko/libaml

max_issues_repo_name: aandriko/libaml

max_forks_repo_name: aandriko/libaml