text:
//  (C) Copyright John Maddock 2005.
//  Use, modification and distribution are 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)

#ifdef TEST_STD_HEADERS
#include <random>
#else
#include <boost/tr1/random.hpp>
#endif

#include <boost/type_traits/is_arithmetic.hpp>
#include <boost/cstdint.hpp>
#include <boost/static_assert.hpp>
#include "verify_return.hpp"
#include <iostream>

template <class T>
void check_uniform(T*)
{
   typedef typename T::result_type result_type;
   BOOST_STATIC_ASSERT(::boost::is_arithmetic<result_type>::value);

   T t;
   result_type r = 0;
   verify_return_type((t.min)(), r);
   verify_return_type((t.max)(), r);
   verify_return_type(t(), r);
}

struct seed_architype
{
   typedef unsigned result_type;
   unsigned operator()()const
   {
      return 0;
   }
};

unsigned seed_proc();

class uniform_random_generator_architype
{
public:
   typedef unsigned long result_type;
   result_type operator()()
   { return 0; }
   result_type min BOOST_PREVENT_MACRO_SUBSTITUTION()const
   { return 0; }
   result_type max BOOST_PREVENT_MACRO_SUBSTITUTION()const
   { return 0; }

   static uniform_random_generator_architype& get()
   {
      static uniform_random_generator_architype r;
      return r;
   }
private:
   uniform_random_generator_architype();
   uniform_random_generator_architype(const uniform_random_generator_architype&);
   uniform_random_generator_architype& operator=(const uniform_random_generator_architype&);
};

class pseudo_random_generator_architype
{
public:
   pseudo_random_generator_architype(){}
   pseudo_random_generator_architype(const pseudo_random_generator_architype&){}
   pseudo_random_generator_architype& operator=(const pseudo_random_generator_architype&)
   { return *this; }

   typedef unsigned long result_type;
   result_type operator()()
   { return 0; }
   result_type min BOOST_PREVENT_MACRO_SUBSTITUTION()const
   { return 0; }
   result_type max BOOST_PREVENT_MACRO_SUBSTITUTION()const
   { return 0; }

   pseudo_random_generator_architype(unsigned long){}
   template <class Gen> pseudo_random_generator_architype(Gen&){}
   void seed(){}
   void seed(unsigned long){}
   template <class Gen> void seed(Gen&){}

   bool operator == (const pseudo_random_generator_architype&)const
   { return false; }
   bool operator != (const pseudo_random_generator_architype&)const
   { return false; }

#if !defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS) && !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x551))
   template<class CharT, class Traits>
   friend std::basic_ostream<CharT,Traits>&
   operator<<(std::basic_ostream<CharT,Traits>& os,
            const pseudo_random_generator_architype& lcg)
   {
      return os;
   }

   template<class CharT, class Traits>
   friend std::basic_istream<CharT,Traits>&
   operator>>(std::basic_istream<CharT,Traits>& is,
            pseudo_random_generator_architype& lcg)
   {
      return is;
   }
#endif
};

class random_distribution_architype
{
public:
   random_distribution_architype(){}
   random_distribution_architype(const random_distribution_architype&){}
   random_distribution_architype& operator=(const random_distribution_architype&)
   { return *this; }

   typedef unsigned input_type;
   typedef double result_type;

   void reset(){}

   template <class U>
   result_type operator()(U& u)
   {
      return u();
   }
#if !defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS) && !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x551))
   template<class CharT, class Traits>
   friend std::basic_ostream<CharT,Traits>&
   operator<<(std::basic_ostream<CharT,Traits>& os,
            const random_distribution_architype& lcg)
   {
      return os;
   }

   template<class CharT, class Traits>
   friend std::basic_istream<CharT,Traits>&
   operator>>(std::basic_istream<CharT,Traits>& is,
            random_distribution_architype& lcg)
   {
      return is;
   }
#endif
};

template <class T>
void check_pseudo_random(T* p)
{
   typedef typename T::result_type result_type;
   check_uniform(p);
   T t1;
   T t2(t1);
   t1 = t2;
   unsigned long s = 0;
   T t3(s);
   seed_architype seed;
   T t4(seed);
   t1.seed();
   t1.seed(s);
   t1.seed(seed);
   T t5(seed_proc);
   t1.seed(seed_proc);
   const T& x = t1;
   const T& y = t2;
   verify_return_type(x == y, true);
   verify_return_type(x == y, false);
#if !defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS) && !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x551))
   std::cout << t1;
   std::cin >> t1;
#endif
}

template <class T>
void check_random_distribution(T* pd)
{
   T t1(*pd);
   t1 = *pd;
   uniform_random_generator_architype& gen = uniform_random_generator_architype::get();
   typedef typename T::input_type input_type;
   typedef typename T::result_type result_type;
   t1.reset();
   verify_return_type(t1(gen), result_type());
   const T& ct = t1;
#if !defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS) && !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x551))
   std::cout << ct << std::endl;
   std::cin >> t1 >> std::ws;
#endif
}

template <class VG>
void check_generator(VG* g)
{
   typedef typename VG::engine_type engine_type;
   typedef typename VG::engine_value_type engine_value_type;
   typedef typename VG::distribution_type distribution_type;
   typedef typename distribution_type::input_type input_type;
   typedef typename VG::result_type result_type;
   verify_return_type((*g)(), result_type(0));
   const VG* cg = g;
   verify_return_type(&g->engine(), static_cast<engine_value_type*>(0));
   verify_return_type(&cg->engine(), static_cast<const engine_value_type*>(0));
   verify_return_type(&g->distribution(), static_cast<distribution_type*>(0));
   verify_return_type(&cg->distribution(), static_cast<const distribution_type*>(0));
}

template <class VG>
void check_generator_extended(VG* g)
{
   typedef typename VG::engine_type engine_type;
   typedef typename VG::engine_value_type engine_value_type;
   typedef typename VG::distribution_type distribution_type;
   typedef typename distribution_type::input_type input_type;
   typedef typename VG::result_type result_type;
   //verify_return_type((*g)(input_type(0)), result_type(0));
   const VG* cg = g;
   verify_return_type((cg->min)(), result_type(0));
   verify_return_type((cg->max)(), result_type(0));
}

int main()
{
   typedef std::tr1::linear_congruential< ::boost::int32_t, 16807, 0, 2147483647> lc_t;
   lc_t lc;
   BOOST_STATIC_ASSERT(lc_t::multiplier == 16807);
   BOOST_STATIC_ASSERT(lc_t::increment == 0);
   BOOST_STATIC_ASSERT(lc_t::modulus == 2147483647);
   check_pseudo_random(&lc);

   typedef std::tr1::mersenne_twister< ::boost::uint32_t,32,351,175,19,0xccab8ee7,11,7,0x31b6ab00,15,0xffe50000,17> mt11213b;
   mt11213b mt;
   check_pseudo_random(&mt);

   typedef std::tr1::subtract_with_carry< ::boost::int32_t, 24, 10, 24> sub_t;
   sub_t sub;
   check_pseudo_random(&sub);

   typedef std::tr1::subtract_with_carry_01<float, 24, 10, 24> ranlux_base_01;
   ranlux_base_01 rl1;
   check_pseudo_random(&rl1);
   typedef std::tr1::subtract_with_carry_01<double, 48, 10, 24> ranlux64_base_01;
   ranlux64_base_01 rl2;
   check_pseudo_random(&rl2);

   typedef std::tr1::discard_block< std::tr1::subtract_with_carry< ::boost::int32_t , (1<<24), 10, 24>, 223, 24> ranlux3;
   ranlux3 rl3;
   check_pseudo_random(&rl3);

   std::tr1::xor_combine<pseudo_random_generator_architype, 0, pseudo_random_generator_architype, 1> xorc;
   check_pseudo_random(&xorc);
   verify_return_type(xorc.base1(), pseudo_random_generator_architype());
   verify_return_type(xorc.base2(), pseudo_random_generator_architype());

#ifndef __SUNPRO_CC
   // we don't normally allow workarounds in here, but this
   // class is unsupported on this platform.
   std::tr1::random_device d;
   check_uniform(&d);
   verify_return_type(d.entropy(), double(0));
#endif

   uniform_random_generator_architype& gen = uniform_random_generator_architype::get();
   std::tr1::uniform_int<unsigned long> ui;
   check_random_distribution(&ui);
   typedef std::tr1::uniform_int<unsigned long>::result_type ui_r_t;
   verify_return_type((ui.min)(), ui_r_t());
   verify_return_type((ui.max)(), ui_r_t());
   //verify_return_type(ui(gen, ui_r_t()), ui_r_t());

   std::tr1::bernoulli_distribution bd;
   verify_return_type(bd.p(), double(0));
   check_random_distribution(&bd);

   std::tr1::geometric_distribution<> gd;
   verify_return_type(gd.p(), double(0));
   check_random_distribution(&gd);
   BOOST_STATIC_ASSERT((::boost::is_same<std::tr1::geometric_distribution<>::result_type, int>::value));
   BOOST_STATIC_ASSERT((::boost::is_same<std::tr1::geometric_distribution<>::input_type, double>::value));
   std::tr1::geometric_distribution<long, double> gd2(0.5);
   verify_return_type(gd2.p(), double(0));
   check_random_distribution(&gd2);
   BOOST_STATIC_ASSERT((::boost::is_same<std::tr1::geometric_distribution<long, double>::result_type, long>::value));
   BOOST_STATIC_ASSERT((::boost::is_same<std::tr1::geometric_distribution<long, double>::input_type, double>::value));

   std::tr1::poisson_distribution<> pd;
   verify_return_type(pd.mean(), double(0));
   check_random_distribution(&pd);
   BOOST_STATIC_ASSERT((::boost::is_same<std::tr1::poisson_distribution<>::result_type, int>::value));
   BOOST_STATIC_ASSERT((::boost::is_same<std::tr1::poisson_distribution<>::input_type, double>::value));
   std::tr1::poisson_distribution<long, double> pd2(0.5);
   verify_return_type(pd2.mean(), double(0));
   check_random_distribution(&pd2);
   BOOST_STATIC_ASSERT((::boost::is_same<std::tr1::poisson_distribution<long, double>::result_type, long>::value));
   BOOST_STATIC_ASSERT((::boost::is_same<std::tr1::poisson_distribution<long, double>::input_type, double>::value));

   std::tr1::binomial_distribution<> bind;
   verify_return_type(bind.p(), double(0));
   verify_return_type(bind.t(), int(0));
   check_random_distribution(&bind);
   BOOST_STATIC_ASSERT((::boost::is_same<std::tr1::binomial_distribution<>::result_type, int>::value));
   //BOOST_STATIC_ASSERT((::boost::is_same<std::tr1::binomial_distribution<>::input_type, double>::value));
   std::tr1::binomial_distribution<long, double> bind2(1, 0.5);
   verify_return_type(bind2.t(), long(0));
   check_random_distribution(&bind2);
   BOOST_STATIC_ASSERT((::boost::is_same<std::tr1::binomial_distribution<long, double>::result_type, long>::value));
   //BOOST_STATIC_ASSERT((::boost::is_same<std::tr1::binomial_distribution<long, double>::input_type, double>::value));

   std::tr1::uniform_real<> urd;
   check_random_distribution(&urd);
   BOOST_STATIC_ASSERT((::boost::is_same<std::tr1::uniform_real<>::result_type, double>::value));
   BOOST_STATIC_ASSERT((::boost::is_same<std::tr1::uniform_real<>::input_type, double>::value));
   std::tr1::uniform_real<long double> urd2(0.5L, 1.5L);
   verify_return_type((urd2.min)(), (long double)(0));
   verify_return_type((urd2.max)(), (long double)(0));
   check_random_distribution(&urd2);
   BOOST_STATIC_ASSERT((::boost::is_same<std::tr1::uniform_real<long double>::result_type, long double>::value));
   BOOST_STATIC_ASSERT((::boost::is_same<std::tr1::uniform_real<long double>::input_type, long double>::value));

   std::tr1::exponential_distribution<> exd;
   check_random_distribution(&exd);
   BOOST_STATIC_ASSERT((::boost::is_same<std::tr1::exponential_distribution<>::result_type, double>::value));
   BOOST_STATIC_ASSERT((::boost::is_same<std::tr1::exponential_distribution<>::input_type, double>::value));
   std::tr1::exponential_distribution<long double> exd2(0.5L);
   verify_return_type(exd2.lambda(), (long double)(0));
   check_random_distribution(&exd2);
   BOOST_STATIC_ASSERT((::boost::is_same<std::tr1::exponential_distribution<long double>::result_type, long double>::value));
   BOOST_STATIC_ASSERT((::boost::is_same<std::tr1::exponential_distribution<long double>::input_type, long double>::value));

   std::tr1::normal_distribution<> normd;
   check_random_distribution(&normd);
   BOOST_STATIC_ASSERT((::boost::is_same<std::tr1::normal_distribution<>::result_type, double>::value));
   BOOST_STATIC_ASSERT((::boost::is_same<std::tr1::normal_distribution<>::input_type, double>::value));
   std::tr1::normal_distribution<long double> normd2(0.5L, 0.1L);
   verify_return_type(normd2.mean(), (long double)(0));
   verify_return_type(normd2.sigma(), (long double)(0));
   check_random_distribution(&normd2);
   BOOST_STATIC_ASSERT((::boost::is_same<std::tr1::normal_distribution<long double>::result_type, long double>::value));
   BOOST_STATIC_ASSERT((::boost::is_same<std::tr1::normal_distribution<long double>::input_type, long double>::value));

   std::tr1::gamma_distribution<> gammad;
   check_random_distribution(&gammad);
   BOOST_STATIC_ASSERT((::boost::is_same<std::tr1::gamma_distribution<>::result_type, double>::value));
   BOOST_STATIC_ASSERT((::boost::is_same<std::tr1::gamma_distribution<>::input_type, double>::value));
   std::tr1::gamma_distribution<long double> gammad2(0.5L);
   verify_return_type(gammad2.alpha(), (long double)(0));
   check_random_distribution(&gammad2);
   BOOST_STATIC_ASSERT((::boost::is_same<std::tr1::gamma_distribution<long double>::result_type, long double>::value));
   BOOST_STATIC_ASSERT((::boost::is_same<std::tr1::gamma_distribution<long double>::input_type, long double>::value));

   //
   // variate_generator:
   //
   std::tr1::variate_generator<uniform_random_generator_architype&, random_distribution_architype> vg1(uniform_random_generator_architype::get(), random_distribution_architype());
   check_generator(&vg1);
   std::tr1::variate_generator<uniform_random_generator_architype&, std::tr1::uniform_int<> > vg2(uniform_random_generator_architype::get(), std::tr1::uniform_int<>());
   check_generator_extended(&vg2);
   std::tr1::variate_generator<uniform_random_generator_architype*, std::tr1::uniform_int<> > vg3(&uniform_random_generator_architype::get(), std::tr1::uniform_int<>());
   check_generator_extended(&vg3);
   return 0;
}

