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

#include "ThreadTask.hpp"

#include <rw/common/ThreadPool.hpp>
#include <rw/common/ThreadSafeVariable.hpp>
#include <rw/core/Exception.hpp>
#include <rw/core/macros.hpp>

#include <boost/bind.hpp>

using namespace rw::common;
using namespace rw::core;

ThreadTask::ThreadTask (ThreadTask::Ptr parent) :
    _pool (new ThreadSafeVariable< ThreadPool::Ptr > (parent != NULL ? parent->getThreadPool ()
                                                                     : NULL)),
    _state (new ThreadSafeVariable< TaskState > (INITIALIZATION)),
    _keepAlive (new ThreadSafeVariable< bool > (false)),
    _blockFinalize (new ThreadSafeVariable< bool > (false)),
    _children (new ThreadSafeVariable< std::vector< ThreadTask::Ptr > > (
        std::vector< ThreadTask::Ptr > ())),
    _childrenMissing (new ThreadSafeVariable< unsigned int > (0)),
    _parentCallback (new ThreadSafeVariable< ParentCallback > (ParentCallback ())),
    _exceptions (new ThreadSafeVariable< std::list< Exception > > (std::list< Exception > ()))
{}

ThreadTask::ThreadTask (ThreadPool::Ptr pool) :
    _pool (new ThreadSafeVariable< ThreadPool::Ptr > (pool)),
    _state (new ThreadSafeVariable< TaskState > (INITIALIZATION)),
    _keepAlive (new ThreadSafeVariable< bool > (false)),
    _blockFinalize (new ThreadSafeVariable< bool > (false)),
    _children (new ThreadSafeVariable< std::vector< ThreadTask::Ptr > > (
        std::vector< ThreadTask::Ptr > ())),
    _childrenMissing (new ThreadSafeVariable< unsigned int > (0)),
    _parentCallback (new ThreadSafeVariable< ParentCallback > (ParentCallback ())),
    _exceptions (new ThreadSafeVariable< std::list< Exception > > (std::list< Exception > ()))
{}

ThreadTask::~ThreadTask ()
{
    delete _pool;
    delete _state;
    delete _keepAlive;
    delete _blockFinalize;
    delete _children;
    delete _childrenMissing;
    delete _parentCallback;
    delete _exceptions;
}

bool ThreadTask::setThreadPool (ThreadPool::Ptr pool)
{
    // Do a quick check on the current state
    if (_state->getVariable () != INITIALIZATION)
        return false;
    // Lock mutex to get exclusive access to change private member variables.
    // (blocks execute() from moving from INITILIZATION state and launching the job before pool has
    // been set)
    boost::mutex::scoped_lock lock (_mutex);
    if (_state->getVariable () != INITIALIZATION)
        return false;
    _pool->setVariable (pool);
    return true;
}

ThreadPool::Ptr ThreadTask::getThreadPool ()
{
    return _pool->getVariable ();
}

void ThreadTask::run ()
{}

void ThreadTask::subTaskDone (ThreadTask* subtask)
{
    for (const Exception& e : subtask->getExceptions ()) {
        registerFailure (e);
    }
}

void ThreadTask::idle ()
{}

void ThreadTask::done ()
{}

bool ThreadTask::execute ()
{
    // Do a quick check on the state
    if (_state->getVariable () != INITIALIZATION)
        return false;
    std::vector< ThreadTask::Ptr > children;
    {
        // Lock mutex to get exclusive access to change private member variables.
        // This ensures:
        // 1. setThreadPool() and addSubTask() is not currently changing the pool or adding subtasks
        // 2. execute() is only called once (otherwise the state would no longer be INITIALIZATION)
        boost::mutex::scoped_lock lock (_mutex);
        if (_state->getVariable () != INITIALIZATION)
            return false;
        _state->setVariable (IN_QUEUE);
        children = _children->getVariable ();
    }
    // At this point new subtasks can again be added
    //  - in this case they are launched from the addSubTasks() function and not from here
    //  - note that a subtask added at this point might actually start executing before we add this
    //  task to the pool
    // The ThreadPool can not change anymore (state is IN_QUEUE) so we just read it without holding
    // the lock:
    ThreadPool::Ptr pool = _pool->getVariable ();
    // Work is now added to the pool, where it is queued (it might start executing immediately).
    if (pool != NULL) {
        ThreadPool::WorkFunction workFct =
            boost::bind (&ThreadTask::runWrap, this, boost::arg< 1 > ());
        pool->addWork (workFct);
    }
    else {
        runWrap (NULL);
    }
    for (ThreadTask::Ptr subtask : children) {
        subtask->execute ();
    }
    return true;
}

ThreadTask::TaskState ThreadTask::wait (ThreadTask::TaskState previous)
{
    return _state->waitForUpdate (previous);
}

void ThreadTask::waitUntilDone ()
{
    ThreadTask::TaskState state = _state->getVariable ();
    while (state != DONE) {
        state = wait (state);
    }
}

ThreadTask::TaskState ThreadTask::getState ()
{
    return _state->getVariable ();
}

bool ThreadTask::addSubTask (ThreadTask::Ptr subtask)
{
    // Do a quick check on the state
    TaskState state = _state->getVariable ();
    if (state == POSTWORK || state == DONE)
        return false;
    {
        // Lock mutex to get exclusive access to change private member variables.
        // This ensures:
        // 1. only one addSubTask() function at a time is adding subtasks to the list
        // 2. if execute() and addSubTask() is invoked at the same time we must be sure that the
        //    task is launched from exactly one of the functions
        // 3. if task is executing, the setKeepAlive(), runWrap() or callbackParent() functions
        //    must be blocked from moving to the POSTWORK or DONE states
        boost::mutex::scoped_lock lock (_mutex);
        state = _state->getVariable ();
        if (state == POSTWORK || state == DONE)
            return false;    // it was too late to add new subtask
        // Add the subtask:
        std::vector< ThreadTask::Ptr > children = _children->getVariable ();
        children.push_back (subtask);
        _children->setVariable (children);
        subtask->_parentCallback->setVariable (
            boost::bind (&ThreadTask::callbackParent, this, boost::arg< 1 > ()));
        _childrenMissing->setVariable (_childrenMissing->getVariable () + 1);
        // If the task is currently IDLE, we change the state to CHILDREN.
        if (state == IDLE) {
            _state->setVariable (CHILDREN);
            state = CHILDREN;
        }
    }
    // Launch the task if parent task is already executing
    if (state != INITIALIZATION)
        subtask->execute ();
    return true;
}

std::vector< ThreadTask::Ptr > ThreadTask::getSubTasks ()
{
    return _children->getVariable ();
}

void ThreadTask::setKeepAlive (bool keepAlive)
{
    // Make a quick check that a change is actually requested
    if (_keepAlive->getVariable () == keepAlive)
        return;
    bool doFinish = false;
    {
        // Lock mutex to get exclusive access to change private member variables.
        // This is done to be sure that the state does not change to and from IDLE while keepAlive
        // is changing this influences if finish() should be invoked or not.
        boost::mutex::scoped_lock lock (_mutex);
        // If keepAlive is switched off and the task is IDLE, we finish it.
        if (_keepAlive->getVariable () && !keepAlive) {
            if (_state->getVariable () == IDLE) {
                if (!_blockFinalize->getVariable ()) {    // only finish task if no subtasks are
                                                          // currently invoking idle
                    _state->setVariable (POSTWORK);    // addSubTasks() can not be used any longer
                    doFinish = true;
                }
            }
        }
        _keepAlive->setVariable (keepAlive);
    }
    if (doFinish)
        finish ();
}

bool ThreadTask::keepAlive ()
{
    return _keepAlive->getVariable ();
}

void ThreadTask::registerFailure (const Exception& e)
{
    boost::mutex::scoped_lock lock (_mutex);
    std::list< Exception > exceptions = _exceptions->getVariable ();
    exceptions.push_back (e);
    _exceptions->setVariable (exceptions);
}

std::list< Exception > ThreadTask::getExceptions () const
{
    return _exceptions->getVariable ();
}

void ThreadTask::runWrap (ThreadPool* pool)
{
    // runWrap is invoked only once - the state is IN_QUEUE
    // State is set to EXECUTING
    {
        boost::mutex::scoped_lock lock (_mutex);
        _state->setVariable (EXECUTING);
    }
    try {
        run ();
    }
    catch (boost::thread_interrupted const&) {
        RW_THROW (
            "Please catch boost::thread_interrupted exception thrown in ThreadTask run funtion!");
    }
    // State is set to CHILDREN causing children to try to move to IDLE when they finish (if keep
    // alive is disabled).
    {
        boost::mutex::scoped_lock lock (_mutex);
        _state->setVariable (CHILDREN);
    }
    // Now check if task should change to IDLE (if there is no subtasks for instance)
    tryIdle ();
}

void ThreadTask::callbackParent (ThreadTask* task)
{
    // Notify the parent that the subtask has now finished
    subTaskDone (task);
    // Decrement children counter
    {
        // Lock the mutex to be sure that:
        // 1. no other children are trying to decrement counter at the same time
        // 2. addSubTasks() is not trying to increment counter at the same time
        boost::mutex::scoped_lock lock (_mutex);
        _childrenMissing->setVariable (_childrenMissing->getVariable () - 1);
    }
    // Now check if task should change to IDLE
    tryIdle ();
}

void ThreadTask::tryIdle ()
{
    bool doIdle = false;
    {
        // Lock the mutex to be sure that:
        // 1. Children counter is not currently changing
        // 2. Change from CHILDREN to IDLE state only happens once (and idle() is invoked once)
        boost::mutex::scoped_lock lock (_mutex);
        if (_childrenMissing->getVariable () == 0) {
            if (_state->getVariable () == CHILDREN) {
                _state->setVariable (IDLE);
                doIdle = true;
                _blockFinalize->setVariable (
                    true);    // to make sure that setKeepAlive(false) will not finish task to early
            }
        }
    }
    bool doFinish = false;
    if (doIdle) {
        idle ();
        {
            // Lock the mutex to be sure that:
            // 1. Children counter is not currently changing
            // 2. If keep alive is disabled, finish is only invoked from here or from setKeepAlive
            boost::mutex::scoped_lock lock (_mutex);
            if (_childrenMissing->getVariable () == 0) {
                if (_state->getVariable () == IDLE) {
                    if (!_keepAlive->getVariable ()) {
                        _state->setVariable (
                            POSTWORK);    // addSubTasks() can not be used any longer
                        doFinish = true;
                    }
                }
            }
            _blockFinalize->setVariable (false);
        }
    }
    if (doFinish) {
        finish ();
    }
}

void ThreadTask::finish ()
{
    // Finish is guaranteed to only be invoked once - state is POSTWORK
    try {
        done ();
    }
    catch (boost::thread_interrupted const&) {
        RW_THROW (
            "Please catch boost::thread_interrupted exception thrown in ThreadTask done funtion!");
    }
    ParentCallback parentCallback;
    {
        boost::mutex::scoped_lock lock (_mutex);
        parentCallback = _parentCallback->getVariable ();
    }
    {
        boost::mutex::scoped_lock lock (_mutex);
        _state->setVariable (DONE);
    }
    if (!parentCallback.empty ())
        parentCallback (this);
}


