text:
/**
 * Copyright (c) 2022 <Daumantas Kavolis>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#pragma once

#include "config.hpp"

MSVC_WARNING_DISABLE(4619)
#include <boost/container/small_vector.hpp>
#include <boost/range/adaptor/indexed.hpp>
#include <boost/range/size.hpp>
MSVC_WARNING_POP()

#include "polynomial.hpp"
#include "traits.hpp"
#include "utils.hpp"

namespace poly {

template <class Poly>
class PolynomialProductView : public view<Poly> {
 public:
  using Base = view<Poly>;
  using Base::Base;

  using Traits = typename Poly::Traits;
  using Real = typename Traits::Real;
  using OrderType = typename Traits::OrderType;

  // NOLINTNEXTLINE(hicpp-explicit-conversions)
  operator PolynomialProductView<Poly const>() const noexcept {
    return {this->data(), this->size()};
  }

  template <bool check = true, class Range,
            typename = std::enable_if_t<detail::is_range<Range>::value>>
  [[nodiscard]] auto operator()(Range const& x,
                                bounds_check<check> /* unused */ = check_bounds) const -> Real {
    if constexpr (check) {
      if (boost::size(x) != this->size())
        throw std::out_of_range("Dimensions do not match size of polynomials");
    }

    Real y = 1.0;
    for (auto&& [index, xx] : x | boost::adaptors::indexed()) y *= (*this)[index](xx);
    return y;
  }

  template <bool check = true, class Range,
            typename = std::enable_if_t<detail::is_range<Range>::value>>
  void assign(Range const& orders, bounds_check<check> c = check_bounds) const {
    check_size(orders, c);

    for (auto&& [index, order] : orders | boost::adaptors::indexed())
      (*this)[index].order(narrow<OrderType>(order));
  }

  template <bool check = true, class Range,
            typename = std::enable_if_t<detail::is_range<Range>::value>>
  auto matches_orders(Range const& orders, bounds_check<check> c = check_bounds) const -> bool {
    return match(
        orders,
        [](Poly const& poly, auto&& order) {
          return poly.order() == narrow_cast<OrderType>(order);
        },
        c);
  }

  template <bool check = true, class Range,
            typename = std::enable_if_t<detail::is_range<Range>::value>>
  auto matches_zeros(Range const& zeros, bounds_check<check> c = check_bounds) const
      -> std::size_t {
    return match(
        zeros,
        [](Poly const& poly, auto&& is_zero) {
          return (poly.order() == 0) == static_cast<bool>(is_zero);
        },
        c);
  }

  template <bool check = true, class Range,
            typename = std::enable_if_t<detail::is_range<Range>::value>>
  auto matches_non_zeros(Range const& non_zeros, bounds_check<check> c = check_bounds) const
      -> std::size_t {
    return match(
        non_zeros,
        [](Poly const& poly, auto&& is_non_zero) {
          return (poly.order() != 0) == static_cast<bool>(is_non_zero);
        },
        c);
  }

 private:
  template <class Range, bool check, class F>
  auto match(Range const& range, F const& function, bounds_check<check> c = check_bounds) const
      -> bool {
    check_size(range, c);
    for (auto&& [index, value] : range | boost::adaptors::indexed()) {
      if (!function((*this)[index], value)) return false;
    }
    return true;
  }

  template <class Range, bool check>
  void check_size(Range const& range, bounds_check<check> /* unused */ = check_bounds) const {
    if constexpr (check) {
      if (boost::size(range) != this->size())
        throw std::out_of_range("Size of orders does not match size of polynomials");
    }
  }
};

template <typename Poly, std::size_t N = SmallStorageSize>
class PolynomialProduct {
 public:
  using Traits = typename Poly::Traits;
  using Real = typename Traits::Real;
  using OrderType = typename Traits::OrderType;
  using PolynomialType = Poly;
  using View = PolynomialProductView<PolynomialType>;
  using ConstView = PolynomialProductView<PolynomialType const>;

  template <typename T>
  using small_vector = boost::container::small_vector<T, N>;
  using polynomials_vector = small_vector<PolynomialType>;
  using iterator = typename polynomials_vector::iterator;
  using const_iterator = typename polynomials_vector::const_iterator;

  explicit PolynomialProduct(OrderType dimensions) : polynomials_{dimensions} {}

  template <class Range, typename = std::enable_if_t<detail::is_range<Range>::value>>
  explicit PolynomialProduct(Range const& orders) {
    auto count = boost::size(orders);
    polynomials_.resize(count);
    static_cast<View>(*this).assign(orders, no_bounds_check);
  }

  [[nodiscard]] auto polynomials() noexcept -> view<PolynomialType> {
    return {polynomials_.data(), polynomials_.size()};
  }
  [[nodiscard]] auto polynomials() const noexcept -> view<PolynomialType const> {
    return {polynomials_.data(), polynomials_.size()};
  }

  template <class... Args>
  void emplace_back(Args... args) {
    polynomials_.emplace_back(std::forward<Args>(args)...);
  }

  auto operator[](std::size_t index) noexcept -> PolynomialType& { return polynomials_[index]; }
  [[nodiscard]] auto operator[](std::size_t index) const noexcept -> PolynomialType const& {
    return polynomials_[index];
  }

  auto at(std::size_t index) noexcept -> PolynomialType& { return polynomials_.at(index); }
  [[nodiscard]] auto at(std::size_t index) const noexcept -> PolynomialType const& {
    return polynomials_.at(index);
  }

  template <bool check = true, class Range,
            typename = std::enable_if_t<detail::is_range<Range>::value>>
  [[nodiscard]] auto operator()(Range const& x, bounds_check<check> c = check_bounds) const
      -> Real {
    return static_cast<ConstView>(*this).operator()(x, c);
  }

  [[nodiscard]] auto dimensions() const noexcept -> std::size_t { return polynomials_.size(); }
  void dimensions(OrderType new_size) { polynomials_.resize(new_size); }
  [[nodiscard]] auto size() const noexcept -> std::size_t { return dimensions(); }
  void resize(std::size_t new_size) { polynomials_.resize(new_size); }
  void clear() { polynomials_.clear(); }

  auto begin() noexcept -> iterator { return polynomials_.begin(); }
  auto begin() const noexcept -> const_iterator { return polynomials_.begin(); }
  auto end() noexcept -> iterator { return polynomials_.end(); }
  auto end() const noexcept -> const_iterator { return polynomials_.end(); }

  // NOLINTNEXTLINE(hicpp-explicit-conversions)
  operator View() noexcept { return {polynomials_.data(), polynomials_.size()}; }

  // NOLINTNEXTLINE(hicpp-explicit-conversions)
  operator ConstView() const noexcept { return {polynomials_.data(), polynomials_.size()}; }

 private:
  polynomials_vector polynomials_;
};
}  // namespace poly

POLY_TEMPLATE_RANGE(poly::PolynomialProduct)

max_stars_repo_name: dkavolis/polynomials

max_issues_repo_name: dkavolis/polynomials

max_forks_repo_name: dkavolis/polynomials


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

#include <boost/hana/assert.hpp>
#include <boost/hana/config.hpp>
#include <boost/hana/equal.hpp>
#include <boost/hana/functional/infix.hpp>
#include <boost/hana/pair.hpp>
namespace hana = boost::hana;

BOOST_HANA_CONSTEXPR_LAMBDA auto divmod = hana::infix([](auto x, auto y) {
    // this could be a more efficient implementation
    return hana::make_pair(x / y, x % y);
});

int main() {
    BOOST_HANA_CONSTEXPR_CHECK((42 ^divmod^ 23) == hana::make_pair(1, 19));
}

ext: cpp


text:
//======================================================================
/*! \file DataTypeId.hpp
 *
 * \copydoc Copyright
 * \author Jan Christian Dittmer (jcd)
 * \date Feb 7, 2014
 *///-------------------------------------------------------------------
#ifndef IBEOSDK_DATATYPEID_HPP_SEEN
#define IBEOSDK_DATATYPEID_HPP_SEEN

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

#include <ibeosdk/misc/Unconvertable.hpp>

#include <ibeosdk/io.hpp>
#include <ibeosdk/bufferIO.hpp>
#include <ibeosdk/Log.hpp>

#include <boost/functional/hash.hpp>

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

namespace ibeosdk {

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

class DataTypeId : public ibeosdk::ComparableUnconvertable<uint16_t> {
public:
	//======================================================================
	/*!\brief Ids of some DataTypes. For convenience.
	 *///-------------------------------------------------------------------
	enum DataType {
		DataType_Unknown                          = 0x0000,
		DataType_CanMessage                       = 0x1002, //!< A single can message that has been received via ethernet.
		DataType_FrameEndSeparator                = 0x1100,
		DataType_Command                          = 0x2010,
		DataType_Reply                            = 0x2020,
		DataType_Notification                     = 0x2030, //!< Not implemented in SDK. error and warning messages sent by ibeo LUX/Scala family sensors
		DataType_LuxScan                          = 0x2202, //!< scan data sent by Ibeo LUX/Scala (before B2) family sensors
		DataType_EcuScan                          = 0x2205, //!< scan data sent by Ibeo ECU devices
		DataType_Scan2208                         = 0x2208, //!< Scan data sent by Ibeo Scala B2 and Ibeo MiniLux sensors
		DataType_LuxObjectList                    = 0x2221, //!< objects sent by Ibeo LUX family sensors
		DataType_EcuObjectList                    = 0x2225, //!< objects sent by Ibeo ECU devices
		DataType_ScalaObjectList                  = 0x2270, //!< send by Scala family sensors (starting with B2)
		DataType_ScalaObjectList2271              = 0x2271, //!< send by Scala family sensors (starting with B2)
		DataType_EcuObjectListET                  = 0x2280, //!< send by ECU devices
		DataType_EcuObjectListETDyn               = 0x2281, //!< send by ECU devices
		DataType_ReferencesObjListET              = 0x2290, //!< generate by the Evaluation Suite
		DataType_ReferencesObjListETDyn           = 0x2291, //!< generate by the Evaluation Suite
		DataType_ScalaFpgaRawData                 = 0x2310, //! Uninterpreted raw data from the FPGA
		DataType_Image                            = 0x2403, //!< An image
		DataType_PositionWgs84                    = 0x2604, //!< GPS position
		DataType_OxtsMessage                      = 0x2610, //!<
		DataType_OxtsStatus                       = 0x2611, //!<
		DataType_MeasurementList2821              = 0x2821, //!< Data type that contains a single measurement list.
		DataType_LuxVehicleStateBasic             = 0x2805, //!< send by LUX/Scala
		DataType_EcuVehicleStateBasic2806         = 0x2806, //!< send by ECU
		DataType_EcuVehicleStateBasic             = 0x2807, //!< send by ECU
		DataType_EcuVehicleStateBasic2808         = 0x2808, //!< send by ECU
		DataType_ObjectAssociationList4001        = 0x4001,
		DataType_IdcTrailer                       = 0x6120, //!< Trailer Message in an IDC file
		DataType_FrameIndex                       = 0x6130, //!< Index over IDC file
		DataType_DeviceStatus                     = 0x6301,
		DataType_DeviceStatus6303                 = 0x6303,
		DataType_LogError                         = 0x6400,
		DataType_LogWarning                       = 0x6410,
		DataType_LogNote                          = 0x6420,
		DataType_LogDebug                         = 0x6430,
		DataType_ObjectLabel6503                  = 0x6503,
		DataType_SystemMonitoringCanStatus6700    = 0x6700,
		DataType_SystemMonitoringDeviceStatus6701 = 0x6701,
		DataType_SystemMonitoringSystemStatus6705 = 0x6705,
		DataType_LogPolygonList2dFloat            = 0x6817, //!<List of informational polygons with text label
		DataType_CarriageWayList                  = 0x6970,
		DataType_EventTag                         = 0x7000,
		DataType_ContentSeparator7100             = 0x7100,
		DataType_MetaInformationList7110          = 0x7110,
		DataType_PointCloudGlobal7500             = 0x7500, //!< PointCloudGlobal
		DataType_PointCloudPlane7510              = 0x7510, //!< PointCloudPlane
		DataType_TimeRecord9000                   = 0x9000,
		DataType_GpsImu9001                       = 0x9001,
		DataType_Odometry9002                     = 0x9002,
		DataType_LastId                           = 0xFFFF
	}; // DataType

public:
	//========================================
	/*!\brief Construtor of DataTypeId.
	 *
	 * \param dtId  DataType Id as integer.
	 *///-------------------------------------
	explicit DataTypeId(const uint16_t dtId) : ibeosdk::ComparableUnconvertable<uint16_t>(dtId) {}
	DataTypeId(const DataType dt) : ibeosdk::ComparableUnconvertable<uint16_t>(uint16_t(dt)) {}
	DataTypeId() : ibeosdk::ComparableUnconvertable<uint16_t>(uint16_t(DataType_Unknown)) {}

public:

	bool isSet() const { return (this->m_data != DataType_Unknown); }
	void unSet() { this->m_data = uint16_t(DataType_Unknown); }

public:
	static std::streamsize getSerializedSize() { return sizeof(uint16_t); }

public:
	std::istream& readBE(std::istream& is)
	{
		ibeosdk::readBE(is, this->m_data);
		return is;
	}

	std::ostream& writeBE(std::ostream& os) const
	{
		ibeosdk::writeBE(os, this->m_data);
		return os;
	}

	void readBE(const char*& target)
	{
		ibeosdk::readBE(target, this->m_data);
	}

	void writeBE(char*& target) const
	{
		ibeosdk::writeBE(target, this->m_data);
	}
}; // DataTypeId

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

template<>
inline
std::string toHex<DataTypeId>(const DataTypeId t)
{
	return toHex(uint16_t(t));
}

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

}// namespace ibeosdk

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

namespace boost {

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

template<>
struct hash<ibeosdk::DataTypeId> {
	std::size_t operator() (ibeosdk::DataTypeId const&  dtId) const
	{
		hash<uint16_t> h;
		return h(dtId);
	}
}; // :hash<DataTypeId>

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

} // namespace boost

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

#endif // IBEOSDK_DATATYPEID_HPP_SEEN

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

ext: hpp


text:
/* $Id: Peer.cpp,v 1.151 2016/06/20 06:37:46 severin Exp $ */

/***

NAME - EEDB::Peer

SYNOPSIS

DESCRIPTION

CONTACT

Jessica Severin <severin@gsc.riken.jp>

LICENSE

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

APPENDIX

The rest of the documentation details each of the object methods. Internal methods are usually preceded with a _

***/

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <rapidxml.hpp>  //rapidxml must be include before boost
#include <boost/algorithm/string.hpp>
#include <sqlite3.h>
#include <stdarg.h>

#include <MQDB/MappedQuery.h>
#include <EEDB/SPStreams/OSCFileDB.h>
#include <EEDB/SPStreams/BAMDB.h>
#include <EEDB/SPStreams/RemoteServerStream.h>
#include <EEDB/Peer.h>

using namespace std;
using namespace MQDB;

bool                      EEDB::Peer::global_should_cache = true;
map<string, EEDB::Peer*>  EEDB::Peer::global_uuid_cache;
string                    EEDB::Peer::global_current_web_url;
const char*               EEDB::Peer::class_name = "Peer";

void _eedb_peer_delete_func(MQDB::DBObject *obj) {
  ((EEDB::Peer*)obj)->_delete();
}
void _eedb_peer_xml_func(MQDB::DBObject *obj, string &xml_buffer) {
  ((EEDB::Peer*)obj)->_xml(xml_buffer);
}
void _eedb_peer_simple_xml_func(MQDB::DBObject *obj, string &xml_buffer) {
  ((EEDB::Peer*)obj)->_xml(xml_buffer);
}

EEDB::Peer::Peer() {
  init();
}

EEDB::Peer::~Peer() {
  free_source_stream();
}

void EEDB::Peer::init() {
  MQDB::MappedQuery::init();  //super
  _classname                 = EEDB::Peer::class_name;
  _funcptr_delete            = _eedb_peer_delete_func;
  _funcptr_xml               = _eedb_peer_xml_func;
  _funcptr_simple_xml        = _eedb_peer_simple_xml_func;

  _federation_depth       = 0;
  _database_is_valid      = -1;  //not tested
  _persistent             = true;
  _is_remote              = false;

  _peer_external_database = NULL;
  _source_stream          = NULL;
}

EEDB::Peer* EEDB::Peer::copy() {
  EEDB::Peer *t_copy = new EEDB::Peer();
  t_copy->set_uuid(_peer_uuid);
  t_copy->alias(_alias);
  t_copy->db_url(_db_url);
  return t_copy;
}

void EEDB::Peer::_delete() {
  disconnect();
  if(_persistent) { return; }
  delete this;
}

bool EEDB::Peer::operator< (const EEDB::Peer& b) {
  if(_federation_depth != b._federation_depth) {
    if(_federation_depth < b._federation_depth) { return true; } else { return false; }
  }
  return (boost::algorithm::to_lower_copy(_alias) < boost::algorithm::to_lower_copy(b._alias));
}

//
// URL based constructor
//
EEDB::Peer*  EEDB::Peer::new_from_url(string url) {
  EEDB::Peer  *peer = NULL;
  if(url.empty()) { return NULL; }
  size_t p1 = url.find("://");
  if(p1==string::npos) { return NULL; }
  string t_driver = boost::algorithm::to_lower_copy(url.substr(0, p1));

  if(t_driver == string("oscdb")) {
    peer = new EEDB::Peer();
    peer->_db_url = url;
    if(peer->_connect_via_oscdb()) {
      //need to transfer all values from internal peer to external peer
      EEDB::SPStreams::OSCFileDB *oscdb = (EEDB::SPStreams::OSCFileDB*)(peer->source_stream());
      peer->set_uuid(oscdb->peer()->uuid());
      peer->alias(oscdb->peer()->alias());
      peer->db_url(oscdb->peer()->db_url());
      return peer;
    }
    delete peer;
    return NULL;
  }
  else if(t_driver == string("bamdb")) {
    peer = new EEDB::Peer();
    peer->_db_url = url;
    if(peer->_connect_via_bamdb()) {
      //need to transfer all values from internal peer to external peer
      EEDB::SPStreams::BAMDB *bamdb = (EEDB::SPStreams::BAMDB*)(peer->source_stream());
      peer->set_uuid(bamdb->peer()->uuid());
      peer->alias(bamdb->peer()->alias());
      peer->db_url(bamdb->db_url());
      return peer;
    }
    delete peer;
    return NULL;
  }
  else if(t_driver == string("zdx")) {
    peer = new EEDB::Peer();
    peer->_db_url = url;
    if(peer->_connect_via_zdx()) {
      //need to transfer all values from internal peer to external peer
      EEDB::ZDX::ZDXstream *zdxstream = (EEDB::ZDX::ZDXstream*)(peer->source_stream());
      peer->set_uuid(zdxstream->self_peer()->uuid());
      peer->alias(zdxstream->self_peer()->alias());
      peer->db_url(zdxstream->self_peer()->db_url());
      return peer;
    }
    delete peer;
    return NULL;
  }
  else if((t_driver == string("http")) or (t_driver == string("zenbu"))) {
    //fprintf(stderr, "try to connect to remote zenbu[%s]\n", url.c_str());
    EEDB::SPStreams::RemoteServerStream *rstream = EEDB::SPStreams::RemoteServerStream::new_from_url(url);
    if(!rstream) { return NULL; }
    EEDB::Peer* peer = rstream->master_peer();
    EEDB::Peer::add_to_cache(peer);
    return peer;
  }
  else if((t_driver == string("mysql")) or  (t_driver == string("sqlite"))) {
    //MQDB database (sqlite or mysql)
    MQDB::Database *db = new MQDB::Database(url);
    if(db == NULL) { return NULL; }
    if(!db->get_connection()) { return NULL; }

    const char *sql = "SELECT * FROM peer WHERE is_self=1";
    MQDB::DBObject *obj = MQDB::fetch_single(EEDB::Peer::create, db, sql, "");
    if(obj != NULL) { peer = (EEDB::Peer*)obj; }
    db->disconnect();

    if(!peer) {
      //not found internally so create new one, will not be "valid" but can be use in creation processes
      db->release();
      peer = new EEDB::Peer;
      peer->create_uuid();
      peer->db_url(url);
      size_t p2 = url.rfind("/");
      if(p2!=string::npos) {
        string t_alias = url.substr(p2+1);
        peer->alias(t_alias);
      }
    }
  }
  return peer;
}

//
// static member function each subclass must implement this code
// replace the "<class*> obj = new <class>" line with subclass specific class type
// must return as DBObject* cast
//
DBObject*  EEDB::Peer::create(map<string, dynadata> &row_map, MQDB::Database* db) {
  Peer  *obj = EEDB::Peer::check_cache(row_map["uuid"].i_string);
  if(obj!=NULL) { obj->retain(); return obj; }

  obj = new EEDB::Peer;
  obj->database(db);
  obj->init_from_row_map(row_map);
  EEDB::Peer::add_to_cache(obj);
  return obj;
}

//
// static member functions for object retrieval from database
//
vector<DBObject*>  EEDB::Peer::fetch_all(MQDB::Database *db) {
  const char *sql = "SELECT * FROM peer";
  return MQDB::fetch_multiple(EEDB::Peer::create, db, sql, "");
}

EEDB::Peer*  EEDB::Peer::fetch_by_uuid(MQDB::Database *db, string uuid) {
  const char *sql = "SELECT * FROM peer WHERE uuid=?";
  return (EEDB::Peer*) MQDB::fetch_single(EEDB::Peer::create, db, sql, "s", uuid.c_str());
}

EEDB::Peer*  EEDB::Peer::fetch_by_name(MQDB::Database *db, string name) {
  //a fuzzy method which allows either the UUID or alias to be used for access
  const char *sql = "SELECT * FROM peer WHERE uuid=? or alias=?";
  return (EEDB::Peer*) MQDB::fetch_single(EEDB::Peer::create, db, sql, "ss", name.c_str(), name.c_str());
}

EEDB::Peer*  EEDB::Peer::fetch_by_alias(MQDB::Database *db, string name) {
  //a fuzzy method which allows either the UUID or alias to be used for access
  const char *sql = "SELECT * FROM peer WHERE alias=?";
  return (EEDB::Peer*) MQDB::fetch_single(EEDB::Peer::create, db, sql, "s", name.c_str());
}

EEDB::Peer*  EEDB::Peer::fetch_self(MQDB::Database *db) {
  const char *sql = "SELECT * FROM peer WHERE is_self=1";
  Peer* peer = (EEDB::Peer*) MQDB::fetch_single(EEDB::Peer::create, db, sql, "");
  if(peer != NULL) { db->uuid(peer->uuid()); }
  return peer;
}

void  EEDB::Peer::set_current_web_url(string value) {
  EEDB::Peer::global_current_web_url = value;
}

void  EEDB::Peer::set_cache_behaviour(bool value) {
  if(EEDB::Peer::global_should_cache != value) {
    //if changing state, then flush the caches
    EEDB::Peer::global_uuid_cache.clear(); //maybe need to release
  }
  EEDB::Peer::global_should_cache = value;
}

EEDB::Peer*  EEDB::Peer::check_cache(string &uuid) {
  if(!EEDB::Peer::global_should_cache) { return NULL; }
  if(EEDB::Peer::global_uuid_cache.find(uuid) == EEDB::Peer::global_uuid_cache.end()) { return NULL; }
  return EEDB::Peer::global_uuid_cache[uuid];
}

int  EEDB::Peer::global_cache_size() {
  return global_uuid_cache.size();
}

vector<EEDB::Peer*>  EEDB::Peer::global_cached_peers() {
  vector<Peer*>  peers;
  map<string, Peer*>::iterator it;
  for(it=global_uuid_cache.begin(); it != global_uuid_cache.end(); it++) {
    peers.push_back((*it).second);
  }
  return peers;
}

void  EEDB::Peer::add_to_cache(Peer *obj) {
  if(!EEDB::Peer::global_should_cache) { return; }
  //if(obj->database() == NULL) { return; }
  if(obj->uuid() == NULL) { return; }
  string uuid = obj->uuid();
  if(EEDB::Peer::global_uuid_cache.find(uuid) != EEDB::Peer::global_uuid_cache.end()) { return; }
  obj->retain();
  EEDB::Peer::global_uuid_cache[uuid] = obj;
}

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

void EEDB::Peer::display_info() {
  printf("%s\n", display_desc().c_str());
}

string EEDB::Peer::display_desc() {
  char buffer[2048];
  string  desc;
  snprintf(buffer, 2040, "Peer[%s] %s", _peer_uuid, alias().c_str());
  desc = buffer;
  if(!_db_url.empty())  { desc += " db::" + _db_url; }
  return desc;
}

string EEDB::Peer::display_contents() {
  return display_desc();
}

void EEDB::Peer::_xml(string &xml_buffer) {
  xml_buffer.append("<peer");
  if(_peer_uuid != NULL) {
    xml_buffer.append(" uuid=\"");
    xml_buffer.append(_peer_uuid);
    xml_buffer.append("\"");
  }
  if(!_alias.empty()) {
    xml_buffer.append(" alias=\"");
    xml_buffer.append(_alias);
    xml_buffer.append("\"");
  }
  if(!_db_url.empty()) {
    xml_buffer.append(" db_url=\"");
    xml_buffer.append(_db_url);
    xml_buffer.append("\"");
  }
  char buffer[2048];
  snprintf(buffer, 2040, " depth=\"%d\"", federation_depth());
  xml_buffer.append(buffer);
  xml_buffer.append(" ></peer>");
}

