<commit_before>#ifndef TOML11_REGION_H
#define TOML11_REGION_H
#include "exception.hpp"
#include <memory>
#include <algorithm>
#include <iterator>

namespace toml
{
namespace detail
{

// location in a container, normally in a file content.
// shared_ptr points the resource that the iter points.
// it can be used not only for resource handling, but also error message.
template<typename Container>
struct location
{
    static_assert(std::is_same<char, typename Container::value_type>::value,"");
    using const_iterator = typename Container::const_iterator;
    using source_ptr     = std::shared_ptr<const Container>;

    location(Container cont)
      : source_(std::make_shared<Container>(std::move(cont))),
        begin_(source_->cbegin()), iter_(source_->cbegin()),
        end_(source_->cend())
    {}
    location(const location&) = default;
    location(location&&)      = default;
    location& operator=(const location&) = default;
    location& operator=(location&&)      = default;
    ~location() = default;

    const_iterator& iter()       noexcept {return iter_;}
    const_iterator  iter() const noexcept {return iter_;}

    const_iterator  begin() const noexcept {return begin_;}
    const_iterator  end()   const noexcept {return end_;}

    source_ptr const& source() const& noexcept {return source_;}
    source_ptr&&      source() &&     noexcept {return std::move(source_);}

  private:

    source_ptr source_;
    const_iterator begin_, iter_, end_;
};

// region in a container, normally in a file content.
// shared_ptr points the resource that the iter points.
// combinators returns this.
// it can be used not only for resource handling, but also error message.
template<typename Container>
struct region
{
    static_assert(std::is_same<char, typename Container::value_type>::value,"");
    using const_iterator = typename Container::const_iterator;
    using source_ptr     = std::shared_ptr<const Container>;

    region(const location<Container>& loc)
      : begin_(loc.begin()), first_(loc.iter()),
        last_(loc.iter()), end_(loc.end()), source_(loc.source())
    {}
    region(location<Container>&& loc)
      : begin_(loc.begin()), first_(loc.iter()),
        last_(loc.iter()), end_(loc.end()), source_(std::move(loc.source()))
    {}

    region(const location<Container>& loc, const_iterator f, const_iterator l)
      : begin_(loc.begin()), first_(f), last_(l), end_(loc.end()),
        source_(loc.source())
    {}
    region(location<Container>&& loc, const_iterator f, const_iterator l)
      : begin_(loc.begin()), first_(f), last_(l), end_(loc.end()),
        source_(std::move(loc.source()))
    {}

    region(const region&) = default;
    region(region&&)      = default;
    region& operator=(const region&) = default;
    region& operator=(region&&)      = default;
    ~region() = default;

    region& operator+=(const region& other)
    {
        if(this->begin_ != other.begin_ || this->end_ != other.end_ ||
           this->last_  != other.first_)
        {
            throw internal_error("invalid region concatenation");
        }
        this->last_ = other.last_;
        return *this;
    }

    std::string str()  const {return std::string(first_, last_);}
    std::size_t size() const {return std::distance(first_, last_);}

    const_iterator  begin() const noexcept {return begin_;}
    const_iterator  end()   const noexcept {return end_;}
    const_iterator  first() const noexcept {return first_;}
    const_iterator  last()  const noexcept {return last_;}

    source_ptr const& source() const& noexcept {return source_;}
    source_ptr&&      source() &&     noexcept {return std::move(source_);}

  private:

    const_iterator begin_, first_, last_, end_;
    source_ptr source_;
};

// to show a better error message.
template<typename Container>
std::string
format_underline(const region<Container>& reg, const std::string& msg)
{
    using const_iterator = typename region<Container>::const_iterator;
    using reverse_iterator = std::reverse_iterator<const_iterator>;
    const auto line_begin = std::find(
            reverse_iterator(reg.first()),
            reverse_iterator(reg.begin()),
            '\n').base();
    const auto line_end = std::find(reg.last(), reg.end(), '\n');

    const auto line_number = std::to_string(
            1 + std::count(reg.begin(), reg.first(), '\n'));

    std::string retval;
    retval += ' ';
    retval += line_number;
    retval += " | ";
    retval += std::string(line_begin, line_end);
    retval += '\n';
    retval += std::string(line_number.size() + 1, ' ');
    retval += " | ";
    retval += std::string(std::distance(line_begin, reg.first()), ' ');
    retval += std::string(std::distance(reg.first(), reg.last()), '~');
    retval += ' ';
    retval += msg;
    return retval;
}

// to show a better error message.
template<typename Container>
std::string format_underline(const region<Container>& reg,
                             typename Container::const_iterator pos,
                             const std::string& msg)
{
    using const_iterator = typename region<Container>::const_iterator;
    using reverse_iterator = std::reverse_iterator<const_iterator>;
    const auto line_begin = std::find(
            reverse_iterator(reg.first()),
            reverse_iterator(reg.begin()),
            '\n').base();
    const auto line_end = std::find(reg.last(), reg.end(), '\n');

    const auto line_number = std::to_string(
            1 + std::count(reg.begin(), reg.first(), '\n'));

    std::string retval;
    retval += ' ';
    retval += line_number;
    retval += " | ";
    retval += std::string(line_begin, line_end);
    retval += '\n';
    retval += std::string(line_number.size() + 1, ' ');
    retval += " | ";
    retval += std::string(std::distance(line_begin, reg.first()), ' ');

    if(std::distance(reg.first(), std::prev(pos)) > 0)
    {
        retval += std::string(std::distance(reg.first(), std::prev(pos)), '-');
    }
    retval += '^';
    if(std::distance(pos, reg.last()) > 0)
    {
        retval += std::string(std::distance(std::next(pos), reg.last()), '-');
    }

    retval += ' ';
    retval += msg;
    return retval;
}

} // detail
} // toml
#endif// TOML11_REGION_H
<commit_msg>add source_name to location/region to show filename<commit_after>#ifndef TOML11_REGION_H
#define TOML11_REGION_H
#include "exception.hpp"
#include <memory>
#include <algorithm>
#include <iterator>
#include <iostream>

namespace toml
{
namespace detail
{

// helper function to avoid std::string(0, 'c')
template<typename Iterator>
std::string make_string(Iterator first, Iterator last)
{
    if(first == last) {return "";}
    return std::string(first, last);
}
inline std::string make_string(std::size_t len, char c)
{
    if(len == 0) {return "";}
    return std::string(len, c);
}

// location in a container, normally in a file content.
// shared_ptr points the resource that the iter points.
// it can be used not only for resource handling, but also error message.
template<typename Container>
struct location
{
    static_assert(std::is_same<char, typename Container::value_type>::value,"");
    using const_iterator = typename Container::const_iterator;
    using source_ptr     = std::shared_ptr<const Container>;

    location(std::string name, Container cont)
      : source_(std::make_shared<Container>(std::move(cont))),
        source_name_(std::move(name)), begin_(source_->cbegin()),
        iter_(source_->cbegin()), end_(source_->cend())
    {}
    location(const location&) = default;
    location(location&&)      = default;
    location& operator=(const location&) = default;
    location& operator=(location&&)      = default;
    ~location() = default;

    const_iterator& iter()       noexcept {return iter_;}
    const_iterator  iter() const noexcept {return iter_;}

    const_iterator  begin() const noexcept {return begin_;}
    const_iterator  end()   const noexcept {return end_;}

    source_ptr const& source() const& noexcept {return source_;}
    source_ptr&&      source() &&     noexcept {return std::move(source_);}

    std::string const& name() const noexcept {return source_name_;}

  private:

    source_ptr     source_;
    std::string    source_name_;
    const_iterator begin_, iter_, end_;
};

// region in a container, normally in a file content.
// shared_ptr points the resource that the iter points.
// combinators returns this.
// it can be used not only for resource handling, but also error message.
template<typename Container>
struct region
{
    static_assert(std::is_same<char, typename Container::value_type>::value,"");
    using const_iterator = typename Container::const_iterator;
    using source_ptr     = std::shared_ptr<const Container>;

    region(const location<Container>& loc)
      : source_(loc.source()), source_name_(loc.name()),
        begin_(loc.begin()), first_(loc.iter()),
        last_(loc.iter()), end_(loc.end())
    {}
    region(location<Container>&& loc)
      : source_(loc.source()), source_name_(loc.name()),
        begin_(loc.begin()), first_(loc.iter()),
        last_(loc.iter()), end_(loc.end())
    {}

    region(const location<Container>& loc, const_iterator f, const_iterator l)
      : source_(loc.source()), source_name_(loc.name()),
        begin_(loc.begin()), first_(f), last_(l), end_(loc.end())
    {}
    region(location<Container>&& loc, const_iterator f, const_iterator l)
      : source_(loc.source()), source_name_(loc.name()),
        begin_(loc.begin()), first_(f), last_(l), end_(loc.end())
    {}

    region(const region&) = default;
    region(region&&)      = default;
    region& operator=(const region&) = default;
    region& operator=(region&&)      = default;
    ~region() = default;

    region& operator+=(const region& other)
    {
        if(this->begin_ != other.begin_ || this->end_ != other.end_ ||
           this->last_  != other.first_)
        {
            throw internal_error("invalid region concatenation");
        }
        this->last_ = other.last_;
        return *this;
    }

    std::string str()  const {return make_string(first_, last_);}
    std::size_t size() const {return std::distance(first_, last_);}

    const_iterator  begin() const noexcept {return begin_;}
    const_iterator  end()   const noexcept {return end_;}
    const_iterator  first() const noexcept {return first_;}
    const_iterator  last()  const noexcept {return last_;}

    source_ptr const& source() const& noexcept {return source_;}
    source_ptr&&      source() &&     noexcept {return std::move(source_);}

    std::string const& name() const noexcept {return source_name_;}

  private:

    source_ptr     source_;
    std::string    source_name_;
    const_iterator begin_, first_, last_, end_;
};

// to show a better error message.
template<typename Container>
std::string
format_underline(const std::string& message, const region<Container>& reg,
                 const std::string& comment_for_underline)
{
    using const_iterator = typename region<Container>::const_iterator;
    using reverse_iterator = std::reverse_iterator<const_iterator>;
    const auto line_begin = std::find(reverse_iterator(reg.first()),
                                      reverse_iterator(reg.begin()),
                                      '\n').base();
    const auto line_end   = std::find(reg.last(), reg.end(), '\n');

    const auto line_number = std::to_string(
            1 + std::count(reg.begin(), reg.first(), '\n'));

    std::string retval;
    retval += message;
    retval += "\n --> ";
    retval += reg.name();
    retval += "\n ";
    retval += line_number;
    retval += " | ";
    retval += make_string(line_begin, line_end);
    retval += '\n';
    retval += make_string(line_number.size() + 1, ' ');
    retval += " | ";
    retval += make_string(std::distance(line_begin, reg.first()), ' ');
    retval += make_string(std::distance(reg.first(), reg.last()), '~');
    retval += ' ';
    retval += comment_for_underline;
    return retval;
}

// to show a better error message.
template<typename Container>
std::string
format_underline(const std::string& message, const location<Container>& loc,
                 const std::string& comment_for_underline)
{
    using const_iterator   = typename location<Container>::const_iterator;
    using reverse_iterator = std::reverse_iterator<const_iterator>;
    const auto line_begin  = std::find(reverse_iterator(loc.iter()),
                                       reverse_iterator(loc.begin()),
                                       '\n').base();
    const auto line_end    = std::find(loc.iter(), loc.end(), '\n');

    const auto line_number = std::to_string(
            1 + std::count(loc.begin(), loc.iter(), '\n'));

    std::string retval;
    retval += message;
    retval += "\n --> ";
    retval += loc.name();
    retval += "\n ";
    retval += line_number;
    retval += " | ";
    retval += make_string(line_begin, line_end);
    retval += '\n';
    retval += make_string(line_number.size() + 1, ' ');
    retval += " | ";
    retval += make_string(std::distance(line_begin, loc.iter()),' ');
    retval += '^';
    retval += make_string(std::distance(std::next(loc.iter()), line_end), '-');
    retval += ' ';
    retval += comment_for_underline;
    return retval;
}

} // detail
} // toml
#endif// TOML11_REGION_H
<|endoftext|>


