text:
#ifndef __GPUDB_INGESTOR_HPP__
#define __GPUDB_INGESTOR_HPP__

#include "gpudb/GPUdb.hpp"
#include "gpudb/Http.hpp"
#include "gpudb/Type.hpp"
#include "gpudb/utils/GPUdbMultiHeadIOUtils.h"

#include <atomic>
#include <map>
#include <string>
#include <vector>
#include <mutex>

#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>

namespace gpudb
{

// Forward declaration
class GPUdb;

/*
 * The multi-head ingestor class (also handles regular insertion).  Using this class is
 * significantly more computation-intensive compared to a regular insertion.  So, it is
 * highly recommended to use this ingestor only if multi-head ingestion is actually turned
 * on in the server and there is a large volume of records to be inserted.
 */
class GPUdbIngestor : private boost::noncopyable
{

public:

    GPUdbIngestor( const gpudb::GPUdb& db, const gpudb::Type& record_type,
                   const std::string& table_name,
                   const WorkerList& worker_list,
                   const std::map<std::string, std::string>& insert_options,
                   size_t batch_size );

    GPUdbIngestor( const gpudb::GPUdb& db, const gpudb::Type& record_type,
                   const std::string& table_name,
                   const WorkerList& worker_list,
                   size_t batch_size );

    GPUdbIngestor( const gpudb::GPUdb& db, const gpudb::Type& record_type,
                   const std::string& table_name,
                   const std::map<std::string, std::string>& insert_options,
                   size_t batch_size );

    GPUdbIngestor( const gpudb::GPUdb& db, const gpudb::Type& record_type,
                   const std::string& table_name, size_t batch_size );

    ~GPUdbIngestor();

    /**
     * Returns the name of the table on which this class operates.
     */
    const std::string& getTableName() const { return m_table_name; }

    /**
     * Returns the GPUdb client handle that this class uses internally.
     */
    const gpudb::GPUdb& getGPUdb() const { return m_db; }

    /**
     * Returns the insertion options the ingestor uses.
     */
    const std::map<std::string, std::string>& getOptions() const { return m_insert_options; }

    /**
     * Returns the count of records inserted so far through this ingestor
     * instance;  An atomic operation.
     */
    size_t getCountInserted() const { return m_count_inserted; }

    /**
     * Returns the count of records updated so far through this ingestor
     * instance;  An atomic operation.
     */
    size_t getCountUpdated() const { return m_count_updated; }

    /**
     * Returns the list of errors and warnings received since the last call
     * to getErrors(), and clears the list.
     */
    std::vector<GPUdbInsertionException> getErrors();

    /**
     * Ensures that all queued records are inserted into the database.  If an error
     * occurs while inserting the records from any queue, the recoreds will no
     * longer be in that queue nor in the database; catch <see cref="GPUdbInsertException{T}" />
     * to get the list of records that were being inserted if needed (for example,
     * to retry).  Other queues may also still contain unflushed records if this
     * occurs.
     */
    void flush();

    /**
     * Queues a record for insertion into GPUdb.  If the queue reaches
     * the <member cref="batch_size" />, all records in the queue will be
     * inserted into Kinetica before the method returns.  If an error occurs
     * while inserting the records, the records will no longer be in the queue
     * nor in Kinetica; catch <see cref="InsertException{T}"/>  to get the list
     * of records that were being inserted if needed (for example, to retry).
     *
     * <param name="record">The record to insert.</param>
     */
    void insert( gpudb::GenericRecord record );

    /**
     * Queues a list of records for insertion into Kientica.  If any queue reaches
     * the <member cref="batch_size" />, all records in the queue will be
     * inserted into Kinetica before the method returns.  If an error occurs
     * while inserting the records, the records will no longer be in the queue
     * nor in Kinetica; catch <see cref="InsertException{T}"/>  to get the list
     * of records that were being inserted if needed (for example, to retry).
     *
     * <param name="records">The records to insert.</param>
     */
    void insert( std::vector<gpudb::GenericRecord> records );

private:

    typedef std::map<std::string, std::string>          str_to_str_map_t;
    typedef boost::shared_ptr<gpudb::WorkerQueue>       worker_queue_ptr_t;

    GPUdbIngestor();

    void construct( const gpudb::GPUdb& db,
                    const gpudb::Type& record_type,
                    const std::string& table_name,
                    const WorkerList& worker_list,
                    size_t batch_size );

    /*
     * Insert the given list of records to the database residing at the given URL.
     * Upon any error, thrown InsertException with the queue of records passed into it.
     */
    void flush( const std::vector<gpudb::GenericRecord>& queue,
                const gpudb::HttpUrl& url );

    const gpudb::GPUdb&              m_db;
    std::string                      m_table_name;
    size_t                           m_batch_size;
    std::atomic<size_t>              m_count_inserted;
    std::atomic<size_t>              m_count_updated;
    str_to_str_map_t                 m_insert_options;
    gpudb::Type                      m_record_type;
    gpudb::RecordKeyBuilder*         m_primary_key_builder_ptr;
    gpudb::RecordKeyBuilder*         m_shard_key_builder_ptr;
//    record_key_buildter_ptr          m_primary_key_builder_ptr;
//    record_key_buildter_ptr          m_shard_key_builder_ptr;
    std::vector<int32_t>             m_routing_table;
    std::vector<worker_queue_ptr_t>  m_worker_queues;
    std::vector<GPUdbInsertionException> m_error_list;
    std::mutex                       m_error_list_lock;

};  // end class GPUdbIngestor

} // namespace gpudb

#endif // __GPUDB_INGESTOR_HPP__

max_stars_repo_name: GPUdb/gpudb-api-cpp

max_issues_repo_name: GPUdb/gpudb-api-cpp

max_forks_repo_name: GPUdb/gpudb-api-cpp


text:
//          Copyright Oliver Kowalke 2014.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_COROUTINE2_DETAIL_WRAP_H
#define BOOST_COROUTINE2_DETAIL_WRAP_H

#include <type_traits>

#include <boost/config.hpp>
#include <boost/context/detail/invoke.hpp>
#include <boost/context/fiber.hpp>

#include <boost/coroutine2/detail/config.hpp>

#ifdef BOOST_HAS_ABI_HEADERS
#include BOOST_ABI_PREFIX
#endif

namespace boost {
namespace coroutines2 {
namespace detail {

template <typename Fn1, typename Fn2> class wrapper {
private:
  typename std::decay<Fn1>::type fn1_;
  typename std::decay<Fn2>::type fn2_;

public:
  wrapper(Fn1 &&fn1, Fn2 &&fn2) : fn1_(std::move(fn1)), fn2_(std::move(fn2)) {}

  wrapper(wrapper const &) = delete;
  wrapper &operator=(wrapper const &) = delete;

  wrapper(wrapper &&other) = default;
  wrapper &operator=(wrapper &&other) = default;

  boost::context::fiber operator()(boost::context::fiber &&c) {
    return boost::context::detail::invoke(
        std::move(fn1_), fn2_, std::forward<boost::context::fiber>(c));
  }
};

template <typename Fn1, typename Fn2>
wrapper<Fn1, Fn2> wrap(Fn1 &&fn1, Fn2 &&fn2) {
  return wrapper<Fn1, Fn2>(std::forward<Fn1>(fn1), std::forward<Fn2>(fn2));
}

} // namespace detail
} // namespace coroutines2
} // namespace boost

#ifdef BOOST_HAS_ABI_HEADERS
#include BOOST_ABI_SUFFIX
#endif

#endif // BOOST_COROUTINE2_DETAIL_WRAP_H

ext: hpp

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
//--------------------------------------------------------------------------------
//This is a file from Arkengine
//
//
//Copyright (c) arkenthera.All rights reserved.
//
//BasicRenderWindow.cpp
//--------------------------------------------------------------------------------

#include "Core/YumeHeaders.h"
#include "Playground.h"
#include "Logging/logging.h"
#include "Core/YumeMain.h"
#include <boost/shared_ptr.hpp>

#include "Input/YumeInput.h"

#include "Renderer/YumeTexture2D.h"

#include "Renderer/YumeResourceManager.h"

#include "Renderer/YumeRHI.h"

#include "UI/YumeDebugOverlay.h"
#include "UI/YumeOptionsMenu.h"

#include "Engine/YumeEngine.h"

#include "Core/SharedPtr.h"

#include "UI/YumeUI.h"

#include "Renderer/StaticModel.h"

#include "Renderer/Scene.h"
#include "Renderer/Light.h"
#include <Renderer/RenderPass.h>

#include "Core/MersenneTwister.h"

YUME_DEFINE_ENTRY_POINT(YumeEngine::PlaygroundDemo);

#define TURNOFF 1
#define NO_MODEL
#define OBJECTS_CAST_SHADOW
#define NO_SKYBOX
#define NO_PLANE
#define CORNELL
#define DISABLE_EVERYTHING
//#define PBR_TEST_SPONZA

#define SCALE ((1<<15))

namespace YumeEngine
{

	MTRand Rng;

	PlaygroundDemo::PlaygroundDemo()
		: rot_(Quaternion::IDENTITY),
		rotationAngle_(0.0f)
	{
		REGISTER_ENGINE_LISTENER;

		m_RadiusMultiplier  = 1;
		m_AngleBias         = 30;
		m_NumDirs		    = 16;
		m_NumSteps		    = 8;
		m_Contrast          = 1.25f;
		m_Attenuation       = 1.0f;
		m_AORadius			= 1;

		m_BlurRadius     = 7;
		m_Sharpness      = 16.0f;
		m_EdgeThreshold  = 0.1f;

		m_NumSamples     = 1;
	}

	PlaygroundDemo::~PlaygroundDemo()
	{

	}

