text:
//          Copyright Oliver Kowalke 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)

#ifndef BOOST_FIBERS_ASIO_ROUND_ROBIN_H
#define BOOST_FIBERS_ASIO_ROUND_ROBIN_H

#include <chrono>
#include <cstddef>
#include <memory>
#include <mutex>
#include <queue>

#include <boost/asio.hpp>
#include <boost/assert.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/config.hpp>

#include <boost/fiber/condition_variable.hpp>
#include <boost/fiber/context.hpp>
#include <boost/fiber/mutex.hpp>
#include <boost/fiber/operations.hpp>
#include <boost/fiber/scheduler.hpp>

#include "yield.hpp"

#ifdef BOOST_HAS_ABI_HEADERS
#  include BOOST_ABI_PREFIX
#endif

namespace boost {
namespace fibers {
namespace asio {

class round_robin : public algo::algorithm {
private:
//[asio_rr_suspend_timer
    std::shared_ptr< boost::asio::io_context >      io_ctx_;
    boost::asio::steady_timer                       suspend_timer_;
//]
    boost::fibers::scheduler::ready_queue_type      rqueue_{};
    boost::fibers::mutex                            mtx_{};
    boost::fibers::condition_variable               cnd_{};
    std::size_t                                     counter_{ 0 };

public:
//[asio_rr_service_top
    struct service : public boost::asio::io_context::service {
        static boost::asio::io_context::id                  id;

        std::unique_ptr< boost::asio::io_context::work >    work_;

        service( boost::asio::io_context & io_ctx) :
            boost::asio::io_context::service( io_ctx),
            work_{ new boost::asio::io_context::work( io_ctx) } {
        }

        virtual ~service() {}

        service( service const&) = delete;
        service & operator=( service const&) = delete;

        void shutdown_service() override final {
            work_.reset();
        }
    };
//]

//[asio_rr_ctor
    round_robin( std::shared_ptr< boost::asio::io_context > const& io_ctx_) :
        io_ctx_( io_ctx),
        suspend_timer_( * io_ctx_) {
        // We use add_service() very deliberately. This will throw
        // service_already_exists if you pass the same io_context instance to
        // more than one round_robin instance.
        boost::asio::add_service( * io_ctx_, new service( * io_ctx_) );
        boost::asio::post( * io_ctx_, [this]() mutable {
//]
//[asio_rr_service_lambda
                while ( ! io_ctx_->stopped() ) {
                    if ( has_ready_fibers() ) {
                        // run all pending handlers in round_robin
                        while ( io_ctx_->poll() );
                        // block this fiber till all pending (ready) fibers are processed
                        // == round_robin::suspend_until() has been called
                        std::unique_lock< boost::fibers::mutex > lk( mtx_);
                        cnd_.wait( lk);
                    } else {
                        // run one handler inside io_context
                        // if no handler available, block this thread
                        if ( ! io_ctx_->run_one() ) {
                            break;
                        }
                    }
               }
//]
            });
    }

    void awakened( context * ctx) noexcept {
        BOOST_ASSERT( nullptr != ctx);
        BOOST_ASSERT( ! ctx->ready_is_linked() );
        ctx->ready_link( rqueue_); /*< fiber, enqueue on ready queue >*/
        if ( ! ctx->is_context( boost::fibers::type::dispatcher_context) ) {
            ++counter_;
        }
    }

    context * pick_next() noexcept {
        context * ctx( nullptr);
        if ( ! rqueue_.empty() ) { /*<
            pop an item from the ready queue
        >*/
            ctx = & rqueue_.front();
            rqueue_.pop_front();
            BOOST_ASSERT( nullptr != ctx);
            BOOST_ASSERT( context::active() != ctx);
            if ( ! ctx->is_context( boost::fibers::type::dispatcher_context) ) {
                --counter_;
            }
        }
        return ctx;
    }

    bool has_ready_fibers() const noexcept {
        return 0 < counter_;
    }

//[asio_rr_suspend_until
    void suspend_until( std::chrono::steady_clock::time_point const& abs_time) noexcept {
        // Set a timer so at least one handler will eventually fire, causing
        // run_one() to eventually return.
        if ( (std::chrono::steady_clock::time_point::max)() != abs_time) {
			// Each expires_at(time_point) call cancels any previous pending
			// call. We could inadvertently spin like this:
			// dispatcher calls suspend_until() with earliest wake time
			// suspend_until() sets suspend_timer_
			// lambda loop calls run_one()
			// some other asio handler runs before timer expires
			// run_one() returns to lambda loop
			// lambda loop yields to dispatcher
			// dispatcher finds no ready fibers
			// dispatcher calls suspend_until() with SAME wake time
			// suspend_until() sets suspend_timer_ to same time, canceling
			// previous async_wait()
			// lambda loop calls run_one()
			// asio calls suspend_timer_ handler with operation_aborted
			// run_one() returns to lambda loop... etc. etc.
			// So only actually set the timer when we're passed a DIFFERENT
			// abs_time value.
            suspend_timer_.expires_at( abs_time);
            suspend_timer_.async_wait([](boost::system::error_code const&){
                                        this_fiber::yield();
                                      });
        }
        cnd_.notify_one();
    }
//]

//[asio_rr_notify
    void notify() noexcept {
        // Something has happened that should wake one or more fibers BEFORE
        // suspend_timer_ expires. Reset the timer to cause it to fire
        // immediately, causing the run_one() call to return. In theory we
        // could use cancel() because we don't care whether suspend_timer_'s
        // handler is called with operation_aborted or success. However --
        // cancel() doesn't change the expiration time, and we use
        // suspend_timer_'s expiration time to decide whether it's already
        // set. If suspend_until() set some specific wake time, then notify()
        // canceled it, then suspend_until() was called again with the same
        // wake time, it would match suspend_timer_'s expiration time and we'd
        // refrain from setting the timer. So instead of simply calling
        // cancel(), reset the timer, which cancels the pending sleep AND sets
        // a new expiration time. This will cause us to spin the loop twice --
        // once for the operation_aborted handler, once for timer expiration
        // -- but that shouldn't be a big problem.
        suspend_timer_.async_wait([](boost::system::error_code const&){
                                    this_fiber::yield();
                                  });
        suspend_timer_.expires_at( std::chrono::steady_clock::now() );
    }
//]
};

boost::asio::io_context::id round_robin::service::id;

}}}

#ifdef BOOST_HAS_ABI_HEADERS
#  include BOOST_ABI_SUFFIX
#endif

#endif // BOOST_FIBERS_ASIO_ROUND_ROBIN_H

max_stars_repo_name: anarthal/boost-unix-mirror

max_issues_repo_name: anarthal/boost-unix-mirror


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

#include <boost/hana/assert.hpp>
#include <boost/hana/bool.hpp>
#include <boost/hana/config.hpp>
#include <boost/hana/ext/std/integral_constant.hpp>
#include <boost/hana/functional.hpp>
#include <boost/hana/integral_constant.hpp>
#include <boost/hana/tuple.hpp>
#include <boost/hana/type.hpp>

#include <type_traits>
#include <vector>
using namespace boost::hana;

int main() {

{

//! [and_]
BOOST_HANA_CONSTANT_CHECK(and_(true_, true_, true_, true_));
BOOST_HANA_CONSTEXPR_CHECK(!and_(true_, false, true_, true_));
//! [and_]

}{

//! [or_]
BOOST_HANA_CONSTANT_CHECK(or_(false_, false_, true_));
BOOST_HANA_CONSTANT_CHECK(!or_(false_, false_, false_));
//! [or_]

}{

//! [if_]
BOOST_HANA_CONSTEXPR_CHECK(if_(true, 1, 2) == 1);
BOOST_HANA_CONSTEXPR_CHECK(if_(false, 1, 2) == 2);

BOOST_HANA_CONSTEXPR_CHECK(
    if_(true_,
        make<Tuple>('t', 'r', 'u', 'e'),
        make<Tuple>('f', 'a', 'l', 's', 'e')
    )
    ==
    make<Tuple>('t', 'r', 'u', 'e')
);
//! [if_]

}{

//! [not_]
BOOST_HANA_CONSTANT_CHECK(not_(true_) == false_);
BOOST_HANA_CONSTEXPR_CHECK(not_(false) == true);
//! [not_]

}{

//! [heterogeneous_eval_if]
BOOST_HANA_CONSTEXPR_LAMBDA auto safe_make_unsigned = [](auto t) {
    return eval_if(trait<std::is_integral>(t),
        [=](auto id) { return id(template_<std::make_unsigned_t>)(t); },
        always(t)
    );
};

BOOST_HANA_CONSTANT_CHECK(safe_make_unsigned(type<void>) == type<void>);
BOOST_HANA_CONSTANT_CHECK(safe_make_unsigned(type<int>) == type<unsigned int>);
//! [heterogeneous_eval_if]
(void)safe_make_unsigned;

//! [homogeneous_eval_if]
BOOST_HANA_CONSTEXPR_LAMBDA auto safe_divide = [](auto x, auto y) {
    return eval_if(y == 0,
        [=](auto) { return 0; },
        [=](auto id) { return id(x) / y; }
    );
};

BOOST_HANA_CONSTEXPR_CHECK(safe_divide(6, 3) == 2);
BOOST_HANA_CONSTEXPR_CHECK(safe_divide(6, 0) == 0);
//! [homogeneous_eval_if]

}{

//! [homogeneous_while]
std::vector<int> ints;
int final_state = while_(_ < 10, 0, [&](int i) {
    ints.push_back(i);
    return i + 1;
});

// The state is known only at runtime
BOOST_HANA_RUNTIME_CHECK(final_state == 10);

BOOST_HANA_RUNTIME_CHECK(ints == std::vector<int>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
//! [homogeneous_while]

}{

//! [heterogeneous_while]
using namespace literals;
std::vector<int> ints;
auto final_state = while_(_ < 10_c, 0_c, [&](auto i) {
    ints.push_back(i);
    return i + 1_c;
});

// The state is known at compile-time
BOOST_HANA_CONSTANT_CHECK(final_state == 10_c);

BOOST_HANA_RUNTIME_CHECK(ints == std::vector<int>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
//! [heterogeneous_while]

}{

//! [homogeneous_until]
std::vector<int> ints;
int final_state = until(_ == 10, 0, [&](int i) {
    ints.push_back(i);
    return i + 1;
});

// The state is known only at runtime
BOOST_HANA_RUNTIME_CHECK(final_state == 10);

BOOST_HANA_RUNTIME_CHECK(ints == std::vector<int>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
//! [homogeneous_until]

}{

//! [heterogeneous_until]
using namespace literals;
std::vector<int> ints;
auto final_state = until(_ == 10_c, 0_c, [&](auto i) {
    ints.push_back(i);
    return i + 1_c;
});

// The state is known at compile-time
BOOST_HANA_CONSTANT_CHECK(final_state == 10_c);

BOOST_HANA_RUNTIME_CHECK(ints == std::vector<int>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
//! [heterogeneous_until]

}

}

ext: cpp

max_stars_repo_name: josephwinston/hana

max_issues_repo_name: josephwinston/hana

max_forks_repo_name: josephwinston/hana


text:
/******************************************************************
*
* Round for C++
*
* Copyright (C) Satoshi Konno 2015
*
* This is licensed under BSD-style license, see file COPYING.
*
******************************************************************/

#include <boost/algorithm/string.hpp>
#include <round/common/RPC.h>
#include <round/common/encoding/URL.h>

Round::RPC::JSON::Request::Request() {
}

Round::RPC::JSON::Request::~Request() {
}

bool Round::RPC::JSON::Request::isValid() {
  if (!hasKey(JSON_RPC))
    return false;

  if (!hasKey(METHOD))
    return false;

  JSONObject *methodObj;
  if (!get(METHOD, &methodObj))
    return false;

  if (!methodObj->isString())
    return false;

  return true;
}

bool Round::RPC::JSON::Request::isNotify() {
  if (!isValid())
    return false;
  return !hasKey(ID);
}

bool Round::RPC::JSON::Request::isMethod(const std::string &method) const {
  std::string reqMethod;
  if (!get(METHOD, &reqMethod))
    return false;
  return (method.compare(reqMethod) == 0) ? true : false;
}

bool Round::RPC::JSON::Request::isJSONParams() const {
  if (!hasParams())
    return false;

  std::string params;
  if (!getParams(&params))
    return false;

  JSONParser jsonParser;
  Error err;

  if (!jsonParser.parse(params, &err))
    return false;

  return true;
}

void Round::RPC::JSON::Request::toHTTPPostRequest(uHTTP::HTTPRequest *httpReq) const {
  if (!httpReq)
    return;

  httpReq->setMethod(RPC::JSON::HTTP::METHOD);
  httpReq->setURI(RPC::JSON::HTTP::ENDPOINT);
  httpReq->setContentType(RPC::JSON::HTTP::CONTENT_TYPE);

  std::string jsonString;
  toJSONString(&jsonString);
  httpReq->setContent(jsonString);
}

void Round::RPC::JSON::Request::toHTTPGetRequest(uHTTP::HTTPRequest *httpReq, bool jsonRpcEncodeEnable) const {
  if (!httpReq)
    return;

  httpReq->setMethod(RPC::JSON::HTTP::GET_METHOD);
  httpReq->setContentType(RPC::JSON::HTTP::CONTENT_TYPE);

  std::stringstream uriBuf;
  std::string paramVal;

  uriBuf << RPC::JSON::HTTP::ENDPOINT;
  if (getMethod(&paramVal)) {
    uriBuf << "?" << RPC::JSON::Message::METHOD << "=" << paramVal;

    if (getParams(&paramVal)) {
      std::string encodedStr;
      if (jsonRpcEncodeEnable) {
        if (RPC::JSON::Encode((byte *)paramVal.c_str(), paramVal.length(), &encodedStr)) {
          uriBuf << "&" << RPC::JSON::Message::PARAMS << "=" << encodedStr;
        }
      }
      else {
        URL::Encode(paramVal, &encodedStr);
        uriBuf << "&" << RPC::JSON::Message::PARAMS << "=" << encodedStr;
        uriBuf << "&" << RPC::JSON::HTTP::ENCORD << "=" << RPC::JSON::HTTP::ENCORD_NONE;
      }
    }

    for (JSONDictionary::const_iterator jsonObjIt = begin(); jsonObjIt != end(); jsonObjIt++) {
      std::string key = jsonObjIt->first;
      if (key.compare(RPC::JSON::Message::METHOD) == 0)
        continue;
      if (key.compare(RPC::JSON::Message::PARAMS) == 0)
        continue;

      JSONObject *jsonObj = jsonObjIt->second;
      if (!jsonObj)
        continue;
      std::string jsonObjStr;
      if (!jsonObj->toJSONString(&jsonObjStr))
        continue;
      boost::trim_if(jsonObjStr, boost::is_any_of("\""));

      uriBuf << "&" << key << "=" << jsonObjStr;
    }
  }

  httpReq->setURI(uriBuf.str());
}

max_stars_repo_name: cybergarage/round-cc

max_issues_repo_name: cybergarage/round-cc

max_forks_repo_name: cybergarage/round-cc


text:
/*! \file
    \brief A property set file path.

    Copyright (C) 2019-2021 kaoru  https://www.tetengo.org/
*/

#include <filesystem>
#include <stdexcept>

#include <boost/preprocessor.hpp>
#include <boost/test/unit_test.hpp>

#include <tetengo/platform_dependent/propertyX.hpp>

BOOST_AUTO_TEST_SUITE(test_tetengo)
BOOST_AUTO_TEST_SUITE(platform_dependent)
BOOST_AUTO_TEST_SUITE(property_set_file_path)

BOOST_AUTO_TEST_CASE(instance)
{
    BOOST_TEST_PASSPOINT();

    [[maybe_unused]] const auto& resolver = tetengo::platform_dependent::property_set_file_path::instance();
}

BOOST_AUTO_TEST_CASE(to_native_path)
{
    BOOST_TEST_PASSPOINT();

    {
        const auto& resolver = tetengo::platform_dependent::property_set_file_path::instance();
        const auto  native_path = resolver.to_native_path(std::filesystem::path{ "hoge" });
    }
    {
        const auto& resolver = tetengo::platform_dependent::property_set_file_path::instance();
        const auto  native_path = resolver.to_native_path(std::filesystem::path{ "hoge" } / "fuga");
    }
    {
        const auto& resolver = tetengo::platform_dependent::property_set_file_path::instance();
        BOOST_CHECK_THROW(
            const auto native_path = resolver.to_native_path(std::filesystem::path{}), std::invalid_argument);
    }
}

BOOST_AUTO_TEST_CASE(to_native_top_path)
{
    BOOST_TEST_PASSPOINT();

    {
        const auto& resolver = tetengo::platform_dependent::property_set_file_path::instance();
        const auto  native_path = resolver.to_native_top_path(std::filesystem::path{ "hoge" });
    }
    {
        const auto& resolver = tetengo::platform_dependent::property_set_file_path::instance();
        const auto  native_path = resolver.to_native_top_path(std::filesystem::path{ "hoge" } / "fuga");
    }
    {
        const auto& resolver = tetengo::platform_dependent::property_set_file_path::instance();
        BOOST_CHECK_THROW(
            const auto native_path = resolver.to_native_top_path(std::filesystem::path{}), std::invalid_argument);
    }
}

BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: kaorut/tetengo

max_issues_repo_name: kaorut/tetengo

max_forks_repo_name: kaorut/tetengo


text:
/*
 * ConfigFile.cpp
 *
 *  Created on: 20 Oct 2011
 *      Author: kreczko
 */

#include "../../interface/Python/ConfigFile.h"
#include "../../interface/Python/PythonParser.h"
#include "../../interface/GlobalVariables.h"

#include "TF1.h"
#include "TFile.h"

#include <iostream>
#include <iomanip>

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

using namespace std;

namespace BAT {
const string DEFAULT_CONFIG_PATH = "python/default_cfg.py";

ConfigFile::ConfigFile(int argc, char **argv) :
		programOptions(getParameters(argc, argv)), //
		config(PythonParser::parse_python_file(configPath())), //
		maxEvents_(PythonParser::getAttributeFromPyObject<long>(config, "maxEvents")), //
		datasetInfoFile_(PythonParser::getAttributeFromPyObject<string>(config, "datasetInfoFile")), //
		pileUpFile_(PythonParser::getAttributeFromPyObject<string>(config, "PUFile")), //
		ttbarLikelihoodFile_(PythonParser::getAttributeFromPyObject<string>(config, "TTbarLikelihoodFile")), //
		btagEfficiencyFile_(PythonParser::getAttributeFromPyObject<string>(config, "BTagEfficiencyFile")), //
		getMuonScaleFactorsFromFile_(PythonParser::getAttributeFromPyObject<bool>(config, "getMuonScaleFactorsFromFile")), //
		muonIdIsoScaleFactorsFile_(PythonParser::getAttributeFromPyObject<string>(config, "MuonIdIsoScaleFactorsFile")), //
		muonTriggerScaleFactorsFile_(PythonParser::getAttributeFromPyObject<string>(config, "MuonTriggerScaleFactorsFile")), //
		getElectronScaleFactorsFromFile_(PythonParser::getAttributeFromPyObject<bool>(config, "getElectronScaleFactorsFromFile")), //
		electronIdIsoScaleFactorsFile_(PythonParser::getAttributeFromPyObject<string>(config, "ElectronIdIsoScaleFactorsFile")), //
		electronTriggerScaleFactorsFile_(PythonParser::getAttributeFromPyObject<string>(config, "ElectronTriggerScaleFactorsFile")), //
		bJetResoFile_(PythonParser::getAttributeFromPyObject<string>(config, "bJetResoFile")), //
		lightJetResoFile_(PythonParser::getAttributeFromPyObject<string>(config, "lightJetResoFile")), //
		getHadronTriggerFromFile_(PythonParser::getAttributeFromPyObject<bool>(config, "getHadronTriggerFromFile")), //
		hadronTriggerFile_(PythonParser::getAttributeFromPyObject<string>(config, "hadronTriggerFile")), //
		useHitFit_(PythonParser::getAttributeFromPyObject<bool>(config, "useHitFit")), //
		fitterOutputFlag_(PythonParser::getAttributeFromPyObject<bool>(config, "produceFitterASCIIoutput")), //
		inputFiles_(PythonParser::getVectorFromPythonObject(config, "inputFiles")), //
		tqafPath_(PythonParser::getAttributeFromPyObject<string>(config, "TQAFPath")), //
		lumi_(PythonParser::getAttributeFromPyObject<double>(config, "lumi")), //
		centerOfMassEnergy_(PythonParser::getAttributeFromPyObject<unsigned int>(config, "centerOfMassEnergy")), //
		nTupleVersion_(PythonParser::getAttributeFromPyObject<unsigned int>(config, "nTuple_version")), //
		electronScaleFactorSystematic_(0), //
		muonScaleFactorSystematic_(0), //
		jesSystematic_(0), //
		jetSmearingSystematic_(0), //
		btagSystematic_(0), //
		lightTagSystematic_(0), //
		custom_file_suffix_(""), //
		pdfWeightNumber_(0), //
		applyMetSysShiftCorr_(0), //
		applyMetType0Corr_(0), //
		applyMetType1Corr_(0), //
		applyJetSmearing_(0), //
		applyTopPtReweighting_(0), //
		verbose_(0) {
	if (PythonParser::hasAttribute(config, "ElectronScaleFactorSystematic"))
		electronScaleFactorSystematic_ = PythonParser::getAttributeFromPyObject<int>(config, "ElectronScaleFactorSystematic");
	if (PythonParser::hasAttribute(config, "MuonScaleFactorSystematic"))
		muonScaleFactorSystematic_ = PythonParser::getAttributeFromPyObject<int>(config, "MuonScaleFactorSystematic");
	if (PythonParser::hasAttribute(config, "JESsystematic"))
		jesSystematic_ = PythonParser::getAttributeFromPyObject<int>(config, "JESsystematic");
	if (PythonParser::hasAttribute(config, "JetSmearingSystematic"))
		jetSmearingSystematic_ = PythonParser::getAttributeFromPyObject<int>(config, "JetSmearingSystematic");
	if (PythonParser::hasAttribute(config, "BTagSystematic"))
		btagSystematic_ = PythonParser::getAttributeFromPyObject<int>(config, "BTagSystematic");
	if (PythonParser::hasAttribute(config, "LightTagSystematic"))
		lightTagSystematic_ = PythonParser::getAttributeFromPyObject<int>(config, "LightTagSystematic");
	if (PythonParser::hasAttribute(config, "custom_file_suffix"))
		custom_file_suffix_ = PythonParser::getAttributeFromPyObject<string>(config, "custom_file_suffix");
	if (PythonParser::hasAttribute(config, "pdfWeightNumber"))
		pdfWeightNumber_ = PythonParser::getAttributeFromPyObject<unsigned int>(config, "pdfWeightNumber");
	if (PythonParser::hasAttribute(config, "applyMetSysShiftCorr"))
		applyMetSysShiftCorr_ = PythonParser::getAttributeFromPyObject<bool>(config, "applyMetSysShiftCorr");
	if (PythonParser::hasAttribute(config, "applyMetType0Corr"))
		applyMetType0Corr_ = PythonParser::getAttributeFromPyObject<bool>(config, "applyMetType0Corr");
	if (PythonParser::hasAttribute(config, "applyMetType1Corr"))
		applyMetType1Corr_ = PythonParser::getAttributeFromPyObject<bool>(config, "applyMetType1Corr");
	if (PythonParser::hasAttribute(config, "applyJetSmearing"))
		applyJetSmearing_ = PythonParser::getAttributeFromPyObject<bool>(config, "applyJetSmearing");
	if (PythonParser::hasAttribute(config, "applyTopPtReweighting"))
		applyTopPtReweighting_ = PythonParser::getAttributeFromPyObject<bool>(config, "applyTopPtReweighting");
}

boost::program_options::variables_map ConfigFile::getParameters(int argc, char** argv) {
	using namespace boost::program_options;
	variables_map vm;
	positional_options_description p;
	p.add("config-file", -1);

	// Declare the supported options.
	options_description desc("Allowed options");
	desc.add_options()("help,h", "produce help message");
	desc.add_options()("maxEvents", value<unsigned long>(), "set maximal number of events to be processed");
	desc.add_options()("config-file", value<std::string>(), "Configuration file for BAT");
	desc.add_options()("datasetInfoFile", value<std::string>(),
			"Dataset information file for event weight calculation");
	desc.add_options()("PUFile", value<std::string>(), "set input PU file for PU re-weighting");
	desc.add_options()("TTbarLikelihoodFile", value<std::string>(), "set input file for ttbar likelihood reconstruction");
	desc.add_options()("BTagEfficiencyFile", value<std::string>(), "set input file for b tag efficiency");
	desc.add_options()("getMuonScaleFactorsFromFile", value<bool>(), "state whether we are getting the muon scale factors from a file or not");
	desc.add_options()("MuonIdIsoScaleFactorsFile", value<std::string>(), "set input file for id iso muon scale factors");
	desc.add_options()("MuonTriggerScaleFactorsFile", value<std::string>(), "set input file for trigger muon scale factors");
	desc.add_options()("getElectronScaleFactorsFromFile", value<bool>(), "state whether we are getting the electron scale factors from a file or not");
	desc.add_options()("ElectronIdIsoScaleFactorsFile", value<std::string>(), "set input file for electron ID & ISO scale factors");
	desc.add_options()("ElectronTriggerScaleFactorsFile", value<std::string>(), "set input file for electron trigger scale factors");
	desc.add_options()("bJetResoFile", value<std::string>(), "set input root file for b-jet L7 resolutions");
	desc.add_options()("lightJetResoFile", value<std::string>(), "set input root file for light jet L7 resolutions");
	desc.add_options()("getHadronTriggerFromFile", value<bool>(), "state whether we are getting the electron trigger hadron leg efficiencies from a file or not");
	desc.add_options()("fitter", value<bool>(), "turn on the fitter (HitFit)");
	desc.add_options()("fitterASCIIoutput", value<bool>(), "produce full kinematic fit output in ASCII format");
	desc.add_options()("TQAFPath", value<std::string>(),
			"path to TopQuarkAnalysis folder (the folder itself not included).");
	desc.add_options()("lumi", value<std::string>(), "Integrated luminosity the MC simulation will be scaled to");
	desc.add_options()("ElectronScaleFactorSystematic", value<int>(),
			"Electron ID, Iso and Trigger scale factor systematic,  the +/- number of uncertainties to vary the scale factor with");
	desc.add_options()("MuonScaleFactorSystematic", value<int>(),
			"Muon ID, Iso and Trigger scale factor systematic,  the +/- number of uncertainties to vary the scale factor with");
	desc.add_options()("BTagSystematic", value<int>(),
			"B-tag scale factor systematic, the +/- number of uncertainties to vary the scale factor with");
	desc.add_options()("LightTagSystematic", value<int>(),
			"Light-tag scale factor systematic, the +/- number of uncertainties to vary the scale factor with");
	desc.add_options()("JESsystematic", value<int>(),
			"JES systematic, the +/- number of uncertainties to vary the jet with");
	desc.add_options()("JetSmearingSystematic", value<int>(),
			"Jet Smearing Systematic, the +/- number of uncertainties to vary the jet with");
	desc.add_options()("custom_file_suffix", value<std::string>(), "Custom file suffix, will be appended to file name");
	desc.add_options()("pdfWeightNumber", value<unsigned int>(),
			"Number of PDF weight to multiply the event weight with");
	desc.add_options()("applyMetSysShiftCorr", value<bool>(), "apply MET systematic shift correction for phi modulation");
	desc.add_options()("applyMetType0Corr", value<bool>(), "apply MET type-0 correction (for PU)");
	desc.add_options()("applyMetType1Corr", value<bool>(), "apply MET type-1 correction (JEC)");
	desc.add_options()("applyJetSmearing", value<bool>(), "apply Jet Smearing");
	desc.add_options()("applyTopPtReweighting", value<bool>(), "apply Top Pt Reweighting");

	desc.add_options()("verbose", value<bool>(), "enable verose output");

	store(command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
	notify(vm);
	if (vm.count("help")) {
		cout << desc << "\n";
		exit(0);
		return 0;
	}

	return vm;
}

boost::array<boost::shared_ptr<TF1>, 12> ConfigFile::getL7Correction(std::string correctionFile) {
	boost::array<boost::shared_ptr<TF1>, 12> correctionsArray;

	boost::array<double, 12> towerBinning = { { 0., 0.174, 0.348, 0.522, 0.696, 0.87, 1.044, 1.218, 1.392, 1.566, 1.74,
			2.5 } };
	if (!boost::filesystem::exists(correctionFile)) {
		cerr << "ConfigFile::getL7Correction(" << correctionFile << "): could not find file" << endl;
		throw "Could not find L7 correction path in " + correctionFile;
	}

	boost::scoped_ptr<TFile> inputFile(TFile::Open(correctionFile.c_str()));

	for (unsigned int etaBin = 0; etaBin < towerBinning.size() - 1; ++etaBin) {
		stringstream graphname;
		graphname << "mean_relative_et_" << fixed << setprecision(3) << towerBinning[etaBin];
		graphname << "_" << fixed << setprecision(3) << towerBinning[etaBin + 1];
		boost::shared_ptr<TF1> corrections((TF1*) inputFile->Get(graphname.str().c_str()));
		correctionsArray[etaBin] = corrections;
	}

	inputFile->Close();
	return correctionsArray;
}

string ConfigFile::bJetResoFile() const {
	if (programOptions.count("bJetResoFile"))
		return programOptions["bJetResoFile"].as<std::string>();
	else
		return bJetResoFile_;
}

string ConfigFile::lightJetResoFile() const {
	if (programOptions.count("lightJetResoFile"))
		return programOptions["lightJetResoFile"].as<std::string>();
	else
		return lightJetResoFile_;
}

string ConfigFile::TQAFPath() const {
	if (programOptions.count("TQAFPath"))
		return programOptions["TQAFPath"].as<std::string>();
	else
		return tqafPath_;
}

string ConfigFile::configPath() const {
	if (programOptions.count("config-file"))
		return programOptions["config-file"].as<std::string>();
	else
		return DEFAULT_CONFIG_PATH;
}

string ConfigFile::PUFile() const {
	if (programOptions.count("PUFile"))
		return programOptions["PUFile"].as<std::string>();
	else
		return pileUpFile_;
}

string ConfigFile::TTbarLikelihoodFile() const {
	if (programOptions.count("TTbarLikelihoodFile"))
		return programOptions["TTbarLikelihoodFile"].as<std::string>();
	else
		return ttbarLikelihoodFile_;
}

string ConfigFile::BTagEfficiencyFile() const {
	if (programOptions.count("BTagEfficiencyFile"))
		return programOptions["BTagEfficiencyFile"].as<std::string>();
	else
		return btagEfficiencyFile_;
}

string ConfigFile::MuonIdIsoScaleFactorsFile() const {
	if (programOptions.count("MuonIdIsoScaleFactorsFile"))
		return programOptions["MuonIdIsoScaleFactorsFile"].as<std::string>();
	else
		return muonIdIsoScaleFactorsFile_;
}

string ConfigFile::MuonTriggerScaleFactorsFile() const {
	if (programOptions.count("MuonTriggerScaleFactorsFile"))
		return programOptions["MuonTriggerScaleFactorsFile"].as<std::string>();
	else
		return muonTriggerScaleFactorsFile_;
}

string ConfigFile::ElectronIdIsoScaleFactorsFile() const {
	if (programOptions.count("ElectronIdIsoScaleFactorsFile"))
		return programOptions["ElectronIdIsoScaleFactorsFile"].as<std::string>();
	else
		return electronIdIsoScaleFactorsFile_;
}

string ConfigFile::ElectronTriggerScaleFactorsFile() const {
	if (programOptions.count("ElectronTriggerScaleFactorsFile"))
		return programOptions["ElectronTriggerScaleFactorsFile"].as<std::string>();
	else
		return electronTriggerScaleFactorsFile_;
}

string ConfigFile::hadronTriggerFile() const {
	if (programOptions.count("hadronTriggerFile"))
		return programOptions["hadronTriggerFile"].as<std::string>();
	else
		return hadronTriggerFile_;
}

string ConfigFile::datasetInfoFile() const {
	if (programOptions.count("datasetInfoFile"))
		return programOptions["datasetInfoFile"].as<std::string>();
	else
		return datasetInfoFile_;
}

long ConfigFile::maxEvents() const {
	if (programOptions.count("maxEvents"))
		return programOptions["maxEvents"].as<unsigned long>();
	else
		return maxEvents_;
}

bool ConfigFile::useHitFit() const {
	if (programOptions.count("fitter"))
		return programOptions["fitter"].as<bool>();
	else
		return useHitFit_;
}

unsigned int ConfigFile::centerOfMassEnergy() const {
	if (programOptions.count("centerOfMassEnergy"))
		return programOptions["centerOfMassEnergy"].as<unsigned int>();
	else
		return centerOfMassEnergy_;
}

bool ConfigFile::fitterOutputFlag() const {
	if (programOptions.count("fitterASCIIoutput"))
		return programOptions["fitterASCIIoutput"].as<bool>();
	else
		return fitterOutputFlag_;
}

const vector<string>& ConfigFile::inputFiles() const {
	return inputFiles_;
}

double ConfigFile::lumi() const {
	if (programOptions.count("lumi"))
		return programOptions["lumi"].as<double>();
	else
		return lumi_;
}

int ConfigFile::electronScaleFactorSystematic() const {
	if (programOptions.count("ElectronScaleFactorSystematic"))
		return programOptions["ElectronScaleFactorSystematic"].as<int>();
	else
		return electronScaleFactorSystematic_;
}

int ConfigFile::muonScaleFactorSystematic() const {
	if (programOptions.count("MuonScaleFactorSystematic"))
		return programOptions["MuonScaleFactorSystematic"].as<int>();
	else
		return muonScaleFactorSystematic_;
}

int ConfigFile::jesSystematic() const {
	if (programOptions.count("JESsystematic"))
		return programOptions["JESsystematic"].as<int>();
	else
		return jesSystematic_;
}

int ConfigFile::jetSmearingSystematic() const {
	if (programOptions.count("JetSmearingSystematic"))
		return programOptions["JetSmearingSystematic"].as<int>();
	else
		return jetSmearingSystematic_;
}

int ConfigFile::BtagSystematic() const {
	if (programOptions.count("BTagSystematic"))
		return programOptions["BTagSystematic"].as<int>();
	else
		return btagSystematic_;
}
int ConfigFile::LightTagSystematic() const {
	if (programOptions.count("LightTagSystematic"))
		return programOptions["LightTagSystematic"].as<int>();
	else
		return lightTagSystematic_;
}

string ConfigFile::custom_file_suffix() const {
	if (programOptions.count("custom_file_suffix"))
		return programOptions["custom_file_suffix"].as<string>();
	else
		return custom_file_suffix_;
}

unsigned int ConfigFile::pdfWeightNumber() const {
	if (programOptions.count("pdfWeightNumber"))
		return programOptions["pdfWeightNumber"].as<unsigned int>();
	else
		return pdfWeightNumber_;
}

bool ConfigFile::applyMetSysShiftCorr() const {
	if (programOptions.count("applyMetSysShiftCorr"))
		return programOptions["applyMetSysShiftCorr"].as<bool>();
	else
		return applyMetSysShiftCorr_;
}

bool ConfigFile::applyMetType0Corr() const {
	if (programOptions.count("applyMetType0Corr"))
		return programOptions["applyMetType0Corr"].as<bool>();
	else
		return applyMetType0Corr_;
}

bool ConfigFile::applyMetType1Corr() const {
	if (programOptions.count("applyMetType1Corr"))
		return programOptions["applyMetType1Corr"].as<bool>();
	else
		return applyMetType1Corr_;
}

bool ConfigFile::applyJetSmearing() const {
	if (programOptions.count("applyJetSmearing"))
		return programOptions["applyJetSmearing"].as<bool>();
	else
		return applyJetSmearing_;
}

bool ConfigFile::applyTopPtReweighting() const {
	if (programOptions.count("applyTopPtReweighting"))
		return programOptions["applyTopPtReweighting"].as<bool>();
	else
		return applyTopPtReweighting_;
}

bool ConfigFile::verbose() const {
	if (programOptions.count("verbose"))
		return programOptions["verbose"].as<bool>();
	else
		return verbose_;
}

ConfigFile::~ConfigFile() {
}

PileUpReweightingMethod::value ConfigFile::PileUpReweightingMethod() const {
	std::string option = "";

	if (isOptionSetInConsole("pileUpReweightingMethod")) {
		option = programOptions["pileUpReweightingMethod"].as<std::string>();
	} else if (isOptionSetInConfig(option)) {
		option = PythonParser::getAttributeFromPyObject<std::string>(config, "pileUpReweightingMethod");
	} else
		return Globals::pileUpReweightingMethod;

	if (option == "averagePileUp")
		return PileUpReweightingMethod::averagePileUp;
	else if (option == "inTimePileUpOnly")
		return PileUpReweightingMethod::inTimePileUpOnly;
	else if (option == "threeDReweighting")
		return PileUpReweightingMethod::threeDReweighting;
	else {
		cout << "WARNING: Unknown or empty pile up reweighting option '" << option << "', using default" << endl;
		return Globals::pileUpReweightingMethod;
	}
}

bool ConfigFile::isOptionSet(std::string option) const {
	bool isInProgramOptions(isOptionSetInConsole(option));
	bool isInConfigFile(isOptionSetInConfig(option));

	return isInProgramOptions || isInConfigFile;
}

bool ConfigFile::isOptionSetInConsole(std::string option) const {
	return programOptions.count(option);
}

bool ConfigFile::isOptionSetInConfig(std::string option) const {
	return PyObject_HasAttrString(config.ptr(), option.c_str());
}

void ConfigFile::loadIntoMemory() {

	//always use function to access the variables
	//general
	Globals::luminosity = lumi();
	Globals::maxEvents = maxEvents();
	Globals::NTupleVersion = nTupleVersion();
	Globals::energyInTeV = centerOfMassEnergy();

	//kinematic fit
	Globals::TQAFPath = TQAFPath();
	Globals::useHitFit = useHitFit();
	Globals::produceFitterASCIIoutput = fitterOutputFlag();

	 Globals::estimatedPileup = getPileUpHistogram(PUFile());

	//Lepton Scale Factors
	Globals::ElectronScaleFactorSystematic = electronScaleFactorSystematic();
	Globals::MuonScaleFactorSystematic = muonScaleFactorSystematic();
	std::cout << "ConfigFile.cpp: Globals::ElectronScaleFactorSystematic = " << Globals::ElectronScaleFactorSystematic << std::endl;
	std::cout << "ConfigFile.cpp: Globals::MuonScaleFactorSystematic = " << Globals::MuonScaleFactorSystematic << std::endl;

	if ( getMuonScaleFactorsFromFile_ && boost::filesystem::exists(MuonTriggerScaleFactorsFile()) && boost::filesystem::exists(MuonIdIsoScaleFactorsFile()) ) {
		std::cout << "Getting muon scale factors from files " << MuonIdIsoScaleFactorsFile() << " and " << MuonTriggerScaleFactorsFile()  << "." << std::endl;
		Globals::muonIdIsoScaleFactorsHistogram = getMuonIdIsoScaleFactorsHistogram(MuonIdIsoScaleFactorsFile());
		Globals::muonTriggerScaleFactorsHistogram = getMuonTriggerScaleFactorsHistogram(MuonTriggerScaleFactorsFile());
	}

	if ( getElectronScaleFactorsFromFile_ && boost::filesystem::exists(ElectronTriggerScaleFactorsFile()) && boost::filesystem::exists(ElectronIdIsoScaleFactorsFile()) ) {
		std::cout << "Getting electron scale factors from file " << ElectronTriggerScaleFactorsFile() << " and " << ElectronIdIsoScaleFactorsFile()  << std::endl;
		Globals::electronTriggerScaleFactorsHistogram = getElectronTriggerScaleFactorsHistogram(ElectronTriggerScaleFactorsFile());
		Globals::electronIdIsoScaleFactorsHistogram = getElectronIdIsoScaleFactorsHistogram(ElectronIdIsoScaleFactorsFile());

	}

	// if (Globals::energyInTeV == 7 && getElectronScaleFactorsFromFile_ && boost::filesystem::exists(ElectronIdIsoScaleFactorsFile()) && boost::filesystem::exists(ElectronTriggerScaleFactorsFile())) {
	// 	std::cout << "Getting electron scale factors from file " << ElectronIdIsoScaleFactorsFile() << " and " << ElectronTriggerScaleFactorsFile() << "." << std::endl;
	// 	Globals::electronIdIsoScaleFactorsHistogram = getElectronIdIsoScaleFactorsHistogram(ElectronIdIsoScaleFactorsFile());
	// 	Globals::electronTriggerScaleFactorsHistogram = getElectronTriggerScaleFactorsHistogram(ElectronTriggerScaleFactorsFile());
	// } else {
	// 	std::cout << "No electron scale factors file, corrections will be set to 1." << std::endl;
	// }

	if ( Globals::energyInTeV == 7 && getHadronTriggerFromFile_ ) {
		std::cout << "Getting electron trigger hadron leg efficiencies from file " << hadronTriggerFile() << "." << std::endl;
		getHadronTriggerLegHistogram(hadronTriggerFile());
	} else {
		std::cout << "No electron trigger hadron leg efficiencies file, corrections will be set to 1." << std::endl;
	}

	getCSVCorrectPermHistogram( TTbarLikelihoodFile() );
	getCSVIncorrectPermHistogram( TTbarLikelihoodFile() );

	getNuChiCorrectPermHistogram( TTbarLikelihoodFile() );
	getNuChiIncorrectPermHistogram( TTbarLikelihoodFile() );

	getHadronicRecoCorrectPermHistogram( TTbarLikelihoodFile() );
	getHadronicRecoIncorrectPermHistogram( TTbarLikelihoodFile() );
	getLeptonicRecoCorrectPermHistogram( TTbarLikelihoodFile() );
	getLeptonicRecoIncorrectPermHistogram( TTbarLikelihoodFile() );

	getbQuarkJet( BTagEfficiencyFile() );
	getcQuarkJet( BTagEfficiencyFile() );
	getudsQuarkJet( BTagEfficiencyFile() );
	getgluonJet( BTagEfficiencyFile() );

	//JES systematic
	Globals::JESsystematic = jesSystematic();

	// Change tree name for JEC variations
	if ( Globals::JESsystematic == -1 ) Globals::treePrefix_ += "_JESDown";
	else if ( Globals::JESsystematic == 1 ) Globals::treePrefix_ += "_JESUp";

	//Jet Smearing systematic
	Globals::JetSmearingSystematic = jetSmearingSystematic();
	std::cout << "ConfigFile.cpp: Globals::JetSmearingSystematic = " << Globals::JetSmearingSystematic << std::endl;

	// Change tree name for JER variations
	if ( Globals::JetSmearingSystematic == -1 ) Globals::treePrefix_ += "_JERDown";
	else if ( Globals::JetSmearingSystematic == 1 ) Globals::treePrefix_ += "_JERUp";

	//b-tag systematics
	Globals::BJetSystematic = BtagSystematic();
	Globals::LightJetSystematic = LightTagSystematic();

	//Loading l7 JEC
	Globals::bL7Corrections = getL7Correction(bJetResoFile());
	Globals::lightL7Corrections = getL7Correction(lightJetResoFile());

	Globals::custom_file_suffix = custom_file_suffix();
	Globals::pdfWeightNumber = pdfWeightNumber();

	//MET corrections
	Globals::applySysShiftMetCorrection = applyMetSysShiftCorr();
	Globals::applyType0MetCorrection = applyMetType0Corr();
	Globals::applyType1MetCorrection = applyMetType1Corr();
	Globals::applyJetSmearing = applyJetSmearing();
	Globals::applyTopPtReweighting = applyTopPtReweighting();

	Globals::verbose = verbose();
	cout << "Verbose: " << verbose() << endl;
}

boost::shared_ptr<TH1D> ConfigFile::getPileUpHistogram(std::string pileUpEstimationFile) {
	using namespace std;

	if (!boost::filesystem::exists(pileUpEstimationFile)) {
		cerr << "ConfigFile::getPileUpHistogram(" << pileUpEstimationFile << "): could not find file" << endl;
		throw "Could not find pile-up histogram file in " + pileUpEstimationFile;
	}

	boost::scoped_ptr<TFile> file(TFile::Open(pileUpEstimationFile.c_str()));
	boost::shared_ptr<TH1D> pileUp((TH1D*) file->Get("pileup")->Clone());
	file->Close();

	return pileUp;
}

boost::shared_ptr<TH2F> ConfigFile::getMuonIdIsoScaleFactorsHistogram(std::string muonIdIsoScaleFactorsFile) {
	using namespace std;

	if (!boost::filesystem::exists(muonIdIsoScaleFactorsFile)) {
		cerr << "ConfigFile::getMuonIdIsoScaleFactorsHistogram(" << muonIdIsoScaleFactorsFile << "): could not find file" << endl;
		throw "Could not find muon ID & iso scale factors histogram file in " + muonIdIsoScaleFactorsFile;
	}

	boost::scoped_ptr<TFile> file(TFile::Open(muonIdIsoScaleFactorsFile.c_str()));
	boost::shared_ptr<TH2F> idIsoHistogram((TH2F*) file->Get("SF_totErr")->Clone());
	file->Close();

	return idIsoHistogram;
}

boost::shared_ptr<TH2F> ConfigFile::getMuonTriggerScaleFactorsHistogram(std::string muonTriggerScaleFactorsFile) {
	using namespace std;

	if (!boost::filesystem::exists(muonTriggerScaleFactorsFile)) {
		cerr << "ConfigFile::getMuonTriggerScaleFactorsHistogram(" << muonTriggerScaleFactorsFile << "): could not find file" << endl;
		throw "Could not find muon trigger scale factors histogram file in " + muonTriggerScaleFactorsFile;
	}

	boost::scoped_ptr<TFile> file(TFile::Open(muonTriggerScaleFactorsFile.c_str()));
	boost::shared_ptr<TH2F> triggerHistogram((TH2F*) file->Get("SF_totErr")->Clone());
	file->Close();

	return triggerHistogram;
}

boost::shared_ptr<TH2D> ConfigFile::getElectronIdIsoScaleFactorsHistogram(std::string electronIdIsoScaleFactorsFile) {
	using namespace std;

	if (!boost::filesystem::exists(electronIdIsoScaleFactorsFile)) {
		cerr << "ConfigFile::getElectronIdIsoScaleFactorsHistogram(" << electronIdIsoScaleFactorsFile << "): could not find file" << endl;
		throw "Could not find electron ID & ISO scale factors histogram file in " + electronIdIsoScaleFactorsFile;
	}

	boost::scoped_ptr<TFile> file(TFile::Open(electronIdIsoScaleFactorsFile.c_str()));
	// boost::scoped_ptr<TCanvas> canvas( (TCanvas*) file->Get("c0"));
	// boost::shared_ptr<TH2D> idIsoHistogram((TH2D*) canvas->GetPrimitive("GlobalSF")->Clone());
	boost::shared_ptr<TH2D> idIsoHistogram((TH2D*) file->Get("GlobalSF")->Clone());
	file->Close();

	return idIsoHistogram;
}

boost::shared_ptr<TH1F> ConfigFile::getElectronTriggerScaleFactorsHistogram(std::string electronTriggerScaleFactorsFile) {
	using namespace std;

	if (!boost::filesystem::exists(electronTriggerScaleFactorsFile)) {
		cerr << "ConfigFile::getElectronTriggerScaleFactorsHistogram(" << electronTriggerScaleFactorsFile << "): could not find file" << endl;
		throw "Could not find electron trigger scale factors histogram file in " + electronTriggerScaleFactorsFile;
	}

	boost::scoped_ptr<TFile> file(TFile::Open(electronTriggerScaleFactorsFile.c_str()));
	// boost::scoped_ptr<TCanvas> canvas( (TCanvas*) file->Get("GsfElectronHLTMedium/HLT/fit_eff_plots/probe_pt_PLOT") );
	boost::shared_ptr<TH1F> triggerHistogram((TH1F*) file->Get("eff"));

	// boost::shared_ptr<TEfficiency> triggerHistogram((TEfficiency*) file->Get("data")->Clone());
	file->Close();

	return triggerHistogram;
}

void ConfigFile::getHadronTriggerLegHistogram(std::string hadronTriggerFile) {
	using namespace std;

	if (!boost::filesystem::exists(hadronTriggerFile)) {
		cerr << "ConfigFile::getHadronTriggerLegHistogram(" << hadronTriggerFile << "): could not find file" << endl;
		throw "Could not find hadron leg efficiency histogram file in " + hadronTriggerFile;
	}

	boost::scoped_ptr<TFile> file(TFile::Open(hadronTriggerFile.c_str()));

	Globals::hadronTriggerLegEfficiencyHistogram_nonIsoJets = (boost::shared_ptr<TEfficiency>) ((TEfficiency*) file->Get("data_1")->Clone("data_1"));
	Globals::hadronTriggerLegEfficiencyHistogram_isoJets = (boost::shared_ptr<TEfficiency>) ((TEfficiency*) file->Get("data_2")->Clone("data_2"));
	Globals::hadronTriggerLegEfficiencyHistogram_isoPFJets = (boost::shared_ptr<TEfficiency>) ((TEfficiency*) file->Get("data_3")->Clone("data_3"));

	file->Close();
}

void ConfigFile::getCSVCorrectPermHistogram(std::string ttbarLikelihoodFile) {
	using namespace std;

	if (!boost::filesystem::exists(ttbarLikelihoodFile)) {
		cerr << "ConfigFile::getCSVCorrectPermHistogram(" << ttbarLikelihoodFile << "): could not find file" << endl;
		throw "Could not find file " + ttbarLikelihoodFile;
	}

	boost::scoped_ptr<TFile> file(TFile::Open(ttbarLikelihoodFile.c_str()));
	Globals::csvCorrectPermHistogram = (boost::shared_ptr<TH1F>) (TH1F*) file->Get("CSV for BJets")->Clone();
	file->Close();
}

void ConfigFile::getCSVIncorrectPermHistogram(std::string ttbarLikelihoodFile) {
	using namespace std;

	if (!boost::filesystem::exists(ttbarLikelihoodFile)) {
		cerr << "ConfigFile::getCSVIncorrectPermHistogram(" << ttbarLikelihoodFile << "): could not find file" << endl;
		throw "Could not find file " + ttbarLikelihoodFile;
	}

	boost::scoped_ptr<TFile> file(TFile::Open(ttbarLikelihoodFile.c_str()));
	Globals::csvIncorrectPermHistogram = (boost::shared_ptr<TH1F>) (TH1F*) file->Get("CSV for LightJets")->Clone();
	file->Close();
}

void ConfigFile::getNuChiCorrectPermHistogram(std::string ttbarLikelihoodFile) {
	using namespace std;

	if (!boost::filesystem::exists(ttbarLikelihoodFile)) {
		cerr << "ConfigFile::getNuChiCorrectPermHistogram(" << ttbarLikelihoodFile << "): could not find file" << endl;
		throw "Could not find file " + ttbarLikelihoodFile;
	}

	boost::scoped_ptr<TFile> file(TFile::Open(ttbarLikelihoodFile.c_str()));
	Globals::NuChiCorrectPermHistogram = (boost::shared_ptr<TH1F>) (TH1F*) file->Get("NeutrinoChiSqLeptonicB")->Clone();
	file->Close();
}

void ConfigFile::getNuChiIncorrectPermHistogram(std::string ttbarLikelihoodFile) {
	using namespace std;

	if (!boost::filesystem::exists(ttbarLikelihoodFile)) {
		cerr << "ConfigFile::getNuChiIncorrectPermHistogram(" << ttbarLikelihoodFile << "): could not find file" << endl;
		throw "Could not find file " + ttbarLikelihoodFile;
	}

	boost::scoped_ptr<TFile> file(TFile::Open(ttbarLikelihoodFile.c_str()));
	Globals::NuChiIncorrectPermHistogram = (boost::shared_ptr<TH1F>) (TH1F*) file->Get("NeutrinoChiSqFalseB")->Clone();
	file->Close();
}

void ConfigFile::getHadronicRecoCorrectPermHistogram(std::string ttbarLikelihoodFile) {
	using namespace std;

	if (!boost::filesystem::exists(ttbarLikelihoodFile)) {
		cerr << "ConfigFile::getHadronicRecoCorrectPermHistogram(" << ttbarLikelihoodFile << "): could not find file" << endl;
		throw "Could not find file " + ttbarLikelihoodFile;
	}

	boost::scoped_ptr<TFile> file(TFile::Open(ttbarLikelihoodFile.c_str()));
	Globals::HadronicRecoCorrectPermHistogram = (boost::shared_ptr<TH2F>) (TH2F*) file->Get("MT vs MW True Reconstructed B(hadronic)")->Clone();
	file->Close();
}

void ConfigFile::getHadronicRecoIncorrectPermHistogram(std::string ttbarLikelihoodFile) {
	using namespace std;

	if (!boost::filesystem::exists(ttbarLikelihoodFile)) {
		cerr << "ConfigFile::getHadronicRecoIncorrectPermHistogram(" << ttbarLikelihoodFile << "): could not find file" << endl;
		throw "Could not find file " + ttbarLikelihoodFile;
	}

	boost::scoped_ptr<TFile> file(TFile::Open(ttbarLikelihoodFile.c_str()));
	Globals::HadronicRecoIncorrectPermHistogram = (boost::shared_ptr<TH2F>) (TH2F*) file->Get("MT vs MW False Reconstructed B(hadronic)")->Clone();
	file->Close();
}

void ConfigFile::getLeptonicRecoCorrectPermHistogram(std::string ttbarLikelihoodFile) {
	using namespace std;

	if (!boost::filesystem::exists(ttbarLikelihoodFile)) {
		cerr << "ConfigFile::getLeptonicRecoCorrectPermHistogram(" << ttbarLikelihoodFile << "): could not find file" << endl;
		throw "Could not find file " + ttbarLikelihoodFile;
	}

	boost::scoped_ptr<TFile> file(TFile::Open(ttbarLikelihoodFile.c_str()));
	Globals::LeptonicRecoCorrectPermHistogram = (boost::shared_ptr<TH2F>) (TH2F*) file->Get("MT vs MW True Reconstructed B(leptonic)")->Clone();
	file->Close();
}

void ConfigFile::getLeptonicRecoIncorrectPermHistogram(std::string ttbarLikelihoodFile) {
	using namespace std;

	if (!boost::filesystem::exists(ttbarLikelihoodFile)) {
		cerr << "ConfigFile::getLeptonicRecoIncorrectPermHistogram(" << ttbarLikelihoodFile << "): could not find file" << endl;
		throw "Could not find file " + ttbarLikelihoodFile;
	}

	boost::scoped_ptr<TFile> file(TFile::Open(ttbarLikelihoodFile.c_str()));
	Globals::LeptonicRecoIncorrectPermHistogram = (boost::shared_ptr<TH2F>) (TH2F*) file->Get("MT vs MW False Reconstructed B(leptonic)")->Clone();
	file->Close();
}

void ConfigFile::getbQuarkJet(std::string btagEfficiencyFile) {
	using namespace std;

	if (!boost::filesystem::exists(btagEfficiencyFile)) {
		cerr << "ConfigFile::getbQuarkJet(" << btagEfficiencyFile << "): could not find file" << endl;
		throw "Could not find file " + btagEfficiencyFile;
	}
	std::cout << btagEfficiencyFile.c_str();
	boost::scoped_ptr<TFile> file(TFile::Open(btagEfficiencyFile.c_str()));

	Globals::bQuarkJet = (boost::shared_ptr<TH2F>) (TH2F*) file->Get("bQuarkJets_BTags_Hist")->Clone();

	file->Close();
}

void ConfigFile::getcQuarkJet(std::string btagEfficiencyFile) {
	using namespace std;

	if (!boost::filesystem::exists(btagEfficiencyFile)) {
		cerr << "ConfigFile::getcQuarkJet(" << btagEfficiencyFile << "): could not find file" << endl;
		throw "Could not find file " + btagEfficiencyFile;
	}

	boost::scoped_ptr<TFile> file(TFile::Open(btagEfficiencyFile.c_str()));
	Globals::cQuarkJet = (boost::shared_ptr<TH2F>) (TH2F*) file->Get("cQuarkJets_BTags_Hist")->Clone();
	file->Close();
}
void ConfigFile::getudsQuarkJet(std::string btagEfficiencyFile) {
	using namespace std;

	if (!boost::filesystem::exists(btagEfficiencyFile)) {
		cerr << "ConfigFile::getudsQuarkJet(" << btagEfficiencyFile << "): could not find file" << endl;
		throw "Could not find file " + btagEfficiencyFile;
	}

	boost::scoped_ptr<TFile> file(TFile::Open(btagEfficiencyFile.c_str()));
	Globals::udsQuarkJet = (boost::shared_ptr<TH2F>) (TH2F*) file->Get("udsQuarkJets_BTags_Hist")->Clone();
	file->Close();
}
void ConfigFile::getgluonJet(std::string btagEfficiencyFile) {
	using namespace std;

	if (!boost::filesystem::exists(btagEfficiencyFile)) {
		cerr << "ConfigFile::getgluonJet(" << btagEfficiencyFile << "): could not find file" << endl;
		throw "Could not find file " + btagEfficiencyFile;
	}

	boost::scoped_ptr<TFile> file(TFile::Open(btagEfficiencyFile.c_str()));
	Globals::gluonJet = (boost::shared_ptr<TH2F>) (TH2F*) file->Get("gluonQuarkJets_BTags_Hist")->Clone();
	file->Close();
}

unsigned int ConfigFile::nTupleVersion() const {
	return nTupleVersion_;
}

} /* namespace BAT */

max_stars_repo_name: kreczko/AnalysisSoftware

max_issues_repo_name: kreczko/AnalysisSoftware

max_forks_repo_name: kreczko/AnalysisSoftware


text:
/*=============================================================================
    Copyright (c) 2001-2005 Joel de Guzman
    Copyright (c) 2004-2005 Hartmut Kaiser

    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)
=============================================================================*/
#if !defined(FUTURES_COMPOSE_HPP)
#define FUTURES_COMPOSE_HPP

#include <boost/futures/detail/as_future.hpp>
#include <boost/futures/detail/compose_impl.hpp>

namespace boost { namespace futures {

    template <typename Op, typename A, typename B>
    struct as_composite
    :   detail::compose_composite<
            Op,
            typename detail::as_future<A>::type,
            typename detail::as_future<B>::type
        >
    {};

    template <typename Op, typename A, typename B>
    inline typename as_composite<Op, A, B>::type
    compose(A const& a, B const& b)
    {
        return as_composite<Op, A, B>::eval(a, b);
    }

}}

#endif // !defined(FUTURES_COMPOSE_HPP)

ext: hpp

max_stars_repo_name: saga-project/saga-cpp

max_issues_repo_name: saga-project/saga-cpp

max_forks_repo_name: saga-project/saga-cpp


text:
#ifndef TYPELIB_MEMORY_LAYOUT_HH
#define TYPELIB_MEMORY_LAYOUT_HH

#include <stdexcept>
#include <typelib/typevisitor.hh>
#include <vector>
#include <boost/static_assert.hpp>

namespace Typelib
{
    /** Exception raised when generating a memory layout for an unsupported type
     */
    struct NoLayout : public std::runtime_error
    {
        NoLayout(Type const& type, std::string const& reason)
            : std::runtime_error("there is no memory layout for type " + type.getName() + ": " + reason) { }
    };

    /** Thrown in operations that are using memlayout bytecode and found an
     * invalid bytecode.
     */
    struct UnknownLayoutBytecode : public std::runtime_error
    {
        UnknownLayoutBytecode() : std::runtime_error("found an unknown marshalling bytecode operation") { }
    };

    // This is needed because the FLAG_CONTAINER descriptor is followed by a
    // pointer on a Container instance
    BOOST_STATIC_ASSERT((sizeof(size_t) == sizeof(void*)));

    typedef std::vector<size_t> MemoryLayout;

    /** Namespace used to define basic constants describing the memory layout
     * of a type. The goal is to have a compact representation, in a buffer, of
     * what is raw data, what is junk and what is Container objects.
     *
     * This is used by most Value operations (init, ...)
     */
    namespace MemLayout
    {
        /** Valid marshalling operations
         *
         * FLAG_MEMCPY    <byte count>
         * FLAG_SKIP      <byte count>
         * FLAG_ARRAY     <element count>  [marshalling ops for pointed-to type] FLAG_END
         * FLAG_CONTAINER <pointer-to-Container-object> [marshalling ops for pointed-to type] FLAG_END
         */
        enum Operations {
            FLAG_MEMCPY,
            FLAG_ARRAY,
            FLAG_CONTAINER,
            FLAG_SKIP,
            FLAG_END
        };

        /** This visitor computes the memory layout for a given type. This memory
         * layout is used by quite a few memory operations
         *
         * You should not have to use this directly. Use
         * Typelib.layout_of(type) instead
         */
        class Visitor : public TypeVisitor
        {
        private:
            MemoryLayout& ops;
            bool   accept_pointers;
            bool   accept_opaques;
            size_t current_op;
            size_t current_op_count;
            bool merge_skip_copy;

        protected:
            void push_current_op();
            void skip(size_t count);
            void memcpy(size_t count);
            void add_generic_op(size_t op, size_t count);
            bool generic_visit(Type const& value);
            bool visit_ (Numeric const& type);
            bool visit_ (Enum    const& type);
            bool visit_ (Array   const& type);
            bool visit_ (Container const& type);
            bool visit_ (Compound const& type);
            bool visit_ (Pointer const& type);
            bool visit_ (OpaqueType const& type);

            void merge_skips_and_copies();

        public:
            Visitor(MemoryLayout& ops, bool accept_pointers = false, bool accept_opaques = false);

            void apply(Type const& type, bool merge_skip_copy = true, bool remove_trailing_skips = true);
        };

        /** Skips the block starting at \c begin. \c end is the end of the
         * complete layout (to avoid invalid memory accesses if the layout is
         * incorrect)
         *
         * It returns the position of the block's FLAG_END
         */
        MemoryLayout::const_iterator skip_block(
                MemoryLayout::const_iterator begin,
                MemoryLayout::const_iterator end);
    }

    /** Returns the memory layout of the given type
     *
     * @param accept_pointers if false (the default), will throw a NoLayout
     * exception if the type given contains pointers. If true, they will simply
     * be skipped
     * @param accept_opaques if false (the default), will throw a NoLayout
     * exception if the type given contains opaques. If true, they will simply
     * be skipped
     * @param merge_skip_copy in a layout, zones that contain data are copied,
     * while zones that are there because of C++ padding rules are skipped. If
     * this is true (the default), consecutive copy/skips are merged into one
     * bigger copy, as doine one big memcpy() is probably more efficient than
     * skipping the few padding bytes. Set to false to turn that off.
     * @param remove_trailing_skips because of C/C++ padding rules, structures
     * might contain trailing bytes that don't contain information. If this
     * option is true (the default), these bytes are removed from the layout.
     */
    inline MemoryLayout layout_of(Type const& t, bool accept_pointers = false, bool accept_opaques = false, bool merge_skip_copy = true, bool remove_trailing_skips = true)
    {
        MemoryLayout ret;
        MemLayout::Visitor visitor(ret, accept_pointers, accept_opaques);
        visitor.apply(t, merge_skip_copy, remove_trailing_skips);
        return ret;
    }
}

#endif

ext: hh

max_stars_repo_name: meyerj/typelib

max_issues_repo_name: meyerj/typelib

max_forks_repo_name: meyerj/typelib


text:
/*
   Copyright (c) Marshall Clow 2010-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)

    For more information, see http://www.boost.org
*/

#include <string>
#include <iostream>     // for cout, etc

#include <boost/algorithm/clamp.hpp>

namespace ba = boost::algorithm;

bool compare_string_lengths ( const std::string &one, const std::string &two )
{
    return one.length () < two.length ();
}

int main ( int /*argc*/, char * /*argv*/ [] ) {
//  Clamp takes a value and two "fenceposts", and brings the value "between" the fenceposts.

//  If the input value is "between" the fenceposts, then it is returned unchanged.
    std::cout << "Clamping   5 to between [1, 10] -> " << ba::clamp ( 5, 1, 10 ) << std::endl;

//  If the input value is out side the range of the fenceposts, it "brought into" range.
    std::cout << "Clamping  15 to between [1, 10] -> " << ba::clamp (  15, 1, 10 ) << std::endl;
    std::cout << "Clamping -15 to between [1, 10] -> " << ba::clamp ( -15, 1, 10 ) << std::endl;

//  It doesn't just work for ints
    std::cout << "Clamping 5.1 to between [1, 10] -> " << ba::clamp ( 5.1, 1.0, 10.0 ) << std::endl;

    {
        std::string one ( "Lower Bound" ), two ( "upper bound!" ), test1 ( "test#" ), test2 ( "#test" );
        std::cout << "Clamping '" << test1 << "' between ['" << one << "' and '" << two << "'] -> '" <<
            ba::clamp ( test1, one, two ) << "'" << std::endl;
        std::cout << "Clamping '" << test2 << "' between ['" << one << "' and '" << two << "'] -> '" <<
            ba::clamp ( test2, one, two ) << "'" << std::endl;
    //  There is also a predicate based version, if you want to compare objects in your own way
        std::cout << "Clamping '" << test1 << "' between ['" << one << "' and '" << two << "'] (comparing lengths) -> '" <<
            ba::clamp ( test1, one, two, compare_string_lengths ) << "'" << std::endl;
        std::cout << "Clamping '" << test2 << "' between ['" << one << "' and '" << two << "'] (comparing lengths) -> '" <<
            ba::clamp ( test2, one, two, compare_string_lengths ) << "'" << std::endl;

    }

//  Sometimes, though, you don't get quite what you expect
//  This is because the two double arguments get converted to int
    std::cout << "Somewhat unexpected: clamp ( 12, 14.7, 15.9 ) --> " << ba::clamp ( 12, 14.7, 15.9 ) << std::endl;
    std::cout << "Expected:     clamp ((double)12, 14.7, 15.9 ) --> " << ba::clamp ((double) 12, 14.7, 15.9 ) << std::endl;
    return 0;
    }

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
//
//=======================================================================
// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.
// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek
//
// 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_GRAPH_DETAIL_ADJ_LIST_EDGE_ITERATOR_HPP
#define BOOST_GRAPH_DETAIL_ADJ_LIST_EDGE_ITERATOR_HPP

#include <iterator>
#include <utility>
#include <boost/detail/workaround.hpp>

#if BOOST_WORKAROUND( __IBMCPP__, <= 600 )
#  define BOOST_GRAPH_NO_OPTIONAL
#endif

#ifdef BOOST_GRAPH_NO_OPTIONAL
#  define BOOST_GRAPH_MEMBER .
#else
#  define BOOST_GRAPH_MEMBER ->
#  include <boost/optional.hpp>
#endif // ndef BOOST_GRAPH_NO_OPTIONAL

namespace boost {

  namespace detail {

    template <class VertexIterator, class OutEdgeIterator, class Graph>
    class adj_list_edge_iterator {
      typedef adj_list_edge_iterator self;
    public:
      typedef std::forward_iterator_tag iterator_category;
      typedef typename OutEdgeIterator::value_type value_type;
      typedef typename OutEdgeIterator::reference  reference;
      typedef typename OutEdgeIterator::pointer    pointer;
      typedef typename OutEdgeIterator::difference_type difference_type;
      typedef difference_type distance_type;

      inline adj_list_edge_iterator() {}

      inline adj_list_edge_iterator(const self& x)
      : vBegin(x.vBegin), vCurr(x.vCurr), vEnd(x.vEnd),
        edges(x.edges), m_g(x.m_g) { }

      template <class G>
      inline adj_list_edge_iterator(VertexIterator b,
                                    VertexIterator c,
                                    VertexIterator e,
                                    const G& g)
        : vBegin(b), vCurr(c), vEnd(e), m_g(&g) {
        if ( vCurr != vEnd ) {
          while ( vCurr != vEnd && out_degree(*vCurr, *m_g) == 0 )
            ++vCurr;
          if ( vCurr != vEnd )
            edges = out_edges(*vCurr, *m_g);
        }
      }

      /*Note:
        In the directed graph cases, it is fine.
        For undirected graphs, one edge go through twice.
      */
      inline self& operator++() {
        ++edges BOOST_GRAPH_MEMBER first;
        if (edges BOOST_GRAPH_MEMBER first == edges BOOST_GRAPH_MEMBER second)
        {
          ++vCurr;
          while ( vCurr != vEnd && out_degree(*vCurr, *m_g) == 0 )
            ++vCurr;
          if ( vCurr != vEnd )
            edges = out_edges(*vCurr, *m_g);
        }
        return *this;
      }
      inline self operator++(int) {
        self tmp = *this;
        ++(*this);
        return tmp;
      }
      inline value_type operator*() const
      { return *edges BOOST_GRAPH_MEMBER first; }
      inline bool operator==(const self& x) const {
        return vCurr == x.vCurr
          && (vCurr == vEnd
              || edges BOOST_GRAPH_MEMBER first == x.edges BOOST_GRAPH_MEMBER first);
      }
      inline bool operator!=(const self& x) const {
        return vCurr != x.vCurr
          || (vCurr != vEnd
              && edges BOOST_GRAPH_MEMBER first != x.edges BOOST_GRAPH_MEMBER first);
      }
    protected:
      VertexIterator vBegin;
      VertexIterator vCurr;
      VertexIterator vEnd;

#ifdef BOOST_GRAPH_NO_OPTIONAL
      std::pair<OutEdgeIterator, OutEdgeIterator> edges;
#else
      boost::optional<std::pair<OutEdgeIterator, OutEdgeIterator> >
        edges;
#endif // ndef BOOST_GRAPH_NO_OPTIONAL
      const Graph* m_g;
    };

  } // namespace detail

}

#undef BOOST_GRAPH_MEMBER

#endif // BOOST_GRAPH_DETAIL_ADJ_LIST_EDGE_ITERATOR_HPP


text:
/*
 * KVH 1750 IMU
 * Eric L. Hahn <erichahn@vt.edu>
 * 12/5/2014
 * Copyright 2014. All Rights Reserved.
 */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wshadow"
#include <ros/ros.h>
#include <tf/tf.h>
#include <pluginlib/class_loader.h>
#pragma GCC diagnostic pop

#include "kvh1750/tov_file.h"
#include "kvh1750/kvh_plugin.h"
#include <sensor_msgs/Temperature.h>
#include <sensor_msgs/Imu.h>
#include <boost/circular_buffer.hpp>
#include <sched.h>

namespace
{
  const std::string DefaultImuLink = "torso";
  const std::string DefaultAddress = "/dev/ttyS4";
  int Rate;
  bool IsDA = true;
  double Ahrs_gyro_x = 0;
  double Ahrs_gyro_y = 0;
  double Ahrs_gyro_z = 0;
  double Prev_stamp = 0;
  boost::shared_ptr<kvh::MessageProcessorBase> Plugin;
}

/**
 * Converts KVH1750Message into the standard ROS messages corresponding
 * to the same set of data, namely an Imu and Temperature message.
 */
void to_ros(const kvh::Message& msg, sensor_msgs::Imu& imu,
  sensor_msgs::Temperature& temp)
{
  msg.time(imu.header.stamp.sec, imu.header.stamp.nsec);

  imu.angular_velocity.x = msg.gyro_x();
  imu.angular_velocity.y = msg.gyro_y();
  imu.angular_velocity.z = msg.gyro_z();
  imu.linear_acceleration.x = msg.accel_x();
  imu.linear_acceleration.y = msg.accel_y();
  imu.linear_acceleration.z = msg.accel_z();

  //scale for ROS if delta angles are enabled
  if(IsDA)
  {
    Ahrs_gyro_x += msg.gyro_x();
    Ahrs_gyro_y += msg.gyro_y();
    Ahrs_gyro_z += msg.gyro_z();

    imu.angular_velocity.x *= Rate;
    imu.angular_velocity.y *= Rate;
    imu.angular_velocity.z *= Rate;
  }
  else
  {
    double current_stamp = imu.header.stamp.sec + imu.header.stamp.nsec * 1E-9;
    double deltatime;
    if (Prev_stamp)
    {
      deltatime = current_stamp - Prev_stamp;
    }
    else
    {
      deltatime = 1/Rate;
    }
    Ahrs_gyro_x += msg.gyro_x()*deltatime;
    Ahrs_gyro_y += msg.gyro_y()*deltatime;
    Ahrs_gyro_z += msg.gyro_z()*deltatime;
    Prev_stamp = current_stamp;
  }

  imu.orientation = tf::createQuaternionMsgFromRollPitchYaw(Ahrs_gyro_x,
    Ahrs_gyro_y, Ahrs_gyro_z);
  temp.header.stamp = imu.header.stamp;
  temp.temperature = msg.temp();
}

int main(int argc, char **argv)
{
  //Name of node
  ros::init(argc, argv, "kvh_1750_imu");
  //Node handle
  ros::NodeHandle nh("~");
  ros::Publisher imu_pub = nh.advertise<sensor_msgs::Imu>("imu", 1);
  ros::Publisher temp_pub = nh.advertise<sensor_msgs::Temperature>("temp", 1);

  std::string imu_link_name = DefaultImuLink;
  nh.getParam("link_name", imu_link_name);

  std::string plugin_name = "";
  nh.getParam("processor_type", plugin_name);
  if(!plugin_name.empty())
  {
    pluginlib::ClassLoader<kvh::MessageProcessorBase> plugin_loader("kvh1750", "kvh::KVHMessageProcessorBase");
    Plugin = plugin_loader.createInstance(plugin_name);
    Plugin->set_link_name(imu_link_name);
  }

  nh.param("rate", Rate, 100);

  bool use_delta_angles = true;

  nh.getParam("use_delta_angles", use_delta_angles);

  sensor_msgs::Imu current_imu;
  sensor_msgs::Temperature current_temp;

  int priority = 99;
  bool use_rt = true;

  nh.getParam("priority", priority);
  nh.getParam("use_rt", use_rt);

  int policy = (use_rt ? SCHED_RR : SCHED_OTHER);

  priority = std::min(sched_get_priority_max(policy),
    std::max(sched_get_priority_min(policy), priority));

  struct sched_param params;
  params.sched_priority = (use_rt ? static_cast<int>(priority) : 0);

  int rc = sched_setscheduler(0, policy, &params);
  if(rc != 0)
  {
    ROS_ERROR("Setting schedule priority produced error: \"%s\"", strerror(errno));
    return 1;
  }

  std::vector<double> ahrs_cov;
  std::vector<double> ang_cov;
  std::vector<double> lin_cov;

  nh.param<std::vector<double>>("orientation_covariance",
    ahrs_cov, {1, 0, 0, 0, 1, 0, 0, 0, 1});
  std::copy(ahrs_cov.begin(), ahrs_cov.end(),
    current_imu.orientation_covariance.begin());

  if(nh.getParam("angular_covariance", ang_cov))
  {
    std::copy(ang_cov.begin(), ang_cov.end(),
      current_imu.angular_velocity_covariance.begin());
  }
  else
  {
    current_imu.angular_velocity_covariance[0] = 1;
    current_imu.angular_velocity_covariance[4] = 1;
    current_imu.angular_velocity_covariance[8] = 1;
  }

  if(nh.getParam("linear_covariance", lin_cov))
  {
    std::copy(lin_cov.begin(), lin_cov.end(),
      current_imu.linear_acceleration_covariance.begin());
  }
  else
  {
    current_imu.linear_acceleration_covariance[0] = 1;
    current_imu.linear_acceleration_covariance[4] = 1;
    current_imu.linear_acceleration_covariance[8] = 1;
  }

  //IMU link locations
  current_temp.header.frame_id = imu_link_name;
  current_imu.header.frame_id = imu_link_name;
  std::string addr = DefaultAddress;
  nh.getParam("address", addr);

  std::string tov_addr = "";
  nh.getParam("tov_address", tov_addr);

  uint32_t baud = 921600;
  int read_baud; //Because rosparam can't provide unsigned ints
  nh.getParam("baudrate", read_baud);
  baud = static_cast<uint32_t>(read_baud);

  int max_temp = kvh::MaxTemp_C;

  nh.getParam("max_temp", max_temp);

  uint32_t wait = 100;
  std::shared_ptr<kvh::IOModule> mod(new kvh::TOVFile(addr, baud, wait,
    tov_addr));
  kvh::IMU1750 imu(mod);

  imu.set_temp_limit(max_temp);
  if(!imu.set_angle_units(use_delta_angles))
  {
    ROS_ERROR("Could not set angle units.");
  }
  if(Rate > 0)
  {
    if(!imu.set_data_rate(Rate))
    {
      ROS_ERROR("Could not set data rate to %d", Rate);
    }
  }

  imu.query_data_rate(Rate);
  imu.query_angle_units(IsDA);

  bool keep_reading = true;
  while(ros::ok() && keep_reading)
  {
    kvh::Message msg;
    switch(imu.read(msg))
    {
      case kvh::IMU1750::VALID:
        to_ros(msg, current_imu, current_temp);
        if(Plugin)
        {
          Plugin->process_message(msg);
        }
        imu_pub.publish(current_imu);
        temp_pub.publish(current_temp);
        break;
      case kvh::IMU1750::BAD_READ:
      case kvh::IMU1750::BAD_CRC:
        ROS_ERROR("Bad data from KVH, ignoring.");
        break;
      case kvh::IMU1750::FATAL_ERROR:
        ROS_FATAL("Lost connection to IMU!"); //should reconnect
        keep_reading = false;
        break;
      case kvh::IMU1750::OVER_TEMP:
        ROS_FATAL("IMU is overheating!");
        keep_reading = false;
        break;
      case kvh::IMU1750::PARTIAL_READ:
      default:
      break;
    }
    ros::spinOnce();
  }

  return 0;
}


text:
#include <mutex>
#include <boost/asio.hpp>
#include <boost/asio/serial_port.hpp>
#include "crocore/filesystem.hpp"
#include "crocore/CircularBuffer.hpp"
#include "crocore/Serial.hpp"

namespace crocore
{
    namespace
    {
        std::mutex g_mutex;
        std::map<std::string, SerialWeakPtr> g_connected_devices;
    };

    struct SerialImpl
    {
        std::string m_device_name;
        boost::asio::serial_port m_serial_port;
        Serial::connection_cb_t m_connect_cb, m_disconnect_cb;
        Serial::receive_cb_t m_receive_cb;
        std::vector<uint8_t> m_rec_buffer = std::vector<uint8_t>(512);
        CircularBuffer<uint8_t> m_buffer{512 * (1 << 10)};
        std::mutex m_mutex;

        SerialImpl(boost::asio::io_service &io, Serial::receive_cb_t rec_cb):
        m_serial_port(io),
        m_receive_cb(rec_cb){}
    };

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

    SerialPtr Serial::create(io_service_t &io, receive_cb_t cb)
    {
        auto ret = SerialPtr(new Serial(io, std::move(cb)));
        ret->set_connect_cb([](ConnectionPtr the_uart)
        {
            LOG_TRACE_1 << "connected: " << the_uart->description();
        });
        return ret;
    }

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

    Serial::Serial(io_service_t &io, receive_cb_t cb):
    m_impl(new SerialImpl(io, std::move(cb)))
    {

    }

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

    Serial::~Serial()
    {
        close();
    }

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

    std::map<std::string, SerialPtr> Serial::connected_devices()
    {
        std::lock_guard<std::mutex> lock(g_mutex);
        std::map<std::string, SerialPtr> ret;

        for(auto &p : g_connected_devices)
        {
            auto ptr = p.second.lock();

            if(ptr){ ret[p.first] = ptr; }
        }
        return ret;
    }

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

    std::vector<std::string> Serial::device_list(const std::set<std::string>& the_patterns)
    {
        std::vector<std::string> ret;
        std::set<std::string> search_patterns = {"tty.usb", "ttyACM"};
        if(!the_patterns.empty()){ search_patterns = the_patterns; }

        for(const auto &path : fs::get_directory_entries("/dev"))
        {
            for(const auto &p : search_patterns)
            {
                if(path.find(p) != std::string::npos){ ret.push_back(path); break; }
            }
        }
        return ret;
    }

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

    bool Serial::open()
    {
        bool ret = false;
        for(const auto &d : device_list()){ if(open(d)){ ret = true; break; } }
        return ret;
    }

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

    bool Serial::open(const std::string &the_name, int the_baudrate)
    {
        if(is_open())
        {
            if(m_impl->m_device_name == the_name){ return false; }
            close();
        }
        boost::asio::serial_port_base::baud_rate br(the_baudrate);
        boost::asio::serial_port_base::flow_control flow_control;
        boost::asio::serial_port_base::parity parity;
        boost::asio::serial_port_base::stop_bits stop_bits;
        boost::asio::serial_port_base::character_size char_size;

        try
        {
            m_impl->m_serial_port.open(the_name);
            m_impl->m_serial_port.set_option(br);
            m_impl->m_serial_port.set_option(flow_control);
            m_impl->m_serial_port.set_option(parity);
            m_impl->m_serial_port.set_option(stop_bits);
            m_impl->m_serial_port.set_option(char_size);
            m_impl->m_device_name = the_name;

            std::lock_guard<std::mutex> lock(g_mutex);
            g_connected_devices[the_name] = shared_from_this();
            async_read_bytes();
            if(m_impl->m_connect_cb){ m_impl->m_connect_cb(shared_from_this()); }
            return true;
        }
        catch(boost::system::system_error &e)
        {
            LOG_WARNING << e.what() << " (" << the_name << ")";
        }
        return false;
    }

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

    void Serial::close()
    {
        if(is_open())
        {
            try{ m_impl->m_serial_port.close(); }
            catch(boost::system::system_error &e){ LOG_WARNING << e.what(); }
        }
    }

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

    bool Serial::is_open() const
    {
        return m_impl->m_serial_port.is_open();
    }

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

    size_t Serial::read_bytes(void *buffer, size_t sz)
    {
        std::unique_lock<std::mutex> lock(m_impl->m_mutex);
        size_t num_bytes = std::min(m_impl->m_buffer.size(), sz);
        std::copy(m_impl->m_buffer.begin(), m_impl->m_buffer.begin() + num_bytes,
                  (uint8_t*)buffer);
        auto tmp = std::vector<uint8_t>(m_impl->m_buffer.begin() + num_bytes,
                                        m_impl->m_buffer.end());
        m_impl->m_buffer.assign(tmp.begin(), tmp.end());
        return num_bytes;
    }

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

    size_t Serial::write_bytes(const void *buffer, size_t sz)
    {
//        try{ return boost::asio::write(m_impl->m_serial_port, boost::asio::buffer(buffer, sz)); }
//        catch(boost::system::system_error &e){ LOG_WARNING << e.what(); }
        async_write_bytes(buffer, sz);
        return sz;
    }

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

    void Serial::async_read_bytes()
    {
        auto weak_self = std::weak_ptr<Serial>(shared_from_this());
        auto impl_cp = m_impl;

        m_impl->m_serial_port.async_read_some(boost::asio::buffer(m_impl->m_rec_buffer),
                                              [weak_self, impl_cp](const boost::system::error_code& error,
                                                                   std::size_t bytes_transferred)
        {
            auto self = weak_self.lock();

            if(!error)
            {
                if(bytes_transferred)
                {
                    LOG_TRACE_3 << "received " << bytes_transferred << " bytes";

                    if(self && impl_cp->m_receive_cb)
                    {
                        std::vector<uint8_t> datavec(impl_cp->m_rec_buffer.begin(),
                                                     impl_cp->m_rec_buffer.begin() + bytes_transferred);
                        impl_cp->m_receive_cb(self, datavec);
                    }
                    else
                    {
                        std::unique_lock<std::mutex> lock(impl_cp->m_mutex);
                        std::copy(impl_cp->m_rec_buffer.begin(),
                                  impl_cp->m_rec_buffer.begin() + bytes_transferred,
                                  std::back_inserter(impl_cp->m_buffer));
                    }
                }
                if(self){ self->async_read_bytes(); }
            }
            else
            {
                switch(error.value())
                {
                    case boost::asio::error::eof:
                    case boost::asio::error::connection_reset:
                    case boost::system::errc::no_such_device_or_address:
                    case boost::asio::error::operation_aborted:
                    {
                        LOG_TRACE_1 << "disconnected: " << impl_cp->m_device_name;

                        if(self && impl_cp->m_disconnect_cb)
                        {
                            auto diconnect_cb = std::move(impl_cp->m_disconnect_cb);
                            diconnect_cb(self);
                        }
                        std::lock_guard<std::mutex> lock(g_mutex);
                        g_connected_devices.erase(impl_cp->m_device_name);
                    }
                        break;

                    default:
                        LOG_TRACE_2 << error.message() << " (" << error.value() << ")";
                        break;
                }
            }
        });
    };

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

    void Serial::async_write_bytes(const void *buffer, size_t sz)
    {
        std::vector<uint8_t> bytes((uint8_t*)buffer, (uint8_t*)buffer + sz);

        boost::asio::async_write(m_impl->m_serial_port, boost::asio::buffer(bytes),
                                 [bytes](const boost::system::error_code& error,
                                         std::size_t bytes_transferred)
        {
            if(error){ LOG_ERROR << error.message(); }
            else if(bytes_transferred < bytes.size())
            {
                LOG_WARNING << "not all bytes written";
            }
        });
    }

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

    size_t Serial::available() const
    {
        return m_impl->m_buffer.size();
    }

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

    std::string Serial::description() const
    {
        return m_impl->m_device_name;
    }

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

    void Serial::drain()
    {
//        m_impl->m_serial_port.cancel();
        m_impl->m_buffer.clear();
//        async_read_bytes();
    }

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

    void Serial::set_receive_cb(receive_cb_t the_cb)
    {
        m_impl->m_receive_cb = std::move(the_cb);

        // we have some buffered data -> deliver it to the newly attached callback
        if(m_impl->m_receive_cb && !m_impl->m_buffer.empty())
        {
            std::unique_lock<std::mutex> lock(m_impl->m_mutex);
            m_impl->m_receive_cb(shared_from_this(), std::vector<uint8_t>(m_impl->m_buffer.begin(),
                                                                          m_impl->m_buffer.end()));
            m_impl->m_buffer.clear();
        }
    }

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

    void Serial::set_connect_cb(connection_cb_t the_cb)
    {
        m_impl->m_connect_cb = std::move(the_cb);
    }

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

    void Serial::set_disconnect_cb(connection_cb_t the_cb)
    {
        m_impl->m_disconnect_cb = std::move(the_cb);
    }

    ///////////////////////////////////////////////////////////////////////////////
}

max_stars_repo_name: crocdialer/crocore

max_issues_repo_name: crocdialer/crocore

max_forks_repo_name: crocdialer/crocore


text:
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2006-2007. 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.
//
//////////////////////////////////////////////////////////////////////////////
#include <boost/interprocess/detail/config_begin.hpp>
#include <boost/interprocess/detail/workaround.hpp>
//[doc_named_allocB
#include <boost/interprocess/managed_shared_memory.hpp>
#include <cstddef>
#include <utility>
#include <cassert>

int main ()
{
   using namespace boost::interprocess;
   typedef std::pair<double, int> MyType;

   try{
      //A special shared memory where we can
      //construct objects associated with a name.
      //Connect to the already created shared memory segment
      //and initialize needed resources
      managed_shared_memory segment(open_only, "MySharedMemory");

      std::pair<MyType*, std::size_t> res;

      //Find the array
      res = segment.find<MyType> ("MyType array");
      //Length should be 10
      assert(res.second == 10);

      //Find the object
      res = segment.find<MyType> ("MyType instance");
      //Length should be 1
      assert(res.second == 1);

      //Find the array constructed from iterators
      res = segment.find<MyType> ("MyType array from it");
      //Length should be 3
      assert(res.second == 3);

      //Use data
      // . . .

      //We're done, delete all the objects
      segment.destroy<MyType>("MyType array");
      segment.destroy<MyType>("MyType instance");
      segment.destroy<MyType>("MyType array from it");
   }
   catch(...){
      shared_memory_object::remove("MySharedMemory");
      throw;
   }
   shared_memory_object::remove("MySharedMemory");
   return 0;
}
//]
#include <boost/interprocess/detail/config_end.hpp>