<commit_before>#ifndef TOML11_REGION_H
#define TOML11_REGION_H
#include <memory>
#include <algorithm>
#include <iterator>
#include <string>

namespace toml
{
namespace detail
{

// location in a container, normally in a file content.
// shared_ptr points the resource that the iter points.
// it can be used not only for resource handling, but also error message.
template<typename Container>
struct location
{
    using const_iterator = typename Container::const_iterator;

    location(Container cont)
        : source(std::make_shared<Container>(std::move(cont))),
          iter(source->begin())
    {}
    location(const location&) = default;
    location(location&&)      = default;
    location& operator=(const location&) = default;
    location& operator=(location&&)      = default;
   ~location() = default;

    std::shared_ptr<const Container> source;
    const_iterator iter;
};

// region in a container, normally in a file content.
// shared_ptr points the resource that the iter points.
// combinators returns this.
// it can be used not only for resource handling, but also error message.
template<typename Container>
struct region
{
    using const_iterator = typename Container::const_iterator;

    region(const location<Container>& loc)
        : first(loc.iter), last(loc.iter), source(loc.source)
    {}
    region(location<Container>&& loc)
        : first(loc.iter), last(loc.iter), source(std::move(loc.source))
    {}

    region(const region&) = default;
    region(region&&)      = default;
    region& operator=(const region&) = default;
    region& operator=(region&&)      = default;
    ~region() = default;

    const_iterator first, last;
    std::shared_ptr<const Container> source;
};

// to show a better error message.
template<typename Container>
std::string
format_underline(const region<Container>& reg, const std::string& msg)
{
    using const_iterator = typename region<Container>::const_iterator;
    using reverse_iterator = std::reverse_iterator<const_iterator>;
    const auto line_begin = std::find(
            reverse_iterator(reg.first),
            reverse_iterator(reg.source->cbegin()),
            '\n').base();
    const auto line_end = std::find(reg.last, reg.source->cend(), '\n');

    const auto line_number = std::to_string(
            1 + std::count(reg.source->cbegin(), reg.first, '\n'));

    std::string retval;
    retval += ' ';
    retval += line_number;
    retval += " | ";
    retval += std::string(line_begin, line_end);
    retval += '\n';
    retval += std::string(line_number.size() + 1, ' ');
    retval += " | ";
    retval += std::string(std::distance(line_begin, reg.first), ' ');
    retval += std::string(std::distance(reg.first, reg.last), '~');
    retval += ' ';
    retval += msg;
    return retval;
}

// to show a better error message.
template<typename Container>
std::string format_underline(const region<Container>& reg,
                             typename Container::const_iterator pos,
                             const std::string& msg)
{
    using const_iterator = typename region<Container>::const_iterator;
    using reverse_iterator = std::reverse_iterator<const_iterator>;
    const auto line_begin = std::find(
            reverse_iterator(reg.first),
            reverse_iterator(reg.source->cbegin()),
            '\n').base();
    const auto line_end = std::find(reg.last, reg.source->cend(), '\n');

    const auto line_number = std::to_string(
            1 + std::count(reg.source->cbegin(), reg.first, '\n'));

    std::string retval;
    retval += ' ';
    retval += line_number;
    retval += " | ";
    retval += std::string(line_begin, line_end);
    retval += '\n';
    retval += std::string(line_number.size() + 1, ' ');
    retval += " | ";
    retval += std::string(std::distance(line_begin, reg.first), ' ');

    if(std::distance(reg.first, std::prev(pos)) > 0)
    {
        retval += std::string(std::distance(reg.first, std::prev(pos)), '-');
    }
    retval += '^';
    if(std::distance(pos, reg.last) > 0)
    {
        retval += std::string(std::distance(std::next(pos), reg.last), '-');
    }

    retval += ' ';
    retval += msg;
    return retval;
}

} // detail
} // toml
#endif// TOML11_REGION_H
<commit_msg>add begin/end to region<commit_after>#ifndef TOML11_REGION_H
#define TOML11_REGION_H
#include <memory>
#include <algorithm>
#include <iterator>
#include <string>

namespace toml
{
namespace detail
{

// location in a container, normally in a file content.
// shared_ptr points the resource that the iter points.
// it can be used not only for resource handling, but also error message.
template<typename Container>
struct location
{
    using const_iterator = typename Container::const_iterator;

    location(Container cont)
      : source(std::make_shared<Container>(std::move(cont))),
        begin(source->cbegin()), iter(source->cbegin()), end(source->cend())
    {}
    location(const location&) = default;
    location(location&&)      = default;
    location& operator=(const location&) = default;
    location& operator=(location&&)      = default;
   ~location() = default;

    std::shared_ptr<const Container> source;
    const_iterator begin, iter, end;
};

// region in a container, normally in a file content.
// shared_ptr points the resource that the iter points.
// combinators returns this.
// it can be used not only for resource handling, but also error message.
template<typename Container>
struct region
{
    using const_iterator = typename Container::const_iterator;

    region(const location<Container>& loc)
      : begin(loc.begin), first(loc.iter), last(loc.iter), end(loc.end),
        source(loc.source)
    {}
    region(location<Container>&& loc)
      : begin(loc.begin), first(loc.iter), last(loc.iter), end(loc.end),
        source(std::move(loc.source))
    {}

    region(const region&) = default;
    region(region&&)      = default;
    region& operator=(const region&) = default;
    region& operator=(region&&)      = default;
    ~region() = default;

    const_iterator begin, first, last, end;
    std::shared_ptr<const Container> source;
};

// to show a better error message.
template<typename Container>
std::string
format_underline(const region<Container>& reg, const std::string& msg)
{
    using const_iterator = typename region<Container>::const_iterator;
    using reverse_iterator = std::reverse_iterator<const_iterator>;
    const auto line_begin = std::find(
            reverse_iterator(reg.first),
            reverse_iterator(reg.begin),
            '\n').base();
    const auto line_end = std::find(reg.last, reg.end, '\n');

    const auto line_number = std::to_string(
            1 + std::count(reg.begin, reg.first, '\n'));

    std::string retval;
    retval += ' ';
    retval += line_number;
    retval += " | ";
    retval += std::string(line_begin, line_end);
    retval += '\n';
    retval += std::string(line_number.size() + 1, ' ');
    retval += " | ";
    retval += std::string(std::distance(line_begin, reg.first), ' ');
    retval += std::string(std::distance(reg.first, reg.last), '~');
    retval += ' ';
    retval += msg;
    return retval;
}

// to show a better error message.
template<typename Container>
std::string format_underline(const region<Container>& reg,
                             typename Container::const_iterator pos,
                             const std::string& msg)
{
    using const_iterator = typename region<Container>::const_iterator;
    using reverse_iterator = std::reverse_iterator<const_iterator>;
    const auto line_begin = std::find(
            reverse_iterator(reg.first),
            reverse_iterator(reg.begin),
            '\n').base();
    const auto line_end = std::find(reg.last, reg.end, '\n');

    const auto line_number = std::to_string(
            1 + std::count(reg.begin, reg.first, '\n'));

    std::string retval;
    retval += ' ';
    retval += line_number;
    retval += " | ";
    retval += std::string(line_begin, line_end);
    retval += '\n';
    retval += std::string(line_number.size() + 1, ' ');
    retval += " | ";
    retval += std::string(std::distance(line_begin, reg.first), ' ');

    if(std::distance(reg.first, std::prev(pos)) > 0)
    {
        retval += std::string(std::distance(reg.first, std::prev(pos)), '-');
    }
    retval += '^';
    if(std::distance(pos, reg.last) > 0)
    {
        retval += std::string(std::distance(std::next(pos), reg.last), '-');
    }

    retval += ' ';
    retval += msg;
    return retval;
}

} // detail
} // toml
#endif// TOML11_REGION_H
<|endoftext|>


<commit_before><commit_msg>flag tracks instead of decays<commit_after><|endoftext|>


<commit_before>/*
*  Author(s):
*  - Cedric Gestes <gestes@aldebaran-robotics.com>
*  - Herve Cuche <hcuche@aldebaran-robotics.com>
*
*  Copyright (C) 2012 Aldebaran Robotics
*/

#include <qimessaging/session.hpp>
#include <qimessaging/datastream.hpp>
#include <qimessaging/transport.hpp>
#include <qimessaging/object.hpp>
#include "src/remoteobject_p.hpp"

static int uniqueRequestId = 0;

namespace qi {

Session::Session()
{
  _nthd = new qi::NetworkThread();

  tc = new qi::TransportSocket();
  tc->setDelegate(this);
}

Session::~Session()
{
  tc->disconnect();
  delete tc;
}

void Session::connect(const std::string &masterAddress)
{
  size_t begin = 0;
  size_t end = 0;
  end = masterAddress.find(":");

  std::string ip = masterAddress.substr(begin, end);
  begin = end + 1;

  unsigned int port;
  std::stringstream ss(masterAddress.substr(begin));
  ss >> port;

  tc->connect(ip, port, _nthd->getEventBase());
}

bool Session::disconnect()
{
  return true;
}

void Session::onDisconnected(TransportSocket *client)
{
}

bool Session::waitForConnected(int msecs)
{
  return tc->waitForConnected(msecs);
}

bool Session::waitForDisconnected(int msecs)
{
  return tc->waitForDisconnected(msecs);
}

std::vector<std::string> Session::services()
{
  std::vector<std::string> result;

  qi::Message msg;
  msg.setType(qi::Message::Call);
  msg.setSource(_name);
  msg.setFunction("services");

  tc->send(msg);

  tc->waitForId(msg.id());
  qi::Message ans;
  tc->read(msg.id(), &ans);

  qi::DataStream d(ans.data());
  d >> result;

  return result;
}

qi::TransportSocket* Session::serviceSocket(const std::string &name,
                                            const std::string &type)
{
  std::string result;
  qi::DataStream dr;
  qi::Message msg;
  dr << name;
  msg.setId(uniqueRequestId++);
  msg.setFunction("service");
  msg.setData(dr.str());

  tc->send(msg);

  tc->waitForId(msg.id());
  qi::Message ans;
  tc->read(msg.id(), &ans);

  qi::DataStream d(ans.data());
  d >> result;

  qi::TransportSocket* ts = NULL;

  qi::EndpointInfo endpoint;
  size_t begin = 0;
  size_t end = 0;
  end = result.find(":");
  endpoint.type = result.substr(begin, end);
  begin = end + 3;
  end = result.find(":", begin);
  endpoint.ip = result.substr(begin, end - begin);
  begin = end + 1;
  std::stringstream ss(result.substr(begin));
  ss >> endpoint.port;

  ts = new qi::TransportSocket();
  ts->setDelegate(this);
  ts->connect(endpoint.ip, endpoint.port, _nthd->getEventBase());
  ts->waitForConnected();

  return ts;
}

qi::Object* Session::service(const std::string &name,
                             const std::string &type)
{
  qi::Object          *obj;
  qi::TransportSocket *ts = serviceSocket(name, type);

  if (ts == 0)
  {
    return 0;
  }

  qi::RemoteObject *robj = new qi::RemoteObject(ts, name);
  obj = robj;
  return obj;
}

void Session::onConnected(TransportSocket *client)
{
  //  std::cout << "connected broker: " << std::endl;
}

void Session::onWriteDone(TransportSocket *client)
{
  //  std::cout << "written broker: " << std::endl;
}

void Session::onReadyRead(TransportSocket *client, const Message &msg)
{
  //  std::cout << "read broker: " << std::endl;
}

}
<commit_msg>Revert some lines from previous merges.<commit_after>/*
*  Author(s):
*  - Cedric Gestes <gestes@aldebaran-robotics.com>
*  - Herve Cuche <hcuche@aldebaran-robotics.com>
*
*  Copyright (C) 2012 Aldebaran Robotics
*/

