text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
 * Copyright (c) 2011-2015  Regents of the University of California.
 *
 * This file is part of ndnSIM. See AUTHORS for complete list of ndnSIM authors and
 * contributors.
 *
 * ndnSIM is free software: you can redistribute it and/or modify it under the terms
 * of the GNU General Public License as published by the Free Software Foundation,
 * either version 3 of the License, or (at your option) any later version.
 *
 * ndnSIM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 * PURPOSE.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * ndnSIM, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
 **/

#ifndef BOOST_GRAPH_NDN_GLOBAL_ROUTING_HELPER_H
#define BOOST_GRAPH_NDN_GLOBAL_ROUTING_HELPER_H

/// @cond include_hidden

#include "ns3/ndnSIM/model/ndn-common.hpp"

#include <boost/graph/graph_traits.hpp>
#include <boost/graph/properties.hpp>
#include <boost/ref.hpp>

#include "ns3/ndnSIM/model/ndn-global-router.hpp"

#include "ns3/node-list.h"
#include "ns3/channel-list.h"

#include <list>
#include <map>

namespace boost {

class NdnGlobalRouterGraph {
public:
  typedef ns3::Ptr<ns3::ndn::GlobalRouter> Vertice;
  typedef uint16_t edge_property_type;
  typedef uint32_t vertex_property_type;

  NdnGlobalRouterGraph()
  {
    for (ns3::NodeList::Iterator node = ns3::NodeList::Begin(); node != ns3::NodeList::End();
         node++) {
      ns3::Ptr<ns3::ndn::GlobalRouter> gr = (*node)->GetObject<ns3::ndn::GlobalRouter>();
      if (gr != 0)
        m_vertices.push_back(gr);
    }

    for (ns3::ChannelList::Iterator channel = ns3::ChannelList::Begin();
         channel != ns3::ChannelList::End(); channel++) {
      ns3::Ptr<ns3::ndn::GlobalRouter> gr = (*channel)->GetObject<ns3::ndn::GlobalRouter>();
      if (gr != 0)
        m_vertices.push_back(gr);
    }
  }

  const std::list<Vertice>&
  GetVertices() const
  {
    return m_vertices;
  }

public:
  std::list<Vertice> m_vertices;
};

class ndn_global_router_graph_category : public virtual vertex_list_graph_tag,
                                         public virtual incidence_graph_tag {
};

template<>
struct graph_traits<NdnGlobalRouterGraph> {
  // Graph concept
  typedef NdnGlobalRouterGraph::Vertice vertex_descriptor;
  typedef ns3::ndn::GlobalRouter::Incidency edge_descriptor;
  typedef directed_tag directed_category;
  typedef disallow_parallel_edge_tag edge_parallel_category;
  typedef ndn_global_router_graph_category traversal_category;

  // VertexList concept
  typedef std::list<vertex_descriptor>::const_iterator vertex_iterator;
  typedef size_t vertices_size_type;

  // AdjacencyGraph concept
  typedef ns3::ndn::GlobalRouter::IncidencyList::iterator out_edge_iterator;
  typedef size_t degree_size_type;

  // typedef size_t edges_size_type;
};

} // namespace boost

namespace boost {

inline graph_traits<NdnGlobalRouterGraph>::vertex_descriptor
source(graph_traits<NdnGlobalRouterGraph>::edge_descriptor e, const NdnGlobalRouterGraph& g)
{
  return std::get<0>(e);
}

inline graph_traits<NdnGlobalRouterGraph>::vertex_descriptor
target(graph_traits<NdnGlobalRouterGraph>::edge_descriptor e, const NdnGlobalRouterGraph& g)
{
  return std::get<2>(e);
}

inline std::pair<graph_traits<NdnGlobalRouterGraph>::vertex_iterator,
                 graph_traits<NdnGlobalRouterGraph>::vertex_iterator>
vertices(const NdnGlobalRouterGraph& g)
{
  return make_pair(g.GetVertices().begin(), g.GetVertices().end());
}

inline graph_traits<NdnGlobalRouterGraph>::vertices_size_type
num_vertices(const NdnGlobalRouterGraph& g)
{
  return g.GetVertices().size();
}

inline std::pair<graph_traits<NdnGlobalRouterGraph>::out_edge_iterator,
                 graph_traits<NdnGlobalRouterGraph>::out_edge_iterator>
out_edges(graph_traits<NdnGlobalRouterGraph>::vertex_descriptor u, const NdnGlobalRouterGraph& g)
{
  return std::make_pair(u->GetIncidencies().begin(), u->GetIncidencies().end());
}

inline graph_traits<NdnGlobalRouterGraph>::degree_size_type
out_degree(graph_traits<NdnGlobalRouterGraph>::vertex_descriptor u, const NdnGlobalRouterGraph& g)
{
  return u->GetIncidencies().size();
}

//////////////////////////////////////////////////////////////
// Property maps

struct EdgeWeights {
  EdgeWeights(const NdnGlobalRouterGraph& graph)
    : m_graph(graph)
  {
  }

private:
  const NdnGlobalRouterGraph& m_graph;
};

struct VertexIds {
  VertexIds(const NdnGlobalRouterGraph& graph)
    : m_graph(graph)
  {
  }

private:
  const NdnGlobalRouterGraph& m_graph;
};

template<>
struct property_map<NdnGlobalRouterGraph, edge_weight_t> {
  typedef const EdgeWeights const_type;
  typedef EdgeWeights type;
};

template<>
struct property_map<NdnGlobalRouterGraph, vertex_index_t> {
  typedef const VertexIds const_type;
  typedef VertexIds type;
};

template<>
struct property_traits<EdgeWeights> {
  // Metric property map
  typedef std::tuple<std::shared_ptr<nfd::Face>, uint16_t, double> value_type;
  typedef std::tuple<std::shared_ptr<nfd::Face>, uint16_t, double> reference;
  typedef ns3::ndn::GlobalRouter::Incidency key_type;
  typedef readable_property_map_tag category;
};

const property_traits<EdgeWeights>::value_type WeightZero(nullptr, 0, 0.0);
const property_traits<EdgeWeights>::value_type
  WeightInf(nullptr, std::numeric_limits<uint16_t>::max(), 0.0);

struct WeightCompare : public std::binary_function<property_traits<EdgeWeights>::reference,
                                                   property_traits<EdgeWeights>::reference, bool> {
  bool
  operator()(std::tuple<std::shared_ptr<nfd::Face>, uint32_t, double> a,
             std::tuple<std::shared_ptr<nfd::Face>, uint32_t, double> b) const
  {
    return std::get<1>(a) < std::get<1>(b);
  }

  bool
  operator()(property_traits<EdgeWeights>::reference a, uint32_t b) const
  {
    return std::get<1>(a) < b;
  }

  bool
  operator()(uint32_t a, uint32_t b) const
  {
    return a < b;
  }
};

struct WeightCombine
  : public std::binary_function<uint32_t, property_traits<EdgeWeights>::reference, uint32_t> {
  uint32_t
  operator()(uint32_t a, property_traits<EdgeWeights>::reference b) const
  {
    return a + std::get<1>(b);
  }

  std::tuple<std::shared_ptr<nfd::Face>, uint32_t, double>
  operator()(std::tuple<std::shared_ptr<nfd::Face>, uint32_t, double> a,
             property_traits<EdgeWeights>::reference b) const
  {
    if (std::get<0>(a) == nullptr)
      return std::make_tuple(std::get<0>(b), std::get<1>(a) + std::get<1>(b),
                             std::get<2>(a) + std::get<2>(b));
    else
      return std::make_tuple(std::get<0>(a), std::get<1>(a) + std::get<1>(b),
                             std::get<2>(a) + std::get<2>(b));
  }
};

template<>
struct property_traits<VertexIds> {
  // Metric property map
  typedef uint32_t value_type;
  typedef uint32_t reference;
  typedef ns3::Ptr<ns3::ndn::GlobalRouter> key_type;
  typedef readable_property_map_tag category;
};

inline EdgeWeights
get(edge_weight_t, const NdnGlobalRouterGraph& g)
{
  return EdgeWeights(g);
}

inline VertexIds
get(vertex_index_t, const NdnGlobalRouterGraph& g)
{
  return VertexIds(g);
}

template<class M, class K, class V>
inline void
put(reference_wrapper<M> mapp, K a, V p)
{
  mapp.get()[a] = p;
}

// void
// put (cref< std::map< ns3::Ptr<ns3::ndn::GlobalRouter>, ns3::Ptr<ns3::ndn::GlobalRouter> > > map,

inline uint32_t
get(const boost::VertexIds&, ns3::Ptr<ns3::ndn::GlobalRouter>& gr)
{
  return gr->GetId();
}

inline property_traits<EdgeWeights>::reference
get(const boost::EdgeWeights&, ns3::ndn::GlobalRouter::Incidency& edge)
{
  if (std::get<1>(edge) == 0)
    return property_traits<EdgeWeights>::reference(nullptr, 0, 0.0);
  else {
    return property_traits<EdgeWeights>::reference(std::get<1>(edge),
                                                   static_cast<uint16_t>(
                                                     std::get<1>(edge)->getMetric()),
                                                   0.0);
  }
}

struct PredecessorsMap
  : public std::map<ns3::Ptr<ns3::ndn::GlobalRouter>, ns3::Ptr<ns3::ndn::GlobalRouter>> {
};

template<>
struct property_traits<reference_wrapper<PredecessorsMap>> {
  // Metric property map
  typedef ns3::Ptr<ns3::ndn::GlobalRouter> value_type;
  typedef ns3::Ptr<ns3::ndn::GlobalRouter> reference;
  typedef ns3::Ptr<ns3::ndn::GlobalRouter> key_type;
  typedef read_write_property_map_tag category;
};

struct DistancesMap : public std::map<ns3::Ptr<ns3::ndn::GlobalRouter>,
                                      std::tuple<std::shared_ptr<nfd::Face>, uint32_t, double>> {
};

template<>
struct property_traits<reference_wrapper<DistancesMap>> {
  // Metric property map
  typedef std::tuple<std::shared_ptr<nfd::Face>, uint32_t, double> value_type;
  typedef std::tuple<std::shared_ptr<nfd::Face>, uint32_t, double> reference;
  typedef ns3::Ptr<ns3::ndn::GlobalRouter> key_type;
  typedef read_write_property_map_tag category;
};

} // boost

namespace std {
template<>
class numeric_limits<std::tuple<std::shared_ptr<nfd::Face>, uint32_t, double>>
{
public:
  typedef std::tuple<std::shared_ptr<nfd::Face>, uint32_t, double> value;
  static value
  max()
  {
    return boost::WeightInf;
  }
};
}

namespace boost {

inline std::tuple<std::shared_ptr<nfd::Face>, uint32_t, double>
get(DistancesMap& map, ns3::Ptr<ns3::ndn::GlobalRouter> key)
{
  boost::DistancesMap::iterator i = map.find(key);
  if (i == map.end())
    return std::tuple<std::shared_ptr<nfd::Face>, uint32_t,
                      double>(nullptr, std::numeric_limits<uint32_t>::max(), 0.0);
  else
    return i->second;
}

} // namespace boost

/// @endcond

#endif // BOOST_GRAPH_NDN_GLOBAL_ROUTING_HELPER_H

max_stars_repo_name: NDNLink/NDN-Chord

max_issues_repo_name: NDNLink/NDN-Chord

max_forks_repo_name: NDNLink/NDN-Chord


text:
// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt
/*

    This is an example illustrating the use of the thread_pool
    object from the dlib C++ Library.

    This is a very simple example.  It creates a thread pool with 3
    threads and then sends a few simple tasks to the pool.
*/

#include <dlib/threads.h>
#include <dlib/misc_api.h>  // for dlib::sleep
#include <dlib/logger.h>
#include <vector>

using namespace dlib;

// We will be using the dlib logger object to print out messages in this example
// because its output is timestamped and labeled with the thread that the log
// message came from.  So this will make it easier to see what is going on in
// this example.  Here we make an instance of the logger.  See the logger
// documentation and examples for detailed information regarding its use.
logger dlog("main");

// Here we make an instance of the thread pool object
thread_pool tp(3);

// ----------------------------------------------------------------------------------------

class test
{
    /*
        The thread_pool accepts "tasks" from the user and schedules them for
        execution in one of its threads when one becomes available.  Each task
        is just a request to call a function.  So here we create a class called
        test with a few member functions which we will have the thread pool call
        as tasks.
    */
public:

    void task()
    {
        dlog << LINFO << "task start";

        future<int> var;

        var = 1;

        // Here we ask the thread pool to call this->subtask() and this->subtask2().
        // Note that calls to add_task() will return immediately if there is an
        // available thread to hand the task off to.  However, if there isn't a
        // thread ready then add_task() blocks until there is such a thread.
        // Also note that since task() is executed within the thread pool (see main() below)
        // calls to add_task() will execute the requested task within the calling thread
        // in cases where the thread pool is full.  This means it is always safe to
        // spawn subtasks from within another task, which is what we are doing here.
        tp.add_task(*this,&test::subtask,var); // schedule call to this->subtask(var)
        tp.add_task(*this,&test::subtask2);    // schedule call to this->subtask2()

        // Since var is a future, this line will wait for the test::subtask task to
        // finish before allowing us to access the contents of var.  Then var will
        // return the integer it contains.  In this case result will be assigned
        // the value 2 since var was incremented by subtask().
        int result = var;
        // print out the result
        dlog << LINFO << "var = " << result;

        // Wait for all the tasks we have started to finish.  Note that
        // wait_for_all_tasks() only waits for tasks which were started
        // by the calling thread.  So you don't have to worry about other
        // unrelated parts of your application interfering.  In this case
        // it just waits for subtask2() to finish.
        tp.wait_for_all_tasks();

        dlog << LINFO << "task end" ;
    }

    void subtask(int& a)
    {
        dlib::sleep(200);
        a = a + 1;
        dlog << LINFO << "subtask end ";
    }

    void subtask2()
    {
        dlib::sleep(300);
        dlog << LINFO << "subtask2 end ";
    }

};

// ----------------------------------------------------------------------------------------

class add_value
{
public:
    add_value(int value):val(value) { }

    void operator()( int& a )
    {
        a += val;
    }

private:
    int val;
};

// ----------------------------------------------------------------------------------------

int main()
{
    // tell the logger to print out everything
    dlog.set_level(LALL);

    dlog << LINFO << "schedule a few tasks";

    test mytask;
    // Schedule the thread pool to call mytask.task().  Note that all forms of add_task()
    // pass in the task object by reference.  This means you must make sure, in this case,
    // that mytask isn't destructed until after the task has finished executing.
    tp.add_task(mytask, &test::task);

    // You can also pass task objects to a thread pool by value.  So in this case we don't
    // have to worry about keeping our own instance of the task.  Here we construct a temporary
    // add_value object and pass it right in and everything works like it should.
    future<int> num = 3;
    tp.add_task_by_value(add_value(7), num);  // adds 7 to num
    int result = num.get();
    dlog << LINFO << "result = " << result;   // prints result = 10

// uncomment this line if your compiler supports the new C++0x lambda functions
//#define COMPILER_SUPPORTS_CPP0X_LAMBDA_FUNCTIONS
#ifdef COMPILER_SUPPORTS_CPP0X_LAMBDA_FUNCTIONS

    // In the above examples we had to explicitly create task objects which is
    // inconvenient.  If you have a compiler which supports C++0x lambda functions
    // then you can use the following simpler method.

    // make a task which will just log a message
    tp.add_task_by_value([](){
                         dlog << LINFO << "A message from a lambda function running in another thread.";
                         });

    // Here we make 10 different tasks, each assigns a different value into
    // the elements of the vector vect.
    std::vector<int> vect(10);
    for (unsigned long i = 0; i < vect.size(); ++i)
    {
        // Make a lambda function which takes vect by reference and i by value.  So what
        // will happen is each assignment statement will run in a thread in the thread_pool.
        tp.add_task_by_value([&vect,i](){
                             vect[i] = i;
                             });
    }
    // Wait for all tasks which were requested by the main thread to complete.
    tp.wait_for_all_tasks();
    for (unsigned long i = 0; i < vect.size(); ++i)
    {
        dlog << LINFO << "vect["<<i<<"]: " << vect[i];
    }
#endif

    /* A possible run of this program might produce the following output (the first column is
       the time the log message occurred and the value in [] is the thread id for the thread
       that generated the log message):

    1 INFO  [0] main: schedule a few tasks
    1 INFO  [1] main: task start
    1 INFO  [0] main: result = 10
  201 INFO  [2] main: subtask end
  201 INFO  [1] main: var = 2
  201 INFO  [2] main: A message from a lambda function running in another thread.
  301 INFO  [3] main: subtask2 end
  301 INFO  [1] main: task end
  301 INFO  [0] main: vect[0]: 0
  301 INFO  [0] main: vect[1]: 1
  301 INFO  [0] main: vect[2]: 2
  301 INFO  [0] main: vect[3]: 3
  301 INFO  [0] main: vect[4]: 4
  301 INFO  [0] main: vect[5]: 5
  301 INFO  [0] main: vect[6]: 6
  301 INFO  [0] main: vect[7]: 7
  301 INFO  [0] main: vect[8]: 8
  301 INFO  [0] main: vect[9]: 9
    */
}

ext: cpp

max_stars_repo_name: ytobah/dlib-mod

max_issues_repo_name: ytobah/dlib-mod

max_forks_repo_name: ytobah/dlib-mod


text:
//==================================================================================================
/**
  Copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
**/
//==================================================================================================

#ifndef BOOST_SIMD_FUNCTION_SIMD_IS_NORMAL_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_SIMD_IS_NORMAL_HPP_INCLUDED

#include <boost/simd/function/scalar/is_normal.hpp>
#include <boost/simd/arch/common/generic/function/autodispatcher.hpp>
#include <boost/simd/arch/common/simd/function/is_normal.hpp>

#endif

ext: hpp

max_stars_repo_name: xmar/pythran

max_issues_repo_name: xmar/pythran

max_forks_repo_name: xmar/pythran


text:
#pragma once

#include <boost/exception/all.hpp>
#include <boost/stacktrace.hpp>

#include <google/protobuf/message.h>
#include <google/protobuf/util/json_util.h>

#include <nlohmann/json.hpp>

#include <koinos/log.hpp>

#define _DETAIL_KOINOS_INIT_VA_ARGS( ... ) init __VA_ARGS__

#define KOINOS_THROW( exception, msg, ... )                                      \
do {                                                                             \
   exception _e( msg );                                                          \
   koinos::detail::json_initializer init( _e );                                  \
   _DETAIL_KOINOS_INIT_VA_ARGS( __VA_ARGS__ );                                   \
   BOOST_THROW_EXCEPTION(                                                        \
      _e                                                                         \
      << koinos::detail::exception_stacktrace( boost::stacktrace::stacktrace() ) \
   );                                                                            \
} while(0)

#define KOINOS_ASSERT( cond, exc_name, msg, ... )     \
   do {                                               \
      if( !(cond) )                                   \
      {                                               \
         KOINOS_THROW( exc_name, msg, __VA_ARGS__ );  \
      }                                               \
   } while (0)

#define KOINOS_CAPTURE_CATCH_AND_RETHROW( ... ) \
catch ( koinos::exception& _e )                 \
{                                               \
   koinos::detail::json_initializer init( _e ); \
   _DETAIL_KOINOS_INIT_VA_ARGS( __VA_ARGS__ );  \
   throw;                                       \
}                                               \
catch ( std::exception& )                       \
{                                               \
   throw;                                       \
}                                               \
catch ( boost::exception& )                     \
{                                               \
   throw;                                       \
}                                               \
catch ( ... )                                   \
{                                               \
   throw;                                       \
}

#define KOINOS_CATCH_LOG_AND_RETHROW( log_level )           \
catch( koinos::exception& _e )                              \
{                                                           \
   LOG( log_level ) << boost::diagnostic_information( _e ); \
   throw;                                                   \
}                                                           \
catch ( std::exception& _e )                                \
{                                                           \
   LOG( log_level ) << _e.what();                           \
   throw;                                                   \
}                                                           \
catch ( boost::exception& _e )                              \
{                                                           \
   LOG( log_level ) << boost::diagnostic_information( _e ); \
   throw;                                                   \
}                                                           \
catch ( ... )                                               \
{                                                           \
   LOG( log_level ) << "caught unknown exception type";     \
   throw;                                                   \
}

#define KOINOS_CATCH_AND_LOG( log_level )                   \
catch( koinos::exception& _e )                              \
{                                                           \
   LOG( log_level ) << boost::diagnostic_information( _e ); \
}                                                           \
catch ( std::exception& _e )                                \
{                                                           \
   LOG( log_level ) << _e.what();                           \
}                                                           \
catch ( boost::exception& _e )                              \
{                                                           \
   LOG( log_level ) << boost::diagnostic_information( _e ); \
}                                                           \
catch ( ... )                                               \
{                                                           \
   LOG( log_level ) << "caught unknown exception type";     \
}

#define KOINOS_CATCH_AND_GET_JSON( j ) \
catch( koinos::exception& _e )         \
{                                      \
   j = _e.get_json();                   \
}

#define KOINOS_CATCH_LOG_AND_GET_JSON( log_level, j )       \
catch( koinos::exception& _e )                              \
{                                                           \
   LOG( log_level ) << boost::diagnostic_information( e );  \
   j = _e.get_json();                                        \
}

#define KOINOS_DECLARE_EXCEPTION( exc_name )                         \
   struct exc_name : public koinos::exception                        \
   {                                                                 \
      exc_name() {}                                                  \
      exc_name( const std::string& m ) : koinos::exception( m ) {}   \
      exc_name( std::string&& m ) : koinos::exception( m ) {}        \
                                                                     \
      virtual ~exc_name() {};                                        \
   };

#define KOINOS_DECLARE_DERIVED_EXCEPTION( exc_name, base )  \
   struct exc_name : public base                            \
   {                                                        \
      exc_name() {}                                         \
      exc_name( const std::string& m ) : base( m ) {}       \
      exc_name( std::string&& m ) : base( m ) {}            \
                                                            \
      virtual ~exc_name() {};                               \
   };

namespace koinos {

// Forward declaration
namespace detail { struct json_initializer; }

struct exception : virtual boost::exception, virtual std::exception
{
   private:
      std::string msg;

   public:
      exception();
      exception( const std::string& m );
      exception( std::string&& m );

      virtual ~exception();

      virtual const char* what() const noexcept override;

      std::string get_stacktrace() const;
      const nlohmann::json& get_json() const;
      const std::string& get_message() const;

   private:
      friend struct detail::json_initializer;

      void do_message_substitution();
};

namespace detail {

using json_info = boost::error_info< struct json_tag, nlohmann::json >;
using exception_stacktrace = boost::error_info< struct stacktrace_tag, boost::stacktrace::stacktrace >;

std::string json_strpolate( const std::string& format_str, const nlohmann::json& j );

/**
 * Initializes a json object using a bubble list of key value pairs.
 */
struct json_initializer
{
   exception& _e;
   nlohmann::json& _j;

   json_initializer() = delete;
   json_initializer( exception& _e );

   json_initializer& operator()( const std::string& key, const google::protobuf::Message& m );
   json_initializer& operator()( const std::string& key, const char* c );

   template< typename T >
   std::enable_if_t< std::is_integral_v< T >, json_initializer& >
   operator()( const std::string& key, T t )
   {
      _j[key] = t;
      _e.do_message_substitution();
      return *this;
   }

   template< typename T >
   std::enable_if_t< !std::is_base_of_v< google::protobuf::Message, T > && !std::is_integral_v< T >, json_initializer& >
   operator()( const std::string& key, const T& t )
   {
      std::stringstream ss;
      ss << t;
      _j[key] = ss.str();
      _e.do_message_substitution();
      return *this;
   }

   json_initializer& operator()( const google::protobuf::Message& m );
   json_initializer& operator()();
};

} } // koinos::detail

max_stars_repo_name: koinos/koinos-exception-cpp

max_issues_repo_name: koinos/koinos-exception-cpp

max_forks_repo_name: koinos/koinos-exception-cpp


text:
#include <stan/math/mix/scal.hpp>
#include <gtest/gtest.h>
#include <boost/math/special_functions/digamma.hpp>
#include <test/unit/math/rev/scal/fun/util.hpp>
#include <test/unit/math/mix/scal/fun/nan_util.hpp>

TEST(AgradFwdLogRisingFactorial,FvarVar_FvarVar_1stDeriv) {
  using stan::math::fvar;
  using stan::math::var;
  using stan::math::log_rising_factorial;
  using boost::math::digamma;

  fvar<var> a(4.0,1.0);
  fvar<var> b(3.0,1.0);
  fvar<var> c = log_rising_factorial(a,b);

  EXPECT_FLOAT_EQ(std::log(120.0), c.val_.val());
  EXPECT_FLOAT_EQ(2.4894509, c.d_.val());

  AVEC y = createAVEC(a.val_,b.val_);
  VEC g;
  c.val_.grad(y,g);
  EXPECT_FLOAT_EQ(0.61666667, g[0]);
  EXPECT_FLOAT_EQ(1.8727844, g[1]);
}
TEST(AgradFwdLogRisingFactorial,FvarVar_Double_1stDeriv) {
  using stan::math::fvar;
  using stan::math::var;
  using stan::math::log_rising_factorial;
  using boost::math::digamma;

  fvar<var> a(4.0,1.0);
  double b(3.0);
  fvar<var> c = log_rising_factorial(a,b);

  EXPECT_FLOAT_EQ(std::log(120.0), c.val_.val());
  EXPECT_FLOAT_EQ(0.61666667, c.d_.val());

  AVEC y = createAVEC(a.val_);
  VEC g;
  c.val_.grad(y,g);
  EXPECT_FLOAT_EQ(0.61666667, g[0]);
}
TEST(AgradFwdLogRisingFactorial,Double_FvarVar_1stDeriv) {
  using stan::math::fvar;
  using stan::math::var;
  using stan::math::log_rising_factorial;
  using boost::math::digamma;

  double a(4.0);
  fvar<var> b(3.0,1.0);
  fvar<var> c = log_rising_factorial(a,b);

  EXPECT_FLOAT_EQ(std::log(120.0), c.val_.val());
  EXPECT_FLOAT_EQ(1.8727844, c.d_.val());

  AVEC y = createAVEC(b.val_);
  VEC g;
  c.val_.grad(y,g);
  EXPECT_FLOAT_EQ(1.8727844, g[0]);
}

TEST(AgradFwdLogRisingFactorial,FvarVar_FvarVar_2ndDeriv) {
  using stan::math::fvar;
  using stan::math::var;
  using stan::math::log_rising_factorial;
  using boost::math::digamma;

  fvar<var> a(4.0,1.0);
  fvar<var> b(3.0,1.0);
  fvar<var> c = log_rising_factorial(a,b);

  AVEC y = createAVEC(a.val_,b.val_);
  VEC g;
  c.d_.grad(y,g);
  EXPECT_FLOAT_EQ(0.023267401, g[0]);
  EXPECT_FLOAT_EQ(0.30709034, g[1]);
}
TEST(AgradFwdLogRisingFactorial,FvarVar_Double_2ndDeriv) {
  using stan::math::fvar;
  using stan::math::var;
  using stan::math::log_rising_factorial;
  using boost::math::digamma;

  fvar<var> a(4.0,1.0);
  double b(3.0);
  fvar<var> c = log_rising_factorial(a,b);

  AVEC y = createAVEC(a.val_);
  VEC g;
  c.d_.grad(y,g);
  EXPECT_FLOAT_EQ(-0.13027778, g[0]);
}
TEST(AgradFwdLogRisingFactorial,Double_FvarVar_2ndDeriv) {
  using stan::math::fvar;
  using stan::math::var;
  using stan::math::log_rising_factorial;
  using boost::math::digamma;

  double a(4.0);
  fvar<var> b(3.0,1.0);
  fvar<var> c = log_rising_factorial(a,b);

  AVEC y = createAVEC(b.val_);
  VEC g;
  c.d_.grad(y,g);
  EXPECT_FLOAT_EQ(0.15354517, g[0]);
}
TEST(AgradFwdLogRisingFactorial,FvarFvarVar_FvarFvarVar_1stDeriv) {
  using stan::math::fvar;
  using stan::math::var;
  using stan::math::log_rising_factorial;
  using boost::math::digamma;

  fvar<fvar<var> > x;
  x.val_.val_ = 4.0;
  x.val_.d_ = 1.0;

  fvar<fvar<var> > y;
  y.val_.val_ = 3.0;
  y.d_.val_ = 1.0;

  fvar<fvar<var> > a = log_rising_factorial(x,y);

  EXPECT_FLOAT_EQ(std::log(120.0), a.val_.val_.val());
  EXPECT_FLOAT_EQ(0.61666667, a.val_.d_.val());
  EXPECT_FLOAT_EQ(1.8727844, a.d_.val_.val());
  EXPECT_FLOAT_EQ(0.15354517, a.d_.d_.val());

  AVEC p = createAVEC(x.val_.val_,y.val_.val_);
  VEC g;
  a.val_.val_.grad(p,g);
  EXPECT_FLOAT_EQ(0.61666667, g[0]);
  EXPECT_FLOAT_EQ(1.8727844, g[1]);
}
TEST(AgradFwdLogRisingFactorial,FvarFvarVar_Double_1stDeriv) {
  using stan::math::fvar;
  using stan::math::var;
  using stan::math::log_rising_factorial;
  using boost::math::digamma;

  fvar<fvar<var> > x;
  x.val_.val_ = 4.0;
  x.val_.d_ = 1.0;
  double y(3.0);

  fvar<fvar<var> > a = log_rising_factorial(x,y);

  EXPECT_FLOAT_EQ(std::log(120.0), a.val_.val_.val());
  EXPECT_FLOAT_EQ(0.61666667, a.val_.d_.val());
  EXPECT_FLOAT_EQ(0, a.d_.val_.val());
  EXPECT_FLOAT_EQ(0, a.d_.d_.val());

  AVEC p = createAVEC(x.val_.val_);
  VEC g;
  a.val_.val_.grad(p,g);
  EXPECT_FLOAT_EQ(0.61666667, g[0]);
}
TEST(AgradFwdLogRisingFactorial,Double_FvarFvarVar_1stDeriv) {
  using stan::math::fvar;
  using stan::math::var;
  using stan::math::log_rising_factorial;
  using boost::math::digamma;

  double x(4.0);
  fvar<fvar<var> > y;
  y.val_.val_ = 3.0;
  y.d_.val_ = 1.0;

  fvar<fvar<var> > a = log_rising_factorial(x,y);

  EXPECT_FLOAT_EQ(std::log(120.0), a.val_.val_.val());
  EXPECT_FLOAT_EQ(0, a.val_.d_.val());
  EXPECT_FLOAT_EQ(1.8727844, a.d_.val_.val());
  EXPECT_FLOAT_EQ(0, a.d_.d_.val());

  AVEC p = createAVEC(y.val_.val_);
  VEC g;
  a.val_.val_.grad(p,g);
  EXPECT_FLOAT_EQ(1.8727844, g[0]);
}
TEST(AgradFwdLogRisingFactorial,FvarFvarVar_FvarFvarVar_2ndDeriv_x) {
  using stan::math::fvar;
  using stan::math::var;
  using stan::math::log_rising_factorial;
  using boost::math::digamma;

  fvar<fvar<var> > x;
  x.val_.val_ = 4.0;
  x.val_.d_ = 1.0;

  fvar<fvar<var> > y;
  y.val_.val_ = 3.0;
  y.d_.val_ = 1.0;

  fvar<fvar<var> > a = log_rising_factorial(x,y);

  AVEC p = createAVEC(x.val_.val_,y.val_.val_);
  VEC g;
  a.val_.d_.grad(p,g);
  EXPECT_FLOAT_EQ(-0.13027778, g[0]);
  EXPECT_FLOAT_EQ(0.15354517, g[1]);
}
TEST(AgradFwdLogRisingFactorial,FvarFvarVar_FvarFvarVar_2ndDeriv_y) {
  using stan::math::fvar;
  using stan::math::var;
  using stan::math::log_rising_factorial;
  using boost::math::digamma;

  fvar<fvar<var> > x;
  x.val_.val_ = 4.0;
  x.val_.d_ = 1.0;

  fvar<fvar<var> > y;
  y.val_.val_ = 3.0;
  y.d_.val_ = 1.0;

  fvar<fvar<var> > a = log_rising_factorial(x,y);

  AVEC p = createAVEC(x.val_.val_,y.val_.val_);
  VEC g;
  a.d_.val_.grad(p,g);
  EXPECT_FLOAT_EQ(0.15354517, g[0]);
  EXPECT_FLOAT_EQ(0.15354517, g[1]);
}
TEST(AgradFwdLogRisingFactorial,FvarFvarVar_Double_2ndDeriv) {
  using stan::math::fvar;
  using stan::math::var;
  using stan::math::log_rising_factorial;
  using boost::math::digamma;

  fvar<fvar<var> > x;
  x.val_.val_ = 4.0;
  x.val_.d_ = 1.0;
  double y(3.0);

  fvar<fvar<var> > a = log_rising_factorial(x,y);

  AVEC p = createAVEC(x.val_.val_);
  VEC g;
  a.val_.d_.grad(p,g);
  EXPECT_FLOAT_EQ(-0.13027778, g[0]);
}
TEST(AgradFwdLogRisingFactorial,Double_FvarFvarVar_2ndDeriv) {
  using stan::math::fvar;
  using stan::math::var;
  using stan::math::log_rising_factorial;
  using boost::math::digamma;

  double x(4.0);
  fvar<fvar<var> > y;
  y.val_.val_ = 3.0;
  y.d_.val_ = 1.0;

  fvar<fvar<var> > a = log_rising_factorial(x,y);

  AVEC p = createAVEC(y.val_.val_);
  VEC g;
  a.d_.val_.grad(p,g);
  EXPECT_FLOAT_EQ(0.15354517, g[0]);
}
TEST(AgradFwdLogRisingFactorial,FvarFvarVar_FvarFvarVar_3rdDeriv) {
  using stan::math::fvar;
  using stan::math::var;
  using stan::math::log_rising_factorial;
  using boost::math::digamma;

  fvar<fvar<var> > x;
  x.val_.val_ = 4.0;
  x.val_.d_ = 1.0;

  fvar<fvar<var> > y;
  y.val_.val_ = 3.0;
  y.d_.val_ = 1.0;

  fvar<fvar<var> > a = log_rising_factorial(x,y);

  AVEC p = createAVEC(x.val_.val_,y.val_.val_);
  VEC g;
  a.d_.d_.grad(p,g);
  EXPECT_FLOAT_EQ(-0.023530472, g[0]);
  EXPECT_FLOAT_EQ(-0.023530472, g[1]);
}
TEST(AgradFwdLogRisingFactorial,FvarFvarVar_Double_3rdDeriv) {
  using stan::math::fvar;
  using stan::math::var;
  using stan::math::log_rising_factorial;
  using boost::math::digamma;

  fvar<fvar<var> > x;
  x.val_.val_ = 4.0;
  x.val_.d_ = 1.0;
  x.d_.val_ = 1.0;
  double y(3.0);

  fvar<fvar<var> > a = log_rising_factorial(x,y);

  AVEC p = createAVEC(x.val_.val_);
  VEC g;
  a.d_.d_.grad(p,g);
  EXPECT_FLOAT_EQ(0.056509256, g[0]);
}
TEST(AgradFwdLogRisingFactorial,Double_FvarFvarVar_3rdDeriv) {
  using stan::math::fvar;
  using stan::math::var;
  using stan::math::log_rising_factorial;
  using boost::math::digamma;

  double x(4.0);
  fvar<fvar<var> > y;
  y.val_.val_ = 3.0;
  y.d_.val_ = 1.0;
  y.val_.d_ = 1.0;

  fvar<fvar<var> > a = log_rising_factorial(x,y);

  AVEC p = createAVEC(y.val_.val_);
  VEC g;
  a.d_.d_.grad(p,g);
  EXPECT_FLOAT_EQ(-0.023530472, g[0]);
}

struct log_rising_factorial_fun {
  template <typename T0, typename T1>
  inline
  typename boost::math::tools::promote_args<T0,T1>::type
  operator()(const T0 arg1,
             const T1 arg2) const {
    return log_rising_factorial(arg1,arg2);
  }
};

TEST(AgradFwdLogRisingFactorial, nan) {
  log_rising_factorial_fun log_rising_factorial_;
  test_nan_mix(log_rising_factorial_,3.0,5.0,false);
}

max_stars_repo_name: yizhang-cae/torsten

max_issues_repo_name: yizhang-cae/torsten

max_forks_repo_name: yizhang-cae/torsten


text:
#pragma once

#include <boost/dll/alias.hpp>
#include <boost/dll/shared_library.hpp>
#include <boost/preprocessor/dec.hpp>
#include <boost/preprocessor/if.hpp>
#include <boost/preprocessor/variadic/elem.hpp>

#include <functional>
#include <memory>

