text:
// Copyright (c) 2008-2016 Emil Dotchevski and Reverge Studios, Inc.

// 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 UUID_3EDF999CA1C011DEBA5C8DA956D89593
#define UUID_3EDF999CA1C011DEBA5C8DA956D89593

#include <boost/qvm/assert.hpp>
#include <boost/qvm/deduce_mat.hpp>
#include <boost/qvm/enable_if.hpp>
#include <boost/qvm/inline.hpp>
#include <boost/qvm/vec_traits.hpp>

namespace boost {
namespace qvm {
////////////////////////////////////////////////

namespace qvm_detail {
template <class OriginalVector> class col_mat_ {
  col_mat_(col_mat_ const &);
  col_mat_ &operator=(col_mat_ const &);
  ~col_mat_();

public:
  template <class T> BOOST_QVM_INLINE_TRIVIAL col_mat_ &operator=(T const &x) {
    assign(*this, x);
    return *this;
  }

  template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const {
    R r;
    assign(r, *this);
    return r;
  }
};
} // namespace qvm_detail

template <class OriginalVector>
struct mat_traits<qvm_detail::col_mat_<OriginalVector>> {
  typedef qvm_detail::col_mat_<OriginalVector> this_matrix;
  typedef typename vec_traits<OriginalVector>::scalar_type scalar_type;
  static int const rows = vec_traits<OriginalVector>::dim;
  static int const cols = 1;

  template <int Row, int Col>
  static BOOST_QVM_INLINE_CRITICAL scalar_type
  read_element(this_matrix const &x) {
    BOOST_QVM_STATIC_ASSERT(Col == 0);
    BOOST_QVM_STATIC_ASSERT(Row >= 0);
    BOOST_QVM_STATIC_ASSERT(Row < rows);
    return vec_traits<OriginalVector>::template read_element<Row>(
        reinterpret_cast<OriginalVector const &>(x));
  }

  template <int Row, int Col>
  static BOOST_QVM_INLINE_CRITICAL scalar_type &write_element(this_matrix &x) {
    BOOST_QVM_STATIC_ASSERT(Col == 0);
    BOOST_QVM_STATIC_ASSERT(Row >= 0);
    BOOST_QVM_STATIC_ASSERT(Row < rows);
    return vec_traits<OriginalVector>::template write_element<Row>(
        reinterpret_cast<OriginalVector &>(x));
  }

  static BOOST_QVM_INLINE_CRITICAL scalar_type
  read_element_idx(int row, int col, this_matrix const &x) {
    BOOST_QVM_ASSERT(col == 0);
    BOOST_QVM_ASSERT(row >= 0);
    BOOST_QVM_ASSERT(row < rows);
    return vec_traits<OriginalVector>::read_element_idx(
        row, reinterpret_cast<OriginalVector const &>(x));
  }

  static BOOST_QVM_INLINE_CRITICAL scalar_type &
  write_element_idx(int row, int col, this_matrix &x) {
    BOOST_QVM_ASSERT(col == 0);
    BOOST_QVM_ASSERT(row >= 0);
    BOOST_QVM_ASSERT(row < rows);
    return vec_traits<OriginalVector>::write_element_idx(
        row, reinterpret_cast<OriginalVector &>(x));
  }
};

template <class OriginalVector, int R, int C>
struct deduce_mat<qvm_detail::col_mat_<OriginalVector>, R, C> {
  typedef mat<typename vec_traits<OriginalVector>::scalar_type, R, C> type;
};

template <class OriginalVector, int R, int C>
struct deduce_mat2<qvm_detail::col_mat_<OriginalVector>,
                   qvm_detail::col_mat_<OriginalVector>, R, C> {
  typedef mat<typename vec_traits<OriginalVector>::scalar_type, R, C> type;
};

template <class A>
typename boost::enable_if_c<is_vec<A>::value,
                            qvm_detail::col_mat_<A> const &>::type
    BOOST_QVM_INLINE_TRIVIAL
    col_mat(A const &a) {
  return reinterpret_cast<typename qvm_detail::col_mat_<A> const &>(a);
}

template <class A>
typename boost::enable_if_c<is_vec<A>::value, qvm_detail::col_mat_<A> &>::type
    BOOST_QVM_INLINE_TRIVIAL
    col_mat(A &a) {
  return reinterpret_cast<typename qvm_detail::col_mat_<A> &>(a);
}

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

namespace qvm_detail {
template <class OriginalVector> class row_mat_ {
  row_mat_(row_mat_ const &);
  row_mat_ &operator=(row_mat_ const &);
  ~row_mat_();

public:
  template <class T> BOOST_QVM_INLINE_TRIVIAL row_mat_ &operator=(T const &x) {
    assign(*this, x);
    return *this;
  }

  template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const {
    R r;
    assign(r, *this);
    return r;
  }
};
} // namespace qvm_detail

template <class OriginalVector>
struct mat_traits<qvm_detail::row_mat_<OriginalVector>> {
  typedef qvm_detail::row_mat_<OriginalVector> this_matrix;
  typedef typename vec_traits<OriginalVector>::scalar_type scalar_type;
  static int const rows = 1;
  static int const cols = vec_traits<OriginalVector>::dim;

  template <int Row, int Col>
  static BOOST_QVM_INLINE_CRITICAL scalar_type
  read_element(this_matrix const &x) {
    BOOST_QVM_STATIC_ASSERT(Row == 0);
    BOOST_QVM_STATIC_ASSERT(Col >= 0);
    BOOST_QVM_STATIC_ASSERT(Col < cols);
    return vec_traits<OriginalVector>::template read_element<Col>(
        reinterpret_cast<OriginalVector const &>(x));
  }

  template <int Row, int Col>
  static BOOST_QVM_INLINE_CRITICAL scalar_type &write_element(this_matrix &x) {
    BOOST_QVM_STATIC_ASSERT(Row == 0);
    BOOST_QVM_STATIC_ASSERT(Col >= 0);
    BOOST_QVM_STATIC_ASSERT(Col < cols);
    return vec_traits<OriginalVector>::template write_element<Col>(
        reinterpret_cast<OriginalVector &>(x));
  }

  static BOOST_QVM_INLINE_CRITICAL scalar_type
  read_element_idx(int row, int col, this_matrix const &x) {
    BOOST_QVM_ASSERT(row == 0);
    BOOST_QVM_ASSERT(col >= 0);
    BOOST_QVM_ASSERT(col < cols);
    return vec_traits<OriginalVector>::read_element_idx(
        col, reinterpret_cast<OriginalVector const &>(x));
  }

  static BOOST_QVM_INLINE_CRITICAL scalar_type &
  write_element_idx(int row, int col, this_matrix &x) {
    BOOST_QVM_ASSERT(row == 0);
    BOOST_QVM_ASSERT(col >= 0);
    BOOST_QVM_ASSERT(col < cols);
    return vec_traits<OriginalVector>::write_element_idx(
        col, reinterpret_cast<OriginalVector &>(x));
  }
};

template <class OriginalVector, int R, int C>
struct deduce_mat<qvm_detail::row_mat_<OriginalVector>, R, C> {
  typedef mat<typename vec_traits<OriginalVector>::scalar_type, R, C> type;
};

template <class OriginalVector, int R, int C>
struct deduce_mat2<qvm_detail::row_mat_<OriginalVector>,
                   qvm_detail::row_mat_<OriginalVector>, R, C> {
  typedef mat<typename vec_traits<OriginalVector>::scalar_type, R, C> type;
};

template <class A>
typename boost::enable_if_c<is_vec<A>::value,
                            qvm_detail::row_mat_<A> const &>::type
    BOOST_QVM_INLINE_TRIVIAL
    row_mat(A const &a) {
  return reinterpret_cast<typename qvm_detail::row_mat_<A> const &>(a);
}

template <class A>
typename boost::enable_if_c<is_vec<A>::value, qvm_detail::row_mat_<A> &>::type
    BOOST_QVM_INLINE_TRIVIAL
    row_mat(A &a) {
  return reinterpret_cast<typename qvm_detail::row_mat_<A> &>(a);
}

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

namespace qvm_detail {
template <class OriginalVector> class translation_mat_ {
  translation_mat_(translation_mat_ const &);
  translation_mat_ &operator=(translation_mat_ const &);
  ~translation_mat_();

public:
  template <class T>
  BOOST_QVM_INLINE_TRIVIAL translation_mat_ &operator=(T const &x) {
    assign(*this, x);
    return *this;
  }

  template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const {
    R r;
    assign(r, *this);
    return r;
  }
};

template <class M, int Row, int Col,
          bool TransCol = (Col == mat_traits<M>::cols - 1)>
struct read_translation_matat;

template <class OriginalVector, int Row, int Col, bool TransCol>
struct read_translation_matat<translation_mat_<OriginalVector>, Row, Col,
                              TransCol> {
  static BOOST_QVM_INLINE_CRITICAL
      typename mat_traits<translation_mat_<OriginalVector>>::scalar_type
      f(translation_mat_<OriginalVector> const &) {
    return scalar_traits<typename mat_traits<
        translation_mat_<OriginalVector>>::scalar_type>::value(0);
  }
};

template <class OriginalVector, int D>
struct read_translation_matat<translation_mat_<OriginalVector>, D, D, false> {
  static BOOST_QVM_INLINE_CRITICAL
      typename mat_traits<translation_mat_<OriginalVector>>::scalar_type
      f(translation_mat_<OriginalVector> const &) {
    return scalar_traits<typename mat_traits<
        translation_mat_<OriginalVector>>::scalar_type>::value(1);
  }
};

template <class OriginalVector, int D>
struct read_translation_matat<translation_mat_<OriginalVector>, D, D, true> {
  static BOOST_QVM_INLINE_CRITICAL
      typename mat_traits<translation_mat_<OriginalVector>>::scalar_type
      f(translation_mat_<OriginalVector> const &) {
    return scalar_traits<typename mat_traits<
        translation_mat_<OriginalVector>>::scalar_type>::value(1);
  }
};

template <class OriginalVector, int Row, int Col>
struct read_translation_matat<translation_mat_<OriginalVector>, Row, Col,
                              true> {
  static BOOST_QVM_INLINE_CRITICAL
      typename mat_traits<translation_mat_<OriginalVector>>::scalar_type
      f(translation_mat_<OriginalVector> const &x) {
    return vec_traits<OriginalVector>::template read_element<Row>(
        reinterpret_cast<OriginalVector const &>(x));
  }
};
} // namespace qvm_detail

template <class OriginalVector>
struct mat_traits<qvm_detail::translation_mat_<OriginalVector>> {
  typedef qvm_detail::translation_mat_<OriginalVector> this_matrix;
  typedef typename vec_traits<OriginalVector>::scalar_type scalar_type;
  static int const rows = vec_traits<OriginalVector>::dim + 1;
  static int const cols = vec_traits<OriginalVector>::dim + 1;

  template <int Row, int Col>
  static BOOST_QVM_INLINE_CRITICAL scalar_type
  read_element(this_matrix const &x) {
    BOOST_QVM_STATIC_ASSERT(Row >= 0);
    BOOST_QVM_STATIC_ASSERT(Row < rows);
    BOOST_QVM_STATIC_ASSERT(Col >= 0);
    BOOST_QVM_STATIC_ASSERT(Col < cols);
    return qvm_detail::read_translation_matat<
        qvm_detail::translation_mat_<OriginalVector>, Row, Col>::f(x);
  }