#include <qimessaging/session.hpp>
#include <qimessaging/datastream.hpp>
#include <qimessaging/transport.hpp>
#include <qimessaging/object.hpp>
#include "src/remoteobject_p.hpp"

static int uniqueRequestId = 0;

namespace qi {

Session::Session()
{
  _nthd = new qi::NetworkThread();

  tc = new qi::TransportSocket();
  tc->setDelegate(this);
}

Session::~Session()
{
  tc->disconnect();
  delete tc;
}

void Session::connect(const std::string &masterAddress)
{
  size_t begin = 0;
  size_t end = 0;
  end = masterAddress.find(":");

  std::string ip = masterAddress.substr(begin, end);
  begin = end + 1;

  unsigned int port;
  std::stringstream ss(masterAddress.substr(begin));
  ss >> port;

  tc->connect(ip, port, _nthd->getEventBase());
}

bool Session::disconnect()
{
  return true;
}

void Session::onDisconnected(TransportSocket *client)
{
}

bool Session::waitForConnected(int msecs)
{
  return tc->waitForConnected(msecs);
}

bool Session::waitForDisconnected(int msecs)
{
  return tc->waitForDisconnected(msecs);
}

std::vector<std::string> Session::services()
{
  std::vector<std::string> result;

  qi::Message msg;
  msg.setType(qi::Message::Call);
  msg.setSource(_name);
  msg.setFunction("services");

  tc->send(msg);

  tc->waitForId(msg.id());
  qi::Message ans;
  tc->read(msg.id(), &ans);

  qi::DataStream d(ans.data());
  d >> result;

  return result;
}

qi::TransportSocket* Session::serviceSocket(const std::string &name,
                                            const std::string &type)
{
  std::vector<std::string> result;
  qi::DataStream dr;
  qi::Message msg;
  dr << name;
  msg.setType(qi::Message::Call);
  msg.setFunction("service");
  msg.setData(dr.str());

  tc->send(msg);

  tc->waitForId(msg.id());
  qi::Message ans;
  tc->read(msg.id(), &ans);

  qi::DataStream d(ans.data());
  d >> result;

  qi::TransportSocket* ts = NULL;

  qi::EndpointInfo endpoint;
  size_t begin = 0;
  size_t end = 0;
  end = result[1].find(":");
  endpoint.type = result[1].substr(begin, end);
  begin = end + 3;
  end = result[1].find(":", begin);
  endpoint.ip = result[1].substr(begin, end - begin);
  begin = end + 1;
  std::stringstream ss(result[1].substr(begin));
  ss >> endpoint.port;

  ts = new qi::TransportSocket();
  ts->setDelegate(this);
  ts->connect(endpoint.ip, endpoint.port, _nthd->getEventBase());
  ts->waitForConnected();

  return ts;
}

qi::Object* Session::service(const std::string &name,
                             const std::string &type)
{
  qi::Object          *obj;
  qi::TransportSocket *ts = serviceSocket(name, type);

  if (ts == 0)
  {
    return 0;
  }

  qi::RemoteObject *robj = new qi::RemoteObject(ts, name);
  obj = robj;
  return obj;
}

void Session::onConnected(TransportSocket *client)
{
  //  std::cout << "connected broker: " << std::endl;
}

void Session::onWriteDone(TransportSocket *client)
{
  //  std::cout << "written broker: " << std::endl;
}

void Session::onReadyRead(TransportSocket *client, const Message &msg)
{
  //  std::cout << "read broker: " << std::endl;
}

}
<|endoftext|>


<commit_before>//
// Created by Miguel Rentes on 11/03/17.
//

#include "strings.h"

int main() {

    return EXIT_SUCCESS;
}
<commit_msg>Starts solution for the Attribute Parser challenge.<commit_after>//
// Created by Miguel Rentes on 11/03/17.
//

#include "strings.h"

int main() {
    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkFloatArray.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include "vtkFloatArray.h"

// Description:
// Instantiate object with 1 components.
vtkFloatArray::vtkFloatArray(int numComp)
{
  this->NumberOfComponents = (numComp < 1 ? 1 : numComp);
  this->Array = NULL;
  this->SaveUserArray = 0;
}

vtkFloatArray::~vtkFloatArray()
{
  if ((this->Array) && (!this->SaveUserArray)) delete [] this->Array;

}

void vtkFloatArray::SetArray(float* array, int size, int save)
{
  if ((this->Array) && (!this->SaveUserArray))
    {
      vtkDebugMacro (<< "Deleting the array...");
      delete [] this->Array;
    }
  else
    {
      vtkDebugMacro (<<"Warning, array not deleted, but will point to new array.");
    }

  vtkDebugMacro(<<"Setting array to: " << array);

  this->Array = array;
  this->Size = size;
  this->MaxId = size-1;
  this->SaveUserArray = save;
}

// Description:
// Allocate memory for this array. Delete old storage only if necessary.
int vtkFloatArray::Allocate(const int sz, const int ext)
{
  if ( sz > this->Size)
    {
    if ((this->Array) && (!this->SaveUserArray))
      {
      delete [] this->Array;
      }
    this->Size = ( sz > 0 ? sz : 1);
    if ( (this->Array = new float[this->Size]) == NULL ) return 0;
    this->SaveUserArray = 0;
    }

  this->Extend = ( ext > 0 ? ext : 1);
  this->MaxId = -1;

  return 1;
}

// Description:
// Release storage and reset array to initial state.
void vtkFloatArray::Initialize()
{
  if (( this->Array != NULL ) && (!this->SaveUserArray))
    {
    delete [] this->Array;
    }
  this->Array = NULL;
  this->Size = 0;
  this->MaxId = -1;
  this->SaveUserArray = 0;
}

// Description:
// Deep copy of another float array.
void vtkFloatArray::DeepCopy(vtkDataArray& fa)
{
  if ( fa.GetDataType() != VTK_FLOAT )
    {
    vtkDataArray::DeepCopy(fa);
    return;
    }

  if ( this != &fa )
    {
    if ((this->Array) && (!this->SaveUserArray))
      {
      delete [] this->Array;
      }

    this->NumberOfComponents = fa.GetNumberOfComponents();
    this->MaxId = fa.GetMaxId();
    this->Size = fa.GetSize();
    this->Extend = fa.GetExtend();
    this->SaveUserArray = 0;

    this->Array = new float[this->Size];
    memcpy(this->Array, (float *)fa.GetVoidPointer(0), this->Size*sizeof(float));
    }
}

void vtkFloatArray::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkObject::PrintSelf(os,indent);

  os << indent << "Array: " << this->Array << "\n";
}

// Protected function does "reallocate"
//
float *vtkFloatArray::Resize(const int sz)
{
  float *newArray;
  int newSize;

  if ( sz > this->Size )
    {
    newSize = this->Size + this->Extend*(((sz-this->Size)/this->Extend)+1);
    }
  else if (sz == this->Size)
    {
    return this->Array;
    }
  else
    {
    newSize = sz;
    }

  if ( (newArray = new float[newSize]) == NULL )
    {
    vtkErrorMacro(<< "Cannot allocate memory\n");
    return 0;
    }

  if (this->Array)
    {
    memcpy(newArray, this->Array,
	   (sz < this->Size ? sz : this->Size) * sizeof(float));
    if (!this->SaveUserArray)
      {
      delete [] this->Array;
      }
    }

  this->Size = newSize;
  this->Array = newArray;
  this->SaveUserArray = 0;
  return this->Array;
}

// Description:
// Set the number of n-tuples in the array.
void vtkFloatArray::SetNumberOfTuples(const int number)
{
  this->SetNumberOfValues(number*this->NumberOfComponents);
}

// Description:
// Get a pointer to a tuple at the ith location.
float *vtkFloatArray::GetTuple(const int i)
{
  return this->Array + this->NumberOfComponents*i;
}

// Description:
// Copy the tuple value into a user-provided array.
void vtkFloatArray::GetTuple(const int i, float tuple[])
{
  float *t = this->Array + this->NumberOfComponents*i;
  for (int j=0; j<this->NumberOfComponents; j++) tuple[j] = t[j];
}

// Description:
// Set the tuple value at the ith location in the array.
void vtkFloatArray::SetTuple(const int i, const float tuple[])
{
  int loc = i * this->NumberOfComponents;
  for (int j=0; j<this->NumberOfComponents; j++) this->Array[loc+j] = tuple[j];
}

// Description:
// Insert (memory allocation performed) the tuple into the ith location
// in the array.
void vtkFloatArray::InsertTuple(const int i, const float tuple[])
{
  float *t = this->WritePointer(i*this->NumberOfComponents,this->NumberOfComponents);

  for (int j=0; j<this->NumberOfComponents; j++) *t++ = *tuple++;
}

// Description:
// Insert (memory allocation performed) the tuple onto the end of the array.
int vtkFloatArray::InsertNextTuple(const float tuple[])
{
  int i = this->MaxId + 1;
  float *t = this->WritePointer(i,this->NumberOfComponents);

  for (i=0; i<this->NumberOfComponents; i++) *t++ = *tuple++;

  return this->MaxId / this->NumberOfComponents;

}

// Description:
// Return the data component at the ith tuple and jth component location.
// Note that i<NumberOfTuples and j<NumberOfComponents.
float vtkFloatArray::GetComponent(const int i, const int j)
{
  return this->GetValue(i*this->NumberOfComponents + j);
}

// Description:
// Set the data component at the ith tuple and jth component location.
// Note that i<NumberOfTuples and j<NumberOfComponents. Make sure enough
// memory has been allocated (use SetNumberOfTuples() and
// SetNumberOfComponents()).
void vtkFloatArray::SetComponent(const int i, const int j, const float c)
{
  this->SetValue(i*this->NumberOfComponents + j, c);
}

