<commit_before>// The MIT License (MIT)

// Copyright (c) 2013-2015 Danny Y., Rapptz

// 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.

#ifndef SOL_STATE_HPP
#define SOL_STATE_HPP

#include "error.hpp"
#include "table.hpp"
#include <memory>

namespace sol {
namespace detail {
inline int atpanic(lua_State* L) {
    const char* message = lua_tostring(L, -1);
    std::string err = message ? message : "An unexpected error occured and forced the lua state to call atpanic";
    throw error(err);
}
} // detail

enum class lib : char {
    base,
    package,
    coroutine,
    string,
    os,
    math,
    table,
    debug,
    bit32,
    io,
    count
};

class state {
private:
    std::unique_ptr<lua_State, void(*)(lua_State*)> L;
    table reg;
    table global;
public:
    state():
    L(luaL_newstate(), lua_close),
    reg(L.get(), LUA_REGISTRYINDEX),
#if SOL_LUA_VERSION < 503
    // Global table is just a special index
    global(L.get(), LUA_GLOBALSINDEX) {
#else
    // Global tables are stored in the environment/registry table
    global(reg.get<table>(LUA_RIDX_GLOBALS)) {
#endif // Lua 5.2
        lua_atpanic(L.get(), detail::atpanic);
    }

    lua_State* lua_state() const {
        return L.get();
    }

    template<typename... Args>
    void open_libraries(Args&&... args) {
        static_assert(are_same<lib, Args...>::value, "all types must be libraries");
        if(sizeof...(args) == 0) {
            luaL_openlibs(L.get());
            return;
        }

        lib libraries[1 + sizeof...(args)] = { lib::count, std::forward<Args>(args)... };

        for(auto&& library : libraries) {
            switch(library) {
#if SOL_LUA_VERSION <= 501 && defined(SOL_LUAJIT)
            case lib::coroutine:
#endif // luajit opens coroutine base stuff
            case lib::base:
                luaL_requiref(L.get(), "base", luaopen_base, 1);
                lua_pop(L.get(), 1);
                break;
            case lib::package:
                luaL_requiref(L.get(), "package", luaopen_package, 1);
                lua_pop(L.get(), 1);
                break;
#if SOL_LUA_VERSION > 501
            case lib::coroutine:
                luaL_requiref(L.get(), "coroutine", luaopen_coroutine, 1);
                lua_pop(L.get(), 1);
                break;
#endif // Lua 5.2+ only
            case lib::string:
                luaL_requiref(L.get(), "string", luaopen_string, 1);
                lua_pop(L.get(), 1);
                break;
            case lib::table:
                luaL_requiref(L.get(), "table", luaopen_table, 1);
                lua_pop(L.get(), 1);
                break;
            case lib::math:
                luaL_requiref(L.get(), "math", luaopen_math, 1);
                lua_pop(L.get(), 1);
                break;
            case lib::bit32:
#if SOL_LUA_VERSION > 510
                luaL_requiref(L.get(), "bit32", luaopen_bit32, 1);
                lua_pop(L.get(), 1);
#else
#endif // Lua 5.2+ only
                break;
            case lib::io:
                luaL_requiref(L.get(), "io", luaopen_io, 1);
                lua_pop(L.get(), 1);
                break;
            case lib::os:
                luaL_requiref(L.get(), "os", luaopen_os, 1);
                lua_pop(L.get(), 1);
                break;
            case lib::debug:
                luaL_requiref(L.get(), "debug", luaopen_debug, 1);
                lua_pop(L.get(), 1);
                break;
            case lib::count:
                break;
            }
        }
    }

    void script(const std::string& code) {
        if(luaL_dostring(L.get(), code.c_str())) {
            lua_error(L.get());
        }
    }

    void open_file(const std::string& filename) {
        if(luaL_dofile(L.get(), filename.c_str())) {
            lua_error(L.get());
        }
    }

    template<typename... Args, typename... Keys>
    auto get(Keys&&... keys) const
    -> decltype(global.get<Args...>(std::forward<Keys>(keys)...)) {
        return global.get<Args...>(std::forward<Keys>(keys)...);
    }

    template<typename T, typename U>
    state& set(T&& key, U&& value) {
        global.set(std::forward<T>(key), std::forward<U>(value));
        return *this;
    }

    template<typename T>
    SOL_DEPRECATED table& set_userdata(usertype<T>& user) {
        return set_usertype(user);
    }

    template<typename Key, typename T>
    SOL_DEPRECATED table& set_userdata(Key&& key, usertype<T>& user) {
        return set_usertype(std::forward<Key>(key), user);
    }

    template<typename Class, typename... CTor, typename... Args>
    SOL_DEPRECATED state& new_userdata(const std::string& name, Args&&... args) {
        return new_usertype<Class>(name, std::forward<Args>(args)...);
    }

    template<typename Class, typename... CArgs, typename... Args>
    SOL_DEPRECATED state& new_userdata(const std::string& name, constructors<CArgs...> ctor, Args&&... args) {
        return new_usertype(name, std::move(ctor), std::forward<Args>(args)...);
    }

    template<typename T>
    state& set_usertype(usertype<T>& user) {
        return set_usertype(usertype_traits<T>::name, user);
    }

    template<typename Key, typename T>
    state& set_usertype(Key&& key, usertype<T>& user) {
        global.set_usertype(std::forward<Key>(key), user);
        return *this;
    }

    template<typename Class, typename... CTor, typename... Args>
    state& new_usertype(const std::string& name, Args&&... args) {
        constructors<types<CTor...>> ctor{};
        return new_usertype<Class>(name, ctor, std::forward<Args>(args)...);
    }

    template<typename Class, typename... CArgs, typename... Args>
    state& new_usertype(const std::string& name, constructors<CArgs...> ctor, Args&&... args) {
        usertype<Class> utype(ctor, std::forward<Args>(args)...);
        set_usertype(name, utype);
        return *this;
    }

    template <typename Fx>
    void for_each(Fx&& fx) {
        global.for_each(std::forward<Fx>(fx));
    }

    template<typename T>
    table create_table(T&& key, int narr = 0, int nrec = 0) {
        lua_createtable(L.get(), narr, nrec);
        table result(L.get());
        lua_pop(L.get(), 1);
        global.set(std::forward<T>(key), result);
        return result;
    }

    table create_table(int narr = 0, int nrec = 0) {
        lua_createtable(L.get(), narr, nrec);
        table result(L.get());
        lua_pop(L.get(), 1);
        return result;
    }

    table global_table() const {
        return global;
    }

    table registry() const {
        return reg;
    }

    template<typename T>
    proxy<table, T> operator[](T&& key) {
        return global[std::forward<T>(key)];
    }

    template<typename T>
    proxy<const table, T> operator[](T&& key) const {
        return global[std::forward<T>(key)];
    }

    template<typename... Args, typename R, typename Key>
    state& set_function(Key&& key, R fun_ptr(Args...)){
        global.set_function(std::forward<Key>(key), fun_ptr);
        return *this;
    }

    template<typename Sig, typename Key>
    state& set_function(Key&& key, Sig* fun_ptr){
        global.set_function(std::forward<Key>(key), fun_ptr);
        return *this;
    }

    template<typename... Args, typename R, typename C, typename T, typename Key>
    state& set_function(Key&& key, R (C::*mem_ptr)(Args...), T&& obj) {
        global.set_function(std::forward<Key>(key), mem_ptr, std::forward<T>(obj));
        return *this;
    }

    template<typename Sig, typename C, typename T, typename Key>
    state& set_function(Key&& key, Sig C::* mem_ptr, T&& obj) {
        global.set_function(std::forward<Key>(key), mem_ptr, std::forward<T>(obj));
        return *this;
    }

    template<typename... Sig, typename Fx, typename Key>
    state& set_function(Key&& key, Fx&& fx) {
        global.set_function<Sig...>(std::forward<Key>(key), std::forward<Fx>(fx));
        return *this;
    }
};
} // sol

#endif // SOL_STATE_HPP
<commit_msg>Set the ability to give your own panic function<commit_after>// The MIT License (MIT)

// Copyright (c) 2013-2015 Danny Y., Rapptz

// 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.

#ifndef SOL_STATE_HPP
#define SOL_STATE_HPP

#include "error.hpp"
#include "table.hpp"
#include <memory>

namespace sol {
namespace detail {
inline int atpanic(lua_State* L) {
    const char* message = lua_tostring(L, -1);
    std::string err = message ? message : "An unexpected error occured and forced the lua state to call atpanic";
    throw error(err);
}
} // detail

enum class lib : char {
    base,
    package,
    coroutine,
    string,
    os,
    math,
    table,
    debug,
    bit32,
    io,
    count
};

class state {
private:
    std::unique_ptr<lua_State, void(*)(lua_State*)> L;
    table reg;
    table global;
public:
    state(lua_CFunction panic = detail::atpanic):
    L(luaL_newstate(), lua_close),
    reg(L.get(), LUA_REGISTRYINDEX),
#if SOL_LUA_VERSION < 503
    // Global table is just a special index
    global(L.get(), LUA_GLOBALSINDEX) {
#else
    // Global tables are stored in the environment/registry table
    global(reg.get<table>(LUA_RIDX_GLOBALS)) {
#endif // Lua 5.2
        set_panic(panic);
    }

    lua_State* lua_state() const {
        return L.get();
    }

    template<typename... Args>
    void open_libraries(Args&&... args) {
        static_assert(are_same<lib, Args...>::value, "all types must be libraries");
        if(sizeof...(args) == 0) {
            luaL_openlibs(L.get());
            return;
        }

        lib libraries[1 + sizeof...(args)] = { lib::count, std::forward<Args>(args)... };

        for(auto&& library : libraries) {
            switch(library) {
#if SOL_LUA_VERSION <= 501 && defined(SOL_LUAJIT)
            case lib::coroutine:
#endif // luajit opens coroutine base stuff
            case lib::base:
                luaL_requiref(L.get(), "base", luaopen_base, 1);
                lua_pop(L.get(), 1);
                break;
            case lib::package:
                luaL_requiref(L.get(), "package", luaopen_package, 1);
                lua_pop(L.get(), 1);
                break;
#if SOL_LUA_VERSION > 501
            case lib::coroutine:
                luaL_requiref(L.get(), "coroutine", luaopen_coroutine, 1);
                lua_pop(L.get(), 1);
                break;
#endif // Lua 5.2+ only
            case lib::string:
                luaL_requiref(L.get(), "string", luaopen_string, 1);
                lua_pop(L.get(), 1);
                break;
            case lib::table:
                luaL_requiref(L.get(), "table", luaopen_table, 1);
                lua_pop(L.get(), 1);
                break;
            case lib::math:
                luaL_requiref(L.get(), "math", luaopen_math, 1);
                lua_pop(L.get(), 1);
                break;
            case lib::bit32:
#if SOL_LUA_VERSION > 510
                luaL_requiref(L.get(), "bit32", luaopen_bit32, 1);
                lua_pop(L.get(), 1);
#else
#endif // Lua 5.2+ only
                break;
            case lib::io:
                luaL_requiref(L.get(), "io", luaopen_io, 1);
                lua_pop(L.get(), 1);
                break;
            case lib::os:
                luaL_requiref(L.get(), "os", luaopen_os, 1);
                lua_pop(L.get(), 1);
                break;
            case lib::debug:
                luaL_requiref(L.get(), "debug", luaopen_debug, 1);
                lua_pop(L.get(), 1);
                break;
            case lib::count:
                break;
            }
        }
    }

    void script(const std::string& code) {
        if(luaL_dostring(L.get(), code.c_str())) {
            lua_error(L.get());
        }
    }

    void open_file(const std::string& filename) {
        if(luaL_dofile(L.get(), filename.c_str())) {
            lua_error(L.get());
        }
    }

    template<typename... Args, typename... Keys>
    auto get(Keys&&... keys) const
    -> decltype(global.get<Args...>(std::forward<Keys>(keys)...)) {
        return global.get<Args...>(std::forward<Keys>(keys)...);
    }

    template<typename T, typename U>
    state& set(T&& key, U&& value) {
        global.set(std::forward<T>(key), std::forward<U>(value));
        return *this;
    }

    template<typename T>
    SOL_DEPRECATED table& set_userdata(usertype<T>& user) {
        return set_usertype(user);
    }

    template<typename Key, typename T>
    SOL_DEPRECATED table& set_userdata(Key&& key, usertype<T>& user) {
        return set_usertype(std::forward<Key>(key), user);
    }

    template<typename Class, typename... CTor, typename... Args>
    SOL_DEPRECATED state& new_userdata(const std::string& name, Args&&... args) {
        return new_usertype<Class>(name, std::forward<Args>(args)...);
    }

    template<typename Class, typename... CArgs, typename... Args>
    SOL_DEPRECATED state& new_userdata(const std::string& name, constructors<CArgs...> ctor, Args&&... args) {
        return new_usertype(name, std::move(ctor), std::forward<Args>(args)...);
    }

    template<typename T>
    state& set_usertype(usertype<T>& user) {
        return set_usertype(usertype_traits<T>::name, user);
    }

    template<typename Key, typename T>
    state& set_usertype(Key&& key, usertype<T>& user) {
        global.set_usertype(std::forward<Key>(key), user);
        return *this;
    }

    template<typename Class, typename... CTor, typename... Args>
    state& new_usertype(const std::string& name, Args&&... args) {
        constructors<types<CTor...>> ctor{};
        return new_usertype<Class>(name, ctor, std::forward<Args>(args)...);
    }

    template<typename Class, typename... CArgs, typename... Args>
    state& new_usertype(const std::string& name, constructors<CArgs...> ctor, Args&&... args) {
        usertype<Class> utype(ctor, std::forward<Args>(args)...);
        set_usertype(name, utype);
        return *this;
    }

    template <typename Fx>
    void for_each(Fx&& fx) {
        global.for_each(std::forward<Fx>(fx));
    }

    template<typename T>
    table create_table(T&& key, int narr = 0, int nrec = 0) {
        lua_createtable(L.get(), narr, nrec);
        table result(L.get());
        lua_pop(L.get(), 1);
        global.set(std::forward<T>(key), result);
        return result;
    }

    table create_table(int narr = 0, int nrec = 0) {
        lua_createtable(L.get(), narr, nrec);
        table result(L.get());
        lua_pop(L.get(), 1);
        return result;
    }

    table global_table() const {
        return global;
    }

    table registry() const {
        return reg;
    }

    void set_panic(lua_CFunction panic){
        lua_atpanic(L.get(), panic);
    }

    template<typename T>
    proxy<table, T> operator[](T&& key) {
        return global[std::forward<T>(key)];
    }

    template<typename T>
    proxy<const table, T> operator[](T&& key) const {
        return global[std::forward<T>(key)];
    }

    template<typename... Args, typename R, typename Key>
    state& set_function(Key&& key, R fun_ptr(Args...)){
        global.set_function(std::forward<Key>(key), fun_ptr);
        return *this;
    }

    template<typename Sig, typename Key>
    state& set_function(Key&& key, Sig* fun_ptr){
        global.set_function(std::forward<Key>(key), fun_ptr);
        return *this;
    }

    template<typename... Args, typename R, typename C, typename T, typename Key>
    state& set_function(Key&& key, R (C::*mem_ptr)(Args...), T&& obj) {
        global.set_function(std::forward<Key>(key), mem_ptr, std::forward<T>(obj));
        return *this;
    }

    template<typename Sig, typename C, typename T, typename Key>
    state& set_function(Key&& key, Sig C::* mem_ptr, T&& obj) {
        global.set_function(std::forward<Key>(key), mem_ptr, std::forward<T>(obj));
        return *this;
    }

    template<typename... Sig, typename Fx, typename Key>
    state& set_function(Key&& key, Fx&& fx) {
        global.set_function<Sig...>(std::forward<Key>(key), std::forward<Fx>(fx));
        return *this;
    }
};
} // sol

#endif // SOL_STATE_HPP
<|endoftext|>


<commit_before>#pragma once

#include "point2d.hpp"

class Box2D
{
public:
  // Разрешаем конструирование по умолчанию.
  Box2D() = default;