text:
/*
 * This file is part of bogus, a C++ sparse block matrix library.
 *
 * Copyright 2013 Gilles Daviet <gdaviet@gmail.com>
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

#ifndef BOGUS_EIGEN_SPARSE_LINEAR_SOLVERS_HPP
#define BOGUS_EIGEN_SPARSE_LINEAR_SOLVERS_HPP

/*  Depending on your version of Eigen, this file may make use of LGPL licensed code.
	See Eigen/src/Sparse/SimplicialCholesky.h for more information
*/

#include "SparseHeader.hpp"

#define BOGUS_WITH_EIGEN_STABLE_SPARSE_API
#ifdef BOGUS_WITH_EIGEN_STABLE_SPARSE_API

#include "EigenLinearSolvers.hpp"
#include "../Utils/LinearSolverBase.hpp"
#include "../Utils/NaiveSharedPtr.hpp"

#include <Eigen/OrderingMethods>

#ifndef EIGEN_MPL2_ONLY
#include <Eigen/SparseCholesky>
#define BOGUS_WITH_EIGEN_SPARSE_LDLT
#endif

#if EIGEN_VERSION_AT_LEAST(3,1,92)
#include <Eigen/SparseLU>
#define BOGUS_WITH_EIGEN_SPARSE_LU
#endif

#ifndef BOGUS_EIGEN_SPARSE_LDLT_IMPL
#define BOGUS_EIGEN_SPARSE_LDLT_IMPL(Derived) Eigen::SimplicialLDLT<Derived>
#endif

#ifndef BOGUS_EIGEN_SPARSE_LU_IMPL
#define BOGUS_EIGEN_SPARSE_LU_IMPL(Derived) Eigen::SparseLU<Derived, Eigen::COLAMDOrdering<int> >
#endif

namespace bogus {

template < typename Derived, typename ImplType >
struct LinearSolverTraits< Factorization< Eigen::SparseMatrixBase< Derived >, ImplType > >
{
	typedef typename Derived::PlainObject MatrixType ;
	typedef ImplType FactType ;

	template < typename RhsT > struct Result {
		typedef typename EigenSolveResult< FactType, RhsT >::Type Type ;
	} ;
	template < typename RhsT >
	struct Result< Eigen::MatrixBase< RhsT > > {
		typedef typename Result< RhsT >::Type Type ;
	} ;
} ;

template < typename Derived, typename FactType >
struct Factorization< Eigen::SparseMatrixBase< Derived >, FactType >
		: public LinearSolverBase< Factorization< Eigen::SparseMatrixBase< Derived >, FactType > >
{
	typedef Eigen::SparseMatrixBase< Derived > MatrixType ;
	typedef LinearSolverTraits< Factorization< MatrixType, FactType > > Traits ;

	Factorization() {}
	template< typename OtherDerived >
	explicit Factorization ( const Eigen::SparseMatrixBase< OtherDerived >& mat )
		: m_fact( new typename Traits::FactType( mat ) )
	{}

	template< typename OtherDerived >
	Factorization& compute ( const Eigen::SparseMatrixBase< OtherDerived >& mat )
	{
		m_fact.reset( new typename Traits::FactType( mat ) ) ;
		return *this ;
	}

	template < typename RhsT, typename ResT >
	void solve( const Eigen::MatrixBase< RhsT >& rhs, ResT& res ) const
	{
		assert( m_fact ) ;
		res = m_fact->solve( rhs ) ;
	}

	template < typename RhsT >
	typename Traits::template Result< Eigen::MatrixBase< RhsT > >::Type
	solve( const Eigen::MatrixBase< RhsT >& rhs ) const
	{
		assert( m_fact ) ;
		return m_fact->solve( rhs ) ;
	}

	const typename Traits::FactType& factorization() const {
		return *m_fact ;
	}

  protected:
	BOGUS_SHARED_PTR( typename Traits::FactType, m_fact ) ;
} ;

template < typename Derived, typename FactType >
struct EigenSparseFactorization : public Factorization<
		Eigen::SparseMatrixBase< Derived >,
		FactType >
{
	EigenSparseFactorization() {}
	explicit EigenSparseFactorization ( const Eigen::SparseMatrixBase< Derived >& mat )
		: Factorization< Eigen::SparseMatrixBase< Derived >, FactType >( mat )
	{}
} ;

// LDLT

#ifdef BOGUS_WITH_EIGEN_SPARSE_LDLT
#if ! EIGEN_VERSION_AT_LEAST(3,2,90)
template < typename MatrixType, typename RhsType >
struct EigenSolveResult< Eigen::SimplicialLDLT< MatrixType >, RhsType >
{
	typedef Eigen::SimplicialLDLT< MatrixType > FactType ;
	typedef Eigen::internal::solve_retval< Eigen::SimplicialCholeskyBase< FactType >, RhsType > Type ;
};
#endif
#endif

template < typename Derived >
struct LinearSolverTraits< LDLT< Eigen::SparseMatrixBase< Derived > > >
		: public LinearSolverTraits< Factorization<Eigen::SparseMatrixBase<Derived>, BOGUS_EIGEN_SPARSE_LDLT_IMPL(Derived) > >
{
} ;
template < typename Derived >
struct LinearSolverTraits< LU< Eigen::SparseMatrixBase< Derived > > >
		: public LinearSolverTraits< Factorization<Eigen::SparseMatrixBase<Derived>, BOGUS_EIGEN_SPARSE_LU_IMPL(Derived) > >
{
} ;

template < typename Derived >
struct LDLT< Eigen::SparseMatrixBase< Derived > >
		: public Factorization< Eigen::SparseMatrixBase< Derived >,
		typename LinearSolverTraits< LDLT< Eigen::SparseMatrixBase< Derived > > >::FactType >
{
	typedef Eigen::SparseMatrixBase< Derived > MatrixType ;
	typedef LinearSolverTraits< LDLT< MatrixType > > Traits ;

	typedef Factorization< MatrixType, typename Traits::FactType > Base ;

	LDLT() : Base() {}
	template< typename OtherDerived >
	explicit LDLT ( const Eigen::SparseMatrixBase< OtherDerived >& mat )
		: Base( mat )
	{}

} ;

template < typename Scalar, int _Options = 0, typename _Index = int >
struct SparseLDLT : public LDLT< Eigen::SparseMatrixBase< Eigen::SparseMatrix< Scalar, _Options, _Index > > >
{
	SparseLDLT() {}
	template< typename OtherDerived >
	explicit SparseLDLT ( const Eigen::SparseMatrixBase< OtherDerived >& mat )
		: LDLT< Eigen::SparseMatrixBase< Eigen::SparseMatrix< Scalar, _Options, _Index > > >( mat )
	{}
} ;

template < typename Derived >
struct LU< Eigen::SparseMatrixBase< Derived > >
		: public Factorization< Eigen::SparseMatrixBase< Derived >,
		typename LinearSolverTraits< LU< Eigen::SparseMatrixBase< Derived > > >::FactType >
{
	typedef Eigen::SparseMatrixBase< Derived > MatrixType ;
	typedef LinearSolverTraits< LU< MatrixType > > Traits ;

	typedef Factorization< MatrixType, typename Traits::FactType > Base ;

	LU() : Base() {}
	template< typename OtherDerived >
	explicit LU ( const Eigen::SparseMatrixBase< OtherDerived >& mat )
		: Base( mat )
	{}

} ;

template < typename Scalar, int _Options = 0, typename _Index = int >
struct SparseLU : public LU< Eigen::SparseMatrixBase< Eigen::SparseMatrix< Scalar, _Options, _Index > > >
{
	SparseLU() {}
	template< typename OtherDerived >
	explicit SparseLU ( const Eigen::SparseMatrixBase< OtherDerived >& mat )
		: LU< Eigen::SparseMatrixBase< Eigen::SparseMatrix< Scalar, _Options, _Index > > >( mat )
	{}
} ;

} //namespace bogus

#endif // EIGEN_STABLE_API

#endif //HPP

ext: hpp

max_stars_repo_name: sjokic/WallDestruction

max_issues_repo_name: sjokic/WallDestruction

max_forks_repo_name: sjokic/WallDestruction


text:
// Copyright (C) 2012-2013 Vicente J. Botet Escriba
//
//  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)

// 2013/04 Vicente J. Botet Escriba
//   Provide implementation up to 10 parameters when BOOST_NO_CXX11_VARIADIC_TEMPLATES is defined.
// 2012/11 Vicente J. Botet Escriba
//   Adapt to boost libc++ implementation

//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
// The make_tuple_indices C++11 code is based on the one from libcxx.
//===----------------------------------------------------------------------===//

#ifndef BOOST_THREAD_DETAIL_MAKE_TUPLE_INDICES_HPP
#define BOOST_THREAD_DETAIL_MAKE_TUPLE_INDICES_HPP

#include <boost/config.hpp>
#include <boost/static_assert.hpp>

namespace boost
{
  namespace detail
  {

#if ! defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
    // make_tuple_indices

    template <std::size_t...> struct tuple_indices
    {};

    template <std::size_t Sp, class IntTuple, std::size_t Ep>
    struct make_indices_imp;

    template <std::size_t Sp, std::size_t ...Indices, std::size_t Ep>
    struct make_indices_imp<Sp, tuple_indices<Indices...>, Ep>
    {
      typedef typename make_indices_imp<Sp+1, tuple_indices<Indices..., Sp>, Ep>::type type;
    };

    template <std::size_t Ep, std::size_t ...Indices>
    struct make_indices_imp<Ep, tuple_indices<Indices...>, Ep>
    {
      typedef tuple_indices<Indices...> type;
    };

    template <std::size_t Ep, std::size_t Sp = 0>
    struct make_tuple_indices
    {
      BOOST_STATIC_ASSERT_MSG(Sp <= Ep, "make_tuple_indices input error");
      typedef typename make_indices_imp<Sp, tuple_indices<>, Ep>::type type;
    };
#else

    // - tuple forward declaration -----------------------------------------------
    template <
      std::size_t T0 = 0, std::size_t T1 = 0, std::size_t T2 = 0,
      std::size_t T3 = 0, std::size_t T4 = 0, std::size_t T5 = 0,
      std::size_t T6 = 0, std::size_t T7 = 0, std::size_t T8 = 0,
      std::size_t T9 = 0>
    class tuple_indices {};

    template <std::size_t Sp, class IntTuple, std::size_t Ep>
    struct make_indices_imp;