ext: cpp

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
// C++ headers
#include <string>
#include <cstring>

// boost headers
#include <boost/regex.hpp>
#include <boost/format.hpp>

// Root headers
#include <TH1F.h>

// CMSSW headers
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/LuminosityBlock.h"
#include "FWCore/Framework/interface/Run.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/ParameterSet/interface/ParameterSetDescription.h"
#include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h"
#include "FWCore/ParameterSet/interface/Registry.h"
#include "FWCore/ServiceRegistry/interface/Service.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "DataFormats/Provenance/interface/ProcessHistory.h"
#include "DataFormats/Common/interface/Handle.h"
#include "DataFormats/Common/interface/TriggerResults.h"
#include "DataFormats/L1TGlobal/interface/GlobalAlgBlk.h"
#include "CondFormats/DataRecord/interface/L1TUtmTriggerMenuRcd.h"
#include "CondFormats/L1TObjects/interface/L1TUtmTriggerMenu.h"
#include "HLTrigger/HLTcore/interface/HLTConfigProvider.h"
#include "DQMServices/Core/interface/DQMStore.h"
#include "DQMServices/Core/interface/DQMEDAnalyzer.h"
#include "DQMServices/Core/interface/MonitorElement.h"

// helper functions
template <typename T>
static
const T & get(const edm::Event & event, const edm::EDGetTokenT<T> & token) {
  edm::Handle<T> handle;
  event.getByToken(token, handle);
  if (not handle.isValid())
    throw * handle.whyFailed();
  return * handle.product();
}

template <typename R, typename T>
static
const T & get(const edm::EventSetup & setup) {
  edm::ESHandle<T> handle;
  setup.get<R>().get(handle);
  return * handle.product();
}

class TriggerBxMonitor : public DQMEDAnalyzer {
public:
  explicit TriggerBxMonitor(edm::ParameterSet const &);
  ~TriggerBxMonitor();

  static void fillDescriptions(edm::ConfigurationDescriptions & descriptions);

private:
  virtual void dqmBeginRun(edm::Run const &, edm::EventSetup const &) override;
  virtual void bookHistograms(DQMStore::IBooker &, edm::Run const &, edm::EventSetup const &) override;
  virtual void analyze(edm::Event const &, edm::EventSetup const &) override;

  // number of bunch crossings
  static const unsigned int s_bx_range = 3564;

  // TCDS trigger types
  // see https://twiki.cern.ch/twiki/bin/viewauth/CMS/TcdsEventRecord
  static constexpr const char * const s_tcds_trigger_types[] = {
    "Empty",           //  0 - No trigger
    "Physics",         //  1 - GT trigger
    "Calibration",     //  2 - Sequence trigger (calibration)
    "Random",          //  3 - Random trigger
    "Auxiliary",       //  4 - Auxiliary (CPM front panel NIM input) trigger
    nullptr,           //  5 - reserved
    nullptr,           //  6 - reserved
    nullptr,           //  7 - reserved
    "Cyclic",          //  8 - Cyclic trigger
    "Bunch-pattern",   //  9 - Bunch-pattern trigger
    "Software",        // 10 - Software trigger
    "TTS",             // 11 - TTS-sourced trigger
    nullptr,           // 12 - reserved
    nullptr,           // 13 - reserved
    nullptr,           // 14 - reserved
    nullptr            // 15 - reserved
  };

  // module configuration
  const edm::EDGetTokenT<GlobalAlgBlkBxCollection>  m_l1t_results;
  const edm::EDGetTokenT<edm::TriggerResults>       m_hlt_results;
  const std::string                                 m_dqm_path;

  // L1T and HLT configuration
  L1TUtmTriggerMenu const * m_l1tMenu;
  HLTConfigProvider         m_hltConfig;

  // L1T and HLT results
  TH2F *                    m_tcds_bx_all;
  TH2F *                    m_l1t_bx_all;
  TH2F *                    m_hlt_bx_all;
  std::vector<TH1F *>       m_tcds_bx;
  std::vector<TH1F *>       m_l1t_bx;
  std::vector<TH1F *>       m_hlt_bx;
};

// definition
constexpr const char * const TriggerBxMonitor::s_tcds_trigger_types[];

void TriggerBxMonitor::fillDescriptions(edm::ConfigurationDescriptions & descriptions)
{
  edm::ParameterSetDescription desc;
  desc.addUntracked<edm::InputTag>( "l1tResults", edm::InputTag("gtStage2Digis"));
  desc.addUntracked<edm::InputTag>( "hltResults", edm::InputTag("TriggerResults"));
  desc.addUntracked<std::string>(   "dqmPath",    "HLT/TriggerBx" );
  descriptions.add("triggerBxMonitor", desc);
}

TriggerBxMonitor::TriggerBxMonitor(edm::ParameterSet const & config) :
  // module configuration
  m_l1t_results( consumes<GlobalAlgBlkBxCollection>( config.getUntrackedParameter<edm::InputTag>( "l1tResults" ) ) ),
  m_hlt_results( consumes<edm::TriggerResults>(      config.getUntrackedParameter<edm::InputTag>( "hltResults" ) ) ),
  m_dqm_path(                                        config.getUntrackedParameter<std::string>(   "dqmPath" ) ),
  // L1T and HLT configuration
  m_l1tMenu(nullptr),
  m_hltConfig(),
  // L1T and HLT results
  m_tcds_bx_all(nullptr),
  m_l1t_bx_all(nullptr),
  m_hlt_bx_all(nullptr),
  m_tcds_bx(),
  m_l1t_bx(),
  m_hlt_bx()
{
}

TriggerBxMonitor::~TriggerBxMonitor()
{
}

void TriggerBxMonitor::dqmBeginRun(edm::Run const & run, edm::EventSetup const & setup)
{
  // initialise the TCDS vector
  m_tcds_bx.clear();
  m_tcds_bx.resize(sizeof(s_tcds_trigger_types) / sizeof(const char *), nullptr);

  // cache the L1 trigger menu
  m_l1tMenu = & get<L1TUtmTriggerMenuRcd, L1TUtmTriggerMenu>(setup);
  if (m_l1tMenu) {
    m_l1t_bx.clear();
    m_l1t_bx.resize(GlobalAlgBlk::maxPhysicsTriggers, nullptr);
  } else {
    edm::LogError("TriggerBxMonitor") << "failed to read the L1 menu from the EventSetup, the L1 trigger bx distribution will not be monitored";
  }

  // initialise the HLTConfigProvider
  bool changed = true;
  edm::EDConsumerBase::Labels labels;
  labelsForToken(m_hlt_results, labels);
  if (m_hltConfig.init(run, setup, labels.process, changed)) {
    m_hlt_bx.clear();
    m_hlt_bx.resize( m_hltConfig.size(), nullptr );
  } else {
    // HLTConfigProvider not initialised, skip the the HLT monitoring
    edm::LogError("TriggerBxMonitor") << "failed to initialise HLTConfigProvider, the HLT bx distribution will not be monitored";
  }
}

void TriggerBxMonitor::bookHistograms(DQMStore::IBooker & booker, edm::Run const & run, edm::EventSetup const & setup)
{
  // TCDS trigger type plots
  {
    size_t size = sizeof(s_tcds_trigger_types) / sizeof(const char *);

    // book 2D histogram to monitor all TCDS trigger types in a single plot
    booker.setCurrentFolder( m_dqm_path );
    m_tcds_bx_all = booker.book2D("TCDS Trigger Types", "TCDS Trigger Types vs. bunch crossing", s_bx_range + 1, -0.5, s_bx_range + 0.5, size, -0.5, size - 0.5)->getTH2F();

    // book the individual histograms for the known TCDS trigger types
    booker.setCurrentFolder( m_dqm_path + "/TCDS" );
    for (unsigned int i = 0; i < size; ++i) {
      if (s_tcds_trigger_types[i]) {
        m_tcds_bx.at(i) = booker.book1D(s_tcds_trigger_types[i], s_tcds_trigger_types[i], s_bx_range + 1, -0.5, s_bx_range + 0.5)->getTH1F();
        m_tcds_bx_all->GetYaxis()->SetBinLabel(i+1, s_tcds_trigger_types[i]);
      }
    }
  }

  // L1T plots
  if (m_l1tMenu) {
    // book 2D histogram to monitor all L1 triggers in a single plot
    booker.setCurrentFolder( m_dqm_path );
    m_l1t_bx_all = booker.book2D("Level 1 Triggers", "Level 1 Triggers vs. bunch crossing", s_bx_range + 1, -0.5, s_bx_range + 0.5, m_l1t_bx.size(), -0.5, m_l1t_bx.size() - 0.5)->getTH2F();

    // book the individual histograms for the L1 triggers that are included in the L1 menu
    booker.setCurrentFolder( m_dqm_path + "/L1T" );
    for (auto const & keyval: m_l1tMenu->getAlgorithmMap()) {
      unsigned int bit = keyval.second.getIndex();
      std::string const & name = (boost::format("%s (bit %d)") % keyval.first % bit).str();
      m_l1t_bx.at(bit) = booker.book1D(name, name, s_bx_range + 1, -0.5, s_bx_range + 0.5)->getTH1F();
      m_l1t_bx_all->GetYaxis()->SetBinLabel(bit+1, keyval.first.c_str());
    }
  }

  // HLT plots
  if (m_hltConfig.inited()) {
    // book 2D histogram to monitor all HLT paths in a single plot
    booker.setCurrentFolder( m_dqm_path );
    m_hlt_bx_all = booker.book2D("High Level Triggers", "High Level Triggers vs. bunch crossing", s_bx_range + 1, -0.5, s_bx_range + 0.5, m_hltConfig.size(), -0.5, m_hltConfig.size() - 0.5)->getTH2F();

    // book the individual HLT triggers histograms
    booker.setCurrentFolder( m_dqm_path + "/HLT" );
    for (unsigned int i = 0; i < m_hltConfig.size(); ++i) {
      std::string const & name = m_hltConfig.triggerName(i);
      m_hlt_bx[i] = booker.book1D(name, name, s_bx_range + 1, -0.5, s_bx_range + 0.5)->getTH1F();
      m_hlt_bx_all->GetYaxis()->SetBinLabel(i+1, name.c_str());
    }
  }
}