  // Конструктор копирования.
  Box2D(Box2D const & obj)
    : m_point1(obj.m_point1), m_point2(obj.m_point2)
  {}

  // Конструктор с параметрами.
  Box2D(Point2D x, Point2D y)
    : m_point1(x), m_point2(y)
  {}

  Point2D & point1() { return m_point1; }
  Point2D & point2() { return m_point2; }

  Point2D const & point1() const { return m_point1; }
  Point2D const & point2() const { return m_point2; }

  // Оператор присваивания.
  Box2D & operator = (Box2D const & obj)
  {
    if (this == &obj) return *this;
    m_point1 = obj.m_point1;
    m_point2 = obj.m_point2;
    return *this;
  }

  // Оператор логического равенства.
  bool operator == (Box2D const & obj) const
  {
    return m_point1 == obj.m_point1 && m_point2 == obj.m_point2;
  }

private:
    Point2D m_point1={ 0.0f, 0.0f };
    Point2D m_point2={ 1.0f, 1.0f };
};

bool checkBoxes(Box2D const & box1,Box2D const & box2)
{
    bool result;
    if( box1.point2().x() <= box2.point1().x() || box2.point2().x() <= box1.point1().x() ||
            box1.point1().y() >= box2.point2().y() || box2.point1().y() >= box1.point2().y() )
        result = false;
    else
        result = true;
    return result;
}
<commit_msg>add inline<commit_after>#pragma once

#include "point2d.hpp"

class Box2D
{
public:
  // Разрешаем конструирование по умолчанию.
  Box2D() = default;

  // Конструктор копирования.
  Box2D(Box2D const & obj)
    : m_point1(obj.m_point1), m_point2(obj.m_point2)
  {}

  // Конструктор с параметрами.
  Box2D(Point2D x, Point2D y)
    : m_point1(x), m_point2(y)
  {}

  Point2D & point1() { return m_point1; }
  Point2D & point2() { return m_point2; }

  Point2D const & point1() const { return m_point1; }
  Point2D const & point2() const { return m_point2; }

  // Оператор присваивания.
  Box2D & operator = (Box2D const & obj)
  {
    if (this == &obj) return *this;
    m_point1 = obj.m_point1;
    m_point2 = obj.m_point2;
    return *this;
  }

  // Оператор логического равенства.
  bool operator == (Box2D const & obj) const
  {
    return m_point1 == obj.m_point1 && m_point2 == obj.m_point2;
  }

private:
    Point2D m_point1={ 0.0f, 0.0f };
    Point2D m_point2={ 1.0f, 1.0f };
};

inline bool checkBoxes(Box2D const & box1,Box2D const & box2)
{
    bool result;
    if( box1.point2().x() <= box2.point1().x() || box2.point2().x() <= box1.point1().x() ||
            box1.point1().y() >= box2.point2().y() || box2.point1().y() >= box1.point2().y() )
        result = false;
    else
        result = true;
    return result;
}
<|endoftext|>


<commit_before>/**
 * @file Cosa/Board/WickedDevice/WildFire.hh
 * @version 1.0
 *
 * @section License
 * Copyright (C) 2015, Mikael Patel
 *
 * 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.
 *
 * This file is part of the Arduino Che Cosa project.
 */

#ifndef COSA_BOARD_WICKEDDDEVICE_WILDFIRE_HH
#define COSA_BOARD_WICKEDDDEVICE_WILDFIRE_HH

/* This board is based on ATmega1248P */
#define BOARD_ATMEGA1248P

/**
 * Cosa pin symbol definitions for Wicked Device WildFire board. Cosa
 * does not use pin numbers as Arduino/Wiring. Instead strong data
 * type is used (enum types) for the specific pin classes; DigitalPin,
 * AnalogPin, PWMPin, etc.
 *
 * The static inline functions, SFR, BIT and UART, rely on compiler
 * optimizations to be reduced.
 * @section Board
 * @code
 *                    Wicked Device WildFire
 *                  -----
 *                +-|(o)|------------------------+
 *                | |   |                        |
 *                | -----                        |
 *                |o-o U8                        |
 *                |o-o                           |
 *                |o-o JTAG                    []| SCL
 *                |o-o                         []| SDA
 *                |o-o U9                      []| AREF
 *                |                            []| GND
 *             NC |[]                          []| D13/SCK/LED
 *          IOREF |[]                          []| D12/MISO
 *          RESET |[]                          []| D11/MOSI/PWM5
 *            3V3 |[]                          []| D10/SS/PWM4
 *             5V |[]                          []| D9/PWM3
 *            GND |[]                          []| D8
 *            GND |[]                            |
 *            Vin |[]                          []| D7
 *                |                            []| D6/PWM2
 *         A0/D14 |[]                          []| D5/PWM1
 *         A1/D15 |[]                          []| D4
 *         A2/D16 |[]  +--------+              []| D3/EXT1/PWM0
 *         A3/D17 |[]  |        |              []| D2/EXT0
 *     SDA/A4/D18 |[]  |   SD   |     +-----+  []| D1/TX
 *     SCL/A5/D19 |[]  |        |     | USB |  []| D0/RX
 *                 \   | ||||   |    /+-----+----/
 *                  +--+--------+---+
 * @endcode
 */
class Board {
  friend class Pin;
  friend class UART;
private:
  /**
   * Do not allow instances. This is a static singleton; name space.
   */
  Board() {}