    template <std::size_t Sp, std::size_t Ep>
    struct make_indices_imp<Sp, tuple_indices<>, Ep>
    {
      typedef typename make_indices_imp<Sp+1, tuple_indices<Sp>, Ep>::type type;
    };
    template <std::size_t Sp, std::size_t I0, std::size_t Ep>
    struct make_indices_imp<Sp, tuple_indices<I0>, Ep>
    {
      typedef typename make_indices_imp<Sp+1, tuple_indices<I0, Sp>, Ep>::type type;
    };
    template <std::size_t Sp, std::size_t I0, std::size_t I1, std::size_t Ep>
    struct make_indices_imp<Sp, tuple_indices<I0, I1>, Ep>
    {
      typedef typename make_indices_imp<Sp+1, tuple_indices<I0, I1, Sp>, Ep>::type type;
    };
    template <std::size_t Sp, std::size_t I0, std::size_t I1, std::size_t I2, std::size_t Ep>
    struct make_indices_imp<Sp, tuple_indices<I0, I1 , I2>, Ep>
    {
      typedef typename make_indices_imp<Sp+1, tuple_indices<I0, I1, I2, Sp>, Ep>::type type;
    };
    template <std::size_t Sp, std::size_t I0, std::size_t I1, std::size_t I2, std::size_t I3, std::size_t Ep>
    struct make_indices_imp<Sp, tuple_indices<I0, I1 , I2, I3>, Ep>
    {
      typedef typename make_indices_imp<Sp+1, tuple_indices<I0, I1, I2, I3, Sp>, Ep>::type type;
    };
    template <std::size_t Sp, std::size_t I0, std::size_t I1, std::size_t I2, std::size_t I3, std::size_t I4, std::size_t Ep>
    struct make_indices_imp<Sp, tuple_indices<I0, I1 , I2, I3, I4>, Ep>
    {
      typedef typename make_indices_imp<Sp+1, tuple_indices<I0, I1, I2, I3, I4, Sp>, Ep>::type type;
    };
    template <std::size_t Sp, std::size_t I0, std::size_t I1, std::size_t I2, std::size_t I3, std::size_t I4, std::size_t I5, std::size_t Ep>
    struct make_indices_imp<Sp, tuple_indices<I0, I1 , I2, I3, I4, I5>, Ep>
    {
      typedef typename make_indices_imp<Sp+1, tuple_indices<I0, I1, I2, I3, I4, I5, Sp>, Ep>::type type;
    };
    template <std::size_t Sp, std::size_t I0, std::size_t I1, std::size_t I2, std::size_t I3, std::size_t I4, std::size_t I5
    , std::size_t I6
    , std::size_t Ep>
    struct make_indices_imp<Sp, tuple_indices<I0, I1 , I2, I3, I4, I5, I6>, Ep>
    {
      typedef typename make_indices_imp<Sp+1, tuple_indices<I0, I1, I2, I3, I4, I5, I6, Sp>, Ep>::type type;
    };
    template <std::size_t Sp, std::size_t I0, std::size_t I1, std::size_t I2, std::size_t I3, std::size_t I4, std::size_t I5
    , std::size_t I6
    , std::size_t I7
    , std::size_t Ep>
    struct make_indices_imp<Sp, tuple_indices<I0, I1 , I2, I3, I4, I5, I6, I7>, Ep>
    {
      typedef typename make_indices_imp<Sp+1, tuple_indices<I0, I1, I2, I3, I4, I5, I6, I7, Sp>, Ep>::type type;
    };
    template <std::size_t Sp, std::size_t I0, std::size_t I1, std::size_t I2, std::size_t I3, std::size_t I4, std::size_t I5
    , std::size_t I6
    , std::size_t I7
    , std::size_t I8
    , std::size_t Ep>
    struct make_indices_imp<Sp, tuple_indices<I0, I1 , I2, I3, I4, I5, I6, I7, I8>, Ep>
    {
      typedef typename make_indices_imp<Sp+1, tuple_indices<I0, I1, I2, I3, I4, I5, I6, I7, I8, Sp>, Ep>::type type;
    };
//    template <std::size_t Sp, std::size_t I0, std::size_t I1, std::size_t I2, std::size_t I3, std::size_t I4, std::size_t I5
//    , std::size_t I6
//    , std::size_t I7
//    , std::size_t I8
//    , std::size_t I9
//    , std::size_t Ep>
//    struct make_indices_imp<Sp, tuple_indices<I0, I1 , I2, I3, I4, I5, I6, I7, I8, I9>, Ep>
//    {
//      typedef typename make_indices_imp<Sp+1, tuple_indices<I0, I1, I2, I3, I4, I5, I6, I7, I8, I9, Sp>, Ep>::type type;
//    };

    template <std::size_t Ep>
    struct make_indices_imp<Ep, tuple_indices<>, Ep>
    {
      typedef tuple_indices<> type;
    };
    template <std::size_t Ep, std::size_t I0>
    struct make_indices_imp<Ep, tuple_indices<I0>, Ep>
    {
      typedef tuple_indices<I0> type;
    };
    template <std::size_t Ep, std::size_t I0, std::size_t I1>
    struct make_indices_imp<Ep, tuple_indices<I0, I1>, Ep>
    {
      typedef tuple_indices<I0, I1> type;
    };
    template <std::size_t Ep, std::size_t I0, std::size_t I1, std::size_t I2>
    struct make_indices_imp<Ep, tuple_indices<I0, I1, I2>, Ep>
    {
      typedef tuple_indices<I0, I1, I2> type;
    };
    template <std::size_t Ep, std::size_t I0, std::size_t I1, std::size_t I2, std::size_t I3>
    struct make_indices_imp<Ep, tuple_indices<I0, I1, I2, I3>, Ep>
    {
      typedef tuple_indices<I0, I1, I2, I3> type;
    };
    template <std::size_t Ep, std::size_t I0, std::size_t I1, std::size_t I2, std::size_t I3, std::size_t I4>
    struct make_indices_imp<Ep, tuple_indices<I0, I1, I2, I3, I4>, Ep>
    {
      typedef tuple_indices<I0, I1, I2, I3, I4> type;
    };
    template <std::size_t Ep, std::size_t I0, std::size_t I1, std::size_t I2, std::size_t I3, std::size_t I4, std::size_t I5>
    struct make_indices_imp<Ep, tuple_indices<I0, I1, I2, I3, I4, I5>, Ep>
    {
      typedef tuple_indices<I0, I1, I2, I3, I4, I5> type;
    };
    template <std::size_t Ep, std::size_t I0, std::size_t I1, std::size_t I2, std::size_t I3, std::size_t I4, std::size_t I5
    , std::size_t I6
    >
    struct make_indices_imp<Ep, tuple_indices<I0, I1, I2, I3, I4, I5, I6>, Ep>
    {
      typedef tuple_indices<I0, I1, I2, I3, I4, I5, I6> type;
    };
    template <std::size_t Ep, std::size_t I0, std::size_t I1, std::size_t I2, std::size_t I3, std::size_t I4, std::size_t I5
    , std::size_t I6
    , std::size_t I7
    >
    struct make_indices_imp<Ep, tuple_indices<I0, I1, I2, I3, I4, I5, I6, I7>, Ep>
    {
      typedef tuple_indices<I0, I1, I2, I3, I4, I5, I6, I7> type;
    };
    template <std::size_t Ep, std::size_t I0, std::size_t I1, std::size_t I2, std::size_t I3, std::size_t I4, std::size_t I5
    , std::size_t I6
    , std::size_t I7
    , std::size_t I8
    >
    struct make_indices_imp<Ep, tuple_indices<I0, I1, I2, I3, I4, I5, I6, I7, I8>, Ep>
    {
      typedef tuple_indices<I0, I1, I2, I3, I4, I5, I6, I7, I8> type;
    };

    template <std::size_t Ep, std::size_t I0, std::size_t I1, std::size_t I2, std::size_t I3, std::size_t I4, std::size_t I5
    , std::size_t I6
    , std::size_t I7
    , std::size_t I8
    , std::size_t I9
    >
    struct make_indices_imp<Ep, tuple_indices<I0, I1, I2, I3, I4, I5, I6, I7, I8, I9>, Ep>
    {
      typedef tuple_indices<I0, I1, I2, I3, I4, I5, I6, I7, I8, I9> type;
    };

    template <std::size_t Ep, std::size_t Sp = 0>
    struct make_tuple_indices
    {
      BOOST_STATIC_ASSERT_MSG(Sp <= Ep, "make_tuple_indices input error");
      typedef typename make_indices_imp<Sp, tuple_indices<>, Ep>::type type;
    };

#endif
  }
}

#endif // header

max_stars_repo_name: cfsengineering/tigl

max_issues_repo_name: cfsengineering/tigl

max_forks_repo_name: cfsengineering/tigl


text:
#include <cstdlib>
#include <iostream>
#include <string>
#include <boost/filesystem.hpp>

#include "_reg_maths.h"
#include "resampleKernel.h"

namespace bfs = boost::filesystem;

static void _test_assert(const bool value, const char condition[]) {
  if (!value) {
    std::cerr << "FAILED: " << condition << std::endl;
    std::abort();
  }
}

#define RESAMPLING_TEST_ASSERT(condition) _test_assert((condition), #condition)

static void _check_image_displacement(const nifti_image &floating, const nifti_image &warped, const float voxel_displacement, const int stride, const int interpolation) {
  const bool use_nearest = interpolation == 0;
  const int max_idx_displacement = use_nearest? int(std::round(voxel_displacement)) : int(std::ceil(voxel_displacement));
  const float *floating_begin = (const float*)(floating.data);
  const float *floating_end = floating_begin + floating.nvox;
  const float *warped_begin = (const float*)(warped.data);

  int nof_nans = 0;
  int boundary_size = 0;

  RESAMPLING_TEST_ASSERT(floating.nvox == warped.nvox);

  for (const float *pc_floating = floating_begin; pc_floating < floating_end; ++pc_floating) {
    if (pc_floating + max_idx_displacement*stride >= floating_begin && pc_floating + max_idx_displacement*stride < floating_end) {
      int offset = pc_floating - floating_begin;
      float ref_value = *(pc_floating + max_idx_displacement*stride);
      float test_value = *(warped_begin + offset);

      if (!use_nearest && voxel_displacement - std::floor(voxel_displacement) > 0.1) {
        ref_value = (*(pc_floating + (max_idx_displacement - 1)*stride) + ref_value)/2;
      }

      if (std::isfinite(test_value)) {
        RESAMPLING_TEST_ASSERT(std::fabs(ref_value - test_value) <= 1e-2*std::fabs(ref_value));
      } else {
        nof_nans += 1;
      }
    }
  }

  if (floating.ndim == 2) {
    boundary_size = (1 + (std::max)(max_idx_displacement, 1)*(interpolation + 1))*(floating.ny + floating.nx);
  } else {
    boundary_size = (7 + (std::max)(max_idx_displacement, 1)*(interpolation + 1))*(std::max)((std::max)(floating.ny*floating.nx, floating.ny*floating.nz), floating.nx*floating.nz);
  }

  RESAMPLING_TEST_ASSERT(nof_nans <= boundary_size);
}

static void _test_displacement(const std::string &image_path) {
  nifti_image const *pc_image = nifti_image_read(image_path.c_str(), 1);
  nifti_image *p_displacements = nifti_copy_nim_info(pc_image);
  std::vector<float> displacement_field(pc_image->nvox*pc_image->dim[0]);

  for (const int interp: {0, 1, 3}) {
    for (int d = 0; d < pc_image->dim[0] - int(pc_image->dim[pc_image->dim[0]] <= 1); ++d) {
      int stride = 1;

      for (int i = 0; i < d; ++i) {
        stride *= pc_image->dim[1+i];
      }

      for (const float voxel_displacement: {0.0f, 1.0f, 0.500001f, 1.50001f}) {
        const float displacement = voxel_displacement*pc_image->pixdim[1+d];

        nifti_image *p_warped;

        std::fill(displacement_field.begin(), displacement_field.end(), 0.f);
        std::fill(displacement_field.begin() + d*pc_image->nvox, displacement_field.begin() + (d + 1)*pc_image->nvox, displacement);

        p_displacements->ndim = p_displacements->dim[0] = 5;
        p_displacements->nt = p_displacements->dim[4] = 1;
        p_displacements->nu = p_displacements->dim[5] = pc_image->dim[0];
        p_displacements->nvox = pc_image->nvox*p_displacements->nu;
        p_displacements->intent_p1 = DISP_FIELD;

        p_displacements->data = (void*)(displacement_field.data());
        p_warped = resample(*p_displacements, *pc_image, interp, std::numeric_limits<float>::quiet_NaN());

        _check_image_displacement(*pc_image, *p_warped, voxel_displacement, stride, interp);

        nifti_image_free(p_warped);
      }
    }
  }
  p_displacements->data = nullptr;
  nifti_image_free(p_displacements);
  nifti_image_free(const_cast<nifti_image*>(pc_image));
}

