text:
// (C) Copyright 2008 CodeRage, LLC (turkanis at coderage dot com)
// (C) Copyright 2004-2007 Jonathan Turkanis
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.)

// See http://www.boost.org/libs/iostreams for documentation.

#include <boost/test/unit_test.hpp>
#include "read_input_test.hpp"
#include "read_bidir_test.hpp"
#include "read_seekable_test.hpp"
#include "read_bidir_streambuf_test.hpp"
#include "read_input_istream_test.hpp"
#include "write_output_test.hpp"
#include "write_bidir_test.hpp"
#include "write_seekable_test.hpp"
#include "write_output_iterator_test.hpp"
#include "write_bidir_streambuf_test.hpp"
#include "write_output_ostream_test.hpp"
#include "read_input_filter_test.hpp"
#include "read_bidir_filter_test.hpp"
#include "write_output_filter_test.hpp"
#include "write_bidir_filter_test.hpp"
#include "seek_test.hpp"
#include "putback_test.hpp"
#include "filtering_stream_flush_test.hpp"

using boost::unit_test::test_suite;

test_suite* init_unit_test_suite(int, char* [])
{
    test_suite* test = BOOST_TEST_SUITE("filtering_stream test");
    test->add(BOOST_TEST_CASE(&read_input_test));
    test->add(BOOST_TEST_CASE(&read_bidirectional_test));
    test->add(BOOST_TEST_CASE(&read_seekable_test));
    test->add(BOOST_TEST_CASE(&read_bidirectional_streambuf_test));
    test->add(BOOST_TEST_CASE(&read_input_istream_test));
    test->add(BOOST_TEST_CASE(&write_output_test));
    test->add(BOOST_TEST_CASE(&write_bidirectional_test));
    test->add(BOOST_TEST_CASE(&write_seekable_test));
    test->add(BOOST_TEST_CASE(&write_output_iterator_test));
    test->add(BOOST_TEST_CASE(&write_bidirectional_streambuf_test));
    test->add(BOOST_TEST_CASE(&write_output_ostream_test));
    test->add(BOOST_TEST_CASE(&read_input_filter_test));
    test->add(BOOST_TEST_CASE(&read_bidirectional_filter_test));
    test->add(BOOST_TEST_CASE(&write_output_filter_test));
    test->add(BOOST_TEST_CASE(&write_bidirectional_filter_test));
    test->add(BOOST_TEST_CASE(&seek_test));
    test->add(BOOST_TEST_CASE(&putback_test));
    test->add(BOOST_TEST_CASE(&test_filtering_ostream_flush));
    return test;
}

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
#include <blitzmemory/PoolAllocator.h>

namespace blitz::memory
{

    PoolAllocator::PoolAllocator(const size_t& size) : poolSize(size) { allocated = 0; }

    PoolAllocator::~PoolAllocator() { assert(pool == nullptr); }

    void PoolAllocator::init() { pool = (char*)malloc(poolSize); }

    void PoolAllocator::reset() { allocated = 0; }

    void PoolAllocator::shutdown() { free(pool); }

    void* PoolAllocator::memalloc(std::size_t count)
    {
        assert(count + allocated < poolSize);
        void* mem = pool + allocated;
        allocated += count;
        return mem;
    };

    void PoolAllocator::memfree(void* memory){
        // NOOP pool don't free individual chunks - use reset()
    };
} // namespace blitz::memory

ext: cpp


text:
/*
 * Copyright (c) 2016-2017 Nicholas Corgan (n.corgan@gmail.com)
 *
 * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
 * or copy at http://opensource.org/licenses/MIT)
 */
#ifndef PKMN_IO_READ_WRITE_HPP
#define PKMN_IO_READ_WRITE_HPP

#include <boost/assert.hpp>

#include <cstdint>
#include <fstream>
#include <string>
#include <vector>

namespace pkmn { namespace io {

    std::vector<uint8_t> read_file(const std::string& filepath);

    inline void write_file(
        const std::string& filepath,
        const std::vector<uint8_t>& contents
    )
    {
        std::ofstream ofile(filepath, std::ios::binary);
        ofile.write((const char*)contents.data(), contents.size());
    }

    inline void write_file(
        const std::string& filepath,
        const void* p_buffer,
        size_t buffer_size
    )
    {
        BOOST_ASSERT(p_buffer != nullptr);

        std::ofstream ofile(filepath, std::ios::binary);
        ofile.write((const char*)p_buffer, buffer_size);
    }

}}

#endif /* PKMN_IO_READ_WRITE_HPP */

ext: hpp

max_stars_repo_name: ncorgan/libpkmn

max_issues_repo_name: PMArkive/libpkmn

max_forks_repo_name: PMArkive/libpkmn


text:
/* Siconos is a program dedicated to modeling, simulation and control
 * of non smooth dynamical systems.
 *
 * Copyright 2021 INRIA.
 *
 * 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.
*/

/*! \file SiconosProperties.hpp

  \brief Exterior properties to vertices or edges of a SiconosGraph
  can be attach with Siconos::Properties. These properties are
  referenced with vertices or edges indices. update_vertices_indices()
  or update_edges_indices() must have been done after any vertices or
  edges insertion or deletion.

*/

#ifndef SICONOS_PROPERTIES_HPP
#define SICONOS_PROPERTIES_HPP

#include "SiconosSerialization.hpp"

#include <boost/config.hpp>
#include <boost/version.hpp>

#if (BOOST_VERSION >= 104000)
#include <boost/property_map/property_map.hpp>
#else
#include <boost/property_map.hpp>
#endif

#include <SiconosConfig.h>
#include <memory>
#include <map>

#include <boost/mpl/eval_if.hpp>
#include <boost/static_assert.hpp>
#include <vector>
#include <queue>

#include <boost/mpl/bool.hpp>
#include <boost/type_traits.hpp>

namespace Siconos
{

/** some local type traits */
template <typename T>
struct IsSharedPtr : boost::mpl::false_ {};

template <typename T>
struct IsSharedPtr<std::shared_ptr<T> > : boost::mpl::true_ {};

template <typename T>
struct IsPointer : boost::mpl::or_<boost::is_pointer<T>, IsSharedPtr<T> > {};

template <typename T>
struct RemovePointer
{
  typedef T type;
};

template <typename T>
struct RemovePointer<std::shared_ptr<T> >
{
  typedef T type;
};

/* a templated way to access edge or vertex with the help of
 * boost::mpl::if_ */

/** get vertex needed data */
template<typename G>
struct VertexAccess
{
  typedef VertexAccess type;
  typedef typename G::VDescriptor descriptor;
  typedef typename G::VIterator iterator;

  std::pair<iterator, iterator> elements(G& g)
  {
    return g.vertices();
  }

  size_t size(G& g)
  {
    return g.vertices_number();
  }

  bool isElem(G& g, typename G::VDescriptor& vd)
  {
    return g.is_vertex(g.bundle(vd));
  }

};

/** get edge needed data */
template<typename G>
struct EdgeAccess
{
  typedef EdgeAccess type;
  typedef typename G::EDescriptor descriptor;
  typedef typename G::EIterator iterator;

  std::pair<iterator, iterator> elements(G& g)
  {
    return g.edges();
  }

  static size_t size(const G& g)
  {
    return g.edges_number();
  }

  bool isElem(G& g, typename G::EDescriptor& ed)
  {
    return g.is_edge(g.source(ed), g.target(ed), g.bundle(ed));
  }
};

/** choose vertex or edge access according to IndexMap */
template<typename G, typename IndexMap>
struct VertexOrEdge
{
  typedef typename boost::mpl::if_ < boost::is_same<typename G::VIndexAccess, IndexMap>,
          VertexAccess<G> ,
          EdgeAccess<G>  >::type Access;
};

/** swap data */
template <typename T>
struct SwapPointedValues
{

  typedef SwapPointedValues type;

  void operator()(T a, T b)
  {
    //note: if T is abstract, swap(T& a, T&b) must be implemented
    using std::swap;
    swap(*a, *b);
  }
};

template <typename T>
struct SwapValues
{

  typedef SwapValues type;

  void operator()(T&a, T&b)
  {
    using std::swap;
    swap(a, b);
  }
};

template <typename T>
struct SwapProperties
{
  typedef typename boost::mpl::if_ < IsPointer<T>,
          SwapPointedValues<T>,
          SwapValues<T> >::type type;
};

template <typename T>
struct GetPointedValue
{
  typedef GetPointedValue type;

  typename RemovePointer<T>::type& operator()(T a)
  {
    return *a;
  }
};

template <typename T>
struct GetValue
{
  typedef GetValue type;

  T& operator()(T& a)
  {
    return a;
  }
};

template <typename T>
struct GetProperty
{

  typedef typename boost::mpl::if_ < IsPointer<T>,
          GetPointedValue<T>,
          GetValue<T> >::type type;

};

/** the general properties structure, from boost::vector_property_map :
 \param T the property data type
 \param G the graph type
 \param IndexMap the index map, should be either G::VIndexAccess or G:EIndexAccess
*/
template<typename T, typename G, typename IndexMap>

class Properties
{

public:
  typedef typename VertexOrEdge<G, IndexMap>::Access Access;

  Access access;

  typedef typename boost::property_traits<IndexMap>::key_type  key_type;
  typedef T value_type;
  typedef typename std::iterator_traits <
  typename std::vector<T>::iterator >::reference reference;
  typedef boost::lvalue_property_map_tag category;

public:
  G& _g;

  // serialization issue with key_type as simple pointer (void *)
  std::shared_ptr< std::map<key_type, T> > _store;

  int _stamp;

  /** constructor from a SiconosGraph
      \param g a SiconosGraph
  */

  Properties(G& g) : _g(g), _store(new std::map<key_type, T>()), _stamp(-1)
  {}

  /** insert an element in the Property descriptor
    * \param v a SiconosGraph::VDescriptor or
    * SiconosGraph::EDescriptor according to IndexMap type
    * \param t the element to be inserted
    */
  void insert(const key_type& v, T t)
  {
    (*_store)[v] = t;
  };

  /** data access from a SiconosGraph vertex descriptor or edge
      descriptor
      \warning this operator creates an empty element if the key
      is not in the map. Dot not use it to test if a key is present
      or not in the map ...
      \param v a SiconosGraph::VDescriptor or
      SiconosGraph::EDescriptor according to IndexMap type
      \return the element in the vector
    */
  reference operator[](const key_type& v)
  {
    return (*_store)[v];
  };

  /** data access from a SiconosGraph vertex descriptor or edge
      descriptor
      \param v a SiconosGraph::VDescriptor or
      SiconosGraph::EDescriptor according to IndexMap type */
  value_type at(const key_type& v)
  {
    return _store->at(v);
  };

  /** find data associated with the given key
      \param v a SiconosGraph::VDescriptor or
      SiconosGraph::EDescriptor according to IndexMap type
      \return an iterator
   */
  reference find(const key_type& v)
  {
    return _store->find(v).second;
  };

  /** check if a given property exists
      \param v a SiconosGraph::VDescriptor or
      SiconosGraph::EDescriptor according to IndexMap type
      \return true if the key is a property, otherwise false
   */
  inline bool hasKey(const key_type& v)
  {
    return _store->find(v) != _store->end();
  };

  typedef void serializable;

  /* Note: compilation with clang fail on this. And friend
   * Siconos::siconos_io is not recognized anyway (attributes are public)

  protected:
    template<typename Archive>
    friend void Siconos::siconos_io(Archive&, Properties<T,G,IndexMap>&, const unsigned int);
    friend class boost::serialization::access;
  */
};

/** vertex property structure:
    \param T the property data type
    \param G the graph type
 */
template<typename T, typename G>
class VertexProperties : public Properties<T, G, typename G::VIndexAccess>
{
public:
  VertexProperties(G& g) : Properties<T, G, typename G::VIndexAccess>(g)
  {};

