text:
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
//    names, trademarks, service marks, or product names of the Licensor
//    and its affiliates, except as required to comply with Section 4(c) of
//    the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "pxr/pxr.h"

#include "pxr/base/tf/pyWeakObject.h"
#include "pxr/base/tf/instantiateSingleton.h"

#include <boost/python/class.hpp>

PXR_NAMESPACE_OPEN_SCOPE

struct Tf_PyWeakObjectRegistry
{
    typedef Tf_PyWeakObjectRegistry This;

    /// Return the singleton instance.
    static This &GetInstance();
    void Insert(PyObject *obj, Tf_PyWeakObjectPtr const &weakObj);
    Tf_PyWeakObjectPtr Lookup(PyObject *obj) const;
    void Remove(PyObject *obj);

  private:
    Tf_PyWeakObjectRegistry() = default;
    friend class TfSingleton<This>;

    TfHashMap<PyObject *, Tf_PyWeakObjectPtr, TfHash> _weakObjects;
};

TF_INSTANTIATE_SINGLETON(Tf_PyWeakObjectRegistry);

Tf_PyWeakObjectRegistry &
Tf_PyWeakObjectRegistry::GetInstance()
{
    return TfSingleton<This>::GetInstance();
}

void
Tf_PyWeakObjectRegistry::Insert(PyObject *obj,
                                Tf_PyWeakObjectPtr const &weakObj)
{
    _weakObjects[obj] = weakObj;
}

Tf_PyWeakObjectPtr
Tf_PyWeakObjectRegistry::Lookup(PyObject *obj) const
{
    auto iter = _weakObjects.find(obj);
    return iter == _weakObjects.end() ? Tf_PyWeakObjectPtr() : iter->second;
}

void
Tf_PyWeakObjectRegistry::Remove(PyObject *obj)
{
    _weakObjects.erase(obj);
}

// A deleter instance is passed to PyWeakref_NewRef as the callback object
// so that when the python object we have the weak ref to dies, we can
// delete the corresponding weak object.
struct Tf_PyWeakObjectDeleter {
    static int WrapIfNecessary();
    explicit Tf_PyWeakObjectDeleter(Tf_PyWeakObjectPtr const &self);
    void Deleted(PyObject * /* weakRef */);
private:
    Tf_PyWeakObjectPtr _self;
};

int
Tf_PyWeakObjectDeleter::WrapIfNecessary()
{
    if (TfPyIsNone(TfPyGetClassObject<Tf_PyWeakObjectDeleter>())) {
        boost::python::class_<Tf_PyWeakObjectDeleter>
            ("Tf_PyWeakObject__Deleter", boost::python::no_init)
            .def("__call__", &Tf_PyWeakObjectDeleter::Deleted);
    }
    return 1;
}

Tf_PyWeakObjectDeleter::Tf_PyWeakObjectDeleter(Tf_PyWeakObjectPtr const &self)
    : _self(self)
{
    static int ensureWrapped = WrapIfNecessary();
    (void)ensureWrapped;
}

void
Tf_PyWeakObjectDeleter::Deleted(PyObject * /* weakRef */)
{
    _self->Delete();
}

Tf_PyWeakObjectPtr
Tf_PyWeakObject::GetOrCreate(boost::python::object const &obj)
{
    // If it's in the registry, return it.
    if (Tf_PyWeakObjectPtr p =
        Tf_PyWeakObjectRegistry::GetInstance().Lookup(obj.ptr()))
        return p;
    // Otherwise, make sure we can create a python weak reference to the
    // object.
    if (PyObject *weakRef = PyWeakref_NewRef(obj.ptr(), NULL)) {
        Py_DECREF(weakRef);
        return TfCreateWeakPtr(new Tf_PyWeakObject(obj));
    }
    // Cannot create a weak reference to obj -- return a null pointer.
    PyErr_Clear();
    return Tf_PyWeakObjectPtr();
}

boost::python::object
Tf_PyWeakObject::GetObject() const
{
    return boost::python::object
        (boost::python::handle<>
         (boost::python::borrowed(PyWeakref_GetObject(_weakRef.get()))));
}

void
Tf_PyWeakObject::Delete()
{
    Tf_PyWeakObjectRegistry::GetInstance().Remove(GetObject().ptr());
    delete this;
}

Tf_PyWeakObject::Tf_PyWeakObject(boost::python::object const &obj)
    : _weakRef(
        PyWeakref_NewRef(
            obj.ptr(), boost::python::
            object(Tf_PyWeakObjectDeleter(TfCreateWeakPtr(this))).ptr()))
{
    Tf_PyWeakObjectPtr self(this);

    // Set our python identity, but release it immediately, since we are a weak
    // reference and will expire as soon as the python object does.
    Tf_PyReleasePythonIdentity(self, GetObject().ptr());

    // Install us in the registry.
    Tf_PyWeakObjectRegistry::GetInstance().Insert(GetObject().ptr(), self);
}

PXR_NAMESPACE_CLOSE_SCOPE

max_stars_repo_name: DougRogers-DigitalFish/USD

max_issues_repo_name: DougRogers-DigitalFish/USD

max_forks_repo_name: DougRogers-DigitalFish/USD


text:
/**********************************************************************
 *  Copyright (c) 2008-2014, Alliance for Sustainable Energy.
 *  All rights reserved.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 **********************************************************************/

#ifndef UTILITIES_UNITS_UNIT_IMPL_HPP
#define UTILITIES_UNITS_UNIT_IMPL_HPP

#include <utilities/UtilitiesAPI.hpp>

#include <utilities/units/Unit.hpp>
#include <utilities/units/Scale.hpp>

#include <boost/smart_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>

namespace openstudio {
namespace detail {

  /** Unit_Impl is the implementation class for Unit.*/
  class UTILITIES_API Unit_Impl : public boost::enable_shared_from_this<Unit_Impl> {
   public:
    /** @name Constructors and Destructors */
    //@{

    /** Default constructor. Can set non-zero exponent (base 10) for the scale, and prettyString
     *  (alias for standardString, as in J = kg*m^2/s^2). The actual scale stored with Unit depends
     *  on what scales are registered in ScaleFactory. Throws if there is no entry for
     *  scaleExponent in ScaleFactory. Example: \verbatim
        openstudio::Unit u(-2,"J");
        u.setBaseUnitExponent("kg",1);
        u.setBaseUnitExponent("m",2);
        u.setBaseUnitExponent("s",-2);
        std::cout << u; // would print cJ, using default openstudio::ScaleFactory initialization \endverbatim
     *  Note that this is not the preferred method for constructing Joules. See openstudio::SIUnit,
     *  and openstudio::UnitFactory for alternatives. */
    Unit_Impl(int scaleExponent = 0,const std::string& prettyString="");

    /** Constructor using scale abbreviations registered in ScaleFactory. For instance, pass
     *  in "k" to access kilo = 10^3 (using the default ScaleFactory initialization). Throws if
     *  there is no entry for scaleAbbreviation in ScaleFactory. */
    Unit_Impl(const std::string& scaleAbbreviation,const std::string& prettyString="");

    virtual ~Unit_Impl() {}

    /** Deep copy constructor. */
    virtual Unit clone() const;

    /** Deep copy constructor that discards system designation. Postcondition: system() == UnitSystem::Mixed. */
    Unit cloneToMixed() const;

    //@}
    /** @name Base Units and Scale */
    //@{

    /// Returns base units already available in Unit.
    std::vector<std::string> baseUnits() const;

    /// Returns true if baseUnit is available in Unit.
    bool isBaseUnit(const std::string& baseUnit) const;

    /// Base unit exponent getter. Returns 0 if baseUnit not present. */
    int baseUnitExponent(const std::string& baseUnit) const;

    /// Sets baseUnit^exponent. If baseUnit not yet present, is added and return value is true.
    virtual void setBaseUnitExponent(const std::string& baseUnit, int exponent);

    /// Scale getter.
    const Scale& scale() const;

    /** Sets the scale to the one registered in ScaleFactory for 10^scaleExponent. Returns true
     *  if successful, false if no Scale with exponent == scaleExponent exists in ScaleFactory.
     *  In that case, Unit remains unchanged. */
    bool setScale(int scaleExponent);

    /** Sets the scale to the one registered in ScaleFactory under scaleAbbreviation. Returns true
     *  if successful, false if no Scale with abbr == scaleAbbreviation exists in ScaleFactory.
     *  In that case, Unit remains unchanged. */
    bool setScale(const std::string& scaleAbbreviation);

    //@}
    /** @name Serialization */
    //@{

    /** Returns the standard output string for this unit. Version withScale==false is used as a
     *  signature elsewhere in the utility. LaTeX formatting is used. Examples of valid strings:
     *
     *

     *
kg*m/s^2

     *
Btu/h

     *

     *
     *  Units with positive exponents come first, then '/', then units with negative exponents.
     *  ^ indicates a non-unity exponent.
     *
     *  If withScale==true (the default since this is probably preferred by users), scale
     *  abbreviation is prefixed. Prefers km^2 to M(m^2), kBtu/ft^2 to k(Btu/ft^2).
     */
    std::string standardString(bool withScale=true) const;

    /** Returns the preferred output string for this unit. For instance, the prettyString
     *  for SI energy is 'J' for Joules, but the standard string is 'kg*m^2/s^2'.
     *
     *  If withScale==true (the default since this is probably preferred by users), scale
     *  abbreviation is prefixed. Prefers km^2 to M(m^2), kBtu/ft^2 to k(Btu/ft^2). */
    std::string prettyString(bool withScale=true) const;

    /** Setter for prettyString (do not include scale abbreviation). openstudio::Unit attempts
     *  to keep up with prettyStrings, but makes no promises. Precondition: isCompoundUnit(str).
     *  Otherwise throws. */
    void setPrettyString(const std::string& str);

    /** Returns prettyString(withScale) if it exists; otherwise returns standardString(withScale). */
    std::string print(bool withScale=true) const;

    //@}
    /** @name Unit System */
    //@{

    /** Getter for this Unit's system */
    UnitSystem system() const;

    //@}
    /** @name Mathematical Operators */
    //@{

    /** Equality for units. Does not require identical systems, scales, or prettyStrings. */
    virtual bool operator==(const Unit& rUnit) const;

    /** Multiply-assign operator. Adds exponents on baseUnits and scales. Returned scale exponent
     *  may differ from expectation based on initialization of openstudio::ScaleFactory, see
     *  Scale operators declared in ScaleFactory.hpp. */
    virtual void operator*=(const Unit& rUnit);

    /** Divide-assign operator. Subtracts exponents on rUnit's baseUnits and scales from lUnits's.
     *  Returned scale exponent may differ from expectation based on initialization of
     *  openstudio::ScaleFactory, see Scale operators declared in ScaleFactory.hpp. */
    virtual void operator/=(const Unit& rUnit);

    /** Raise Unit to a rational power. Throws openstudio::Exception if expDenom is not a common divisor
     *  for all baseUnit and scale exponents. Returned scale exponent may differ from expectation
     *  based on initialization of openstudio::ScaleFactory, see Scale operators declared in
     *  ScaleFactory.hpp.  */
    void pow(int expNum,int expDenom=1,bool okToCallFactory=true);

    //@}
    /** @name Type Casting */
    //@{

    /** Get a public object that wraps this impl.*/
    template<typename T>
    T getPublicObject() const {
      T result(boost::dynamic_pointer_cast<typename T::ImplType>(
                 boost::const_pointer_cast<Unit_Impl>(shared_from_this())));
      return result;
    }

    //@}
   protected:
    typedef std::pair<std::string,int> UnitElement;
    std::vector<UnitElement> m_units;
    ScaleConstant m_scale;
    std::string m_prettyString;
    UnitSystem m_system;

    // constructor for derived classes
    Unit_Impl(int scaleExponent,
              const std::string& prettyString,
              int numBaseUnits,
              UnitSystem system);

    // constructor for derived classes
    Unit_Impl(const std::string& scaleAbbreviation,
              const std::string& prettyString,
              int numBaseUnits,
              UnitSystem system);

    std::vector<UnitElement>::iterator findBaseUnit(const std::string&);