int main(int argc, char* argv[]) {
  const bfs::path data_path = bfs::path(argv[0]).parent_path();

  _test_displacement((data_path/"data"/"test_image_2.nii").native());
  _test_displacement((data_path/"data"/"test_image_3.nii").native());

  return 0;
}

ext: cpp

max_stars_repo_name: tvercaut/NiftyNet

max_issues_repo_name: tvercaut/NiftyNet

max_forks_repo_name: tvercaut/NiftyNet


text:
#include "panoptic_mapping/map/submap_collection.h"

#include <sys/stat.h>

#include <memory>
#include <string>
#include <sstream>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>

#include <boost/filesystem.hpp>

#include "panoptic_mapping/SubmapCollection.pb.h"

namespace fs = boost::filesystem;

namespace panoptic_mapping {

Submap* SubmapCollection::createSubmap(const Submap::Config& config) {
  submaps_.emplace_back(std::make_unique<Submap>(config, &submap_id_manager_,
                                                 &instance_id_manager_)); //add a new one
  Submap* new_submap = submaps_.back().get(); //get the new one
  id_to_index_[new_submap->getID()] = submaps_.size() - 1; //submap index
  return new_submap;
}

bool SubmapCollection::removeSubmap(int id) {
  auto it = id_to_index_.find(id);
  if (it == id_to_index_.end()) {
    // Submap does not exist.
    return false;
  }
  size_t previous_index = it->second;
  submaps_.erase(submaps_.begin() + it->second);
  id_to_index_.erase(it);
  // correct the index table
  for (auto& id_index_pair : id_to_index_) {
    if (id_index_pair.second > previous_index) {
      id_index_pair.second -= 1;
    }
  }
  return true;
}

bool SubmapCollection::submapIdExists(int id) const {
  return id_to_index_.find(id) != id_to_index_.end();
}

const Submap& SubmapCollection::getSubmap(int id) const {
  auto it = id_to_index_.find(id);
  if (it == id_to_index_.end()) {
    LOG(FATAL) << "Tried to get inexistent submap " << id << ".";
  }
  // This assumes we checked that the id exists.
  return *submaps_[id_to_index_.at(id)];
}

Submap* SubmapCollection::getSubmapPtr(int id) {
  // This assumes we checked that the id exists.
  return submaps_[id_to_index_.at(id)].get();
}

void SubmapCollection::clear() {
  submaps_.clear();
  id_to_index_.clear();
  instance_id_manager_ = InstanceIDManager();
  submap_id_manager_ = SubmapIDManager();
  instance_to_submap_ids_.clear();
  active_freespace_submap_id_ = -1;
}

void SubmapCollection::updateIDList(const std::vector<int>& id_list,
                                    std::vector<int>* new_ids,
                                    std::vector<int>* deleted_ids) const {
  CHECK_NOTNULL(new_ids);
  CHECK_NOTNULL(deleted_ids);
  // Find all deleted submaps.
  for (const int& id : id_list) {
    if (!submapIdExists(id)) {
      deleted_ids->emplace_back(id);
    }
  }
  // Find all new submaps.
  for (const auto& id_submap_pair : id_to_index_) {
    auto it = std::find(id_list.begin(), id_list.end(), id_submap_pair.first);
    if (it == id_list.end()) {
      new_ids->emplace_back(id_submap_pair.first);
    }
  }
}

void SubmapCollection::updateInstanceToSubmapIDTable() {
  // Clear the table and add all new elements.
  instance_to_submap_ids_ = std::unordered_map<int, std::unordered_set<int>>();
  for (const Submap& submap : *this) {
    instance_to_submap_ids_[submap.getInstanceID()].emplace(submap.getID());
  }
}

// Save load functionality was heavily adapted from cblox.
bool SubmapCollection::saveToFile(const std::string& file_path) const {
  CHECK(!file_path.empty());

  // Check for proper extensions.
  const std::string file_name = checkMapFileExtension(file_path);

  // Open the ouput file.
  std::fstream outfile;
  outfile.open(file_name, std::fstream::out | std::fstream::binary);
  if (!outfile.is_open()) {
    LOG(ERROR) << "Could not open file '" << file_name
               << "' to save the submap collection.";
    return false;
  }

  // Saving the submap collection header object.
  SubmapCollectionProto submap_collection_proto;
  submap_collection_proto.set_num_submaps(submaps_.size());
  if (!voxblox::utils::writeProtoMsgToStream(submap_collection_proto,
                                             &outfile)) {
    LOG(ERROR) << "Could not write submap collection header message.";
    outfile.close();
    return false;
  }

  // Saving the submaps.
  for (const auto& submap : submaps_) {
    if (!submap->saveToStream(&outfile)) {
      LOG(WARNING) << "Failed to save submap with ID '" << submap->getID()
                   << "'.";
      outfile.close();
      return false;
    }
    // else {
    //   LOG(INFO) << "Save submap with ID '" << submap->getID() << "' ("
    //             << submap->getName().c_str() << ").";
    // }
  }
  outfile.close();
  return true;
}

bool SubmapCollection::loadFromFile(const std::string& file_path,
                                    bool recompute_data) {
  CHECK(!file_path.empty());
  const std::string file_name = checkMapFileExtension(file_path);

  // Check the file exists.
  struct stat buffer;
  if (stat(file_name.c_str(), &buffer) != 0) {
    LOG(ERROR) << "Target file '" << file_name << "' does not exist.";
    return false;
  }

  // Clear the current maps.
  submaps_.clear();

  // Open and check the file.
  std::ifstream proto_file;
  proto_file.open(file_name, std::fstream::in);
  if (!proto_file.is_open()) {
    LOG(ERROR) << "Could not open protobuf file '" << file_name << "'.";
    return false;
  }

  // Unused byte offset result.
  uint64_t tmp_byte_offset = 0u;
  SubmapCollectionProto submap_collection_proto;
  if (!voxblox::utils::readProtoMsgFromStream(
          &proto_file, &submap_collection_proto, &tmp_byte_offset)) {
    LOG(ERROR) << "Could not read the protobuf message.";
    return false;
  }

  // Loading each of the submaps.
  for (size_t sub_map_index = 0u;
       sub_map_index < submap_collection_proto.num_submaps(); ++sub_map_index) {
    std::unique_ptr<Submap> submap_ptr =
        Submap::loadFromStream(&proto_file, &tmp_byte_offset,
                               &submap_id_manager_, &instance_id_manager_);
    if (submap_ptr == nullptr) {
      LOG(ERROR) << "Failed to load submap '" << sub_map_index
                 << "' from stream.";
      proto_file.close();
      return false;
    }

    // Add to the collection.
    id_to_index_[submap_ptr->getID()] = submaps_.size();
    submaps_.emplace_back(std::move(submap_ptr));
  }
  proto_file.close();

  // Recompute data that is not stored with the submap (bounding volume and mesh)
  if (recompute_data) {
    for (Submap& submap : *this) {
      submap.updateEverything();
    }
  }
  return true;
}

std::string SubmapCollection::checkMapFileExtension(const std::string& file) {
  const std::string extension = ".panmap";
  if (!(file.size() >= extension.size() &&
        file.compare(file.size() - extension.size(), extension.size(),
                     extension) == 0)) {
    return file + extension;
  }
  return file;
}

bool SubmapCollection::saveMeshToFile(const std::string& folder_path) const {
  CHECK(!folder_path.empty());

  if (!fs::exists(folder_path.c_str())) {
    if(!boost::filesystem::create_directory(folder_path.c_str()))
      return false;
  }

  // TODO(py): consider make it run with multi-thread to speed up
  for (const Submap& submap : *this) {
    std::string id_pad;
    std::ostringstream oss;
		oss << std::setfill('0') << std::setw(5) << submap.getID() << "_" << submap.getName() << ".ply";
    std::string file_path = folder_path + "/" + oss.str();
    voxblox::outputMeshLayerAsPly(file_path,
                                  submap.getMeshLayer());
  }

  return true;
}

std::unique_ptr<SubmapCollection> SubmapCollection::clone() const {
  std::unique_ptr<SubmapCollection> result =
      std::make_unique<SubmapCollection>();

  // Copy all the meta data.
  result->submap_id_manager_ = submap_id_manager_;
  result->instance_id_manager_ = instance_id_manager_;
  result->id_to_index_ = id_to_index_;
  result->instance_to_submap_ids_ = instance_to_submap_ids_;
  result->active_freespace_submap_id_ = active_freespace_submap_id_;

  // Deep copy all the submaps to the new managers.
  for (const Submap& submap : *this) {
    result->submaps_.emplace_back(submap.clone(&result->submap_id_manager_,
                                               &result->instance_id_manager_));
  }

  return result;
}

}  // namespace panoptic_mapping


text:
#include <boost/test/unit_test.hpp>
#include <cpp-utils/pattern/monointerface.h>
#include <cpp-utils/resourcehandler.h>

namespace {

class I {
public:
	I() { }
	virtual ~I() { }

	virtual int test() = 0;
};

class A : public I {
public:
	int test() override {
		return 42;
	}
};

}

using HANDLE = void*;
HANDLE CreateHandle() { return reinterpret_cast<HANDLE>(-1); }
void DestroyHandle(HANDLE) { }

using Handle = cpp::resource_handler<HANDLE, struct HandleTag>;
namespace cpp {
template<> void Handle::cleanup() noexcept {
	if (resource_)
	  DestroyHandle(resource_);
}
}

BOOST_AUTO_TEST_SUITE(Pattern_Tests)

BOOST_AUTO_TEST_CASE(MonoInterface_All) {
	using MonoI = cpp::mono_interface<I>;

	MonoI mono(std::unique_ptr<I>(new A()));
  BOOST_CHECK_EQUAL(42, mono->test());
  BOOST_CHECK_EQUAL(42, (*mono).test());
  BOOST_CHECK_EQUAL(42, (&mono)->test());

  MonoI mono2;
  BOOST_CHECK_EQUAL(42, mono->test());

  BOOST_CHECK_EQUAL(42, MonoI::get().test());
  BOOST_CHECK_EQUAL(42, MonoI::instance().test());
  BOOST_CHECK_EQUAL(42, MonoI::pointer()->test());
}

BOOST_AUTO_TEST_CASE(ResourceHandler_All) {
	Handle h(CreateHandle());
}

BOOST_AUTO_TEST_SUITE_END()


text:
#ifndef TIKSRV_APP_SERVER_HPP
#define TIKSRV_APP_SERVER_HPP

#include "config/config.hpp"
#include "log/logger.hpp"

#include "net/tcp_client.hpp"
#include "net/tcp_listener.hpp"

#include "interop/command.hpp"
#include "services/hooks_manager.hpp"

#include <boost/asio/io_context.hpp>
#include <boost/system/error_code.hpp>

#include <cstdint>
#include <memory>
#include <utility>

