text:
// generate by pypp <https://github.com/mugwort-rc/pypp>
// original source code: SPK_Destroyer.h

#include <Extensions/Modifiers/SPK_Destroyer.h>
#include <boost/python.hpp>

class DestroyerWrapper :
    public SPK::Destroyer,
    public boost::python::wrapper<SPK::Destroyer>
{
public:
    using SPK::Destroyer::Destroyer;
    std::string getClassName () const {
        if ( auto getClassName = this->get_override("getClassName") ) {
            return getClassName();
        } else {
            return Destroyer::getClassName();
        }
    }
};

BOOST_PYTHON_FUNCTION_OVERLOADS(create_overload, SPK::Destroyer::create, 0, 2)

void init_SPK_Destroyer_h() {
    boost::python::class_<DestroyerWrapper, boost::python::bases<SPK::Modifier>, std::shared_ptr<SPK::Destroyer>>("Destroyer",
		boost::python::init<boost::python::optional<SPK::Zone *, SPK::ModifierTrigger>>(
			":brief: Constructor of Destroyer\n"
			":param zone: the Zone of the Destroyer\n"
			":param trigger: the trigger of the Destroyer\n"))
        .def("getClassName", &SPK::Destroyer::getClassName)
        .def("create", &SPK::Destroyer::create, create_overload(
			":brief: Creates and registers a new Destroyer\n"
			":param zone: the Zone of the Destroyer\n"
			":param trigger: the trigger of the Destroyer\n"
			":return: A new registered Destroyer\n"
			":since: 1.04.00\n")
			[boost::python::return_value_policy<boost::python::reference_existing_object>()])
        .staticmethod("create")
        ;
}

ext: cpp

max_stars_repo_name: chromia/pyspk

max_issues_repo_name: chromia/pyspk

max_forks_repo_name: chromia/pyspk


text:
/////////////////////////////////////////////////////////////////////
//@file main.cpp
//@brief	主程序
//@copyright	上海信易信息科技股份有限公司 版权所有
/////////////////////////////////////////////////////////////////////

#include "log.h"
#include "md_service.h"
#include "ins_list.h"
#include "config.h"

#include <iostream>
#include <string>

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

int main(int argc, char* argv[])
{
	Log().WithField("fun","main")
		.WithField("key","mdservice")
		.Log(LOG_INFO,"mdservice init!");

	//加载配置文件
	if (!LoadConfig())
	{
		Log().WithField("fun", "main")
			.WithField("key", "mdservice")
			.Log(LOG_WARNING, "mdservice load config failed!");
		return -1;
	}

	boost::asio::io_context ioc;

	mdservice s(ioc);
	if (!s.init())
	{
		Log().WithField("fun","main")
			.WithField("key","mdservice")
			.Log(LOG_INFO,"mdservice init fail!");
		return -1;
	}
	else
	{
		Log().WithField("fun","main")
			.WithField("key","mdservice")
			.Log(LOG_INFO,"mdservice init success!");
	}

	std::atomic_bool flag;
	flag.store(true);

	boost::asio::signal_set signals_(ioc);
	signals_.add(SIGINT);
	signals_.add(SIGTERM);
	#if defined(SIGQUIT)
		signals_.add(SIGQUIT);
	#endif

	signals_.async_wait(
			[&s, &ioc, &flag](boost::system::error_code, int sig)
		{
			Log().WithField("fun","main")
			.WithField("key","mdservice")
			.WithField("sig",sig)
			.Log(LOG_INFO,"mdservice got sig");

			s.stop();

			flag.store(false);
			ioc.stop();

			Log().WithField("fun","main")
				.WithField("key","mdservice")
				.Log(LOG_INFO,"mdservice exit");
		});

	while (flag.load())
	{
		try
		{
			ioc.run();
			break;
		}
		catch (std::exception& ex)
		{
			Log().WithField("fun","main")
				.WithField("key","mdservice")
				.WithField("errmsg",ex.what())
				.Log(LOG_INFO,"mdservice ios run exception");
		}
	}

	return 0;
}

max_stars_repo_name: yuanfengyun/helloctp

max_issues_repo_name: yuanfengyun/helloctp

max_forks_repo_name: yuanfengyun/helloctp


text:
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/serialization/base_object.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/set.hpp>
#include <boost/serialization/map.hpp>

// text forms
//#define SERIALIZE(x) i_ar & (x)
//#define SERIALIZE_PARENT(PARTYPE) i_ar & boost::serialization::base_object<PARTYPE>(*this)

// xml forms
#define SERIALIZE(x) i_ar & BOOST_SERIALIZATION_NVP(x)
#define SERIALIZE_PARENT(PARTYPE) i_ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(PARTYPE)

#define SERIALIZE_FUNC \
friend class boost::serialization::access; \
template<class Archive> void serialize(Archive &i_ar,const unsigned int version)

#define SERIALIZE_FRIENDSHIP friend class boost::serialization::access

#define SERIALIZE_LOAD_FUNC  \
template<class Archive> void load(Archive &i_ar,const unsigned int version)

#define SERIALIZE_SAVE_FUNC  \
template<class Archive> void save(Archive &i_ar,const unsigned int version) const

typedef boost::archive::xml_oarchive SaveArchive;
typedef boost::archive::xml_iarchive LoadArchive;

// to serialize:
// within classes:
// private:
//   SERIALIZE_FUNC
//   {
//     SERIALIZE(var1);
//     SERIALIZE(var2);
//   }
// if class is a subclass:
// private:
//   SERIALIZE_FUNC
//   {
//     SERIALIZE_PARENT(<parent class name>);
//     SERIALIZE(var3);
//     SERIALISE(var4);
//
//
// to make serialization versions:
// if (version > x)
//     SERIALIZE(new item)
//
// BOOST_CLASS_VERSION(<class name>,version)

ext: hpp

max_stars_repo_name: chiendarrendor/AlbertsGameMachine

max_issues_repo_name: chiendarrendor/AlbertsGameMachine

max_forks_repo_name: chiendarrendor/AlbertsGameMachine


text:
#include <cstdint>
#include <fstream>
#include <iostream>
#include <string>
#include <string_view>
#include <locale>

#include <deque>
#include <list>
#include <map>

#include <chrono>
#include <utility>

#include <mutex>  // For std::unique_lock
#include <shared_mutex>

#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>

#include "ledger.hpp"

// ISO date to decimal encoded date
unsigned int parse_date(std::string_view s) {
   if (s.size() != 10) {
      return 0;
   };
   size_t sz;
   int date = std::stoi(s.data(), &sz);
   if (sz != 4) {
      return 0;
   }
   s.remove_prefix(5);
   date = date * 100 + std::stoi(s.data(), &sz);
   if (sz != 2) {
      return 0;
   }
   s.remove_prefix(3);
   date = date * 100 + std::stoi(s.data(), &sz);
   if (sz != 2) {
      return 0;
   }
   return date;
}

// Handle both decimal points and decimal comma
// regardless of locale setting
// Todo: This could be replaced with a fixed point class
// but for now double is good.
double parse_number(std::string_view s) {
   double retval;
   struct Decimalcomma : std::numpunct<char> {
      char do_decimal_point()   const { return ','; }  // separate with Decimalcomma
   };
   std::stringstream temp_string_stream;
   temp_string_stream.imbue(std::locale(std::cout.getloc(), new Decimalcomma ));
   temp_string_stream << s ;
   temp_string_stream >> retval;
   return retval;
}

TransactionSet::TransactionSet() {
   brokerage = 0;
   amount = 0;
   num_trans = 0;
}

std::string TransactionSet::to_json() {
   boost::property_tree::ptree pt;
   pt.put("isin.amount", amount);
   pt.put("isin.brokerage", brokerage);
   pt.put("isin.num", num_trans);

   std::ostringstream buf;
   boost::property_tree::write_json(buf, pt, false);
   return buf.str();
};

class Transactionless {
  public:
   bool operator()(const Transaction *const a, const Transaction *const b) const { return a->date < b->date; }
   bool operator()(const Transaction *const a, uint32_t b) const { return a->date < b; }
   bool operator()(const uint32_t a, const Transaction *const b) const { return a < b->date; }
};

/// Tranasaction Implementation
bool Transaction::operator==(const Transaction &t) const {
   return (t.brokerage == brokerage && t.isin == isin && t.date == date && t.amount == amount && t.curenecy == curenecy &&
           t.sec_name == sec_name);
}
bool Transaction::operator<(const Transaction &t) const { return date < t.date; }

void Ledger::import_csv(std::istream &infile) {
   std::unique_lock lock(mutex);
   std::string line;
   const auto t1 = std::chrono::high_resolution_clock::now();
   bool pushing_data = ledger.empty();
   std::list<Transaction> que;
   while (getline(infile, line)) {
      const char *index = nullptr;
      index = line.c_str();
      const auto index0 = index;
      std::vector<int> field_index;
      while (*index) {
         if (*index++ == ';') {
            field_index.push_back(index - index0);
         }
      }

      // Check if expected numer of fields is found
      if (field_index.size() == 9) {
         // Example csv format. Expect first line to have been shaved off by caller:
         // Datum;Konto;Typ av transaktion;Värdepapper/beskrivning;Antal;Kurs;Belopp;Courtage;Valuta;ISIN
         // 2019-02-01;Depå;Insättning;Insättning;-;-;1000,00;-;SEK;-
         // 2019-01-29;ISK;Köp;Handelsbanken B;20;105,00;-2105;5,00;SEK;SE0007100607

         const auto isin = line.substr(field_index[8], 12);

         Transaction t;
         t.date = parse_date(line.substr(0, field_index[0] - 1));
         t.amount = parse_number(line.substr(field_index[5], field_index[6] - field_index[5] - 1));
         t.isin = isin;
         t.curenecy = line.substr(field_index[7], 3);
         t.sec_name = line.substr(field_index[2], field_index[3] - field_index[2] - 1);
         t.brokerage = parse_number(line.substr(field_index[6], field_index[7] - field_index[6] - 1));

         if (pushing_data) {
            const auto iter = ledger.insert(ledger.end(), t);

            /// create an index with isin
            /// TOTAL execution time - two iterations
            /// =====================================
            /// With create of index: Reading data took 0.00309825
            /// Without               Reading data took 0.00277055
            ///                                         0.0003277
            /// Using index:
            /// Gathering data took 1.0169e-05
            /// fetching data without index took 0.000367927

            /// Conclusion:: the cost of creating the index is payed back the first time it is used !

            isin_index[isin].push_front(&*iter);

            // Save iterator first date in index.
            // do nothing if already exist
            date_index.emplace(t.date, iter);
         } else {
            // Knowm limitation: last Transaction could be identical if identical Transaction have been done
            // multiple times the same day.
            if (t == ledger[0]) {
               for (auto item = que.rbegin(); item != que.rend(); ++item) {
                  ledger.push_front(*item);
                  LedgerDeque::const_iterator iter = ledger.begin();
                  // we are now rebuilding the data in reverse order;
                  isin_index[item->isin].push_back(&*iter);

                  // overwrite index to save the first date - which will be called last
                  date_index[t.date] = iter;
               }
               break;
            }
            que.push_back(t);
         }
      }
   }
   const auto t2 = std::chrono::high_resolution_clock::now();

   std::chrono::duration<double> time_span = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);
   std::cout << "Reading data took " << time_span.count() << std::endl << std::endl << std::endl << std::endl;
   return;
}

/// Verify all asumptionions on data was correct
bool Ledger::data_integrity_self_check() const {
   std::unique_lock lock(mutex);
   bool status = true;
   std::cout << "Ledger length is: " << ledger.size() << std::endl;
   {
      const auto t1 = std::chrono::high_resolution_clock::now();
      bool was_sorted = std::is_sorted(ledger.begin(), ledger.end(), [](const Transaction &t1, const Transaction &t2) { return t1.date > t2.date; });
      const auto t2 = std::chrono::high_resolution_clock::now();

      std::chrono::duration<double> time_span = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);
      std::cout << "Ledger is:" << (was_sorted ? "sorted" : "unsorted") << "  " << time_span.count() << std::endl;
      status = status && was_sorted;
   }
   for (const auto i : isin_index) {
      const auto t1 = std::chrono::high_resolution_clock::now();
      // i.second is a list of all tranactions with one security in same order
      // as found on ledger - which was sorted.
      int count = 0;
      bool was_sorted = std::is_sorted(i.second.begin(), i.second.end(), [&count](const Transaction *t1, const Transaction *t2) {
         ++count;
         return t1->date < t2->date;
      });

      const auto t2 = std::chrono::high_resolution_clock::now();
      status = status && was_sorted;
      std::chrono::duration<double> time_span = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);
      std::cout << i.first << " is " << (was_sorted ? "sorted" : "unsorted") << " x " << count << "  " << time_span.count() << std::endl;
   }
   // Regenerate date index
   LedgerDateIndex new_index;
   {
      const auto t1 = std::chrono::high_resolution_clock::now();
      for (LedgerDeque::const_iterator item = ledger.cbegin(); item != ledger.cend(); item++) {
         new_index.emplace(item->date, item);
      }
      const auto t2 = std::chrono::high_resolution_clock::now();
      std::chrono::duration<double> time_span = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);
      std::cout << "Recreate date index " << time_span.count() << std::endl;
   }
   {
      const auto t1 = std::chrono::high_resolution_clock::now();
      // check
      auto pair = std::mismatch(new_index.begin(), new_index.end(), date_index.begin());
      status = status && (pair.first == new_index.end() && pair.second == date_index.end());
      const auto t2 = std::chrono::high_resolution_clock::now();
      std::chrono::duration<double> time_span = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);
      std::cout << "Verify date index " << time_span.count() << std::endl;
   }
   return status;
}

TransactionSet Ledger::sum(const std::string &isin, uint32_t startdate, uint32_t stopdate) const {
   TransactionSet t;

   std::shared_lock lock(mutex);
   const auto t1 = std::chrono::high_resolution_clock::now();
   const std::string::size_type limit = isin.size();

   for (std::string::size_type offset = 0; offset + 12 <= limit; offset += 12) {
      auto s = isin.substr(offset, 12);
      for (auto j : isin_index[s]) {
         if (j->date >= stopdate) {
            break;
         }
         if (j->date >= startdate) {
            t.amount += j->amount;
            t.brokerage += j->brokerage;
            ++t.num_trans;
         }
      }
      if (offset + 13 < limit && isin[offset + 12] == ';') {
         ++offset;
      }
   }

   const auto t2 = std::chrono::high_resolution_clock::now();

   std::chrono::duration<double> time_span = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);
   std::cout << "impl1 Gathering data took " << time_span.count() << std::endl;
   std::cout << "Transgalactic Sum: " << t.amount << std::endl;

   return t;
}
//
double Ledger::april(int startdate, int stopdate) const {
   std::shared_lock lock(mutex);
   const auto t1 = std::chrono::high_resolution_clock::now();
   double sum = 0;

   const auto &begin_dateindex_iter = date_index.lower_bound(startdate);
   if (begin_dateindex_iter != date_index.end()) {
      const auto &dateindex_final_date = date_index.upper_bound(stopdate);

      const auto &ledger_final_date_iter = ( dateindex_final_date != date_index.end()) ? dateindex_final_date->second : ledger.begin()-1 ;
      const auto &ledger_fist_date_iter = begin_dateindex_iter->second;

      // Todo there is need for a unit test of the corner case.
      // dates are stored falling order.
      for (LedgerDeque::const_iterator legeriter = ledger_fist_date_iter ; legeriter != ledger_final_date_iter; --legeriter) {
         sum += legeriter->brokerage;
      }
   }
   const auto t2 = std::chrono::high_resolution_clock::now();
   std::cout << sum << " brokerage payed in April" << std::endl;
   std::chrono::duration<double> time_span = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);
   std::cout << "brokerage calc took " << time_span.count() << std::endl;
   return sum;
}

/// Orignal seach code moved into this function.
void Ledger::find_something() const {
   std::shared_lock lock(mutex);
   //  Calculate total sum for all

   for (const auto i : isin_index) {
      double sum = 0;
      const auto t1 = std::chrono::high_resolution_clock::now();
      // i.second is a list of all tranactions with one security in same order
      // as found on ledger - which was sorted.
      for (const auto j : i.second) {
         sum += j->amount;
      }
      const auto t2 = std::chrono::high_resolution_clock::now();

      std::chrono::duration<double> time_span = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);
      std::cout << i.first << " Sum: " << sum << "    Gathering data took " << time_span.count() << std::endl;
   }
   {
      // Inside Asia --> Inside Australia: SE0004751337 SE0004113926
      double sum = 0;
      for (auto s : {"SE0004751337", "SE0004113926"}) {
         for (auto j : isin_index[s]) {
            sum += j->amount;
         }
      };
      std::cout << "Insite Asia/Australia Sum: " << sum << std::endl;
   }
   // fpc: SE0000422107 SE0008374250
   double sum = 0;
   for (const auto s : {"SE0000422107", "SE0008374250"}) {
      for (const auto j : isin_index[s]) {
         sum += j->amount;
      }
   };
   std::cout << "FPC Sum: " << sum << std::endl;
   // adv: SE0009888803 SE0012116267 SE0006219473

   sum = 0;
   for (const auto s : {"SE0009888803", "SE0012116267", "SE0006219473"}) {
      for (const auto j : isin_index[s]) {
         sum += j->amount;
      }
   };
   std::cout << "Advenica Sum: " << sum << std::endl;
}

max_stars_repo_name: simonsso/furry-waddle

max_issues_repo_name: simonsso/furry-waddle

max_forks_repo_name: simonsso/furry-waddle


text:
/*
Copyright 2020 Glen Joseph Fernandes
(glenjofe@gmail.com)

Distributed under the Boost Software License, Version 1.0.
(http://www.boost.org/LICENSE_1_0.txt)
*/
#include <boost/core/allocator_access.hpp>
#include <boost/core/lightweight_test.hpp>

template<class T>
struct A1 {
    typedef T value_type;
    typedef std::size_t size_type;
    typedef T* pointer;
    typedef const T* const_pointer;
    template<class U>
    struct rebind {
        typedef A1<U> other;
    };
    A1()
        : value() { }
    T* allocate(std::size_t n, const void*) {
        value = n;
        return 0;
    }
    std::size_t value;
};

#if !defined(BOOST_NO_CXX11_ALLOCATOR)
template<class T>
struct A2 {
    typedef T value_type;
    A2()
        : value() { }
    T* allocate(std::size_t n) {
        value = n;
        return 0;
    }
    std::size_t value;
};
#endif

int main()
{
    {
        A1<int> a;
        BOOST_TEST_NOT(boost::allocator_allocate(a, 5, 0));
        BOOST_TEST_EQ(a.value, 5);
    }
#if !defined(BOOST_NO_CXX11_ALLOCATOR)
    {
        A2<int> a;
        BOOST_TEST_NOT(boost::allocator_allocate(a, 5, 0));
        BOOST_TEST_EQ(a.value, 5);
    }
#endif
    return boost::report_errors();
}


text: #include <boost/accumulators/framework/depends_on.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include <cctbx/boost_python/flex_fwd.h>

#include <cctbx/maptbx/structure_factors.h>
#include <boost/python/class.hpp>
#include <boost/python/args.hpp>

namespace cctbx { namespace maptbx { namespace structure_factors {

namespace {

  struct to_map_wrappers
  {
    typedef to_map<> w_t;

    static void
    wrap()
    {
      using namespace boost::python;
      class_<w_t>("structure_factors_to_map", no_init)
        .def(init<
          sgtbx::space_group const&,
          bool,
          af::const_ref<miller::index<> > const&,
          af::const_ref<std::complex<double> > const&,
          af::int3 const&,
          af::flex_grid<> const&,
          bool,
          optional<bool> >((
            arg("space_group"),
            arg("anomalous_flag"),
            arg("miller_indices"),
            arg("structure_factors"),
            arg("n_real"),
            arg("map_grid"),
            arg("conjugate_flag"),
            arg("treat_restricted")=true)))
        .def("complex_map", &w_t::complex_map)
      ;
    }
  };

  struct from_map_wrappers
  {
    typedef from_map<> w_t;

    static void
    wrap()
    {
      using namespace boost::python;
      class_<w_t>("structure_factors_from_map", no_init)
        .def(init<
          uctbx::unit_cell const&,
          sgtbx::space_group_type const&,
          bool,
          double,
          af::const_ref<std::complex<double>,
            af::c_grid_padded<3> > const&,
          bool,
          optional<bool> >((
            arg("unit_cell"),
            arg("space_group_type"),
            arg("anomalous_flag"),
            arg("d_min"),
            arg("complex_map"),
            arg("conjugate_flag"),
            arg("discard_indices_affected_by_aliasing")=false)))
        .def(init<
          bool,
          af::const_ref<miller::index<> > const&,
          af::const_ref<std::complex<double>,
            af::c_grid_padded<3> > const&,
          bool,
          optional<bool> >((
            arg("anomalous_flag"),
            arg("miller_indices"),
            arg("complex_map"),
            arg("conjugate_flag"),
            arg("allow_miller_indices_outside_map")=false)))
        .def(init<
          sgtbx::space_group const&,
          bool,
          af::const_ref<miller::index<> > const&,
          af::const_ref<std::complex<double>,
          af::c_grid_padded<3> > const&,
          bool>((
            arg("space_group"),
            arg("anomalous_flag"),
            arg("miller_indices"),
            arg("complex_map"),
            arg("conjugate_flag"))))
        .def("miller_indices", &w_t::miller_indices)
        .def("data", &w_t::data)
        .def("n_indices_affected_by_aliasing",
             &w_t::n_indices_affected_by_aliasing)
        .def("outside_map", &w_t::outside_map)
      ;
    }
  };

}} // namespace structure_factors::<anoymous>

namespace boost_python {

  void wrap_structure_factors()
  {
    structure_factors::to_map_wrappers::wrap();
    structure_factors::from_map_wrappers::wrap();
  }

}}} // namespace cctbx::maptbx::boost_python


text:
// Copyright (c) 2017-2019 The Multiverse developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "mode/dbp_config.h"

#include <boost/algorithm/algorithm.hpp>
#include "mode/config_macro.h"

namespace multiverse
{
namespace po = boost::program_options;
namespace fs = boost::filesystem;
using tcp = boost::asio::ip::tcp;

/////////////////////////////////////////////////////////////////////
// CMvDbpBasicConfig

CMvDbpBasicConfig::CMvDbpBasicConfig()
{
    po::options_description desc("DbpBasic");

    CMvDbpBasicConfigOption::AddOptionsImpl(desc);

    AddOptions(desc);
}

CMvDbpBasicConfig::~CMvDbpBasicConfig() {}

bool CMvDbpBasicConfig::PostLoad()
{
    if (fHelp)
    {
        return true;
    }

    if (nDbpPortInt <= 0 || nDbpPortInt > 0xFFFF)
    {
        nDbpPort = (fTestNet ? DEFAULT_TESTNET_DBPPORT : DEFAULT_DBPPORT);
    }
    else
    {
        nDbpPort = (unsigned short)nDbpPortInt;
    }

    if (!fs::path(strDbpCAFile).is_complete())
    {
        strDbpCAFile = (pathRoot / strDbpCAFile).string();
    }

    if (!fs::path(strDbpCertFile).is_complete())
    {
        strDbpCertFile = (pathRoot / strDbpCertFile).string();
    }

    if (!fs::path(strDbpPKFile).is_complete())
    {
        strDbpPKFile = (pathRoot / strDbpPKFile).string();
    }

    return true;
}

std::string CMvDbpBasicConfig::ListConfig() const
{
    std::ostringstream oss;
    oss << CMvDbpBasicConfigOption::ListConfigImpl();
    oss << "DbpPort: " << nDbpPort << "\n";
    return oss.str();
}

std::string CMvDbpBasicConfig::Help() const
{
    return CMvDbpBasicConfigOption::HelpImpl();
}

/////////////////////////////////////////////////////////////////////
// CMvRPCServerConfig

CMvDbpServerConfig::CMvDbpServerConfig()
{
    po::options_description desc("DbpServer");

    CMvDbpServerConfigOption::AddOptionsImpl(desc);

    AddOptions(desc);
}

CMvDbpServerConfig::~CMvDbpServerConfig() {}

bool CMvDbpServerConfig::PostLoad()
{
    if (fHelp)
    {
        return true;
    }

    CMvDbpBasicConfig::PostLoad();

    if(fDbpListen || fDbpListen4 || (!fDbpListen4 && !fDbpListen6))
    {
        epDbp = tcp::endpoint(!vDbpAllowIP.empty()
                              ? boost::asio::ip::address_v4::any()
                              : boost::asio::ip::address_v4::loopback(),
                          nDbpPort);
    }

    if(!fDbpListen && !fDbpListen4 && fDbpListen6)
    {
        epDbp = tcp::endpoint(!vDbpAllowIP.empty()
                              ? boost::asio::ip::address_v6::any()
                              : boost::asio::ip::address_v6::loopback(),
                          nDbpPort);
    }

    return true;
}

std::string CMvDbpServerConfig::ListConfig() const
{
    std::ostringstream oss;
    oss << CMvDbpServerConfigOption::ListConfigImpl();
    oss << "epDbp: " << epDbp << "\n";
    return CMvDbpBasicConfig::ListConfig() + oss.str();
}

std::string CMvDbpServerConfig::Help() const
{
    return CMvDbpBasicConfig::Help() + CMvDbpServerConfigOption::HelpImpl();
}

CMvDbpClientConfig::CMvDbpClientConfig()
{
    po::options_description desc("DbpClient");

    CMvDbpClientConfigOption::AddOptionsImpl(desc);

    AddOptions(desc);
}

CMvDbpClientConfig::~CMvDbpClientConfig()
{

}

bool CMvDbpClientConfig::PostLoad()
{
    if (fHelp)
    {
        return true;
    }

    CMvDbpBasicConfig::PostLoad();
    return true;
}

std::string CMvDbpClientConfig::ListConfig() const
{
    std::ostringstream oss;
    oss << CMvDbpClientConfigOption::ListConfigImpl();
    oss << "epParentDbp: " << epParentHost << "\n";
    return oss.str();
}

std::string CMvDbpClientConfig::Help() const
{
    return CMvDbpClientConfigOption::HelpImpl();
}

} // namepspace multiverse

max_stars_repo_name: FissionAndFusion/FnFnMvWallet-Pre

max_issues_repo_name: FissionAndFusion/FnFnMvWallet-Pre

max_forks_repo_name: FissionAndFusion/FnFnMvWallet-Pre


text:
#include <bits/stdc++.h>
#include <zlib.h>
#include <boost/algorithm/string.hpp>
#include <string>

#include "log.h"
#include "config.h"
#include "settings.h"
#include "cfg.h"
#include "lbr_miss_sample.h"

using namespace std;

int main(int argc, char *argv[])
{
    if(argc<2)
    {
        panic("Usage ./exec config_cfg_file_path");
    }
    MyConfigWrapper config(argv[1]);
    Settings sim_settings(config);
    CFG dynamic_cfg(config, sim_settings);
    Miss_Profile profile(config, sim_settings, dynamic_cfg, true);
    return 0;
}

max_stars_repo_name: efeslab/frontsuite

max_issues_repo_name: efeslab/frontsuite

max_forks_repo_name: efeslab/frontsuite


text:
// Copyright 2004-present Facebook. All Rights Reserved.

#include <vector>
#include <string>

#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/predicate.hpp>

#include <osquery/core.h>
#include <osquery/filesystem.h>
#include <osquery/logger.h>
#include <osquery/tables.h>

namespace osquery {
namespace tables {

void genNFSShare(const std::string& share_line, QueryData& results) {
  auto line = split(share_line);
  if (line.size() == 0 || boost::starts_with(line[0], "#")) {
    return;
  }

  std::vector<std::string> line_exports;
  unsigned int readonly = 0;
  int options_index = -1;

  for (const auto& iter : line) {
    options_index++;
    if (iter[0] == '/') {
      line_exports.push_back(iter);
    } else {
      break;
    }
  }

  // Start looping through starting at the first options
  // (so skip the exports)
  for (auto iter = line.begin() + options_index; iter != line.end(); ++iter) {
    if (iter->compare("-ro") == 0 || iter->compare("-o") == 0) {
      readonly = 1;
    }
  }

  for (const auto& iter : line_exports) {
    Row r;
    r["share"] = iter;
    r["readonly"] = (readonly) ? "1" : "0";

    std::ostringstream oss;
    std::copy(line.begin() + options_index,
              line.end(),
              std::ostream_iterator<std::string>(oss, " "));
    r["options"] = oss.str();
    results.push_back(r);
  }
}

QueryData genNFSShares(QueryContext& context) {
  QueryData results;

  std::string content;
  auto status = osquery::readFile("/etc/exports", content);
  if (!status.ok()) {
    VLOG(1) << "Error reading /etc/exports: " << status.toString();
    return {};
  }

  for (const auto& share_line : split(content, "\n")) {
    genNFSShare(share_line, results);
  }
  return results;
}
}
}

max_stars_repo_name: majacQ/osquery

max_issues_repo_name: majacQ/osquery

max_forks_repo_name: majacQ/osquery


text:
#pragma once

#include <boost/type_traits/is_same.hpp>
#include <boost/utility/enable_if.hpp>

namespace metaSMT {
  namespace type {

    struct BitVector {

      unsigned width;

      BitVector() {}

      BitVector(unsigned w)
        : width(w)
      {}

      template<typename STREAM>
      friend STREAM & operator<< (STREAM & out, BitVector const & self) \
      {  return (out << "BitVector [" << self.width <<"]"); }

    };

    /** equality of BitVector Types **/
    template <typename T>
    typename boost::enable_if< boost::is_same<BitVector, T>, bool>::type
    operator== (BitVector const & a , T const & b)  \
    {  return a.width==b.width; }

    template <typename T>
    typename boost::disable_if< boost::is_same<BitVector, T>, bool>::type
    operator== (BitVector const & a , T const & b)  \
    {  return false; }

  } /* type */
} /* metaSMT */

max_stars_repo_name: finnhaedicke/metaSMT

max_issues_repo_name: finnhaedicke/metaSMT

max_forks_repo_name: finnhaedicke/metaSMT


text:
#ifndef UUID_4B926C10_9735_4A15_BC4B_22DE65201DD1
#define UUID_4B926C10_9735_4A15_BC4B_22DE65201DD1
#pragma once

#include "assert.hpp"
#include "except.hpp"

#include <cstring>
#include <boost/operators.hpp>

namespace Neptools
{

// like string_view, except it CString=true, it must be zero terminated if
// !empty() (but can contain embedded zeros)
template <typename Char, bool CString, typename Traits = std::char_traits<Char>>
class BaseBasicNonowningString
    : boost::totally_ordered<BaseBasicNonowningString<Char, CString, Traits>>,
      boost::totally_ordered<BaseBasicNonowningString<Char, CString, Traits>,
                             const Char*>
{
public:
    static constexpr bool ZERO_TERMINATED = CString;
    using traits_type = Traits;
    using value_type = Char;
    using pointer = Char*;
    using const_pointer = const Char*;
    using reference = Char&;
    using const_reference = const Char&;
    using const_iterator = const Char*;
    using iterator = const_iterator;
    using const_reverse_iterator = std::reverse_iterator<const_iterator>;
    using reverse_iterator = const_reverse_iterator;
    using size_type = std::size_t;
    using difference_type = std::ptrdiff_t;

    using unsigned_value_type = std::make_unsigned_t<Char>;
    using unsigned_pointer = unsigned_value_type*;
    using unsigned_const_pointer = const unsigned_value_type*;
    using unsigned_reference = unsigned_value_type&;
    using unsigned_const_reference = const unsigned_value_type&;

    constexpr BaseBasicNonowningString() noexcept : str{nullptr}, len{0} {}

    BaseBasicNonowningString(const_pointer str) noexcept : str{str}
    { len = str ? Traits::length(str) : 0; }

    BaseBasicNonowningString(unsigned_const_pointer str) noexcept
        : BaseBasicNonowningString{reinterpret_cast<const_pointer>(str)} {}

    constexpr BaseBasicNonowningString(const_pointer str, size_type len) noexcept
        : str{str}, len{len}
    {
        NEPTOOLS_ASSERT(str != nullptr || len == 0);
        if (CString && str) NEPTOOLS_ASSERT(str[len] == '\0');
    }

    constexpr BaseBasicNonowningString(
        unsigned_const_pointer str, size_type len) noexcept
        : BaseBasicNonowningString{reinterpret_cast<const_pointer>(str), len} {}

    template <typename Allocator>
    BaseBasicNonowningString(
        const std::basic_string<Char, Traits, Allocator>& str) noexcept
        : str{str.c_str()}, len{str.size()} {}

    template <size_t N>
    constexpr BaseBasicNonowningString(const Char (&str)[N]) noexcept
        : str{str}, len{N-1} {}

    constexpr const_iterator  begin() const noexcept { return str; }
    constexpr const_iterator cbegin() const noexcept { return str; }
    constexpr const_iterator  end() const noexcept { return str+len; }
    constexpr const_iterator cend() const noexcept { return str+len; }

    constexpr const_reverse_iterator  rbegin() const noexcept { return end(); }
    constexpr const_reverse_iterator crbegin() const noexcept { return end(); }
    constexpr const_reverse_iterator  rend() const noexcept { return begin(); }
    constexpr const_reverse_iterator crend() const noexcept { return begin(); }

    constexpr const_reference operator[](size_type i) const noexcept
    { return str[i]; }
    constexpr const_reference at(size_type i) const
    {
        if (CString ? (i > len) : (i >= len))
            NEPTOOLS_THROW(std::out_of_range{"NonowningString"});
        return str[i];
    }

    constexpr unsigned_const_reference uindex(size_type i) const noexcept
    { return reinterpret_cast<unsigned_const_reference>(str[i]); }
    constexpr unsigned_const_reference uat(size_type i) const noexcept
    { return reinterpret_cast<unsigned_const_reference>(at(i)); }

    // undefined if string is empty
    constexpr const_reference front() const noexcept { return str[0]; }
    constexpr const_reference back() const noexcept { return str[len-1]; }
    // can return nullptr or pointer to '\0' in case of empty string
    constexpr const_pointer data() const noexcept { return str; }
    constexpr unsigned_const_pointer udata() const noexcept
    { return reinterpret_cast<unsigned_const_pointer>(str); }

    constexpr size_type size() const noexcept { return len; }
    constexpr size_type length() const noexcept { return len; }
    constexpr size_type max_size() const noexcept
    { return std::numeric_limits<size_type>::max(); }
    constexpr bool empty() const noexcept { return len == 0; }

    constexpr void remove_prefix(size_type n) noexcept { str += n; len -= n; }

    template <typename Allocator = std::allocator<Char>>
    std::basic_string<Char, Traits, Allocator> to_string() const
    { return {str, len}; }

    template <typename Allocator>
    operator std::basic_string<Char, Traits, Allocator>() const
    { return {str, len}; }

    // copy, *find*, substr: too lazy
    template <bool CStringO>
    constexpr int compare(
        BaseBasicNonowningString<Char, CStringO, Traits> o) const noexcept
    {
        auto cmp = Traits::compare(str, o.str, std::min(len, o.len));
        if (cmp == 0) cmp = (len == o.len ? 0 : (len < o.len ? -1 : 1));
        return cmp;
    }
    constexpr int compare(BaseBasicNonowningString o) const noexcept
    { return compare<CString>(o); }
    // too lazy for the other overloads

    template <bool CStringO>
    constexpr bool operator==(
        BaseBasicNonowningString<Char, CStringO, Traits> o) const noexcept
    {
        return len == o.len &&
            (str == o.str || Traits::compare(str, o.str, len) == 0);
    }
    constexpr bool operator==(BaseBasicNonowningString o) const noexcept
    { return operator==<CString>(o); }

    template <bool CStringO>
    constexpr bool operator<(
        BaseBasicNonowningString<Char, CStringO, Traits> o) const noexcept
    { return compare(o) < 0; }
    constexpr bool operator<(BaseBasicNonowningString o) const noexcept
    { return operator< <CString>(o); }

protected:
    const_pointer str;
    size_type len;
};

#define X_GEN_OP(op)                                                            \
    template <typename Char, bool CString, typename Traits, typename Allocator> \
    inline bool operator op(                                                    \
        const std::basic_string<Char, Traits, Allocator>& lhs,                  \
        BaseBasicNonowningString<Char, CString, Traits> rhs)                    \
    {                                                                           \
         return BaseBasicNonowningString<Char, CString, Traits>{lhs} op rhs;    \
    }
X_GEN_OP(==)
X_GEN_OP(!=)
X_GEN_OP(<)
X_GEN_OP(<=)
X_GEN_OP(>)
X_GEN_OP(>=)
#undef X_GEN_OP

template <typename Char, bool CString, typename Traits = std::char_traits<Char>>
class BasicNonowningString;

template <typename Char, typename Traits>
class BasicNonowningString<Char, true, Traits> final
    : public BaseBasicNonowningString<Char, true, Traits>
{
    using Base = BaseBasicNonowningString<Char, true, Traits>;
public:
    using Base::Base;

    constexpr typename Base::const_pointer c_str() const noexcept
    { return this->data(); }
};

template <typename Char, typename Traits>
class BasicNonowningString<Char, false, Traits> final
    : public BaseBasicNonowningString<Char, false, Traits>
{
    using Base = BaseBasicNonowningString<Char, false, Traits>;
public:
    using Base::Base;

    BasicNonowningString(BaseBasicNonowningString<Char, true, Traits> str)
        : Base{str.data(), str.length()} {}

    constexpr void remove_suffix(typename Base::size_type n) noexcept
    { Base::len -= n; }
};

using NonowningString = BasicNonowningString<char, true>;
using NonowningWString = BasicNonowningString<wchar_t, true>;

using StringView = BasicNonowningString<char, false>;
using WStringView = BasicNonowningString<wchar_t, false>;

}

#endif

max_stars_repo_name: clienthax/neptools

max_issues_repo_name: clienthax/neptools

max_forks_repo_name: clienthax/neptools


text:
#include <wf700tk/device.hpp>

#include <algorithm>

#include <boost/asio/buffer.hpp>
#include <boost/asio/read_until.hpp>
#include <boost/asio/write.hpp>

#include <wf700tk/request_writer.hpp>

#include <iostream>

namespace wf700tk {

device::device(net::serial_port &&port)
    : port_(std::move(port)), poll_timer_(port_.get_executor()),
      request_buffer_(request_writer{}.length()) {}

void device::input_callback(
    const std::function<void(const device::error_code &, credit_channel)>
        &callback) {
    if (input_callback_) {
        input_callback_(error_code(net::error::operation_aborted),
                        credit_channel::none);
    }
    input_callback_ = callback;
    if (response_timeout_counter_ < 0) {
        // we should inform the new callback also if there is a timeout
        response_timeout_counter_ = -1;
    }
}

void device::output(ticket_channel channel, unsigned int amount,
                    const device::output_handler &handler) {
    if (amount == 0) {
        handler(error_code(), amount);
        return;
    }

    auto index = ticket_channel_index(channel);
    if (!index) {
        handler(net::error::invalid_argument, amount);
        return;
    }

    auto &output = ticket_output_[*index];
    if (!output.active) {
        output.to_dispense = amount;
        output.callback = handler;
    } else {
        handler(net::error::already_started, amount);
    }
}

net::serial_port &device::serial_port() { return port_; }

const net::serial_port &device::serial_port() const { return port_; }

void device::start_poll() {
    poll_timer_.expires_after(polling_duration_);
    poll_timer_.async_wait([this](const error_code &ec) {
        if (!ec) {
            poll();
        }
    });
}

void device::start_read() {
    port_.async_read_some(net::buffer(response_buffer_),
                          [this](const error_code &ec, std::size_t len) {
                              if (!ec) {
                                  handle_read(len);
                              }
                          });
}

void device::handle_read(std::size_t len) {
    response_reader_.put(net::buffer(response_buffer_.data(), len));
    if (response_reader_.success()) {
        handle_poll_response(response_reader_.message());
        response_timeout_counter_ = response_timeout_;
    }
    start_read();
}

void device::handle_poll_response(const response &resp) {
    if (resp.accepted_credit_) {
        input_callback_(error_code(), resp.credit_channel_);
    }

    if (auto i = ticket_channel_index(resp.ticket_channel_)) {
        auto &channel = ticket_output_[*i];
        if (channel.active) {
            channel.inform(resp.tickets_to_dispense_);
        }
    }
}

void device::poll() {
    request_writer req_w;
    req_w.ack(next_ack);
    next_ack = next_ack ? 0 : 1;
    prepare_poll(req_w.msg());
    auto buf = net::buffer(request_buffer_);
    req_w.write(buf);

    if (response_timeout_counter_ >= 0) {
        --response_timeout_counter_;
    } else {
        handle_response_timeout();
    }

    net::async_write(
        port_, buf,
        [this](const error_code &ec, std::size_t /*bytes_written*/) {
            if (!ec) {
                start_poll();
            } else {
                handle_port_error(ec);
            }
        });
}

void device::prepare_poll(request &req) {
    for (unsigned int i = 0; i < ticket_output_.size(); ++i) {
        // TODO: check wether this works. This should stop running outputs that
        // timed out
        auto &output = ticket_output_[i];
        if (output.active && output.timed_out()) {
            req.ticket_channel_ = *make_ticket_channel_from_index(i);
            req.tickets_to_dispense(0);
            if (output.callback) {
                output.callback(error_code(net::error::timed_out),
                                output.to_dispense);
            }
            output.reset();
            return;
        }
    }

    for (unsigned int i = 0; i < ticket_output_.size(); ++i) {
        auto &output = ticket_output_[i];
        if (!output.active && output.to_dispense > 0) {
            req.ticket_channel_ = *make_ticket_channel_from_index(i);
            req.tickets_to_dispense(output.next_dispense_amount());
            output.prepare_for_sending(req.tickets_to_dispense());
            return;
        }
    }
}

void device::handle_response_timeout() {
    error_code ec(net::error::timed_out);
    if (response_timeout_counter_ == -1 && input_callback_) {
        // do not inform this callback anymore
        response_timeout_counter_ = -2;
        input_callback_(ec, credit_channel::none);
    }
    handle_global_output_error(ec);
}

void device::handle_port_error(const device::error_code &ec) {
    port_.close();
    if (input_callback_) {
        input_callback_(ec, credit_channel::none);
    }
    handle_global_output_error(ec);
}

void device::handle_global_output_error(const error_code &ec) {
    for (auto &channel : ticket_output_) {
        if (channel.active) {
            if (channel.callback) {
                channel.callback(ec, channel.to_dispense);
            }
            channel.reset();
        }
    }
}

void device::output_state::inform(unsigned char tickets_to_dispense) {
    if (last_dispense_state > tickets_to_dispense) {
        timeout_counter = 0;

        int dispensed = last_dispense_state - tickets_to_dispense;

        to_dispense = std::max(0, to_dispense - dispensed);

        if (to_dispense == 0) {
            callback(error_code(), 0);
            reset();
        } else if (tickets_to_dispense == 0) {
            active = false;
            timeout_counter = -1; // add timeout bonus to prevent timeouts due
                                  // to transmission times
        }
    } else {
        ++timeout_counter;
    }

    last_dispense_state = tickets_to_dispense;
}

unsigned char device::output_state::next_dispense_amount() const {
    return std::min(static_cast<unsigned char>(to_dispense),
                    static_cast<unsigned char>(0x0f));
}

void device::output_state::prepare_for_sending(unsigned int amount) {
    last_dispense_state = amount;
    active = true;
}

void device::output_state::reset() {
    active = false;
    to_dispense = 0;
    timeout_counter = 0;
    callback = decltype(callback)();
}

bool device::output_state::timed_out() const { return timeout_counter > 2; }

} // namespace wf700tk


text:
#include <atomic>
#include <boost/asio.hpp>
#include <chrono>
#include <iostream>
#include <map>
#include <mutex>
#include <shared_mutex>

#include "stats_if.hpp"

#pragma once

namespace config
{
class params;
}
using namespace std::chrono;

namespace stats
{
using mutex_type = std::shared_timed_mutex;
using read_lock = std::shared_lock<mutex_type>;
using write_lock = std::unique_lock<mutex_type>;

struct snapshot
{
    friend inline bool operator==(const snapshot& lhs, const snapshot& rhs)
    {
        return lhs.sent == rhs.sent && lhs.responded_ok == rhs.responded_ok &&
               lhs.timed_out == rhs.timed_out && lhs.rate == rhs.rate && lhs.avg_rt == rhs.avg_rt &&
               lhs.max_rt == rhs.max_rt && lhs.min_rt == rhs.min_rt &&
               lhs.response_codes_ok == rhs.response_codes_ok &&
               lhs.response_codes_nok == rhs.response_codes_nok;
    }

    int64_t sent = 0;
    int64_t responded_ok = 0;
    int64_t timed_out = 0;
    float rate = 0;
    float avg_rt = 0;
    float max_rt = 0;
    float min_rt = 0;
    std::map<int, int64_t> response_codes_ok{};
    std::map<int, int64_t> response_codes_nok{};
    time_point<steady_clock> init_time{steady_clock::now()};
};

class stats : public stats_if
{
public:
    stats(boost::asio::io_context& io_ctx, const int print_period,
          const std::string& output_file_name, const std::vector<std::string>& msg_names);

    stats(const stats& s) = delete;

    ~stats() = default;

    void print();
    void end();

    void increase_sent(const std::string& id) override;
    void add_measurement(const std::string& id, const int64_t time, const int code) override;
    void add_timeout(const std::string& id) override;
    void add_error(const std::string& id, const int e) override;
    void add_client_error(const std::string& id, const int e) override;

protected:
    static std::string create_headers_str();
    void write_headers(std::fstream& fs);
    void write_errors() const;
    void print_headers() const;
    void print_snapshot(const snapshot& snap, const time_point<steady_clock>& init_time,
                        std::ostream& out = std::cout) const;
    void do_print();

    void update_rcs(snapshot& snap, const int code, const bool is_error);
    void update_rts(snapshot& snap, const int64_t elapsed_time);
    void add_measurement(snapshot& snap, const int64_t elapsed_time, const int code);

    boost::asio::steady_timer timer;
    int print_period;
    bool cancel;
    std::atomic<int64_t> counter;

    std::string file_prefix;
    std::string accum_filename;
    std::string partial_filename;
    std::string err_filename;

    snapshot total_snap;
    snapshot partial_snap;
    std::map<std::string, snapshot> msg_snaps;

    mutable mutex_type rw_mutex;

    const std::string stats_headers;
};
}  // namespace stats

max_stars_repo_name: PepeluDev/hermes

max_issues_repo_name: PepeluDev/hermes

max_forks_repo_name: PepeluDev/hermes


text:
#ifndef PROCESSES_H
#define PROCESSES_H

#include"heaps.hpp"
#include"lockeds.hpp"
#include"history.hpp"

#include <vector>
#include <map>
#include <string>

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

class HlError {
private:
	std::string info; // UTF-8
public:
	HlError(const char *c) : info(c) {}
	std::string err_str() { return info; }
};

void throw_HlError(char const*);

/*Consider putting this into the process's heap*/
class ProcessStack : public std::vector<Object::ref> {
public:
  Object::ref & top(size_t off=1){
    if(off > size() || off == 0){
      // consider throwing a VMError instead of an hl-side error
      throw_HlError("internal: process stack underflow in top()");
    }
    return (*this)[size() - off];
  }

  void pop(size_t num=1){
    if(num > size()){
      throw_HlError( "internal: Process stack underflow in pop()");
    }
    if(num != 0) resize(size() - num);
  }

  void push(Object::ref gp){
    push_back(gp);
  }

  void restack(size_t sz) {
    if(sz > size()){
      throw_HlError( "internal: process stack underflow in restack()");
    }
    size_t off = size() - sz;
    /*Not exactly the best way to do it?*/
    if(off != 0) erase(begin(), begin() + off);
  }

  Object::ref& operator[](size_t pos) {
    if (pos >= size())
      throw_HlError("internal: stack overflow in []");
    return (*static_cast<std::vector<Object::ref>*>(this))[pos];
  }
};

enum ProcessStatus {
	process_dead,
	process_waiting,
	process_anesthesized,
	process_running,

	/*Not actually a valid process status, but
	Process::execute should return this if it
	wants to switch to another process.
	We switch to another process under the following
	conditions:
		1. when we awaken a waiting process by
		   sending it a message.
		2. when we launch a new process.
	*/
	process_change
};

class Process;
class HeapTraverser;

/*
 * A mailbox is an abstraction on top of a Process.
 */
class MailBox {
private:
	Process & parent;
	explicit MailBox(Process & parent) : parent(parent) {}
	MailBox(void); /*disallowed*/
public:

	/*adds the message M to this process's mailbox*/
	/*Must atomically insert M to the mailbox, then
	check if this process is waiting.  If so, it should
	set is_waiting to true and change the process state
	to process_running.
	returns true if it was able to insert M, false if
	not (e.g. due to contention on the mailbox)
	*/
	bool receive_message( ValueHolderRef& M, bool& is_waiting);

	/*atomically check if the attached process
	  has any messages.  Change stat to
	  process_waiting if the process's mailbox
	  is empty*/
	bool extract_message(Object::ref& M);
	/*attempt to atomically check if the attached
	  process has any messages.  If it can't
	  check (e.g. heavy contention on mailbox),
	  it just returns false.  If it can check,
	  it sets has_message to true if there was
	  indeed a message, or false if there were
	  no messages yet.  Does not change status.*/
	bool try_extract_message(Object::ref& M, bool& has_message);

	/*traverses the messages in the attached
	process's mailbox.
	NOTE!  A message can be received *during*
	the traversal.  If a message is received,
	it will *not* be traversed.
	*/
	void traverse(HeapTraverser* ht);

	friend class Process;
};

class HlPid;
class Worker;
class AllWorkers;

class Process : public Heap {
private:
	ProcessStatus stat;
	bool black;
	AppMutex mtx;

	/*if this flag is true, it means this process is the only
	running process.
	*/
	bool only_running;

	/*in the future, consider using a limited cache*/
	std::map<Symbol*, Object::ref> global_cache;

	AppMutex notification_mtx;
	std::vector<Symbol*> invalid_globals;

	/*invalidates globals which have been changed*/
	void invalidate_changed_globals(void);

        /*extra root objects to scan during GC*/
        std::vector<Object::ref*> extra_roots;

        void push_extra_root(Object::ref & root) {
          extra_roots.push_back(&root);
        }

        void pop_extra_root() { extra_roots.pop_back(); }

	/*The multipush hack:
	The event system can, in theory, push multiple processes
	onto the workqueue simultaneously.  The worker system
	does not support this directly (it only expects one
	pushed process at a time).  So, as a quick-n-dirty hack,
	we store this potentially-multiple set of processes
	here.
	*/
	boost::scoped_ptr<std::vector<Process*> > multipush;

	void give_multipush(
			boost::scoped_ptr<std::vector<Process*> >& other) {
		other.swap(multipush);
		multipush.reset(); /*for paranoia only*/
	}

	/*The real mailbox*/
	ValueHolderRef the_mailbox;

public:
	bool is_only_running(void) const {
		return only_running;
	}

	/*Must be called from within the execution of *this
	P must be a process we just recently did a
	Process::receive_message() on.  The receive_message()
	should have returned an is_waiting of true.
	*/
	void add_to_multipush(Process* P) {
		/*implicitly, we know that we aren't the only
		running process anymore
		*/
		only_running = 0;
		if(!multipush) {
			multipush.reset(new std::vector<Process*>());
		}
		multipush->push_back(P);
	}

	/*grabs the multipush slot.  used only for class Worker*/
	class GrabMultipush : boost::noncopyable {
	private:
		GrabMultipush(); //disallowed!
		GrabMultipush(Process* P,
				boost::scoped_ptr<std::vector<Process*> >&
					to ) {
			P->give_multipush(to);
		}
	public:
		friend class Worker;
	};

	/*sets or clears the only-running flag.  used only for
	class AllWorkers and class Worker
	*/
	class SetOnlyRunning : boost::noncopyable {
	private:
		SetOnlyRunning(); //disallowed!
		SetOnlyRunning(Process* P, bool val) {
			P->only_running = val;
		}
	public:
		friend class AllWorkers;
		friend class Worker;
	};

	// spawn a new Process
	// take a continuation (allocated in the current process)
	// and return the HlPid (also allocated in the current process)
	// of the newly created process
	// spawned process is *not* registered or added to a workqueue
	HlPid* spawn(Object::ref cont);

	/*RAII class for extra roots*/
	class ExtraRoot {
	private:
		Process& proc;
		Object::ref val;
	public:
		ExtraRoot(Process& nproc) : proc(nproc), val() {
			proc.push_extra_root(val);
		}
		~ExtraRoot() {
			proc.pop_extra_root();
		}
		inline operator Object::ref const&(void) const {
			return val;
		}
		inline operator Object::ref&(void) {
			return val;
		}
		inline ExtraRoot& operator=(Object::ref const& nval) {
			val = nval;
			return *this;
		}
		inline ExtraRoot& operator=(ExtraRoot const& n) {
			val = n.val;
			return *this;
		}
		inline bool operator==(Object::ref const& o) const {
			return val == o;
		}
	};

	/*holds the bytecode sequence object.
	This is necessary because it's possible
	to lose all references to a bytecode
	sequence while it's being executed,
	in particular, during a k-closure-reuse
	or k-closure-recreate.
	*/
	Object::ref bytecode_slot;

	/*the process-local slot*/
	Object::ref proc_local_slot;
	/*current error handler slot*/
	Object::ref err_handler_slot;

	Process(void)
		: stat(process_running),
		  black(0),
		  mtx(),
		  only_running(0),
		  global_cache(),
		  notification_mtx(),
		  invalid_globals(),
		  bytecode_slot(),
		  multipush(0),
		  is_main(0)
	{ }

/*-----------------------------------------------------------------------------
Global Variable Access
-----------------------------------------------------------------------------*/
	/*notifies the process of changes in a particular global*/
	void notify_global_change(Symbol*);
	/*gets the value of a global*/
	Object::ref global_read(Symbol*);
	/*sets the value of a global*/
	void global_write(Symbol*, Object::ref);
	/*clears the cache of global variables*/
	void global_acquire( void );

/*-----------------------------------------------------------------------------
For process-level garbage collection
-----------------------------------------------------------------------------*/
	/*atomically check if status is process_waiting and it is not marked*/
	bool waiting_and_not_black(void);

	/*anesthesizes this process if appropriate*/
	/*Must atomically check if process status is process_waiting,
	and process color is not black.  If so, set to
	process_anesthesized.
	returns true if the process was correctly anesthesized
	*/
	bool anesthesize(void);

	/*unanesthesizes this process if possible*/
	/*Must atomically check if the mailbox is empty,
	and set to process_running if there is a message,
	or set to process_waiting if mailbox is empty.
	returns true if the mailbox was not empty.
	*/
	bool unanesthesize(void);

	/*sets color to black*/
	void blacken(void) {
		AppLock l(mtx);
		black = true;
	}
	/*sets color to white*/
	void whiten(void) {
		AppLock l(mtx);
		black = false;
	}
	/*checks color.  no atomicity necessary*/
	bool is_black(void) {
		AppLock l(mtx);
		return black;
	}

	/*checks if the process is dead.*/
	bool is_dead(void) {
		AppLock l(mtx);
		return stat == process_dead;
	}

	/*sets process status to process_dead, and frees its
	heap.
	*/
	void kill(void);
	/*like kill(), but does so atomically (with locks!)*/
	void atomic_kill(void);

	/*Executes the process for a time slice
	caller will protect with a try-catch block, which will
	inform the user of the error and kill this process.
	timeslice is the number of function calls (or whatever
	unit) to process before returning.
	Q is an empty pointer to be filled in if this returns
	process_change.
	returns:
	process_dead - process status was set to dead and its
		memory was freed (i.e. execute() has called
		atomic_kill()), and caller should silently
		drop this process.
	process_waiting - process status was set to waiting,
		and caller should silently drop this process.
	process_anesthesized - invalid!
	process_running - process status was not changed,
		and caller should return this process to
		the workqueue.
	process_change - process executor will donate its
		remaining timeslice to Q.  Q should be a
		process that is not on the workqueue! (i.e.
		Q should not have been process_running state
		previously).  Used when the process sends a
		message to Q and Q has been waiting, or if
		the process started a new process Q.
		Process::execute is responsible for
		atomically changing Q to process_running.
	*/
	ProcessStatus execute(size_t& timeslice, Process*& Q);

	/*allows access to the heap object*/
	Heap& heap(void);

	/*allows access to the mailbox*/
	MailBox mailbox(void) { return MailBox(*this); }
	/*allows access to the history*/
	History history(void) { return History(stack); }

	ProcessStack stack;

	virtual void scan_root_object(GenericTraverser* gt);

	/*flags if this is the main process*/
	bool is_main;

	friend class MailBox;
};

#endif // PROCESSES_H

max_stars_repo_name: AmkG/hl

max_issues_repo_name: AmkG/hl

max_forks_repo_name: AmkG/hl


text:
#include <arti_base_control/vehicle.h>
#include <arti_base_control/axle.h>
#include <arti_base_control/utils.h>
#include <boost/range/irange.hpp>
#include <Eigen/Core>
#include <Eigen/QR>
#include <functional>
#include <memory>

namespace arti_base_control
{
VehicleVelocityConstraint::VehicleVelocityConstraint(double a_v_x_, double a_v_y_, double a_v_theta_, double b_)
  : a_v_x(a_v_x_), a_v_y(a_v_y_), a_v_theta(a_v_theta_), b(b_)
{
}

Vehicle::Vehicle(const ros::NodeHandle& nh, const JointActuatorFactoryPtr& motor_factory, bool process_ackermann)
  : nh_(nh), motor_factory_(motor_factory), reconfigure_server_(nh), process_ackermann_(process_ackermann)
{
  reconfigure_server_.setCallback(std::bind(&Vehicle::reconfigure, this, std::placeholders::_1));
}

void Vehicle::reconfigure(VehicleConfig& config)
{
  config_ = config;

  if (config.max_velocity_linear == 0.0)
  {
    ROS_ERROR("Parameter max_velocity_linear is not set");
  }

  if (config.allowed_brake_velocity == 0.0)
  {
    ROS_WARN("Parameter allowed_brake_velocity is not set");
  }

  if (config.brake_velocity == 0.0)
  {
    ROS_WARN("Parameter brake_velocity is not set");
  }

  if (config.brake_current == 0.0)
  {
    ROS_WARN("Parameter brake_current is not set");
  }

  if (axles_.empty())
  {
    XmlRpc::XmlRpcValue axles_param;
    if (nh_.getParam("axles", axles_param))
    {
      if (axles_param.getType() == XmlRpc::XmlRpcValue::TypeStruct)
      {
        const ros::NodeHandle axles_nh(nh_, "axles");
        for (const XmlRpc::XmlRpcValue::ValueStruct::value_type& axle_param : axles_param)
        {
          axles_.emplace_back(
            std::make_shared<Axle>(ros::NodeHandle(axles_nh, axle_param.first), config_, motor_factory_));
        }
      }
      else
      {
        ROS_ERROR_STREAM("axles parameter has invalid type, must be map");
      }
    }
    else
    {
      ROS_ERROR_STREAM("axles parameter is missing");
    }
  }

  wheelbase_ = config_.wheelbase;
  if (process_ackermann_)
  {
    if (wheelbase_ == 0.0)
    {
      for (const AxlePtr& axle : axles_)
      {
        const AxleConfig& axle_config = axle->getConfig();

        if (axle_config.is_steered)
        {
          wheelbase_ = std::fabs(axle_config.position_x - config_.icr_x);
          if (wheelbase_ != 0.0)
          {
            break;
          }
        }
      }

      if (wheelbase_ == 0.0)
      {
        ROS_WARN_STREAM("Wheelbase is not set and could not be determined automatically, this prevents control via"
                        " Ackermann messages");
      }
    }
  }

  for (const AxlePtr& axle : axles_)
  {
    axle->setVehicleConfig(config_);
  }
}

void Vehicle::setVelocity(const ackermann_msgs::AckermannDrive& velocity, const ros::Time& time)
{
  if (!process_ackermann_)
  {
    ROS_ERROR("got ackerman command but should not process ackerman commands");
    return;
  }

  const double steering_angle = limit(normalizeSteeringAngle(velocity.steering_angle), config_.max_steering_angle,
                                      "steering angle");
  const double sin_steering_angle = std::sin(steering_angle);
  const double cos_steering_angle = std::cos(steering_angle);

  // Limit linear velocity to stay below angular velocity limit
  // (angular_velocity = tan(steering_angle) * linear_velocity / wheelbase; this can become infinite when
  // steering_angle approaches 90 degrees):
  double angular_velocity = 0.0;
  double linear_velocity = limit(velocity.speed, config_.max_velocity_linear, "linear velocity");
  if (linear_velocity != 0.0 && wheelbase_ != 0.0)
  {
    const double a = std::fabs(linear_velocity * sin_steering_angle);
    const double b = std::fabs(config_.max_velocity_angular * wheelbase_ * cos_steering_angle);
    if (a > b)
    {
      const double limited_linear_velocity = linear_velocity * b / a;
      ROS_WARN_NAMED("limit", "linear velocity (%f) exceeded maximum (%f) due to angular velocity constraint and was"
                              " limited", linear_velocity, limited_linear_velocity);
      linear_velocity = limited_linear_velocity;
      angular_velocity = config_.max_velocity_angular * (linear_velocity < 0.0 ? -1.0 : 1.0)
                         * (steering_angle < 0.0 ? -1.0 : 1.0);
    }
    else
    {
      angular_velocity = linear_velocity * sin_steering_angle / (wheelbase_ * cos_steering_angle);
    }
  }

  for (const AxlePtr& axle : axles_)
  {
    const AxleConfig& axle_config = axle->getConfig();

    double axle_steering_angle = 0.0;
    if (axle_config.is_steered)
    {
      axle_steering_angle = normalizeSteeringAngle(
        std::atan2(sin_steering_angle * (axle_config.position_x - config_.icr_x), cos_steering_angle * wheelbase_));
    }

    axle->setVelocity(linear_velocity, angular_velocity, axle_steering_angle, time);
  }
}

void Vehicle::setVelocity(const geometry_msgs::Twist& velocity, const ros::Time& time)
{
  const double linear_velocity = limit(velocity.linear.x, config_.max_velocity_linear, "linear velocity");
  double angular_velocity = limit(velocity.angular.z, config_.max_velocity_angular, "angular velocity");

  if (angular_velocity != 0)
  {
    const double a = std::fabs(std::cos(config_.max_steering_angle) * wheelbase_ * angular_velocity);
    const double b = std::fabs(std::sin(config_.max_steering_angle) * linear_velocity);
    if (a > b)
    {
      const double limited_angular_velocity = angular_velocity * b / a;
      ROS_WARN_NAMED("limit", "angular velocity (%f) exceeded maximum (%f) due to steering angle constraint and was"
                              " limited", angular_velocity, limited_angular_velocity);
      angular_velocity = limited_angular_velocity;
    }
  }

  for (const AxlePtr& axle : axles_)
  {
    const AxleConfig& axle_config = axle->getConfig();

    double axle_steering_angle = 0.0;
    if (axle_config.is_steered)
    {
      axle_steering_angle = normalizeSteeringAngle(
        std::atan2((axle_config.position_x - config_.icr_x) * angular_velocity, linear_velocity));
    }

    axle->setVelocity(linear_velocity, angular_velocity, axle_steering_angle, time);
  }
}

VehicleState Vehicle::getState(const ros::Time& time) const
{
  VehicleState state;
  for (const AxlePtr& axle : axles_)
  {
    state.axle_states.emplace_back(axle->getState(time));
  }
  return state;
}

void Vehicle::getVelocity(const VehicleState& state, geometry_msgs::Twist& velocity) const
{
  if (state.axle_states.size() != axles_.size())
  {
    throw std::runtime_error("number of axle states in vehicle state differs from number of vehicle axles");
  }

  // Compute vehicle velocity using pseudo inverse of velocity constraints:
  VehicleVelocityConstraints constraints;
  for (const size_t i : boost::irange<size_t>(0, axles_.size()))
  {
    axles_.at(i)->getVelocityConstraints(state.axle_states.at(i), constraints);
  }

  Eigen::MatrixXd a(Eigen::MatrixXd::Zero(constraints.size(), 3));
  Eigen::VectorXd b(Eigen::VectorXd::Zero(constraints.size()));
  for (size_t i = 0; i < constraints.size(); ++i)
  {
    a(i, 0) = constraints[i].a_v_x;
    a(i, 1) = constraints[i].a_v_y;
    a(i, 2) = constraints[i].a_v_theta;
    b(i) = constraints[i].b;
  }

  const Eigen::Vector3d x = a.fullPivHouseholderQr().solve(b);

  velocity.linear.x = x(0);
  velocity.linear.y = x(1);
  velocity.linear.z = 0.0;
  velocity.angular.x = 0.0;
  velocity.angular.y = 0.0;
  velocity.angular.z = x(2);
}

void Vehicle::getVelocity(const VehicleState& state, ackermann_msgs::AckermannDrive& velocity) const
{
  if (state.axle_states.size() != axles_.size())
  {
    throw std::runtime_error("number of axle states in vehicle state differs from number of vehicle axles");
  }

  geometry_msgs::Twist twist;
  getVelocity(state, twist);
  velocity.speed = twist.linear.x;

  // Compute steering angle as average of axle's steering angles:
  double accumulated_steering_angle = 0;
  size_t steered_axles_count = 0;

  for (const size_t i : boost::irange<size_t>(0, axles_.size()))
  {
    const AxleState& axle_state = state.axle_states.at(i);
    if (axle_state.steering_motor_state)
    {
      const double axle_steering_angle = axle_state.steering_motor_state->position;
      const AxleConfig& axle_config = axles_.at(i)->getConfig();

      accumulated_steering_angle += normalizeSteeringAngle(std::atan2(
        std::sin(axle_steering_angle) * wheelbase_,
        std::cos(axle_steering_angle) * (axle_config.position_x - config_.icr_x)));
      ++steered_axles_count;
    }
  }

  if (steered_axles_count != 0)
  {
    velocity.steering_angle = accumulated_steering_angle / static_cast<double>(steered_axles_count);
  }
  else
  {
    velocity.steering_angle = 0.0;
  }
}

void Vehicle::getJointStates(const VehicleState& state, JointStates& joint_states) const
{
  if (state.axle_states.size() != axles_.size())
  {
    throw std::runtime_error("number of axle states in vehicle state differs from number of vehicle axles");
  }

  for (const size_t i : boost::irange<size_t>(0, axles_.size()))
  {
    axles_.at(i)->getJointStates(state.axle_states.at(i), joint_states);
  }
}

boost::optional<double> Vehicle::getSupplyVoltage()
{
  double supply_voltage = 0.0;
  int num_measurements = 0;

  for (const AxlePtr& axle : axles_)
  {
    const boost::optional<double> axle_supply_voltage = axle->getSupplyVoltage();
    if (axle_supply_voltage)
    {
      supply_voltage += *axle_supply_voltage;
      ++num_measurements;
    }
  }

  if (num_measurements != 0)
  {
    return supply_voltage / num_measurements;
  }

  return boost::none;
}

double Vehicle::limit(const double value, const double max, const char* name)
{
  const double limited_value = std::min(std::max(-max, value), max);
  if (limited_value != value)
  {
    ROS_WARN_NAMED("limit", "%s (%f) exceeded maximum (%f) and was limited", name, value, max);
  }
  return limited_value;
}
}


text:
#include "PbbamInternalConfig.h"

#include "RunMetadataParser.h"

#include <fstream>
#include <istream>
#include <stdexcept>

#include <boost/algorithm/string.hpp>

#include <pbcopper/utility/StringUtils.h>

namespace PacBio {
namespace BAM {
namespace {

std::shared_ptr<internal::DataSetElement> MakeRunMetadataElement(const pugi::xml_node& xmlNode)
{
    std::string name = xmlNode.name();
    const auto foundColon = name.find(':');
    if (foundColon != std::string::npos) {
        name = name.substr(foundColon + 1);
    }

    const internal::FromInputXml fromInputXml;
    if (name == Element::Automation) {
        return std::make_shared<Automation>(fromInputXml);
    }
    if (name == Element::AutomationParameter) {
        return std::make_shared<AutomationParameter>(fromInputXml);
    }
    if (name == Element::AutomationParameters) {
        return std::make_shared<AutomationParameters>(fromInputXml);
    }
    if (name == Element::BindingKit) {
        return std::make_shared<BindingKit>(fromInputXml);
    }
    if (name == Element::Collections) {
        return std::make_shared<Collections>(fromInputXml);
    }
    if (name == Element::ControlKit) {
        return std::make_shared<ControlKit>(fromInputXml);
    }
    if (name == Element::SequencingKitPlate) {
        return std::make_shared<SequencingKitPlate>(fromInputXml);
    }
    if (name == Element::TemplatePrepKit) {
        return std::make_shared<TemplatePrepKit>(fromInputXml);
    }

    return std::make_shared<internal::DataSetElement>(name, internal::FromInputXml{});
}

void FromRunMetadataXml(const pugi::xml_node& xmlNode, internal::DataSetElement& parent)
{
    const std::string label = xmlNode.name();
    if (label.empty()) {
        return;
    }

    auto e = MakeRunMetadataElement(xmlNode);
    e->Label(xmlNode.name());
    e->Text(xmlNode.text().get());

    // iterate attributes
    auto attrIter = xmlNode.attributes_begin();
    auto attrEnd = xmlNode.attributes_end();
    for (; attrIter != attrEnd; ++attrIter) {
        e->Attribute(attrIter->name(), attrIter->value());
    }

    // iterate children, recursively building up subtree
    auto childIter = xmlNode.begin();
    auto childEnd = xmlNode.end();
    for (; childIter != childEnd; ++childIter) {
        pugi::xml_node childNode = *childIter;
        FromRunMetadataXml(childNode, *e.get());
    }

    parent.AddChild(e);
}

CollectionMetadata SubreadSetCollection(const std::string& subreadSetName,
                                        const pugi::xml_node& subreadSetNode)
{
    // find & initialize CollectionMetadata from node
    const auto cmNode = subreadSetNode.child(Element::DataSetMetadata)
                            .child(Element::Collections)
                            .child(Element::CollectionMetadata);
    if (!cmNode) {
        throw std::runtime_error{"[pbbam] run metadata ERROR: XML is missing expected elements"};
    }

    CollectionMetadata cm{subreadSetName};
    cm.Label(cmNode.name());

    // load element attributes
    auto attrIter = cmNode.attributes_begin();
    auto attrEnd = cmNode.attributes_end();
    for (; attrIter != attrEnd; ++attrIter) {
        const std::string name = attrIter->name();
        const std::string value = attrIter->value();
        cm.Attribute(name, value);
    }

    // load children, recursively
    auto childIter = cmNode.begin();
    auto childEnd = cmNode.end();
    for (; childIter != childEnd; ++childIter) {
        pugi::xml_node childNode = *childIter;
        FromRunMetadataXml(childNode, cm);
    }

    return cm;
}

pugi::xml_node FetchSubreadSetsNode(const pugi::xml_document& doc)
{
    const auto rootNode = doc.document_element();
    if (!rootNode) {
        throw std::runtime_error{"[pbbam] run metadata ERROR: could not fetch XML root node"};
    }
    if (std::string{rootNode.name()} != Element::PacBioDataModel) {
        throw std::runtime_error{
            "[pbbam] run metadata ERROR: expected 'PacBioDataModel' as root node, instead "
            "found: " +
            std::string{rootNode.name()}};
    }

    const auto result = rootNode.child(Element::ExperimentContainer)
                            .child(Element::Runs)
                            .child(Element::Run)
                            .child(Element::Outputs)
                            .child(Element::SubreadSets);
    if (!result) {
        throw std::runtime_error{"[pbbam] run metadata ERROR: XML is missing expected elements"};
    }
    return result;
}

std::map<std::string, CollectionMetadata> CollectionsFromXml(std::istream& in)
{
    std::map<std::string, CollectionMetadata> collections;

    pugi::xml_document doc;
    const pugi::xml_parse_result loadResult = doc.load(in);
    if (!loadResult) {
        throw std::runtime_error{
            "[pbbam] run metadata ERROR: could not read XML document\n"
            "  reason: " +
            std::string{loadResult.description()}};
    }

    const auto subreadSetsNode = FetchSubreadSetsNode(doc);
    for (const auto& subreadSetNode : subreadSetsNode) {
        const auto& subreadSetName = subreadSetNode.attribute("Name").value();
        collections.emplace(subreadSetName, SubreadSetCollection(subreadSetName, subreadSetNode));
    }

    return collections;
}

}  // namespace

CollectionMetadata RunMetadataParser::LoadCollection(const std::string& metadataXmlFn)
{
    std::ifstream in{metadataXmlFn};
    return LoadCollection(in);
}

CollectionMetadata RunMetadataParser::LoadCollection(std::istream& in)
{
    const auto& collections = CollectionsFromXml(in);
    // enforce only a single collection
    if (collections.size() != 1) {
        throw std::runtime_error{
            "[pbbam] run metadata ERROR: expected 1 SubreadSet, instead found: " +
            std::to_string(collections.size())};
    }
    return collections.begin()->second;
}

std::map<std::string, CollectionMetadata> RunMetadataParser::LoadCollections(
    const std::string& runMetadataXmlFn)
{
    std::ifstream in{runMetadataXmlFn};
    return LoadCollections(in);
}

std::map<std::string, CollectionMetadata> RunMetadataParser::LoadCollections(std::istream& in)
{
    return CollectionsFromXml(in);
}

}  // namespace BAM
}  // namespace PacBio

max_stars_repo_name: PacificBiosciences/pbbam

max_issues_repo_name: PacificBiosciences/pbbam

max_forks_repo_name: PacificBiosciences/pbbam


text:
// Copyright DEWETRON GmbH 2020

#include "odkapi_marker_xml.h"

#include "odkuni_xpugixml.h"
#include "odkuni_string_util.h"

#include <boost/lexical_cast.hpp>

#include <algorithm>
#include <map>

namespace odk
{
    static const std::map<std::string, MarkerType> g_marker_type_map = {
        { "UNKNOWN",                UNKNOWN             },
        { "RECORDING_START",        RECORDING_START     },
        { "RECORDING_STOP",         RECORDING_STOP      },
        { "RECORDING_PAUSE",        RECORDING_PAUSE     },
        { "RECORDING_RESUME",       RECORDING_RESUME    },
        { "TRIGGER_START",          TRIGGER_START       },
        { "TRIGGER_STOP",           TRIGGER_STOP        },
        { "TRIGGER_PRETIME",        TRIGGER_PRETIME     },
        { "TRIGGER_POSTTIME",       TRIGGER_POSTTIME    },
        { "TRIGGER_ARMED",          TRIGGER_ARMED       },
        { "TRIGGER_DISARMED",       TRIGGER_DISARMED    },
        { "TEXT",                   TEXT                },
        { "SYNC_SIGNAL_LOST",       SYNC_SIGNAL_LOST    },
        { "SYNC_TIME_ERROR",        SYNC_TIME_ERROR     },
        { "SYNC_SYNC_LOST",         SYNC_SYNC_LOST      },
        { "SYNC_SYNC_ERROR",        SYNC_SYNC_ERROR     },
        { "SYNC_RESYNCED",          SYNC_RESYNCED       },
        { "TOPOLOGY_NODE_LOST",     TOPOLOGY_NODE_LOST  },
        { "STORING_START",          STORING_START       },
        { "STORING_STOP",           STORING_STOP        },
        { "ALARM",                  ALARM               },
        { "ALARM_ACK",              ALARM_ACK           },
        { "EVENT",                  EVENT               },
        { "SPLIT_START",            SPLIT_START         },
        { "SPLIT_STOP",             SPLIT_STOP          },
    };

    MarkerType getMarkerType(const std::string& marker_type)
    {
        auto it = g_marker_type_map.find(marker_type);
        return it != g_marker_type_map.end() ? it->second : UNKNOWN;
    }

    std::string toTypeString(const MarkerType tp)
    {
        const auto it = std::find_if(g_marker_type_map.begin(), g_marker_type_map.end(),
            [tp]
            (const std::pair<std::string, MarkerType> p)
            {
                return p.second == tp;
            });
        return (it != g_marker_type_map.end()) ? it->first : "";
    }

    PluginMarkerRequest::PluginMarkerRequest()
        : m_start(std::numeric_limits<double>::max())
        , m_stop(std::numeric_limits<double>::max())
    {}

    PluginMarkerRequest::PluginMarkerRequest(double start, double stop)
        : m_start(start)
        , m_stop(stop)
    {}

    bool PluginMarkerRequest::parse(const char *xml_string)
    {
        pugi::xml_document doc;
        auto status = doc.load_string(xml_string);
        if (status.status == pugi::status_ok)
        {
            try
            {
                auto marker_request_node = doc.document_element();
                auto window_node = marker_request_node.select_node("Window");
                m_start = boost::lexical_cast<double>(window_node.node().attribute("start").value());
                m_stop = boost::lexical_cast<double>(window_node.node().attribute("end").value());
            }
            catch (const boost::bad_lexical_cast&)
            {
                return false;
            }
        }
        return true;
    }

    std::string PluginMarkerRequest::generate() const
    {
        pugi::xml_document doc;
        auto marker_request_node = doc.append_child("MarkerRequest");

        auto window_node = marker_request_node.append_child("Window");

        window_node.append_attribute("start").set_value(m_start);
        window_node.append_attribute("end").set_value(m_stop);

        return xpugi::toXML(doc);
    }

    Marker::Marker()
        : m_timestamp()
        , m_type("UNKNOWN")
        , m_msg{}
        , m_desc{}
        , m_group_id{}
        , m_is_mutable(true)
    {
    }

    Marker::Marker( std::uint64_t ticks
                                     ,double frequency
                                     ,const std::string& type
                                     ,const std::string& message
                                     ,const std::string& description
                                     ,const std::string& group_id
                                     ,bool is_mutable
                                      )
        : m_timestamp(ticks, frequency)
        , m_type(type)
        , m_msg(message)
        , m_desc(description)
        , m_group_id(group_id)
        , m_is_mutable(is_mutable)
    {
    }

    bool Marker::parse(const char* xml_string)
    {
        m_timestamp = odk::Timestamp();

        pugi::xml_document doc;
        auto status = doc.load_string(xml_string);
        if (status.status == pugi::status_ok)
        {
            if (!parseMarker(doc.document_element()))
            {
                return false;
            }
            return true;
        }
        return false;
    }

    bool Marker::parseMarker(const pugi::xml_node& parent)
    {
        try
        {
            if (!odk::strequal(parent.name(), "Marker"))
            {
                return false;
            }

            if (auto type_attr = parent.attribute("type"))
            {
                m_type = type_attr.value();
            }

            if (auto ismutable_attr = parent.attribute("ismutable"))
            {
                m_is_mutable = ismutable_attr.as_bool();
            }

            auto timestamp_node = parent.child("Timestamp");
            if (timestamp_node)
            {
                m_timestamp.parseTickFrequencyAttributes(timestamp_node);
            }

            if(auto message_node = parent.child("Message"))
            {
                m_msg = message_node.child_value();
            }

            if(auto desc_node = parent.child("Description"))
            {
                m_desc = desc_node.child_value();
            }

            if(auto storage_node = parent.child("StorageGroup"))
            {
                m_group_id = storage_node.child_value();
            }

            return true;
        }
        catch (const boost::bad_lexical_cast&)
        {
            return false;
        }
    }

    std::string Marker::generate() const
    {
        pugi::xml_document doc;
        generateMarker(doc);
        return xpugi::toXML(doc);
    }

    void Marker::generateMarker(pugi::xml_node& parent) const
    {
        auto marker_node = parent.append_child("Marker");
        marker_node.append_attribute("type").set_value(m_type.c_str());
        marker_node.append_attribute("ismutable").set_value(m_is_mutable);

        auto timestamp_node = marker_node.append_child("Timestamp");
        m_timestamp.writeTickFrequencyAttributes(timestamp_node);

        if (!m_msg.empty())
        {
            auto message_node = marker_node.append_child("Message");
            message_node.append_child(pugi::node_pcdata).set_value(m_msg.c_str());
        }

        if (!m_desc.empty())
        {
            auto desc_node = marker_node.append_child("Description");
            desc_node.append_child(pugi::node_pcdata).set_value(m_desc.c_str());
        }
        if (!m_group_id.empty())
        {
            auto storage_group_node = marker_node.append_child("StorageGroup");
            storage_group_node.append_child(pugi::node_pcdata).set_value(m_group_id.c_str());
        }
    }

    MarkerList::MarkerList()
    {
    }

    bool MarkerList::parse(const char* xml_string)
    {
        pugi::xml_document doc;
        auto status = doc.load_string(xml_string);
        if (status.status != pugi::status_ok)
        {
            return false;
        }

        auto node = doc.document_element();
        if (!node)
        {
            return false;
        }

        if (!odk::strequal(node.name(), "Markers"))
        {
            return false;
        }

        for (const auto marker_node : node.children())
        {
            Marker marker;
            if(marker.parseMarker(marker_node))
            {
                m_markers.push_back(marker);
            }
        }

        return true;
    }

    std::string MarkerList::generate() const
    {
        pugi::xml_document doc;
        auto root = doc.append_child("Markers");

        for(const auto& marker : m_markers)
        {
            marker.generateMarker(root);
        }

        return xpugi::toXML(doc);
    }

}

max_stars_repo_name: HpLightcorner/OXYGEN-SDK

max_issues_repo_name: HpLightcorner/OXYGEN-SDK

max_forks_repo_name: HpLightcorner/OXYGEN-SDK