    std::vector<UnitElement>::const_iterator findBaseUnit(const std::string&) const;

   private:
    REGISTER_LOGGER("openstudio.units.Unit");
  };

} // detail

} // openstudio

#endif // UTILITIES_UNITS_UNIT_IMPL_HPP

ext: hpp

max_stars_repo_name: ORNL-BTRIC/OpenStudio

max_issues_repo_name: ORNL-BTRIC/OpenStudio

max_forks_repo_name: ORNL-BTRIC/OpenStudio


text:
#pragma once

#include <cstdint>
#include <functional>
#include <string>
#include <type_traits>

#include <boost/mpl/contains.hpp>
#include <boost/mpl/vector.hpp>

#include "blackhole/stdext/string_view.hpp"

namespace blackhole {
inline namespace v1 {

/// Trait that describes how to format user defined types provided as attributes.
///
/// The trait must implement `apply` function that matches attribute function type signature.
template<typename T>
struct display_traits;

/// Represents a trait for mapping an owned types to their associated lightweight view types.
///
/// By default all types are transparently mapped to itself, but Blackhole provides some
/// specializations.
///
/// \warning it is undefined behavior to add specializations for this trait.
template<typename T>
struct view_of {
    typedef T type;
};

/// Forward.
class writer_t;

}  // namespace v1
}  // namespace blackhole

namespace blackhole {
inline namespace v1 {
namespace attribute {

class value_t;
class view_t;

/// Represents an attribute value holder.
///
/// Attribute value is an algebraic data type that can be initialized with one of the following
/// predefined primitive types:
///     - none marker;
///     - boolean type (true or false);
///     - signed integer types up to 64-bit size;
///     - unsigned integer types up to 64-bit size;
///     - floating point type;
///     - owned string type;
///     - and a function type, which can fill the specified writer with the value lazily.
///
/// The underlying value can be obtained through `blackhole::attribute::get` function with providing
/// the desired result type. For example:
///     blackhole::attribute::value_t value(42);
///     const auto actual = blackhole::attribute::get<std::int64_t>(value);
///
///     assert(42 == actual);
///
/// As an alternative a visitor pattern is provided for enabling underlying value visitation. To
/// enable this feature, implement the `value_t::visitor_t` interface and provide an instance of
/// this implementation to the `apply` method.
class value_t {
public:
    /// Available types.
    typedef std::nullptr_t null_type;
    typedef bool           bool_type;
    typedef std::int64_t   sint64_type;
    typedef std::uint64_t  uint64_type;
    typedef double         double_type;
    typedef std::string    string_type;
    typedef std::function<auto(writer_t& writer) -> void> function_type;

    /// The type sequence of all available types.
    typedef boost::mpl::vector<
        null_type,
        bool_type,
        sint64_type,
        uint64_type,
        double_type,
        string_type,
        function_type
    > types;

    /// Visitor interface.
    class visitor_t {
    public:
        virtual ~visitor_t() = 0;
        virtual auto operator()(const null_type&) -> void = 0;
        virtual auto operator()(const bool_type&) -> void = 0;
        virtual auto operator()(const sint64_type&) -> void = 0;
        virtual auto operator()(const uint64_type&) -> void = 0;
        virtual auto operator()(const double_type&) -> void = 0;
        virtual auto operator()(const string_type&) -> void = 0;
        virtual auto operator()(const function_type&) -> void = 0;
    };

    struct inner_t;

private:
    typedef std::aligned_storage<sizeof(function_type) + sizeof(int)>::type storage_type;

    /// The underlying type.
    storage_type storage;

public:
    /// Constructs a null value containing tagged nullptr value.
    value_t();

    value_t(std::nullptr_t);

    /// Constructs a value initialized with the given boolean value.
    value_t(bool value);

    /// Constructs a value initialized with the given signed integer.
    value_t(char value);
    value_t(short value);
    value_t(int value);
    value_t(long value);
    value_t(long long value);

    /// Constructs a value initialized with the given unsigned integer.
    value_t(unsigned char value);
    value_t(unsigned short value);
    value_t(unsigned int value);
    value_t(unsigned long value);
    value_t(unsigned long long value);

    value_t(double value);

    /// Constructs a value from the given string literal not including the terminating null
    /// character.
    ///
    /// \note this overload is required to prevent implicit conversion literal values to bool.
    template<std::size_t N>
    value_t(const char(&value)[N]) { construct(string_type{value, N - 1}); }

    value_t(std::string value);

    value_t(const value_t& other);
    value_t(value_t&& other);

    ~value_t();

    auto operator=(const value_t& other) -> value_t&;
    auto operator=(value_t&& other) -> value_t&;

    /// Applies the given visitor to perform pattern matching.
    auto apply(visitor_t& visitor) const -> void;

    /// Returns the internal underlying value.
    auto inner() noexcept -> inner_t&;
    auto inner() const noexcept -> const inner_t&;

private:
    template<typename T>
    auto construct(T&& value) -> void;
};

extern template auto value_t::construct<value_t::string_type>(value_t::string_type&&) -> void;

/// Represents an attribute value holder view, containing only lightweight views of the actual
/// values.
///
/// If an owned value is small enough to keep its copy - this class does it, otherwise keeping only
/// view proxy values. For example for `std::string` values there is a lightweight mapping that
/// holds only two members: a pointer to constant char and a size.
///
/// The underlying value can also be obtained through `blackhole::attribute::get` function with
/// providing the desired result type. For example:
///     blackhole::attribute::view_t value("le vinegret");
///     const auto actual = blackhole::attribute::get<std::int64_t>(value);
///
///     assert("le vinegret" == actual);
///
class view_t {
public:
    /// Available types.
    typedef std::nullptr_t null_type;
    typedef bool           bool_type;
    typedef std::int64_t   sint64_type;
    typedef std::uint64_t  uint64_type;
    typedef double         double_type;
    typedef string_view    string_type;

    struct function_type {
        const void* value;
        std::reference_wrapper<auto(const void* value, writer_t& writer) -> void> fn;

        auto operator()(writer_t& wr) const -> void {
            fn(value, wr);
        }

        auto operator==(const function_type& other) const noexcept -> bool {
            return value == other.value && fn.get() == other.fn.get();
        }
    };

    /// The type sequence of all available types.
    typedef boost::mpl::vector<
        null_type,
        bool_type,
        sint64_type,
        uint64_type,
        double_type,
        string_type,
        function_type
    > types;

    /// Visitor interface.
    class visitor_t {
    public:
        virtual ~visitor_t() = 0;
        virtual auto operator()(const null_type&) -> void = 0;
        virtual auto operator()(const bool_type&) -> void = 0;
        virtual auto operator()(const sint64_type&) -> void = 0;
        virtual auto operator()(const uint64_type&) -> void = 0;
        virtual auto operator()(const double_type&) -> void = 0;
        virtual auto operator()(const string_type&) -> void = 0;
        virtual auto operator()(const function_type&) -> void = 0;
    };

    struct inner_t;

private:
    typedef std::aligned_storage<2 * sizeof(void*) + sizeof(int)>::type storage_type;

    /// The underlying type.
    storage_type storage;

public:
    /// Constructs a null value view containing tagged nullptr value.
    view_t();

    view_t(std::nullptr_t);

    /// Constructs a value view initialized with the given boolean value.
    view_t(bool value);

    /// Constructs a value view initialized with the given signed integer.
    view_t(char value);
    view_t(short value);
    view_t(int value);
    view_t(long value);
    view_t(long long value);

    /// Constructs a value view initialized with the given unsigned integer.
    view_t(unsigned char value);
    view_t(unsigned short value);
    view_t(unsigned int value);
    view_t(unsigned long value);
    view_t(unsigned long long value);

    /// Constructs a value view from the given floating point value.
    view_t(float value);
    view_t(double value);

    /// Constructs a value view from the given string literal not including the terminating null
    /// character.
    ///
    /// \note this overload is required to prevent implicit conversion literal values to bool.
    template<std::size_t N>
    view_t(const char(&value)[N]) { construct(string_type{value, N - 1}); }

    /// Constructs a value view from the given string view.
    view_t(const string_type& value);

    /// Constructs a value view from the given string.
    view_t(const std::string& value);

    /// Constructs a value view from the given owned attribute value.
    view_t(const value_t& value);

    /// Constructs a value view from a custom type that implements `display_traits` trait.
    ///
    /// \sa display_traits for more information.
    template<typename T>
    view_t(const T& value, decltype(&display_traits<T>::apply)* = nullptr) {
        construct(function_type{static_cast<const void*>(&value), std::ref(display<T>)});
    }

    view_t(const view_t& other) = default;
    view_t(view_t&& other) = default;

    ~view_t() = default;

    auto operator=(const view_t& other) -> view_t& = default;
    auto operator=(view_t&& other) -> view_t& = default;

    /// Applies the given visitor to perform pattern matching.
    auto apply(visitor_t& visitor) const -> void;

    auto operator==(const view_t& other) const -> bool;
    auto operator!=(const view_t& other) const -> bool;

    /// Returns the internal underlying value.
    auto inner() noexcept -> inner_t&;
    auto inner() const noexcept -> const inner_t&;

private:
    template<typename T>
    auto construct(T&& value) -> void;

    template<typename T>
    static auto display(const void* value, writer_t& wr) -> void {
        display_traits<T>::apply(*static_cast<const T*>(value), wr);
    }
};

extern template auto view_t::construct<string_view>(string_view&& value) -> void;
extern template auto view_t::construct<view_t::function_type>(view_t::function_type&& value) -> void;

/// Retrieves a value of a specified, but yet restricted type, from a given attribute value.
///
/// \throws std::bad_cast if the content is not of the specified type T.
template<typename T>
auto get(const value_t& value) ->
    typename std::enable_if<boost::mpl::contains<value_t::types, T>::value, const T&>::type;

/// Retrieves a value of a specified, but yet restricted type, from a given attribute value view.
///
/// \throws std::bad_cast if the content is not of the specified type T.
template<typename T>
auto get(const view_t& value) ->
    typename std::enable_if<boost::mpl::contains<view_t::types, T>::value, const T&>::type;

}  // namespace attribute
}  // namespace v1
}  // namespace blackhole

max_stars_repo_name: JakariaBlaine/blackhole

max_issues_repo_name: JakariaBlaine/blackhole

max_forks_repo_name: JakariaBlaine/blackhole


text:
//  (C) Copyright Gennadiy Rozental 2001.
//  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/test for the library home page.
//
/// @file
/// Defines global_fixture
// ***************************************************************************

#ifndef BOOST_TEST_TREE_GLOBAL_FIXTURE_HPP_091911GER
#define BOOST_TEST_TREE_GLOBAL_FIXTURE_HPP_091911GER

// Boost.Test
#include <boost/test/detail/config.hpp>
#include <boost/test/detail/global_typedef.hpp>

#include <boost/test/tree/observer.hpp>
#include <boost/test/tree/fixture.hpp>

#include <boost/test/detail/suppress_warnings.hpp>

//____________________________________________________________________________//

namespace boost {
namespace unit_test {

// ************************************************************************** //
// **************             global_configuration             ************** //
// ************************************************************************** //

class BOOST_TEST_DECL global_configuration : public test_observer {

public:
    // Constructor
    global_configuration();

    /// Unregisters the global fixture from the framework
    ///
    /// This is called by the framework at shutdown time
    void unregister_from_framework();

    // Dtor
    virtual ~global_configuration();

    // Happens after the framework global observer init has been done
    virtual int     priority() { return 1; }

private:
    bool registered;
};

// ************************************************************************** //
// **************                global_fixture                ************** //
// ************************************************************************** //

class BOOST_TEST_DECL global_fixture : public test_unit_fixture {

public:
    // Constructor
    global_fixture();

    /// Unregisters the global fixture from the framework
    ///
    /// This is called by the framework at shutdown time
    void unregister_from_framework();

    // Dtor
    virtual ~global_fixture();

private:
    bool registered;
};

//____________________________________________________________________________//

namespace ut_detail {

template<typename F>
struct global_configuration_impl : public global_configuration {
    // Constructor
    global_configuration_impl() : m_configuration_observer( 0 )  {
    }