void TriggerBxMonitor::analyze(edm::Event const & event, edm::EventSetup const & setup)
{
  unsigned int bx = event.bunchCrossing();

  // monitor the bx distribution for the TCDS trigger types
  {
    size_t size = sizeof(s_tcds_trigger_types) / sizeof(const char *);
    unsigned int type = event.experimentType();
    if (type < size and m_tcds_bx[type])
      m_tcds_bx[type]->Fill(bx);
    m_tcds_bx_all->Fill(bx, type);
  }

  // monitor the bx distribution for the L1 triggers
  if (m_l1tMenu) {
    auto const & bxvector = get<GlobalAlgBlkBxCollection>(event, m_l1t_results);
    if (not bxvector.isEmpty(0)) {
      auto const & results = bxvector.at(0, 0);
      for (unsigned int i = 0; i < GlobalAlgBlk::maxPhysicsTriggers; ++i)
        if (results.getAlgoDecisionFinal(i)) {
          if (m_l1t_bx[i])
            m_l1t_bx[i]->Fill(bx);
          m_l1t_bx_all->Fill(bx, i);
        }
    }
  }

  // monitor the bx distribution for the HLT triggers
  if (m_hltConfig.inited()) {
    auto const & hltResults = get<edm::TriggerResults>(event, m_hlt_results);
    if (hltResults.size() == m_hlt_bx.size()) {
      for (unsigned int i = 0; i < m_hlt_bx.size(); ++i) {
        if (hltResults.at(i).accept()) {
          m_hlt_bx[i]->Fill(bx);
          m_hlt_bx_all->Fill(bx, i);
        }
      }
    } else {
      edm::LogWarning("TriggerBxMonitor") << "This should never happen: the number of HLT paths has changed since the beginning of the run";
    }
  }
}

//define this as a plug-in
#include "FWCore/Framework/interface/MakerMacros.h"
DEFINE_FWK_MODULE(TriggerBxMonitor);

ext: cc

max_stars_repo_name: pasmuss/cmssw

max_issues_repo_name: pasmuss/cmssw

max_forks_repo_name: pasmuss/cmssw


text:
/*
 Copyright (C) 2016 Quaternion Risk Management Ltd
 All rights reserved.

 This file is part of ORE, a free-software/open-source library
 for transparent pricing and risk analysis - http://opensourcerisk.org

 ORE is free software: you can redistribute it and/or modify it
 under the terms of the Modified BSD License.  You should have received a
 copy of the license along with this program.
 The license is also available online at <http://opensourcerisk.org>

 This program is distributed on the basis that it will form a useful
 contribution to risk analytics and model standardisation, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/

/*! \file orea/cube/cubewriter.hpp
    \brief A Class to write a cube out to file
    \ingroup cube
*/

#pragma once

#include <boost/shared_ptr.hpp>
#include <map>
#include <orea/cube/npvcube.hpp>
#include <string>

namespace ore {
namespace analytics {

//! Write an NPV cube to a human readable text file
/*! \ingroup cube
 */
class CubeWriter {
public:
    //! ctor
    CubeWriter(const std::string& filename);

    //! Return the filename this writer is writing too
    const std::string& filename() { return filename_; }

    //! Write a cube out to file
    void write(const boost::shared_ptr<NPVCube>& cube, const std::map<std::string, std::string>& nettingSetMap,
               bool append = false);

private:
    std::string filename_;
};
} // namespace analytics
} // namespace ore

ext: hpp

max_stars_repo_name: mrslezak/Engine

max_issues_repo_name: mrslezak/Engine

max_forks_repo_name: mrslezak/Engine


text:
// -*- Mode: C++; c-file-style: "stroustrup"; indent-tabs-mode:nil; -*-
#include "testapi.h"

#include <boost/python.hpp>

using namespace boost::python;

void (Multiplier::*factor1) () = &Multiplier::SetFactor;
void (Multiplier::*factor2) (double) = &Multiplier::SetFactor;

struct MultiplierWrap : Multiplier, wrapper<Multiplier>
{
    MultiplierWrap () : Multiplier ()
        {
        }
    MultiplierWrap (double factor) : Multiplier (factor)
        {
        }

    double Multiply (double value) const
    {
        return this->get_override("Multiply") (value);
    }

    double default_Multiply (double value) const
    {
        return this->Multiplier::Multiply (value);
    }

};

BOOST_PYTHON_MODULE(testapi_boost)
{
    def("func1", func1);
    def("func2", func2);
    def("call_virtual_from_cpp", call_virtual_from_cpp);

    class_<MultiplierWrap, boost::noncopyable>("Multiplier")
        .def(init<double>())
        .def("GetFactor", &Multiplier::GetFactor)
        .def("SetFactor", factor1)
        .def("SetFactor", factor2)
        .def("Multiply", &Multiplier::Multiply, &MultiplierWrap::default_Multiply)
        ;

}


text:
/*
  Copyright 2007 Albert Strasheim <fullung@gmail.com>

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

#include <boost/python/class.hpp>
#include <boost/python/enum.hpp>

#include <cms/Destination.h>
#include <cms/Topic.h>
#include <cms/Queue.h>
#include <cms/TemporaryTopic.h>
#include <cms/TemporaryQueue.h>

namespace py = boost::python;

using cms::Destination;
using cms::Topic;
using cms::Queue;
using cms::TemporaryTopic;
using cms::TemporaryQueue;

static const char* Destination_docstring = "A C{Destination} object encapsulates a provider-specific address.";
static const char* Destination_destinationType_docstring = "Returns the C{Destination} type for this destination.";
static const char* DestinationType_docstring = "Available L{Destination} types";
static const char* Topic_docstring = "An interface encapsulating a provider-specific topic name.";
static const char* Topic_name_docstring = "The topic name.";
static const char* Queue_docstring = "An interface encapsulating a provider-specific queue name.";
static const char* Queue_name_docstring = "The queue name.";
static const char* TemporaryTopic_docstring = "An interface encapsulating a provider-specific topic name.";
static const char* TemporaryTopic_name_docstring = "The topic name.";
static const char* TemporaryQueue_docstring = "An interface encapsulating a provider-specific queue name.";
static const char* TemporaryQueue_name_docstring = "The queue name.";

bool Destination__eq__(const Destination& self, const Destination& other)
{
    if (self.getDestinationType() != other.getDestinationType()) {
        return false;
    }
    switch (self.getDestinationType())
    {
    case Destination::TOPIC:
    {
        const Topic& selfTopic = dynamic_cast<const Topic&>(self);
        const Topic& otherTopic = dynamic_cast<const Topic&>(other);
        return selfTopic.getTopicName() == otherTopic.getTopicName();
    }
    case Destination::QUEUE:
    {
        const Queue& selfQueue = dynamic_cast<const Queue&>(self);
        const Queue& otherQueue = dynamic_cast<const Queue&>(other);
        return selfQueue.getQueueName() == otherQueue.getQueueName();
    }
    case Destination::TEMPORARY_TOPIC:
    {
        const TemporaryTopic& selfTopic =
            dynamic_cast<const TemporaryTopic&>(self);
        const TemporaryTopic& otherTopic =
            dynamic_cast<const TemporaryTopic&>(other);
        return selfTopic.getTopicName() == otherTopic.getTopicName();
    }
    case Destination::TEMPORARY_QUEUE:
    {
        const TemporaryQueue& selfQueue =
            dynamic_cast<const TemporaryQueue&>(self);
        const TemporaryQueue& otherQueue =
            dynamic_cast<const TemporaryQueue&>(other);
        return selfQueue.getQueueName() == otherQueue.getQueueName();
    }
    default:
        Py_FatalError("Failed to compare destinations");
        return false;
    }
}

void export_Destinations()
{
    py::class_<Destination, boost::noncopyable>("Destination", Destination_docstring, py::no_init)
        .add_property("destinationType", &Destination::getDestinationType, Destination_destinationType_docstring)
        .def("__eq__", Destination__eq__)
        .add_property("CMSProperties", make_function(&Destination::getCMSProperties, py::return_internal_reference<>()))
        ;

    py::enum_<Destination::DestinationType>("DestinationType")
        .value("TOPIC", Destination::TOPIC)
        .value("QUEUE", Destination::QUEUE)
        .value("TEMPORARY_TOPIC", Destination::TEMPORARY_TOPIC)
        .value("TEMPORARY_QUEUE", Destination::TEMPORARY_QUEUE)
        ;

    py::class_<Topic, py::bases<Destination>, boost::noncopyable>("Topic", Topic_docstring, py::no_init)
        .add_property("name", &Topic::getTopicName, Topic_name_docstring)
        ;

    py::class_<Queue, py::bases<Destination>, boost::noncopyable>("Queue", Queue_docstring, py::no_init)
        .add_property("name", &Queue::getQueueName, Queue_name_docstring)
        ;

    py::class_<TemporaryTopic, py::bases<Destination>, boost::noncopyable>("TemporaryTopic", TemporaryTopic_docstring, py::no_init)
        .add_property("name", &TemporaryTopic::getTopicName, TemporaryTopic_name_docstring)
        ;

    py::class_<TemporaryQueue, py::bases<Destination>, boost::noncopyable>("TemporaryQueue", TemporaryQueue_docstring, py::no_init)
        .add_property("name", &TemporaryQueue::getQueueName, TemporaryQueue_name_docstring)
        ;
}


text:
#include <boost/ut.hpp>
#include <iostream>
#include <pqrs/dispatcher.hpp>

void run_dispatcher_test(void) {
  using namespace boost::ut;
  using namespace boost::ut::literals;

  "dispatcher"_test = [] {
    std::cout << "dispatcher" << std::endl;

    auto time_source = std::make_shared<pqrs::dispatcher::pseudo_time_source>();

    {
      for (int i = 0; i < 10000; ++i) {
        pqrs::dispatcher::dispatcher d(time_source);
        d.terminate();
      }
    }

    {
      size_t count = 0;

      pqrs::dispatcher::dispatcher d(time_source);

      auto object_id = pqrs::dispatcher::make_new_object_id();
      d.attach(object_id);

      expect(d.dispatcher_thread() == false);

      auto start = std::chrono::steady_clock::now();

      for (int i = 0; i < 10000; ++i) {
        d.enqueue(
            object_id,
            [&d, &count, i] {
              ++count;
              if (i % 1000 == 0) {
                std::cout << "." << std::flush;
                std::this_thread::sleep_for(std::chrono::milliseconds(50));
              }

              expect(d.dispatcher_thread() == true);
            });
      }

      auto wait = pqrs::make_thread_wait();
      d.enqueue(
          object_id,
          [wait] {
            wait->notify();
          });
      wait->wait_notice();

      auto elapsed = std::chrono::steady_clock::now() - start;
      expect(elapsed > std::chrono::milliseconds(400));

      d.detach(object_id);
      d.terminate();
    }

    std::cout << std::endl;
  };

  "dispatcher.preserve_the_order_of_entries"_test = [] {
    std::cout << "dispatcher.preserve_the_order_of_entries" << std::endl;

    auto time_source = std::make_shared<pqrs::dispatcher::pseudo_time_source>();

    {
      std::string text;

      pqrs::dispatcher::dispatcher d(time_source);

      auto object_id = pqrs::dispatcher::make_new_object_id();
      d.attach(object_id);

      d.enqueue(
          object_id,
          [&] {
            text += "a";
          });
      d.enqueue(
          object_id,
          [&] {
            text += "b";
          });
      d.enqueue(
          object_id,
          [&] {
            text += "c";
          });

      auto wait = pqrs::make_thread_wait();
      d.enqueue(
          object_id,
          [wait] {
            wait->notify();
          });
      wait->wait_notice();

      d.detach(object_id);
      d.terminate();

      expect(text == "abc");
    }
  };

  "dispatcher.ignore_enqueue_after_terminate"_test = [] {
    std::cout << "dispatcher.ignore_enqueue_after_terminate" << std::endl;

    auto time_source = std::make_shared<pqrs::dispatcher::pseudo_time_source>();

    {
      size_t count = 0;

      pqrs::dispatcher::dispatcher d(time_source);

      auto object_id = pqrs::dispatcher::make_new_object_id();
      d.attach(object_id);

      d.terminate();

      d.enqueue(
          object_id,
          [&count] {
            ++count;
          });

      std::this_thread::sleep_for(std::chrono::milliseconds(100));

      expect(count == 0);
    }
  };
}

max_stars_repo_name: tekezo/dispatcher

max_issues_repo_name: tekezo/dispatcher

max_forks_repo_name: tekezo/dispatcher


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

#include <Eigen/Geometry>
#include <gazebo/physics/Link.hh>

namespace gazebo_server {

using Eigen::Matrix3d;
using Eigen::Quaterniond;
using Eigen::Vector3d;

void Link::GetWorldPose(Vector3d* world_p_link, Matrix3d* world_r_link) const {
  assert(world_p_link != nullptr);
  assert(world_r_link != nullptr);

  const auto world_t_link = link_->WorldPose();
  *world_p_link = {world_t_link.Pos().X(), world_t_link.Pos().Y(),
                   world_t_link.Pos().Z()};
  *world_r_link = Quaterniond(world_t_link.Rot().W(), world_t_link.Rot().X(),
                              world_t_link.Rot().Y(), world_t_link.Rot().Z())
                      .toRotationMatrix();
}
Vector3d Link::GetWorldLinearVel() const {
  const auto ret = link_->WorldLinearVel();
  return Vector3d(ret.X(), ret.Y(), ret.Z());
}
Vector3d Link::GetWorldAngularVel() const {
  const auto ret = link_->WorldAngularVel();
  return Vector3d(ret.X(), ret.Y(), ret.Z());
}
Vector3d Link::GetWorldLinearAccel() const {
  const auto ret = link_->WorldLinearAccel();
  return Vector3d(ret.X(), ret.Y(), ret.Z());
}
Vector3d Link::GetWorldAngularAccel() const {
  const auto ret = link_->WorldAngularAccel();
  return Vector3d(ret.X(), ret.Y(), ret.Z());
}

Vector3d Link::GetRelativeLinearVel() const {
  const auto ret = link_->RelativeLinearVel();
  return Vector3d(ret.X(), ret.Y(), ret.Z());
}
Vector3d Link::GetRelativeLinearAccel() const {
  const auto ret = link_->RelativeLinearAccel();
  return Vector3d(ret.X(), ret.Y(), ret.Z());
}
Vector3d Link::GetRelativeAngularVel() const {
  const auto ret = link_->RelativeAngularVel();
  return Vector3d(ret.X(), ret.Y(), ret.Z());
}
Vector3d Link::GetRelativeAngularAccel() const {
  const auto ret = link_->RelativeAngularAccel();
  return Vector3d(ret.X(), ret.Y(), ret.Z());
}

}  // namespace gazebo_server


text:
    /**
  *********************************************************************
*************************************************************************
***
*** \file  SignalHandler.cpp
*** \brief SignalHandler class body
***
*****************************************
  *****************************************
    **/

