text:
/////////////////////////////////////////////////////////////////////////////
// Name:        src/screen.cpp
// Purpose:     source for screen managing class
// Author:      Akiva Miura <akiva.miura@gmail.com>
// Modified by:
// Created:     01/14/2012
// Copyright:   (C) 2010-2012 Akiva Miura
// Licence:     MIT License
/////////////////////////////////////////////////////////////////////////////

// pre-compiled header
#include "prec.h"

// declarations
#include "lev/font.hpp"
#include "lev/image.hpp"
#include "lev/screen.hpp"

// dependencies
#include "lev/debug.hpp"
#include "lev/entry.hpp"
#include "lev/system.hpp"
#include "lev/util.hpp"

// libraries
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
#include <luabind/luabind.hpp>
#include <GL/glu.h>
#include <SDL2/SDL.h>

namespace lev
{

  class impl_screen : public screen
  {
    public:
      typedef boost::shared_ptr<impl_screen> ptr;
    protected:
      impl_screen() :
        wptr(),
        screen(),
        win(NULL),
        context(NULL),
        event_funcs(), win_funcs(),
        on_left_down(), on_left_up(),
        on_middle_down(), on_middle_up(),
        on_right_down(), on_right_up(),
        on_wheel(), on_wheel_down(), on_wheel_up()
        { }
    public:
      virtual ~impl_screen()
      {
        if (context)
        {
          SDL_GL_DeleteContext(context);
          context = NULL;
        }
        if (win)
        {
          SDL_DestroyWindow(win);
          win = NULL;
        }
      }

      virtual bool blit(int dst_x, int dst_y, bitmap::ptr src,
                        int src_x, int src_y, int w, int h, unsigned char alpha)
      {
//printf("SCREEN BLIT?\n");
        if (src == NULL) { return false; }
        if (src->is_texturized())
        {
          return blit(dst_x, dst_y, src->get_texture(), src_x, src_y, w, h, alpha);
        }

        int src_h = src->get_h();
        int src_w = src->get_w();
        if (w < 0) { w = src_w; }
        if (h < 0) { h = src_h; }
        glBegin(GL_POINTS);
          for (int y = 0; y < h; y++)
          {
            for (int x = 0; x < w; x++)
            {
              int real_src_x = src_x + x;
              int real_src_y = src_y + y;
              if (real_src_x < 0 || real_src_x >= src_w || real_src_y < 0 || real_src_y >= src_h)
              {
                continue;
              }
              color::ptr pixel(src->get_pixel(real_src_x, real_src_y));
              if (! pixel) { continue; }
              unsigned char a = (unsigned short)pixel->get_a() * alpha / 255;
              if (a > 0)
              {
                glColor4ub(pixel->get_r(), pixel->get_g(), pixel->get_b(), a);
                glVertex2i(dst_x + x, dst_y + y);
              }
            }
          }
        glEnd();
        return true;
      }

      virtual bool blit(int dst_x, int dst_y, texture::ptr src,
                        int src_x, int src_y, int w, int h, unsigned char alpha)
      {
        return src->blit_on(to_screen(), dst_x, dst_y, src_x, src_y, w, h, alpha);
      }

      virtual bool clear(unsigned char r, unsigned char g,
                         unsigned char b, unsigned char a)
      {
        set_current();
        glClearColor(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    //    glClear(GL_COLOR_BUFFER_BIT);
        return true;
      }

      virtual bool close()
      {
        if (context)
        {
          SDL_GL_DeleteContext(context);
          context = NULL;
        }
        if (win)
        {
          SDL_DestroyWindow(win);
          win = NULL;
        }
        return false;
      }

      static impl_screen::ptr create(const char *title, int x, int y, int w, int h,
                                     const char *style)
      {
        impl_screen::ptr s;
        system::ptr sys = system::get();
        if (! sys) { return s; }

        unsigned long flags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
        if (style)
        {
          if (strstr(style, "borderless"))    { flags |= SDL_WINDOW_BORDERLESS; }
          if (strstr(style, "full"))          { flags |= SDL_WINDOW_FULLSCREEN; }
          if (strstr(style, "hidden"))        { flags |= SDL_WINDOW_HIDDEN; }
    //      if (strstr(flags_str, "input"))         { flags |= SDL_WINDOW_INPUT_GRABBED; }
          if (strstr(style, "input_grabbed")) { flags |= SDL_WINDOW_INPUT_GRABBED; }
          if (strstr(style, "max"))           { flags |= SDL_WINDOW_MAXIMIZED; }
          if (strstr(style, "min"))           { flags |= SDL_WINDOW_MINIMIZED; }
          if (strstr(style, "resizable"))     { flags |= SDL_WINDOW_RESIZABLE; }
          if (strstr(style, "shown"))         { flags |= SDL_WINDOW_SHOWN; }
        }

        try {
          s.reset(new impl_screen);
          if (! s) { throw -1; }
          s->wptr = s;
          s->win = SDL_CreateWindow(title, x, y, w, h, flags);
          if (! s->win) { throw -2; }
          s->context = SDL_GL_CreateContext(s->win);
          if (! s->context) { throw -3; }

          SDL_GL_SetSwapInterval(0);
    //      glMatrixMode(GL_PROJECTION);
    //      glLoadIdentity();
    //      glOrtho(0.0f, 640, 480, 0.0f, 0.0f, 1000.0f);
    //      glMatrixMode(GL_MODELVIEW);

          glOrtho(0, s->get_w(), s->get_h(), 0, -1, 1);
          glEnable(GL_BLEND);
          glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
          if (! sys->attach(s->to_screen())) { throw -4; }
        }
        catch (...) {
          s.reset();
          lev::debug_print("error on screen instance creation");
        }
        return s;
      }

      static int create_l(lua_State *L)
      {
        using namespace luabind;
        const char *title = "Lev Application";
        int x = SDL_WINDOWPOS_UNDEFINED, y = SDL_WINDOWPOS_UNDEFINED;
        int w = 640, h = 480;
        const char *flags_str = NULL;

        try {
          object t = util::get_merged(L, 1, -1);

          if (t["title"]) { title = object_cast<const char *>(t["title"]); }
          else if (t["t"]) { title = object_cast<const char *>(t["t"]); }
          else if (t["name"]) { title = object_cast<const char *>(t["name"]); }
          else if (t["n"]) { title = object_cast<const char *>(t["n"]); }
          else if (t["caption"]) { title = object_cast<const char *>(t["caption"]); }
          else if (t["c"]) { title = object_cast<const char *>(t["c"]); }
          else if (t["lua.string1"]) { title = object_cast<const char *>(t["lua.string1"]); }

          if (t["w"]) { w = object_cast<int>(t["w"]); }
          else if (t["lua.number1"]) { w = object_cast<int>(t["lua.number1"]); }

          if (t["h"]) { h = object_cast<int>(t["h"]); }
          else if (t["lua.number2"]) { h = object_cast<int>(t["lua.number2"]); }

          if (t["x"]) { x = object_cast<int>(t["x"]); }
          else if (t["lua.number3"]) { x = object_cast<int>(t["lua.number3"]); }

          if (t["y"]) { y = object_cast<int>(t["y"]); }
          else if (t["lua.number4"]) { y = object_cast<int>(t["lua.number4"]); }

          if (t["flags"]) { flags_str = object_cast<const char *>(t["flags"]); }
          else if (t["f"]) { flags_str = object_cast<const char *>(t["f"]); }
          else if (t["lua.string2"]) { flags_str = object_cast<const char *>(t["lua.string2"]); }
          object o = globals(L)["lev"]["classes"]["screen"]["create_c"](title, x, y, w, h, flags_str);
          o.push(L);
          return 1;
        }
        catch (...) {
          lev::debug_print(lua_tostring(L, -1));
          lev::debug_print("error on wrapped screen creation");
          lua_pushnil(L);
          return 1;
        }
      }

      virtual bool draw(drawable::ptr src, int x, int y, unsigned char alpha)
      {
//printf("SCREEN DRAW!\n");
        if (! src) { return false; }
        set_current();
//printf("SCREEN DRAW ON!\n");
//printf("TO SCREEN: %p\n", to_screen().get());
        return src->draw_on(to_screen(), x, y, alpha);
      }

      virtual bool draw_pixel(int x, int y, const color &c)
      {
        glBegin(GL_POINTS);
          glColor4ub(c.get_r(), c.get_g(), c.get_b(), c.get_a());
          glVertex2i(x, y);
        glEnd();
        return true;
      }

//      virtual bool draw_raster(const raster *r, int offset_x, int offset_y, boost::shared_ptr<color> c)
//      {
//        if (! r) { return false; }
//
//        if (! c) { c = color::white(); }
//        if (! c) { return false; }
//        glBegin(GL_POINTS);
//          for (int y = 0; y < r->get_h(); y++)
//          {
//            for (int x = 0; x < r->get_w(); x++)
//            {
//              unsigned char a = (unsigned short)c->get_a() * r->get_pixel(x, y) / 255;
//              if (a > 0)
//              {
//                glColor4ub(c->get_r(), c->get_g(), c->get_b(), a);
//                glVertex2i(offset_x + x, offset_y + y);
//              }
//            }
//          }
//        glEnd();
//        return true;
//      }

      virtual bool enable_alpha_blending(bool enable)
      {
        set_current();
        if (enable)
        {
          glEnable(GL_BLEND);
          glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        }
        else
        {
          glDisable(GL_BLEND);
        }
        return true;
      }

      virtual int get_h() const
      {
        if (! win) { return 0; }
        int h;
        SDL_GetWindowSize(win, NULL, &h);
        return h;
      }

      virtual long get_id() const
      {
        if (! win) { return -1; }
        return SDL_GetWindowID(win);
      }

      virtual luabind::object get_on_close()
      {
        if (! win) { return luabind::object(); }
        return win_funcs[SDL_WINDOWEVENT_CLOSE];
      }

      virtual luabind::object get_on_key_down()
      {
        if (! win) { return luabind::object(); }
        return event_funcs[SDL_KEYDOWN];
      }

      virtual luabind::object get_on_key_up()
      {
        if (! win) { return luabind::object(); }
        return event_funcs[SDL_KEYUP];
      }

      virtual luabind::object get_on_left_down()
      {
        if (! win) { return luabind::object(); }
        return on_left_down;
      }

      virtual luabind::object get_on_left_up()
      {
        if (! win) { return luabind::object(); }
        return on_left_up;
      }

      virtual luabind::object get_on_middle_down()
      {
        if (! win) { return luabind::object(); }
        return on_middle_down;
      }

      virtual luabind::object get_on_middle_up()
      {
        if (! win) { return luabind::object(); }
        return on_middle_up;
      }

      virtual luabind::object get_on_motion()
      {
        if (! win) { return luabind::object(); }
        return event_funcs[SDL_MOUSEMOTION];
      }

      virtual luabind::object get_on_right_down()
      {
        if (! win) { return luabind::object(); }
        return on_right_down;
      }

      virtual luabind::object get_on_right_up()
      {
        if (! win) { return luabind::object(); }
        return on_right_up;
      }

      virtual luabind::object get_on_wheel()
      {
        if (! win) { return luabind::object(); }
        return event_funcs[SDL_MOUSEWHEEL];
      }

      virtual luabind::object get_on_wheel_down()
      {
        if (! win) { return luabind::object(); }
        return on_wheel_down;
      }

      virtual luabind::object get_on_wheel_up()
      {
        if (! win) { return luabind::object(); }
        return on_wheel_up;
      }

      virtual bitmap::ptr get_screenshot()
      {
        bitmap::ptr img;
        if (! win) { return img; }
        set_current();
        try {
          if (get_id() > 0)
          {
            const int w = get_w();
            const int h = get_h();
            img = bitmap::create(w, h);
            if (! img) { throw -1; }
            glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, img->get_buffer());
            Uint32 *buf = (Uint32 *)img->get_buffer();
            for (int y = 0; y < h / 2; y++)
            {
              for (int x = 0; x < w; x++)
              {
                Uint32 tmp = buf[y * w + x];
                buf[y * w + x] = buf[(h - 1 - y) * w + x];
                buf[(h - 1 - y) * w + x] = tmp;
              }
            }
          }
          else { throw -1; }
        }
        catch (...) {
          img.reset();
          lev::debug_print("error on screen shot bitmap creation");
        }
        return img;
      }

      virtual int get_w() const
      {
        if (! win) { return 0; }
        int w;
        SDL_GetWindowSize(win, &w, NULL);
        return w;
      }

      virtual bool hide()
      {
        if (! win) { return false; }
        SDL_HideWindow(win);
        return true;
      }

      virtual bool is_fullscreen() const
      {
        if (! win) { return false; }
        if (SDL_GetWindowFlags(win) & SDL_WINDOW_FULLSCREEN) { return true; }
        return false;
      }

      virtual bool is_shown() const
      {
        if (! win) { return false; }
        if (SDL_GetWindowFlags(win) & SDL_WINDOW_SHOWN) { return true; }
        return false;
      }

      virtual bool map2d_auto()
      {
        if (win)
        {
          int w = get_w();
          int h = get_h();
          set_current();
          glLoadIdentity();
          glOrtho(0, w, h, 0, -1, 1);
          return true;
        }
        return false;
      }

      virtual bool map2d(int left, int right, int top, int bottom)
      {
        if (win)
        {
          set_current();
          glLoadIdentity();
          glOrtho(left, right, bottom, top, -1, 1);
          return true;
        }
        return false;
      }

      virtual bool set_current()
      {
        if (win)
        {
          if (get_id() < 0) { return false; }
          SDL_GL_MakeCurrent(win, context);
          return true;
        }
        return false;
      }

      virtual bool set_fullscreen(bool enable)
      {
        if (! win) { return false; }
        if (SDL_SetWindowFullscreen(win, (SDL_bool)enable) == 0)
        {
          return true;
        }
        return false;
      }

      virtual bool set_h(int h)
      {
        if (! win) { return false; }
        int w = get_w();
        SDL_SetWindowSize(win, w, h);
        return true;
      }

      virtual bool set_on_close(luabind::object func)
      {
        if (! win) { return false; }
        win_funcs[SDL_WINDOWEVENT_CLOSE] = func;
        return true;
      }

      virtual bool set_on_key_down(luabind::object func)
      {
        if (! win) { return false; }
        event_funcs[SDL_KEYDOWN] = func;
        return true;
      }

      virtual bool set_on_key_up(luabind::object func)
      {
        if (! win) { return false; }
        event_funcs[SDL_KEYUP] = func;
        return true;
      }

      virtual bool set_on_left_down(luabind::object func)
      {
        if (! win) { return false; }
        on_left_down = func;
        return true;
      }

      virtual bool set_on_left_up(luabind::object func)
      {
        if (! win) { return false; }
        on_left_up = func;
        return true;
      }

      virtual bool set_on_middle_down(luabind::object func)
      {
        if (! win) { return false; }
        on_middle_down = func;
        return true;
      }

      virtual bool set_on_middle_up(luabind::object func)
      {
        if (! win) { return false; }
        on_middle_up = func;
        return true;
      }

      virtual bool set_on_motion(luabind::object func)
      {
        if (! win) { return false; }
        event_funcs[SDL_MOUSEMOTION] = func;
        return true;
      }

      virtual bool set_on_right_down(luabind::object func)
      {
        if (! win) { return false; }
        on_right_down = func;
        return true;
      }

      virtual bool set_on_right_up(luabind::object func)
      {
        if (! win) { return false; }
        on_right_up = func;
        return true;
      }

      virtual bool set_on_wheel(luabind::object func)
      {
        if (! win) { return false; }
        event_funcs[SDL_MOUSEWHEEL] = func;
        return true;
      }

      virtual bool set_on_wheel_down(luabind::object func)
      {
        if (! win) { return false; }
        on_wheel_down = func;
        return true;
      }

      virtual bool set_on_wheel_up(luabind::object func)
      {
        if (! win) { return false; }
        on_wheel_up = func;
        return true;
      }

      virtual bool set_w(int w)
      {
        if (! win) { return false; }
        int h = get_h();
        SDL_SetWindowSize(win, w, h);
        return true;
      }

      virtual bool show(bool showing)
      {
        if (! win) { return false; }
        if (showing)
        {
          SDL_ShowWindow(win);
          return true;
        }
        return hide();
      }

      virtual bool swap()
      {
        if (win)
        {
          if (get_id() < 0) { return false; }
          SDL_GL_SwapWindow(win);
          return true;
        }
        return false;
      }

      virtual canvas::ptr to_canvas()
      {
        return canvas::ptr(wptr);
      }

      virtual screen::ptr to_screen()
      {
        return screen::ptr(wptr);
      }

      boost::weak_ptr<impl_screen> wptr;
      SDL_GLContext context;
      SDL_Window *win;
      std::map<Uint8, luabind::object> win_funcs;
      std::map<Uint32, luabind::object> event_funcs;
      luabind::object on_left_down, on_left_up;
      luabind::object on_middle_down, on_middle_up;
      luabind::object on_right_down, on_right_up;
      luabind::object on_wheel, on_wheel_down, on_wheel_up;
  };

  static SDL_GLContext cast_ctx(void *obj) { return (SDL_GLContext)obj; }

  screen::ptr screen::create(const char *title, int x, int y, int w, int h, const char *style)
  {
    return impl_screen::create(title, x, y, w, h, style);
  }

//  bool canvas::draw_point(point *pt)
//  {
//    set_current();
//
//    glPushMatrix();
//    glBegin(GL_POINTS);
//    {
//      color *c = pt->get_color();
//      vector *v = pt->get_vertex();
//      if (c)
//      {
//        glColor4ub(c->get_r(), c->get_g(), c->get_b(), c->get_a());
//      }
//      glVertex3i(v->get_x(), v->get_y(), v->get_z());
//    }
//    glEnd();
//    glPopMatrix();
//
//    return true;
//  }

//  int canvas::draw_points(lua_State *L)
//  {
//    using namespace luabind;
//
//    int n = lua_gettop(L);
//    luaL_checktype(L, 1, LUA_TUSERDATA);
//    glBegin(GL_POINTS);
//    for (int i = 2; i <= n; i++)
//    {
//      object o(from_stack(L, i));
//      if (type(o) == LUA_TUSERDATA && o["type_id"] == LEV_TVECTOR)
//      {
//      }
//    }
//    glEnd();
//  }
//
//
//  bool canvas::fill_rect(int x, int y, int w, int h, color *fill)
//  {
//    set_current();
//    glBegin(GL_QUADS);
//      glColor4ub(fill->get_r(), fill->get_g(), fill->get_b(), fill->get_a());
//      glVertex2i(x    , y);
//      glVertex2i(x    , y + h);
//      glVertex2i(x + w, y + h);
//      glVertex2i(x + w, y);
//    glEnd();
//  }
//

//  void canvas::flush()
//  {
//    glFlush();
//  }

//  void canvas::line(int x1, int y1, int x2, int y2)
//  {
//    glBegin(GL_LINES);
//      glVertex2i(x1, y1);
//      glVertex2i(x2, y2);
//    glEnd();
//  }
//
//  bool canvas::print(const char *text)
//  {
//    try {
//      boost::shared_ptr<image> img(image::string(text, NULL, NULL, NULL));
//      draw_image(img.get(), 200, 80);
//    }
//    catch (...) {
//      return false;
//    }
//  }

}

int luaopen_lev_screen(lua_State *L)
{
  using namespace luabind;
  using namespace lev;

  open(L);
  // beginning of loading
  globals(L)["package"]["loaded"]["lev.screen"] = true;
  // pre-requirement
  globals(L)["require"]("lev.draw");
  globals(L)["require"]("lev.system");

  module(L, "lev")
  [
    namespace_("classes")
    [
      class_<screen, canvas, boost::shared_ptr<canvas> >("screen")
        .def("close", &screen::close)
        .def("enable_alpha_blending", &screen::enable_alpha_blending0)
        .def("enable_alpha_blending", &screen::enable_alpha_blending)
        .def("flip", &screen::swap)
        .def("get_screen_shot", &screen::get_screenshot)
        .def("get_screenshot", &screen::get_screenshot)
        .property("h", &screen::get_h, &screen::set_h)
        .property("height", &screen::get_h, &screen::set_h)
        .def("hide", &screen::hide)
        .property("id", &screen::get_id)
        .property("is_full_screen", &screen::is_fullscreen, &screen::set_fullscreen)
        .property("is_fullscreen", &screen::is_fullscreen, &screen::set_fullscreen)
        .property("is_shown", &screen::is_shown, &screen::show)
        .def("map2d", &screen::map2d)
        .def("map2d", &screen::map2d_auto)
        .property("on_close", &screen::get_on_close, &screen::set_on_close)
        .property("on_key_down", &screen::get_on_key_down, &screen::set_on_key_down)
        .property("on_key_up", &screen::get_on_key_down, &screen::set_on_key_up)
        .property("on_left_down", &screen::get_on_left_down, &screen::set_on_left_down)
        .property("on_left_up", &screen::get_on_left_up, &screen::set_on_left_up)
        .property("on_middle_down", &screen::get_on_middle_down, &screen::set_on_middle_down)
        .property("on_middle_up", &screen::get_on_middle_up, &screen::set_on_middle_up)
        .property("on_motion", &screen::get_on_motion, &screen::set_on_motion)
        .property("on_right_down", &screen::get_on_right_down, &screen::set_on_right_down)
        .property("on_right_up", &screen::get_on_right_up, &screen::set_on_right_up)
        .property("on_wheel", &screen::get_on_wheel, &screen::set_on_wheel)
        .property("on_wheel_down", &screen::get_on_wheel_down, &screen::set_on_wheel_down)
        .property("on_wheel_up", &screen::get_on_wheel_up, &screen::set_on_wheel_up)
        .property("screen_shot", &screen::get_screenshot)
        .property("screenshot", &screen::get_screenshot)
        .def("set_current", &screen::set_current)
        .def("set_full_screen", &screen::set_fullscreen)
        .def("set_fullscreen", &screen::set_fullscreen)
        .def("show", &screen::show)
        .def("show", &screen::show0)
        .def("swap", &screen::swap)
        .property("w", &screen::get_w, &screen::set_w)
        .property("width", &screen::get_w, &screen::set_w)
        .scope
        [
          def("create_c", &screen::create)
        ]
    ]
  ];
  object lev = globals(L)["lev"];
  object classes = lev["classes"];
  register_to(classes["screen"], "draw", &screen::draw_l);
  register_to(classes["screen"], "create", &impl_screen::create_l);

  lev["screen"] = classes["screen"]["create"];

  globals(L)["package"]["loaded"]["lev.screen"] = true;
  return 0;
}

max_stars_repo_name: akivajp/lev

max_issues_repo_name: akivajp/lev

max_forks_repo_name: akivajp/lev


text:
// Copyright (c) 2018-2019 Emil Dotchevski and Reverge Studios, Inc.

// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

// This is a simple program that demonstrates the use of LEAF to transport E-objects between threads,
// without using exception handling. See capture_eh.cpp for the exception-handling variant.

// See also

#include <boost/leaf/capture.hpp>
#include <boost/leaf/handle_exception.hpp>
#include <boost/leaf/exception.hpp>
#include <vector>
#include <string>
#include <future>
#include <iterator>
#include <iostream>
#include <algorithm>

namespace leaf = boost::leaf;

// Define several e-types.
struct e_thread_id { std::thread::id value; };
struct e_failure_info1 { std::string value; };
struct e_failure_info2 { int value; };

// The type our tasks return.
struct task_result { };

 // This is our task function. It produces objects of type task_result, but it may fail...
task_result task()
{
	bool succeed = (rand()%4) != 0; //...at random.
	if( succeed )
		return { };
	else
		throw leaf::exception( std::exception(),
			e_thread_id{std::this_thread::get_id()},
			e_failure_info1{"info"},
			e_failure_info2{42} );
};

int main()
{
	int const task_count = 42;

	// The error_handler is called in this thread (see leaf::remote_try_catch below). The
	// arguments passed to individual lambdas are transported from the worker thread to
	// the main thread automatically.
	auto error_handler = []( leaf::error_info const & error )
	{
		return leaf::remote_handle_exception( error,
			[]( e_failure_info1 const & v1, e_failure_info2 const & v2, e_thread_id const & tid )
			{
				std::cerr << "Error in thread " << tid.value << "! failure_info1: " << v1.value << ", failure_info2: " << v2.value << std::endl;
			},
			[]( leaf::diagnostic_info const & unmatched )
			{
				std::cerr <<
					"Unknown failure detected" << std::endl <<
					"Cryptic diagnostic information follows" << std::endl <<
					unmatched;
			} );
	};

	// Container to collect the generated std::future objects.
	std::vector<std::future<task_result>> fut;

	// Launch the tasks, but rather than launching the task function directly, we launch a
	// wrapper function which calls leaf::capture, passing a context object that will hold
	// the E-objects loaded from the task in case it throws. The E-types the context is
	// able to hold statically are automatically deduced from the type of the error_handler
	// function.
	std::generate_n( std::inserter(fut,fut.end()), task_count,
		[&]
		{
			return std::async(
				std::launch::async,
				[&]
				{
					return leaf::capture(leaf::make_shared_context(&error_handler), &task);
				} );
		} );

	// Wait on the futures, get the task results, handle errors.
	for( auto & f : fut )
	{
		f.wait();

		leaf::remote_try_catch(
			[&]
			{
				task_result r = f.get();

				// Success! Use r to access task_result.
				std::cout << "Success!" << std::endl;
				(void) r;
			},
			[&]( leaf::error_info const & error )
			{
				return error_handler(error);
			} );
	}
}

ext: cpp


text:
#include <boost/thread/thread.hpp>
#include <pcl/visualization/pcl_visualizer.h>

namespace map3d{

boost::shared_ptr<pcl::visualization::PCLVisualizer> simpleVis (pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloud)
{
  // --------------------------------------------
  // -----Open 3D viewer and add point cloud-----
  // --------------------------------------------
  boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
  viewer->setBackgroundColor (0, 0, 0);
  viewer->addPointCloud<pcl::PointXYZ> (cloud, "sample cloud");
  viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "sample cloud");
  viewer->addCoordinateSystem (1.0);
  viewer->initCameraParameters ();
  return (viewer);
}

boost::shared_ptr<pcl::visualization::PCLVisualizer> MutiVis (std::vector<pcl::PointCloud<pcl::PointXYZ>::ConstPtr > cloud)
{
  // --------------------------------------------
  // -----Open 3D viewer and add point cloud-----
  // --------------------------------------------
  boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
  viewer->setBackgroundColor (0, 0, 0);
  viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "registration cloud");
  int step=(255+255+255)/cloud.size();
  int R,G,B;
  for(int i=0;i<cloud.size();i++)
  {
    std::string cloudName;
   char cloudname[50];
   sprintf(cloudname,"cloud%.3d",i);
    if(step*(i+1)<=255)
    {
      R=(i+1)*step;
      G=0;
       B=0;
    }
   else if(step*(i+1)>=255&&step*(i+1)<=510)
    {
     R=255;
     G=(i+1)*step-255;
     B=0;
    }
    else{
       R=255;
      G=255;
      B=(i+1)*step-510;
    }
    pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> single_color(cloud[i], R, G, B);
    viewer->addPointCloud<pcl::PointXYZ>(cloud[i],single_color,cloudName);
  }
  viewer->addCoordinateSystem (1.0);
  viewer->initCameraParameters ();
  return (viewer);
}

boost::shared_ptr<pcl::visualization::PCLVisualizer> normalVis(pcl::PointCloud<pcl::PointXYZ>::ConstPtr pc1, pcl::PointCloud<pcl::PointXYZ>::ConstPtr pc2)
{
 boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer(new pcl::visualization::PCLVisualizer("point"));
  viewer->setBackgroundColor(0,0,0);
  pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> single_color(pc1, 0, 255, 0);
  pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> n_color(pc2, 0,0,255);
  //重载函数
 viewer->addPointCloud<pcl::PointXYZ>(pc1,single_color,"sample cloud");

 //首先设置渲染特性，PCL_VISUALIZER_POINT_SIZE是一种.
 viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE,1,"sample cloud");
 //注意后面这个必须在命名时与上面的不同，不然与上面的点云颜色相同
 viewer->addPointCloud<pcl::PointXYZ >(pc2,n_color,"normals");
 viewer->addCoordinateSystem(1.0);
 viewer->initCameraParameters();
return viewer;
}

boost::shared_ptr<pcl::visualization::PCLVisualizer> normalVis(pcl::PointCloud<pcl::PointXYZ>::ConstPtr pc, pcl::PointCloud<pcl::Normal>::ConstPtr Normals)
{
 boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer(new pcl::visualization::PCLVisualizer("point with Normal"));
  viewer->setBackgroundColor(0,0,0);
  pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> single_color(pc, 0, 255, 0);
  pcl::visualization::PointCloudColorHandlerCustom<pcl::Normal> n_color(Normals, 0,0,255);
  //重载函数
 viewer->addPointCloud<pcl::PointXYZ>(pc,single_color,"sample cloud");

 //首先设置渲染特性，PCL_VISUALIZER_POINT_SIZE是一种.
 viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE,1,"sample cloud");
 //注意后面这个必须在命名时与上面的不同，不然与上面的点云颜色相同
 viewer->addPointCloudNormals<pcl::PointXYZ,pcl::Normal >(pc,Normals,10,5,"normals");
 viewer->addCoordinateSystem(1.0);
 viewer->initCameraParameters();
return viewer;
}
}

ext: hpp

max_stars_repo_name: zoumaguanxin/slamEvaluation

max_issues_repo_name: zoumaguanxin/slamEvaluation

max_forks_repo_name: zoumaguanxin/slamEvaluation


text:
/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */
#include "FailoverExchange.h"
#include "Event.h"
#include "qpid/broker/amqp_0_10/MessageTransfer.h"
#include "qpid/broker/Message.h"
#include "qpid/broker/DeliverableMessage.h"
#include "qpid/broker/Queue.h"
#include "qpid/framing/MessageProperties.h"
#include "qpid/framing/AMQFrame.h"
#include "qpid/framing/AMQHeaderBody.h"
#include "qpid/framing/MessageTransferBody.h"
#include "qpid/log/Statement.h"
#include "qpid/framing/Array.h"
#include "qpid/RefCounted.h"
#include "qpid/UrlArray.h"
#include <boost/bind.hpp>
#include <algorithm>

namespace qpid {
namespace ha {

using namespace std;

using namespace broker;
using namespace framing;
using broker::amqp_0_10::MessageTransfer;

const string FailoverExchange::typeName("amq.failover");

namespace {
struct OstreamUrls {
    OstreamUrls(const FailoverExchange::Urls& u) : urls(u) {}
    FailoverExchange::Urls urls;
};

ostream& operator<<(ostream& o, const OstreamUrls& urls) {
    ostream_iterator<qpid::Url> out(o, " ");
    copy(urls.urls.begin(), urls.urls.end(), out);
    return o;
}
}

FailoverExchange::FailoverExchange(management::Manageable& parent, Broker& b)
    : Exchange(typeName, &parent, &b)
{
    if (mgmtExchange != 0)
        mgmtExchange->set_type(typeName);
}

void FailoverExchange::setUrls(const vector<Url>& u) {
    QPID_LOG(debug, typeName << " URLs set to " << OstreamUrls(u));
    Lock l(lock);
    urls = u;
}

void FailoverExchange::updateUrls(const vector<Url>& u) {
    QPID_LOG(debug, typeName << " Updating URLs " << OstreamUrls(u) << " to "
             << queues.size() << " subscribers.");
    Lock l(lock);
    urls=u;
    if (!urls.empty() && !queues.empty()) {
        for (Queues::const_iterator i = queues.begin(); i != queues.end(); ++i)
            sendUpdate(*i, l);
    }
}

string FailoverExchange::getType() const { return typeName; }

bool FailoverExchange::bind(Queue::shared_ptr queue, const string&,
                            const framing::FieldTable*) {
    QPID_LOG(debug, typeName << " binding " << queue->getName());
    Lock l(lock);
    sendUpdate(queue, l);
    return queues.insert(queue).second;
}

bool FailoverExchange::unbind(Queue::shared_ptr queue, const string&,
                              const framing::FieldTable*) {
    QPID_LOG(debug, typeName << " un-binding " << queue->getName());
    Lock l(lock);
    return queues.erase(queue);
}

bool FailoverExchange::isBound(Queue::shared_ptr queue, const string* const,
                               const framing::FieldTable*) {
    Lock l(lock);
    return queues.find(queue) != queues.end();
}

bool FailoverExchange::hasBindings() {
    Lock l(lock);
    return !queues.empty();
}

void FailoverExchange::route(Deliverable&) {
    QPID_LOG(warning, typeName << " unexpected message, ignored.");
}

void FailoverExchange::sendUpdate(const Queue::shared_ptr& queue, sys::Mutex::ScopedLock&) {
    QPID_LOG(debug, typeName << " sending " << OstreamUrls(urls) << " to " << queue->getName());
    if (urls.empty()) return;
    framing::Array array = vectorToUrlArray(urls);
    const ProtocolVersion v;
    broker::Message message(makeMessage(std::string(), typeName, typeName));
    MessageTransfer& transfer = MessageTransfer::get(message);
    MessageProperties* props =
        transfer.getFrames().getHeaders()->get<framing::MessageProperties>(true);
    props->setContentLength(0);
    props->getApplicationHeaders().setArray(typeName, array);
    DeliverableMessage(message, 0).deliverTo(queue);
}

}} // namespace ha


text:
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
#include <manipulations.h>

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/format.hpp>

#include "svm.h"
#include "util.h"

int main(int argc, char* argv[]) {

	if (argc != 2) {
		std::cerr
			<< "Usage: " << argv[0]
			<< " input_info.ini" << std::endl;
		system("pause");
		return EXIT_FAILURE;
	}
	std::string path = argv[1];

	std::string train_path = read_param_boost<std::string>(path, "path", "train_path");
	std::string label_path = read_param_boost<std::string>(path, "path", "label_path");
	std::string test_path = read_param_boost<std::string>(path, "path", "test_path");
	std::string dir_o = read_param_boost<std::string>(path, "path", "dir_o");
	std::string model_name = read_param_boost <std::string>(path, "param", "model_name");
	mkdir_boost(dir_o);

	constexpr std::size_t n_feat = 1;
	svm_problem prob;
	set_svm_input<n_feat>(prob, train_path, label_path);

	svm_parameter param;

	param.svm_type = C_SVC;
	param.kernel_type = RBF;
	param.C = 10;
	param.gamma = 1;

	param.coef0 = 0;
	param.cache_size = 100;
	param.eps = 1e-3;
	param.shrinking = 1;
	param.probability = 0;

	param.degree = 3;
	param.nu = 0.5;
	param.p = 0.1;
	param.nr_weight = 0;
	param.weight_label = nullptr;
	param.weight = nullptr;

	svm_model* model;

	// train
	std::cout << "Now training..." << std::endl;
	model = svm_train(&prob, &param);
	std::cout << "Training complete !" << std::endl;

	// save
	std::cout << "Save model..." << std::endl;
	std::string model_path = dir_o + model_name;
	svm_save_model(model_path.c_str(), model);

	// test
	std::vector<svm_node*> test;
	set_test_data<n_feat>(test, test_path);
	predict_and_save_result<n_feat>(dir_o + "result.json", model, test);

	svm_free_and_destroy_model(&model);
	delete[] prob.x;
	delete[] prob.y;

	system("pause");
	return EXIT_SUCCESS;
}


text:
#ifndef INGLUED_GENERATE_INSTALL_DOC_HPP
#define INGLUED_GENERATE_INSTALL_DOC_HPP

#include <boost/filesystem.hpp>
#include <mstch/mstch.hpp>

#include <inglued/install_doc_tpl.hpp>
#include <inglued/dep.hpp>
#include <inglued/tpl.hpp>

namespace inglued {

  namespace fs = boost::filesystem;

  constexpr auto INSTALL_DOC_TPL_PATH="INSTALL.md.tpl";
  constexpr auto INSTALL_DOC_PATH="INSTALL.md";

  inline void generate_install_doc(const std::string& org, const std::string& project, const std::string& project_srcs, map_deps_t& deps) {

    std::string install_doc_view{install_doc_tpl};

    use_template_if_exists(INSTALL_DOC_TPL_PATH, install_doc_view);

    mstch::config::escape = [](const std::string& str) { return str; };

    mstch::array mstch_deps;
    for (auto d : deps) {

      mstch_deps.push_back(
        mstch::map{
          {"org", d.second.get_gh_organization()},
          {"name", d.second.get_gh_name()},
          {"ref", d.second.ref},
          {"include_path", d.second.include_path}
        }
      );
    }

    mstch::map context{
      {"org", org},
      {"project", project},
      {"project_srcs", project_srcs},
      {"deps", mstch_deps}
    };

    fs::path path{INSTALL_DOC_PATH};
    if (!fs::path(path).parent_path().empty()) { fs::create_directories(fs::path(path).parent_path()); }

    std::fstream install_md{path.native().data(), std::ios::trunc | std::ios::in | std::ios::out };
    install_md.exceptions(std::ios::badbit);
    install_md << mstch::render(install_doc_view, context);

    std::cout << "Generated " << INSTALL_DOC_PATH << std::endl;
  }
}

#endif

max_stars_repo_name: sniperkit/inglued

max_issues_repo_name: sniperkit/inglued

max_forks_repo_name: sniperkit/inglued


text:
#include <common/test/test_home_dir.hpp>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <iomanip>
#include <node/self_node.hpp>
#include <terminal/terminal.hpp>
#include <boost/filesystem.hpp>

using namespace prologcoin::common;
using namespace prologcoin::node;
using namespace prologcoin::terminal;
using namespace prologcoin::global;

std::string test_dir;

static void header( const std::string &str )
{
    std::cout << "\n";
    std::cout << "--- [" + str + "] " + std::string(60 - str.length(), '-') << "\n";
    std::cout << "\n";
}

static void test_terminal()
{
    header("test_terminal()");

    std::cout << "Start node at port 8000" << std::endl;

    global::erase_db(test_dir);

    self_node node(test_dir, 8000);
    node.start();

    std::cout << "Open terminal..." << std::endl;

    terminal tm(8000);

    if (!tm.connect()) {
	std::cout << "Failed to open connection." << std::endl;
    }

    bool r = tm.execute("member(X, [1,2,3,4]).");
    assert(r);

    const size_t N = 4;
    std::string expect [N] = { "1", "2", "3", "4" };

    for (size_t i = 0; i < N; i++) {
	auto actual = tm.get_result_string("X");
	std::cout << "Expect: X = " << expect[i] << std::endl;
	if (actual.empty()) {
	    actual = "<no value>";
	}
	std::cout << "Actual: X = " << actual << std::endl;
	assert(expect[i] == actual);

	std::cout << "Text  : " << tm.flush_text() << std::endl;

	if (i < N - 1) {
	    assert(tm.has_more());
	    assert(tm.next());
	}
    }
    // Check that we don't have more solutions...
    assert(!tm.next());

    // Shutdown terminal
    tm.close();

    // Shutdown node
    node.stop();
    node.join();
}

int main(int argc, char *argv[])
{
    std::string home_dir = find_home_dir(argv[0]);
    test_dir = (boost::filesystem::path(home_dir) / "bin" / "test" / "node" / "triedb").string();

    test_terminal();
    return 0;
}

max_stars_repo_name: datavetaren/prologcoin

max_issues_repo_name: datavetaren/prologcoin

max_forks_repo_name: datavetaren/prologcoin


text:
///////////////////////////////////////////////////////////////////////////////
/// \file xpressive_fwd.hpp
/// Forward declarations for all of xpressive's public data types.
//
//  Copyright 2008 Eric Niebler. Distributed under the Boost
//  Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_XPRESSIVE_XPRESSIVE_FWD_HPP_EAN_10_04_2005
#define BOOST_XPRESSIVE_XPRESSIVE_FWD_HPP_EAN_10_04_2005

// MS compatible compilers support #pragma once
#if defined(_MSC_VER)
#pragma once
#endif

#include <boost/config.hpp>
#include <boost/iterator/iterator_traits.hpp>
#include <boost/version.hpp>
#include <string>

#if BOOST_VERSION >= 103500
#define BOOST_PROTO_FUSION_V2
#endif

#if defined(BOOST_NO_STD_LOCALE) & !defined(BOOST_XPRESSIVE_USE_C_TRAITS)
#define BOOST_XPRESSIVE_USE_C_TRAITS
#endif

#if defined(BOOST_NO_CWCHAR) || defined(BOOST_NO_CWCTYPE) ||                   \
    defined(BOOST_NO_STD_WSTRING)
#ifndef BOOST_XPRESSIVE_NO_WREGEX
#define BOOST_XPRESSIVE_NO_WREGEX
#endif
#endif

// Stack protection under MS Windows
// Config logic taken from boost/regex/config.hpp
#ifndef BOOST_XPRESSIVE_HAS_MS_STACK_GUARD
#if (defined(_WIN32) || defined(_WIN64) || defined(_WINCE)) &&                 \
    !defined(__GNUC__) &&                                                      \
    !(defined(__BORLANDC__) && (__BORLANDC__ >= 0x600)) &&                     \
    !(defined(__MWERKS__) && (__MWERKS__ <= 0x3003))
#define BOOST_XPRESSIVE_HAS_MS_STACK_GUARD 1
#else
#define BOOST_XPRESSIVE_HAS_MS_STACK_GUARD 0
#endif
#endif

#include <boost/proto/proto_fwd.hpp>

namespace boost
{
namespace xpressive
{

template <typename Char>
struct cpp_regex_traits;

template <typename Char>
struct c_regex_traits;

template <typename Elem>
struct null_regex_traits;

namespace detail
{
template <typename Char>
struct default_regex_traits
{
#ifdef BOOST_XPRESSIVE_USE_C_TRAITS
    typedef c_regex_traits<Char> type;
#else
    typedef cpp_regex_traits<Char> type;
#endif
};

struct mark_placeholder;
typedef proto::expr<proto::tag::terminal, proto::term<mark_placeholder>, 0>
    basic_mark_tag;

struct regex_domain;

} // namespace detail

struct mark_tag;

typedef void const* regex_id_type;

struct regex_error;

struct regex_traits_version_1_tag;

struct regex_traits_version_2_tag;

// DEPRECATED
/// INTERNAL ONLY
///
struct regex_traits_version_1_case_fold_tag;

template <typename Trait>
struct has_fold_case;

template <typename BidiIter>
struct basic_regex;

template <typename BidiIter>
struct match_results;

template <typename BidiIter>
struct regex_iterator;

template <typename BidiIter>
struct regex_token_iterator;

template <typename BidiIter>
struct regex_id_filter_predicate;

template <typename BidiIter>
struct sub_match;

template <typename RegexTraits>
struct compiler_traits;

template <typename Char,
          typename Impl = typename detail::default_regex_traits<Char>::type>
struct regex_traits;

template <typename BidiIter,
          typename RegexTraits =
              regex_traits<typename iterator_value<BidiIter>::type>,
          typename CompilerTraits = compiler_traits<RegexTraits>>
struct regex_compiler;

template <typename T>
struct value;

template <typename T>
struct reference;

template <typename T>
struct local;

template <typename T, int I = 0, typename Dummy = proto::is_proto_expr>
struct placeholder;

namespace op
{
struct at;
struct push;
struct push_back;
struct push_front;
struct pop;
struct pop_back;
struct pop_front;
struct front;
struct back;
struct top;
struct first;
struct second;
struct matched;
struct length;
struct str;
struct insert;
struct make_pair;
template <typename T>
struct as;
template <typename T>
struct static_cast_;
template <typename T>
struct dynamic_cast_;
template <typename T>
struct const_cast_;
template <typename T>
struct construct;
template <typename Except>
struct throw_;
struct unwrap_reference;
} // namespace op

///////////////////////////////////////////////////////////////////////////////
// Common typedefs
//
typedef basic_regex<std::string::const_iterator> sregex;
typedef basic_regex<char const*> cregex;

#ifndef BOOST_XPRESSIVE_NO_WREGEX
typedef basic_regex<std::wstring::const_iterator> wsregex;
typedef basic_regex<wchar_t const*> wcregex;
#endif

typedef sub_match<std::string::const_iterator> ssub_match;
typedef sub_match<char const*> csub_match;

#ifndef BOOST_XPRESSIVE_NO_WREGEX
typedef sub_match<std::wstring::const_iterator> wssub_match;
typedef sub_match<wchar_t const*> wcsub_match;
#endif

typedef regex_compiler<std::string::const_iterator> sregex_compiler;
typedef regex_compiler<char const*> cregex_compiler;

#ifndef BOOST_XPRESSIVE_NO_WREGEX
typedef regex_compiler<std::wstring::const_iterator> wsregex_compiler;
typedef regex_compiler<wchar_t const*> wcregex_compiler;
#endif

typedef regex_iterator<std::string::const_iterator> sregex_iterator;
typedef regex_iterator<char const*> cregex_iterator;

#ifndef BOOST_XPRESSIVE_NO_WREGEX
typedef regex_iterator<std::wstring::const_iterator> wsregex_iterator;
typedef regex_iterator<wchar_t const*> wcregex_iterator;
#endif

typedef regex_token_iterator<std::string::const_iterator> sregex_token_iterator;
typedef regex_token_iterator<char const*> cregex_token_iterator;

#ifndef BOOST_XPRESSIVE_NO_WREGEX
typedef regex_token_iterator<std::wstring::const_iterator>
    wsregex_token_iterator;
typedef regex_token_iterator<wchar_t const*> wcregex_token_iterator;
#endif

typedef match_results<std::string::const_iterator> smatch;
typedef match_results<char const*> cmatch;

#ifndef BOOST_XPRESSIVE_NO_WREGEX
typedef match_results<std::wstring::const_iterator> wsmatch;
typedef match_results<wchar_t const*> wcmatch;
#endif

typedef regex_id_filter_predicate<std::string::const_iterator>
    sregex_id_filter_predicate;
typedef regex_id_filter_predicate<char const*> cregex_id_filter_predicate;

#ifndef BOOST_XPRESSIVE_NO_WREGEX
typedef regex_id_filter_predicate<std::wstring::const_iterator>
    wsregex_id_filter_predicate;
typedef regex_id_filter_predicate<wchar_t const*> wcregex_id_filter_predicate;
#endif

} // namespace xpressive
} // namespace boost

#endif

max_stars_repo_name: sotaoverride/backup

max_issues_repo_name: sotaoverride/backup

max_forks_repo_name: sotaoverride/backup


text:
//
// Created by minirop on 04/11/17.
//

#include <fstream>
#include <vector>
#include <boost/algorithm/string/split.hpp>
#include <iostream>

using namespace std::string_literals;

static inline void ltrim(std::string &s)
{
    s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) {
        return !std::isspace(ch);
    }));
}

// trim from end (in place)
static inline void rtrim(std::string &s)
{
    s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) {
        return !std::isspace(ch);
    }).base(), s.end());
}

// trim from both ends (in place)
static inline void trim(std::string &s)
{
    ltrim(s);
    rtrim(s);
}

void defineAst(std::ofstream & file, std::string_view baseName, std::vector<std::string_view> types);
void defineType(std::ofstream & file, std::string_view baseName, std::string_view className, std::string_view fieldsList);
void defineVisitor(std::ofstream & file, std::string_view baseName, std::vector<std::string> types);

int main(int argc, char** argv)
{
    std::ofstream file("ast.h"s);

    file<< "#ifndef LOXPLUS_AST_H\n"
        << "#define LOXPLUS_AST_H\n"
        << "\n"
        << "#include \"Token.h\"\n"
        << "#include \"Object.h\"\n"
        << "#include \"CreatableType.h\"\n"
        << "#include <vector>\n"
        << "\n";

    defineAst(file, "Expr", {
        "Assign   : Token name, Expr* value",
        "Binary   : Expr* left, Token op, Expr* right",
        "Call     : Expr* callee, Token paren, std::vector<Expr*> arguments",
        "Get      : Expr* object, Token name",
        "Grouping : Expr* expression",
        "Literal  : Object value",
        "Logical  : Expr* left, Token op, Expr* right",
        "Set      : Expr* object, Token name, Expr* value",
        "This     : Token keyword",
        "Unary    : Token op, Expr* right",
        "Variable : Token name"
    });

    defineAst(file, "Stmt", {
        "Block      : std::vector<Stmt*> statements",
        "Class      : Token name, std::vector<FunctionStmt*> methods",
        "Expression : Expr* expression",
        "Function   : Token name, std::vector<Token> parameters, std::vector<Stmt*> body",
        "If         : Expr* condition, Stmt* thenBranch, Stmt* elseBranch",
        "Print      : Expr* expression",
        "Return     : Token keyword, Expr* value",
        "Var        : Token name, Expr* initializer",
        "While      : Expr* condition, Stmt* body"
    });

    file<< "#endif //LOXPLUS_AST_H\n";
    file.close();
    return 0;
}

void defineAst(std::ofstream & file, std::string_view baseName, std::vector<std::string_view> types)
{
    std::vector<std::pair<std::string, std::string>> typeFields;
    std::vector<std::string> typesList;
    for (auto & type : types)
    {
        auto it = type.find_first_of(':');
        auto typeName = std::string { type.substr(0, it) };
        auto fieldsNames = std::string { type.substr(it+1) };

        trim(typeName);
        trim(fieldsNames);

        typeFields.emplace_back(typeName, fieldsNames);
        typesList.push_back(typeName);
        file<< "class " << typeName << baseName << ";\n";
    }
    file<< '\n';

    defineVisitor(file, baseName, typesList);

    file<< "struct " << baseName << "\n"
        << "{\n"
        << "\tvirtual void accept(Visitor" << baseName << " & visitor) = 0;\n"
        << "};\n"
        << "\n";

    for (auto & type : typeFields)
    {
        defineType(file, baseName, type.first, type.second);
    }
}

void defineVisitor(std::ofstream & file, std::string_view baseName, std::vector<std::string> types)
{
    file<< "struct Visitor" << baseName << "\n"
        << "{\n"
        << "\tvirtual ~Visitor" << baseName << "() = default;\n\n";

    for (auto & type : types)
    {
        std::string varName { baseName };
        varName[0] = static_cast<char>(std::tolower(varName[0]));
        file<< "\tvirtual void visit" << type << baseName << "(" << type << baseName << " & " << varName << ") = 0;\n";
    }
    file<< "};\n\n";
}

void defineType(std::ofstream & file, std::string_view baseName, std::string_view className, std::string_view fieldsList)
{
    file<< "struct " << className << baseName << " : CreatableType<" << className << baseName << ">, " << baseName << "\n"
        << "{\n";

    std::vector<std::string> fields;
    boost::split(fields, fieldsList, [](char c){ return c == ','; });

    file<< "\t" << (fields.size() == 1 ? "explicit " : "") << className << baseName << "(" << fieldsList << ")\n"
        << "\t\t: ";
    int i = 0;
    for (auto & field : fields)
    {
        trim(field);
        std::vector<std::string> data;
        boost::split(data, field, [](char c){ return c == ' '; });

        file<< data[1] << " { ";
        if (data[0].find(':') != std::string::npos || data[0] == "Token" || data[0] == "Object")
        {
            file<< "std::move(" << data[1] << ")";
        }
        else
        {
            file<< data[1];
        }
        file<< " }";
        i++;
        if (i < fields.size()) file<< ", ";
        else file<< "\n";
    }
    file<< "\t{\n\t}\n\n";

    for (auto & field : fields)
    {
        trim(field);
        file<< "\t" << field << ";\n";
    }

    file<< "\n"
        << "\tvoid accept(Visitor" << baseName << " & visitor) override\n"
        << "\t{\n"
        << "\t\tvisitor.visit" << className << baseName << "(*this);\n"
        << "\t}\n";

    file<< "};\n"
        << "\n";
}

max_stars_repo_name: minirop/lox-plus

max_issues_repo_name: minirop/lox-plus

max_forks_repo_name: minirop/lox-plus


text:
//=======================================================================
// Copyright Baptiste Wicht 2011-2016.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#define BOOST_NO_RTTI
#define BOOST_NO_TYPEID
#include <boost/range/adaptors.hpp>

#include "Type.hpp"
#include "FunctionContext.hpp"
#include "GlobalContext.hpp"
#include "Variable.hpp"

#include "mtac/DeadCodeElimination.hpp"
#include "mtac/GlobalOptimizations.hpp"
#include "mtac/LiveVariableAnalysisProblem.hpp"
#include "mtac/Utils.hpp"
#include "mtac/Offset.hpp"
#include "mtac/Quadruple.hpp"

using namespace eddic;

bool mtac::dead_code_elimination::operator()(mtac::Function& function){
    bool optimized = false;

    std::vector<std::size_t> to_delete;

    //1. DCE based on data-flow analysis

    mtac::LiveVariableAnalysisProblem problem;
    auto results = mtac::data_flow(function, problem);

    for(auto& block : function){
        auto& out = results->OUT[block];

        for(auto& quadruple : boost::adaptors::reverse(block->statements)){
            if(quadruple.result && mtac::erase_result(quadruple.op)){
                if(out.top() || out.values().find(quadruple.result) == out.values().end()){
                    to_delete.push_back(quadruple.uid());
                }
            }

            problem.transfer(block, quadruple, out);
        }
    }

    //Delete what has been found on previous steps

    if(!to_delete.empty()){
        optimized = true;

        for(auto& block : function){
            for(auto& quadruple : block->statements){
                if(std::find(to_delete.begin(), to_delete.end(), quadruple.uid()) != to_delete.end()){
                    mtac::transform_to_nop(quadruple);
                }
            }
        }
    }

    //2. Remove variables that contribute only to themselves
    //TODO This could probably be done directly in the data-flow DCE

    std::unordered_set<std::shared_ptr<Variable>> candidates;

    for(auto& block : function){
        for(auto& quadruple : block->statements){
            if(quadruple.result && mtac::erase_result(quadruple.op)){
                if_init_equals(quadruple.arg1, quadruple.result, [&candidates, &quadruple](){ candidates.insert(quadruple.result);});
                if_init_equals(quadruple.arg2, quadruple.result, [&candidates, &quadruple](){ candidates.insert(quadruple.result);});
            }
        }
    }

    for(auto& block : function){
        for(auto& quadruple : block->statements){
            if(quadruple.result && mtac::erase_result(quadruple.op)){
                if_init_not_equals<std::shared_ptr<Variable>>(quadruple.arg1, quadruple.result, [&candidates](std::shared_ptr<Variable>& var){ candidates.erase(var);});
                if_init_not_equals<std::shared_ptr<Variable>>(quadruple.arg2, quadruple.result, [&candidates](std::shared_ptr<Variable>& var){ candidates.erase(var);});
            } else {
                candidates.erase(quadruple.result);

                if_init<std::shared_ptr<Variable>>(quadruple.arg1, [&candidates](std::shared_ptr<Variable>& var){ candidates.erase(var); });
                if_init<std::shared_ptr<Variable>>(quadruple.arg2, [&candidates](std::shared_ptr<Variable>& var){ candidates.erase(var); });
            }
        }
    }

    if(!candidates.empty()){
        for(auto& block : function){
            for(auto& quadruple : block->statements){
                if(quadruple.result && mtac::erase_result(quadruple.op) && candidates.find(quadruple.result) != candidates.end()){
                    mtac::transform_to_nop(quadruple);
                    optimized = true;
                }
            }
        }
    }

    //TODO Review or remove this optimization, this is quite unsafe

    std::unordered_set<Offset, mtac::OffsetHash> used_offsets;
    std::unordered_set<std::shared_ptr<Variable>> invalidated_offsets;

    for(auto& block : function){
        for(auto& quadruple : block->statements){
            if(quadruple.op == mtac::Operator::DOT || quadruple.op == mtac::Operator::FDOT || quadruple.op == mtac::Operator::PDOT){
                if(auto* var_ptr = boost::get<std::shared_ptr<Variable>>(&*quadruple.arg1)){
                    if(auto* offset_ptr = boost::get<int>(&*quadruple.arg2)){
                        mtac::Offset offset(*var_ptr, *offset_ptr);
                        used_offsets.insert(offset);
                    } else {
                        invalidated_offsets.insert(*var_ptr);
                    }
                }
            }
        }
    }

    for(auto& block : function){
        for(auto& quadruple : block->statements){
            if(quadruple.op == mtac::Operator::DOT_ASSIGN || quadruple.op == mtac::Operator::DOT_FASSIGN || quadruple.op == mtac::Operator::DOT_PASSIGN){
                if(invalidated_offsets.find(quadruple.result) == invalidated_offsets.end()){
                    //Arrays are a problem because they are not considered as escaped after being passed in parameters
                    if(!quadruple.result->type()->is_pointer() && !quadruple.result->type()->is_array()){
                        if(auto* offset_ptr = boost::get<int>(&*quadruple.arg1)){
                            if(quadruple.result->type()->is_custom_type() || quadruple.result->type()->is_template_type()){
                                auto struct_type = function.context->global()->get_struct(quadruple.result->type()->mangle());
                                auto member_type = function.context->global()->member_type(struct_type, *offset_ptr);

                                if(member_type->is_pointer()){
                                    continue;
                                }
                            }

                            mtac::Offset offset(quadruple.result, *offset_ptr);

                            if(problem.pointer_escaped->find(quadruple.result) == problem.pointer_escaped->end() && used_offsets.find(offset) == used_offsets.end()){
                                mtac::transform_to_nop(quadruple);
                                optimized=true;
                            }
                        }
                    }
                }
            }
        }
    }

    return optimized;
}

max_stars_repo_name: wichtounet/eddic

max_issues_repo_name: wichtounet/eddic

max_forks_repo_name: wichtounet/eddic


text:
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <algorithm>
#include <functional>
#include <string>
#include <assert.h>

void foo() {

    boost::array<int, 12> values = {{1, 2, 3, 4, 5, 6, 7, 100, 99, 98, 97, 96}};

    // Counting values greater or equal to 5
    std::size_t count0 = std::count_if(values.begin(), values.end(),
    std::bind1st(std::less<int>(), 5));
    std::size_t count1 = std::count_if(values.begin(), values.end(),
    boost::bind(std::less<int>(), 5, _1));
    assert(count0 == count1);

    // Counting values less than 5
    count0 = std::count_if(values.begin(), values.end(),
    std::bind2nd(std::less<int>(), 5));
    count1 = std::count_if(values.begin(), values.end(),
    boost::bind(std::less<int>(), _1, 5));
    assert(count0 == count1);

    boost::array<std::string, 3>  str_values = {{"We ", "are", " the champions!"}};

    // Counting empty strings
    count0 = std::count_if(str_values.begin(), str_values.end(),
    std::mem_fun_ref(&std::string::empty));
    count1 = std::count_if(str_values.begin(), str_values.end(),
    boost::bind(&std::string::empty, _1));
    assert(count0 == count1);

    // Counting strings with length less than 5

    // That code won't compile! And it is hard to understand
    //count0 = std::count_if(str_values.begin(), str_values.end(),
    //std::bind2nd(
    //    std::bind1st(
    //        std::less<std::size_t>(),
    //        std::mem_fun_ref(&std::string::size)
    //    )
    //, 5
    //));

    // This will become much more readable,
    // when you get used to bind
    count1 = std::count_if(str_values.begin(), str_values.end(),
    boost::bind(std::less<std::size_t>(), boost::bind(&std::string::size, _1), 5));
    assert(2 == count1);

    std::string s("Expensive copy constructor of std::string will be called when binding");
    count0 = std::count_if(str_values.begin(), str_values.end(), std::bind2nd(std::less<std::string>(), s));
    count1 = std::count_if(str_values.begin(), str_values.end(), boost::bind(std::less<std::string>(), _1, s));
    assert(count0 == count1);

} // foo

#include <boost/ref.hpp>

void wierd_appender(std::string& to, const std::string& from) {
    to += from;
};

void foo2() {

    std::size_t count0;
    std::size_t count1;
    boost::array<std::string, 3>  str_values = {{"We ", "are", " the champions!"}};

    std::string s("Expensive copy constructor of std::string now won't becalled when binding");
    count0 = std::count_if(str_values.begin(), str_values.end(), std::bind2nd(std::less<std::string>(), boost::cref(s)));
    count1 = std::count_if(str_values.begin(), str_values.end(), boost::bind(std::less<std::string>(), _1, boost::cref(s)));
    assert(count0 == count1);

    std::string result;
    std::for_each(str_values.cbegin(), str_values.cend(), boost::bind(&wierd_appender, boost::ref(result), _1));
    assert(result == "We are the champions!");

} // foo2

int main () {
    foo();
    foo2();

    return 0;
}


text:
//==================================================================================================
/*!
  @file

  @copyright 2015 NumScale SAS
  @copyright 2015 J.T. Lapreste

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_SIGN_HPP_INCLUDED
#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_SIGN_HPP_INCLUDED

#ifndef BOOST_SIMD_NO_NANS
#include <boost/simd/function/scalar/is_nan.hpp>
#endif
#include <boost/simd/function/scalar/is_gtz.hpp>
#include <boost/simd/function/scalar/is_ltz.hpp>
#include <boost/simd/function/scalar/shift_right.hpp>
#include <boost/dispatch/function/overload.hpp>
#include <boost/config.hpp>

namespace boost { namespace simd { namespace ext
{
  namespace bd = boost::dispatch;
  BOOST_DISPATCH_OVERLOAD ( sign_
                          , (typename A0)
                          , bd::cpu_
                          , bd::scalar_< bd::signed_<A0> >
                          )
  {
    BOOST_FORCEINLINE A0 operator() ( A0 a0) const BOOST_NOEXCEPT
    {
      return shift_right(a0, (sizeof(A0)*8-1)) - shift_right(-a0, (sizeof(A0)*8-1));
    }
  };

  BOOST_DISPATCH_OVERLOAD ( sign_
                          , (typename A0)
                          , bd::cpu_
                          , bd::scalar_< bd::unsigned_<A0> >
                          )
  {
    BOOST_FORCEINLINE A0 operator() ( A0 a0) const BOOST_NOEXCEPT
    {
      return !!a0;
    }
  };

  BOOST_DISPATCH_OVERLOAD ( sign_
                          , (typename A0)
                          , bd::cpu_
                          , bd::scalar_< bd::floating_<A0> >
                          )
  {
    BOOST_FORCEINLINE A0 operator() ( A0 a0) const BOOST_NOEXCEPT
    {
      A0 r = bool(is_gtz(a0))-bool(is_ltz(a0));
#ifdef BOOST_SIMD_NO_NANS
      return r;
#else
      return is_nan(a0) ? a0 : r;
#endif
    }
  };
} } }

#endif


text:
/*********************************************************************
* Software License Agreement (BSD License)
*
*  Copyright (c) 2008, Willow Garage, Inc.
*  All rights reserved.
*
*  Redistribution and use in source and binary forms, with or without
*  modification, are permitted provided that the following conditions
*  are met:
*
*   * Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*   * Redistributions in binary form must reproduce the above
*     copyright notice, this list of conditions and the following
*     disclaimer in the documentation and/or other materials provided
*     with the distribution.
*   * Neither the name of the Willow Garage nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
*  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
*  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
*  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
*  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
*  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
*  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
*  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
*  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
*  POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#include <boost/version.hpp>
#if ((BOOST_VERSION / 100) % 1000) >= 53
#include <boost/thread/lock_guard.hpp>
#endif

#include <ros/ros.h>
#include <nodelet/nodelet.h>
#include <image_transport/image_transport.h>
#include <image_geometry/pinhole_camera_model.h>
#include <cv_bridge/cv_bridge.h>
#include <dynamic_reconfigure/server.h>
#include <image_proc/RectifyConfig.h>

namespace image_proc {

class RectifyNodelet : public nodelet::Nodelet
{
  // ROS communication
  boost::shared_ptr<image_transport::ImageTransport> it_;
  image_transport::CameraSubscriber sub_camera_;
  int queue_size_;

  boost::mutex connect_mutex_;
  image_transport::Publisher pub_rect_;

  // Dynamic reconfigure
  boost::recursive_mutex config_mutex_;
  typedef image_proc::RectifyConfig Config;
  typedef dynamic_reconfigure::Server<Config> ReconfigureServer;
  boost::shared_ptr<ReconfigureServer> reconfigure_server_;
  Config config_;

  // Processing state (note: only safe because we're using single-threaded NodeHandle!)
  image_geometry::PinholeCameraModel model_;

  virtual void onInit();

  void connectCb();

  void imageCb(const sensor_msgs::ImageConstPtr& image_msg,
               const sensor_msgs::CameraInfoConstPtr& info_msg);

  void configCb(Config &config, uint32_t level);
};

void RectifyNodelet::onInit()
{
  ros::NodeHandle &nh         = getNodeHandle();
  ros::NodeHandle &private_nh = getPrivateNodeHandle();
  it_.reset(new image_transport::ImageTransport(nh));

  // Read parameters
  private_nh.param("queue_size", queue_size_, 5);

  // Set up dynamic reconfigure
  reconfigure_server_.reset(new ReconfigureServer(config_mutex_, private_nh));
  ReconfigureServer::CallbackType f = boost::bind(&RectifyNodelet::configCb, this, _1, _2);
  reconfigure_server_->setCallback(f);

  // Monitor whether anyone is subscribed to the output
  image_transport::SubscriberStatusCallback connect_cb = boost::bind(&RectifyNodelet::connectCb, this);
  // Make sure we don't enter connectCb() between advertising and assigning to pub_rect_
  boost::lock_guard<boost::mutex> lock(connect_mutex_);
  pub_rect_  = it_->advertise("image_rect",  1, connect_cb, connect_cb);
}

// Handles (un)subscribing when clients (un)subscribe
void RectifyNodelet::connectCb()
{
  boost::lock_guard<boost::mutex> lock(connect_mutex_);
  if (pub_rect_.getNumSubscribers() == 0)
    sub_camera_.shutdown();
  else if (!sub_camera_)
  {
    image_transport::TransportHints hints("raw", ros::TransportHints(), getPrivateNodeHandle());
    sub_camera_ = it_->subscribeCamera("image_mono", queue_size_, &RectifyNodelet::imageCb, this, hints);
  }
}

void RectifyNodelet::imageCb(const sensor_msgs::ImageConstPtr& image_msg,
                             const sensor_msgs::CameraInfoConstPtr& info_msg)
{
  // Verify camera is actually calibrated
  if (info_msg->K[0] == 0.0) {
    NODELET_ERROR_THROTTLE(30, "Rectified topic '%s' requested but camera publishing '%s' "
                           "is uncalibrated", pub_rect_.getTopic().c_str(),
                           sub_camera_.getInfoTopic().c_str());
    return;
  }

  // If zero distortion, just pass the message along
  bool zero_distortion = true;
  for (size_t i = 0; i < info_msg->D.size(); ++i)
  {
    if (info_msg->D[i] != 0.0)
    {
      zero_distortion = false;
      break;
    }
  }
  // This will be true if D is empty/zero sized
  if (zero_distortion)
  {
    pub_rect_.publish(image_msg);
    return;
  }

  // Update the camera model
  model_.fromCameraInfo(info_msg);

  // Create cv::Mat views onto both buffers
  const cv::Mat image = cv_bridge::toCvShare(image_msg)->image;
  cv::Mat rect;

  // Rectify and publish
  int interpolation;
  {
    boost::lock_guard<boost::recursive_mutex> lock(config_mutex_);
    interpolation = config_.interpolation;
  }
  model_.rectifyImage(image, rect, interpolation);

  // Allocate new rectified image message
  sensor_msgs::ImagePtr rect_msg = cv_bridge::CvImage(image_msg->header, image_msg->encoding, rect).toImageMsg();
  pub_rect_.publish(rect_msg);
}

void RectifyNodelet::configCb(Config &config, uint32_t level)
{
  config_ = config;
}

} // namespace image_proc

// Register nodelet
#include <pluginlib/class_list_macros.h>
PLUGINLIB_EXPORT_CLASS( image_proc::RectifyNodelet, nodelet::Nodelet)


text:
//
// Oliver Wilson <oliver.wilson@ed.ac.uk>
//

// This file should be compiled only when the LM_RAND flag is enabled.
//
// The following ifdef prevents XCode and other non-bjam build systems
// from attempting to compile this file when LM_RAND is disabled.
//
#ifdef LM_RAND

#include "LM/Base.h"
#include "LM/LDHT.h"
#include "moses/FFState.h"
#include "moses/TypeDef.h"
#include "moses/Hypothesis.h"
#include "moses/StaticData.h"
#include "util/exception.hh"

#include <LDHT/Client.h>
#include <LDHT/ClientLocal.h>
#include <LDHT/NewNgram.h>
#include <LDHT/FactoryCollection.h>

#include <boost/thread/tss.hpp>

namespace Moses
{

struct LDHTLMState : public FFState {
  LDHT::NewNgram gram_fingerprints;
  bool finalised;
  std::vector<int> request_tags;

  LDHTLMState(): finalised(false) {
  }

  void setFinalised() {
    this->finalised = true;
  }

  void appendRequestTag(int tag) {
    this->request_tags.push_back(tag);
  }

  void clearRequestTags() {
    this->request_tags.clear();
  }

  std::vector<int>::iterator requestTagsBegin() {
    return this->request_tags.begin();
  }

  std::vector<int>::iterator requestTagsEnd() {
    return this->request_tags.end();
  }

  int Compare(const FFState& uncast_other) const {
    const LDHTLMState &other = static_cast<const LDHTLMState&>(uncast_other);
    //if (!this->finalised)
    //    return -1;

    return gram_fingerprints.compareMoses(other.gram_fingerprints);
  }

  void copyFrom(const LDHTLMState& other) {
    gram_fingerprints.copyFrom(other.gram_fingerprints);
    finalised = false;
  }
};

class LanguageModelLDHT : public LanguageModel
{
public:
  LanguageModelLDHT();
  LanguageModelLDHT(const std::string& path,
                    ScoreIndexManager& manager,
                    FactorType factorType);
  LanguageModelLDHT(ScoreIndexManager& manager,
                    LanguageModelLDHT& copyFrom);

  LDHT::Client* getClientUnsafe() const;
  LDHT::Client* getClientSafe();
  LDHT::Client* initTSSClient();
  virtual ~LanguageModelLDHT();
  virtual void InitializeForInput(ttasksptr const& ttask);
  virtual void CleanUpAfterSentenceProcessing(const InputType &source);
  virtual const FFState* EmptyHypothesisState(const InputType& input) const;
  virtual void CalcScore(const Phrase& phrase,
                         float& fullScore,
                         float& ngramScore,
                         std::size_t& oovCount) const;
  virtual void CalcScoreFromCache(const Phrase& phrase,
                                  float& fullScore,
                                  float& ngramScore,
                                  std::size_t& oovCount) const;
  FFState* Evaluate(const Hypothesis& hypo,
                    const FFState* input_state,
                    ScoreComponentCollection* score_output) const;
  FFState* EvaluateWhenApplied(const ChartHypothesis& hypo,
                               int featureID,
                               ScoreComponentCollection* accumulator) const;

  virtual void IssueRequestsFor(Hypothesis& hypo,
                                const FFState* input_state);
  float calcScoreFromState(LDHTLMState* hypo) const;
  void sync();
  void SetFFStateIdx(int state_idx);

protected:
  boost::thread_specific_ptr<LDHT::Client> m_client;
  std::string m_configPath;
  FactorType m_factorType;
  int m_state_idx;
  int m_calc_score_count;
  uint64_t m_start_tick;

};

LanguageModel* ConstructLDHTLM(const std::string& path,
                               ScoreIndexManager& manager,
                               FactorType factorType)
{
  return new LanguageModelLDHT(path, manager, factorType);
}

LanguageModelLDHT::LanguageModelLDHT() : LanguageModel(), m_client(NULL)
{
  m_enableOOVFeature = false;
}

LanguageModelLDHT::LanguageModelLDHT(ScoreIndexManager& manager,
                                     LanguageModelLDHT& copyFrom)
{
  m_calc_score_count = 0;
  //m_client = copyFrom.m_client;
  m_factorType = copyFrom.m_factorType;
  m_configPath = copyFrom.m_configPath;
  Init(manager);
}

LanguageModelLDHT::LanguageModelLDHT(const std::string& path,
                                     ScoreIndexManager& manager,
                                     FactorType factorType)
  : m_factorType(factorType)
{
  m_configPath = path;
  Init(manager);
}

LanguageModelLDHT::~LanguageModelLDHT()
{
  // TODO(wilson): should cleanup for each individual thread.
  //delete getClientSafe();
}

// Check that there is a TSS Client instance, and instantiate one if
// there isn't.
LDHT::Client* LanguageModelLDHT::getClientSafe()
{
  if (m_client.get() == NULL)
    m_client.reset(initTSSClient());
  return m_client.get();
}

// Do not check that there is a TSS Client instance.
LDHT::Client* LanguageModelLDHT::getClientUnsafe() const
{
  return m_client.get();
}

LDHT::Client* LanguageModelLDHT::initTSSClient()
{
  std::ifstream config_file(m_configPath.c_str());
  std::string ldht_config_path;
  getline(config_file, ldht_config_path);
  std::string ldhtlm_config_path;
  getline(config_file, ldhtlm_config_path);

  LDHT::FactoryCollection* factory_collection =
    LDHT::FactoryCollection::createDefaultFactoryCollection();

  LDHT::Client* client;
  //client = new LDHT::ClientLocal();
  client = new LDHT::Client();
  client->fromXmlFiles(*factory_collection,
                       ldht_config_path,
                       ldhtlm_config_path);
  return client;
}

void LanguageModelLDHT::InitializeForInput(ttasksptr const& ttask)
{
  getClientSafe()->clearCache();
  m_start_tick = LDHT::Util::rdtsc();
}

void LanguageModelLDHT::CleanUpAfterSentenceProcessing(const InputType &source)
{
  LDHT::Client* client = getClientSafe();

  std::cerr << "LDHT sentence stats:" << std::endl;
  std::cerr << "  ngrams submitted: " << client->getNumNgramsSubmitted() << std::endl
            << "  ngrams requested: " << client->getNumNgramsRequested() << std::endl
            << "  ngrams not found: " << client->getKeyNotFoundCount() << std::endl
            << "        cache hits: " << client->getCacheHitCount() << std::endl
            << "        inferences: " << client->getInferenceCount() << std::endl
            << "      pcnt latency: " << (float)client->getLatencyTicks() / (float)(LDHT::Util::rdtsc() - m_start_tick) * 100.0 << std::endl;
  m_start_tick = 0;
  client->resetLatencyTicks();
  client->resetNumNgramsSubmitted();
  client->resetNumNgramsRequested();
  client->resetInferenceCount();
  client->resetCacheHitCount();
  client->resetKeyNotFoundCount();
}

const FFState* LanguageModelLDHT::EmptyHypothesisState(
  const InputType& input) const
{
  return NULL;
}

void LanguageModelLDHT::CalcScore(const Phrase& phrase,
                                  float& fullScore,
                                  float& ngramScore,
                                  std::size_t& oovCount) const
{
  const_cast<LanguageModelLDHT*>(this)->m_calc_score_count++;
  if (m_calc_score_count > 10000) {
    const_cast<LanguageModelLDHT*>(this)->m_calc_score_count = 0;
    const_cast<LanguageModelLDHT*>(this)->sync();
  }

  // TODO(wilson): handle nonterminal words.
  LDHT::Client* client = getClientUnsafe();
  // Score the first order - 1 words of the phrase.
  int order = LDHT::NewNgram::k_max_order;
  int prefix_start = 0;
  int prefix_end = std::min(phrase.GetSize(), static_cast<size_t>(order - 1));
  LDHT::NewNgram ngram;
  for (int word_idx = prefix_start; word_idx < prefix_end; ++word_idx) {
    ngram.appendGram(phrase.GetWord(word_idx)
                     .GetFactor(m_factorType)->GetString().c_str());
    client->requestNgram(ngram);
  }
  // Now score all subsequent ngrams to end of phrase.
  int internal_start = prefix_end;
  int internal_end = phrase.GetSize();
  for (int word_idx = internal_start; word_idx < internal_end; ++word_idx) {
    ngram.appendGram(phrase.GetWord(word_idx)
                     .GetFactor(m_factorType)->GetString().c_str());
    client->requestNgram(ngram);
  }

  fullScore = 0;
  ngramScore = 0;
  oovCount = 0;
}

void LanguageModelLDHT::CalcScoreFromCache(const Phrase& phrase,
    float& fullScore,
    float& ngramScore,
    std::size_t& oovCount) const
{
  // Issue requests for phrase internal ngrams.
  // Sync if necessary. (or autosync).
  const_cast<LanguageModelLDHT*>(this)->sync();

  // TODO(wilson): handle nonterminal words.
  LDHT::Client* client = getClientUnsafe();
  // Score the first order - 1 words of the phrase.
  int order = LDHT::NewNgram::k_max_order;
  int prefix_start = 0;
  int prefix_end = std::min(phrase.GetSize(), static_cast<size_t>(order - 1));
  LDHT::NewNgram ngram;
  std::deque<int> full_score_tags;
  for (int word_idx = prefix_start; word_idx < prefix_end; ++word_idx) {
    ngram.appendGram(phrase.GetWord(word_idx)
                     .GetFactor(m_factorType)->GetString().c_str());
    full_score_tags.push_back(client->requestNgram(ngram));
  }
  // Now score all subsequent ngrams to end of phrase.
  int internal_start = prefix_end;
  int internal_end = phrase.GetSize();
  std::deque<int> internal_score_tags;
  for (int word_idx = internal_start; word_idx < internal_end; ++word_idx) {
    ngram.appendGram(phrase.GetWord(word_idx)
                     .GetFactor(m_factorType)->GetString().c_str());
    internal_score_tags.push_back(client->requestNgram(ngram));
  }

  // Wait for resposes from the servers.
  //client->awaitResponses();

  // Calculate the full phrase score, and the internal score.
  fullScore = 0.0;
  while (!full_score_tags.empty()) {
    fullScore += client->getNgramScore(full_score_tags.front());
    full_score_tags.pop_front();
  }
  ngramScore = 0.0;
  while (!internal_score_tags.empty()) {
    float score = client->getNgramScore(internal_score_tags.front());
    internal_score_tags.pop_front();
    fullScore += score;
    ngramScore += score;
  }
  fullScore = TransformLMScore(fullScore);
  ngramScore = TransformLMScore(ngramScore);
  oovCount = 0;
}

void LanguageModelLDHT::IssueRequestsFor(Hypothesis& hypo,
    const FFState* input_state)
{
  // TODO(wilson): handle nonterminal words.
  LDHT::Client* client = getClientUnsafe();

  // Create a new state and copy the contents of the input_state if
  // supplied.
  LDHTLMState* new_state = new LDHTLMState();
  if (input_state == NULL) {
    if (hypo.GetCurrTargetWordsRange().GetStartPos() != 0) {
      UTIL_THROW2("got a null state but not at start of sentence");
    }
    new_state->gram_fingerprints.appendGram(BOS_);
  } else {
    if (hypo.GetCurrTargetWordsRange().GetStartPos() == 0) {
      UTIL_THROW2("got a non null state but at start of sentence");
    }
    new_state->copyFrom(static_cast<const LDHTLMState&>(*input_state));
  }

  // Score ngrams that overlap with the previous phrase.
  int order = LDHT::NewNgram::k_max_order;
  int phrase_start = hypo.GetCurrTargetWordsRange().GetStartPos();
  int phrase_end = hypo.GetCurrTargetWordsRange().GetEndPos() + 1;
  int overlap_start = phrase_start;
  int overlap_end = std::min(phrase_end, phrase_start + order - 1);
  int word_idx = overlap_start;
  LDHT::NewNgram& ngram = new_state->gram_fingerprints;
  for (; word_idx < overlap_end; ++word_idx) {
    ngram.appendGram(
      hypo.GetFactor(word_idx, m_factorType)->GetString().c_str());
    new_state->appendRequestTag(client->requestNgram(ngram));
  }
  // No need to score phrase internal ngrams, but keep track of them
  // in the state (which in this case is the NewNgram containing the
  // hashes of the individual grams).
  for (; word_idx < phrase_end; ++word_idx) {
    ngram.appendGram(
      hypo.GetFactor(word_idx, m_factorType)->GetString().c_str());
  }
  // If this is the last phrase in the sentence, score the last ngram
  // with the end of sentence marker on it.
  if (hypo.IsSourceCompleted()) {
    ngram.appendGram(EOS_);
    //request_tags.push_back(client->requestNgram(ngram));
    new_state->appendRequestTag(client->requestNgram(ngram));
  }
  hypo.SetFFState(m_state_idx, new_state);
}

void LanguageModelLDHT::sync()
{
  m_calc_score_count = 0;
  getClientUnsafe()->awaitResponses();
}

void LanguageModelLDHT::SetFFStateIdx(int state_idx)
{
  m_state_idx = state_idx;
}

FFState* LanguageModelLDHT::Evaluate(
  const Hypothesis& hypo,
  const FFState* input_state_ignored,
  ScoreComponentCollection* score_output) const
{
  // Input state is the state from the previous hypothesis, which
  // we are not interested in. The requests for this hypo should
  // already have been issued via IssueRequestsFor() and the LM then
  // synced and all responses processed, and the tags placed in our
  // FFState of hypo.
  LDHTLMState* state = const_cast<LDHTLMState*>(static_cast<const LDHTLMState*>(hypo.GetFFState(m_state_idx)));

  float score = calcScoreFromState(state);
  score = FloorScore(TransformLMScore(score));
  score_output->PlusEquals(this, score);

  return state;
}

FFState* LanguageModelLDHT::EvaluateWhenApplied(
  const ChartHypothesis& hypo,
  int featureID,
  ScoreComponentCollection* accumulator) const
{
  return NULL;
}

float LanguageModelLDHT::calcScoreFromState(LDHTLMState* state) const
{
  float score = 0.0;
  std::vector<int>::iterator tag_iter;
  LDHT::Client* client = getClientUnsafe();
  for (tag_iter = state->requestTagsBegin();
       tag_iter != state->requestTagsEnd();
       ++tag_iter) {
    score += client->getNgramScore(*tag_iter);
  }
  state->clearRequestTags();
  state->setFinalised();
  return score;
}

}  // namespace Moses.

#endif

max_issues_repo_name: Pangeamt/nectm

max_forks_repo_name: Pangeamt/nectm


text:
/*
 * Representer.hxx
 *
 * Created by Remi Blanc, Marcel Luethi
 *
 * Copyright (c) 2011 ETH Zurich
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 *
 * Neither the name of the project's author nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#ifndef __ConditionalModelBuilder_hxx
#define __ConditionalModelBuilder_hxx

#include "CommonTypes.h"
#include "Exceptions.h"
#include <iostream>

#include <Eigen/SVD>
#include "PCAModelBuilder.h"
#include "ConditionalModelBuilder.h"

namespace statismo {

//
// ConditionalModelBuilder
//
//

template <typename T>
unsigned
ConditionalModelBuilder<T>::PrepareData(const DataItemListType& sampleDataList,
                                        const SurrogateTypeInfoType& surrogateTypesInfo,
                                        const CondVariableValueVectorType& conditioningInfo,
                                        DataItemListType *acceptedSamples,
                                        MatrixType *surrogateMatrix,
                                        VectorType *conditions) const {
    bool acceptSample;
    unsigned nbAcceptedSamples = 0;
    unsigned nbContinuousSurrogatesInUse = 0, nbCategoricalSurrogatesInUse = 0;
    std::vector<unsigned> indicesContinuousSurrogatesInUse;
    std::vector<unsigned> indicesCategoricalSurrogatesInUse;

    //first: identify the continuous and categorical variables, which are used for conditioning and which are not
    for (unsigned i=0 ; i<conditioningInfo.size() ; i++) {
        if (conditioningInfo[i].first) { //only variables that are used for conditioning are of interest here
            if (surrogateTypesInfo.types[i] == DataItemWithSurrogatesType::Continuous) {
                nbContinuousSurrogatesInUse++;
                indicesContinuousSurrogatesInUse.push_back(i);
            } else {
                nbCategoricalSurrogatesInUse++;
                indicesCategoricalSurrogatesInUse.push_back(i);
            }
        }
    }
    conditions->resize(nbContinuousSurrogatesInUse);
    for (unsigned i=0 ; i<nbContinuousSurrogatesInUse ; i++) (*conditions)(i) = conditioningInfo[i].second;
    surrogateMatrix->resize(nbContinuousSurrogatesInUse, sampleDataList.size()); //number of variables is now known: nbContinuousSurrogatesInUse ; the number of samples is yet unknown...

    //now, browse all samples to select the ones which fall into the requested categories
    for (typename DataItemListType::const_iterator it = sampleDataList.begin(); it != sampleDataList.end(); ++it) {
        const DataItemWithSurrogatesType* sampleData = dynamic_cast<const DataItemWithSurrogatesType*>(*it);
        if (sampleData == 0)  {
            // this is a normal sample without surrogate information.
            // we simply discard it
            std::cout<<"WARNING: ConditionalModelBuilder, sample data "<< (*it)->GetDatasetURI()<<" has no surrogate data associated, and is ignored"<<std::endl;
            continue;
        }

        VectorType surrogateData = sampleData->GetSurrogateVector();
        acceptSample = true;
        for (unsigned i=0 ; i<nbCategoricalSurrogatesInUse ; i++) { //check that this sample respect the requested categories
            if ( conditioningInfo[indicesCategoricalSurrogatesInUse[i]].second !=
                    surrogateData[indicesCategoricalSurrogatesInUse[i]] ) {
                //if one of the categories does not fit the requested one, then the sample is discarded
                acceptSample = false;
                continue;
            }
        }

        if (acceptSample) { //if the sample is of the right category
            acceptedSamples->push_back(*it);
            //and fill in the matrix of continuous variables
            for (unsigned j=0 ; j<nbContinuousSurrogatesInUse ; j++) {
                (*surrogateMatrix)(j,nbAcceptedSamples) = surrogateData[indicesContinuousSurrogatesInUse[j]];
            }
            nbAcceptedSamples++;
        }
    }
    //resize the matrix of surrogate data to the effective number of accepted samples
    surrogateMatrix->conservativeResize(Eigen::NoChange_t(), nbAcceptedSamples);

    return nbAcceptedSamples;
}

template <typename T>
typename ConditionalModelBuilder<T>::StatisticalModelType*
ConditionalModelBuilder<T>::BuildNewModel(const DataItemListType& sampleDataList,
        const SurrogateTypeInfoType& surrogateTypesInfo,
        const CondVariableValueVectorType& conditioningInfo,
        float noiseVariance,
        double modelVarianceRetained) const {
    DataItemListType acceptedSamples;
    MatrixType X;
    VectorType x0;
    unsigned nSamples = PrepareData(sampleDataList, surrogateTypesInfo, conditioningInfo, &acceptedSamples, &X, &x0);
    assert(nSamples == acceptedSamples.size());

    unsigned nCondVariables = X.rows();

    // build a normal PCA model
    typedef PCAModelBuilder<T> PCAModelBuilderType;
    PCAModelBuilderType* modelBuilder = PCAModelBuilderType::Create();
    StatisticalModelType* pcaModel = modelBuilder->BuildNewModel(acceptedSamples, noiseVariance);

    unsigned nPCAComponents = pcaModel->GetNumberOfPrincipalComponents();

    if ( X.cols() == 0 || X.rows() == 0) {
        return pcaModel;
    } else {
        // the scores in the pca model correspond to the parameters of each sample in the model.
        MatrixType B = pcaModel->GetModelInfo().GetScoresMatrix().transpose();
        assert(B.rows() == nSamples);
        assert(B.cols() == nPCAComponents);

        // A is the joint data matrix B, X, where X contains the conditional information for each sample
        // Thus the i-th row of A contains the PCA parameters b of the i-th sample,
        // together with the conditional information for each sample
        MatrixType A(nSamples, nPCAComponents+nCondVariables);
        A << B,X.transpose();

        // Compute the mean and the covariance of the joint data matrix
        VectorType mu = A.colwise().mean().transpose(); // colwise returns a row vector
        assert(mu.rows() == nPCAComponents + nCondVariables);

        MatrixType A0 = A.rowwise() - mu.transpose(); //
        MatrixType cov = 1.0 / (nSamples-1) * A0.transpose() *  A0;

        assert(cov.rows() == cov.cols());
        assert(cov.rows() == pcaModel->GetNumberOfPrincipalComponents() + nCondVariables);

        // extract the submatrices involving the conditionals x
        // note that since the matrix is symmetric, Sbx = Sxb.transpose(), hence we only store one
        MatrixType Sbx = cov.topRightCorner(nPCAComponents, nCondVariables);
        MatrixType Sxx = cov.bottomRightCorner(nCondVariables, nCondVariables);
        MatrixType Sbb = cov.topLeftCorner(nPCAComponents, nPCAComponents);

        // compute the conditional mean
        VectorType condMean = mu.topRows(nPCAComponents) + Sbx * Sxx.inverse() * (x0 - mu.bottomRows(nCondVariables));

        // compute the conditional covariance
        MatrixType condCov = Sbb - Sbx * Sxx.inverse() * Sbx.transpose();

        // get the sample mean corresponding the the conditional given mean of the parameter vectors
        VectorType condMeanSample = pcaModel->GetRepresenter()->SampleToSampleVector(pcaModel->DrawSample(condMean));

        // so far all the computation have been done in parameter (latent) space. Go back to sample space.
        // (see PartiallyFixedModelBuilder for a detailed documentation)
        // TODO we should factor this out into the base class, as it is the same code as it is used in
        // the partially fixed model builder
        const VectorType& pcaVariance = pcaModel->GetPCAVarianceVector();
        VectorTypeDoublePrecision pcaSdev = pcaVariance.cast<double>().array().sqrt();

        typedef Eigen::JacobiSVD<MatrixTypeDoublePrecision> SVDType;
        MatrixTypeDoublePrecision innerMatrix = pcaSdev.asDiagonal() * condCov.cast<double>() * pcaSdev.asDiagonal();
        SVDType svd(innerMatrix, Eigen::ComputeThinU);
        VectorType singularValues = svd.singularValues().cast<ScalarType>();

        // keep only the necessary number of modes, wrt modelVarianceRetained...
        double totalRemainingVariance = singularValues.sum(); //
        //and count the number of modes required for the model
        double cumulatedVariance = singularValues(0);
        unsigned numComponentsToReachPrescribedVariance = 1;
        while ( cumulatedVariance/totalRemainingVariance < modelVarianceRetained ) {
            numComponentsToReachPrescribedVariance++;
            if (numComponentsToReachPrescribedVariance==singularValues.size()) break;
            cumulatedVariance += singularValues(numComponentsToReachPrescribedVariance-1);
        }

        unsigned numComponentsToKeep = std::min<unsigned>( numComponentsToReachPrescribedVariance, singularValues.size() );

        VectorType newPCAVariance = singularValues.topRows(numComponentsToKeep);
        MatrixType newPCABasisMatrix = (pcaModel->GetOrthonormalPCABasisMatrix() * svd.matrixU().cast<ScalarType>()).topLeftCorner(X.cols(), numComponentsToKeep);

        StatisticalModelType* model = StatisticalModelType::Create(pcaModel->GetRepresenter(),  condMeanSample, newPCABasisMatrix, newPCAVariance, noiseVariance);

        // add builder info and data info to the info list
        MatrixType scores(0,0);
        BuilderInfo::ParameterInfoList bi;

        bi.push_back(BuilderInfo::KeyValuePair("NoiseVariance ", Utils::toString(noiseVariance)));

        //generate a matrix ; first column = boolean (yes/no, this variable is used) ; second: conditioning value.
        MatrixType conditioningInfoMatrix(conditioningInfo.size(), 2);
        for (unsigned i=0 ; i<conditioningInfo.size() ; i++) {
            conditioningInfoMatrix(i,0) = conditioningInfo[i].first;
            conditioningInfoMatrix(i,1) = conditioningInfo[i].second;
        }
        bi.push_back(BuilderInfo::KeyValuePair("ConditioningInfo ", Utils::toString(conditioningInfoMatrix)));

        typename BuilderInfo::DataInfoList di;

        unsigned i = 0;
        for (typename DataItemListType::const_iterator it = sampleDataList.begin();
                it != sampleDataList.end();
                ++it, i++) {
            const DataItemWithSurrogatesType* sampleData = dynamic_cast<const DataItemWithSurrogatesType*>(*it);
            std::ostringstream os;
            os << "URI_" << i;
            di.push_back(BuilderInfo::KeyValuePair(os.str().c_str(),sampleData->GetDatasetURI()));

            os << "_surrogates";
            di.push_back(BuilderInfo::KeyValuePair(os.str().c_str(),sampleData->GetSurrogateFilename()));
        }

        std::ostringstream os;
        os << "surrogates_types";
        di.push_back(BuilderInfo::KeyValuePair(os.str().c_str(),surrogateTypesInfo.typeFilename));

        BuilderInfo builderInfo("ConditionalModelBuilder", di, bi);

        ModelInfo::BuilderInfoList biList;
        biList.push_back(builderInfo);

        ModelInfo info(scores, biList);
        model->SetModelInfo(info);

        delete pcaModel;

        return model;
    }

}

} // namespace statismo

#endif

ext: hxx

max_stars_repo_name: tom-albrecht/statismo

max_issues_repo_name: tom-albrecht/statismo

max_forks_repo_name: tom-albrecht/statismo