namespace ts::app {

class server final : public ts::net::tcp_listener_handler,
                     public ts::net::tcp_client_handler {
    using error_code = boost::system::error_code;
    using client_ptr = std::shared_ptr<ts::net::tcp_client>;

  public:
    server(const ts::config::config &                   conf,
           boost::asio::io_context &                    io,
           std::shared_ptr<ts::services::hooks_manager> hooks_manger)
        : io_ {io},
          listener_ {
              io_,
              conf[ts::config::config_key::listen_port].as<std::uint16_t>(),
              conf[ts::config::config_key::liten_backlog].as<std::uint32_t>(),
              *this, *this},
          hooks_manager_ {std::move(hooks_manger)},
          logger_ {"server"} {
    }

    inline void run() {
        listener_.start();
    }

    inline void add_command(std::uint32_t                           id,
                            std::unique_ptr<ts::interop::command> &&cmd) {
        commands_.emplace(std::make_pair(id, std::move(cmd)));
    }

    void on_accept(std::shared_ptr<ts::net::tcp_client> client) override;
    void on_error(client_ptr client, const error_code &err) override;
    void on_request(client_ptr client, ts::net::request &&req) override;

  private:
    boost::asio::io_context &                    io_;
    ts::net::tcp_listener                        listener_;
    std::shared_ptr<ts::services::hooks_manager> hooks_manager_;
    ts::log::logger                              logger_;

    std::map<std::uint32_t, std::unique_ptr<ts::interop::command>> commands_;
};

} // namespace ts::app

#endif


text:
//
// Created by alex on 9/23/19.
//

#ifndef BABEL_SERVER_SERVERAPPLICATION_HPP
#define BABEL_SERVER_SERVERAPPLICATION_HPP

#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/enable_shared_from_this.hpp>
#include "Database.hpp"
#include "ServerConfig.hpp"
#include "ServerError.hpp"
#include "Session.hpp"
#include "SharedData.hpp"
#include <memory>
#include <list>

typedef boost::asio::ip::tcp BoostTcp;

class Session;

class ServerApplication {
public:
    explicit ServerApplication(const ServerConfig& config);

    ~ServerApplication() = default;

    ServerApplication(const ServerApplication&) = delete;

    void run();
private:
    void accept();

    Database database_;
    bool running_;

    // Network
    boost::asio::io_context context_;
    BoostTcp::acceptor acceptor_;
    std::list<boost::shared_ptr<Session>> sessions_;

    // Private logic
    void handleAccept(const boost::shared_ptr<Session>& session, const boost::system::error_code& ec);
};

#endif //BABEL_SERVER_SERVERAPPLICATION_HPP

max_stars_repo_name: LiardeauxQ/Babel

max_issues_repo_name: LiardeauxQ/Babel

max_forks_repo_name: LiardeauxQ/Babel


text:
/*
 * Copyright 2016 Adam Chyła, adam@chyla.org
 * All rights reserved. Distributed under the terms of the MIT License.
 */

#include "network_trainer.h"

#include <slas/util/run_partially.h>

#include <algorithm>
#include <vector>
#include <fstream>
#include <boost/log/trivial.hpp>

#include "src/bash/analyzer/detail/command_summary_divider/command_summary_divider.h"
#include "src/library/fann/fann_wrapper.h"
#include "src/library/fann/fann_guard.h"

namespace bash
{

namespace analyzer
{

namespace detail
{

namespace network_trainer
{

NetworkTrainerPtr NetworkTrainer::Create(::bash::database::detail::DatabaseFunctionsInterfacePtr database_functions,
                                         ::database::detail::GeneralDatabaseFunctionsInterfacePtr general_database_functions,
                                         const std::string &neural_network_data_directory) {
  BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::Create: Function call";

  auto fann_wrapper = ::library::fann::FannWrapper::Create();

  return Create(database_functions, general_database_functions, neural_network_data_directory, fann_wrapper);
}

NetworkTrainerPtr NetworkTrainer::Create(::bash::database::detail::DatabaseFunctionsInterfacePtr database_functions,
                                         ::database::detail::GeneralDatabaseFunctionsInterfacePtr general_database_functions,
                                         const std::string &neural_network_data_directory,
                                         ::library::fann::detail::FannWrapperInterfacePtr fann_wrapper) {
  BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::Create: Function call";

  return NetworkTrainerPtr(new NetworkTrainer(database_functions, general_database_functions, neural_network_data_directory, fann_wrapper));
}

void NetworkTrainer::Train() {
  BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::Train: Function call";

  auto configurations = database_functions_->GetAnomalyDetectionConfigurations();

  for (const auto &c : configurations) {
    BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::Train: Is configuration changed for agent " << c.agent_name_id << "?: " << c.changed;

    if (c.changed) {
      CreateLearningSetFile(c);
      CreateNetworkConfiguration(c);
      database_functions_->MarkConfigurationAsUnchanged(c.id);
    }
  }
}

NetworkTrainer::NetworkTrainer(::bash::database::detail::DatabaseFunctionsInterfacePtr database_functions,
                               ::database::detail::GeneralDatabaseFunctionsInterfacePtr general_database_functions,
                               const std::string &neural_network_data_directory,
                               ::library::fann::detail::FannWrapperInterfacePtr fann_wrapper) :
database_functions_(database_functions),
general_database_functions_(general_database_functions),
neural_network_data_directory_(neural_network_data_directory),
fann_wrapper_(fann_wrapper) {
}

void NetworkTrainer::CreateLearningSetFile(const ::bash::database::type::AnomalyDetectionConfiguration &configuration) {
  BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Function call";

  auto users = database_functions_->GetUsersIdsFromSelectedDailyStatisticsInConfiguration(configuration.id);

  BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Found " << users.size() << " users";

  constexpr int ANOMALY_NETWORK_VALUE = 0;
  constexpr::database::type::RowsCount MAX_ROWS_IN_MEMORY = 100;
  constexpr unsigned int number_of_inputs = 100;
  unsigned int number_of_outputs = users.size();
  long long learning_set_size = database_functions_->CountSelectedDailyStatisticsWithoutUnknownClassificationInConfiguration(configuration.id);
  std::string file_path = neural_network_data_directory_ + "/training-" + std::to_string(configuration.id) + ".data";

  BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Number of inputs: " << number_of_inputs;
  BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Number of outputs: " << number_of_outputs;
  BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Learning set size: " << learning_set_size;
  BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Training file path: " << file_path;

  std::vector<double> input;
  input.resize(number_of_inputs, 0);

  std::vector<int> output;
  output.resize(number_of_outputs, ANOMALY_NETWORK_VALUE);

  BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Opening training file";
  std::fstream file(file_path.c_str(), std::ios::out | std::ios::trunc);

  BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Writing training data";
  file << learning_set_size << ' ' << number_of_inputs << ' ' << number_of_outputs << '\n';

  auto selected_commands_ids = database_functions_->GetMarkedCommandsIds(configuration.id);
  BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Found " << selected_commands_ids.size() << " selected commands ids";

  for (const auto &id : selected_commands_ids)
    BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: id: " << id;

  command_summary_divider::CommandSummaryDivider divider;
  unsigned selected_commands_position = 0;
  unsigned commands_statistics_position = 0;
  int user_output_position = 0;
  for (const auto &user_id : users) {
    BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Writing data for user id (from database) " << user_id;

    auto daily_user_statistics_count = database_functions_->CountSelectedDailyUserStatisticsWithoutUnknownClassificationFromConfigurationByUser(configuration.id, user_id);
    BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Found " << daily_user_statistics_count << " daily user statistics";

    util::RunPartially(MAX_ROWS_IN_MEMORY, daily_user_statistics_count, [&](long long part_count, long long offset) {
      auto daily_user_statistics = database_functions_->GetSelectedDailyUserStatisticsWithoutUnknownClassificationFromConfigurationByUser(configuration.id, user_id, part_count, offset);
      BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Found " << daily_user_statistics.size() << " statistics in part";

      for (const auto &statistic : daily_user_statistics) {
        std::fill(input.begin(), input.end(), 0);

        auto commands_statistics = database_functions_->GetSelectedDailyUserCommandsStatistics(statistic.id);
        BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Found " << commands_statistics.size() << " selected daily user commands statistics with statistic id " << statistic.id;

        selected_commands_position = 0;
        commands_statistics_position = 0;
        while (selected_commands_position < selected_commands_ids.size()
            && commands_statistics_position < commands_statistics.size()) {
          const auto &command_statistic = commands_statistics.at(commands_statistics_position);
          BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Position " << selected_commands_position;

          if (command_statistic.command_id == selected_commands_ids.at(selected_commands_position)) {
            BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Found command with id " << command_statistic.command_id;

            input.at(selected_commands_position) = command_statistic.summary;
            commands_statistics_position++;
          }

          selected_commands_position++;
        }

        std::transform(input.begin(), input.end(), input.begin(), divider);

        if (statistic.classification == ::database::type::Classification::ANOMALY)
          output.at(user_output_position) = ANOMALY_NETWORK_VALUE;
        else if (statistic.classification == ::database::type::Classification::NORMAL)
          output.at(user_output_position) = 1;

        BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Classification set: " << output.at(user_output_position);

        BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Saving to file";

        for (const auto &v : input)
          file << v << " ";
        file << '\n';

        for (const auto &v : output)
          file << v << " ";
        file << '\n';
      }
    });

    output.at(user_output_position) = ANOMALY_NETWORK_VALUE;
    user_output_position++;
  }

  BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Closing training file";
  file.close();

  BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Done";
}

void NetworkTrainer::CreateNetworkConfiguration(const ::bash::database::type::AnomalyDetectionConfiguration &configuration) {
  BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateNetworkConfiguration: Done";

  auto users = database_functions_->GetUsersIdsFromSelectedDailyStatisticsInConfiguration(configuration.id);

  constexpr::database::type::RowsCount MAX_ROWS_IN_MEMORY = 100;
  constexpr unsigned int number_of_inputs = 100;
  constexpr unsigned int number_of_layers = 3;
  constexpr unsigned int number_of_hidden_neurons = 30;
  const unsigned int number_of_outputs = users.size();
  constexpr float desired_error = 0.001f;
  constexpr unsigned int max_epochs = 100;
  constexpr unsigned int epochs_between_reports = 10;

  const std::string file_path = neural_network_data_directory_ + "/training-" + std::to_string(configuration.id) + ".data";
  const std::string network_configuration_file_path = neural_network_data_directory_ + "/network-" + std::to_string(configuration.id) + ".data";

  BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateNetworkConfiguration: Creating network";

  struct fann *ann = fann_wrapper_->CreateStandard(number_of_layers, number_of_inputs, number_of_hidden_neurons, number_of_outputs);
  ::library::fann::FannGuard fann_guard(ann);

  fann_wrapper_->SetActivationFunctionHidden(ann, FANN_SIGMOID);
  fann_wrapper_->SetActivationFunctionOutput(ann, FANN_SIGMOID);

  BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateNetworkConfiguration: Training network";
  fann_wrapper_->TrainOnFile(ann, file_path, max_epochs, epochs_between_reports, desired_error);

  BOOST_LOG_TRIVIAL(debug) << "bash::analyzer::detail::network_trainer::NetworkTrainer::CreateNetworkConfiguration: Saving network to file: " << network_configuration_file_path;
  fann_wrapper_->Save(ann, network_configuration_file_path);
}

}

}

}

}

max_stars_repo_name: chyla/slas

max_issues_repo_name: chyla/slas

max_forks_repo_name: chyla/slas


text:
//==============================================================================
//         Copyright 2014          LRI    UMR 8623 CNRS/Univ Paris Sud XI
//         Copyright 2014          NumScale SAS
//
//          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
//==============================================================================
#include <boost/numeric/odeint.hpp>
#include <nt2/table.hpp>
#include <nt2/include/functions/zeros.hpp>
#include <nt2/include/functions/ones.hpp>