/*

  Copyright (c) 2007, Tim Burrell
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

*/

#include "SignalHandler.hpp"
#include "Debug.hpp"
#include "Exception.hpp"
#include <signal.h>
#include <boost/bind.hpp>

using namespace H;
using namespace boost;
using namespace std;

////////////////////////////////////////////////////////////////////////////
// Defines / Type Defs
///////////////////////////////////////

SignalHandler * SignalHandler::mpThis = NULL;

////////////////////////////////////////////////////////////////////////////
// Construction
///////////////////////////////////////

/**
 * \brief Default Constructor
**/
SignalHandler::SignalHandler() {
	if (mpThis)
		throw H::Exception("There can only be one SignalHandler!", __FILE__, __FUNCTION__, __LINE__);
	mpThis = this;
}

/**
 * \brief Destructor
**/
SignalHandler::~SignalHandler() {
	if (mpThis)
		mpThis = NULL;
}

////////////////////////////////////////////////////////////////////////////
// Class Body
///////////////////////////////////////

/**
 * \brief Initialize the signal handler
**/
void SignalHandler::initSignals() {
	signal(SIGINT,   signalHandler);
	signal(SIGHUP,   signalHandler);
	signal(SIGQUIT,  signalHandler);
	signal(SIGKILL,  signalHandler);
	signal(SIGTERM,  signalHandler);
	signal(SIGSTOP,  signalHandler);
}

/**
 * \brief Signal handler for SEGV
**/
void SignalHandler::onSignalSegv() {
	// override me
	cerr << "Unhandled SEGV Signal" << endl;
}

/**
 * \brief Signal handler for INT
**/
void SignalHandler::onSignalInt() {
	// override me
	cerr << "Unhandled INT Signal" << endl;
}

/**
 * \brief Signal handler for HUP
**/
void SignalHandler::onSignalHup() {
	// override me
	cerr << "Unhandled HUP Signal" << endl;
}

/**
 * \brief Signal handler for QUIT
**/
void SignalHandler::onSignalQuit() {
	// override me
	cerr << "Unhandled QUIT Signal" << endl;
}

/**
 * \brief Signal handler for KILL
**/
void SignalHandler::onSignalKill() {
	// override me
	cerr << "Unhandled KILL Signal" << endl;
}

/**
 * \brief Signal handler for TERM
**/
void SignalHandler::onSignalTerm() {
	// override me
	cerr << "Unhandled TERM Signal" << endl;
}

/**
 * \brief Signal handler for STOP
**/
void SignalHandler::onSignalStop() {
	// override me
	cerr << "Unhandled STOP Signal" << endl;
}

/**
 * \brief Signal handler for Unknown Signals
**/
void SignalHandler::onSignalUnknown(int Signal) {
	// override me
	cerr << "Unhandled Unknown Signal" << endl;
}

/**
 * \brief Signal handler
**/
void SignalHandler::signalHandler(int Signal) {
	if (!mpThis) {
		cerr << "Unhandled Signal Caught!" << endl;
		return;
	}

	switch (Signal) {
	case SIGSEGV:
		mpThis->onSignalSegv();
		break;
	case SIGINT:
		mpThis->onSignalInt();
		break;
	case SIGHUP:
		mpThis->onSignalHup();
		break;
	case SIGQUIT:
		mpThis->onSignalQuit();
		break;
	case SIGKILL:
		mpThis->onSignalKill();
		break;
	case SIGTERM:
		mpThis->onSignalTerm();
		break;
	case SIGSTOP:
		mpThis->onSignalStop();
		break;
	default:
		mpThis->onSignalUnknown(Signal);
	}

	signal(Signal, &signalHandler);
}

max_stars_repo_name: pauljeremyturner/gizmod

max_issues_repo_name: pauljeremyturner/gizmod

max_forks_repo_name: pauljeremyturner/gizmod


text:
//          Copyright Gavin Band 2008 - 2012.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#ifndef GENFILE_VCF_FORMAT_SNP_DATA_SINK_HPP
#define GENFILE_VCF_FORMAT_SNP_DATA_SINK_HPP

#include <string>
#include <set>
#include <iostream>
#include <boost/function.hpp>
#include <boost/optional.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include "genfile/SNPDataSink.hpp"

namespace genfile {
	struct VCFFormatSNPDataSink: public SNPDataSink {
	public:
		VCFFormatSNPDataSink( std::string const& filename ) ;

	public:
		void set_output_fields( std::set< std::string > const& fields ) ;

	private:
		void write_header( std::size_t number_of_samples, SampleNameGetter sample_name_getter ) const ;

		// Methods required by SNPDataSink
		operator bool() const { return m_stream_ptr->good() ; }

		void set_metadata_impl( Metadata const& metadata ) ;

		void write_variant_data_impl(
			VariantIdentifyingData const& id_data,
			VariantDataReader& data_reader,
			Info const& info
		) ;

		std::string get_spec() const ;

		void set_sample_names_impl( std::size_t number_of_samples, SampleNameGetter ) ;
		SinkPos get_stream_pos() const ;

	private:
		std::string const m_filename ;
		boost::optional< std::set< std::string > > m_output_fields ;
		CompressionType const m_compression_type ;
		std::auto_ptr< std::ostream > m_stream_ptr ;
		bool m_have_written_header ;
		std::size_t m_number_of_samples ;
		boost::ptr_vector< std::ostringstream > m_streams ;
		Metadata m_metadata ;

	private:
		void write_info( Info const& info ) ;
	} ;
}

#endif

max_stars_repo_name: CreRecombinase/qctool

max_issues_repo_name: CreRecombinase/qctool

max_forks_repo_name: gavinband/qctool


text:
#define BOOST_TEST_MODULE syntax_test
#include <boost/test/unit_test.hpp>

#include <rill/syntax_analysis/parse.hpp>

#define PASS( src )                                         \
    std::string const s = src;                              \
    auto const& ast = rill::syntax_analysis::parse( s );    \
    BOOST_CHECK( ast != nullptr );                          \

#define FAIL( src )                                         \
    std::string const s = src;                              \
    auto const& ast = rill::syntax_analysis::parse( s );    \
    BOOST_CHECK( ast == nullptr );                          \

BOOST_AUTO_TEST_SUITE( Syntax )

BOOST_AUTO_TEST_CASE( pass_test_0 )
{
    PASS( R"s(; ; /**/;)s" )
}

BOOST_AUTO_TEST_CASE( pass_test_1 )
{
    PASS( R"s(a+a;)s" )
}

BOOST_AUTO_TEST_CASE( pass_test_2 )
{
    PASS( R"s(
def test() {
}
)s" )
}

BOOST_AUTO_TEST_CASE( pass_test_3 )
{
    PASS( R"s(
def test( val a: int ) {
}
)s" )
}

BOOST_AUTO_TEST_CASE( pass_test_4 )
{
    PASS( R"s(
def test( ref a: int ) => a;
)s" )
}

BOOST_AUTO_TEST_CASE( pass_test_5 )
{
    PASS( R"s(
class test {
}
)s" )
}

BOOST_AUTO_TEST_CASE( pass_test_6 )
{
    PASS( R"s(
def main(): int
{
    val a = HogeHuga!(int, int)();
    val b: HogeHuga!(int, string) = HogeHuga!(int, string)();
    val c: HogeHuga!(void, string) = HogeHuga!(void, string)();

    return 0;
}

class HogeHuga!(T: type, U: type)
{
    def ctor()
    {
    }

    def f(): void
    {
        this.a;
    }

    val b: 32;
    val a: T;
}
)s" )
}

BOOST_AUTO_TEST_CASE( fail_test_0 )
{
    FAIL( R"s(def fg; /**/; ;/**/)s" )
}

BOOST_AUTO_TEST_CASE( fail_test_1 )
{
    FAIL( R"s(
deftest( ref a: int ) => a;
)s" )
}

BOOST_AUTO_TEST_CASE( fail_test_2 )
{
    FAIL( R"s(
classtest{}
)s" )
}

BOOST_AUTO_TEST_CASE( fail_test_3 )
{
    FAIL( R"s(
deftest( ref a: int ) => a;
deftest( ref a: int ) => a;
deftest( ref a: int ) => a;
)s" )
}

BOOST_AUTO_TEST_CASE( fail_test_4 )
{
    FAIL( R"s(
def main(): int
{
    val a = HogeHuga!(int, int)();
    val b: HogeHuga!(int, string) = HogeHuga!(int, string)();
    val c: HogeHuga!(void, string) = HogeHuga!(void, string)();

    return 0;
}

class HogeHuga!(T: type, U: type)
{
    def ctor()
    {
    }

    def f(): void
    {
        this.a;b
    }

    val b: 32;
    val a: T;
}
)s" )
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: rhysd/rill

max_issues_repo_name: rhysd/rill

max_forks_repo_name: rhysd/rill


text:
/*
 *          Copyright Andrey Semashev 2007 - 2013.
 * 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   intptr_t.hpp
 * \author Andrey Semashev
 * \date   06.05.2013
 *
 * \brief  This header is the Boost.Log library implementation, see the library documentation
 *         at http://www.boost.org/libs/log/doc/log.html.
 */

#ifndef BOOST_LOG_DETAIL_INTPTR_T_HPP_INCLUDED_
#define BOOST_LOG_DETAIL_INTPTR_T_HPP_INCLUDED_

#include <boost/cstdint.hpp>
#include <boost/log/detail/config.hpp>
#include <boost/log/detail/header.hpp>

#ifdef BOOST_LOG_HAS_PRAGMA_ONCE
#pragma once
#endif

namespace boost {

BOOST_LOG_OPEN_NAMESPACE

namespace aux {

// PGI seems to not support intptr_t/uintptr_t properly. BOOST_HAS_STDINT_H is not defined for this compiler by Boost.Config.
#if !defined(__PGIC__)

#if (defined(BOOST_WINDOWS) && !defined(_WIN32_WCE)) \
    || (defined(_XOPEN_UNIX) && (_XOPEN_UNIX+0 > 0) && !defined(__UCLIBC__)) \
    || defined(__CYGWIN__) \
    || defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) \
    || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)

typedef ::intptr_t intptr_t;
typedef ::uintptr_t uintptr_t;
#define BOOST_LOG_HAS_INTPTR_T

#elif (defined(__GNUC__) || defined(__clang__)) && defined(__INTPTR_TYPE__) && defined(__UINTPTR_TYPE__)

typedef __INTPTR_TYPE__ intptr_t;
typedef __UINTPTR_TYPE__ uintptr_t;
#define BOOST_LOG_HAS_INTPTR_T

#endif

#endif

} // namespace aux

