text:
#include "io_ledger_tcp.hpp"
#include "common/oxen.h"
#include <array>
#include <boost/endian/conversion.hpp>
#include <cstring>
#include <stdexcept>
#include "epee/misc_log_ex.h"

extern "C" {
#ifdef _WIN32
#  include <ws2tcpip.h>
#  include <winsock2.h>
#else
#  include <arpa/inet.h>
#  include <netdb.h>
#  include <netinet/in.h>
#  include <sys/socket.h>
#endif
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
}

#undef OXEN_DEFAULT_LOG_CATEGORY
#define OXEN_DEFAULT_LOG_CATEGORY "device.io"

namespace hw::io {

static std::string to_string(const addrinfo* a) {
  std::array<char, INET6_ADDRSTRLEN> buf;
  std::string addr;
#ifdef _WIN32
  unsigned long buflen = buf.size();
  if (auto rc = WSAAddressToString(a->ai_addr, a->ai_addrlen, nullptr, buf.data(), &buflen);
      rc == 0)
    addr = buf.data();
  else
    addr = "[error:"s + std::to_string(rc) + "]";
#else
  if (inet_ntop(a->ai_family, a->ai_addr, buf.data(), buf.size()))
    addr = buf.data();
  else
    addr = "[error:"s + strerror(errno) + "]";
#endif
  if (a->ai_family == AF_INET)
    (addr += ':') += std::to_string(reinterpret_cast<sockaddr_in*>(a->ai_addr)->sin_port);
  else if (a->ai_family == AF_INET6)
    (addr += ':') += std::to_string(reinterpret_cast<sockaddr_in6*>(a->ai_addr)->sin6_port);
  return addr;
}

void ledger_tcp::connect() {
  disconnect();

  int fd = socket(AF_INET, SOCK_STREAM, 0);
  if (fd < 0)
    throw std::runtime_error{"Failed to open socket: "s + strerror(errno)};
  auto closer = oxen::defer([&] { close(fd); });

#ifdef _WIN32
  unsigned long blocking_param = 1; // 1 = make non-blocking, 0 = blocking
  if (auto result = ioctlsocket(fd, FIONBIO, &blocking_param);
      result != NO_ERROR)
    throw std::runtime_error{"ioctlsocket failed with error: " + std::to_string(result)};
#else
  if (-1 == fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK))
    throw std::runtime_error{"Failed to set socket non-blocking: "s + strerror(errno)};
#endif

  addrinfo* addr;
  if (int rc = getaddrinfo(host.data(), port.data(), nullptr, &addr);
      rc != 0)
    throw std::runtime_error{"Failed to resolve " + host + ":" + port + ": " + gai_strerror(rc)};
  auto addr_free = oxen::defer([&] { freeaddrinfo(addr); });

  const addrinfo* a;
  bool connected = false;
  const char* err = "An unknown error occurred";
  for (a = addr; a && !connected; a = a->ai_next) {
    MDEBUG("Attempting to connect to " << to_string(a));
    int rc = ::connect(fd, a->ai_addr, a->ai_addrlen);
    connected = rc == 0;
    if (rc == -1) {
      if (errno == EINPROGRESS) {
        timeval timeo;
        timeo.tv_sec = std::chrono::duration_cast<std::chrono::seconds>(connect_timeout).count();
        timeo.tv_usec = (connect_timeout % 1s).count();
        fd_set myset;
        FD_ZERO(&myset);
        FD_SET(fd, &myset);
        rc = select(fd + 1, nullptr, &myset, nullptr, &timeo);
        if (rc > 0)
          connected = true;
        else if (rc == 0)
          err = "Connection timed out";
        else
          err = strerror(errno);
      } else {
        err = strerror(errno);
      }
    }
  }
  if (!connected)
    throw std::runtime_error{"Failed to connect to " + host + ":" + port + ": " + err};

  MDEBUG("Connected to " << to_string(a));

#ifdef _WIN32
  blocking_param = 0;
  if (auto result = ioctlsocket(fd, FIONBIO, &blocking_param);
      result != NO_ERROR)
    throw std::runtime_error{"ioctlsocket failed with error: " + std::to_string(result)};
#else
  if (-1 == fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) & ~O_NONBLOCK))
    throw std::runtime_error{"Failed to set socket back to blocking: "s + strerror(errno)};
#endif

  timeval timeo;
  timeo.tv_sec = std::chrono::duration_cast<std::chrono::seconds>(exchange_timeout).count();
  timeo.tv_usec = (exchange_timeout % 1s).count();

  // The reinterpret_cast here is needed for Windows's shitty imitation of the api
  setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const char*>(&timeo), sizeof(timeo));
  setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<const char*>(&timeo), sizeof(timeo));

  sockfd = std::make_unique<int>(fd);
  closer.cancel();
}

void ledger_tcp::disconnect() {
  if (!sockfd)
    return;

  close(*sockfd);
  sockfd.reset();
}

ledger_tcp::~ledger_tcp() {
  disconnect();
}

bool ledger_tcp::connected() const {
  return (bool) sockfd;
}

void full_read(int fd, unsigned char* to, int size) {
  while (size > 0) {
    auto read_size = read(fd, to, size);
    if (read_size == -1)
      throw std::runtime_error{"Failed to read from hardware wallet socket: "s + strerror(errno)};
    size -= read_size;
    to += read_size;
  }
}

void full_write(int fd, const unsigned char* from, int size) {
  while (size > 0) {
    auto wrote = write(fd, from, size);
    if (wrote == -1)
      throw std::runtime_error{"Failed to write to hardware wallet socket: "s + strerror(errno)};
    size -= wrote;
    from += wrote;
  }
}

int ledger_tcp::exchange(const unsigned char* command, unsigned int cmd_len, unsigned char* response, unsigned int max_resp_len, bool user_input) {
  if (!sockfd)
    throw std::runtime_error{"Unable to exchange data with hardware wallet: not connected"};

  // Sending: [SIZE][DATA], where SIZE is a uint32_t in network order
  uint32_t size = boost::endian::native_to_big(cmd_len);
  const unsigned char* size_bytes = reinterpret_cast<const unsigned char*>(&size);
  full_write(*sockfd, size_bytes, 4);
  full_write(*sockfd, command, cmd_len);

  // Receiving: [SIZE][DATA], where SIZE is the length of DATA minus 2 (WTF) because the last two
  // bytes of DATA are a 2-byte, u16 status code and... therefore not... included.  Good job, Ledger
  // devs.
  full_read(*sockfd, reinterpret_cast<unsigned char*>(&size), 4);
  auto data_size = boost::endian::big_to_native(size) + 2;

  if (data_size > max_resp_len)
    throw std::runtime_error{"Hardware wallet returned unexpectedly large response: got " +
      std::to_string(data_size) + " bytes, expected <= " + std::to_string(max_resp_len)};

  full_read(*sockfd, response, data_size);

  return data_size;
}

}


text:
// Author: Senthil Kumar Thangavelu kingjuliyen@gmail.com

/*
  Compile:
  g++  HiddenFactorsLearner.cpp \
       -I/opt/boost/1_61_0/include/						\
       -L/opt/boost/1_61_0/lib						\
       -lboost_program_options \
       -O3 -o /tmp/hidden-factor-learner

  Usage:
  export DYLD_LIBRARY_PATH=/opt/boost/1_61_0/lib:$DYLD_LIBRARY_PATH

  DYLD_LIBRARY_PATH=/opt/boost/1_61_0/lib:$DYLD_LIBRARY_PATH \
  time /tmp/hidden-factor-learner --num-factors 5 \
          --default-rating 2.8485 \
          --regularization-param-p 0.002 \
          --regularization-param-q 0.002 \
          --learning-rate-p 0.000002 \
          --learning-rate-q 0.000002 \
          --training-sample-percentage 0.7 \
          --gradient-descent-iteration-count 100 \
          --max-row-dimension 100000000 \
          --max-column-dimension 100000000 \
          --verbose-mode-level 1 \
          --loop-mode-count 3 \
          --input-csv-file-path /tmp/1000.csv \
          --p-q-matrix-output-file-path /tmp/

e.g csv file (remove header)
usrid  itemid rating
785166 6066 3
521295 4972 3
1665652 11701 5
1963419 15887 3

  Linux:

  LD_LIBRARY_PATH=/opt/boost/1_61_0/lib:$LD_LIBRARY_PATH \
  time /tmp/hidden-factor-learner --num-factors 2 \
          --default-rating 2.8485 \
          --regularization-param-p 0.002 \
          --regularization-param-q 0.002 \
          --learning-rate-p 0.000002 \
          --learning-rate-q 0.000002 \
          --training-sample-percentage 0.7 \
          --gradient-descent-iteration-count 100 \
          --max-row-dimension 100000000 \
          --max-column-dimension 100000000 \
          --verbose-mode-level 1 \
          --loop-mode-count 3 \
          --input-csv-file-path /tmp/sf41.csv \
          --p-q-matrix-output-file-path /tmp/

  Install boost:
  ./bootstrap.sh --prefix=/opt/boost/1_61_0
  ./b2 install
*/

#include <iostream>
#include <string>
#include <boost/program_options.hpp>

#include "HiddenFactorsLearner.hpp"

namespace ProgOpts = boost::program_options;

const char * num_factors_str =
  "Number of hidden factors aka K ";
const char * default_rating_str =
  "Default rating used in the matrix factorization"
  " at start of gradient descent ";
const char * regularization_param_p_str =
  "Regularization parameter for matrix P ";
const char * regularization_param_q_str =
  "Regularization parameter for matrix Q ";
const char * learning_rate_p_str =
  "Learning rate for matrix P parameters in gradient descent ";
const char * learning_rate_q_str =
  "Learning rate for matrix Q parameters in gradient descent ";
const char * gradient_descent_iteration_count_str =
  "Number of times gradient descent iterations need to be run ";
const char * training_sample_percentage_str =
  "Percentage of data set to be used for training ";
  //"remaining percentage will be used for validation ";
const char * max_row_dim_str= "Max dimension for rows in matrix";
const char * max_col_dim_str = "Max dimension for columns in matrix";
const char * input_csv_str = "Path of input csv file to read rating "
  "entries from ";
const char * verbose_mode_level_str = "Show debug info about inner workings ";
const char * loop_mode_count_str = "Run repeatedly in loop mode for same input ";
const char * P_Q_matrix_output_file_path_str = "path to store P and Q matrix output";

bool processInputArgs(int argc, char * argv[], ProgOpts::variables_map &varMap,
        MatrixFactorizationParams &params)
{
  try {
    ProgOpts::options_description desc("Allowed Options");

    desc.add_options()
      ("help", "produce help message")
      ("num-factors", ProgOpts::value<INT_T>(), num_factors_str)
      ("default-rating", ProgOpts::value<FLT_T>(), default_rating_str)
      ("regularization-param-p", ProgOpts::value<FLT_T>(), regularization_param_p_str)
      ("regularization-param-q", ProgOpts::value<FLT_T>(), regularization_param_q_str)
      ("learning-rate-p", ProgOpts::value<FLT_T>(), learning_rate_p_str)
      ("learning-rate-q", ProgOpts::value<FLT_T>(), learning_rate_q_str)
      ("gradient-descent-iteration-count", ProgOpts::value<INT_T>(), gradient_descent_iteration_count_str)
      ("training-sample-percentage", ProgOpts::value<FLT_T>(), training_sample_percentage_str)
      ("max-row-dimension", ProgOpts::value<INT_T>(), max_row_dim_str)
      ("max-column-dimension", ProgOpts::value<INT_T>(), max_col_dim_str)
      ("input-csv-file-path", ProgOpts::value<STRING_T>(), input_csv_str)
      ("verbose-mode-level", ProgOpts::value<INT_T>(), verbose_mode_level_str)
      ("loop-mode-count", ProgOpts::value<INT_T>(), loop_mode_count_str)
      ("p-q-matrix-output-file-path", ProgOpts::value<STRING_T>(), P_Q_matrix_output_file_path_str)
      ; // leave this semi colon at end don't move this

    ProgOpts::store(ProgOpts::parse_command_line(argc, argv, desc), varMap);
    ProgOpts::notify(varMap);

    if (varMap.count("help")) {
      cout << desc << "\n";
      return false;
    }

    OPT(num_factors , "num-factors", INT_T,  5);
    OPT(default_rating ,"default-rating" , FLT_T,  2.8485);
    OPT(regularization_param_p ,"regularization-param-p", FLT_T,  0.002);
    OPT(regularization_param_q ,"regularization-param-q", FLT_T,  0.002);
    OPT(learning_rate_p ,"learning-rate-p", FLT_T,  0.000002);
    OPT(learning_rate_q ,"learning-rate-q", FLT_T,  0.000002);
    OPT(gradient_descent_iteration_count ,"gradient-descent-iteration-count", INT_T,  100);
    OPT(training_sample_percentage ,"training-sample-percentage", FLT_T,  0.70);
    OPT(max_row_dim ,"max-row-dimension", INT_T,  100000000);
    OPT(max_col_dim ,"max-column-dimension", INT_T,  100000000);
    OPT(csv_input_file_path ,"input-csv-file-path", STRING_T,  STRING_T("unknown_bad.csv"));
    OPT(verbose_mode_level ,"verbose-mode-level", INT_T,  0);
    OPT(loop_mode_count ,"loop-mode-count", INT_T,  1);
    OPT(p_q_matrix_output_file_path, "p-q-matrix-output-file-path", STRING_T,  STRING_T("P_Q_matrix.mtx"));

  }
  catch(exception &e)
  {
    cerr << "\n processInputArgs error: " << e.what() << "\n";
    return false;
  }
  return true;
}

void Sleep() {
  cout << "\n\n\n\n\n\nSleeping for 10 seconds \n";
  system("sleep 10");
}

void printHeader() {
  cout << "\n\n\n=================================================\n";
  cout << "=============== START TRAINING ==================\n";
  cout << "=================================================\n\n";
}

int startMatrixFactorization_Trainer(int argc, char * argv[])
{
  ProgOpts::variables_map vmp; // varmap
  MatrixFactorizationParams params;

  bool b = processInputArgs(argc, argv, vmp, params);
  if(!b)
    return 3;

  printHeader();
  FLT_T rmseSum = 0;
  FLT_T iterationCount = 0;

  for(int i=0; i<params.loop_mode_count; i++) {
    MatrixFactorization trainer(params);
    if(!trainer.startTraining()) {
      cout << "Training failed check input files and training params\n";
      return 4;
    }
    cout << "Trial " << i << " finalRMSE " << trainer.getFinalRMSE()
      << " num iterations " << trainer.getNumIterations() << "\n";
    rmseSum += trainer.getFinalRMSE();
    iterationCount += 1;
    trainer.printPredictedValues(10);
  }
  cout << " avg RMSE " << (rmseSum/iterationCount)
    << " found using "<< iterationCount << " trials \n";
  return 0;
}

int main(int argc, char * argv[])
{
  return startMatrixFactorization_Trainer(argc, argv);
}

ext: cpp

max_stars_repo_name: kingjuliyen/RecommenderSystemExplicit

max_issues_repo_name: kingjuliyen/RecommenderSystemExplicit

max_forks_repo_name: kingjuliyen/RecommenderSystemExplicit


text: #include <boost/interprocess/sync/sharable_lock.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/*
 *
 * Copyright (c) 2003 Dr John Maddock
 * Use, modification and distribution is subject to the
 * Boost Software License, Version 1.0. (See accompanying file
 * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
 *
 * This file implements the following:
 *    void bcp_implementation::copy_path(const fs::path& p)
 *    void bcp_implementation::create_path(const fs::path& p)
 */

#include "bcp_imp.hpp"
#include "fileview.hpp"
#include <boost/filesystem/operations.hpp>
#include <boost/regex.hpp>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <iostream>

struct get_new_library_name
{
   get_new_library_name(const std::string& n) : m_new_name(n) {}
   template <class I>
   std::string operator()(const boost::match_results<I>& what)
   {
      std::string s = what[0];
      std::string::size_type n = s.find("boost");
      if(n == std::string::npos)
      {
         s.insert(0, m_new_name);
      }
      else
      {
         s.replace(n, 5, m_new_name);
      }
      return s;
   }
private:
   std::string m_new_name;
};

void bcp_implementation::copy_path(const fs::path& p)
{
   assert(!fs::is_directory(m_boost_path / p));
   if(fs::exists(m_dest_path / p))
   {
      std::cout << "Copying (and overwriting) file: " << p.string() << "\n";
     fs::remove(m_dest_path / p);
   }
   else
      std::cout << "Copying file: " << p.string() << "\n";
   //
   // create the path to the new file if it doesn't already exist:
   //
   create_path(p.branch_path());
   //
   // do text based copy if requested:
   //
   if(p.leaf() == "Jamroot")
   {
      static std::vector<char> v1, v2;
      v1.clear();
      v2.clear();
      std::ifstream is((m_boost_path / p).c_str());
      std::copy(std::istreambuf_iterator<char>(is), std::istreambuf_iterator<char>(), std::back_inserter(v1));

      static boost::regex libname_matcher;
      if(libname_matcher.empty())
      {
         libname_matcher.assign("boost_");
      }

      regex_replace(std::back_inserter(v2), v1.begin(), v1.end(), libname_matcher, m_namespace_name + "_");
      std::swap(v1, v2);
      v2.clear();

      std::ofstream os;
      if(m_unix_lines)
         os.open((m_dest_path / p).c_str(), std::ios_base::binary | std::ios_base::out);
      else
         os.open((m_dest_path / p).c_str(), std::ios_base::out);
      os.write(&*v1.begin(), v1.size());
      os.close();
   }
   else if(m_namespace_name.size() && m_lib_names.size() && is_jam_file(p))
   {
      static std::vector<char> v1, v2;
      v1.clear();
      v2.clear();
      std::ifstream is((m_boost_path / p).c_str());
      std::copy(std::istreambuf_iterator<char>(is), std::istreambuf_iterator<char>(), std::back_inserter(v1));

      static boost::regex libname_matcher;
      if(libname_matcher.empty())
      {
         std::string re = "\\<";
         re += *m_lib_names.begin();
         for(std::set<std::string>::const_iterator i = ++m_lib_names.begin(); i != m_lib_names.end(); ++i)
         {
            re += "|" + *i;
         }
         re += "\\>";
         libname_matcher.assign(re);
      }

      regex_replace(std::back_inserter(v2), v1.begin(), v1.end(), libname_matcher, get_new_library_name(m_namespace_name));
      std::swap(v1, v2);
      v2.clear();

      std::ofstream os;
      if(m_unix_lines)
         os.open((m_dest_path / p).c_str(), std::ios_base::binary | std::ios_base::out);
      else
         os.open((m_dest_path / p).c_str(), std::ios_base::out);
      os.write(&*v1.begin(), v1.size());
      os.close();
   }
   else if(m_namespace_name.size() && is_source_file(p))
   {
      //
      // v1 hold the current content, v2 is temp buffer.
      // Each time we do a search and replace the new content
      // ends up in v2: we then swap v1 and v2, and clear v2.
      //
      static std::vector<char> v1, v2;
      v1.clear();
      v2.clear();
      std::ifstream is((m_boost_path / p).c_str());
      std::copy(std::istreambuf_iterator<char>(is), std::istreambuf_iterator<char>(), std::back_inserter(v1));

      static const boost::regex namespace_matcher(
         "(?|"
            "(namespace\\s+)boost(_\\w+)?(?:(\\s*::\\s*)phoenix)?"
         "|"
            "(namespace\\s+)(adstl|phoenix|rapidxml)\\>"
         "|"
            "()\\<boost((?:_(?!intrusive_tags)\\w+)?\\s*(?:::))(?:(\\s*)phoenix)?"
         "|"
            "()\\<((?:adstl|phoenix|rapidxml)\\s*(?:::))"
         "|"
         "(namespace\\s+\\w+\\s*=\\s*(?:::\\s*)?)boost(_\\w+)?(?:(\\s*::\\s*)phoenix)?"
         "|"
            "(namespace\\s+\\w+\\s*=\\s*(?:::\\s*)?(?:\\w+\\s*::\\s*)?)(adstl|phoenix|rapidxml)\\>"
         "|"
            "(^\\s*#\\s*define\\s+\\w+\\s+)boost((?:_\\w+)?\\s*)$"
         "|"
            "(^\\s*#\\s*define[^\\n]+)((?:adstl|phoenix|rapidxml)\\s*)$"
         "|"
            "()boost(_asio_detail_posix_thread_function|_regex_free_static_mutex)"
         "|"
            "()(lw_thread_routine|at_thread_exit|on_process_enter|on_process_exit|on_thread_enter|on_thread_exit|tss_cleanup_implemented)"
         "|"
            "(BOOST_CLASS_REQUIRE4?[^;]*)boost((?:_\\w+)?\\s*,)"
         "|"
            "(\\(\\s*)boost(\\s*\\))"
         ")"
      );

      regex_replace(std::back_inserter(v2), v1.begin(), v1.end(), namespace_matcher, "$1" + m_namespace_name + "$2(?3$3" + m_namespace_name + "phoenix)", boost::regex_constants::format_all);
      std::swap(v1, v2);
      v2.clear();

      if(m_namespace_alias)
      {
         static const boost::regex namespace_alias(
            /*
            "namespace\\s+" + m_namespace_name +
            "\\s*"
            "("
               "\\{"
               "(?:"
                  "(?>[^\\{\\}/]+)"
                  "(?>"
                     "(?:"
                        "(?1)"
                        "|//[^\\n]+$"
                        "|/[^/]"
                        "|(?:^\\s*#[^\\n]*"
                           "(?:(?<=\\\\)\\n[^\\n]*)*)"
                     ")"
                     "[^\\{\\}]+"
                  ")*"
               ")*"
               "\\}"
            ")"
            */
            /*
            "(namespace\\s+" + m_namespace_name +
            "\\s*\\{.*"
            "\\})([^\\{\\};]*)\\z"
            */
            "namespace\\s+" + m_namespace_name +
            "\\s*\\{"
            );
         regex_replace(std::back_inserter(v2), v1.begin(), v1.end(), namespace_alias,
            "namespace " + m_namespace_name + "{} namespace boost = " + m_namespace_name + "; namespace " + m_namespace_name + "{");
         std::swap(v1, v2);
         v2.clear();
      }

      std::ofstream os;
      if(m_unix_lines)
         os.open((m_dest_path / p).c_str(), std::ios_base::binary | std::ios_base::out);
      else
         os.open((m_dest_path / p).c_str(), std::ios_base::out);
      if(v1.size())
         os.write(&*v1.begin(), v1.size());
      os.close();
   }
   else if(m_unix_lines && !is_binary_file(p))
   {
      std::ifstream is((m_boost_path / p).c_str());
      std::istreambuf_iterator<char> isi(is);
      std::istreambuf_iterator<char> end;

      std::ofstream os((m_dest_path / p).c_str(), std::ios_base::binary | std::ios_base::out);
      std::ostreambuf_iterator<char> osi(os);

      std::copy(isi, end, osi);
   }
   else
   {
      // binary copy:
      fs::copy_file(m_boost_path / p, m_dest_path / p);
   }
}

void bcp_implementation::create_path(const fs::path& p)
{
   if(!fs::exists(m_dest_path / p))
   {
      // recurse then create the path:
      create_path(p.branch_path());
      fs::create_directory(m_dest_path / p);
   }
}

max_forks_repo_name: olegshnitko/libboost


text:
//=======================================================================
// Copyright (c)
//
// 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 tree_augmentation_example.cpp
 * @brief
 * @author Attila Bernath, Piotr Godlewski
 * @version 1.0
 * @date 2013-10-17
 */

//! [Tree Augmentation Example]
#include "paal/iterative_rounding/treeaug/tree_augmentation.hpp"

#include <boost/graph/adjacency_list.hpp>

#include <iostream>
#include <vector>

int main() {
    using EdgeProp = boost::property<boost::edge_weight_t, double,
                boost::property<boost::edge_color_t, bool>>;
    using Graph = boost::adjacency_list<boost::vecS, boost::vecS,
                boost::undirectedS, boost::no_property, EdgeProp>;
    using Edge = boost::graph_traits<Graph>::edge_descriptor;

    // sample problem
    std::vector<std::pair<int, int>> edges {{0,1},{1,2},{1,3},{3,4},{3,5},
            {0,3},{0,3},{2,4},{2,5},{4,5}};
    std::vector<EdgeProp> edge_properties {EdgeProp(0, true),
        EdgeProp(0, true), EdgeProp(0, true), EdgeProp(0, true),
        EdgeProp(0, true), EdgeProp(1, false), EdgeProp(1, false),
        EdgeProp(1, false), EdgeProp(1, false), EdgeProp(1,false)};

    Graph g(edges.begin(), edges.end(), edge_properties.begin(), 6);

    std::vector<Edge> solution;

    // optional input validity checking
    auto tree_aug = paal::ir::make_tree_aug(g, std::back_inserter(solution));
    auto error = tree_aug.check_input_validity();
    if (error) {
        std::cerr << "The input is not valid!" << std::endl;
        std::cerr << *error << std::endl;
        return -1;
    }

    // solve it
    auto result = paal::ir::tree_augmentation_iterative_rounding(
        g, std::back_inserter(solution));

    // print result
    if (result.first == paal::lp::OPTIMAL) {
        std::cout << "The solution contains the following nontree edges:"
            << std::endl;
        for (auto e : solution) {
            std::cout << "Edge " << e << std::endl;
        }
        std::cout << "Cost of the solution: " << *(result.second) << std::endl;
    } else {
        std::cout << "The instance is infeasible" << std::endl;
    }
    paal::lp::glp::free_env();
    return 0;
}
    //! [Tree Augmentation Example]

max_stars_repo_name: Kommeren/AA

max_issues_repo_name: Kommeren/AA

max_forks_repo_name: Kommeren/AA


text:
/*
 * Copyright (c) 2014 by Matthias Noack, Zuse Institute Berlin
 *
 * Licensed under the BSD License, see LICENSE file for details.
 *
 */

#include "ld_preload/preload.h"

#include <pthread.h>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <stdio.h>
#include <fcntl.h>
#include <list>
#include <string>
#include <boost/atomic.hpp>
#include "libxtreemfs/client.h"
#include "libxtreemfs/file_handle.h"
#include "libxtreemfs/options.h"
#include "libxtreemfs/pbrpc_url.h"
#include "libxtreemfs/system_user_mapping_unix.h"
#include "libxtreemfs/volume_implementation.h"
#include "libxtreemfs/xtreemfs_exception.h"
#include "util/logging.h"

#include "ld_preload/environment.h"
#include "ld_preload/misc.h"
#include "ld_preload/passthrough.h"

static Environment* env = NULL;

/**
 * The environment should be initialised exactly once during shared library initialisation.
 * Prior to that, all operations work in pass-through mode.
 * To overcome undefined global initialisation order, we use a local static variable.
 * This variable is accesd by a single writer (lib (de)initialisation), and multiple readers (exported operations).
 * Writer: toggle == true (toggles is_initialised)
 * Reader: toggle == false (returns the current value of is_initialised)
 *
 * NOTE: pthread_once initialisation for the overlay leads to a deadlock due to a re-entry situation:
 * - environment ctor is called the first time via pthread_once
 * - which leads a write somewhere (probably to a socket during client initialisation)
 * - which then enters the pthread_once initialisation mechanism again and blocks deadlocks
 */
bool overlay_initialized(bool toggle /* defaults to: false */) {
  static boost::atomic<bool> is_initilized(false);

  // writer
  if(toggle) {
    return is_initilized.exchange(!is_initilized.load());
  }

  // reader
  return is_initilized.load();
}

void initialize_env() {
  env = new Environment();
  xprintf("env initialised\n");
}

void deinitialize_env() {
  xprintf("deinitialize_env()\n");
  delete env;
  xprintf("env deinitialised\n");
}

Environment* get_env() {
  return env;
}

bool is_xtreemfs_fd(int fd) {
  return env->open_file_table_.Has(fd);
}

bool is_xtreemfs_path(const char *path) {
  Path path_obj(path);
  return path_obj.IsXtreemFS();
}

/* Library constructor */
void
__attribute__((constructor))
init_preload(void) {
  initialize_passthrough_if_necessary();
  xprintf("library initialisation 1\n");
  xprintf("library initialisation 2\n");
  initialize_env();
  xprintf("library initialisation 3\n");
  bool ret = overlay_initialized(true); // activate overlay filesystem
  xprintf("library initialised! %d\n", ret);
}

/* Library destructor */
void
__attribute__((destructor))
deinit_preload(void) {
  xprintf("library deinitialisation started.\n");
  bool ret = overlay_initialized(true); // deactivate overlay filesystem
  deinitialize_env();
  xprintf("library deinitialised! %d\n", ret);
}

/* XtreemFS equivalents to POSIX file system calls */

int xtreemfs_open(const char* pathname, int flags, int mode) {
  xprintf(" open on xtreemfs(%s)\n", pathname);
  Path path(pathname);
  path.Parse();

  xtreemfs::Volume* volume = env->GetVolume();
  const xtreemfs::pbrpc::SYSTEM_V_FCNTL xtreem_flags = ConvertFlagsUnixToXtreemFS(flags);

  xtreemfs::FileHandle* handle = volume->OpenFile(
      env->user_creds_,
      path.GetXtreemFSPath(),
      xtreem_flags,
      mode);

  int fd = env->open_file_table_.Register(handle);
  xprintf(" open on xtreemfs(%s) -> %d\n", pathname, fd);
  return fd;
}

int xtreemfs_close(int fd) {
  xprintf(" close xtreemfs(%d)\n", fd);
  OpenFile handle = env->open_file_table_.Get(fd);
  env->open_file_table_.Unregister(fd);
  //handle.fh_->Flush(); // implicit by close
  handle.fh_->Close(); // TODO: error code
  return 0;
}

uint64_t xtreemfs_pread(int fd, void* buf, uint64_t nbyte, uint64_t offset) {
  xprintf(" read xtreemfs(%d)\n", fd);
  OpenFile handle = env->open_file_table_.Get(fd);
  return handle.fh_->Read((char*)buf, nbyte, offset);
}

uint64_t xtreemfs_read(int fd, void* buf, uint64_t nbyte) {
  xprintf(" read xtreemfs(%d)\n", fd);
  OpenFile handle = env->open_file_table_.Get(fd);
  int read = handle.fh_->Read((char*)buf, nbyte, handle.offset_);
  env->open_file_table_.SetOffset(fd, handle.offset_ + read);
  return read;
}

uint64_t xtreemfs_write(int fd, const void* buf, uint64_t nbyte) {
  xprintf(" write xtreemfs(%d)\n", fd);
  OpenFile handle = env->open_file_table_.Get(fd);
  int written = handle.fh_->Write((char*)buf, nbyte, handle.offset_);
  env->open_file_table_.SetOffset(fd, handle.offset_ + written);
  return written;
}

int xtreemfs_dup2(int oldfd, int newfd) {
  xprintf(" dup2 xtreemfs(%d, %d)\n", oldfd, newfd);
  OpenFile handle = env->open_file_table_.Get(oldfd);
  if (handle.fh_ == NULL) {
    xprintf(" dup2 error(%d, %d)\n", oldfd, newfd);
    return -1;
  }
  xprintf(" dup2 fffxtreemfs(%d, %d)\n", oldfd, newfd);
  xtreemfs::FileHandle* new_handle; // = handle.fh_->Duplicate(); // TODO: implement Duplicate

  xprintf(" dup2 yxtreemfs(%d, %d)\n", oldfd, newfd);
  env->open_file_table_.Set(newfd, new_handle);
  return newfd;
}

int xtreemfs_dup(int fd) {
  xprintf(" dup xtreemfs(%d)\n", fd);
  OpenFile handle = env->open_file_table_.Get(fd);
  xtreemfs::FileHandle* new_handle; // = handle.fh_->Duplicate(); // TODO: implement Duplicate
  return env->open_file_table_.Register(new_handle);
}

off_t xtreemfs_lseek(int fd, off_t offset, int mode) {
  xprintf(" lseek xtreemfs(%d)\n", fd);
  OpenFile handle = env->open_file_table_.Get(fd);

  switch (mode) {
    case SEEK_SET:
      env->open_file_table_.SetOffset(fd, offset);
      return offset;
    case SEEK_CUR:
      env->open_file_table_.SetOffset(fd, handle.offset_ + offset);
      return handle.offset_ + offset;
    case SEEK_END:
      env->open_file_table_.SetOffset(fd, offset);  // TODO
      return offset;
  }
  return EINVAL;
}

/* T should be "struct stat" or "struct stat64" */
template<typename T>
static int xtreemfs_stat_impl(const char *pathname, T *buf) {
  Path path(pathname);
  path.Parse();
  xtreemfs::pbrpc::Stat stat;

  try {
    env->GetVolume()->GetAttr(env->user_creds_, path.GetXtreemFSPath(), &stat);
  } catch(const xtreemfs::PosixErrorException& e) {
    errno = ConvertXtreemFSErrnoToUnix(e.posix_errno());
    xprintf(" xtreemfs_stat_impl(%s), returning -1, errno(%d)\n", pathname, errno);
    return -1;
  } catch(const xtreemfs::XtreemFSException& e) {
    xprintf(" xtreemfs_stat_impl(%s), returning -1, errno(%d)\n", pathname, errno);
    errno = EIO;
    return -1;
  } catch(const std::exception& e) {
    xprintf("A non-XtreemFS exception occurred: %s", std::string(e.what()).c_str());
    xprintf(" xtreemfs_stat_impl(%s), returning -1, errno(%d)\n", pathname, errno);
    errno = EIO;
    return -1;
  }

  ConvertXtreemFSStatToUnix(stat, buf, env->GetSystemUserMapping());
  xprintf(" xtreemfs_fstat_impl(%s), returning 0\n", pathname);
  return 0;
}

/* T should be "struct stat" or "struct stat64" */
template<typename T>
static int xtreemfs_fstat_impl(int fd, T *buf) {
  OpenFile handle = env->open_file_table_.Get(fd);
  xtreemfs::pbrpc::Stat stat;

  try {
    handle.fh_->GetAttr(env->user_creds_, &stat);
  } catch(const xtreemfs::PosixErrorException& e) {
    errno = ConvertXtreemFSErrnoToUnix(e.posix_errno());
    return -1;
  } catch(const xtreemfs::XtreemFSException& e) {
    errno = EIO;
    return -1;
  } catch(const std::exception& e) {
    xprintf("A non-XtreemFS exception occurred: %s", std::string(e.what()).c_str());
    errno = EIO;
    return -1;
  }

  ConvertXtreemFSStatToUnix(stat, buf, env->GetSystemUserMapping());
  return 0;
}

int xtreemfs_stat(const char *pathname, struct stat *buf) {
  xprintf(" xtreemfs_stat(%s)\n", pathname);
  return xtreemfs_stat_impl(pathname, buf);
}

int xtreemfs_stat64(const char *pathname, struct stat64 *buf) {
  xprintf(" xtreemfs_stat64(%s)\n", pathname);
  return xtreemfs_stat_impl(pathname, buf);
}

int xtreemfs_fstat(int fd, struct stat *buf) {
  xprintf(" xtreemfs_fstat(%d)\n", fd);
  return xtreemfs_fstat_impl(fd, buf);
}

int xtreemfs_fstat64(int fd, struct stat64 *buf) {
  xprintf(" xtreemfs_fstat64(%d)\n", fd);
  return xtreemfs_fstat_impl(fd, buf);
}

int xtreemfs_setxattr(const char *pathname, const char *name, const void *value, size_t size, int flags) {
  Path path(pathname);
  path.Parse();

  try {
    env->GetVolume()->SetXAttr(env->user_creds_, path.GetXtreemFSPath(), std::string(name),
        std::string(static_cast<const char*>(value), size), static_cast<xtreemfs::pbrpc::XATTR_FLAGS>(flags));
  } catch(const xtreemfs::PosixErrorException& e) {
    errno = ConvertXtreemFSErrnoToUnix(e.posix_errno());
    return -1;
  } catch(const xtreemfs::XtreemFSException& e) {
    errno = EIO;
    return -1;
  } catch(const std::exception& e) {
    xprintf("A non-XtreemFS exception occurred: %s", std::string(e.what()).c_str());
    errno = EIO;
    return -1;
  }
  return 0;
}

int xtreemfs_fsetxattr(int fd, const char *name, const void *value, size_t size, int flags) {
//  OpenFile handle = env->open_file_table_.Get(fd);
//  env->GetVolume()->SetXAttr(env->user_creds_, path.GetXtreemFSPath(), name, value, flags);
//
//  handle.fh_->SetX
  return 0;
}

max_stars_repo_name: harnesscloud/xtreemfs

max_issues_repo_name: harnesscloud/xtreemfs

max_forks_repo_name: harnesscloud/xtreemfs


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

#include <omo/app/application.hpp>

#include <boost/program_options.hpp>
#include <fc/io/json.hpp>

namespace omo { namespace app {

class abstract_plugin
{
   public:
      virtual ~abstract_plugin(){}
      virtual std::string plugin_name()const = 0;

      /**
       * @brief Perform early startup routines and register plugin indexes, callbacks, etc.
       *
       * Plugins MUST supply a method initialize() which will be called early in the application startup. This method
       * should contain early setup code such as initializing variables, adding indexes to the database, registering
       * callback methods from the database, adding APIs, etc., as well as applying any options in the @ref options map
       *
       * This method is called BEFORE the database is open, therefore any routines which require any chain state MUST
       * NOT be called by this method. These routines should be performed in startup() instead.
       *
       * @param options The options passed to the application, via configuration files or command line
       */
      virtual void plugin_initialize( const boost::program_options::variables_map& options ) = 0;

      /**
       * @brief Begin normal runtime operations
       *
       * Plugins MUST supply a method startup() which will be called at the end of application startup. This method
       * should contain code which schedules any tasks, or requires chain state.
       */
      virtual void plugin_startup() = 0;

      /**
       * @brief Cleanly shut down the plugin.
       *
       * This is called to request a clean shutdown (e.g. due to SIGINT or SIGTERM).
       */
      virtual void plugin_shutdown() = 0;

      /**
       * @brief Register the application instance with the plugin.
       *
       * This is called by the framework to set the application.
       */
      virtual void plugin_set_app( application* a ) = 0;

      /**
       * @brief Fill in command line parameters used by the plugin.
       *
       * @param command_line_options All options this plugin supports taking on the command-line
       * @param config_file_options All options this plugin supports storing in a configuration file
       *
       * This method populates its arguments with any
       * command-line and configuration file options the plugin supports.
       * If a plugin does not need these options, it
       * may simply provide an empty implementation of this method.
       */
      virtual void plugin_set_program_options(
         boost::program_options::options_description& command_line_options,
         boost::program_options::options_description& config_file_options
         ) = 0;
};

/**
 * Provides basic default implementations of abstract_plugin functions.
 */

class plugin : public abstract_plugin
{
   public:
      plugin();
      virtual ~plugin() override;

      virtual std::string plugin_name()const override;
      virtual void plugin_initialize( const boost::program_options::variables_map& options ) override;
      virtual void plugin_startup() override;
      virtual void plugin_shutdown() override;
      virtual void plugin_set_app( application* app ) override;
      virtual void plugin_set_program_options(
         boost::program_options::options_description& command_line_options,
         boost::program_options::options_description& config_file_options
         ) override;

      chain::database& database() { return *app().chain_database(); }
      application& app()const { assert(_app); return *_app; }
   protected:
      net::node& p2p_node() { return *app().p2p_node(); }

   private:
      application* _app = nullptr;
};

/// @group Some useful tools for boost::program_options arguments using vectors of JSON strings
/// @{
template<typename T>
T dejsonify(const string& s)
{
   return fc::json::from_string(s).as<T>();
}

#define DEFAULT_VALUE_VECTOR(value) default_value({fc::json::to_string(value)}, fc::json::to_string(value))
#define LOAD_VALUE_SET(options, name, container, type) \
if( options.count(name) ) { \
      const std::vector<std::string>& ops = options[name].as<std::vector<std::string>>(); \
      std::transform(ops.begin(), ops.end(), std::inserter(container, container.end()), &omo::app::dejsonify<type>); \
}
/// @}

} } //omo::app


text:
/*! \file Renderer.cpp
 *  \author Jared Hoberock
 *  \brief Implementation of Renderer class.
 */

#include "Renderer.h"
#include <boost/date_time/posix_time/posix_time.hpp>
#include "../primitives/Scene.h"
#include <iostream>
#include "../records/RenderFilm.h"

using namespace boost;

// XXX this is so friggin ugly
std::ostream &silence(std::ostream &os)
{
  os.setstate(std::ios_base::badbit);
  return os;
} // end silence()

Renderer::ProgressCallback
  ::ProgressCallback(void)
    :Parent(ULONG_MAX, silence(std::cout))
{
  // XXX this hacks around boost::progress_display's
  //     insistence on outputting as soon as it's
  //     constructed

  // this line turns the os back on
  std::cout.clear(std::ios_base::goodbit);
} // end ProgressCallback::ProgressCallback()

void Renderer::ProgressCallback
  ::restart(unsigned long expected_count)
{
  if(expected_count != ULONG_MAX)
  {
    Parent::restart(expected_count);
  } // end
} // end ProgressCallback::restart()

void Renderer
  ::render(ProgressCallback &progress)
{
  preprocess();
  kernel(progress);
  postprocess();
} // end Renderer::render()

void Renderer
  ::preprocess(void)
{
  // preprocess the shading context
  mShadingContext->preprocess();

  // preprocess the scene
  // XXX now the design is broken
  //     should we assume a Renderer
  //     has non-const access to a Scene?
  //     does this make sense?
  //     can a Renderer change its Scene?
  //     if my beliefs determine my actions, and
  //     i can't choose my beliefs, do i have
  //     free will?
  const_cast<Scene*>(mScene.get())->preprocess();

  // preprocess the record
  mRecord->preprocess();

  // start the timer
  mTimer.restart();
} // end Renderer::preprocess()

void Renderer
  ::postprocess(void)
{
  // stop the timer
  double elapsed = mTimer.elapsed();

  postRenderReport(elapsed);
  mShadingContext->postprocess();

  mRecord->postprocess();
} // end Renderer::postprocess()

void Renderer
  ::postRenderReport(const double elapsed) const
{
  std::cout << "Finished." << std::endl;

  unsigned long minutes = static_cast<unsigned long>(elapsed) % 60;
  unsigned long hours = static_cast<unsigned long>(minutes) % (60*60);
  unsigned long seconds = static_cast<unsigned long>(elapsed) - hours*60*60 - minutes*60;

  boost::posix_time::time_duration td(hours,minutes,seconds);
  std::cout << "Seconds elapsed: " << elapsed << std::endl;
  //std::cout << "Time elapsed: " << td << std::endl;
  std::cout << "Rays cast: " << mScene->getRaysCast() << std::endl;
  std::cout << "Shadow rays cast: " << mScene->getShadowRaysCast() << std::endl;
  std::cout << "Blocked shadow rays: " << mScene->getBlockedShadowRays() << std::endl;
  std::cout << "Shadow rate: " << static_cast<float>(mScene->getBlockedShadowRays()) / static_cast<float>(mScene->getShadowRaysCast()) << std::endl;
  std::cout << "Rays per second: " << static_cast<double>(mScene->getRaysCast()) / elapsed << std::endl;
} // end Renderer::postRenderReport()

std::string Renderer
  ::getRenderParameters(void) const
{
  return std::string("");
} // end Renderer::getRenderParameters()

max_stars_repo_name: jaredhoberock/gotham

max_issues_repo_name: jaredhoberock/gotham

max_forks_repo_name: jaredhoberock/gotham


text:
/**
 * $Id$
 *
 * Copyright (C)
 * 2015 - $Date$
 *     Martin Wolf <ndhist@martin-wolf.org>
 *
 * This file is distributed under the BSD 2-Clause Open Source License
 * (See LICENSE file).
 *
 */
#ifndef NDHIST_DETAIL_UTILS_HPP_INCLUDED
#define NDHIST_DETAIL_UTILS_HPP_INCLUDED 1

#include <sstream>

#include <boost/python.hpp>

#include <ndhist/error.hpp>

namespace ndhist {
namespace detail {

namespace py {

// inline
// bool
// are_same_type_objects(bp::object const & obj1, bp::object const & obj2)
// {
//     bp::object obj2_type(bp::handle<>(bp::borrowed(bp::downcast<PyTypeObject>(PyObject_Type(obj2.ptr())))));
//     return PyObject_TypeCheck(obj1.ptr(), (PyTypeObject*)obj2_type.ptr());
// }

inline
bool
is_object_of_type(
    bp::object const & obj
  , PyTypeObject & type_obj0
)
{
    if(PyObject_TypeCheck(obj.ptr(), &type_obj0))
    {
        return true;
    }
    return false;
}

inline
bool
is_object_of_type(
    bp::object const & obj
  , PyTypeObject & type_obj0
  , PyTypeObject & type_obj1
)
{
    if(   PyObject_TypeCheck(obj.ptr(), &type_obj0)
       || PyObject_TypeCheck(obj.ptr(), &type_obj1)
      )
    {
        return true;
    }
    return false;
}

inline
bool
is_object_of_type(
    bp::object const & obj
  , PyTypeObject & type_obj0
  , PyTypeObject & type_obj1
  , PyTypeObject & type_obj2
)
{
    if(   PyObject_TypeCheck(obj.ptr(), &type_obj0)
       || PyObject_TypeCheck(obj.ptr(), &type_obj1)
       || PyObject_TypeCheck(obj.ptr(), &type_obj2)
      )
    {
        return true;
    }
    return false;
}

}// namespace py

/**
 * @brief Adjust the axis index to the correct axis index. The axis index
 *     can be negative, which means, the index is counted from the back.
 *     The returned axis index lies in the interval [0, nd). On error, an
 *     IndexError is thrown.
 */
inline
intptr_t
adjust_axis_index(intptr_t const nd, intptr_t axis)
{
    if(axis < 0) {
        axis += nd;
    }
    if(axis < 0)
    {
        std::stringstream ss;
        ss << "The axis value \""<< axis <<"\" specifies an axis < 0!";
        throw IndexError(ss.str());
    }
    else if(axis >= nd)
    {
        std::stringstream ss;
        ss << "The axis value \""<< axis <<"\" must be smaller than the "
           << "dimensionality of the histogram, i.e. smaller than "
           << nd <<"!";
        throw IndexError(ss.str());
    }
    return axis;
}

}// namespace detail
}// namespace ndhist

#endif // NDHIST_DETAIL_UTILS_HPP_INCLUDED

max_stars_repo_name: martwo/ndhist

max_issues_repo_name: martwo/ndhist

max_forks_repo_name: martwo/ndhist


text:
//  boost/endian/endian.hpp  -----------------------------------------------------------//

//  Copyright Beman Dawes 2015

//  Distributed under the Boost Software License, Version 1.0.
//  See http://www.boost.org/LICENSE_1_0.txt

//  See library home page at http://www.boost.org/libs/endian

#ifndef BOOST_ENDIAN_ENDIAN_HPP
#define BOOST_ENDIAN_ENDIAN_HPP

#ifndef BOOST_ENDIAN_DEPRECATED_NAMES
# error "<boost/endian/endian.hpp> is deprecated. Define BOOST_ENDIAN_DEPRECATED_NAMES to use."
#endif

#include <boost/endian/arithmetic.hpp>

#endif  //BOOST_ENDIAN_ENDIAN_HPP

max_stars_repo_name: rudylee/expo

max_issues_repo_name: rudylee/expo

max_forks_repo_name: rudylee/expo


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

#include <iostream>
#include <fstream>
#include "global_hv.h"
#include <boost/timer/timer.hpp>
#include "../../eval_tool/eval_helpers_detection.h"

/**
 * Evaluation pipeline for the approach described in
 *
 * A. Aldoma, F. Tombari, L. Di Stefano, M. Vincze:
 *     A global hypothesis verification method for 3D object recognition.
 *     2012, ECCV
 *
 * There is also a tutorial for this approach in
 *
 * A. Aldoma, Z.C. Marton, F. Tombari, W. Wohlkinger, C. Potthast, B. Zeisl, R.B. Rusu, S. Gedikli, M. Vincze:
 *      Point Cloud Library: Three-Dimensional Object Recognition and 6 DOF Pose Estimation
 *      2012, IEEE Robotics and Automation Magazine
 *
 * Also see:
 *      https://pcl.readthedocs.io/en/latest/correspondence_grouping.html
 *      https://pcl.readthedocs.io/en/latest/global_hypothesis_verification.html
 */

int main (int argc, char** argv)
{
    if(argc != 6)
    {
        std::cout << std::endl << "Usage:" << std::endl << std::endl;
        std::cout << argv[0] << " [object file] [scene description file]" << std::endl << std::endl;
        std::cout << "Example:" << std::endl << std::endl;
        std::cout << argv[0] << " object_files.txt scene_001.txt" << std::endl << std::endl;
        std::cout << "The object file must contain a filename " << std::endl;
        std::cout << "and class label per line, separated by a space." << std::endl;
        std::cout << "The pcd files from the object file will be search for and localized" << std::endl;
        std::cout << "in the scene file contained in the scene description." << std::endl;
        std::cout << "The scene description file contains the name of a scene pcd " << std::endl;
        std::cout << "and locations and class labels of objects in that scene." << std::endl;
        exit(1);
    }

    // input data
    std::string dataset = argv[1];
    std::string model = argv[2];
    float bin = atof(argv[3]);
    float th = atof(argv[4]);
    int count = atoi(argv[5]);

    // parse input
    std::vector<std::string> filenames;
    std::vector<std::string> gt_filenames;
    std::vector<unsigned> class_labels;
    std::vector<unsigned> instance_labels;
    std::string mode;

    // find dataset name from input file
    std::string datasetname;
    int pos1 = dataset.find_first_of('_');
    std::string str1 = dataset.substr(0, pos1);
    int pos2 = dataset.substr(pos1+1).find_first_of('_');
    std::string str2 = dataset.substr(pos1+1, pos2);

    if(str1 == "train" || str1 == "test" || str1 == "training" || str1 == "testing")
    {
        datasetname = str2;
    }
    else
    {
        datasetname = str1;
    }

    std::shared_ptr<GlobalHV> global_hv(new GlobalHV(datasetname, bin, th, count));

    // workaround to set "mode"
    {
        std::ifstream infile(dataset);
        std::string file;
        std::string class_label;
        // special treatment of first line: determine mode
        infile >> file;         // in the first line: #
        infile >> class_label;  // in the first line: the mode ("train" or "test")
        if(file == "#" && (class_label == "train" || class_label == "test"))
        {
            mode = class_label;
        }
    }

    if(mode == "train")
    {
        label_usage = parseFileListDetectionTrain(dataset, filenames, class_labels, instance_labels, "train");

        // if both, class and instance labels given, use instances
        // usually, this leads to better accuracy
        if(label_usage == LabelUsage::BOTH_GIVEN)
        {
            label_usage = LabelUsage::INSTANCE_PRIMARY;
        }

        if(label_usage == LabelUsage::CLASS_ONLY)
        {
            // instance ids must be filled even if training with class labels only
            instance_labels = class_labels;
        }
        else if(label_usage == LabelUsage::INSTANCE_PRIMARY)
        {
            // use instance labels for classes
            class_labels = instance_labels;
        }

        std::cout << "Started training!" << std::endl;
        global_hv->setLabels(class_labels_rmap, instance_labels_rmap, instance_to_class_map);
        global_hv->train(filenames, class_labels, instance_labels, model);
    }
    else if(mode == "test")
    {
        boost::timer::cpu_timer timer;
        std::cout << "Started testing!" << std::endl;

        parseFileListDetectionTest(dataset, filenames, gt_filenames);

        if(global_hv->loadModel(model))
        {
            class_labels_rmap = global_hv->getClassLabels();
            instance_labels_rmap = global_hv->getInstanceLabels();
            instance_to_class_map = global_hv->getInstanceClassMap();
            // populate maps with loaded data
            for(auto &elem : class_labels_rmap)
            {
                class_labels_map.insert({elem.second, elem.first});
            }
            for(auto &elem : instance_labels_rmap)
            {
                instance_labels_map.insert({elem.second, elem.first});
            }

            // determine label_usage: empty mapping means that no instance labels were given
            if(instance_to_class_map.size() == 0)
            {
                label_usage = LabelUsage::CLASS_ONLY;
                // instance ids must be filled even if testing with class labels only
                instance_labels = class_labels;
            }
            else
            {
                // determine label_usage: compare all instance and class labels
                bool all_equal = true;
                for(auto elem : class_labels_rmap)
                {
                    std::string label1 = elem.second;
                    std::string label2 = instance_labels_rmap[elem.first];
                    if(label1 != label2)
                    {
                        all_equal = false;
                        break;
                    }
                }

                if(all_equal)
                {
                    // instances used as primary labels, classes determined over mapping
                    label_usage = LabelUsage::INSTANCE_PRIMARY;
                }
                else
                {
                    std::cerr << "Mismatch in instance label usage!" << std::endl;
                    return 1;
                }
            }

            std::vector<DetectionObject> gt_objects;
            std::vector<DetectionObject> detected_objects;

            std::string outputname = model.substr(0, model.find_last_of('.')) + ".txt";
            std::ofstream summaryFile("output_aldoma_"+std::to_string(bin)+"_"+std::to_string(th)+"_"+std::to_string(count)+"_"+outputname);

            for(unsigned i = 0; i < filenames.size(); i++)
            {
                // detect
                std::string pointCloud = filenames.at(i);
                std::string gt_file = gt_filenames.at(i);
                std::vector<ism3d::VotingMaximum> maxima;

                std::cout << "Processing file " << pointCloud << std::endl;

                bool use_global_hv = true; // true --> aldoma global hv (default), false --> no global hv
                bool use_hough = (count % 2 == 0); //false; // false --> use chen (default), true --> use tombari to generate hypotheses
                maxima = global_hv->detect(pointCloud, use_hough, use_global_hv);

                // collect all gt objects
                std::vector<DetectionObject> gt_objects_from_file = parseGtFile(gt_file);
                gt_objects.insert(gt_objects.end(), gt_objects_from_file.begin(), gt_objects_from_file.end());
                // collect all detections
                for (int i = 0; i < (int)maxima.size(); i++)
                {
                    DetectionObject detected_obj = convertMaxToObj(maxima[i], gt_file);
                    detected_objects.push_back(std::move(detected_obj));
                }
            }

            // maps a class label id to list of objects
            std::map<std::string, std::vector<DetectionObject>> gt_class_map;
            std::map<std::string, std::vector<DetectionObject>> det_class_map;

            rearrangeObjects(gt_objects, gt_class_map);
            rearrangeObjects(detected_objects, det_class_map);

            // max. allowed distance to ground truth position to count the detection as correct
            // TODO VS depends on dataset/cloud resolution --> make param?
            float dist_threshold = 0.05;

            // collect all metrics
            // combined detection - primary metrics
            std::vector<float> ap_per_class(gt_class_map.size(), 0.0);
            std::vector<float> precision_per_class(gt_class_map.size(), 0.0);
            std::vector<float> recall_per_class(gt_class_map.size(), 0.0);

            summaryFile << "  class       num gt   tp    fp   precision  recall   AP";
            summaryFile << std::endl;

            // these variables sum over the whole dataset
            int num_gt_dataset = 0;
            int cumul_tp_dataset = 0;
            int cumul_fp_dataset = 0;

            for(auto item : gt_class_map)
            {
                std::string class_label = item.first;
                unsigned class_id = class_labels_map[class_label];
                std::vector<DetectionObject> class_objects_gt = item.second;
                // these variables sum over each class
                int num_gt = int(class_objects_gt.size());
                int cumul_tp = 0;
                int cumul_fp = 0;

                // if there are no detections for this class
                if(det_class_map.find(class_label) == det_class_map.end())
                {
                    ap_per_class[class_id] = 0;
                    precision_per_class[class_id] = 0;
                    recall_per_class[class_id] = 0;
                }
                else
                {
                    std::vector<DetectionObject> class_objects_det = det_class_map.at(class_label);

                    float precision, recall, ap;
                    std::tie(precision, recall, ap, cumul_tp, cumul_fp, std::ignore, std::ignore) = computeMetrics(class_objects_gt,
                                                                                class_objects_det,
                                                                                dist_threshold);
                    precision_per_class[class_id] = precision;
                    recall_per_class[class_id] = recall;
                    ap_per_class[class_id] = ap;
                }

                // log class to summary
                float ap = ap_per_class[class_id];
                float precision = precision_per_class[class_id];
                float recall = recall_per_class[class_id];

                summaryFile << std::setw(3) << std::right << class_id << " "
                            << std::setw(13) << std::left << class_label
                            << std::setw(3) << std::right << num_gt
                            << std::setw(5) << cumul_tp
                            << std::setw(6) << cumul_fp << "   "
                            << std::setw(11) << std::left << std::round(precision*10000.0f)/10000.0f
                            << std::setw(9) << std::round(recall*10000.0f)/10000.0f
                            << std::setw(10) << std::round(ap*10000.0f)/10000.0f;
                summaryFile << std::endl;

                // accumulate values of complete dataset
                num_gt_dataset += num_gt;
                cumul_tp_dataset += cumul_tp;
                cumul_fp_dataset += cumul_fp;
            }

            // store sums
            summaryFile << "-------------------------------------------------------------" << std::endl;
            summaryFile << "Sums:" << std::setw(15) << std::right << num_gt_dataset
                        << std::setw(5) << std::right << cumul_tp_dataset
                        << std::setw(6) << std::right << cumul_fp_dataset << std::endl;

            // compute average metrics
            float mAP = 0;
            float mPrec = 0;
            float mRec = 0;
            for(int idx = 0; idx < ap_per_class.size(); idx++)
            {
                mAP += ap_per_class[idx];
                mPrec += precision_per_class[idx];
                mRec += recall_per_class[idx];
            }
            mAP /= ap_per_class.size();
            mPrec /= ap_per_class.size();
            mRec /= ap_per_class.size();
            float fscore = 2*mPrec*mRec / (mPrec+mRec);
            summaryFile << std::endl << std::endl;
            summaryFile << "main metrics:" << std::endl;
            summaryFile << "       mAP:            " << std::setw(7) << std::round(mAP*10000.0f)/10000.0f    << " (" << std::round(mAP*10000.0f)/100.0f   << " %)" << std::endl;
            summaryFile << "       mean precision: " << std::setw(7) << std::round(mPrec*10000.0f)/10000.0f  << " (" << std::round(mPrec*10000.0f)/100.0f << " %)" << std::endl;
            summaryFile << "       mean recall:    " << std::setw(7) << std::round(mRec*10000.0f)/10000.0f   << " (" << std::round(mRec*10000.0f)/100.0f  << " %)" << std::endl;
            summaryFile << "       f-score:        " << std::setw(7) << std::round(fscore*10000.0f)/10000.0f << " (" << std::round(fscore*10000.0f)/100.0f<< " %)" << std::endl << std::endl;

            // complete and close summary file
            summaryFile << "total processing time: " << timer.format(4, "%w") << " seconds \n";
            summaryFile.close();
        }
        else
        {
            std::cerr << "ERROR: could not load model from file " << model << "!" << std::endl;
        }
    }
    else
    {
        std::cerr << "ERROR: wrong mode specified: " << mode << "! Must be train or test!" << std::endl;
    }

    return (0);
}

max_stars_repo_name: Pandinosaurus/PointCloudDonkey

max_issues_repo_name: Pandinosaurus/PointCloudDonkey

max_forks_repo_name: Pandinosaurus/PointCloudDonkey


text:
/**************************************************************
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 *************************************************************/

#ifndef INCLUDED_CANVAS_ISURFACEPROXYMANAGER_HXX
#define INCLUDED_CANVAS_ISURFACEPROXYMANAGER_HXX

#include <canvas/rendering/irendermodule.hxx>
#include <canvas/rendering/icolorbuffer.hxx>

#include <boost/shared_ptr.hpp>

#include <canvas/canvastoolsdllapi.h>

namespace canvas
{
    struct ISurfaceProxy;

    /** Manager interface, which handles surface proxy objects.

        Typically, each canvas instantiation has one
        SurfaceProxyManager object, to handle their surfaces. Surfaces
        itself are opaque objects, which encapsulate a framebuffer to
        render upon, plus an optional (possibly accelerated) texture.
     */
    struct ISurfaceProxyManager
    {
        virtual ~ISurfaceProxyManager() {}

        /** Create a surface proxy for a color buffer.

            The whole idea is build around the concept that you create
            some arbitrary buffer which contains the image data and
            tell the texture manager about it.  From there on you can
            draw into this image using any kind of graphics api you
            want.  In the technical sense we allocate some space in
            local videomemory or AGP memory which will be filled on
            demand, which means if there exists any rendering
            operation that needs to read from this memory location.
            This method creates a logical hardware surface object
            which uses the given color buffer as the image source.
            Internally this texture may even be distributed to several
            real hardware surfaces.
        */
        virtual ::boost::shared_ptr< ISurfaceProxy > createSurfaceProxy(
            const IColorBufferSharedPtr& pBuffer ) const = 0;
    };

    typedef ::boost::shared_ptr< ISurfaceProxyManager > ISurfaceProxyManagerSharedPtr;

    /** Create a surface proxy for the given render module.
     */
	CANVASTOOLS_DLLPUBLIC ISurfaceProxyManagerSharedPtr createSurfaceProxyManager( const IRenderModuleSharedPtr& rRenderModule );
}

#endif /* INCLUDED_CANVAS_ISURFACEPROXYMANAGER_HXX */

ext: hxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice


text: #include <boost/fusion/iterator/key_of.hpp>


text:
//
// SPDX-License-Identifier: MIT
// Copyright (c) 2016-2020 Michael Purcaro, Henry Pratt, Jill Moore, Zhiping Weng
//

#include <vector>
#include <fstream>
#include <iterator>
#include <string>
#include <cmath>
#include <numeric>
#include <unordered_map>

#include <boost/filesystem.hpp>

#include "zentLib/src/BigWigWrapper.hpp"
#include "cpp/files.hpp"
#include "cpp/string_utils.hpp"

#include "utils.hpp"
#include "lambda.hpp"
#include "region.hpp"
#include "zscore.hpp"

namespace SCREEN {

  float log10orNeg10(float x) {
    // TODO: floating point tolerance?
    // http://realtimecollisiondetection.net/blog/?p=89
    if (0.0 == x){
      return -10.0;
    }
    return std::log10(x + 0.01);
  }

} // SCREEN

max_stars_repo_name: weng-lab/SCREEN

max_issues_repo_name: weng-lab/SCREEN

max_forks_repo_name: weng-lab/SCREEN


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

#include <boost/format.hpp>

#include "EALog.h"
#include "SystemStatusTracker.hpp"
#include "CBCEvent.hpp"

// Tag for SystemStatusTracker.
#define TAG "SST"

namespace earlyapp
{
    /*
      Initialize the device controller.
     */
    void SystemStatusTracker::init(void)
    {
        m_SysState = eSTATE_INIT;
    }

    /*
      Has gear status changed?
      This will return false once return true.
     */
    bool SystemStatusTracker::isStatusChanged(void)
    {
        if(m_statusChanged)
        {
            m_statusChanged = false;
            return true;
        }
        return false;
    }

    /*
      CBC event handler.
     */
    bool SystemStatusTracker::handleCBCEvent(std::shared_ptr<CBCEvent> pEv)
    {
        if(pEv == nullptr || ! pEv->isValid())
        {
            LWRN_(TAG, "Invalid event");
            return false;
        }

        // State transition.
        if((m_statusChanged = updateState(pEv)))
        {
            return true;
        }

        return false;
    }

    /*
      Application exit requested.
     */
    bool SystemStatusTracker::isExitRequested(void)
    {
        return m_exitReq;
    }

    /*
      currentState
      Returns current state.
     */
    SystemStatusTracker::eSystemState SystemStatusTracker::currentState(void)
    {
        eSystemState curSt;

        // Critical section (read)
        m_StateMtx.lock();
        curSt = m_SysState;
        m_StateMtx.unlock();

        return curSt;
    }

    /*
      updateState
      - True: Transition made.
      - False: Fail to transit.
     */
    bool SystemStatusTracker::updateState(std::shared_ptr<CBCEvent> pEv)
    {
        if(pEv == nullptr)
            return false;

        return updateState(pEv->toEnum());
    }

    /*
      TestCase: State transitions.

      State transition table.

      Current state | signal  | next state
      --------------+---------+------------
      INIT          | REVERSE | BOOTRVC
      INIT          | FORWARD | BOOTVIDEO
      BOOTRVC       | FORWARD | IDLE
      BOOTVIDEO     | REVERSE | RVC
      IDLE          | REVERSE | RVC
      RVC           | FORWARD | IDLE

               +---------------F-------------->+
               |                               |
        +------+-+   R     +-------+    F    +----+
     -->|  INIT  +-------> |BOOTRVC| ------> |IDLE+---+
        +--------+         +-------+     +-> +----+   |
                 |                      F|            |R
                 |   F    +---------+    +---+----+   |
                 +------->|BOOTVIDEO|   R    |RVC |<--+
                          +---------+------->+----+

      *) Signal eEXIT from all states will make transition to EXIT state.
      **) Unspecified signals will be ignored.
    */
    bool SystemStatusTracker::updateState(CBCEvent::eCBCEvent e)
    {
        eSystemState prvState = m_SysState;
        eSystemState nextState = m_SysState;

        LINF_(TAG, boost::str(
                  boost::format("Current state: %s(%d), signal: %s(%d)")
                  % stateToString() % m_SysState
                  % CBCEvent::toString(e) % e));

        switch(m_SysState)
        {
        case eSTATE_INIT:
            // REVERSE gear signal.
            if(e == CBCEvent::eGEARSTATUS_REVERSE)
            {
                nextState = eSTATE_BOOTRVC;
            }
            // FOWARD gear signal.
            else if(e == CBCEvent::eGEARSTATUS_FORWARD)
            {
                nextState = eSTATE_BOOTVIDEO;
            }
            // EXIT
            else if(e == CBCEvent::eAPPLICATION_EXIT)
            {
                nextState = eSTATE_EXIT;
            }
            break;

        case eSTATE_BOOTRVC:
            // FOWARD gear signal.
            if(e == CBCEvent::eGEARSTATUS_FORWARD)
            {
                nextState = eSTATE_IDLE;
            }
            // EXIT
            else if(e == CBCEvent::eAPPLICATION_EXIT)
            {
                nextState = eSTATE_EXIT;
            }
            break;

        case eSTATE_BOOTVIDEO:
            // REVERSE gear signal.
            if(e == CBCEvent::eGEARSTATUS_REVERSE)
            {
                nextState = eSTATE_RVC;
            }
            // EXIT
            else if(e == CBCEvent::eAPPLICATION_EXIT)
            {
                nextState = eSTATE_EXIT;
            }
            break;

        case eSTATE_IDLE:
            // REVERSE gear signal.
            if(e == CBCEvent::eGEARSTATUS_REVERSE)
            {
                nextState = eSTATE_RVC;
            }
            // EXIT
            else if(e == CBCEvent::eAPPLICATION_EXIT)
            {
                nextState = eSTATE_EXIT;
            }
            break;

        case eSTATE_RVC:
            // FORWARD gear signal.
            if(e == CBCEvent::eGEARSTATUS_FORWARD)
            {
                nextState = eSTATE_IDLE;
            }
            // EXIT
            else if(e == CBCEvent::eAPPLICATION_EXIT)
            {
                nextState = eSTATE_EXIT;
            }
            break;

        default:
            // Exit from all states.
            if(e == CBCEvent::eAPPLICATION_EXIT)
            {
                nextState = eSTATE_EXIT;
            }
            break;
        }

        // Update device state if state has changed
        if(prvState != nextState)
        {
            // Critical section(update)
            m_StateMtx.lock();
            m_SysState = nextState;
            m_StateMtx.unlock();

            LINF_(TAG, boost::str(
                      boost::format("State changed from %s(%d) -> %s(%d)")
                      % stateToString(prvState) % prvState
                      % stateToString(nextState) % nextState));

            // Application exit control.
            if(nextState == eSTATE_EXIT)
            {
                LINF_(TAG, "Application exit requested.");
                m_exitReq = true;
            }

            return true;
        }
        else
        {
            LWRN_(TAG,
                  boost::str(
                      boost::format("State won't be changed from %s(%d).")
                      % stateToString(prvState) % prvState));

            return false;
        }
    }

    /*
      stateToString
     */
    std::string SystemStatusTracker::stateToString(void)
    {
        return stateToString(m_SysState);
    }

    /*
      stateToString
     */
    std::string SystemStatusTracker::stateToString(eSystemState st)
    {
        const std::vector<const char*> strT =
        {
            "UNKNOWN",
            "INIT",
            "BOOTRVC",
            "BOOTVIDEO",
            "IDLE",
            "RVC",
            "EXIT",
            "UNDEFINED"
        };

        int idx = static_cast<int>(st);
        if(st < eSTATE_MIN || st > eSTATE_MAX)
        {
            idx = (int)strT.size() - 1;
        }

        const std::string r = std::string(strT[idx]);
        return r;
    }

} // namespace

max_stars_repo_name: nayanavenkataramana/earlyapp

max_issues_repo_name: nayanavenkataramana/earlyapp

max_forks_repo_name: nayanavenkataramana/earlyapp


text:
#ifdef USE_UPNP
#include <string>
#include <thread>

#include <boost/thread/thread.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>

#include "Log.h"

#include "RouterContext.h"
#include "UPnP.h"
#include "NetDb.h"
#include "util.h"
#include "RouterInfo.h"
#include "Config.h"

#include <miniupnpc/miniupnpc.h>
#include <miniupnpc/upnpcommands.h>

namespace i2p
{
namespace transport
{
    UPnP::UPnP () : m_IsRunning(false), m_Thread (nullptr), m_Timer (m_Service)
    {
    }

    void UPnP::Stop ()
    {
		if (m_IsRunning)
		{
		    LogPrint(eLogInfo, "UPnP: stopping");
			m_IsRunning = false;
			m_Timer.cancel ();
			m_Service.stop ();
		    if (m_Thread)
		    {
		        m_Thread->join ();
		        m_Thread.reset (nullptr);
		    }
			CloseMapping ();
		    Close ();
		}
    }

    void UPnP::Start()
    {
		m_IsRunning = true;
        LogPrint(eLogInfo, "UPnP: starting");
		m_Service.post (std::bind (&UPnP::Discover, this));
		std::unique_lock<std::mutex> l(m_StartedMutex);
        m_Thread.reset (new std::thread (std::bind (&UPnP::Run, this)));
		m_Started.wait_for (l, std::chrono::seconds (5)); // 5 seconds maximum
    }

    UPnP::~UPnP ()
    {
		Stop ();
    }

    void UPnP::Run ()
    {
		while (m_IsRunning)
		{
			try
			{
				m_Service.run ();
			}
			catch (std::exception& ex)
			{
				LogPrint (eLogError, "UPnP: runtime exception: ", ex.what ());
			}
		}
    }

    void UPnP::Discover ()
    {
        int nerror = 0;
#if MINIUPNPC_API_VERSION >= 14
        m_Devlist = upnpDiscover (2000, m_MulticastIf, m_Minissdpdpath, 0, 0, 2, &nerror);
#else
        m_Devlist = upnpDiscover (2000, m_MulticastIf, m_Minissdpdpath, 0, 0, &nerror);
#endif
		{
			// notify satrting thread
			std::unique_lock<std::mutex> l(m_StartedMutex);
			m_Started.notify_all ();
		}

        int r;
        r = UPNP_GetValidIGD (m_Devlist, &m_upnpUrls, &m_upnpData, m_NetworkAddr, sizeof (m_NetworkAddr));
        if (r == 1)
        {
            r = UPNP_GetExternalIPAddress (m_upnpUrls.controlURL, m_upnpData.first.servicetype, m_externalIPAddress);
            if(r != UPNPCOMMAND_SUCCESS)
            {
                LogPrint (eLogError, "UPnP: UPNP_GetExternalIPAddress() returned ", r);
                return;
            }
            else
            {
                if (!m_externalIPAddress[0])
                {
                    LogPrint (eLogError, "UPnP: GetExternalIPAddress() failed.");
                    return;
                }
            }
        }
		else
		{
			 LogPrint (eLogError, "UPnP: GetValidIGD() failed.");
             return;
		}

		// UPnP discovered
		LogPrint (eLogDebug, "UPnP: ExternalIPAddress is ", m_externalIPAddress);
        i2p::context.UpdateAddress (boost::asio::ip::address::from_string (m_externalIPAddress));
		// port mapping
		PortMapping ();
    }

	void UPnP::PortMapping ()
	{
		const auto& a = context.GetRouterInfo().GetAddresses();
		for (const auto& address : a)
        {
            if (!address->host.is_v6 ())
            	TryPortMapping (address);
        }
		m_Timer.expires_from_now (boost::posix_time::minutes(20));	// every 20 minutes
		m_Timer.async_wait ([this](const boost::system::error_code& ecode)
			{
				if (ecode != boost::asio::error::operation_aborted)
					PortMapping ();
			});

	}

	void UPnP::CloseMapping ()
	{
		const auto& a = context.GetRouterInfo().GetAddresses();
		for (const auto& address : a)
        {
            if (!address->host.is_v6 ())
            	CloseMapping (address);
        }
	}

    void UPnP::TryPortMapping (std::shared_ptr<i2p::data::RouterInfo::Address> address)
    {
        std::string strType (GetProto (address)), strPort (std::to_string (address->port));
        int r;
        std::string strDesc; i2p::config::GetOption("upnp.name", strDesc);
        r = UPNP_AddPortMapping (m_upnpUrls.controlURL, m_upnpData.first.servicetype, strPort.c_str (), strPort.c_str (), m_NetworkAddr, strDesc.c_str (), strType.c_str (), 0, "0");
        if (r!=UPNPCOMMAND_SUCCESS)
        {
            LogPrint (eLogError, "UPnP: AddPortMapping (", m_NetworkAddr, ":", strPort, ") failed with code ", r);
            return;
        }
        else
        {
            LogPrint (eLogDebug, "UPnP: Port Mapping successful. (", m_NetworkAddr ,":", strPort, " type ", strType, " -> ", m_externalIPAddress ,":", strPort ,")");
            return;
        }
    }

    void UPnP::CloseMapping (std::shared_ptr<i2p::data::RouterInfo::Address> address)
    {
        std::string strType (GetProto (address)), strPort (std::to_string (address->port));
        int r = 0;
        r = UPNP_DeletePortMapping (m_upnpUrls.controlURL, m_upnpData.first.servicetype, strPort.c_str (), strType.c_str (), 0);
        LogPrint (eLogError, "UPnP: DeletePortMapping() returned : ", r);
    }

    void UPnP::Close ()
    {
        freeUPNPDevlist (m_Devlist);
        m_Devlist = 0;
        FreeUPNPUrls (&m_upnpUrls);
    }

	std::string UPnP::GetProto (std::shared_ptr<i2p::data::RouterInfo::Address> address)
	{
		switch (address->transportStyle)
        {
            case i2p::data::RouterInfo::eTransportNTCP:
                return "TCP";
            break;
            case i2p::data::RouterInfo::eTransportSSU:
            default:
                return "UDP";
        }
	}
}
}
#else /* USE_UPNP */
namespace i2p {
namespace transport {
}
}
#endif /* USE_UPNP */


text:
//==================================================================================================
/*!
  @file

    @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_COTD_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_COTD_HPP_INCLUDED

#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{

  /*!
    @ingroup group-trigonometric
    This function object returns the cotangent of input in degree:
    \f$\cos(\pi x/180)/\sin(\pi x/180)\f$.

    @par Header <boost/simd/function/cotd.hpp>

    @par Note

      As most other trigonometric function cotd can be called
      with a second optional parameter  which is a tag on speed
      and accuracy (see @ref cos for further details)

    @see cos, sin, tan, cot, cotpi

    @par Example:

      @snippet cotd.cpp cotd

    @par Possible output:

      @snippet cotd.txt cotd

  **/
  IEEEValue cotd(IEEEValue const& x);
} }
#endif

#include <boost/simd/function/scalar/cotd.hpp>
#include <boost/simd/function/simd/cotd.hpp>

#endif

max_stars_repo_name: SylvainCorlay/pythran

max_issues_repo_name: SylvainCorlay/pythran

max_forks_repo_name: SylvainCorlay/pythran