text:
// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt
/*
    This is an example illustrating the use of the deep learning tools from the dlib C++
    Library.  I'm assuming you have already read the dnn_introduction_ex.cpp, the
    dnn_introduction2_ex.cpp and the dnn_introduction3_ex.cpp examples.  In this example
    program we are going to show how one can train Generative Adversarial Networks (GANs).  In
    particular, we will train a Deep Convolutional Generative Adversarial Network (DCGAN) like
    the one introduced in this paper:
    "Unsupervised Representation Learning with Deep Convolutional Generative Adversarial Networks"
    by Alec Radford, Luke Metz, Soumith Chintala.

    The main idea is that there are two neural networks training at the same time:
    - the generator is in charge of generating images that look as close as possible to the
      ones from the dataset.
    - the discriminator will decide whether an image is fake (created by the generator) or real
      (selected from the dataset).

    Each training iteration alternates between training the discriminator and the generator.
    We first train the discriminator with real and fake images and then use the gradient from
    the discriminator to update the generator.

    In this example, we are going to learn how to generate digits from the MNIST dataset, but
    the same code can be run using the Fashion MNIST datset:
    https://github.com/zalandoresearch/fashion-mnist
*/

#include <algorithm>
#include <iostream>

#include <dlib/data_io.h>
#include <dlib/dnn.h>
#include <dlib/gui_widgets.h>
#include <dlib/matrix.h>

using namespace std;
using namespace dlib;

// Some helper definitions for the noise generation
const size_t noise_size = 100;
using noise_t = std::array<matrix<float, 1, 1>, noise_size>;

noise_t make_noise(dlib::rand& rnd)
{
    noise_t noise;
    for (auto& n : noise)
    {
        n = rnd.get_random_gaussian();
    }
    return noise;
}

// A convolution with custom padding
template<long num_filters, long kernel_size, int stride, int padding, typename SUBNET>
using conp = add_layer<con_<num_filters, kernel_size, kernel_size, stride, stride, padding, padding>, SUBNET>;

// A transposed convolution to with custom padding
template<long num_filters, long kernel_size, int stride, int padding, typename SUBNET>
using contp = add_layer<cont_<num_filters, kernel_size, kernel_size, stride, stride, padding, padding>, SUBNET>;

// The generator is made of a bunch of deconvolutional layers.  Its input is a 1 x 1 x k noise
// tensor, and the output is the generated image.  The loss layer does not matter for the
// training, we just stack a compatible one on top to be able to have a () operator on the
// generator.
using generator_type =
    loss_binary_log_per_pixel<
    sig<contp<1, 4, 2, 1,
    relu<bn_con<contp<64, 4, 2, 1,
    relu<bn_con<contp<128, 3, 2, 1,
    relu<bn_con<contp<256, 4, 1, 0,
    input<noise_t>
    >>>>>>>>>>>>;

// Now, let's proceed to define the discriminator, whose role will be to decide whether an
// image is fake or not.
using discriminator_type =
    loss_binary_log<
    conp<1, 3, 1, 0,
    leaky_relu<bn_con<conp<256, 4, 2, 1,
    leaky_relu<bn_con<conp<128, 4, 2, 1,
    leaky_relu<conp<64, 4, 2, 1,
    input<matrix<unsigned char>>
    >>>>>>>>>>;

// Some helper functions to generate and get the images from the generator
matrix<unsigned char> generate_image(generator_type& net, const noise_t& noise)
{
    const matrix<float> output = net(noise);
    matrix<unsigned char> image;
    assign_image(image, 255 * output);
    return image;
}

std::vector<matrix<unsigned char>> get_generated_images(const tensor& out)
{
    std::vector<matrix<unsigned char>> images;
    for (long n = 0; n < out.num_samples(); ++n)
    {
        matrix<float> output = image_plane(out, n);
        matrix<unsigned char> image;
        assign_image(image, 255 * output);
        images.push_back(std::move(image));
    }
    return images;
}

#if defined(BUILD_MONOLITHIC)
#define main(cnt, arr)      dlib_dnn_dcgan_train_ex_main(cnt, arr)
#endif

int main(int argc, const char** argv)
try
{
    // This example is going to run on the MNIST dataset.
    if (argc != 2)
    {
        cout << "This example needs the MNIST dataset to run!" << endl;
        cout << "You can get MNIST from http://yann.lecun.com/exdb/mnist/" << endl;
        cout << "Download the 4 files that comprise the dataset, decompress them, and" << endl;
        cout << "put them in a folder.  Then give that folder as input to this program." << endl;
        return EXIT_FAILURE;
    }

    // MNIST is broken into two parts, a training set of 60000 images and a test set of 10000
    // images.  Each image is labeled so that we know what hand written digit is depicted.
    // These next statements load the dataset into memory.
    std::vector<matrix<unsigned char>> training_images;
    std::vector<unsigned long>         training_labels;
    std::vector<matrix<unsigned char>> testing_images;
    std::vector<unsigned long>         testing_labels;
    load_mnist_dataset(argv[1], training_images, training_labels, testing_images, testing_labels);

    // Fix the random generator seeds for network initialization and noise
    srand(1234);
    dlib::rand rnd(std::rand());

    // Instantiate both generator and discriminator
    generator_type generator;
    discriminator_type discriminator;
    // setup all leaky_relu_ layers in the discriminator to have alpha = 0.2
    visit_computational_layers(discriminator, [](leaky_relu_& l){ l = leaky_relu_(0.2); });
    // Remove the bias learning from all bn_ inputs in both networks
    disable_duplicative_biases(generator);
    disable_duplicative_biases(discriminator);
    // Forward random noise so that we see the tensor size at each layer
    discriminator(generate_image(generator, make_noise(rnd)));
    cout << "generator (" << count_parameters(generator) << " parameters)" << endl;
    cout << generator << endl;
    cout << "discriminator (" << count_parameters(discriminator) << " parameters)" << endl;
    cout << discriminator << endl;

    // The solvers for the generator and discriminator networks.  In this example, we are going to
    // train the networks manually, so we don't need to use a dnn_trainer.  Note that the
    // discriminator could be trained using a dnn_trainer, but not the generator, since its
    // training process is a bit particular.
    std::vector<adam> g_solvers(generator.num_computational_layers, adam(0, 0.5, 0.999));
    std::vector<adam> d_solvers(discriminator.num_computational_layers, adam(0, 0.5, 0.999));
    double learning_rate = 2e-4;

    // Resume training from last sync file
    size_t iteration = 0;
    if (file_exists("dcgan_sync"))
    {
        deserialize("dcgan_sync") >> generator >> discriminator >> iteration;
    }

    const size_t minibatch_size = 64;
    const std::vector<float> real_labels(minibatch_size, 1);
    const std::vector<float> fake_labels(minibatch_size, -1);
    dlib::image_window win;
    resizable_tensor real_samples_tensor, fake_samples_tensor, noises_tensor;
    running_stats<double> g_loss, d_loss;
    while (iteration < 50000)
    {
        // Train the discriminator with real images
        std::vector<matrix<unsigned char>> real_samples;
        while (real_samples.size() < minibatch_size)
        {
            auto idx = rnd.get_random_32bit_number() % training_images.size();
            real_samples.push_back(training_images[idx]);
        }
        // The following lines are equivalent to calling train_one_step(real_samples, real_labels)
        discriminator.to_tensor(real_samples.begin(), real_samples.end(), real_samples_tensor);
        d_loss.add(discriminator.compute_loss(real_samples_tensor, real_labels.begin()));
        discriminator.back_propagate_error(real_samples_tensor);
        discriminator.update_parameters(d_solvers, learning_rate);

        // Train the discriminator with fake images
        // 1. Generate some random noise
        std::vector<noise_t> noises;
        while (noises.size() < minibatch_size)
        {
            noises.push_back(make_noise(rnd));
        }
        // 2. Convert noises into a tensor
        generator.to_tensor(noises.begin(), noises.end(), noises_tensor);
        // 3. Forward the noise through the network and convert the outputs into images.
        const auto fake_samples = get_generated_images(generator.forward(noises_tensor));
        // 4. Finally train the discriminator.  The following lines are equivalent to calling
        // train_one_step(fake_samples, fake_labels)
        discriminator.to_tensor(fake_samples.begin(), fake_samples.end(), fake_samples_tensor);
        d_loss.add(discriminator.compute_loss(fake_samples_tensor, fake_labels.begin()));
        discriminator.back_propagate_error(fake_samples_tensor);
        discriminator.update_parameters(d_solvers, learning_rate);

        // Train the generator
        // This part is the essence of the Generative Adversarial Networks.  Until now, we have
        // just trained a binary classifier that the generator is not aware of.  But now, the
        // discriminator is going to give feedback to the generator on how it should update
        // itself to generate more realistic images.  The following lines perform the same
        // actions as train_one_step() except for the network update part.  They can also be
        // seen as test_one_step() plus the error back propagation.

        // Forward the fake samples and compute the loss with real labels
        g_loss.add(discriminator.compute_loss(fake_samples_tensor, real_labels.begin()));
        // Back propagate the error to fill the final data gradient
        discriminator.back_propagate_error(fake_samples_tensor);
        // Get the gradient that will tell the generator how to update itself
        const tensor& d_grad = discriminator.get_final_data_gradient();
        generator.back_propagate_error(noises_tensor, d_grad);
        generator.update_parameters(g_solvers, learning_rate);

        // At some point, we should see that the generated images start looking like samples from
        // the MNIST dataset
        if (++iteration % 1000 == 0)
        {
            serialize("dcgan_sync") << generator << discriminator << iteration;
            std::cout <<
                "step#: " << iteration <<
                "\tdiscriminator loss: " << d_loss.mean() * 2 <<
                "\tgenerator loss: " << g_loss.mean() << '\n';
            win.set_image(tile_images(fake_samples));
            win.set_title("DCGAN step#: " + to_string(iteration));
            d_loss.clear();
            g_loss.clear();
        }
    }

    // Once the training has finished, we don't need the discriminator any more. We just keep the
    // generator.
    generator.clean();
    serialize("dcgan_mnist.dnn") << generator;

    // To test the generator, we just forward some random noise through it and visualize the
    // output.
    while (!win.is_closed())
    {
        const auto image = generate_image(generator, make_noise(rnd));
        const auto real = discriminator(image) > 0;
        win.set_image(image);
        cout << "The discriminator thinks it's " << (real ? "real" : "fake");
        cout << ". Hit enter to generate a new image";
        cin.get();
    }

    return EXIT_SUCCESS;
}
catch(exception& e)
{
    cout << e.what() << endl;
    return EXIT_FAILURE;
}

max_stars_repo_name: GerHobbelt/dlib

max_issues_repo_name: GerHobbelt/dlib

max_forks_repo_name: GerHobbelt/dlib


text:
// for friend classes: their cpp files can use this header to access
// implementation

#ifndef FORMAST_STATS_IMPL_HPP_INCLUDED
#define FORMAST_STATS_IMPL_HPP_INCLUDED

#include <boost/shared_ptr.hpp>
#include <boost/variant/recursive_variant.hpp>

#include "formast.hpp"

namespace formast
{
namespace detail
{

typedef boost::make_recursive_variant<formast::Field, formast::If>::type StatDecl;

}
}

class formast::Stats::Impl : public std::vector<formast::detail::StatDecl>
{
private:
    // see http://www.boost.org/doc/libs/1_51_0/libs/smart_ptr/sp_techniques.html#pimpl
    Impl(Impl const &);
    Impl & operator=(Impl const &);
public:
    Impl();
};

#endif

ext: hpp

max_stars_repo_name: niftools/formast

max_issues_repo_name: niftools/formast

max_forks_repo_name: niftools/formast


text:
// ----------------------------------------------------------------------------
// "THE BEER-WARE LICENSE" (Revision 42):
// <ztn@zurreal.com> wrote this file.  As long as you retain this notice you
// can do whatever you want with this stuff. If we meet some day, and you think
// this stuff is worth it, you can buy me a beer in return.  Ziesche Til Newman
// ----------------------------------------------------------------------------
#ifndef HEROESPATH_CREATURE_PLAYER_PARTY_SERIALIZE_INCLUDES_HPP_INCLUDED
#define HEROESPATH_CREATURE_PLAYER_PARTY_SERIALIZE_INCLUDES_HPP_INCLUDED
//
// party-serialize-includes.hpp
//  A collection of includes that allows boost serialization of Character and Party objects.
//  This must only be included once, in game-state-factory.cpp
//
#include <fstream>

#include "misc/boost-serialize-includes.hpp"

#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/serialization/export.hpp>

#include "item/item.hpp"
BOOST_CLASS_EXPORT(heroespath::item::Item)

#include "creature/creature.hpp"
BOOST_CLASS_EXPORT(heroespath::creature::Creature)

#include "creature/player-party.hpp"
BOOST_CLASS_EXPORT(heroespath::creature::PlayerParty)

#endif // HEROESPATH_CREATURE_PLAYER_PARTY_SERIALIZE_INCLUDES_HPP_INCLUDED

max_stars_repo_name: tilnewman/heroespath-src

max_issues_repo_name: tilnewman/heroespath-src

max_forks_repo_name: tilnewman/heroespath-src


text:
#include "ZoneDatabase.h"
#include "AppConfig.h"
#include "string_format.h"
#include "StdStreamUtils.h"
#include "Log.h"
#include "xml/Parser.h"
#include "xml/Utils.h"

#define LOG_NAME "ZoneDatabase"

//////////////////////////////////////
//NOTE: This was pulled from 3D engine, we need to find a better place for it
//////////////////////////////////////

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