  /**
   * Return Special Function Register for given Arduino pin number.
   * @param[in] pin number.
   * @return special register pointer.
   */
  static volatile uint8_t* SFR(uint8_t pin)
    __attribute__((always_inline))
  {
    return (pin < 8  ? &PINA:
	    pin < 16 ? &PINB :
	    pin < 24 ? &PINC :
	               &PIND);
  }

  /**
   * Return bit position for given Arduino pin number in Special
   * Function Register.
   * @param[in] pin number.
   * @return pin bit position.
   */
  static uint8_t BIT(uint8_t pin)
    __attribute__((always_inline))
  {
    return (pin & 0x7);
  }

  /**
   * Return Pin Change Mask Register for given Arduino pin number.
   * @param[in] pin number.
   * @return pin change mask register pointer.
   */
  static volatile uint8_t* PCIMR(uint8_t pin)
    __attribute__((always_inline))
  {
    return (pin < 8  ? &PCMSK0 :
	    pin < 16 ? &PCMSK1 :
	    pin < 24 ? &PCMSK2 :
	               &PCMSK3);
  }

  /**
   * Return UART Register for given Arduino serial port.
   * @param[in] port number.
   * @return UART register pointer.
   */
  static volatile uint8_t* UART(uint8_t port)
    __attribute__((always_inline))
  {
    return (port == 1 ? &UCSR1A : &UCSR0A);
  }

public:
  /**
   * Digital pin symbols
   */
  enum DigitalPin {
    D0 = 24,			// PD0
    D1 = 25,			// PD1
    D2 = 26,			// PD2
    D3 = 27,			// PD3
    D4 = 11,			// PB3
    D5 = 29,			// PD5
    D6 = 30,			// PD6
    D7 = 19,			// PC3
    D8 = 28,			// PD4
    D9 = 12,			// PB4
    D10 = 31,			// PD7
    D11 = 13,			// PB5
    D12 = 14,			// PB6
    D13 = 15,			// PB7
    D14 = 20,			// PC4
    D15 = 18,			// PC2
    D16 = 21,			// PC5
    D17 = 22,			// PC6
    D18 = 23,			// PC7
    D19 = 17,			// PC1
    D20 = 16,			// PC0
    D21 = 8,			// PB0
    D22 = 10,			// PB2
    D23 = 9,			// PB1
    D24 = 0,			// PA0
    D25 = 1,			// PA1
    D26 = 2,			// PA2
    D27 = 3,			// PA3
    D28 = 4,			// PA4
    D29 = 5,			// PA5
    D30 = 6,			// PA6
    D31 = 7,			// PA7
    LED = D13
  } __attribute__((packed));

  /**
   * Analog pin symbols (ADC channel numbers)
   */
  enum AnalogPin {
    A0 = 0,			// PA0
    A1,				// PA1
    A2,				// PA2
    A3,				// PA3
    A4,				// PA4
    A5,				// PA5
    A6,				// PA6
    A7				// PA7
  } __attribute__((packed));

  /**
   * Reference voltage; ARef pin, Vcc or internal 1V1.
   */
  enum Reference {
    APIN_REFERENCE = 0,
    AVCC_REFERENCE = _BV(REFS0),
    A1V1_REFERENCE = _BV(REFS1),
    A2V56_REFERENCE = (_BV(REFS1) | _BV(REFS0))
  } __attribute__((packed));

  /**
   * PWM pin symbols; sub-set of digital pins to allow compile
   * time checking
   */
  enum PWMPin {
    PWM0 = D3,			// PB3 => OCR0A
    PWM1 = D4,			// PB4 => OCR0B
#if defined(__AVR_ATmega1284P__)
    PWM2 = D6,			// PB6 => OCR3A
    PWM3 = D7,			// PB7 => OCR3B
#else
    PWM2 = 255,			// PB6 => NOP
    PWM3 = 255,			// PB7 => NOP
#endif
    PWM4 = D12,			// PD4 => OCR1B
    PWM5 = D13,			// PD5 => OCR1A
    PWM6 = D14,			// PD6 => OCR2B
    PWM7 = D15			// PD7 => OCR2A
  } __attribute__((packed));

  /**
   * External interrupt pin symbols; sub-set of digital pins
   * to allow compile time checking.
   */
  enum ExternalInterruptPin {
    EXT0 = D10,			// PD2
    EXT1 = D11,			// PD3
    EXT2 = D2			// PB2
  } __attribute__((packed));

  /**
   * Pin change interrupt. Number of port registers.
   */
  enum InterruptPin {
    PCI0 = 0,			// PA0
    PCI1,			// PA1
    PCI2,			// PA2
    PCI3,			// PA3
    PCI4,			// PA4
    PCI5,			// PA5
    PCI6,			// PA6
    PCI7,			// PA7
    PCI8,			// PB0
    PCI9,			// PB1
    PCI10,			// PB2
    PCI11,			// PB3
    PCI12,			// PB4
    PCI13,			// PB5
    PCI14,			// PB6
    PCI15,			// PB7
    PCI16,			// PC0
    PCI17,			// PC1
    PCI18,			// PC2
    PCI19,			// PC3
    PCI20,			// PC4
    PCI21,			// PC5
    PCI22,			// PC6
    PCI23,			// PC7
    PCI24,			// PD0
    PCI25,			// PD1
    PCI26,			// PD2
    PCI27,			// PD3
    PCI28,			// PD4
    PCI29,			// PD5
    PCI30,			// PD6
    PCI31			// PD7
  } __attribute__((packed));

  /**
   * Size of pin maps.
   */
  enum {
    ANALOG_PIN_MAX = 8,
    DIGITAL_PIN_MAX = 32,
    EXT_PIN_MAX = 3,
    PCI_PIN_MAX = 32,
    PWM_PIN_MAX = 8
  };

  /**
   * Pins used for TWI interface (in port C, bit 0-1, D20-D19)
   */
  enum TWIPin {
    SDA = 1,			// PC1/D20
    SCL = 0			// PC0/D19
  } __attribute__((packed));

 /**
   * Pins used for SPI interface (in port B, bit 4-7, D9,D11-D13)
   */
  enum SPIPin {
    SS = 4,			// PB4/D9
    MOSI = 5,			// PB5/D11
    MISO = 6,			// PB6/D12
    SCK = 7			// PB7/D13
  } __attribute__((packed));

  /**
   * Auxiliary
   */
  enum {
    VBG = (_BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1)),
    UART_MAX = 2,
    EXT_MAX = 3,
    PCMSK_MAX = 4,
    PCINT_MAX = 32
  } __attribute__((packed));
};

/**
 * Redefinition of symbols to allow generic code.
 */
#define USART_UDRE_vect USART0_UDRE_vect
#define USART_RX_vect USART0_RX_vect
#define USART_TX_vect USART0_TX_vect

/**
 * Forward declare interrupt service routines to allow them as friends.
 */
extern "C" {
  void ADC_vect(void) __attribute__ ((signal));
  void ANALOG_COMP_vect(void) __attribute__ ((signal));
  void INT0_vect(void) __attribute__ ((signal));
  void INT1_vect(void) __attribute__ ((signal));
  void INT2_vect(void) __attribute__ ((signal));
  void PCINT0_vect(void) __attribute__ ((signal));
  void PCINT1_vect(void) __attribute__ ((signal));
  void PCINT2_vect(void) __attribute__ ((signal));
  void PCINT3_vect(void) __attribute__ ((signal));
  void SPI_STC_vect(void) __attribute__ ((signal));
  void TIMER0_COMPA_vect(void) __attribute__ ((signal));
  void TIMER0_COMPB_vect(void) __attribute__ ((signal));
  void TIMER0_OVF_vect(void) __attribute__ ((signal));
  void TIMER1_CAPT_vect(void) __attribute__ ((signal));
  void TIMER1_COMPA_vect(void) __attribute__ ((signal));
  void TIMER1_COMPB_vect(void) __attribute__ ((signal));
  void TIMER1_OVF_vect(void) __attribute__ ((signal));
  void TIMER2_COMPA_vect(void) __attribute__ ((signal));
  void TIMER2_COMPB_vect(void) __attribute__ ((signal));
  void TIMER2_OVF_vect(void) __attribute__ ((signal));
#if defined(__AVR_ATmega1284P__)
  void TIMER3_CAPT_vect(void) __attribute__ ((signal));
  void TIMER3_COMPA_vect(void) __attribute__ ((signal));
  void TIMER3_COMPB_vect(void) __attribute__ ((signal));
  void TIMER3_OVF_vect(void) __attribute__ ((signal));
#endif
  void TWI_vect(void) __attribute__ ((signal));
  void WDT_vect(void) __attribute__ ((signal));
  void USART_RX_vect(void) __attribute__ ((signal));
  void USART_TX_vect(void) __attribute__ ((signal));
  void USART_UDRE_vect(void) __attribute__ ((signal));
  void USART1_RX_vect(void) __attribute__ ((signal));
  void USART1_UDRE_vect(void) __attribute__ ((signal));
  void USART1_TX_vect(void) __attribute__ ((signal));
}
#endif
<commit_msg>Fixed missing A6 and A7 in WildFire sketch (in header file).<commit_after>/**
 * @file Cosa/Board/WickedDevice/WildFire.hh
 * @version 1.0
 *
 * @section License
 * Copyright (C) 2015, Mikael Patel
 *
 * 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.
 *
 * This file is part of the Arduino Che Cosa project.
 */

#ifndef COSA_BOARD_WICKEDDDEVICE_WILDFIRE_HH
#define COSA_BOARD_WICKEDDDEVICE_WILDFIRE_HH

/* This board is based on ATmega1248P */
#define BOARD_ATMEGA1248P

/**
 * Cosa pin symbol definitions for Wicked Device WildFire board. Cosa
 * does not use pin numbers as Arduino/Wiring. Instead strong data
 * type is used (enum types) for the specific pin classes; DigitalPin,
 * AnalogPin, PWMPin, etc.
 *
 * The static inline functions, SFR, BIT and UART, rely on compiler
 * optimizations to be reduced.
 * @section Board
 * @code
 *                    Wicked Device WildFire
 *                  -----
 *                +-|(o)|------------------------+
 *                | |   |                        |
 *                | -----                        |
 *                |o-o U8                        |
 *                |o-o                           |
 *                |o-o JTAG                    []| SCL
 *                |o-o                         []| SDA
 *                |o-o U9                      []| AREF
 *                |                            []| GND
 *             NC |[]                          []| D13/SCK/LED
 *          IOREF |[]                          []| D12/MISO
 *          RESET |[]                          []| D11/MOSI/PWM5
 *            3V3 |[]                          []| D10/SS/PWM4
 *             5V |[]                          []| D9/PWM3
 *            GND |[]                          []| D8
 *            GND |[]                            |
 *            Vin |[]                          []| D7
 *                |                            []| D6/PWM2
 *         A0/D14 |[]                          []| D5/PWM1
 *         A1/D15 |[]                          []| D4
 *         A2/D16 |[]  +--------+              []| D3/EXT1/PWM0
 *         A3/D17 |[]  |        |              []| D2/EXT0
 *     SDA/A4/D18 |[]  |   SD   |      +-----+ []| D1/TX
 *     SCL/A5/D19 |[]  |        |      | USB | []| D0/RX
 *         A6/D24 |[]  | || ||  |      +-----+---/
 *         A7/D25 |[]  +--------+     /
 *                 \------------------
 * @endcode
 */
class Board {
  friend class Pin;
  friend class UART;
private:
  /**
   * Do not allow instances. This is a static singleton; name space.
   */
  Board() {}