// Description:
// Insert the data component at ith tuple and jth component location.
// Note that memory allocation is performed as necessary to hold the data.
void vtkFloatArray::InsertComponent(const int i, const int j, const float c)
{
  this->InsertValue(i*this->NumberOfComponents + j, c);
}

<commit_msg>Added comment on SetArray.  Turek.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkFloatArray.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include "vtkFloatArray.h"

// Description:
// Instantiate object with 1 components.
vtkFloatArray::vtkFloatArray(int numComp)
{
  this->NumberOfComponents = (numComp < 1 ? 1 : numComp);
  this->Array = NULL;
  this->SaveUserArray = 0;
}

vtkFloatArray::~vtkFloatArray()
{
  if ((this->Array) && (!this->SaveUserArray)) delete [] this->Array;

}

// Description:
// This method lets the user specify data to be held by the array.  The
// array argument is a pointer to the data.  size is the size of
// the array supplied by the user.  Set save to 1 to keep the class
// from deleting the array when it cleans up or reallocates memory.
// The class uses the actual array provided; it does not copy the data
// from the suppled array.
void vtkFloatArray::SetArray(float* array, int size, int save)
{
  if ((this->Array) && (!this->SaveUserArray))
    {
      vtkDebugMacro (<< "Deleting the array...");
      delete [] this->Array;
    }
  else
    {
      vtkDebugMacro (<<"Warning, array not deleted, but will point to new array.");
    }

  vtkDebugMacro(<<"Setting array to: " << array);

  this->Array = array;
  this->Size = size;
  this->MaxId = size-1;
  this->SaveUserArray = save;
}

// Description:
// Allocate memory for this array. Delete old storage only if necessary.
int vtkFloatArray::Allocate(const int sz, const int ext)
{
  if ( sz > this->Size)
    {
    if ((this->Array) && (!this->SaveUserArray))
      {
      delete [] this->Array;
      }
    this->Size = ( sz > 0 ? sz : 1);
    if ( (this->Array = new float[this->Size]) == NULL ) return 0;
    this->SaveUserArray = 0;
    }

  this->Extend = ( ext > 0 ? ext : 1);
  this->MaxId = -1;

  return 1;
}

// Description:
// Release storage and reset array to initial state.
void vtkFloatArray::Initialize()
{
  if (( this->Array != NULL ) && (!this->SaveUserArray))
    {
    delete [] this->Array;
    }
  this->Array = NULL;
  this->Size = 0;
  this->MaxId = -1;
  this->SaveUserArray = 0;
}

// Description:
// Deep copy of another float array.
void vtkFloatArray::DeepCopy(vtkDataArray& fa)
{
  if ( fa.GetDataType() != VTK_FLOAT )
    {
    vtkDataArray::DeepCopy(fa);
    return;
    }

  if ( this != &fa )
    {
    if ((this->Array) && (!this->SaveUserArray))
      {
      delete [] this->Array;
      }

    this->NumberOfComponents = fa.GetNumberOfComponents();
    this->MaxId = fa.GetMaxId();
    this->Size = fa.GetSize();
    this->Extend = fa.GetExtend();
    this->SaveUserArray = 0;

    this->Array = new float[this->Size];
    memcpy(this->Array, (float *)fa.GetVoidPointer(0), this->Size*sizeof(float));
    }
}

void vtkFloatArray::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkObject::PrintSelf(os,indent);

  os << indent << "Array: " << this->Array << "\n";
}

// Protected function does "reallocate"
//
float *vtkFloatArray::Resize(const int sz)
{
  float *newArray;
  int newSize;

  if ( sz > this->Size )
    {
    newSize = this->Size + this->Extend*(((sz-this->Size)/this->Extend)+1);
    }
  else if (sz == this->Size)
    {
    return this->Array;
    }
  else
    {
    newSize = sz;
    }

  if ( (newArray = new float[newSize]) == NULL )
    {
    vtkErrorMacro(<< "Cannot allocate memory\n");
    return 0;
    }

  if (this->Array)
    {
    memcpy(newArray, this->Array,
	   (sz < this->Size ? sz : this->Size) * sizeof(float));
    if (!this->SaveUserArray)
      {
      delete [] this->Array;
      }
    }

  this->Size = newSize;
  this->Array = newArray;
  this->SaveUserArray = 0;
  return this->Array;
}

// Description:
// Set the number of n-tuples in the array.
void vtkFloatArray::SetNumberOfTuples(const int number)
{
  this->SetNumberOfValues(number*this->NumberOfComponents);
}

// Description:
// Get a pointer to a tuple at the ith location.
float *vtkFloatArray::GetTuple(const int i)
{
  return this->Array + this->NumberOfComponents*i;
}

// Description:
// Copy the tuple value into a user-provided array.
void vtkFloatArray::GetTuple(const int i, float tuple[])
{
  float *t = this->Array + this->NumberOfComponents*i;
  for (int j=0; j<this->NumberOfComponents; j++) tuple[j] = t[j];
}

// Description:
// Set the tuple value at the ith location in the array.
void vtkFloatArray::SetTuple(const int i, const float tuple[])
{
  int loc = i * this->NumberOfComponents;
  for (int j=0; j<this->NumberOfComponents; j++) this->Array[loc+j] = tuple[j];
}

// Description:
// Insert (memory allocation performed) the tuple into the ith location
// in the array.
void vtkFloatArray::InsertTuple(const int i, const float tuple[])
{
  float *t = this->WritePointer(i*this->NumberOfComponents,this->NumberOfComponents);

  for (int j=0; j<this->NumberOfComponents; j++) *t++ = *tuple++;
}

// Description:
// Insert (memory allocation performed) the tuple onto the end of the array.
int vtkFloatArray::InsertNextTuple(const float tuple[])
{
  int i = this->MaxId + 1;
  float *t = this->WritePointer(i,this->NumberOfComponents);

  for (i=0; i<this->NumberOfComponents; i++) *t++ = *tuple++;

  return this->MaxId / this->NumberOfComponents;

}

// Description:
// Return the data component at the ith tuple and jth component location.
// Note that i<NumberOfTuples and j<NumberOfComponents.
float vtkFloatArray::GetComponent(const int i, const int j)
{
  return this->GetValue(i*this->NumberOfComponents + j);
}

// Description:
// Set the data component at the ith tuple and jth component location.
// Note that i<NumberOfTuples and j<NumberOfComponents. Make sure enough
// memory has been allocated (use SetNumberOfTuples() and
// SetNumberOfComponents()).
void vtkFloatArray::SetComponent(const int i, const int j, const float c)
{
  this->SetValue(i*this->NumberOfComponents + j, c);
}

// Description:
// Insert the data component at ith tuple and jth component location.
// Note that memory allocation is performed as necessary to hold the data.
void vtkFloatArray::InsertComponent(const int i, const int j, const float c)
{
  this->InsertValue(i*this->NumberOfComponents + j, c);
}

<|endoftext|>


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

#ifndef LIBQ_EXCEPTION_EXCEPTION_HPP
#define LIBQ_EXCEPTION_EXCEPTION_HPP

#include <q/types.hpp>
#include <q/type_traits.hpp>

#include <exception>
#include <vector>
#include <iosfwd>
#include <sstream>

#define Q_THROW( ... ) \
	throw ::q::add_exception_properties( __VA_ARGS__ )

#define Q_MAKE_SIMPLE_EXCEPTION( Name ) \
	class Name \
	: public ::q::exception \
	{ \
		virtual const char* name( ) const noexcept override \
		{ \
			return #Name ; \
		} \
		using exception::exception; \
	}

/**
 * Run @c fn and ensure that it doesn't throw any exception. If it does, invoke
 * the "uncaught exception handler".
 */
#define Q_ENSURE_NOEXCEPT( fn ) \
	do \
	{ \
		try \
		{ \
			fn( ); \
		} \
		catch ( ... ) \
		{ \
			LIBQ_UNCAUGHT_EXCEPTION( std::current_exception( ) ); \
		} \
	} while ( false )

namespace q {

namespace detail {

template< typename T > class exception_info;

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

	template< typename T >
	const exception_info< T >* cast( ) const
	{
		return dynamic_cast< const exception_info< T >* >( this );
	}

	template< typename T >
	exception_info< T >* cast( )
	{
		return dynamic_cast< exception_info< T >* >( this );
	}

	virtual std::string string( ) const = 0;

protected:
	exception_info_base( )
	{ }
};

template< typename T >
class exception_info
: public exception_info_base
{
public:
	exception_info( ) = delete;
	exception_info( const exception_info& ) = delete;

	exception_info( exception_info&& ) = default;

	exception_info( T&& t )
	: t_( std::move( t ) )
	{ }

	exception_info( const T& t )
	: t_( t )
	{ }

	const T& get( ) const
	{
		return t_;
	}

	T consume( )
	{
		return std::move( t_ );
	}

	static exception_info< T >* cast( exception_info_base& eib )
	{
		return eib.cast< T >( );
	}

	static const exception_info< T >* cast( const exception_info_base& eib )
	{
		return eib.cast< T >( );
	}

	std::string string( ) const override
	{
		std::stringstream ss;
		ss << t_;
		return ss.str( );
	}

private:
	T t_;
};

} // namespace detail

class exception
: std::exception
{
public:
	exception( );
	exception( exception&& );
	exception( const exception& );
	virtual ~exception( );

	template< typename T >
	const detail::exception_info< T >* get_info( ) const
	{
		auto& _infos = infos( );
		for ( const auto& info : _infos )
		{
			auto ei = detail::exception_info< T >::cast( *info );
			if ( ei )
				return ei;
		}
		return nullptr;
	}

	template< typename T >
	detail::exception_info< T >* get_info( )
	{
		for ( auto& info : infos( ) )
		{
			auto ei = detail::exception_info< T >::cast( *info );
			if ( ei )
				return ei;
		}
		return nullptr;
	}

	const std::vector< std::shared_ptr< detail::exception_info_base > >&
	infos( ) const;

	template< typename T >
	typename std::enable_if<
		!std::is_lvalue_reference< T >::value and
		!is_c_string< T >::value,
		exception&
	>::type
	operator<<( T&& t )
	{
		std::shared_ptr< detail::exception_info_base > ptr(
			new detail::exception_info< T >(
				std::forward< T >( t ) ) );

		add_info( std::move( ptr ) );

		return *this;
	}

	template< typename T >
	typename std::enable_if< is_c_string< T >::value, exception& >::type
	operator<<( T&& t )
	{
		return operator<<( std::string( std::forward< T >( t ) ) );
	}

	virtual const char* name( ) const noexcept
	{
		return "q::exception";
	}

private:
	void add_info( std::shared_ptr< detail::exception_info_base >&& ptr );

	std::vector< std::shared_ptr< detail::exception_info_base > >&
	infos( );

	struct pimpl;
	std::unique_ptr< pimpl > pimpl_;
};

std::ostream& operator<<( std::ostream&, const exception& );

template< typename E, typename Arg, typename... Args >
static typename std::enable_if<
	std::is_rvalue_reference< E&& >::value,
	E