static float ParseFloat(const std::string& valueString)
{
	float result = 0;
	std::stringstream ss;
	ss.imbue(std::locale::classic());
	ss << valueString;
	ss >> result;
	return result;
}

static ActorVector3 ParseVector3(const std::string& vectorString)
{
	std::vector<std::string> components;
	boost::split(components, vectorString, boost::is_any_of(", "), boost::algorithm::token_compress_on);
	ActorVector3 result(0.f, 0.f, 0.f);
	if(components.size() != 3) return result;
	return std::make_tuple(
		ParseFloat(components[0]),
		ParseFloat(components[1]),
		ParseFloat(components[2]));
}

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

const CZoneDatabase::ZONE_DEF_LOCATION CZoneDatabase::m_zoneLocations[] =
{
	{ 101,	"lanoscea"		},
	{ 102,	"coerthas"		},
	{ 103,	"blackshroud"	},
	{ 104,	"thanalan"		},
	{ 105,	"mordhona"		},
	{ 109,	"rivenroad"		}
};

CZoneDatabase::CZoneDatabase()
{
	m_defaultZone.backgroundMusicId = 0x39;
	m_defaultZone.battleMusicId = 0x0D;
}

CZoneDatabase::~CZoneDatabase()
{

}

void CZoneDatabase::Load()
{
	auto configPath = CAppConfig::GetInstance().GetBasePath();
	for(const auto& zoneLocation : m_zoneLocations)
	{
		auto zoneDefFilename = string_format("ffxivd_zone_%s.xml", zoneLocation.name);
		try
		{
			auto zoneDefPath = configPath / zoneDefFilename;
			if(boost::filesystem::exists(zoneDefPath))
			{
				auto inputStream = Framework::CreateInputStdStream(zoneDefPath.native());
				auto zone = LoadZoneDefinition(inputStream);
				m_zones.insert(std::make_pair(zoneLocation.zoneId, zone));
			}
			else
			{
				CLog::GetInstance().LogMessage(LOG_NAME, "File '%s' doesn't exist. Not loading any data for that zone.", zoneDefPath.string().c_str());
			}
		}
		catch(const std::exception& exception)
		{
			CLog::GetInstance().LogError(LOG_NAME, "Failed to load zone definition from '%s'. Reason: %s.", zoneDefFilename.c_str(), exception.what());
		}
	}
}

const ZONE_DEFINITION* CZoneDatabase::GetZone(uint32 zoneId) const
{
	auto zoneIterator = m_zones.find(zoneId);
	if(zoneIterator == std::end(m_zones))
	{
		return nullptr;
	}
	else
	{
		return &zoneIterator->second;
	}
}

const ZONE_DEFINITION* CZoneDatabase::GetDefaultZone() const
{
	return &m_defaultZone;
}

const ZONE_DEFINITION* CZoneDatabase::GetZoneOrDefault(uint32 zoneId) const
{
	if(auto zone = GetZone(zoneId))
	{
		return zone;
	}
	else
	{
		return GetDefaultZone();
	}
}

ZONE_DEFINITION CZoneDatabase::LoadZoneDefinition(Framework::CStream& stream)
{
	ZONE_DEFINITION result;
	auto documentNode = std::unique_ptr<Framework::Xml::CNode>(Framework::Xml::CParser::ParseDocument(stream));
	auto zoneNode = documentNode->Select("Zone");
	if(zoneNode == nullptr)
	{
		CLog::GetInstance().LogMessage(LOG_NAME, "Zone definition file doesn't contain a 'Zone' node.");
		return result;
	}

	result.backgroundMusicId = Framework::Xml::GetAttributeIntValue(zoneNode, "BackgroundMusicId");
	result.battleMusicId = Framework::Xml::GetAttributeIntValue(zoneNode, "BattleMusicId");

	auto actorNodes = zoneNode->SelectNodes("Actors/Actor");
	result.actors.reserve(actorNodes.size());
	for(const auto& actorNode : actorNodes)
	{
		ACTOR_DEFINITION actor;
		actor.id = Framework::Xml::GetAttributeIntValue(actorNode, "Id");
		actor.nameStringId = Framework::Xml::GetAttributeIntValue(actorNode, "NameString");
		actor.baseModelId = Framework::Xml::GetAttributeIntValue(actorNode, "BaseModel");
		actor.topModelId = Framework::Xml::GetAttributeIntValue(actorNode, "TopModel");
		actor.pos = ParseVector3(Framework::Xml::GetAttributeStringValue(actorNode, "Position"));
		result.actors.push_back(actor);
	}
	return result;
}

ext: cpp

max_stars_repo_name: Zackmon/SeventhUmbral

max_issues_repo_name: Zackmon/SeventhUmbral

max_forks_repo_name: Zackmon/SeventhUmbral


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * File:   HttpTransactionManager.cpp
 * Author: ubuntu
 *
 * Created on March 2, 2018, 7:11 AM
 */

#include <boost/beast/http/message.hpp>

#include "BlockChain.pb.h"
#include "Protocol.pb.h"
#include "google/protobuf/any.h"

#include "keto/common/HttpEndPoints.hpp"
#include "keto/common/StringCodec.hpp"
#include "keto/asn1/HashHelper.hpp"

#include "keto/server_common/EventUtils.hpp"
#include "keto/server_common/Events.hpp"
#include "keto/server_common/EventServiceHelpers.hpp"

#include "keto/server_session/HttpTransactionManager.hpp"
#include "keto/server_session/HttpSessionManager.hpp"
#include "keto/server_session/HttpSession.hpp"
#include "keto/server_session/Exception.hpp"
#include "keto/crypto/SecureVectorUtils.hpp"

#include "keto/transaction_common/MessageWrapperProtoHelper.hpp"

namespace keto {
namespace server_session {

HttpTransactionManager::HttpTransactionManager(
    std::shared_ptr<HttpSessionManager>& httpSessionManagerPtr) :
    httpSessionManagerPtr(httpSessionManagerPtr) {

}

HttpTransactionManager::~HttpTransactionManager() {
}

std::string HttpTransactionManager::processTransaction(
        boost::beast::http::request<boost::beast::http::string_body>& req,
        const std::string& transactionMsg) {
    std::string sessionHash = (const std::string&)req.base().at(keto::common::HttpEndPoints::HEADER_SESSION_HASH);
    keto::asn1::HashHelper hashHelper(
            sessionHash,keto::common::HEX);
    std::vector<uint8_t> vectorHash = keto::crypto::SecureVectorUtils().copyFromSecure(hashHelper);
    if (!httpSessionManagerPtr->isValid(vectorHash)) {
        BOOST_THROW_EXCEPTION(keto::server_session::InvalidSessionException());
    }
    std::shared_ptr<HttpSession> httpSession =
            httpSessionManagerPtr->getSession(vectorHash);

    keto::proto::Transaction transaction;

    if (!transaction.ParseFromString(transactionMsg)) {
        BOOST_THROW_EXCEPTION(keto::server_session::MessageDeserializationException(
                "Failed to deserialized the transaction message."));
    }

    keto::transaction_common::MessageWrapperProtoHelper messageWrapperProtoHelper;
    messageWrapperProtoHelper.setSessionHash(hashHelper).setTransaction(transaction);

    keto::proto::MessageWrapper messageWrapper = messageWrapperProtoHelper;
    keto::proto::MessageWrapperResponse  messageWrapperResponse =
            keto::server_common::fromEvent<keto::proto::MessageWrapperResponse>(
            keto::server_common::processEvent(keto::server_common::toEvent<keto::proto::MessageWrapper>(
            keto::server_common::Events::ROUTE_MESSAGE,messageWrapper)));

    return messageWrapperResponse.result();
}

}
}

max_stars_repo_name: burntjam/keto

max_issues_repo_name: burntjam/keto

max_forks_repo_name: burntjam/keto


text:
//******************************************************************************
// RCF - Remote Call Framework
//
// Copyright (c) 2005 - 2013, Delta V Software. All rights reserved.
// http://www.deltavsoft.com
//
// RCF is distributed under dual licenses - closed source or GPL.
// Consult your particular license for conditions of use.
//
// If you have not purchased a commercial license, you are using RCF
// under GPL terms.
//
// Version: 2.0
// Contact: support <at> deltavsoft.com
//
//******************************************************************************

#ifndef INCLUDE_RCF_SERVERSTUB_HPP
#define INCLUDE_RCF_SERVERSTUB_HPP

#include <map>
#include <memory>
#include <vector>

#include <boost/shared_ptr.hpp>

#include <RCF/Config.hpp>
#include <RCF/Export.hpp>
#include <RCF/GetInterfaceName.hpp>
#include <RCF/RcfClient.hpp>
#include <RCF/RcfSession.hpp>
#include <RCF/SerializationProtocol.hpp>
#include <RCF/Token.hpp>

// NB: occurrences of "interface" in this file have been replaced with "interface_", due to obscure bugs with Visual C++

namespace RCF {

    class                                   I_RcfClient;
    typedef boost::shared_ptr<I_RcfClient>  RcfClientPtr;

    template<typename T>
    class I_Deref
    {
    public:
        virtual ~I_Deref() {}
        virtual T &deref() = 0;
    };

    template<typename T>
    class DerefObj : public I_Deref<T>
    {
    public:
        DerefObj(T &t) :
            mT(t)
        {}

        T &deref()
        {
            return mT;
        }

    private:
        T &mT;
    };

    template<typename T>
    class DerefSharedPtr : public I_Deref<T>
    {
    public:
        DerefSharedPtr(boost::shared_ptr<T> tPtr) :
            mTPtr(tPtr)
        {}

        T &deref()
        {
            return *mTPtr;
        }

    private:
        boost::shared_ptr<T> mTPtr;
    };

    RCF_EXPORT void setCurrentCallDesc(
        std::string &                   desc,
        RCF::MethodInvocationRequest &  request,
        const char *                    szFunc,
        const char *                    szArity);

    class StubAccess
    {
    public:

#ifdef _MSC_VER
#pragma warning( push )
#pragma warning( disable: 4702 )
#endif

        template<typename InterfaceT, typename IdT, typename ImplementationT>
        void invoke(
            InterfaceT &                interface_,
            const IdT &                 id,
            RcfSession &                session,
            ImplementationT &           t)
        {
            setCurrentCallDesc(
                session.mCurrentCallDesc,
                session.mRequest,
                interface_.getFunctionName(id),
                interface_.getArity(id));

            RCF_LOG_2() << "RcfServer - begin remote call. " << session.mCurrentCallDesc;
            interface_.invoke(id, session, t);
        }

#ifdef _MSC_VER
#pragma warning( pop )
#endif

        template<typename InterfaceT, typename DerefPtrT>
        void registerInvokeFunctors(
            InterfaceT &                interface_,
            InvokeFunctorMap &          invokeFunctorMap,
            DerefPtrT                   derefPtr)
        {
            interface_.registerInvokeFunctors(invokeFunctorMap, derefPtr);
        }

        template<typename RcfClientT>
        ClientStubPtr getClientStubPtr(const RcfClientT &rcfClient)
        {
            return rcfClient.mClientStubPtr;
        }

    };