  /**
   * Return Special Function Register for given Arduino pin number.
   * @param[in] pin number.
   * @return special register pointer.
   */
  static volatile uint8_t* SFR(uint8_t pin)
    __attribute__((always_inline))
  {
    return (pin < 8  ? &PINA:
	    pin < 16 ? &PINB :
	    pin < 24 ? &PINC :
	               &PIND);
  }

  /**
   * Return bit position for given Arduino pin number in Special
   * Function Register.
   * @param[in] pin number.
   * @return pin bit position.
   */
  static uint8_t BIT(uint8_t pin)
    __attribute__((always_inline))
  {
    return (pin & 0x7);
  }

  /**
   * Return Pin Change Mask Register for given Arduino pin number.
   * @param[in] pin number.
   * @return pin change mask register pointer.
   */
  static volatile uint8_t* PCIMR(uint8_t pin)
    __attribute__((always_inline))
  {
    return (pin < 8  ? &PCMSK0 :
	    pin < 16 ? &PCMSK1 :
	    pin < 24 ? &PCMSK2 :
	               &PCMSK3);
  }

  /**
   * Return UART Register for given Arduino serial port.
   * @param[in] port number.
   * @return UART register pointer.
   */
  static volatile uint8_t* UART(uint8_t port)
    __attribute__((always_inline))
  {
    return (port == 1 ? &UCSR1A : &UCSR0A);
  }

public:
  /**
   * Digital pin symbols
   */
  enum DigitalPin {
    D0 = 24,			// PD0
    D1 = 25,			// PD1
    D2 = 26,			// PD2
    D3 = 27,			// PD3
    D4 = 11,			// PB3
    D5 = 29,			// PD5
    D6 = 30,			// PD6
    D7 = 19,			// PC3
    D8 = 28,			// PD4
    D9 = 12,			// PB4
    D10 = 31,			// PD7
    D11 = 13,			// PB5
    D12 = 14,			// PB6
    D13 = 15,			// PB7
    D14 = 20,			// PC4
    D15 = 18,			// PC2
    D16 = 21,			// PC5
    D17 = 22,			// PC6
    D18 = 23,			// PC7
    D19 = 17,			// PC1
    D20 = 16,			// PC0
    D21 = 8,			// PB0
    D22 = 10,			// PB2
    D23 = 9,			// PB1
    D24 = 0,			// PA0
    D25 = 1,			// PA1
    D26 = 2,			// PA2
    D27 = 3,			// PA3
    D28 = 4,			// PA4
    D29 = 5,			// PA5
    D30 = 6,			// PA6
    D31 = 7,			// PA7
    LED = D13
  } __attribute__((packed));

  /**
   * Analog pin symbols (ADC channel numbers)
   */
  enum AnalogPin {
    A0 = 0,			// PA0
    A1,				// PA1
    A2,				// PA2
    A3,				// PA3
    A4,				// PA4
    A5,				// PA5
    A6,				// PA6
    A7				// PA7
  } __attribute__((packed));

  /**
   * Reference voltage; ARef pin, Vcc or internal 1V1.
   */
  enum Reference {
    APIN_REFERENCE = 0,
    AVCC_REFERENCE = _BV(REFS0),
    A1V1_REFERENCE = _BV(REFS1),
    A2V56_REFERENCE = (_BV(REFS1) | _BV(REFS0))
  } __attribute__((packed));

  /**
   * PWM pin symbols; sub-set of digital pins to allow compile
   * time checking
   */
  enum PWMPin {
    PWM0 = D3,			// PB3 => OCR0A
    PWM1 = D4,			// PB4 => OCR0B
#if defined(__AVR_ATmega1284P__)
    PWM2 = D6,			// PB6 => OCR3A
    PWM3 = D7,			// PB7 => OCR3B
#else
    PWM2 = 255,			// PB6 => NOP
    PWM3 = 255,			// PB7 => NOP
#endif
    PWM4 = D12,			// PD4 => OCR1B
    PWM5 = D13,			// PD5 => OCR1A
    PWM6 = D14,			// PD6 => OCR2B
    PWM7 = D15			// PD7 => OCR2A
  } __attribute__((packed));

  /**
   * External interrupt pin symbols; sub-set of digital pins
   * to allow compile time checking.
   */
  enum ExternalInterruptPin {
    EXT0 = D10,			// PD2
    EXT1 = D11,			// PD3
    EXT2 = D2			// PB2
  } __attribute__((packed));

  /**
   * Pin change interrupt. Number of port registers.
   */
  enum InterruptPin {
    PCI0 = 0,			// PA0
    PCI1,			// PA1
    PCI2,			// PA2
    PCI3,			// PA3
    PCI4,			// PA4
    PCI5,			// PA5
    PCI6,			// PA6
    PCI7,			// PA7
    PCI8,			// PB0
    PCI9,			// PB1
    PCI10,			// PB2
    PCI11,			// PB3
    PCI12,			// PB4
    PCI13,			// PB5
    PCI14,			// PB6
    PCI15,			// PB7
    PCI16,			// PC0
    PCI17,			// PC1
    PCI18,			// PC2
    PCI19,			// PC3
    PCI20,			// PC4
    PCI21,			// PC5
    PCI22,			// PC6
    PCI23,			// PC7
    PCI24,			// PD0
    PCI25,			// PD1
    PCI26,			// PD2
    PCI27,			// PD3
    PCI28,			// PD4
    PCI29,			// PD5
    PCI30,			// PD6
    PCI31			// PD7
  } __attribute__((packed));

  /**
   * Size of pin maps.
   */
  enum {
    ANALOG_PIN_MAX = 8,
    DIGITAL_PIN_MAX = 32,
    EXT_PIN_MAX = 3,
    PCI_PIN_MAX = 32,
    PWM_PIN_MAX = 8
  };

  /**
   * Pins used for TWI interface (in port C, bit 0-1, D20-D19)
   */
  enum TWIPin {
    SDA = 1,			// PC1/D20
    SCL = 0			// PC0/D19
  } __attribute__((packed));

 /**
   * Pins used for SPI interface (in port B, bit 4-7, D9,D11-D13)
   */
  enum SPIPin {
    SS = 4,			// PB4/D9
    MOSI = 5,			// PB5/D11
    MISO = 6,			// PB6/D12
    SCK = 7			// PB7/D13
  } __attribute__((packed));

  /**
   * Auxiliary
   */
  enum {
    VBG = (_BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1)),
    UART_MAX = 2,
    EXT_MAX = 3,
    PCMSK_MAX = 4,
    PCINT_MAX = 32
  } __attribute__((packed));
};

/**
 * Redefinition of symbols to allow generic code.
 */
#define USART_UDRE_vect USART0_UDRE_vect
#define USART_RX_vect USART0_RX_vect
#define USART_TX_vect USART0_TX_vect

/**
 * Forward declare interrupt service routines to allow them as friends.
 */
extern "C" {
  void ADC_vect(void) __attribute__ ((signal));
  void ANALOG_COMP_vect(void) __attribute__ ((signal));
  void INT0_vect(void) __attribute__ ((signal));
  void INT1_vect(void) __attribute__ ((signal));
  void INT2_vect(void) __attribute__ ((signal));
  void PCINT0_vect(void) __attribute__ ((signal));
  void PCINT1_vect(void) __attribute__ ((signal));
  void PCINT2_vect(void) __attribute__ ((signal));
  void PCINT3_vect(void) __attribute__ ((signal));
  void SPI_STC_vect(void) __attribute__ ((signal));
  void TIMER0_COMPA_vect(void) __attribute__ ((signal));
  void TIMER0_COMPB_vect(void) __attribute__ ((signal));
  void TIMER0_OVF_vect(void) __attribute__ ((signal));
  void TIMER1_CAPT_vect(void) __attribute__ ((signal));
  void TIMER1_COMPA_vect(void) __attribute__ ((signal));
  void TIMER1_COMPB_vect(void) __attribute__ ((signal));
  void TIMER1_OVF_vect(void) __attribute__ ((signal));
  void TIMER2_COMPA_vect(void) __attribute__ ((signal));
  void TIMER2_COMPB_vect(void) __attribute__ ((signal));
  void TIMER2_OVF_vect(void) __attribute__ ((signal));
#if defined(__AVR_ATmega1284P__)
  void TIMER3_CAPT_vect(void) __attribute__ ((signal));
  void TIMER3_COMPA_vect(void) __attribute__ ((signal));
  void TIMER3_COMPB_vect(void) __attribute__ ((signal));
  void TIMER3_OVF_vect(void) __attribute__ ((signal));
#endif
  void TWI_vect(void) __attribute__ ((signal));
  void WDT_vect(void) __attribute__ ((signal));
  void USART_RX_vect(void) __attribute__ ((signal));
  void USART_TX_vect(void) __attribute__ ((signal));
  void USART_UDRE_vect(void) __attribute__ ((signal));
  void USART1_RX_vect(void) __attribute__ ((signal));
  void USART1_UDRE_vect(void) __attribute__ ((signal));
  void USART1_TX_vect(void) __attribute__ ((signal));
}
#endif
<|endoftext|>