    // test observer interface
    virtual void    test_start( counter_t ) {
        m_configuration_observer = new F;
    }

    // test observer interface
    virtual void    test_finish()           {
        if(m_configuration_observer) {
            delete m_configuration_observer;
            m_configuration_observer = 0;
        }
    }
private:
    // Data members
    F*  m_configuration_observer;
};

template<typename F>
struct global_fixture_impl : public global_fixture {
    // Constructor
    global_fixture_impl() : m_fixture( 0 )  {
    }

    // test fixture interface
    virtual void setup()                    {
        m_fixture = new F;
        setup_conditional(*m_fixture);
    }

    // test fixture interface
    virtual void teardown()                 {
        if(m_fixture) {
            teardown_conditional(*m_fixture);
        }
        delete m_fixture;
        m_fixture = 0;
    }

private:
    // Data members
    F*  m_fixture;
};

} // namespace ut_detail
} // namespace unit_test
} // namespace boost

#include <boost/test/detail/enable_warnings.hpp>

#endif // BOOST_TEST_TREE_GLOBAL_FIXTURE_HPP_091911GER

max_stars_repo_name: Netis/packet-agent

max_issues_repo_name: Netis/packet-agent

max_forks_repo_name: Netis/packet-agent


text:
#include "IStorage.h"
#include <regex>
#include <boost/uuid/uuid.hpp>

IStorage::IStorage(HecubaSession* session, std::string id_model, std::string id_object, uint64_t* storage_id, Writer* writer) {
	this->currentSession = session;
	this->id_model = id_model;
	this->id_obj = id_object;

	this->storageid = storage_id;
	this->dataWriter = writer;
}

IStorage::~IStorage() {
	delete(dataWriter);
}

std::string IStorage::generate_numpy_table_name(std::string attributename) {
    /* ksp.DUUIDtableAttribute extracted from hdict::make_val_persistent */
    //std::cout << "DEBUG: IStorage::generate_numpy_table_name: BEGIN attribute:"<<attributename<<std::endl;
    std::regex what("-");
    std::string name;
    // Obtain keyspace and table_name from id_obj (keyspace.table_name)
    uint32_t pos = id_obj.find_first_of(".");
    //std::string ksp = id_obj.substr(0, pos);
    std::string table_name = id_obj.substr(pos+1, id_obj.length()); //skip the '.'

    // Generate a new UUID for this attribute
    uint64_t *c_uuid = currentSession->generateUUID(); // UUID for the new object
    std::string uuid = std::regex_replace(currentSession->UUID2str(c_uuid), what, "_");

    // attributename contains "name1.name2.....attributename" therefore keep the last attribute name TODO: Fix this 'name.name...' nightmare
    //name = ksp + ".D" + uuid + table_name + attributename.substr(attributename.find_last_of('_'), attributename.size());
    name = "D" + uuid + table_name + attributename;

    name = name.substr(0,48);
    //std::cout << "DEBUG: IStorage::generate_numpy_table_name: END "<<name<<std::endl;
    return name;
}

uint64_t* IStorage::getStorageID() {
    return storageid;
}

Writer *
IStorage::getDataWriter(void) {
    return dataWriter;
}

void
IStorage::sync(void) {
    this->dataWriter->flush_elements();
}

/* Transform IStorage pointers to StorageIDs pointers
    Args:
        dst: block of memory to update
        value_type: string from ObjSpec specifying the type to transform,
            anything different from a basic type will be transformed
        src: block of memory to transform
        src_size: size of src

    value is a pointer to a block of memory with a value (if basic types) or pointer to the IStorage:
     src ----> +---------+
               |     *---+------------------->+----------+
               +---------+                    | IStorage-+-------->+-----------+
                                              +----------+         | StorageID |
    Generates:                                                     +-----------+

     dst ----> +---------+
               |     *---+------------------->+-----------+
               +---------+                    | StorageID |
                                              +-----------+
    But:
     src ----> +---------+
               | 42      |
               +---------+
    Generates:

     dst ----> +---------+
               | 42      |
               +---------+

*/
void IStorage::convert_IStorage_to_UUID(char * dst, const std::string& value_type, void* src, int64_t src_size) const {
    void * result;
    if (!ObjSpec::isBasicType(value_type)) {
        result = (*(IStorage **)src)->getStorageID(); // 'src' MUST be a valid pointer or it will segfault here...
        // Minimal Check for UUID
        boost::uuids::uuid u;
        memcpy(&u, result, 16);
        boost::uuids::uuid::variant_type variant = u.variant();
        boost::uuids::uuid::version_type version = u.version();
        if ( ! ((variant == boost::uuids::uuid::variant_rfc_4122) && (version == boost::uuids::uuid::version_name_based_sha1))) {
            throw ModuleException("IStorage:: Set Item. Wrong UUID format for object... is it a pointer to an IStorage?");
        }
        // It seems like a valid UUID
        void * sid = malloc(sizeof(uint64_t)*2);
        memcpy(sid, result, sizeof(uint64_t)*2);
        memcpy(dst, &sid, src_size) ;
    } else{ // it is a basic type, just copy the value
        memcpy(dst, src, src_size) ;
    }
}

/* Args:
    key and value are pointers to a block of memory with the values (if basic types) or pointer to the IStorage:
    key/value -+
               |
               V
               +---------+
               |     *---+------------------->+----------+
               +---------+                    | IStorage |-------->+-----------+
               | 42      |                    +----------+         | StorageID |
               +---------+                                         +-----------+
               | 0.66    |
               +---------+
               |     *---+------------------->+----------+
               +---------+                    | IStorage |-------->+-----------+
                                              +----------+         | StorageID |
                                                                   +-----------+
    Create a copy of it, normalizing the pointer to other structs keeping just the storageID:
    cc_key/cc_val
               |
               V
               +---------+
               |     *---+------------------->+-----------+
               +---------+                    | StorageID |
               | 42      |                    +-----------+
               +---------+
               | 0.66    |
               +---------+
               |     *---+------------------->+-----------+
               +---------+                    | StorageID |
                                              +-----------+
*/
void
IStorage::writeTable(const void* key, void* value, const enum IStorage::valid_writes mytype) {
	/* PRE: key and value arrives already coded as expected */

    void * cc_val;

    const TableMetadata* writerMD = dataWriter->get_metadata();

    DataModel* model = this->currentSession->getDataModel();

    ObjSpec ospec = model->getObjSpec(this->id_model);
    //std::cout << "DEBUG: IStorage::setItem: obtained model for "<<id_model<<std::endl;

    std::string value_type;
    if (ospec.getType() == ObjSpec::valid_types::STORAGEDICT_TYPE) {
        if (mytype != SETITEM_TYPE) {
            throw ModuleException("IStorage:: Set Item on a non Dictionary is not supported");
        }
        // Dictionary values may have N  columns, create a new structure with all of them normalized.
        std::cout<< "WriteTable malloc("<<writerMD->get_values_size()<<")"<<std::endl;
        cc_val = malloc(writerMD->get_values_size()); // This memory will be freed after the execution of the query (at callback)

        uint64_t offset=0;
        uint32_t numcolumns = writerMD->get_values()->size();
        std::cout<< "WriteTable numcols="<<numcolumns<<std::endl;
        int64_t value_size;

        for (uint32_t i=0; i < numcolumns; i++) {

            std::cout<< "WriteTable offset ="<<offset<<std::endl;
            value_size = writerMD->get_values_size(i);
            std::string value_type = ospec.getIDModelFromCol(i);

            convert_IStorage_to_UUID(((char *)cc_val)+offset, value_type, ((char*)value) + offset, value_size);

            offset += value_size;
        }

    } else if (ospec.getType() == ObjSpec::valid_types::STORAGEOBJ_TYPE) {
        if (mytype != SETATTR_TYPE) {
            throw ModuleException("IStorage:: Set Attr on a non Object is not supported");
        }
        int64_t value_size = (*writerMD->get_single_value((char*)key))[0].size;
        cc_val = malloc(value_size); // This memory will be freed after the execution of the query (at callback)

        std::string value_type = ospec.getIDModelFromColName(std::string((char*)key));
        convert_IStorage_to_UUID((char *)cc_val, value_type, value, value_size);
    }

    //std::cout << "DEBUG: IStorage::setItem: After creating value object "<<std::endl;

    // STORE THE ENTRY IN TABLE (Ex: keys + value ==> storage_id del numpy)

    std::pair<uint16_t, uint16_t> keySize = writerMD->get_keys_size();
    uint64_t partKeySize = keySize.first;
    uint64_t clustKeySize = keySize.second;
    std::cout<< "DEBUG: Istorage::setItem --> partKeySize = "<<partKeySize<<" clustKeySize = "<< clustKeySize << std::endl;

    void *cc_key= NULL;
    if (mytype == SETITEM_TYPE) {
        cc_key = malloc(partKeySize+clustKeySize); // This memory will be freed after the execution of the query (at callback)
        std::memcpy(cc_key, key, partKeySize+clustKeySize);
    } else {
        uint64_t* sid = this->getStorageID();
        void* c_key = malloc(2*sizeof(uint64_t)); //uuid
        std::memcpy(c_key, sid, 2*sizeof(uint64_t));

        cc_key = malloc(sizeof(uint64_t *)); // This memory will be freed after the execution of the query (at callback)
        std::memcpy(cc_key, &c_key, sizeof(uint64_t *));
    }

    if (mytype == SETITEM_TYPE) {
        // key arrives codified and contains latitude(double) + timestep(int)
        this->dataWriter->write_to_cassandra(cc_key, cc_val);
    } else {
        char* attr_name = (char*) key;
        this->dataWriter->write_to_cassandra(cc_key, cc_val, attr_name);
    }
}

void IStorage::setAttr(const char *attr_name, void* value) {
    /* PRE: value arrives already coded as expected: block of memory with pointers to IStorages or basic values*/
    //std::cout << "DEBUG: IStorage::setAttr: "<<std::endl;
    writeTable(attr_name, value, SETATTR_TYPE);
}

void IStorage::setAttr(const char *attr_name, IStorage* value) {
    /* 'writetable' expects a block of memory with pointers to IStorages, therefore add an indirection */
    writeTable(attr_name, (void *) &value, SETATTR_TYPE);
}

void IStorage::setItem(void* key, void* value) {
    /* PRE: value arrives already coded as expected: block of memory with pointers to IStorages or basic values*/
    writeTable(key, value, SETITEM_TYPE);
}

void IStorage::setItem(void* key, IStorage * value){
    /* 'writetable' expects a block of memory with pointers to IStorages, therefore add an indirection */
    writeTable(key, (void *) &value, SETITEM_TYPE);
}

ext: cpp

max_stars_repo_name: cugni/hecuba

max_issues_repo_name: cugni/hecuba

max_forks_repo_name: cugni/hecuba


text:
#include "ros/ros.h"
#include "std_msgs/String.h"
#include"Eigen/Dense"
#include <vector>
#include <iostream>
#include <QString>
#include <QList>
#include "Robot.h"
//#include"TaskSpace.h"
#include"taskspaceoffline.h"
#include <qmath.h>
#include <cstring>
#include<qdebug.h>
#include <Eigen/Geometry>
#include <cstdlib>
//#include <link.h>
#include "Eigen/eiquadprog.h"
#include "Eigen/Core"
#include "Eigen/Cholesky"
#include "Eigen/LU"
#include<std_msgs/Int32MultiArray.h>
#include<std_msgs/Float32MultiArray.h>
#include<math.h>
#include<sensor_msgs/Imu.h>
#include<std_msgs/Float64.h>
#include "qcgenerator.h"
#include <gazebo_msgs/LinkStates.h>
#include<termios.h>
#include<QTime>
#include<geometry_msgs/Wrench.h>
#include<sensor_msgs/JointState.h>
#include "qcgenerator.h"
#include<termios.h>

using namespace  std;
using namespace Eigen;
QTime timer;
int count;

double saturate(double a, double min, double max){
    if(a<min){return min;}
    else if(a>max){return max;}
    else{return a;}
}