>::type
add_exception_properties( E&& e, Arg&& first, Args&&... args )
{
	e << std::forward< Arg >( first );

	return add_exception_properties(
		std::forward< E >( e ),
		std::forward< Args >( args )... );
}

template< typename E >
static typename std::enable_if<
	std::is_rvalue_reference< E&& >::value,
	E
>::type
add_exception_properties( E&& e )
{
	return std::move( e );
}

class stream_exception
{
public:
	stream_exception( ) = delete;
	stream_exception( std::exception_ptr&& e );
	stream_exception( const std::exception_ptr& e );

	const std::exception_ptr& exception( ) const;

private:
	std::exception_ptr exception_;
};

std::ostream& operator<<( std::ostream& , const stream_exception& );

} // namespace q

#endif // LIBQ_EXCEPTION_EXCEPTION_HPP
<commit_msg>Fixed sub-classing 'exception' with the same name (but different ns)<commit_after>/*
 * Copyright 2013 Gustaf Räntilä
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef LIBQ_EXCEPTION_EXCEPTION_HPP
#define LIBQ_EXCEPTION_EXCEPTION_HPP

#include <q/types.hpp>
#include <q/type_traits.hpp>

#include <exception>
#include <vector>
#include <iosfwd>
#include <sstream>

#define Q_THROW( ... ) \
	throw ::q::add_exception_properties( __VA_ARGS__ )

#define Q_MAKE_SIMPLE_EXCEPTION( Name ) \
	class Name \
	: public ::q::exception \
	{ \
		virtual const char* name( ) const noexcept override \
		{ \
			return #Name ; \
		} \
		using ::q::exception::exception; \
	}

/**
 * Run @c fn and ensure that it doesn't throw any exception. If it does, invoke
 * the "uncaught exception handler".
 */
#define Q_ENSURE_NOEXCEPT( fn ) \
	do \
	{ \
		try \
		{ \
			fn( ); \
		} \
		catch ( ... ) \
		{ \
			LIBQ_UNCAUGHT_EXCEPTION( std::current_exception( ) ); \
		} \
	} while ( false )

namespace q {

namespace detail {

template< typename T > class exception_info;

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

	template< typename T >
	const exception_info< T >* cast( ) const
	{
		return dynamic_cast< const exception_info< T >* >( this );
	}

	template< typename T >
	exception_info< T >* cast( )
	{
		return dynamic_cast< exception_info< T >* >( this );
	}

	virtual std::string string( ) const = 0;

protected:
	exception_info_base( )
	{ }
};

template< typename T >
class exception_info
: public exception_info_base
{
public:
	exception_info( ) = delete;
	exception_info( const exception_info& ) = delete;

	exception_info( exception_info&& ) = default;

	exception_info( T&& t )
	: t_( std::move( t ) )
	{ }

	exception_info( const T& t )
	: t_( t )
	{ }

	const T& get( ) const
	{
		return t_;
	}

	T consume( )
	{
		return std::move( t_ );
	}

	static exception_info< T >* cast( exception_info_base& eib )
	{
		return eib.cast< T >( );
	}

	static const exception_info< T >* cast( const exception_info_base& eib )
	{
		return eib.cast< T >( );
	}

	std::string string( ) const override
	{
		std::stringstream ss;
		ss << t_;
		return ss.str( );
	}

private:
	T t_;
};

} // namespace detail

class exception
: std::exception
{
public:
	exception( );
	exception( exception&& );
	exception( const exception& );
	virtual ~exception( );

	template< typename T >
	const detail::exception_info< T >* get_info( ) const
	{
		auto& _infos = infos( );
		for ( const auto& info : _infos )
		{
			auto ei = detail::exception_info< T >::cast( *info );
			if ( ei )
				return ei;
		}
		return nullptr;
	}

	template< typename T >
	detail::exception_info< T >* get_info( )
	{
		for ( auto& info : infos( ) )
		{
			auto ei = detail::exception_info< T >::cast( *info );
			if ( ei )
				return ei;
		}
		return nullptr;
	}

	const std::vector< std::shared_ptr< detail::exception_info_base > >&
	infos( ) const;

	template< typename T >
	typename std::enable_if<
		!std::is_lvalue_reference< T >::value and
		!is_c_string< T >::value,
		exception&
	>::type
	operator<<( T&& t )
	{
		std::shared_ptr< detail::exception_info_base > ptr(
			new detail::exception_info< T >(
				std::forward< T >( t ) ) );

		add_info( std::move( ptr ) );

		return *this;
	}

	template< typename T >
	typename std::enable_if< is_c_string< T >::value, exception& >::type
	operator<<( T&& t )
	{
		return operator<<( std::string( std::forward< T >( t ) ) );
	}

	virtual const char* name( ) const noexcept
	{
		return "q::exception";
	}

private:
	void add_info( std::shared_ptr< detail::exception_info_base >&& ptr );

	std::vector< std::shared_ptr< detail::exception_info_base > >&
	infos( );

	struct pimpl;
	std::unique_ptr< pimpl > pimpl_;
};

std::ostream& operator<<( std::ostream&, const exception& );

template< typename E, typename Arg, typename... Args >
static typename std::enable_if<
	std::is_rvalue_reference< E&& >::value,
	E
>::type
add_exception_properties( E&& e, Arg&& first, Args&&... args )
{
	e << std::forward< Arg >( first );

	return add_exception_properties(
		std::forward< E >( e ),
		std::forward< Args >( args )... );
}

template< typename E >
static typename std::enable_if<
	std::is_rvalue_reference< E&& >::value,
	E
>::type
add_exception_properties( E&& e )
{
	return std::move( e );
}

class stream_exception
{
public:
	stream_exception( ) = delete;
	stream_exception( std::exception_ptr&& e );
	stream_exception( const std::exception_ptr& e );

	const std::exception_ptr& exception( ) const;

private:
	std::exception_ptr exception_;
};

std::ostream& operator<<( std::ostream& , const stream_exception& );

} // namespace q

#endif // LIBQ_EXCEPTION_EXCEPTION_HPP
<|endoftext|>


<commit_before>#define DEBUG 1
/**
 * File    : D.cpp
 * Author  : Kazune Takahashi
 * Created : 11/23/2019, 9:31:05 PM
 * Powered by Visual Studio Code
 */
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
// ----- boost -----
#include <boost/rational.hpp>
// ----- using directives and manipulations -----
using boost::rational;
using namespace std;
using ll = long long;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
  }
}
template <typename T>
void ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
  }
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{x % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(const Mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(const Mint &a) { return *this += -a; }
  Mint &operator*=(const Mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(const Mint &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(const Mint &a) const { return Mint(*this) += a; }
  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
  bool operator<(const Mint &a) const { return x < a.x; }
  bool operator==(const Mint &a) const { return x == a.x; }
  const Mint power(ll N)
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      Mint half = power(N / 2);
      return half * half;
    }
  }
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
  return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
  return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
  return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
  return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
  return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
  return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
  vector<Mint<MOD>> inv, fact, factinv;
  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i = 2LL; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[MOD % i]) * (MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i = 1LL; i < MAX_SIZE; i++)
    {
      fact[i] = Mint<MOD>(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  Mint<MOD> operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
  Mint<MOD> catalan(int x, int y)
  {
    return (*this)(x + y, y) - (*this)(x + y, y - 1);
  }
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}
// ----- main() -----

using info = tuple<vector<ll>, vector<ll>>;

info calc(info X, ll &ans)
{
  vector<ll> &d{get<0>(X)}, &c{get<1>(X)};
  assert(d.size() == c.size());
  ll manipulation{accumulate(c.begin(), c.end(), 0LL) - 1LL};
  ll sum{0LL};
  for (auto i = 0u; i < d.size(); i++)
  {
    sum += d[i] * c[i];
  }
  ll add_up{sum / 10};
#if DEBUG == 1
  cerr << "manipulation = " << manipulation << ", add_up = " << add_up << endl;
#endif
  ans += manipulation + add_up;
  vector<ll> nd, nc;
  while (sum > 0)
  {
    nd.push_back(sum % 10);
    nc.push_back(1);
    sum /= 10;
  }
  return info{nd, nc};
}

int main()
{
  ll M;
  cin >> M;
  vector<ll> d(M), c(M);
  for (auto i = 0; i < M; i++)
  {
    cin >> d[i] >> c[i];
  }
  info X{d, c};
  ll ans{0LL};
  while (!(get<0>(X).size() == 1u && get<1>(X).size() == 1u && get<1>(X)[0] == 1))
  {
    X = calc(X, ans);
  }
  cout << ans << endl;
}
<commit_msg>tried D.cpp to 'D'<commit_after>#define DEBUG 1
/**
 * File    : D.cpp
 * Author  : Kazune Takahashi
 * Created : 11/23/2019, 9:31:05 PM
 * Powered by Visual Studio Code
 */
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
// ----- boost -----
#include <boost/rational.hpp>
// ----- using directives and manipulations -----
using boost::rational;
using namespace std;
using ll = long long;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
  }
}
template <typename T>
void ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
  }
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{x % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(const Mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(const Mint &a) { return *this += -a; }
  Mint &operator*=(const Mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(const Mint &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(const Mint &a) const { return Mint(*this) += a; }
  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
  bool operator<(const Mint &a) const { return x < a.x; }
  bool operator==(const Mint &a) const { return x == a.x; }
  const Mint power(ll N)
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      Mint half = power(N / 2);
      return half * half;
    }
  }
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
  return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
  return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
  return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
  return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
  return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
  return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
  vector<Mint<MOD>> inv, fact, factinv;
  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i = 2LL; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[MOD % i]) * (MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i = 1LL; i < MAX_SIZE; i++)
    {
      fact[i] = Mint<MOD>(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  Mint<MOD> operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
  Mint<MOD> catalan(int x, int y)
  {
    return (*this)(x + y, y) - (*this)(x + y, y - 1);
  }
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}
// ----- main() -----

using info = tuple<vector<ll>, vector<ll>>;

info calc(info X, ll &ans)
{
  vector<ll> &d{get<0>(X)}, &c{get<1>(X)};
  assert(d.size() == c.size());
  ll manipulation{accumulate(c.begin(), c.end(), 0LL) - 1LL};
  ll sum{0LL};
  for (auto i = 0u; i < d.size(); i++)
  {
    sum += d[i] * c[i];
  }
#if DEBUG == 1
  cerr << "manipulation = " << manipulation << endl;
#endif
  ans += manipulation;
  vector<ll> nd{1, sum % 10};
  vector<ll> nc{sum / 10, 1};
  return info{nd, nc};
}

int main()
{
  ll M;
  cin >> M;
  vector<ll> d(M), c(M);
  for (auto i = 0; i < M; i++)
  {
    cin >> d[i] >> c[i];
  }
  info X{d, c};
  ll ans{0LL};
  while (!(get<0>(X).size() == 1u && get<1>(X).size() == 1u && get<1>(X)[0] == 1))
  {
    X = calc(X, ans);
  }
  cout << ans << endl;
}
<|endoftext|>


<commit_before>#include "Vertex.hpp"
#include "GameManager.hpp"
#include "simple_hero.hpp"

int main( void ) {
	GraphMap* map = new GraphMap( "maps/basic.txt" );

	map.make_graph( map );

	delete( map );
	return 0;
}
<commit_msg>Fixed capitalization/ added lines<commit_after>#include "Vertex.hpp"
#include "GameManager.hpp"
#include "simple_hero.hpp"
#include "stdio.h"

int main( void ) {
	GraphMap* map = new GraphMap( fopen( "maps/basic.txt", "r" ) );

	Simple_Hero hero( 1 );

	hero.make_graph( map );

	delete( map );
	return 0;
}
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

#include <TChain.h>
#include <TFile.h>

#include "AliTender.h"
#include "AliTenderSupply.h"
#include "AliAnalysisManager.h"
#include "AliCDBManager.h"
#include "AliESDEvent.h"
#include "AliESDInputHandler.h"
#include "AliLog.h"

ClassImp(AliTender)

//______________________________________________________________________________
AliTender::AliTender():
           AliAnalysisTaskSE(),
           fRun(0),
           fRunChanged(kFALSE),
           fCDBkey(0),
           fDefaultStorage(),
           fCDB(NULL),
           fESDhandler(NULL),
           fESD(NULL),
           fSupplies(NULL),
           fCDBSettings(NULL)
{
// Dummy constructor
}

//______________________________________________________________________________
AliTender::AliTender(const char* name):
           AliAnalysisTaskSE(name),
           fRun(0),
           fRunChanged(kFALSE),
           fCDBkey(0),
           fDefaultStorage(),
           fCDB(NULL),
           fESDhandler(NULL),
           fESD(NULL),
           fSupplies(NULL),
           fCDBSettings(NULL)
{
// Default constructor
  DefineOutput(1,  AliESDEvent::Class());
}

//______________________________________________________________________________
AliTender::~AliTender()
{
// Destructor
  if (fSupplies) {
    fSupplies->Delete();
    delete fSupplies;
  }
}

//______________________________________________________________________________
void AliTender::AddSupply(AliTenderSupply *supply)
{
// Addition of supplies.
  if (!fSupplies) fSupplies = new TObjArray();
  if (fSupplies->FindObject(supply)) {
     Error("AddSupply", "Tender supply %s already connected.", supply->GetName());
     return;
  }
  fSupplies->Add(supply);
  supply->SetTender(this);
}

//______________________________________________________________________________
void AliTender::ConnectInputData(Option_t* option)
{
// Connect the input data, create CDB manager.
  if (fDebug > 1) Printf("AliTender::ConnectInputData()\n");
  AliAnalysisTaskSE::ConnectInputData(option);
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) AliFatal("No tender without an analysis manager");
  fESDhandler = dynamic_cast<AliESDInputHandler *>(mgr->GetInputEventHandler());

  if (fESDhandler) {
     fESD = fESDhandler->GetEvent();
  } else {
     AliFatal("No ESD input event handler connected") ;
  }
  // Create CDB manager
  if (!fDefaultStorage.Length()) AliFatal("Default CDB storage not set.");
  fCDB = AliCDBManager::Instance();
  // SetDefault storage. Specific storages must be set by AliTenderSupply::Init()
  fCDB->SetDefaultStorage(fDefaultStorage);
  fRun = fESD->GetRunNumber();
  // Unlock CDB
  fCDBkey = fCDB->SetLock(kFALSE, fCDBkey);
  fCDB->SetRun(fRun);
  TIter next(fSupplies);
  AliTenderSupply *supply;
  while ((supply=(AliTenderSupply*)next())) supply->Init();
  // Lock CDB
  fCDBkey = fCDB->SetLock(kTRUE, fCDBkey);
}

//______________________________________________________________________________
void AliTender::UserCreateOutputObjects()
{
// Nothing for the moment, but we may need ESD event replication here.
  if (fDebug > 1) Printf("AliTender::CreateOutputObjects()\n");
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) AliFatal("No tender without an analysis manager");
  fESDhandler = dynamic_cast<AliESDInputHandler *>(mgr->GetInputEventHandler());
  if (fESDhandler && TObject::TestBit(kCheckEventSelection)) {
     fESDhandler->SetUserCallSelectionMask(kTRUE);
     Info("UserCreateOutputObjects","The TENDER will check the event selection. Make sure you add the tender as FIRST wagon!");
  }
}

//______________________________________________________________________________
void AliTender::UserExec(Option_t* /*option*/)
{
//
// Execute all supplied analysis of one event. Notify run change via RunChanged().
  if (fDebug > 1) {
    Long64_t entry = fESDhandler->GetReadEntry();
    Printf("AliTender::Exec() %s ==> processing event %lld\n", fESDhandler->GetTree()->GetCurrentFile()->GetName(),entry);
  }
  fESD = fESDhandler->GetEvent();
  if (TObject::TestBit(kCheckEventSelection)) fESDhandler->CheckSelectionMask();

// Call the user analysis
  // Unlock CDB
  fCDBkey = fCDB->SetLock(kFALSE, fCDBkey);
  // Intercept when the run number changed
  if (fRun != fESD->GetRunNumber()) {
    fRunChanged = kTRUE;
    fRun = fESD->GetRunNumber();
    fCDB->SetRun(fRun);
  }
  TIter next(fSupplies);
  AliTenderSupply *supply;
  while ((supply=(AliTenderSupply*)next())) supply->ProcessEvent();
  fRunChanged = kFALSE;
  // Lock CDB
  fCDBkey = fCDB->SetLock(kTRUE, fCDBkey);
  PostData(1, fESD);
}

//______________________________________________________________________________
void AliTender::SetDefaultCDBStorage(const char *dbString)
{
// Set default CDB storage
   fDefaultStorage = dbString;
}
<commit_msg>Corrected calling sequence.<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

#include <TChain.h>
#include <TFile.h>

#include "AliTender.h"
#include "AliTenderSupply.h"
#include "AliAnalysisManager.h"
#include "AliCDBManager.h"
#include "AliESDEvent.h"
#include "AliESDInputHandler.h"
#include "AliLog.h"

ClassImp(AliTender)

//______________________________________________________________________________
AliTender::AliTender():
           AliAnalysisTaskSE(),
           fRun(0),
           fRunChanged(kFALSE),
           fCDBkey(0),
           fDefaultStorage(),
           fCDB(NULL),
           fESDhandler(NULL),
           fESD(NULL),
           fSupplies(NULL),
           fCDBSettings(NULL)
{
// Dummy constructor
}

//______________________________________________________________________________
AliTender::AliTender(const char* name):
           AliAnalysisTaskSE(name),
           fRun(0),
           fRunChanged(kFALSE),
           fCDBkey(0),
           fDefaultStorage(),
           fCDB(NULL),
           fESDhandler(NULL),
           fESD(NULL),
           fSupplies(NULL),
           fCDBSettings(NULL)
{
// Default constructor
  DefineOutput(1,  AliESDEvent::Class());
}

//______________________________________________________________________________
AliTender::~AliTender()
{
// Destructor
  if (fSupplies) {
    fSupplies->Delete();
    delete fSupplies;
  }
}

//______________________________________________________________________________
void AliTender::AddSupply(AliTenderSupply *supply)
{
// Addition of supplies.
  if (!fSupplies) fSupplies = new TObjArray();
  if (fSupplies->FindObject(supply)) {
     Error("AddSupply", "Tender supply %s already connected.", supply->GetName());
     return;
  }
  fSupplies->Add(supply);
  supply->SetTender(this);
}

//______________________________________________________________________________
void AliTender::ConnectInputData(Option_t* option)
{
// Connect the input data, create CDB manager.
  if (fDebug > 1) Printf("AliTender::ConnectInputData()\n");
  AliAnalysisTaskSE::ConnectInputData(option);
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) AliFatal("No tender without an analysis manager");
  fESDhandler = dynamic_cast<AliESDInputHandler *>(mgr->GetInputEventHandler());

  if (fESDhandler) {
     fESD = fESDhandler->GetEvent();
  } else {
     AliFatal("No ESD input event handler connected") ;
  }
  // Create CDB manager
  if (!fDefaultStorage.Length()) AliFatal("Default CDB storage not set.");
  fCDB = AliCDBManager::Instance();
  // SetDefault storage. Specific storages must be set by AliTenderSupply::Init()
  fCDB->SetDefaultStorage(fDefaultStorage);
  fRun = fESD->GetRunNumber();
  // Unlock CDB
  fCDBkey = fCDB->SetLock(kFALSE, fCDBkey);
  fCDB->SetRun(fRun);
  TIter next(fSupplies);
  AliTenderSupply *supply;
  while ((supply=(AliTenderSupply*)next())) supply->Init();
  // Lock CDB
  fCDBkey = fCDB->SetLock(kTRUE, fCDBkey);
}

//______________________________________________________________________________
void AliTender::UserCreateOutputObjects()
{
// Nothing for the moment, but we may need ESD event replication here.
  if (fDebug > 1) Printf("AliTender::CreateOutputObjects()\n");
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) AliFatal("No tender without an analysis manager");
  fESDhandler = dynamic_cast<AliESDInputHandler *>(mgr->GetInputEventHandler());
  if (fESDhandler && TObject::TestBit(kCheckEventSelection)) {
     fESDhandler->SetUserCallSelectionMask(kTRUE);
     Info("UserCreateOutputObjects","The TENDER will check the event selection. Make sure you add the tender as FIRST wagon!");
  }
}

//______________________________________________________________________________
void AliTender::UserExec(Option_t* /*option*/)
{
//
// Execute all supplied analysis of one event. Notify run change via RunChanged().
  if (fDebug > 1) {
    Long64_t entry = fESDhandler->GetReadEntry();
    Printf("AliTender::Exec() %s ==> processing event %lld\n", fESDhandler->GetTree()->GetCurrentFile()->GetName(),entry);
  }
  fESD = fESDhandler->GetEvent();

// Call the user analysis
  // Unlock CDB
  fCDBkey = fCDB->SetLock(kFALSE, fCDBkey);
  // Intercept when the run number changed
  if (fRun != fESD->GetRunNumber()) {
    fRunChanged = kTRUE;
    fRun = fESD->GetRunNumber();
    fCDB->SetRun(fRun);
  }
  TIter next(fSupplies);
  AliTenderSupply *supply;
  while ((supply=(AliTenderSupply*)next())) supply->ProcessEvent();
  fRunChanged = kFALSE;

  if (TObject::TestBit(kCheckEventSelection)) fESDhandler->CheckSelectionMask();

  // Lock CDB
  fCDBkey = fCDB->SetLock(kTRUE, fCDBkey);
  PostData(1, fESD);
}

//______________________________________________________________________________
void AliTender::SetDefaultCDBStorage(const char *dbString)
{
// Set default CDB storage
   fDefaultStorage = dbString;
}
<|endoftext|>


<commit_before>/*
 * Manager.cpp
 *
 *  Created on: 23 Oct 2015
 *      Author: hieu
 */
#include <boost/foreach.hpp>
#include <cstdlib>
#include <vector>
#include <sstream>
#include "../System.h"
#include "../TranslationModel/PhraseTable.h"
#include "Manager.h"
#include "InputPath.h"
#include "Hypothesis.h"
#include "TargetPhraseImpl.h"
#include "ActiveChart.h"
#include "Sentence.h"

using namespace std;

namespace Moses2
{
namespace SCFG
{

Manager::Manager(System &sys, const TranslationTask &task,
    const std::string &inputStr, long translationId)
:ManagerBase(sys, task, inputStr, translationId)
{

}

Manager::~Manager()
{

}

void Manager::Decode()
{
  // init pools etc
  //cerr << "START InitPools()" << endl;
  InitPools();
  //cerr << "START ParseInput()" << endl;

  FactorCollection &vocab = system.GetVocab();
  m_input = Sentence::CreateFromString(GetPool(), vocab, system, m_inputStr,
      m_translationId);

  const SCFG::Sentence &sentence = static_cast<const SCFG::Sentence&>(GetInput());

  size_t inputSize = sentence.GetSize();
  //cerr << "inputSize=" << inputSize << endl;

  m_inputPaths.Init(sentence, *this);
  //cerr << "CREATED m_inputPaths" << endl;

  m_stacks.Init(*this, inputSize);
  //cerr << "CREATED m_stacks" << endl;

  for (int startPos = inputSize - 1; startPos >= 0; --startPos) {
    //cerr << endl << "startPos=" << startPos << endl;
    SCFG::InputPath &initPath = *m_inputPaths.GetMatrix().GetValue(startPos, 0);

    //cerr << "BEFORE InitActiveChart=" << initPath.Debug(system) << endl;
    InitActiveChart(initPath);
    //cerr << "AFTER InitActiveChart=" << initPath.Debug(system) << endl;

    int maxPhraseSize = inputSize - startPos + 1;
    for (int phraseSize = 1; phraseSize < maxPhraseSize; ++phraseSize) {
      //cerr << endl << "phraseSize=" << phraseSize << endl;
      SCFG::InputPath &path = *m_inputPaths.GetMatrix().GetValue(startPos, phraseSize);

      Stack &stack = m_stacks.GetStack(startPos, phraseSize);

      //cerr << "BEFORE LOOKUP path=" << path.Debug(system) << endl;
      Lookup(path);
      //cerr << "AFTER LOOKUP path="  << path.Debug(system) << endl;
      Decode(path, stack);
      //cerr << "AFTER DECODE path=" << path.Debug(system) << endl;

      LookupUnary(path);
      //cerr << "AFTER LookupUnary path=" << path.Debug(system) << endl;

      //cerr << "#rules=" << path.GetNumRules() << endl;
    }
  }

  //m_stacks.OutputStacks();
}

void Manager::InitActiveChart(SCFG::InputPath &path)
{
   size_t numPt = system.mappings.size();
   //cerr << "numPt=" << numPt << endl;

   for (size_t i = 0; i < numPt; ++i) {
     const PhraseTable &pt = *system.mappings[i];
     //cerr << "START InitActiveChart" << endl;
     pt.InitActiveChart(GetPool(), *this, path);
     //cerr << "FINISHED InitActiveChart" << endl;
   }
}

void Manager::Lookup(SCFG::InputPath &path)
{
  size_t numPt = system.mappings.size();
  //cerr << "numPt=" << numPt << endl;

  for (size_t i = 0; i < numPt; ++i) {
    const PhraseTable &pt = *system.mappings[i];
    size_t maxChartSpan = system.maxChartSpans[i];
    pt.Lookup(GetPool(), *this, maxChartSpan, m_stacks, path);
  }

  /*
  size_t tpsNum = path.targetPhrases.GetSize();
  if (tpsNum) {
    cerr << tpsNum << " " << path << endl;
  }
  */
}

void Manager::LookupUnary(SCFG::InputPath &path)
{
  size_t numPt = system.mappings.size();
  //cerr << "numPt=" << numPt << endl;

  for (size_t i = 0; i < numPt; ++i) {
    const PhraseTable &pt = *system.mappings[i];
    pt.LookupUnary(GetPool(), *this, m_stacks, path);
  }

  /*
  size_t tpsNum = path.targetPhrases.GetSize();
  if (tpsNum) {
    cerr << tpsNum << " " << path << endl;
  }
  */
}

///////////////////////////////////////////////////////////////
// CUBE-PRUNING
///////////////////////////////////////////////////////////////
void Manager::Decode(SCFG::InputPath &path, Stack &stack)
{
  // clear cube pruning data
  //std::vector<QueueItem*> &container = Container(m_queue);
  //container.clear();
  Recycler<HypothesisBase*> &hypoRecycler = GetHypoRecycle();
  while (!m_queue.empty()) {
    QueueItem *item = m_queue.top();
    m_queue.pop();
    // recycle unused hypos from queue
    Hypothesis *hypo = item->hypo;
    hypoRecycler.Recycle(hypo);

    // recycle queue item
    m_queueItemRecycler.push_back(item);
  }

  m_seenPositions.clear();

  // init queue
  BOOST_FOREACH(const InputPath::Coll::value_type &valPair, *path.targetPhrases) {
    const SymbolBind &symbolBind = valPair.first;
    const SCFG::TargetPhrases &tps = *valPair.second;
    CreateQueue(path, symbolBind, tps);
  }

  // MAIN LOOP
  size_t pops = 0;
  while (!m_queue.empty() && pops < system.options.cube.pop_limit) {
    //cerr << "pops=" << pops << endl;
    QueueItem *item = m_queue.top();
    m_queue.pop();

    // add hypo to stack
    Hypothesis *hypo = item->hypo;

    //cerr << "hypo=" << *hypo << " " << endl;
    stack.Add(hypo, GetHypoRecycle(), arcLists);
    //cerr << "Added " << *hypo << " " << endl;

    item->CreateNext(GetSystemPool(), GetPool(), *this, m_queue, m_seenPositions, path);
    //cerr << "Created next " << endl;
    m_queueItemRecycler.push_back(item);

    ++pops;
  }

}

void Manager::CreateQueue(
    const SCFG::InputPath &path,
    const SymbolBind &symbolBind,
    const SCFG::TargetPhrases &tps)
{
  QueueItem *item = QueueItem::Create(GetPool(), *this);
  item->Init(GetPool(), symbolBind, tps);
  for (size_t i = 0; i < symbolBind.coll.size(); ++i) {
    const SymbolBindElement &ele = symbolBind.coll[i];
    if (ele.hypos) {
      item->AddHypos(*ele.hypos);
    }
  }
  item->CreateHypo(GetSystemPool(), *this, path, symbolBind);

  //cerr << "hypo=" << item->hypo->Debug(system) << endl;

  m_queue.push(item);
}

///////////////////////////////////////////////////////////////
// NON CUBE-PRUNING
///////////////////////////////////////////////////////////////
/*
void Manager::Decode(SCFG::InputPath &path, Stack &stack)
{
  //cerr << "path=" << path << endl;

  boost::unordered_map<SCFG::SymbolBind, SCFG::TargetPhrases*>::const_iterator iterOuter;
  for (iterOuter = path.targetPhrases->begin(); iterOuter != path.targetPhrases->end(); ++iterOuter) {
    const SCFG::SymbolBind &symbolBind = iterOuter->first;

    const SCFG::TargetPhrases &tps = *iterOuter->second;
    //cerr << "symbolBind=" << symbolBind << " tps=" << tps.GetSize() << endl;

    SCFG::TargetPhrases::const_iterator iter;
    for (iter = tps.begin(); iter != tps.end(); ++iter) {
      const SCFG::TargetPhraseImpl &tp = **iter;
      //cerr << "tp=" << tp << endl;
      ExpandHypo(path, symbolBind, tp, stack);
    }
  }
}
*/

void Manager::ExpandHypo(
    const SCFG::InputPath &path,
    const SCFG::SymbolBind &symbolBind,
    const SCFG::TargetPhraseImpl &tp,
    Stack &stack)
{
  Recycler<HypothesisBase*> &hypoRecycler = GetHypoRecycle();

  std::vector<const SymbolBindElement*> ntEles = symbolBind.GetNTElements();
  Vector<size_t> prevHyposIndices(GetPool(), symbolBind.numNT);
  assert(ntEles.size() == symbolBind.numNT);
  //cerr << "ntEles:" << ntEles.size() << endl;

  size_t ind = 0;
  while (IncrPrevHypoIndices(prevHyposIndices, ind, ntEles)) {
    SCFG::Hypothesis *hypo = SCFG::Hypothesis::Create(GetSystemPool(), *this);
    hypo->Init(*this, path, symbolBind, tp, prevHyposIndices);
    hypo->EvaluateWhenApplied();

    stack.Add(hypo, hypoRecycler, arcLists);

    ++ind;
  }
}

bool Manager::IncrPrevHypoIndices(
    Vector<size_t> &prevHyposIndices,
    size_t ind,
    const std::vector<const SymbolBindElement*> ntEles)
{
  if (ntEles.size() == 0) {
    // no nt. Do the 1st
    return ind ? false : true;
  }

  size_t numHypos = 0;

  //cerr << "IncrPrevHypoIndices:" << ind << " " << ntEles.size() << " ";
  for (size_t i = 0; i < ntEles.size() - 1; ++i) {
    const SymbolBindElement &ele = *ntEles[i];
    const Hypotheses &hypos = *ele.hypos;
    numHypos = hypos.size();

    std::div_t divRet = std::div((int)ind, (int)numHypos);
    ind = divRet.quot;

    size_t hypoInd = divRet.rem;
    prevHyposIndices[i] = hypoInd;
    //cerr << "(" << i << "," << ind << "," << numHypos << "," << hypoInd << ")";
  }

  // last
  prevHyposIndices.back() = ind;

  // check if last is over limit
  const SymbolBindElement &ele = *ntEles.back();
  const Hypotheses &hypos = *ele.hypos;
  numHypos = hypos.size();

  //cerr << "(" << (ntEles.size() - 1) << "," << ind << "," << numHypos << ","  << ind << ")";
  //cerr << endl;

  if (ind >= numHypos) {
    return false;
  }
  else {
    return true;
  }
}

std::string Manager::OutputBest() const
{
  string outStr;
  const Stack &lastStack = m_stacks.GetLastStack();
  const Hypothesis *bestHypo = lastStack.GetBestHypo(*this, const_cast<ArcLists&>(arcLists));

  if (bestHypo) {
    //cerr << "BEST TRANSLATION: " << bestHypo << bestHypo->Debug(system) << endl;
    //cerr << " " << out.str() << endl;
    stringstream out;
    bestHypo->OutputToStream(out);

    outStr = out.str();
    outStr = outStr.substr(4);
    outStr = outStr.substr(0, outStr.size() - 6);

    if (system.options.output.ReportHypoScore) {
      outStr = SPrint(bestHypo->GetScores().GetTotalScore()) + " " + outStr;
    }
  }
  else {
    if (system.options.output.ReportHypoScore) {
      outStr = "0 ";
    }

    //cerr << "NO TRANSLATION " << m_input->GetTranslationId() << endl;
  }

  outStr += "\n";
  return outStr;
}

} // namespace
}

<commit_msg>don't output <s> </s><commit_after>/*
 * Manager.cpp
 *
 *  Created on: 23 Oct 2015
 *      Author: hieu
 */