<commit_before>#include <stdlib.h>
#include <iostream>
#include <vector>

#include <boost/program_options.hpp>
#include <boost/program_options/parsers.hpp>

// #include <thrift/processor/TMultiplexedProcessor.h>

// #include "xbt.h"
#include "simgrid/s4u.hpp"

#include "rsg/TZmqServer.hpp"
#include "rsg/RsgThriftServer.hpp"
// #include "rsg/Socket.hpp"
// #include "rsg/services.hpp"
// #include "rsg/Server.hpp"
#include "common.hpp"

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

using boost::shared_ptr;
using namespace ::simgrid;

std::mutex print;
std::vector<std::thread*> threads;
bool start_clients;

XBT_LOG_NEW_CATEGORY(RSG_THRIFT, "Remote SimGrid");
XBT_LOG_NEW_DEFAULT_SUBCATEGORY(RSG_THRIFT_SERVER, RSG_THRIFT , "RSG server (Remote SimGrid)");

extern char **environ;

/*!
 *  Fork a remote process, creates an RPC server to handle all the actor communication
 *  The function first creates an RPC server with an unused TCP port. When the server is succefully setted in listen mode
 *  the function forks and set the Rpc port to the environment with execve.
*/
static int rsg_representative(int argc, char **argv) {

    std::string name;
    TZmqServer::get_new_endpoint(name);

    debug_server_print("STARTING %s", name.c_str());
    if (!start_clients)
    {
        printf("RsgRpcNetworkName=%s\n", name.c_str());
        fflush(stdout);
    }

    RsgThriftServer srv(name);

    //We create the string formated to environment variables (key=value)
    std::string envKeyValueStr = "RsgRpcNetworkName=" + name;

    if (start_clients)
    {
        // We fork the actor process
        pid_t pid = fork();
        if (! pid) {
            putenv((char*)envKeyValueStr.c_str());

            int newargc = argc-1+2+1;
            char **newargv = (char**)calloc(newargc, sizeof(char*));
            newargv[0] = (char*)"/usr/bin/env";
            newargv[1] = (char*)"--";
            for(int i=1; i < argc; i++) {
                newargv[1+i] = argv[i];
            }
            newargv[newargc-1] = NULL;

            debug_server_print("fork+exec: %s with ENV(%s)",
                               newargv[2], envKeyValueStr.c_str());
            execve(newargv[0], newargv, environ);
        }
        debug_server_print("Child started at pid %i", pid);
    }
    else
    {
        printf("NOT DOING fork+exec: %s with ENV(%s)\n",
               argv[1], envKeyValueStr.c_str());

        std::string command_str;
        for (int i = 1; i < argc-1; ++i)
        {
            command_str += (std::string)(argv[i]) + " ";
        }
        command_str += argv[argc-1];

        printf("Waiting for client external launch. "
               "Environment: %s. "
               "Command: %s\n",
               envKeyValueStr.c_str(),
               command_str.c_str());
    }

    srv();

    debug_server_print("END");
    return 0;
}

int main(int argc, char **argv) {
    std::string platform_file;
    std::string deployment_file;
    start_clients = true;

    namespace po = boost::program_options;
    po::options_description desc("Options description");
    desc.add_options()
            ("help,h", "print usage message")
            ("server-only",
             "prevents the server to fork+exec into clients to deploy")
            ("platform-file", po::value(&platform_file)->required(),
             "the SimGrid platform to simulate")
            ("deployment-file", po::value(&deployment_file)->required(),
             "the SimGrid initial deployment")
            ;

    po::positional_options_description positional_options;
    positional_options.add("platform-file", 1);
    positional_options.add("deployment-file", 1);

    po::variables_map vm;

    try
    {
        po::store(po::command_line_parser(argc, argv).options(desc)
                  .positional(positional_options).run(),
                  vm); // throws on error

        if (vm.count("help") > 0)
        {
            printf("Usage : %s platform_file deployment_file [options]\n",
                   argv[0]);
            std::cout << desc << "\n";
            return 0;
        }

        if (vm.count("server-only"))
        {
            start_clients = false;
        }

        po::notify(vm);
    }
    catch(boost::program_options::required_option& e)
    {
        std::cerr << "ERROR: " << e.what() << "\n";
        return 1;
    }
    catch(boost::program_options::error& e)
    {
        std::cerr << "ERROR: " << e.what() << "\n";
        return 1;
    }

    if (DEBUG_SERVER) {
        int major, minor, patch;
        zmq_version (&major, &minor, &patch);
        fprintf(stderr, DEBUG_PREFIX_STR "0MQ version is %i.%i.%i\n",
                major, minor, patch);
    }

    s4u::Engine *e = new s4u::Engine(&argc,argv);

    pthread_t router;
    pthread_create(&router, NULL, TZmqServer::router_thread, 0);

    // Initialize the SimGrid world
    e->loadPlatform(platform_file.c_str());
    e->registerDefault(rsg_representative);
    e->loadDeployment(deployment_file.c_str());
    e->run();

    //wait for the router to close cleanly
    pthread_join(router, 0);
    return 0;
}
<commit_msg>[code] launch servers in parallel<commit_after>#include <stdlib.h>
#include <iostream>
#include <vector>

#include <boost/program_options.hpp>
#include <boost/program_options/parsers.hpp>

// #include <thrift/processor/TMultiplexedProcessor.h>

// #include "xbt.h"
#include "simgrid/s4u.hpp"

#include "rsg/TZmqServer.hpp"
#include "rsg/RsgThriftServer.hpp"
// #include "rsg/Socket.hpp"
// #include "rsg/services.hpp"
// #include "rsg/Server.hpp"
#include "common.hpp"

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

using boost::shared_ptr;
using namespace ::simgrid;

std::mutex print;
std::vector<std::thread*> threads;
bool start_clients;

XBT_LOG_NEW_CATEGORY(RSG_THRIFT, "Remote SimGrid");
XBT_LOG_NEW_DEFAULT_SUBCATEGORY(RSG_THRIFT_SERVER, RSG_THRIFT , "RSG server (Remote SimGrid)");

extern char **environ;

/*!
 *  Fork a remote process, creates an RPC server to handle all the actor communication
 *  The function first creates an RPC server with an unused TCP port. When the server is succefully setted in listen mode
 *  the function forks and set the Rpc port to the environment with execve.
*/
static int rsg_representative(int argc, char **argv) {

    std::string name;
    TZmqServer::get_new_endpoint(name);

    debug_server_print("STARTING %s", name.c_str());
    if (!start_clients)
    {
        printf("RsgRpcNetworkName=%s\n", name.c_str());
        fflush(stdout);
    }

    RsgThriftServer srv(name);

    //We create the string formated to environment variables (key=value)
    std::string envKeyValueStr = "RsgRpcNetworkName=" + name;

    if (start_clients)
    {
        // We fork the actor process
        pid_t pid = fork();
        if (! pid) {
            putenv((char*)envKeyValueStr.c_str());

            int newargc = argc-1+2+1;
            char **newargv = (char**)calloc(newargc, sizeof(char*));
            newargv[0] = (char*)"/usr/bin/env";
            newargv[1] = (char*)"--";
            for(int i=1; i < argc; i++) {
                newargv[1+i] = argv[i];
            }
            newargv[newargc-1] = NULL;

            debug_server_print("fork+exec: %s with ENV(%s)",
                               newargv[2], envKeyValueStr.c_str());
            execve(newargv[0], newargv, environ);
        }
        debug_server_print("Child started at pid %i", pid);
    }
    else
    {
        printf("NOT DOING fork+exec: %s with ENV(%s)\n",
               argv[1], envKeyValueStr.c_str());

        std::string command_str;
        for (int i = 1; i < argc-1; ++i)
        {
            command_str += (std::string)(argv[i]) + " ";
        }
        command_str += argv[argc-1];

        printf("Waiting for client external launch. "
               "Environment: %s. "
               "Command: %s\n",
               envKeyValueStr.c_str(),
               command_str.c_str());
    }

    // Yielding before srv() allows launch parallelization
    simgrid::s4u::this_actor::yield();

    srv();

    debug_server_print("END");
    return 0;
}

int main(int argc, char **argv) {
    std::string platform_file;
    std::string deployment_file;
    start_clients = true;

    namespace po = boost::program_options;
    po::options_description desc("Options description");
    desc.add_options()
            ("help,h", "print usage message")
            ("server-only",
             "prevents the server to fork+exec into clients to deploy")
            ("platform-file", po::value(&platform_file)->required(),
             "the SimGrid platform to simulate")
            ("deployment-file", po::value(&deployment_file)->required(),
             "the SimGrid initial deployment")
            ;

    po::positional_options_description positional_options;
    positional_options.add("platform-file", 1);
    positional_options.add("deployment-file", 1);

    po::variables_map vm;

    try
    {
        po::store(po::command_line_parser(argc, argv).options(desc)
                  .positional(positional_options).run(),
                  vm); // throws on error

        if (vm.count("help") > 0)
        {
            printf("Usage : %s platform_file deployment_file [options]\n",
                   argv[0]);
            std::cout << desc << "\n";
            return 0;
        }

        if (vm.count("server-only"))
        {
            start_clients = false;
        }

        po::notify(vm);
    }
    catch(boost::program_options::required_option& e)
    {
        std::cerr << "ERROR: " << e.what() << "\n";
        return 1;
    }
    catch(boost::program_options::error& e)
    {
        std::cerr << "ERROR: " << e.what() << "\n";
        return 1;
    }

    if (DEBUG_SERVER) {
        int major, minor, patch;
        zmq_version (&major, &minor, &patch);
        fprintf(stderr, DEBUG_PREFIX_STR "0MQ version is %i.%i.%i\n",
                major, minor, patch);
    }

    s4u::Engine *e = new s4u::Engine(&argc,argv);

    pthread_t router;
    pthread_create(&router, NULL, TZmqServer::router_thread, 0);

    // Initialize the SimGrid world
    e->loadPlatform(platform_file.c_str());
    e->registerDefault(rsg_representative);
    e->loadDeployment(deployment_file.c_str());
    e->run();

    //wait for the router to close cleanly
    pthread_join(router, 0);
    return 0;
}
<|endoftext|>