BOOST_LOG_CLOSE_NAMESPACE // namespace log

} // namespace boost

#include <boost/log/detail/footer.hpp>

#endif // BOOST_LOG_DETAIL_INTPTR_T_HPP_INCLUDED_

max_issues_repo_name: graehl/boost

max_forks_repo_name: graehl/boost


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

#include "kmclifetime.h"
#include <votca/xtp/gnode.h>
#include <votca/tools/property.h>
#include <votca/tools/constants.h>
#include <boost/format.hpp>
#include <votca/ctp/topology.h>
#include <locale>

using namespace std;

namespace votca {
    namespace xtp {

    void KMCLifetime::Initialize( tools::Property *options) {

    std::string key = "options." + Identify();

    _insertions=options->ifExistsReturnElseThrowRuntimeError<unsigned int>(key+".numberofinsertions");
    _seed=options->ifExistsReturnElseThrowRuntimeError<int>(key+".seed");
    _numberofcharges=options->ifExistsReturnElseThrowRuntimeError<int>(key+".numberofcharges");
    _injection_name=options->ifExistsReturnElseThrowRuntimeError<std::string>(key+".injectionpattern");
    _lifetimefile=options->ifExistsReturnElseThrowRuntimeError<string>(key+".lifetimefile");

    _maxrealtime=options->ifExistsReturnElseReturnDefault<double>(key+".maxrealtime",1E10);
     _trajectoryfile=options->ifExistsReturnElseReturnDefault<std::string>(key+".trajectoryfile","trajectory.csv");
    _temperature=options->ifExistsReturnElseReturnDefault<double>(key+".temperature",300);
    _rates=options->ifExistsReturnElseReturnDefault<std::string>(key+".rates","statefile");

     std::string subkey=key+".carrierenergy";
    if (options->exists(subkey)) {
        _do_carrierenergy=options->ifExistsReturnElseReturnDefault<bool>(subkey+".run",false);
        _energy_outputfile = options->ifExistsReturnElseReturnDefault<std::string>(subkey+".outputfile","energy.tab");
         _alpha = options->ifExistsReturnElseReturnDefault<double>(subkey+".alpha",0.3);
         _outputsteps=options->ifExistsReturnElseReturnDefault<double>(subkey+".outputsteps",100);

    } else {
        _do_carrierenergy=false;
    }

    _carriertype = 2;
    cout << "carrier type:"<<CarrierInttoLongString(_carriertype) << endl;
    _field=tools::vec(0.0);

    if (_rates != "statefile" && _rates != "calculate") {
        cout << "WARNING in kmclifetime: Invalid option rates. Valid options are 'statefile' or 'calculate'. Setting it to 'statefile'." << endl;
        _rates = "statefile";
    }

    lengthdistribution = options->ifExistsReturnElseReturnDefault<double>(key+".jumplengthdist",0);
    if(lengthdistribution>0){
        dolengthdistributon=true;
    }

    return;
    }

    void KMCLifetime::ReadLifetimeFile(std::string filename){
        tools::Property xml;
        load_property_from_xml(xml, filename);
        list<tools::Property*> jobProps = xml.Select("lifetimes.site");
        if (jobProps.size()!=_nodes.size()){
            throw  runtime_error((boost::format("The number of sites in the sqlfile: %i does not match the number in the lifetimefile: %i")
                    % _nodes.size() % jobProps.size()).str());
        }

        for (list<tools::Property*> ::iterator  it = jobProps.begin(); it != jobProps.end(); ++it) {
            int site_id =(*it)->getAttribute<int>("id")-1;
            double lifetime=boost::lexical_cast<double>((*it)->value());
            bool check=false;
            for (unsigned i=0;i<_nodes.size();i++){
                if (_nodes[i]->id==site_id && !(_nodes[i]->hasdecay)){
                    _nodes[i]->AddDecayEvent(1.0/lifetime);
                    check=true;
                    break;
                }
                else if(_nodes[i]->id==site_id && _nodes[i]->hasdecay){
                    throw runtime_error((boost::format("Node %i appears twice in your list") %site_id).str());
                }

            }
            if (!check){
            throw runtime_error((boost::format("Site from file with id: %i not found in sql") %site_id).str());
            }
        }

        return;
    }

    void  KMCLifetime::RunVSSM(ctp::Topology *top) {

        int realtime_start = time(NULL);
        cout << endl << "Algorithm: VSSM for Multiple Charges with finite Lifetime" << endl;
        cout << "number of charges: " << _numberofcharges << endl;
        cout << "number of nodes: " << _nodes.size() << endl;

        if (_numberofcharges > _nodes.size()) {
            throw runtime_error("ERROR in kmclifetime: specified number of charges is greater than the number of nodes. This conflicts with single occupation.");
        }

        fstream traj;
        fstream energyfile;

        cout << "Writing trajectory to " <<  _trajectoryfile << "." << endl;
        traj.open ( _trajectoryfile.c_str(), fstream::out);
        traj << "#Simtime [s]\t Insertion\t Carrier ID\t Lifetime[s]\tSteps\t Last Segment\t x_travelled[nm]\t y_travelled[nm]\t z_travelled[nm]"<<endl;

        if(_do_carrierenergy){

            cout << "Tracking the energy of one charge carrier and exponential average with alpha=" << _alpha << " to "<<_energy_outputfile << endl;
            energyfile.open(_energy_outputfile.c_str(),fstream::out);
            energyfile << "Simtime [s]\tSteps\tCarrier ID\tEnergy_a="<<_alpha<<"[eV]"<<endl;
        }

        // Injection
        cout << endl << "injection method: " << _injectionmethod << endl;

        RandomlyCreateCharges();

        unsigned insertioncount = 0;
        unsigned long step=0;
        double simtime=0.0;

        std::vector<int> forbiddennodes;
        std::vector<int> forbiddendests;

        time_t now = time(0);
        tm* localtm = localtime(&now);
        cout << "Run started at " << asctime(localtm) << endl;

        double avlifetime=0.0;
        double meanfreepath=0.0;
        tools::vec difflength=tools::vec(0,0,0);

        double avgenergy=_carriers[0]->getCurrentEnergy();
        int     carrieridold=_carriers[0]->id;

        while (insertioncount < _insertions) {
            if ((time(NULL) - realtime_start) > _maxrealtime * 60. * 60.) {
                cout << endl << "Real time limit of " << _maxrealtime << " hours (" << int(_maxrealtime * 60 * 60 + 0.5) << " seconds) has been reached. Stopping here." << endl << endl;
                break;
            }

            double cumulated_rate = 0;

            for (unsigned int i = 0; i < _carriers.size(); i++) {
                cumulated_rate += _carriers[i]->getCurrentEscapeRate();
            }
            if (cumulated_rate == 0) { // this should not happen: no possible jumps defined for a node
                throw runtime_error("ERROR in kmclifetime: Incorrect rates in the database file. All the escape rates for the current setting are 0.");
            }
            // go forward in time
            double dt=Promotetime(cumulated_rate);

            if(_do_carrierenergy){
                bool print=false;
                if (_carriers[0]->id>carrieridold){
                    avgenergy=_carriers[0]->getCurrentEnergy();
                    print=true;
                    carrieridold=_carriers[0]->id;
                }
                else if(step%_outputsteps==0){
                    avgenergy=_alpha*_carriers[0]->getCurrentEnergy()+(1-_alpha)*avgenergy;
                    print=true;
                }
                if(print){
                    energyfile << simtime<<"\t"<<step <<"\t"<<_carriers[0]->id<<"\t"<<avgenergy<<endl;
                }
            }

            simtime += dt;
            step++;
            for (unsigned int i = 0; i < _carriers.size(); i++) {
                _carriers[i]->updateLifetime(dt);
                _carriers[i]->updateSteps(1);
                _carriers[i]->updateOccupationtime(dt);
            }

            ResetForbiddenlist(forbiddennodes);
            bool secondlevel=true;
            while (secondlevel){

                // determine which carrier will escape
                GNode* newnode=NULL;
                Chargecarrier* affectedcarrier=ChooseAffectedCarrier(cumulated_rate);

                if (CheckForbidden(affectedcarrier->getCurrentNodeId(), forbiddennodes)) {
                    continue;
                }

                // determine where it will jump to
                ResetForbiddenlist(forbiddendests);

                while (true) {
                    // LEVEL 2

                    newnode = NULL;
                    GLink* event=ChooseHoppingDest(affectedcarrier->getCurrentNode());

                    if (event->decayevent){

                        avlifetime+=affectedcarrier->getLifetime();
                        meanfreepath+=tools::abs(affectedcarrier->dr_travelled);
                        difflength+=tools::elementwiseproduct(affectedcarrier->dr_travelled,affectedcarrier->dr_travelled);
                        traj << simtime<<"\t"<<insertioncount<< "\t"<< affectedcarrier->id<<"\t"<< affectedcarrier->getLifetime()<<"\t"<<affectedcarrier->getSteps()<<"\t"<< affectedcarrier->getCurrentNodeId()+1<<"\t"<<affectedcarrier->dr_travelled.getX()<<"\t"<<affectedcarrier->dr_travelled.getY()<<"\t"<<affectedcarrier->dr_travelled.getZ()<<endl;
                        if( tools::globals::verbose &&(_insertions<1500 ||insertioncount% (_insertions/1000)==0 || insertioncount<0.001*_insertions)){
                            std::cout << "\rInsertion " << insertioncount+1<<" of "<<_insertions;
                            std::cout << std::flush;
                        }
                        RandomlyAssignCarriertoSite(affectedcarrier);
                        affectedcarrier->resetCarrier();
                        insertioncount++;
                        affectedcarrier->id=_numberofcharges-1+insertioncount;
                        secondlevel=false;
                        break;
                            }
                    else{
                    newnode = _nodes[event->destination];
                    }

                    // check after the event if this was allowed
                    if (CheckForbidden(newnode->id, forbiddendests)) {
                        continue;
                    }

                    // if the new segment is unoccupied: jump; if not: add to forbidden list and choose new hopping destination
                    if (newnode->occupied) {
                        if (CheckSurrounded(affectedcarrier->getCurrentNode(), forbiddendests)) {
                            AddtoForbiddenlist(affectedcarrier->getCurrentNodeId(), forbiddennodes);
                            break; // select new escape node (ends level 2 but without setting level1step to 1)
                        }
                        AddtoForbiddenlist(newnode->id, forbiddendests);
                        continue; // select new destination
                    } else {
                        affectedcarrier->jumpfromCurrentNodetoNode(newnode);
                        affectedcarrier->dr_travelled += event->dr;
                        AddtoJumplengthdistro(event,dt);
                        secondlevel=false;

                        break; // this ends LEVEL 2 , so that the time is updated and the next MC step started
                    }

                    // END LEVEL 2
                }
                // END LEVEL 1
            }
        }

        cout<<endl;
        cout << "Total runtime:\t\t\t\t\t"<< simtime << " s"<< endl;
        cout << "Total KMC steps:\t\t\t\t"<< step << endl;
        cout << "Average lifetime:\t\t\t\t"<<avlifetime/insertioncount<< " s"<<endl;
        cout << "Mean freepath\t l=<|r_x-r_o|> :\t\t"<<(meanfreepath/insertioncount)<< " nm"<<endl;
        cout << "Average diffusionlength\t d=sqrt(<(r_x-r_o)^2>)\t"<<sqrt(abs(difflength)/insertioncount)<< " nm"<<endl;
        cout<<endl;

        PrintJumplengthdistro();

        vector< ctp::Segment* >& seg = top->Segments();

        for (unsigned i = 0; i < seg.size(); i++) {
            double occupationprobability=_nodes[i]->occupationtime / simtime;
            seg[i]->setOcc(occupationprobability,_carriertype);
        }
        traj.close();
        if(_do_carrierenergy){
            energyfile.close();
        }
        return;
    }