#include <boost/foreach.hpp>
#include <cstdlib>
#include <vector>
#include <sstream>
#include "../System.h"
#include "../TranslationModel/PhraseTable.h"
#include "Manager.h"
#include "InputPath.h"
#include "Hypothesis.h"
#include "TargetPhraseImpl.h"
#include "ActiveChart.h"
#include "Sentence.h"

using namespace std;

namespace Moses2
{
namespace SCFG
{

Manager::Manager(System &sys, const TranslationTask &task,
    const std::string &inputStr, long translationId)
:ManagerBase(sys, task, inputStr, translationId)
{

}

Manager::~Manager()
{

}

void Manager::Decode()
{
  // init pools etc
  //cerr << "START InitPools()" << endl;
  InitPools();
  //cerr << "START ParseInput()" << endl;

  FactorCollection &vocab = system.GetVocab();
  m_input = Sentence::CreateFromString(GetPool(), vocab, system, m_inputStr,
      m_translationId);

  const SCFG::Sentence &sentence = static_cast<const SCFG::Sentence&>(GetInput());

  size_t inputSize = sentence.GetSize();
  //cerr << "inputSize=" << inputSize << endl;

  m_inputPaths.Init(sentence, *this);
  //cerr << "CREATED m_inputPaths" << endl;

  m_stacks.Init(*this, inputSize);
  //cerr << "CREATED m_stacks" << endl;

  for (int startPos = inputSize - 1; startPos >= 0; --startPos) {
    //cerr << endl << "startPos=" << startPos << endl;
    SCFG::InputPath &initPath = *m_inputPaths.GetMatrix().GetValue(startPos, 0);

    //cerr << "BEFORE InitActiveChart=" << initPath.Debug(system) << endl;
    InitActiveChart(initPath);
    //cerr << "AFTER InitActiveChart=" << initPath.Debug(system) << endl;

    int maxPhraseSize = inputSize - startPos + 1;
    for (int phraseSize = 1; phraseSize < maxPhraseSize; ++phraseSize) {
      //cerr << endl << "phraseSize=" << phraseSize << endl;
      SCFG::InputPath &path = *m_inputPaths.GetMatrix().GetValue(startPos, phraseSize);

      Stack &stack = m_stacks.GetStack(startPos, phraseSize);

      //cerr << "BEFORE LOOKUP path=" << path.Debug(system) << endl;
      Lookup(path);
      //cerr << "AFTER LOOKUP path="  << path.Debug(system) << endl;
      Decode(path, stack);
      //cerr << "AFTER DECODE path=" << path.Debug(system) << endl;

      LookupUnary(path);
      //cerr << "AFTER LookupUnary path=" << path.Debug(system) << endl;

      //cerr << "#rules=" << path.GetNumRules() << endl;
    }
  }

  //m_stacks.OutputStacks();
}

void Manager::InitActiveChart(SCFG::InputPath &path)
{
   size_t numPt = system.mappings.size();
   //cerr << "numPt=" << numPt << endl;

   for (size_t i = 0; i < numPt; ++i) {
     const PhraseTable &pt = *system.mappings[i];
     //cerr << "START InitActiveChart" << endl;
     pt.InitActiveChart(GetPool(), *this, path);
     //cerr << "FINISHED InitActiveChart" << endl;
   }
}

void Manager::Lookup(SCFG::InputPath &path)
{
  size_t numPt = system.mappings.size();
  //cerr << "numPt=" << numPt << endl;

  for (size_t i = 0; i < numPt; ++i) {
    const PhraseTable &pt = *system.mappings[i];
    size_t maxChartSpan = system.maxChartSpans[i];
    pt.Lookup(GetPool(), *this, maxChartSpan, m_stacks, path);
  }

  /*
  size_t tpsNum = path.targetPhrases.GetSize();
  if (tpsNum) {
    cerr << tpsNum << " " << path << endl;
  }
  */
}

void Manager::LookupUnary(SCFG::InputPath &path)
{
  size_t numPt = system.mappings.size();
  //cerr << "numPt=" << numPt << endl;

  for (size_t i = 0; i < numPt; ++i) {
    const PhraseTable &pt = *system.mappings[i];
    pt.LookupUnary(GetPool(), *this, m_stacks, path);
  }

  /*
  size_t tpsNum = path.targetPhrases.GetSize();
  if (tpsNum) {
    cerr << tpsNum << " " << path << endl;
  }
  */
}

///////////////////////////////////////////////////////////////
// CUBE-PRUNING
///////////////////////////////////////////////////////////////
void Manager::Decode(SCFG::InputPath &path, Stack &stack)
{
  // clear cube pruning data
  //std::vector<QueueItem*> &container = Container(m_queue);
  //container.clear();
  Recycler<HypothesisBase*> &hypoRecycler = GetHypoRecycle();
  while (!m_queue.empty()) {
    QueueItem *item = m_queue.top();
    m_queue.pop();
    // recycle unused hypos from queue
    Hypothesis *hypo = item->hypo;
    hypoRecycler.Recycle(hypo);

    // recycle queue item
    m_queueItemRecycler.push_back(item);
  }

  m_seenPositions.clear();

  // init queue
  BOOST_FOREACH(const InputPath::Coll::value_type &valPair, *path.targetPhrases) {
    const SymbolBind &symbolBind = valPair.first;
    const SCFG::TargetPhrases &tps = *valPair.second;
    CreateQueue(path, symbolBind, tps);
  }

  // MAIN LOOP
  size_t pops = 0;
  while (!m_queue.empty() && pops < system.options.cube.pop_limit) {
    //cerr << "pops=" << pops << endl;
    QueueItem *item = m_queue.top();
    m_queue.pop();

    // add hypo to stack
    Hypothesis *hypo = item->hypo;

    //cerr << "hypo=" << *hypo << " " << endl;
    stack.Add(hypo, GetHypoRecycle(), arcLists);
    //cerr << "Added " << *hypo << " " << endl;

    item->CreateNext(GetSystemPool(), GetPool(), *this, m_queue, m_seenPositions, path);
    //cerr << "Created next " << endl;
    m_queueItemRecycler.push_back(item);

    ++pops;
  }

}

void Manager::CreateQueue(
    const SCFG::InputPath &path,
    const SymbolBind &symbolBind,
    const SCFG::TargetPhrases &tps)
{
  QueueItem *item = QueueItem::Create(GetPool(), *this);
  item->Init(GetPool(), symbolBind, tps);
  for (size_t i = 0; i < symbolBind.coll.size(); ++i) {
    const SymbolBindElement &ele = symbolBind.coll[i];
    if (ele.hypos) {
      item->AddHypos(*ele.hypos);
    }
  }
  item->CreateHypo(GetSystemPool(), *this, path, symbolBind);

  //cerr << "hypo=" << item->hypo->Debug(system) << endl;

  m_queue.push(item);
}

///////////////////////////////////////////////////////////////
// NON CUBE-PRUNING
///////////////////////////////////////////////////////////////
/*
void Manager::Decode(SCFG::InputPath &path, Stack &stack)
{
  //cerr << "path=" << path << endl;

  boost::unordered_map<SCFG::SymbolBind, SCFG::TargetPhrases*>::const_iterator iterOuter;
  for (iterOuter = path.targetPhrases->begin(); iterOuter != path.targetPhrases->end(); ++iterOuter) {
    const SCFG::SymbolBind &symbolBind = iterOuter->first;

    const SCFG::TargetPhrases &tps = *iterOuter->second;
    //cerr << "symbolBind=" << symbolBind << " tps=" << tps.GetSize() << endl;

    SCFG::TargetPhrases::const_iterator iter;
    for (iter = tps.begin(); iter != tps.end(); ++iter) {
      const SCFG::TargetPhraseImpl &tp = **iter;
      //cerr << "tp=" << tp << endl;
      ExpandHypo(path, symbolBind, tp, stack);
    }
  }
}
*/

void Manager::ExpandHypo(
    const SCFG::InputPath &path,
    const SCFG::SymbolBind &symbolBind,
    const SCFG::TargetPhraseImpl &tp,
    Stack &stack)
{
  Recycler<HypothesisBase*> &hypoRecycler = GetHypoRecycle();

  std::vector<const SymbolBindElement*> ntEles = symbolBind.GetNTElements();
  Vector<size_t> prevHyposIndices(GetPool(), symbolBind.numNT);
  assert(ntEles.size() == symbolBind.numNT);
  //cerr << "ntEles:" << ntEles.size() << endl;

  size_t ind = 0;
  while (IncrPrevHypoIndices(prevHyposIndices, ind, ntEles)) {
    SCFG::Hypothesis *hypo = SCFG::Hypothesis::Create(GetSystemPool(), *this);
    hypo->Init(*this, path, symbolBind, tp, prevHyposIndices);
    hypo->EvaluateWhenApplied();

    stack.Add(hypo, hypoRecycler, arcLists);

    ++ind;
  }
}

bool Manager::IncrPrevHypoIndices(
    Vector<size_t> &prevHyposIndices,
    size_t ind,
    const std::vector<const SymbolBindElement*> ntEles)
{
  if (ntEles.size() == 0) {
    // no nt. Do the 1st
    return ind ? false : true;
  }

  size_t numHypos = 0;

  //cerr << "IncrPrevHypoIndices:" << ind << " " << ntEles.size() << " ";
  for (size_t i = 0; i < ntEles.size() - 1; ++i) {
    const SymbolBindElement &ele = *ntEles[i];
    const Hypotheses &hypos = *ele.hypos;
    numHypos = hypos.size();

    std::div_t divRet = std::div((int)ind, (int)numHypos);
    ind = divRet.quot;

    size_t hypoInd = divRet.rem;
    prevHyposIndices[i] = hypoInd;
    //cerr << "(" << i << "," << ind << "," << numHypos << "," << hypoInd << ")";
  }

  // last
  prevHyposIndices.back() = ind;

  // check if last is over limit
  const SymbolBindElement &ele = *ntEles.back();
  const Hypotheses &hypos = *ele.hypos;
  numHypos = hypos.size();

  //cerr << "(" << (ntEles.size() - 1) << "," << ind << "," << numHypos << ","  << ind << ")";
  //cerr << endl;

  if (ind >= numHypos) {
    return false;
  }
  else {
    return true;
  }
}

std::string Manager::OutputBest() const
{
  string out;
  const Stack &lastStack = m_stacks.GetLastStack();
  const Hypothesis *bestHypo = lastStack.GetBestHypo(*this, const_cast<ArcLists&>(arcLists));

  if (bestHypo) {
    //cerr << "BEST TRANSLATION: " << bestHypo << bestHypo->Debug(system) << endl;
    //cerr << " " << out.str() << endl;
    stringstream outStrm;
    bestHypo->OutputToStream(outStrm);

    out = outStrm.str();
    out = out.substr(4, out.size() - 10);

    if (system.options.output.ReportHypoScore) {
      out = SPrint(bestHypo->GetScores().GetTotalScore()) + " " + out;
    }
  }
  else {
    if (system.options.output.ReportHypoScore) {
      out = "0 ";
    }

    //cerr << "NO TRANSLATION " << m_input->GetTranslationId() << endl;
  }

  out += "\n";
  return out;
}

} // namespace
}

<|endoftext|>