  template <int Row, int Col>
  static BOOST_QVM_INLINE_CRITICAL scalar_type &write_element(this_matrix &x) {
    BOOST_QVM_STATIC_ASSERT(Row >= 0);
    BOOST_QVM_STATIC_ASSERT(Row < rows);
    BOOST_QVM_STATIC_ASSERT(Col == cols - 1);
    BOOST_QVM_STATIC_ASSERT(Col != Row);
    return vec_traits<OriginalVector>::template write_element<Row>(
        reinterpret_cast<OriginalVector &>(x));
  }

  static BOOST_QVM_INLINE_CRITICAL scalar_type
  read_element_idx(int row, int col, this_matrix const &x) {
    BOOST_QVM_ASSERT(row >= 0);
    BOOST_QVM_ASSERT(row < rows);
    BOOST_QVM_ASSERT(col >= 0);
    BOOST_QVM_ASSERT(col < cols);
    return row == col
               ? scalar_traits<scalar_type>::value(1)
               : (col == cols - 1
                      ? vec_traits<OriginalVector>::read_element_idx(
                            row, reinterpret_cast<OriginalVector const &>(x))
                      : scalar_traits<scalar_type>::value(0));
  }

  static BOOST_QVM_INLINE_CRITICAL scalar_type &
  write_element_idx(int row, int col, this_matrix const &x) {
    BOOST_QVM_ASSERT(row >= 0);
    BOOST_QVM_ASSERT(row < rows);
    BOOST_QVM_ASSERT(col == cols - 1);
    BOOST_QVM_ASSERT(col != row);
    return vec_traits<OriginalVector>::write_element_idx(
        row, reinterpret_cast<OriginalVector &>(x));
  }
};

template <class OriginalVector, int R, int C>
struct deduce_mat<qvm_detail::translation_mat_<OriginalVector>, R, C> {
  typedef mat<typename vec_traits<OriginalVector>::scalar_type, R, C> type;
};

template <class OriginalVector, int R, int C>
struct deduce_mat2<qvm_detail::translation_mat_<OriginalVector>,
                   qvm_detail::translation_mat_<OriginalVector>, R, C> {
  typedef mat<typename vec_traits<OriginalVector>::scalar_type, R, C> type;
};

template <class A>
typename boost::enable_if_c<is_vec<A>::value,
                            qvm_detail::translation_mat_<A> const &>::type
    BOOST_QVM_INLINE_TRIVIAL
    translation_mat(A const &a) {
  return reinterpret_cast<typename qvm_detail::translation_mat_<A> const &>(a);
}

template <class A>
typename boost::enable_if_c<is_vec<A>::value,
                            qvm_detail::translation_mat_<A> &>::type
    BOOST_QVM_INLINE_TRIVIAL
    translation_mat(A &a) {
  return reinterpret_cast<typename qvm_detail::translation_mat_<A> &>(a);
}

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

namespace qvm_detail {
template <class OriginalVector> class diag_mat_ {
  diag_mat_(diag_mat_ const &);
  diag_mat_ &operator=(diag_mat_ const &);
  ~diag_mat_();

public:
  template <class T> BOOST_QVM_INLINE_TRIVIAL diag_mat_ &operator=(T const &x) {
    assign(*this, x);
    return *this;
  }

  template <class R> BOOST_QVM_INLINE_TRIVIAL operator R() const {
    R r;
    assign(r, *this);
    return r;
  }
};
} // namespace qvm_detail

template <class OriginalVector>
struct mat_traits<qvm_detail::diag_mat_<OriginalVector>> {
  typedef qvm_detail::diag_mat_<OriginalVector> this_matrix;
  typedef typename vec_traits<OriginalVector>::scalar_type scalar_type;
  static int const rows = vec_traits<OriginalVector>::dim;
  static int const cols = vec_traits<OriginalVector>::dim;

  template <int Row, int Col>
  static BOOST_QVM_INLINE_CRITICAL scalar_type
  read_element(this_matrix const &x) {
    BOOST_QVM_STATIC_ASSERT(Row >= 0);
    BOOST_QVM_STATIC_ASSERT(Row < rows);
    BOOST_QVM_STATIC_ASSERT(Col >= 0);
    BOOST_QVM_STATIC_ASSERT(Col < cols);
    return Row == Col ? vec_traits<OriginalVector>::template read_element<Row>(
                            reinterpret_cast<OriginalVector const &>(x))
                      : scalar_traits<scalar_type>::value(0);
  }

  template <int Row, int Col>
  static BOOST_QVM_INLINE_CRITICAL scalar_type &write_element(this_matrix &x) {
    BOOST_QVM_STATIC_ASSERT(Row >= 0);
    BOOST_QVM_STATIC_ASSERT(Row < rows);
    BOOST_QVM_STATIC_ASSERT(Row == Col);
    return vec_traits<OriginalVector>::template write_element<Row>(
        reinterpret_cast<OriginalVector &>(x));
  }

  static BOOST_QVM_INLINE_CRITICAL scalar_type
  read_element_idx(int row, int col, this_matrix const &x) {
    BOOST_QVM_ASSERT(row >= 0);
    BOOST_QVM_ASSERT(row < rows);
    BOOST_QVM_ASSERT(col >= 0);
    BOOST_QVM_ASSERT(col < cols);
    return row == col ? vec_traits<OriginalVector>::read_element_idx(
                            row, reinterpret_cast<OriginalVector const &>(x))
                      : scalar_traits<scalar_type>::value(0);
  }

  static BOOST_QVM_INLINE_CRITICAL scalar_type &
  write_element_idx(int row, int col, this_matrix &x) {
    BOOST_QVM_ASSERT(row >= 0);
    BOOST_QVM_ASSERT(row < rows);
    BOOST_QVM_ASSERT(row == col);
    return vec_traits<OriginalVector>::write_element_idx(
        row, reinterpret_cast<OriginalVector &>(x));
  }
};

template <class OriginalVector, int R, int C>
struct deduce_mat<qvm_detail::diag_mat_<OriginalVector>, R, C> {
  typedef mat<typename vec_traits<OriginalVector>::scalar_type, R, C> type;
};

template <class OriginalVector, int R, int C>
struct deduce_mat2<qvm_detail::diag_mat_<OriginalVector>,
                   qvm_detail::diag_mat_<OriginalVector>, R, C> {
  typedef mat<typename vec_traits<OriginalVector>::scalar_type, R, C> type;
};

template <class A>
typename boost::enable_if_c<is_vec<A>::value,
                            qvm_detail::diag_mat_<A> const &>::type
    BOOST_QVM_INLINE_TRIVIAL
    diag_mat(A const &a) {
  return reinterpret_cast<typename qvm_detail::diag_mat_<A> const &>(a);
}

template <class A>
typename boost::enable_if_c<is_vec<A>::value, qvm_detail::diag_mat_<A> &>::type
    BOOST_QVM_INLINE_TRIVIAL
    diag_mat(A &a) {
  return reinterpret_cast<typename qvm_detail::diag_mat_<A> &>(a);
}

////////////////////////////////////////////////
} // namespace qvm
} // namespace boost

#endif

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
// Copyright 2019 Hans Dembinski
//
// 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)

#include <boost/core/lightweight_test.hpp>
#include <boost/core/lightweight_test_trait.hpp>
#include <boost/histogram/detail/accumulator_traits.hpp>
#include <boost/histogram/weight.hpp>
#include <tuple>

namespace dtl = boost::histogram::detail;

int main() {
  using boost::histogram::weight_type;

  struct A1 {
    void operator()(){};
  };

  BOOST_TEST_NOT(dtl::accumulator_traits<A1>::wsupport::value);
  BOOST_TEST_TRAIT_SAME(typename dtl::accumulator_traits<A1>::args, std::tuple<>);

  struct A2 {
    void operator()(int, double) {}
  };

  BOOST_TEST_NOT(dtl::accumulator_traits<A2>::wsupport::value);
  BOOST_TEST_TRAIT_SAME(typename dtl::accumulator_traits<A2>::args,
                        std::tuple<int, double>);

  struct A3 {
    void operator()() {}
    void operator()(weight_type<int>) {}
  };

  BOOST_TEST(dtl::accumulator_traits<A3>::wsupport::value);
  BOOST_TEST_TRAIT_SAME(typename dtl::accumulator_traits<A3>::args, std::tuple<>);

  struct A4 {
    void operator()(int, double, char) {}
    void operator()(weight_type<int>, int, double, char) {}
  };

  BOOST_TEST(dtl::accumulator_traits<A4>::wsupport::value);
  BOOST_TEST_TRAIT_SAME(typename dtl::accumulator_traits<A4>::args,
                        std::tuple<int, double, char>);

  struct A5 {
    void operator()(const weight_type<int>, int) {}
  };

  BOOST_TEST(dtl::accumulator_traits<A5>::wsupport::value);
  BOOST_TEST_TRAIT_SAME(typename dtl::accumulator_traits<A5>::args, std::tuple<int>);

  struct A6 {
    void operator()(const weight_type<int>&, const int) {}
  };

  BOOST_TEST(dtl::accumulator_traits<A6>::wsupport::value);
  BOOST_TEST_TRAIT_SAME(typename dtl::accumulator_traits<A6>::args, std::tuple<int>);

  struct A7 {
    void operator()(weight_type<int>&&, int&&) {}
  };

  BOOST_TEST(dtl::accumulator_traits<A7>::wsupport::value);
  BOOST_TEST_TRAIT_SAME(typename dtl::accumulator_traits<A7>::args, std::tuple<int&&>);

  struct B {
    int operator+=(int) { return 0; }
  };

  BOOST_TEST(dtl::accumulator_traits<B>::wsupport::value);
  BOOST_TEST_TRAIT_SAME(typename dtl::accumulator_traits<B>::args, std::tuple<>);

  BOOST_TEST(dtl::accumulator_traits<int>::wsupport::value);
  BOOST_TEST_TRAIT_SAME(dtl::accumulator_traits<int>::args, std::tuple<>);

  return boost::report_errors();
}

ext: cpp


text:
/*
 * **==============================================================================
 * **
 * ** Copyright (c) Microsoft Corporation. All rights reserved. See file LICENSE
 * ** for license information.
 * **
 * **==============================================================================
 * */
#include <iostream>
#include <fstream>
#include <sstream>
#if VC_SUPPORTS_STD_FILESYSTEM
#include <filesystem> Not yet supported in vc
#endif
#include "windows.h"
#include "service_unit.h"
#include <map>
#include <boost/program_options.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string/join.hpp>

char usage[] = "usage: "\
               "  systemctl start <servicename>\n" \
               "  systemctl start <servicename>\n";

using namespace std;

wstring SystemDUnitPool::UNIT_DIRECTORY_PATH = L""; // Quasi constant
wstring SystemDUnitPool::ACTIVE_UNIT_DIRECTORY_PATH = L""; // Quasi constant
wstring SystemDUnitPool::UNIT_WORKING_DIRECTORY_PATH = L""; // Quasi constant

enum SystemCtl_Cmd {
    SYETEMCTL_CMD_DAEMON_RELOAD = 0,
    SYSTEMCTL_CMD_LIST_UNITS,
    SYSTEMCTL_CMD_LIST_SOCKETS,
    SYSTEMCTL_CMD_LIST_TIMERS,
    SYSTEMCTL_CMD_START,
    SYSTEMCTL_CMD_STOP,
    SYSTEMCTL_CMD_RELOAD,
    SYSTEMCTL_CMD_RESTART,
    SYSTEMCTL_CMD_TRY_RESTART,
    SYSTEMCTL_CMD_RELOAD_OR_RESTART,
    SYSTEMCTL_CMD_TRY_RELOAD_OR_RESTART,
    SYSTEMCTL_CMD_ISOLATE,
    SYSTEMCTL_CMD_KILL,
    SYSTEMCTL_CMD_IS_ACTIVE,
    SYSTEMCTL_CMD_IS_FAILED,
    SYSTEMCTL_CMD_STATUS,
    SYSTEMCTL_CMD_SHOW,
    SYSTEMCTL_CMD_CAT,
    SYSTEMCTL_CMD_SET_PROPERTY,
    SYSTEMCTL_CMD_HELP,
    SYSTEMCTL_CMD_RESET_FAILED,
    SYSTEMCTL_CMD_LIST_DEPENDENCIES,
    SYSTEMCTL_CMD_LIST_UNIT_FILES,
    SYSTEMCTL_CMD_ENABLE,
    SYSTEMCTL_CMD_DISABLE,
    SYSTEMCTL_CMD_REENABLE,
    SYSTEMCTL_CMD_PRESET,
    SYSTEMCTL_CMD_PRESET_ALL,
    SYSTEMCTL_CMD_IS_ENABLED,
    SYSTEMCTL_CMD_MASK,
    SYSTEMCTL_CMD_UNMASK,
    SYSTEMCTL_CMD_LINK,
    SYSTEMCTL_CMD_REVERT,
    SYSTEMCTL_CMD_ADD_WANTS,
    SYSTEMCTL_CMD_ADD_REQUIRES,
    SYSTEMCTL_CMD_EDIT,
    SYSTEMCTL_CMD_GET_DEFAULT,
    SYSTEMCTL_CMD_SET_DEFAULT,
    SYSTEMCTL_CMD_LIST_MACHINES,
    SYSTEMCTL_CMD_LIST_JOBS,
    SYSTEMCTL_CMD_CANCEL,
    SYSTEMCTL_CMD_SHOW_ENVIRONMENT,
    SYSTEMCTL_CMD_SET_ENVIRONMENT,
    SYSTEMCTL_CMD_UNSET_ENVIRONMENT,
    SYSTEMCTL_CMD_IMPORT_ENVIRONMENT,
    SYSTEMCTL_CMD_DAEMON_RELOAD,
    SYSTEMCTL_CMD_DAEMON_REEXEC,
    SYSTEMCTL_CMD_IS_SYSTEM_RUNNING,
    SYSTEMCTL_CMD_DEFAULT,
    SYSTEMCTL_CMD_RESCUE,
    SYSTEMCTL_CMD_EMERGENCY,
    SYSTEMCTL_CMD_HALT,
    SYSTEMCTL_CMD_POWEROFF,
    SYSTEMCTL_CMD_REBOOT,
    SYSTEMCTL_CMD_KEXEC,
    SYSTEMCTL_CMD_EXIT,
    SYSTEMCTL_CMD_SWITCH_ROOT,
    SYSTEMCTL_CMD_SUSPEND,
    SYSTEMCTL_CMD_HIBERNATE,
    SYSTEMCTL_CMD_HYBRID_SLEEP
};

int SystemCtrl_Cmd_List_Units( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_List_Sockets( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_List_Timers( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Start( boost::program_options::variables_map &vm )
{
   wstring usage = L"usage: Systemctl start <unitname>[ unitname .. unitname]\n";

    vector<wstring> units = vm["system_units"].as<vector<wstring>>();
    if (units.empty()) {
        // Complain and exit
        wcerr << "No unit specified\n";
         wcerr << usage.c_str();
         exit(1);
    }

    for (wstring unitname: units) {

        if (unitname.rfind(L".service") == string::npos &&
            unitname.rfind(L".target")  == string::npos &&
            unitname.rfind(L".timer")   == string::npos &&
            unitname.rfind(L".socket")  == string::npos ) {
              unitname.append(L".service");
        }

        class SystemDUnit *unit = SystemDUnitPool::FindUnit(unitname);
        if (!unit) {
            // Complain and exit
            wcerr << "Failed to enable unit: Unit file " << unitname.c_str() << "does not exist\n";
            wcerr << usage.c_str();
            exit(1);
        }
        unit->StartService(false); // We will add non-blocking later
    }

    return 0;
}

int SystemCtrl_Cmd_Stop( boost::program_options::variables_map &vm )
{
   wstring usage = L"usage: Systemctl stop <unitname>\n";

    vector<wstring> units = vm["system_units"].as<vector<wstring>>();
    if (units.empty()) {
        // Complain and exit
        wcerr << "No unit specified\n";
         wcerr << usage.c_str();
         exit(1);
    }

    for (wstring unitname: units) {
        if (unitname.rfind(L".service") == string::npos &&
            unitname.rfind(L".target")  == string::npos &&
            unitname.rfind(L".timer")   == string::npos &&
            unitname.rfind(L".socket")  == string::npos ) {
              unitname.append(L".service");
        }

        wcerr << L"Stop service " << unitname << std::endl;
        class SystemDUnit *unit = SystemDUnitPool::FindUnit(unitname);
        if (!unit) {
            // Complain and exit
            wcerr << "Failed to stop service: Unit file " << unitname.c_str() << "does not exist\n";
            wcerr << usage.c_str();
            exit(1);
        }
        unit->StopService(false); // We will add non-blocking later
    }
    return 0;
}

int SystemCtrl_Cmd_Reload( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Restart( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Try_Restart( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Reload_Or_Restart( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Try_Reload_Or_Restart( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Isolate( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Kill( boost::program_options::variables_map &vm )

{
    wstring usage = L"usage: Systemctl kill unitname1 [unitname2 ...]\n";

    vector<wstring> units = vm["system_units"].as<vector<wstring>>();
    if (units.empty()) {
        // Complain and exit
        wcerr << "No unit specified\n";
        wcerr << usage.c_str();
        exit(1);
    }

    for (wstring unitname: units) {
        if (unitname.rfind(L".service") == string::npos) {
              unitname.append(L".service");
        }

        wstring kill_who;
        if (vm.count("kill-who")) {
            kill_who = vm["kill-who"].as<wstring>();
        }

        wstring kill_signal;
        if (vm.count("signal")) {
            kill_signal = vm["signal"].as<wstring>();
        }
        int kill_action = 0; // 2 do. Mainly reject other than SIGKILL or SIGTERM

        class SystemDUnit *unit = SystemDUnitPool::FindUnit(unitname);
        if (!unit) {
            // Complain and exit
            wcerr << "Failed to enable unit: Unit file " << unitname.c_str() << "does not exist\n";
            wcerr << usage.c_str();
            exit(1);
        }
        unit->Kill(kill_action, kill_who, false); // We will add non-blocking later
    }
    return 0;
}

int SystemCtrl_Cmd_Is_Active( boost::program_options::variables_map &vm )
{
    if (vm["system_units"].empty()) {
        // Complain and exit
        wcerr << "No unit specified\n";
        exit(1);
    }
    vector<wstring> units = vm["system_units"].as<vector<wstring>>();
    if (units.size() > 1) {
        wcerr << "One unit only\n";
        exit(2);
    }

    for (wstring unitname: units) {
        SystemDUnit *unit = SystemDUnitPool::FindUnit(unitname);
        if (!unit) {
                // Complain and exit
                wcerr << "Failed to get unit file state for " << unitname.c_str() << ": No such file or directory\n";
                exit(1);
        }
        if (unit->IsActive() ) {
            wcout << L"active";
            exit(0);
        }
        else {
            wcout << L"false";
            exit(1);
        }
    }
    return 0;
}

int SystemCtrl_Cmd_Is_Failed( boost::program_options::variables_map &vm )
{
    if (vm["system_units"].empty()) {
        // Complain and exit
        wcerr << "No unit specified\n";
        exit(1);
    }
    vector<wstring> units = vm["system_units"].as<vector<wstring>>();
    if (units.size() > 1) {
        wcerr << "One unit only\n";
        exit(2);
    }

    for (wstring unitname: units) {
        SystemDUnit *unit = SystemDUnitPool::FindUnit(unitname);
        if (!unit) {
                // Complain and exit
                wcerr << "Failed to get unit file state for " << unitname.c_str() << ": No such file or directory\n";
                exit(1);
        }
        if (unit->IsFailed() ) {
            wcout << L"failed";
            exit(0);
        }
        else {
            wcout << L"false";
            exit(1);
        }
    }
    return 0;
}

int SystemCtrl_Cmd_Status( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Show( boost::program_options::variables_map &vm )
{
   wstring usage = L"usage: Systemctl show [ <unitname> ]\n";

   if (vm["system_units"].empty()) {
		g_pool->ShowGlobal();
		return 0;
   }
   vector<wstring> units = vm["system_units"].as<vector<wstring>>();
    for (wstring unitname: units) {
        if (unitname.rfind(L".service") == string::npos &&
            unitname.rfind(L".target")  == string::npos &&
            unitname.rfind(L".timer")   == string::npos &&
            unitname.rfind(L".socket")  == string::npos ) {
              unitname.append(L".service");
        }

        wcerr << L"Show service " << unitname << std::endl;
        class SystemDUnit *unit = SystemDUnitPool::FindUnit(unitname);
        if (!unit) {
            // Complain and exit
            wcerr << "Failed to show service: Unit file " << unitname.c_str() << "does not exist\n";
            wcerr << usage.c_str();
            exit(1);
        }
        unit->ShowService(); // We will add non-blocking later
    }
    return 0;
}

int SystemCtrl_Cmd_Cat( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Set_Property( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Help( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Reset_Failed( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_List_Dependencies( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_List_Unit_Files( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Enable( boost::program_options::variables_map &vm )
{
    wstring usage = L"usage: Systemctl enable <unitname>\n";

    if (vm["system_units"].empty()) {
        // Complain and exit
        wcerr << "No unit specified\n";
         wcerr << usage.c_str();
         exit(1);
    }

    vector<wstring> units = vm["system_units"].as<vector<wstring>>();
    for (wstring unitname: units) {
        // We allow a shorthand reference via just the service name, but
        // we recognise the valid file extensions if given.
        if (unitname.rfind(L".service") == string::npos &&
            unitname.rfind(L".target")  == string::npos &&
            unitname.rfind(L".timer")   == string::npos &&
            unitname.rfind(L".socket")  == string::npos ) {
              unitname.append(L".service");
        }

        wstring service_unit_path = SystemDUnitPool::UNIT_DIRECTORY_PATH+L"\\"+unitname; // We only look for service unit files in the top level directory
        class SystemDUnit *unit = SystemDUnitPool::FindUnit(unitname);
        if (!unit) {
            unit = SystemDUnitPool::ReadServiceUnit(unitname, service_unit_path);
            if (!unit) {
                // Complain and exit
                wcerr << "Failed to load unit: Unit file " << service_unit_path.c_str() << "is invalid\n";
                return -1;
           }
        }
        unit->Enable(false); // We will add non-blocking later
    }

    ::Sleep(1000);

    return 0;
}

int SystemCtrl_Cmd_Disable( boost::program_options::variables_map &vm )
{
    wstring usage = L"usage: Systemctl disable <unitname>\n";

    if (vm["system_units"].empty()) {
        // Complain and exit
        wcerr << "No unit specified\n";
         wcerr << usage.c_str();
         exit(1);
    }

    vector<wstring> units = vm["system_units"].as<vector<wstring>>();
    for (wstring unitname: units) {
        if (unitname.rfind(L".service") == string::npos) {
              unitname.append(L".service");
        }

        class SystemDUnit *unit = SystemDUnitPool::FindUnit(unitname);
        if (!unit) {
            // Complain and exit
            wcerr << "Failed to enable unit: Unit file " << unitname.c_str() << "does not exist\n";
            wcerr << usage.c_str();
            exit(1);
        }
        unit->Disable(false); // We will add non-blocking later
    }
    return 0;
}

int SystemCtrl_Cmd_Reenable( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Preset( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Preset_All( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Is_Enabled( boost::program_options::variables_map &vm )
{
    if (vm["system_units"].empty()) {
        // Complain and exit
        wcerr << "No unit specified\n";
        exit(1);
    }
    vector<wstring> units = vm["system_units"].as<vector<wstring>>();
    if (units.size() > 1) {
        wcerr << "One unit only\n";
        exit(2);
    }

    for (wstring unitname: units) {
        SystemDUnit *unit = SystemDUnitPool::FindUnit(unitname);
        if (!unit) {
                // Complain and exit
                wcerr << "Failed to get unit file state for " << unitname.c_str() << ": No such file or directory\n";
                exit(1);
        }
        if (unit->IsEnabled() ) {
            wcout << L"enabled";
            exit(0);
        }
        else {
            wcout << L"false";
            exit(1);
        }
    }
    return 0;
}

int SystemCtrl_Cmd_Mask( boost::program_options::variables_map &vm )
{
    wstring usage = L"usage: Systemctl mask <unitname>\n";

    if (vm["system_units"].empty()) {
        // Complain and exit
        wcerr << "No unit specified\n";
        exit(1);
    }
    vector<wstring> units = vm["system_units"].as<vector<wstring>>();
    if (units.size() > 1) {
        wcerr << "One unit only\n";
        exit(2);
    }

    for (wstring unitname: units) {
        if (unitname.rfind(L".service") == string::npos &&
            unitname.rfind(L".target")  == string::npos &&
            unitname.rfind(L".timer")   == string::npos &&
            unitname.rfind(L".socket")  == string::npos ) {
            unitname.append(L".service");
        }

wcerr << L"Mask unit " << unitname << std::endl;

        class SystemDUnit *unit = SystemDUnitPool::FindUnit(unitname);
        if (!unit) {
            // Complain and exit
            wcerr << "Failed to enable unit: Unit file " << unitname.c_str() << "does not exist\n";
            wcerr << usage.c_str();
            exit(1);
        }
        unit->Mask(false); // We will add non-blocking later
    }
    return 0;
}

int SystemCtrl_Cmd_Unmask( boost::program_options::variables_map &vm )
{
    wstring usage = L"usage: Systemctl unmask <unitname>\n";

    if (vm["system_units"].empty()) {
        // Complain and exit
        wcerr << "No unit specified\n";
        wcerr << usage.c_str();
        exit(1);
    }

    vector<wstring> units = vm["system_units"].as<vector<wstring>>();
    if (units.size() > 1) {
        wcerr << "One unit only\n";
        wcerr << usage.c_str();
        exit(2);
    }

    for (wstring unitname: units) {
        if (unitname.rfind(L".service") == string::npos) {
              unitname.append(L".service");
        }

        class SystemDUnit *unit = SystemDUnitPool::FindUnit(unitname);
        if (!unit) {
            // Complain and exit
            wcerr << "Failed to enable unit: Unit file " << unitname.c_str() << "does not exist\n";
            wcerr << usage.c_str();
            exit(1);
        }
        unit->Unmask(false); // We will add non-blocking later
    }
    return 0;
}

int SystemCtrl_Cmd_Link( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Revert( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Add_Wants( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Add_Requires( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Edit( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Get_Default( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Set_Default( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_List_Machines( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_List_Jobs( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Cancel( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Show_Environment( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Set_Environment( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Unset_Environment( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Import_Environment( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Daemon_Reload( boost::program_options::variables_map &vm )
{
    g_pool->ReloadPool( );
    return 0;
}

int SystemCtrl_Cmd_Daemon_Reexec( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Is_System_Running( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Default( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Rescue( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Emergency( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Halt( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Poweroff( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Reboot( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Kexec( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Exit( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Switch_Root( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Suspend( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Hibernate( boost::program_options::variables_map &vm )
{
    return -1;
}

int SystemCtrl_Cmd_Hybrid_Sleep( boost::program_options::variables_map &vm )
{
    return -1;
}

typedef int (*cmdfunc)( boost::program_options::variables_map &vm );

std::map< std::wstring , cmdfunc> Command_Map =  {
        { L"list-units", SystemCtrl_Cmd_List_Units},
        { L"list-sockets", SystemCtrl_Cmd_List_Sockets},
        { L"list-timers", SystemCtrl_Cmd_List_Timers},
        { L"start", SystemCtrl_Cmd_Start},
        { L"stop", SystemCtrl_Cmd_Stop},
        { L"reload", SystemCtrl_Cmd_Reload},
        { L"restart", SystemCtrl_Cmd_Restart},
        { L"try-restart", SystemCtrl_Cmd_Try_Restart},
        { L"reload-or-restart", SystemCtrl_Cmd_Reload_Or_Restart},
        { L"try-reload-or-restart", SystemCtrl_Cmd_Try_Reload_Or_Restart},
        { L"isolate", SystemCtrl_Cmd_Isolate},
        { L"kill", SystemCtrl_Cmd_Kill},
        { L"is-active", SystemCtrl_Cmd_Is_Active},
        { L"is-failed", SystemCtrl_Cmd_Is_Failed},
        { L"status", SystemCtrl_Cmd_Status},
        { L"show", SystemCtrl_Cmd_Show},
        { L"cat", SystemCtrl_Cmd_Cat},
        { L"set-property", SystemCtrl_Cmd_Set_Property},
        { L"help", SystemCtrl_Cmd_Help},
        { L"reset-failed", SystemCtrl_Cmd_Reset_Failed},
        { L"list-dependencies", SystemCtrl_Cmd_List_Dependencies},
        { L"list-unit-files", SystemCtrl_Cmd_List_Unit_Files},
        { L"enable", SystemCtrl_Cmd_Enable},
        { L"disable", SystemCtrl_Cmd_Disable},
        { L"reenable", SystemCtrl_Cmd_Reenable},
        { L"preset", SystemCtrl_Cmd_Preset},
        { L"preset-all", SystemCtrl_Cmd_Preset_All},
        { L"is-enabled", SystemCtrl_Cmd_Is_Enabled},
        { L"mask", SystemCtrl_Cmd_Mask},
        { L"unmask", SystemCtrl_Cmd_Unmask},
        { L"link", SystemCtrl_Cmd_Link},
        { L"revert", SystemCtrl_Cmd_Revert},
        { L"add-wants", SystemCtrl_Cmd_Add_Wants},
        { L"add-requires", SystemCtrl_Cmd_Add_Requires},
        { L"edit", SystemCtrl_Cmd_Edit},
        { L"get-default", SystemCtrl_Cmd_Get_Default},
        { L"set-default", SystemCtrl_Cmd_Set_Default},
        { L"list-machines", SystemCtrl_Cmd_List_Machines},
        { L"list-jobs", SystemCtrl_Cmd_List_Jobs},
        { L"cancel", SystemCtrl_Cmd_Cancel},
        { L"show-environment", SystemCtrl_Cmd_Show_Environment},
        { L"set-environment", SystemCtrl_Cmd_Set_Environment},
        { L"unset-environment", SystemCtrl_Cmd_Unset_Environment},
        { L"import-environment", SystemCtrl_Cmd_Import_Environment},
        { L"daemon-reload", SystemCtrl_Cmd_Daemon_Reload},
        { L"daemon-reexec", SystemCtrl_Cmd_Daemon_Reexec},
        { L"is-system-running", SystemCtrl_Cmd_Is_System_Running},
        { L"default", SystemCtrl_Cmd_Default},
        { L"rescue", SystemCtrl_Cmd_Rescue},
        { L"emergency", SystemCtrl_Cmd_Emergency},
        { L"halt", SystemCtrl_Cmd_Halt},
        { L"poweroff", SystemCtrl_Cmd_Poweroff},
        { L"reboot", SystemCtrl_Cmd_Reboot},
        { L"kexec", SystemCtrl_Cmd_Kexec},
        { L"exit", SystemCtrl_Cmd_Exit},
        { L"switch-root", SystemCtrl_Cmd_Switch_Root},
        { L"suspend", SystemCtrl_Cmd_Suspend},
        { L"hibernate", SystemCtrl_Cmd_Hibernate},
        { L"hybrid-sleep", SystemCtrl_Cmd_Hybrid_Sleep}
};

void ParseArgs(int argc, wchar_t *argv[])

{
    int result = 0;
    boost::program_options::positional_options_description pd;
    pd.add("command", 1);
    pd.add("system_units", -1);

    boost::program_options::options_description desc{ "Options" };
    desc.add_options()
        ("command", boost::program_options::wvalue<wstring>(), "command to execute")
        ("systemd-execpath", boost::program_options::wvalue<wstring>(), "location of service wrapper")
        ("system_units", boost::program_options::wvalue<vector<wstring>>(), "system_units")
        ("help,t", "Show this help")
        ("version", "Show package version")
        ("system", "Connect to system manager")
        ("user", "Connect to user service manager")
        ("host,H", boost::program_options::wvalue<wstring>(), "Operate on remote host")
        ("machine,M", boost::program_options::wvalue<wstring>(), "Operate on local container")
        ("type,t", boost::program_options::wvalue<wstring>(), "List units of a particular type")
        ("state", boost::program_options::wvalue<wstring>(), "List units with particular LOAD or SUB or ACTIVE state")
        ("property,p", boost::program_options::wvalue<wstring>(), "Show only properties by this name")
        ("all,a", "Show all properties/all units currently in memory, including dead/empty ones. "\
            "To list all units installed on the system, use the 'list-unit-files' command instead.")
            ("failed", "Same as --state=failed")
        ("full,l", "Don't ellipsize unit names on output")
        ("recursive,r", "Show unit list of host and local containers")
        ("reverse", "Show reverse dependencies with 'list-dependencies'")
        ("job-mode", boost::program_options::wvalue<wstring>(), "Specify how to deal with already queued jobs, when queueing a new job")
        ("show-types", "When showing sockets, explicitly show their type")
        ("value", "When showing properties, only print the value")
        ("ignore-inhibitors,i", "When shutting down or sleeping, ignore inhibitors")
        ("kill-who", boost::program_options::wvalue<wstring>(), "Who to send signal to")
        ("signal,s", boost::program_options::wvalue<wstring>(), "Which signal to send")
        ("now", "Start or stop unit in addition to enabling or disabling it")
        ("quiet", "Suppress output")
        ("wait", "For (re)start, wait until service stopped again")
        ("no-block", "Do not wait until operation finished")
        ("no-wall", "Don't send wall message before halt/power-off/reboot")
        ("no-reload", "Don't reload daemon after en-/dis-abling unit files")
        ("no-legend", "Do not print a legend (column headers and hints)")
        ("no-pager", "Do not pipe output into a pager")
        ("no-ask-password", "Do not ask for system passwords")
        ("global", "Enable/disable unit files globally")
        ("runtime", "Enable unit files only temporarily until next reboot")
        ("force,f", "When enabling unit files, override existing symlinks When shutting down, execute action immediately")
        ("preset-mode", boost::program_options::wvalue<wstring>(), "Apply only enable, only disable, or all presets")
        ("root", "Enable unit files in the specified root directory")
        ("lines,n", boost::program_options::wvalue<int>(), "Number of journal entries to show")
        ("output", boost::program_options::wvalue<wstring>(), "Change journal output mode (short, short-precise, short-iso, short-iso-precise, "\
            "short-full, short-monotonic, short-unix, verbose, export, json, json-pretty, json-sse, cat)")
            ("firmware-setup", "Tell the firmware to show the setup menu on next boot")
        ("plain", "Print unit dependencies as a list instead of a tree");

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

    vector<wstring> system_units;
    if (vm.count("system_units")) {
        system_units = vm["system_units"].as<vector<wstring>>();
    }
    wstring cmd;

    if (vm.count("command")) {
        cmd = vm["command"].as<wstring>();
    }
    else {
        // show usage message
    }

    if (vm.count("systemd-execpath")) {
         SystemDUnitPool::SERVICE_WRAPPER_PATH = vm["systemd-execpath"].as<wstring>();
    }
    else {
        // show usage message
    }

    cmdfunc func = Command_Map[cmd];
    if (!func) {
        std::wstringstream msg;
        msg << "Invalid command " << cmd;
        std::wstring ws = msg.str();
        std::string msgstr = std::string(ws.begin(), ws.end());

        throw std::exception(msgstr.c_str());
    }
    else {
        result = (*func)(vm);

        if (result) {
            std::wstringstream msg;
            msg << "the command " << cmd << " failed. code = " << result;
            std::wstring ws = msg.str();
            std::string msgstr = std::string(ws.begin(), ws.end());

            throw std::exception(msgstr.c_str());
        }
    }
}

int wmain(int argc, wchar_t *argv[])
{
    try {
        g_pool->LoadPool();
        ParseArgs(argc, argv);
    }
    catch(std::exception &e) {
        wcerr << e.what() << endl;
        exit(1);
    }
    exit(0);
}


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)

// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.

// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_GEOMETRY_IO_VESHAPE_WRITE_VESHAPE_HPP
#define BOOST_GEOMETRY_IO_VESHAPE_WRITE_VESHAPE_HPP

#include <ostream>
#include <string>

#include <boost/concept/assert.hpp>
#include <boost/range.hpp>

#include <boost/geometry/core/exterior_ring.hpp>
#include <boost/geometry/core/interior_rings.hpp>
#include <boost/geometry/core/ring_type.hpp>

#include <boost/geometry/geometries/concepts/point_concept.hpp>

namespace boost { namespace geometry
{

#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace veshape
{

// Define the coordinate streamer, specialized for either 2 or 3 dimensions.
// Any other number of dimensions make no sense for VE, and we have to take care about
// the order lat,long (--> y,x)
template <typename P, std::size_t D>
struct stream_coordinate {};

template <typename P>
struct stream_coordinate<P, 2>
{
    template <typename Char, typename Traits>
    static inline void stream(std::basic_ostream<Char, Traits>& os, P const& p)
    {
        os << geometry::get<1>(p) << "," << geometry::get<0>(p);
    }
};

template <typename P>
struct stream_coordinate<P, 3>
{
    template <typename Char, typename Traits>
    static inline void stream(std::basic_ostream<Char, Traits>& os, P const& p)
    {
        stream_coordinate<P, 2>::stream(os, p);
        os << "," << geometry::get<2>(p);
    }
};

template <typename P>
struct stream_point
{
    template <typename Char, typename Traits>
    static inline void stream(std::basic_ostream<Char, Traits>& os, P const& p)
    {
        os << "new VELatLong(";
        stream_coordinate<P, dimension<P>::value>::stream(os, p);
        os << ")";
    }
};

struct prefix_point
{
    static inline const char* prefix()
    { return "new VEShape(VEShapeType.Pushpin, "; }

    static inline const char* postfix()
    { return ")"; }
};

struct prefix_linestring
{
    static inline const char* prefix()
    { return "new VEShape(VEShapeType.Polyline, "; }

    static inline const char* postfix()
    { return ")"; }
};

struct prefix_polygon
{
    static inline const char* prefix()
    { return "new VEShape(VEShapeType.Polygon, "; }

    static inline const char* postfix()
    { return ")"; }
};

/*!
\brief Stream points as \ref VEShape
*/
template <typename P, typename Policy>
struct veshape_point
{
    template <typename Char, typename Traits>
    static inline void stream(std::basic_ostream<Char, Traits>& os, P const& p)
    {
        os << Policy::prefix();
        stream_point<P>::stream(os, p);
        os << Policy::postfix();
    }

    private:
        BOOST_CONCEPT_ASSERT( (concept::ConstPoint<P>) );
};

/*!
\brief Stream ranges as VEShape
\note policy is used to stream prefix/postfix, enabling derived classes to override this
*/
template <typename R, typename Policy>
struct veshape_range
{
    template <typename Char, typename Traits>
    static inline void stream(std::basic_ostream<Char, Traits>& os, R const& range)
    {
        typedef typename boost::range_iterator<R const>::type iterator;

        bool first = true;

        os << Policy::prefix() << "new Array(";

        for (iterator it = boost::begin(range); it != boost::end(range); ++it)
        {
            os << (first ? "" : ", ");
            stream_point<point>::stream(os, *it);
            first = false;
        }

        os << ")" << Policy::postfix();
    }

    private:
        typedef typename boost::range_value<R>::type point;
        BOOST_CONCEPT_ASSERT( (concept::ConstPoint<point>) );
};

template <typename P, typename Policy>
struct veshape_poly
{
    template <typename Char, typename Traits>
    static inline void stream(std::basic_ostream<Char, Traits>& os, P const& poly)
    {
        typedef typename ring_type<P>::type ring;

        veshape_range<ring, Policy>::stream(os, exterior_ring(poly));

        // For VE shapes: inner rings are not supported or undocumented
        /***
        for (iterator it = boost::begin(interior_rings(poly));
            it != boost::end(interior_rings(poly)); it++)
        {
            os << ",";
            veshape_range<ring, null>::stream(os, *it);
        }
        os << ")";
        ***/
    }

    private:
        BOOST_CONCEPT_ASSERT( (concept::ConstPoint<typename point_type<P>::type>) );
};

}} // namespace detail::veshape
#endif // DOXYGEN_NO_DETAIL

#ifndef DOXYGEN_NO_DISPATCH
namespace dispatch
{

/*!
\brief Dispatching base struct for VEShape streaming, specialized below per geometry type
\details Specializations should implement a static method "stream" to stream a geometry
The static method should have the signature:

template <typename Char, typename Traits>
static inline void stream(std::basic_ostream<Char, Traits>& os, G const& geometry)
*/
template <typename T, typename G>
struct veshape
{};

template <typename P>
struct veshape<point_tag, P>
    : detail::veshape::veshape_point<P, detail::veshape::prefix_point>
{};

template <typename R>
struct veshape<linestring_tag, R>
    : detail::veshape::veshape_range<R, detail::veshape::prefix_linestring>
{};

template <typename R>
struct veshape<ring_tag, R>
    : detail::veshape::veshape_range<R, detail::veshape::prefix_polygon>
{};

template <typename P>
struct veshape<polygon_tag, P>
    : detail::veshape::veshape_poly<P, detail::veshape::prefix_polygon>
{};

} // namespace dispatch
#endif // DOXYGEN_NO_DISPATCH

/*!
\brief Generic geometry template manipulator class, takes corresponding output class from traits class
\ingroup veshape
\details Stream manipulator, streams geometry classes as Virtual Earth shape
*/
template <typename G>
class veshape_manip
{
public:

    inline veshape_manip(G const& g)
        : m_geometry(g)
    {}

    template <typename Char, typename Traits>
    inline friend std::basic_ostream<Char, Traits>& operator<<(
                    std::basic_ostream<Char, Traits>& os, veshape_manip const& m)
    {
        dispatch::veshape<typename tag<G>::type, G>::stream(os, m.m_geometry);
        os.flush();
        return os;
    }

private:
    G const& m_geometry;
};

/*!
\brief Object generator to conveniently stream objects without including streamveshape
\ingroup veshape
\par Example:
Small example showing how to use the veshape helper function
\dontinclude doxygen_1.cpp
\skip example_as_veshape_vector
\line {
\until }
*/
template <typename T>
inline veshape_manip<T> veshape(T const& t)
{
    return veshape_manip<T>(t);
}

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_IO_VESHAPE_WRITE_VESHAPE_HPP

ext: hpp

max_stars_repo_name: bowlofstew/omim

max_issues_repo_name: bowlofstew/omim

max_forks_repo_name: bowlofstew/omim


text:
/*==============================================================================
  Copyright (c) 2016, 2017, 2018 Matt Calabrese

  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 ARGOT_RECEIVER_GRAPHVIZ_DOT_HPP_
#define ARGOT_RECEIVER_GRAPHVIZ_DOT_HPP_
#if 0
#include <argot/concepts/argument_receiver.hpp>
#include <argot/detail/xml_sanitize.hpp>
#include <argot/prov/argument_provider.hpp>
#include <argot/prov_traits/provide.hpp>
#include <argot/receiver_traits/provider_types.hpp>

#include <boost/core/demangle.hpp>

#include <cstddef>
#include <sstream>
#include <string>
#include <type_traits>
#include <typeinfo>
#include <utility>

namespace argot {
namespace receiver {

enum class ignore_internal_nodes { no, yes };

namespace graphviz_dot_detail {

template< class... P >
struct output_params;

template<>
struct output_params<>
{
  template< class Os, class TypeOutput >
  static void run( Os&& os, TypeOutput&& /*type_output*/ )
  {
    os << "$ no parameters $";
  }
};

template< class Head >
struct output_params< Head >
{
  template< class Os, class TypeOutput >
  static void run( Os&& os, TypeOutput&& type_output )
  {
    type_output.template output< Head >( os );
  }
};

template< class Head, class Next, class... Tail >
struct output_params< Head, Next, Tail... >
{
  template< class Os, class TypeOutput >
  static void run( Os&& os, TypeOutput&& type_output )
  {
    output_params< Head >::run( os, type_output );
    os << '|';
    output_params< Next, Tail... >::run( os, type_output );
  }
};

template< class Os, class TypeOutput, class ValOutput >
void output_args( Os&& os, TypeOutput&, ValOutput& )
{
  os << "$ no arguments $";
}

template< class Os, class TypeOutput, class ValOutput
        , class Head, class... Tail
        >
void output_args( Os&& os, TypeOutput& type_output, ValOutput& val_output
                , Head&& head, Tail&&... tail
                )
{
  os << '{';

  // TODO(mattcalabrese) Do the sanitization here.
  type_output.template output< Head >( os );
  os << '|';

  // TODO(mattcalabrese) Do the sanitization here.
  val_output.output( os, std::forward< Head >( head ) );
  os << '}';

  // TODO(mattcalabres) if constexpr here
  if constexpr( sizeof...( Tail ) != 0 )
  {
    os << '|';
    ( output_args )
    ( os, type_output, val_output, std::forward< Tail >( tail )... );
  }
}

char const* untaken_edge_attributes()
{
  return "";
}

char const* taken_edge_attributes()
{
  return "[color=yellowgreen,penwidth=4.0]";
}

template< std::size_t BranchIndex >
std::string branch_name( std::string const& parent_name )
{
  std::ostringstream os;
  os << parent_name << ':' << BranchIndex;
  return std::move( os ).str();
}

template< std::size_t LocalBranchIndex, class Os, class TypeOutput >
void untaken_branch_impl
( Os& os, std::string const& parent_name, TypeOutput& type_output )
{
  std::string const name = ( branch_name< LocalBranchIndex > )( parent_name );

  // TODO(mattcalabrese) Put type info into the label instead of just an index.
  os << "  \"" << name << "\"[label=\"Branch" << LocalBranchIndex << "\"]\n"
     << "  \"" << parent_name << "\" -> \"" << name << "\" "
     << untaken_edge_attributes() << '\n';
}

template< ignore_internal_nodes ignore_internal_nodes_value
        , std::size_t IDOffset, class... P, class Os, class TypeOutput
        >
void untaken_receive_impl
( Os& os, std::string const& parent_name, TypeOutput& type_output )
{
  os << "  Leaf" << IDOffset << "[label=\"{" << IDOffset << "|{";

  output_params< P... >::run( os, type_output );

  os << "}}\",fillcolor=wheat]\n"
        "  \""
     << (   ignore_internal_nodes_value == ignore_internal_nodes::no
          ? parent_name
          : "Root"  // TODO(mattcalabrese) Don't hard-code the root name.
        )
     << "\" -> Leaf" << IDOffset << ' '
     << untaken_edge_attributes() << '\n';
}

template< ignore_internal_nodes ignore_internal_nodes_value
        , std::size_t IDOffset
        , class Os, class TypeOutput, class ValOutput, class... P
        >
void receive_impl
( Os& os, std::string const& parent_name
, TypeOutput& type_output, ValOutput& val_output
, P&&... args
)
{
  os << "  Arguments[label=\"{" << IDOffset << "|{";

  ( output_args )( os, type_output, val_output, std::forward< P >( args )... );

  os << "}}\",fillcolor=yellowgreen]\n"
        "  \""
     << (   ignore_internal_nodes_value == ignore_internal_nodes::no
          ? parent_name
          : "Root"  // TODO(mattcalabrese) Don't hard-code the root name.
        )
     << "\" -> Arguments"
     << taken_edge_attributes() << '\n';
}

template< ignore_internal_nodes ignore_internal_nodes_value
        , std::size_t OverallIndex, class... P
        >
struct receive_result
{
  template< class Os, class TypeOutput >
  static std::integral_constant< std::size_t, OverallIndex + 1 >
  write_edges
  ( Os& os, std::string const& parent_name, TypeOutput& type_output )
  {
    ( untaken_receive_impl< ignore_internal_nodes_value, OverallIndex, P... > )
    ( os, parent_name, type_output );

    return {};
  }
};

template< ignore_internal_nodes ignore_internal_nodes_value
        , std::size_t OverallIndex
        >
class graphviz_dot_untaken_t;

template< ignore_internal_nodes ignore_internal_nodes_value
        , std::size_t OverallIndex, std::size_t LocalBranchIndex
        , class... PossibleProviders
        >
struct branch_result;

template< ignore_internal_nodes ignore_internal_nodes_value
        , std::size_t OverallIndex, std::size_t LocalBranchIndex
        >
struct branch_result
< ignore_internal_nodes_value, OverallIndex, LocalBranchIndex >
{
  template< class Os, class TypeOutput >
  static std::integral_constant< std::size_t, OverallIndex > write_edges
  ( Os& os
  , std::string const& /*parent_name*/, TypeOutput& /*type_output*/
  )
  {
    return {};
  }
};

template< ignore_internal_nodes ignore_internal_nodes_value
        , std::size_t OverallIndex, std::size_t LocalBranchIndex
        , class Provider
        >
struct branch_result
< ignore_internal_nodes_value, OverallIndex, LocalBranchIndex, Provider >
{
  template< class Os, class TypeOutput >
  static auto write_edges
  ( Os& os, std::string const& parent_name, TypeOutput& type_output )
  {
    using edge_writer
      = decltype
        ( prov_traits::provide
          ( std::declval< Provider >()
          , std::declval
            < graphviz_dot_untaken_t
              < ignore_internal_nodes_value, OverallIndex >
            >()
          )
        );

    if constexpr( ignore_internal_nodes_value == ignore_internal_nodes::no )
    {
      ( untaken_branch_impl< LocalBranchIndex > )
      ( os, parent_name, type_output );
    }

    return edge_writer::write_edges
    ( os, ( branch_name< LocalBranchIndex > )( parent_name ), type_output );
  }
};

template
< ignore_internal_nodes ignore_internal_nodes_value
, std::size_t OverallIndex, std::size_t LocalBranchIndex, class Provider
, class HeadTrailingPossibleProvider, class... TailTrailingPossibleProviders
>
struct branch_result
< ignore_internal_nodes_value
, OverallIndex, LocalBranchIndex, Provider
, HeadTrailingPossibleProvider, TailTrailingPossibleProviders...
>
{
  template< class Os, class TypeOutput >
  static auto write_edges
  ( Os& os, std::string const& parent_name, TypeOutput& type_output )
  {
    auto const next_overall_index
      = branch_result
        < ignore_internal_nodes_value
        , OverallIndex, LocalBranchIndex, Provider
        >::write_edges( os, parent_name, type_output );

    return branch_result
    < ignore_internal_nodes_value
    , decltype( next_overall_index )::value, LocalBranchIndex + 1
    , HeadTrailingPossibleProvider, TailTrailingPossibleProviders...
    >::write_edges( os, parent_name, type_output );
  }
};

template< ignore_internal_nodes ignore_internal_nodes_value
        , std::size_t OverallIndex
        >
struct graphviz_dot_untaken_t
{
  template< class Self, class... P >
  static receive_result< ignore_internal_nodes_value, OverallIndex, P... >
  receive( Self&& /*self*/, P&&... /*args*/ ) { return {}; }

  template
  < class Self
  , class Provider
  , class... TrailingPossibleProviders
  >
  static branch_result
  < ignore_internal_nodes_value
  , OverallIndex, 0, Provider, TrailingPossibleProviders...
  >
  branch
  ( Self&& self
  , receiver_traits::provider_types_t<>
  , Provider&& provider
  , receiver_traits::provider_types_t< TrailingPossibleProviders... >
  )
  {
    return {};
  }

  template
  < class Self
  , class HeadLeadingPossibleProvider, class... TailLeadingPossibleProviders
  , class Provider
  , class... TrailingPossibleProviders
  >
  static branch_result
  < ignore_internal_nodes_value
  , OverallIndex, 0, HeadLeadingPossibleProvider
  , TailLeadingPossibleProviders..., Provider, TrailingPossibleProviders...
  >
  branch
  ( Self&& self
  , receiver_traits::provider_types_t
    < HeadLeadingPossibleProvider, TailLeadingPossibleProviders... >
  , Provider&& provider
  , receiver_traits::provider_types_t< TrailingPossibleProviders... >
  )
  {
    return {};
  }
};

template< ignore_internal_nodes ignore_internal_nodes_value
        , class Os
        , std::size_t OverallIndex
        , class TypeOutput, class ValOutput
        >
class graphviz_dot_edges_t
{
  Os&& os;  // TODO(mattcalabrese) Use contained here
  std::string parent_name;
  TypeOutput type_output;
  ValOutput val_output;
 public:
  graphviz_dot_edges_t
  ( Os&& os, std::string parent_name
  , TypeOutput type_output, ValOutput val_output
  )
    : os( std::forward< Os >( os ) )
    , parent_name( std::move( parent_name ) )
    , type_output( std::move( type_output ) )
    , val_output( std::move( val_output ) ) {}

  template< class Self, class... P >
  static std::integral_constant< std::size_t, OverallIndex + 1 >
  receive( Self&& self, P&&... args )
  {
    ( receive_impl< ignore_internal_nodes_value, OverallIndex > )
    ( self.os, self.parent_name, self.type_output, self.val_output
    , std::forward< P >( args )...
    );

    return {};
  }

  template
  < class Self
  , class... LeadingPossibleProviders
  , class Provider
  , class... TrailingPossibleProviders
  >
  static auto branch
  ( Self&& self
  , receiver_traits::provider_types_t< LeadingPossibleProviders... >
  , Provider&& provider
  , receiver_traits::provider_types_t< TrailingPossibleProviders... >
  )
  {
    auto const overall_taken_index
      = branch_result
        < ignore_internal_nodes_value
        , OverallIndex, 0
        , LeadingPossibleProviders...
        >::write_edges( self.os, self.parent_name, self.type_output );

    std::size_t constexpr local_taken_branch_index
      = sizeof...( LeadingPossibleProviders );

    std::string const name
      = ( branch_name< local_taken_branch_index > )( self.parent_name );

    if constexpr( ignore_internal_nodes_value == ignore_internal_nodes::no )
    {
      // TODO(mattcalabrese) Put value into the label instead of just an index.
      self.os
        << "  \"" << name << "\"[label=\"Branch"
                          << local_taken_branch_index
                          << "\",fillcolor=yellowgreen]\n"
        << "  \"" << self.parent_name << "\" -> \"" << name << "\" "
        << taken_edge_attributes() << '\n';
    }

    auto const next_index
      = prov_traits::provide
        ( std::forward< Provider >( provider )
        , graphviz_dot_edges_t
          < ignore_internal_nodes_value
          , Os&, decltype( overall_taken_index )::value
          , TypeOutput, ValOutput
          >( self.os
           , ( branch_name< sizeof...( LeadingPossibleProviders ) > )
             ( self.parent_name )
           , self.type_output, self.val_output
           )
        );

    return branch_result
    < ignore_internal_nodes_value
    , decltype( next_index )::value, sizeof...( LeadingPossibleProviders ) + 1
    , TrailingPossibleProviders...
    >::write_edges( self.os, self.parent_name, self.type_output );
  }
};

template< ignore_internal_nodes ignore_internal_nodes_value
        , class TypeOutput, class ValOutput
        >
class graphviz_dot_t
{
 public:
  graphviz_dot_t
  ( std::string graph_name, std::string prov_form
  , TypeOutput type_output, ValOutput val_output
  )
    : graph_name( std::move( graph_name ) )
    , prov_form( std::move( prov_form ) )
    , type_output( std::move( type_output ) )
    , val_output( std::move( val_output ) ) {}

  template< class Self, class... P >
  static std::string receive( Self&& self, P&&... args )
  {
    std::ostringstream os;

    begin_impl( self, os );

    using underlying_receiver_type
      = graphviz_dot_edges_t
        < ignore_internal_nodes_value
        , std::ostringstream&, 0, TypeOutput, ValOutput
        >;

    os
      << underlying_receiver_type::receive
         ( underlying_receiver_type
           ( os, root_name(), std::forward< Self >( self ).type_output
           , std::forward< Self >( self ).val_output
           )
         , std::forward< P >( args )...
         );

    end_impl( os );

    return std::move( os ).str();
  }

  template
  < class Self
  , class... LeadingPossibleProviders
  , class Provider
  , class... TrailingPossibleProviders
  >
  static std::string branch
  ( Self&& self
  , receiver_traits::provider_types_t< LeadingPossibleProviders... >
  , Provider&& provider
  , receiver_traits::provider_types_t< TrailingPossibleProviders... >
  )
  {
    std::ostringstream os;

    begin_impl( self, os );

    using underlying_receiver_type
      = graphviz_dot_edges_t
        < ignore_internal_nodes_value
        , std::ostringstream&, 0, TypeOutput, ValOutput
        >;

    underlying_receiver_type::branch
    ( underlying_receiver_type
      ( os, root_name(), std::forward< Self >( self ).type_output
      , std::forward< Self >( self ).val_output
      )
    , receiver_traits::provider_types< LeadingPossibleProviders... >
    , std::forward< Provider >( provider )
    , receiver_traits::provider_types< TrailingPossibleProviders... >
    );

    end_impl( os );

    return std::move( os ).str();
  }
 private:
  static char const* root_name() { return "Root"; }

  template< class Self, class Os >
  static void begin_impl( Self&& self, Os& os )
  {
    os
      << "digraph " << call_detail::xml_sanitize( self.graph_name ) << "\n"
         "{\n"
         "  edge[headport=w,tailport=e]\n"
         "  rankdir=LR\n"
         "  node[shape=Mrecord,style=filled]\n"
         "  Root[label=\""<< call_detail::xml_sanitize( self.prov_form )
                          << "\",shape=box3d,fillcolor=yellowgreen]\n";
  }

  template< class Os >
  static  void end_impl( Os& os )
  {
    os << '}';
  }

  std::string graph_name;
  std::string prov_form;
  TypeOutput type_output;
  ValOutput val_output;
};

} // namespace argot::receiver::graphviz_dot_detail

struct demangled_type_output
{
  template< class T >
  struct impl
  {
    template< class Os >
    static void run( Os&& os )
    {
      os
        << call_detail::xml_sanitize
           ( boost::core::demangle( typeid( T ).name() ) )
        << ( std::is_volatile< T >::value ? " volatile" : "" )
        << ( std::is_const< T >::value ? " const" : "" );
    }
  };

  template< class T >
  struct impl< T& >
  {
    template< class Os >
    static void run( Os&& os )
    {
      impl< T >::run( os );
      os << "&";
    }
  };

  template< class T >
  struct impl< T&& >
  {
    template< class Os >
    static void run( Os&& os )
    {
      impl< T >::run( os );
    }
  };

  template< class T, class Os >
  Os&& output( Os&& os ) const
  {
    impl< T >::run( os );
    return std::forward< Os >( os );
  }
};

template< class Os, class T >
void value_output_impl( Os& os, const T& arg )
{
  os << arg;
}

template< class Os, class ValueType, ValueType Value >
Os& value_output_impl( Os& os, std::integral_constant< ValueType, Value > )
{
  os << "{}";
  return os;
}

struct value_output
{
 private:
  template< class Os, class T, class /*Enabler*/ = void >
  struct can_describe : std::false_type{};

  template< class Os, class T >
  struct can_describe
  < Os, T
  , std::void_t
    < decltype( std::declval< T const& >().describe( std::declval< Os >() ) ) >
  > : std::true_type{};

 public:
  template< class Os, class T >
  void output( Os&& os, T const& arg ) const
  {
    // TODO(mattcalabrese) Check for error
    std::ostringstream unsanitized;
    value_output_impl( unsanitized, arg );
    os << call_detail::xml_sanitize( unsanitized.str() );
  }

  template
  < class Os, class Impl
  , std::enable_if_t
    < !can_describe< std::ostringstream&, Impl >::value, int > = 0
  >
  void output( Os&& os, prov::argument_provider< Impl > const& arg ) const
  {
    // TODO(mattcalabrese) Check for error
    os << call_detail::xml_sanitize( "?" );
  }

  template
  < class Os, class Impl
  , std::enable_if_t
    < can_describe< std::ostringstream&, Impl >::value, int > = 0
  >
  void output( Os&& os, prov::argument_provider< Impl > const& arg ) const
  {
    // TODO(mattcalabrese) Check for error
    std::ostringstream unsanitized;
    arg.state().describe( unsanitized );
    os << call_detail::xml_sanitize( unsanitized.str() );
  }
};

// TODO(mattcalabrese) Make this a function object.
template< ignore_internal_nodes ignore_internal_nodes_value
            = ignore_internal_nodes::no
        , class TypeOutput = demangled_type_output
        , class ValOutput = value_output
        >
argument_receiver
< graphviz_dot_detail::graphviz_dot_t
  < ignore_internal_nodes_value, TypeOutput, ValOutput >
>
graphviz_dot
( std::string graph_name, std::string prov_form
, TypeOutput type_output = TypeOutput()
, ValOutput val_output = ValOutput()
)
{
  return graphviz_dot_detail::graphviz_dot_t
  < ignore_internal_nodes_value, TypeOutput, ValOutput >
  ( std::move( graph_name ), std::move( prov_form )
  , std::move( type_output ), std::move( val_output )
  );
}

} // namespace argot::receiver
} // namespace argot

#endif

#endif  // ARGOT_RECEIVER_GRAPHVIZ_DOT_HPP_

max_stars_repo_name: mattcalabrese/argot

max_issues_repo_name: mattcalabrese/argot

max_forks_repo_name: mattcalabrese/argot


text:
//==============================================================================
//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_TOOLBOX_REDUCTION_FUNCTIONS_SIMD_SSE_AVX_SUM_HPP_INCLUDED
#define BOOST_SIMD_TOOLBOX_REDUCTION_FUNCTIONS_SIMD_SSE_AVX_SUM_HPP_INCLUDED
#ifdef BOOST_SIMD_HAS_AVX_SUPPORT

#include <boost/simd/toolbox/reduction/functions/sum.hpp>
#include <boost/simd/include/constants/one.hpp>

// /////////////////////////////////////////////////////////////////////////////
// // Implementation when type  is arithmetic_
// /////////////////////////////////////////////////////////////////////////////
namespace boost { namespace simd { namespace ext
{
  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::sum_, boost::simd::tag::avx_,
                                    (A0),
                                    ((simd_<double_<A0>,boost::simd::tag::sse_>))
                                    ((simd_<double_<A0>,boost::simd::tag::sse_>))
                                   )
  {
    typedef typename meta::scalar_of<A0>::type result_type;
    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)
    {
      A0 r = _mm256_dp_pd(a0, One<A0>(), 0x3);
      return r[0];
    }
  };

  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::sum_, boost::simd::tag::avx_,
                                    (A0),
                                    ((simd_<single_<A0>,boost::simd::tag::avx_>))
                                    ((simd_<single_<A0>,boost::simd::tag::avx_>))
                                   )
  {
    typedef typename meta::scalar_of<A0>::type result_type;
    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)
    {
      A0 r = _mm256_dp_ps(a0, One<A0>(), 0xFF);
      return r[0]+r[4];
      // this in another solution for floats,  perhaps speedier ?
      // x3 = _mm256_add_ps(x0, _mm256_movehdup_ps(x0));
      // x4 = _mm256_unpackhi_ps(x3, x3)  ;
      // x4 = _mm256_add_ps(x3, x4)  ;
      // x5 = _mm256_permute2f128_ps(x4, x4, 0x01)  ;
      // x5 = _mm256_add_ps(x5, x4)  ;
    }
  };

} } }
#endif
#endif


text:
#include "downloader.hpp"

#include "download.hpp"
#include "file.hpp"
#include "filedownload.hpp"
#include "install.hpp"
#include "vitahttp.hpp"

#include <fmt/format.h>

#include <boost/scope_exit.hpp>

std::string type_to_string(Type type)
{
    switch (type)
    {
    case Type::Game:
        return "game";
    case Type::Patch:
        return "patch";
    case Type::Dlc:
        return "DLC";
    case Type::PsmGame:
        return "PSM game";
    case Type::PsxGame:
        return "PSX game";
    case Type::PspGame:
        return "PSP game";
    case Type::PspDlc:
        return "PSP DLC";
    case Type::CompPackBase:
        return "Base Comp Pack";
    case Type::CompPackPatch:
        return "Patch Comp Pack";
    }
    return "unknown";
}

Downloader::Downloader()
    : _cond("downloader_cond"), _thread("downloader_thread", [this] { run(); })
{
    LOG("new downloader");
}

Downloader::~Downloader()
{
    LOG("destroying downloader");
    _dying = true;
    _cond.notify_one();
    _thread.join();
    LOG("downloader destroyed");
}

void Downloader::add(const DownloadItem& d)
{
    LOG("adding download %s", d.name.c_str());
    {
        ScopeLock _(_cond.get_mutex());
        _queue.push_back(d);
    }
    _cond.notify_one();
}

bool Downloader::is_in_queue(Type type, const std::string& contentid)
{
    ScopeLock _(_cond.get_mutex());
    if (type == _current_download.type &&
        contentid == _current_download.content)
        return true;

    for (const auto& item : _queue)
        if (item.type == type && item.content == contentid)
            return true;
    return false;
}

std::optional<DownloadItem> Downloader::get_current_download()
{
    ScopeLock _(_cond.get_mutex());
    if (_current_download.content.empty())
        return std::nullopt;
    return _current_download;
}

std::tuple<uint64_t, uint64_t> Downloader::get_current_download_progress()
{
    return {_download_offset.load(), _download_size.load()};
}

void Downloader::remove_from_queue(Type type, const std::string& contentid)
{
    ScopeLock _(_cond.get_mutex());
    if (type == _current_download.type &&
        contentid == _current_download.content)
        _cancel_current = true;
    else
        _queue.erase(
                std::remove_if(
                        _queue.begin(),
                        _queue.end(),
                        [&](auto const& item) {
                            return item.type == type &&
                                   item.content == contentid;
                        }),
                _queue.end());
}

void Downloader::run()
{
    while (true)
    {
        DownloadItem item;
        {
            ScopeLock _(_cond.get_mutex());

            _current_download = {};
            _cancel_current = false;
            _download_offset = 0;
            _download_size = 0;

            if (_dying)
                return;
            else if (!_queue.empty())
            {
                item = _current_download = _queue.front();
                _queue.pop_front();
            }
            else
                _cond.wait();
        }

        try
        {
            if (!item.content.empty())
                do_download(item);
        }
        catch (const std::exception& e)
        {
            LOG("download error: %s", e.what());
            error(e.what());
        }
    }
}

void Downloader::do_download_package(const DownloadItem& item)
{
    BOOST_SCOPE_EXIT_ALL(&)
    {
        refresh(item.content);
    };

    ScopeProcessLock _;
    LOG("downloading %s", item.name.c_str());
    auto download = std::make_unique<Download>(std::make_unique<VitaHttp>());
    download->save_as_iso = item.save_as_iso;
    download->update_progress_cb = [this](uint64_t download_offset,
                                          uint64_t download_size) {
        _download_offset = download_offset;
        _download_size = download_size;
    };
    download->update_status = [](auto&&) {};
    download->is_canceled = [this] { return _cancel_current || _dying; };
    if (!download->pkgi_download(
                item.partition.c_str(),
                item.content.c_str(),
                item.url.c_str(),
                item.rif.empty() ? nullptr : item.rif.data(),
                item.digest.empty() ? nullptr : item.digest.data()))
        return;
    LOG("download of %s completed!", item.name.c_str());
    switch (item.type)
    {
    case Game:
    case Dlc:
        pkgi_install(item.partition.c_str(), item.content.c_str());
        break;
    case Patch:
        pkgi_install_update(item.partition.c_str(), item.content.c_str());
        break;
    case PspGame:
        if (item.save_as_iso)
            pkgi_install_pspgame_as_iso(
                    item.partition.c_str(), item.game_path.c_str(), item.iso_path.c_str(), item.content.c_str());
        else
            pkgi_install_pspgame(item.partition.c_str(), item.game_path.c_str(), item.content.c_str());
        break;
    case PspDlc:
        pkgi_install_pspdlc(item.partition.c_str(), item.game_path.c_str(), item.content.c_str());
        break;
    case PsmGame:
        pkgi_install_psmgame(item.partition.c_str(), item.content.c_str());
        break;
    case PsxGame:
        pkgi_install_pspgame(item.partition.c_str(), item.psx_path.c_str(), item.content.c_str());
        break;
    case CompPackBase:
    case CompPackPatch:
        throw std::runtime_error(
                "assertion failure: can't handle comppack in download_package");
    }
    pkgi_rm(fmt::format("{}pkgj/{}.resume", item.partition, item.content)
                    .c_str());
    pkgi_delete_dir(fmt::format("{}pkgj/{}", item.partition, item.content));
    LOG("install of %s completed!", item.name.c_str());
}

void Downloader::do_download_comppack(const DownloadItem& item)
{
    BOOST_SCOPE_EXIT_ALL(&)
    {
        refresh("");
    };

    ScopeProcessLock _;
    LOGF("downloading comppack {}", item.url);
    auto download =
            std::make_unique<FileDownload>(std::make_unique<VitaHttp>());

    download->update_progress_cb = [this](uint64_t download_offset,
                                          uint64_t download_size) {
        _download_offset = download_offset;
        _download_size = download_size;
    };
    download->is_canceled = [this] { return _cancel_current || _dying; };

    download->download(
            item.partition.c_str(), item.content.c_str(), item.url.c_str());
    LOGF("download of comppack {} completed!", item.url);
    pkgi_install_comppack(
            item.partition, item.content, item.type == CompPackPatch, item.version);
    pkgi_rm(fmt::format("{}pkgj/{}-comp.ppk", item.partition, item.content)
                    .c_str());
    LOG("install of %s completed!", item.name.c_str());
}

void Downloader::do_download(const DownloadItem& item)
{
    if (item.type == CompPackBase || item.type == CompPackPatch)
        do_download_comppack(item);
    else
        do_download_package(item);
}

max_stars_repo_name: BurAndBY/pkgj

max_issues_repo_name: BurAndBY/pkgj

max_forks_repo_name: BurAndBY/pkgj


text:
////////////////////////////////////////////////////////////////////////////////////////////////////
// integral_constant.hpp
// A simple basic_action that returns a constant
//
//  Copyright 2012 Eric Niebler. 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 BOOST_PROTO_V5_ACTION_INTEGRAL_CONSTANT_HPP_INCLUDED
#define BOOST_PROTO_V5_ACTION_INTEGRAL_CONSTANT_HPP_INCLUDED

#include <utility>
#include <boost/proto/v5/proto_fwd.hpp>
#include <boost/proto/v5/action/basic_action.hpp>

namespace boost
{
    namespace proto
    {
        inline namespace v5
        {
            template<typename T, T Value>
            struct _integral_constant
              : basic_action<_integral_constant<T, Value>>
            {
                template<typename ...Args>
                constexpr T operator()(Args &&...) const noexcept(noexcept(T(std::declval<T>())))
                {
                    return Value;
                }
            };

            using _true = _integral_constant<bool, true>;
            using _false = _integral_constant<bool, false>;
        }
    }
}

#endif


text:
#pragma once

#include <stdexcept>
#include <limits>

#include <boost/container/flat_map.hpp>
#include <boost/dynamic_bitset.hpp>

namespace FACore {
    template<unsigned int AlphabetSize>
    class NAutomaton {
        public:
            constexpr static unsigned int ALPHABET_SIZE = AlphabetSize;
            constexpr static unsigned int INVALID_STATE = std::numeric_limits<unsigned int>::max();

            // A StateId is really just an index into a vector
            typedef unsigned int StateId;

            // Label values must be between 0 and ALPHABET_SIZE
            typedef unsigned int Label;

            // <(src,label),dest>
            typedef std::pair<std::tuple<StateId,Label>,StateId> TransitionMapEntry;

            typedef boost::container::flat_multimap<std::tuple<StateId,Label>,StateId>::const_iterator TransitionIterator;

            class ArcRange {
                public:
                    ArcRange (const std::pair<TransitionIterator,TransitionIterator> &range)
                    {
                        mIterStart = range.first;
                        mIterEnd = range.second;
                    }

                    TransitionIterator begin() const { return mIterStart; }
                    TransitionIterator end() const { return mIterEnd; }

                private:
                    TransitionIterator mIterStart;
                    TransitionIterator mIterEnd;
            };

            StateId AddState(bool isFinal) {
                if(mFinalStates.size() == INVALID_STATE) {
                    // WARNING this is outside of testing code coverage
                    throw std::out_of_range("Invalid label");
                }
                StateId result = mFinalStates.size();
                mFinalStates.push_back(isFinal);
                return result;
            }

            void AddArc(StateId src, Label label, StateId dest) {
                if(!IsValidLabel(label)) {
                    throw std::out_of_range("Invalid label");
                }
                if(!IsValidState(src)) {
                    throw std::out_of_range("Invalid source state.");
                }
                if(!IsValidState(dest)) {
                    throw std::out_of_range("Invalid dest state");
                }
                TransitionMapEntry newTransition {std::make_tuple(src,label),dest};
                mTransitions.insert(newTransition);
            }

            bool IsValidState(StateId state) const {
                return state < mFinalStates.size();
            }

            bool IsValidLabel(Label label) const {
                return label < ALPHABET_SIZE;
            }

            ArcRange GetNext(StateId src, Label label) const {
                std::tuple<StateId,Label> key(src,label);
                return ArcRange( mTransitions.equal_range(key) );
            }

            bool IsFinal(StateId state) const {
                if(!IsValidState(state)) {
                    return false;
                }
                return mFinalStates[state];
            }

        private:
            boost::container::flat_multimap<std::tuple<StateId,Label>,StateId> mTransitions;
            boost::dynamic_bitset<> mFinalStates;
    };

    typedef NAutomaton<2> NFA;

    template<typename StateId, typename Label>
    StateId ArcSource( const std::pair<std::tuple<StateId,Label>,StateId> &entry ) {
        return std::get<0>(entry->first);
    }

    template<typename StateId, typename Label>
    StateId ArcLabel( const std::pair<std::tuple<StateId,Label>,StateId> &entry ) {
        return std::get<1>(entry->first);
    }

    template<typename StateId, typename Label>
    StateId ArcDestination( const std::pair<std::tuple<StateId,Label>,StateId> &entry ) {
        return entry.second; // std::get<0>(entry->first);
    }
}


text:
#define BOOST_MPL11_NO_ASSERTIONS
#include <boost/mpl11/detail/left_folds/bounded.hpp>
#include <boost/mpl11/list.hpp>

<%= render('_main.erb') do |f, state, xs|
    list = "boost::mpl11::list<#{xs.join(', ')}>"
    <<-EOS
    boost::mpl11::detail::left_folds::bounded<
        #{xs.size}, #{f}::type::apply, #{state}, #{list}
    >
    EOS
end %>


text:
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2007-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)
//
// See http://www.boost.org/libs/interprocess for documentation.
//
//////////////////////////////////////////////////////////////////////////////

#ifndef BOOST_INTERPROCESS_SYNC_NAMED_CREATION_FUNCTOR_HPP
#define BOOST_INTERPROCESS_SYNC_NAMED_CREATION_FUNCTOR_HPP

#ifndef BOOST_CONFIG_HPP
#  include <boost/config.hpp>
#endif
#
#if defined(BOOST_HAS_PRAGMA_ONCE)
#  pragma once
#endif

#include <boost/interprocess/creation_tags.hpp>
#include <boost/interprocess/detail/type_traits.hpp>
#include <boost/interprocess/detail/mpl.hpp>
#include <boost/container/detail/placement_new.hpp>

namespace boost {
namespace interprocess {
namespace ipcdetail {

struct named_creation_functor_no_arg{};

template <class T, class Arg = named_creation_functor_no_arg>
class named_creation_functor
{
   typedef named_creation_functor_no_arg no_arg_t;
   public:
   named_creation_functor(create_enum_t type, Arg arg = Arg())
      :  m_creation_type(type), m_arg(arg){}

   template<class ArgType>
   void construct(void *address, typename enable_if_c<is_same<ArgType, no_arg_t>::value>::type * = 0) const
   {  ::new(address, boost_container_new_t())T; }

   template<class ArgType>
   void construct(void *address, typename enable_if_c<!is_same<ArgType, no_arg_t>::value>::type * = 0) const
   {  ::new(address, boost_container_new_t())T(m_arg); }

   bool operator()(void *address, std::size_t, bool created) const
   {
      switch(m_creation_type){
         case DoOpen:
            return true;
         break;
         case DoCreate:
         case DoOpenOrCreate:
            if(created){
               construct<Arg>(address);
            }
            return true;
         break;

         default:
            return false;
         break;
      }
   }

   std::size_t get_min_size() const
   {  return sizeof(T);  }

   private:
   create_enum_t m_creation_type;
   Arg m_arg;
};

}  //namespace ipcdetail {
}  //namespace interprocess {
}  //namespace boost {

#endif   //BOOST_INTERPROCESS_SYNC_NAMED_CREATION_FUNCTOR_HPP

max_stars_repo_name: multi-os-engine/cinder-natj-binding

max_issues_repo_name: multi-os-engine/cinder-natj-binding

max_forks_repo_name: multi-os-engine/cinder-natj-binding