    bool KMCLifetime::EvaluateFrame(ctp::Topology *top) {
        std::cout << "-----------------------------------" << std::endl;
        std::cout << "      KMCLIFETIME started" << std::endl;
        std::cout << "-----------------------------------" << std::endl << std::endl;

        // Initialise random number generator
        if (votca::tools::globals::verbose) {
            cout << endl << "Initialising random number generator" << endl;
        }
        std::srand(_seed); // srand expects any integer in order to initialise the random number generator
        _RandomVariable = new tools::Random2();
        _RandomVariable->init(rand(), rand(), rand(), rand());
        LoadGraph(top);
        ReadLifetimeFile(_lifetimefile);

        if(_rates == "calculate")
        {
           cout << "Calculating rates (i.e. rates from state file are not used)." << endl;
            InitialRates();
        }
        else
        {
            cout << "Using rates from state file." << endl;
        }
        RunVSSM(top);

        time_t now = time(0);
        tm* localtm = localtime(&now);
        std::cout << "      KMCLIFETIME finished at:" <<asctime(localtm) <<  std::endl;

        return true;
    }

    }
}

max_stars_repo_name: choudarykvsp/xtp

max_issues_repo_name: choudarykvsp/xtp

max_forks_repo_name: choudarykvsp/xtp


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

#include "qtl_allele.h"
#include "clotho/utility/clotho_strings.hpp"
#include "clotho/utility/random_generator.hpp"

#include <boost/random/uniform_real_distribution.hpp>
#include <algorithm>

namespace clotho {
namespace utility {

template < class URNG >
class random_generator< URNG, qtl_allele > : public clotho::utility::random_generator< URNG, basic_allele > {
public:
    typedef random_generator< URNG, qtl_allele >    self_type;
    typedef qtl_allele                              result_type;

    typedef typename qtl_allele::real_type real_type;
    typedef typename qtl_allele::key_type  key_type;

    typedef real_type selection_type;
    typedef real_type dominance_type;

    typedef boost::random::uniform_01< real_type > dist_type;

    typedef clotho::utility::random_generator< URNG, basic_allele >                  random_allele;
    typedef clotho::utility::random_generator< URNG, qtl_allele::weight_type >       random_traits;
    typedef typename random_traits::param_type  param_type;

    random_generator( URNG & rng, boost::property_tree::ptree & config ) :
        random_allele(rng, config )
        , m_traits( rng, config )
        , m_nTraits( 1 ) {
        parseConfig( config );
    }

    random_generator( URNG & rng, unsigned int n = 1, real_type trait_mean = 0.0, real_type trait_sigma = 1.0 ) :
        random_allele( rng )
        , m_traits(rng, trait_mean, trait_sigma)
        , m_nTraits(n) {
    }

    result_type operator()( unsigned int age = 0 ) {
        qtl_allele q;

        random_allele::generate(q, age);

        if( q.isNeutral() ) {
            // neutral alleles, by definition, do not contribute
            // to traits (phenotype)
            std::fill_n( std::back_inserter(q.m_weights), m_nTraits, 0);
        } else {
            std::generate_n( std::back_inserter(q.m_weights), m_nTraits, m_traits);
        }

        return q;
    }

protected:

    void parseConfig( boost::property_tree::ptree & config ) {
        boost::property_tree::ptree lconfig;
        lconfig = config.get_child( TRAIT_BLOCK_K, lconfig );

        m_nTraits = lconfig.get< unsigned int >( MAX_K, m_nTraits);
        lconfig.put( MAX_K, m_nTraits );
        config.put_child( TRAIT_BLOCK_K, lconfig );
    }

    random_traits   m_traits;

    unsigned int    m_nTraits;
};

}   // namespace utility {
}   // namespace clotho {

#endif  // QTL_ALLELE_GENERATOR_HPP_

max_stars_repo_name: putnampp/clotho

max_issues_repo_name: putnampp/clotho

max_forks_repo_name: putnampp/clotho


text:
/*
Copyright 2012 Cloudbase Solutions Srl
All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may 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.
*/

#pragma region Includes
#include <stdio.h>
#include <windows.h>
#include <boost/program_options.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string/join.hpp>
#include <ostream>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <regex>
#include <vector>
#include "ServiceBase.h"
#include "OpenStackService.h"
#pragma endregion

using namespace std;
using namespace boost::program_options;

struct CLIArgs
{
    wstring unitPath;
    vector<wstring> environmentFiles;
    vector<wstring> environmentFilesPShell;
    vector<wstring> environmentVars;

    vector<wstring> execStartPre;
    wstring         execStart;
    vector<wstring> execStartPost;
    wstring execStop;
    vector<wstring> execStopPost;
    wstring serviceName;
    vector<wstring> conditionArchitecture;
    vector<wstring> conditionVirtualization;
    vector<wstring> conditionHost;
    vector<wstring> conditionKernelCommandLine;
    vector<wstring> conditionKernelVersion;
    vector<wstring> conditionSecurity;
    vector<wstring> conditionCapability;
    vector<wstring> conditionACPower;
    vector<wstring> conditionNeedsUpdate;
    vector<wstring> conditionFirstBoot;
    vector<wstring> conditionPathExists;
    vector<wstring> conditionPathExistsGlob;
    vector<wstring> conditionPathIsDirectory;
    vector<wstring> conditionPathIsSymbolicLink;
    vector<wstring> conditionPathIsMountPoint;
    vector<wstring> conditionPathIsReadWrite;
    vector<wstring> conditionDirectoryNotEmpty;
    vector<wstring> conditionFileNotEmpty;
    vector<wstring> conditionFileIsExecutable;
    vector<wstring> conditionUser;
    vector<wstring> conditionGroup;
    vector<wstring> conditionControlGroupController;
    wstring logFilePath;
    wstring serviceUnit;
    wstring shellCmd_pre;
    wstring shellCmd_post;
    enum CWrapperService::ServiceType serviceType;
    vector<wstring> requisite_files;
    vector<wstring> requisite_services;
    vector<wstring> before_files;
    vector<wstring> before_services;
    vector<wstring> after_files;
    vector<wstring> after_services;
    wstring stderrOutputType;
    wstring stderrFilePath;
    wstring stdoutOutputType;
    wstring stdoutFilePath;
    enum CWrapperService::RestartAction restartAction;
    int  restartMillis;
    wstring workingDirectory;
};

CLIArgs ParseArgs(int argc, wchar_t *argv[]);
EnvMap LoadEnvVarsFromFile(const wstring& path);
EnvMap GetCurrentEnv();

std::wstring DEFAULT_LOG_DIRECTORY         = L"C:\\var\\log\\";
std::wstring DEFAULT_LOG_PATH      = L"c:\\var\\log\\system.log";

//wofstream g_logfile("c:\\var\\log\\openstackservice.log", std::ios_base::out | std::ios_base::app);

class wojournalstream unit_stderr;
class wojournalstream unit_stdout;
class wojournalstream unit_log;

class wojournalstream *logfile = &unit_log;

//wstring DEFAULT_SHELL_PRE  =  L"powershell -command \"& {";
wstring DEFAULT_SHELL_PRE  =  L"pwsh.exe -command \"& {";
wstring DEFAULT_SHELL_POST =  L" } \" ";
wstring DEFAULT_START_ACTION = L"Write-Host \"No Start Action\" ";

CWrapperService::ServiceParams params;

static int string_duration_to_millis(wstring dur)

{ int millis = 0;

*logfile << L"restart duration " << dur << std::endl;
*logfile << L"first not of " << dur.find_first_not_of(L"0123456789 ") << std::endl;

    if (dur.find_first_not_of(L"0123456789 ") == std::string::npos) {
        // Then it is just a decimal number of seconds
        millis = std::stoi(dur);
        return millis*1000;
    }
    else if (dur.find(L"ns") != std::string::npos) {
        return 1;  // We just don't resolve down to nanoseconds
    }
    else if  (dur.find(L"ms") != std::string::npos) {
        wstring millistr = dur.substr(dur.find(L"ms"));
        millis = std::stoi(millistr);
        return millis;
    }
    else if (dur.find(L"hour") != std::string::npos) {
        return -1;
    }
    else if (dur.find(L"hr") != std::string::npos) {
        return -1;
    }
    else if (dur.find(L"min") != std::string::npos) {
        wstring minutes = dur.substr(dur.find(L"min"));
        minutes = minutes.substr(minutes.find_last_of(L"012345678"));
        millis = std::stoi(minutes)*60000;
        return millis;
    }
    return -1;

}

static void EscapeForPowershell(std::wstring &cmdline)

{
    for ( size_t start = 0; start != std::string::npos; ) {
        size_t end = cmdline.find(L'\"', start);
        if (end != std::string::npos) {
             cmdline.insert(end,  L"\\`");
             end += 3;
        }
        start = end;
    }

    for ( size_t start = 0; start != std::string::npos; ) {
        size_t end = cmdline.find(L'&', start);
        if (end != std::string::npos) {
             cmdline.insert(end,  L"\\`");
             end += 3;
        }
        start = end;
    }

}

CLIArgs ParseArgs(int argc, wchar_t *argv[])
{
    CLIArgs args;

    variables_map service_unit_options;

    options_description config{ "service-unit-options" };
    config.add_options()
        ("Unit.Description", value<string>(), "Description")
        ("Unit.Requisite", wvalue<vector<wstring>>(), "Prereuqisites. If not present, stop service")
        ("Unit.Before",    wvalue<vector<wstring>>(), "Do not run service if these things exist")
        ("Unit.After",     wvalue<vector<wstring>>(), "Do not run service until these things exist")
        ("Unit.ConditionArchitecture", wvalue<vector<wstring>>(), "Evaluatate the condition and run if true")
        ("Unit.ConditionVirtualization", wvalue<vector<wstring>>(), "Evaluatate the condition and run if true")
        ("Unit.ConditionHost", wvalue<vector<wstring>>(), "Evaluatate the condition and run if true")
        ("Unit.ConditionKernelCommandLine", wvalue<vector<wstring>>(), "Evaluatate the condition and run if true")
        ("Unit.ConditionKernelVersion", wvalue<vector<wstring>>(), "Evaluatate the condition and run if true")
        ("Unit.ConditionSecurity", wvalue<vector<wstring>>(), "Evaluatate the condition and run if true")
        ("Unit.ConditionCapability", wvalue<vector<wstring>>(), "Evaluatate the condition and run if true")
        ("Unit.ConditionACPower", wvalue<vector<wstring>>(), "Evaluatate the condition and run if true")
        ("Unit.ConditionNeedsUpdate", wvalue<vector<wstring>>(), "Evaluatate the condition and run if true")
        ("Unit.ConditionFirstBoot", wvalue<vector<wstring>>(), "Evaluatate the condition and run if true")
        ("Unit.ConditionPathExists", wvalue<vector<wstring>>(), "Evaluatate the condition and run if true")
        ("Unit.ConditionPathExistsGlob", wvalue<vector<wstring>>(), "Evaluatate the condition and run if true")
        ("Unit.ConditionPathIsDirectory", wvalue<vector<wstring>>(), "Evaluatate the condition and run if true")
        ("Unit.ConditionPathIsSymbolicLink", wvalue<vector<wstring>>(), "Evaluatate the condition and run if true")
        ("Unit.ConditionPathIsMountPoint", wvalue<vector<wstring>>(), "Evaluatate the condition and run if true")
        ("Unit.ConditionPathIsReadWrite", wvalue<vector<wstring>>(), "Evaluatate the condition and run if true")
        ("Unit.ConditionDirectoryNotEmpty", wvalue<vector<wstring>>(), "Evaluatate the condition and run if true")
        ("Unit.ConditionFileNotEmpty", wvalue<vector<wstring>>(), "Evaluatate the condition and run if true")
        ("Unit.ConditionFileIsExecutable", wvalue<vector<wstring>>(), "Evaluatate the condition and run if true")
        ("Unit.ConditionUser", wvalue<vector<wstring>>(), "Evaluatate the condition and run if true")
        ("Unit.ConditionGroup", wvalue<vector<wstring>>(), "Evaluatate the condition and run if true")
        ("Unit.ConditionControlGroupController", wvalue<vector<wstring>>(), "Evaluatate the condition and run if true")
        ("Service.Type", wvalue<wstring>(), "Systemd service type")
        ("Service.Shell", wvalue<wstring>(), "Windows Extension. Shell to use for exec actions. Default is Powershell")
        ("Service.EnvironmentFile", wvalue<vector<wstring>>(), "Environment files" )
        ("Service.EnvironmentFile-PS", wvalue<vector<wstring>>(), "Environment files in powershell format" )
        ("Service.Environment", wvalue<vector<wstring>>(), "Environment Variable settings" )
        ("Service.ExecStartPre", wvalue<vector<wstring>>(), "Execute before starting service")
        ("Service.ExecStart", wvalue<wstring>(), "Execute commands at when starting service")
        ("Service.ExecStartPost", wvalue<vector<wstring>>(), "Execute after starting service")
        ("Service.ExecStop", wvalue<wstring>(), "Execute command when stopping service")
        ("Service.ExecStopPost", wvalue<vector<wstring>>(), "Execute multiple commands  after stopping service")
        ("Service.StandardOutput", wvalue<wstring>(), "standard out")
        ("Service.StandardError", wvalue<wstring>(), "standard error")
        ("Service.BusName", wvalue<wstring>(), "Systemd dbus name. Used only for resolving service type")
        ("Service.Restart", wvalue<wstring>(), "restart policy for the service")
        ("Service.RestartSec", wvalue<wstring>(), "restart policy for the service")
        ("Service.WorkingDirectory", wvalue<wstring>(), "working directory")
        ("Service.StartLimitInterval", wvalue<wstring>(), "minimum time between restarts")
        ("Service.KillSignal", wvalue<wstring>(), "signal to send process when stopping. Ignored")
        ("Service.PermissionStartOnly", wvalue<wstring>(), "not implemented")
        ("Service.SupplementaryGroups", wvalue<wstring>(), "not implemented")
        ("Service.User",       wvalue<wstring>(), "not implemented")
        ("Service.LimitNOFILE", wvalue<wstring>(), "maximum number of file handles allowed for this service Not implmenented");

    options_description desc{ "Options" };
    desc.add_options()
        ("debug", "run from the command line")
        ("service-unit", wvalue<wstring>(), "Service uses the service unit file in %SystemDrive%/etc/SystemD/active" )
        ("log-file,l", wvalue<wstring>(), "Log file containing  the redirected STD OUT and ERR of the child process")
        ("service-name", wvalue<wstring>(), "Service name");

    variables_map vm;
    auto parsed = wcommand_line_parser(argc, argv)
                .options(desc).allow_unregistered().run();
    store(parsed, vm);
    auto additionalArgs = collect_unrecognized(parsed.options, include_positional);
    notify(vm);

    if (vm.count("debug")) {
        CServiceBase::bDebug = true;
    }

*logfile << L"check for service unit" << std::endl;
    if (vm.count("service-unit")) {
        args.unitPath = vm["service-unit"].as<wstring>();
        string unit_path( args.unitPath.begin(), args.unitPath.end());
        std::ifstream service_unit_file;
        std::string service_unit_contents;
        try {

            service_unit_file.open(unit_path.c_str(), ios::in);
            if (!service_unit_file.is_open()) {
                *logfile << L"counldnt open" << std::endl;
            }

            //service_unit_contents = std::string((std::istreambuf_iterator<char>()), std::istreambuf_iterator<char>());
            char buf[256];
            service_unit_file.getline(buf, 256);

            service_unit_file.clear();
            service_unit_file.seekg(0, std::ios::beg);
        }
        catch (...) {
            *logfile << L"Problems reading" << std::endl;
        }

*logfile << L"opened service unit " << service_unit_contents.c_str() << std::endl;
        auto config_parsed = parse_config_file<char>(service_unit_file, config, true);
        store(config_parsed, service_unit_options);
        notify(service_unit_options);

        for(unsigned i = 0; i < args.unitPath.length(); i++ ) {
            if (args.unitPath[i] == '\\') {
                args.unitPath[i] = '/';
            }
        }
        int start_index = args.unitPath.rfind('/');
*logfile << L"start index = " << start_index << std::endl;
        args.serviceUnit = args.unitPath.substr(start_index+1, args.unitPath.length() - start_index);
*logfile << L"has service unit " << args.serviceUnit.c_str() << std::endl;

    *logfile << L"unit path " << args.unitPath << std::endl ;
#if 0
try {
for (auto elem : service_unit_options) {
    try {
        *logfile << "elem_name ";
        *logfile << elem.first.c_str() << std::endl;
      //  *logfile << std::wstring(elem.first.begin(), elem.first.end()) << std::endl;
    } catch(...) {
        *logfile << "bad elem_name ";
    }
}
}
catch (...) {
    *logfile << "exception but keep going" << std::endl;
}
#endif

*logfile << "zut alors!" << std::endl;
    }
    else {
        // 2do: Else derive the service name from the execStart executable
        // else give up
    }

    if (service_unit_options.count("Service.StandardOutput")) {
        args.stdoutOutputType = service_unit_options["Service.StandardOutput"].as<wstring>();

        if (args.stdoutOutputType.compare(0, 5, L"file:", 5)) {
            args.stdoutFilePath = args.stdoutOutputType.substr(0, args.stdoutOutputType.find_first_of(':')+1);
        }
    }
    else {
        args.stdoutOutputType = L"journal";
    }

    if (args.stdoutFilePath.empty()) {
        args.stdoutFilePath = DEFAULT_LOG_DIRECTORY;
        args.stdoutFilePath.append(args.serviceUnit);
        args.stdoutFilePath.append(L".stdout.log");
    }

*logfile << L"open stdoutFile outputtype = " << args.stdoutOutputType << std::endl;
*logfile << L"open stdoutFile Path = " << args.stdoutFilePath << std::endl;
    unit_stdout.open(args.stdoutOutputType, args.stdoutFilePath);

    args.stderrOutputType = L"journal";
    if ( service_unit_options.count("Service.StandardError")) {
        args.stderrOutputType = service_unit_options["Service.StandardOutput"].as<wstring>();

        if (args.stderrOutputType.compare(0, 5, L"file:", 5)) {
            args.stderrFilePath = args.stderrOutputType.substr(0, args.stderrOutputType.find_first_of(':')+1);
        }
    }
    else {
        args.stderrOutputType = L"journal";
    }

    if (args.stderrFilePath.empty()) {
        args.stderrFilePath = DEFAULT_LOG_DIRECTORY;
        args.stderrFilePath.append(args.serviceUnit);
        args.stderrFilePath.append(L".stderr.log");
    }

*logfile << "open stderrFile Path = " << args.stderrFilePath.c_str() << std::endl;
    unit_stderr.open(args.stderrOutputType, args.stderrFilePath);

*logfile << "p1" << std::endl;
    if (vm.count("log-file")) {
        args.logFilePath = vm["log-file"].as<wstring>();
        args.logFilePath.erase(remove( args.logFilePath.begin(), args.logFilePath.end(), '\"' ), args.logFilePath.end());
        args.logFilePath.erase(remove( args.logFilePath.begin(), args.logFilePath.end(), '\'' ), args.logFilePath.end());
*logfile << "p1.1 open log " << args.logFilePath << std::endl;
        unit_log.open(L"file:", args.logFilePath);
        logfile = &unit_log;
    }

*logfile << "p2" << std::endl;
    if (vm.count("service-name")) {
        args.serviceName = vm["service-name"].as<wstring>();
        args.serviceName.erase(remove( args.serviceName.begin(), args.serviceName.end(), '\"' ), args.serviceName.end());
        args.serviceName.erase(remove( args.serviceName.begin(), args.serviceName.end(), '\'' ), args.serviceName.end());
    }
*logfile << "p4" << std::endl;

    if (service_unit_options.count("Service.Type")) {

        // Convert string to enum
        if (service_unit_options["Service.Type"].as<std::wstring>().compare(L"simple") == 0) {
            args.serviceType = CWrapperService::SERVICE_TYPE_SIMPLE;
        }
        else if (service_unit_options["Service.Type"].as<std::wstring>().compare(L"forking") == 0) {
            args.serviceType = CWrapperService::SERVICE_TYPE_FORKING;
        }
        else if (service_unit_options["Service.Type"].as<std::wstring>().compare(L"oneshot") == 0) {
            args.serviceType = CWrapperService::SERVICE_TYPE_ONESHOT;
        }
        else if (service_unit_options["Service.Type"].as<std::wstring>().compare(L"dbus") == 0) {
            args.serviceType = CWrapperService::SERVICE_TYPE_DBUS;
        }
        else if (service_unit_options["Service.Type"].as<std::wstring>().compare(L"notify") == 0) {
            args.serviceType = CWrapperService::SERVICE_TYPE_NOTIFY;
        }
        else if (service_unit_options["Service.Type"].as<std::wstring>().compare(L"idle") == 0) {
            args.serviceType = CWrapperService::SERVICE_TYPE_IDLE;
        }
*logfile << "p4.1 " << args.serviceType << std::endl;
    }
    else {

        // Unit type not defined. Figure out a default
        if (service_unit_options.count("Service.BusName")) {
            args.serviceType =CWrapperService:: SERVICE_TYPE_DBUS;
        }
        else if (service_unit_options.count("Service.ExecStart")) {
            args.serviceType = CWrapperService::SERVICE_TYPE_SIMPLE;
        }
        else {
            args.serviceType = CWrapperService::SERVICE_TYPE_ONESHOT;
        }
    }

    if (service_unit_options.count("Service.Restart")) {
        if (service_unit_options["Service.Restart"].as<std::wstring>().compare(L"no") == 0) {
            args.restartAction = CWrapperService::RESTART_ACTION_NO;
        }
        else if (service_unit_options["Service.Restart"].as<std::wstring>().compare(L"always") == 0) {
            args.restartAction = CWrapperService::RESTART_ACTION_ALWAYS;
        }
        else if (service_unit_options["Service.Restart"].as<std::wstring>().compare(L"on-success") == 0) {
            args.restartAction = CWrapperService::RESTART_ACTION_ON_SUCCESS;
        }
        else if (service_unit_options["Service.Restart"].as<std::wstring>().compare(L"on-failure") == 0) {
            args.restartAction = CWrapperService::RESTART_ACTION_ON_FAILURE;
        }
        else if (service_unit_options["Service.Restart"].as<std::wstring>().compare(L"on-abnormal") == 0) {
            args.restartAction = CWrapperService::RESTART_ACTION_ON_ABNORMAL;
        }
        else if (service_unit_options["Service.Restart"].as<std::wstring>().compare(L"on-abort") == 0) {
            args.restartAction = CWrapperService::RESTART_ACTION_ON_ABORT;
        }
        else if (service_unit_options["Service.Restart"].as<std::wstring>().compare(L"on-watchdog") == 0) {
            args.restartAction = CWrapperService::RESTART_ACTION_ON_WATCHDOG;
        }
        else {
            args.restartAction = CWrapperService::RESTART_ACTION_UNDEFINED;
        }
    }
    else {
        args.restartAction = CWrapperService::RESTART_ACTION_NO;
    }

    if (service_unit_options.count("Service.WorkingDirectory")) {
        args.workingDirectory = service_unit_options["Service.Restart"].as<std::wstring>();
    }

    if (service_unit_options.count("Service.RestartSec")) {
        wstring str_sec = service_unit_options["Service.RestartSec"].as<std::wstring>();
        int millis = string_duration_to_millis(str_sec);
        args.restartMillis = millis;
    }
    else {
        args.restartMillis = 100; // From systemd.service default 100ms
    }

*logfile << "p4.1 service type " << args.serviceType << std::endl;
    if (service_unit_options.count("Unit.Requisite")) {

        // Sort into service and non service members. They require different code to check
        std::vector<std::wstring> wsv = service_unit_options["Unit.Requisite"].as<std::vector<std::wstring>>();
        for (auto ws: wsv) {
            if (ws.rfind(L".service") != std::string::npos ) {
                args.requisite_services.push_back(ws);
            }
            else if (ws.rfind(L".target") != std::string::npos ) {
                args.requisite_files.push_back(ws);
            }
        }
    }

    if (service_unit_options.count("Unit.Before")) {

        // Sort into service and non service members. They require different code to check
        std::vector<std::wstring> wsv = service_unit_options["Unit.Before"].as<std::vector<std::wstring>>();
        for (auto ws: wsv) {
            if (ws.rfind(L".service") != std::string::npos ) {
                args.before_services.push_back(ws);
            }
            else if (ws.rfind(L".target") != std::string::npos ) {
                args.before_files.push_back(ws);
            }
        }
    }

    if (service_unit_options.count("Unit.After")) {

        // Sort into service and non service members. They require different code to check
        std::vector<std::wstring> wsv = service_unit_options["Unit.After"].as<std::vector<std::wstring>>();

*logfile << "p4.4 after count = " << wsv.size() << std::endl;

        for (auto ws: wsv) {
            if (ws.rfind(L".service") != std::string::npos ) {
                args.after_services.push_back(ws);
*logfile << L"p4.5 after service  = " << ws << std::endl;
            }
            else if (ws.rfind(L".target") != std::string::npos ) {
                args.after_files.push_back(ws);
            }
        }
    }

    if (service_unit_options.count( "Unit.ConditionArchitecture")) {
        args.conditionArchitecture = service_unit_options["Unit.ConditionArchitecture"].as<std::vector<std::wstring>>();
    }
    if (service_unit_options.count( "Unit.ConditionVirtualization")) {
        args.conditionVirtualization = service_unit_options["Unit.ConditionVirtualization"].as<std::vector<std::wstring>>();
    }
    if (service_unit_options.count( "Unit.ConditionHost")) {
        args.conditionHost = service_unit_options["Unit.ConditionHost"].as<std::vector<std::wstring>>();
    }
    if (service_unit_options.count( "Unit.ConditionKernelCommandLine")) {
        args.conditionKernelCommandLine = service_unit_options["Unit.ConditionKernelCommandLine"].as<std::vector<std::wstring>>();
    }
    if (service_unit_options.count( "Unit.ConditionKernelVersion")) {
        args.conditionKernelVersion = service_unit_options["Unit.ConditionKernelVersion"].as<std::vector<std::wstring>>();
    }
    if (service_unit_options.count( "Unit.ConditionSecurity")) {
        args.conditionSecurity = service_unit_options["Unit.ConditionSecurity"].as<std::vector<std::wstring>>();
    }
    if (service_unit_options.count( "Unit.ConditionCapability")) {
        args.conditionCapability = service_unit_options["Unit.ConditionCapability"].as<std::vector<std::wstring>>();
    }
    if (service_unit_options.count( "Unit.ConditionACPower")) {
        args.conditionACPower = service_unit_options["Unit.ConditionACPower"].as<std::vector<std::wstring>>();
    }
    if (service_unit_options.count( "Unit.ConditionNeedsUpdate")) {
        args.conditionNeedsUpdate = service_unit_options["Unit.ConditionNeedsUpdate"].as<std::vector<std::wstring>>();
    }
    if (service_unit_options.count( "Unit.ConditionFirstBoot")) {
        args.conditionFirstBoot = service_unit_options["Unit.ConditionFirstBoot"].as<std::vector<std::wstring>>();
    }
    if (service_unit_options.count( "Unit.ConditionPathExists")) {
        args.conditionPathExists = service_unit_options["Unit.ConditionPathExists"].as<std::vector<std::wstring>>();
    }
    if (service_unit_options.count( "Unit.ConditionPathExistsGlob")) {
        args.conditionPathExistsGlob = service_unit_options["Unit.ConditionPathExistsGlob"].as<std::vector<std::wstring>>();
    }
    if (service_unit_options.count( "Unit.ConditionPathIsDirectory")) {
        args.conditionPathIsDirectory = service_unit_options["Unit.ConditionPathIsDirectory"].as<std::vector<std::wstring>>();
    }
    if (service_unit_options.count( "Unit.ConditionPathIsSymbolicLink")) {
        args.conditionPathIsSymbolicLink = service_unit_options["Unit.ConditionPathIsSymbolicLink"].as<std::vector<std::wstring>>();
    }
    if (service_unit_options.count( "Unit.ConditionPathIsMountPoint")) {
        args.conditionPathIsMountPoint = service_unit_options["Unit.ConditionPathIsMountPoint"].as<std::vector<std::wstring>>();
    }
    if (service_unit_options.count("Unit.ConditionPathIsReadWrite")) {
        args.conditionPathIsReadWrite = service_unit_options["Unit.ConditionPathIsReadWrite"].as<std::vector<std::wstring>>();
    }
    if (service_unit_options.count( "Unit.ConditionDirectoryNotEmpty")) {
        args.conditionDirectoryNotEmpty = service_unit_options["Unit.ConditionDirectoryNotEmpty"].as<std::vector<std::wstring>>();
    }
    if (service_unit_options.count("Unit.ConditionFileNotEmpty")) {
        args.conditionFileNotEmpty = service_unit_options["Unit.ConditionFileNotEmpty"].as<std::vector<std::wstring>>();
    }
    if (service_unit_options.count( "Unit.ConditionFileIsExecutable")) {
        args.conditionFileIsExecutable = service_unit_options["Unit.ConditionFileIsExecutable"].as<std::vector<std::wstring>>();
    }
    if (service_unit_options.count("Unit.ConditionUser")) {
        args.conditionUser = service_unit_options["Unit.ConditionUser"].as<std::vector<std::wstring>>();
    }

    if (service_unit_options.count("Unit.ConditionGroup")) {
        args.conditionGroup = service_unit_options["Unit.ConditionGroup"].as<std::vector<std::wstring>>();
    }

    if (service_unit_options.count("Unit.ConditionControlGroupController")) {
        args.conditionControlGroupController = service_unit_options["Unit.ConditionControlGroupController"].as<std::vector<std::wstring>>();
    }

    if (service_unit_options.count("Service.Shell")) {
        wstring shellname = service_unit_options["Service.Shell"].as<wstring>();
        transform(shellname.begin(), shellname.end(), shellname.begin(), tolower);
        if (shellname.compare(L"powershell") == 0) {
            args.shellCmd_pre = L"powershell -command \"& {";
            args.shellCmd_post = L" } \" ";
        }
        else if (shellname.compare(L"cmd") == 0) {
            args.shellCmd_pre = L"cmd /c \'";  // Untested. Fix if needed;
            args.shellCmd_post = L"\' ";
        }
        else if (shellname.compare(L"bash") == 0) {
            args.shellCmd_pre = L"bash -c \'";  // Untested. Fix if needed;
            args.shellCmd_post = L"\' ";
        }
        else {
            wostringstream ws;
            ws << "Unsupported shell type " << shellname << " specified in service unit "
                                            << args.serviceName << std::endl;
            throw exception(std::string(ws.str().begin(), ws.str().end()).c_str());
        }
    }
    else {
        args.shellCmd_pre = DEFAULT_SHELL_PRE;
        args.shellCmd_post = DEFAULT_SHELL_POST;
    }

    if (service_unit_options.count("Service.Environment")) {
        args.environmentVars = service_unit_options["Service.Environment"].as<vector<wstring>>();
    }

*logfile << L"service_unit_options.count(\"Service.EnvironmentFile\") " << service_unit_options.count("Service.EnvironmentFile") << std::endl;
    if (service_unit_options.count("Service.EnvironmentFile")) {
        args.environmentFiles = service_unit_options["Service.EnvironmentFile"].as<vector<wstring>>();
*logfile << L"Env file" <<std::endl;
    }

    if (service_unit_options.count("Service.EnvironmentFile-PS")) {
        args.environmentFilesPShell = service_unit_options["Service.EnvironmentFilesPS"].as<vector<wstring>>();
*logfile << L"Env file psh" <<std::endl;
    }

*logfile << "p5" << std::endl;
    if (service_unit_options.count("Service.ExecStartPre")) {
        vector<wstring> ws_vector = service_unit_options["Service.ExecStartPre"].as<vector<wstring>>();

        for (auto ws : ws_vector) {
           EscapeForPowershell(ws);
*logfile << "p5.1 exec start pre cmdline = " << ws << std::endl;
        }
        args.execStartPre = ws_vector;
    }

*logfile << "p6" << std::endl;

    if (service_unit_options.count("Service.ExecStart")) {

        args.execStart = service_unit_options["Service.ExecStart"].as<wstring>();
        EscapeForPowershell(args.execStart);
*logfile << "p6.1 execstart = " << args.execStart << std::endl;
    }

    if (service_unit_options.count("Service.ExecStartPost")) {
        vector<wstring> ws_vector = service_unit_options["Service.ExecStartPost"].as<vector<wstring>>();

        for (auto ws : ws_vector) {
            EscapeForPowershell(ws);
*logfile << "p6.2 execstartpost = " << ws << std::endl;
        }
        args.execStartPost = ws_vector;
    }

    if (service_unit_options.count("Service.ExecStop")) {
        args.execStop = service_unit_options["Service.ExecStop"].as<wstring>();
        EscapeForPowershell(args.execStop);
*logfile << "p6.1 execstop = " << args.execStop << std::endl;
    }

    if (service_unit_options.count("Service.ExecStopPost")) {
        vector<wstring> ws_vector = service_unit_options["Service.ExecStopPost"].as<vector<wstring>>();
        for (auto ws : ws_vector) {
            EscapeForPowershell(ws);
*logfile << "p6.2 execstoppost = " << ws << std::endl;
        }
        args.execStopPost = ws_vector;
    }

*logfile << "p7" << std::endl;
*logfile << L"service name " << args.serviceName << std::endl;
for (auto arg: additionalArgs ) {
*logfile << L"additionalArgs " << arg << std::endl;
}

*logfile << "p8" << std::endl;
    if(args.serviceName.empty())
        throw exception("Service name not provided");

    return args;
}