<commit_before>//=====================================================================//
/*!	@file
	@brief	OpenGL カメラ・クラス（ヘッダー）
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "core/glcore.hpp"
#include "gl_fw/glutils.hpp"
#include "gl_fw/glcamera.hpp"
#include "gl_fw/glmatrix.hpp"

namespace gl {

	//-----------------------------------------------------------------//
	/*!
		@brief	update
	 */
	//-----------------------------------------------------------------//
	void camera::update()
	{
		using namespace vtx;

		core& core = core::get_instance();
		const device& dev = core.get_device();

		const spos& mspos = dev.get_locator().get_cursor();
///		const spos msdiff = mspos - mouse_pos_;
		mouse_pos_ = mspos;

		bool trans = dev.get_level(translate_key_);
		bool rotate = dev.get_level(rotate_key_);
		bool zoom = dev.get_level(zoom_key_);

		if(trans || rotate || zoom) {
			if(dev.get_positive(device::key::MOUSE_LEFT)) {
				mouse_left_first_pos_ = mspos;
				eye_first_ = eye_;
				target_first_ = target_;
				up_first_ = up_;
				quat_handle_first_ = quat_handle_;
				touch_ = true;
			}
		}

		if(touch_) {
			if(dev.get_level(device::key::MOUSE_LEFT)) {
				// 並行移動
				spos diff_pos = mspos - mouse_left_first_pos_;
				if(trans) {
					fvtx d;
					d.x = static_cast<float>(-diff_pos.x);
					d.y = 0.0f;
					d.z = static_cast<float>(diff_pos.y);
					d *= 0.01f;
					eye_ = eye_first_ + d;
					target_ = target_first_ + d;
				}

				// 回転
				if(rotate) {
					fpos d;
					d.x = static_cast<float>(diff_pos.x);
					d.y = static_cast<float>(diff_pos.y);
					vtx::fpos qh = d * -0.005f;
					qtx::fquat q;
					if(q.rot_xz(qh.x, qh.y, 1.0f)) {
						glmat_.at_current_matrix() = q.create_matrix();
						vtx::fvtx4 fv;
						matrixf::vertex_world(glmat_.get_current_matrix(), up_first_, fv);
						up_.set(fv.x,  fv.y,  fv.z);
						matrixf::vertex_world(glmat_.get_current_matrix(), eye_first_ - target_first_, fv);
						eye_ = target_first_ + vtx::fvtx(fv.x, fv.y, fv.z);
					}
				}

			// ズーム
				if(zoom) {
					vtx::fpos d(static_cast<float>(diff_pos.x), static_cast<float>(diff_pos.y));
					vtx::fvtx n;
					if(vtx::normalize(target_ - eye_, n)) {
						eye_ = eye_first_ + n * d.y * 0.01f;
					}
				}
			}
		} else {
			touch_ = false;
		}
	}

	//-----------------------------------------------------------------//
	/*!
		@brief	サービス
	 */
	//-----------------------------------------------------------------//
	void camera::service()
	{
		core& core = core::get_instance();
///		const device& dev = core.get_device();

		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		size_ = core.get_rect().size;
		aspect_ = static_cast<float>(size_.x) / static_cast<float>(size_.y);
		gl::gluPerspectivef(fov_, aspect_, z_near_, z_far_);
		gl::gluLookAtf(eye_.x, eye_.y, eye_.z,
			target_.x, target_.y, target_.z,
			up_.x, up_.y, up_.z);

		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
	}

}

<commit_msg>Update camera navigation<commit_after>//=====================================================================//
/*!	@file
	@brief	OpenGL カメラ・クラス（ヘッダー）
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "core/glcore.hpp"
#include "gl_fw/glutils.hpp"
#include "gl_fw/glcamera.hpp"
#include "gl_fw/glmatrix.hpp"

namespace gl {

	//-----------------------------------------------------------------//
	/*!
		@brief	update
	 */
	//-----------------------------------------------------------------//
	void camera::update()
	{
		using namespace vtx;

		core& core = core::get_instance();
		const device& dev = core.get_device();

		const spos& mspos = dev.get_locator().get_cursor();
///		const spos msdiff = mspos - mouse_pos_;
		mouse_pos_ = mspos;

		bool trans = dev.get_level(translate_key_);
		bool rotate = dev.get_level(rotate_key_);
		bool zoom = dev.get_level(zoom_key_);

		if(trans || rotate || zoom) {
			if(dev.get_positive(device::key::MOUSE_LEFT)) {
				mouse_left_first_pos_ = mspos;
				eye_first_ = eye_;
				target_first_ = target_;
				up_first_ = up_;
				quat_handle_first_ = quat_handle_;
				touch_ = true;
			}
		}

		if(touch_) {
			if(dev.get_level(device::key::MOUSE_LEFT)) {
				// 並行移動
				spos diff_pos = mspos - mouse_left_first_pos_;
				if(trans) {
					fvtx d;
					d.x = static_cast<float>(-diff_pos.x);
					d.y = 0.0f;
					d.z = static_cast<float>(diff_pos.y);
					d *= 0.01f;
					eye_ = eye_first_ + d;
					target_ = target_first_ + d;
				}

				// 回転
				if(rotate) {
					fpos d;
					d.x = static_cast<float>(diff_pos.x);
					d.y = static_cast<float>(diff_pos.y);
					vtx::fpos qh = d * -0.0025f;
					if(quat_.rot_xz(qh.x, qh.y, 1.0f)) {
						glmat_.at_current_matrix() = quat_.create_matrix();
						vtx::fvtx4 fv;
						matrixf::vertex_world(glmat_.get_current_matrix(), up_first_, fv);
						up_.set(fv.x,  fv.y,  fv.z);
						matrixf::vertex_world(glmat_.get_current_matrix(), eye_first_ - target_first_, fv);
						eye_ = target_first_ + vtx::fvtx(fv.x, fv.y, fv.z);
					}
				}

			// ズーム
				if(zoom) {
					vtx::fpos d(static_cast<float>(diff_pos.x), static_cast<float>(diff_pos.y));
					vtx::fvtx n;
					if(vtx::normalize(target_ - eye_, n)) {
						eye_ = eye_first_ + n * d.y * 0.01f;
					}
				}
			}
		} else {
			touch_ = false;
		}
	}

	//-----------------------------------------------------------------//
	/*!
		@brief	サービス
	 */
	//-----------------------------------------------------------------//
	void camera::service()
	{
		core& core = core::get_instance();
///		const device& dev = core.get_device();

		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		size_ = core.get_rect().size;
		aspect_ = static_cast<float>(size_.x) / static_cast<float>(size_.y);
		gl::gluPerspectivef(fov_, aspect_, z_near_, z_far_);
		gl::gluLookAtf(eye_.x, eye_.y, eye_.z,
			target_.x, target_.y, target_.z,
			up_.x, up_.y, up_.z);

		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
	}

}

<|endoftext|>