	void PlaygroundDemo::Start()
	{
		YumeResourceManager* rm_ = gYume->pResourceManager;

		gYume->pInput->AddListener(this);

#ifndef DISABLE_CEF
		optionsMenu_ = new YumeOptionsMenu;
		gYume->pUI->AddUIElement(optionsMenu_);
		optionsMenu_->SetVisible(true);

		overlay_ = new YumeDebugOverlay;
		gYume->pUI->AddUIElement(overlay_);
		overlay_->SetVisible(true);
		overlay_->GetBinding("SampleName")->SetValue("Playground");
#endif

		MaterialPtr diff = YumeAPINew Material;
		diff->SetShaderParameter("DiffuseColor",DirectX::XMFLOAT4(0.4f,0.4f,0.4f,1));
		diff->SetShaderParameter("SpecularColor",DirectX::XMFLOAT4(1,1,1,1));
		diff->SetShaderParameter("Roughness",1.0f);
		diff->SetShaderParameter("ShadingMode",2.0f);
		diff->SetShaderParameter("has_diffuse_tex",false);
		diff->SetShaderParameter("has_alpha_tex",false);
		diff->SetShaderParameter("has_specular_tex",false);
		diff->SetShaderParameter("has_normal_tex",false);
		diff->SetShaderParameter("has_roughness_tex",false);

		DirectX::XMFLOAT3 min = gYume->pRenderer->GetMinBb();
		DirectX::XMFLOAT3 max = gYume->pRenderer->GetMaxBb();

		DirectX::XMFLOAT3 delta = DirectX::XMFLOAT3(max.x - min.x,max.y - min.y,max.z - min.z);

		float x = 0;
		float y = 5;

		Light* dirLight = new Light;
		dirLight->SetName("DirLight");
		dirLight->SetType(LT_DIRECTIONAL);
		/*dirLight->SetPosition(DirectX::XMVectorSet(0,20,0,0));*/
		dirLight->SetPosition(DirectX::XMVectorSet(0,20,0,0));
		dirLight->SetDirection(DirectX::XMVectorSet(0,-1,0,0));
		dirLight->SetRotation(DirectX::XMVectorSet(-1,0,0,0));
		dirLight->SetColor(YumeColor(1,1,1,0));

		StaticModel* jeyjeyModel = CreateModel("Models/dragon/dragon.yume");

		StaticModel* mitsubaLeft = CreateModel("Models/Mitsuba/mitsuba-sphere.yume",DirectX::XMFLOAT3(-5,0,0),DirectX::XMFLOAT4(0,0,0,0),DirectX::XMFLOAT3(2.3f,2.3f,2.3f));
		StaticModel* mitsubaRight = CreateModel("Models/Mitsuba/mitsuba-sphere.yume",DirectX::XMFLOAT3(5,0,0),DirectX::XMFLOAT4(0,0,0,0),DirectX::XMFLOAT3(2.3f,2.3f,2.3f));

		mitsubaLeft->SetMaterial(diff);
		mitsubaRight->SetMaterial(diff);

		StaticModel* dragon= CreateModel("Models/cornell/cornell-empty.yume");
		jeyjeyModel->SetScale(18,18,18);
		jeyjeyModel->SetPosition(DirectX::XMVectorSet(0,10,0,1));
		jeyjeyModel->SetRotation(DirectX::XMVectorSet(0,M_DEGTORAD * 90,0,1));

		RenderPass* dp = gYume->pRenderer->GetDefaultPass();
		//dp->Load("RenderCalls/Bloom.xml",true);
		dp->Load("RenderCalls/FXAA.xml",true);
		dp->Load("RenderCalls/LensDistortion.xml",true);
		dp->Load("RenderCalls/SSAO.xml",true);

		gYume->pRenderer->GetScene()->AddNode(dirLight);

		RenderTargetDesc desc;
		desc.Index = 5;

		randomMap_ = (gYume->pRHI->CreateTexture2D());
		randomMap_->SetName("RandomVec");
		randomMap_->SetDesc(desc);
		randomMap_->SetSize(64,64,gYume->pRHI->GetRGBA16FormatNs(),TEXTURE_STATIC,1,1);

		RenderPass* d = gYume->pRenderer->GetDefaultPass();

		d->AddTexture(5,"HorizonBasedAO",randomMap_);

		UpdateSSAO();
		UpdateAngleBias();
		UpdateRadius();

		UpdateBlur();
		UpdateSharpness();

		float width = gYume->pRHI->GetWidth() * 0.5f;
		float height = gYume->pRHI->GetHeight() * 0.5f;

		float fovy = 60 * M_DEGTORAD;

		m_FocalLen[0]      = 1.0f / tanf(fovy * 0.5f) *  (float)width / (float)height;
		m_FocalLen[1]      = 1.0f / tanf(fovy * 0.5f);
		m_InvFocalLen[0]   = 1.0f / m_FocalLen[0];
		m_InvFocalLen[1]   = 1.0f / m_FocalLen[1];
		m_InvResolution[0] = 1.0f / width;
		m_InvResolution[1] = 1.0f / height;
		m_Resolution[0]    = (float)width;
		m_Resolution[1]    = (float)height;

		d->SetShaderParameter("g_NumSteps",(float)m_NumSteps);
		d->SetShaderParameter("g_Attenuation",m_Attenuation);
		d->SetShaderParameter("g_FocalLen",Vector2(m_FocalLen[0],m_FocalLen[1]));
		d->SetShaderParameter("g_InvFocalLen",Vector2(m_InvFocalLen[0],m_InvFocalLen[1]));

		d->SetShaderParameter("g_Resolution",Vector2(m_Resolution[0],m_Resolution[1]));
		d->SetShaderParameter("g_InvResolution",Vector2(m_InvResolution[0],m_InvResolution[1]));

	}
	inline float sqr(float x)
	{
		return x * x;
	}

	void PlaygroundDemo::UpdateBlur()
	{
		RenderPass* d = gYume->pRenderer->GetDefaultPass();

		float radius     = m_BlurRadius;
		float sigma      = (radius+1) / 2;
		float inv_sigma2 = 1.0f / (2*sigma*sigma);

		d->SetShaderParameter("g_BlurFalloff",(float)inv_sigma2);
		d->SetShaderParameter("g_BlurRadius",(float)radius);

		d->SetShaderParameter("g_EdgeThreshold",m_EdgeThreshold);
	}

	void PlaygroundDemo::UpdateSharpness()
	{
		RenderPass* d = gYume->pRenderer->GetDefaultPass();

		float sharpness = sqr(m_Sharpness / m_AORadius);
		d->SetShaderParameter("g_Sharpness",sharpness);
	}

	void PlaygroundDemo::UpdateRadius()
	{
		float R = m_RadiusMultiplier * m_AORadius;
		gYume->pRenderer->GetDefaultPass()->SetShaderParameter("g_R",R);
		gYume->pRenderer->GetDefaultPass()->SetShaderParameter("g_inv_R",1.0f / R);
		gYume->pRenderer->GetDefaultPass()->SetShaderParameter("g_sqr_R",R * R);
	}

	void PlaygroundDemo::UpdateAngleBias()
	{
		float angle = m_AngleBias * M_PI/ 180;
		gYume->pRenderer->GetDefaultPass()->SetShaderParameter("g_AngleBias",angle);
		gYume->pRenderer->GetDefaultPass()->SetShaderParameter("g_TanAngleBias",tan(angle));
		UpdateContrast();
	}

	void PlaygroundDemo::UpdateContrast()
	{
		float contrast = m_Contrast / (1.0f - sin(m_AngleBias * M_PI / 180));
		gYume->pRenderer->GetDefaultPass()->SetShaderParameter("g_Contrast",contrast);
	}

	void PlaygroundDemo::UpdateSSAO()
	{
		Rng.seed((unsigned)0);

		gYume->pRenderer->GetDefaultPass()->SetShaderParameter("g_NumDir",(float)m_NumDirs);

		signed short f[64*64*4];
		for(int i=0; i<64*64*4; i+=4)
		{
			float angle = 2.0f*M_PI * Rng.randExc() / (float)m_NumDirs;
			f[i] = (signed short)(SCALE*cos(angle));
			f[i+1] = (signed short)(SCALE*sin(angle));
			f[i+2] = (signed short)(SCALE*Rng.randExc());
			f[i+3] = 0;
		}

		randomMap_->SetData(0,0,0,64,64,f);

	}

	void PlaygroundDemo::CreateCircleOfPointLights(DirectX::XMFLOAT3 origin,float numberOfLights,float rad)
	{
		float radius = rad;
		int numPoints = numberOfLights;
		for(int pointNum = 0; pointNum < numPoints; ++pointNum)
		{
			float i = (pointNum * 1.0f) / numPoints;
			float angle = i * M_PI * 2;
			float xPos =  sinf(angle)*radius + origin.x;
			float zPos =  cosf(angle)*radius + origin.z;

			float r = Random(360);
			float g = Random(360);
			float b = Random(360);
			CreateLight(DirectX::XMFLOAT3(xPos,5,zPos),YumeColor(r / 360.0f,g / 360.0f,b / 360.0f,0),30);
		}
	}

	void PlaygroundDemo::CreateLight(DirectX::XMFLOAT3 pos,YumeColor color,float range)
	{
		Light* pointLight = new Light;
		pointLight->SetName("PointLight");
		pointLight->SetType(LT_POINT);
		pointLight->SetPosition(DirectX::XMVectorSet(pos.x,pos.y,pos.z,0),true);
		pointLight->SetColor(color);
		pointLight->SetRange(range);

		lights_.push_back(pointLight);

		gYume->pRenderer->GetScene()->AddNode(pointLight);
	}

	void PlaygroundDemo::SSAOOffsetVectors()
	{

	}

	void PlaygroundDemo::CreateCube(Vector3 Pos,Quaternion Rot,Vector3 size,YumeColor color)
	{

	}

	void PlaygroundDemo::CreateCube(Vector3 Pos,Quaternion Rot,float size,YumeColor color)
	{

	}
	void PlaygroundDemo::CreateSphere(Vector3 Pos,Quaternion Rot,float size,YumeColor color)
	{

	}
	void PlaygroundDemo::CreateCylinder(Vector3 Pos,Quaternion Rot,float size,YumeColor color)
	{

	}
	void PlaygroundDemo::CreatePyramid(Vector3 Pos,Quaternion Rot,float size,YumeColor color)
	{

	}
	void PlaygroundDemo::CreateCone(Vector3 Pos,Quaternion Rot,float size,YumeColor color)
	{
	}
	void PlaygroundDemo::MoveCamera(float timeStep)
	{
	}

	void PlaygroundDemo::HandleUpdate(float timeStep)
	{

	}
	void PlaygroundDemo::HandleRenderUpdate(float timeStep)
	{
		//rotationAngle_ += M_PI * 0.9f * timeStep;

		//yume_->SetRotation(DirectX::XMVectorSet(0,rotationAngle_,0,1));
		//gYume->pRenderer->UpdateGI();
	}

	void PlaygroundDemo::Setup()
	{
		BaseApplication::Setup();
	}
}

ext: cc

max_stars_repo_name: rodrigobmg/YumeEngine

max_issues_repo_name: rodrigobmg/YumeEngine

max_forks_repo_name: rodrigobmg/YumeEngine


text:
#include <catch.hpp>

#define BOOST_LOG_DYN_LINK 1
#include <boost/log/trivial.hpp>

#include "../core_power.cpp"

TEST_CASE( "UNIT TEST: growth functions {growth_factor, growth_rate, growth_change}", "[core_power]" )
{
    BOOST_LOG_TRIVIAL(info) << "growth functions {growth_factor, growth_rate, growth_change}";

    int argc = 1;
    const char* const argv[1] = {"test"};
    Sim_Param sim(argc, argv);
    FTYPE_t D, D_to_a, f, Oma, OLa, dDda, factor;
    for (FTYPE_t a =0; a <= 1.0; a += 0.1)
    {
        D = growth_factor(a, sim.cosmo);
        f = growth_rate(a, sim.cosmo);
        dDda = growth_change(a, sim.cosmo);
        D_to_a = a ? D/a : dDda;
        CHECK( dDda == Approx(D_to_a*f) );
    }

    CHECK(0.0 == growth_factor(0, sim.cosmo));
    CHECK(1.0 == growth_factor(1, sim.cosmo));
}

ext: cpp

max_stars_repo_name: vrastil/Adhesion-Approximation

max_issues_repo_name: vrastil/Adhesion-Approximation

max_forks_repo_name: vrastil/Adhesion-Approximation


text:
#include <mesh_array.h>

#define BOOST_AUTO_TEST_MAIN
#include <boost/test/auto_unit_test.hpp>
#include <boost/test/unit_test_suite.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/test_tools.hpp>

BOOST_AUTO_TEST_SUITE(MESH_ARRAY);

BOOST_AUTO_TEST_CASE(tetrahedron_test)
{
  mesh_array::Tetrahedron T1;

  BOOST_CHECK_EQUAL(T1.idx(),  mesh_array::UNASSIGNED());
  BOOST_CHECK_EQUAL(T1.i(),    mesh_array::UNASSIGNED());
  BOOST_CHECK_EQUAL(T1.j(),    mesh_array::UNASSIGNED());
  BOOST_CHECK_EQUAL(T1.k(),    mesh_array::UNASSIGNED());
  BOOST_CHECK_EQUAL(T1.m(),    mesh_array::UNASSIGNED());

  mesh_array::Tetrahedron T2(4,5,6,7,1);

  BOOST_CHECK(T2.has_vertex(4));
  BOOST_CHECK(T2.has_vertex(5));
  BOOST_CHECK(T2.has_vertex(6));
  BOOST_CHECK(T2.has_vertex(7));
  BOOST_CHECK(!T2.has_vertex(10));

  BOOST_CHECK_EQUAL(T2.idx(),  1);
  BOOST_CHECK_EQUAL(T2.i(),    4);
  BOOST_CHECK_EQUAL(T2.j(),    5);
  BOOST_CHECK_EQUAL(T2.k(),    6);
  BOOST_CHECK_EQUAL(T2.m(),    7);

  BOOST_CHECK(!(T1 == T2));

  T1 = T2;

  BOOST_CHECK(T1 == T2);

  BOOST_CHECK_EQUAL(T1.idx(),  1);
  BOOST_CHECK_EQUAL(T1.i(),    4);
  BOOST_CHECK_EQUAL(T1.j(),    5);
  BOOST_CHECK_EQUAL(T1.k(),    6);
  BOOST_CHECK_EQUAL(T1.m(),    7);

  mesh_array::Tetrahedron T3(T1);

  BOOST_CHECK(T3 == T2);

  BOOST_CHECK_EQUAL(T3.idx(),  1);
  BOOST_CHECK_EQUAL(T3.i(),    4);
  BOOST_CHECK_EQUAL(T3.j(),    5);
  BOOST_CHECK_EQUAL(T3.k(),    6);
  BOOST_CHECK_EQUAL(T3.m(),    7);
  }

BOOST_AUTO_TEST_SUITE_END();

max_stars_repo_name: diku-dk/PROX

max_issues_repo_name: erleben/matchstick

max_forks_repo_name: erleben/matchstick


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

#include <boost/detail/atomic_count.hpp>
#include <graehl/shared/string_to.hpp>
#include <string>

namespace graehl {

// default-false bool
struct flag {
  bool v;
  void set(bool val) { v = val; }
  bool get() const { return v; }
  operator bool() const { return v; }
  operator bool&() { return v; }
  bool first() {
    bool r = !v;
    v = true;
    return r;
  }
  friend inline bool latch(flag& once) { return once.first(); }
  void finish() { v = true; }
  void clear() { v = false; }
  /** \return if first() has already returned true (peeks without modifying state) */
  bool already() const { return v; }
  flag() : v() {}
  flag(bool v) : v(v) {}
  flag(flag const& o) : v(o.v) {}
  flag& operator=(bool newv) {
    v = newv;
    return *this;
  }
  typedef void leaf_configure;
  typedef void assign_bool;  // TODO: debug in context of configure_program_options flag() and value_str-bad
  // any_cast (from bool, presumably)
  friend std::string to_string_impl(flag const& x) { return to_string(x.v); }
  friend void string_to_impl(std::string const& str, flag& x) { string_to(str, x.v); }
  friend std::string type_string(flag const&) { return "boolean"; }  // TODO: ADL
};

using boost::detail::atomic_count;
/**
   unlike flag or default_true, this is thread-safe with Size = atomic_count (for unsafe: use std::size_t)
*/
template <class Size = atomic_count>
struct counter {
  friend inline std::ostream& operator<<(std::ostream& out, counter const& self) {
    self.print(out);
    return out;
  }
  void print(std::ostream& out) const { out << v; }
  typedef Size size_type;
  size_type v;
  void set(std::size_t val) { v = size_type(val); }
  std::size_t get() const { return (std::size_t)v; }
  operator std::size_t() const { return (std::size_t)v; }
  operator size_type&() { return v; }
  bool first() { return ++v == 1; }
  counter() : v() {}
  counter(std::size_t v) : v(v) {}
  counter& operator=(std::size_t newv) {
    v = size_type(newv);
    return *this;
  }
  typedef void leaf_configure;
  friend std::string to_string_impl(counter const& x) { return to_string(x.v); }
  friend void string_to_impl(std::string const& str, counter& x) { string_to(str, x.v); }
  friend std::string type_string(counter const&) { return "count"; }  // TODO: ADL
};

struct default_true {
  bool v;
  void set(bool val) { v = val; }
  bool get() const { return v; }
  operator bool() const { return v; }
  operator bool&() { return v; }
  default_true() : v(true) {}
  default_true(bool v) : v(v) {}
  default_true(default_true const& o) : v(o.v) {}
  default_true& operator=(bool newv) {
    v = newv;
    return *this;
  }
  bool first() {
    bool r = v;
    v = false;
    return r;
  }
  typedef void leaf_configure;
  typedef void assign_bool;  // TODO: debug in context of configure_program_options default_true() and
  // value_str-bad any_cast (from bool, presumably)
  friend std::string to_string_impl(default_true const& x) { return to_string(x.v); }
  friend void string_to_impl(std::string const& str, default_true& x) { string_to(str, x.v); }
  friend std::string type_string(default_true const&) { return "boolean"; }  // TODO: ADL
};

}

#endif

max_stars_repo_name: graehl/carmel

max_issues_repo_name: graehl/carmel

max_forks_repo_name: graehl/carmel


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

#include <kernel/equip/coil_array.h>
#include <boost/format.hpp>

namespace ssl {
namespace equip {

CoilArray::CoilArray() {
  // TODO Auto-generated constructor stub

}
CoilArray::CoilArray(const char *coil_file) {
  load_via_xml(coil_file);
}

CoilArray::~CoilArray() {
  // TODO Auto-generated destructor stub
}
std::vector<Coil *> CoilArray::get_coil_pointer(CoilMode mode) const {
  std::vector<Coil *> coils;
  for (size_t i = 0; i < array_.size(); i++) {
    if (array_[i]->get_mode() == mode || array_[i]->get_mode() == kTxRx)
      coils.push_back(array_[i]);
  }
  return coils;
}
std::vector<size_t> CoilArray::get_coil_index(CoilMode mode) const {
  std::vector<size_t> index;
  for (size_t i = 0; i < array_.size(); i++) {
    if (array_[i]->get_mode() == mode || array_[i]->get_mode() == kTxRx)
      index.push_back(i);
  }
  return index;
}
std::vector<vec3> CoilArray::get_shape() const {
  std::vector<vec3> data;
  for (size_t i = 0; i < array_.size(); i++) {
    std::vector<vec3> tmp = array_[i]->get_shape();
    std::copy(tmp.begin(), tmp.end(), std::back_inserter(data));
  }
  return data;
}
void CoilArray::graphic_view() const {
  std::string file = "coils.xyza";
  std::ofstream ofstr(file.c_str(), std::ios::binary);
  ofstr.precision(3);
  ofstr.setf(std::ios::fixed);
  std::vector<vec3> data = get_shape();
  if (data.size() == 0)
    return;
  for (size_t i = 0; i < data.size(); i++) {
    vec3 pt = data[i];
    ofstr << pt(cx) << " " << pt(cy) << " " << pt(cz) << " " << 2 << "\n";
  }
  ofstr.close();
#ifdef SSL_ENABLE_VTK
  VTKRenderer vtk;
  vtk.view_xyza(file.c_str());
#endif
}
void CoilArray::load_via_xml(const char *coil_file) {
//  tinyxml2::XMLDocument doc;
//  tinyxml2::XMLError error = doc.LoadFile(coil_file);
//  if (error != tinyxml2::XML_NO_ERROR) {
//    std::cout
//        << boost::format("%s %s %s %s.\n") % "S-S-L error: " % error
//            % "failed to load coil file" % coil_file;
//    exit(0);
//  }
//
//  // print the seq xml tree.
////  XMLPrinter printer;
////  doc.Print(&printer);
////  std::cout << printer.CStr();
//
//  tinyxml2::XMLElement* root = doc.RootElement();
//  /*if (std_string(root->Name()) != "CoilArray") {
//	std::cout
//		<< boost::format("%1% %2% %3%.\n") % "S-S-L error: " % coil_file
//			% "should use CoilArray as root node";
//	exit(0);
//  }*/
//  tinyxml2::XMLElement* child;
//  for (child = root->FirstChildElement(); child != 0;
//      child = child->NextSiblingElement()) {
//    create_coil(child);
//  }
}
void CoilArray::create_coil(/*tinyxml2::XMLElement* node*/) {
  //Coil* coil = factory_coils_.clone_coil(node);
  //if (!coil)  // the input coil does not exist in the coil-factory.
  //{
  // /*std::cout
  //  << boost::format("%1% '%2%' %3%.\n")
  //	  % "S-S-L error: non-existent coil type -" % std_string(node->Name())
  //	  % "in coil array xml file";*/
  //  exit(0);
  //}
  //coil->associate_node(node);
  //coil->assign();
  //array_.push_back(coil);
}
}
/* namespace equip */
} /* namespace ssl */

max_stars_repo_name: spin-scenario/spin-scenario

max_issues_repo_name: spin-scenario/spin-scenario

max_forks_repo_name: spin-scenario/spin-scenario


text:
#include "dynet/expr.h"

#include <iostream>
#include <fstream>
#include <sstream>
#include <type_traits>
#include <random>

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

#include "s2s/dynet/dict.h"
#include "s2s/corpus/dict_set.hpp"

#ifndef INCLUDE_GUARD_S2S_DICTS_HPP
#define INCLUDE_GUARD_S2S_DICTS_HPP

namespace s2s {

class dicts {

public:

    dict_set_token dict_set_src;
    dict_set_label dict_set_trg;

    void set(const s2s_options &opts){
        // src
        /* resize vectors */
        dict_set_src.init(opts.enc_feature_vocab_size.size());
        /* construct dictionary */
        std::cerr << "Reading source language training text from " << opts.srcfile << "...\n";
        dict_set_src.freq_cut(opts, opts.srcfile, opts.enc_word_vocab_size, opts.enc_char_vocab_size, opts.enc_feature_vocab_size);
        // trg
        dict_set_trg.set_id(opts);
    }

    void load(const s2s_options &opts){
        // src
        dict_set_src.init(opts.enc_feature_vocab_size.size());
        std::string file_prefix = opts.rootdir + "/" + opts.dict_prefix + "src_";
        dict_set_src.load(opts, file_prefix);
        // trg
        dict_set_trg.set_id(opts);
    }

    void save(const s2s_options &opts){
        // src
        std::string file_prefix = opts.rootdir + "/" + opts.dict_prefix + "src_";
        dict_set_src.save(opts, file_prefix);
    }

};

};

#endif

max_stars_repo_name: kamigaito/SLAHAN

max_issues_repo_name: kamigaito/SLAHAN

max_forks_repo_name: kamigaito/SLAHAN


text:
// This file is part of the ROS PLUGIN for V-REP
//
// Copyright 2006-2015 Coppelia Robotics GmbH. All rights reserved.
// marc@coppeliarobotics.com
// www.coppeliarobotics.com
//
// A big thanks to Svetlin Penkov for his precious help!
//
// The ROS PLUGIN is licensed under the terms of GNU GPL:
//
// -------------------------------------------------------------------
// The ROS PLUGIN is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// THE ROS PLUGIN IS DISTRIBUTED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
// WARRANTY. THE USER WILL USE IT AT HIS/HER OWN RISK. THE ORIGINAL
// AUTHORS AND COPPELIA ROBOTICS GMBH WILL NOT BE LIABLE FOR DATA LOSS,
// DAMAGES, LOSS OF PROFITS OR ANY OTHER KIND OF LOSS WHILE USING OR
// MISUSING THIS SOFTWARE.
//
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with the ROS PLUGIN.  If not, see <http://www.gnu.org/licenses/>.
// -------------------------------------------------------------------
//
// This file was automatically created for V-REP release V3.2.3 rev4 on December 21st 2015

#include "../include/v_repLib.h"
#include "../include/luaFunctionData.h"
#include <boost/lexical_cast.hpp>
#include "../include/vrep_plugin/vrep_plugin.h"
#include "../include/vrep_plugin/ROS_server.h"

#include "ros/ros.h"
#include "std_msgs/Float32.h"

#include <iostream>
#include <opencv2/opencv.hpp>

#define PLUGIN_VERSION 4

#define CONCAT(x,y,z) x y z
#define strConCat(x,y,z)	CONCAT(x,y,z)

LIBRARY vrepLib; // the V-REP library that we will dynamically load and bind

// --------------------------------------------------------------------------------------
// simExtROS_enablePublisher
// --------------------------------------------------------------------------------------
#define LUA_ENABLEPUBLISHER_COMMAND "simExtROS_enablePublisher"

const int inArgs_ENABLEPUBLISHER[]={
	7,
    sim_lua_arg_string,0,
    sim_lua_arg_int,0,
    sim_lua_arg_int,0,
    sim_lua_arg_int,0,
    sim_lua_arg_int,0,
    sim_lua_arg_string,0,
    sim_lua_arg_int,0,
};

void LUA_ENABLEPUBLISHER_CALLBACK(SLuaCallBack* p)
{
	p->outputArgCount=0;
	CLuaFunctionData D;
	std::string effectiveTopicName;
	if (D.readDataFromLua(p,inArgs_ENABLEPUBLISHER,inArgs_ENABLEPUBLISHER[0]-1,LUA_ENABLEPUBLISHER_COMMAND)) // -1 because the last argument is optional
	{
		std::vector<CLuaFunctionDataItem>* inData=D.getInDataPtr();
		std::string topicName(inData->at(0).stringData[0]);
		if (topicName.length()>0)
		{
			int queueSize=inData->at(1).intData[0];
			int streamCmd=inData->at(2).intData[0];
			int auxInt1=inData->at(3).intData[0];
			int auxInt2=inData->at(4).intData[0];
			std::string auxString(inData->at(5).stringData[0]);
			int publishCnt=0; // 0 is the default value for this optional argument
			if (inData->size()>6)
				publishCnt=inData->at(6).intData[0];

			int errorModeSaved;
			simGetIntegerParameter(sim_intparam_error_report_mode,&errorModeSaved);
			simSetIntegerParameter(sim_intparam_error_report_mode,sim_api_errormessage_ignore);

			effectiveTopicName=ROS_server::addPublisher(topicName.c_str(),queueSize,streamCmd,auxInt1,auxInt2,auxString.c_str(),publishCnt);

			simSetIntegerParameter(sim_intparam_error_report_mode,errorModeSaved); // restore previous settings

			if (effectiveTopicName.length()==0)
				simSetLastError(LUA_ENABLEPUBLISHER_COMMAND, "Topic could not be published."); // output an error
		}
		else
			simSetLastError(LUA_ENABLEPUBLISHER_COMMAND, "Invalid topic name."); // output an error
	}
	if (effectiveTopicName.size()!=0)
		D.pushOutData(CLuaFunctionDataItem(effectiveTopicName));
	D.writeDataToLua(p);
}
// --------------------------------------------------------------------------------------

// --------------------------------------------------------------------------------------
// simExtROS_disablePublisher
// --------------------------------------------------------------------------------------
#define LUA_DISABLEPUBLISHER_COMMAND "simExtROS_disablePublisher"

const int inArgs_DISABLEPUBLISHER[]={
	1,
    sim_lua_arg_string,0,
};

void LUA_DISABLEPUBLISHER_CALLBACK(SLuaCallBack* p)
{
	p->outputArgCount=0;
	CLuaFunctionData D;
	int result=-1;
	if (D.readDataFromLua(p,inArgs_DISABLEPUBLISHER,inArgs_DISABLEPUBLISHER[0],LUA_DISABLEPUBLISHER_COMMAND))
	{
		std::vector<CLuaFunctionDataItem>* inData=D.getInDataPtr();
		std::string topicName(inData->at(0).stringData[0]);
		if (topicName.length()>0)
		{
			int errorModeSaved;
			simGetIntegerParameter(sim_intparam_error_report_mode,&errorModeSaved);
			simSetIntegerParameter(sim_intparam_error_report_mode,sim_api_errormessage_ignore);

			result=ROS_server::removePublisher(topicName.c_str(),false);

			simSetIntegerParameter(sim_intparam_error_report_mode,errorModeSaved); // restore previous settings

			if (result==-1)
				simSetLastError(LUA_DISABLEPUBLISHER_COMMAND, "Topic could not be unpublished."); // output an error
		}
		else
			simSetLastError(LUA_DISABLEPUBLISHER_COMMAND, "Invalid topic name."); // output an error
	}
	D.pushOutData(CLuaFunctionDataItem(result));
	D.writeDataToLua(p);
}
// --------------------------------------------------------------------------------------

// --------------------------------------------------------------------------------------
// simExtROS_wakePublisher
// --------------------------------------------------------------------------------------
#define LUA_WAKEPUBLISHER_COMMAND "simExtROS_wakePublisher"

const int inArgs_WAKEPUBLISHER[]={
	2,
    sim_lua_arg_string,0,
    sim_lua_arg_int,0,
};

void LUA_WAKEPUBLISHER_CALLBACK(SLuaCallBack* p)
{
	p->outputArgCount=0;
	CLuaFunctionData D;
	int result=-1;
	if (D.readDataFromLua(p,inArgs_WAKEPUBLISHER,inArgs_WAKEPUBLISHER[0],LUA_WAKEPUBLISHER_COMMAND))
	{
		std::vector<CLuaFunctionDataItem>* inData=D.getInDataPtr();
		std::string topicName(inData->at(0).stringData[0]);
		if (topicName.length()>0)
		{
			int publishCnt=inData->at(1).intData[0];

			int errorModeSaved;
			simGetIntegerParameter(sim_intparam_error_report_mode,&errorModeSaved);
			simSetIntegerParameter(sim_intparam_error_report_mode,sim_api_errormessage_ignore);

			result=ROS_server::wakePublisher(topicName.c_str(),publishCnt);

			simSetIntegerParameter(sim_intparam_error_report_mode,errorModeSaved); // restore previous settings

			if (result==-2)
				simSetLastError(LUA_WAKEPUBLISHER_COMMAND, "Topic could not be found."); // output an error
		}
		else
			simSetLastError(LUA_WAKEPUBLISHER_COMMAND, "Invalid topic name."); // output an error
	}
	D.pushOutData(CLuaFunctionDataItem(result));
	D.writeDataToLua(p);
}
// --------------------------------------------------------------------------------------

// --------------------------------------------------------------------------------------
// simExtROS_enableSubscriber
// --------------------------------------------------------------------------------------
#define LUA_ENABLESUBSCRIBER_COMMAND "simExtROS_enableSubscriber"

const int inArgs_ENABLESUBSCRIBER[]={
	8,
    sim_lua_arg_string,0,
    sim_lua_arg_int,0,
    sim_lua_arg_int,0,
    sim_lua_arg_int,0,
    sim_lua_arg_int,0,
    sim_lua_arg_string,0,
    sim_lua_arg_int,0,
    sim_lua_arg_int,0,
};

void LUA_ENABLESUBSCRIBER_CALLBACK(SLuaCallBack* p)
{
	p->outputArgCount=0;
	CLuaFunctionData D;
	int result=-1;
	if (D.readDataFromLua(p,inArgs_ENABLESUBSCRIBER,inArgs_ENABLESUBSCRIBER[0]-2,LUA_ENABLESUBSCRIBER_COMMAND)) // -2 because the last two args are optional
	{
		std::vector<CLuaFunctionDataItem>* inData=D.getInDataPtr();
		std::string topicName(inData->at(0).stringData[0]);
		if (topicName.length()>0)
		{
			int queueSize=inData->at(1).intData[0];
			int streamCmd=inData->at(2).intData[0];
			int auxInt1=inData->at(3).intData[0];
			int auxInt2=inData->at(4).intData[0];
			std::string auxString(inData->at(5).stringData[0]);
			int callbackTag_before=-1; // no callback (default)
			int callbackTag_after=-1; // no callback (default)
			if (inData->size()>6)
				callbackTag_before=inData->at(6).intData[0];
			if (inData->size()>7)
				callbackTag_after=inData->at(7).intData[0];

			int errorModeSaved;
			simGetIntegerParameter(sim_intparam_error_report_mode,&errorModeSaved);
			simSetIntegerParameter(sim_intparam_error_report_mode,sim_api_errormessage_ignore);

			result=ROS_server::addSubscriber(topicName.c_str(),queueSize,streamCmd,auxInt1,auxInt2,auxString.c_str(),callbackTag_before,callbackTag_after);

			simSetIntegerParameter(sim_intparam_error_report_mode,errorModeSaved); // restore previous settings

			if (result==-1)
				simSetLastError(LUA_ENABLESUBSCRIBER_COMMAND, "Topic could not be subscribed."); // output an error
		}
		else
			simSetLastError(LUA_ENABLESUBSCRIBER_COMMAND, "Invalid topic name."); // output an error
	}
	D.pushOutData(CLuaFunctionDataItem(result));
	D.writeDataToLua(p);
}
// --------------------------------------------------------------------------------------

// --------------------------------------------------------------------------------------
// simExtROS_disableSubscriber
// --------------------------------------------------------------------------------------
#define LUA_DISABLESUBSCRIBER_COMMAND "simExtROS_disableSubscriber"

const int inArgs_DISABLESUBSCRIBER[]={
	1,
    sim_lua_arg_int,0,
};

void LUA_DISABLESUBSCRIBER_CALLBACK(SLuaCallBack* p)
{
	p->outputArgCount=0;
	CLuaFunctionData D;
	bool result=false;
	if (D.readDataFromLua(p,inArgs_DISABLESUBSCRIBER,inArgs_DISABLESUBSCRIBER[0],LUA_DISABLESUBSCRIBER_COMMAND))
	{
		std::vector<CLuaFunctionDataItem>* inData=D.getInDataPtr();
		int errorModeSaved;
		simGetIntegerParameter(sim_intparam_error_report_mode,&errorModeSaved);
		simSetIntegerParameter(sim_intparam_error_report_mode,sim_api_errormessage_ignore);

		result=ROS_server::removeSubscriber(inData->at(0).intData[0]);

		simSetIntegerParameter(sim_intparam_error_report_mode,errorModeSaved); // restore previous settings

		if (!result)
			simSetLastError(LUA_DISABLESUBSCRIBER_COMMAND, "Topic could not be unsubscribed."); // output an error
	}
	D.pushOutData(CLuaFunctionDataItem(result));
	D.writeDataToLua(p);
}
// --------------------------------------------------------------------------------------

// This is the plugin start routine (called just once, just after the plugin was loaded):
VREP_DLLEXPORT unsigned char v_repStart(void* reservedPointer,int reservedInt)
{
	// Dynamically load and bind V-REP functions:
	// ******************************************
	// 1. Figure out this plugin's directory:
	char curDirAndFile[1024];
	getcwd(curDirAndFile, sizeof(curDirAndFile));

	std::string currentDirAndPath(curDirAndFile);
	// 2. Append the V-REP library's name:
	std::string temp(currentDirAndPath);
	#ifdef _WIN32
		temp+="\\v_rep.dll";
	#elif defined (__linux)
		temp+="/libv_rep.so";
	#elif defined (__APPLE__)
		temp+="/libv_rep.dylib";
	#endif

	// 3. Load the V-REP library:
	vrepLib=loadVrepLibrary(temp.c_str());
	if (vrepLib==NULL)
	{
		std::cout << "Error, could not find or correctly load the V-REP library. Cannot start 'ROS' plugin.\n";
		return(0); // Means error, V-REP will unload this plugin
	}
	if (getVrepProcAddresses(vrepLib)==0)
	{
		std::cout << "Error, could not find all required functions in the V-REP library. Cannot start 'ROS' plugin.\n";
		unloadVrepLibrary(vrepLib);
		return(0); // Means error, V-REP will unload this plugin
	}
	// ******************************************

	// Check the version of V-REP:
	// ******************************************
	int vrepVer;
	simGetIntegerParameter(sim_intparam_program_version,&vrepVer);
	if (vrepVer<20605) // if V-REP version is smaller than 2.06.04
	{
		std::cout << "Sorry, your V-REP copy is somewhat old. Cannot start 'ROS' plugin.\n";
		unloadVrepLibrary(vrepLib);
		return(0); // Means error, V-REP will unload this plugin
	}
	// ******************************************

	// Initialize the ROS part:
	if(!ROS_server::initialize())
	{
		std::cout << "ROS master is not running. Cannot start 'ROS' plugin.\n";
		return (0); //If the master is not running then the plugin is not loaded.
	}

	std::vector<int> inArgs;
	// Register the new Lua commands:
	CLuaFunctionData::getInputDataForFunctionRegistration(inArgs_ENABLEPUBLISHER,inArgs);
	simRegisterCustomLuaFunction(LUA_ENABLEPUBLISHER_COMMAND,strConCat("string topicName=",LUA_ENABLEPUBLISHER_COMMAND,"(string topicName,number queueSize,number rosStreamCmd,number auxInt1,number auxInt2,string auxString,number publishCnt=0)"),&inArgs[0],LUA_ENABLEPUBLISHER_CALLBACK);

	CLuaFunctionData::getInputDataForFunctionRegistration(inArgs_DISABLEPUBLISHER,inArgs);
	simRegisterCustomLuaFunction(LUA_DISABLEPUBLISHER_COMMAND,strConCat("number referenceCounter=",LUA_DISABLEPUBLISHER_COMMAND,"(string topicName)"),&inArgs[0],LUA_DISABLEPUBLISHER_CALLBACK);

	CLuaFunctionData::getInputDataForFunctionRegistration(inArgs_WAKEPUBLISHER,inArgs);
	simRegisterCustomLuaFunction(LUA_WAKEPUBLISHER_COMMAND,strConCat("number result=",LUA_WAKEPUBLISHER_COMMAND,"(string topicName,number publishCnt)"),&inArgs[0],LUA_WAKEPUBLISHER_CALLBACK);

	CLuaFunctionData::getInputDataForFunctionRegistration(inArgs_ENABLESUBSCRIBER,inArgs);
	simRegisterCustomLuaFunction(LUA_ENABLESUBSCRIBER_COMMAND,strConCat("number subscriberId=",LUA_ENABLESUBSCRIBER_COMMAND,"(string topicName,number queueSize,number rosStreamCmd,number auxInt1,number auxInt2,string auxString,number callbackTag_before=-1,number callbackTag_after=-1)"),&inArgs[0],LUA_ENABLESUBSCRIBER_CALLBACK);

	CLuaFunctionData::getInputDataForFunctionRegistration(inArgs_DISABLESUBSCRIBER,inArgs);
	simRegisterCustomLuaFunction(LUA_DISABLESUBSCRIBER_COMMAND,strConCat("boolean result=",LUA_DISABLESUBSCRIBER_COMMAND,"(number subscriberID)"),&inArgs[0],LUA_DISABLESUBSCRIBER_CALLBACK);

	// Publisher constants:
	simRegisterCustomLuaVariable("simros_strmcmd_get_laser_scanner_data",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_laser_scanner_data))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_get_odom_data",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_odom_data))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_get_object_selection",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_object_selection))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_get_array_parameter",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_array_parameter))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_get_boolean_parameter",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_boolean_parameter))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_get_dialog_result",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_dialog_result))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_get_floating_parameter",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_floating_parameter))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_get_integer_parameter",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_integer_parameter))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_get_joint_state",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_joint_state))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_get_object_pose",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_object_pose))).c_str());