#include <boost/config.hpp>
#ifdef BOOST_MSVC
    #pragma warning(disable:4996)
#endif

#define BOOST_TEST_MODULE odeint_nt2_copy

#include <boost/test/included/unit_test.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/numeric/odeint/external/nt2/nt2_norm_inf.hpp>

#include <boost/mpl/list.hpp>

using namespace boost::unit_test;
using namespace boost::numeric::odeint;

typedef boost::mpl::list< float , double > fp_types;

BOOST_AUTO_TEST_SUITE( nt2_norm_inf )

BOOST_AUTO_TEST_CASE_TEMPLATE( test_norm_inf, T, fp_types )
{
  nt2::table<T> x = nt2::ones(10,1, nt2::meta::as_<T>() );
  x(4) = 55;

  nt2::table<T> y = nt2::zeros(8,8, nt2::meta::as_<T>() );
  y(6,4) = -42;

  BOOST_CHECK_SMALL(vector_space_norm_inf<nt2::table<T> >()(x) - T(55), T(1e-10));
  BOOST_CHECK_SMALL(vector_space_norm_inf<nt2::table<T> >()(y) - T(42), T(1e-10));
}

BOOST_AUTO_TEST_SUITE_END()


text:
#include <stdio.h>

#ifdef _WIN32
//#include <time.h>
#include <boost/chrono.hpp>
/*long timediff(clock_t t1, clock_t t2) {
    long elapsed;
    elapsed = ((double)t2 - t1) / CLOCKS_PER_SEC * 1000;
    return elapsed;
}*/
#else
#include <unistd.h>
#include <sys/time.h>
#include <chrono>
#endif

#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/transport/TSocket.h>
#include <thrift/transport/TTransportUtils.h>

#include "LatencyTest.h"

using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;

#include "ApacheClient.h"

double ApacheClientTest::run(string ip, int samples, int bytes)
{

#ifdef _WIN32

	using namespace boost::chrono;
	system_clock::time_point m_t1 = system_clock::now();
	system_clock::time_point m_t2;
	for(int i=0;i<1000;i++)
		m_t2 = system_clock::now();
	double m_overhead = duration_cast<microseconds>(m_t2 - m_t1).count()/1001;
	//printf("Overhead: %lf\n", m_overhead);
#else

	typedef std::chrono::high_resolution_clock Clock;
	typedef std::chrono::microseconds microseconds;

	Clock::time_point m_t1;
	Clock::time_point m_t2;

	m_t1 = Clock::now();
	for(int i=0;i<1000;i++)
		m_t2 = Clock::now();
	double m_overhead = std::chrono::duration_cast<microseconds>(m_t2 - m_t1).count()/1001;

#endif

	//START APACHE CLIENT:
	boost::shared_ptr<TTransport> socket(new TSocket(ip, 9092));
	boost::shared_ptr<TTransport> transport(new TBufferedTransport(socket));
	boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
	LatencyTestClient client(protocol);
	try {
		transport->open();
	}
	catch (TException &tx) {
		printf("ERROR: %s\n", tx.what());
		return -1;
	}

    element elm;
    elm.__set_att1(true);
    elm.__set_att2("ABCDEFG");
    elm.__set_att3(65000);
    elm.__set_att4(564);
    elm.__set_att5(false);

    st payload;
	for(int i = 0; i < bytes; ++i) {
        payload.push_back(elm);
	}

	st _return;

#ifdef _WIN32
	m_t1 = system_clock::now();
#else
	m_t1 = Clock::now();
#endif

	int isam = 0;
	for(isam = 0;isam<samples;++isam)
	{
		try {
			client.latency(_return, payload);
		} catch (exception &io) {
			printf("Exception: %s\n", io.what());
			break;
		}
	}

#ifdef _WIN32
	m_t2 = system_clock::now();
#else
	m_t2 = Clock::now();
#endif

	transport->close();

	if(isam == samples)
	{
#ifdef _WIN32
		return (duration_cast<microseconds>(m_t2 - m_t1).count() - m_overhead) / samples;
#else
		return (std::chrono::duration_cast<microseconds>(m_t2 - m_t1).count() - m_overhead) / samples;
#endif
	}

	return -1;
}

max_stars_repo_name: romain-gimenez/RPC

max_issues_repo_name: romain-gimenez/RPC

max_forks_repo_name: romain-gimenez/RPC


text:
<<<<<<< HEAD
/*    Copyright (c) 2010-2018, Delft University of Technology
=======
/*    Copyright (c) 2010-2019, Delft University of Technology
>>>>>>> origin/master
 *    All rigths reserved
 *
 *    This file is part of the Tudat. Redistribution and use in source and
 *    binary forms, with or without modification, are permitted exclusively
 *    under the terms of the Modified BSD license. You should have received
 *    a copy of the license with this file. If not, please or visit:
 *    http://tudat.tudelft.nl/LICENSE.
 *
 *    References
 *      Mengali, G., and A.A. Quarta, Fondamenti di Meccanica del volo Spaziale.
 *      Noomen, R., Lambert targeter Excel file.
 *
 *    Notes
 *      DISCLAIMER: At the moment, the Lambert targeter only converges for about half of the cases.
 *      This is not evident from the tests below, but it was observed during simulations carried
 *      out by the author. The reason might very well be an erroneous definition of the starters.
 *
 *      The elliptical case was taken from Example 6.1, page 159-162 of ( Mengali, Quarta ). The
 *      hyperbolic case was taken from ( Noomen, R. ).
 *
 */

#define BOOST_TEST_MAIN

#include <boost/test/unit_test.hpp>

#include <Eigen/Core>
#include <Eigen/Geometry>

#include "Tudat/Astrodynamics/BasicAstrodynamics/unitConversions.h"

#include "Tudat/Astrodynamics/MissionSegments/lambertTargeterGooding.h"

namespace tudat
{
namespace unit_tests
{

using namespace unit_conversions;

//! Test the Gooding Lambert targeting algorithm code.
BOOST_AUTO_TEST_SUITE( test_lambert_targeter_gooding )

//! Test hyperbolic case.
BOOST_AUTO_TEST_CASE( testHyperbolicCase )
{
    // Expected test result in meters.
    // Hyperbolic test case (results from excel file [1]).
    const double expectedValueOfSemiMajorAxisHyperbola = -1270129.3602e3;
    const double expectedValueOfRadialVelocityAtDepartureHyperbola = -0.74546e3;
    const double expectedValueOfRadialVelocityAtArrivalHyperbola = 0.69321e3;
    const double expectedValueOfTransverseVelocityAtDepartureHyperbola = 0.15674e3;
    const double expectedValueOfTransverseVelocityAtArrivalHyperbola = 0.10450e3;
    const Eigen::Vector3d expectedInertialVelocityAtDeparture( -745.457, 156.743, 0.0 );
    const Eigen::Vector3d expectedInertialVelocityAtArrival( 104.495, -693.209, 0.0 );

    // Tolerances.
    const double toleranceSemiMajorAxisHyperbola = 1.0e-7;
    const double toleranceVelocity = 1.0e-4;

    // Time conversions.
    const double timeOfFlightInDaysHyperbola = 100.0;
    const double timeOfFlightHyperbola = convertJulianDaysToSeconds(
            timeOfFlightInDaysHyperbola );

    // Central body gravitational parameter.
    const double earthGravitationalParameter = 398600.4418e9;

    // The starting point is twice as far as L1 and L2, which is not really
    // realistic, but it is not about the case, but about the verification.
    const Eigen::Vector3d positionAtDepartureHyperbola( convertAstronomicalUnitsToMeters( 0.02 ),
                                                        0.0, 0.0 ),
            positionAtArrivalHyperbola( 0.0, convertAstronomicalUnitsToMeters( -0.03 ), 0.0 );

    // Hyperbolic orbit case.
    mission_segments::LambertTargeterGooding lambertTargeterHyperbola(
                positionAtDepartureHyperbola, positionAtArrivalHyperbola, timeOfFlightHyperbola,
                earthGravitationalParameter );

    // Create local vectors for position and velocity.
    const Eigen::Vector3d positionDepartureHyperbola = positionAtDepartureHyperbola;
    const Eigen::Vector3d velocityDepartureHyperbola =
            lambertTargeterHyperbola.getInertialVelocityAtDeparture( );

    // Test if the computed semi-major axis corresponds to the expected value within the specified
    // tolerance.
    BOOST_CHECK_CLOSE_FRACTION( lambertTargeterHyperbola.getSemiMajorAxis( ),
                                expectedValueOfSemiMajorAxisHyperbola,
                                toleranceSemiMajorAxisHyperbola );

    // Test if the computed velocity components corresponds to the expected value within the
    // specified tolerance.
    BOOST_CHECK_CLOSE_FRACTION( lambertTargeterHyperbola.getRadialVelocityAtDeparture( ),
                                expectedValueOfRadialVelocityAtDepartureHyperbola,
                                toleranceVelocity );
    BOOST_CHECK_CLOSE_FRACTION( lambertTargeterHyperbola.getRadialVelocityAtArrival( ),
                                expectedValueOfRadialVelocityAtArrivalHyperbola,
                                toleranceVelocity );
    BOOST_CHECK_CLOSE_FRACTION( lambertTargeterHyperbola.getTransverseVelocityAtDeparture( ),
                                expectedValueOfTransverseVelocityAtDepartureHyperbola,
                                toleranceVelocity );
    BOOST_CHECK_CLOSE_FRACTION( lambertTargeterHyperbola.getTransverseVelocityAtArrival( ),
                                expectedValueOfTransverseVelocityAtArrivalHyperbola,
                                toleranceVelocity );

    // Check that velocities match expected values within the defined tolerance.
    BOOST_CHECK_CLOSE_FRACTION( expectedInertialVelocityAtDeparture.x( ),
                                lambertTargeterHyperbola.getInertialVelocityAtDeparture( ).x( ),
                                toleranceVelocity );
    BOOST_CHECK_CLOSE_FRACTION( expectedInertialVelocityAtDeparture.y( ),
                                lambertTargeterHyperbola.getInertialVelocityAtDeparture( ).y( ),
                                toleranceVelocity );
    BOOST_CHECK_SMALL( lambertTargeterHyperbola.getInertialVelocityAtDeparture( ).z( ),
                       toleranceVelocity );
    BOOST_CHECK_CLOSE_FRACTION( expectedInertialVelocityAtArrival.x( ),
                                lambertTargeterHyperbola.getInertialVelocityAtArrival( ).x( ),
                                toleranceVelocity );
    BOOST_CHECK_CLOSE_FRACTION( expectedInertialVelocityAtArrival.y( ),
                                lambertTargeterHyperbola.getInertialVelocityAtArrival( ).y( ),
                                toleranceVelocity );
    BOOST_CHECK_SMALL( lambertTargeterHyperbola.getInertialVelocityAtArrival( ).z( ),
                       toleranceVelocity );

    // Test if the computed solution is anti-clockwise, if the z-component of the angular momentum
    // (h = r \times v) is positive.
    BOOST_CHECK_GT( positionDepartureHyperbola.cross( velocityDepartureHyperbola ).z( ),
                    std::numeric_limits< double >::epsilon( ) );
}

//! Test elliptical case.
BOOST_AUTO_TEST_CASE( testEllipticalCase )
{
    // Elliptical test case (results from example 6.1 page 159-162 [2]).
    // Set canonical units for Earth (see page 29 [2]).
    const double distanceUnit = 6.378136e6;
    const double timeUnit = 806.78;

    // Expected test result in meters.
    const double expectedValueOfSemiMajorAxisEllipse = 5.4214 * distanceUnit;
    const double expectedValueOfRadialVelocityAtDepartureEllipse = 2.73580e3;
    const double expectedValueOfRadialVelocityAtArrivalEllipse = 2.97503e3;
    const double expectedValueOfTransverseVelocityAtDepartureEllipse = 6.59430e3;
    const double expectedValueOfTransverseVelocityAtArrivalEllipse = 3.29715e3;
    const Eigen::Vector3d expectedInertialVelocityAtDeparture( 2735.8, 6594.3, 0.0 );
    const Eigen::Vector3d expectedInertialVelocityAtArrival( -1367.9, 4225.03, 0.0 );

    // Tolerance.
    const double toleranceSemiMajorAxisEllipse = 1.0e-3;
    const double toleranceVelocity = 1.0e-6;

    // Time conversions.
    const double timeOfFlightEllipse = 5.0 * timeUnit;

    // Central body gravitational parameter.
    const double earthGravitationalParameter = 398600.4418e9;

    const Eigen::Vector3d positionAtDepartureEllipse( 2.0 * distanceUnit, 0.0, 0.0 ),
            positionAtArrivalEllipse( 2.0 * distanceUnit, 2.0 * sqrt( 3.0 ) * distanceUnit, 0.0 );

    // Elliptical orbit case.
    mission_segments::LambertTargeterGooding lambertTargeterEllipse(
                positionAtDepartureEllipse, positionAtArrivalEllipse, timeOfFlightEllipse,
                earthGravitationalParameter );

    // Create local vectors for position and velocity.
    const Eigen::Vector3d positionDepartureEllipse = positionAtDepartureEllipse;
    const Eigen::Vector3d velocityDepartureEllipse =
            lambertTargeterEllipse.getInertialVelocityAtDeparture( );

    // Test if the computed semi-major axis corresponds to the expected value within the specified
    // tolerance.
    BOOST_CHECK_CLOSE_FRACTION( lambertTargeterEllipse.getSemiMajorAxis( ),
                                expectedValueOfSemiMajorAxisEllipse,
                                toleranceSemiMajorAxisEllipse );

    // Test if the computed velocity components corresponds to the expected value within the
    // specified tolerance.
    BOOST_CHECK_CLOSE_FRACTION( lambertTargeterEllipse.getRadialVelocityAtDeparture( ),
                                expectedValueOfRadialVelocityAtDepartureEllipse,
                                toleranceVelocity );
    BOOST_CHECK_CLOSE_FRACTION( lambertTargeterEllipse.getRadialVelocityAtArrival( ),
                                expectedValueOfRadialVelocityAtArrivalEllipse,
                                toleranceVelocity );
    BOOST_CHECK_CLOSE_FRACTION( lambertTargeterEllipse.getTransverseVelocityAtDeparture( ),
                                expectedValueOfTransverseVelocityAtDepartureEllipse,
                                toleranceVelocity );
    BOOST_CHECK_CLOSE_FRACTION( lambertTargeterEllipse.getTransverseVelocityAtArrival( ),
                                expectedValueOfTransverseVelocityAtArrivalEllipse,
                                toleranceVelocity );

    // Check that velocities match expected values within the defined tolerance.
    BOOST_CHECK_CLOSE_FRACTION( expectedInertialVelocityAtDeparture.x( ),
                                lambertTargeterEllipse.getInertialVelocityAtDeparture( ).x( ),
                                toleranceVelocity );
    BOOST_CHECK_CLOSE_FRACTION( expectedInertialVelocityAtDeparture.y( ),
                                lambertTargeterEllipse.getInertialVelocityAtDeparture( ).y( ),
                                toleranceVelocity );
    BOOST_CHECK_SMALL( lambertTargeterEllipse.getInertialVelocityAtDeparture( ).z( ),
                       toleranceVelocity );
    BOOST_CHECK_CLOSE_FRACTION( expectedInertialVelocityAtArrival.x( ),
                                lambertTargeterEllipse.getInertialVelocityAtArrival( ).x( ),
                                toleranceVelocity );
    BOOST_CHECK_CLOSE_FRACTION( expectedInertialVelocityAtArrival.y( ),
                                lambertTargeterEllipse.getInertialVelocityAtArrival( ).y( ),
                                toleranceVelocity );
    BOOST_CHECK_SMALL( lambertTargeterEllipse.getInertialVelocityAtArrival( ).z( ),
                       toleranceVelocity );

    // Test if the computed solution is anti-clockwise, if the z-component of the angular momentum
    // (h = r \times v) is positive.
    BOOST_CHECK_GT( positionDepartureEllipse.cross( velocityDepartureEllipse ).z( ),
                    std::numeric_limits< double >::epsilon( ) );
}

BOOST_AUTO_TEST_SUITE_END( )

} // namespace unit_tests
} // namespace tudat

