<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * 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 St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_CONFIG_HELPERS_INCLUDED
#define MAPNIK_CONFIG_HELPERS_INCLUDED

#include <mapnik/enumeration.hpp>
#include <mapnik/config_error.hpp>
#include <mapnik/color_factory.hpp>

#include <boost/property_tree/ptree.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/optional.hpp>

#include <iostream>
#include <sstream>

namespace mapnik {

    template <typename T>
    T get(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute,
            const T & default_value);
    template <typename T>
    T get(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute);
    template <typename T>
    T get_own(const boost::property_tree::ptree & node, const std::string & name);
    template <typename T>
    boost::optional<T> get_optional(const boost::property_tree::ptree & node, const std::string & name,
                                    bool is_attribute);

    template <typename T>
    boost::optional<T> get_opt_attr( const boost::property_tree::ptree & node,
                                      const std::string & name)
    {
        return get_optional<T>( node, name, true);
    }

    template <typename T>
    boost::optional<T> get_opt_child( const boost::property_tree::ptree & node,
                                      const std::string & name)
    {
        return get_optional<T>( node, name, false);
    }

    template <typename T>
    T get_attr( const boost::property_tree::ptree & node, const std::string & name,
                const T & default_value )
    {
        return get<T>( node, name, true, default_value);
    }

    template <typename T>
    T get_attr( const boost::property_tree::ptree & node, const std::string & name )
    {
        return get<T>( node, name, true );
    }

    template <typename T>
    T get_css( const boost::property_tree::ptree & node, const std::string & name )
    {
        return get_own<T>( node, std::string("CSS parameter '") + name + "'");
    }

   // specialization for color type
   template <>
   inline color get_css (boost::property_tree::ptree const& node, std::string const& name)
   {
      std::string str = get_own<std::string>( node, std::string("CSS parameter '") + name + "'"); ;
      try
      {
         return mapnik::color_factory::from_string(str.c_str());
      }
      catch (...)
      {
         throw config_error(string("Failed to parse ") +

                            name + "'. Expected CSS color"  +
                            " but got '" + str + "'");
      }
   }

    template <typename charT, typename traits>
    std::basic_ostream<charT, traits> &
    operator << ( std::basic_ostream<charT, traits> & s, const mapnik::color & c )
    {
        std::string hex_string( c.to_hex_string() );
        s << hex_string;
        return s;
    }

    /** Helper for class bool */
    class boolean {
        public:
            boolean() {}
            boolean(bool b) : b_(b) {}
            boolean(const boolean & b) : b_(b.b_) {}

            operator bool() const
            {
                return b_;
            }
            boolean & operator = (const boolean & other)
            {
                b_ = other.b_;
                return * this;
            }
            boolean & operator = (bool other)
            {
                b_ = other;
                return * this;
            }
        private:
            bool b_;
    };

    /** Special stream input operator for boolean values */
    template <typename charT, typename traits>
    std::basic_istream<charT, traits> &
    operator >> ( std::basic_istream<charT, traits> & s, boolean & b )
    {
        std::string word;
        s >> word;
        if ( s )
        {
            if ( word == "true" || word == "yes" || word == "on" ||
                 word == "1")
            {
                b = true;
            }
            else if ( word == "false" || word == "no" || word == "off" ||
                      word == "0")
            {
                b = false;
            }
            else
            {
                s.setstate( std::ios::failbit );
            }
        }
        return s;
    }

    template <typename charT, typename traits>
    std::basic_ostream<charT, traits> &
    operator << ( std::basic_ostream<charT, traits> & s, const boolean & b )
    {
        s << ( b ? "true" : "false" );
        return s;
    }

    template <typename T>
    void set_attr(boost::property_tree::ptree & pt, const std::string & name, const T & v)
    {
        pt.put("<xmlattr>." + name, v);
    }

    /*
    template <>
    void set_attr<bool>(boost::property_tree::ptree & pt, const std::string & name, const bool & v)
    {
        pt.put("<xmlattr>." + name, boolean(v));
    }
    */

    class boolean;

    template <typename T>
    void set_css(boost::property_tree::ptree & pt, const std::string & name, const T & v)
    {
        boost::property_tree::ptree & css_node = pt.push_back(
            boost::property_tree::ptree::value_type("CssParameter",
            boost::property_tree::ptree()))->second;
        css_node.put("<xmlattr>.name", name );
        css_node.put_own( v );
    }

    template <typename T>
    struct name_trait
    {
        static std::string name()
        {
            return "<unknown>";
        }
        // missing name_trait for type ...
        // if you get here you are probably using a new type
        // in the XML file. Just add a name trait for the new
        // type below.
        BOOST_STATIC_ASSERT( sizeof(T) == 0 );
    };

#define DEFINE_NAME_TRAIT_WITH_NAME( type, type_name ) \
    template <> \
    struct name_trait<type> \
    { \
        static std::string name() { return std::string("type ") + type_name; } \
    };

#define DEFINE_NAME_TRAIT( type ) \
    DEFINE_NAME_TRAIT_WITH_NAME( type, #type );

    DEFINE_NAME_TRAIT( double );
    DEFINE_NAME_TRAIT( float );
    DEFINE_NAME_TRAIT( unsigned );
    DEFINE_NAME_TRAIT( boolean );
    DEFINE_NAME_TRAIT_WITH_NAME( int, "integer" );
    DEFINE_NAME_TRAIT_WITH_NAME( std::string, "string" );
    DEFINE_NAME_TRAIT_WITH_NAME( color, "color" );

    template <typename ENUM, int MAX>
    struct name_trait< mapnik::enumeration<ENUM, MAX> >
    {
        typedef enumeration<ENUM, MAX> Enum;

        static std::string name()
        {
            std::string value_list("one of [");
            for (unsigned i = 0; i < Enum::MAX; ++i)
            {
                value_list += Enum::get_string( i );
                if ( i + 1 < Enum::MAX ) value_list += ", ";
            }
            value_list += "]";

            return value_list;
        }
    };

    template <typename T>
    T get(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute,
          const T & default_value)
    {
        boost::optional<std::string> str;
        if (is_attribute)
        {
            str = node.get_optional<std::string>( std::string("<xmlattr>.") + name );
        }
        else
        {
            str = node.get_optional<std::string>(name );
        }

        if ( str ) {
            try
            {
                return boost::lexical_cast<T>( * str );
            }
            catch (const boost::bad_lexical_cast & )
            {
                throw config_error(string("Failed to parse ") +
                        (is_attribute ? "attribute" : "child node") + " '" +
                        name + "'. Expected " + name_trait<T>::name() +
                        " but got '" + *str + "'");
            }
        } else {
            return default_value;
        }
    }

   template <>
   inline color get(boost::property_tree::ptree const& node, std::string const& name, bool is_attribute,
             color const& default_value)
   {
      boost::optional<std::string> str;
      if (is_attribute)
      {
         str = node.get_optional<std::string>( std::string("<xmlattr>.") + name );
      }
      else
      {
         str = node.get_optional<std::string>(name );
      }

      if ( str )
      {
         try
         {
            return mapnik::color_factory::from_string((*str).c_str());
         }
         catch (...)
         {
            throw config_error(string("Failed to parse ") +
                               (is_attribute ? "attribute" : "child node") + " '" +
                               name + "'. Expected " + name_trait<color>::name() +
                               " but got '" + *str + "'");
         }
      }
      else
      {
         return default_value;
      }
   }

    template <typename T>
    T get(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute)
    {
        boost::optional<std::string> str;
        if (is_attribute)
        {
            str = node.get_optional<std::string>( std::string("<xmlattr>.") + name);
        }
        else
        {
            str = node.get_optional<std::string>(name);
        }

        if ( ! str ) {
            throw config_error(string("Required ") +
                    (is_attribute ? "attribute " : "child node ") +
                    "'" + name + "' is missing");
        }
        try
        {
            return boost::lexical_cast<T>( *str );
        }
        catch (const boost::bad_lexical_cast & )
        {
            throw config_error(string("Failed to parse ") +
                    (is_attribute ? "attribute" : "child node") + " '" +
                    name + "'. Expected " + name_trait<T>::name() +
                    " but got '" + *str + "'");
        }
    }

    template <typename T>
    T get_own(const boost::property_tree::ptree & node, const std::string & name)
    {
        try
        {
            return node.get_own<T>();
        }
        catch (...)
        {
            throw config_error(string("Failed to parse ") +
                    name + ". Expected " + name_trait<T>::name() +
                    " but got '" + node.data() + "'");
        }
    }

    template <typename T>
    boost::optional<T> get_optional(const boost::property_tree::ptree & node, const std::string & name,
                                    bool is_attribute)
    {
        boost::optional<std::string> str;
        if (is_attribute)
        {
            str = node.get_optional<std::string>( std::string("<xmlattr>.") + name);
        }
        else
        {
            str = node.get_optional<std::string>(name);
        }

        boost::optional<T> result;
        if ( str )
        {
           try
           {
              result = boost::lexical_cast<T>( *str );
           }
           catch (const boost::bad_lexical_cast &)
           {
              throw config_error(string("Failed to parse ") +
                                 (is_attribute ? "attribute" : "child node") + " '" +
                                 name + "'. Expected " + name_trait<T>::name() +
                                 " but got '" + *str + "'");
           }
        }

        return result;
    }
   //

   template <>
   inline boost::optional<color> get_optional(const boost::property_tree::ptree & node, const std::string & name,
                                       bool is_attribute)
    {
        boost::optional<std::string> str;
        if (is_attribute)
        {
            str = node.get_optional<std::string>( std::string("<xmlattr>.") + name);
        }
        else
        {
            str = node.get_optional<std::string>(name);
        }

        boost::optional<color> result;
        if ( str )
        {
           try
           {
              //result = boost::lexical_cast<T>( *str );
              result = mapnik::color_factory::from_string((*str).c_str());
           }
           catch (...)
           {
              throw config_error(string("Failed to parse ") +
                                 (is_attribute ? "attribute" : "child node") + " '" +
                                 name + "'. Expected " + name_trait<color>::name() +
                                 " but got '" + *str + "'");
           }
        }

        return result;
    }
} // end of namespace mapnik

#endif // MAPNIK_CONFIG_HELPERS_INCLUDED
<commit_msg>+ mapnik-write-colors-using-rgba-not-hex.patch (jonb)      When you use save_xml() the colors are written out in #RGB format   which can not represent alpha information. The patch makes it save using   the rgb()/rgba() strings.<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * 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 St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_CONFIG_HELPERS_INCLUDED
#define MAPNIK_CONFIG_HELPERS_INCLUDED

#include <mapnik/enumeration.hpp>
#include <mapnik/config_error.hpp>
#include <mapnik/color_factory.hpp>

#include <boost/property_tree/ptree.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/optional.hpp>

#include <iostream>
#include <sstream>

namespace mapnik {