  typedef void serializable;

  /*
  protected:
    template<typename Archive>
    friend void Siconos::siconos_io(Archive&, VertexProperties<T,G>&, const unsigned int);
    friend class boost::serialization::access;
  */
};

/** vertex property structure with shared_pre
    \param T the property data type
    \param G the graph type
 */
template<typename T, typename G>
class VertexSPProperties : public VertexProperties<std::shared_ptr<T>, G>
{
public:
  VertexSPProperties(G& g) : VertexProperties<std::shared_ptr<T>, G>(g)
  {};

  typedef typename boost::property_traits<typename G::VIndexAccess>::key_type  key_type;
  typedef void serializable;

  /** data access from a SiconosGraph vertex descriptor or edge
      descriptor
      \warning this operator creates an empty element if the key
      is not in the map. Dot not use it to test if a key os present
      or not in the map ...
      \param v a SiconosGraph::VDescriptor or
      SiconosGraph::EDescriptor according to IndexMap type
      \return the element in the vector
    */
  inline T& getRef(const key_type& v)
  {
    return *((*this->_store)[v]).get();
  };
};

/** edge property structure:
    \param T the property data type
    \param G the graph type
 */
template<typename T, typename G>
class EdgeProperties : public Properties<T, G, typename G::EIndexAccess>
{
public:
  EdgeProperties(G& g) : Properties<T, G, typename G::EIndexAccess>(g)
  {};

  typedef void serializable;

  /*
  protected:
    template<typename Archive>
    friend void Siconos::siconos_io(Archive&, EdgeProperties<T,G>&, const unsigned int);
    friend class boost::serialization::access;
  */
};

/** function to build a VertexProperties from one template parameter
  \param g the graph
*/
template<typename T, typename G>
VertexProperties<T, G> vertexProperties(G& g)
{
  return VertexProperties<T, G>(g);
}

/** function to build a EdgeProperties from one template parameter
  \param g the graph
*/
template<typename T, typename G>
EdgeProperties<T, G> edgeProperties(G& g)
{
  return EdgeProperties<T, G>(g);
}

/** global properties : they may be attached to main graph and may be
 * referenced from subgraphs. They are not used for the moment */

template<typename T, typename G, typename IndexMap>
class SubProperties
{
private:
  typedef Properties<T, G, IndexMap> RefProperties;
  RefProperties _properties;
  G& _g;

  typedef typename boost::property_traits<IndexMap>::key_type  key_type;
  typedef T value_type;
  typedef typename std::iterator_traits <
  typename std::vector<T>::iterator >::reference reference;
  typedef boost::lvalue_property_map_tag category;

public:

  SubProperties(RefProperties& p, G& g)
    : _properties(p), _g(g) {}

  reference operator[](const key_type& v)
  {
    return _properties[_g.descriptor0(v)];
  }

};

template<typename T, typename G>
class VertexSubProperties : public SubProperties<T, G, typename G::VIndexAccess>
{
public:
  typedef Properties<T, G, typename G::VIndexAccess> RefProperties;

  VertexSubProperties(RefProperties& p, G& g) : SubProperties<T, G, typename G::VIndexAccess>(p, g)
  {};
};

template<typename T, typename G>
class EdgeSubProperties : public SubProperties<T, G, typename G::EIndexAccess>
{
public:
  typedef Properties<T, G, typename G::EIndexAccess> RefProperties;

  EdgeSubProperties(RefProperties& p, G& g) : SubProperties<T, G, typename G::EIndexAccess>(p, g)
  {};
};

}

/* convenience macro for properties declarations */

#include <boost/preprocessor/seq/seq.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/tuple/elem.hpp>
#include <boost/preprocessor/cat.hpp>

#define I_DECLARE_MEMBERS(r,gt,p) \
  Siconos:: BOOST_PP_CAT(BOOST_PP_TUPLE_ELEM(3,0,p),Properties)< BOOST_PP_TUPLE_ELEM(3,1,p), BOOST_PP_CAT(_,gt)> BOOST_PP_TUPLE_ELEM(3,2,p);

#define I_CONS_MEMBERS(r,gt,p) \
  BOOST_PP_TUPLE_ELEM(3,2,p) (Siconos:: BOOST_PP_CAT(BOOST_PP_TUPLE_ELEM(3,0,p),Properties)< BOOST_PP_TUPLE_ELEM(3,1,p), BOOST_PP_CAT(_,gt)>(*static_cast<BOOST_PP_CAT(_,gt)*>(this))),

#define INSTALL_GRAPH_PROPERTIES(GraphType, PROPERTIES)                 \
  BOOST_PP_SEQ_FOR_EACH(I_DECLARE_MEMBERS, BOOST_PP_CAT(GraphType, Graph), PROPERTIES) \
  bool dummy;                                                           \
                                                                        \
  BOOST_PP_CAT(GraphType, Graph)() :                                    \
    BOOST_PP_SEQ_FOR_EACH(I_CONS_MEMBERS, BOOST_PP_CAT(GraphType, Graph), PROPERTIES) dummy(true) {} \

#endif

max_stars_repo_name: BuildJet/siconos

max_issues_repo_name: BuildJet/siconos

max_forks_repo_name: BuildJet/siconos