int getch()
{

        static struct termios oldt, newt;
        tcgetattr( STDIN_FILENO, &oldt);           // save old settings
        newt = oldt;
        newt.c_lflag &= ~(ICANON);                 // disable buffering
        tcsetattr( STDIN_FILENO, TCSANOW, &newt);  // apply new settings

        int c = getchar();  // read character (non-blocking)

        tcsetattr( STDIN_FILENO, TCSANOW, &oldt);  // restore old settings
        return c;

}

int qc_offset[12];
bool qc_initial_bool;

void qc_initial(const sensor_msgs::JointState & msg){
    if (qc_initial_bool){

        for (int i = 0; i < 12; ++i) {
            qc_offset[i]=int(msg.position[i+1]);

        }

        qc_initial_bool=false;

        ROS_INFO("Offset=%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t\nInitialized!",
                 qc_offset[0],qc_offset[1],qc_offset[2],qc_offset[3],qc_offset[4],
                qc_offset[5],qc_offset[6],qc_offset[7],qc_offset[8],qc_offset[9],
                qc_offset[10],qc_offset[11]);}
    }

double Fxl,Fyr, Fzl,Fzr,Mxl,Myl,Myr,Mxr;
VectorXd CoPR(2), CoPL(2);
void FT_left_feedback(const geometry_msgs::Wrench &msg){
 Fzl=msg.force.z;
 Mxl=-msg.torque.y;
 Myl=msg.torque.x;
 CoPL << Myl/Fzl,
         Mxl/Fzl;

}

void FT_right_feedback(const geometry_msgs::Wrench &msg){
 Fzr=msg.force.z;
 Mxr=-msg.torque.x;
 Myr=-msg.torque.y;
 CoPR << Myr/Fzr,
         Mxr/Fzr;

}

double IMU_roll,IMU_pitch,IMU_yaw;

void IMU_feedback(const sensor_msgs::Imu &msg){
IMU_roll=msg.orientation.x;
IMU_pitch=msg.orientation.y;
IMU_yaw=msg.orientation.z;
}

int main(int argc, char **argv)
{
double d=M_PI/180/20;//0.05 degree
    qc_initial_bool=true;
    QCgenerator QC;
    for (int i = 0; i < 12; ++i) {
        qc_offset[i]=0;
    }

int count = 0;
double t=0;
double dt=.005;

ros::init(argc, argv, "myNode");
ros::NodeHandle nh;
ros::Publisher  chatter_pub  = nh.advertise<std_msgs::Int32MultiArray>("jointdata/qc",1000);
ros::Subscriber ft_left = nh.subscribe("/surena/ft_l_state",1000,FT_left_feedback);
ros::Subscriber ft_right = nh.subscribe("/surena/ft_r_state",1000,FT_right_feedback);
ros::Subscriber qcinit = nh.subscribe("/surena/inc_joint_state", 1000, qc_initial);
ros::Subscriber imu = nh.subscribe("/surena/imu_state",1000,IMU_feedback);

ros::Rate loop_rate(200);

std_msgs::Int32MultiArray msg;
std_msgs::MultiArrayDimension msg_dim;

msg_dim.label = "joint_position";
msg_dim.size = 1;
msg.layout.dim.clear();
msg.layout.dim.push_back(msg_dim);

vector<double> q(13);
for (int var = 0; var < 13; ++var) {
    q[var]=0;
}
double qkamar=0;
qDebug()<<"press any key to start!";
getch();
qDebug()<<"started!";

while (ros::ok())
{

    if (qc_initial_bool) {
        ROS_INFO_ONCE("qc is initializing!");
        ros::spinOnce();
        continue;
    }

count++;
int c=0;
//if(count>5) {
//    c= getch();
//    count=0;
//    ROS_INFO("ascii=%d",c);
//}
qDebug()<<"\nright: HY='6,y' HR='5,t' HP='4,r' K='3,e' AP='2,w' AR='1,q'\nleft: HY='h,n' HR='g,b' HP='f,v' K='d,c' AP='s,x' AR='a,z'\nWP='/,'\t'`' for quit!";
double Fz=Fzl+Fzr;
double My=Myl+Myr;

c= getch();
qDebug()<<c;

if(c==96){break;}

if(c==49){q[7-1]+=d;}if(c==113){q[7-1]-=d;}
if(c==50){q[7-2]+=d;}if(c==119){q[7-2]-=d;}
if(c==51){q[7-3]+=d;}if(c==101){q[7-3]-=d;}
if(c==52){q[7-4]+=d;}if(c==114){q[7-4]-=d;}
if(c==53){q[7-5]+=d;}if(c==116){q[7-5]-=d;}
if(c==54){q[7-6]+=d;}if(c==121){q[7-6]-=d;}

if(c==97) {q[19-7]+=d;}   if(c==122){q[19-7]-=d;}
if(c==115){q[19-8]+=d;}   if(c==120){q[19-8]-=d;}
if(c==100){q[19-9]+=d;}    if(c==99){q[19-9]-=d;}
if(c==102){q[19-10]+=d;}  if(c==118){q[19-10]-=d;}
if(c==103){q[19-11]+=d;}   if(c==98){q[19-11]-=d;}
if(c==104){q[19-12]+=d;}  if(c==110){q[19-12]-=d;}

if(c==39){qkamar+=d;}  if(c==47){qkamar-=d;}
if(c==46){q[7-4]+=d;q[19-10]+=d;}  if(c==59){q[7-4]-=d;q[19-10]-=d;}

ROS_INFO("\nright: HY=%f HR=%f HP=%f K=%f AP=%f AR=%f\nleft: HY=%f HR=%f HP=%f K=%f AP=%f AR=%f WP=%f",
         q[1]*180/M_PI,q[2]*180/M_PI,q[3]*180/M_PI,q[4]*180/M_PI,q[5]*180/M_PI,q[6]*180/M_PI,
        q[7]*180/M_PI,q[8]*180/M_PI,q[9]*180/M_PI,q[10]*180/M_PI,q[11]*180/M_PI,q[12]*180/M_PI,qkamar*180/M_PI);
ROS_INFO("CoPL=(%f\t%f),Mxl=%f,Myl=%f,Fzl=%f",CoPL(0),CoPL(1),Mxl,Myl,Fzl);
ROS_INFO("CoPR=(%f\t%f),MxR=%f,MyR=%f,Fzr=%f",CoPR(0),CoPR(1),Mxr,Myr,Fzr);
ROS_INFO("CoPx=%f,My=%f,Fz=%f",My/Fz,My,Fz);
ROS_INFO("roll=%f,pitch=%f,yaw=%f",IMU_roll,IMU_pitch,IMU_yaw);
vector<int> qref(12);
qref=QC.ctrldata2qc(q);

int qrefkamar=int(qkamar*(1/(2*M_PI))*(2304)*50);

 msg.data.clear();
for(int  i = 0;i < 12;i++)
{
    msg.data.push_back(qref[i]+qc_offset[i]);
}
for(int  i = 12;i < 28;i++)
{
    msg.data.push_back(0);
}
msg.data.push_back(qrefkamar);

    chatter_pub.publish(msg);

ros::spinOnce();
loop_rate.sleep();
++count;
t+=dt;
}

return 0;
}

max_stars_repo_name: amin-amani/humanoid

max_issues_repo_name: amin-amani/humanoid

max_forks_repo_name: amin-amani/humanoid


text:
#include <boost/property_tree/json_parser.hpp>
#include <fstream>
#include <iostream>
#include <nano/lib/utility.hpp>
#include <nano/nano_node/daemon.hpp>
#include <nano/node/daemonconfig.hpp>
#include <nano/node/ipc.hpp>
#include <nano/node/working.hpp>

void nano_daemon::daemon::run (boost::filesystem::path const & data_path, nano::node_flags const & flags)
{
	boost::filesystem::create_directories (data_path);
	boost::system::error_code error_chmod;
	nano::set_secure_perm_directory (data_path, error_chmod);
	std::unique_ptr<nano::thread_runner> runner;
	nano::daemon_config config;
	auto error = nano::read_and_update_daemon_config (data_path, config);

	if (!error)
	{
		config.node.logging.init (data_path);
		boost::asio::io_context io_ctx;
		auto opencl (nano::opencl_work::create (config.opencl_enable, config.opencl, config.node.logging));
		nano::work_pool opencl_work (config.node.work_threads, config.node.pow_sleep_interval, opencl ? [&opencl](nano::uint256_union const & root_a, uint64_t difficulty_a) {
			return opencl->generate_work (root_a, difficulty_a);
		}
		                                                                              : std::function<boost::optional<uint64_t> (nano::uint256_union const &, uint64_t)> (nullptr));
		nano::alarm alarm (io_ctx);
		nano::node_init init;
		try
		{
			auto node (std::make_shared<nano::node> (init, io_ctx, data_path, alarm, config.node, opencl_work, flags));
			if (!init.error ())
			{
				node->start ();
				std::unique_ptr<nano::rpc> rpc = get_rpc (io_ctx, *node, config.rpc);
				if (rpc)
				{
					rpc->start (config.rpc_enable);
				}
				nano::ipc::ipc_server ipc (*node, *rpc);
				runner = std::make_unique<nano::thread_runner> (io_ctx, node->config.io_threads);
				runner->join ();
			}
			else
			{
				std::cerr << "Error initializing node\n";
			}
		}
		catch (const std::runtime_error & e)
		{
			std::cerr << "Error while running node (" << e.what () << ")\n";
		}
	}
	else
	{
		std::cerr << "Error deserializing config: " << error.get_message () << std::endl;
	}
}


text:
//
// Object implementation.
//
//  Copyright (C) 2001-2007  Peter Johnson
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND OTHER CONTRIBUTORS ``AS IS''
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR OTHER CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
#define DEBUG_TYPE "Object"

#include "yasmx/Object.h"

#include <memory>

#include <boost/pool/object_pool.hpp>

#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/Twine.h"
#include "yasmx/Basic/Diagnostic.h"
#include "yasmx/Config/functional.h"
#include "yasmx/Arch.h"
#include "yasmx/Bytecode.h"
#include "yasmx/Optimizer.h"
#include "yasmx/Section.h"
#include "yasmx/Symbol.h"

#include "hamt.h"

STATISTIC(num_exist_symbol, "Number of existing symbols found by name");
STATISTIC(num_new_symbol, "Number of symbols created by name");

using namespace yasm;

namespace {
/// Get name helper for symbol table HAMT.
class SymGetName
{
public:
    StringRef operator() (const Symbol* sym) const
    { return sym->getName(); }
};
} // anonymous namespace

namespace yasm {
class Object::Impl
{
public:
    Impl(bool nocase)
        : sym_map(nocase)
        , special_sym_map(true)
    {}
    ~Impl() {}

    Symbol* NewSymbol(StringRef name)
    {
        return m_sym_pool.construct(name);
    }

    void DeleteSymbol(Symbol* sym)
    {
        m_sym_pool.destroy(sym);
    }

    typedef hamt<StringRef, Symbol, SymGetName> SymbolTable;

    /// Symbol table symbols, indexed by name.
    SymbolTable sym_map;

    /// Special symbols, indexed by name.
    SymbolTable special_sym_map;

    /// Sections, indexed by name.
    llvm::StringMap<Section*> section_map;

private:
    /// Pool for symbols not in the symbol table.
    boost::object_pool<Symbol> m_sym_pool;
};
} // namespace yasm

Object::Object(StringRef src_filename, StringRef obj_filename, Arch* arch)
    : m_src_filename(src_filename),
      m_arch(arch),
      m_cur_section(0),
      m_sections_owner(m_sections),
      m_symbols_owner(m_symbols),
      m_impl(new Impl(false))
{
    m_options.DisableGlobalSubRelative = false;
    m_options.PowerOfTwoAlignment = false;
    m_config.ExecStack = false;
    m_config.NoExecStack = false;
}

void
Object::setSourceFilename(StringRef src_filename)
{
    m_src_filename = src_filename;
}

void
Object::setObjectFilename(StringRef obj_filename)
{
    m_obj_filename = obj_filename;
}

Object::~Object()
{
}

void
Object::Finalize(DiagnosticsEngine& diags)
{
    for (section_iterator i=m_sections.begin(), end=m_sections.end();
         i != end; ++i)
        i->Finalize(diags);
}