//	simRegisterCustomLuaVariable("simros_strmcmd_get_object_quaternion",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_object_quaternion))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_get_object_parent",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_object_parent))).c_str());
//	simRegisterCustomLuaVariable("simros_strmcmd_get_object_position",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_object_position))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_get_objects",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_objects))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_get_string_parameter",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_string_parameter))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_get_ui_event_button",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_ui_event_button))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_get_vision_sensor_depth_buffer",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_vision_sensor_depth_buffer))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_get_vision_sensor_image",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_vision_sensor_image))).c_str());
//	simRegisterCustomLuaVariable("simros_strmcmd_get_joint_force",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_joint_force))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_read_collision",(boost::lexical_cast<std::string>(int(simros_strmcmd_read_collision))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_read_distance",(boost::lexical_cast<std::string>(int(simros_strmcmd_read_distance))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_read_force_sensor",(boost::lexical_cast<std::string>(int(simros_strmcmd_read_force_sensor))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_read_proximity_sensor",(boost::lexical_cast<std::string>(int(simros_strmcmd_read_proximity_sensor))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_read_vision_sensor",(boost::lexical_cast<std::string>(int(simros_strmcmd_read_vision_sensor))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_get_object_float_parameter",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_object_float_parameter))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_get_object_int_parameter",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_object_int_parameter))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_get_ui_button_property",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_ui_button_property))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_get_ui_slider",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_ui_slider))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_get_float_signal",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_float_signal))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_get_integer_signal",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_integer_signal))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_get_string_signal",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_string_signal))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_get_and_clear_string_signal",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_and_clear_string_signal))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_get_transform",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_transform))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_get_range_finder_data",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_range_finder_data))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_get_depth_sensor_data",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_depth_sensor_data))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_get_vision_sensor_info",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_vision_sensor_info))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_get_twist_status",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_twist_status))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_get_object_group_data",(boost::lexical_cast<std::string>(int(simros_strmcmd_get_object_group_data))).c_str());

	// Subscriber constants:
	simRegisterCustomLuaVariable("simros_strmcmd_add_status_bar_message",(boost::lexical_cast<std::string>(int(simros_strmcmd_add_status_bar_message))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_set_object_selection",(boost::lexical_cast<std::string>(int(simros_strmcmd_set_object_selection))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_auxiliary_console_print",(boost::lexical_cast<std::string>(int(simros_strmcmd_auxiliary_console_print))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_set_array_parameter",(boost::lexical_cast<std::string>(int(simros_strmcmd_set_array_parameter))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_set_boolean_parameter",(boost::lexical_cast<std::string>(int(simros_strmcmd_set_boolean_parameter))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_set_floating_parameter",(boost::lexical_cast<std::string>(int(simros_strmcmd_set_floating_parameter))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_set_integer_parameter",(boost::lexical_cast<std::string>(int(simros_strmcmd_set_integer_parameter))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_set_joint_force",(boost::lexical_cast<std::string>(int(simros_strmcmd_set_joint_force))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_set_joint_position",(boost::lexical_cast<std::string>(int(simros_strmcmd_set_joint_position))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_set_joint_target_position",(boost::lexical_cast<std::string>(int(simros_strmcmd_set_joint_target_position))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_set_joint_target_velocity",(boost::lexical_cast<std::string>(int(simros_strmcmd_set_joint_target_velocity))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_set_vision_sensor_image",(boost::lexical_cast<std::string>(int(simros_strmcmd_set_vision_sensor_image))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_set_object_float_parameter",(boost::lexical_cast<std::string>(int(simros_strmcmd_set_object_float_parameter))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_set_object_int_parameter",(boost::lexical_cast<std::string>(int(simros_strmcmd_set_object_int_parameter))).c_str());
//	simRegisterCustomLuaVariable("simros_strmcmd_set_object_orientation",(boost::lexical_cast<std::string>(int(simros_strmcmd_set_object_orientation))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_set_object_position",(boost::lexical_cast<std::string>(int(simros_strmcmd_set_object_position))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_set_object_pose",(boost::lexical_cast<std::string>(int(simros_strmcmd_set_object_pose))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_set_joint_state",(boost::lexical_cast<std::string>(int(simros_strmcmd_set_joint_state))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_set_object_quaternion",(boost::lexical_cast<std::string>(int(simros_strmcmd_set_object_quaternion))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_set_ui_button_label",(boost::lexical_cast<std::string>(int(simros_strmcmd_set_ui_button_label))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_set_ui_button_property",(boost::lexical_cast<std::string>(int(simros_strmcmd_set_ui_button_property))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_set_ui_slider",(boost::lexical_cast<std::string>(int(simros_strmcmd_set_ui_slider))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_clear_float_signal",(boost::lexical_cast<std::string>(int(simros_strmcmd_clear_float_signal))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_clear_integer_signal",(boost::lexical_cast<std::string>(int(simros_strmcmd_clear_integer_signal))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_clear_string_signal",(boost::lexical_cast<std::string>(int(simros_strmcmd_clear_string_signal))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_set_float_signal",(boost::lexical_cast<std::string>(int(simros_strmcmd_set_float_signal))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_set_integer_signal",(boost::lexical_cast<std::string>(int(simros_strmcmd_set_integer_signal))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_set_string_signal",(boost::lexical_cast<std::string>(int(simros_strmcmd_set_string_signal))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_append_string_signal",(boost::lexical_cast<std::string>(int(simros_strmcmd_append_string_signal))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_set_twist_command",(boost::lexical_cast<std::string>(int(simros_strmcmd_set_twist_command))).c_str());
	simRegisterCustomLuaVariable("simros_strmcmd_set_joy_sensor",(boost::lexical_cast<std::string>(int(simros_strmcmd_set_joy_sensor))).c_str());
//	simRegisterCustomLuaVariable("simros_strmcmd_set_joint_trajectory",(boost::lexical_cast<std::string>(int(simros_strmcmd_set_joint_trajectory))).c_str());

	return(PLUGIN_VERSION); // initialization went fine, we return the version number of this plugin (can be queried with simGetModuleName)
}

// This is the plugin end routine (called just once, when V-REP is ending, i.e. releasing this plugin):
VREP_DLLEXPORT void v_repEnd()
{
	ROS_server::shutDown();	// shutdown the ROS_server
	unloadVrepLibrary(vrepLib); // release the library
}

// This is the plugin messaging routine (i.e. V-REP calls this function very often, with various messages):
VREP_DLLEXPORT void* v_repMessage(int message,int* auxiliaryData,void* customData,int* replyData)
{
	// This is called quite often. Just watch out for messages/events you want to handle
	// Keep following 4 lines at the beginning and unchanged:
	int errorModeSaved;
	simGetIntegerParameter(sim_intparam_error_report_mode,&errorModeSaved);
	simSetIntegerParameter(sim_intparam_error_report_mode,sim_api_errormessage_ignore);
	void* retVal=NULL;

	// Here we can intercept many messages from V-REP (actually callbacks). Only the most important messages are listed here:

	if (message==sim_message_eventcallback_instancepass)
	{
		// This message is sent each time the scene was rendered (well, shortly after) (very often)
		// When a simulation is not running, but you still need to execute some commands, then put some code here
		ROS_server::instancePass();
	}

	if (message==sim_message_eventcallback_mainscriptabouttobecalled)
	{
		// Main script is about to be run (only called while a simulation is running (and not paused!))
		//
		// This is a good location to execute simulation commands

		if (ROS_server::mainScriptAboutToBeCalled())
		{
			simSetBooleanParameter(sim_boolparam_waiting_for_trigger,1); // the remote API client can query that value
			replyData[0]=0; // this tells V-REP that we don't wanna execute the main script
		}
		else
			simSetBooleanParameter(sim_boolparam_waiting_for_trigger,0); // the remote API client can query that value
	}

	if (message==sim_message_eventcallback_simulationabouttostart)
	{
	    // Simulation is about to start

		ROS_server::simulationAboutToStart();
	}

	if (message==sim_message_eventcallback_simulationended)
	{
		// Simulation just ended
		simSetBooleanParameter(sim_boolparam_waiting_for_trigger,0); // the remote API client can query that value
		ROS_server::simulationEnded();
	}

	// Keep following unchanged:
	simSetIntegerParameter(sim_intparam_error_report_mode,errorModeSaved); // restore previous settings
	return(retVal);
}


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

#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/ref.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/random.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

#include <iostream>
#include <fstream>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <cstdlib>

#include <ir/index_manager/utility/Bitset.h>
#include <ir/index_manager/store/FSDirectory.h>
#include <util/ClockTimer.h>

using namespace std;
using namespace boost;
using namespace izenelib::ir::indexmanager;

/**
 * check Bitset functions.
 * @param count bits size to test
 * @param isCheckEachBit whether check each bit in the loop,
 * when @p count is large, it would better to be false to avoid consuming lots of test time.
 */
void checkBitset(size_t count, bool isCheckEachBit = true)
{
    BOOST_TEST_MESSAGE("checkBitset, count: " << count);

    Bitset bitset(count);
    BOOST_CHECK_EQUAL(bitset.size(), count);
    for(size_t i = 0; i < count && isCheckEachBit; ++i)
        bitset.set(i);
    for(size_t i = 0; i < count && isCheckEachBit; ++i)
        BOOST_CHECK(bitset.test(i));
    BOOST_CHECK(!bitset.test(count));
    BOOST_CHECK(!bitset.test(2 * count + 1));

    for(size_t i = 0; i < count && isCheckEachBit; ++i)
        bitset.reset(i);
    for(size_t i = 0; i < count && isCheckEachBit; ++i)
        BOOST_CHECK(!bitset.test(i));

    bitset.set();
    bitset.flip();
    for(size_t i = 0; i < count && isCheckEachBit; ++i)
        BOOST_CHECK(!bitset.test(i));
    BOOST_CHECK(!bitset.any());

    bitset.flip();
    for(size_t i = 0; i < count && isCheckEachBit; ++i)
        BOOST_CHECK(bitset.test(i));

    bitset.set();
    Bitset bitvector2(count);
    bitvector2 |= bitset;
    for(size_t i = 0; i < count && isCheckEachBit; ++i)
        BOOST_CHECK(bitvector2.test(i));

    bitvector2 &= bitset;
    for(size_t i = 0; i < count && isCheckEachBit; ++i)
        BOOST_CHECK(bitvector2.test(i));

    bitvector2 ^= bitset;
    for(size_t i = 0; i < count && isCheckEachBit; ++i)
        BOOST_CHECK(!bitvector2.test(i));

    // output & intput
    bitset.set();
    const char* dirStr = "bitset";
    ostringstream ost;
    ost << count << ".bits";
    string fileName = ost.str();
    Directory* pDirectory = new FSDirectory(dirStr, true);
    bitset.write(pDirectory, fileName.c_str());

    Bitset bitvector3;
    bitvector3.read(pDirectory, fileName.c_str());
    delete pDirectory;
    BOOST_CHECK_EQUAL(bitset.size(), count);
    for(size_t i = 0; i < count && isCheckEachBit; ++i)
        BOOST_CHECK_EQUAL(bitvector3.test(i), bitset.test(i));
    BOOST_CHECK(!bitvector3.test(count));
    BOOST_CHECK(!bitvector3.test(2 * count + 1));

    // at middle
    bitset.reset();
    BOOST_CHECK(!bitset.any(0, count));
    BOOST_CHECK(!bitset.any(0, count * 2 + 2));
    BOOST_CHECK(!bitset.any(count, count * 2 + 2));
    size_t mid = count / 2;
    bitset.set(mid);
    BOOST_CHECK(bitset.any());
    BOOST_CHECK(bitset.any(0, count + 1));
    BOOST_CHECK(bitset.any(0, mid + 1));
    BOOST_CHECK(bitset.any(mid, mid + 1));
    BOOST_CHECK(bitset.any(0, count * 2 + 2));
    std::swap(bitset, bitvector2);
    std::swap(bitset, bitvector2);
    if(mid > 0)
    {
        BOOST_CHECK(!bitset.any(0, mid - 1));
        BOOST_CHECK(bitset.any(0, count));
        BOOST_CHECK(!bitset.any(0, mid));
        BOOST_CHECK(bitset.any(mid, count));
        BOOST_CHECK(bitset.any(mid - 1, mid + 2));
        if(mid + 1 <= count - 1)
            BOOST_CHECK(!bitset.any(mid + 1, count));
        BOOST_CHECK(!bitset.any(count, count * 2 + 2));
    }

    // at boundary
    bitset.reset(count);
    bitset.set();
    BOOST_CHECK_EQUAL(bitset.size(), count + 1);
    bitset.set(count + 4);
    BOOST_CHECK_EQUAL(bitset.size(), count + 5);
    BOOST_CHECK(bitset.test(count));
    BOOST_CHECK(!bitset.test(count + 1));
    BOOST_CHECK(!bitset.test(count + 2));
    BOOST_CHECK(!bitset.test(count + 3));
    BOOST_CHECK(bitset.test(count + 4));
    BOOST_CHECK(!bitset.test(count + 5));
    BOOST_CHECK(!bitset.test(count + 6));
    BOOST_CHECK(!bitset.test(count + 7));
}

void testIterate(std::size_t maxBitNum, std::size_t setBitNum)
{
    Bitset bitset(maxBitNum);
    std::set<size_t> goldSet;

    // init
    for (std::size_t i = 0; i < setBitNum; ++i)
    {
        int k = std::rand() % maxBitNum;
        bitset.set(k);
        goldSet.insert(k);
    }

    // forward iterate
    size_t pos = bitset.find_first();
    for (std::set<size_t>::const_iterator it = goldSet.begin();
         it != goldSet.end(); ++it)
    {
        BOOST_CHECK_EQUAL(pos, *it);
        pos = bitset.find_next(pos);
    }
    BOOST_CHECK_EQUAL(pos, -1);

    // backward iterate
    pos = bitset.find_last();
    for (std::set<size_t>::const_reverse_iterator it = goldSet.rbegin();
         it != goldSet.rend(); ++it)
    {
        BOOST_CHECK_EQUAL(pos, *it);
        pos = bitset.find_prev(pos);
    }
    BOOST_CHECK_EQUAL(pos, -1);
}

void setBitset(Bitset& bitset, std::size_t setBitNum)
{
    std::size_t bitNum = bitset.size();
    for (std::size_t i = 0; i < setBitNum; ++i)
    {
        int k = std::rand() % bitNum;
        bitset.set(k);
    }
}

void testLogicalNotAnd(std::size_t bitNum)
{
    Bitset bitVector1(bitNum);
    Bitset bitVector2(bitNum);

    const std::size_t setBitNum = bitNum / 2;
    setBitset(bitVector1, setBitNum);
    setBitset(bitVector2, setBitNum);

    Bitset gold(bitNum);
    for (std::size_t i = 0; i < bitNum; ++i)
    {
        if (bitVector1.test(i) && bitVector2.test(i) == false)
        {
            gold.set(i);
        }
    }

    bitVector1 -= bitVector2;

    BOOST_CHECK_EQUAL(bitVector1, gold);
}

void runLogicalNotAnd(std::size_t bitNum, std::size_t runNum)
{
    const std::size_t setBitNum = bitNum / 2;

    Bitset bitVector1(bitNum);
    Bitset bitVector2(bitNum);

    setBitset(bitVector1, setBitNum);
    setBitset(bitVector2, setBitNum);

    izenelib::util::ClockTimer timer;

    for (std::size_t i = 0; i < runNum; ++i)
    {
        bitVector1 -= bitVector2;
    }

    BOOST_TEST_MESSAGE("it costs " << timer.elapsed() << " seconds in running "
                       "Bitset::operator-=() of " << runNum << " times "
                       "on " << bitNum << " bits");
}

void runToggle(std::size_t bitNum, std::size_t runNum)
{
    Bitset bitset(bitNum);
    const std::size_t setBitNum = bitNum / 2;
    setBitset(bitset, setBitNum);

    izenelib::util::ClockTimer timer;

    for (std::size_t i = 0; i < runNum; ++i)
    {
        bitset.flip();
    }

    BOOST_TEST_MESSAGE("it costs " << timer.elapsed() << " seconds in running "
                       "Bitset::flip() of " << runNum << " times "
                       "on " << bitNum << " bits");
}

BOOST_AUTO_TEST_SUITE(t_bitvector)

BOOST_AUTO_TEST_CASE(bitset)
{
    for(size_t i=0; i<70; ++i)
        checkBitset(i);

    checkBitset(100, false);
    checkBitset(1000, false);
    checkBitset(100000, false);
    checkBitset(10000000, false); // 10M
    checkBitset(134217728, false); // 128M
    checkBitset(1073741825, false); // 1G + 1
}

BOOST_AUTO_TEST_CASE(iterate)
{
    testIterate(10, 0);
    testIterate(10, 10);
    testIterate(100, 10);
    testIterate(1000, 10);
    testIterate(1000, 500);
    testIterate(10000, 1000);
}

BOOST_AUTO_TEST_CASE(logicalNotAnd)
{
    const std::size_t maxBitNum = 100;

    for (std::size_t i = 0; i <= maxBitNum; ++i)
    {
        testLogicalNotAnd(i);
    }
}

BOOST_AUTO_TEST_CASE(benchLogicalNotAnd)
{
    const std::size_t bitNum = 1e7;
    const std::size_t runNum = 1e4;

    runLogicalNotAnd(bitNum, runNum);
}

BOOST_AUTO_TEST_CASE(benchToggle)
{
    const std::size_t bitNum = 1e7;
    const std::size_t runNum = 1e4;

    runToggle(bitNum, runNum);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: izenecloud/izenelib

max_issues_repo_name: izenecloud/izenelib

max_forks_repo_name: izenecloud/izenelib


text:
//////////////////////////////////////////////////////////////////////////////
//  Boost.Assign v2                                                         //
//                                                                          //
//  Copyright (C) 2003-2004 Thorsten Ottosen                                //
//  Copyright (C) 2011 Erwann Rogard                                        //
//  Use, modification and distribution are subject to the                   //
//  Boost Software License, Version 1.0. (See accompanying file             //
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)        //
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_ASSIGN_V2_SUPPORT_TRAITS_AUX_VALUE_CONTAINER_ER_2011_HPP
#define BOOST_ASSIGN_V2_SUPPORT_TRAITS_AUX_VALUE_CONTAINER_ER_2011_HPP
#include <boost/assign/v2/support/traits/aux_/fwd_container.hpp>
#include <boost/config.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/multi_array/base.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/seq.hpp>
#include <boost/type_traits/add_const.hpp>
#include <boost/type_traits/is_base_of.hpp>
#include <boost/type_traits/detail/yes_no_type.hpp>

namespace boost{
namespace assign{
namespace v2{
namespace container_aux{

// CATEGORIES

    template<typename C>
    struct value_is_fifo : ::boost::mpl::false_{};

    template<typename V>
    struct value_is_lifo : ::boost::mpl::false_{};

    template<typename C>
    struct value_is_associative : ::boost::mpl::false_{};

    template<typename C>
    struct value_is_sorted : ::boost::mpl::false_{};

    template<typename C>
    struct value_is_array : ::boost::mpl::false_{};

    template<typename C>
    struct value_is_map : ::boost::mpl::false_{};

    typedef ::boost::detail::multi_array::multi_array_base multi_array_base_;

    template<typename C>
    struct value_is_multi_array
        : boost::is_base_of<multi_array_base_, C>
    {};

}// container_aux

#define BOOST_ASSIGN_V2_TRAITS_CONTAINER_CATEGORY(SeqPar, IsCategory, Identifier, SeqArg)\
namespace container_aux{\
    template<BOOST_PP_SEQ_ENUM(SeqPar)>\
    struct BOOST_PP_CAT(value_,IsCategory) <\
        Identifier<BOOST_PP_SEQ_ENUM(SeqArg)> \
    > : ::boost::mpl::true_{};\
}\
/**/
#define BOOST_ASSIGN_V2_TRAITS_CONTAINER_CATEGORIES_HELPER(r, data, elem)\
    BOOST_ASSIGN_V2_TRAITS_CONTAINER_CATEGORY(\
        BOOST_PP_SEQ_ELEM(0, data),\
        elem,\
        BOOST_PP_SEQ_ELEM(1, data),\
        BOOST_PP_SEQ_ELEM(2, data)\
    )
/**/
#define BOOST_ASSIGN_V2_TRAITS_CONTAINER_CATEGORIES(SeqPar, SeqIsCategory, Identifier, SeqArg)\
    BOOST_PP_SEQ_FOR_EACH(\
        BOOST_ASSIGN_V2_TRAITS_CONTAINER_CATEGORIES_HELPER,\
        (SeqPar)(Identifier)(SeqArg),\
        SeqIsCategory\
    )\
/**/

BOOST_ASSIGN_V2_TRAITS_CONTAINER_CATEGORIES(
    (typename T)( std::size_t sz ), (is_array),
    boost::array, (T)(sz)
)
BOOST_ASSIGN_V2_TRAITS_CONTAINER_CATEGORIES(
    (typename K)(typename T)(typename C)(typename A),
    (is_associative)(is_map)(is_sorted),
    std::map, (K)(T)(C)(A)
)
BOOST_ASSIGN_V2_TRAITS_CONTAINER_CATEGORIES(
    (typename T)(typename A), (is_fifo),
    std::queue, (T)(A)
)
BOOST_ASSIGN_V2_TRAITS_CONTAINER_CATEGORIES(
    (typename T)(typename C)(typename A), (is_sorted)(is_associative),
    std::set, (T)(C)(A)
)
BOOST_ASSIGN_V2_TRAITS_CONTAINER_CATEGORIES(
    (typename T)(typename A), (is_lifo),
    std::stack, (T)(A)
)
BOOST_ASSIGN_V2_TRAITS_CONTAINER_CATEGORIES(
    (typename K)(typename M)(typename H)(typename P)(typename A),
    (is_associative)(is_map),
    boost::unordered_map, (K)(M)(H)(P)(A)
)
BOOST_ASSIGN_V2_TRAITS_CONTAINER_CATEGORIES(
    (typename K)(typename H)(typename P)(typename A), (is_associative),
    boost::unordered_set, (K)(H)(P)(A)
)

namespace container_aux{

// DATA-MEMBER

    template<
        typename C    // Ptr or value container
    >
    struct value_key{ typedef typename C::key_type type; };

    template<
        typename C    // Ptr or value multi-array
    >
    struct value_element{ typedef typename C::element type; };

    template<
        typename C    // Ptr or value container
    >
    struct value_value{ typedef typename C::value_type type; };

    template<
        typename C    // Ptr or value container
    >
    struct value_mapped{
        typedef typename C::mapped_type type;
    };

// HAS_VALUE

    template<typename T>
    struct value_has_value_type{

        typedef typename boost::type_traits::yes_type yes_;
        typedef typename boost::type_traits::no_type no_;

        template<typename U>
        static yes_ test(U*, typename U::value_type* p = 0);
        static no_ test(...);

        BOOST_STATIC_CONSTANT(
            bool,
            value = sizeof( test((T*)0) ) == sizeof( yes_ )
        );
        typedef ::boost::mpl::bool_<value> type;
    };

// HAS_PUSH

    template<typename C, typename T = typename C::value_type>
    struct value_has_push{

        typedef typename boost::type_traits::yes_type yes_;
        typedef typename boost::type_traits::no_type no_;

        template<typename U,void (U::*fp)(T const&)>
        struct helper{
            // See http://lists.boost.org/Archives/boost/2002/03/27233.php
        };

        template<typename U>
        static yes_ test(U*, helper<U, &U::push>* p = 0);
        static no_ test(...);

        BOOST_STATIC_CONSTANT(
            bool,
            value = sizeof( test((C*)0) ) == sizeof( yes_ )
        );

        typedef ::boost::mpl::bool_<value> type;

    };

    template<typename C>
    struct value_has_push_deduced_value : value_has_push<C>{};

}// container_aux
}// v2
}// assign
}// boost

#endif // BOOST_ASSIGN_V2_SUPPORT_TRAITS_AUX_VALUE_CONTAINER_ER_2011_HPP


text:
/*! \file demo_2d_bars.cpp
    \brief Demonstrate the bars (& columns or sticks).
    \details
    \date 11 Feb 2009
    \author Paul A. Bristow
*/

// Copyright Paul A. Bristow 2008

// Distributed under the Boost Software License, Version 1.0.
// For more information, see http://www.boost.org

#include <boost/svg_plot/svg_2d_plot.hpp>
#include <map>

using std::map;
using namespace boost::svg;

int main()
{
  map<double, double> map1; // Two sample data series.
  map<double, double> map2;

  // This is random data used purely for example purposes.
  map1[1.] = 3.2; // map[x] = y
  map1[2.] = 5.4;
  map1[7.3] = 9.1;
  map1[8.] = 7.3;
  map1[5.5] = 5.4;
  map1[9.3] = 9.9;

  map2[-3.1] = -6.1;
  map2[5.4] = 4.7;

  svg_2d_plot my_plot1;

  my_plot1.title("X Times")
         .legend_on(true)
         .x_range(-1, 11)
         .background_border_color(black);

  my_plot1.plot(map1, "Series 1").fill_color(blue).shape(none).line_on(false).bar_opt(x_stick).bar_width(5).bar_color(red);
  my_plot1.write("./demo_2d_bar_x_stick.svg");
  my_plot1.plot(map1, "Series 1").shape(none).line_on(false).bar_opt(x_block).bar_width(10);
  my_plot1.write("./demo_2d_bar_x_block.svg");

  svg_2d_plot my_plot2;

  my_plot2.title("Y Times")
         .legend_on(true)
         .x_range(-10, 10)
         .background_border_color(blue);

  my_plot2.plot(map2, "Series 2").fill_color(green).shape(none).line_on(false).bar_opt(y_stick).bar_width(5).bar_color(cyan);
  my_plot2.write("./demo_2d_bar_y_stick.svg");
  my_plot2.plot(map2, "Series 2").shape(none).line_on(false).bar_opt(y_block).bar_width(10).bar_color(green).bar_area_fill(magenta);
  my_plot2.write("./demo_2d_bar_y_block.svg");

  return 0;
} // int main()

/* Output:

demo_2d_bars.cpp
Linking...
Embedding manifest...
Autorun "j:\Cpp\SVG\debug\demo_2d_bars.exe"

*/


text:
/**
 * Copyright (C) 2015 Dato, Inc.
 * All rights reserved.
 *
 * This software may be modified and distributed under the terms
 * of the BSD license. See the LICENSE file for details.
 */
#ifndef FAULT_SOCKETS_ASYNC_REPLY_SOCKET_HPP
#define FAULT_SOCKETS_ASYNC_REPLY_SOCKET_HPP
#include <string>
#include <vector>
#include <set>
#include <queue>
#include <zmq.h>
#include <boost/function.hpp>
#include <boost/thread/condition_variable.hpp>
#include <boost/thread/mutex.hpp>
#include <fault/zmq/zmq_msg_vector.hpp>
#include <fault/sockets/socket_receive_pollset.hpp>
#include <export.hpp>
namespace graphlab {
namespace zookeeper_util {
class key_value;
}
}

namespace libfault {
/**
 * \ingroup fault
 * Constructs a zookeeper backed asynchronous reply socket.
 * Will automatically retry sockets.
 *
 * This object works together with the socket_receive_pollset().
 * The general construction is to
 *  - Create a async_reply_socket
 *  - Create a socket_receive_pollset
 *  - Register the keys this socket should listen on (register_key() )
 *  - register this reply_socket with the pollset
 *    (add_to_pollset())
 *  - start the pollset ( socket_receive_pollset::start_poll_thread() )
 *
 * \note
 * The first part of the message must be a key. This must be a key the
 * current client is registered for.
 */
class EXPORT async_reply_socket {
 public:

  /**
   * Returns true if there are contents to reply.
   * Returns false otherwise.
   * If the reply socket is connected to a request socket,
   * this must always return true.
   * \note There is no provided way to figure out if a reply is necessary.
   * This must be managed on a higher protocol layer.
   */
   typedef boost::function<bool (zmq_msg_vector& recv,
                                zmq_msg_vector& reply)> callback_type;

  /**
   * Constructs a reply socket.
   * \param zmq_ctx A zeroMQ Context
   * \param keyval A zookeeper key_value object to bind to
   * \param callback The function used to process replies. Multiple
   *                 threads may call the callback simultaneously
   * \param nthreads The maximum number of threads to use
   * \param alternate_bind_address If set, this will be address to bind to.
   *                               Otherwise, binds to a free tcp address.
   *
   * keyval can be NULL, in which case, the alternate_bind_address must be
   * provided, in which case this socket behaves like a simple
   * messaging wrapper around ZeroMQ which provides asynchronous messaging
   * capabilities.
   */
  async_reply_socket(void* zmq_ctx,
                     graphlab::zookeeper_util::key_value* keyval,
                     callback_type callback,
                     size_t nthreads = 4,
                     std::string alternate_bind_address = "",
                     std::string secret_key = "");

  /**
   * Closes the socket. Once closed. It cannot be opened again
   */
  void close();

  /**
   * Tries to register this socket under a given object key.
   * Returns true on success and false on failure.
   */
  bool register_key(std::string key);

  /**
   * Like register, but sets the key to an empty value.
   * Reserves ownership of the key, but prohibits people from joining
   */
  bool reserve_key(std::string key);

  /**
   * Tries to unregister this socket from a given object key.
   * Returns true on success and false on failure
   */
  bool unregister_key(std::string key);

  /**
   * Unregisters all keys this socket was registered under
   */
  void unregister_all_keys();

  /**
   * Registers this socket with the pollset
   * This socket should only registered with one pollset.
   */
  void add_to_pollset(socket_receive_pollset* pollset);

  /**
   * Unregisters this socket with the pollset
   */
  void remove_from_pollset();

  /**
   * Returns the address the socket is bound to
   */
  std::string get_bound_address();

  ~async_reply_socket();

 private:
  void* z_ctx;
  void* z_socket;
  std::string local_address;
  std::string secret_key;
  graphlab::zookeeper_util::key_value* zk_keyval;
  callback_type callback;
  socket_receive_pollset* associated_pollset;

  std::set<std::string> registered_keys;

  // some thought went into the decision whether to use a condition variable
  // or to use the DEALER-REP pattern. I decided that the condition variable
  // is better in this case since the DEALER's distribution pattern is not
  // exactly what we want here. If a callback takes a long time, the DEALER-REP
  // pattern could queue additional messages on that thread rather than
  // distributing it to other available threads.

  // for now, we use a single queue, but we could use multiple queues +
  // work stealing later if this turns out to block too heavily.
  std::queue<zmq_msg_vector*> jobqueue;
  boost::mutex queuelock;
  boost::condition_variable queuecond;
  void* inproc_pull_socket;
  bool queue_terminate; // false initially. If true, all threads die.

  // replies however have to go through the PUSH-PULL pattern.
  struct thread_data {
    async_reply_socket* parent;
    void* inproc_push_socket;
    boost::thread* thread;
  };

  void thread_function(thread_data* data);
  void process_job(thread_data* data, zmq_msg_vector* msg);

  std::vector<thread_data> threads;

  void wrapped_callback(socket_receive_pollset* unused, const zmq_pollitem_t& unused2);
  void pull_socket_callback(socket_receive_pollset* unused, const zmq_pollitem_t& data);
};

} // libfault
#endif

max_stars_repo_name: parquette/ParFrame

max_issues_repo_name: parquette/ParFrame

max_forks_repo_name: parquette/ParFrame


text:
// Copyright (C) 2016-2018 T. Zachary Laine
//
// 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)
//[ lazy_vector
// Defining this allows the assignment below of an expression to a double
// without writing any specific code to do so.
#include <boost/yap/expression.hpp>

#include <algorithm>
#include <cassert>
#include <iostream>
#include <vector>

template<boost::yap::expr_kind Kind, typename Tuple>
struct lazy_vector_expr;

// This transform turns a terminal of std::vector<double> into a terminal
// containing the nth double in that vector.  Think of it as turning our
// expression of vectors into an expression of scalars.
struct take_nth
{
    boost::yap::terminal<lazy_vector_expr, double> operator()(
        boost::yap::terminal<lazy_vector_expr, std::vector<double>> const &
            expr);

    std::size_t n;
};

// A custom expression template that defines lazy + and - operators that
// produce expressions, and an eager [] operator that returns the nth element
// of the expression.
//[ lazy_vector_decl
template<boost::yap::expr_kind Kind, typename Tuple>
struct lazy_vector_expr
{
    static const boost::yap::expr_kind kind = Kind;

    Tuple elements;

    // Note that this does not return an expression; it is greedily evaluated.
    auto operator[](std::size_t n) const;
};

BOOST_YAP_USER_BINARY_OPERATOR(plus, lazy_vector_expr, lazy_vector_expr)
BOOST_YAP_USER_BINARY_OPERATOR(minus, lazy_vector_expr, lazy_vector_expr)
//]

template<boost::yap::expr_kind Kind, typename Tuple>
auto lazy_vector_expr<Kind, Tuple>::operator[](std::size_t n) const
{
    return boost::yap::evaluate(boost::yap::transform(*this, take_nth{n}));
}

boost::yap::terminal<lazy_vector_expr, double> take_nth::operator()(
    boost::yap::terminal<lazy_vector_expr, std::vector<double>> const & expr)
{
    double x = boost::yap::value(expr)[n];
    // This move is something of a hack.  The move indicates that the terminal
    // should keep the value of x (since, being an rvalue, it may be a
    // temporary), rather than a reference to x.  See the "How Expression
    // Operands Are Treated" section of the tutorial for details.
    return boost::yap::make_terminal<lazy_vector_expr, double>(std::move(x));
}

// In order to define the += operator with the semantics we want, it's
// convenient to derive a terminal type from a terminal instantiation of
// lazy_vector_expr.  note that we could have written a template
// specialization here instead -- either one would work.  That would of course
// have required more typing.
struct lazy_vector : lazy_vector_expr<
                         boost::yap::expr_kind::terminal,
                         boost::hana::tuple<std::vector<double>>>
{
    lazy_vector() {}

    explicit lazy_vector(std::vector<double> && vec)
    {
        elements = boost::hana::tuple<std::vector<double>>(std::move(vec));
    }

    template<boost::yap::expr_kind Kind, typename Tuple>
    lazy_vector & operator+=(lazy_vector_expr<Kind, Tuple> const & rhs)
    {
        std::vector<double> & this_vec = boost::yap::value(*this);
        for (int i = 0, size = (int)this_vec.size(); i < size; ++i) {
            this_vec[i] += rhs[i];
        }
        return *this;
    }
};

lazy_vector v1{std::vector<double>(4, 1.0)};
lazy_vector v2{std::vector<double>(4, 2.0)};
lazy_vector v3{std::vector<double>(4, 3.0)};

double get_d1_with_yap()
{
    double retval = (v2 + v3)[2];
    return retval;
}

double get_d1_by_hand()
{
    std::vector<double> & v2_ref = boost::yap::value(v2);
    std::vector<double> & v3_ref = boost::yap::value(v3);
    double retval = v2_ref[2] + v3_ref[2];
    return retval;
}

void update_v1_with_yap() { v1 += v2 - v3; }

void update_v1_by_hand()
{
    std::vector<double> & v1_ref = boost::yap::value(v1);
    std::vector<double> & v2_ref = boost::yap::value(v2);
    std::vector<double> & v3_ref = boost::yap::value(v3);
    for (int i = 0, size = (int)v1_ref.size(); i < size; ++i) {
        v1_ref[i] += v2_ref[i] - v3_ref[i];
    }
}

int main()
{
    double d1_1 = get_d1_with_yap();
    std::cout << d1_1 << "\n";

    double d1_2 = get_d1_by_hand();
    std::cout << d1_2 << "\n";

    update_v1_with_yap();
    std::cout << '{' << v1[0] << ',' << v1[1] << ',' << v1[2] << ',' << v1[3]
              << '}' << "\n";

    boost::yap::value(v1) = std::vector<double>(4, 1.0);

    update_v1_by_hand();
    std::cout << '{' << v1[0] << ',' << v1[1] << ',' << v1[2] << ',' << v1[3]
              << '}' << "\n";

    // This expression is disallowed because it does not conform to the
    // implicit grammar.  operator+= is only defined on terminals, not
    // arbitrary expressions.
    // (v2 + v3) += v1;

    return 0;
}
//]

max_stars_repo_name: cpp-pm/boost

max_issues_repo_name: cpp-pm/boost

max_forks_repo_name: cpp-pm/boost


text:
// Copyright (C) 2013-2018 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <config.h>

#include <hooks/callout_handle.h>
#include <hooks/callout_manager.h>
#include <hooks/hooks_log.h>
#include <hooks/pointer_converter.h>
#include <util/stopwatch.h>

#include <boost/static_assert.hpp>

#include <algorithm>
#include <climits>
#include <functional>
#include <utility>

using namespace std;

namespace isc {
namespace hooks {

// Constructor
CalloutManager::CalloutManager(int num_libraries)
    : server_hooks_(ServerHooks::getServerHooks()),
      current_hook_(-1), current_library_(-1),
      hook_vector_(ServerHooks::getServerHooks().getCount()),
      library_handle_(this), pre_library_handle_(this, 0),
      post_library_handle_(this, INT_MAX), num_libraries_(num_libraries)
{
    if (num_libraries < 0) {
        isc_throw(isc::BadValue, "number of libraries passed to the "
                  "CalloutManager must be >= 0");
    }
}

// Check that the index of a library is valid.  It can range from 1 - n
// (n is the number of libraries), 0 (pre-user library callouts), or INT_MAX
// (post-user library callouts).  It can also be -1 to indicate an invalid
// value.

void
CalloutManager::checkLibraryIndex(int library_index) const {
    if (((library_index >= -1) && (library_index <= num_libraries_)) ||
        (library_index == INT_MAX)) {
        return;
    }

    isc_throw(NoSuchLibrary, "library index " << library_index <<
              " is not valid for the number of loaded libraries (" <<
              num_libraries_ << ")");
}

// Register a callout for the current library.

void
CalloutManager::registerCallout(const std::string& name, CalloutPtr callout) {
    // Note the registration.
    LOG_DEBUG(callouts_logger, HOOKS_DBG_CALLS, HOOKS_CALLOUT_REGISTRATION)
        .arg(current_library_).arg(name);

    // Sanity check that the current library index is set to a valid value.
    checkLibraryIndex(current_library_);

    // New hooks could have been registered since the manager was constructed.
    ensureHookLibsVectorSize();

    // Get the index associated with this hook (validating the name in the
    // process).
    int hook_index = server_hooks_.getIndex(name);

    // Iterate through the callout vector for the hook from start to end,
    // looking for the first entry where the library index is greater than
    // the present index.
    for (CalloutVector::iterator i = hook_vector_[hook_index].begin();
         i != hook_vector_[hook_index].end(); ++i) {
        if (i->first > current_library_) {
            // Found an element whose library index number is greater than the
            // current index, so insert the new element ahead of this one.
            hook_vector_[hook_index].insert(i, make_pair(current_library_,
                                                         callout));
            return;
        }
    }

    // Reached the end of the vector, so there is no element in the (possibly
    // empty) set of callouts with a library index greater than the current
    // library index.  Inset the callout at the end of the list.
    hook_vector_[hook_index].push_back(make_pair(current_library_, callout));
}

// Check if callouts are present for a given hook index.

bool
CalloutManager::calloutsPresent(int hook_index) const {
    // Validate the hook index.
    if ((hook_index < 0) || (hook_index >= hook_vector_.size())) {
        isc_throw(NoSuchHook, "hook index " << hook_index <<
                  " is not valid for the list of registered hooks");
    }

    // Valid, so are there any callouts associated with that hook?
    return (!hook_vector_[hook_index].empty());
}

bool
CalloutManager::commandHandlersPresent(const std::string& command_name) const {
    // Check if the hook point for the specified command exists.
    int index = ServerHooks::getServerHooks().findIndex(
                    ServerHooks::commandToHookName(command_name));
    if (index >= 0) {
        // The hook point exits but it is possible that there are no
        // callouts/command handlers. This is possible if there was a
        // hook library supporting this command attached, but it was
        // later unloaded. The hook points are not deregistered in
        // this case. Only callouts are deregistered.
        // Let's check if callouts are present for this hook point.
        return (calloutsPresent(index));
    }

    // Hook point not created, so we don't support this command in
    // any of the hooks libraries.
    return (false);
}

// Call all the callouts for a given hook.

void
CalloutManager::callCallouts(int hook_index, CalloutHandle& callout_handle) {

    // Clear the "skip" flag so we don't carry state from a previous call.
    // This is done regardless of whether callouts are present to avoid passing
    // any state from the previous call of callCallouts().
    callout_handle.setStatus(CalloutHandle::NEXT_STEP_CONTINUE);

    // Only initialize and iterate if there are callouts present.  This check
    // also catches the case of an invalid index.
    if (calloutsPresent(hook_index)) {

        // Set the current hook index.  This is used should a callout wish to
        // determine to what hook it is attached.
        current_hook_ = hook_index;

        // Duplicate the callout vector for this hook and work through that.
        // This step is needed because we allow dynamic registration and
        // deregistration of callouts.  If a callout attached to a hook modified
        // the list of callouts on that hook, the underlying CalloutVector would
        // change and potentially affect the iteration through that vector.
        CalloutVector callouts(hook_vector_[hook_index]);

        // This object will be used to measure execution time of each callout
        // and the total time spent in callouts for this hook point.
        util::Stopwatch stopwatch;

        // Mark that the callouts begin for the hook.
        LOG_DEBUG(callouts_logger, HOOKS_DBG_CALLS, HOOKS_CALLOUTS_BEGIN)
            .arg(server_hooks_.getName(current_hook_));

        // Call all the callouts.
        for (CalloutVector::const_iterator i = callouts.begin();
             i != callouts.end(); ++i) {
            // In case the callout tries to register or deregister a callout,
            // set the current library index to the index associated with the
            // library that registered the callout being called.
            current_library_ = i->first;

            // Call the callout
            try {
                stopwatch.start();
                int status = (*i->second)(callout_handle);
                stopwatch.stop();
                if (status == 0) {
                    LOG_DEBUG(callouts_logger, HOOKS_DBG_EXTENDED_CALLS,
                              HOOKS_CALLOUT_CALLED).arg(current_library_)
                        .arg(server_hooks_.getName(current_hook_))
                        .arg(PointerConverter(i->second).dlsymPtr())
                        .arg(stopwatch.logFormatLastDuration());
                } else {
                    LOG_ERROR(callouts_logger, HOOKS_CALLOUT_ERROR)
                        .arg(current_library_)
                        .arg(server_hooks_.getName(current_hook_))
                        .arg(PointerConverter(i->second).dlsymPtr())
                        .arg(stopwatch.logFormatLastDuration());
                }
            } catch (const std::exception& e) {
                // If an exception occurred, the stopwatch.stop() hasn't been
                // called, so we have to call it here.
                stopwatch.stop();
                // Any exception, not just ones based on isc::Exception
                LOG_ERROR(callouts_logger, HOOKS_CALLOUT_EXCEPTION)
                    .arg(current_library_)
                    .arg(server_hooks_.getName(current_hook_))
                    .arg(PointerConverter(i->second).dlsymPtr())
                    .arg(e.what())
                    .arg(stopwatch.logFormatLastDuration());
            }

        }

        // Mark end of callout execution. Include the total execution
        // time for callouts.
        LOG_DEBUG(callouts_logger, HOOKS_DBG_CALLS, HOOKS_CALLOUTS_COMPLETE)
            .arg(server_hooks_.getName(current_hook_))
            .arg(stopwatch.logFormatTotalDuration());

        // Reset the current hook and library indexes to an invalid value to
        // catch any programming errors.
        current_hook_ = -1;
        current_library_ = -1;
    }
}

void
CalloutManager::callCommandHandlers(const std::string& command_name,
                                    CalloutHandle& callout_handle) {
    // Get the index of the hook point for the specified command.
    // This will throw an exception if the hook point doesn't exist.
    // The caller should check if the hook point exists by calling
    // commandHandlersPresent.
    int index = ServerHooks::getServerHooks().getIndex(
                    ServerHooks::commandToHookName(command_name));
    // Call the handlers for this command.
    callCallouts(index, callout_handle);
}

// Deregister a callout registered by the current library on a particular hook.

bool
CalloutManager::deregisterCallout(const std::string& name, CalloutPtr callout) {
    // Sanity check that the current library index is set to a valid value.
    checkLibraryIndex(current_library_);

    // New hooks could have been registered since the manager was constructed.
    ensureHookLibsVectorSize();

    // Get the index associated with this hook (validating the name in the
    // process).
    int hook_index = server_hooks_.getIndex(name);

    // New hooks can have been registered since the manager was constructed.
    if (hook_index >= hook_vector_.size()) {
        return (false);
    }

    /// Construct a CalloutEntry matching the current library and the callout
    /// we want to remove.
    CalloutEntry target(current_library_, callout);

    /// To decide if any entries were removed, we'll record the initial size
    /// of the callout vector for the hook, and compare it with the size after
    /// the removal.
    size_t initial_size = hook_vector_[hook_index].size();

    // The next bit is standard STL (see "Item 33" in "Effective STL" by
    // Scott Meyers).
    //
    // remove_if reorders the hook vector so that all items not matching
    // the predicate are at the start of the vector and returns a pointer
    // to the next element. (In this case, the predicate is that the item
    // is equal to the value of the passed callout.)  The erase() call
    // removes everything from that element to the end of the vector, i.e.
    // all the matching elements.
    hook_vector_[hook_index].erase(remove_if(hook_vector_[hook_index].begin(),
                                             hook_vector_[hook_index].end(),
                                             bind1st(equal_to<CalloutEntry>(),
                                                     target)),
                                   hook_vector_[hook_index].end());

    // Return an indication of whether anything was removed.
    bool removed = initial_size != hook_vector_[hook_index].size();
    if (removed) {
        LOG_DEBUG(callouts_logger, HOOKS_DBG_EXTENDED_CALLS,
                  HOOKS_CALLOUT_DEREGISTERED).arg(current_library_).arg(name);
    }

    return (removed);
}

// Deregister all callouts on a given hook.

bool
CalloutManager::deregisterAllCallouts(const std::string& name) {

    // New hooks could have been registered since the manager was constructed.
    ensureHookLibsVectorSize();

    // Get the index associated with this hook (validating the name in the
    // process).
    int hook_index = server_hooks_.getIndex(name);

    /// Construct a CalloutEntry matching the current library (the callout
    /// pointer is NULL as we are not checking that).
    CalloutEntry target(current_library_, static_cast<CalloutPtr>(0));

    /// To decide if any entries were removed, we'll record the initial size
    /// of the callout vector for the hook, and compare it with the size after
    /// the removal.
    size_t initial_size = hook_vector_[hook_index].size();

    // Remove all callouts matching this library.
    hook_vector_[hook_index].erase(remove_if(hook_vector_[hook_index].begin(),
                                             hook_vector_[hook_index].end(),
                                             bind1st(CalloutLibraryEqual(),
                                                     target)),
                                   hook_vector_[hook_index].end());

    // Return an indication of whether anything was removed.
    bool removed = initial_size != hook_vector_[hook_index].size();
    if (removed) {
        LOG_DEBUG(callouts_logger, HOOKS_DBG_EXTENDED_CALLS,
                  HOOKS_ALL_CALLOUTS_DEREGISTERED).arg(current_library_)
                                                .arg(name);
    }

    return (removed);
}

void
CalloutManager::registerCommandHook(const std::string& command_name) {

    // New hooks could have been registered since the manager was constructed.
    ensureHookLibsVectorSize();

    ServerHooks& hooks = ServerHooks::getServerHooks();
    int hook_index = hooks.findIndex(ServerHooks::commandToHookName(command_name));
    if (hook_index < 0) {
        // Hook for this command doesn't exist. Let's create one.
        hooks.registerHook(ServerHooks::commandToHookName(command_name));
        // Callout Manager's vector of hooks have to be resized to hold the
        // information about callouts for this new hook point. This should
        // add new element at the end of the hook_vector_. The index of this
        // element will match the index of the hook point in the ServerHooks
        // because ServerHooks allocates indexes incrementally.
        hook_vector_.resize(server_hooks_.getCount());
    }
}

void
CalloutManager::ensureHookLibsVectorSize() {
    ServerHooks& hooks = ServerHooks::getServerHooks();
    if (hooks.getCount() > hook_vector_.size()) {
        // Uh oh, there are more hook points that our vector allows.
        hook_vector_.resize(hooks.getCount());
    }
}

} // namespace util
} // namespace isc

max_stars_repo_name: mcr/kea

max_issues_repo_name: jxiaobin/kea

max_forks_repo_name: jxiaobin/kea