text:
 /*
 *	DeviceLiveDataFetcher.cpp
 *	!CHOAS
 *	Created by Bisegni Claudio.
 *
 *    	Copyright 2012 INFN, National Institute of Nuclear Physics
 *
 *    	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 "DeviceController.h"
#include <chaos/ui_toolkit/LowLevelApi/LLRpcApi.h>
#include <chaos/common/io/IOMemcachedIODriver.h>

#include <boost/lexical_cast.hpp>

using namespace std;
using namespace chaos;
using namespace chaos::ui;
namespace chaos_batch = chaos::common::batch_command;
namespace cc_data = chaos::common::data;

#define MSEC_WAIT_OPERATION 1000

//---------------------------------------------------------------------------------------------------
DeviceController::DeviceController(string& _deviceID):
device_id(_deviceID),
datasetDB(true) {
    mdsChannel = NULL;
    deviceChannel = NULL;
    ioLiveDataDriver = NULL;
    millisecToWait = MSEC_WAIT_OPERATION;

	output_key	= device_id + DataPackPrefixID::OUTPUT_DATASE_PREFIX;
	input_key	= device_id + DataPackPrefixID::INPUT_DATASE_PREFIX;
	system_key	= device_id + DataPackPrefixID::SYSTEM_DATASE_PREFIX;
	custom_key	= device_id + DataPackPrefixID::CUSTOM_DATASE_PREFIX;
}

//---------------------------------------------------------------------------------------------------
DeviceController::~DeviceController() {
    stopTracking();

    if(mdsChannel){
        LLRpcApi::getInstance()->deleteMessageChannel(mdsChannel);
    }

    if(deviceChannel){
        LLRpcApi::getInstance()->deleteMessageChannel(deviceChannel);
    }

    if(ioLiveDataDriver){
        ioLiveDataDriver->deinit();
        delete(ioLiveDataDriver);
    }
}

//---------------------------------------------------------------------------------------------------
void DeviceController::setRequestTimeWaith(uint32_t newMillisecToWait){
    millisecToWait = newMillisecToWait;
}

//---------------------------------------------------------------------------------------------------
uint32_t DeviceController::getRequestTimeWaith(){
    return millisecToWait;
}

//---------------------------------------------------------------------------------------------------
void DeviceController::getDeviceId(string& dId) {
	dId = device_id;
}

//---------------------------------------------------------------------------------------------------
void DeviceController::updateChannel() throw(CException) {
    int err = ErrorCode::EC_NO_ERROR;
    CDataWrapper *devDefHandler = NULL;
    CDeviceNetworkAddress *devAddress = NULL;
    //make the live driver
    if(!mdsChannel){
        mdsChannel = LLRpcApi::getInstance()->getNewMetadataServerChannel();
        if(!mdsChannel) throw CException(-1, "No MDS Channel created", "DeviceController::init");
    }

    err = mdsChannel->getLastDatasetForDevice(device_id, &devDefHandler, millisecToWait);
    if(err!=ErrorCode::EC_NO_ERROR || !devDefHandler) throw CException(-2, "No device dataset received", "DeviceController::updateChannel");

    auto_ptr<CDataWrapper> lastDeviceDefinition(devDefHandler);

    datasetDB.addAttributeToDataSetFromDataWrapper(*lastDeviceDefinition.get());

    err = mdsChannel->getNetworkAddressForDevice(device_id, &devAddress, millisecToWait);
    if(err!=ErrorCode::EC_NO_ERROR || !devAddress) throw CException(-3, "No Address found for device", "DeviceController::init");

    //update live data driver
	if(!ioLiveDataDriver) {
    ioLiveDataDriver = LLRpcApi::getInstance()->getDataProxyChannelNewInstance();
		if(ioLiveDataDriver) {
			ioLiveDataDriver->init(NULL);
		}
	}
    if(ioLiveDataDriver) ioLiveDataDriver->updateConfiguration(lastDeviceDefinition.get());

    //allocate device channel the memory of the CDeviceNetworkAddress * is managed by channel
    if(!deviceChannel){
        deviceChannel = LLRpcApi::getInstance()->getNewDeviceMessageChannel(devAddress);
        if(!deviceChannel) throw CException(-4, "Invalid device channel created", "DeviceController::init");
    }else{
        deviceChannel->setNewAddress(devAddress);
    }
}

//---------------------------------------------------------------------------------------------------
int DeviceController::setScheduleDelay(uint64_t microseconds) {
    CHAOS_ASSERT(deviceChannel)
    return deviceChannel->setScheduleDelay(microseconds, millisecToWait);
}

//---------------------------------------------------------------------------------------------------
void DeviceController::getDeviceDatasetAttributesName(vector<string>& attributesName) {
    datasetDB.getDatasetAttributesName(attributesName);
}

//---------------------------------------------------------------------------------------------------
void DeviceController::getAttributeDescription(const string& attributesName, string& attributeDescription) {
    datasetDB.getAttributeDescription(attributesName, attributeDescription);
}

//---------------------------------------------------------------------------------------------------
void DeviceController::getDeviceDatasetAttributesName(vector<string>& attributesName, DataType::DataSetAttributeIOAttribute directionType) {
    datasetDB.getDatasetAttributesName(directionType, attributesName);
}

//---------------------------------------------------------------------------------------------------
void DeviceController::getDeviceAttributeRangeValueInfo(const string& attributesName, chaos::common::data::RangeValueInfo& rangeInfo) {
    datasetDB.getAttributeRangeValueInfo(attributesName, rangeInfo);
}
//---------------------------------------------------------------------------------------------------
int DeviceController::getDeviceAttributeDirection(const string& attributesName, DataType::DataSetAttributeIOAttribute& directionType) {
    return datasetDB.getAttributeDirection(attributesName, directionType);
}

//---------------------------------------------------------------------------------------------------
int DeviceController::getAttributeStrValue(string attribute_name, string& attribute_value) {
	int err = 0;
	CDataWrapper *  dataWrapper = getLiveCDataWrapperPtr();
	if(dataWrapper) {
		DataType::DataType attributeType;
		err = getDeviceAttributeType(attribute_name, attributeType);
		if(err == 0){
			switch (attributeType) {
				case DataType::TYPE_INT64:
					attribute_value = boost::lexical_cast<string>(dataWrapper->getInt64Value(attribute_name.c_str()));
					break;

				case DataType::TYPE_INT32:
					attribute_value = boost::lexical_cast<string>(dataWrapper->getInt64Value(attribute_name.c_str()));
					break;

				case DataType::TYPE_DOUBLE:
					attribute_value = boost::lexical_cast<string>(dataWrapper->getDoubleValue(attribute_name.c_str()));
					break;

				case DataType::TYPE_STRING:
					attribute_value = boost::lexical_cast<string>(dataWrapper->getStringValue(attribute_name.c_str()));
					break;

				case DataType::TYPE_BOOLEAN:
					attribute_value = boost::lexical_cast<string>(dataWrapper->getBoolValue(attribute_name.c_str()));
					break;

				case DataType::TYPE_BYTEARRAY: {
					const char *buffer = NULL;
					int size;
					buffer = dataWrapper->getBinaryValue(attribute_name.c_str(), size);
					if(buffer) attribute_value.assign(buffer, size);
					break;
				}

				default:
					err = -1;
					break;
			}
		}

	}
	return err;
}
//---------------------------------------------------------------------------------------------------
int DeviceController::getDeviceAttributeType(const string& attributesName, DataType::DataType& type) {
	int err = 0;
	if(attributeTypeMap.count(attributesName)){
		type = attributeTypeMap[attributesName];
	} else {
		err = -1;
	}
	return err;
}

//---------------------------------------------------------------------------------------------------
int DeviceController::getType(std::string& control_unit_type) {
	int err = 0;
	if(!cu_type.size()) {
		err = deviceChannel->getType(cu_type, millisecToWait);
	}
	control_unit_type = cu_type;
	return err;
}

//---------------------------------------------------------------------------------------------------
int DeviceController::initDevice() {
	CHAOS_ASSERT(mdsChannel && deviceChannel)
	int err = 0;
	CDataWrapper initConf;
	datasetDB.fillDataWrapperWithDataSetDescription(initConf);

	//initialize the devica with the metadataserver data
	err = deviceChannel->initDevice(&initConf, millisecToWait);
	//configure the live data with the same server where the device write
	return err;
}

//---------------------------------------------------------------------------------------------------
int DeviceController::startDevice() {
	CHAOS_ASSERT(deviceChannel)
	return deviceChannel->startDevice(millisecToWait);
}

//---------------------------------------------------------------------------------------------------
int DeviceController::stopDevice() {
	CHAOS_ASSERT(deviceChannel)
	return deviceChannel->stopDevice(millisecToWait);
}

//---------------------------------------------------------------------------------------------------
int DeviceController::deinitDevice() {
	CHAOS_ASSERT(deviceChannel)
	return deviceChannel->deinitDevice(millisecToWait);
}

//---------------------------------------------------------------------------------------------------
int DeviceController::getState(CUStateKey::ControlUnitState& deviceState) {
	CHAOS_ASSERT(deviceChannel)
	return deviceChannel->getState(deviceState, millisecToWait);
}

//---------------------------------------------------------------------------------------------------
int DeviceController::setAttributeValue(string& attributeName, int32_t attributeValue) {
	return setAttributeValue(attributeName.c_str(), attributeValue);
}

//---------------------------------------------------------------------------------------------------
int DeviceController::setAttributeValue(const char *attributeName, int32_t attributeValue) {
	CDataWrapper attributeValuePack;
	attributeValuePack.addInt32Value(attributeName, attributeValue);
	return deviceChannel->setAttributeValue(attributeValuePack, millisecToWait);
}

//---------------------------------------------------------------------------------------------------
int DeviceController::setAttributeValue(string& attributeName, double attributeValue) {
	return setAttributeValue(attributeName.c_str(), attributeValue);
}

//---------------------------------------------------------------------------------------------------
int DeviceController::setAttributeValue(const char *attributeName, double attributeValue) {
	CDataWrapper attributeValuePack;
	attributeValuePack.addDoubleValue(attributeName, attributeValue);
	return deviceChannel->setAttributeValue(attributeValuePack, millisecToWait);
}

//---------------------------------------------------------------------------------------------------
int DeviceController::setAttributeToValue(const char *attributeName, const char *attributeValue, bool noWait) {
	int err = ErrorCode::EC_NO_ERROR;
	CDataWrapper attributeValuePack;
	cc_data::RangeValueInfo range_info;

	//get type for the value
	if((err = datasetDB.getAttributeRangeValueInfo(attributeName, range_info)))
		return err;

	switch (range_info.valueType) {
		case DataType::TYPE_BOOLEAN: {
			bool boolValuePtr = lexical_cast<bool>(attributeValue);
			attributeValuePack.addBoolValue(attributeName, boolValuePtr);
			break;
		}
		case DataType::TYPE_STRING:{
			attributeValuePack.addStringValue(attributeName, attributeValue);
			break;
		}
		case DataType::TYPE_DOUBLE:{
			double doubleValuePtr = lexical_cast<double>(attributeValue);
			attributeValuePack.addDoubleValue(attributeName, doubleValuePtr);
			break;
		}
		case DataType::TYPE_INT32:{
			int32_t i32ValuePtr = lexical_cast<int32_t>(attributeValue);
			attributeValuePack.addInt32Value(attributeName, i32ValuePtr);
			break;
		}
		case DataType::TYPE_INT64:{
			int64_t i64ValuePtr = lexical_cast<int64_t>(attributeValue);
			attributeValuePack.addInt64Value(attributeName, i64ValuePtr);
			break;
		}
		case DataType::TYPE_BYTEARRAY:{
			//const char *byteArrayValuePtr = static_cast<const char*>(attributeValue);
			//attributeValuePack.addBinaryValue(attributeName, byteArrayValuePtr, bufferValuedDim);
			throw CException(1, "The byte array set is not managed", "DeviceController::setAttributeToValue");
			break;
		}
	}
	return deviceChannel->setAttributeValue(attributeValuePack, noWait, millisecToWait);
}

//---------------------------------------------------------------------------------------------------
int DeviceController::setAttributeToValue(const char *attributeName, void *attributeValue, bool noWait, int32_t bufferValuedDim) {
	cc_data::RangeValueInfo range_info;

	//get type for the value
	datasetDB.getAttributeRangeValueInfo(attributeName, range_info);

	//call default API
	return setAttributeToValue(attributeName, range_info.valueType, attributeValue, noWait, bufferValuedDim);
}

//---------------------------------------------------------------------------------------------------
int DeviceController::setAttributeToValue(const char *attributeName, DataType::DataType attributeType, void *attributeValue, bool noWait, int32_t bufferValuedDim) {
	CDataWrapper attributeValuePack;
	switch (attributeType) {
		case DataType::TYPE_BOOLEAN: {
			bool *boolValuePtr = static_cast<bool *>(attributeValue);
			attributeValuePack.addBoolValue(attributeName, *boolValuePtr);
			break;
		}
		case DataType::TYPE_STRING:{
			const char *strValuePtr = static_cast<const char *>(attributeValue);
			attributeValuePack.addStringValue(attributeName, strValuePtr);
			break;
		}
		case DataType::TYPE_DOUBLE:{
			double *doubleValuePtr = static_cast<double*>(attributeValue);
			attributeValuePack.addDoubleValue(attributeName, *doubleValuePtr);
			break;
		}
		case DataType::TYPE_INT32:{
			int32_t *i32ValuePtr = static_cast<int32_t*>(attributeValue);
			attributeValuePack.addInt32Value(attributeName, *i32ValuePtr);
			break;
		}
		case DataType::TYPE_INT64:{
			int64_t *i64ValuePtr = static_cast<int64_t*>(attributeValue);
			attributeValuePack.addInt64Value(attributeName, *i64ValuePtr);
			break;
		}
		case DataType::TYPE_BYTEARRAY:{
			const char *byteArrayValuePtr = static_cast<const char*>(attributeValue);
			attributeValuePack.addBinaryValue(attributeName, byteArrayValuePtr, bufferValuedDim);
			break;
		}
	}
	return deviceChannel->setAttributeValue(attributeValuePack, noWait, millisecToWait);
}

//---------------------------------------------------------------------------------------------------
int DeviceController::submitSlowControlCommand(string commandAlias,
											   chaos_batch::SubmissionRuleType::SubmissionRule submissionRule,
											   uint32_t priority,
											   uint64_t& command_id,
											   uint32_t execution_channel,
											   uint64_t scheduler_steps_delay,
											   uint32_t submission_checker_steps_delay,
											   CDataWrapper *slow_command_data) {
	CDataWrapper localCommandPack;
	CDataWrapper *resultData = NULL;
	int err = ErrorCode::EC_NO_ERROR;

	if(slow_command_data) {
		localCommandPack.appendAllElement(*slow_command_data);
	}

	// set the default slow command information
	localCommandPack.addStringValue(chaos_batch::BatchCommandSubmissionKey::COMMAND_ALIAS_STR, commandAlias);
	localCommandPack.addInt32Value(chaos_batch::BatchCommandSubmissionKey::SUBMISSION_RULE_UI32, (uint32_t) submissionRule);
	localCommandPack.addInt32Value(chaos_batch::BatchCommandSubmissionKey::SUBMISSION_PRIORITY_UI32, (uint32_t) priority);

	if(execution_channel) localCommandPack.addInt32Value(chaos_batch::BatchCommandSubmissionKey::COMMAND_EXECUTION_CHANNEL, (uint32_t) execution_channel);
	if(scheduler_steps_delay) localCommandPack.addInt64Value(chaos_batch::BatchCommandSubmissionKey::SCHEDULER_STEP_TIME_INTERVALL_UI64, scheduler_steps_delay);
	if(submission_checker_steps_delay) localCommandPack.addInt32Value(chaos_batch::BatchCommandSubmissionKey::SUBMISSION_RETRY_DELAY_UI32, submission_checker_steps_delay);

	//err = deviceChannel->setAttributeValue(localCommandPack, false, millisecToWait);
	localCommandPack.addStringValue(DatasetDefinitionkey::DEVICE_ID, device_id);
	err = deviceChannel->sendCustomRequest("setDatasetAttribute", &localCommandPack, &resultData, millisecToWait);
	if(err == ErrorCode::EC_NO_ERROR && resultData && resultData->hasKey(chaos_batch::BatchCommandExecutorRpcActionKey::RPC_GET_COMMAND_STATE_CMD_ID_UI64)) {
		//fill the command id
		command_id = resultData->getUInt64Value(chaos_batch::BatchCommandExecutorRpcActionKey::RPC_GET_COMMAND_STATE_CMD_ID_UI64);
		delete(resultData);
	}
	//forward the request
	return err;
}

//---------------------------------------------------------------------------------------------------
int DeviceController::submitSlowControlCommand(string commandAlias,
											   chaos_batch::SubmissionRuleType::SubmissionRule submissionRule,
											   uint64_t& command_id,
											   uint32_t execution_channel,
											   uint64_t scheduler_steps_delay,
											   uint32_t submission_checker_steps_delay,
											   CDataWrapper *slow_command_data) {
	CDataWrapper localCommandPack;
	CDataWrapper *resultData = NULL;
	int err = ErrorCode::EC_NO_ERROR;

	if(slow_command_data) {
		localCommandPack.appendAllElement(*slow_command_data);
	}
	// set the default slow command information
	localCommandPack.addStringValue(chaos_batch::BatchCommandSubmissionKey::COMMAND_ALIAS_STR, commandAlias);
	localCommandPack.addInt32Value(chaos_batch::BatchCommandSubmissionKey::SUBMISSION_RULE_UI32, (uint32_t) submissionRule);

	if(execution_channel) localCommandPack.addInt32Value(chaos_batch::BatchCommandSubmissionKey::COMMAND_EXECUTION_CHANNEL, (uint32_t) execution_channel);
	if(scheduler_steps_delay) localCommandPack.addInt64Value(chaos_batch::BatchCommandSubmissionKey::SCHEDULER_STEP_TIME_INTERVALL_UI64, scheduler_steps_delay);
	if(submission_checker_steps_delay) localCommandPack.addInt32Value(chaos_batch::BatchCommandSubmissionKey::SUBMISSION_RETRY_DELAY_UI32, (uint32_t) submission_checker_steps_delay);

	//forward the request
	localCommandPack.addStringValue(DatasetDefinitionkey::DEVICE_ID, device_id);
	err = deviceChannel->sendCustomRequest("setDatasetAttribute", &localCommandPack, &resultData, millisecToWait);
	if(err == ErrorCode::EC_NO_ERROR && resultData && resultData->hasKey(chaos_batch::BatchCommandExecutorRpcActionKey::RPC_GET_COMMAND_STATE_CMD_ID_UI64)) {
		//fill the command id
		command_id = resultData->getUInt64Value(chaos_batch::BatchCommandExecutorRpcActionKey::RPC_GET_COMMAND_STATE_CMD_ID_UI64);
		delete(resultData);
	}
	//forward the request
	return err;
}

//---------------------------------------------------------------------------------------------------
int DeviceController::setSlowCommandFeatures(chaos_batch::features::Features& features, bool lock_features, uint32_t execution_channel) {
	CDataWrapper localCommandPack;
	if(features.featuresFlag & chaos_batch::features::FeaturesFlagTypes::FF_LOCK_USER_MOD) {
		localCommandPack.addBoolValue(chaos_batch::BatchCommandExecutorRpcActionKey::RPC_SET_COMMAND_FEATURES_LOCK_BOOL, lock_features);
	}

	if(features.featuresFlag & chaos_batch::features::FeaturesFlagTypes::FF_SET_SCHEDULER_DELAY) {
		localCommandPack.addInt64Value(chaos_batch::BatchCommandExecutorRpcActionKey::RPC_SET_COMMAND_FEATURES_SCHEDULER_STEP_WAITH_UI64, features.featureSchedulerStepsDelay);
	}

	if(execution_channel) localCommandPack.addInt32Value(chaos_batch::BatchCommandSubmissionKey::COMMAND_EXECUTION_CHANNEL, (uint32_t) execution_channel);

	return deviceChannel->sendCustomRequest(chaos_batch::BatchCommandExecutorRpcActionKey::RPC_SET_COMMAND_FEATURES, &localCommandPack, NULL, millisecToWait);
}

//---------------------------------------------------------------------------------------------------
int DeviceController::setSlowCommandLockOnFeatures(bool lock_features) {
	CDataWrapper localCommandPack;
	localCommandPack.addBoolValue(chaos_batch::BatchCommandExecutorRpcActionKey::RPC_SET_COMMAND_FEATURES_LOCK_BOOL, lock_features);
	return deviceChannel->sendCustomRequest(chaos_batch::BatchCommandExecutorRpcActionKey::RPC_SET_COMMAND_FEATURES, &localCommandPack, NULL, millisecToWait);
}

//---------------------------------------------------------------------------------------------------
int DeviceController::getCommandState(chaos_batch

									  ::CommandState& command_state) {
	CDataWrapper localCommandPack;
	CDataWrapper *resultData = NULL;
	int err = ErrorCode::EC_NO_ERROR;
	localCommandPack.addInt64Value(chaos_batch::BatchCommandExecutorRpcActionKey::RPC_GET_COMMAND_STATE_CMD_ID_UI64, command_state.command_id);
	err = deviceChannel->sendCustomRequest(chaos_batch::BatchCommandExecutorRpcActionKey::RPC_GET_COMMAND_STATE, &localCommandPack, &resultData, millisecToWait);
	if(err == ErrorCode::EC_NO_ERROR && resultData) {
		//fill the command state
		command_state.last_event = static_cast<chaos_batch::BatchCommandEventType::BatchCommandEventType>(resultData->getUInt32Value(chaos_batch::BatchCommandExecutorRpcActionKey::RPC_GET_COMMAND_STATE_LAST_EVENT_UI32));
		if(command_state.last_event == chaos_batch::BatchCommandEventType::EVT_FAULT) {
			command_state.fault_description.code = resultData->getUInt32Value(chaos_batch::BatchCommandExecutorRpcActionKey::RPC_GET_COMMAND_STATE_ERROR_CODE_UI32);
			command_state.fault_description.description = resultData->getStringValue(chaos_batch::BatchCommandExecutorRpcActionKey::RPC_GET_COMMAND_STATE_ERROR_DESC_STR);
			command_state.fault_description.domain = chaos_batch::BatchCommandExecutorRpcActionKey::RPC_GET_COMMAND_STATE_ERROR_DOMAIN_STR;
		} else {
			command_state.fault_description.code = 0;
			command_state.fault_description.description.clear();
			command_state.fault_description.domain.clear();
		}
		delete(resultData);
	}
	return err;
}

//---------------------------------------------------------------------------------------------------
int DeviceController::killCurrentCommand() {
	return deviceChannel->sendCustomRequest(chaos_batch::BatchCommandExecutorRpcActionKey::RPC_KILL_CURRENT_COMMAND, NULL, NULL, millisecToWait);
}

//---------------------------------------------------------------------------------------------------
int DeviceController::flushCommandStateHistory() {
	return deviceChannel->sendCustomRequest(chaos_batch::BatchCommandExecutorRpcActionKey::RPC_FLUSH_COMMAND_HISTORY, NULL, NULL, millisecToWait);
}

//---------------------------------------------------------------------------------------------------
int DeviceController::sendCustomRequest(const char * const action, common::data::CDataWrapper * const param, common::data::CDataWrapper**const result, bool async, bool queued) {
	return deviceChannel->sendCustomRequest(action, param, result, millisecToWait, async, queued);
}

//---------------------------------------------------------------------------------------------------
void DeviceController::sendCustomMessage(const char * const action, common::data::CDataWrapper * const param, bool queued) {
	deviceChannel->sendCustomMessage(action, param, !queued);
}

//---------------------------------------------------------------------------------------------------
int DeviceController::setAttributeValue(string& attributeName, string& attributeValue) {
	return setAttributeValue(attributeName, attributeValue.c_str(),(uint32_t)attributeValue.size());
}

//---------------------------------------------------------------------------------------------------
int DeviceController::setAttributeValue(string& attributeName, const char* attributeValue) {
	return setAttributeValue(attributeName, attributeValue,(uint32_t)strlen(attributeValue));
}

//---------------------------------------------------------------------------------------------------
int DeviceController::setAttributeValue(string& attributeName, const char* attributeValue, uint32_t size) {
	CDataWrapper attributeValuePack;
	const char *attrname=attributeName.c_str();

	if(attributeTypeMap.find(attributeName) == attributeTypeMap.end() )
		return ErrorCode::EC_ATTRIBUTE_NOT_FOUND;

	if(attributeDirectionMap[attributeName]==DataType::Output)
		return ErrorCode::EC_ATTRIBUTE_BAD_DIR;

	switch (attributeTypeMap[attributeName]) {
		case DataType::TYPE_INT64:
			attributeValuePack.addInt64Value(attrname, boost::lexical_cast<int64_t>(attributeValue));
			return deviceChannel->setAttributeValue(attributeValuePack,millisecToWait);

		case DataType::TYPE_INT32:
			attributeValuePack.addInt32Value(attrname, boost::lexical_cast<int32_t>(attributeValue));
			return deviceChannel->setAttributeValue(attributeValuePack,millisecToWait);

		case DataType::TYPE_DOUBLE:
			attributeValuePack.addDoubleValue(attrname, boost::lexical_cast<double>(attributeValue));
			return deviceChannel->setAttributeValue(attributeValuePack,millisecToWait);

		case DataType::TYPE_BYTEARRAY:
			attributeValuePack.addBinaryValue(attrname,attributeValue,size);
			return deviceChannel->setAttributeValue(attributeValuePack,millisecToWait);

		case DataType::TYPE_STRING:
			attributeValuePack.addStringValue(attrname,attributeValue);
			return deviceChannel->setAttributeValue(attributeValuePack,millisecToWait);
		default:
			break;
	};
	return ErrorCode::EC_ATTRIBUTE_TYPE_NOT_SUPPORTED;
}

//---------------------------------------------------------------------------------------------------
void DeviceController::initializeAttributeIndexMap() {
	boost::recursive_mutex::scoped_lock lock(trackMutext);
	vector<string> attributeNames;
	RangeValueInfo attributerangeInfo;

	attributeTypeMap.clear();
	attributeDirectionMap.clear();

	//get all attribute name from db
	datasetDB.getDatasetAttributesName(DataType::Input, attributeNames);
	for (vector<string>::iterator iter = attributeNames.begin();
		 iter != attributeNames.end();
		 iter++) {

		datasetDB.getAttributeRangeValueInfo(*iter, attributerangeInfo);
		attributeDirectionMap.insert(make_pair(*iter, (DataType::DataSetAttributeIOAttribute)DataType::Input));
		attributeTypeMap.insert(make_pair(*iter, (DataType::DataType)attributerangeInfo.valueType));
	}

	attributeNames.clear();
	datasetDB.getDatasetAttributesName(DataType::Output, attributeNames);
	for (vector<string>::iterator iter = attributeNames.begin();
		 iter != attributeNames.end();
		 iter++) {

		datasetDB.getAttributeRangeValueInfo(*iter, attributerangeInfo);
		attributeDirectionMap.insert(make_pair(*iter, (DataType::DataSetAttributeIOAttribute)DataType::Output));
		attributeTypeMap.insert(make_pair(*iter, (DataType::DataType)attributerangeInfo.valueType));
	}

}

//---------------------------------------------------------------------------------------------------
void DeviceController::allocateNewLiveBufferForAttributeAndType(string& attributeName,
																DataType::DataSetAttributeIOAttribute attributeDirection,
																DataType::DataType attrbiuteType) {
	boost::recursive_mutex::scoped_lock  lock(trackMutext);
	if(attributeDirection == DataType::Output ||
	   attributeDirection == DataType::Bidirectional ){

		switch (attributeTypeMap[attributeName]) {

			case DataType::TYPE_INT32:{
				chaos::SingleBufferCircularBuffer<int32_t> *newBuffer = new chaos::SingleBufferCircularBuffer<int32_t>(30);
				int32AttributeLiveBuffer.insert(make_pair(attributeName, newBuffer));
			}
				break;

			case DataType::TYPE_INT64:{
				chaos::SingleBufferCircularBuffer<int64_t> *newBuffer = new chaos::SingleBufferCircularBuffer<int64_t>(30);
				int64AttributeLiveBuffer.insert(make_pair(attributeName, newBuffer));
			}
				break;

			case DataType::TYPE_DOUBLE:{
				chaos::SingleBufferCircularBuffer<double_t> *newBuffer = new chaos::SingleBufferCircularBuffer<double_t>(30);
				doubleAttributeLiveBuffer.insert(make_pair(attributeName, newBuffer));
			}
				break;
			case DataType::TYPE_BYTEARRAY:{
				chaos::PointerBuffer *newBuffer = new chaos::PointerBuffer();
				pointerAttributeLiveBuffer.insert(make_pair(attributeName, newBuffer));
			}
				break;
		}
	} else if(attributeDirection == DataType::Input ||
			  attributeDirection == DataType::Bidirectional ){

	}

}

//---------------------------------------------------------------------------------------------------
chaos::DataBuffer *DeviceController::getBufferForAttribute(string& attributeName) {
	boost::recursive_mutex::scoped_lock lock(trackMutext);
	chaos::DataBuffer * result = NULL;
	//allocate attribute traccking
	if(attributeTypeMap.count(attributeName) == 0 || attributeDirectionMap.count(attributeName) == 0 ) return result;

	switch (attributeTypeMap[attributeName]) {
		case DataType::TYPE_INT32:
			result = int32AttributeLiveBuffer[attributeName];
			break;

		case DataType::TYPE_INT64:
			result = int64AttributeLiveBuffer[attributeName];
			break;

		case DataType::TYPE_DOUBLE:
			result = doubleAttributeLiveBuffer[attributeName];
			break;
	}
	return result;
}

//---------------------------------------------------------------------------------------------------
chaos::PointerBuffer *DeviceController::getPtrBufferForAttribute(string& attributeName) {
	boost::recursive_mutex::scoped_lock lock(trackMutext);
	chaos::PointerBuffer * result = NULL;
	//allocate attribute traccking
	if(attributeTypeMap.count(attributeName) == 0 || attributeDirectionMap.count(attributeName) == 0 ) return result;

	switch (attributeTypeMap[attributeName]) {
		case DataType::TYPE_BYTEARRAY:
			result = pointerAttributeLiveBuffer[attributeName];
			break;
		default:
			break;
	}
	return result;
}

//---------------------------------------------------------------------------------------------------
chaos::DataBuffer *DeviceController::getPtrBufferForTimestamp(const int initialDimension) {
	return int64AttributeLiveBuffer.count(DataPackCommonKey::DPCK_TIMESTAMP)>0? int64AttributeLiveBuffer[DataPackCommonKey::DPCK_TIMESTAMP]:NULL;
}

//---------------------------------------------------------------------------------------------------
void DeviceController::deinitializeAttributeIndexMap() {
	//boost::recursive_mutex::scoped_lock lock(trackMutext);
	//dispose circula buffer
	for (std::map<string,  chaos::SingleBufferCircularBuffer<int32_t> *>::iterator iter = int32AttributeLiveBuffer.begin();
		 iter != int32AttributeLiveBuffer.end();
		 iter++) {
		delete(iter->second);
	}
	int32AttributeLiveBuffer.clear();

	for (std::map<string,  chaos::SingleBufferCircularBuffer<int64_t> *>::iterator iter = int64AttributeLiveBuffer.begin();
		 iter != int64AttributeLiveBuffer.end();
		 iter++) {
		delete(iter->second);
	}
	int64AttributeLiveBuffer.clear();

	for (std::map<string,  chaos::SingleBufferCircularBuffer<double_t> *>::iterator iter = doubleAttributeLiveBuffer.begin();
		 iter != doubleAttributeLiveBuffer.end();
		 iter++) {
		delete(iter->second);
	}
	doubleAttributeLiveBuffer.clear();

	for (std::map<string,  PointerBuffer*>::iterator iter = pointerAttributeLiveBuffer.begin();
		 iter != pointerAttributeLiveBuffer.end();
		 iter++) {
		delete(iter->second);
	}
	pointerAttributeLiveBuffer.clear();
}

//---------------------------------------------------------------------------------------------------
void DeviceController::addAttributeToTrack(string& attrbiuteName) {
	boost::recursive_mutex::scoped_lock lock(trackMutext);

	//add attribute name to list of tracking attribute
	trackingAttribute.push_back(attrbiuteName);

	//allocate attribute traccking
	if(attributeTypeMap.count(attrbiuteName) == 0 || attributeDirectionMap.count(attrbiuteName) == 0 ) return;

	//allcoate the buffer for the new attribute to track
	allocateNewLiveBufferForAttributeAndType(attrbiuteName, attributeDirectionMap[attrbiuteName], attributeTypeMap[attrbiuteName]);
}

//---------------------------------------------------------------------------------------------------
CDataWrapper * DeviceController::getLiveCDataWrapperPtr() {
	return current_output_dataset.get();
}

//---------------------------------------------------------------------------------------------------
CDataWrapper * DeviceController::getCurrentDatasetForDomain(DatasetDomain domain) {
	CDataWrapper *result = NULL;
	switch(domain) {
		case DatasetDomainOutput:
			result = current_output_dataset.get();
			break;
		case DatasetDomainInput:
			result = current_input_dataset.get();
			break;
		case DatasetDomainCustom:
			result = current_custom_dataset.get();
			break;
		case DatasetDomainSystem:
			result = current_system_dataset.get();
			break;
	}
	return result;
}

//---------------------------------------------------------------------------------------------------
void DeviceController::fetchCurrentDatatasetFromDomain(DatasetDomain domain) {
	CHAOS_ASSERT(ioLiveDataDriver)
	char *value = NULL;
	unsigned long value_len = 0;
	switch(domain) {
		case DatasetDomainOutput:
		  value = ioLiveDataDriver->retriveRawData(output_key, (size_t*)&value_len);
			//check if some value has bee fetcher
			if(!value) return;
			current_output_dataset.reset(new CDataWrapper(value));
			break;
		case DatasetDomainInput:
			value = ioLiveDataDriver->retriveRawData(input_key, (size_t*)&value_len);
			//check if some value has bee fetcher
			if(!value) return;
			current_input_dataset.reset(new CDataWrapper(value));
			break;
		case DatasetDomainCustom:
			value = ioLiveDataDriver->retriveRawData(custom_key, (size_t*)&value_len);
			//check if some value has bee fetcher
			if(!value) return;
			current_custom_dataset.reset(new CDataWrapper(value));
			break;
		case DatasetDomainSystem:
			value = ioLiveDataDriver->retriveRawData(system_key, (size_t*)&value_len);
			//check if some value has bee fetcher
			if(!value) return;
			current_system_dataset.reset(new CDataWrapper(value));
			break;
		default:
			return;
	}
	free(value);
}

//---------------------------------------------------------------------------------------------------
int DeviceController::getTimeStamp(uint64_t& live){
	CDataWrapper * d= current_output_dataset.get();
	if(d){
		live = d->getInt64Value(DataPackCommonKey::DPCK_TIMESTAMP);
		return 0;
	}
	return -1;
}
//---------------------------------------------------------------------------------------------------
void DeviceController::setupTracking() {
	boost::recursive_mutex::scoped_lock lock(trackMutext);

	//init live buffer
	initializeAttributeIndexMap();

	//initialize timestamp buffer
	chaos::SingleBufferCircularBuffer<int64_t> *newBuffer = new chaos::SingleBufferCircularBuffer<int64_t>(10);
	int64AttributeLiveBuffer.insert(make_pair(DataPackCommonKey::DPCK_TIMESTAMP, newBuffer));
}

//---------------------------------------------------------------------------------------------------
void DeviceController::stopTracking() {
	boost::recursive_mutex::scoped_lock lock(trackMutext);
	deinitializeAttributeIndexMap();
}

//---------------------------------------------------------------------------------------------------
void DeviceController::fetchCurrentDeviceValue() {
	boost::recursive_mutex::scoped_lock lock(trackMutext);

	//! fetch the output odmain
	fetchCurrentDatatasetFromDomain(DatasetDomainOutput);

	if(trackingAttribute.size() == 0) return;
	CDataWrapper *tmpPtr = current_output_dataset.get();

	//add timestamp value
	int64_t got_ts = tmpPtr->getInt64Value(DataPackCommonKey::DPCK_TIMESTAMP);
	if(int64AttributeLiveBuffer[DataPackCommonKey::DPCK_TIMESTAMP]->getLastValue() == got_ts) return;

	int64AttributeLiveBuffer[DataPackCommonKey::DPCK_TIMESTAMP]->addValue(got_ts);

	//update buffer for tracked attribute
	for (std::vector<string>::iterator iter = trackingAttribute.begin();
		 iter != trackingAttribute.end();
		 iter++) {
		const char *key = (*iter).c_str();
		if(!tmpPtr->hasKey(key)) continue;

		switch (attributeTypeMap[*iter]) {
			case DataType::TYPE_INT32:
				int32AttributeLiveBuffer[*iter]->addValue(tmpPtr->getInt32Value(key));
				break;

			case DataType::TYPE_INT64:
				int64AttributeLiveBuffer[*iter]->addValue(tmpPtr->getInt64Value(key));
				break;

			case DataType::TYPE_DOUBLE:
				doubleAttributeLiveBuffer[*iter]->addValue(tmpPtr->getDoubleValue(key));
				break;

			case DataType::TYPE_BYTEARRAY:
				int32_t ptrLen = 0;
				const char * tmpPtrAttribute = tmpPtr->getBinaryValue(key, ptrLen);
				pointerAttributeLiveBuffer[*iter]->updateData(tmpPtrAttribute, ptrLen);
				break;
		}
	}
}

CDataWrapper *DeviceController::getCurrentData(){
	return current_output_dataset.get();
}
/*!
 Set the handler for all answer received by the device
 */
void DeviceController::setHandler(MessageHandler async_handler) {
	if(!deviceChannel) return;
	deviceChannel->setHandler(async_handler);
}

/*!
 Remove the handler for all answer received by the device
 */
void DeviceController::clearHandler() {
	if(!deviceChannel) return;
	deviceChannel->clearHandler();
}

//! get datapack between time itervall
void DeviceController::executeTimeIntervallQuery(uint64_t start_ts, uint64_t end_ts, chaos_io::QueryFuture **query_future) {
	*query_future = ioLiveDataDriver->performQuery(device_id, start_ts, end_ts);
}

//! release a query
void DeviceController::releaseQuery(chaos_io::QueryFuture *query_future) {
	ioLiveDataDriver->releaseQuery(query_future);
}


text:
/**
    Definitions of functions wrapping lapack.
    Declarations depends on compilations options PROXTV_USE_LAPACK

    @author Pablo Hernandez-Cerdan
*/

#include "lapackFunctionsWrap.h"

#ifndef PROXTV_USE_LAPACK // USE_EIGEN
#include <Eigen/Dense>
void dpttrf_plus_dpttrs_eigen( lapack_int* n, double* d, double* e, double *b)
{
    using EigenMatrix = Eigen::MatrixXd;
    using EigenVector = Eigen::VectorXd;
    using EigenVectorMap = Eigen::Map<EigenVector>;
    // Eigen has to create the full matrix from the diagonal d and subdiagonal e
    int mSize = *n;
    EigenMatrix eigenM(mSize,mSize);
    EigenVectorMap diag(d, mSize);
    EigenVectorMap subAndUpperDiag(e, mSize - 1);
    EigenVectorMap inputB_outputX(b, mSize);
    // Populate matrix
    eigenM.diagonal() = diag;
    eigenM.diagonal( 1) = subAndUpperDiag;
    eigenM.diagonal(-1) = subAndUpperDiag;

    // Factorize using ldlt (ldl is also possible, faster but less accurate)
    // A = LDL'
    Eigen::LDLT<EigenMatrix> factorization(eigenM);
    // A*X = b
    // This modifies the input/output pointer: b
    inputB_outputX = factorization.solve(inputB_outputX);
    // This modifies the input/output pointers: d and e
    EigenMatrix factorized = factorization.matrixLDLT();
    diag = factorized.diagonal();
    subAndUpperDiag = factorized.diagonal(-1);
}
#endif

max_stars_repo_name: dzenanz/proxTV

max_issues_repo_name: dzenanz/proxTV

max_forks_repo_name: dzenanz/proxTV


text:
#if not defined BEASTHTTP_REACTOR_IMPL_LISTENER_HXX
#define BEASTHTTP_REACTOR_IMPL_LISTENER_HXX

#include <http/base/config.hxx>

#include <boost/asio/post.hpp>

#define BEASTHTTP_REACTOR_LISTENER_TMPL_DECLARE \
    template<template<typename> class OnAccept, \
    template<typename> class OnError, \
    class Protocol, \
    class Acceptor, \
    class Socket, \
    template<typename> class Endpoint>

namespace _0xdead4ead {
namespace http {
namespace reactor {

BEASTHTTP_REACTOR_LISTENER_TMPL_DECLARE
template<class... _OnAction>
auto
listener<BEASTHTTP_REACTOR_LISTENER_TMPL_ATTRIBUTES>::launch(
        boost::asio::io_context& ctx, const endpoint_type& endpoint, _OnAction&&... on_action) -> decltype (
        void(self_type(std::declval<boost::asio::io_context&>(), std::declval<_OnAction>()...)))
{
#if BEASTHTTP_USE_MAKE_SHARED == 0
    using Alloc = std::allocator<self_type>;

    Alloc a = Alloc();

    std::shared_ptr<self_type>(new (std::allocator_traits<Alloc>::allocate(a, 1)) self_type(
                ctx, std::forward<_OnAction>(on_action)...))->loop(endpoint);
#else
    std::make_shared<self_type>(ctx, std::forward<_OnAction>(on_action)...)->loop(endpoint);
#endif // BEASTHTTP_USE_MAKE_SHARED == 0
}

BEASTHTTP_REACTOR_LISTENER_TMPL_DECLARE
template<class... _OnAction>
auto
listener<BEASTHTTP_REACTOR_LISTENER_TMPL_ATTRIBUTES>::launch(
        boost::asio::io_context& acceptor_ctx, boost::asio::io_context& socket_ctx,
     const endpoint_type& endpoint, _OnAction&&... on_action) -> decltype (
        void(self_type(std::declval<boost::asio::io_context&>(),
                       std::declval<boost::asio::io_context&>(), std::declval<_OnAction>()...)))
{
#if BEASTHTTP_USE_MAKE_SHARED == 0
    using Alloc = std::allocator<self_type>;

    Alloc a = Alloc();

    std::shared_ptr<self_type>(new (std::allocator_traits<Alloc>::allocate(a, 1)) self_type(
                acceptor_ctx, socket_ctx, std::forward<_OnAction>(on_action)...))->loop(endpoint);
#else
    std::make_shared<self_type>(acceptor_ctx, socket_ctx, std::forward<_OnAction>(on_action)...)->loop(endpoint);
#endif // BEASTHTTP_USE_MAKE_SHARED == 0
}

BEASTHTTP_REACTOR_LISTENER_TMPL_DECLARE
template<class Deleter, class Allocator, class... _OnAction>
auto
listener<BEASTHTTP_REACTOR_LISTENER_TMPL_ATTRIBUTES>::launch(
        boost::asio::io_context& ctx, const Deleter& d, const Allocator& alloc, const endpoint_type& endpoint,
        _OnAction&&... on_action) -> decltype (
        void(self_type(std::declval<boost::asio::io_context&>(), std::declval<_OnAction>()...)))
{
    using Alloc = typename std::allocator_traits<Allocator>::template rebind_alloc<self_type>;

    Alloc a = Alloc(alloc);

    std::shared_ptr<self_type>(new (std::allocator_traits<Alloc>::allocate(a, 1)) self_type(
                ctx, std::forward<_OnAction>(on_action)...), d, alloc)->loop(endpoint);
}

BEASTHTTP_REACTOR_LISTENER_TMPL_DECLARE
template<class Deleter, class Allocator, class... _OnAction>
auto
listener<BEASTHTTP_REACTOR_LISTENER_TMPL_ATTRIBUTES>::launch(
        boost::asio::io_context& acceptor_ctx, boost::asio::io_context& socket_ctx,
        const Deleter& d, const Allocator& alloc, const endpoint_type& endpoint, _OnAction&&... on_action) -> decltype (
        void(self_type(std::declval<boost::asio::io_context&>(),
                       std::declval<boost::asio::io_context&>(), std::declval<_OnAction>()...)))
{
    using Alloc = typename std::allocator_traits<Allocator>::template rebind_alloc<self_type>;

    Alloc a = Alloc(alloc);

    std::shared_ptr<self_type>(new (std::allocator_traits<Alloc>::allocate(a, 1)) self_type(
                acceptor_ctx, socket_ctx, std::forward<_OnAction>(on_action)...), d, alloc)
            ->loop(endpoint);
}

BEASTHTTP_REACTOR_LISTENER_TMPL_DECLARE
template<class _OnAccept>
listener<BEASTHTTP_REACTOR_LISTENER_TMPL_ATTRIBUTES>::listener(
        boost::asio::io_context& ctx, _OnAccept&& on_accept,
        typename std::enable_if<base::traits::TryInvoke<
        _OnAccept, void(socket_type)>::value, int>::type)
    : base::strand_stream{ctx.get_executor()},
      acceptor_{ctx},
      socket_ctx_{ctx},
      on_accept_{std::forward<_OnAccept>(on_accept)}
{
}

BEASTHTTP_REACTOR_LISTENER_TMPL_DECLARE
template<class _OnAccept, class _OnError>
listener<BEASTHTTP_REACTOR_LISTENER_TMPL_ATTRIBUTES>::listener(
        boost::asio::io_context& ctx, _OnAccept&& on_accept, _OnError&& on_error,
        typename std::enable_if<base::traits::TryInvoke<
        _OnAccept, void(socket_type)>::value and
        base::traits::TryInvoke<_OnError, void(
            boost::system::error_code, boost::string_view)>::value, int>::type)
    : base::strand_stream{ctx.get_executor()},
      acceptor_{ctx},
      socket_ctx_{ctx},
      on_accept_{std::forward<_OnAccept>(on_accept)},
      on_error_{std::forward<_OnError>(on_error)}
{
}

BEASTHTTP_REACTOR_LISTENER_TMPL_DECLARE
template<class _OnAccept>
listener<BEASTHTTP_REACTOR_LISTENER_TMPL_ATTRIBUTES>::listener(
        boost::asio::io_context& acceptor_ctx, boost::asio::io_context& socket_ctx, _OnAccept&& on_accept,
        typename std::enable_if<base::traits::TryInvoke<
        _OnAccept, void(socket_type)>::value, int>::type)
    : base::strand_stream{acceptor_ctx.get_executor()},
      acceptor_{acceptor_ctx},
      socket_ctx_{socket_ctx},
      on_accept_{std::forward<_OnAccept>(on_accept)}
{
}

BEASTHTTP_REACTOR_LISTENER_TMPL_DECLARE
template<class _OnAccept, class _OnError>
listener<BEASTHTTP_REACTOR_LISTENER_TMPL_ATTRIBUTES>::listener(
        boost::asio::io_context& acceptor_ctx, boost::asio::io_context& socket_ctx, _OnAccept&& on_accept, _OnError&& on_error,
        typename std::enable_if<base::traits::TryInvoke<
        _OnAccept, void(socket_type)>::value and
        base::traits::TryInvoke<_OnError, void(
            boost::system::error_code, boost::string_view)>::value, int>::type)
    : base::strand_stream{acceptor_ctx.get_executor()},
      acceptor_{acceptor_ctx},
      socket_ctx_{socket_ctx},
      on_accept_{std::forward<_OnAccept>(on_accept)},
      on_error_{std::forward<_OnError>(on_error)}
{
}

BEASTHTTP_REACTOR_LISTENER_TMPL_DECLARE
void
listener<BEASTHTTP_REACTOR_LISTENER_TMPL_ATTRIBUTES>::on_spawn_connect(boost::system::error_code ec, socket_type& socket)
{
    if (ec) {
        if (on_error_)
            on_error_(ec, "accept/do_loop");

        return;
    }

    on_accept_(std::move(socket));
}

BEASTHTTP_REACTOR_LISTENER_TMPL_DECLARE
void
listener<BEASTHTTP_REACTOR_LISTENER_TMPL_ATTRIBUTES>::on_accept(boost::system::error_code ec, socket_type socket)
{
    boost::asio::post(static_cast<base::strand_stream&>(*this),
                      std::bind(&self_type::on_spawn_connect, this->shared_from_this(), ec, std::move(socket)));

    do_accept();
}

BEASTHTTP_REACTOR_LISTENER_TMPL_DECLARE
void
listener<BEASTHTTP_REACTOR_LISTENER_TMPL_ATTRIBUTES>::loop(
        const endpoint_type& endpoint)
{
    auto ec = boost::system::error_code{};

    acceptor_.open(endpoint.protocol(), ec);
    if (ec) {
        if (on_error_)
            on_error_(ec, "open/loop");

        return;
    }
#ifdef _WIN32
    typedef boost::asio::detail::socket_option::boolean<BOOST_ASIO_OS_DEF(SOL_SOCKET), SO_EXCLUSIVEADDRUSE> exclusive_address_use;
    acceptor_.set_option(exclusive_address_use(true), ec);
#else
    acceptor_.set_option(boost::asio::socket_base::reuse_address(true), ec);
#endif
    if (ec) {
        if (on_error_)
            on_error_(ec, "set_option/loop");

        return;
    }

    acceptor_.bind(endpoint, ec);
    if (ec) {
        if (on_error_)
            on_error_(ec, "bind/loop");

        return;
    }

    acceptor_.listen(
        boost::asio::socket_base::max_listen_connections, ec);
    if (ec) {
        if (on_error_)
            on_error_(ec, "listen/loop");

        return;
    }

    endpoint_ = endpoint;

    do_accept();
}

BEASTHTTP_REACTOR_LISTENER_TMPL_DECLARE
void
listener<BEASTHTTP_REACTOR_LISTENER_TMPL_ATTRIBUTES>::do_accept()
{
    acceptor_.async_accept(socket_ctx_,
                           std::bind(
                               &self_type::on_accept,
                               this->shared_from_this(),
                               std::placeholders::_1,
                               std::placeholders::_2));
}

} // namespace reactor
} // namespace http
} // namespace _0xdead4ead

#endif // not defined BEASTHTTP_REACTOR_IMPL_LISTENER_HXX

ext: hxx


text:
/*
 *  Copyright (c) 2014, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */

#include <csignal>

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

#include <osquery/events.h>
#include <osquery/filesystem.h>
#include <osquery/logger.h>
#include <osquery/registry.h>
#include <osquery/sql.h>

#include "osquery/extensions/interface.h"
#include "osquery/core/watcher.h"

using namespace osquery::extensions;

namespace fs = boost::filesystem;

namespace osquery {

// Millisecond latency between initalizing manager pings.
const size_t kExtensionInitializeLatencyUS = 20000;

#ifdef __APPLE__
const std::string kModuleExtension = ".dylib";
#else
const std::string kModuleExtension = ".so";
#endif

CLI_FLAG(bool, disable_extensions, false, "Disable extension API");

CLI_FLAG(string,
         extensions_socket,
         "/var/osquery/osquery.em",
         "Path to the extensions UNIX domain socket")

CLI_FLAG(string,
         extensions_autoload,
         "/etc/osquery/extensions.load",
         "Optional path to a list of autoloaded & managed extensions")

CLI_FLAG(string,
         extensions_timeout,
         "3",
         "Seconds to wait for autoloaded extensions");

CLI_FLAG(string,
         extensions_interval,
         "3",
         "Seconds delay between connectivity checks")

CLI_FLAG(string,
         modules_autoload,
         "/etc/osquery/modules.load",
         "Optional path to a list of autoloaded registry modules")

/**
 * @brief Alias the extensions_socket (used by core) to a simple 'socket'.
 *
 * Extension binaries will more commonly set the path to an extension manager
 * socket. Alias the long switch name to 'socket' for an easier UX.
 *
 * We include timeout and interval, where the 'extensions_' prefix is removed
 * in the alias since we are already within the context of an extension.
 */
EXTENSION_FLAG_ALIAS(socket, extensions_socket);
EXTENSION_FLAG_ALIAS(timeout, extensions_timeout);
EXTENSION_FLAG_ALIAS(interval, extensions_interval);

void ExtensionWatcher::start() {
  // Watch the manager, if the socket is removed then the extension will die.
  while (true) {
    watch();
    interruptableSleep(interval_);
  }
}

void ExtensionWatcher::exitFatal(int return_code) {
  // Exit the extension.
  ::exit(return_code);
}

void ExtensionWatcher::watch() {
  ExtensionStatus status;
  try {
    auto client = EXManagerClient(path_);
    // Ping the extension manager until it goes down.
    client.get()->ping(status);
  } catch (const std::exception& e) {
    LOG(WARNING) << "Extension watcher ending: osquery core has gone away";
    exitFatal(0);
  }

  if (status.code != ExtensionCode::EXT_SUCCESS && fatal_) {
    exitFatal();
  }
}

void ExtensionManagerWatcher::watch() {
  // Watch the set of extensions, if the socket is removed then the extension
  // will be deregistered.
  const auto uuids = Registry::routeUUIDs();

  ExtensionStatus status;
  for (const auto& uuid : uuids) {
    try {
      auto client = EXClient(getExtensionSocket(uuid));
      // Ping the extension until it goes down.
      client.get()->ping(status);
    } catch (const std::exception& e) {
      failures_[uuid] += 1;
      continue;
    }

    if (status.code != ExtensionCode::EXT_SUCCESS) {
      LOG(INFO) << "Extension UUID " << uuid << " ping failed";
      failures_[uuid] += 1;
    } else {
      failures_[uuid] = 0;
    }
  }

  for (const auto& uuid : failures_) {
    if (uuid.second >= 3) {
      LOG(INFO) << "Extension UUID " << uuid.first << " has gone away";
      Registry::removeBroadcast(uuid.first);
      failures_[uuid.first] = 0;
    }
  }
}

inline Status socketWritable(const fs::path& path) {
  if (pathExists(path).ok()) {
    if (!isWritable(path).ok()) {
      return Status(1, "Cannot write extension socket: " + path.string());
    }

    if (!remove(path).ok()) {
      return Status(1, "Cannot remove extension socket: " + path.string());
    }
  } else {
    if (!pathExists(path.parent_path()).ok()) {
      return Status(1, "Extension socket directory missing: " + path.string());
    }

    if (!isWritable(path.parent_path()).ok()) {
      return Status(1, "Cannot write extension socket: " + path.string());
    }
  }
  return Status(0, "OK");
}

void loadExtensions() {
  // Disabling extensions will disable autoloading.
  if (FLAGS_disable_extensions) {
    return;
  }

  // Optionally autoload extensions
  auto status = loadExtensions(FLAGS_extensions_autoload);
  if (!status.ok()) {
    VLOG(1) << "Could not autoload extensions: " << status.what();
  }
}

void loadModules() {
  auto status = loadModules(FLAGS_modules_autoload);
  if (!status.ok()) {
    VLOG(1) << "Could not autoload modules: " << status.what();
  }
}

Status loadExtensions(const std::string& loadfile) {
  std::string autoload_paths;
  if (readFile(loadfile, autoload_paths).ok()) {
    for (auto& path : osquery::split(autoload_paths, "\n")) {
      boost::trim(path);
      if (path.size() > 0 && path[0] != '#' && path[0] != ';') {
        Watcher::addExtensionPath(path);
      }
    }
    return Status(0, "OK");
  }
  return Status(1, "Failed reading: " + loadfile);
}

Status loadModuleFile(const std::string& path) {
  fs::path module(path);
  if (safePermissions(module.parent_path().string(), path)) {
    if (module.extension().string() == kModuleExtension) {
      // Silently allow module load failures to drop.
      RegistryModuleLoader loader(module.string());
      loader.init();
      return Status(0, "OK");
    }
  }
  return Status(1, "Module check failed");
}

Status loadModules(const std::string& loadfile) {
  // Split the search path for modules using a ':' delimiter.
  std::string autoload_paths;
  if (readFile(loadfile, autoload_paths).ok()) {
    auto status = Status(0, "OK");
    for (auto& module_path : osquery::split(autoload_paths, "\n")) {
      boost::trim(module_path);
      auto path_status = loadModuleFile(module_path);
      if (!path_status.ok()) {
        status = path_status;
      }
    }
    // Return an aggregate failure if any load fails (invalid search path).
    return status;
  }
  return Status(1, "Failed reading: " + loadfile);
}

Status extensionPathActive(const std::string& path, bool use_timeout = false) {
  // Make sure the extension manager path exists, and is writable.
  size_t delay = 0;
  // The timeout is given in seconds, but checked interval is microseconds.
  size_t timeout = atoi(FLAGS_extensions_timeout.c_str()) * 1000000;
  if (timeout < kExtensionInitializeLatencyUS * 10) {
    timeout = kExtensionInitializeLatencyUS * 10;
  }
  do {
    if (pathExists(path) && isWritable(path)) {
      try {
        auto client = EXManagerClient(path);
        return Status(0, "OK");
      } catch (const std::exception& e) {
        // Path might exist without a connected extension or extension manager.
      }
    }
    // Only check active once if this check does not allow a timeout.
    if (!use_timeout || timeout == 0) {
      break;
    }
    // Increase the total wait detail.
    delay += kExtensionInitializeLatencyUS;
    ::usleep(kExtensionInitializeLatencyUS);
  } while (delay < timeout);
  return Status(1, "Extension socket not available: " + path);
}

Status startExtension(const std::string& name, const std::string& version) {
  return startExtension(name, version, "0.0.0");
}

Status startExtension(const std::string& name,
                      const std::string& version,
                      const std::string& min_sdk_version) {
  Registry::setExternal();
  // Latency converted to milliseconds, used as a thread interruptible.
  auto latency = atoi(FLAGS_extensions_interval.c_str()) * 1000;
  auto status = startExtensionWatcher(FLAGS_extensions_socket, latency, true);
  if (!status.ok()) {
    // If the threaded watcher fails to start, fail the extension.
    return status;
  }

  status = startExtension(
      FLAGS_extensions_socket, name, version, min_sdk_version, kSDKVersion);
  if (!status.ok()) {
    // If the extension failed to start then the EM is most likely unavailable.
    return status;
  }

  try {
    // The extension does nothing but serve the thrift API.
    // Join on both the thrift and extension manager watcher services.
    Dispatcher::joinServices();
  } catch (const std::exception& e) {
    // The extension manager may shutdown without notifying the extension.
    return Status(0, e.what());
  }

  // An extension will only return on failure.
  return Status(0, "Extension was shutdown");
}

Status startExtension(const std::string& manager_path,
                      const std::string& name,
                      const std::string& version,
                      const std::string& min_sdk_version,
                      const std::string& sdk_version) {
  // Make sure the extension manager path exists, and is writable.
  auto status = extensionPathActive(manager_path, true);
  if (!status.ok()) {
    return status;
  }

  // The Registry broadcast is used as the ExtensionRegistry.
  auto broadcast = Registry::getBroadcast();
  // The extension will register and provide name, version, sdk details.
  InternalExtensionInfo info;
  info.name = name;
  info.version = version;
  info.sdk_version = sdk_version;
  info.min_sdk_version = min_sdk_version;

  // If registration is successful, we will also request the manager's options.
  InternalOptionList options;
  // Register the extension's registry broadcast with the manager.
  ExtensionStatus ext_status;
  try {
    auto client = EXManagerClient(manager_path);
    client.get()->registerExtension(ext_status, info, broadcast);
    // The main reason for a failed registry is a duplicate extension name
    // (the extension process is already running), or the extension broadcasts
    // a duplicate registry item.
    if (ext_status.code != ExtensionCode::EXT_SUCCESS) {
      return Status(ext_status.code, ext_status.message);
    }
    // Request the core options, mainly to set the active registry plugins for
    // logger and config.
    client.get()->options(options);
  } catch (const std::exception& e) {
    return Status(1, "Extension register failed: " + std::string(e.what()));
  }

  // Now that the uuid is known, try to clean up stale socket paths.
  auto extension_path = getExtensionSocket(ext_status.uuid, manager_path);
  status = socketWritable(extension_path);
  if (!status) {
    return status;
  }

  // Set the active config and logger plugins. The core will arbitrate if the
  // plugins are not available in the extension's local registry.
  Registry::setActive("config", options["config_plugin"].value);
  Registry::setActive("logger", options["logger_plugin"].value);
  // Set up all lazy registry plugins and the active config/logger plugin.
  Registry::setUp();

  // Start the extension's Thrift server
  Dispatcher::addService(
      std::make_shared<ExtensionRunner>(manager_path, ext_status.uuid));
  VLOG(1) << "Extension (" << name << ", " << ext_status.uuid << ", " << version
          << ", " << sdk_version << ") registered";
  return Status(0, std::to_string(ext_status.uuid));
}

Status queryExternal(const std::string& manager_path,
                     const std::string& query,
                     QueryData& results) {
  // Make sure the extension path exists, and is writable.
  auto status = extensionPathActive(manager_path);
  if (!status.ok()) {
    return status;
  }

  ExtensionResponse response;
  try {
    auto client = EXManagerClient(manager_path);
    client.get()->query(response, query);
  } catch (const std::exception& e) {
    return Status(1, "Extension call failed: " + std::string(e.what()));
  }

  for (const auto& row : response.response) {
    results.push_back(row);
  }

  return Status(response.status.code, response.status.message);
}

Status queryExternal(const std::string& query, QueryData& results) {
  return queryExternal(FLAGS_extensions_socket, query, results);
}

Status getQueryColumnsExternal(const std::string& manager_path,
                               const std::string& query,
                               TableColumns& columns) {
  // Make sure the extension path exists, and is writable.
  auto status = extensionPathActive(manager_path);
  if (!status.ok()) {
    return status;
  }

  ExtensionResponse response;
  try {
    auto client = EXManagerClient(manager_path);
    client.get()->getQueryColumns(response, query);
  } catch (const std::exception& e) {
    return Status(1, "Extension call failed: " + std::string(e.what()));
  }

  // Translate response map: {string: string} to a vector: pair(name, type).
  for (const auto& column : response.response) {
    for (const auto& column_detail : column) {
      columns.push_back(make_pair(column_detail.first, column_detail.second));
    }
  }

  return Status(response.status.code, response.status.message);
}

Status getQueryColumnsExternal(const std::string& query,
                               TableColumns& columns) {
  return getQueryColumnsExternal(FLAGS_extensions_socket, query, columns);
}

Status pingExtension(const std::string& path) {
  if (FLAGS_disable_extensions) {
    return Status(1, "Extensions disabled");
  }

  // Make sure the extension path exists, and is writable.
  auto status = extensionPathActive(path);
  if (!status.ok()) {
    return status;
  }

  ExtensionStatus ext_status;
  try {
    auto client = EXClient(path);
    client.get()->ping(ext_status);
  } catch (const std::exception& e) {
    return Status(1, "Extension call failed: " + std::string(e.what()));
  }

  return Status(ext_status.code, ext_status.message);
}

Status getExtensions(ExtensionList& extensions) {
  if (FLAGS_disable_extensions) {
    return Status(1, "Extensions disabled");
  }
  return getExtensions(FLAGS_extensions_socket, extensions);
}

Status getExtensions(const std::string& manager_path,
                     ExtensionList& extensions) {
  // Make sure the extension path exists, and is writable.
  auto status = extensionPathActive(manager_path);
  if (!status.ok()) {
    return status;
  }

  InternalExtensionList ext_list;
  try {
    auto client = EXManagerClient(manager_path);
    client.get()->extensions(ext_list);
  } catch (const std::exception& e) {
    return Status(1, "Extension call failed: " + std::string(e.what()));
  }

  // Add the extension manager to the list called (core).
  extensions[0] = {"core", kVersion, "0.0.0", kSDKVersion};

  // Convert from Thrift-internal list type to RouteUUID/ExtenionInfo type.
  for (const auto& ext : ext_list) {
    extensions[ext.first] = {ext.second.name,
                             ext.second.version,
                             ext.second.min_sdk_version,
                             ext.second.sdk_version};
  }

  return Status(0, "OK");
}

Status callExtension(const RouteUUID uuid,
                     const std::string& registry,
                     const std::string& item,
                     const PluginRequest& request,
                     PluginResponse& response) {
  if (FLAGS_disable_extensions) {
    return Status(1, "Extensions disabled");
  }
  return callExtension(
      getExtensionSocket(uuid), registry, item, request, response);
}

Status callExtension(const std::string& extension_path,
                     const std::string& registry,
                     const std::string& item,
                     const PluginRequest& request,
                     PluginResponse& response) {
  // Make sure the extension manager path exists, and is writable.
  auto status = extensionPathActive(extension_path);
  if (!status.ok()) {
    return status;
  }

  ExtensionResponse ext_response;
  try {
    auto client = EXClient(extension_path);
    client.get()->call(ext_response, registry, item, request);
  }
  catch (const std::exception& e) {
    return Status(1, "Extension call failed: " + std::string(e.what()));
  }

  // Convert from Thrift-internal list type to PluginResponse type.
  if (ext_response.status.code == ExtensionCode::EXT_SUCCESS) {
    for (const auto& item : ext_response.response) {
      response.push_back(item);
    }
  }
  return Status(ext_response.status.code, ext_response.status.message);
}

Status startExtensionWatcher(const std::string& manager_path,
                             size_t interval,
                             bool fatal) {
  // Make sure the extension manager path exists, and is writable.
  auto status = extensionPathActive(manager_path, true);
  if (!status.ok()) {
    return status;
  }

  // Start a extension manager watcher, if the manager dies, so should we.
  Dispatcher::addService(
      std::make_shared<ExtensionWatcher>(manager_path, interval, fatal));
  return Status(0, "OK");
}

Status startExtensionManager() {
  if (FLAGS_disable_extensions) {
    return Status(1, "Extensions disabled");
  }
  return startExtensionManager(FLAGS_extensions_socket);
}

Status startExtensionManager(const std::string& manager_path) {
  // Check if the socket location exists.
  auto status = socketWritable(manager_path);
  if (!status.ok()) {
    return status;
  }

  // Seconds converted to milliseconds, used as a thread interruptible.
  auto latency = atoi(FLAGS_extensions_interval.c_str()) * 1000;
  // Start a extension manager watcher, if the manager dies, so should we.
  Dispatcher::addService(
      std::make_shared<ExtensionManagerWatcher>(manager_path, latency));

  // Start the extension manager thread.
  Dispatcher::addService(
      std::make_shared<ExtensionManagerRunner>(manager_path));
  return Status(0, "OK");
}
}

max_stars_repo_name: eastebry/osquery

max_issues_repo_name: eastebry/osquery

max_forks_repo_name: eastebry/osquery


text:
//  Copyright (c) 2014 Thomas Heller
//  Copyright (c) 2015 Anton Bikineev
//
//  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 HPX_SERIALIZATION_DETAIL_POINTER_HPP
#define HPX_SERIALIZATION_DETAIL_POINTER_HPP

#include <hpx/runtime/serialization/access.hpp>
#include <hpx/runtime/serialization/basic_archive.hpp>
#include <hpx/runtime/serialization/detail/non_default_constructible.hpp>
#include <hpx/runtime/serialization/detail/polymorphic_id_factory.hpp>
#include <hpx/runtime/serialization/detail/polymorphic_intrusive_factory.hpp>
#include <hpx/runtime/serialization/detail/polymorphic_nonintrusive_factory.hpp>
#include <hpx/runtime/serialization/serialization_fwd.hpp>
#include <hpx/runtime/serialization/string.hpp>
#include <hpx/traits/polymorphic_traits.hpp>
#include <hpx/util/identity.hpp>
#include <hpx/util/lazy_conditional.hpp>

#include <boost/intrusive_ptr.hpp>

#include <cstdint>
#include <memory>
#include <string>
#include <type_traits>
#include <utility>

namespace hpx { namespace serialization
{
    namespace detail
    {
        struct ptr_helper;

        typedef std::unique_ptr<ptr_helper> ptr_helper_ptr;
    }

    HPX_FORCEINLINE
        void register_pointer(input_archive & ar, std::uint64_t pos,
            detail::ptr_helper_ptr helper);

    template <typename Helper>
    Helper & tracked_pointer(input_archive & ar, std::uint64_t pos);

    namespace detail
    {
        template <class Pointer>
        struct erase_ptr_helper : ptr_helper
        {
            typedef typename Pointer::element_type referred_type;

            erase_ptr_helper(Pointer&& t, Pointer& ptr)
                : t_(std::move(t))
            {
                ptr = t_;
            }

            Pointer t_;
        };

        template <class Pointer>
        class pointer_input_dispatcher
        {
            typedef typename Pointer::element_type referred_type;

            struct intrusive_polymorphic
            {
                static Pointer call(input_archive& ar)
                {
                    std::string name;
                    ar >> name;

                    Pointer t(polymorphic_intrusive_factory::instance().
                        create<referred_type>(name));
                    ar >> *t;
                    return t;
                }
            };

            struct polymorphic_with_id
            {
                static Pointer call(input_archive& ar)
                {
#if !defined(HPX_DEBUG)
                    std::uint32_t id;
                    ar >> id;

                    Pointer t(polymorphic_id_factory::create<referred_type>(id));
                    ar >> *t;
                    return t;
#else
                    std::uint32_t id;
                    std::string name;
                    ar >> name;
                    ar >> id;

                    Pointer t(
                        polymorphic_id_factory::create<referred_type>(id, &name));
                    ar >> *t;
                    return t;
#endif
                }
            };

            struct nonintrusive_polymorphic
            {
                static Pointer call(input_archive& ar)
                {
                    return Pointer(polymorphic_nonintrusive_factory::
                        instance().load<referred_type>(ar));
                }
            };

            struct usual
            {
                static Pointer call(input_archive& ar)
                {
                    Pointer t(constructor_selector<referred_type>::create(ar));
                    return t;
                }
            };

        public:
            typedef typename util::lazy_conditional<
                hpx::traits::is_serialized_with_id<referred_type>::value,
                hpx::util::identity<polymorphic_with_id>,
                std::conditional<
                    hpx::traits::is_intrusive_polymorphic<referred_type>::value,
                    intrusive_polymorphic,
                    typename std::conditional<
                        hpx::traits::is_nonintrusive_polymorphic<referred_type>::value,
                        nonintrusive_polymorphic,
                        usual
                    >::type
                >
            >::type type;
        };

        template <class Pointer>
        class pointer_output_dispatcher
        {
            typedef typename Pointer::element_type referred_type;

            struct intrusive_polymorphic
            {
                static void call(output_archive& ar, const Pointer& ptr)
                {
                    const std::string name = access::get_name(ptr.get());
                    ar << name;
                    ar << *ptr;
                }
            };

            struct polymorphic_with_id
            {
                static void call(output_archive& ar, const Pointer& ptr)
                {
#if !defined(HPX_DEBUG)
                    const std::uint32_t id =
                        polymorphic_id_factory::get_id(
                            access::get_name(ptr.get()));
                    ar << id;
                    ar << *ptr;
#else
                    std::string const name(access::get_name(ptr.get()));
                    const std::uint32_t id =
                        polymorphic_id_factory::get_id(name);
                    ar << name;
                    ar << id;
                    ar << *ptr;
#endif
                }
            };

            struct usual
            {
                static void call(output_archive& ar, const Pointer& ptr)
                {
                    call(ar, *ptr);
                }

                template <typename T>
                static typename std::enable_if<
                    !std::is_constructible<T>::value
                >::type
                call(output_archive& ar, T const& val)
                {
                    save_construct_data(ar, &val, 0);
                    ar << val;
                }

                template <typename T>
                static typename std::enable_if<
                    std::is_constructible<T>::value
                >::type
                call(output_archive& ar, T const& val)
                {
                    ar << val;
                }
            };

        public:
            typedef typename std::conditional<
                hpx::traits::is_serialized_with_id<referred_type>::value,
                polymorphic_with_id,
                typename std::conditional<
                    hpx::traits::is_intrusive_polymorphic<referred_type>::value,
                    intrusive_polymorphic,
                    usual
                >::type
            >::type type;
        };

        // forwarded serialize pointer functions
        template <typename Pointer> HPX_FORCEINLINE
        void serialize_pointer_tracked(output_archive & ar, const Pointer& ptr)
        {
            bool valid = static_cast<bool>(ptr);
            ar << valid;
            if(valid)
            {
                std::uint64_t cur_pos = current_pos(ar);
                std::uint64_t pos = track_pointer(ar, ptr.get());
                ar << pos;
                if(pos == std::uint64_t(-1))
                {
                    ar << cur_pos;
                    detail::pointer_output_dispatcher<Pointer>::type::call(ar, ptr);
                }
            }
        }

        template <class Pointer> HPX_FORCEINLINE
        void serialize_pointer_tracked(input_archive& ar, Pointer& ptr)
        {
            bool valid = false;
            ar >> valid;
            if(valid)
            {
                std::uint64_t pos = 0;
                ar >> pos;
                if(pos == std::uint64_t(-1))
                {
                    pos = 0;
                    ar >> pos;
                    Pointer temp = detail::pointer_input_dispatcher<
                        Pointer>::type::call(ar);
                    register_pointer(ar, pos, ptr_helper_ptr(
                            new detail::erase_ptr_helper<Pointer>
                                (std::move(temp), ptr)));
                }
                else
                {
                    detail::erase_ptr_helper<Pointer> & helper =
                        tracked_pointer<detail::erase_ptr_helper<Pointer> >(ar, pos);
                    ptr = helper.t_;
                }
            }
        }

        template <typename Pointer> HPX_FORCEINLINE
        void serialize_pointer_untracked(output_archive & ar, const Pointer& ptr)
        {
            bool valid = static_cast<bool>(ptr);
            ar << valid;
            if(valid)
            {
                detail::pointer_output_dispatcher<Pointer>::type::call(ar, ptr);
            }
        }

        template <class Pointer> HPX_FORCEINLINE
        void serialize_pointer_untracked(input_archive& ar, Pointer& ptr)
        {
            bool valid = false;
            ar >> valid;
            if(valid)
            {
                ptr = detail::pointer_input_dispatcher<Pointer>::type::call(ar);
            }
        }

    } // detail
}}

#endif // HPX_SERIALIZATION_DETAIL_POINTER_HPP

max_forks_repo_name: biddisco/hpx


text:
#define BOOST_TEST_MODULE test_vision

#include <boost/test/included/unit_test.hpp>
#include <boost/format.hpp>
#include <goliath/vision.h>

using namespace goliath;

BOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)
    BOOST_AUTO_TEST_CASE(test_webcam_line_following) {
        vision::Webcam camera(0);

        while (true) {
            cv::Mat input = camera.getFrame();
            vision::FollowLineDetector followLineDetector(input, 4, 100, 20, 0, 10, 10000);

            std::vector<cv::Vec4d> output = followLineDetector.detect();

            std::cout << "Direction: " << output[0][0]
                      << " Offset:    " << output[0][1] << std::endl;

        }
    }

    BOOST_AUTO_TEST_CASE(test_webcam_colored_spot) {
        vision::Webcam camera(0, CV_BGR2HSV);
        cv::namedWindow("webcam");

        while (true) {
            cv::Mat input = camera.getFrame();
            vision::ColorRegionDetector colorRegionDetector(input, 150, 200, 50, 100);

            std::cout << colorRegionDetector.detect()[0][0] << std::endl;

            cv::imshow("webcam", input);
            cv::waitKey(1);
        }
    }

BOOST_AUTO_TEST_SUITE_END()