namespace bunsan {

template <typename Constructor>
class plugin {};

template <typename T, typename... Args>
class plugin<T *(Args...)> {
 public:
  using unique_ptr = std::unique_ptr<T>;
  using shared_ptr = std::shared_ptr<T>;
  using weak_ptr = std::weak_ptr<T>;

  using unique_constructor = unique_ptr(Args...);
  using shared_constructor = unique_ptr(Args...);

  // TODO make shared_library_ptr ctor
  explicit plugin(boost::dll::shared_library library, const std::string &key)
      : m_library(std::move(library)),
        m_constructor(m_library.get_alias<unique_constructor>(key)) {}

  explicit plugin(const boost::filesystem::path &library_path,
                  const std::string &key)
      : plugin(boost::dll::shared_library(
                   library_path, boost::dll::load_mode::append_decorations),
               key) {}

  unique_ptr unique_instance(Args... args) {
    return m_constructor(std::forward<Args>(args)...);
  }

  shared_ptr shared_instance(Args... args) {
    return shared_ptr(unique_instance(std::forward<Args>(args)...).release());
  }

 private:
  boost::dll::shared_library m_library;
  std::function<unique_constructor> m_constructor;
};

}  // namespace bunsan

#define BUNSAN_PLUGIN_PUBLIC_BODY_DEFINES(KEY, CLASS)                         \
  using CLASS##_uptr = plugin::unique_ptr;                                    \
  using CLASS##_sptr = plugin::shared_ptr;                                    \
  using CLASS##_wptr = plugin::weak_ptr;                                      \
  template <typename... PluginArgs>                                           \
  static plugin load_plugin(PluginArgs &&... args) {                          \
    return plugin(std::forward<PluginArgs>(args)..., #KEY);                   \
  }                                                                           \
  template <typename... PluginArgs>                                           \
  static std::shared_ptr<plugin> load_shared_plugin(PluginArgs &&... args) {  \
    return std::make_shared<plugin>(std::forward<PluginArgs>(args)..., #KEY); \
  }

#define BUNSAN_PLUGIN_PUBLIC_BODY_ARGS(KEY, CLASS, ...)  \
  using plugin = ::bunsan::plugin<CLASS *(__VA_ARGS__)>; \
  BUNSAN_PLUGIN_PUBLIC_BODY_DEFINES(KEY, CLASS)

#define BUNSAN_PLUGIN_PUBLIC_BODY_EMPTY(KEY, CLASS) \
  using plugin = ::bunsan::plugin<CLASS *()>;       \
  BUNSAN_PLUGIN_PUBLIC_BODY_DEFINES(KEY, CLASS)

// key, base, constructor parameters
#define BUNSAN_PLUGIN_BODY(KEY, ...)                             \
 public:                                                         \
  BOOST_PP_IF(BOOST_PP_DEC(BOOST_PP_VARIADIC_SIZE(__VA_ARGS__)), \
              BUNSAN_PLUGIN_PUBLIC_BODY_ARGS,                    \
              BUNSAN_PLUGIN_PUBLIC_BODY_EMPTY)(KEY, __VA_ARGS__) \
 private:

#define BUNSAN_PLUGIN_AUTO_KEY(CLASS) BOOST_PP_CAT(bunsan_plugin_, CLASS)

#define BUNSAN_PLUGIN_AUTO_KEY_NESTED(PREFIX, CLASS) \
  BUNSAN_PLUGIN_AUTO_KEY(BOOST_PP_CAT(BOOST_PP_CAT(PREFIX, __), CLASS))

#define BUNSAN_PLUGIN_AUTO_BODY(...)                                  \
  BUNSAN_PLUGIN_BODY(                                                 \
      BUNSAN_PLUGIN_AUTO_KEY(BOOST_PP_VARIADIC_ELEM(0, __VA_ARGS__)), \
      __VA_ARGS__)

#define BUNSAN_PLUGIN_AUTO_BODY_NESTED(PREFIX, ...)                       \
  BUNSAN_PLUGIN_BODY(BUNSAN_PLUGIN_AUTO_KEY_NESTED(                       \
                         PREFIX, BOOST_PP_VARIADIC_ELEM(0, __VA_ARGS__)), \
                     __VA_ARGS__)

#define BUNSAN_PLUGIN_TYPES(CLASS)          \
  using CLASS##_uptr = CLASS::CLASS##_uptr; \
  using CLASS##_wptr = CLASS::CLASS##_sptr; \
  using CLASS##_sptr = CLASS::CLASS##_wptr;

#define BUNSAN_PLUGIN_REGISTER(KEY, BASE, CONCRETE, UNIQUE_CTOR) \
  BOOST_DLL_ALIAS(UNIQUE_CTOR, KEY)

#define BUNSAN_PLUGIN_AUTO_REGISTER(BASE, CONCRETE, UNIQUE_CTOR)       \
  BUNSAN_PLUGIN_REGISTER(BUNSAN_PLUGIN_AUTO_KEY(BASE), BASE, CONCRETE, \
                         UNIQUE_CTOR)

#define BUNSAN_PLUGIN_AUTO_REGISTER_NESTED(PREFIX, BASE, CONCRETE,          \
                                           UNIQUE_CTOR)                     \
  BUNSAN_PLUGIN_REGISTER(BUNSAN_PLUGIN_AUTO_KEY_NESTED(PREFIX, BASE), BASE, \
                         CONCRETE, UNIQUE_CTOR)


text:
/**
* Connected Vision - https://github.com/ConnectedVision
* MIT License
*/

// template include guard
#ifndef TestHelper_Store_SQLite_code
#define TestHelper_Store_SQLite_code

#include <boost/assign/list_of.hpp>

#include "IStore.h"
#include "DataHandling/Store_SQLite_BaseClass.h"

#include "TestHelper_DataHandling.hpp"

namespace ConnectedVision {
namespace DataHandling {

namespace TestWrapper_Store_SQLite_Table
{
static const std::string tableName = "Test_Store_SQLite_table";
static const std::vector<std::string> columnDesc =
	boost::assign::list_of("'_sortID' BIGINT NOT NULL DEFAULT '0'")
							("'configID' VARCHAR(32) NOT NULL DEFAULT '' /* ID of config chain (string) */")
							("'id' VARCHAR(32) NOT NULL DEFAULT '' /* detection ID (string) */")
							("'timestamp' BIGINT NOT NULL DEFAULT '0' /* timestamp in milliseconds since 1970-01-01 00:00:00.000 UTC (integer) */")
							("'x' BIGINT NOT NULL DEFAULT '0' /* test name with one character */");
}

/**
 * simple test SQLite store
 *
 * implementing IStore_ReadWrite interface
 */
class TestWrapper_Store_SQLite : public Store_SQLite_BaseClass<TestDataClass>
{
public:
	TestWrapper_Store_SQLite(
		const id_t& configID,			///< [in] config ID
		DBConnection& db,				///< [in] DB connection object
		const std::vector<std::string> columnDesc = TestWrapper_Store_SQLite_Table::columnDesc		///< [in] default column description
	) : Store_SQLite_BaseClass(configID, db, TestWrapper_Store_SQLite_Table::tableName, columnDesc)
	{};

	// implement abstract methodes

	/**
	* read Object from DB
	* @note This function is MANDATORY.
	*
	*	Read table colum fields to object member variables.
	*	Call sqlite3_step() to read all sub/child objects.
	*
	* @return SQLite return code
	*/
	virtual int readObject(
		sqlite3_stmt *stmt,						///< [in] pre-executed SQLite statement
		shared_ptr<const TestDataClass>& outObj,	///< [out] data object read from DB
		sqlite3 *db								///< [in] SQLite DB object
	)
	{
		int error = SQLITE_ROW;

		outObj.reset();
		auto obj = this->create();

		// process row
		if ( sqlite3_column_type(stmt, 1) != SQLITE_NULL )
			obj->set_configID( strToID( reinterpret_cast<const char *>(sqlite3_column_text(stmt,1) ) ) );
		if ( sqlite3_column_type(stmt, 2) != SQLITE_NULL )
			obj->set_id( strToID( reinterpret_cast<const char *>(sqlite3_column_text(stmt,2) ) ) );
		if ( sqlite3_column_type(stmt, 3) != SQLITE_NULL )
			obj->set_timestamp( sqlite3_column_int64(stmt,3) );
		if ( sqlite3_column_type(stmt, 4) != SQLITE_NULL )
			obj->set_x( sqlite3_column_int64(stmt,4) );
		outObj = this->make_const(obj);

		error = sqlite3_step(stmt);
		return error;
	}

	/**
	* write Object to DB
	* @note This function is MANDATORY.
	*
	*	Bind object member variables to table colum fields.
	*	This function has to write the whole objects,
	*	i.e. ti has to loop over all sub/child object bind them and call sqlite3_step() for each row.
	*
	* @return SQLite return code
	*/
	virtual int writeObject(
		sqlite3_stmt *stmt,							///< [in] prepared SQLite statement
		const shared_ptr<const TestDataClass>& obj,	///< [in] data object read from DB
		sqlite3 *db,								///< [in] SQLite DB object
		const int64_t sortID						///< [in] unique index of object
	)
	{
		int error = 0;

		sqlite3_reset(stmt);
		sqlite3_clear_bindings(stmt);

		// set object bindings
		sqlite3_bind_int64(stmt, 1, sortID );
		sqlite3_bind_text(stmt, 2, IDToChar(obj->getconst_configID()), -1, SQLITE_STATIC);
		sqlite3_bind_text(stmt, 3, IDToChar(obj->getconst_id()), -1, SQLITE_STATIC);
		sqlite3_bind_int64(stmt, 4, obj->getconst_timestamp() );
		sqlite3_bind_int64(stmt, 5, obj->getconst_x() );

		// write object base data and sub objects
		error = sqlite3_step(stmt);
		return error;
	}

	/**
	* append object internal sort criteria to list
	* @note This function is MANDATORY.
	*/
	virtual void appendObjectGrouping(
		std::vector< Store::SortEntry >& sortList ///< [in/out] list of sort criteria for table rows
	) const
	{
		sortList.push_back( Store::SortEntry ("_sortID", Store::Order::ASC) );
	}

	/**
	* get name of internal sort criteria column
	* @note This function is MANDATORY.
	*
	* @return column name
	*/
	virtual const std::string objectKey() const
	{
		return std::string("_sortID");
	}

};

/**
 * factory for TestWrapper_Store_SQLite
 */
class TestWrapper_Store_SQLite_Factory : public IStore_ReadWrite_Factory<TestDataClass>
{
public:
	/**
	* constructor
	*	uses DataAllocator_Primitive (new / delete for every object request)
	*/
	TestWrapper_Store_SQLite_Factory(
		DBConnection& db				///< [in] DB connection object
	) :	db(db)
	{}

	/**
	* virtual desctuctor
	*/
	virtual ~TestWrapper_Store_SQLite_Factory() {};

	/**
	* creates a new store
	*/
	virtual shared_ptr< IStore_ReadWrite<TestDataClass> > create(
		const id_t configID	= ID_NULL	///< [in] config ID of requested store (optional)
	)
	{
		return boost::static_pointer_cast<IStore_ReadWrite<TestDataClass>>(make_shared<TestWrapper_Store_SQLite>(configID, this->db));
	}

protected:
	DBConnection& db;
};

}} // namespace scope
#endif // TestHelper_Store_SQLite_code

max_stars_repo_name: ConnectedVision/ConnectedVision

max_issues_repo_name: ConnectedVision/ConnectedVision

max_forks_repo_name: ConnectedVision/ConnectedVision


text:
// Copyright (C) 2009-2020 Christian@Schladetsch.com
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

// documentation at https://svn.boost.org/svn/boost/sandbox/monotonic/libs/object_model/doc/index.html
// sandbox at https://svn.boost.org/svn/boost/sandbox/monotonic/object_model/

#include <boost/object_model/generic/object.hpp>
#include <boost/object_model/generic/class.hpp>
#include <boost/object_model/generic/storage.hpp>
#include <boost/object_model/registry.hpp>
#include <boost/object_model/label.hpp>

BOOST_OM_BEGIN

namespace generic
{
    // object_base

    object_base::object_base()
        : reg(0), type(0), number(0)
    {
    }

    object_base::object_base(const object_base &other)
        : reg(other.reg), type(other.type), number(other.number)
    {
    }

    void object_base::construct(registry &r, klass const &k, handle h)
    {
        reg = &r;
        type = &k;
        number = h;
    }

    registry &object_base::get_registry() const
    {
        if (reg == 0)
            throw empty_object();
        return *reg;
    }
    klass const &object_base::get_class() const
    {
        if (type == 0)
            throw empty_object();
        return *type;
    }

    type::number object_base::get_type_number() const
    {
        return get_class().get_type_number();
    }

    handle object_base::get_handle() const
    {
        return number;
    }

    bool object_base::exists() const
    {
        return get_registry().exists(number);
    }

    const object_base &object_base::get_storage() const
    {
        return get_registry().get_storage(get_handle());
    }

    object_base &object_base::get_storage()
    {
        return get_registry().get_storage(get_handle());
    }

    object_base &mutable_object::get_storage()
    {
        return get_registry().get_storage(get_handle());
    }

    // object

    object::object() : konst(false) { }

    object::object(const const_object& obj) : const_object(obj), konst(true) { }

    object::object(const mutable_object& obj) : const_object(obj), konst(false) { }

    object &object::operator=(const const_object& obj)
    {
        const_object::operator=(obj);
        konst = true;
        return *this;
    }

    object &object::operator=(const mutable_object& obj)
    {
        const_object::operator=(obj);
        konst = false;
        return *this;
    }
    object_base &object::get_storage()
    {
        if (is_const())
            throw const_error();
        return get_registry().get_storage(get_handle());
    }
    const object_base &object::get_storage() const
    {
        return get_registry().get_storage(get_handle());
    }
}

const generic::object null_object;

BOOST_OM_END

//EOF

max_stars_repo_name: cschladetsch/Monotonic

max_issues_repo_name: cschladetsch/Monotonic

max_forks_repo_name: cschladetsch/Monotonic


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

#include "convert_to_polar_data_transformer.h"

#include "neural_network_exception.h"

#include <opencv2/imgproc/imgproc.hpp>
#include <boost/format.hpp>

namespace nnforge
{
	const float convert_to_polar_data_transformer::pi = atan(1.0F) * 4.0F;

	convert_to_polar_data_transformer::convert_to_polar_data_transformer(
		const std::vector<unsigned int>& input_window_sizes,
		const std::vector<unsigned int>& output_window_sizes,
		float start_angle,
		float step_angle,
		float input_radius,
		unsigned char border_value)
		: input_window_sizes(input_window_sizes)
		, output_window_sizes(output_window_sizes)
		, start_angle(start_angle)
		, step_angle(step_angle)
		, input_radius(input_radius)
		, border_value(border_value)
	{
		if (input_window_sizes.size() != output_window_sizes.size())
			throw neural_network_exception((boost::format("convert_to_polar_data_transformer is created with different dimensions: %1% and %2%") % input_window_sizes.size() % output_window_sizes.size()).str());

		if (input_window_sizes.size() != 2)
			throw neural_network_exception((boost::format("convert_to_polar_data_transformer is created with wrong dimension count: %1%") % input_window_sizes.size()).str());

		map_x.create(output_window_sizes[1], output_window_sizes[0]);
		map_y.create(output_window_sizes[1], output_window_sizes[0]);
		float step_theta = step_angle * (pi * (2.0F / 360.0F));
		float start_theta = start_angle * (pi * (2.0F / 360.0F));
		float step_r = input_radius / static_cast<float>(output_window_sizes[1]);
		float start_r = step_r;
		float mid_input_x = static_cast<float>(input_window_sizes[0] - 1) * 0.5F;
		float mid_input_y = static_cast<float>(input_window_sizes[1] - 1) * 0.5F;
		for(int outut_y = 0; outut_y < map_x.rows; ++outut_y)
		{
			float r = start_r + static_cast<float>(map_x.rows - 1 - outut_y) * step_r;
			for(int ouput_x = 0; ouput_x < map_x.cols; ++ouput_x)
			{
				float theta = start_theta + static_cast<float>(ouput_x) * step_theta;
				float input_x = cosf(theta) * r + mid_input_x;
				float input_y = sinf(theta) * r + mid_input_y;
				map_x.at<float>(outut_y, ouput_x) = input_x;
				map_y.at<float>(outut_y, ouput_x) = input_y;
			}
		}
	}

	convert_to_polar_data_transformer::~convert_to_polar_data_transformer()
	{
	}

	void convert_to_polar_data_transformer::transform(
		const void * data,
		void * data_transformed,
		neuron_data_type::input_type type,
		const layer_configuration_specific& original_config,
		unsigned int sample_id)
	{
		if (type != neuron_data_type::type_byte)
			throw neural_network_exception("convert_to_polar_data_transformer is implemented for data stored as bytes only");

		if (original_config.dimension_sizes.size() != 2)
			throw neural_network_exception((boost::format("convert_to_polar_data_transformer is processing 2D data only, data is passed with number of dimensions %1%") % original_config.dimension_sizes.size()).str());

		if (original_config.dimension_sizes != input_window_sizes)
			throw neural_network_exception("convert_to_polar_data_transformer: input window size mismatch between creation and actual transform");

		unsigned int original_neuron_count_per_feature_map = original_config.get_neuron_count_per_feature_map();
		unsigned int transformed_neuron_count_per_feature_map = get_transformed_configuration(original_config).get_neuron_count_per_feature_map();
		for(unsigned int feature_map_id = 0; feature_map_id < original_config.feature_map_count; ++feature_map_id)
		{
			cv::Mat1b original_image(static_cast<int>(original_config.dimension_sizes[1]), static_cast<int>(original_config.dimension_sizes[0]), const_cast<unsigned char *>(static_cast<const unsigned char *>(data)) + (original_neuron_count_per_feature_map * feature_map_id));
			cv::Mat1b dest_image(static_cast<int>(output_window_sizes[1]), static_cast<int>(output_window_sizes[0]), static_cast<unsigned char *>(data_transformed) + (transformed_neuron_count_per_feature_map * feature_map_id));

			// Should try INTER_CUBIC and INTER_LANCZOS4 as well
			cv::remap(original_image, dest_image, map_x, map_y, cv::INTER_LINEAR, cv::BORDER_CONSTANT, border_value);
		}
	}

	layer_configuration_specific convert_to_polar_data_transformer::get_transformed_configuration(const layer_configuration_specific& original_config) const
	{
		layer_configuration_specific res(original_config.feature_map_count);
		res.dimension_sizes = output_window_sizes;

		return res;
	}

	bool convert_to_polar_data_transformer::is_in_place() const
	{
		return false;
	}

 	bool convert_to_polar_data_transformer::is_deterministic() const
	{
		return true;
	}
}

max_stars_repo_name: anshumang/nnForgeINST

max_issues_repo_name: anshumang/nnForgeINST

max_forks_repo_name: anshumang/nnForgeINST


text:
//==================================================================================================
/**
  EVE - Expressive Vector Engine
  Copyright : EVE Contributors & Maintainers
  SPDX-License-Identifier: MIT
**/
//==================================================================================================
#include "test.hpp"
#include <eve/module/core.hpp>
#include <eve/module/special.hpp>
#include <boost/math/special_functions/erf.hpp>

//==================================================================================================
// Types tests
//==================================================================================================
EVE_TEST_TYPES( "Check return types of erf_inv"
            , eve::test::simd::ieee_reals
            )
<typename T>(eve::as<T>)
{
  using v_t = eve::element_type_t<T>;

  TTS_EXPR_IS( eve::erf_inv(T())  , T);
  TTS_EXPR_IS( eve::erf_inv(v_t()), v_t);
};

//==================================================================================================
// erf_inv  tests
//==================================================================================================
EVE_TEST( "Check behavior of erf_inv on wide"
        , eve::test::simd::ieee_reals
        , eve::test::generate(eve::test::randoms(-1.0, 1.0))
        )
<typename T>(T const& a0 )
{
  using v_t = eve::element_type_t<T>;
  using eve::erf_inv;
  using eve::as;
  TTS_ULP_EQUAL( erf_inv(a0),  map([](auto e){return boost::math::erf_inv(e);}, a0), 2);
  auto derf_inv = [](auto e){return v_t(0.886226925452758013649)*std::exp(eve::sqr(erf_inv(e)));};
  TTS_ULP_EQUAL( eve::diff(erf_inv)(a0),  map(derf_inv, a0), 2);

  TTS_ULP_EQUAL(erf_inv(T(0.5)), T(boost::math::erf_inv(v_t(0.5))), 1. );

  if constexpr(eve::platform::supports_denormals)
  {
    TTS_ULP_EQUAL ( erf_inv(T(eve::smallestposval(as<T>())))
                  , T(boost::math::erf_inv(eve::smallestposval(as<v_t>())))
                  , 0.5
                  );
  }

  if constexpr( eve::platform::supports_invalids )
  {
    TTS_IEEE_EQUAL(erf_inv(eve::nan(eve::as<T>()))  , eve::nan(eve::as<T>()) );
    TTS_IEEE_EQUAL(erf_inv(eve::inf(eve::as<T>()))  , eve::nan(eve::as<T>()) );
    TTS_IEEE_EQUAL(erf_inv(eve::minf(eve::as<T>())) , eve::nan(eve::as<T>()) );
  }

  TTS_ULP_EQUAL(erf_inv(T(35)), eve::nan(eve::as<T>()), 0.5);
  TTS_ULP_EQUAL(erf_inv(T(-35)), eve::nan(eve::as<T>()), 0.5);

  TTS_IEEE_EQUAL(erf_inv(T( 0 )),T(0)  );
  TTS_IEEE_EQUAL(erf_inv(T(-0.)), T(0) );
  TTS_ULP_EQUAL(erf_inv(T( 0.1 )), T( boost::math::erf_inv(0.1)), 0.5 );
  TTS_ULP_EQUAL(erf_inv(T( 0.2 )), T( boost::math::erf_inv(0.2)), 0.5 );
  TTS_ULP_EQUAL(erf_inv(T( 0.3 )), T( boost::math::erf_inv(0.3)), 0.5 );
  TTS_ULP_EQUAL(erf_inv(T( 0.5 )), T( boost::math::erf_inv(0.5)),  1 );
  TTS_ULP_EQUAL(erf_inv(T( 0.15)), T( boost::math::erf_inv(0.15)), 0.5 );
  TTS_ULP_EQUAL(erf_inv(T( 0.75)), T( boost::math::erf_inv(0.75)), 0.5 );
  TTS_ULP_EQUAL(erf_inv(T(- 0.1 )), T( boost::math::erf_inv(-0.1)), 0.5 );
  TTS_ULP_EQUAL(erf_inv(T( -0.2 )), T( boost::math::erf_inv(-0.2)), 0.5 );
  TTS_ULP_EQUAL(erf_inv(T( -0.3 )), T( boost::math::erf_inv(-0.3)), 0.5 );
  TTS_ULP_EQUAL(erf_inv(T( -0.5 )), T( boost::math::erf_inv(-0.5)),  1 );
  TTS_ULP_EQUAL(erf_inv(T( -0.15)), T( boost::math::erf_inv(-0.15)), 0.5 );
  TTS_ULP_EQUAL(erf_inv(T( -0.75)), T( boost::math::erf_inv(-0.75)), 0.5 );
};

max_stars_repo_name: clayne/eve

max_issues_repo_name: clayne/eve

max_forks_repo_name: clayne/eve


text:
#include <sys/stat.h>
#include <boost/filesystem.hpp>
#include <time.h>

#include <queue>
#include <set>
#include <sstream>
#include <string>

#include <boost/lexical_cast.hpp>
#include <boost/regex.hpp>
#include <boost/thread.hpp>
#include <boost/thread/xtime.hpp>
#include <boost/date_time/local_time/local_time.hpp>

#include <ros/ros.h>
#include <topic_tools/shape_shifter.h>

#include "ros/network.h"
#include "ros/xmlrpc_manager.h"
#include "xmlrpcpp/XmlRpc.h"

#include "roscap/exceptions.h"
#include "roscap/recorder.h"

using std::cout;
using std::endl;
using std::set;
using std::string;
using std::vector;
using boost::shared_ptr;
using ros::Time;

namespace roscap {

mcap::McapWriterOptions RecorderOptionsToMcapWriterOptions(const RecorderOptions& options) {
    mcap::McapWriterOptions output{"ros1"};
    switch (options.compression) {
        case CompressionType::Uncompressed:
            output.compression = mcap::Compression::None;
            break;
        case CompressionType::ZSTD:
            output.compression = mcap::Compression::Zstd;
            break;
        case CompressionType::LZ4:
            output.compression = mcap::Compression::Lz4;
            break;
    }
    output.chunkSize = options.chunk_size;
    return output;
}

// OutgoingMessage

OutgoingMessage::OutgoingMessage(string const& _topic, topic_tools::ShapeShifter::ConstPtr _msg, boost::shared_ptr<ros::M_string> _connection_header, Time _time) :
    topic(_topic), msg(_msg), connection_header(_connection_header), time(_time)
{
}

// OutgoingQueue

OutgoingQueue::OutgoingQueue(string const& _filename, std::queue<OutgoingMessage>* _queue, Time _time) :
    filename(_filename), queue(_queue), time(_time)
{
}

// FileWriter

void FileWriter::open(std::string_view filename) {
    end();
    file_ = fopen(filename.data(), "wb");
    if (!file_) {
        throw McapIOException(mcap::StrFormat("Error opening file: {}", filename));
    }
}

FileWriter::~FileWriter() {
    end();
}

void FileWriter::handleWrite(const std::byte* data, uint64_t size) {
    size_t result = fwrite(data, 1, size, file_);
    if (result != size) {
        throw McapIOException(mcap::StrFormat("Error writing to file: writing {} bytes, wrote {} bytes", size, result));
    }
    size_ += size;
}

void FileWriter::end() {
    if (file_) {
        fclose(file_);
        file_ = nullptr;
    }
    size_ = 0;
}

uint64_t FileWriter::size() const {
    return size_;
}

// RecorderOptions

RecorderOptions::RecorderOptions() :
    trigger(false),
    record_all(false),
    regex(false),
    do_exclude(false),
    quiet(false),
    append_date(true),
    snapshot(false),
    verbose(false),
    publish(false),
    compression(CompressionType::Uncompressed),
    prefix(""),
    name(""),
    exclude_regex(),
    buffer_size(1048576 * 256),
    chunk_size(1024 * 768),
    limit(0),
    split(false),
    max_size(0),
    max_splits(0),
    max_duration(-1.0),
    node(""),
    min_space(1024 * 1024 * 1024),
    min_space_str("1G")
{
}

// Recorder

Recorder::Recorder(RecorderOptions const& options) :
    options_(options),
    mcap_options_("ros1"),
    num_subscribers_(0),
    exit_code_(0),
    queue_size_(0),
    split_count_(0),
    writing_enabled_(true)
{
}

int Recorder::run() {
    if (options_.trigger) {
        doTrigger();
        return 0;
    }

    if (options_.topics.size() == 0) {
        // Make sure limit is not specified with automatic topic subscription
        if (options_.limit > 0) {
            fprintf(stderr, "Specifying a count is not valid with automatic topic subscription.\n");
            return 1;
        }

        // Make sure topics are specified
        if (!options_.record_all && (options_.node == std::string(""))) {
            fprintf(stderr, "No topics specified.\n");
            return 1;
        }
    }

    ros::NodeHandle nh;
    if (!nh.ok())
        return 0;

    if (options_.publish)
    {
        pub_begin_write = nh.advertise<std_msgs::String>("begin_write", 1, true);
    }

    last_buffer_warn_ = Time();
    queue_ = new std::queue<OutgoingMessage>;

    // Subscribe to each topic
    if (!options_.regex) {
    	for (string const& topic : options_.topics)
            subscribe(topic);
    }

    if (!ros::Time::waitForValid(ros::WallDuration(2.0)))
      ROS_WARN("/use_sim_time set to true and no clock published.  Still waiting for valid time...");

    ros::Time::waitForValid();

    start_time_ = ros::Time::now();

    // Don't bother doing anything if we never got a valid time
    if (!nh.ok())
        return 0;

    ros::Subscriber trigger_sub;

    // Spin up a thread for writing to the file
    boost::thread record_thread;
    if (options_.snapshot)
    {
        record_thread = boost::thread([this]() {
          try
          {
            this->doRecordSnapshotter();
          }
          catch (const roscap::McapException& ex)
          {
            ROS_ERROR_STREAM(ex.what());
            exit_code_ = 1;
          }
          catch (const std::exception& ex)
          {
            ROS_ERROR_STREAM(ex.what());
            exit_code_ = 2;
          }
          catch (...)
          {
            ROS_ERROR_STREAM("Unknown exception thrown while recording MCAP, exiting.");
            exit_code_ = 3;
          }
        });

        // Subscribe to the snapshot trigger
        trigger_sub = nh.subscribe<std_msgs::Empty>("snapshot_trigger", 100, boost::bind(&Recorder::snapshotTrigger, this, boost::placeholders::_1));
    }
    else
    {
        record_thread = boost::thread([this]() {
          try
          {
            this->doRecord();
          }
          catch (const roscap::McapException& ex)
          {
            ROS_ERROR_STREAM(ex.what());
            exit_code_ = 1;
          }
          catch (const std::exception& ex)
          {
            ROS_ERROR_STREAM(ex.what());
            exit_code_ = 2;
          }
          catch (...)
          {
            ROS_ERROR_STREAM("Unknown exception thrown while recording MCAP, exiting.");
            exit_code_ = 3;
          }
        });
    }

    ros::Timer check_master_timer;
    if (options_.record_all || options_.regex || (options_.node != std::string("")))
    {
        // check for master first
        doCheckMaster(ros::TimerEvent(), nh);
        check_master_timer = nh.createTimer(ros::Duration(1.0), boost::bind(&Recorder::doCheckMaster, this, boost::placeholders::_1, boost::ref(nh)));
    }

    ros::AsyncSpinner s(10);
    s.start();

    record_thread.join();
    queue_condition_.notify_all();
    delete queue_;

    return exit_code_;
}

shared_ptr<ros::Subscriber> Recorder::subscribe(string const& topic) {
    ROS_INFO("Subscribing to %s", topic.c_str());

    ros::NodeHandle nh;
    shared_ptr<int> count(boost::make_shared<int>(options_.limit));
    shared_ptr<ros::Subscriber> sub(boost::make_shared<ros::Subscriber>());

    ros::SubscribeOptions ops;
    ops.topic = topic;
    ops.queue_size = 100;
    ops.md5sum = ros::message_traits::md5sum<topic_tools::ShapeShifter>();
    ops.datatype = ros::message_traits::datatype<topic_tools::ShapeShifter>();
    ops.helper = boost::make_shared<ros::SubscriptionCallbackHelperT<
        const ros::MessageEvent<topic_tools::ShapeShifter const> &> >(
            boost::bind(&Recorder::doQueue, this, boost::placeholders::_1, topic, sub, count));
    ops.transport_hints = options_.transport_hints;
    *sub = nh.subscribe(ops);

    currently_recording_.insert(topic);
    num_subscribers_++;

    return sub;
}

bool Recorder::isSubscribed(string const& topic) const {
    return currently_recording_.find(topic) != currently_recording_.end();
}

bool Recorder::shouldSubscribeToTopic(std::string const& topic, bool from_node) {
    // ignore already known topics
    if (isSubscribed(topic)) {
        return false;
    }

    // subtract exclusion regex, if any
    if(options_.do_exclude && boost::regex_match(topic, options_.exclude_regex)) {
        return false;
    }

    if(options_.record_all || from_node) {
        return true;
    }

    if (options_.regex) {
        // Treat the topics as regular expressions
	return std::any_of(
            std::begin(options_.topics), std::end(options_.topics),
            [&topic] (string const& regex_str){
                boost::regex e(regex_str);
                boost::smatch what;
                return boost::regex_match(topic, what, e, boost::match_extra);
            });
    }

    return std::find(std::begin(options_.topics), std::end(options_.topics), topic)
	    != std::end(options_.topics);
}

template<class T>
std::string Recorder::timeToStr(T ros_t)
{
    (void)ros_t;
    std::stringstream msg;
    const boost::posix_time::ptime now=
        boost::posix_time::second_clock::local_time();
    boost::posix_time::time_facet *const f=
        new boost::posix_time::time_facet("%Y-%m-%d-%H-%M-%S");
    msg.imbue(std::locale(msg.getloc(),f));
    msg << now;
    return msg.str();
}

//! Callback to be invoked to save messages into a queue
void Recorder::doQueue(const ros::MessageEvent<topic_tools::ShapeShifter const>& msg_event, string const& topic, shared_ptr<ros::Subscriber> subscriber, shared_ptr<int> count) {
    //void Recorder::doQueue(topic_tools::ShapeShifter::ConstPtr msg, string const& topic, shared_ptr<ros::Subscriber> subscriber, shared_ptr<int> count) {
    Time rectime = Time::now();

    if (options_.verbose)
        cout << "Received message on topic " << subscriber->getTopic() << endl;

    OutgoingMessage out(topic, msg_event.getMessage(), msg_event.getConnectionHeaderPtr(), rectime);

    {
        boost::mutex::scoped_lock lock(queue_mutex_);

        queue_->push(out);
        queue_size_ += out.msg->size();

        if (options_.repeat_latched)
        {
            ros::M_string::const_iterator it = out.connection_header->find("latching");
            if ((it != out.connection_header->end()) && (it->second == "1"))
            {
                ros::M_string::const_iterator it2 = out.connection_header->find("callerid");
                if (it2 != out.connection_header->end())
                {
                    latched_msgs_.insert({{subscriber->getTopic(), it2->second}, out});
                }
            }
        }

        // Check to see if buffer has been exceeded
        while (options_.buffer_size > 0 && queue_size_ > options_.buffer_size) {
            OutgoingMessage drop = queue_->front();
            queue_->pop();
            queue_size_ -= drop.msg->size();

            if (!options_.snapshot) {
                Time now = Time::now();
                if (now > last_buffer_warn_ + ros::Duration(5.0)) {
                    ROS_WARN("roscap record buffer exceeded.  Dropping oldest queued message.");
                    last_buffer_warn_ = now;
                }
            }
        }
    }

    if (!options_.snapshot)
        queue_condition_.notify_all();

    // If we are book-keeping count, decrement and possibly shutdown
    if ((*count) > 0) {
        (*count)--;
        if ((*count) == 0) {
            subscriber->shutdown();

            num_subscribers_--;

            if (num_subscribers_ == 0)
                ros::shutdown();
        }
    }
}

void Recorder::updateFilenames() {
    vector<string> parts;

    std::string prefix = options_.prefix;
    size_t ind = prefix.rfind(".mcap");

    if (ind != std::string::npos && ind == prefix.size() - 4)
    {
      prefix.erase(ind);
    }

    if (prefix.length() > 0)
        parts.push_back(prefix);
    if (options_.append_date)
        parts.push_back(timeToStr(ros::WallTime::now()));
    if (options_.split)
        parts.push_back(boost::lexical_cast<string>(split_count_));

    if (parts.size() == 0)
    {
      throw McapException("MCAP filename is empty (neither of these was specified: prefix, append_date, split)");
    }

    target_filename_ = parts[0];
    for (unsigned int i = 1; i < parts.size(); i++)
        target_filename_ += string("_") + parts[i];

    target_filename_ += string(".mcap");
    write_filename_ = target_filename_ + string(".active");
}

//! Callback to be invoked to actually do the recording
void Recorder::snapshotTrigger(std_msgs::Empty::ConstPtr trigger) {
    (void)trigger;
    updateFilenames();

    ROS_INFO("Triggered snapshot recording with name '%s'.", target_filename_.c_str());

    {
        boost::mutex::scoped_lock lock(queue_mutex_);
        queue_queue_.push(OutgoingQueue(target_filename_, queue_, Time::now()));
        queue_      = new std::queue<OutgoingMessage>;
        queue_size_ = 0;
    }

    queue_condition_.notify_all();
}

void Recorder::startWriting() {
    mcap_options_ = RecorderOptionsToMcapWriterOptions(options_);

    updateFilenames();

    try
    {
        file_writer_.open(write_filename_);
    }
    catch (const roscap::McapException& ex)
    {
        ROS_ERROR("Error writing: %s", ex.what());
        exit_code_ = 1;
        ros::shutdown();
    }

    mcap_.open(file_writer_, mcap_options_);
    ROS_INFO("Recording to '%s'.", target_filename_.c_str());

    if (options_.repeat_latched)
    {
        // Start each new MCAP file with copies of all latched messages.
        ros::Time now = ros::Time::now();
        // std::map<std::pair<std::string, std::string>, OutgoingMessage>
        for (auto const& [topicAndCallerId, messageEvent] : latched_msgs_)
        {
            // Overwrite the original receipt time, otherwise the new MCAP will
            // have a gap before the new messages start.
            mcapWrite(messageEvent.topic, now, *messageEvent.msg, nullptr);
        }
    }

    if (options_.publish)
    {
        std_msgs::String msg;
        msg.data = target_filename_.c_str();
        pub_begin_write.publish(msg);
    }
}

void Recorder::stopWriting() {
    ROS_INFO("Closing '%s'.", target_filename_.c_str());
    mcap_.close();
    rename(write_filename_.c_str(), target_filename_.c_str());
}

void Recorder::checkNumSplits()
{
    if(options_.max_splits>0)
    {
        current_files_.push_back(target_filename_);
        if(current_files_.size()>options_.max_splits)
        {
            int err = unlink(current_files_.front().c_str());
            if(err != 0)
            {
                ROS_ERROR("Unable to remove %s: %s", current_files_.front().c_str(), strerror(errno));
            }
            current_files_.pop_front();
        }
    }
}

bool Recorder::checkSize()
{
    if (options_.max_size > 0)
    {
        if (file_writer_.size() > options_.max_size)
        {
            if (options_.split)
            {
                stopWriting();
                split_count_++;
                checkNumSplits();
                startWriting();
            } else {
                ros::shutdown();
                return true;
            }
        }
    }
    return false;
}

bool Recorder::checkDuration(const ros::Time& t)
{
    if (options_.max_duration > ros::Duration(0))
    {
        if (t - start_time_ > options_.max_duration)
        {
            if (options_.split)
            {
                while (start_time_ + options_.max_duration < t)
                {
                    stopWriting();
                    split_count_++;
                    checkNumSplits();
                    start_time_ += options_.max_duration;
                    startWriting();
                }
            } else {
                ros::shutdown();
                return true;
            }
        }
    }
    return false;
}

//! Thread that actually does writing to file.
void Recorder::doRecord() {
    // Open MCAP file for writing
    startWriting();

    // Schedule the disk space check
    warn_next_ = ros::WallTime();

    try
    {
        checkDisk();
    }
    catch (const roscap::McapException& ex)
    {
        ROS_ERROR_STREAM(ex.what());
        exit_code_ = 1;
        stopWriting();
        return;
    }

    check_disk_next_ = ros::WallTime::now() + ros::WallDuration().fromSec(20.0);

    // Technically the queue_mutex_ should be locked while checking empty.
    // Except it should only get checked if the node is not ok, and thus
    // it shouldn't be in contention.
    ros::NodeHandle nh;
    while (nh.ok() || !queue_->empty()) {
        boost::unique_lock<boost::mutex> lock(queue_mutex_);

        bool finished = false;
        while (queue_->empty()) {
            if (!nh.ok()) {
                lock.release()->unlock();
                finished = true;
                break;
            }
            boost::xtime xt;
            boost::xtime_get(&xt, boost::TIME_UTC_);
            xt.nsec += 250000000;
            queue_condition_.timed_wait(lock, xt);
            if (checkDuration(ros::Time::now()))
            {
                finished = true;
                break;
            }
        }
        if (finished)
            break;

        OutgoingMessage out = queue_->front();
        queue_->pop();
        queue_size_ -= out.msg->size();

        lock.release()->unlock();

        if (checkSize())
            break;

        if (checkDuration(out.time))
            break;

        if (scheduledCheckDisk() && checkLogging()) {
            if (!mcapWrite(out.topic, out.time, *out.msg, out.connection_header)) {
                exit_code_ = 1;
                break;
            }
        }
    }

    stopWriting();
}

void Recorder::doRecordSnapshotter() {
    ros::NodeHandle nh;

    while (nh.ok() || !queue_queue_.empty()) {
        boost::unique_lock<boost::mutex> lock(queue_mutex_);
        while (queue_queue_.empty()) {
            if (!nh.ok())
                return;
            queue_condition_.wait(lock);
        }

        OutgoingQueue out_queue = queue_queue_.front();
        queue_queue_.pop();

        lock.release()->unlock();

        string target_filename = out_queue.filename;
        string write_filename  = target_filename + string(".active");

        try
        {
            file_writer_.open(write_filename);
        }
        catch (const roscap::McapException& ex)
        {
            ROS_ERROR("Error writing: %s", ex.what());
            return;
        }

        mcap_.open(file_writer_, mcap_options_);

        while (!out_queue.queue->empty()) {
            OutgoingMessage out = out_queue.queue->front();
            out_queue.queue->pop();

            if (!mcapWrite(out.topic, out.time, *out.msg, nullptr)) {
                break;
            }
        }

        stopWriting();
    }
}

template<class T>
bool Recorder::mcapWrite(std::string const& topic, ros::MessageEvent<T> const& event) {
    return doWrite(topic, event.getReceiptTime(), *event.getMessage(), event.getConnectionHeaderPtr());
}

template<class T>
bool Recorder::mcapWrite(std::string const& topic, ros::Time const& time, T const& msg, boost::shared_ptr<ros::M_string> connection_header) {
    return doWrite(topic, time, msg, connection_header);
}

template<class T>
bool Recorder::mcapWrite(std::string const& topic, ros::Time const& time, boost::shared_ptr<T const> const& msg, boost::shared_ptr<ros::M_string> connection_header) {
    return doWrite(topic, time, *msg, connection_header);
}

template<class T>
bool Recorder::mcapWrite(std::string const& topic, ros::Time const& time, boost::shared_ptr<T> const& msg, boost::shared_ptr<ros::M_string> connection_header) {
    return doWrite(topic, time, *msg, connection_header);
}

template<class T>
bool Recorder::doWrite(std::string const& topic, ros::Time const& time, T const& msg, boost::shared_ptr<ros::M_string> const& connection_header) {
    if (time < ros::TIME_MIN)
    {
        throw McapException("Tried to insert a message with time less than ros::TIME_MIN");
    }

    // Whenever we write we increment our revision
    // bag_revision_++;

    mcap::ChannelId channel_id = 0;
    if (!connection_header) {
        // No connection header: look up by topic

        auto topic_channel_ids_it = topic_channel_ids_.find(topic);
        if (topic_channel_ids_it == topic_channel_ids_.end()) {
            channel_id = createChannel(topic, msg);
            topic_channel_ids_[topic] = channel_id;
        } else {
            channel_id = topic_channel_ids_it->second;
        }
    } else {
        // Store the connection info by the address of the connection header

        // Add the topic name to the connection header, so that when we later search by
        // connection header, we can disambiguate connections that differ only by topic name (i.e.,
        // same callerid, same message type), #3755.  This modified connection header is only used
        // for our bookkeeping, and will not appear in the resulting .mcap file.
        ros::M_string connection_header_copy(*connection_header);
        connection_header_copy["topic"] = topic;

        auto header_channel_ids_it = header_channel_ids_.find(connection_header_copy);
        if (header_channel_ids_it == header_channel_ids_.end()) {
            channel_id = createChannel(topic, msg);
            header_channel_ids_[connection_header_copy] = channel_id;
        } else {
            channel_id = header_channel_ids_it->second;
        }
    }

    // Write the message data
    uint32_t msg_ser_len = ros::serialization::serializationLength(msg);
    record_buffer_.setSize(msg_ser_len);

    ros::serialization::OStream s(record_buffer_.getData(), msg_ser_len);
    ros::serialization::serialize(s, msg);

    mcap::Message message;
    message.channelId = channel_id;
    message.sequence = 0;
    message.logTime = time.toNSec();
    message.publishTime = message.logTime;
    message.dataSize = msg_ser_len;
    message.data = reinterpret_cast<const std::byte*>(record_buffer_.getData());
    const auto status = mcap_.write(message);
    if (!status.ok()) {
        ROS_ERROR("Error writing: %s", status.message.c_str());
        return false;
    }
    return true;
}

template <class T>
mcap::ChannelId Recorder::createChannel(std::string const& topic, T const& msg) {
    mcap::SchemaId schema_id = 0;

    // Find or create the schema
    auto md5sum = std::string(ros::message_traits::md5sum(msg));
    auto md5sum_schema_ids_it = md5sum_schema_ids_.find(md5sum);
    if (md5sum_schema_ids_it == md5sum_schema_ids_.end()) {
        // No mcap::Schema for this md5sum: create one
        auto datatype = std::string(ros::message_traits::datatype(msg));
        auto msg_def  = std::string(ros::message_traits::definition(msg));
        mcap::Schema schema{datatype, "ros1msg", msg_def};
        mcap_.addSchema(schema);
        schema_id = schema.id;
        md5sum_schema_ids_[md5sum] = schema_id;
    } else {
        schema_id = md5sum_schema_ids_it->second;
    }

    // Create the channel
    mcap::KeyValueMap metadata = { {"md5sum", md5sum} };
    mcap::Channel channel{topic, "ros1", schema_id, metadata};
    mcap_.addChannel(channel);
    return channel.id;
}

void Recorder::doCheckMaster(ros::TimerEvent const& e, ros::NodeHandle& node_handle) {
    (void)e;
    (void)node_handle;
    ros::master::V_TopicInfo topics;
    if (ros::master::getTopics(topics)) {
	for (ros::master::TopicInfo const& t : topics) {
	    if (shouldSubscribeToTopic(t.name))
	        subscribe(t.name);
	}
    }

    if (options_.node != std::string(""))
    {

      XmlRpc::XmlRpcValue req;
      req[0] = ros::this_node::getName();
      req[1] = options_.node;
      XmlRpc::XmlRpcValue resp;
      XmlRpc::XmlRpcValue payload;

      if (ros::master::execute("lookupNode", req, resp, payload, true))
      {
        std::string peer_host;
        uint32_t peer_port;

        if (!ros::network::splitURI(static_cast<std::string>(resp[2]), peer_host, peer_port))
        {
          ROS_ERROR("Bad xml-rpc URI trying to inspect node at: [%s]", static_cast<std::string>(resp[2]).c_str());
        } else {

          XmlRpc::XmlRpcClient c(peer_host.c_str(), peer_port, "/");
          XmlRpc::XmlRpcValue req2;
          XmlRpc::XmlRpcValue resp2;
          req2[0] = ros::this_node::getName();
          c.execute("getSubscriptions", req2, resp2);

          if (!c.isFault() && resp2.valid() && resp2.size() > 0 && static_cast<int>(resp2[0]) == 1)
          {
            for(int i = 0; i < resp2[2].size(); i++)
            {
              if (shouldSubscribeToTopic(resp2[2][i][0], true))
                subscribe(resp2[2][i][0]);
            }
          } else {
            ROS_ERROR("Node at: [%s] failed to return subscriptions.", static_cast<std::string>(resp[2]).c_str());
          }
        }
      }
    }
}

void Recorder::doTrigger() {
    ros::NodeHandle nh;
    ros::Publisher pub = nh.advertise<std_msgs::Empty>("snapshot_trigger", 1, true);
    pub.publish(std_msgs::Empty());

    ros::Timer terminate_timer = nh.createTimer(ros::Duration(1.0), boost::bind(&ros::shutdown));
    ros::spin();
}

bool Recorder::scheduledCheckDisk() {
    boost::mutex::scoped_lock lock(check_disk_mutex_);

    if (ros::WallTime::now() < check_disk_next_)
        return true;

    check_disk_next_ += ros::WallDuration().fromSec(20.0);
    return checkDisk();
}

bool Recorder::checkDisk() {
    boost::filesystem::path p(boost::filesystem::system_complete(write_filename_.c_str()));
    p = p.parent_path();
    boost::filesystem::space_info info;
    try
    {
        info = boost::filesystem::space(p);
    }
    catch (const boost::filesystem::filesystem_error& e)
    {
        ROS_WARN("Failed to check filesystem stats [%s].", e.what());
        writing_enabled_ = false;
        return false;
    }
    if ( info.available < options_.min_space)
    {
        writing_enabled_ = false;
        throw McapException("Less than " + options_.min_space_str + " of space free on disk with " + write_filename_ + ". Disabling recording.");
    }
    else if (info.available < 5 * options_.min_space)
    {
        ROS_WARN("Less than 5 x %s of space free on disk with '%s'.", options_.min_space_str.c_str(), write_filename_.c_str());
        writing_enabled_ = true;
    }
    else
    {
        writing_enabled_ = true;
    }
    return true;
}

bool Recorder::checkLogging() {
    if (writing_enabled_)
        return true;

    ros::WallTime now = ros::WallTime::now();
    if (now >= warn_next_) {
        warn_next_ = now + ros::WallDuration().fromSec(5.0);
        ROS_WARN("Not logging message because logging disabled. Most likely cause is a full disk.");
    }
    return false;
}

} // namespace roscap

max_stars_repo_name: jhurliman/roscap

max_issues_repo_name: jhurliman/roscap

max_forks_repo_name: jhurliman/roscap


text:
#ifndef OPENGM_PYTHON_INTERFACE
#define OPENGM_PYTHON_INTERFACE 1
#endif

#include <stdexcept>
#include <stddef.h>
#include <string>
#include <boost/python.hpp>
#include "nifty_iterator.hxx"
#include "inferencehelpers.hxx"
#include "export_typedes.hxx"

#include <opengm/inference/icm.hxx>

// to print parameter as string
template<class ICM, class PARAM>
std::string icmParamAsString(const PARAM & param) {
   std::string s = "[ moveType=";
   if (param.moveType_ == ICM::SINGLE_VARIABLE)
      s.append("variable");
   else
      s.append("factor ]");
   return s;
}

namespace pyicm{
   template<class PARAM,class INF>
   typename pyenums::IcmMoveType getMoveType(const PARAM & p){
      if(p.moveType_==INF::SINGLE_VARIABLE)
         return pyenums::SINGLE_VARIABLE;
      else
         return pyenums::FACTOR;
   }
   template<class PARAM,class INF>
   void setMoveType( PARAM & p,const pyenums::IcmMoveType h){
      if(h==pyenums::SINGLE_VARIABLE)
         p.moveType_=INF::SINGLE_VARIABLE;
      else
         p.moveType_=INF::FACTOR;
   }
}
// export function
template<class GM, class ACC>
void export_icm() {
   using namespace boost::python;
   // import numpy c-api
   import_array();
   // Inference typedefs
   typedef opengm::ICM<GM, ACC> PyICM;
   typedef typename PyICM::Parameter PyICMParameter;
   typedef typename PyICM::VerboseVisitorType PyICMVerboseVisitor;
   // export inference parameter
   class_<PyICMParameter > ("IcmParameter", init< typename PyICM::MoveType > (args("moveType")))
      .def(init<>())
      .add_property("moveType",
           &pyicm::getMoveType<PyICMParameter,PyICM>, pyicm::setMoveType<PyICMParameter,PyICM>)
      .def ("set", &pyicm::setMoveType<PyICMParameter,PyICM>, (arg("moveType")=pyenums::SINGLE_VARIABLE) )
      .def("__str__", &icmParamAsString<PyICM, PyICMParameter>)
      ;
   // export inference verbose visitor via macro
   OPENGM_PYTHON_VERBOSE_VISITOR_EXPORTER(PyICMVerboseVisitor, "IcmVerboseVisitor");
   // export inference via macro
   OPENGM_PYTHON_INFERENCE_EXPORTER(PyICM, "Icm");
}
// explicit template instantiation for the supported semi-rings
template void export_icm<GmAdder, opengm::Minimizer>();
template void export_icm<GmAdder, opengm::Maximizer>();
template void export_icm<GmMultiplier, opengm::Minimizer>();
template void export_icm<GmMultiplier, opengm::Maximizer>();

ext: cxx

max_stars_repo_name: amueller/opengm

max_issues_repo_name: amueller/opengm

max_forks_repo_name: amueller/opengm


text:
#include "Misc.h"
#include "Windows.h"

#include <TlHelp32.h>

#include <boost/algorithm/string.hpp>

unsigned long procIdByWindowName(const std::string& windName)
{
	DWORD dwPID = 0;
	HWND wHandle = 0;
	wHandle = FindWindow(NULL, windName.c_str());
	if (wHandle == 0 || wHandle == INVALID_HANDLE_VALUE)
		return dwPID;

	GetWindowThreadProcessId(wHandle, &dwPID);
	return dwPID;
}

unsigned long procIdByProcName(const std::string& procName)
{
	PROCESSENTRY32 entry;
	DWORD dwPID = 0;

	HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (hSnapshot == 0 || hSnapshot == INVALID_HANDLE_VALUE)
		return dwPID;

	entry.dwSize = sizeof(entry);
	Process32First(hSnapshot, &entry);

	while (Process32Next(hSnapshot, &entry))
	{
		if (boost::iequals(entry.szExeFile, procName))
		{
			dwPID = entry.th32ProcessID;
			break;
		}
	}

	CloseHandle(hSnapshot);
	return dwPID;
}


text:
// Software License for MTL
//
// Copyright (c) 2007 The Trustees of Indiana University.
//               2008 Dresden University of Technology and the Trustees of Indiana University.
//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.
// All rights reserved.
// Authors: Peter Gottschling and Andrew Lumsdaine
//
// This file is part of the Matrix Template Library
//
// See also license.mtl.txt in the distribution.

#ifndef ITL_PC_IS_IDENTITY_INCLUDE
#define ITL_PC_IS_IDENTITY_INCLUDE

#include <boost/mpl/bool.hpp>
#include <boost/numeric/itl/itl_fwd.hpp>

namespace itl { namespace pc {

template <typename PC>
bool is_identity(const PC&)
{ return false; }

template <typename Matrix, typename Value>
bool is_identity(const itl::pc::identity<Matrix, Value>&)
{ return true; }

template <typename PC>
struct static_is_identity
  : boost::mpl::false_
{};

template <typename Matrix, typename Value>
struct static_is_identity<itl::pc::identity<Matrix, Value> >
  : boost::mpl::true_
{};

}} // namespace itl::pc

#endif // ITL_PC_IS_IDENTITY_INCLUDE


text:
//=======================================================================
// Copyright (c) 2013 Piotr Smulewicz
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
/**
 * @file k_cut.hpp
 * @brief
 * @author Piotr Smulewicz, Piotr Godlewski
 * @version 1.0
 * @date 2013-09-25
 */
#ifndef PAAL_K_CUT_HPP
#define PAAL_K_CUT_HPP

#include "paal/utils/functors.hpp"
#include "paal/utils/type_functions.hpp"
#include "paal/utils/irange.hpp"

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/copy.hpp>
#include <boost/graph/iteration_macros.hpp>
#include <boost/graph/one_bit_color_map.hpp>
#include <boost/graph/stoer_wagner_min_cut.hpp>
#include <boost/graph/subgraph.hpp>
#include <boost/range/as_array.hpp>

#include <queue>

namespace paal {
namespace greedy {

/**
 * @brief this is solve k_cut problem
 * and return cut_cost
 * example:
 *  \snippet k_cut_example.cpp K Cut Example
 *
 * example file is k_cut_example.cpp
 * @param graph
 * @param number_of_parts
 * @param result pairs of vertex_descriptor and number form (1,2,
* ... ,k) id of part
 * @param index_map
 * @param weight_map
 * @tparam InGraph
 * @tparam OutputIterator
 * @tparam VertexIndexMap
 * @tparam EdgeWeightMap
 */
template<typename InGraph, class OutputIterator, typename VertexIndexMap, typename EdgeWeightMap>
auto k_cut(const InGraph& graph, unsigned int number_of_parts,OutputIterator result,
            VertexIndexMap index_map, EdgeWeightMap weight_map) ->
            typename boost::property_traits<EdgeWeightMap>::value_type{
    using cost_t = typename boost::property_traits<EdgeWeightMap>::value_type;
    using Vertex = typename boost::graph_traits<InGraph>::vertex_descriptor;

    using Graph = boost::adjacency_list<
        boost::vecS, boost::vecS, boost::undirectedS, boost::no_property,
        boost::property<boost::edge_weight_t, cost_t,
                        boost::property<boost::edge_index_t, int>>>;

    assert(num_vertices(graph) >= number_of_parts);

    std::vector<int> vertex_to_part(num_vertices(graph));
    using VertexIndexToVertex = typename std::vector<Vertex>;
    using VertexIndexToVertexIndex = std::vector<int>;
    VertexIndexToVertex vertex_in_subgraph_to_vertex(num_vertices(graph));
    VertexIndexToVertexIndex vertex_to_vertex_in_subgraph(num_vertices(graph));
    int vertex_in_part;
    int parts = 1;
    // cuts contain pair(x,y)
    // x is the cost of the cut
    // y and y+1 are index parts of graph after make a cut
    std::priority_queue<
            std::pair<cost_t,int>,
            std::vector<std::pair<cost_t,int> >
            ,utils::greater> cuts;

    int id_part = 0;

    //get part id and compute minimum cost of cut of that part and add it to queue
    auto make_cut = [&](int id) {
        vertex_in_part=0;
        for (auto v: boost::as_array(vertices(graph))) {
            if (vertex_to_part[get(index_map, v)] == id) {
                vertex_in_subgraph_to_vertex[vertex_in_part] = v;
                vertex_to_vertex_in_subgraph[get(index_map, v)] = vertex_in_part;
                ++vertex_in_part;
            }
        }
        Graph part(vertex_in_part);
        for (auto edge : boost::as_array(edges(graph))) {
            auto sour = get(index_map, source(edge,graph));
            auto targ = get(index_map, target(edge,graph));
            if (vertex_to_part[sour] == id &&
                    vertex_to_part[targ] == id &&
                    sour != targ) {
                add_edge(vertex_to_vertex_in_subgraph[sour],
                         vertex_to_vertex_in_subgraph[targ],
                         get(weight_map, edge),
                         part);
            }
        }
        if (vertex_in_part < 2) {
            ++id_part;
            *result = std::make_pair(vertex_in_subgraph_to_vertex[0], id_part);
            ++result;
            return;
        }
        auto parities = boost::make_one_bit_color_map(num_vertices(part),
                                            get(boost::vertex_index, part));
        auto cut_cost = boost::stoer_wagner_min_cut(part,
                                          get(boost::edge_weight, part),
                                          boost::parity_map(parities));

        for (auto i : irange(num_vertices(part))) {
            vertex_to_part[get(index_map, vertex_in_subgraph_to_vertex[i])] =
                    parts + get(parities, i); //return value convertable to 0/1
        }
        cuts.push(std::make_pair(cut_cost, parts));
        parts += 2;
    };

    make_cut(0);
    cost_t k_cut_cost = cost_t();
    while (--number_of_parts) {
        auto cut = cuts.top();
        cuts.pop();
        k_cut_cost += cut.first;
        make_cut(cut.second);
        make_cut(cut.second + 1);
    }

    while (!cuts.empty()) {
        auto cut = cuts.top();
        cuts.pop();
        ++id_part;
        for (auto v: boost::as_array(vertices(graph))) {
            if (vertex_to_part[get(index_map, v)] == cut.second ||
                    vertex_to_part[get(index_map, v)] == cut.second + 1) {
                *result = std::make_pair(v, id_part);
                ++result;
            }
        }
    }
    return k_cut_cost;
}

/**
 * @brief this is solve k_cut problem
 * and return cut_cost
 * example:
 *  \snippet k_cut_example.cpp K Cut Example
 *
 * example file is k_cut_example.cpp
 * @param graph
 * @param number_of_parts
 * @param result pairs of vertex_descriptor and number form (1,2, ... ,k) id of part
 * @param params
 * @tparam InGraph
 * @tparam OutputIterator
 * @tparam T
 * @tparam P
 * @tparam R
 */
template<typename InGraph
        ,class OutputIterator
        ,typename T
        ,typename P
        ,typename R>
auto k_cut(const InGraph& graph, unsigned int number_of_parts,
    OutputIterator result, const boost::bgl_named_params<P, T, R>& params) ->
        typename boost::property_traits<
            puretype(boost::choose_const_pmap(get_param(params, boost::edge_weight), graph, boost::edge_weight))
            >::value_type {
    return k_cut(graph, number_of_parts, result,
        boost::choose_const_pmap(get_param(params, boost::vertex_index), graph,boost::vertex_index),
        boost::choose_const_pmap(get_param(params, boost::edge_weight), graph,boost::edge_weight)
    );
}

/**
 * @brief this is solve k_cut problem
 * and return cut_cost
 * example:
 *  \snippet k_cut_example.cpp K Cut Example
 *
 * example file is k_cut_example.cpp
 * @param graph
 * @param number_of_parts
 * @param result pairs of vertex_descriptor and number form (1,2, ... ,k) id of part
 * @tparam InGraph
 * @tparam OutputIterator
 */
template<typename InGraph, class OutputIterator>
auto k_cut(const InGraph& graph, unsigned int number_of_parts, OutputIterator result) ->
        typename boost::property_traits<puretype(get(boost::edge_weight,graph))>::value_type{
    return k_cut(graph, number_of_parts, result, boost::no_named_parameters());
}

} //!greedy
} //!paal

#endif // PAAL_K_CUT_HPP

max_stars_repo_name: Kommeren/AA

max_issues_repo_name: Kommeren/AA

max_forks_repo_name: Kommeren/AA