EEDB::Peer*  EEDB::Peer::new_from_xml(void *xml_node) {
  //pseudo constructor using a rapidxml node
  rapidxml::xml_node<>      *root_node = (rapidxml::xml_node<>*)xml_node;
  rapidxml::xml_attribute<> *attr;

  if(root_node==NULL) { return NULL; }
  if(string(root_node->name()) != "peer") { return NULL; }

  attr = root_node->first_attribute("uuid");
  if(!attr) { return NULL; }
  string uuid = attr->value();
  EEDB::Peer *peer = EEDB::Peer::check_cache(uuid);
  if(peer!=NULL) { peer->retain(); return peer; }

  peer = new EEDB::Peer;
  peer->set_uuid(uuid);
  if((attr = root_node->first_attribute("alias")))   { peer->alias(attr->value()); }
  if((attr = root_node->first_attribute("db_url")))  { peer->db_url(attr->value()); }

  EEDB::Peer::add_to_cache(peer);
  return peer;
}

////////////////////////////////////////////////////
//
// getter/setter methods of data which is stored in database
//
////////////////////////////////////////////////////

string       EEDB::Peer::driver() { return _driver; }
const char*  EEDB::Peer::uuid() { return _peer_uuid; }
string       EEDB::Peer::alias() { return _alias; }
string       EEDB::Peer::db_url() { return _db_url; }
int          EEDB::Peer::federation_depth() { return _federation_depth; }

long  EEDB::Peer::source_file_size() {
  if(_driver == "oscdb") {
    EEDB::SPStreams::OSCFileDB *oscdb = (EEDB::SPStreams::OSCFileDB*)source_stream();
    return oscdb->source_file_size();
  }
  if(_driver == "bamdb") {
    EEDB::SPStreams::BAMDB *bamdb = (EEDB::SPStreams::BAMDB*)source_stream();
    return bamdb->source_file_size();
  }
  return 0;
}

string  EEDB::Peer::source_md5sum() {
  if(_driver == "oscdb") {
    EEDB::SPStreams::OSCFileDB *oscdb = (EEDB::SPStreams::OSCFileDB*)source_stream();
    return oscdb->source_md5sum();
  }
  if(_driver == "bamdb") {
    EEDB::SPStreams::BAMDB *bamdb = (EEDB::SPStreams::BAMDB*)source_stream();
    return bamdb->source_md5sum();
  }
  return 0;
}

void EEDB::Peer::db_url(string value) {
  _db_url = value;
  size_t p1 = _db_url.find("://");
  if(p1!=string::npos) { _driver = _db_url.substr(0, p1); }
}

void EEDB::Peer::alias(string value) { _alias = value; }

void EEDB::Peer::federation_depth(int value) {
  if((_federation_depth == 0) or (value < _federation_depth)) {
    _federation_depth = value;
  }
}

void EEDB::Peer::set_uuid(string value) {
  char *t_uuid = (char*)malloc(value.size()+1);
  bzero(t_uuid, value.size()+1);
  strcpy(t_uuid, value.c_str());
  if(_peer_uuid != NULL) { free((void*)_peer_uuid); }
  _peer_uuid = t_uuid;
}

void EEDB::Peer::create_uuid() {
  string uuid = MQDB::uuid_hexstring();
  set_uuid(uuid);
}

void  EEDB::Peer::persistent(bool value) {
  _persistent = value;
}

//////////////////////////////////////////////////////////////////////////////////////////////////
//
// DBObject override methods : storage methods
//
//////////////////////////////////////////////////////////////////////////////////////////////////

void  EEDB::Peer::init_from_row_map(map<string, dynadata> &row_map) {
  set_uuid(row_map["uuid"].i_string);
  alias(row_map["alias"].i_string);
  db_url(row_map["db_url"].i_string);
}

bool  EEDB::Peer::store(MQDB::Database *db) {
  if(db==NULL) { return false; }
  if(_peer_uuid == NULL) { create_uuid(); }

  db->do_sql("INSERT ignore INTO peer (uuid, alias, db_url) VALUES(?,?,?)", "sss",
             _peer_uuid, _alias.c_str(), _db_url.c_str());

  database(db);
  return true;
}

EEDB::Peer*  EEDB::Peer::create_self_peer_for_db(MQDB::Database *db) {
  if(!db) { return NULL; }
  if(!(db->get_connection())) { return NULL; }

  //db->do_sql("DELETE from peer WHERE is_self=1");
  //db->do_sql("UPDATE peer SET is_self=-1 WHERE is_self=1"); //clears old "selfs"

  string url = db->public_url();
  EEDB::Peer *peer = new EEDB::Peer();
  peer->create_uuid();
  peer->db_url(url);

  size_t p2 = url.rfind("/");
  if(p2!=string::npos) {
    string t_alias = url.substr(p2+1);
    peer->alias(t_alias);
  }

  peer->store(db);
  db->do_sql("UPDATE peer SET is_self=1 WHERE uuid=?", "s", peer->uuid());
  //printf("new peer : %s\n", peer->xml().c_str());
  db->disconnect();

  return peer;
}

void EEDB::Peer::disconnect() {
  if(_source_stream != NULL) {
    _source_stream->disconnect();
  }
  if(_peer_external_database != NULL) {
    _peer_external_database->disconnect();
  }
}

void  EEDB::Peer::free_source_stream() {
  if((_driver == string("mysql")) or (_driver == string("sqlite"))) {
    //first release stream then database
    if(_source_stream != NULL) {
      _source_stream->disconnect();
      _source_stream->release();
    }
    if(_peer_external_database != NULL) {
      _peer_external_database->disconnect();
      _peer_external_database->release();
    }
    _source_stream = NULL;
    _peer_external_database = NULL;
  }

  if(_driver != string("oscdb")) {
    //database managed inside so just delete stream
    if(_source_stream != NULL) {
      _source_stream->disconnect();
      _source_stream->release();
    }
    _source_stream = NULL;
    _peer_external_database = NULL;
  }

  _neighbor_peers.clear();
}

//////////////////////////////////////////////////////////////////////
//
// peer database connection section
//
//////////////////////////////////////////////////////////////////////

bool EEDB::Peer::is_valid() {
  if(test_peer_database_is_valid()) { return true; }
  return false;
}

bool EEDB::Peer::retest_is_valid() {
  if(_driver == "oscdb") {
    EEDB::SPStreams::OSCFileDB *oscdb = (EEDB::SPStreams::OSCFileDB*)source_stream();
    if(!oscdb) { return false; }
  }
  if(_driver == "bamdb") {
    EEDB::SPStreams::BAMDB *bamdb = (EEDB::SPStreams::BAMDB*)source_stream();
    if(!bamdb) { return false; }
  }

  if(_database_is_valid == 1) {  return true; }
  //TODO retest is still broken with fcgi

  //fprintf(stderr, "retest_is_valid[%s]\n", uuid());
  if(_database_is_valid == 1) {
    MQDB::Database *db = peer_database();
    if((db!=NULL) and db->get_connection()) { return true; }
  }
  //failed the simple retest so do full disconnect and reconnect
  fprintf(stderr, "retest_is_valid[%s] full test\n", uuid());
  free_source_stream();
  _database_is_valid   = -1;
  return is_valid();
}

bool EEDB::Peer::test_peer_database_is_valid() {
  //_database_is_valid == -1 means not tested yet
  //_database_is_valid == 0  means tested but failed
  //_database_is_valid == 1  means tested and OK

  if(_database_is_valid == 1) { return true; }
  if(_database_is_valid == 0) { return false; }

  if(_peer_uuid == NULL) { _database_is_valid = 0; return false; }

  _connect_to_source_stream();

  if(_database_is_valid == 1) { return true; }
  return false;
}

MQDB::Database* EEDB::Peer::peer_database() {
  if(_database_is_valid==1) { return _peer_external_database; }
  _connect_to_source_stream();
  return _peer_external_database;
}

EEDB::SPStreams::SourceStream* EEDB::Peer::source_stream() {
  if(_source_stream != NULL) { return _source_stream; }
  _connect_to_source_stream();
  return _source_stream;
}

void  EEDB::Peer::remote_server_stream(EEDB::SPStreams::RemoteServerStream *stream) {
  if(_source_stream!=NULL) { _source_stream->release(); }
  _source_stream = stream;
  _source_stream->retain();
  _database_is_valid = 1;
  _is_remote = true;
}

bool  EEDB::Peer::is_remote() {
  return _is_remote;
}

void EEDB::Peer::_connect_to_source_stream() {
  if(_source_stream != NULL) { return; }  //already connected

  if(_peer_uuid == NULL) { _database_is_valid = 0; return; }

  if(_db_url.empty())  { _database_is_valid = 0; }

  if(_driver == "oscdb" and _connect_via_oscdb()) { return; }
  if(_driver == "bamdb" and _connect_via_bamdb()) { return; }
  if(((_driver == "mysql") or (_driver == "sqlite")) and _connect_via_mqdb()) { return; }
  if(((_driver == "http") or (_driver == "zenbu")) and _connect_via_remote_stream()) { return; }
  if(_driver == "zdx") { if(_connect_via_zdx()) { return; } else { fprintf(stderr, "zdx FAILED INIT [%s] %s\n", _peer_uuid, _db_url.c_str()); } }

  _database_is_valid = 0;  //fell through so no valid database connection
}

bool EEDB::Peer::_connect_via_mqdb() {
  if(_database_is_valid == 0) { return false; }  //previously tested and failed

  size_t p1 = _db_url.find("://");
  if(p1==string::npos) { return false; }
  string t_driver = _db_url.substr(0, p1);
  if((t_driver != string("mysql")) && (t_driver != string("sqlite"))) { return false; }

  if(_peer_external_database != NULL) { return true; }

  MQDB::Database *db = new MQDB::Database(_db_url);
  if(db == NULL) { return false; }

  if(!(db->get_connection())) {
    db->disconnect();
    delete db;
    return false;
  }

  dynadata value = db->fetch_col_value("SELECT uuid FROM peer WHERE is_self=1 and uuid=?", "s", _peer_uuid);
  if(value.type != MQDB::STRING) { db->disconnect(); delete db; return false; }
  if(value.i_string != string(_peer_uuid)) { db->disconnect(); delete db; return false; }

  //OK
  db->disconnect();

  db->alias(_alias);
  db->uuid(_peer_uuid);

  _peer_external_database = db;
  _source_stream          = new EEDB::SPStreams::SourceStream(db);
  _database_is_valid      = 1;
  _driver                 = db->driver();
  return true;
}

bool EEDB::Peer::_connect_via_oscdb() {
  if(_database_is_valid == 0) { return false; }  //previously tested and failed
  size_t p1 = _db_url.find("://");
  if(p1==string::npos) { return false; }
  string t_driver = boost::algorithm::to_lower_copy(_db_url.substr(0, p1));
  if(t_driver != string("oscdb")) { return false; }

  if(_source_stream != NULL) { return true; } //already connected

  EEDB::SPStreams::OSCFileDB *oscdb = EEDB::SPStreams::OSCFileDB::new_from_url(_db_url);
  if(oscdb == NULL) { return false; }

  //test internal peer
  if((oscdb->peer() == NULL) ||
     (oscdb->peer()->uuid() == NULL) ||
     (_peer_uuid != NULL && strcmp(oscdb->peer()->uuid(), _peer_uuid) != 0)) {
    _database_is_valid = 0;
    return false;
  }

  _source_stream          = oscdb;
  _database_is_valid      = 1;
  _driver                 = "oscdb";

  if(_db_url != oscdb->peer()->db_url()) {
    //fprintf(stderr, "warning: peer[%s] internal db_url [%s] does not match external db_url [%s]\n",
    //        _peer_uuid, oscdb->peer()->db_url().c_str(), _db_url.c_str());
  }

  return true;
}