<commit_before>#include <silicium/absolute_path.hpp>
#include <silicium/asio/accepting_source.hpp>
#include <silicium/asio/connecting_observable.hpp>
#include <silicium/asio/connecting_source.hpp>
#include <silicium/asio/post_forwarder.hpp>
#include <silicium/asio/posting_observable.hpp>
#include <silicium/asio/process_output.hpp>
#include <silicium/asio/reading_observable.hpp>
#include <silicium/asio/socket_sink.hpp>
#include <silicium/asio/socket_source.hpp>
#include <silicium/asio/tcp_acceptor.hpp>
#include <silicium/asio/timer.hpp>
#include <silicium/asio/use_observable.hpp>
#include <silicium/asio/writing_observable.hpp>
#include <silicium/async_process.hpp>
#include <silicium/boost_threading.hpp>
#include <silicium/buffer.hpp>
#include <silicium/c_string.hpp>
#include <silicium/config.hpp>
#include <silicium/detail/argument_of.hpp>
#include <silicium/detail/basic_dynamic_library.hpp>
#include <silicium/detail/element_from_optional_like.hpp>
#include <silicium/detail/integer_sequence.hpp>
#include <silicium/detail/line_source.hpp>
#include <silicium/detail/proper_value_function.hpp>
#include <silicium/dynamic_library.hpp>
#include <silicium/error_code.hpp>
#include <silicium/error_or.hpp>
#include <silicium/exchange.hpp>
#include <silicium/explicit_operator_bool.hpp>
#include <silicium/fast_variant.hpp>
#include <silicium/file_handle.hpp>
#include <silicium/file_notification.hpp>
#include <silicium/file_size.hpp>
#include <silicium/flush.hpp>
#include <silicium/function.hpp>
#include <silicium/git/repository.hpp>
#include <silicium/html.hpp>
#include <silicium/http/generate_header.hpp>
#include <silicium/http/generate_request.hpp>
#include <silicium/http/generate_response.hpp>
#include <silicium/http/http.hpp>
#include <silicium/http/parse_request.hpp>
#include <silicium/http/parse_response.hpp>
#include <silicium/http/receive_request.hpp>
#include <silicium/http/request_parser_sink.hpp>
#include <silicium/http/uri.hpp>
#include <silicium/is_handle.hpp>
#include <silicium/iterator_range.hpp>
#include <silicium/linux/dynamic_library_impl.hpp>
#include <silicium/linux/inotify.hpp>
#include <silicium/linux/inotify_watch_descriptor.hpp>
#include <silicium/linux/process_handle.hpp>
#include <silicium/linux/single_directory_watcher.hpp>
#include <silicium/memory_range.hpp>
#include <silicium/noexcept_string.hpp>
#include <silicium/observable/bridge.hpp>
#include <silicium/observable/cache.hpp>
#include <silicium/observable/constant.hpp>
#include <silicium/observable/consume.hpp>
#include <silicium/observable/coroutine.hpp>
#include <silicium/observable/coroutine_generator.hpp>
#include <silicium/observable/deref_optional.hpp>
#include <silicium/observable/empty.hpp>
#include <silicium/observable/end.hpp>
#include <silicium/observable/enumerate.hpp>
#include <silicium/observable/erase_shared.hpp>
#include <silicium/observable/erase_unique.hpp>
#include <silicium/observable/erased_observer.hpp>
#include <silicium/observable/extensible_observer.hpp>
#include <silicium/observable/filter.hpp>
#include <silicium/observable/finite_state_machine.hpp>
#include <silicium/observable/flatten.hpp>
#include <silicium/observable/for_each.hpp>
#include <silicium/observable/function.hpp>
#include <silicium/observable/function_observer.hpp>
#include <silicium/observable/generator.hpp>
#include <silicium/observable/limited.hpp>
#include <silicium/observable/observable.hpp>
#include <silicium/observable/observer.hpp>
#include <silicium/observable/on_first.hpp>
#include <silicium/observable/ptr.hpp>
#include <silicium/observable/ready_future.hpp>
#include <silicium/observable/ref.hpp>
#include <silicium/observable/source.hpp>
#include <silicium/observable/spawn_coroutine.hpp>
#include <silicium/observable/spawn_observable.hpp>
#include <silicium/observable/take.hpp>
#include <silicium/observable/thread.hpp>
#include <silicium/observable/thread_generator.hpp>
#include <silicium/observable/total_consumer.hpp>
#include <silicium/observable/transform.hpp>
#include <silicium/observable/transform_if_initialized.hpp>
#include <silicium/observable/tuple.hpp>
#include <silicium/observable/variant.hpp>
#include <silicium/observable/virtualized.hpp>
#include <silicium/observable/while.hpp>
#include <silicium/observable/yield_context.hpp>
#include <silicium/open.hpp>
#include <silicium/optional.hpp>
#include <silicium/os_string.hpp>
#include <silicium/path.hpp>
#include <silicium/path_char.hpp>
#include <silicium/path_segment.hpp>
#include <silicium/posix/native_file_descriptor.hpp>
#include <silicium/posix/open.hpp>
#include <silicium/posix/pipe.hpp>
#include <silicium/posix/run_process.hpp>
#include <silicium/process_handle.hpp>
#include <silicium/process_parameters.hpp>
#include <silicium/ptr_adaptor.hpp>
#include <silicium/range_value.hpp>
#include <silicium/read_file.hpp>
#include <silicium/relative_path.hpp>
#include <silicium/run_process.hpp>
#include <silicium/single_directory_watcher.hpp>
#include <silicium/sink/buffering_sink.hpp>
#include <silicium/sink/container_buffer.hpp>
#include <silicium/sink/file_sink.hpp>
#include <silicium/sink/iterator_sink.hpp>
#include <silicium/sink/ostream_sink.hpp>
#include <silicium/sink/ptr_sink.hpp>
#include <silicium/sink/sink.hpp>
#include <silicium/sink/throwing_sink.hpp>
#include <silicium/sink/virtualized_sink.hpp>
#include <silicium/source/buffering_source.hpp>
#include <silicium/source/empty.hpp>
#include <silicium/source/enumerating_source.hpp>
#include <silicium/source/error_extracting_source.hpp>
#include <silicium/source/file_source.hpp>
#include <silicium/source/filter_source.hpp>
#include <silicium/source/generator_source.hpp>
#include <silicium/source/memory_source.hpp>
#include <silicium/source/observable_source.hpp>
#include <silicium/source/ptr_source.hpp>
#include <silicium/source/range_source.hpp>
#include <silicium/source/received_from_socket_source.hpp>
#include <silicium/source/single_source.hpp>
#include <silicium/source/source.hpp>
#include <silicium/source/throwing_source.hpp>
#include <silicium/source/transforming_source.hpp>
#include <silicium/source/virtualized_source.hpp>
#include <silicium/std_threading.hpp>
#include <silicium/then.hpp>
#include <silicium/to_shared.hpp>
#include <silicium/to_unique.hpp>
#include <silicium/utility.hpp>
#include <silicium/version.hpp>
#include <silicium/write_file.hpp>
#include <silicium/zlib/deflating_sink.hpp>
#include <silicium/zlib/inflating_sink.hpp>
#include <silicium/zlib/zlib.hpp>
<commit_msg>generate headers testers for Linux<commit_after>#include <silicium/absolute_path.hpp>
#include <silicium/asio/accepting_source.hpp>
#include <silicium/asio/connecting_observable.hpp>
#include <silicium/asio/connecting_source.hpp>
#include <silicium/asio/post_forwarder.hpp>
#include <silicium/asio/posting_observable.hpp>
#include <silicium/asio/process_output.hpp>
#include <silicium/asio/reading_observable.hpp>
#include <silicium/asio/socket_sink.hpp>
#include <silicium/asio/socket_source.hpp>
#include <silicium/asio/tcp_acceptor.hpp>
#include <silicium/asio/timer.hpp>
#include <silicium/asio/use_observable.hpp>
#include <silicium/asio/writing_observable.hpp>
#include <silicium/async_process.hpp>
#include <silicium/boost_threading.hpp>
#include <silicium/buffer.hpp>
#include <silicium/c_string.hpp>
#include <silicium/config.hpp>
#include <silicium/detail/argument_of.hpp>
#include <silicium/detail/basic_dynamic_library.hpp>
#include <silicium/detail/element_from_optional_like.hpp>
#include <silicium/detail/integer_sequence.hpp>
#include <silicium/detail/line_source.hpp>
#include <silicium/detail/proper_value_function.hpp>
#include <silicium/dynamic_library.hpp>
#include <silicium/error_code.hpp>
#include <silicium/error_or.hpp>
#include <silicium/exchange.hpp>
#include <silicium/explicit_operator_bool.hpp>
#include <silicium/fast_variant.hpp>
#include <silicium/file_handle.hpp>
#include <silicium/file_notification.hpp>
#include <silicium/file_size.hpp>
#include <silicium/flush.hpp>
#include <silicium/function.hpp>
#include <silicium/html.hpp>
#include <silicium/http/generate_header.hpp>
#include <silicium/http/generate_request.hpp>
#include <silicium/http/generate_response.hpp>
#include <silicium/http/http.hpp>
#include <silicium/http/parse_request.hpp>
#include <silicium/http/parse_response.hpp>
#include <silicium/http/receive_request.hpp>
#include <silicium/http/request_parser_sink.hpp>
#include <silicium/http/uri.hpp>
#include <silicium/is_handle.hpp>
#include <silicium/iterator_range.hpp>
#include <silicium/linux/dynamic_library_impl.hpp>
#include <silicium/linux/inotify.hpp>
#include <silicium/linux/inotify_watch_descriptor.hpp>
#include <silicium/linux/process_handle.hpp>
#include <silicium/linux/single_directory_watcher.hpp>
#include <silicium/memory_range.hpp>
#include <silicium/noexcept_string.hpp>
#include <silicium/observable/bridge.hpp>
#include <silicium/observable/cache.hpp>
#include <silicium/observable/constant.hpp>
#include <silicium/observable/consume.hpp>
#include <silicium/observable/coroutine.hpp>
#include <silicium/observable/coroutine_generator.hpp>
#include <silicium/observable/deref_optional.hpp>
#include <silicium/observable/empty.hpp>
#include <silicium/observable/end.hpp>
#include <silicium/observable/enumerate.hpp>
#include <silicium/observable/erase_shared.hpp>
#include <silicium/observable/erase_unique.hpp>
#include <silicium/observable/erased_observer.hpp>
#include <silicium/observable/extensible_observer.hpp>
#include <silicium/observable/filter.hpp>
#include <silicium/observable/finite_state_machine.hpp>
#include <silicium/observable/flatten.hpp>
#include <silicium/observable/for_each.hpp>
#include <silicium/observable/function.hpp>
#include <silicium/observable/function_observer.hpp>
#include <silicium/observable/generator.hpp>
#include <silicium/observable/limited.hpp>
#include <silicium/observable/observable.hpp>
#include <silicium/observable/observer.hpp>
#include <silicium/observable/on_first.hpp>
#include <silicium/observable/ptr.hpp>
#include <silicium/observable/ready_future.hpp>
#include <silicium/observable/ref.hpp>
#include <silicium/observable/source.hpp>
#include <silicium/observable/spawn_coroutine.hpp>
#include <silicium/observable/spawn_observable.hpp>
#include <silicium/observable/take.hpp>
#include <silicium/observable/thread.hpp>
#include <silicium/observable/thread_generator.hpp>
#include <silicium/observable/total_consumer.hpp>
#include <silicium/observable/transform.hpp>
#include <silicium/observable/transform_if_initialized.hpp>
#include <silicium/observable/tuple.hpp>
#include <silicium/observable/variant.hpp>
#include <silicium/observable/virtualized.hpp>
#include <silicium/observable/while.hpp>
#include <silicium/observable/yield_context.hpp>
#include <silicium/open.hpp>
#include <silicium/optional.hpp>
#include <silicium/os_string.hpp>
#include <silicium/path.hpp>
#include <silicium/path_char.hpp>
#include <silicium/path_segment.hpp>
#include <silicium/posix/native_file_descriptor.hpp>
#include <silicium/posix/open.hpp>
#include <silicium/posix/pipe.hpp>
#include <silicium/posix/run_process.hpp>
#include <silicium/process_handle.hpp>
#include <silicium/process_parameters.hpp>
#include <silicium/ptr_adaptor.hpp>
#include <silicium/range_value.hpp>
#include <silicium/read_file.hpp>
#include <silicium/relative_path.hpp>
#include <silicium/run_process.hpp>
#include <silicium/single_directory_watcher.hpp>
#include <silicium/sink/buffering_sink.hpp>
#include <silicium/sink/container_buffer.hpp>
#include <silicium/sink/file_sink.hpp>
#include <silicium/sink/iterator_sink.hpp>
#include <silicium/sink/ostream_sink.hpp>
#include <silicium/sink/ptr_sink.hpp>
#include <silicium/sink/sink.hpp>
#include <silicium/sink/throwing_sink.hpp>
#include <silicium/sink/virtualized_sink.hpp>
#include <silicium/source/buffering_source.hpp>
#include <silicium/source/empty.hpp>
#include <silicium/source/enumerating_source.hpp>
#include <silicium/source/error_extracting_source.hpp>
#include <silicium/source/file_source.hpp>
#include <silicium/source/filter_source.hpp>
#include <silicium/source/generator_source.hpp>
#include <silicium/source/memory_source.hpp>
#include <silicium/source/observable_source.hpp>
#include <silicium/source/ptr_source.hpp>
#include <silicium/source/range_source.hpp>
#include <silicium/source/received_from_socket_source.hpp>
#include <silicium/source/single_source.hpp>
#include <silicium/source/source.hpp>
#include <silicium/source/throwing_source.hpp>
#include <silicium/source/transforming_source.hpp>
#include <silicium/source/virtualized_source.hpp>
#include <silicium/std_threading.hpp>
#include <silicium/then.hpp>
#include <silicium/to_shared.hpp>
#include <silicium/to_unique.hpp>
#include <silicium/utility.hpp>
#include <silicium/version.hpp>
#include <silicium/write_file.hpp>
#include <silicium/zlib/deflating_sink.hpp>
#include <silicium/zlib/inflating_sink.hpp>
#include <silicium/zlib/zlib.hpp>
<|endoftext|>


<commit_before>#ifndef RFR_DATA_CONTAINER_HPP
#define RFR_DATA_CONTAINER_HPP

#include <vector>
#include <utility>

namespace rfr{ namespace data_containers{
/** \brief The interface for any data container with the minimal functionality
 *
 */
template <typename num_t=float, typename response_t=float, typename index_t=unsigned int>
class base{
  public:

	virtual ~base(){};

	/** \brief Function for accessing a single feature value, consistency checks might be omitted for performance
	 *
	 * \param feature_index The index of the feature requested
	 * \param sample_index The index of the data point.
	 *
	 * \return the stored value
	 */
	virtual num_t feature (index_t feature_index, index_t sample_index) const = 0;

	/** \brief member function for accessing the feature values of multiple data points at once, consistency checks might be omitted for performance
	 *
	 * \param feature_index The index of the feature requested
	 * \param sample_indices The indices of the data point.
	 *
	 * \return the stored values
	 */
	virtual std::vector<num_t> features (index_t feature_index, const std::vector<index_t> &sample_indices) const = 0;

	/** \brief member function to query a single response value, consistency checks might be omitted for performance
	 *
	 * \param sample_index the response of which data point
	 *
	 * \return the response value
	 */
	virtual response_t response (index_t sample_index) const = 0;
	virtual response_t predict_value(index_t sample_index) const = 0;  // Contains the values used to predict

	/** \brief function to access the weight attributed to a single data point
	 *
	 * \param sample_index which data point
	 *
	 * \return the weigth of that sample
	 */
	virtual num_t weight(index_t sample_index) const = 0;

	/** \brief method to add a single data point
	 *
	 * \param features a vector containing the features
	 * \param response the corresponding response value
	 * \param weight the weight of the data point
	 */
    virtual void add_data_point (std::vector<num_t> features, response_t response, num_t weight) = 0;
    virtual void add_data_point (std::vector<num_t> features, std::vector<response_t> response, num_t weight) = 0;

	/** \brief method to retrieve a data point
	 *
	 * \param index index of the datapoint to extract
	 *
	 * \return std::vector<num_t> the features of the data point
	 */
	virtual std::vector<num_t> retrieve_data_point (index_t index) const = 0;

	/** \brief query the type of a feature
	 *
	 * \param feature_index the index of the feature
	 *
	 * \return int type of the feature: 0 - numerical value (float or int); n>0 - categorical value with n different values {0,1,...,n-1}
	 */
	virtual index_t get_type_of_feature (index_t feature_index) const = 0;

	/** \brief query the type of the response
	 *
	 * \return index_t type of the response: 0 - numerical value (float or int); n>0 - categorical value with n different values {0,1,...,n-1}
	 */
	virtual index_t get_type_of_response () const = 0;

	/** \brief specifying the type of a feature
	 *
	 * \param feature_index the index of the feature whose type is specified
	 * \param feature_type the actual type (0 - numerical, value >0 catergorical with values from {0,1,...value-1}
	 */
	virtual void set_type_of_feature (index_t feature_index, index_t feature_type) = 0;

	/** \brief specifying the type of the response
	 *
	 * \param response_type the actual type (0 - numerical, value >0 catergorical with values from {0,1,...value-1}
	 */
	virtual void set_type_of_response (index_t response_type) = 0;

	/** \brief specifies the interval of allowed values for a feature
	 *
	 * To marginalize out certain feature dimensions using non-i.i.d. data, the numerical bounds
	 * on each variable have to be known. This only applies to numerical features.
	 *
	 * Note: The forest will not check if a datapoint is consistent with the specified bounds!
	 *
	 * \param feature_index feature_index the index of the feature
	 * \param min the smallest value for the feature
	 * \param max the largest value for the feature
	 */
	virtual void set_bounds_of_feature(index_t feature_index, num_t min, num_t max) = 0;

	/** \brief query the allowed interval for a feature; applies only to continuous variables
	 *
	 * \param feature_index the index of the feature
	 * \return std::pair<num_t,num_t> interval of allowed values
	 */
	virtual std::pair<num_t,num_t> get_bounds_of_feature(index_t feature_index) const = 0;

	/** \brief the number of features of every datapoint in the container */
	virtual index_t num_features() const = 0;
	/** \brief the number of data points in the container */
	virtual index_t num_data_points()  const = 0;
};

}} // namespace rfr::data_containers
#endif // RFR_DATA_CONTAINER_BASE_HPP
<commit_msg>MAINT documentation<commit_after>#ifndef RFR_DATA_CONTAINER_HPP
#define RFR_DATA_CONTAINER_HPP

#include <vector>
#include <utility>

namespace rfr{ namespace data_containers{
/** \brief The interface for any data container with the minimal functionality
 *
 */
template <typename num_t=float, typename response_t=float, typename index_t=unsigned int>
class base{
  public:

	virtual ~base(){};

	/** \brief Function for accessing a single feature value, consistency checks might be omitted for performance
	 *
	 * \param feature_index The index of the feature requested
	 * \param sample_index The index of the data point.
	 *
	 * \return the stored value
	 */
	virtual num_t feature (index_t feature_index, index_t sample_index) const = 0;

	/** \brief member function for accessing the feature values of multiple data points at once, consistency checks might be omitted for performance
	 *
	 * \param feature_index The index of the feature requested
	 * \param sample_indices The indices of the data point.
	 *
	 * \return the stored values
	 */
	virtual std::vector<num_t> features (index_t feature_index, const std::vector<index_t> &sample_indices) const = 0;

	/** \brief member function to query a single response value, consistency checks might be omitted for performance
	 *
	 * \param sample_index the response of which data point
	 *
	 * \return the response value
	 */
	virtual response_t response (index_t sample_index) const = 0;

    /** \brief member function to query a single response value, consistency checks might be omitted for performance
     *
     * \param sample_index the response of which data point
     *
     * \return the prediction value
     */
	virtual response_t predict_value(index_t sample_index) const = 0;  // Contains the values used to predict

	/** \brief function to access the weight attributed to a single data point
	 *
	 * \param sample_index which data point
	 *
	 * \return the weigth of that sample
	 */
	virtual num_t weight(index_t sample_index) const = 0;

	/** \brief method to add a single data point
	 *
	 * \param features a vector containing the features
	 * \param response the corresponding response value
	 * \param weight the weight of the data point
	 */
    virtual void add_data_point (std::vector<num_t> features, response_t response, num_t weight) = 0;

    /** \brief method to add a single data point
     *
     * \param features a vector containing the features
     * \param response the corresponding response vector. The first entry is the value used to fit the trees with,
     *        the second is used to predict.
     * \param weight the weight of the data point
     */
    virtual void add_data_point (std::vector<num_t> features, std::vector<response_t> response, num_t weight) = 0;

	/** \brief method to retrieve a data point
	 *
	 * \param index index of the datapoint to extract
	 *
	 * \return std::vector<num_t> the features of the data point
	 */
	virtual std::vector<num_t> retrieve_data_point (index_t index) const = 0;

	/** \brief query the type of a feature
	 *
	 * \param feature_index the index of the feature
	 *
	 * \return int type of the feature: 0 - numerical value (float or int); n>0 - categorical value with n different values {0,1,...,n-1}
	 */
	virtual index_t get_type_of_feature (index_t feature_index) const = 0;

	/** \brief query the type of the response
	 *
	 * \return index_t type of the response: 0 - numerical value (float or int); n>0 - categorical value with n different values {0,1,...,n-1}
	 */
	virtual index_t get_type_of_response () const = 0;

	/** \brief specifying the type of a feature
	 *
	 * \param feature_index the index of the feature whose type is specified
	 * \param feature_type the actual type (0 - numerical, value >0 catergorical with values from {0,1,...value-1}
	 */
	virtual void set_type_of_feature (index_t feature_index, index_t feature_type) = 0;

	/** \brief specifying the type of the response
	 *
	 * \param response_type the actual type (0 - numerical, value >0 catergorical with values from {0,1,...value-1}
	 */
	virtual void set_type_of_response (index_t response_type) = 0;

	/** \brief specifies the interval of allowed values for a feature
	 *
	 * To marginalize out certain feature dimensions using non-i.i.d. data, the numerical bounds
	 * on each variable have to be known. This only applies to numerical features.
	 *
	 * Note: The forest will not check if a datapoint is consistent with the specified bounds!
	 *
	 * \param feature_index feature_index the index of the feature
	 * \param min the smallest value for the feature
	 * \param max the largest value for the feature
	 */
	virtual void set_bounds_of_feature(index_t feature_index, num_t min, num_t max) = 0;

	/** \brief query the allowed interval for a feature; applies only to continuous variables
	 *
	 * \param feature_index the index of the feature
	 * \return std::pair<num_t,num_t> interval of allowed values
	 */
	virtual std::pair<num_t,num_t> get_bounds_of_feature(index_t feature_index) const = 0;

	/** \brief the number of features of every datapoint in the container */
	virtual index_t num_features() const = 0;
	/** \brief the number of data points in the container */
	virtual index_t num_data_points()  const = 0;
};

}} // namespace rfr::data_containers
#endif // RFR_DATA_CONTAINER_BASE_HPP
<|endoftext|>


<commit_before><commit_msg>framework: improve choreography context (#7855)<commit_after><|endoftext|>