void
Object::AppendSection(std::auto_ptr<Section> sect)
{
    sect->m_object = this;
    m_impl->section_map[sect->getName()] = sect.get();
    m_sections.push_back(sect.release());
}

Section*
Object::FindSection(StringRef name)
{
    return m_impl->section_map[name];
}

SymbolRef
Object::getAbsoluteSymbol()
{
    SymbolRef sym = getSymbol("");

    // If we already defined it, we're done.
    if (sym->isDefined())
        return sym;

    // Define it
    sym->DefineEqu(Expr(0));
    sym->Use(SourceLocation());
    return sym;
}

SymbolRef
Object::FindSymbol(StringRef name)
{
    return SymbolRef(m_impl->sym_map.Find(name));
}

SymbolRef
Object::getSymbol(StringRef name)
{
    // Don't use pool allocator for symbols in the symbol table.
    // We have to maintain an ordered link list of all symbols in the symbol
    // table, so it's easy enough to reuse that for deleting the symbols.
    // The memory impact of keeping a second linked list (internal to the pool)
    // seems to outweigh the moderate time savings of pool deletion.
    std::auto_ptr<Symbol> sym(new Symbol(name));
    Symbol* sym2 = m_impl->sym_map.Insert(sym.get());
    if (sym2)
    {
        ++num_exist_symbol;
        return SymbolRef(sym2);
    }

    ++num_new_symbol;
    sym2 = sym.get();
    m_symbols.push_back(sym.release());
    return SymbolRef(sym2);
}

SymbolRef
Object::getSymbol(Location loc)
{
    // TODO: try to find a matching named symbol.
    SymbolRef sym = AddNonTableSymbol("$");
    sym->DefineLabel(loc);
    return sym;
}

SymbolRef
Object::AppendSymbol(StringRef name)
{
    Symbol* sym = new Symbol(name);
    m_symbols.push_back(sym);
    return SymbolRef(sym);
}

SymbolRef
Object::AddNonTableSymbol(StringRef name)
{
    Symbol* sym = m_impl->NewSymbol(name);
    return SymbolRef(sym);
}

void
Object::RenameSymbol(SymbolRef sym, StringRef name)
{
    m_impl->sym_map.Remove(sym->getName());
    sym->m_name = name;
    m_impl->sym_map.Insert(sym);
}

void
Object::ExternUndefinedSymbols()
{
    for (symbol_iterator i=m_symbols.begin(), end=m_symbols.end();
         i != end; ++i)
    {
        i->ExternUndefined();
    }
}

void
Object::FinalizeSymbols(DiagnosticsEngine& diags)
{
    bool firstundef = true;

    for (symbol_iterator i=m_symbols.begin(), end=m_symbols.end();
         i != end; ++i)
    {
        if (i->isUndefined())
        {
            // error if a symbol is used but not defined or extern/common
            diags.Report(i->getUseSource(), diag::err_symbol_undefined)
                << i->getName();
            if (firstundef)
            {
                diags.Report(i->getUseSource(),
                             diag::note_symbol_undefined_once);
                firstundef = false;
            }
        }
    }
}

SymbolRef
Object::AddSpecialSymbol(StringRef name)
{
    Symbol* sym = m_impl->NewSymbol(name);
    m_impl->special_sym_map.Insert(sym);
    return SymbolRef(sym);
}

SymbolRef
Object::FindSpecialSymbol(StringRef name)
{
    return SymbolRef(m_impl->special_sym_map.Find(name));
}

#ifdef WITH_XML
pugi::xml_node
Object::Write(pugi::xml_node out) const
{
    pugi::xml_node root = out.append_child("Object");
    append_child(root, "SrcFilename", m_src_filename);
    append_child(root, "ObjFilename", m_obj_filename);

    if (m_arch)
        append_child(root, "Arch", m_arch->getModule().getKeyword());

    if (m_cur_section)
        append_child(root, "CurSection", m_cur_section->getName());

    // sections (and their bytecodes)
    for (const_section_iterator i=m_sections.begin(), end=m_sections.end();
         i != end; ++i)
        append_data(root, *i);

    // symbols
    for (const_symbol_iterator i=m_symbols.begin(), end=m_symbols.end();
         i != end; ++i)
        append_data(root, *i);

    return root;
}
#endif // WITH_XML

void
Object::UpdateBytecodeOffsets(DiagnosticsEngine& diags)
{
    for (section_iterator sect=m_sections.begin(), end=m_sections.end();
         sect != end; ++sect)
        sect->UpdateOffsets(diags);
}

void
Object::Optimize(DiagnosticsEngine& diags)
{
    Optimizer opt(diags);
    unsigned long bc_index = 0;

    // Step 1a
    for (section_iterator sect=m_sections.begin(), sectend=m_sections.end();
         sect != sectend; ++sect)
    {
        unsigned long offset = 0;

        // Set the offset of the first (empty) bytecode.
        sect->bytecodes_front().setIndex(bc_index++);
        sect->bytecodes_front().setOffset(0);

        // Iterate through the remainder, if any.
        for (Section::bc_iterator bc=sect->bytecodes_begin(),
             bcend=sect->bytecodes_end(); bc != bcend; ++bc)
        {
            bc->setIndex(bc_index++);
            bc->setOffset(offset);

            if (bc->CalcLen(TR1::bind(&Optimizer::AddSpan, &opt,
                                      _1, _2, _3, _4, _5),
                            diags))
            {
                if (bc->getSpecial() == Bytecode::Contents::SPECIAL_OFFSET)
                    opt.AddOffsetSetter(*bc);

                offset = bc->getNextOffset();
            }
        }
    }

    if (diags.hasErrorOccurred())
        return;

    // Step 1b
    opt.Step1b();
    if (diags.hasErrorOccurred())
        return;

    // Step 1c
    UpdateBytecodeOffsets(diags);
    if (diags.hasErrorOccurred())
        return;

    // Step 1d
    if (opt.Step1d())
        return;

    // Step 1e
    opt.Step1e();
    if (diags.hasErrorOccurred())
        return;

    // Step 2
    opt.Step2();
    if (diags.hasErrorOccurred())
        return;

    // Step 3
    UpdateBytecodeOffsets(diags);
}


text:
//
// Created by kerin on 2019-02-28.
//

#include "eigen_utils.hpp"
#include "mpi_utils.hpp"

#include "tools/eigen3.3/Dense"
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/filter/gzip.hpp>

#include <iostream>
#include <cmath>
#include <map>
#include <vector>
#include <string>
#include <set>

namespace boost_io = boost::iostreams;

Eigen::MatrixXd EigenUtils::subset_matrix(const Eigen::MatrixXd &orig,
                                          const std::vector<int> &valid_points) {
	long n_cols = orig.cols(), n_rows = valid_points.size();
	Eigen::MatrixXd subset(n_rows, n_cols);

	for(int kk = 0; kk < n_rows; kk++) {
		for(int jj = 0; jj < n_cols; jj++) {
			subset(kk, jj) = orig(valid_points[kk], jj);
		}
	}
	return subset;
}

template <typename EigenMat>
void EigenUtils::write_matrix(boost_io::filtering_ostream& outf,
                              EigenMat& M,
                              std::vector<std::string >& col_names,
                              std::vector<std::string>& row_names){
	if(!col_names.empty()) {
		if (row_names.size() > 0) assert(col_names.size() == M.cols() + 1);
		if (row_names.size() == 0) assert(col_names.size() == M.cols());
		for (int jj = 0; jj < col_names.size(); jj++) {
			outf << col_names[jj];
			if (jj < col_names.size() - 1) {
				outf << " ";
			}
		}
		outf << std::endl;
	}

	if(!row_names.empty()) {
		assert(row_names.size() == M.rows());
		for (long ii = 0; ii < M.rows(); ii++) {
			outf << row_names[ii] << " ";
			for (long jj = 0; jj < M.cols(); jj++) {
				outf << M(ii, jj);
				if (jj < M.cols() - 1) {
					outf << " ";
				}
			}
			outf << std::endl;
		}
	} else {
		outf << M;
	}
}

template <typename EigenMat>
void EigenUtils::read_matrix( const std::string& filename,
                              EigenMat& M){
	std::vector<std::string> placeholder;
	EigenUtils::read_matrix(filename, M, placeholder);
}

template <typename EigenMat>
void EigenUtils::read_matrix(const std::string &filename,
                             EigenMat &M,
                             std::vector <std::string> &col_names){
	std::map<long, bool> incomplete_row;
	EigenUtils::read_matrix(filename, M, col_names, incomplete_row);
}

template <typename EigenMat>
void EigenUtils::read_matrix(const std::string &filename,
                             EigenMat &M,
                             std::vector <std::string> &col_names,
                             std::map<long, bool> &incomplete_row) {
	/* Read txt file into martix. Files can be gzipped. */

	boost_io::filtering_istream fg;
	std::string gz_str = ".gz";
	if (filename.find(gz_str) != std::string::npos) {
		fg.push(boost_io::gzip_decompressor());
	}
	fg.push(boost_io::file_source(filename));
	if (!fg) {
		throw std::runtime_error(filename+" could not be opened.");
	}

	// Read file twice to acertain number of lines
	std::string line;
	int n_rows = 0;
	getline(fg, line);
	while (getline(fg, line)) {
		n_rows++;
	}
	fg.reset();
	if (filename.find(gz_str) != std::string::npos) {
		fg.push(boost_io::gzip_decompressor());
	}
	fg.push(boost_io::file_source(filename));

	// Reading column names
	if (!getline(fg, line)) {
		throw std::runtime_error(filename+" contains zero lines.");
	}
	std::stringstream ss;
	std::string s1;
	int n_cols = 0;
	ss.clear();
	ss.str(line);
	while (ss >> s1) {
		++n_cols;
		col_names.push_back(s1);
	}
	std::cout << "Reading matrix of size " << n_rows << " x " << n_cols << " from " << filename << std::endl;

	// Write remainder of file to Eigen matrix M
	incomplete_row.clear();
	M.resize(n_rows, n_cols);
	int i = 0;
	double tmp_d;
	while (getline(fg, line)) {
		if (i >= n_rows) {
			throw std::runtime_error("ERROR: could not convert txt file (too many lines).");
		}
		ss.clear();
		ss.str(line);
		for (int k = 0; k < n_cols; k++) {
			std::string sss;
			ss >> sss;
			if (sss == "NA" || sss == "NAN" || sss == "NaN" || sss == "nan") {
				tmp_d = 0;
				incomplete_row[i] = true;
			} else {
				try {
					tmp_d = stod(sss);
				} catch (const std::invalid_argument &exc) {
					std::cout << sss << " on line " << i << std::endl;
					throw;
				}
			}
			M(i, k) = tmp_d;
		}
		i++;
	}
}

void EigenUtils::read_matrix_and_skip_cols(const std::string &filename,
                                           const int& n_skip_cols,
                                           Eigen::MatrixXd &M,
                                           std::vector <std::string> &col_names) {
	/* Assumptions:
	   - dimensions unknown
	   - assume no missing values
	 */

	boost_io::filtering_istream fg;
	std::string gz_str = ".gz";
	if (filename.find(gz_str) != std::string::npos) {
		fg.push(boost_io::gzip_decompressor());
	}
	fg.push(boost_io::file_source(filename));
	if (!fg) {
		throw std::runtime_error(filename+" could not be opened.");
	}

	// Read file twice to acertain number of lines
	std::string line;
	int n_rows = 0;
	getline(fg, line);
	while (getline(fg, line)) {
		n_rows++;
	}
	fg.reset();
	if (filename.find(gz_str) != std::string::npos) {
		fg.push(boost_io::gzip_decompressor());
	}
	fg.push(boost_io::file_source(filename));

	// Reading column names
	if (!getline(fg, line)) {
		throw std::runtime_error(filename+" contains zero lines.");
	}
	std::stringstream ss;
	std::string s1;
	int n_cols = 0;
	ss.clear();
	ss.str(line);
	while (ss >> s1) {
		++n_cols;
		col_names.push_back(s1);
	}
	std::cout << " Reading matrix of size " << n_rows << " x " << n_cols << " from " << filename << std::endl;
	assert(n_skip_cols < n_cols);

	// Write remainder of file to Eigen matrix M
	M.resize(n_rows, n_cols - n_skip_cols);
	int i = 0;
	double tmp_d;
	while (getline(fg, line)) {
		if (i >= n_rows) {
			throw std::runtime_error("ERROR: could not convert txt file (too many lines).");
		}
		ss.clear();
		ss.str(line);
		for (int k = 0; k < n_cols; k++) {
			std::string s;
			ss >> s;
			if (k >= n_skip_cols) {
				try {
					tmp_d = stod(s);
				} catch (const std::invalid_argument &exc) {
					std::cout << s << " on line " << i << std::endl;
					throw;
				}
				M(i, k - n_skip_cols) = tmp_d;
			}
		}
		i++;
	}
	if (i < n_rows) {
		throw std::runtime_error("ERROR: could not convert txt file (too few lines).");
	}
}