max_stars_repo_name: ViktorJordanov/tudat

max_issues_repo_name: ViktorJordanov/tudat

max_forks_repo_name: ViktorJordanov/tudat


text:
#ifndef EDIT_HISTORY_MGR_HPP_
#define EDIT_HISTORY_MGR_HPP_
//============================================================================
// Name        :
// Author      : Avi
// Revision    : $Revision: #72 $
//
// Copyright 2009- ECMWF.
// This software is licensed under the terms of the Apache Licence version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation
// nor does it submit to any jurisdiction.
//
// This class manages the edit history, for the commands.
// It determines if there was a state change, if there was, it adds edit
// history to the stored nodes.
// Additionally we check that if there was an edit then the command must
// return ClientToServerCmd::isWrite() true.
//============================================================================
#include <boost/core/noncopyable.hpp>
class ClientToServerCmd;
class AbstractServer;

class EditHistoryMgr : private boost::noncopyable  {
public:
   EditHistoryMgr(const ClientToServerCmd*,AbstractServer*);
   ~EditHistoryMgr();

private:
   const ClientToServerCmd* cts_cmd_;
   AbstractServer* as_;
   mutable unsigned int state_change_no_;        // detect state change in defs
   mutable unsigned int modify_change_no_;       // detect state change in defs
};
#endif

max_stars_repo_name: mpartio/ecflow

max_issues_repo_name: mpartio/ecflow

max_forks_repo_name: mpartio/ecflow


text:
// ---------------------------------------------------------------------
// pion:  a Boost C++ framework for building lightweight HTTP interfaces
// ---------------------------------------------------------------------
// Copyright (C) 2007-2014 Splunk Inc.  (https://github.com/splunk/pion)
//
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
//

#include <boost/exception/diagnostic_information.hpp>
#include <boost/date_time/posix_time/posix_time_duration.hpp>
#include <pion/scheduler.hpp>

namespace pion {    // begin namespace pion

// static members of scheduler

const boost::uint32_t   scheduler::DEFAULT_NUM_THREADS = 8;
const boost::uint32_t   scheduler::NSEC_IN_SECOND = 1000000000; // (10^9)
const boost::uint32_t   scheduler::MICROSEC_IN_SECOND = 1000000;    // (10^6)

// scheduler member functions

void scheduler::shutdown(void)
{
    // lock mutex for thread safety
    boost::mutex::scoped_lock scheduler_lock(m_mutex);

    if (m_is_running) {

        PION_LOG_INFO(m_logger, "Shutting down the thread scheduler");

        while (m_active_users > 0) {
            // first, wait for any active users to exit
            PION_LOG_INFO(m_logger, "Waiting for " << m_active_users << " scheduler users to finish");
            m_no_more_active_users.wait(scheduler_lock);
        }

        // shut everything down
        m_is_running = false;
    }

    stop_services();
    stop_threads();
    finish_services();
    finish_threads();

    PION_LOG_INFO(m_logger, "The thread scheduler has shutdown");

    // Make sure anyone waiting on shutdown gets notified
    // even if the scheduler did not startup successfully
    m_scheduler_has_stopped.notify_all();
}

void scheduler::join(void)
{
    boost::mutex::scoped_lock scheduler_lock(m_mutex);
    while (m_is_running) {
        // sleep until scheduler_has_stopped condition is signaled
        m_scheduler_has_stopped.wait(scheduler_lock);
    }
}

void scheduler::add_active_user(void)
{
    if (++m_active_users == 1)
        startup();
}

void scheduler::remove_active_user(void)
{
    if (--m_active_users == 0)
        shutdown();
}

boost::system_time scheduler::get_wakeup_time(boost::uint32_t sleep_sec,
    boost::uint32_t sleep_nsec)
{
    return boost::get_system_time() + boost::posix_time::seconds(sleep_sec) + boost::posix_time::microseconds(sleep_nsec / 1000);
}

void scheduler::process_service_work(boost::asio::io_service& service) {
    boost::asio::io_service::work work(service);
    while (m_is_running) {
        try {
            service.run();
        } catch (std::exception& e) {
            PION_LOG_ERROR(m_logger, boost::diagnostic_information(e));
        } catch (...) {
            PION_LOG_ERROR(m_logger, "caught unrecognized exception");
        }
    }
}

// single_service_scheduler member functions

void single_service_scheduler::startup(void)
{
    // lock mutex for thread safety
    boost::mutex::scoped_lock scheduler_lock(m_mutex);

    if (! m_is_running) {
        PION_LOG_INFO(m_logger, "Starting thread scheduler");
        m_is_running = true;

        // schedule a work item to make sure that the service doesn't complete
        m_service.reset();

        // start multiple threads to handle async tasks
        for (boost::uint32_t n = 0; n < m_num_threads; ++n) {
            boost::shared_ptr<boost::thread> new_thread(new boost::thread( boost::bind(&scheduler::process_service_work,
                                                                                this, boost::ref(m_service)) ));
            m_thread_pool.push_back(new_thread);
        }
    }
}

// one_to_one_scheduler member functions

void one_to_one_scheduler::startup(void)
{
    // lock mutex for thread safety
    boost::mutex::scoped_lock scheduler_lock(m_mutex);

    if (! m_is_running) {
        PION_LOG_INFO(m_logger, "Starting thread scheduler");
        m_is_running = true;

        // make sure there are enough services initialized
        while (m_service_pool.size() < m_num_threads) {
            boost::shared_ptr<service_pair_type>  service_ptr(new service_pair_type());
            m_service_pool.push_back(service_ptr);
        }

        // start multiple threads to handle async tasks
        for (boost::uint32_t n = 0; n < m_num_threads; ++n) {
            boost::shared_ptr<boost::thread> new_thread(new boost::thread( boost::bind(&scheduler::process_service_work,
                                                                                this, boost::ref(m_service_pool[n]->first)) ));
            m_thread_pool.push_back(new_thread);
        }
    }
}

}   // end namespace pion

max_stars_repo_name: odant/conan-pion

max_issues_repo_name: odant/conan-pion

max_forks_repo_name: odant/conan-pion


text:
#ifndef JIMBO_RESOURCE_RESOURCE_HPP
#define JIMBO_RESOURCE_RESOURCE_HPP

/////////////////////////////////////////////////////////
// resource.hpp
//
// Ben Storey
//
// A resource is an object that can be loaded and read from an istream
// The representation for how these are stored should be determined
// by any subclasses. For resources that get streamed in/out, these may
// also require explicit synchronisation in the implementing class
//
/////////////////////////////////////////////////////////

#include <boost/noncopyable.hpp>
#include <vector>
#include "resource/resourceid.hpp"

namespace jimbo
{
    class Resource : boost::noncopyable
    {
    public:

        Resource(ResourceID id) : id_(id) { }
        virtual ~Resource() {}

        virtual void release() = 0;
        virtual int sizeInBytes() const = 0;

        // read will normally read all the data entirely. Textures etc don't make sense to load partially
        virtual void read(std::unique_ptr<std::istream> s) = 0;

        // Music etc may want to stream piece by piece. For that it should keep a reference to the istream
        // and then implement loads here as appropriate. As the name implies, it will process this call in another thread
        virtual void updateInBackgroundThread() {}

        // Streamable resources will typically set this to no until they've been loaded in full
        // Non-streamable resources should load everything at once, so after being read set this to yes
        virtual bool isFullyLoaded() = 0;

        ResourceID resourceID() const { return id_; }

        // To be called by the ResourceManager, implementing classes shouldn't be concerned with these...
        //void setInputStream(std::unique_ptr<std::istream> s) { stream_ = std::move(s); }
        //void releaseInputStream() { stream_ = nullptr; }
        //bool hasInputStream() const { return stream_ != nullptr; }

    protected:

        // Remember the resourceID we are referencing. Since these resources will get loaded within
        // another thread and passed back, it's helpful to embed the id so we can see what the pool
        // has loaded without having to track individual threads
        ResourceID id_;

        // The istream is also provided for the lifetime of the resource (at least, as long as it isn't released)
        // The resource itself needs to take ownership since it should remember the place when readBytes() is called
        //std::unique_ptr<std::istream> stream_;
    };

}

#endif // JIMBO_RESOURCE_RESOURCE_HPP

max_stars_repo_name: BenStorey/Jimbo

max_issues_repo_name: BenStorey/Jimbo

max_forks_repo_name: BenStorey/Jimbo


text:
///////////////////////////////////////////////////////////////////////////////////////
// survival::modelss::exponential::scalar::meta::is_survival_model.hpp         		 //
//                                                                                //
//  Copyright 2009 Erwann Rogard. 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_STATISTICS_DETAIL_DISTRIBUTION_SURVIVAL_MODELS_EXPONENTIAL_SCALAR_META_IS_SURVIVAL_MODEL_HPP_ER_2009
#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_SURVIVAL_MODELS_EXPONENTIAL_SCALAR_META_IS_SURVIVAL_MODEL_HPP_ER_2009
#include <boost/mpl/bool.hpp>
#include <boost/statistics/detail/distribution/survival/models/common/meta/is_survival_model.hpp>
#include <boost/statistics/detail/distribution/survival/models/exponential/scalar/model.hpp>

namespace boost {
namespace statistics{
namespace detail{
namespace distribution{
namespace survival {
namespace meta{

    template<typename T,typename L>
    struct is_survival_model< exponential_model<T,L> >
        : boost::mpl::bool_<true>{};

}// meta
}// survival
}// distribution
}// detail
}// statistics
}// boost

#endif


text:
#include <boost/test/unit_test.hpp>
#include "clangmm.h"
#include <string>

BOOST_AUTO_TEST_CASE(cursor) {
  // [ Should be changed with mockery

  std::string path("./case/main.cpp");

  clang::Index index(0, 0);
  clang::TranslationUnit tu(index, path, {});

  // ]

  auto cursor=tu.get_cursor(path, 103);

  BOOST_CHECK(cursor.get_kind() == clang::CursorKind::ReturnStmt);
}

ext: cc

max_stars_repo_name: MarcSeebold/libclangmm

max_issues_repo_name: MarcSeebold/libclangmm

max_forks_repo_name: MarcSeebold/libclangmm


text:
//EmulationStation, a graphical front-end for ROM browsing. Created by Alec "Aloshi" Lofquist.
//http://www.aloshi.com

#include <SDL.h>
#include <iostream>
#include <iomanip>
#include "Renderer.h"
#include "components/GuiGameList.h"
#include "SystemData.h"
#include <boost/filesystem.hpp>
#include "components/GuiDetectDevice.h"
#include "AudioManager.h"
#include "platform.h"
#include "Log.h"
#include "Window.h"
#include "EmulationStation.h"
#include "Settings.h"

#ifdef _RPI_
	#include <bcm_host.h>
#endif

#include <sstream>

namespace fs = boost::filesystem;

bool parseArgs(int argc, char* argv[], unsigned int* width, unsigned int* height)
{
	if(argc > 1)
	{
		for(int i = 1; i < argc; i++)
		{
			if(strcmp(argv[i], "-w") == 0)
			{
				*width = atoi(argv[i + 1]);
				i++; //skip the argument value
			}else if(strcmp(argv[i], "-h") == 0)
			{
				*height = atoi(argv[i + 1]);
				i++; //skip the argument value
			}else if(strcmp(argv[i], "--gamelist-only") == 0)
			{
				Settings::getInstance()->setBool("PARSEGAMELISTONLY", true);
			}else if(strcmp(argv[i], "--ignore-gamelist") == 0)
			{
				Settings::getInstance()->setBool("IGNOREGAMELIST", true);
			}else if(strcmp(argv[i], "--draw-framerate") == 0)
			{
				Settings::getInstance()->setBool("DRAWFRAMERATE", true);
			}else if(strcmp(argv[i], "--no-exit") == 0)
			{
				Settings::getInstance()->setBool("DONTSHOWEXIT", true);
			}else if(strcmp(argv[i], "--debug") == 0)
			{
				Settings::getInstance()->setBool("DEBUG", true);
				Log::setReportingLevel(LogDebug);
			}else if(strcmp(argv[i], "--dimtime") == 0)
			{
				Settings::getInstance()->setInt("DIMTIME", atoi(argv[i + 1]) * 1000);
				i++; //skip the argument value
			}else if(strcmp(argv[i], "--windowed") == 0)
			{
				Settings::getInstance()->setBool("WINDOWED", true);
			}else if(strcmp(argv[i], "--help") == 0)
			{
				std::cout << "EmulationStation, a graphical front-end for ROM browsing.\n";
				std::cout << "Command line arguments:\n";
				std::cout << "-w [width in pixels]		set screen width\n";
				std::cout << "-h [height in pixels]		set screen height\n";
				std::cout << "--gamelist-only			skip automatic game detection, only read from gamelist.xml\n";
				std::cout << "--ignore-gamelist		ignore the gamelist (useful for troubleshooting)\n";
				std::cout << "--draw-framerate		display the framerate\n";
				std::cout << "--no-exit			don't show the exit option in the menu\n";
				std::cout << "--debug				even more logging\n";
				std::cout << "--dimtime [seconds]		time to wait before dimming the screen (default 30, use 0 for never)\n";

				#ifdef USE_OPENGL_DESKTOP
					std::cout << "--windowed			not fullscreen\n";
				#endif

				std::cout << "--help				summon a sentient, angry tuba\n\n";
				std::cout << "More information available in README.md.\n";
				return false; //exit after printing help
			}
		}
	}

	return true;
}

bool verifyHomeFolderExists()
{
	//make sure the config directory exists
	std::string home = getHomePath();
	std::string configDir = home + "/.emulationstation";
	if(!fs::exists(configDir))
	{
		std::cout << "Creating config directory \"" << configDir << "\"\n";
		fs::create_directory(configDir);
		if(!fs::exists(configDir))
		{
			std::cerr << "Config directory could not be created!\n";
			return false;
		}
	}

	return true;
}

//called on exit, assuming we get far enough to have the log initialized
void onExit()
{
	Log::close();

	#ifdef _RPI_
		bcm_host_deinit();
	#endif
}

int main(int argc, char* argv[])
{
	unsigned int width = 0;
	unsigned int height = 0;

	if(!parseArgs(argc, argv, &width, &height))
		return 0;

	//if ~/.emulationstation doesn't exist and cannot be created, bail
	if(!verifyHomeFolderExists())
		return 1;

	#ifdef _RPI_
		bcm_host_init();
	#endif

	//start the logger
	Log::open();
	LOG(LogInfo) << "EmulationStation - " << PROGRAM_VERSION_STRING;

	//always close the log and deinit the BCM library on exit
	atexit(&onExit);

	Window window;
	if(!window.init(width, height))
	{
		LOG(LogError) << "Window failed to initialize!";
		return 1;
	}

	//dont generate joystick events while we're loading (hopefully fixes "automatically started emulator" bug)
	SDL_JoystickEventState(SDL_DISABLE);

	//try loading the system config file
	if(!SystemData::loadConfig(SystemData::getConfigPath(), true))
	{
		LOG(LogError) << "Error parsing system config file!";
		return 1;
	}

	//make sure it wasn't empty
	if(SystemData::sSystemVector.size() == 0)
	{
		LOG(LogError) << "No systems found! Does at least one system have a game present? (check that extensions match!)";
		return 1;
	}

	//choose which GUI to open depending on if an input configuration already exists
	if(fs::exists(InputManager::getConfigPath()))
	{
		GuiGameList::create(&window);
	}else{
		window.pushGui(new GuiDetectDevice(&window));
	}

	//generate joystick events since we're done loading
	SDL_JoystickEventState(SDL_ENABLE);

	bool sleeping = false;
	unsigned int timeSinceLastEvent = 0;
	int lastTime = 0;
	bool running = true;

	while(running)
	{
		SDL_Event event;
		while(SDL_PollEvent(&event))
		{
			switch(event.type)
			{
				case SDL_JOYHATMOTION:
				case SDL_JOYBUTTONDOWN:
				case SDL_JOYBUTTONUP:
				case SDL_KEYDOWN:
				case SDL_KEYUP:
				case SDL_JOYAXISMOTION:
					if(window.getInputManager()->parseEvent(event))
					{
						sleeping = false;
						timeSinceLastEvent = 0;
					}
					break;
				case SDL_USEREVENT:
					//try to poll input devices, but do not necessarily wake up...
					window.getInputManager()->parseEvent(event);
					break;
				case SDL_QUIT:
					running = false;
					break;
			}
		}

		if(sleeping)
		{
			lastTime = SDL_GetTicks();
			SDL_Delay(1); //this doesn't need to be accurate
			continue;
		}

		int curTime = SDL_GetTicks();
		int deltaTime = curTime - lastTime;
		lastTime = curTime;

		//cap deltaTime at 1000
		if(deltaTime > 1000 || deltaTime < 0)
			deltaTime = 1000;

		window.update(deltaTime);
		Renderer::swapBuffers(); //swap here so we can read the last screen state during updates (see ImageComponent::copyScreen())
		window.render();

		//sleep if we're past our threshold
		//sleeping entails setting a flag to start skipping frames
		//and initially drawing a black semi-transparent rect to dim the screen
		timeSinceLastEvent += deltaTime;
		if(timeSinceLastEvent >= (unsigned int)Settings::getInstance()->getInt("DIMTIME") && Settings::getInstance()->getInt("DIMTIME") != 0)
		{
			sleeping = true;
			timeSinceLastEvent = 0;
			Renderer::drawRect(0, 0, Renderer::getScreenWidth(), Renderer::getScreenHeight(), 0x000000A0);
			Renderer::swapBuffers();
		}

		Log::flush();
	}

	Renderer::deinit();
	SystemData::deleteSystems();

	std::cout << "EmulationStation cleanly shutting down...\n";

	return 0;
}