    template<typename InterfaceT, typename ImplementationT>
    inline void invoke(
        InterfaceT &                    interface_,
        ImplementationT &               t,
        int                             fnId,
        RcfSession  &                   session)
    {
        switch (fnId) {
        case   0: StubAccess().invoke(interface_, boost::mpl::int_<  0>(), session, t); break;
        case   1: StubAccess().invoke(interface_, boost::mpl::int_<  1>(), session, t); break;
        case   2: StubAccess().invoke(interface_, boost::mpl::int_<  2>(), session, t); break;
        case   3: StubAccess().invoke(interface_, boost::mpl::int_<  3>(), session, t); break;
        case   4: StubAccess().invoke(interface_, boost::mpl::int_<  4>(), session, t); break;
        case   5: StubAccess().invoke(interface_, boost::mpl::int_<  5>(), session, t); break;
        case   6: StubAccess().invoke(interface_, boost::mpl::int_<  6>(), session, t); break;
        case   7: StubAccess().invoke(interface_, boost::mpl::int_<  7>(), session, t); break;
        case   8: StubAccess().invoke(interface_, boost::mpl::int_<  8>(), session, t); break;
        case   9: StubAccess().invoke(interface_, boost::mpl::int_<  9>(), session, t); break;
        case  10: StubAccess().invoke(interface_, boost::mpl::int_< 10>(), session, t); break;
        case  11: StubAccess().invoke(interface_, boost::mpl::int_< 11>(), session, t); break;
        case  12: StubAccess().invoke(interface_, boost::mpl::int_< 12>(), session, t); break;
        case  13: StubAccess().invoke(interface_, boost::mpl::int_< 13>(), session, t); break;
        case  14: StubAccess().invoke(interface_, boost::mpl::int_< 14>(), session, t); break;
        case  15: StubAccess().invoke(interface_, boost::mpl::int_< 15>(), session, t); break;
        case  16: StubAccess().invoke(interface_, boost::mpl::int_< 16>(), session, t); break;
        case  17: StubAccess().invoke(interface_, boost::mpl::int_< 17>(), session, t); break;
        case  18: StubAccess().invoke(interface_, boost::mpl::int_< 18>(), session, t); break;
        case  19: StubAccess().invoke(interface_, boost::mpl::int_< 19>(), session, t); break;
        case  20: StubAccess().invoke(interface_, boost::mpl::int_< 20>(), session, t); break;
        case  21: StubAccess().invoke(interface_, boost::mpl::int_< 21>(), session, t); break;
        case  22: StubAccess().invoke(interface_, boost::mpl::int_< 22>(), session, t); break;
        case  23: StubAccess().invoke(interface_, boost::mpl::int_< 23>(), session, t); break;
        case  24: StubAccess().invoke(interface_, boost::mpl::int_< 24>(), session, t); break;
        case  25: StubAccess().invoke(interface_, boost::mpl::int_< 25>(), session, t); break;
        case  26: StubAccess().invoke(interface_, boost::mpl::int_< 26>(), session, t); break;
        case  27: StubAccess().invoke(interface_, boost::mpl::int_< 27>(), session, t); break;
        case  28: StubAccess().invoke(interface_, boost::mpl::int_< 28>(), session, t); break;
        case  29: StubAccess().invoke(interface_, boost::mpl::int_< 29>(), session, t); break;
        case  30: StubAccess().invoke(interface_, boost::mpl::int_< 30>(), session, t); break;
        case  31: StubAccess().invoke(interface_, boost::mpl::int_< 31>(), session, t); break;
        case  32: StubAccess().invoke(interface_, boost::mpl::int_< 32>(), session, t); break;
        case  33: StubAccess().invoke(interface_, boost::mpl::int_< 33>(), session, t); break;
        case  34: StubAccess().invoke(interface_, boost::mpl::int_< 34>(), session, t); break;
        case  35: StubAccess().invoke(interface_, boost::mpl::int_< 35>(), session, t); break;
        case  36: StubAccess().invoke(interface_, boost::mpl::int_< 36>(), session, t); break;
        case  37: StubAccess().invoke(interface_, boost::mpl::int_< 37>(), session, t); break;
        case  38: StubAccess().invoke(interface_, boost::mpl::int_< 38>(), session, t); break;
        case  39: StubAccess().invoke(interface_, boost::mpl::int_< 39>(), session, t); break;
        case  40: StubAccess().invoke(interface_, boost::mpl::int_< 40>(), session, t); break;
        case  41: StubAccess().invoke(interface_, boost::mpl::int_< 41>(), session, t); break;
        case  42: StubAccess().invoke(interface_, boost::mpl::int_< 42>(), session, t); break;
        case  43: StubAccess().invoke(interface_, boost::mpl::int_< 43>(), session, t); break;
        case  44: StubAccess().invoke(interface_, boost::mpl::int_< 44>(), session, t); break;
        case  45: StubAccess().invoke(interface_, boost::mpl::int_< 45>(), session, t); break;
        case  46: StubAccess().invoke(interface_, boost::mpl::int_< 46>(), session, t); break;
        case  47: StubAccess().invoke(interface_, boost::mpl::int_< 47>(), session, t); break;
        case  48: StubAccess().invoke(interface_, boost::mpl::int_< 48>(), session, t); break;
        case  49: StubAccess().invoke(interface_, boost::mpl::int_< 49>(), session, t); break;
        case  50: StubAccess().invoke(interface_, boost::mpl::int_< 50>(), session, t); break;
        case  51: StubAccess().invoke(interface_, boost::mpl::int_< 51>(), session, t); break;
        case  52: StubAccess().invoke(interface_, boost::mpl::int_< 52>(), session, t); break;
        case  53: StubAccess().invoke(interface_, boost::mpl::int_< 53>(), session, t); break;
        case  54: StubAccess().invoke(interface_, boost::mpl::int_< 54>(), session, t); break;
        case  55: StubAccess().invoke(interface_, boost::mpl::int_< 55>(), session, t); break;
        case  56: StubAccess().invoke(interface_, boost::mpl::int_< 56>(), session, t); break;
        case  57: StubAccess().invoke(interface_, boost::mpl::int_< 57>(), session, t); break;
        case  58: StubAccess().invoke(interface_, boost::mpl::int_< 58>(), session, t); break;
        case  59: StubAccess().invoke(interface_, boost::mpl::int_< 59>(), session, t); break;
        case  60: StubAccess().invoke(interface_, boost::mpl::int_< 60>(), session, t); break;
        case  61: StubAccess().invoke(interface_, boost::mpl::int_< 61>(), session, t); break;
        case  62: StubAccess().invoke(interface_, boost::mpl::int_< 62>(), session, t); break;
        case  63: StubAccess().invoke(interface_, boost::mpl::int_< 63>(), session, t); break;
        case  64: StubAccess().invoke(interface_, boost::mpl::int_< 64>(), session, t); break;
        case  65: StubAccess().invoke(interface_, boost::mpl::int_< 65>(), session, t); break;
        case  66: StubAccess().invoke(interface_, boost::mpl::int_< 66>(), session, t); break;
        case  67: StubAccess().invoke(interface_, boost::mpl::int_< 67>(), session, t); break;
        case  68: StubAccess().invoke(interface_, boost::mpl::int_< 68>(), session, t); break;
        case  69: StubAccess().invoke(interface_, boost::mpl::int_< 69>(), session, t); break;
        case  70: StubAccess().invoke(interface_, boost::mpl::int_< 70>(), session, t); break;
        case  71: StubAccess().invoke(interface_, boost::mpl::int_< 71>(), session, t); break;
        case  72: StubAccess().invoke(interface_, boost::mpl::int_< 72>(), session, t); break;
        case  73: StubAccess().invoke(interface_, boost::mpl::int_< 73>(), session, t); break;
        case  74: StubAccess().invoke(interface_, boost::mpl::int_< 74>(), session, t); break;
        case  75: StubAccess().invoke(interface_, boost::mpl::int_< 75>(), session, t); break;
        case  76: StubAccess().invoke(interface_, boost::mpl::int_< 76>(), session, t); break;
        case  77: StubAccess().invoke(interface_, boost::mpl::int_< 77>(), session, t); break;
        case  78: StubAccess().invoke(interface_, boost::mpl::int_< 78>(), session, t); break;
        case  79: StubAccess().invoke(interface_, boost::mpl::int_< 79>(), session, t); break;
        case  80: StubAccess().invoke(interface_, boost::mpl::int_< 80>(), session, t); break;
        case  81: StubAccess().invoke(interface_, boost::mpl::int_< 81>(), session, t); break;
        case  82: StubAccess().invoke(interface_, boost::mpl::int_< 82>(), session, t); break;
        case  83: StubAccess().invoke(interface_, boost::mpl::int_< 83>(), session, t); break;
        case  84: StubAccess().invoke(interface_, boost::mpl::int_< 84>(), session, t); break;
        case  85: StubAccess().invoke(interface_, boost::mpl::int_< 85>(), session, t); break;
        case  86: StubAccess().invoke(interface_, boost::mpl::int_< 86>(), session, t); break;
        case  87: StubAccess().invoke(interface_, boost::mpl::int_< 87>(), session, t); break;
        case  88: StubAccess().invoke(interface_, boost::mpl::int_< 88>(), session, t); break;
        case  89: StubAccess().invoke(interface_, boost::mpl::int_< 89>(), session, t); break;
        case  90: StubAccess().invoke(interface_, boost::mpl::int_< 90>(), session, t); break;
        case  91: StubAccess().invoke(interface_, boost::mpl::int_< 91>(), session, t); break;
        case  92: StubAccess().invoke(interface_, boost::mpl::int_< 92>(), session, t); break;
        case  93: StubAccess().invoke(interface_, boost::mpl::int_< 93>(), session, t); break;
        case  94: StubAccess().invoke(interface_, boost::mpl::int_< 94>(), session, t); break;
        case  95: StubAccess().invoke(interface_, boost::mpl::int_< 95>(), session, t); break;
        case  96: StubAccess().invoke(interface_, boost::mpl::int_< 96>(), session, t); break;
        case  97: StubAccess().invoke(interface_, boost::mpl::int_< 97>(), session, t); break;
        case  98: StubAccess().invoke(interface_, boost::mpl::int_< 98>(), session, t); break;
        case  99: StubAccess().invoke(interface_, boost::mpl::int_< 99>(), session, t); break;
        case 100: StubAccess().invoke(interface_, boost::mpl::int_<100>(), session, t); break;
        case 101: StubAccess().invoke(interface_, boost::mpl::int_<101>(), session, t); break;
        case 102: StubAccess().invoke(interface_, boost::mpl::int_<102>(), session, t); break;
        case 103: StubAccess().invoke(interface_, boost::mpl::int_<103>(), session, t); break;
        case 104: StubAccess().invoke(interface_, boost::mpl::int_<104>(), session, t); break;
        case 105: StubAccess().invoke(interface_, boost::mpl::int_<105>(), session, t); break;
        case 106: StubAccess().invoke(interface_, boost::mpl::int_<106>(), session, t); break;
        case 107: StubAccess().invoke(interface_, boost::mpl::int_<107>(), session, t); break;
        case 108: StubAccess().invoke(interface_, boost::mpl::int_<108>(), session, t); break;
        case 109: StubAccess().invoke(interface_, boost::mpl::int_<109>(), session, t); break;
        case 110: StubAccess().invoke(interface_, boost::mpl::int_<110>(), session, t); break;
        case 111: StubAccess().invoke(interface_, boost::mpl::int_<111>(), session, t); break;
        case 112: StubAccess().invoke(interface_, boost::mpl::int_<112>(), session, t); break;
        case 113: StubAccess().invoke(interface_, boost::mpl::int_<113>(), session, t); break;
        case 114: StubAccess().invoke(interface_, boost::mpl::int_<114>(), session, t); break;
        case 115: StubAccess().invoke(interface_, boost::mpl::int_<115>(), session, t); break;
        case 116: StubAccess().invoke(interface_, boost::mpl::int_<116>(), session, t); break;
        case 117: StubAccess().invoke(interface_, boost::mpl::int_<117>(), session, t); break;
        case 118: StubAccess().invoke(interface_, boost::mpl::int_<118>(), session, t); break;
        case 119: StubAccess().invoke(interface_, boost::mpl::int_<119>(), session, t); break;
        case 120: StubAccess().invoke(interface_, boost::mpl::int_<120>(), session, t); break;
        case 121: StubAccess().invoke(interface_, boost::mpl::int_<121>(), session, t); break;
        case 122: StubAccess().invoke(interface_, boost::mpl::int_<122>(), session, t); break;
        case 123: StubAccess().invoke(interface_, boost::mpl::int_<123>(), session, t); break;
        case 124: StubAccess().invoke(interface_, boost::mpl::int_<124>(), session, t); break;
        case 125: StubAccess().invoke(interface_, boost::mpl::int_<125>(), session, t); break;
        case 126: StubAccess().invoke(interface_, boost::mpl::int_<126>(), session, t); break;
        case 127: StubAccess().invoke(interface_, boost::mpl::int_<127>(), session, t); break;
        case 128: StubAccess().invoke(interface_, boost::mpl::int_<128>(), session, t); break;
        case 129: StubAccess().invoke(interface_, boost::mpl::int_<129>(), session, t); break;
        case 130: StubAccess().invoke(interface_, boost::mpl::int_<130>(), session, t); break;
        case 131: StubAccess().invoke(interface_, boost::mpl::int_<131>(), session, t); break;
        case 132: StubAccess().invoke(interface_, boost::mpl::int_<132>(), session, t); break;
        case 133: StubAccess().invoke(interface_, boost::mpl::int_<133>(), session, t); break;
        case 134: StubAccess().invoke(interface_, boost::mpl::int_<134>(), session, t); break;
        case 135: StubAccess().invoke(interface_, boost::mpl::int_<135>(), session, t); break;
        case 136: StubAccess().invoke(interface_, boost::mpl::int_<136>(), session, t); break;
        case 137: StubAccess().invoke(interface_, boost::mpl::int_<137>(), session, t); break;
        case 138: StubAccess().invoke(interface_, boost::mpl::int_<138>(), session, t); break;
        case 139: StubAccess().invoke(interface_, boost::mpl::int_<139>(), session, t); break;
        case 140: StubAccess().invoke(interface_, boost::mpl::int_<140>(), session, t); break;
        case 141: StubAccess().invoke(interface_, boost::mpl::int_<141>(), session, t); break;
        case 142: StubAccess().invoke(interface_, boost::mpl::int_<142>(), session, t); break;
        case 143: StubAccess().invoke(interface_, boost::mpl::int_<143>(), session, t); break;
        case 144: StubAccess().invoke(interface_, boost::mpl::int_<144>(), session, t); break;
        case 145: StubAccess().invoke(interface_, boost::mpl::int_<145>(), session, t); break;
        case 146: StubAccess().invoke(interface_, boost::mpl::int_<146>(), session, t); break;
        case 147: StubAccess().invoke(interface_, boost::mpl::int_<147>(), session, t); break;
        case 148: StubAccess().invoke(interface_, boost::mpl::int_<148>(), session, t); break;
        case 149: StubAccess().invoke(interface_, boost::mpl::int_<149>(), session, t); break;
        case 150: StubAccess().invoke(interface_, boost::mpl::int_<150>(), session, t); break;
        case 151: StubAccess().invoke(interface_, boost::mpl::int_<151>(), session, t); break;
        case 152: StubAccess().invoke(interface_, boost::mpl::int_<152>(), session, t); break;
        case 153: StubAccess().invoke(interface_, boost::mpl::int_<153>(), session, t); break;
        case 154: StubAccess().invoke(interface_, boost::mpl::int_<154>(), session, t); break;
        case 155: StubAccess().invoke(interface_, boost::mpl::int_<155>(), session, t); break;
        case 156: StubAccess().invoke(interface_, boost::mpl::int_<156>(), session, t); break;
        case 157: StubAccess().invoke(interface_, boost::mpl::int_<157>(), session, t); break;
        case 158: StubAccess().invoke(interface_, boost::mpl::int_<158>(), session, t); break;
        case 159: StubAccess().invoke(interface_, boost::mpl::int_<159>(), session, t); break;
        case 160: StubAccess().invoke(interface_, boost::mpl::int_<160>(), session, t); break;
        case 161: StubAccess().invoke(interface_, boost::mpl::int_<161>(), session, t); break;
        case 162: StubAccess().invoke(interface_, boost::mpl::int_<162>(), session, t); break;
        case 163: StubAccess().invoke(interface_, boost::mpl::int_<163>(), session, t); break;
        case 164: StubAccess().invoke(interface_, boost::mpl::int_<164>(), session, t); break;
        case 165: StubAccess().invoke(interface_, boost::mpl::int_<165>(), session, t); break;
        case 166: StubAccess().invoke(interface_, boost::mpl::int_<166>(), session, t); break;
        case 167: StubAccess().invoke(interface_, boost::mpl::int_<167>(), session, t); break;
        case 168: StubAccess().invoke(interface_, boost::mpl::int_<168>(), session, t); break;
        case 169: StubAccess().invoke(interface_, boost::mpl::int_<169>(), session, t); break;
        case 170: StubAccess().invoke(interface_, boost::mpl::int_<170>(), session, t); break;
        case 171: StubAccess().invoke(interface_, boost::mpl::int_<171>(), session, t); break;
        case 172: StubAccess().invoke(interface_, boost::mpl::int_<172>(), session, t); break;
        case 173: StubAccess().invoke(interface_, boost::mpl::int_<173>(), session, t); break;
        case 174: StubAccess().invoke(interface_, boost::mpl::int_<174>(), session, t); break;
        case 175: StubAccess().invoke(interface_, boost::mpl::int_<175>(), session, t); break;
        case 176: StubAccess().invoke(interface_, boost::mpl::int_<176>(), session, t); break;
        case 177: StubAccess().invoke(interface_, boost::mpl::int_<177>(), session, t); break;
        case 178: StubAccess().invoke(interface_, boost::mpl::int_<178>(), session, t); break;
        case 179: StubAccess().invoke(interface_, boost::mpl::int_<179>(), session, t); break;
        case 180: StubAccess().invoke(interface_, boost::mpl::int_<180>(), session, t); break;
        case 181: StubAccess().invoke(interface_, boost::mpl::int_<181>(), session, t); break;
        case 182: StubAccess().invoke(interface_, boost::mpl::int_<182>(), session, t); break;
        case 183: StubAccess().invoke(interface_, boost::mpl::int_<183>(), session, t); break;
        case 184: StubAccess().invoke(interface_, boost::mpl::int_<184>(), session, t); break;
        case 185: StubAccess().invoke(interface_, boost::mpl::int_<185>(), session, t); break;
        case 186: StubAccess().invoke(interface_, boost::mpl::int_<186>(), session, t); break;
        case 187: StubAccess().invoke(interface_, boost::mpl::int_<187>(), session, t); break;
        case 188: StubAccess().invoke(interface_, boost::mpl::int_<188>(), session, t); break;
        case 189: StubAccess().invoke(interface_, boost::mpl::int_<189>(), session, t); break;
        case 190: StubAccess().invoke(interface_, boost::mpl::int_<190>(), session, t); break;
        case 191: StubAccess().invoke(interface_, boost::mpl::int_<191>(), session, t); break;
        case 192: StubAccess().invoke(interface_, boost::mpl::int_<192>(), session, t); break;
        case 193: StubAccess().invoke(interface_, boost::mpl::int_<193>(), session, t); break;
        case 194: StubAccess().invoke(interface_, boost::mpl::int_<194>(), session, t); break;
        case 195: StubAccess().invoke(interface_, boost::mpl::int_<195>(), session, t); break;
        case 196: StubAccess().invoke(interface_, boost::mpl::int_<196>(), session, t); break;
        case 197: StubAccess().invoke(interface_, boost::mpl::int_<197>(), session, t); break;
        case 198: StubAccess().invoke(interface_, boost::mpl::int_<198>(), session, t); break;
        case 199: StubAccess().invoke(interface_, boost::mpl::int_<199>(), session, t); break;
        case 200: StubAccess().invoke(interface_, boost::mpl::int_<200>(), session, t); break;

        default: RCF_THROW(Exception(_RcfError_FnId(fnId)));
        }
    }

    template<typename InterfaceT, typename DerefPtrT>
    class InterfaceInvocator
    {
    public:
        InterfaceInvocator(InterfaceT &interface_, DerefPtrT derefPtr) :
            mInterface(interface_),
            mDerefPtr(derefPtr)
        {}

        void operator()(
            int                         fnId,
            RcfSession &                session)
        {
            invoke<InterfaceT>(mInterface, mDerefPtr->deref(), fnId, session);
        }

    private:
        InterfaceT &    mInterface;
        DerefPtrT       mDerefPtr;
    };

    template<typename InterfaceT, typename DerefPtrT>
    void registerInvokeFunctors(
        InterfaceT &                    interface_,
        InvokeFunctorMap &              invokeFunctorMap,
        DerefPtrT                       derefPtr)
    {
        // NB: same interface may occur more than once in the inheritance hierarchy of another interface, and in
        // that case, via overwriting, only one InterfaceInvocator is registered, so only the functions in one of the interfaces will ever be called.
        // But it doesn't matter, since even if an interface occurs several times in the inheritance hierarchy, each occurrence
        // of the interface will be bound to derefPtr in exactly the same way.

        typedef typename InterfaceT::Interface Interface;
        std::string interfaceName = ::RCF::getInterfaceName( (Interface *) NULL);

        invokeFunctorMap[ interfaceName ] =
            InterfaceInvocator<InterfaceT, DerefPtrT>(interface_, derefPtr);
    }

    class ServerBinding;

    typedef boost::shared_ptr<ServerBinding> ServerBindingPtr;

    class RCF_EXPORT ServerBinding
    {
    public:

        typedef boost::function<bool(int)> CbAccessControl;

        void setAccessControl(CbAccessControl cbAccessControl);

        template<typename InterfaceT, typename DerefPtrT>
        void registerInvokeFunctors(InterfaceT &interface_, DerefPtrT derefPtr)
        {
            StubAccess access;
            access.registerInvokeFunctors(
                interface_,
                mInvokeFunctorMap,
                derefPtr);
        }

    private:

        friend class RcfServer;
        friend class RcfSession;

        void invoke(
            const std::string &         subInterface,
            int                         fnId,
            RcfSession &                session);

    private:

        Mutex                           mMutex;

        // TODO: too much overhead per server stub?
        InvokeFunctorMap                mInvokeFunctorMap;

        CbAccessControl                 mCbAccessControl;
    };

    template<typename InterfaceT, typename ImplementationT, typename ImplementationPtrT>
    RcfClientPtr createServerStub(
        InterfaceT *,
        ImplementationT *,
        ImplementationPtrT px)
    {
        typedef typename InterfaceT::RcfClientT RcfClientT;
        return RcfClientPtr( new RcfClientT(
            ServerBindingPtr(new ServerBinding()),
            px,
            (boost::mpl::true_ *) NULL));
    }

} // namespace RCF

#endif // ! INCLUDE_RCF_SERVERSTUB_HPP

max_stars_repo_name: ASMlover/study

max_issues_repo_name: ASMlover/study

max_forks_repo_name: ASMlover/study


text:
#include "ros/ros.h"

#include <boost/bind.hpp>
#include <boost/ref.hpp>

#include "robotiq_epick_grippers_control/robotiq_epick_grippers_tcp_client.h"
#include "robotiq_epick_control/RobotiqVacuumGrippers_robot_input.h"
#include "robotiq_modbus_tcp/tcp_manager.h"

void changeCallback(robotiq_vacuum_grippers_control::RobotiqEpickTcpClient& client,
                    const robotiq_vacuum_grippers_control::RobotiqEpickTcpClient::GripperOutput::ConstPtr& msg)
{
  client.writeOutputs(*msg);
}

int main(int argc, char** argv)
{
  using robotiq_modbus_tcp::TcpManager;
  using robotiq_vacuum_grippers_control::RobotiqEpickTcpClient;

  typedef RobotiqEpickTcpClient::GripperOutput GripperOutput;
  typedef RobotiqEpickTcpClient::GripperInput GripperInput;

  ros::init(argc, argv, "robotiq_epick_driver_node");

  ros::NodeHandle nh ("");

  // Parameter names
  std::string ip;
  int port;
  bool activate;

  nh.param<std::string>("epick_ip", ip, "10.30.99.123");
  nh.param<int>("port", port, 502);
  nh.param<bool>("activate", activate, true);

  // Start ethercat manager
  TcpManager manager(ip, port);

  // register client
  RobotiqEpickTcpClient client(manager);

  // conditionally activate the gripper
  if (activate)
  {
    // Check to see if resetting is required? Or always reset?
    GripperOutput out;
    out.rACT = 0x1;
    client.writeOutputs(out);
  }

  // Sorry for the indentation, trying to keep it under 100 chars
  ros::Subscriber sub =
        nh.subscribe<GripperOutput>("output", 1,
                                    boost::bind(changeCallback, boost::ref(client), _1));

  ros::Publisher pub = nh.advertise<GripperInput>("input", 100);

  ros::Rate rate(10); // 10 Hz

  while (ros::ok())
  {
    RobotiqEpickTcpClient::GripperInput input = client.readInputs();
    pub.publish(input);
    ros::spinOnce();
    rate.sleep();
  }

  return 0;
}


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

#include "PyIlmBaseConfigInternal.h"

#include <Python.h>
#include <boost/python.hpp>
#include <boost/python/make_constructor.hpp>
#include <boost/format.hpp>
#include <ImathVec.h>
#include <ImathQuat.h>
#include <ImathEuler.h>
#include <ImathFun.h>
#include <ImathMatrixAlgo.h>

#include <PyIexExport.h>
#include "PyImathFixedArray.h"
#include "PyImath.h"
#include "PyImathExport.h"
#include "PyImathBasicTypes.h"
#include "PyImathVec.h"
#include "PyImathMatrix.h"
#include "PyImathBox.h"
#include "PyImathFun.h"
#include "PyImathQuat.h"
#include "PyImathEuler.h"
#include "PyImathColor.h"
#include "PyImathFrustum.h"
#include "PyImathPlane.h"
#include "PyImathLine.h"
#include "PyImathRandom.h"
#include "PyImathShear.h"
#include "PyImathMathExc.h"
#include "PyImathAutovectorize.h"
#include "PyImathStringArrayRegister.h"
#include <PyIex.h>

using namespace boost::python;

namespace {

template <typename T>
IMATH_NAMESPACE::Box<IMATH_NAMESPACE::Vec3<T> >
computeBoundingBox(const PyImath::FixedArray<IMATH_NAMESPACE::Vec3<T> >& position)
{
    IMATH_NAMESPACE::Box<IMATH_NAMESPACE::Vec3<T> > bounds;
    int len = position.len();
    for (int i = 0; i < len; ++i)
        bounds.extendBy(position[i]);
    return bounds;
}

IMATH_NAMESPACE::M44d
procrustes1 (PyObject* from_input,
             PyObject* to_input,
             PyObject* weights_input = 0,
             bool doScale = false)
{
    // Verify the sequences:
    if (!PySequence_Check (from_input))
    {
        PyErr_SetString (PyExc_TypeError, "Expected a sequence type for 'from'");
        boost::python::throw_error_already_set();
    }

    if (!PySequence_Check (to_input))
    {
        PyErr_SetString (PyExc_TypeError, "Expected a sequence type for 'to'");
        boost::python::throw_error_already_set();
    }

    bool useWeights = PySequence_Check (weights_input);

    // Now verify the lengths:
    const Py_ssize_t n = PySequence_Length (from_input);
    if (n != PySequence_Length (to_input) ||
        (useWeights && n != PySequence_Length (weights_input)))
    {
        PyErr_SetString (PyExc_TypeError, "'from, 'to', and 'weights' should all have the same lengths.");
        boost::python::throw_error_already_set();
    }

    std::vector<IMATH_NAMESPACE::V3d> from;  from.reserve (n);
    std::vector<IMATH_NAMESPACE::V3d> to;    to.reserve (n);
    std::vector<double> weights;   weights.reserve (n);

    for (Py_ssize_t i = 0; i < n; ++i)
    {
        PyObject* f = PySequence_GetItem (from_input, i);
        PyObject* t = PySequence_GetItem (to_input, i);
        PyObject* w = 0;
        if (useWeights)
            w = PySequence_GetItem (weights_input, i);

        if (f == 0 || t == 0 || (useWeights && w == 0))
        {
            PyErr_SetString (PyExc_TypeError,
                             "Missing element in array");
            boost::python::throw_error_already_set();
        }

        from.push_back (boost::python::extract<IMATH_NAMESPACE::V3d> (f));
        to.push_back (boost::python::extract<IMATH_NAMESPACE::V3d> (t));
        if (useWeights)
            weights.push_back (boost::python::extract<double> (w));
    }

    if (useWeights)
        return IMATH_NAMESPACE::procrustesRotationAndTranslation (&from[0], &to[0], &weights[0], n, doScale);
    else
        return IMATH_NAMESPACE::procrustesRotationAndTranslation (&from[0], &to[0], n, doScale);
}

PyImath::FixedArray2D<int> rangeX(int sizeX, int sizeY)
{
    PyImath::FixedArray2D<int> f(sizeX, sizeY);
    for (int j=0; j<sizeY; j++)
        for (int i=0; i<sizeX; i++)
            f(i,j) = i;
    return f;
}

PyImath::FixedArray2D<int> rangeY(int sizeX, int sizeY)
{
    PyImath::FixedArray2D<int> f(sizeX, sizeY);
    for (int j=0; j<sizeY; j++)
        for (int i=0; i<sizeX; i++)
            f(i,j) = j;
    return f;
}

} // namespace

namespace PyImath {

void register_all()
{
    scope().attr("__doc__") = "Imath module";

    register_basicTypes();

    class_<IntArray2D> iclass2D = IntArray2D::register_("IntArray2D","Fixed length array of ints");
    add_arithmetic_math_functions(iclass2D);
    add_mod_math_functions(iclass2D);
    add_comparison_functions(iclass2D);
    add_ordered_comparison_functions(iclass2D);
    add_explicit_construction_from_type<float>(iclass2D);
    add_explicit_construction_from_type<double>(iclass2D);

    class_<IntMatrix> imclass = IntMatrix::register_("IntMatrix","Fixed size matrix of ints");
    add_arithmetic_math_functions(imclass);

    class_<FloatArray2D> fclass2D = FloatArray2D::register_("FloatArray2D","Fixed length 2D array of floats");
    add_arithmetic_math_functions(fclass2D);
    add_pow_math_functions(fclass2D);
    add_comparison_functions(fclass2D);
    add_ordered_comparison_functions(fclass2D);
    add_explicit_construction_from_type<int>(fclass2D);
    add_explicit_construction_from_type<double>(fclass2D);

    class_<FloatMatrix> fmclass = FloatMatrix::register_("FloatMatrix","Fixed size matrix of floats");
    add_arithmetic_math_functions(fmclass);
    add_pow_math_functions(fmclass);

    class_<DoubleArray2D> dclass2D = DoubleArray2D::register_("DoubleArray2D","Fixed length array of doubles");
    add_arithmetic_math_functions(dclass2D);
    add_pow_math_functions(dclass2D);
    add_comparison_functions(dclass2D);
    add_ordered_comparison_functions(dclass2D);
    add_explicit_construction_from_type<int>(dclass2D);
    add_explicit_construction_from_type<float>(dclass2D);

    class_<DoubleMatrix> dmclass = DoubleMatrix::register_("DoubleMatrix","Fixed size matrix of doubles");
    add_arithmetic_math_functions(dmclass);
    add_pow_math_functions(dmclass);

    def("rangeX", &rangeX);
    def("rangeY", &rangeY);

    //
    //  Vec2
    //
    register_Vec2<short>();
    register_Vec2<int>();
    register_Vec2<float>();
    register_Vec2<double>();
    class_<FixedArray<IMATH_NAMESPACE::V2s> > v2s_class = register_Vec2Array<short>();
    class_<FixedArray<IMATH_NAMESPACE::V2i> > v2i_class = register_Vec2Array<int>();
    class_<FixedArray<IMATH_NAMESPACE::V2f> > v2f_class = register_Vec2Array<float>();
    class_<FixedArray<IMATH_NAMESPACE::V2d> > v2d_class = register_Vec2Array<double>();
    add_explicit_construction_from_type<IMATH_NAMESPACE::V2f>(v2i_class);
    add_explicit_construction_from_type<IMATH_NAMESPACE::V2d>(v2i_class);
    add_explicit_construction_from_type<IMATH_NAMESPACE::V2i>(v2f_class);
    add_explicit_construction_from_type<IMATH_NAMESPACE::V2d>(v2f_class);
    add_explicit_construction_from_type<IMATH_NAMESPACE::V2i>(v2d_class);
    add_explicit_construction_from_type<IMATH_NAMESPACE::V2f>(v2d_class);

    //
    //  Vec3
    //
    register_Vec3<unsigned char>();
    register_Vec3<short>();
    register_Vec3<int>();
    register_Vec3<float>();
    register_Vec3<double>();
    class_<FixedArray<IMATH_NAMESPACE::V3s> > v3s_class = register_Vec3Array<short>();
    class_<FixedArray<IMATH_NAMESPACE::V3i> > v3i_class = register_Vec3Array<int>();
    class_<FixedArray<IMATH_NAMESPACE::V3f> > v3f_class = register_Vec3Array<float>();
    class_<FixedArray<IMATH_NAMESPACE::V3d> > v3d_class = register_Vec3Array<double>();
    add_explicit_construction_from_type<IMATH_NAMESPACE::V3f>(v3i_class);
    add_explicit_construction_from_type<IMATH_NAMESPACE::V3d>(v3i_class);
    add_explicit_construction_from_type<IMATH_NAMESPACE::V3i>(v3f_class);
    add_explicit_construction_from_type<IMATH_NAMESPACE::V3d>(v3f_class);
    add_explicit_construction_from_type<IMATH_NAMESPACE::V3i>(v3d_class);
    add_explicit_construction_from_type<IMATH_NAMESPACE::V3f>(v3d_class);

    //
    //  Vec4
    //
    register_Vec4<unsigned char>();
    register_Vec4<short>();
    register_Vec4<int>();
    register_Vec4<float>();
    register_Vec4<double>();
    class_<FixedArray<IMATH_NAMESPACE::V4s> > v4s_class = register_Vec4Array<short>();
    class_<FixedArray<IMATH_NAMESPACE::V4i> > v4i_class = register_Vec4Array<int>();
    class_<FixedArray<IMATH_NAMESPACE::V4f> > v4f_class = register_Vec4Array<float>();
    class_<FixedArray<IMATH_NAMESPACE::V4d> > v4d_class = register_Vec4Array<double>();
    add_explicit_construction_from_type<IMATH_NAMESPACE::V4f>(v4i_class);
    add_explicit_construction_from_type<IMATH_NAMESPACE::V4d>(v4i_class);
    add_explicit_construction_from_type<IMATH_NAMESPACE::V4i>(v4f_class);
    add_explicit_construction_from_type<IMATH_NAMESPACE::V4d>(v4f_class);
    add_explicit_construction_from_type<IMATH_NAMESPACE::V4i>(v4d_class);

    //
    //  Quat
    //
    register_Quat<float>();
    register_Quat<double>();
    class_<FixedArray<IMATH_NAMESPACE::Quatf> > quatf_class = register_QuatArray<float>();
    class_<FixedArray<IMATH_NAMESPACE::Quatd> > quatd_class = register_QuatArray<double>();
    add_explicit_construction_from_type<IMATH_NAMESPACE::Quatd>(quatf_class);
    add_explicit_construction_from_type<IMATH_NAMESPACE::Quatf>(quatd_class);

    //
    // Euler
    //
    register_Euler<float>();
    register_Euler<double>();
    class_<FixedArray<IMATH_NAMESPACE::Eulerf> > eulerf_class = register_EulerArray<float>();
    class_<FixedArray<IMATH_NAMESPACE::Eulerd> > eulerd_class = register_EulerArray<double>();
    add_explicit_construction_from_type<IMATH_NAMESPACE::Eulerd>(eulerf_class);
    add_explicit_construction_from_type<IMATH_NAMESPACE::Eulerf>(eulerd_class);

    //
    // Box2
    //
    register_Box2<IMATH_NAMESPACE::V2s>();
    register_Box2<IMATH_NAMESPACE::V2i>();
    register_Box2<IMATH_NAMESPACE::V2f>();
    register_Box2<IMATH_NAMESPACE::V2d>();
    class_<FixedArray<IMATH_NAMESPACE::Box2s> > b2s_class = register_BoxArray<IMATH_NAMESPACE::V2s>();
    class_<FixedArray<IMATH_NAMESPACE::Box2i> > b2i_class = register_BoxArray<IMATH_NAMESPACE::V2i>();
    class_<FixedArray<IMATH_NAMESPACE::Box2f> > b2f_class = register_BoxArray<IMATH_NAMESPACE::V2f>();
    class_<FixedArray<IMATH_NAMESPACE::Box2d> > b2d_class = register_BoxArray<IMATH_NAMESPACE::V2d>();

    //
    // Box3
    //
    register_Box3<IMATH_NAMESPACE::V3s>();
    register_Box3<IMATH_NAMESPACE::V3i>();
    register_Box3<IMATH_NAMESPACE::V3f>();
    register_Box3<IMATH_NAMESPACE::V3d>();
    class_<FixedArray<IMATH_NAMESPACE::Box3s> > b3s_class = register_BoxArray<IMATH_NAMESPACE::V3s>();
    class_<FixedArray<IMATH_NAMESPACE::Box3i> > b3i_class = register_BoxArray<IMATH_NAMESPACE::V3i>();
    class_<FixedArray<IMATH_NAMESPACE::Box3f> > b3f_class = register_BoxArray<IMATH_NAMESPACE::V3f>();
    class_<FixedArray<IMATH_NAMESPACE::Box3d> > b3d_class = register_BoxArray<IMATH_NAMESPACE::V3d>();

    //
    // Matrix22/33/44
    //
    register_Matrix22<float>();
    register_Matrix22<double>();
    register_Matrix33<float>();
    register_Matrix33<double>();
    register_Matrix44<float>();
    register_Matrix44<double>();

    //
    // M22/M33/44Array
    //
    class_<FixedArray<IMATH_NAMESPACE::M44d> > m44d_class = register_M44Array<double>();
    class_<FixedArray<IMATH_NAMESPACE::M44f> > m44f_class = register_M44Array<float>();
    add_explicit_construction_from_type< IMATH_NAMESPACE::Matrix44<double> >(m44d_class);
    add_explicit_construction_from_type< IMATH_NAMESPACE::Matrix44<float> > (m44f_class);

    class_<FixedArray<IMATH_NAMESPACE::M33d> > m33d_class = register_M33Array<double>();
    class_<FixedArray<IMATH_NAMESPACE::M33f> > m33f_class = register_M33Array<float>();
    add_explicit_construction_from_type< IMATH_NAMESPACE::Matrix33<double> >(m33d_class);
    add_explicit_construction_from_type< IMATH_NAMESPACE::Matrix33<float> > (m33f_class);

    class_<FixedArray<IMATH_NAMESPACE::M22d> > m22d_class = register_M22Array<double>();
    class_<FixedArray<IMATH_NAMESPACE::M22f> > m22f_class = register_M22Array<float>();
    add_explicit_construction_from_type< IMATH_NAMESPACE::Matrix22<double> >(m22d_class);
    add_explicit_construction_from_type< IMATH_NAMESPACE::Matrix22<float> > (m22f_class);

    //
    // String Array
    //
    register_StringArrays();

    //
    // Color3/4
    //
    register_Color3<unsigned char>();
    register_Color3<float>();
    register_Color4<unsigned char>();
    register_Color4<float>();

    //
    // C3/4Array
    //
    class_<FixedArray<IMATH_NAMESPACE::Color3f> > c3f_class = register_Color3Array<float>();
    class_<FixedArray<IMATH_NAMESPACE::Color3c> > c3c_class = register_Color3Array<unsigned char>();
    add_explicit_construction_from_type<IMATH_NAMESPACE::V3f>(c3f_class);
    add_explicit_construction_from_type<IMATH_NAMESPACE::V3d>(c3f_class);

    class_<FixedArray<IMATH_NAMESPACE::Color4f> > c4f_class = register_Color4Array<float>();
    class_<FixedArray<IMATH_NAMESPACE::Color4c> > c4c_class = register_Color4Array<unsigned char>();

    //
    // Color4Array
    //
    register_Color4Array2D<float>();
    register_Color4Array2D<unsigned char>();

    //
    // Frustum
    //
    register_Frustum<float>();
    register_Frustum<double>();
    register_FrustumTest<float>();
    register_FrustumTest<double>();

    //
    // Plane
    //
    register_Plane<float>();
    register_Plane<double>();

    //
    // Line
    //
    register_Line<float>();
    register_Line<double>();

    //
    // Shear
    //
    register_Shear<float>();
    register_Shear<double>();

    //
    // Utility Functions
    //
    register_functions();

    def("procrustesRotationAndTranslation", procrustes1,
        args("fromPts", "toPts", "weights", "doScale"),  // Can't use 'from' and 'to' because 'from' is a reserved keywork in Python
        "Computes the orthogonal transform (consisting only of rotation and translation) mapping the "
        "'fromPts' points as close as possible to the 'toPts' points in the least squares norm.  The 'fromPts' and "
        "'toPts' lists must be the same length or the function will error out.  If weights "
        "are provided, then the points are weighted (that is, some points are considered more important "
        "than others while computing the transform).  If the 'doScale' parameter is True, then "
        "the resulting matrix is also allowed to have a uniform scale.");

    //
    // Rand
    //
    register_Rand32();
    register_Rand48();

    //
    // Initialize constants
    //

    scope().attr("EULER_XYZ")    = IMATH_NAMESPACE::Eulerf::XYZ;
    scope().attr("EULER_XZY")    = IMATH_NAMESPACE::Eulerf::XZY;
    scope().attr("EULER_YZX")    = IMATH_NAMESPACE::Eulerf::YZX;
    scope().attr("EULER_YXZ")    = IMATH_NAMESPACE::Eulerf::YXZ;
    scope().attr("EULER_ZXY")    = IMATH_NAMESPACE::Eulerf::ZXY;
    scope().attr("EULER_ZYX")    = IMATH_NAMESPACE::Eulerf::ZYX;
    scope().attr("EULER_XZX")    = IMATH_NAMESPACE::Eulerf::XZX;
    scope().attr("EULER_XYX")    = IMATH_NAMESPACE::Eulerf::XYX;
    scope().attr("EULER_YXY")    = IMATH_NAMESPACE::Eulerf::YXY;
    scope().attr("EULER_YZY")    = IMATH_NAMESPACE::Eulerf::YZY;
    scope().attr("EULER_ZYZ")    = IMATH_NAMESPACE::Eulerf::ZYZ;
    scope().attr("EULER_ZXZ")    = IMATH_NAMESPACE::Eulerf::ZXZ;
    scope().attr("EULER_XYZr")   = IMATH_NAMESPACE::Eulerf::XYZr;
    scope().attr("EULER_XZYr")   = IMATH_NAMESPACE::Eulerf::XZYr;
    scope().attr("EULER_YZXr")   = IMATH_NAMESPACE::Eulerf::YZXr;
    scope().attr("EULER_YXZr")   = IMATH_NAMESPACE::Eulerf::YXZr;
    scope().attr("EULER_ZXYr")   = IMATH_NAMESPACE::Eulerf::ZXYr;
    scope().attr("EULER_ZYXr")   = IMATH_NAMESPACE::Eulerf::ZYXr;
    scope().attr("EULER_XZXr")   = IMATH_NAMESPACE::Eulerf::XZXr;
    scope().attr("EULER_XYXr")   = IMATH_NAMESPACE::Eulerf::XYXr;
    scope().attr("EULER_YXYr")   = IMATH_NAMESPACE::Eulerf::YXYr;
    scope().attr("EULER_YZYr")   = IMATH_NAMESPACE::Eulerf::YZYr;
    scope().attr("EULER_ZYZr")   = IMATH_NAMESPACE::Eulerf::ZYZr;
    scope().attr("EULER_ZXZr")   = IMATH_NAMESPACE::Eulerf::ZXZr;
    scope().attr("EULER_X_AXIS") = IMATH_NAMESPACE::Eulerf::X;
    scope().attr("EULER_Y_AXIS") = IMATH_NAMESPACE::Eulerf::Y;
    scope().attr("EULER_Z_AXIS") = IMATH_NAMESPACE::Eulerf::Z;

    scope().attr("INT_MIN")      = IMATH_NAMESPACE::limits<int>::min();
    scope().attr("INT_MAX")      = IMATH_NAMESPACE::limits<int>::max();
    scope().attr("INT_SMALLEST") = IMATH_NAMESPACE::limits<int>::smallest();
    scope().attr("INT_EPS")      = IMATH_NAMESPACE::limits<int>::epsilon();

    scope().attr("FLT_MIN")      = IMATH_NAMESPACE::limits<float>::min();
    scope().attr("FLT_MAX")      = IMATH_NAMESPACE::limits<float>::max();
    scope().attr("FLT_SMALLEST") = IMATH_NAMESPACE::limits<float>::smallest();
    scope().attr("FLT_EPS")      = IMATH_NAMESPACE::limits<float>::epsilon();

    scope().attr("DBL_MIN")      = IMATH_NAMESPACE::limits<double>::min();
    scope().attr("DBL_MAX")      = IMATH_NAMESPACE::limits<double>::max();
    scope().attr("DBL_SMALLEST") = IMATH_NAMESPACE::limits<double>::smallest();
    scope().attr("DBL_EPS")      = IMATH_NAMESPACE::limits<double>::epsilon();

    //
    // Register Exceptions
    //
    PyIex::registerExc<IMATH_NAMESPACE::NullVecExc,IEX_NAMESPACE::MathExc>("NullVecExc","imath");
    PyIex::registerExc<IMATH_NAMESPACE::NullQuatExc,IEX_NAMESPACE::MathExc>("NullQuatExc","imath");
    PyIex::registerExc<IMATH_NAMESPACE::SingMatrixExc,IEX_NAMESPACE::MathExc>("SingMatrixExc","imath");
    PyIex::registerExc<IMATH_NAMESPACE::ZeroScaleExc,IEX_NAMESPACE::MathExc>("ZeroScaleExc","imath");
    PyIex::registerExc<IMATH_NAMESPACE::IntVecNormalizeExc,IEX_NAMESPACE::MathExc>("IntVecNormalizeExc","imath");

    def("computeBoundingBox", &computeBoundingBox<float>,
        "computeBoundingBox(position) -- computes the bounding box from the position array.");

    def("computeBoundingBox", &computeBoundingBox<double>,
        "computeBoundingBox(position) -- computes the bounding box from the position array.");
}

} // namespace PyImath

max_stars_repo_name: marza-animation-planet/openexr

max_issues_repo_name: marza-animation-planet/openexr

max_forks_repo_name: marza-animation-planet/openexr


text:
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2015-2015. 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)
//
// See http://www.boost.org/libs/container for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#include <boost/container/pmr/global_resource.hpp>
#include <boost/container/pmr/memory_resource.hpp>
#include <boost/core/lightweight_test.hpp>
#include <boost/core/no_exceptions_support.hpp>

#include "derived_from_memory_resource.hpp"

#include <cstdlib>
#include <new>

using namespace boost::container;
using namespace boost::container::pmr;

#ifdef BOOST_MSVC
#pragma warning (push)
#pragma warning (disable : 4290)
#endif

#if __cplusplus >= 201103L
#define BOOST_CONTAINER_NEW_EXCEPTION_SPECIFIER
#define BOOST_CONTAINER_DELETE_EXCEPTION_SPECIFIER noexcept
#else
#define BOOST_CONTAINER_NEW_EXCEPTION_SPECIFIER    throw(std::bad_alloc)
#define BOOST_CONTAINER_DELETE_EXCEPTION_SPECIFIER throw()
#endif

#if defined(BOOST_GCC) && (BOOST_GCC >= 50000)
#pragma GCC diagnostic ignored "-Wsized-deallocation"
#endif

//ASAN does not support operator new overloading
#ifndef BOOST_CONTAINER_ASAN

std::size_t allocation_count = 0;

void* operator new[](std::size_t count) BOOST_CONTAINER_NEW_EXCEPTION_SPECIFIER
{
   ++allocation_count;
   return std::malloc(count);
}

void operator delete[](void *p) BOOST_CONTAINER_DELETE_EXCEPTION_SPECIFIER
{
   --allocation_count;
   return std::free(p);
}

#endif   //BOOST_CONTAINER_ASAN

#ifdef BOOST_MSVC
#pragma warning (pop)
#endif

#ifndef BOOST_CONTAINER_ASAN

void test_new_delete_resource()
{
   //Make sure new_delete_resource calls new[]/delete[]
   std::size_t memcount = allocation_count;
   memory_resource *mr = new_delete_resource();
   //each time should return the same pointer
   BOOST_TEST(mr == new_delete_resource());
   #if !defined(BOOST_CONTAINER_DYNAMIC_LINKING)  //No new delete replacement possible new_delete is a DLL
   BOOST_TEST(memcount == allocation_count);
   #endif
   void *addr = mr->allocate(16, 1);
   #if !defined(BOOST_CONTAINER_DYNAMIC_LINKING)  //No new delete replacement possible new_delete is a DLL
   BOOST_TEST((allocation_count - memcount) == 1);
   #endif
   mr->deallocate(addr, 16, 1);
   BOOST_TEST(memcount == allocation_count);
}

#endif   //BOOST_CONTAINER_ASAN

void test_null_memory_resource()
{
   //Make sure it throw or returns null
   memory_resource *mr = null_memory_resource();
   BOOST_TEST(mr != 0);

   #if !defined(BOOST_NO_EXCEPTIONS)
   bool bad_allocexception_thrown = false;

   BOOST_TRY{
      mr->allocate(1, 1);
   }
   BOOST_CATCH(std::bad_alloc&) {
      bad_allocexception_thrown = true;
   }
   BOOST_CATCH(...) {
   }
   BOOST_CATCH_END

   BOOST_TEST(bad_allocexception_thrown == true);
   #endif   //BOOST_NO_EXCEPTIONS
}

void test_default_resource()
{
   //Default resource must be new/delete before set_default_resource
   BOOST_TEST(get_default_resource() == new_delete_resource());
   //Set default resource and obtain previous
   derived_from_memory_resource d;
   memory_resource *prev_default = set_default_resource(&d);
   BOOST_TEST(get_default_resource() == &d);
   //Set default resource with null, which should be new/delete
   prev_default = set_default_resource(0);
   BOOST_TEST(prev_default == &d);
   BOOST_TEST(get_default_resource() == new_delete_resource());
}

int main()
{
   #ifndef BOOST_CONTAINER_ASAN
   test_new_delete_resource();
   #endif
   test_null_memory_resource();
   test_default_resource();
   return ::boost::report_errors();
}


text:
#include "SapConnection.h"
#include <boost/bind.hpp>
#include <iostream>
#include "SapLogHelper.h"
#include "SapMessage.h"
#include "SapCommon.h"
#include "Cipher.h"
#include "TimerManager.h"
#include "SessionManager.h"

#define MAX_SAP_PAKET_LEN 1024*1024*2

int CSapConnection::sm_nHeartInterval=60;
int CSapConnection::sm_nTimeoutInterval=120;

CSapConnection::CSapConnection(boost::asio::io_service &io_service,void *pManager):
    m_socket(io_service),m_resolver(io_service),
    bClientType(false),m_tmHeartBeat((CTimerManager *)pManager),
    bRunning(true),m_nQueueLen(0),m_pManager(pManager),m_pOwner(NULL),
    m_isLocalDigest(false),m_isPeerDigest(false),m_isEnc(false)
{
    m_heartSequence=0;

    m_heartRequest.byIdentifer=SAP_PACKET_REQUEST;
    m_heartRequest.dwServiceId=0;
    m_heartRequest.dwMsgId=0;

    m_heartRequest.byContext=0;
	m_heartRequest.byPrio=0;
	m_heartRequest.byBodyType=0;
	m_heartRequest.byCharset=0;

    m_heartRequest.byHeadLen=sizeof(SSapMsgHeader);
    m_heartRequest.dwPacketLen=htonl(sizeof(SSapMsgHeader));
    m_heartRequest.byVersion=0x01;
    m_heartRequest.byM=0xFF;
    m_heartRequest.dwCode=htonl(SAP_CODE_SUCC);
    memset(m_heartRequest.bySignature,0,16);

    m_heartResponse.byIdentifer=SAP_PACKET_RESPONSE;
    m_heartResponse.dwServiceId=0;
    m_heartResponse.dwMsgId=0;

    m_heartResponse.byContext=0;
	m_heartResponse.byPrio=0;
	m_heartResponse.byBodyType=0;
	m_heartResponse.byCharset=0;

    m_heartResponse.byHeadLen=sizeof(SSapMsgHeader);
    m_heartResponse.dwPacketLen=htonl(sizeof(SSapMsgHeader));
    m_heartResponse.byVersion=0x01;
    m_heartResponse.byM=0xFF;
    m_heartResponse.dwCode=htonl(SAP_CODE_SUCC);
    memset(m_heartResponse.bySignature,0,16);

}

CSapConnection::~CSapConnection()
{
    SS_XLOG(XLOG_TRACE,"CSapConnection::~CSapConnection,\n");
}

void CSapConnection::AsyncConnect(const string &strIp,unsigned int dwPort,int nTimeout,unsigned int dwLocalPort)
{
    SS_XLOG(XLOG_TRACE,"CSapConnection::async_connect,addr[%s:%d],timeout[%d]\n",strIp.c_str(),dwPort,nTimeout);
    bClientType=true;
    m_tmHeartBeat.Init((CTimerManager *)m_pManager,sm_nHeartInterval,boost::bind(&CSapConnection::OnTimer,shared_from_this()),CThreadTimer::TIMER_CIRCLE);

    char szBuf[16]={0};
    sprintf(szBuf,"%d",dwPort);
    tcp::resolver::query query(strIp,szBuf);
    m_resolver.async_resolve(query,
        MakeSapAllocHandler(m_allocReader,
        boost::bind(&CSapConnection::HandleResolve, shared_from_this(),
              boost::asio::placeholders::error,
              boost::asio::placeholders::iterator,dwLocalPort)));
}
void CSapConnection::HandleResolve(const boost::system::error_code& err,tcp::resolver::iterator endpoint_iterator,unsigned int dwLocalPort)
{
    if (!err)
    {
        if(dwLocalPort!=0)
        {
            boost::system::error_code ec;
            m_socket.open(tcp::v4(),ec);
            if(ec)
            {
                SS_SLOG(XLOG_WARNING,"CSapConnection::"<<__FUNCTION__<<",open socket error:" <<ec.message()<<"\n");
                ConnectFinish(-1);
                return;
            }
			m_socket.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true),ec);
            m_socket.bind(tcp::endpoint(tcp::v4(),dwLocalPort),ec);
            if(ec)
            {
                SS_SLOG(XLOG_WARNING,"CSapConnection::"<<__FUNCTION__<<",bind port error:" <<ec.message()<<"\n");
                ConnectFinish(-1);
                return;
            }
        }
        tcp::endpoint endpoint = *endpoint_iterator;
        SS_XLOG(XLOG_DEBUG,"CSapConnection::%s,addr[%s:%d]\n",__FUNCTION__,endpoint.address().to_string() .c_str() ,endpoint.port());
        m_socket.async_connect(endpoint,
            MakeSapAllocHandler(m_allocReader,
          boost::bind(&CSapConnection::HandleConnected, shared_from_this(),
            boost::asio::placeholders::error, ++endpoint_iterator)));
    }
    else
    {
      SS_SLOG(XLOG_WARNING,"CSapConnection::"<<__FUNCTION__<<",error:" <<err.message()<<"\n");
      ConnectFinish(-2);
    }
}
void CSapConnection::HandleConnected(const boost::system::error_code& err,tcp::resolver::iterator endpoint_iterator)
{
    SS_XLOG(XLOG_DEBUG,"CSapConnection::%s\n",__FUNCTION__);
    if (!err)
    {
        SetRemoteAddr();
        ConnectFinish(0);
        AsyncRead();
    }
    else if (endpoint_iterator != tcp::resolver::iterator())
    {
      boost::system::error_code ignore_ec;
      m_socket.close(ignore_ec);
      tcp::endpoint endpoint = *endpoint_iterator;
      m_socket.async_connect(endpoint,
          MakeSapAllocHandler(m_allocReader,boost::bind(&CSapConnection::HandleConnected, shared_from_this(),
            boost::asio::placeholders::error, ++endpoint_iterator)));
    }
    else
    {
        SS_SLOG(XLOG_WARNING,"CSapConnection::"<<__FUNCTION__<<",error:" <<err.message()<<"\n");
        ConnectFinish(-3);
    }
}
void CSapConnection::ConnectFinish(int result)
{
    boost::system::error_code ignore_ec;
    if(m_pOwner!=NULL)
    {
        m_pOwner->OnConnectResult(result);
    }
    if(result!=0)
    {
        CloseInner();
    }
}
void CSapConnection::ASyncReadInner()
{
    ((CSessionManager*)m_pManager)->gettimeofday(&m_AlivePoint, false);
    m_tmHeartBeat.Init((CTimerManager *)m_pManager,sm_nHeartInterval,boost::bind(&CSapConnection::OnTimer,shared_from_this()),CThreadTimer::TIMER_CIRCLE);
    m_tmHeartBeat.Start();

    SS_XLOG(XLOG_DEBUG,"CSapConnection::%s\n",__FUNCTION__);

    m_pHeader=buffer_.base();
    m_socket.async_read_some( boost::asio::buffer(buffer_.top(),buffer_.capacity()),
					MakeSapAllocHandler(m_allocReader,boost::bind(&CSapConnection::HandleRead, shared_from_this(),
							boost::asio::placeholders::error,boost::asio::placeholders::bytes_transferred)));
}

void CSapConnection::SetRemoteAddr()
{
    try{
        m_strRemoteIp=m_socket.remote_endpoint().address().to_string();
		m_dwRemotePort=m_socket.remote_endpoint().port();
    }
    catch(boost::system::system_error & ec){
		SS_SLOG(XLOG_WARNING,"CSapConnection::SetRemoteAddr,code:" <<ec.what()<<"\n");
        m_strRemoteIp="";
        m_dwRemotePort=0;
    }
}
void CSapConnection::AsyncRead()
{
    m_socket.get_io_service().post(boost::bind(&CSapConnection::ASyncReadInner, shared_from_this()));
}
void CSapConnection::HandleRead(const boost::system::error_code& err,std::size_t dwTransferred)
{
    SS_XLOG(XLOG_DEBUG,"CSapConnection::%s,bytes_transferred[%d]\n",__FUNCTION__,dwTransferred);
    if(!err)
    {
        ((CSessionManager*)m_pManager)->gettimeofday(&m_AlivePoint, false);
        buffer_.inc_loc(dwTransferred);
        while(buffer_.top()>=m_pHeader+sizeof(SSapMsgHeader))
        {
            SSapMsgHeader *ptrHeader=(SSapMsgHeader *)m_pHeader;
            unsigned int packetlen=ntohl(ptrHeader->dwPacketLen);
            if(packetlen<=MAX_SAP_PAKET_LEN&&packetlen>0&&(ptrHeader->byIdentifer==SAP_PACKET_REQUEST||ptrHeader->byIdentifer==SAP_PACKET_RESPONSE))
            {
                if(buffer_.top()>=m_pHeader+packetlen)
                {
                    ReadPacketCompleted(m_pHeader,packetlen);
                    m_pHeader+=packetlen;
                }
                else
                {
                    break;
                }
            }
            else
            {
                SS_XLOG(XLOG_WARNING,"CSapConnection::%s,packetlen[%d],identifier[%d], will close this socket\n",__FUNCTION__,packetlen,ptrHeader->byIdentifer);
                ResponseFail(8,8,ntohl(ptrHeader->dwSequence),SAP_CODE_PACKET_ERROR);
                StopConnection();
                return;
            }
        }
        if(m_pHeader!=buffer_.base())
        {
            memmove(buffer_.base(),m_pHeader,buffer_.top()-m_pHeader);
            buffer_.reset_loc(buffer_.top()-m_pHeader);
            m_pHeader=buffer_.base();
        }
        else if(buffer_.capacity()==0)
        {
			m_pHeader=buffer_.base();
	    	SSapMsgHeader *ptrHeader=(SSapMsgHeader *)m_pHeader;
            unsigned int packetlen=ntohl(ptrHeader->dwPacketLen);
            buffer_.add_capacity(SAP_ALIGN(packetlen));
            m_pHeader=buffer_.base();
        }
        m_socket.async_read_some(boost::asio::buffer(buffer_.top(),buffer_.capacity()),
           MakeSapAllocHandler(m_allocReader,boost::bind(&CSapConnection::HandleRead, shared_from_this(),
                boost::asio::placeholders::error,boost::asio::placeholders::bytes_transferred)));
    }
    else
    {
        SS_SLOG(XLOG_WARNING,"CSapConnection::"<<__FUNCTION__<<",addr["<<m_strRemoteIp<<":"<<m_dwRemotePort<<"],error:" <<err.message()<<"\n");
        StopConnection();
    }
}
void CSapConnection::ReadPacketCompleted(const void *pBuffer, unsigned int nLen)
{
    SSapMsgHeader *pHeader=(SSapMsgHeader *)pBuffer;
    unsigned int dwServiceId=ntohl(pHeader->dwServiceId);
    unsigned int dwMsgId=ntohl(pHeader->dwMsgId);
    unsigned int dwSequence=ntohl(pHeader->dwSequence);
    if(pHeader->byIdentifer==SAP_PACKET_REQUEST&&
        dwServiceId==0&&dwMsgId==0)
    {
        dump_sap_packet_info(pBuffer,E_SAP_IN);
        m_heartResponse.dwSequence=pHeader->dwSequence;
        dump_sap_packet_info(&m_heartResponse,E_SAP_OUT);
        WriteDataInner(&m_heartResponse,sizeof(SSapMsgHeader));
    }
    else if(pHeader->byIdentifer==SAP_PACKET_RESPONSE&&
        dwServiceId==0&&dwMsgId==0)
    {
        dump_sap_packet_info(pBuffer,E_SAP_IN);
    }
    else if(pHeader->byIdentifer==SAP_PACKET_RESPONSE||
        (pHeader->byIdentifer==SAP_PACKET_REQUEST&&pHeader->byM!=0))
    {
        dump_sap_packet_notice(pBuffer,E_SAP_IN);

        if(m_isPeerDigest)
        {
            unsigned char arSignature[16];
            SSapMsgHeader *pHeader=(SSapMsgHeader *)pBuffer;
            memcpy(arSignature,pHeader->bySignature,16);

            int nDigestLen=m_strPeerKey.size();
            int nMin=(nDigestLen<16?nDigestLen:16);

            memset(pHeader->bySignature,0,16);
            memcpy(pHeader->bySignature,m_strPeerKey.c_str(),nMin);

            CCipher::Md5((const unsigned char *)pBuffer,nLen,pHeader->bySignature);
            if(memcmp(arSignature,pHeader->bySignature,16)!=0)
            {
                ResponseFail(dwServiceId,dwMsgId,dwSequence,SAP_CODE_DEGEST_ERROR);
                return;
            }
        }

        if(m_isEnc)
        {
            SSapMsgHeader *pHeader=(SSapMsgHeader *)pBuffer;
            unsigned char *ptrLoc=(unsigned char *)pBuffer+pHeader->byHeadLen;
            CCipher::AesDec(m_arEncKey,ptrLoc,nLen-pHeader->byHeadLen,ptrLoc);
        }
        if(m_pOwner!=NULL)
        {
            m_pOwner->OnReadCompleted(pBuffer,nLen);
        }
    }
    else if(pHeader->byIdentifer==SAP_PACKET_REQUEST&&pHeader->byM==0)
    {
        dump_sap_packet_notice(pBuffer,E_SAP_IN);
        ResponseFail(dwServiceId,dwMsgId,dwSequence,SAP_CODE_MAX_FORWARD);
    }
    else
    {
        dump_sap_packet_notice(pBuffer,E_SAP_IN);
    }
}
void CSapConnection::WriteDataInner(const void *pBuffer,int nLen,unsigned int dwTimeout)
{
    SSapLenMsg msg;
    msg.nLen=nLen;
    msg.pBuffer=pBuffer;

    bool write_in_progress = !m_queue.empty();
    m_queue.push_back(msg);
    m_nQueueLen++;
    if (!write_in_progress)//if empty before pushing
    {
        boost::asio::async_write(m_socket,
                  boost::asio::buffer(m_queue.front().pBuffer,m_queue.front().nLen),
                  MakeSapAllocHandler(m_allocWrite,boost::bind(&CSapConnection::HandleWrite, shared_from_this(),
                    boost::asio::placeholders::error)));
    }
}
void CSapConnection::WriteData(const void *pBuffer,int nLen, const void* pExHead, int nExLen,unsigned int dwTimeout)
{
    SSapMsgHeader *pHeader=(SSapMsgHeader *)pBuffer;

    if(m_nQueueLen>MAX_QUEUE_FULL)
    {
        SS_XLOG(XLOG_ERROR,"CSapConnection::%s,queueLen too many[%d], will discard,identifer[%d],target addr[%s:%d]\n",
            __FUNCTION__,m_nQueueLen,pHeader->byIdentifer,m_strRemoteIp.c_str(),m_dwRemotePort);
        if(pHeader->byIdentifer==SAP_PACKET_REQUEST&&m_pOwner!=NULL)
        {
            SSapMsgHeader stSendFailResponse;
            stSendFailResponse.byIdentifer=SAP_PACKET_RESPONSE;
            stSendFailResponse.byHeadLen=sizeof(SSapMsgHeader);
            stSendFailResponse.dwPacketLen=htonl(sizeof(SSapMsgHeader));
            stSendFailResponse.byVersion=0x1;
            stSendFailResponse.dwCode=htonl(SAP_CODE_QUEUE_FULL);

            stSendFailResponse.dwServiceId=pHeader->dwServiceId;
            stSendFailResponse.dwMsgId=pHeader->dwMsgId;
            stSendFailResponse.dwSequence=pHeader->dwSequence;
            m_pOwner->OnReadCompleted(&stSendFailResponse,sizeof(stSendFailResponse));
        }
        return;
    }

/*first enc, then digest*/
    int nFactLen=nLen+nExLen;
    unsigned int nLeft=0x10-(nLen-pHeader->byHeadLen)&0x0f;

    if(m_isEnc)
    {
        nFactLen=nLen+nExLen+nLeft;
    }

	void *wrBuffer=malloc(nFactLen);
	memcpy(wrBuffer,pBuffer,pHeader->byHeadLen);
	if (nExLen > 0)
		memcpy((char *)wrBuffer+pHeader->byHeadLen, pExHead, nExLen);
	memcpy((char *)wrBuffer+pHeader->byHeadLen+nExLen, (char *)pBuffer+pHeader->byHeadLen, nLen-pHeader->byHeadLen);

    pHeader=(SSapMsgHeader *)wrBuffer;
    pHeader->byHeadLen += nExLen;
    pHeader->dwPacketLen = htonl(ntohl(pHeader->dwPacketLen)+nExLen);

    dump_sap_packet_notice(wrBuffer,E_SAP_OUT);
    if(m_isEnc)
    {
    	if(nLeft>0)
    	{
            memset((char *)wrBuffer+nExLen+nLen,0,nLeft);
    	}

        unsigned char *pbyInBlk=(unsigned char *)wrBuffer+pHeader->byHeadLen;
        CCipher::AesEnc(m_arEncKey,pbyInBlk,nFactLen-pHeader->byHeadLen,pbyInBlk);
        pHeader->dwPacketLen=htonl(nFactLen);
    }

    if(m_isLocalDigest)
    {
        int nDigestLen=m_strLocalKey.length();
        int nMin=(nDigestLen<16?nDigestLen:16);
        memcpy(pHeader->bySignature,m_strLocalKey.c_str(),nMin);
        CCipher::Md5((unsigned char *)wrBuffer,nFactLen,pHeader->bySignature);
    }

    WriteDataInner(wrBuffer,nFactLen,dwTimeout);
}

void CSapConnection::WriteData(const void *pBuffer,int nLen,unsigned int dwTimeout)
{
    SSapMsgHeader *pHeader=(SSapMsgHeader *)pBuffer;
    dump_sap_packet_notice(pBuffer,E_SAP_OUT);

    if(m_nQueueLen>MAX_QUEUE_FULL)
    {
        SS_XLOG(XLOG_ERROR,"CSapConnection::%s,queueLen too many[%d], will discard,identifer[%d],target addr[%s:%d]\n",
            __FUNCTION__,m_nQueueLen,pHeader->byIdentifer,m_strRemoteIp.c_str(),m_dwRemotePort);
        if(pHeader->byIdentifer==SAP_PACKET_REQUEST&&m_pOwner!=NULL)
        {
            SSapMsgHeader stSendFailResponse;
            stSendFailResponse.byIdentifer=SAP_PACKET_RESPONSE;
            stSendFailResponse.byHeadLen=sizeof(SSapMsgHeader);
            stSendFailResponse.dwPacketLen=htonl(sizeof(SSapMsgHeader));
            stSendFailResponse.byVersion=0x1;
            stSendFailResponse.dwCode=htonl(SAP_CODE_QUEUE_FULL);

            stSendFailResponse.dwServiceId=pHeader->dwServiceId;
            stSendFailResponse.dwMsgId=pHeader->dwMsgId;
            stSendFailResponse.dwSequence=pHeader->dwSequence;
            m_pOwner->OnReadCompleted(&stSendFailResponse,sizeof(stSendFailResponse));
        }
        return;
    }

/*first enc, then digest*/
    int nFactLen=nLen;
    unsigned int nLeft=0x10-(nLen-pHeader->byHeadLen)&0x0f;

    if(m_isEnc)
    {
        nFactLen=nLen+nLeft;
    }

    void *wrBuffer=malloc(nFactLen);
    memcpy(wrBuffer,pBuffer,nLen);
    pHeader=(SSapMsgHeader *)wrBuffer;

    if(m_isEnc)
    {
    	if(nLeft>0)
    	{
            memset((char *)wrBuffer+nLen,0,nLeft);
    	}

        unsigned char *pbyInBlk=(unsigned char *)wrBuffer+pHeader->byHeadLen;
        CCipher::AesEnc(m_arEncKey,pbyInBlk,nFactLen-pHeader->byHeadLen,pbyInBlk);
        pHeader->dwPacketLen=htonl(nFactLen);
    }

    if(m_isLocalDigest)
    {
        int nDigestLen=m_strLocalKey.length();
        int nMin=(nDigestLen<16?nDigestLen:16);
        memcpy(pHeader->bySignature,m_strLocalKey.c_str(),nMin);
        CCipher::Md5((unsigned char *)wrBuffer,nFactLen,pHeader->bySignature);
    }

    WriteDataInner(wrBuffer,nFactLen,dwTimeout);
}
void CSapConnection::HandleWrite(const boost::system::error_code& err)
{
    SS_XLOG(XLOG_DEBUG,"CSapConnection::%s\n",__FUNCTION__);
    SSapMsgHeader *pHeader=NULL;
    unsigned int dwServiceId=0;
    unsigned int dwMsgId=0;
    if(err)
    {
        SS_SLOG(XLOG_WARNING,"CSapConnection::"<<__FUNCTION__<<",addr["<<m_strRemoteIp<<":"<<m_dwRemotePort<<"],error:" <<err.message()<<"\n");
        while(!m_queue.empty())
        {
            SSapMsgHeader *pHeader=(SSapMsgHeader *)(m_queue.front().pBuffer);
            unsigned int dwServiceId=ntohl(pHeader->dwServiceId);
            unsigned int dwMsgId=ntohl(pHeader->dwMsgId);

            if(!(dwServiceId==0&&dwMsgId==0))
            {
                SSapMsgHeader stSendFailResponse;
                stSendFailResponse.byIdentifer=SAP_PACKET_RESPONSE;
                stSendFailResponse.byHeadLen=sizeof(SSapMsgHeader);
                stSendFailResponse.dwPacketLen=htonl(sizeof(SSapMsgHeader));
                stSendFailResponse.byVersion=0x1;
                stSendFailResponse.dwCode=htonl(SAP_CODE_SEND_FAIL);

                stSendFailResponse.dwServiceId=pHeader->dwServiceId;
                stSendFailResponse.dwMsgId=pHeader->dwMsgId;
                stSendFailResponse.dwSequence=pHeader->dwSequence;
                if(m_pOwner!=NULL)
                {
                    m_pOwner->OnReadCompleted(&stSendFailResponse,sizeof(stSendFailResponse));
                }
                free((void *)(m_queue.front().pBuffer));
            }
            m_queue.pop_front();
            m_nQueueLen--;
        }
        CloseInner();
        return;
    }

    pHeader = (SSapMsgHeader *)(m_queue.front().pBuffer);
    dwServiceId = ntohl(pHeader->dwServiceId);
    dwMsgId = ntohl(pHeader->dwMsgId);
    if(!(dwServiceId==0&&dwMsgId==0))
    {
        free((void *)(m_queue.front().pBuffer));
    }

    m_queue.pop_front();
    m_nQueueLen--;
    if (!m_queue.empty())
    {
        boost::asio::async_write(m_socket,
              boost::asio::buffer(m_queue.front().pBuffer,m_queue.front().nLen),
              MakeSapAllocHandler(m_allocWrite,boost::bind(&CSapConnection::HandleWrite, shared_from_this(),
                boost::asio::placeholders::error)));
    }
}

void CSapConnection::OnTimer()
{
    if(bClientType==true)
    {
        m_heartRequest.dwSequence=htonl(m_heartSequence++);
        dump_sap_packet_info(&m_heartRequest,E_SAP_OUT);
        WriteDataInner(&m_heartRequest,sizeof(SSapMsgHeader));
    }

    struct timeval_a now,interval,endtime;
    gettimeofday_a(&now,NULL);
    interval.tv_sec=sm_nTimeoutInterval;
    interval.tv_usec=0;
    timeradd(&m_AlivePoint,&interval,&endtime);
    if(timercmp(&now,&endtime,>))
    {
        SS_XLOG(XLOG_WARNING,"CSapConnection::%s, will close[%s:%d].alive[%ld.%06ld] now[%ld.%06ld]\n",
            __FUNCTION__,m_strRemoteIp.c_str(),m_dwRemotePort, m_AlivePoint.tv_sec,m_AlivePoint.tv_usec,
            now.tv_sec,now.tv_usec);
        CloseInner();
    }
}
void CSapConnection::Close()
{
    bRunning=false;
    CloseInner();
}
void CSapConnection::CloseInner()
{
    SS_XLOG(XLOG_TRACE,"CSapConnection::%s\n",__FUNCTION__);

    boost::system::error_code ignore_ec;
    m_socket.close(ignore_ec);
    m_tmHeartBeat.Stop();
    m_tmHeartBeat.Init();
}

void CSapConnection::StopConnection()
{
    boost::system::error_code ignore_ec;
    m_socket.close(ignore_ec);
    m_tmHeartBeat.Stop();
    m_tmHeartBeat.Init();
    if(bRunning)
    {
        bRunning=false;
        if(m_pOwner!=NULL)
        {
            m_pOwner->OnPeerClose();

        }
    }
}
void CSapConnection::SetLocalDigest(const string &strDigest)
{
    m_isLocalDigest=true;
	m_strLocalKey=strDigest;
}
void CSapConnection::SetPeerDigest(const string &strDigest)
{
    m_isPeerDigest=true;
    m_strPeerKey=strDigest;
}
void CSapConnection::SetEncKey(unsigned char arKey[16])
{
    m_isEnc=true;
	memcpy(m_arEncKey,arKey,16);
}
void CSapConnection::ResponseFail(unsigned int dwServiceId,unsigned int dwMsgId,unsigned int dwSequence,unsigned int dwCode)
{
    SSapMsgHeader response;
    response.byIdentifer=SAP_PACKET_RESPONSE;
    response.dwServiceId=htonl(dwServiceId);
    response.dwMsgId=htonl(dwMsgId);
    response.dwSequence=htonl(dwSequence);

    response.byContext=0;
	response.byPrio=0;
	response.byBodyType=0;
	response.byCharset=0;

    response.byHeadLen=sizeof(SSapMsgHeader);
    response.dwPacketLen=htonl(sizeof(SSapMsgHeader));
    response.byVersion=0x01;
    response.byM=0xFF;
    response.dwCode=htonl(dwCode);
    WriteData(&response,sizeof(SSapMsgHeader));
}

void CSapConnection::dump_sap_packet_notice(const void *pBuffer,ESapDirectType type)
{
    if(IsEnableLevel(SAP_STACK_MODULE,XLOG_NOTICE))
    {
        string strPacket;
        char szPeer[128]={0};
        sprintf(szPeer,"%s:%d",m_strRemoteIp.c_str() ,m_dwRemotePort);

        if(type==E_SAP_IN)
        {
            strPacket=string("Read Sap Command from  addr[")+szPeer+"]\n";
        }
        else
        {
            strPacket=string("Write Sap Command to  addr[")+szPeer+"]\n";
        }

        SSapMsgHeader *pHeader=(SSapMsgHeader *)pBuffer;

        unsigned char *pChar=(unsigned char *)pBuffer;
        unsigned int nPacketlen=ntohl(pHeader->dwPacketLen);
        int nLine=nPacketlen>>3;
        int nLast=(nPacketlen&0x7);
        int i=0;
        for(i=0;(i<nLine)&&(i<200);i++)
        {
            char szBuf[128]={0};
            unsigned char * pBase=pChar+(i<<3);
            sprintf(szBuf,"                [%2d]    %02x %02x %02x %02x    %02x %02x %02x %02x    ......\n",
                i,*(pBase),*(pBase+1),*(pBase+2),*(pBase+3),*(pBase+4),*(pBase+5),*(pBase+6),*(pBase+7));
            strPacket+=szBuf;
        }

        unsigned char * pBase=pChar+(i<<3);
        if(nLast>0)
        {
            for(int j=0;j<8;j++)
            {
                char szBuf[128]={0};
                if(j==0)
                {
                    sprintf(szBuf,"                [%2d]    %02x ",i,*(pBase+j));
                    strPacket+=szBuf;
                }
                else if(j<nLast&&j==3)
                {
                    sprintf(szBuf,"%02x    ",*(pBase+j));
                    strPacket+=szBuf;
                }
                else if(j>=nLast&&j==3)
                {
                    strPacket+="      ";
                }
                else if(j<nLast)
                {
                    sprintf(szBuf,"%02x ",*(pBase+j));
                    strPacket+=szBuf;
                }
                else
                {
                    strPacket+="   ";
                }

            }
            strPacket+="   ......\n";
        }
        SS_XLOG(XLOG_NOTICE,strPacket.c_str());
    }
}
void CSapConnection::dump_sap_packet_info(const void *pBuffer,ESapDirectType type)
{
    if(IsEnableLevel(SAP_STACK_MODULE,XLOG_INFO))
    {
        string strPacket;
        char szPeer[64]={0};
        sprintf(szPeer,"%s:%d",m_strRemoteIp.c_str() ,m_dwRemotePort);

        if(type==E_SAP_IN)
        {
            strPacket=string("Read Sap Command from addr[")+szPeer+"]\n";
        }
        else
        {
            strPacket=string("Write Sap Command to addr[")+szPeer+"]\n";
        }

        SSapMsgHeader *pHeader=(SSapMsgHeader *)pBuffer;

        unsigned char *pChar=(unsigned char *)pBuffer;
        unsigned int nPacketlen=ntohl(pHeader->dwPacketLen);
        int nLine=nPacketlen>>3;
        int nLast=(nPacketlen&0x7);
        int i=0;
        for(i=0;(i<nLine) && (i<200);i++)
        {
            char szBuf[128]={0};
            unsigned char * pBase=pChar+(i<<3);
            sprintf(szBuf,"                [%2d]    %02x %02x %02x %02x    %02x %02x %02x %02x    ......\n",
                i,*(pBase),*(pBase+1),*(pBase+2),*(pBase+3),*(pBase+4),*(pBase+5),*(pBase+6),*(pBase+7));
            strPacket+=szBuf;
        }

        unsigned char * pBase=pChar+(i<<3);
        if(nLast>0)
        {
            for(int j=0;j<8;j++)
            {
                char szBuf[128]={0};
                if(j==0)
                {
                    sprintf(szBuf,"                [%2d]    %02x ",i,*(pBase+j));
                    strPacket+=szBuf;
                }
                else if(j<nLast&&j==3)
                {
                    sprintf(szBuf,"%02x    ",*(pBase+j));
                    strPacket+=szBuf;
                }
                else if(j>=nLast&&j==3)
                {
                    strPacket+="      ";
                }
                else if(j<nLast)
                {
                    sprintf(szBuf,"%02x ",*(pBase+j));
                    strPacket+=szBuf;
                }
                else
                {
                    strPacket+="   ";
                }

            }
            strPacket+="   ......\n";
        }
        SS_XLOG(XLOG_INFO,strPacket.c_str());
    }
}
void CSapConnection::Dump()
{
    SS_XLOG(XLOG_NOTICE,"@@@@      manager[%x],own[%x],addr[%s:%d],type[%d]\n",
        m_pManager,m_pOwner,m_strRemoteIp.c_str(),m_dwRemotePort,bClientType);
    SS_XLOG(XLOG_NOTICE,"           isLocalKey[%d],localkey[%s]\n",m_isLocalDigest,m_strLocalKey.c_str());
    SS_XLOG(XLOG_NOTICE,"           isPeerDigest[%d],PeerKey[%s]\n",m_isPeerDigest,m_strPeerKey.c_str());
    SS_XLOG(XLOG_NOTICE,"           isEnc[%d],enckey[%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x]\n",
        m_isEnc,m_arEncKey[0],m_arEncKey[1],m_arEncKey[2],m_arEncKey[3],
        m_arEncKey[4],m_arEncKey[5],m_arEncKey[6],m_arEncKey[7],
        m_arEncKey[8],m_arEncKey[9],m_arEncKey[10],m_arEncKey[11],
        m_arEncKey[12],m_arEncKey[13],m_arEncKey[14],m_arEncKey[15]);
}

max_stars_repo_name: shrewdlin/BPE

max_issues_repo_name: shrewdlin/BPE

max_forks_repo_name: shrewdlin/BPE


text:
#pragma once

#include <boost/asio.hpp>

namespace beast_fun_times::config
{
    namespace net = boost::asio;
    using error_code = boost::system::error_code;
    using system_error = boost::system::system_error;
}