Eigen::MatrixXf EigenUtils::solve(const Eigen::MatrixXf &A, const Eigen::MatrixXf &b) {
	Eigen::MatrixXf x = A.colPivHouseholderQr().solve(b);
	double check = fabs((double)((A * x - b).norm()/b.norm()));
	if (check > 1e-6) {
		// std::string ms = "ERROR: could not solve covariate scatter matrix (Check = " +
		// std::to_string(check) + ").";
		// throw std::runtime_error(ms);
		std::cout << "WARNING: Error in solving covariate scatter matrix is: " << check << std::endl;
	}
	return x;
}

Eigen::MatrixXd EigenUtils::solve(const Eigen::MatrixXd &A, const Eigen::MatrixXd &b) {
	Eigen::MatrixXd x = A.colPivHouseholderQr().solve(b);
	double check = fabs((double)((A * x - b).norm()/b.norm()));
	if (check > 1e-8) {
		std::string ms = "ERROR: could not solve covariate scatter matrix (Check = " +
		                 std::to_string(check) + ").";
		throw std::runtime_error(ms);
	}
	return x;
}

template <typename EigenMat>
void EigenUtils::scale_matrix_and_remove_constant_cols(EigenMat &M,
                                                       long &n_cols,
                                                       std::vector<std::string> &col_names){
	// Scale eigen matrix passed by reference.
	// Removes columns with zero variance + updates col_names.
	// Only call on matrixes which have been reduced to complete cases,
	// as no check for incomplete rows.
	double Nlocal = M.rows();
	double Nglobal = mpiUtils::mpiReduce_inplace(&Nlocal);

	std::vector<std::size_t> keep;
	std::vector<std::string> keep_names;
	std::vector<std::string> reject_names;
	for (std::size_t k = 0; k < n_cols; k++) {
		double sum_mik2 = M.col(k).array().square().sum();
		sum_mik2 = mpiUtils::mpiReduce_inplace(&sum_mik2);
//		double sigma = 0.0;
//		double count = 0;
//		for (int i = 0; i < n_rows; i++) {
//			double val = M(i, k);
//			sigma += val * val;
//			count += 1;
//		}
		double sigma = std::sqrt(sum_mik2 / (Nglobal - 1));

//		sigma = sqrt(sigma/(count - 1));
		if (sigma > 1e-12) {
			M.col(k).array() /= sigma;
//			for (int i = 0; i < n_rows; i++) {
//				M(i, k) /= sigma;
//			}
			keep.push_back(k);
			keep_names.push_back(col_names[k]);
		} else {
			reject_names.push_back(col_names[k]);
		}
	}

	if (keep.size() != n_cols) {
		std::cout << " Removing " << (n_cols - keep.size())  << " column(s) with zero variance:" << std::endl;
		for(auto name : reject_names) {
			std::cout << name << std::endl;
		}
		// subset cols
		for (std::size_t i = 0; i < keep.size(); i++) {
			M.col(i) = M.col(keep[i]);
		}
		M.conservativeResize(M.rows(), keep.size());

		n_cols = keep.size();
		col_names = keep_names;
	}

	if (n_cols == 0) {
		throw std::runtime_error("ERROR: No columns left with nonzero variance after scale_matrix()");
	}
}

template <typename EigenMat>
void EigenUtils::center_matrix(EigenMat& M){
	// Center eigen matrix passed by reference.
	// Only call on matrixes which have been reduced to complete cases,
	// as no check for incomplete rows.
	long n_cols = M.cols();
	long n_rows = M.rows();
	double Nlocal = M.rows();
	double Nglobal = mpiUtils::mpiReduce_inplace(&Nlocal);

	for (int k = 0; k < n_cols; k++) {
		double sum_mik = 0.0;
		for (int i = 0; i < n_rows; i++) {
			sum_mik += M(i, k);
		}

		sum_mik = mpiUtils::mpiReduce_inplace(&sum_mik);
		double mu = sum_mik / Nglobal;
		for (int i = 0; i < n_rows; i++) {
			M(i, k) -= mu;
		}
	}
}

Eigen::MatrixXd EigenUtils::project_out_covars(Eigen::Ref<Eigen::MatrixXd> rhs, const Eigen::Ref<const Eigen::MatrixXd> &C,
                                               const Eigen::Ref<const Eigen::MatrixXd> &CtC_inv) {
	assert(CtC_inv.cols() == C.cols());
	assert(CtC_inv.rows() == C.cols());
	assert(C.rows() == rhs.rows());
	Eigen::MatrixXd CtRHS = C.transpose() * rhs;
	CtRHS = mpiUtils::mpiReduce_inplace(CtRHS);
	Eigen::MatrixXd beta = CtC_inv * CtRHS;
	Eigen::MatrixXd yhat = C * beta;
	Eigen::MatrixXd res = rhs - yhat;
	return res;
}

// Explicit instantiation
// https://stackoverflow.com/questions/2152002/how-do-i-force-a-particular-instance-of-a-c-template-to-instantiate

template void EigenUtils::read_matrix(const std::string&,
                                      Eigen::MatrixXf&, std::vector<std::string>&, std::map<long, bool>&);
template void EigenUtils::read_matrix(const std::string&,
                                      Eigen::MatrixXd&, std::vector<std::string>&, std::map<long, bool>&);
template void EigenUtils::read_matrix(const std::string&,
                                      Eigen::MatrixXf&, std::vector<std::string>&);
template void EigenUtils::read_matrix(const std::string&,
                                      Eigen::MatrixXd&, std::vector<std::string>&);
template void EigenUtils::read_matrix(const std::string&, Eigen::MatrixXf&);
template void EigenUtils::read_matrix(const std::string&, Eigen::MatrixXd&);
template void EigenUtils::write_matrix(boost_io::filtering_ostream&,
                                       Eigen::VectorXd&,
                                       std::vector<std::string>&,
                                       std::vector<std::string>&);
template void EigenUtils::write_matrix(boost_io::filtering_ostream&,
                                       Eigen::MatrixXd&,
                                       std::vector<std::string>&,
                                       std::vector<std::string>&);
template void EigenUtils::center_matrix(Eigen::MatrixXd&);
template void EigenUtils::center_matrix(Eigen::MatrixXf&);
template void EigenUtils::center_matrix(Eigen::VectorXd&);
template void EigenUtils::center_matrix(Eigen::VectorXf&);
template void EigenUtils::scale_matrix_and_remove_constant_cols(Eigen::MatrixXf&,
                                                                long&, std::vector<std::string>&);
template void EigenUtils::scale_matrix_and_remove_constant_cols(Eigen::MatrixXd&,
                                                                long&, std::vector<std::string>&);
template void EigenUtils::scale_matrix_and_remove_constant_cols(Eigen::VectorXd&,
                                                                long&, std::vector<std::string>&);

max_stars_repo_name: mkerin/LEMMA

max_issues_repo_name: lfelipe-ferrao/LEMMA

max_forks_repo_name: lfelipe-ferrao/LEMMA


text:
// This file is part of CaptureTheBanana++.
//
// Copyright (c) 2018 the CaptureTheBanana++ contributors (see CONTRIBUTORS.md)
// This file is licensed under the MIT license; see LICENSE file in the root of this
// project for details.

#include <iostream>
#include <stdexcept>

#include <boost/filesystem.hpp>

#include "engine/Engine.hpp"
#include "engine/gui/Label.hpp"
#include "engine/input/InputManager.hpp"
#include "engine/input/Keyboard.hpp"
#include "engine/menu/CreditsMenu.hpp"
#include "engine/menu/HighscoreMenu.hpp"
#include "engine/menu/StartMenu.hpp"
#include "engine/util/Color.hpp"
#include "engine/util/Vector2d.hpp"