    template <typename T>
    T get(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute,
            const T & default_value);
    template <typename T>
    T get(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute);
    template <typename T>
    T get_own(const boost::property_tree::ptree & node, const std::string & name);
    template <typename T>
    boost::optional<T> get_optional(const boost::property_tree::ptree & node, const std::string & name,
                                    bool is_attribute);

    template <typename T>
    boost::optional<T> get_opt_attr( const boost::property_tree::ptree & node,
                                      const std::string & name)
    {
        return get_optional<T>( node, name, true);
    }

    template <typename T>
    boost::optional<T> get_opt_child( const boost::property_tree::ptree & node,
                                      const std::string & name)
    {
        return get_optional<T>( node, name, false);
    }

    template <typename T>
    T get_attr( const boost::property_tree::ptree & node, const std::string & name,
                const T & default_value )
    {
        return get<T>( node, name, true, default_value);
    }

    template <typename T>
    T get_attr( const boost::property_tree::ptree & node, const std::string & name )
    {
        return get<T>( node, name, true );
    }

    template <typename T>
    T get_css( const boost::property_tree::ptree & node, const std::string & name )
    {
        return get_own<T>( node, std::string("CSS parameter '") + name + "'");
    }

   // specialization for color type
   template <>
   inline color get_css (boost::property_tree::ptree const& node, std::string const& name)
   {
      std::string str = get_own<std::string>( node, std::string("CSS parameter '") + name + "'"); ;
      try
      {
         return mapnik::color_factory::from_string(str.c_str());
      }
      catch (...)
      {
         throw config_error(string("Failed to parse ") +

                            name + "'. Expected CSS color"  +
                            " but got '" + str + "'");
      }
   }

    template <typename charT, typename traits>
    std::basic_ostream<charT, traits> &
    operator << ( std::basic_ostream<charT, traits> & s, const mapnik::color & c )
    {
        std::string hex_string( c.to_string() );
        s << hex_string;
        return s;
    }

    /** Helper for class bool */
    class boolean {
        public:
            boolean() {}
            boolean(bool b) : b_(b) {}
            boolean(const boolean & b) : b_(b.b_) {}

            operator bool() const
            {
                return b_;
            }
            boolean & operator = (const boolean & other)
            {
                b_ = other.b_;
                return * this;
            }
            boolean & operator = (bool other)
            {
                b_ = other;
                return * this;
            }
        private:
            bool b_;
    };

    /** Special stream input operator for boolean values */
    template <typename charT, typename traits>
    std::basic_istream<charT, traits> &
    operator >> ( std::basic_istream<charT, traits> & s, boolean & b )
    {
        std::string word;
        s >> word;
        if ( s )
        {
            if ( word == "true" || word == "yes" || word == "on" ||
                 word == "1")
            {
                b = true;
            }
            else if ( word == "false" || word == "no" || word == "off" ||
                      word == "0")
            {
                b = false;
            }
            else
            {
                s.setstate( std::ios::failbit );
            }
        }
        return s;
    }

    template <typename charT, typename traits>
    std::basic_ostream<charT, traits> &
    operator << ( std::basic_ostream<charT, traits> & s, const boolean & b )
    {
        s << ( b ? "true" : "false" );
        return s;
    }

    template <typename T>
    void set_attr(boost::property_tree::ptree & pt, const std::string & name, const T & v)
    {
        pt.put("<xmlattr>." + name, v);
    }

    /*
    template <>
    void set_attr<bool>(boost::property_tree::ptree & pt, const std::string & name, const bool & v)
    {
        pt.put("<xmlattr>." + name, boolean(v));
    }
    */

    class boolean;

    template <typename T>
    void set_css(boost::property_tree::ptree & pt, const std::string & name, const T & v)
    {
        boost::property_tree::ptree & css_node = pt.push_back(
            boost::property_tree::ptree::value_type("CssParameter",
            boost::property_tree::ptree()))->second;
        css_node.put("<xmlattr>.name", name );
        css_node.put_own( v );
    }

    template <typename T>
    struct name_trait
    {
        static std::string name()
        {
            return "<unknown>";
        }
        // missing name_trait for type ...
        // if you get here you are probably using a new type
        // in the XML file. Just add a name trait for the new
        // type below.
        BOOST_STATIC_ASSERT( sizeof(T) == 0 );
    };

#define DEFINE_NAME_TRAIT_WITH_NAME( type, type_name ) \
    template <> \
    struct name_trait<type> \
    { \
        static std::string name() { return std::string("type ") + type_name; } \
    };

#define DEFINE_NAME_TRAIT( type ) \
    DEFINE_NAME_TRAIT_WITH_NAME( type, #type );

    DEFINE_NAME_TRAIT( double );
    DEFINE_NAME_TRAIT( float );
    DEFINE_NAME_TRAIT( unsigned );
    DEFINE_NAME_TRAIT( boolean );
    DEFINE_NAME_TRAIT_WITH_NAME( int, "integer" );
    DEFINE_NAME_TRAIT_WITH_NAME( std::string, "string" );
    DEFINE_NAME_TRAIT_WITH_NAME( color, "color" );

    template <typename ENUM, int MAX>
    struct name_trait< mapnik::enumeration<ENUM, MAX> >
    {
        typedef enumeration<ENUM, MAX> Enum;

        static std::string name()
        {
            std::string value_list("one of [");
            for (unsigned i = 0; i < Enum::MAX; ++i)
            {
                value_list += Enum::get_string( i );
                if ( i + 1 < Enum::MAX ) value_list += ", ";
            }
            value_list += "]";

            return value_list;
        }
    };

    template <typename T>
    T get(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute,
          const T & default_value)
    {
        boost::optional<std::string> str;
        if (is_attribute)
        {
            str = node.get_optional<std::string>( std::string("<xmlattr>.") + name );
        }
        else
        {
            str = node.get_optional<std::string>(name );
        }

        if ( str ) {
            try
            {
                return boost::lexical_cast<T>( * str );
            }
            catch (const boost::bad_lexical_cast & )
            {
                throw config_error(string("Failed to parse ") +
                        (is_attribute ? "attribute" : "child node") + " '" +
                        name + "'. Expected " + name_trait<T>::name() +
                        " but got '" + *str + "'");
            }
        } else {
            return default_value;
        }
    }

   template <>
   inline color get(boost::property_tree::ptree const& node, std::string const& name, bool is_attribute,
             color const& default_value)
   {
      boost::optional<std::string> str;
      if (is_attribute)
      {
         str = node.get_optional<std::string>( std::string("<xmlattr>.") + name );
      }
      else
      {
         str = node.get_optional<std::string>(name );
      }

      if ( str )
      {
         try
         {
            return mapnik::color_factory::from_string((*str).c_str());
         }
         catch (...)
         {
            throw config_error(string("Failed to parse ") +
                               (is_attribute ? "attribute" : "child node") + " '" +
                               name + "'. Expected " + name_trait<color>::name() +
                               " but got '" + *str + "'");
         }
      }
      else
      {
         return default_value;
      }
   }

    template <typename T>
    T get(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute)
    {
        boost::optional<std::string> str;
        if (is_attribute)
        {
            str = node.get_optional<std::string>( std::string("<xmlattr>.") + name);
        }
        else
        {
            str = node.get_optional<std::string>(name);
        }

        if ( ! str ) {
            throw config_error(string("Required ") +
                    (is_attribute ? "attribute " : "child node ") +
                    "'" + name + "' is missing");
        }
        try
        {
            return boost::lexical_cast<T>( *str );
        }
        catch (const boost::bad_lexical_cast & )
        {
            throw config_error(string("Failed to parse ") +
                    (is_attribute ? "attribute" : "child node") + " '" +
                    name + "'. Expected " + name_trait<T>::name() +
                    " but got '" + *str + "'");
        }
    }

    template <typename T>
    T get_own(const boost::property_tree::ptree & node, const std::string & name)
    {
        try
        {
            return node.get_own<T>();
        }
        catch (...)
        {
            throw config_error(string("Failed to parse ") +
                    name + ". Expected " + name_trait<T>::name() +
                    " but got '" + node.data() + "'");
        }
    }

    template <typename T>
    boost::optional<T> get_optional(const boost::property_tree::ptree & node, const std::string & name,
                                    bool is_attribute)
    {
        boost::optional<std::string> str;
        if (is_attribute)
        {
            str = node.get_optional<std::string>( std::string("<xmlattr>.") + name);
        }
        else
        {
            str = node.get_optional<std::string>(name);
        }

        boost::optional<T> result;
        if ( str )
        {
           try
           {
              result = boost::lexical_cast<T>( *str );
           }
           catch (const boost::bad_lexical_cast &)
           {
              throw config_error(string("Failed to parse ") +
                                 (is_attribute ? "attribute" : "child node") + " '" +
                                 name + "'. Expected " + name_trait<T>::name() +
                                 " but got '" + *str + "'");
           }
        }

        return result;
    }
   //

   template <>
   inline boost::optional<color> get_optional(const boost::property_tree::ptree & node, const std::string & name,
                                       bool is_attribute)
    {
        boost::optional<std::string> str;
        if (is_attribute)
        {
            str = node.get_optional<std::string>( std::string("<xmlattr>.") + name);
        }
        else
        {
            str = node.get_optional<std::string>(name);
        }

        boost::optional<color> result;
        if ( str )
        {
           try
           {
              //result = boost::lexical_cast<T>( *str );
              result = mapnik::color_factory::from_string((*str).c_str());
           }
           catch (...)
           {
              throw config_error(string("Failed to parse ") +
                                 (is_attribute ? "attribute" : "child node") + " '" +
                                 name + "'. Expected " + name_trait<color>::name() +
                                 " but got '" + *str + "'");
           }
        }

        return result;
    }
} // end of namespace mapnik

#endif // MAPNIK_CONFIG_HELPERS_INCLUDED
<|endoftext|>


<commit_before>#ifndef NO_RESUME_HPP
#define NO_RESUME_HPP

#include <chrono>
#include <utility>

#include "caf/exception.hpp"
#include "caf/exit_reason.hpp"
#include "caf/policy/resume_policy.hpp"

namespace caf {
namespace policy {

class no_resume {
 public:
  template <class Base, class Derived>
  struct mixin : Base {
    template <class... Ts>
    mixin(Ts&&... args) : Base(std::forward<Ts>(args)...), m_hidden(true) {
      // nop
    }

    void attach_to_scheduler() {
      this->ref();
    }

    void detach_from_scheduler() {
      this->deref();
    }

    resumable::resume_result resume(execution_unit*, size_t) {
      auto done_cb = [=](uint32_t reason) {
        this->planned_exit_reason(reason);
        this->on_exit();
        this->cleanup(reason);
      };
      try {
        this->act();
        done_cb(exit_reason::normal);
      }
      catch (actor_exited& e) {
        done_cb(e.reason());
      }
      catch (...) {
        done_cb(exit_reason::unhandled_exception);
      }
      return resumable::done;
    }

    bool m_hidden;
  };

  template <class Actor>
  void await_ready(Actor* self) {
    self->await_data();
  }
};

} // namespace policy
} // namespace caf

#endif // NO_RESUME_HPP
<commit_msg>Fix possible issue w/ exception in no_resume<commit_after>#ifndef NO_RESUME_HPP
#define NO_RESUME_HPP

#include <chrono>
#include <utility>

#include "caf/exception.hpp"
#include "caf/exit_reason.hpp"
#include "caf/policy/resume_policy.hpp"

namespace caf {
namespace policy {

class no_resume {
 public:
  template <class Base, class Derived>
  struct mixin : Base {
    template <class... Ts>
    mixin(Ts&&... args) : Base(std::forward<Ts>(args)...), m_hidden(true) {
      // nop
    }

    void attach_to_scheduler() {
      this->ref();
    }

    void detach_from_scheduler() {
      this->deref();
    }

    resumable::resume_result resume(execution_unit*, size_t) {
      uint32_t rsn = exit_reason::normal;
      try {
        this->act();
      }
      catch (actor_exited& e) {
        rsn = e.reason();
      }
      catch (...) {
        rsn = exit_reason::unhandled_exception;
      }
      this->planned_exit_reason(rsn);
      try {
        this->on_exit();
      }
      catch (...) {
        // simply ignore exception
      }
      // exit reason might have been changed by on_exit()
      this->cleanup(this->planned_exit_reason());
      return resumable::done;
    }

    bool m_hidden;
  };

  template <class Actor>
  void await_ready(Actor* self) {
    self->await_data();
  }
};

} // namespace policy
} // namespace caf

#endif // NO_RESUME_HPP
<|endoftext|>


<commit_before>#ifndef __GLOBALS_HPP_INCLUDED
#define __GLOBALS_HPP_INCLUDED

#include <string>
#include <vector>
#include <stdint.h> // uint32_t etc.

// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h>
#endif

// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp>
#endif

#ifndef WINDOW_WIDTH
#define WINDOW_WIDTH (1600.0f)
#endif

#ifndef WINDOW_HEIGHT
#define WINDOW_HEIGHT (900.0f)
#endif

#ifndef ASPECT_RATIO
#define ASPECT_RATIO (WINDOW_WIDTH / WINDOW_HEIGHT)
#endif

#ifndef PI
#define PI 3.14159265359f
#endif

#ifndef EARTH_RADIUS
#define EARTH_RADIUS 6371000.0f
#endif

#ifndef TEXT_SIZE
#define TEXT_SIZE 40
#endif

#ifndef FONT_SIZE
#define FONT_SIZE 16
#endif

#ifndef MAX_FPS
#define MAX_FPS 60
#endif

extern glm::vec3 position;
extern GLfloat gravity;
extern bool inFlightmode;
extern GLfloat fallSpeed;
extern double horizontalAngle;
extern double verticalAngle;
extern GLfloat initialFoV;
extern double earth_radius;
extern bool hasMouseEverMoved;
extern bool is_invert_mouse_in_use;
extern bool is_key_I_released;
extern bool is_world_loaded;                 // no more than one world object can be loaded. TODO: check that no more than one world is loaded!
extern bool is_world_spherical;

typedef struct
{
#ifdef __gnu_linux__
    void *world_pointer = NULL;              // pointer to the world (draw list).
#endif
#ifdef _WIN32
    void *world_pointer;                     // pointer to the world (draw list).
#endif
    std::string vertex_shader;               // filename of vertex shader.
    std::string fragment_shader;             // filename of fragment shader.
} ShaderStruct;

#ifdef __gnu_linux__
#define SHADERSTRUCT(x) \
ShaderStruct x
#endif
#ifdef _WIN32
#define SHADERSTRUCT(x) \
ShaderStruct x; x.world_pointer = NULL
#endif

typedef struct
{
#ifdef __gnu_linux__
    void *shader_pointer = NULL;             // pointer to the shader.
#endif
#ifdef _WIN32
    void *shader_pointer;                    // pointer to the shader.
#endif
    std::string texture_file_format;         // type of the texture file. supported file formats so far: `"bmp"`/`"BMP"`, `"dds"`/`"DDS"`.
    std::string texture_filename;            // filename of the model file.
    std::string image_path;
} TextureStruct;

#ifdef __gnu_linux__
#define TEXTURESTRUCT(x) \
TextureStruct x
#endif
#ifdef _WIN32
#define TEXTURESTRUCT(x) \
TextureStruct x; x.shader_pointer = NULL
#endif

typedef struct
{
    GLuint nodeID;
    void *graph_pointer = NULL;
    glm::vec3 coordinate_vector;
    std::vector<uint32_t> neighbor_nodeIDs;
} NodeStruct;

typedef struct
{
    glm::vec3 coordinate_vector;     // coordinate vector.
    GLfloat rotate_angle = NAN;      // rotate angle.
    glm::vec3 rotate_vector;         // rotate vector.
    glm::vec3 translate_vector;      // translate vector.
    glm::mat4 model_matrix;          // model matrix.
    glm::mat4 MVP_matrix;            // model view projection matrix.
    void *species_pointer = NULL;    // pointer to the species.
} ObjectStruct;

typedef struct
{
    // used for all files (for all species).
    void *texture_pointer = NULL;            // pointer to the texture object.
    std::string model_file_format;           // type of the model file. supported file formats so far: `"bmp"`/`"BMP"`, `"obj"`/`"OBJ"`.
                                             // TODO: add support for `"SRTM"`.
    std::string vertex_shader;               // filename of vertex shader.
    std::string fragment_shader;             // filename of fragment shader.
    glm::vec3 lightPos;                      // light position.
    std::vector<ObjectStruct> object_vector; // vector of individual objects of this species.
    bool is_world = false;                   // worlds currently do not rotate nor translate.
    std::string coordinate_system;           // used only for worlds (`is_world` == `true`). valid values: `"cartesian"`.
                                             // TODO: add support for `"spherical"`. `"spherical"` is used eg. in SRTM heightmaps.
    double world_radius = NAN;               // radius of sea level in meters. used only for worlds.

    // for `"bmp"` model files.
    std::string model_filename;              // filename of the model file.
    std::string color_channel;               // color channel to use for altitude data.
} SpeciesStruct;

typedef struct
{
    GLuint screen_width;
    GLuint screen_height;
    GLuint x;
    GLuint y;
    GLuint text_size;
    GLuint font_size;
    const char *text;
    const char *char_font_texture_file_format;
    const char *horizontal_alignment;
    const char *vertical_alignment;
} PrintingStruct;

typedef struct
{
    double rho;
    double theta;
    double phi;
} SphericalCoordinatesStruct;

typedef struct
{
    double southern_latitude;
    double northern_latitude;
    double western_longitude;
    double eastern_longitude;
} SphericalWorldStruct;

extern SphericalCoordinatesStruct spherical_position;

#endif
<commit_msg>`#define NODESTRUCT(x)`.<commit_after>#ifndef __GLOBALS_HPP_INCLUDED
#define __GLOBALS_HPP_INCLUDED

#include <string>
#include <vector>
#include <stdint.h> // uint32_t etc.

// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h>
#endif

// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp>
#endif

#ifndef WINDOW_WIDTH
#define WINDOW_WIDTH (1600.0f)
#endif

#ifndef WINDOW_HEIGHT
#define WINDOW_HEIGHT (900.0f)
#endif

#ifndef ASPECT_RATIO
#define ASPECT_RATIO (WINDOW_WIDTH / WINDOW_HEIGHT)
#endif

#ifndef PI
#define PI 3.14159265359f
#endif

#ifndef EARTH_RADIUS
#define EARTH_RADIUS 6371000.0f
#endif

#ifndef TEXT_SIZE
#define TEXT_SIZE 40
#endif

#ifndef FONT_SIZE
#define FONT_SIZE 16
#endif

#ifndef MAX_FPS
#define MAX_FPS 60
#endif

extern glm::vec3 position;
extern GLfloat gravity;
extern bool inFlightmode;
extern GLfloat fallSpeed;
extern double horizontalAngle;
extern double verticalAngle;
extern GLfloat initialFoV;
extern double earth_radius;
extern bool hasMouseEverMoved;
extern bool is_invert_mouse_in_use;
extern bool is_key_I_released;
extern bool is_world_loaded;                 // no more than one world object can be loaded. TODO: check that no more than one world is loaded!
extern bool is_world_spherical;

typedef struct
{
#ifdef __gnu_linux__
    void *world_pointer = NULL;              // pointer to the world (draw list).
#endif
#ifdef _WIN32
    void *world_pointer;                     // pointer to the world (draw list).
#endif
    std::string vertex_shader;               // filename of vertex shader.
    std::string fragment_shader;             // filename of fragment shader.
} ShaderStruct;

#ifdef __gnu_linux__
#define SHADERSTRUCT(x) \
ShaderStruct x
#endif
#ifdef _WIN32
#define SHADERSTRUCT(x) \
ShaderStruct x; x.world_pointer = NULL
#endif

typedef struct
{
#ifdef __gnu_linux__
    void *shader_pointer = NULL;             // pointer to the shader.
#endif
#ifdef _WIN32
    void *shader_pointer;                    // pointer to the shader.
#endif
    std::string texture_file_format;         // type of the texture file. supported file formats so far: `"bmp"`/`"BMP"`, `"dds"`/`"DDS"`.
    std::string texture_filename;            // filename of the model file.
    std::string image_path;
} TextureStruct;

#ifdef __gnu_linux__
#define TEXTURESTRUCT(x) \
TextureStruct x
#endif
#ifdef _WIN32
#define TEXTURESTRUCT(x) \
TextureStruct x; x.shader_pointer = NULL
#endif

typedef struct
{
    GLuint nodeID;
#ifdef __gnu_linux__
    void *graph_pointer = NULL;
#endif
#ifdef _WIN32
    void *graph_pointer;
#endif
    glm::vec3 coordinate_vector;
    std::vector<uint32_t> neighbor_nodeIDs;
} NodeStruct;

#ifdef __gnu_linux__
#define NODESTRUCT(x) \
NodeStruct x
#endif
#ifdef _WIN32
#define NODESTRUCT(x) \
NodeStruct x; x.graph_pointer = NULL
#endif

typedef struct
{
    glm::vec3 coordinate_vector;     // coordinate vector.
    GLfloat rotate_angle = NAN;      // rotate angle.
    glm::vec3 rotate_vector;         // rotate vector.
    glm::vec3 translate_vector;      // translate vector.
    glm::mat4 model_matrix;          // model matrix.
    glm::mat4 MVP_matrix;            // model view projection matrix.
    void *species_pointer = NULL;    // pointer to the species.
} ObjectStruct;

typedef struct
{
    // used for all files (for all species).
    void *texture_pointer = NULL;            // pointer to the texture object.
    std::string model_file_format;           // type of the model file. supported file formats so far: `"bmp"`/`"BMP"`, `"obj"`/`"OBJ"`.
                                             // TODO: add support for `"SRTM"`.
    std::string vertex_shader;               // filename of vertex shader.
    std::string fragment_shader;             // filename of fragment shader.
    glm::vec3 lightPos;                      // light position.
    std::vector<ObjectStruct> object_vector; // vector of individual objects of this species.
    bool is_world = false;                   // worlds currently do not rotate nor translate.
    std::string coordinate_system;           // used only for worlds (`is_world` == `true`). valid values: `"cartesian"`.
                                             // TODO: add support for `"spherical"`. `"spherical"` is used eg. in SRTM heightmaps.
    double world_radius = NAN;               // radius of sea level in meters. used only for worlds.

    // for `"bmp"` model files.
    std::string model_filename;              // filename of the model file.
    std::string color_channel;               // color channel to use for altitude data.
} SpeciesStruct;

typedef struct
{
    GLuint screen_width;
    GLuint screen_height;
    GLuint x;
    GLuint y;
    GLuint text_size;
    GLuint font_size;
    const char *text;
    const char *char_font_texture_file_format;
    const char *horizontal_alignment;
    const char *vertical_alignment;
} PrintingStruct;

typedef struct
{
    double rho;
    double theta;
    double phi;
} SphericalCoordinatesStruct;

typedef struct
{
    double southern_latitude;
    double northern_latitude;
    double western_longitude;
    double eastern_longitude;
} SphericalWorldStruct;

extern SphericalCoordinatesStruct spherical_position;

#endif
<|endoftext|>


<commit_before>// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in
// the main distribution directory for license terms and copyright or visit
// https://github.com/actor-framework/actor-framework/blob/master/LICENSE.

#pragma once

#include <vector>

#include "caf/actor.hpp"
#include "caf/actor_addr.hpp"
#include "caf/actor_cast.hpp"
#include "caf/check_typed_input.hpp"
#include "caf/detail/core_export.hpp"
#include "caf/intrusive_ptr.hpp"
#include "caf/message.hpp"
#include "caf/message_id.hpp"
#include "caf/response_type.hpp"

namespace caf {

/// Enables actors to delay a response message by capturing the context of a
/// request message. This is particularly useful when an actor needs to
/// communicate to other actors in order to fulfill a request for a client.
class CAF_CORE_EXPORT response_promise {
public:
  // -- member types -----------------------------------------------------------

  using forwarding_stack = std::vector<strong_actor_ptr>;

  // -- constructors, destructors, and assignment operators --------------------

  response_promise(strong_actor_ptr self, strong_actor_ptr source,
                   forwarding_stack stages, message_id id);

  response_promise(strong_actor_ptr self, mailbox_element& src);

  response_promise() = default;

  response_promise(response_promise&&) = default;

  response_promise(const response_promise&) = default;

  response_promise& operator=(response_promise&&) = default;

  response_promise& operator=(const response_promise&) = default;

  [[deprecated("use the default constructor instead")]] response_promise(none_t)
    : response_promise() {
    // nop
  }

  // -- properties -------------------------------------------------------------

  /// Returns whether this response promise replies to an asynchronous message.
  bool async() const noexcept;

  /// Queries whether this promise is a valid promise that is not satisfied yet.
  bool pending() const noexcept;

  /// Returns the source of the corresponding request.
  strong_actor_ptr source() const noexcept;

  /// Returns the remaining stages for the corresponding request.
  forwarding_stack stages() const;

  /// Returns the actor that will receive the response, i.e.,
  /// `stages().front()` if `!stages().empty()` or `source()` otherwise.
  strong_actor_ptr next() const noexcept;

  /// Returns the message ID of the corresponding request.
  message_id id() const noexcept;

  // -- delivery ---------------------------------------------------------------

  /// Satisfies the promise by sending the given message.
  /// @note Drops empty messages silently when responding to an asynchronous
  ///       request message, i.e., if `async() == true`.
  /// @post `pending() == false`
  void deliver(message msg);

  /// Satisfies the promise by sending an error message.
  /// @post `pending() == false`
  void deliver(error x);

  /// Satisfies the promise by sending an empty message.
  /// @note Sends no message if the request message was asynchronous, i.e., if
  ///       `async() == true`.
  /// @post `pending() == false`
  void deliver();

  /// Satisfies the promise by sending an empty message.
  /// @note Sends no message if the request message was asynchronous, i.e., if
  ///       `async() == true`.
  /// @post `pending() == false`
  void deliver(unit_t) {
    deliver();
  }

  /// Satisfies the promise by sending `make_message(xs...)`.
  /// @post `pending() == false`
  template <class... Ts>
  void deliver(Ts... xs) {
    using arg_types = detail::type_list<Ts...>;
    static_assert(!detail::tl_exists<arg_types, detail::is_result>::value,
                  "delivering a result<T> is not supported");
    static_assert(!detail::tl_exists<arg_types, detail::is_expected>::value,
                  "mixing expected<T> with regular values is not supported");
    if (pending()) {
      state_->deliver_impl(make_message(std::move(xs)...));
      state_.reset();
    }
  }

  /// Satisfies the promise by sending the content of `x`, i.e., either a value
  /// of type `T` or an @ref error.
  /// @post `pending() == false`
  template <class T>
  void deliver(expected<T> x) {
    if (pending()) {
      if (x) {
        if constexpr (std::is_same<T, void>::value
                      || std::is_same<T, unit_t>::value)
          state_->deliver_impl(make_message());
        else
          state_->deliver_impl(make_message(std::move(*x)));
      } else {
        state_->deliver_impl(make_message(std::move(x.error())));
      }
      state_.reset();
    }
  }

  // -- delegation -------------------------------------------------------------

  /// Satisfies the promise by delegating to another actor.
  /// @post `pending() == false`
  template <message_priority P = message_priority::normal, class Handle = actor,
            class... Ts>
  delegated_response_type_t<
    typename Handle::signatures,
    detail::implicit_conversions_t<typename std::decay<Ts>::type>...>
  delegate(const Handle& dest, Ts&&... xs) {
    static_assert(sizeof...(Ts) > 0, "nothing to delegate");
    using token = detail::type_list<typename detail::implicit_conversions<
      typename std::decay<Ts>::type>::type...>;
    static_assert(response_type_unbox<signatures_of_t<Handle>, token>::valid,
                  "receiver does not accept given message");
    if (pending()) {
      if constexpr (P == message_priority::high)
        state_->id = state_->id.with_high_priority();
      if constexpr (std::is_same<detail::type_list<message>,
                                 detail::type_list<std::decay_t<Ts>...>>::value)
        state_->delegate_impl(actor_cast<abstract_actor*>(dest),
                              std::forward<Ts>(xs)...);
      else
        state_->delegate_impl(actor_cast<abstract_actor*>(dest),
                              make_message(std::forward<Ts>(xs)...));
      state_.reset();
    }
    return {};
  }

private:
  // Note: response promises must remain local to their owner. Hence, we don't
  //       need a thread-safe reference count for the state.
  class state {
  public:
    state() = default;
    state(const state&) = delete;
    state& operator=(const state&) = delete;
    ~state();

    void cancel();

    void deliver_impl(message msg);

    void delegate_impl(abstract_actor* receiver, message msg);

    mutable size_t ref_count = 1;
    strong_actor_ptr self;
    strong_actor_ptr source;
    forwarding_stack stages;
    message_id id;

    friend void intrusive_ptr_add_ref(const state* ptr) {
      ++ptr->ref_count;
    }

    friend void intrusive_ptr_release(const state* ptr) {
      if (--ptr->ref_count == 0)
        delete ptr;
    }
  };

  intrusive_ptr<state> state_;
};

} // namespace caf
<commit_msg>Fix linker issue on MSVC<commit_after>// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in
// the main distribution directory for license terms and copyright or visit
// https://github.com/actor-framework/actor-framework/blob/master/LICENSE.

#pragma once

#include <vector>

#include "caf/actor.hpp"
#include "caf/actor_addr.hpp"
#include "caf/actor_cast.hpp"
#include "caf/check_typed_input.hpp"
#include "caf/detail/core_export.hpp"
#include "caf/intrusive_ptr.hpp"
#include "caf/message.hpp"
#include "caf/message_id.hpp"
#include "caf/response_type.hpp"

namespace caf {

/// Enables actors to delay a response message by capturing the context of a
/// request message. This is particularly useful when an actor needs to
/// communicate to other actors in order to fulfill a request for a client.
class CAF_CORE_EXPORT response_promise {
public:
  // -- member types -----------------------------------------------------------

  using forwarding_stack = std::vector<strong_actor_ptr>;

  // -- constructors, destructors, and assignment operators --------------------

  response_promise(strong_actor_ptr self, strong_actor_ptr source,
                   forwarding_stack stages, message_id id);

  response_promise(strong_actor_ptr self, mailbox_element& src);

  response_promise() = default;

  response_promise(response_promise&&) = default;

  response_promise(const response_promise&) = default;

  response_promise& operator=(response_promise&&) = default;

  response_promise& operator=(const response_promise&) = default;

  [[deprecated("use the default constructor instead")]] response_promise(none_t)
    : response_promise() {
    // nop
  }

  // -- properties -------------------------------------------------------------

  /// Returns whether this response promise replies to an asynchronous message.
  bool async() const noexcept;

  /// Queries whether this promise is a valid promise that is not satisfied yet.
  bool pending() const noexcept;

  /// Returns the source of the corresponding request.
  strong_actor_ptr source() const noexcept;

  /// Returns the remaining stages for the corresponding request.
  forwarding_stack stages() const;

  /// Returns the actor that will receive the response, i.e.,
  /// `stages().front()` if `!stages().empty()` or `source()` otherwise.
  strong_actor_ptr next() const noexcept;

  /// Returns the message ID of the corresponding request.
  message_id id() const noexcept;

  // -- delivery ---------------------------------------------------------------

  /// Satisfies the promise by sending the given message.
  /// @note Drops empty messages silently when responding to an asynchronous
  ///       request message, i.e., if `async() == true`.
  /// @post `pending() == false`
  void deliver(message msg);

  /// Satisfies the promise by sending an error message.
  /// @post `pending() == false`
  void deliver(error x);

  /// Satisfies the promise by sending an empty message.
  /// @note Sends no message if the request message was asynchronous, i.e., if
  ///       `async() == true`.
  /// @post `pending() == false`
  void deliver();

  /// Satisfies the promise by sending an empty message.
  /// @note Sends no message if the request message was asynchronous, i.e., if
  ///       `async() == true`.
  /// @post `pending() == false`
  void deliver(unit_t) {
    deliver();
  }

  /// Satisfies the promise by sending `make_message(xs...)`.
  /// @post `pending() == false`
  template <class... Ts>
  void deliver(Ts... xs) {
    using arg_types = detail::type_list<Ts...>;
    static_assert(!detail::tl_exists<arg_types, detail::is_result>::value,
                  "delivering a result<T> is not supported");
    static_assert(!detail::tl_exists<arg_types, detail::is_expected>::value,
                  "mixing expected<T> with regular values is not supported");
    if (pending()) {
      state_->deliver_impl(make_message(std::move(xs)...));
      state_.reset();
    }
  }

  /// Satisfies the promise by sending the content of `x`, i.e., either a value
  /// of type `T` or an @ref error.
  /// @post `pending() == false`
  template <class T>
  void deliver(expected<T> x) {
    if (pending()) {
      if (x) {
        if constexpr (std::is_same<T, void>::value
                      || std::is_same<T, unit_t>::value)
          state_->deliver_impl(make_message());
        else
          state_->deliver_impl(make_message(std::move(*x)));
      } else {
        state_->deliver_impl(make_message(std::move(x.error())));
      }
      state_.reset();
    }
  }

  // -- delegation -------------------------------------------------------------

  /// Satisfies the promise by delegating to another actor.
  /// @post `pending() == false`
  template <message_priority P = message_priority::normal, class Handle = actor,
            class... Ts>
  delegated_response_type_t<
    typename Handle::signatures,
    detail::implicit_conversions_t<typename std::decay<Ts>::type>...>
  delegate(const Handle& dest, Ts&&... xs) {
    static_assert(sizeof...(Ts) > 0, "nothing to delegate");
    using token = detail::type_list<typename detail::implicit_conversions<
      typename std::decay<Ts>::type>::type...>;
    static_assert(response_type_unbox<signatures_of_t<Handle>, token>::valid,
                  "receiver does not accept given message");
    if (pending()) {
      if constexpr (P == message_priority::high)
        state_->id = state_->id.with_high_priority();
      if constexpr (std::is_same<detail::type_list<message>,
                                 detail::type_list<std::decay_t<Ts>...>>::value)
        state_->delegate_impl(actor_cast<abstract_actor*>(dest),
                              std::forward<Ts>(xs)...);
      else
        state_->delegate_impl(actor_cast<abstract_actor*>(dest),
                              make_message(std::forward<Ts>(xs)...));
      state_.reset();
    }
    return {};
  }

private:
  // Note: response promises must remain local to their owner. Hence, we don't
  //       need a thread-safe reference count for the state.
  class CAF_CORE_EXPORT state {
  public:
    state() = default;
    state(const state&) = delete;
    state& operator=(const state&) = delete;
    ~state();

    void cancel();

    void deliver_impl(message msg);

    void delegate_impl(abstract_actor* receiver, message msg);

    mutable size_t ref_count = 1;
    strong_actor_ptr self;
    strong_actor_ptr source;
    forwarding_stack stages;
    message_id id;

    friend void intrusive_ptr_add_ref(const state* ptr) {
      ++ptr->ref_count;
    }

    friend void intrusive_ptr_release(const state* ptr) {
      if (--ptr->ref_count == 0)
        delete ptr;
    }
  };

  intrusive_ptr<state> state_;
};

} // namespace caf
<|endoftext|>


<commit_before>#pragma once

#include <tuple>

#include "oqpi/scheduling/task_base.hpp"
#include "oqpi/scheduling/task_result.hpp"
#include "oqpi/scheduling/task_notifier.hpp"

namespace oqpi {

    template<task_type _TaskType, typename _EventType, typename _TaskContext, typename _Func>
    class task final
        : public task_base
        , public task_result<typename std::result_of<_Func()>::type>
        , public _TaskContext
        , public notifier<_TaskType, _EventType>
    {
        //------------------------------------------------------------------------------------------
        using self_type         = task<_TaskType, _EventType, _TaskContext, _Func>;
        using return_type       = typename std::result_of<_Func()>::type;
        using task_result_type  = task_result<return_type>;
        using notifier_type     = notifier<_TaskType, _EventType>;

    public:
        //------------------------------------------------------------------------------------------
        task(const std::string &name, task_priority priority, _Func func)
            : task_base(priority)
            , _TaskContext(this, name)
            , notifier_type(task_base::getUID())
            , func_(std::move(func))
        {}

        //------------------------------------------------------------------------------------------
        // Movable
        task(self_type &&other)
            : task_base(std::move(other))
            , _TaskContext(std::move(other))
            , notifier_type(std::move(other))
            , func_(std::move(other.func_))
        {}

        //------------------------------------------------------------------------------------------
        self_type& operator =(self_type &&rhs)
        {
            if (this != &rhs)
            {
                task_base::operator =(std::move(rhs));
                _TaskContext::operator =(std::move(rhs));
                notifier_type::operator =(std::move(rhs));
                func_ = std::move(rhs.func_);
            }
            return (*this);
        }

        //------------------------------------------------------------------------------------------
        // Not copyable
        task(const self_type &)                     = delete;
        self_type& operator =(const self_type &)    = delete;

    public:
        //------------------------------------------------------------------------------------------
        virtual void execute() override final
        {
            if (oqpi_ensuref(task_base::isGrabbed(), "Trying to execute an ungrabbed task: %d", task_base::getUID()))
            {
                invoke();
                task_base::notifyParent();
            }
        }

        //------------------------------------------------------------------------------------------
        virtual void executeSingleThreaded() override final
        {
            if (task_base::tryGrab())
            {
                invoke();
                // We are single threaded meaning that our parent (if any) is running this task
                // in its executeSingleThreaded function, so no need to notify it.
            }
        }

        //------------------------------------------------------------------------------------------
        virtual void wait() override final
        {
            notifier_type::wait();
        }

        //------------------------------------------------------------------------------------------
        virtual void activeWait() override final
        {
            if (task_base::tryGrab())
            {
                execute();
            }
            else
            {
                wait();
            }
        }

        //------------------------------------------------------------------------------------------
        virtual void onParentGroupSet() override final
        {
            _TaskContext::task_onAddedToGroup(this->spParentGroup_);
        }

        //------------------------------------------------------------------------------------------
        return_type getResult() const
        {
            oqpi_checkf(task_base::isDone(), "Trying to get the result of an unfinished task: %d", task_base::getUID());
            return task_result_type::getResult();
        }

        //------------------------------------------------------------------------------------------
        return_type waitForResult() const
        {
            wait();
            return getResult();
        }

    private:
        //------------------------------------------------------------------------------------------
        inline void invoke()
        {
            // Run the preExecute code of the context
            _TaskContext::task_onPreExecute();
            // Run the task itself
            task_result_type::run(func_);
            // Flag the task as done
            task_base::setDone();
            // Run the postExecute code of the context
            _TaskContext::task_onPostExecute();
            // Signal that the task is done
            notifier_type::notify();
        }

    private:
        _Func func_;
    };
    //----------------------------------------------------------------------------------------------

    //----------------------------------------------------------------------------------------------
    // Type     : user defined
    // Context  : user defined
    template<task_type _TaskType, typename _EventType, typename _TaskContext, typename _Func, typename... _Args>
    inline auto make_task(const std::string &name, task_priority priority, _Func &&func, _Args &&...args)
    {
        auto f = [func = std::forward<_Func>(func), args = std::make_tuple(std::forward<_Args>(args)...)] () mutable
        {
            return std::apply(func, args);
        };

        using task_type = task<_TaskType, _EventType, _TaskContext, std::decay_t<decltype(f)>>;
        return std::make_shared<task_type>
        (
            name,
            priority,
            std::move(f)
        );
    }
    //----------------------------------------------------------------------------------------------

} /*oqpi*/
<commit_msg>Used std::invoke_result instead of deprecated std::result_of.<commit_after>#pragma once

#include <tuple>
#include <type_traits>

#include "oqpi/scheduling/task_base.hpp"
#include "oqpi/scheduling/task_result.hpp"
#include "oqpi/scheduling/task_notifier.hpp"

namespace oqpi {

    template<task_type _TaskType, typename _EventType, typename _TaskContext, typename _Func>
    class task final
        : public task_base
        , public task_result<typename std::invoke_result_t<_Func>>
        , public _TaskContext
        , public notifier<_TaskType, _EventType>
    {
        //------------------------------------------------------------------------------------------
        using self_type         = task<_TaskType, _EventType, _TaskContext, _Func>;
        using return_type       = typename std::invoke_result_t<_Func>;
        using task_result_type  = task_result<return_type>;
        using notifier_type     = notifier<_TaskType, _EventType>;

    public:
        //------------------------------------------------------------------------------------------
        task(const std::string &name, task_priority priority, _Func func)
            : task_base(priority)
            , _TaskContext(this, name)
            , notifier_type(task_base::getUID())
            , func_(std::move(func))
        {}

        //------------------------------------------------------------------------------------------
        // Movable
        task(self_type &&other)
            : task_base(std::move(other))
            , _TaskContext(std::move(other))
            , notifier_type(std::move(other))
            , func_(std::move(other.func_))
        {}

        //------------------------------------------------------------------------------------------
        self_type& operator =(self_type &&rhs)
        {
            if (this != &rhs)
            {
                task_base::operator =(std::move(rhs));
                _TaskContext::operator =(std::move(rhs));
                notifier_type::operator =(std::move(rhs));
                func_ = std::move(rhs.func_);
            }
            return (*this);
        }

        //------------------------------------------------------------------------------------------
        // Not copyable
        task(const self_type &)                     = delete;
        self_type& operator =(const self_type &)    = delete;

    public:
        //------------------------------------------------------------------------------------------
        virtual void execute() override final
        {
            if (oqpi_ensuref(task_base::isGrabbed(), "Trying to execute an ungrabbed task: %d", task_base::getUID()))
            {
                invoke();
                task_base::notifyParent();
            }
        }

        //------------------------------------------------------------------------------------------
        virtual void executeSingleThreaded() override final
        {
            if (task_base::tryGrab())
            {
                invoke();
                // We are single threaded meaning that our parent (if any) is running this task
                // in its executeSingleThreaded function, so no need to notify it.
            }
        }

        //------------------------------------------------------------------------------------------
        virtual void wait() override final
        {
            notifier_type::wait();
        }

        //------------------------------------------------------------------------------------------
        virtual void activeWait() override final
        {
            if (task_base::tryGrab())
            {
                execute();
            }
            else
            {
                wait();
            }
        }

        //------------------------------------------------------------------------------------------
        virtual void onParentGroupSet() override final
        {
            _TaskContext::task_onAddedToGroup(this->spParentGroup_);
        }

        //------------------------------------------------------------------------------------------
        return_type getResult() const
        {
            oqpi_checkf(task_base::isDone(), "Trying to get the result of an unfinished task: %d", task_base::getUID());
            return task_result_type::getResult();
        }

        //------------------------------------------------------------------------------------------
        return_type waitForResult()
        {
            wait();
            return getResult();
        }

    private:
        //------------------------------------------------------------------------------------------
        inline void invoke()
        {
            // Run the preExecute code of the context
            _TaskContext::task_onPreExecute();
            // Run the task itself
            task_result_type::run(func_);
            // Flag the task as done
            task_base::setDone();
            // Run the postExecute code of the context
            _TaskContext::task_onPostExecute();
            // Signal that the task is done
            notifier_type::notify();
        }

    private:
        _Func func_;
    };
    //----------------------------------------------------------------------------------------------

    //----------------------------------------------------------------------------------------------
    // Type     : user defined
    // Context  : user defined
    template<task_type _TaskType, typename _EventType, typename _TaskContext, typename _Func, typename... _Args>
    inline auto make_task(const std::string &name, task_priority priority, _Func &&func, _Args &&...args)
    {
        auto f = [func = std::forward<_Func>(func), args = std::make_tuple(std::forward<_Args>(args)...)] () mutable
        {
            return std::apply(func, std::move(args));
        };

        using task_type = task<_TaskType, _EventType, _TaskContext, std::decay_t<decltype(f)>>;
        return std::make_shared<task_type>
        (
            name,
            priority,
            std::move(f)
        );
    }
    //----------------------------------------------------------------------------------------------

} /*oqpi*/
<|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	ルネサス RX 選択
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2016, 2017 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/byte_order.h"
#include "common/vect.h"
#include "common/delay.hpp"

#if defined(SIG_RX621)
#include "RX600/port.hpp"
#include "RX600/cmt.hpp"
#include "RX621/system.hpp"
#include "RX621/sci.hpp"
#include "RX621/icu.hpp"

#elif defined(SIG_RX24T)
#include "RX24T/peripheral.hpp"
#include "RX600/port.hpp"
#include "RX24T/system.hpp"
#include "RX24T/system_io.hpp"
#include "RX24T/dtc.hpp"
#include "RX24T/icu.hpp"
#include "RX24T/mtu3.hpp"
#include "RX24T/mtu_io.hpp"
#include "RX24T/poe3.hpp"
#include "RX24T/gpt.hpp"
#include "RX24T/tmr.hpp"
#include "RX600/cmt.hpp"
#include "RX24T/sci.hpp"
#include "RX24T/riic.hpp"
#include "RX24T/rspi.hpp"
#include "RX24T/crc.hpp"
#include "RX24T/s12ad.hpp"
#include "RX24T/adc_io.hpp"
#include "RX24T/da.hpp"
#include "RX24T/cmpc.hpp"
#include "RX24T/doc.hpp"
#include "RX24T/port_map.hpp"
#include "RX24T/power_cfg.hpp"
#include "RX24T/icu_mgr.hpp"
#include "RX24T/flash.hpp"
#include "RX24T/flash_io.hpp"

#elif defined(SIG_RX63T)
#include "RX63T/peripheral.hpp"
#include "RX600/port.hpp"
#include "RX600/cmt.hpp"
#include "RX63T/system.hpp"
#include "RX63T/sci.hpp"
#include "RX63T/icu.hpp"
#include "RX63T/port_map.hpp"
#include "RX63T/power_cfg.hpp"
#include "RX63T/icu_mgr.hpp"

#elif defined(SIG_RX64M)
#include "RX600/peripheral.hpp"
#include "RX600/port.hpp"
#include "RX600/cmt.hpp"
#include "RX600/system.hpp"
#include "RX600/system_io.hpp"
#include "RX600/bus.hpp"
#include "RX600/mpc.hpp"
#include "RX600/icu.hpp"
#include "RX600/tpu.hpp"
#include "RX600/mtu3.hpp"
#include "RX600/sci.hpp"
#include "RX600/scif.hpp"
#include "RX600/riic.hpp"
#include "RX600/rspi.hpp"
#include "RX600/port_map.hpp"
#include "RX600/power_cfg.hpp"
#include "RX600/icu_mgr.hpp"
#include "RX600/s12adc.hpp"
#include "RX600/adc_io.hpp"
#include "RX600/r12da.hpp"
#include "RX600/dac_out.hpp"
#include "RX600/sdram.hpp"
#include "RX600/etherc.hpp"
#include "RX600/edmac.hpp"
#include "RX600/rtc.hpp"
#include "RX600/rtc_io.hpp"
#include "RX600/wdta.hpp"
#include "RX600/flash.hpp"
#include "RX600/flash_io.hpp"
#include "RX600/ether_io.hpp"
#include "RX600/ssi.hpp"
#include "RX600/src.hpp"
#include "RX600/sdhi.hpp"
#include "RX600/standby_ram.hpp"
#include "RX600/ssi_io.hpp"

#elif defined(SIG_RX65N)
#include "RX600/peripheral.hpp"
#include "RX600/port.hpp"
#include "RX600/cmt.hpp"
#include "RX600/system.hpp"
#include "RX600/system_io.hpp"
#include "RX600/bus.hpp"
#include "RX600/mpc.hpp"
#include "RX600/icu.hpp"
#include "RX600/tpu.hpp"
#include "RX600/mtu3.hpp"
#include "RX600/sci.hpp"
#include "RX600/scif.hpp"
#include "RX600/riic.hpp"
#include "RX600/rspi.hpp"
#include "RX600/port_map.hpp"
#include "RX600/power_cfg.hpp"
#include "RX600/icu_mgr.hpp"
#include "RX600/s12adc.hpp"
#include "RX600/adc_io.hpp"
#include "RX600/r12da.hpp"
#include "RX600/dac_out.hpp"
#include "RX600/sdram.hpp"
#include "RX600/etherc.hpp"
#include "RX600/edmac.hpp"
#include "RX600/rtc.hpp"
#include "RX600/rtc_io.hpp"
#include "RX600/wdta.hpp"
#include "RX600/flash.hpp"
#include "RX600/flash_io.hpp"
#include "RX600/ether_io.hpp"
#include "RX600/ssi.hpp"
#include "RX600/src.hpp"
#include "RX600/sdhi.hpp"
#include "RX600/standby_ram.hpp"
#include "RX600/ssi_io.hpp"
#include "RX600/glcdc.hpp"
#include "RX600/drw2d.hpp"

#elif defined(SIG_RX71M)
#include "RX600/peripheral.hpp"
#include "RX600/port.hpp"
#include "RX600/cmt.hpp"
#include "RX600/system.hpp"
#include "RX600/system_io.hpp"
#include "RX600/bus.hpp"
#include "RX600/mpc.hpp"
#include "RX600/icu.hpp"
#include "RX600/tpu.hpp"
#include "RX600/mtu3.hpp"
#include "RX600/sci.hpp"
#include "RX600/scif.hpp"
#include "RX600/riic.hpp"
#include "RX600/rspi.hpp"
#include "RX600/port_map.hpp"
#include "RX600/power_cfg.hpp"
#include "RX600/icu_mgr.hpp"
#include "RX600/s12adc.hpp"
#include "RX600/adc_io.hpp"
#include "RX600/r12da.hpp"
#include "RX600/dac_out.hpp"
#include "RX600/sdram.hpp"
#include "RX600/etherc.hpp"
#include "RX600/edmac.hpp"
#include "RX600/rtc.hpp"
#include "RX600/rtc_io.hpp"
#include "RX600/wdta.hpp"
#include "RX600/flash.hpp"
#include "RX600/flash_io.hpp"
#include "RX600/ether_io.hpp"
#include "RX600/ssi.hpp"
#include "RX600/src.hpp"
#include "RX600/sdhi.hpp"
#include "RX600/standby_ram.hpp"
#include "RX600/ssi_io.hpp"

#else
#  error "Requires SIG_XXX to be defined"
#endif
<commit_msg>update: RX65N support<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	ルネサス RX 選択
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2016, 2017 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/byte_order.h"
#include "common/vect.h"
#include "common/delay.hpp"

#if defined(SIG_RX621)
#include "RX600/port.hpp"
#include "RX600/cmt.hpp"
#include "RX621/system.hpp"
#include "RX621/sci.hpp"
#include "RX621/icu.hpp"

#elif defined(SIG_RX24T)
#include "RX24T/peripheral.hpp"
#include "RX600/port.hpp"
#include "RX24T/system.hpp"
#include "RX24T/system_io.hpp"
#include "RX24T/dtc.hpp"
#include "RX24T/icu.hpp"
#include "RX24T/mtu3.hpp"
#include "RX24T/mtu_io.hpp"
#include "RX24T/poe3.hpp"
#include "RX24T/gpt.hpp"
#include "RX24T/tmr.hpp"
#include "RX600/cmt.hpp"
#include "RX24T/sci.hpp"
#include "RX24T/riic.hpp"
#include "RX24T/rspi.hpp"
#include "RX24T/crc.hpp"
#include "RX24T/s12ad.hpp"
#include "RX24T/adc_io.hpp"
#include "RX24T/da.hpp"
#include "RX24T/cmpc.hpp"
#include "RX24T/doc.hpp"
#include "RX24T/port_map.hpp"
#include "RX24T/power_cfg.hpp"
#include "RX24T/icu_mgr.hpp"
#include "RX24T/flash.hpp"
#include "RX24T/flash_io.hpp"

#elif defined(SIG_RX63T)
#include "RX63T/peripheral.hpp"
#include "RX600/port.hpp"
#include "RX600/cmt.hpp"
#include "RX63T/system.hpp"
#include "RX63T/sci.hpp"
#include "RX63T/icu.hpp"
#include "RX63T/port_map.hpp"
#include "RX63T/power_cfg.hpp"
#include "RX63T/icu_mgr.hpp"

#elif defined(SIG_RX64M)
#include "RX600/peripheral.hpp"
#include "RX600/port.hpp"
#include "RX600/cmt.hpp"
#include "RX600/system.hpp"
#include "RX600/system_io.hpp"
#include "RX600/bus.hpp"
#include "RX600/mpc.hpp"
#include "RX600/icu.hpp"
#include "RX600/tpu.hpp"
#include "RX600/mtu3.hpp"
#include "RX600/sci.hpp"
#include "RX600/scif.hpp"
#include "RX600/riic.hpp"
#include "RX600/rspi.hpp"
#include "RX600/port_map.hpp"
#include "RX600/power_cfg.hpp"
#include "RX600/icu_mgr.hpp"
#include "RX600/s12adc.hpp"
#include "RX600/adc_io.hpp"
#include "RX600/r12da.hpp"
#include "RX600/dac_out.hpp"
#include "RX600/sdram.hpp"
#include "RX600/etherc.hpp"
#include "RX600/edmac.hpp"
#include "RX600/rtc.hpp"
#include "RX600/rtc_io.hpp"
#include "RX600/wdta.hpp"
#include "RX600/flash.hpp"
#include "RX600/flash_io.hpp"
#include "RX600/ether_io.hpp"
#include "RX600/ssi.hpp"
#include "RX600/src.hpp"
#include "RX600/sdhi.hpp"
#include "RX600/standby_ram.hpp"
#include "RX600/ssi_io.hpp"

#elif defined(SIG_RX65N)
#include "RX600/peripheral.hpp"
#include "RX600/port.hpp"
#include "RX600/cmt.hpp"
#include "RX600/system.hpp"
#include "RX600/system_io.hpp"
#include "RX600/bus.hpp"
#include "RX600/mpc.hpp"
#include "RX600/icu.hpp"
#include "RX600/tpu.hpp"
#include "RX600/mtu3.hpp"
#include "RX600/sci.hpp"
#include "RX600/scif.hpp"
#include "RX600/riic.hpp"
#include "RX600/rspi.hpp"
#include "RX600/port_map.hpp"
#include "RX600/power_cfg.hpp"
#include "RX600/icu_mgr.hpp"
#include "RX600/s12adc.hpp"
#include "RX600/adc_io.hpp"
#include "RX600/r12da.hpp"
#include "RX600/dac_out.hpp"
#include "RX600/sdram.hpp"
#include "RX600/etherc.hpp"
#include "RX600/edmac.hpp"
#include "RX600/rtc.hpp"
#include "RX600/rtc_io.hpp"
#include "RX600/wdta.hpp"
#include "RX600/flash.hpp"
#include "RX600/flash_io.hpp"
#include "RX600/ether_io.hpp"
#include "RX600/ssi.hpp"
#include "RX600/src.hpp"
#include "RX600/sdhi.hpp"
#include "RX600/standby_ram.hpp"
#include "RX600/ssi_io.hpp"
#include "RX65x/glcdc.hpp"
#include "RX65x/glcdc_io.hpp"
#include "RX65x/drw2d.hpp"

#elif defined(SIG_RX71M)
#include "RX600/peripheral.hpp"
#include "RX600/port.hpp"
#include "RX600/cmt.hpp"
#include "RX600/system.hpp"
#include "RX600/system_io.hpp"
#include "RX600/bus.hpp"
#include "RX600/mpc.hpp"
#include "RX600/icu.hpp"
#include "RX600/tpu.hpp"
#include "RX600/mtu3.hpp"
#include "RX600/sci.hpp"
#include "RX600/scif.hpp"
#include "RX600/riic.hpp"
#include "RX600/rspi.hpp"
#include "RX600/port_map.hpp"
#include "RX600/power_cfg.hpp"
#include "RX600/icu_mgr.hpp"
#include "RX600/s12adc.hpp"
#include "RX600/adc_io.hpp"
#include "RX600/r12da.hpp"
#include "RX600/dac_out.hpp"
#include "RX600/sdram.hpp"
#include "RX600/etherc.hpp"
#include "RX600/edmac.hpp"
#include "RX600/rtc.hpp"
#include "RX600/rtc_io.hpp"
#include "RX600/wdta.hpp"
#include "RX600/flash.hpp"
#include "RX600/flash_io.hpp"
#include "RX600/ether_io.hpp"
#include "RX600/ssi.hpp"
#include "RX600/src.hpp"
#include "RX600/sdhi.hpp"
#include "RX600/standby_ram.hpp"
#include "RX600/ssi_io.hpp"

#else
#  error "Requires SIG_XXX to be defined"
#endif
<|endoftext|>


<commit_before>/*
 * ProbingPT.cpp
 *
 *  Created on: 3 Nov 2015
 *      Author: hieu
 */
#include <boost/foreach.hpp>
#include "ProbingPT.h"
#include "../System.h"
#include "../Scores.h"
#include "../FF/FeatureFunctions.h"
#include "../Search/Manager.h"
#include "../legacy/FactorCollection.h"
#include "../legacy/ProbingPT/quering.hh"
#include "../legacy/Util2.h"

using namespace std;

namespace Moses2
{

ProbingPT::ProbingPT(size_t startInd, const std::string &line)
:PhraseTable(startInd, line)
{
	  ReadParameters();
}

ProbingPT::~ProbingPT()
{
  delete m_engine;
}

void ProbingPT::Load(System &system)
{
  m_engine = new QueryEngine(m_path.c_str());

  m_unkId = 456456546456;

  FactorCollection &vocab = system.GetVocab();

  // source vocab
  const std::map<uint64_t, std::string> &sourceVocab = m_engine->getSourceVocab();
  std::map<uint64_t, std::string>::const_iterator iterSource;
  for (iterSource = sourceVocab.begin(); iterSource != sourceVocab.end(); ++iterSource) {
	const string &wordStr = iterSource->second;
	const Factor *factor = vocab.AddFactor(wordStr, system);

	uint64_t probingId = iterSource->first;
	size_t factorId = factor->GetId();

	if (factorId >= m_sourceVocab.size()) {
		m_sourceVocab.resize(factorId + 1, m_unkId);
	}
	m_sourceVocab[factorId] = probingId;
  }

  // target vocab
  const std::map<unsigned int, std::string> &probingVocab = m_engine->getVocab();
  std::map<unsigned int, std::string>::const_iterator iter;
  for (iter = probingVocab.begin(); iter != probingVocab.end(); ++iter) {
	const string &wordStr = iter->second;
	const Factor *factor = vocab.AddFactor(wordStr, system);

	unsigned int probingId = iter->first;

	if (probingId >= m_targetVocab.size()) {
		m_targetVocab.resize(probingId + 1, NULL);
	}
	m_targetVocab[probingId] = factor;
  }
}

void ProbingPT::Lookup(const Manager &mgr, InputPaths &inputPaths) const
{
  RecycleData &recycler = GetThreadSpecificObj(m_recycleData);

  BOOST_FOREACH(InputPath &path, inputPaths) {
	TargetPhrases *tpsPtr;
	tpsPtr = Lookup(mgr, mgr.GetPool(), path, recycler);
	path.AddTargetPhrases(*this, tpsPtr);
  }
}

TargetPhrases* ProbingPT::Lookup(const Manager &mgr,
		MemPool &pool,
		InputPath &inputPath,
		RecycleData &recycler) const
{
	const Phrase &sourcePhrase = inputPath.subPhrase;
	TargetPhrases *ret = CreateTargetPhrase(pool, mgr.system, sourcePhrase, recycler);
	return ret;
}

TargetPhrases* ProbingPT::CreateTargetPhrase(MemPool &pool,
		const System &system,
		const Phrase &sourcePhrase,
		RecycleData &recycler) const
{

  // create a target phrase from the 1st word of the source, prefix with 'ProbingPT:'
  size_t sourceSize = sourcePhrase.GetSize();
	assert(sourceSize);

  TargetPhrases *tps = NULL;
  uint64_t probingSource[sourceSize];
  bool ok;
  ConvertToProbingSourcePhrase(sourcePhrase, ok, probingSource);
  if (!ok) {
    // source phrase contains a word unknown in the pt.
    // We know immediately there's no translation for it
    return tps;
  }

  std::pair<bool, std::vector<target_text*>* > query_result;

  //Actual lookup
  query_result = m_engine->query(probingSource, sourceSize, recycler);

  if (query_result.first) {
    //m_engine->printTargetInfo(query_result.second);
	std::vector<target_text*> *probingTargetPhrases = query_result.second;
	tps = new (pool.Allocate<TargetPhrases>()) TargetPhrases(pool, probingTargetPhrases->size());

    for (size_t i = 0; i < probingTargetPhrases->size(); ++i) {
      target_text *probingTargetPhrase = (*probingTargetPhrases)[i];
      TargetPhrase *tp = CreateTargetPhrase(pool, system, sourcePhrase, *probingTargetPhrase);

      tps->AddTargetPhrase(*tp);

      recycler.tt.Add(probingTargetPhrase);
    }

    recycler.tts.Add(probingTargetPhrases);

    tps->SortAndPrune(m_tableLimit);
    system.featureFunctions.EvaluateAfterTablePruning(pool, *tps, sourcePhrase);
  }
  else {
	  assert(query_result.second->size() == 0);
  }

  return tps;

}

TargetPhrase *ProbingPT::CreateTargetPhrase(MemPool &pool, const System &system, const Phrase &sourcePhrase, const target_text &probingTargetPhrase) const
{

  const std::vector<unsigned int> &probingPhrase = probingTargetPhrase.target_phrase;
  size_t size = probingPhrase.size();

  TargetPhrase *tp = new (pool.Allocate<TargetPhrase>()) TargetPhrase(pool, system, size);

  // words
  for (size_t i = 0; i < size; ++i) {
    uint64_t probingId = probingPhrase[i];
    const Factor *factor = GetTargetFactor(probingId);
    assert(factor);

    Word &word = (*tp)[i];
    word[0] = factor;
  }

  // score for this phrase table
  SCORE scores[probingTargetPhrase.prob.size()];
  std::copy(probingTargetPhrase.prob.begin(), probingTargetPhrase.prob.end(), scores);
  std::transform(scores, scores + probingTargetPhrase.prob.size(), scores, TransformScore);
  std::transform(scores, scores + probingTargetPhrase.prob.size(), scores, FloorScore);
  tp->GetScores().PlusEquals(system, *this, scores);

  // extra scores
  //cerr << "probingTargetPhrase.prob.size()=" << probingTargetPhrase.prob.size() << endl;
  if (probingTargetPhrase.prob.size() > m_numScores) {
	  // we have extra scores, possibly for lex ro. Keep them in the target phrase.
	  size_t numExtraScores = probingTargetPhrase.prob.size() - m_numScores;
	  tp->scoreProperties = pool.Allocate<SCORE>(numExtraScores);
	  memcpy(tp->scoreProperties, scores + m_numScores, sizeof(SCORE) * numExtraScores);

	  /*
	  for (size_t i = 0; i < probingTargetPhrase.prob.size(); ++i) {
		  cerr << probingTargetPhrase.prob[i] << " ";
	  }
	  cerr << endl;

	  for (size_t i = 0; i < probingTargetPhrase.prob.size(); ++i) {
		  cerr << scores[i] << " ";
	  }
	  cerr << endl;

	  for (size_t i = 0; i < numExtraScores; ++i) {
		  cerr << tp->scoreProperties[i] << " ";
	  }
	  cerr << endl;
	  */
  }

//  // alignment
//  /*
//  const std::vector<unsigned char> &alignments = probingTargetPhrase.word_all1;
//
//  AlignmentInfo &aligns = tp->GetAlignTerm();
//  for (size_t i = 0; i < alignS.size(); i += 2 ) {
//    aligns.Add((size_t) alignments[i], (size_t) alignments[i+1]);
//  }
//  */

  // score of all other ff when this rule is being loaded
  const FeatureFunctions &ffs = system.featureFunctions;
  ffs.EvaluateInIsolation(pool, system, sourcePhrase, *tp);
  return tp;

}

void ProbingPT::ConvertToProbingSourcePhrase(const Phrase &sourcePhrase, bool &ok, uint64_t probingSource[]) const
{

  size_t size = sourcePhrase.GetSize();
  for (size_t i = 0; i < size; ++i) {
    const Factor *factor = sourcePhrase[i][0];
    uint64_t probingId = GetSourceProbingId(factor);
    if (probingId == m_unkId) {
      ok = false;
      return;
    } else {
      probingSource[i] = probingId;
    }
  }

  ok = true;
}

void ProbingPT::GetScoresProperty(const std::string &key, size_t ind, SCORE *scoreArr)
		{

		}

}

<commit_msg>Revert "leak"<commit_after>/*
 * ProbingPT.cpp
 *
 *  Created on: 3 Nov 2015
 *      Author: hieu
 */
#include <boost/foreach.hpp>
#include "ProbingPT.h"
#include "../System.h"
#include "../Scores.h"
#include "../FF/FeatureFunctions.h"
#include "../Search/Manager.h"
#include "../legacy/FactorCollection.h"
#include "../legacy/ProbingPT/quering.hh"
#include "../legacy/Util2.h"

using namespace std;

namespace Moses2
{

ProbingPT::ProbingPT(size_t startInd, const std::string &line)
:PhraseTable(startInd, line)
{
	  ReadParameters();
}

ProbingPT::~ProbingPT()
{
  delete m_engine;
}

void ProbingPT::Load(System &system)
{
  m_engine = new QueryEngine(m_path.c_str());

  m_unkId = 456456546456;

  FactorCollection &vocab = system.GetVocab();

  // source vocab
  const std::map<uint64_t, std::string> &sourceVocab = m_engine->getSourceVocab();
  std::map<uint64_t, std::string>::const_iterator iterSource;
  for (iterSource = sourceVocab.begin(); iterSource != sourceVocab.end(); ++iterSource) {
	const string &wordStr = iterSource->second;
	const Factor *factor = vocab.AddFactor(wordStr, system);

	uint64_t probingId = iterSource->first;
	size_t factorId = factor->GetId();

	if (factorId >= m_sourceVocab.size()) {
		m_sourceVocab.resize(factorId + 1, m_unkId);
	}
	m_sourceVocab[factorId] = probingId;
  }

  // target vocab
  const std::map<unsigned int, std::string> &probingVocab = m_engine->getVocab();
  std::map<unsigned int, std::string>::const_iterator iter;
  for (iter = probingVocab.begin(); iter != probingVocab.end(); ++iter) {
	const string &wordStr = iter->second;
	const Factor *factor = vocab.AddFactor(wordStr, system);

	unsigned int probingId = iter->first;

	if (probingId >= m_targetVocab.size()) {
		m_targetVocab.resize(probingId + 1, NULL);
	}
	m_targetVocab[probingId] = factor;
  }
}

void ProbingPT::Lookup(const Manager &mgr, InputPaths &inputPaths) const
{
  RecycleData &recycler = GetThreadSpecificObj(m_recycleData);

  BOOST_FOREACH(InputPath &path, inputPaths) {
	TargetPhrases *tpsPtr;
	tpsPtr = Lookup(mgr, mgr.GetPool(), path, recycler);
	path.AddTargetPhrases(*this, tpsPtr);
  }
}

TargetPhrases* ProbingPT::Lookup(const Manager &mgr,
		MemPool &pool,
		InputPath &inputPath,
		RecycleData &recycler) const
{
	const Phrase &sourcePhrase = inputPath.subPhrase;
	TargetPhrases *ret = CreateTargetPhrase(pool, mgr.system, sourcePhrase, recycler);
	return ret;
}

TargetPhrases* ProbingPT::CreateTargetPhrase(MemPool &pool,
		const System &system,
		const Phrase &sourcePhrase,
		RecycleData &recycler) const
{

  // create a target phrase from the 1st word of the source, prefix with 'ProbingPT:'
  size_t sourceSize = sourcePhrase.GetSize();
	assert(sourceSize);

  TargetPhrases *tps = NULL;
  uint64_t probingSource[sourceSize];
  bool ok;
  ConvertToProbingSourcePhrase(sourcePhrase, ok, probingSource);
  if (!ok) {
    // source phrase contains a word unknown in the pt.
    // We know immediately there's no translation for it
    return tps;
  }

  std::pair<bool, std::vector<target_text*>* > query_result;

  //Actual lookup
  query_result = m_engine->query(probingSource, sourceSize, recycler);

  if (query_result.first) {
    //m_engine->printTargetInfo(query_result.second);
	const std::vector<target_text*> &probingTargetPhrases = *query_result.second;
	tps = new (pool.Allocate<TargetPhrases>()) TargetPhrases(pool, probingTargetPhrases.size());

    for (size_t i = 0; i < probingTargetPhrases.size(); ++i) {
      target_text *probingTargetPhrase = probingTargetPhrases[i];
      TargetPhrase *tp = CreateTargetPhrase(pool, system, sourcePhrase, *probingTargetPhrase);

      tps->AddTargetPhrase(*tp);

      recycler.tt.Add(probingTargetPhrase);
    }

    recycler.tts.Add(probingTargetPhrases);

    tps->SortAndPrune(m_tableLimit);
    system.featureFunctions.EvaluateAfterTablePruning(pool, *tps, sourcePhrase);
  }
  else {
	  assert(query_result.second.size() == 0);
  }

  return tps;

}

TargetPhrase *ProbingPT::CreateTargetPhrase(MemPool &pool, const System &system, const Phrase &sourcePhrase, const target_text &probingTargetPhrase) const
{

  const std::vector<unsigned int> &probingPhrase = probingTargetPhrase.target_phrase;
  size_t size = probingPhrase.size();

  TargetPhrase *tp = new (pool.Allocate<TargetPhrase>()) TargetPhrase(pool, system, size);

  // words
  for (size_t i = 0; i < size; ++i) {
    uint64_t probingId = probingPhrase[i];
    const Factor *factor = GetTargetFactor(probingId);
    assert(factor);

    Word &word = (*tp)[i];
    word[0] = factor;
  }

  // score for this phrase table
  SCORE scores[probingTargetPhrase.prob.size()];
  std::copy(probingTargetPhrase.prob.begin(), probingTargetPhrase.prob.end(), scores);
  std::transform(scores, scores + probingTargetPhrase.prob.size(), scores, TransformScore);
  std::transform(scores, scores + probingTargetPhrase.prob.size(), scores, FloorScore);
  tp->GetScores().PlusEquals(system, *this, scores);

  // extra scores
  //cerr << "probingTargetPhrase.prob.size()=" << probingTargetPhrase.prob.size() << endl;
  if (probingTargetPhrase.prob.size() > m_numScores) {
	  // we have extra scores, possibly for lex ro. Keep them in the target phrase.
	  size_t numExtraScores = probingTargetPhrase.prob.size() - m_numScores;
	  tp->scoreProperties = pool.Allocate<SCORE>(numExtraScores);
	  memcpy(tp->scoreProperties, scores + m_numScores, sizeof(SCORE) * numExtraScores);

	  /*
	  for (size_t i = 0; i < probingTargetPhrase.prob.size(); ++i) {
		  cerr << probingTargetPhrase.prob[i] << " ";
	  }
	  cerr << endl;

	  for (size_t i = 0; i < probingTargetPhrase.prob.size(); ++i) {
		  cerr << scores[i] << " ";
	  }
	  cerr << endl;

	  for (size_t i = 0; i < numExtraScores; ++i) {
		  cerr << tp->scoreProperties[i] << " ";
	  }
	  cerr << endl;
	  */
  }

//  // alignment
//  /*
//  const std::vector<unsigned char> &alignments = probingTargetPhrase.word_all1;
//
//  AlignmentInfo &aligns = tp->GetAlignTerm();
//  for (size_t i = 0; i < alignS.size(); i += 2 ) {
//    aligns.Add((size_t) alignments[i], (size_t) alignments[i+1]);
//  }
//  */

  // score of all other ff when this rule is being loaded
  const FeatureFunctions &ffs = system.featureFunctions;
  ffs.EvaluateInIsolation(pool, system, sourcePhrase, *tp);
  return tp;

}

void ProbingPT::ConvertToProbingSourcePhrase(const Phrase &sourcePhrase, bool &ok, uint64_t probingSource[]) const
{

  size_t size = sourcePhrase.GetSize();
  for (size_t i = 0; i < size; ++i) {
    const Factor *factor = sourcePhrase[i][0];
    uint64_t probingId = GetSourceProbingId(factor);
    if (probingId == m_unkId) {
      ok = false;
      return;
    } else {
      probingSource[i] = probingId;
    }
  }

  ok = true;
}

void ProbingPT::GetScoresProperty(const std::string &key, size_t ind, SCORE *scoreArr)
		{

		}

}

<|endoftext|>