int wmain(int argc, wchar_t *argv[])
{
    try
    {
        EnvMap env;

        unit_log.open(L"file:", L"c:\\var\\log\\openstackservice.log");
        auto args = ParseArgs(argc, argv);

*logfile << L"log file name " << args.logFilePath.c_str() << std::endl;

        params.szServiceName  = args.serviceName.c_str();
        params.szShellCmdPre  = args.shellCmd_pre.c_str();
        params.szShellCmdPost = args.shellCmd_post.c_str();

        params.execStartPre = args.execStartPre;
        params.execStart      = args.execStart;
        params.execStartPost  = args.execStartPost;
        params.execStop       = args.execStop;
        params.execStopPost   = args.execStopPost;
        params.environmentFilesPS = args.environmentFilesPShell;
        params.environmentFiles   = args.environmentFiles;
        params.environmentVars    = args.environmentVars;
        params.files_before       = args.before_files;
        params.services_before    = args.before_services;
        params.files_after        = args.after_files;
        params.services_after     = args.after_services;
        params.files_requisite    = args.requisite_files;
        params.services_requisite = args.requisite_services;
        params.stdErr         = &unit_stderr;
        params.stdOut         = &unit_stdout;
        params.fCanStop       = TRUE;
        params.fCanShutdown   = TRUE;
        params.fCanPauseContinue = FALSE;

        params.conditionArchitecture = args.conditionArchitecture;
        params.conditionVirtualization = args.conditionVirtualization;
        params.conditionHost = args.conditionHost;
        params.conditionKernelCommandLine = args.conditionKernelCommandLine;
        params.conditionKernelVersion = args.conditionKernelVersion;
        params.conditionSecurity = args.conditionSecurity;
        params.conditionCapability = args.conditionCapability;
        params.conditionACPower = args.conditionACPower;
        params.conditionNeedsUpdate = args.conditionNeedsUpdate;
        params.conditionFirstBoot = args.conditionFirstBoot;
        params.conditionPathExists = args.conditionPathExists;
        params.conditionPathExistsGlob = args.conditionPathExistsGlob;
        params.conditionPathIsDirectory = args.conditionPathIsDirectory;
        params.conditionPathIsSymbolicLink = args.conditionPathIsSymbolicLink;
        params.conditionPathIsMountPoint = args.conditionPathIsMountPoint;
        params.conditionPathIsReadWrite = args.conditionPathIsReadWrite;
        params.conditionDirectoryNotEmpty = args.conditionDirectoryNotEmpty;
        params.conditionFileNotEmpty = args.conditionFileNotEmpty;
        params.conditionFileIsExecutable = args.conditionFileIsExecutable;
        params.conditionUser = args.conditionUser;
        params.conditionGroup = args.conditionGroup;
        params.conditionControlGroupController = args.conditionControlGroupController;
        params.restartAction = args.restartAction;
        params.restartMillis = args.restartMillis;
        params.workingDirectory = args.workingDirectory;

        CWrapperService service(params);
        if (!CServiceBase::Run(service))
        {
            char msg[100];
            sprintf_s(msg, "Service failed to run w/err 0x%08lx", GetLastError());
*logfile << msg << '\n';
            throw exception(msg);
        }
        if (CWrapperService::bDebug) {
            // For offline debug

            ::Sleep(10000); // Let the service start
            service.Stop();
        }

        return 0;
    }
    catch (exception &ex)
    {
*logfile << ex.what() << '\n';
        return -1;
    }

}