namespace ctb {
namespace engine {

StartMenu::StartMenu(parser::GameConfig* config)
    : m_gameconfig(config),
      m_lastRenderTicks(0),
      m_selected(0),
      m_startEnabled(true),
      m_freePlayersUsed(true) {
    setFPS(4);  // blick with 4 fps
    setupPlayers();
    setupUI();
}

void StartMenu::setupPlayers() {
    uint32_t max_players = static_cast<uint32_t>(m_gameconfig->getPlayers().size());
    Player* player = nullptr;
    parser::PlayerConfig* config;

    // Create all players.
    for (uint32_t i = 0; i < max_players; i++) {
        // get the config
        config = m_gameconfig->getPlayers()[i];

        player =
            new Player(Team::R2L, Window::getWindow().loadTexture(config->getName()),
                       config->getFrameWidth(), config->getFrameHeight(), config->getNumFrames());
        player->setFPS(14);

        m_playersUnused.push_back(player);
    }
}

void StartMenu::registerInputs(const std::vector<Input*> inputs) {
    // call base function
    Menu::registerInputs(inputs);

    // Check, if not too much inputs are there.
    uint64_t maxPlayers = m_gameconfig->getPlayers().size();
    if (inputs.size() > maxPlayers) {
        throw std::runtime_error("Too Many Inputs!");
    }

    // Map all teams to the given inputs
    Team team = Team::R2L;
    for (Input* i : inputs) {
        // get player and save it to m_playersUsed
        Player* player = m_playersUnused.back();
        m_playersUnused.pop_back();
        m_playersUsed.push_back(player);

        // register input
        player->registerInput(i);
        player->setTeam(team);

        // toggle teams
        if (team == Team::R2L) {
            team = Team::L2R;
        } else {
            team = Team::R2L;
        }
    }

    // Update divider height
    updateDividerHeight();
    updateStartEntry();
}

void StartMenu::updateDividerHeight() {
    int height = static_cast<int>(m_playersUsed.size()) * 60 + 100;
    m_divider->setH(height);
}

void StartMenu::setupUI() {
    int w = Window::getWindow().w();
    int h = Window::getWindow().h();

    // one tenths of padding here.
    int menuX = w / 10;
    int menuY = h / 10;

    // create all labels
    m_lblHeader = new Label("std_12px", "CaptureTheBanana++", Vector2dT(menuX, menuY), 2);
    m_lblHeader->setColor(Color(255, 0, 255));

    m_lblStart = new Label("std_12px", "Start", Vector2dT(menuX, menuY += 75), 2);
    m_menuLabels.emplace_back(m_lblStart, StartMenuAction::Start);

    m_menuLabels.emplace_back(new Label("std_12px", "Highscores", Vector2dT(menuX, menuY += 30), 2),
                              StartMenuAction::Highscores);
    // Just add the enable/disable keyboard only, if there are other controls and not too much.
    uint64_t maxPlayers = m_gameconfig->getPlayers().size();
    uint64_t inputs = Window::getInputManager().getInputs().size();
    if (inputs > 1 && inputs < maxPlayers) {
        std::string kb;
        if (Window::getInputManager().hasKeyboard()) {
            kb = "Disable keyboard";
        } else {
            kb = "Enable keyboard";
        }
        m_lblKeyboard = new Label("std_12px", kb, Vector2dT(menuX, menuY += 30), 2);
        m_menuLabels.emplace_back(m_lblKeyboard, StartMenuAction::Keyboard);
    } else {
        m_lblKeyboard = nullptr;
    }
    m_menuLabels.emplace_back(new Label("std_12px", "Edit game", Vector2dT(menuX, menuY += 30), 2),
                              StartMenuAction::EditGame);
    m_menuLabels.emplace_back(new Label("std_12px", "Credits", Vector2dT(menuX, menuY += 30), 2),
                              StartMenuAction::Credits);
    m_menuLabels.emplace_back(new Label("std_12px", "Quit", Vector2dT(menuX, menuY += 30), 2),
                              StartMenuAction::Quit);

    // --team1 (200px)--|--team2 (200px)-- <- menuX ->|
    // the divider is 5 px wide.
    menuY = h / 10;
    int teamX = w - menuX - 405;
    m_lblTeamR2L = new Label("std_12px", "L2R", Vector2dT(teamX + 100, menuY), 2);
    m_lblTeamR2L->setAlignment(LabelAlignment::Center);
    m_lblTeamL2R = new Label("std_12px", "R2L", Vector2dT(teamX + 305, menuY), 2);
    m_lblTeamL2R->setAlignment(LabelAlignment::Center);

    // Add divider. The right hight is set later
    SDL_Rect r = {teamX + 200, menuY - 25, 5, 200};
    m_divider = new Rect(r);
}

void StartMenu::updateBlink() {
    Uint32 ticks = SDL_GetTicks();
    float time = static_cast<float>(ticks - m_lastRenderTicks);

    // Check, if we have reached an update
    if (time > static_cast<float>(m_frameTimeout)) {
        m_menuLabels[m_selected].first->toggleShow();

        // Save current tick count
        m_lastRenderTicks = ticks;
    }
}

// Set the blink speed to the selected entry.
void StartMenu::setFPS(const int fps) {
    m_frameTimeout = static_cast<Uint32>(1000.0 / fps);
}

void StartMenu::render() {
    // render every label and the players
    renderBackground();
    updateBlink();

    m_divider->render();

    m_lblHeader->render();
    for (auto& lbl : m_menuLabels) {
        lbl.first->render();
    }
    m_lblTeamR2L->render();
    m_lblTeamL2R->render();

    renderPlayers();
}

void StartMenu::renderPlayers() {
    int w = Window::getWindow().w();
    int h = Window::getWindow().h();

    int xBase = (w * 9) / 10 - 405;
    int y = h / 10 + 50;
    // iterate over all players
    for (auto& player : m_playersUsed) {
        if (player->getTeam() == Team::R2L) {
            Vector2dT p(xBase + 305 - 24, y);
            player->renderStatic(p);
        } else {
            Vector2dT p(xBase + 100 - 24, y);
            player->renderStatic(p);
        }
        y += 60;
    }
}

void StartMenu::handleInput(InputType type, const Input* input, bool state, float /*angle*/) {
    // Just listen to key presses
    if (!state) {
        return;
    }

    switch (type) {
        case InputType::INPUT_SELECT:
            select();
            break;

        case InputType::INPUT_UP:
            // Special case: Do not go to 0 (start) if it is disabled
            if (m_selected > 1 || (m_startEnabled && m_selected > 0)) {
                m_menuLabels[m_selected].first->setShow(true);
                m_selected--;
            }
            break;

        case InputType::INPUT_DOWN:
            if (m_selected < m_menuLabels.size() - 1) {
                m_menuLabels[m_selected].first->setShow(true);
                m_selected++;
            }
            break;

        case InputType::INPUT_TEAM_1:  // join L2R
            // find the right player
            for (auto& player : m_playersUsed) {
                if (player->getInput() == input && player->getTeam() == Team::R2L) {
                    // found!
                    player->setTeam(Team::L2R);
                }
            }
            updateStartEntry();
            break;

        case InputType::INPUT_TEAM_2:  // join R2L
            // find the right player
            for (auto& player : m_playersUsed) {
                if (player->getInput() == input && player->getTeam() == Team::L2R) {
                    // found!
                    player->setTeam(Team::R2L);
                }
            }
            updateStartEntry();
            break;

        default:
            break;
    }
}

void StartMenu::select() {
    // Which entry is selected?
    switch (m_menuLabels[m_selected].second) {
        case StartMenuAction::Start:
            m_freePlayersUsed = false;
            Window::getEngine().getGame()->startGame(m_playersUsed);
            Window::getWindow().closeCurrentMenu();
            break;

        case StartMenuAction::Highscores: {
            HighscoreMenu* menu = new HighscoreMenu();
            Window::getWindow().addMenu(menu);
        } break;

        case StartMenuAction::Keyboard:
            if (m_lblKeyboard) {
                toggleKeyboard();
            }
            break;

        case StartMenuAction::EditGame: {
            Window::getWindow().quit();

            std::string editorPath{};
            std::vector<std::string> paths = {"ctb-editor" /*release*/,
                                              "../editor/ctb-editor" /*build*/};

            // try find the editor executable
            bool found = false;
            for (auto& item : paths) {
                if (boost::filesystem::exists(item)) {
                    editorPath = boost::filesystem::canonical(item).string();
                    found = true;
                    break;
                }
            }

            if (found) {
                boost::filesystem::path absoluteGameXml =
                    boost::filesystem::canonical(Window::getEngine().getGameFile());

                // execute it!
                execl(editorPath.c_str(), "ctb-editor", absoluteGameXml.string().c_str(), nullptr);
                throw std::runtime_error("Editor could not be started! (Editor path: " +
                                         editorPath);
            }
            break;
        }
        case StartMenuAction::Credits:
            Window::getWindow().addMenu(new CreditsMenu());
            break;

        case StartMenuAction::Quit:
            Window::getWindow().quit();
            break;
    }
}

void StartMenu::updateStartEntry() {
    // is a team empty?
    bool r2l_empty = true;
    bool l2r_empty = true;

    // check each player.
    for (auto& player : m_playersUsed) {
        if (player->getTeam() == Team::R2L) {
            r2l_empty = false;
        } else {
            l2r_empty = false;
        }
    }

    // One team is empty, so disable start.
    // But only, if the -d argument was not given...
    if ((r2l_empty || l2r_empty) && !Window::isDebug()) {
        Color c(128, 128, 128);
        m_lblStart->setColor(c);
        m_lblStart->setShow(true);
        m_startEnabled = false;
        if (m_selected == 0) {
            m_selected = 1;
        }
    } else {
        Color c(255, 255, 255);
        m_lblStart->setColor(c);
        m_lblStart->setShow(true);
        m_startEnabled = true;
    }
}

void StartMenu::toggleKeyboard() {
    if (Window::getInputManager().hasKeyboard()) {
        // remove the keyboard
        Keyboard* k = Window::getInputManager().getKeyboard();

        // Remove from player from used players
        auto it = std::find_if(m_playersUsed.begin(), m_playersUsed.end(),
                               [&k](Player* player) { return player->getInput() == k; });

        if (it != m_playersUsed.end()) {
            (*it)->deregisterInput();
            m_playersUnused.push_back(*it);
            m_playersUsed.erase(it);
        }

        // Deregister and remove inputhandler
        k->deregister_handler(m_inputHandlerIds[k]);
        m_inputHandlerIds.erase(k);

        // Finally delete the keyboard.
        Window::getInputManager().removeKeyboard();
        m_lblKeyboard->setText("Enable keyboard");
    } else {  // Add it.
        Window::getInputManager().addKeyboard();
        Keyboard* k = Window::getInputManager().getKeyboard();

        // Register the keyboard input
        registerInput(k);

        // use player
        Player* player = m_playersUnused.back();
        m_playersUnused.pop_back();
        player->setTeam(Team::L2R);
        player->registerInput(k);
        m_playersUsed.push_back(player);

        m_lblKeyboard->setText("Disable keyboard");
    }
    updateDividerHeight();
    updateStartEntry();
}

StartMenu::~StartMenu() {
    delete m_lblHeader;
    for (auto& lbl : m_menuLabels) {
        delete lbl.first;
    }
    delete m_lblTeamR2L;
    delete m_lblTeamL2R;

    delete m_divider;

    // Delete unused players
    for (auto& player : m_playersUnused) {
        delete player;
    }

    if (m_freePlayersUsed) {
        for (auto& player : m_playersUsed) {
            delete player;
        }
    }
}

}  // namespace engine
}  // namespace ctb

max_stars_repo_name: CaptureTheBanana/CaptureTheBanana

max_issues_repo_name: CaptureTheBanana/CaptureTheBanana

max_forks_repo_name: CaptureTheBanana/CaptureTheBanana


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

#include <boost/foreach.hpp>
#include <boost/unordered_set.hpp>
#include <boost/algorithm/string.hpp>

#include "luxcore/luxcorelogger.h"
#include "luxcore/luxcore.h"
#include "luxcore/luxcoreimpl.h"

using namespace std;
using namespace luxrays;
using namespace luxcore;
using namespace luxcore::detail;

//------------------------------------------------------------------------------
// KernelCacheFill
//------------------------------------------------------------------------------

#if !defined(LUXRAYS_DISABLE_OPENCL)

static void CreateBox(Scene *scene, const string &objName, const string &meshName,
		const string &matName, const bool enableUV, const BBox &bbox) {
	Point *p = (Point *)Scene::AllocVerticesBuffer(24);
	// Bottom face
	p[0] = Point(bbox.pMin.x, bbox.pMin.y, bbox.pMin.z);
	p[1] = Point(bbox.pMin.x, bbox.pMax.y, bbox.pMin.z);
	p[2] = Point(bbox.pMax.x, bbox.pMax.y, bbox.pMin.z);
	p[3] = Point(bbox.pMax.x, bbox.pMin.y, bbox.pMin.z);
	// Top face
	p[4] = Point(bbox.pMin.x, bbox.pMin.y, bbox.pMax.z);
	p[5] = Point(bbox.pMax.x, bbox.pMin.y, bbox.pMax.z);
	p[6] = Point(bbox.pMax.x, bbox.pMax.y, bbox.pMax.z);
	p[7] = Point(bbox.pMin.x, bbox.pMax.y, bbox.pMax.z);
	// Side left
	p[8] = Point(bbox.pMin.x, bbox.pMin.y, bbox.pMin.z);
	p[9] = Point(bbox.pMin.x, bbox.pMin.y, bbox.pMax.z);
	p[10] = Point(bbox.pMin.x, bbox.pMax.y, bbox.pMax.z);
	p[11] = Point(bbox.pMin.x, bbox.pMax.y, bbox.pMin.z);
	// Side right
	p[12] = Point(bbox.pMax.x, bbox.pMin.y, bbox.pMin.z);
	p[13] = Point(bbox.pMax.x, bbox.pMax.y, bbox.pMin.z);
	p[14] = Point(bbox.pMax.x, bbox.pMax.y, bbox.pMax.z);
	p[15] = Point(bbox.pMax.x, bbox.pMin.y, bbox.pMax.z);
	// Side back
	p[16] = Point(bbox.pMin.x, bbox.pMin.y, bbox.pMin.z);
	p[17] = Point(bbox.pMax.x, bbox.pMin.y, bbox.pMin.z);
	p[18] = Point(bbox.pMax.x, bbox.pMin.y, bbox.pMax.z);
	p[19] = Point(bbox.pMin.x, bbox.pMin.y, bbox.pMax.z);
	// Side front
	p[20] = Point(bbox.pMin.x, bbox.pMax.y, bbox.pMin.z);
	p[21] = Point(bbox.pMin.x, bbox.pMax.y, bbox.pMax.z);
	p[22] = Point(bbox.pMax.x, bbox.pMax.y, bbox.pMax.z);
	p[23] = Point(bbox.pMax.x, bbox.pMax.y, bbox.pMin.z);

	Triangle *vi = (Triangle *)Scene::AllocTrianglesBuffer(12);
	// Bottom face
	vi[0] = Triangle(0, 1, 2);
	vi[1] = Triangle(2, 3, 0);
	// Top face
	vi[2] = Triangle(4, 5, 6);
	vi[3] = Triangle(6, 7, 4);
	// Side left
	vi[4] = Triangle(8, 9, 10);
	vi[5] = Triangle(10, 11, 8);
	// Side right
	vi[6] = Triangle(12, 13, 14);
	vi[7] = Triangle(14, 15, 12);
	// Side back
	vi[8] = Triangle(16, 17, 18);
	vi[9] = Triangle(18, 19, 16);
	// Side back
	vi[10] = Triangle(20, 21, 22);
	vi[11] = Triangle(22, 23, 20);

	// Define the Mesh
	if (!enableUV) {
		// Define the object
		scene->DefineMesh(meshName, 24, 12, (float *)p, (unsigned int *)vi, NULL, NULL, NULL, NULL);
	} else {
		UV *uv = new UV[24];
		// Bottom face
		uv[0] = UV(0.f, 0.f);
		uv[1] = UV(1.f, 0.f);
		uv[2] = UV(1.f, 1.f);
		uv[3] = UV(0.f, 1.f);
		// Top face
		uv[4] = UV(0.f, 0.f);
		uv[5] = UV(1.f, 0.f);
		uv[6] = UV(1.f, 1.f);
		uv[7] = UV(0.f, 1.f);
		// Side left
		uv[8] = UV(0.f, 0.f);
		uv[9] = UV(1.f, 0.f);
		uv[10] = UV(1.f, 1.f);
		uv[11] = UV(0.f, 1.f);
		// Side right
		uv[12] = UV(0.f, 0.f);
		uv[13] = UV(1.f, 0.f);
		uv[14] = UV(1.f, 1.f);
		uv[15] = UV(0.f, 1.f);
		// Side back
		uv[16] = UV(0.f, 0.f);
		uv[17] = UV(1.f, 0.f);
		uv[18] = UV(1.f, 1.f);
		uv[19] = UV(0.f, 1.f);
		// Side front
		uv[20] = UV(0.f, 0.f);
		uv[21] = UV(1.f, 0.f);
		uv[22] = UV(1.f, 1.f);
		uv[23] = UV(0.f, 1.f);

		// Define the object
		scene->DefineMesh(meshName, 24, 12, (float *)p, (unsigned int *)vi, NULL, (float *)uv, NULL, NULL);
	}

	// Add the object to the scene
	Properties props;
	props.SetFromString(
		"scene.objects." + objName + ".shape = " + meshName + "\n"
		"scene.objects." + objName + ".material = " + matName + "\n"
		);
	scene->Parse(props);
}