bool EEDB::Peer::_connect_via_bamdb() {
  if(_database_is_valid == 0) { return false; }  //previously tested and failed
  size_t p1 = _db_url.find("://");
  if(p1==string::npos) { return false; }
  string t_driver = boost::algorithm::to_lower_copy(_db_url.substr(0, p1));
  if(t_driver != string("bamdb")) { return false; }

  if(_source_stream != NULL) { return true; } //already connected

  EEDB::SPStreams::BAMDB *bamdb = EEDB::SPStreams::BAMDB::new_from_url(_db_url);
  if(bamdb == NULL) { return false; }

  //test internal peer
  if((bamdb->peer() == NULL) ||
     (bamdb->peer()->uuid() == NULL) ||
     (_peer_uuid != NULL && strcmp(bamdb->peer()->uuid(), _peer_uuid) != 0)) {
    _database_is_valid = 0;
    fprintf(stderr, "BAMDB peer_uuid mismatch external[%s] internal[%s]\n", _peer_uuid, bamdb->peer()->uuid());
    return false;
  }

  _source_stream          = bamdb;
  _database_is_valid      = 1;
  _driver                 = "bamdb";

  if(_db_url != bamdb->peer()->db_url()) {
    //fprintf(stderr, "warning: peer[%s] internal db_url [%s] does not match external db_url [%s]\n",
    //        _peer_uuid, oscdb->peer()->db_url().c_str(), _db_url.c_str());
  }

  return true;
}

bool EEDB::Peer::_connect_via_remote_stream() {
  if(_database_is_valid == 0) { return false; }  //previously tested and failed
  if(_source_stream!= NULL) { return true; } //already connected
  fprintf(stderr, "EEDB::Peer::_connect_via_remote_stream try to connect [%s] %ld\n", _db_url.c_str(), (long)this);

  EEDB::SPStreams::RemoteServerStream *rstream = EEDB::SPStreams::RemoteServerStream::new_from_url(_db_url);
  if(!rstream) { return false; }

  _source_stream          = rstream;
  _database_is_valid      = 1;
  _driver                 = "zenbu";

  return true;
}

bool EEDB::Peer::_connect_via_zdx() {
  if(_database_is_valid == 0) { return false; }  //previously tested and failed
  if(_source_stream!= NULL) { return true; } //already connected

  size_t p1 = _db_url.find("://");
  if(p1==string::npos) { return false; }
  string t_driver = _db_url.substr(0, p1);
  if(t_driver != string("zdx")) { return false; }

  string t_path = _db_url.substr(p1+3);
  EEDB::ZDX::ZDXstream* zdxstream = EEDB::ZDX::ZDXstream::open(t_path);
  if(!zdxstream) { return false; }
  ZDXdb* zdxdb = zdxstream->zdxdb();
  if(!zdxdb) { return false; }
  if(zdxdb->magic() != string("ZDXRIKENZENBU01")) { return false; }

  if(!zdxstream->self_peer()) { return false; }
  if(_peer_uuid && (strcmp(_peer_uuid, zdxstream->self_peer()->uuid()) !=0)) { return false; }
  if(!_peer_uuid) { set_uuid(zdxstream->self_peer()->uuid()); }

  _source_stream          = zdxstream;
  _database_is_valid      = 1;
  _driver                 = "zdx";

  return true;
}

////////////////////////////////////////////////////
//
// federated peer-2-peer searching/caching
//
////////////////////////////////////////////////////

EEDB::Peer* EEDB::Peer::find_peer(string uuid, int max_depth) {
  map<string, EEDB::Peer*> uuid_peers;
  uuid_peers[uuid] = NULL;
  bool rtn = find_peers(uuid_peers, max_depth);
  if(rtn) { return uuid_peers[uuid]; }
  return NULL;
}

bool EEDB::Peer::find_peers(map<string, EEDB::Peer*> &uuid_peers, int max_depth) {
  if(uuid_peers.empty()) { return false; }
  if(max_depth<=0) { return false; }
  map<string, bool>  network_search_flag;  //to track which peers we have visited
  /*
  fprintf(stderr, "find_peers [%d]\n", uuid_peers.size());
  map<string, EEDB::Peer*>::iterator  it;
  for(it = uuid_peers.begin(); it != uuid_peers.end(); it++) {
    fprintf(stderr, "  %s\n", it->first.c_str());
  }
  */

  //first recursive search the cached neighbor peers
  bool rtn = _multipeer_neighbor_search(uuid_peers, max_depth, network_search_flag);
  if(rtn) { return rtn; }
  if(_is_remote) { return rtn; }

  //then do again connecting to network
  network_search_flag.clear();
  rtn = _multipeer_network_search(uuid_peers, max_depth, network_search_flag);
  return rtn;
}

EEDB::Peer* EEDB::Peer::cache_find_peer(string uuid, int max_depth) {
  map<string, EEDB::Peer*> uuid_peers;
  uuid_peers[uuid] = NULL;
  bool rtn = cache_find_peers(uuid_peers, max_depth);
  if(rtn) { return uuid_peers[uuid]; }
  return NULL;
}

bool EEDB::Peer::cache_find_peers(map<string, EEDB::Peer*> &uuid_peers, int max_depth) {
  if(uuid_peers.empty()) { return false; }
  if(max_depth<=0) { return false; }
  map<string, bool>  network_search_flag;  //to track which peers we have visited
  //fprintf(stderr, "find_peers [%d]\n", uuid_peers.size());
  return _multipeer_neighbor_search(uuid_peers, max_depth, network_search_flag);
}

bool EEDB::Peer::_multipeer_neighbor_search(map<string, EEDB::Peer*> &uuid_peers,
                                           int max_depth,
                                           map<string, bool> &network_search_flag) {
  //fprintf(stderr, "_multipeer_neighbor_search [%s]\n", display_desc().c_str());
  //recursive search of the cached neighbors
  if(network_search_flag.find(uuid()) != network_search_flag.end()) { return false; }
  network_search_flag[uuid()] = true;

  if(_multipeer_add_testdone(uuid_peers, this)) { return true; } //finished

  //no need to search inside an oscdb or bamdb for additional peers
  if(driver() == string("oscdb")) { return false; }
  if(driver() == string("bamdb")) { return false; }
  if(_is_remote) { return false; }

  //test next layer down
  if(federation_depth() + 1 > max_depth) { return false; }
  map<string, EEDB::Peer*>::iterator it;
  for(it = _neighbor_peers.begin(); it != _neighbor_peers.end(); it++) {
    if((*it).second->_multipeer_neighbor_search(uuid_peers, max_depth, network_search_flag)) { return true; }
  }
  return false;
}

bool EEDB::Peer::_multipeer_network_search(map<string, EEDB::Peer*> &uuid_peers,
                                           int max_depth,
                                           map<string, bool> &network_search_flag) {
  //fprintf(stderr, "_multipeer_network_search [%s]\n", display_desc().c_str());
  if(network_search_flag.find(uuid()) != network_search_flag.end()) { return false; }
  network_search_flag[uuid()] = true;

  if(_multipeer_add_testdone(uuid_peers, this)) { return true; } //finished

  //no need to search inside an oscdb or bamdb for additional peers
  if(driver() == string("oscdb")) { return false; }
  if(driver() == string("bamdb")) { return false; }
  if(_is_remote) { return false; }
  //fprintf(stderr, "  driver [%s]\n", driver().c_str());

  //test next layer down
  int next_depth = federation_depth() + 1;
  if(next_depth > max_depth) { return false; }

  //fprintf(stderr, "  network search into [%s]\n", display_desc().c_str());
  EEDB::SPStreams::SourceStream *stream = source_stream();
  if(stream == NULL) { return false; }

  if((_driver == "http") or (_driver == "zenbu")) {
    map<string, EEDB::Peer*>::iterator it;
    EEDB::SPStreams::RemoteServerStream *rstream = (EEDB::SPStreams::RemoteServerStream*)stream;
    rstream->clear_filters();
    for(it = uuid_peers.begin(); it != uuid_peers.end(); it++) {
      if((*it).second == NULL) {
        //fprintf(stderr, "add [%s] to peer filter\n", (*it).first.c_str());
        rstream->add_peer_id_filter((*it).first.c_str());
      }
    }
  }
  stream->stream_peers();

  EEDB::Peer *peer = (EEDB::Peer*)stream->next_in_stream();
  while(peer != NULL) {
    _neighbor_peers[peer->uuid()] = peer;
    peer->federation_depth(next_depth);
    if(peer->_multipeer_network_search(uuid_peers, max_depth, network_search_flag)) { return true; }
    peer = (EEDB::Peer*)stream->next_in_stream();
  }
  return false;
}

bool EEDB::Peer::_multipeer_add_testdone(map<string, EEDB::Peer*> &uuid_peers, EEDB::Peer *peer) {
  map<string, EEDB::Peer*>::iterator  it;
  bool                                finished = true;

  if(peer == NULL) { return false; }
  for(it = uuid_peers.begin(); it != uuid_peers.end(); it++) {
    if((it->first == peer->uuid()) or (it->first == peer->alias())) {
      //fprintf(stderr, "found uuid match [%s]\n", peer->uuid());
      if(peer->is_valid()) {
        it->second = peer;
      }
    }
    if(it->second == NULL) { finished=false; }
  }
  return finished;
}

bool EEDB::Peer::_multipeer_test_done(map<string, EEDB::Peer*> &uuid_peers) {
  map<string, EEDB::Peer*>::iterator  it;
  for(it = uuid_peers.begin(); it != uuid_peers.end(); it++) {
    //any missing peer (NULL) means we are not done
    if((*it).second == NULL) { return false; }
  }
  return true;  //yep all found
}

/***** all_network_peers

  Description: performs a peer-2-peer network search collecting
               all peers into a hash reference with a recursive algorithm
  Returntype : hash reference of peers;
  Exceptions : none

*****/

void EEDB::Peer::all_network_peers(int max_depth, map<string, EEDB::Peer*> &uuid_peers) {
  if(max_depth<0) { max_depth =7; }

  if(uuid_peers.find(uuid()) != uuid_peers.end()) { return; }  //already found

  if(!is_valid()) { return; }
  if(_federation_depth == 0) { _federation_depth = 1; }
  if(_federation_depth > max_depth) { return; }

  EEDB::SPStreams::SourceStream *stream = source_stream();
  if(stream == NULL) { return; }

  //only place where peer is placed into the hash
  uuid_peers[uuid()] = this;

  //no need to search inside an oscdb or bamdb for additional peers
  if(driver() == string("oscdb")) { return; }
  if(driver() == string("bamdb")) { return; }
  if(driver() == string("zdx")) { return; }
  if(_is_remote) { return; }

  //tested test next layer down
  vector<EEDB::Peer*>            new_peers;
  vector<EEDB::Peer*>::iterator  it;

  stream->stream_peers();
  int next_depth = _federation_depth + 1;
  EEDB::Peer *peer;
  while((peer = (EEDB::Peer*)stream->next_in_stream())) {
    _neighbor_peers[peer->uuid()] = peer;
    if(uuid_peers.find(peer->uuid()) != uuid_peers.end()) { continue; }
    peer->federation_depth(next_depth);
    new_peers.push_back(peer);
  }
  //fprintf(stderr, "peer search registry [%s] %s -- %ld new peers added\n", uuid(), db_url().c_str(), new_peers.size());
  for(it = new_peers.begin(); it != new_peers.end(); it++) {
    (*it)->all_network_peers(max_depth, uuid_peers);
  }
}


text:
#include <oslo/crypto_lib/random_pool.hpp>
#include <oslo/lib/config.hpp>
#include <oslo/lib/threading.hpp>
#include <oslo/node/common.hpp>
#include <oslo/node/testing.hpp>
#include <oslo/qt/qt.hpp>

#include <boost/format.hpp>

#include <thread>

int main (int argc, char ** argv)
{
	oslo::network_constants::set_active_network (oslo::oslo_networks::oslo_test_network);
	oslo::node_singleton_memory_pool_purge_guard memory_pool_cleanup_guard;
	QApplication application (argc, argv);
	QCoreApplication::setOrganizationName ("Oslo");
	QCoreApplication::setOrganizationDomain ("oslo.org");
	QCoreApplication::setApplicationName ("Oslo Wallet");
	oslo_qt::eventloop_processor processor;
	const uint16_t count (16);
	oslo::system system (count);
	oslo::thread_runner runner (system.io_ctx, system.nodes[0]->config.io_threads);
	std::unique_ptr<QTabWidget> client_tabs (new QTabWidget);
	std::vector<std::unique_ptr<oslo_qt::wallet>> guis;
	for (auto i (0); i < count; ++i)
	{
		auto wallet (system.nodes[i]->wallets.create (oslo::random_wallet_id ()));
		oslo::keypair key;
		wallet->insert_adhoc (key.prv);
		guis.push_back (std::make_unique<oslo_qt::wallet> (application, processor, *system.nodes[i], wallet, key.pub));
		client_tabs->addTab (guis.back ()->client_window, boost::str (boost::format ("Wallet %1%") % i).c_str ());
	}
	client_tabs->show ();
	QObject::connect (&application, &QApplication::aboutToQuit, [&]() {
		system.stop ();
	});
	int result;
	try
	{
		result = application.exec ();
	}
	catch (...)
	{
		result = -1;
		debug_assert (false);
	}
	runner.join ();
	return result;
}

max_stars_repo_name: oslocurrency/oslo-node

max_issues_repo_name: oslocurrency/oslo-node

max_forks_repo_name: oslocurrency/oslo-node


text:
#ifndef OSRM_GUIDANCE_TURN_LANE_TYPES_HPP_
#define OSRM_GUIDANCE_TURN_LANE_TYPES_HPP_

#include <bitset>
#include <cstddef>
#include <cstdint>
#include <string>
#include <unordered_map>
#include <vector>

#include <boost/functional/hash.hpp>

#include "util/json_container.hpp"
#include "util/typedefs.hpp"

namespace osrm
{
namespace extractor
{
namespace guidance
{

namespace TurnLaneType
{
namespace detail
{
const constexpr std::size_t num_supported_lane_types = 11;

const constexpr char *translations[detail::num_supported_lane_types] = {"none",
                                                                        "straight",
                                                                        "sharp left",
                                                                        "left",
                                                                        "slight left",
                                                                        "slight right",
                                                                        "right",
                                                                        "sharp right",
                                                                        "uturn",
                                                                        "merge to left",
                                                                        "merge to right"};

} // namespace detail

typedef std::uint16_t Mask;
const constexpr Mask empty = 0u;
const constexpr Mask none = 1u << 0u;
const constexpr Mask straight = 1u << 1u;
const constexpr Mask sharp_left = 1u << 2u;
const constexpr Mask left = 1u << 3u;
const constexpr Mask slight_left = 1u << 4u;
const constexpr Mask slight_right = 1u << 5u;
const constexpr Mask right = 1u << 6u;
const constexpr Mask sharp_right = 1u << 7u;
const constexpr Mask uturn = 1u << 8u;
const constexpr Mask merge_to_left = 1u << 9u;
const constexpr Mask merge_to_right = 1u << 10u;

inline std::string toString(const Mask lane_type)
{
    if (lane_type == 0)
        return "none";

    std::bitset<8 * sizeof(Mask)> mask(lane_type);
    std::string result = "";
    for (std::size_t lane_id_nr = 0; lane_id_nr < detail::num_supported_lane_types; ++lane_id_nr)
        if (mask[lane_id_nr])
            result += (result.empty() ? detail::translations[lane_id_nr]
                                      : (std::string(";") + detail::translations[lane_id_nr]));

    return result;
}

inline util::json::Array toJsonArray(const Mask lane_type)
{
    util::json::Array result;
    std::bitset<8 * sizeof(Mask)> mask(lane_type);
    for (std::size_t lane_id_nr = 0; lane_id_nr < detail::num_supported_lane_types; ++lane_id_nr)
        if (mask[lane_id_nr])
            result.values.push_back(detail::translations[lane_id_nr]);
    return result;
}
} // TurnLaneType

typedef std::vector<TurnLaneType::Mask> TurnLaneDescription;

// hash function for TurnLaneDescription
struct TurnLaneDescription_hash
{
    std::size_t operator()(const TurnLaneDescription &lane_description) const
    {
        std::size_t seed = 0;
        boost::hash_range(seed, lane_description.begin(), lane_description.end());
        return seed;
    }
};

typedef std::unordered_map<guidance::TurnLaneDescription,
                           LaneDescriptionID,
                           guidance::TurnLaneDescription_hash>
    LaneDescriptionMap;

} // guidance
} // extractor
} // osrm

#endif /* OSRM_GUIDANCE_TURN_LANE_TYPES_HPP_ */

max_stars_repo_name: jhermsmeier/osrm-backend

max_issues_repo_name: jhermsmeier/osrm-backend

max_forks_repo_name: jhermsmeier/osrm-backend


text:
#include <boost/spirit/include/karma_generate.hpp>
#include <boost/spirit/include/karma_real.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/qi_auto.hpp>
#include <boost/spirit/include/qi_no_skip.hpp>
#include <boost/spirit/include/qi_numeric.hpp>
#include <boost/spirit/include/qi_parse_auto.hpp>
#include <boost/spirit/include/support_ascii.hpp>
#include <celero/Celero.h>
#include <fmt/format.h>
#include <limits>
#include <random>
#include <sstream>
#include <string>
#include <boost/spirit/home/x3.hpp>
#include <boost/spirit/home/x3/core.hpp>
#include <boost/spirit/home/x3/numeric.hpp>
//#include <formatxx/format.h>
//#include <formatxx/string.h>

CELERO_MAIN

// toggle to inspect
//#define INSPECT_OUTPUT

// toggle
//#define DO_NOT_OPTIMIZE

#ifdef INSPECT_OUTPUT
constexpr int g_samples = 1;
constexpr int g_iterations = 1;
#else
constexpr int g_samples = 1000;
constexpr int g_iterations = 1000;
#endif

std::mt19937 rng;
auto distribution_int = std::uniform_int_distribution<>(std::numeric_limits<int>::min(), std::numeric_limits<int>::max());
auto random_int = [] {
	return distribution_int(rng);
};

//auto distribution_float = std::uniform_real_distribution<float>(std::numeric_limits<float>::lowest(), std::numeric_limits<float>::max());
auto distribution_float = std::uniform_real_distribution<float>(-1000000, 1000000);
auto random_float = [] {
	return distribution_float(rng);
};

template <typename T>
struct fixed_policy : boost::spirit::karma::real_policies<T> {
	typedef boost::spirit::karma::real_policies<T> base_type;
	static int floatfield(T) { return base_type::fmtflags::fixed; }
	static unsigned int precision(T) { return 10; }
};

using float_fixed_type = boost::spirit::karma::real_generator<double, fixed_policy<float>>;
auto const float_fixed = float_fixed_type();

fmt::memory_buffer g_buf;

std::string naive_int_to_str(int x)
{
	constexpr char ascii_offset = 48;

	std::string str;

	if (x < 0) {
		x *= -1;
		str += '-';
	}

	while (x > 0) {
		str += static_cast<unsigned char>(x % 10) + ascii_offset;
		x /= 10;
	}

	std::reverse(str.begin() + (str[0] == '-'), str.end());

	return str;
}

template<unsigned max>
char get_digit(int& x)
{
	const auto d = x / max;
	x -= d * max;
	return d;
}

std::string naive2_int_to_str(int x)
{
	constexpr char ascii_offset = 48;

	std::string str;

	if (x < 0) {
		x *= -1;
		str += '-';
	}

	const auto write_digit = [&str, &ascii_offset](char d) {
		str += d + ascii_offset;
	};

	{
		constexpr unsigned max = 1000000000;
		if (x >= max)
			write_digit(get_digit<max>(x));
	}
	{
		constexpr unsigned max = 100000000;
		if (x >= max)
			write_digit(get_digit<max>(x));
	}
	{
		constexpr unsigned max = 10000000;
		if (x >= max)
			write_digit(get_digit<max>(x));
	}
	{
		constexpr unsigned max = 1000000;
		if (x >= max)
			write_digit(get_digit<max>(x));
	}
	{
		constexpr unsigned max = 100000;
		if (x >= max)
			write_digit(get_digit<max>(x));
	}
	{
		constexpr unsigned max = 10000;
		if (x >= max)
			write_digit(get_digit<max>(x));
	}
	{
		constexpr unsigned max = 1000;
		if (x >= max)
			write_digit(get_digit<max>(x));
	}
	{
		constexpr unsigned max = 100;
		if (x >= max)
			write_digit(get_digit<max>(x));
	}
	{
		constexpr unsigned max = 10;
		if (x >= max)
			write_digit(get_digit<max>(x));
	}
	{
		constexpr unsigned max = 1;
		if (x >= max)
			write_digit(get_digit<max>(x));
	}

	return str;
}

struct IntFixture : celero::TestFixture
{
	int value;
	std::string value_str;

	void setUp(const celero::TestFixture::ExperimentValue& experimentValue) override
	{
		value = random_int();
		value_str = std::to_string(value);
	}
};

struct FloatFixture : celero::TestFixture
{
	float value;
	std::string value_str;

	void setUp(const celero::TestFixture::ExperimentValue& experimentValue) override
	{
		value = 12345.6789f;//random_float();
		std::stringstream ss;
		ss << value;
		value_str = ss.str();
	}
};

// int to string
BASELINE_F(int_to_str, to_string, IntFixture, g_samples, g_iterations)
{
	std::string s;

#ifdef DO_NOT_OPTIMIZE
	celero::DoNotOptimizeAway(
#endif
		s = std::to_string(value)
#ifdef DO_NOT_OPTIMIZE
	)
#endif
	;

#ifdef INSPECT_OUTPUT
	std::cout << s << std::endl;
#endif
}

BENCHMARK_F(int_to_str, sstream, IntFixture, g_samples, g_iterations)
{
	std::stringstream ss;

#ifdef DO_NOT_OPTIMIZE
	celero::DoNotOptimizeAway(
#endif
		ss << value
#ifdef DO_NOT_OPTIMIZE
	)
#endif
	;

#ifdef INSPECT_OUTPUT
	std::cout << ss.str() << std::endl;
#endif
}

BENCHMARK_F(int_to_str, karma, IntFixture, g_samples, g_iterations)
{
	std::string s;
	std::back_insert_iterator<std::string> sink(s);

#ifdef DO_NOT_OPTIMIZE
	celero::DoNotOptimizeAway(
#endif
		boost::spirit::karma::generate(sink, value)
#ifdef DO_NOT_OPTIMIZE
	)
#endif
	;

#ifdef INSPECT_OUTPUT
	std::cout << s << std::endl;
#endif
}

BENCHMARK_F(int_to_str, karma_int_, IntFixture, g_samples, g_iterations)
{
	using namespace boost::spirit::karma;

	std::string s;
	std::back_insert_iterator<std::string> sink(s);

#ifdef DO_NOT_OPTIMIZE
	celero::DoNotOptimizeAway(
#endif
		generate(sink, int_(value))
#ifdef DO_NOT_OPTIMIZE
	)
#endif
		;

#ifdef INSPECT_OUTPUT
	std::cout << s << std::endl;
#endif
}

BENCHMARK_F(int_to_str, karma_reserve, IntFixture, g_samples, g_iterations)
{
	std::string s;
	s.reserve(50);

#ifdef DO_NOT_OPTIMIZE
	celero::DoNotOptimizeAway(
#endif
		boost::spirit::karma::generate(s.begin(), value)
#ifdef DO_NOT_OPTIMIZE
	)
#endif
		;

#ifdef INSPECT_OUTPUT
	std::cout << s << std::endl;
#endif
}

BENCHMARK_F(int_to_str, karma_ins_reserve, IntFixture, g_samples, g_iterations)
{
	using boost::spirit::karma::int_inserter;

	std::string s;
	s.reserve(50);
	auto iter = s.begin();

#ifdef DO_NOT_OPTIMIZE
	celero::DoNotOptimizeAway(
#endif
		int_inserter<10>::call(iter, value)
#ifdef DO_NOT_OPTIMIZE
	)
#endif
		;

#ifdef INSPECT_OUTPUT
	std::cout << s << std::endl;
#endif
}

BENCHMARK_F(int_to_str, karma_ins_buff, IntFixture, g_samples, g_iterations)
{
	using boost::spirit::karma::int_inserter;

	char buffer[50];
	char* p = buffer;

#ifdef DO_NOT_OPTIMIZE
	celero::DoNotOptimizeAway(
#endif
		int_inserter<10>::call(p, value)
#ifdef DO_NOT_OPTIMIZE
	)
#endif
		;

#ifdef INSPECT_OUTPUT
	std::cout << buffer << std::endl;
#endif
}

BENCHMARK_F(int_to_str, fmt_format, IntFixture, g_samples, g_iterations)
{
	std::string s;

#ifdef DO_NOT_OPTIMIZE
	celero::DoNotOptimizeAway(
#endif
		s = fmt::format("{}", value)
#ifdef DO_NOT_OPTIMIZE
	)
#endif
		;

#ifdef INSPECT_OUTPUT
	std::cout << s << std::endl;
#endif
}

BENCHMARK_F(int_to_str, fmt_buffer, IntFixture, g_samples, g_iterations)
{
	std::string s;
	fmt::memory_buffer buf;

#ifdef DO_NOT_OPTIMIZE
	celero::DoNotOptimizeAway(
#endif
	format_to(buf, "{}", value);
	s = buf.data();
#ifdef DO_NOT_OPTIMIZE
	)
#endif
		;

#ifdef INSPECT_OUTPUT
	std::cout << s << std::endl;
#endif
}

BENCHMARK_F(int_to_str, fmt_buffer_g, IntFixture, g_samples, g_iterations)
{
	std::string s;
	g_buf.clear();

#ifdef DO_NOT_OPTIMIZE
	celero::DoNotOptimizeAway(
#endif
	format_to(g_buf, "{}", value);
	s = g_buf.data();
#ifdef DO_NOT_OPTIMIZE
	)
#endif
		;

#ifdef INSPECT_OUTPUT
	std::cout << s << std::endl;
#endif
}

BENCHMARK_F(int_to_str, naive, IntFixture, g_samples, g_iterations)
{
	std::string s;

#ifdef DO_NOT_OPTIMIZE
	celero::DoNotOptimizeAway(
#endif
		s = naive_int_to_str(value)
#ifdef DO_NOT_OPTIMIZE
	)
#endif
		;

#ifdef INSPECT_OUTPUT
	std::cout << s << std::endl;
#endif
}

BENCHMARK_F(int_to_str, naive2, IntFixture, g_samples, g_iterations)
{
	std::string s;

#ifdef DO_NOT_OPTIMIZE
	celero::DoNotOptimizeAway(
#endif
		s = naive2_int_to_str(value)
#ifdef DO_NOT_OPTIMIZE
	)
#endif
		;

#ifdef INSPECT_OUTPUT
	std::cout << s << std::endl;
#endif
}

// float to string
BASELINE_F(float_to_str, to_string, FloatFixture, g_samples, g_iterations)
{
	std::string s;

#ifdef DO_NOT_OPTIMIZE
	celero::DoNotOptimizeAway(
#endif
		s = std::to_string(value)
#ifdef DO_NOT_OPTIMIZE
	)
#endif
		;

#ifdef INSPECT_OUTPUT
	std::cout << s << std::endl;	// keeps trailing zeros
#endif
}
BENCHMARK_F(float_to_str, to_string_trim, FloatFixture, g_samples, g_iterations)
{
	std::string s;

#ifdef DO_NOT_OPTIMIZE
	celero::DoNotOptimizeAway(
#endif
		s = std::to_string(value)
#ifdef DO_NOT_OPTIMIZE
	)
#endif
		;

	// trim zeros and decimal point
	const auto pos = s.find_last_not_of('0');
	if(s[pos] == '.')
		s.erase(pos);
	else
		s.erase(pos+1);

#ifdef INSPECT_OUTPUT
	std::cout << s << std::endl;
#endif
}

BENCHMARK_F(float_to_str, to_string_trim2, FloatFixture, g_samples, g_iterations)
{
	std::string s;

#ifdef DO_NOT_OPTIMIZE
	celero::DoNotOptimizeAway(
#endif
		s = std::to_string(value)
#ifdef DO_NOT_OPTIMIZE
	)
#endif
		;

	// trim trailing zeros and decimal point
	const auto pos = s.find_last_not_of('0');
	s.erase(pos + (s[pos] != '.'));

#ifdef INSPECT_OUTPUT
	std::cout << s << std::endl;
#endif
}

BENCHMARK_F(float_to_str, to_string_trim3, FloatFixture, g_samples, g_iterations)
{
	std::string s;

#ifdef DO_NOT_OPTIMIZE
	celero::DoNotOptimizeAway(
#endif
		s = std::to_string(value)
#ifdef DO_NOT_OPTIMIZE
	)
#endif
		;

	// trim zeros and decimal point
	for (size_t pos = s.size() - 1; pos > 0/*not erasing last char*/; --pos) {
		if (s[pos] != '0') {
			s.erase(pos + (s[pos] != '.'));
			break;
		}
	}

#ifdef INSPECT_OUTPUT
	std::cout << s << std::endl;
#endif
}

BENCHMARK_F(float_to_str, sstream, FloatFixture, g_samples, g_iterations)
{
	std::stringstream ss;

#ifdef DO_NOT_OPTIMIZE
	celero::DoNotOptimizeAway(
#endif
		ss << value
#ifdef DO_NOT_OPTIMIZE
	)
#endif
		;

#ifdef INSPECT_OUTPUT
	std::cout << ss.str() << std::endl;	// no redundant trail
#endif
}

BENCHMARK_F(float_to_str, karma, FloatFixture, g_samples, g_iterations)
{
	std::string s;
	std::back_insert_iterator<std::string> sink(s);

#ifdef DO_NOT_OPTIMIZE
	celero::DoNotOptimizeAway(
#endif
		boost::spirit::karma::generate(sink, value)
#ifdef DO_NOT_OPTIMIZE
	)
#endif
		;

#ifdef INSPECT_OUTPUT
	std::cout << s << std::endl;	// if no fraction, keeps trailing ".0"
#endif
}

BENCHMARK_F(float_to_str, karma_fixed, FloatFixture, g_samples, g_iterations)
{
	std::string s;
	std::back_insert_iterator<std::string> sink(s);

#ifdef DO_NOT_OPTIMIZE
	celero::DoNotOptimizeAway(
#endif
		boost::spirit::karma::generate(sink, float_fixed, value)
#ifdef DO_NOT_OPTIMIZE
	)
#endif
		;

#ifdef INSPECT_OUTPUT
	std::cout << s << std::endl;	// if no fraction, keeps trailing ".0"
#endif
}

BENCHMARK_F(float_to_str, fmt_format, FloatFixture, g_samples, g_iterations)
{
	std::string s;

#ifdef DO_NOT_OPTIMIZE
	celero::DoNotOptimizeAway(
#endif
		s = fmt::format("{}", value)
#ifdef DO_NOT_OPTIMIZE
	)
#endif
		;

#ifdef INSPECT_OUTPUT
	std::cout << s << std::endl;	// no redundant trail
#endif
}

BENCHMARK_F(float_to_str, fmt_buffer, FloatFixture, g_samples, g_iterations)
{
	std::string s;
	fmt::memory_buffer buf;

#ifdef DO_NOT_OPTIMIZE
	celero::DoNotOptimizeAway(
#endif
	format_to(buf, "{}", value);
	s = buf.data();
#ifdef DO_NOT_OPTIMIZE
	)
#endif
		;

#ifdef INSPECT_OUTPUT
	std::cout << s << std::endl;	// no redundant trail
#endif
}

BENCHMARK_F(float_to_str, fmt_buffer_g, FloatFixture, g_samples, g_iterations)
{
	std::string s;
	g_buf.clear();

#ifdef DO_NOT_OPTIMIZE
	celero::DoNotOptimizeAway(
#endif
	format_to(g_buf, "{}", value);
	s = g_buf.data();
#ifdef DO_NOT_OPTIMIZE
	)
#endif
		;

#ifdef INSPECT_OUTPUT
	std::cout << s << std::endl;
#endif
}

// string to int
BASELINE_F(str_to_int, stoi, IntFixture, g_samples, g_iterations)
{
	int i;

#ifdef DO_NOT_OPTIMIZE
	celero::DoNotOptimizeAway(
#endif
		i = std::stoi(value_str)
#ifdef DO_NOT_OPTIMIZE
	)
#endif
		;
}

BENCHMARK_F(str_to_int, qi, IntFixture, g_samples, g_iterations)
{
	namespace qi = boost::spirit::qi;

	int i;

#ifdef DO_NOT_OPTIMIZE
	celero::DoNotOptimizeAway(
#endif
		qi::phrase_parse(value_str.begin(), value_str.end(), qi::auto_, boost::spirit::ascii::space, i)
#ifdef DO_NOT_OPTIMIZE
	)
#endif
		;
}

BENCHMARK_F(str_to_int, x3, IntFixture, g_samples, g_iterations)
{
	namespace x3 = boost::spirit::x3;

	int i;

#ifdef DO_NOT_OPTIMIZE
	celero::DoNotOptimizeAway(
#endif
		x3::phrase_parse(value_str.begin(), value_str.end(), x3::int_parser<int>(), x3::ascii::space, i)
#ifdef DO_NOT_OPTIMIZE
	)
#endif
		;
}

// string to float
BASELINE_F(str_to_float, stof, FloatFixture, g_samples, g_iterations)
{
	float x;

#ifdef DO_NOT_OPTIMIZE
	celero::DoNotOptimizeAway(
#endif
		x = std::stof(value_str)
#ifdef DO_NOT_OPTIMIZE
	)
#endif
		;
}

BENCHMARK_F(str_to_float, qi, FloatFixture, g_samples, g_iterations)
{
	namespace qi = boost::spirit::qi;

	float x;

#ifdef DO_NOT_OPTIMIZE
	celero::DoNotOptimizeAway(
#endif
		qi::phrase_parse(value_str.begin(), value_str.end(), qi::auto_, boost::spirit::ascii::space, x)
#ifdef DO_NOT_OPTIMIZE
	)
#endif
		;
}

BENCHMARK_F(str_to_float, x3, FloatFixture, g_samples, g_iterations)
{
	namespace x3 = boost::spirit::x3;

	float x;

#ifdef DO_NOT_OPTIMIZE
	celero::DoNotOptimizeAway(
#endif
		x3::phrase_parse(value_str.begin(), value_str.end(), x3::real_parser<float>(), x3::ascii::space, x)
#ifdef DO_NOT_OPTIMIZE
	)
#endif
		;
}

max_stars_repo_path: string parsing/src/Source.cpp

max_stars_repo_name: Enhex/Benchmarks

max_issues_repo_path: string parsing/src/Source.cpp

max_issues_repo_name: Enhex/Benchmarks

max_forks_repo_path: string parsing/src/Source.cpp

max_forks_repo_name: Enhex/Benchmarks


text:
/* --------------------------------------------------------------------------
*
* (C) Copyright …
*
* ---------------------------------------------------------------------------
*/

/*!
 * @file SelectionTester.hpp
 * @date 04/05/2018
 * @author Alessandro Bianco
 */

/*!
 * @addtogroup GuiTests
 *
 * This class will test requirement 4.1.1.2 of deliverable 5.5.
 * "The number of features detected should be within 10% of the number of features in a reference case for feature detection obtained by a standard detection algorithm (open source and in OpenCV)
 * implemented for a given descriptor.  These open-source descriptor implementations are considered to be industry standard, only parameters are expected to cause differences between implementations
 * of the same descriptor on the same data." and
 * "90% of manually detected features should lay within a 5 pixel distance of the a detected feature.  Manually detected features are considered to be features identified by a human inspecting
 * a close-up of an image to establish whether a feature is centered correctly on a part of the image.  A human will inspect features to identify any that are misplaced on a part of an image."
 *
 * @{
 */

#ifndef SELECTION_TESTER_HPP
#define SELECTION_TESTER_HPP

/* --------------------------------------------------------------------------
 *
 * Includes
 *
 * --------------------------------------------------------------------------
 */
#include <FeaturesExtraction2D/FeaturesExtraction2DInterface.hpp>
#include <Errors/Assert.hpp>

#include <Types/CPP/VisualPointFeatureVector2D.hpp>
#include <Types/CPP/Frame.hpp>
#include <Types/CPP/Pose.hpp>
#include <Converters/MatToFrameConverter.hpp>

#include <stdlib.h>
#include <fstream>
#include <string>
#include <vector>
#include <boost/make_shared.hpp>

/* --------------------------------------------------------------------------
 *
 * Class definition
 *
 * --------------------------------------------------------------------------
 */
class SelectionTester
	{
	/* --------------------------------------------------------------------
	 * Public
	 * --------------------------------------------------------------------
	 */
	public:
		SelectionTester(const std::string& configurationFilePath, CDFF::DFN::FeaturesExtraction2DInterface* dfn);
		~SelectionTester();

		void SetFilesPaths(const std::string& inputImageFilePath, const std::string& numberReferenceFilePath, const std::string& precisionReferenceFilePath);
		void ExecuteDfn();
		bool IsSelectionValid(float numberPercentageThreshold, unsigned pixelOutlierThreshold, float outliersPercentageThreshold);

	/* --------------------------------------------------------------------
	 * Protected
	 * --------------------------------------------------------------------
	 */
	protected:

	/* --------------------------------------------------------------------
	 * Private
	 * --------------------------------------------------------------------
	 */
	private:
		std::string configurationFilePath;
		std::string inputImageFilePath;
		std::string numberReferenceFilePath;
		std::string precisionReferenceFilePath;
		FrameWrapper::FrameConstPtr inputFrame;
		VisualPointFeatureVector2DWrapper::VisualPointFeatureVector2DConstPtr outputFeaturesVector;
		cv::Mat numberKeypointsMatrix;
		cv::Mat precisionKeypointsMatrix;

		Converters::MatToFrameConverter frameConverter;
		CDFF::DFN::FeaturesExtraction2DInterface* dfn;

		bool inputImageWasLoaded;
		bool numberReferenceWasLoaded;
		bool precisionReferenceWasLoaded;

		void LoadInputImage();
		void LoadReferenceFeatures(const std::string& filePath, cv::Mat& keypointsMatrix);
		void ConfigureDfn();

		bool ValidateNumberOfKeypoints(float numberPercentageThreshold);
		bool ValidateKeypoints(unsigned pixelOutlierThreshold, float outliersPercentageThreshold);
		unsigned ComputePixelDistance(unsigned outputKeypointIndex, unsigned precisionReferenceKeypointIndex);
	};

#endif

/* SelectionTester.hpp */
/** @} */


text:
/**
 *  @copyright Copyright 2020 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 * 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 JPetGeantParserDecayTreeTest.cpp
 */

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetGeantParserDecayTreeTest
#include <boost/test/unit_test.hpp>

#include "JPetGeantDecayTree/JPetGeantDecayTree.h"

BOOST_AUTO_TEST_SUITE(FirstSuite)

BOOST_AUTO_TEST_CASE(branch_default_constructor)
{
  int testID = -1;

  Branch branch;

  BOOST_REQUIRE_EQUAL(branch.GetTrackID(), testID);
  BOOST_REQUIRE_EQUAL(branch.GetPrimaryBranchID(), testID);
}

BOOST_AUTO_TEST_CASE(branch_nonstandard_constructor)
{
  int primaryBranchID = 1;
  int trackID = 2;

  Branch branch(trackID, primaryBranchID);

  BOOST_REQUIRE_EQUAL(branch.GetTrackID(), trackID);
  BOOST_REQUIRE_EQUAL(branch.GetPrimaryBranchID(), primaryBranchID);
}

BOOST_AUTO_TEST_CASE(check_branch_setting_one_element)
{
  int primaryBranchID = 1;
  int trackID = 2;
  int nodeID = 3;
  InteractionType interactionType = InteractionType::kPrimaryGamma;

  Branch branch(trackID, primaryBranchID);
  branch.AddNodeID(nodeID, interactionType);

  BOOST_REQUIRE_EQUAL(branch.GetPrimaryNodeID(), nodeID);
  BOOST_REQUIRE_EQUAL(branch.GetLastNodeID(), nodeID);
  BOOST_REQUIRE_EQUAL(branch.GetPreviousNodeID(nodeID), nodeID);
  BOOST_REQUIRE_EQUAL(branch.GetInteractionType(nodeID), interactionType);
}

BOOST_AUTO_TEST_CASE(check_branch_setting_more_elements)
{
  int primaryBranchID = 1;
  int trackID = 2;
  int firstNodeID = 3;
  int secondNodeID = 13;
  int thirdNodeID = 113;
  InteractionType firstInteractionType = InteractionType::kPrimaryGamma;
  InteractionType secondInteractionType = InteractionType::kScattNonActivePart;
  InteractionType thirdInteractionType = InteractionType::kScattActivePart;

  Branch branch(trackID, primaryBranchID);
  branch.AddNodeID(firstNodeID, firstInteractionType);
  branch.AddNodeID(secondNodeID, secondInteractionType);
  branch.AddNodeID(thirdNodeID, thirdInteractionType);

  BOOST_REQUIRE_EQUAL(branch.GetPrimaryNodeID(), firstNodeID);
  BOOST_REQUIRE_EQUAL(branch.GetLastNodeID(), thirdNodeID);
  BOOST_REQUIRE_EQUAL(branch.GetPreviousNodeID(thirdNodeID), secondNodeID);
  BOOST_REQUIRE_EQUAL(branch.GetPreviousNodeID(secondNodeID), firstNodeID);
  BOOST_REQUIRE_EQUAL(branch.GetInteractionType(firstNodeID), firstInteractionType);
  BOOST_REQUIRE_EQUAL(branch.GetInteractionType(secondNodeID), secondInteractionType);
  BOOST_REQUIRE_EQUAL(branch.GetInteractionType(thirdNodeID), thirdInteractionType);
}

BOOST_AUTO_TEST_CASE(check_decayTree_creation_and_getting_branch)
{
  JPetGeantDecayTree decayTree;
  int primaryBranchID = -1;
  int firstTrackID = 2;
  int firstNodeID = 3;
  int secondNodeID = 13;
  int thirdNodeID = 113;
  int secondTrackID = 3;
  int secondBranchID = 1;
  int fourthNodeID = 3;
  int thirdTrackID = 5;
  int fifthNodeID = 30;

  InteractionType firstInteractionType = InteractionType::kPrimaryGamma;
  InteractionType secondInteractionType = InteractionType::kScattNonActivePart;
  InteractionType thirdInteractionType = InteractionType::kScattActivePart;
  InteractionType fourthInteractionType = InteractionType::kPrimaryGamma;
  InteractionType fifthInteractionType = InteractionType::kSecondaryPart;

  decayTree.AddNodeToBranch(firstNodeID, firstTrackID, firstInteractionType);
  decayTree.AddNodeToBranch(secondNodeID, firstTrackID, secondInteractionType);
  decayTree.AddNodeToBranch(thirdNodeID, firstTrackID, thirdInteractionType);
  decayTree.AddNodeToBranch(fourthNodeID, secondTrackID, fourthInteractionType);
  decayTree.AddNodeToBranch(fifthNodeID, thirdTrackID, fifthInteractionType);

  Branch firstBranch = decayTree.GetBranch(firstTrackID);
  Branch secondBranch = decayTree.GetBranch(secondTrackID);
  Branch thirdBranch = decayTree.GetBranch(thirdTrackID);

  BOOST_REQUIRE_EQUAL(firstBranch.GetPrimaryBranchID(), primaryBranchID);
  BOOST_REQUIRE_EQUAL(firstBranch.GetTrackID(), firstTrackID);
  BOOST_REQUIRE_EQUAL(firstBranch.GetPrimaryNodeID(), firstNodeID);
  BOOST_REQUIRE_EQUAL(firstBranch.GetLastNodeID(), thirdNodeID);
  BOOST_REQUIRE_EQUAL(firstBranch.GetPreviousNodeID(thirdNodeID), secondNodeID);
  BOOST_REQUIRE_EQUAL(firstBranch.GetPreviousNodeID(secondNodeID), firstNodeID);
  BOOST_REQUIRE_EQUAL(firstBranch.GetInteractionType(firstNodeID), firstInteractionType);
  BOOST_REQUIRE_EQUAL(firstBranch.GetInteractionType(secondNodeID), secondInteractionType);
  BOOST_REQUIRE_EQUAL(firstBranch.GetInteractionType(thirdNodeID), thirdInteractionType);

  BOOST_REQUIRE_EQUAL(secondBranch.GetPrimaryBranchID(), primaryBranchID);
  BOOST_REQUIRE_EQUAL(secondBranch.GetTrackID(), secondTrackID);
  BOOST_REQUIRE_EQUAL(secondBranch.GetPrimaryNodeID(), fourthNodeID);
  BOOST_REQUIRE_EQUAL(secondBranch.GetLastNodeID(), fourthNodeID);
  BOOST_REQUIRE_EQUAL(secondBranch.GetPreviousNodeID(fourthNodeID), fourthNodeID);
  BOOST_REQUIRE_EQUAL(secondBranch.GetInteractionType(fourthNodeID), fourthInteractionType);

  BOOST_REQUIRE_EQUAL(thirdBranch.GetPrimaryBranchID(), secondBranchID);
  BOOST_REQUIRE_EQUAL(thirdBranch.GetTrackID(), thirdTrackID);
  BOOST_REQUIRE_EQUAL(thirdBranch.GetPrimaryNodeID(), fifthNodeID);
  BOOST_REQUIRE_EQUAL(thirdBranch.GetLastNodeID(), fifthNodeID);
  BOOST_REQUIRE_EQUAL(thirdBranch.GetPreviousNodeID(fifthNodeID), fifthNodeID);
  BOOST_REQUIRE_EQUAL(thirdBranch.GetInteractionType(fifthNodeID), fifthInteractionType);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: BlurredChoise/j-pet-framework

max_issues_repo_name: BlurredChoise/j-pet-framework

max_forks_repo_name: BlurredChoise/j-pet-framework


text:
/**************************************************************************
 * Copyright (c) 2017-2019 by the mfmg authors                            *
 * All rights reserved.                                                   *
 *                                                                        *
 * This file is part of the mfmg library. mfmg is distributed under a BSD *
 * 3-clause license. For the licensing terms see the LICENSE file in the  *
 * top-level directory                                                    *
 *                                                                        *
 * SPDX-License-Identifier: BSD-3-Clause                                  *
 *************************************************************************/

#include <mfmg/common/instantiation.hpp>
#include <mfmg/common/operator.hpp>
#include <mfmg/dealii/dealii_hierarchy_helpers.hpp>
#include <mfmg/dealii/dealii_smoother.hpp>
#include <mfmg/dealii/dealii_solver.hpp>
#include <mfmg/dealii/dealii_trilinos_matrix_operator.hpp>
#include <mfmg/dealii/dealii_utils.hpp>

#include <deal.II/base/work_stream.h>
#include <deal.II/dofs/dof_accessor.h>

#include <EpetraExt_MatrixMatrix.h>
#include <Epetra_Map.h>

#include <boost/container_hash/hash.hpp>
#include <boost/smart_ptr/make_unique.hpp>

#include <unordered_map>

namespace mfmg
{
template <int dim, typename VectorType>
std::shared_ptr<Operator<VectorType>>
DealIIHierarchyHelpers<dim, VectorType>::get_global_operator(
    std::shared_ptr<MeshEvaluator> mesh_evaluator)
{
  // Downcast to DealIIMeshEvaluator
  auto dealii_mesh_evaluator =
      std::dynamic_pointer_cast<DealIIMeshEvaluator<dim>>(mesh_evaluator);

  auto system_matrix =
      std::make_shared<dealii::TrilinosWrappers::SparseMatrix>();

  // Call user function to fill in the system matrix
  dealii_mesh_evaluator->evaluate_global(
      dealii_mesh_evaluator->get_dof_handler(),
      dealii_mesh_evaluator->get_constraints(), *system_matrix);

  std::shared_ptr<Operator<VectorType>> global_operator =
      std::make_shared<DealIITrilinosMatrixOperator<VectorType>>(system_matrix);

  return global_operator;
}

template <int dim, typename VectorType>
std::shared_ptr<Operator<VectorType>>
DealIIHierarchyHelpers<dim, VectorType>::build_restrictor(
    MPI_Comm comm, std::shared_ptr<MeshEvaluator> mesh_evaluator,
    std::shared_ptr<boost::property_tree::ptree const> params)
{
  // Downcast to DealIIMeshEvaluator
  auto dealii_mesh_evaluator =
      std::dynamic_pointer_cast<DealIIMeshEvaluator<dim>>(mesh_evaluator);

  auto eigensolver_params = params->get_child("eigensolver");
  int n_eigenvectors = eigensolver_params.get("number of eigenvectors", 1);
  double tolerance = eigensolver_params.get("tolerance", 1e-14);

  auto restrictor_matrix =
      std::make_shared<dealii::TrilinosWrappers::SparseMatrix>();

  auto locally_relevant_global_diag = dealii_mesh_evaluator->get_diagonal();

  bool fast_ap = params->get("fast_ap", false);
  auto agglomerate_params = params->get_child("agglomeration");
  if (fast_ap)
  {
    AMGe_host<dim, DealIIMeshEvaluator<dim>, VectorType> amge(
        comm, dealii_mesh_evaluator->get_dof_handler(), eigensolver_params);
    std::vector<double> eigenvalues;
    // We use unique_ptr because we want to use a special constructor when we
    // fill the matrix, i.e., we don't want to provide a SparsityPattern. All
    // the reinit functions require a SparsityPattern.
    std::unique_ptr<dealii::TrilinosWrappers::SparseMatrix> eigenvector_matrix;
    std::unique_ptr<dealii::TrilinosWrappers::SparseMatrix>
        delta_eigenvector_matrix;
    amge.setup_restrictor(agglomerate_params, n_eigenvectors, tolerance,
                          *dealii_mesh_evaluator, locally_relevant_global_diag,
                          restrictor_matrix, eigenvector_matrix,
                          delta_eigenvector_matrix, eigenvalues);

    dealii::TrilinosWrappers::SparseMatrix delta_correction_matrix(
        eigenvector_matrix->locally_owned_range_indices(),
        eigenvector_matrix->locally_owned_domain_indices(),
        eigenvector_matrix->get_mpi_communicator());

    // Need to apply delta_eigenvector_matrix
    std::vector<std::vector<unsigned int>> interior_agglomerates;
    std::vector<std::vector<unsigned int>> halo_agglomerates;
    std::tie(interior_agglomerates, halo_agglomerates) =
        amge.build_boundary_agglomerates();
    std::unordered_map<std::pair<unsigned int, unsigned int>, double,
                       boost::hash<std::pair<unsigned int, unsigned int>>>
        delta_correction_acc;
    bool is_halo_agglomerate = false;

    // In case there are no patches we own, we still need to construct the
    // restriction operators. We set the number of eigenvalues to zero instead
    // of returning early and duplicating the setup.
    unsigned int const n_local_eigenvectors =
        interior_agglomerates.empty()
            ? 0
            : eigenvector_matrix->locally_owned_range_indices().n_elements() /
                  interior_agglomerates.size();

    for (auto const &agglomerates_vector :
         {interior_agglomerates, halo_agglomerates})
    {
      struct ScratchData
      {
      } scratch_data;
      struct CopyData
      {
        std::vector<dealii::types::global_dof_index> rows;
        std::vector<dealii::types::global_dof_index> cols;
        std::vector<std::vector<dealii::TrilinosScalar>> values_per_row;
      } copy_data;

      auto worker =
          [&](const std::vector<std::vector<unsigned int>>::const_iterator
                  &agglomerate_it,
              ScratchData &, CopyData &local_copy_data) {
            dealii::Triangulation<dim> agglomerate_triangulation;
            std::map<typename dealii::Triangulation<dim>::active_cell_iterator,
                     typename dealii::DoFHandler<dim>::active_cell_iterator>
                patch_to_global_map;
            amge.build_agglomerate_triangulation(*agglomerate_it,
                                                 agglomerate_triangulation,
                                                 patch_to_global_map);
            if (patch_to_global_map.empty())
            {
              return;
            }

            // Now that we have the triangulation, we can do the evaluation on
            // the agglomerate
            dealii::DoFHandler<dim> agglomerate_dof_handler(
                agglomerate_triangulation);
            dealii::AffineConstraints<double> agglomerate_constraints;
            dealii::SparsityPattern agglomerate_sparsity_pattern;
            dealii::SparseMatrix<ScalarType> agglomerate_system_matrix;
            // Call user function to build the system matrix
            dealii_mesh_evaluator->evaluate_agglomerate(
                agglomerate_dof_handler, agglomerate_constraints,
                agglomerate_sparsity_pattern, agglomerate_system_matrix);

            // Put the result in the matrix
            // Compute the map between the local and the global dof indices.
            local_copy_data.rows.resize(n_local_eigenvectors);

            local_copy_data.cols = amge.compute_dof_index_map(
                patch_to_global_map, agglomerate_dof_handler);
            auto const &dof_indices_map = local_copy_data.cols;
            unsigned int const n_elem = dof_indices_map.size();

            // We need a clean reset for the values we are going to store.
            // Otherwise, we would accumulate values across patches
            // corresponding to different degrees of freedom.
            local_copy_data.values_per_row.resize(n_local_eigenvectors);
            std::fill(local_copy_data.values_per_row.begin(),
                      local_copy_data.values_per_row.end(),
                      std::vector<dealii::TrilinosScalar>(n_elem));

            unsigned int const i = agglomerate_it - agglomerates_vector.begin();

            for (unsigned int j = 0; j < n_local_eigenvectors; ++j)
            {
              unsigned int const local_row = i * n_local_eigenvectors + j;
              unsigned int const global_row =
                  eigenvector_matrix->locally_owned_range_indices()
                      .nth_index_in_set(local_row);
              // Get the vector used for the matrix-vector multiplication
              dealii::Vector<ScalarType> delta_eig(n_elem);
              if (is_halo_agglomerate)
              {
                for (unsigned int k = 0; k < n_elem; ++k)
                {
                  delta_eig[k] =
                      delta_eigenvector_matrix->el(global_row,
                                                   dof_indices_map[k]) +
                      eigenvector_matrix->el(global_row, dof_indices_map[k]);
                }
              }
              else
              {
                for (unsigned int k = 0; k < n_elem; ++k)
                {
                  delta_eig[k] = delta_eigenvector_matrix->el(
                      global_row, dof_indices_map[k]);
                }
              }

              // Perform the matrix-vector multiplication
              dealii::Vector<ScalarType> correction(n_elem);
              agglomerate_system_matrix.vmult(correction, delta_eig);

              // Store the values the delta correction matrix is to be filled
              // with.
              local_copy_data.rows[j] = global_row;
              std::transform(correction.begin(), correction.end(),
                             local_copy_data.values_per_row[j].begin(),
                             local_copy_data.values_per_row[j].begin(),
                             std::plus<double>());
            }
          };

      auto copier = [&](const CopyData &local_copy_data) {
        for (unsigned int i = 0; i < local_copy_data.rows.size(); ++i)
        {
          // Since we didn't provide a sparsity pattern this "set" operation
          // actually acts as an "add" operation until "compress" is called.
          delta_correction_matrix.set(
              local_copy_data.rows[i], local_copy_data.cols.size(),
              local_copy_data.cols.data(),
              local_copy_data.values_per_row[i].data(), true);
        }
      };

      dealii::WorkStream::run(agglomerates_vector.begin(),
                              agglomerates_vector.end(), worker, copier,
                              scratch_data, copy_data);

      is_halo_agglomerate = true;
    }

    // Fill delta_correction_matrix
    delta_correction_matrix.compress(dealii::VectorOperation::insert);

    // Scale the eigenvectors by their corresponding eigenvalues.
    // It turned out that accessing the individual matrix entries through the
    // deal.II TrilinosWrapper::SparseMatrix::begin() interface is much slower
    // than constructing a representation of the eigenvalues as
    // Epetra_MultiVector and calling a Epetra_CrsMatrix member function.
    auto const range_start = eigenvector_matrix->local_range().first;
    auto const range_end = eigenvector_matrix->local_range().second;

    dealii::IndexSet locally_owned_elements(eigenvector_matrix->m());
    locally_owned_elements.add_range(range_start, range_end);
    dealii::TrilinosWrappers::MPI::Vector vector_eigenvalues(
        locally_owned_elements, comm);
    std::vector<dealii::types::global_dof_index> local_indices(
        eigenvalues.size());
    std::iota(local_indices.begin(), local_indices.end(), range_start);
    vector_eigenvalues.set(local_indices, eigenvalues);
    vector_eigenvalues.compress(dealii::VectorOperation::insert);

    Epetra_MultiVector &dummy_multi_vector =
        vector_eigenvalues.trilinos_vector();
    auto &dummy_matrix =
        const_cast<Epetra_CrsMatrix &>(eigenvector_matrix->trilinos_matrix());
    dummy_matrix.LeftScale(*dummy_multi_vector(0));

    eigenvector_matrix->compress(dealii::VectorOperation::insert);

    // Add the eigenvector matrix and the delta correction matrix to create ap
    Epetra_CrsMatrix *ap = nullptr;
    // We want to use functions that have been deprecated in deal.II but they
    // won't be removed in the foreseeable future
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
    Epetra_Map range_map = eigenvector_matrix->domain_partitioner();
    Epetra_Map domain_map = eigenvector_matrix->range_partitioner();
#pragma GCC diagnostic pop
    bool const transpose = true;
    int error_code = EpetraExt::MatrixMatrix::Add(
        eigenvector_matrix->trilinos_matrix(), transpose, 1.,
        delta_correction_matrix.trilinos_matrix(), transpose, 1., ap);
    ap->FillComplete(domain_map, range_map);
    ASSERT(error_code == 0, "Problem when adding matrices");

    // Copy the Epetra_CrsMatrix to a dealii::TrilinosWrappers::SparseMatrix
    auto dealii_ap = std::make_shared<dealii::TrilinosWrappers::SparseMatrix>();
    dealii_ap->reinit(*ap);
    delete ap;

    _ap_operator.reset(new DealIITrilinosMatrixOperator<VectorType>(dealii_ap));
  }
  else
  {
    AMGe_host<dim, DealIIMeshEvaluator<dim>, VectorType> amge(
        comm, dealii_mesh_evaluator->get_dof_handler(), eigensolver_params);

    amge.setup_restrictor(agglomerate_params, n_eigenvectors, tolerance,
                          *dealii_mesh_evaluator, locally_relevant_global_diag,
                          *restrictor_matrix);
  }

  std::shared_ptr<Operator<VectorType>> op(
      new DealIITrilinosMatrixOperator<VectorType>(restrictor_matrix));

  return op;
}

template <int dim, typename VectorType>
std::shared_ptr<Smoother<VectorType>>
DealIIHierarchyHelpers<dim, VectorType>::build_smoother(
    std::shared_ptr<Operator<VectorType> const> op,
    std::shared_ptr<boost::property_tree::ptree const> params)
{
  return std::make_shared<DealIISmoother<VectorType>>(op, params);
}

template <int dim, typename VectorType>
std::shared_ptr<Solver<VectorType>>
DealIIHierarchyHelpers<dim, VectorType>::build_coarse_solver(
    std::shared_ptr<Operator<VectorType> const> op,
    std::shared_ptr<boost::property_tree::ptree const> params)
{
  return std::make_shared<DealIISolver<VectorType>>(op, params);
}

template <int dim, typename VectorType>
std::shared_ptr<Operator<VectorType>>
DealIIHierarchyHelpers<dim, VectorType>::fast_multiply_transpose()
{
  return _ap_operator;
}

} // namespace mfmg

// Explicit Instantiation
INSTANTIATE_DIM_VECTORTYPE(TUPLE(DealIIHierarchyHelpers))

ext: cc

max_stars_repo_name: Rombur/mfmg

max_issues_repo_name: Rombur/mfmg

max_forks_repo_name: Rombur/mfmg


text:
#pragma once

#include <xgt/protocol/block.hpp>

#include <xgt/plugins/database_api/database_api.hpp>
#include <xgt/plugins/p2p/p2p_plugin.hpp>
#include <xgt/plugins/chain/chain_plugin.hpp>
#include <xgt/plugins/json_rpc/utility.hpp>
#include <xgt/plugins/transaction_status/transaction_status_objects.hpp>

#include <fc/optional.hpp>
#include <fc/variant.hpp>
#include <fc/vector.hpp>

#include <boost/thread/mutex.hpp>

namespace xgt { namespace plugins { namespace transaction_api {

using std::vector;
using fc::variant;
using fc::optional;
using xgt::plugins::json_rpc::void_type;

using xgt::protocol::signed_transaction;
using xgt::protocol::transaction_id_type;
using xgt::protocol::signed_block;

using namespace chain;

typedef vector< variant > get_transaction_hex_args;

typedef string get_transaction_hex_return;

typedef vector< variant > broadcast_transaction_args;

struct broadcast_transaction_return
{
   broadcast_transaction_return() {}
   broadcast_transaction_return( transaction_id_type txid )
   : id(txid) {}

   transaction_id_type   id;
};

struct broadcast_block_args
{
   signed_block   block;
};

typedef void_type broadcast_block_return;

struct find_transaction_args
{
   chain::transaction_id_type transaction_id;
   fc::optional< fc::time_point_sec > expiration;
};

struct find_transaction_return
{
   transaction_status::transaction_status status;
   fc::optional< uint32_t > block_num;
};

namespace detail{ class transaction_api_impl; }

class transaction_api
{
   public:
      transaction_api();
      ~transaction_api();

      DECLARE_API(
         (get_transaction_hex)
         (broadcast_transaction)
         (broadcast_block)
         (find_transaction)
      )

   private:
      friend class transaction_api_plugin;
      void api_startup();

      std::unique_ptr< detail::transaction_api_impl > my;
};

} } } // xgt::plugins::transaction_api

FC_REFLECT( xgt::plugins::transaction_api::broadcast_transaction_return,
   (id) )

FC_REFLECT( xgt::plugins::transaction_api::broadcast_block_args,
   (block) )

FC_REFLECT( xgt::plugins::transaction_api::find_transaction_args,
   (transaction_id)
   (expiration) )

FC_REFLECT( xgt::plugins::transaction_api::find_transaction_return,
   (status)
   (block_num) )


text:
#include <iostream>
#include <boost/format.hpp>
#include <stdlib.h>
#include <exception>

inline boost::format safe_format(boost::format &fmt)
{
}

template<typename First, typename... Rest>
void safe_format(boost::format &fmt, const First& first, const Rest&... rest)
{
  fmt = fmt % first;
}

template<typename First, typename... Rest>
std::string safe_sprintf(const char *fmt, const First& first, const Rest&... rest)
{
  try
  {
    boost::format bfmt(fmt);
    safe_format(bfmt, first, rest...);
    std::cout << bfmt << std::endl;
    return "";
  }
  catch (std::exception &e)
  {
    std::cerr << e.what() << std::endl;
    exit(EXIT_FAILURE);
  }
}

int main()
{
  std::cout << safe_sprintf("Hello %s, %02d, %.3f\n", "world", 3, 1.2);
  return 0;
}