static void RenderTestScene(const Properties &cfgSetUpProps, const Properties &scnSetUpProps) {
	LC_LOG("Creating kernel cache entry with configuration properties:");
	LC_LOG(cfgSetUpProps);
	LC_LOG("And scene properties:");
	LC_LOG(scnSetUpProps);

	// Build the scene to render
	Scene *scene = Scene::Create();

	Properties scnProps = scnSetUpProps;

	scnProps <<
			Property("scene.camera.lookat.orig")(1.f , 6.f , 3.f) <<
			Property("scene.camera.lookat.target")(0.f , 0.f , .5f) <<
			Property("scene.camera.fieldofview")(60.f);

	// Define image maps
	const u_int size = 256;
	vector<u_char> img(size * size * 3);
	u_char *ptr = &img[0];
	for (u_int y = 0; y < size; ++y) {
		for (u_int x = 0; x < size; ++x) {
			if ((x % 64 < 32) ^ (y % 64 < 32)) {
				*ptr++ = 255;
				*ptr++ = 0;
				*ptr++ = 0;
			} else {
				*ptr++ = 255;
				*ptr++ = 255;
				*ptr++ = 0;
			}
		}
	}

	scene->DefineImageMap<u_char>("image.png", &img[0], 1.f, 3, size, size, Scene::DEFAULT);

	// Define light sources
	const Property lightSetUpProp = scnSetUpProps.Get(Property("kernelcachefill.light.types")("infinite"));
	bool hasTriangleLight = false;
	for (u_int i = 0; i < lightSetUpProp.GetSize(); ++i) {
		const string lightType = lightSetUpProp.Get<string>(i);
		if (lightType == "trianglelight") {
			hasTriangleLight = true;
			continue;
		}

		scnProps << Property("scene.lights." + lightType + "_light.type")(lightType);
		if (lightType == "mappoint")
			scnProps << Property("scene.lights." + lightType + "_light.mapfile")("image.png");
	}

	// Parse the scene definition properties
	scene->Parse(scnProps);

	const string geometrySetUp = cfgSetUpProps.Get(Property("kernelcachefill.geometry.type")("test")).Get<string>();
	if (geometrySetUp == "test") {
		// Define materials and meshes
		if (hasTriangleLight) {
			Properties props;
			props <<
				Property("scene.materials.triangle_light.type")("matte") <<
				Property("scene.materials.triangle_light.emission")(1000000.f, 1000000.f, 1000000.f);
			scene->Parse(props);

			CreateBox(scene, "box_triangle_light", "mesh_box_triangle_light", "triangle_light", false, BBox(Point(-1.75f, 1.5f, .75f), Point(-1.5f, 1.75f, .5f)));
		}

		// One box for each material
		const Property materialSetUpProp = scnSetUpProps.Get(Property("kernelcachefill.material.types")("matte"));
		for (u_int i = 0; i < materialSetUpProp.GetSize(); ++i) {
			const string materialType = materialSetUpProp.Get<string>(i);

			Properties props;
			props << Property("scene.materials." + materialType + "_mat.type")(materialType);
			scene->Parse(props);

			CreateBox(scene, "mbox_" + materialType, "mesh_mbox_" + materialType, materialType + "_mat", false, BBox(Point(-1.75f, 1.5f, .75f + i), Point(-1.5f, 1.75f, .5f + i)));
		}

		// One box for each texture
		const Property textureSetUpProp = scnSetUpProps.Get(Property("kernelcachefill.texture.types")("constfloat3"));
		for (u_int i = 0; i < textureSetUpProp.GetSize(); ++i) {
			const string textureType = textureSetUpProp.Get<string>(i);

			Properties props;
			props <<
					Property("scene.textures." + textureType + "_tex.type")(textureType) <<
					Property("scene.materials." + textureType + "_tmat.type")("matte") <<
					Property("scene.materials." + textureType + "_tmat.kd")(textureType + "_tex");
			scene->Parse(props);

			CreateBox(scene, "tbox_" + textureType, "mesh_tbox_" + textureType, textureType + "_tmat", false, BBox(Point(-1.75f, 2.5f, .75f + i), Point(-1.5f, 2.75f, .5f + i)));
		}
	} else {
		if (hasTriangleLight && (lightSetUpProp.GetSize() == 1)) {
			// I can not render an empty scene with only area light sources
			return;
		}

		scene->Parse(scnProps);
	}

	// Do the render

	Properties cfgProps = cfgSetUpProps;
	cfgProps <<
			Property("film.outputs.1.type")("RGB_IMAGEPIPELINE") <<
			Property("film.outputs.1.filename")("image.png");

	RenderConfig *config = RenderConfig::Create(cfgProps, scene);
	RenderSession *session = RenderSession::Create(config);

	// Start the rendering
	session->Start();

	session->UpdateStats();

	// Save the rendered image
	//session->GetFilm().SaveOutputs();

	// Stop the rendering
	session->Stop();

	delete session;
	delete config;
	delete scene;

	LC_LOG("Done.");
}

static void KernelCacheFillImpl(const Properties &config, void (*ProgressHandler)(const size_t, const size_t)) {
	// Extract the render engines
	const Property renderEngines = config.Get(Property("kernelcachefill.renderengine.types")("PATHOCL", "TILEPATHOCL", "RTPATHOCL"));
	const size_t count = renderEngines.GetSize();

	// For each render engine type
	for (u_int renderEngineIndex = 0; renderEngineIndex < renderEngines.GetSize(); ++renderEngineIndex) {
		const string renderEngineType = renderEngines.Get<string>(renderEngineIndex);
		string samplerType;
		if ((renderEngineType == "TILEPATHOCL") || (renderEngineType == "RTPATHOCL"))
			samplerType = "TILEPATHSAMPLER";
		else
			samplerType = "SOBOL";

		Properties cfgProps;
		cfgProps <<
				Property("renderengine.type")(renderEngineType) <<
				Property("sampler.type")(samplerType) <<
				config.Get(Property("scene.epsilon.min")(DEFAULT_EPSILON_MIN)) <<
				config.Get(Property("scene.epsilon.max")(DEFAULT_EPSILON_MAX));

		if (config.IsDefined("opencl.devices.select"))
			cfgProps << config.Get("opencl.devices.select");

		// Run the rendering
		LC_LOG("====================================================================");
		if (ProgressHandler)
			ProgressHandler(renderEngineIndex, count);
		LC_LOG("Step: " << renderEngineIndex << "/" << count);
		RenderTestScene(cfgProps, Properties());
	}

	LC_LOG("====================================================================");
}

#endif

void luxcore::KernelCacheFill(const Properties &config, void (*ProgressHandler)(const size_t, const size_t)) {
	API_BEGIN("{}, {}", ToArgString(config),(void *)ProgressHandler);

#if !defined(LUXRAYS_DISABLE_OPENCL)
	KernelCacheFillImpl(config, ProgressHandler);
#endif

	API_END();
}

max_stars_repo_name: julescmay/LuxCore

max_issues_repo_name: julescmay/LuxCore

max_forks_repo_name: julescmay/LuxCore


text:
/*
 ___ ___ __     __ ____________
|   |   |  |   |__|__|__   ___/  Ubiquitout Internet @ IIT-CNR
|   |   |  |  /__/  /  /  /      C++ support library
|   |   |  |/__/  /   /  /       https://github.com/ccicconetti/support/
|_______|__|__/__/   /__/

Licensed under the MIT License <http://opensource.org/licenses/MIT>.
Copyright (c) 2019 Claudio Cicconetti https://ccicconetti.github.io/

Permission is hereby  granted, free of charge, to any  person obtaining a copy
of this software and associated  documentation files (the "Software"), to deal
in the Software  without restriction, including without  limitation the rights
to  use, copy,  modify, merge,  publish, distribute,  sublicense, and/or  sell
copies  of  the Software,  and  to  permit persons  to  whom  the Software  is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE  IS PROVIDED "AS  IS", WITHOUT WARRANTY  OF ANY KIND,  EXPRESS OR
IMPLIED,  INCLUDING BUT  NOT  LIMITED TO  THE  WARRANTIES OF  MERCHANTABILITY,
FITNESS FOR  A PARTICULAR PURPOSE AND  NONINFRINGEMENT. IN NO EVENT  SHALL THE
AUTHORS  OR COPYRIGHT  HOLDERS  BE  LIABLE FOR  ANY  CLAIM,  DAMAGES OR  OTHER
LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE  OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include "stat.h"

#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/max.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/min.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/variance.hpp>

namespace bacc = boost::accumulators;

namespace uiiit {
namespace support {

class Accumulator final
{
 public:
  Accumulator()
      : theObj() {
  }

  ~Accumulator() {}

  boost::accumulators::accumulator_set<
      SummaryStat::Real,
      boost::accumulators::stats<boost::accumulators::tag::mean,
                                 boost::accumulators::tag::variance,
                                 boost::accumulators::tag::min,
                                 boost::accumulators::tag::max>>
      theObj;
};

SummaryStat::SummaryStat()
    : theAcc(new Accumulator()) {
}

SummaryStat::~SummaryStat() {
}

void SummaryStat::operator()(const Real aValue) {
  theAcc->theObj(aValue);
}

void SummaryStat::reset() {
  theAcc = std::make_unique<Accumulator>();
}

SummaryStat::Real SummaryStat::mean() const {
  return bacc::mean(theAcc->theObj);
}

SummaryStat::Real SummaryStat::min() const {
  return bacc::min(theAcc->theObj);
}

SummaryStat::Real SummaryStat::max() const {
  return bacc::max(theAcc->theObj);
}

bool SummaryStat::empty() const {
  return bacc::count(theAcc->theObj) == 0;
}

size_t SummaryStat::count() const {
  return bacc::count(theAcc->theObj);
}

SummaryStat::Real SummaryStat::stddev() const {
  return sqrt(bacc::variance(theAcc->theObj));
}

} // namespace support
} // namespace uiiit

max_stars_repo_name: ccicconetti/support

max_issues_repo_name: ccicconetti/support

max_forks_repo_name: ccicconetti/support


text: #include <boost/spirit/home/karma/operator/kleene.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino