<commit_before>#include <iostream>
#include "velocypack/vpack.h"
#include "velocypack/velocypack-exception-macros.h"

using namespace arangodb::velocypack;

// this is our handler for custom types
struct MyCustomTypeHandler : public CustomTypeHandler {
  // serialize a custom type into JSON
  static int const myMagicNumber = 42;

  std::string toString(Slice const& value, Options const*, Slice const&) override final {
    if (value.head() == 0xf0) {
      return std::to_string(myMagicNumber);
    }
    if (value.head() == 0xf4) {
      char const* start = value.startAs<char const>();
      // read string length
      uint8_t length = *(value.start() + 1);
      // append string (don't care about escaping here...)
      return std::string(start, length);
    }
    throw "unknown type!";
  }

  void dump(Slice const& value, Dumper* dumper, Slice const&) override final {
    Sink* sink = dumper->sink();

    if (value.head() == 0xf0) {
      sink->append(std::to_string(myMagicNumber));
      return;
    }
    if (value.head() == 0xf4) {
      char const* start = value.startAs<char const>();
      // read string length
      uint8_t length = *(value.start() + 1);
      // append string (don't care about escaping here...)
      sink->push_back('"');
      sink->append(start + 2, static_cast<ValueLength>(length));
      sink->push_back('"');
      return;
    }
    throw "unknown type!";
  }
};

int main(int, char* []) {
  VELOCYPACK_GLOBAL_EXCEPTION_TRY

  MyCustomTypeHandler handler;
  Options options;
  options.customTypeHandler = &handler;

  Builder b(&options);

  b(Value(ValueType::Object));

  uint8_t* p;
  // create an attribute "custom1" of type 0xf0 with bytesize 1
  // this type will be serialized into the value of 42
  p = b.add("custom1", ValuePair(2ULL, ValueType::Custom));
  *p = 0xf0;

  // create an attribute "custom2" of type 0xf1 with bytesize 8
  // this type will be contain a user-defined string type, with
  // one byte of string length information following the Slice's
  // head byte, and the string bytes are it.
  p = b.add("custom2", ValuePair(8ULL, ValueType::Custom));
  *p++ = 0xf4;
  // fill it with something useful...
  *p++ = static_cast<uint8_t>(6);  // length of following string
  *p++ = 'f';
  *p++ = 'o';
  *p++ = 'o';
  *p++ = 'b';
  *p++ = 'a';
  *p++ = 'r';

  // another 0xf1 value
  p = b.add("custom3", ValuePair(5ULL, ValueType::Custom));
  *p++ = 0xf4;
  *p++ = static_cast<uint8_t>(3);  // length of following string
  *p++ = 'q';
  *p++ = 'u';
  *p++ = 'x';

  b.close();

  Slice s = b.slice();

  // now print 'custom1':
  std::cout << "'custom1': byteSize: " << s.get("custom1").byteSize()
            << ", JSON: " << s.get("custom1").toJson() << std::endl;

  // and 'custom2':
  std::cout << "'custom2': byteSize: " << s.get("custom2").byteSize()
            << ", JSON: " << s.get("custom2").toJson() << std::endl;

  // and 'custom3':
  std::cout << "'custom3': byteSize: " << s.get("custom3").byteSize()
            << ", JSON: " << s.get("custom3").toJson() << std::endl;

  VELOCYPACK_GLOBAL_EXCEPTION_CATCH
}
<commit_msg>Make exampleCustom.cpp work<commit_after>#include <iostream>
#include "velocypack/vpack.h"
#include "velocypack/velocypack-exception-macros.h"

using namespace arangodb::velocypack;

// this is our handler for custom types
struct MyCustomTypeHandler : public CustomTypeHandler {
  // serialize a custom type into JSON
  static int const myMagicNumber = 42;

  std::string toString(Slice const& value, Options const*, Slice const&) override final {
    if (value.head() == 0xf0) {
      return std::to_string(myMagicNumber);
    }
    if (value.head() == 0xf4) {
      char const* start = value.startAs<char const>();
      // read string length
      uint8_t length = *(value.start() + 1);
      // append string (don't care about escaping here...)
      return std::string(start, length);
    }
    throw "unknown type!";
  }

  void dump(Slice const& value, Dumper* dumper, Slice const&) override final {
    Sink* sink = dumper->sink();

    if (value.head() == 0xf0) {
      sink->append(std::to_string(myMagicNumber));
      return;
    }
    if (value.head() == 0xf4) {
      char const* start = value.startAs<char const>();
      // read string length
      uint8_t length = *(value.start() + 1);
      // append string (don't care about escaping here...)
      sink->push_back('"');
      sink->append(start + 2, static_cast<ValueLength>(length));
      sink->push_back('"');
      return;
    }
    throw "unknown type!";
  }
};

int main(int, char* []) {
  VELOCYPACK_GLOBAL_EXCEPTION_TRY

  MyCustomTypeHandler handler;
  Options options;
  options.customTypeHandler = &handler;

  Builder b(&options);

  b(Value(ValueType::Object));

  uint8_t* p;
  // create an attribute "custom1" of type 0xf0 with bytesize 1
  // this type will be serialized into the value of 42
  p = b.add("custom1", ValuePair(2ULL, ValueType::Custom));
  *p = 0xf0;

  // create an attribute "custom2" of type 0xf1 with bytesize 8
  // this type will be contain a user-defined string type, with
  // one byte of string length information following the Slice's
  // head byte, and the string bytes are it.
  p = b.add("custom2", ValuePair(8ULL, ValueType::Custom));
  *p++ = 0xf4;
  // fill it with something useful...
  *p++ = static_cast<uint8_t>(6);  // length of following string
  *p++ = 'f';
  *p++ = 'o';
  *p++ = 'o';
  *p++ = 'b';
  *p++ = 'a';
  *p++ = 'r';

  // another 0xf1 value
  p = b.add("custom3", ValuePair(5ULL, ValueType::Custom));
  *p++ = 0xf4;
  *p++ = static_cast<uint8_t>(3);  // length of following string
  *p++ = 'q';
  *p++ = 'u';
  *p++ = 'x';

  b.close();

  Slice s = b.slice();

  // now print 'custom1':
  std::cout << "'custom1': byteSize: " << s.get("custom1").byteSize()
            << ", JSON: " << s.get("custom1").toJson(&options) << std::endl;

  // and 'custom2':
  std::cout << "'custom2': byteSize: " << s.get("custom2").byteSize()
            << ", JSON: " << s.get("custom2").toJson(&options) << std::endl;

  // and 'custom3':
  std::cout << "'custom3': byteSize: " << s.get("custom3").byteSize()
            << ", JSON: " << s.get("custom3").toJson(&options) << std::endl;

  VELOCYPACK_GLOBAL_EXCEPTION_CATCH
}
<|endoftext|>


<commit_before>#include "SDL.h"
#include "SDL_image.h"
#include <iostream>
#include <assert.h>
#include "shared/path_creator.hpp"
#include "shared/tdmap.hpp"
#include "shared/sizes.h"
#include <map>
#include <set>
#include <boost/foreach.hpp>
#include "graphics/graphics_path.hpp"

using namespace std;

class GUI
{

private:

  void logSDLError(std::ostream &os, const std::string &msg)
  {
    os << msg << " error: " << SDL_GetError() << std::endl;
  }

  std::map<std::string, SDL_Texture *> loaded_textures;
  std::string resPath;

  SDL_Texture* loadTexture(const std::string &file, SDL_Renderer *ren)
  {
    SDL_Texture *texture;

    if(loaded_textures.find(file) != loaded_textures.end())
    {
      texture = loaded_textures[file];
    }
    else
    {
      texture = IMG_LoadTexture(ren, (resPath + file).c_str());
      if (texture == nullptr)
      {
        logSDLError(std::cout, "LoadTexture");
      }
      loaded_textures[file] = texture;
    }
    return texture;
  }

    /**
  * Draw an SDL_Texture to an SDL_Renderer at position x, y, preserving
  * the texture's width and height
  * @param tex The source texture we want to draw
  * @param ren The renderer we want to draw to
  * @param x The x Coordinate to draw to
  * @param y The y Coordinate to draw to
  */
  void renderTexture(SDL_Texture *tex, SDL_Renderer *ren, int x, int y, int rw, int rh)
  {
    //Setup the destination rectangle to be at the position we want
    SDL_Rect dst;
    dst.x = x;
    dst.y = y;
    dst.w = rw;
    dst.h = rh;
    SDL_RenderCopy(ren, tex, NULL, &dst);
  }

  int row_width;
  int row_height;
  SDL_Renderer * ren;
  Path * main_path;
  int numrows;
  int numcols;

  Coordinate screen_to_game_coord(Coordinate c)
  {
    return Coordinate(c.x / row_width, c.y / row_height);
  }

  void re_render()
  {
    std::set<Coordinate> s( diff_coords.begin(), diff_coords.end() );
    diff_coords.assign( diff_coords.begin(), diff_coords.end() );

    BOOST_FOREACH(Coordinate &screen_cord, diff_coords)
    {

      Coordinate game_coord = screen_to_game_coord(screen_cord);

      renderTexture(background, ren, screen_cord.x, screen_cord.y, row_width, row_height);

      if(main_path->in(game_coord.x, game_coord.y))
      {
        renderTexture(tile, ren, screen_cord.x, screen_cord.y, row_width, row_height);
      }

      Tile& t = map->at(game_coord.x, game_coord.y);

      if(t.tower != nullptr)
      {
        SDL_Texture * texture = loadTexture(t.tower->get_image_string(), ren);
        if(texture != nullptr)
        {
          renderTexture(texture, ren, screen_cord.x, screen_cord.y, row_width, row_height);
        }
      }

    }
  }

  void fill_screen_tiles()
  {

    for(int i = 0; i < numrows; i++)
    {
      for(int j = 0; j < numcols; j++)
      {

        Coordinate screen_cord = game_to_screen_coord(Coordinate(i, j));

        renderTexture(background, ren, screen_cord.x, screen_cord.y, row_width, row_height);

        if(main_path->in(i, j))
        {
          renderTexture(tile, ren, screen_cord.x, screen_cord.y, row_width, row_height);
        }

        Tile& t = map->at(i, j);

        if(t.tower != nullptr)
        {
          SDL_Texture * texture = loadTexture(t.tower->get_image_string(), ren);

          Coordinate current_cord = game_to_screen_coord(Coordinate(i, j));

          if(texture != nullptr)
          {
            renderTexture(texture, ren, current_cord.x, current_cord.y, row_width, row_height);
          }
        }
      }
    }

  }

  TDMap * map;
  int current_anim_frame;
  SDL_Texture * tile;
  SDL_Texture * background;

  public:
    GUI(int rows, int columns, Path * path, TDMap * map)
    {

        assert(rows > 0 && columns > 0 && path != nullptr && map != nullptr);

        current_anim_frame = 0;
        row_width = DEFAULT_WIDTH/rows;
        row_height = DEFAULT_HEIGHT/columns;
        resPath = GRAPHICS_PATH;
        numrows = rows;
        numcols = columns;
        this->map = map;
        SDL_Window *win;
        main_path = path;

        if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
        {
          logSDLError(std::cout, "SDL_Init");
          exit(1);
        }

        win = SDL_CreateWindow("Tower Defense",
          SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, DEFAULT_WIDTH, DEFAULT_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI);

        if (win == nullptr)
        {
          logSDLError(std::cout, "CreateWindow");
          SDL_Quit();
          exit(1);

        }
        ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);

        if (ren == nullptr)
        {
          logSDLError(std::cout, "CreateRenderer");
          //TODO free window
          SDL_Quit();
          exit(1);
        }

        background = loadTexture("grass.png", ren);
        tile = loadTexture("tile.png", ren);

        if (background == nullptr || tile == nullptr)
        {
          logSDLError(std::cout, "Getting Images");
          //TODO cleanup
          SDL_Quit();
          exit(1);
        }

        fill_screen_tiles();
        SDL_RenderPresent(ren);
    }

    typedef std::pair<std::pair<SDL_Texture *, Coordinate> , std::pair<Coordinate, Coordinate>> anim_type;

    std::vector<anim_type> animations;

    std::vector<Coordinate> diff_coords;

    // takes pixel coords.
    // pls take care while using.
    void set_up_animation(SDL_Texture * texture, Coordinate from, Coordinate to, bool addToDiff)
    {
        animations.push_back(anim_type(std::make_pair(texture, from), std::make_pair(from, to)));
        diff_coords.push_back(from);
        diff_coords.push_back(to);
    }

    void clear_attack_animations()
    {
        animations.clear();
    }

    #define ANIMATION_CONSTANT 10

    bool show_animations()
    {
        re_render();
        BOOST_FOREACH(anim_type & animation, animations)
        {
            SDL_Texture * tex = animation.first.first;
            auto from_to = animation.second;
            int hdiff = from_to.second.x - from_to.first.x;
            int vdiff = from_to.second.y - from_to.first.y;
            hdiff = hdiff/ANIMATION_CONSTANT;
            vdiff = vdiff/ANIMATION_CONSTANT;
            animation.first.second.x += hdiff;
            animation.first.second.y += vdiff;
            renderTexture(tex, ren, animation.first.second.x, animation.first.second.y, row_width, row_height);
        }
        if(++current_anim_frame < ANIMATION_CONSTANT)
        {
          //SDL_Delay(1);
          return false;
        }
        return true;
    }

    void Update()
    {
      current_anim_frame = 0;
      for(int i = 0; i < NUM_ROWS; i++)
      {
        for(int j = 0; j < NUM_COLS; j++)
        {
          Tile& t = map->at(i, j);
          if(t.tower != nullptr)
          {
            Coordinate current_cord = game_to_screen_coord(Coordinate(i, j));
            SDL_Texture * attack_texture = loadTexture(t.tower->get_attack_image_string(), ren);
            BOOST_FOREACH(Coordinate c, t.tower->get_attack_tiles())
            {
              Coordinate screen_cord = game_to_screen_coord(c);
              set_up_animation(attack_texture, current_cord, screen_cord, true);
            }
          }
          BOOST_FOREACH(Sprite * s, t.sprites)
          {

            SDL_Texture * sprite_texture = loadTexture(s->image_string, ren);
            Coordinate previous_cord = game_to_screen_coord(s->get_previous_position());
            set_up_animation(sprite_texture, previous_cord, game_to_screen_coord(s->get_coordinate()), true);
          }
        }
      }
      while(!show_animations())
      {
        SDL_RenderPresent(ren);
        SDL_RenderPresent(ren);
      }
      re_render();
      SDL_RenderPresent(ren);
      clear_attack_animations();
    }

    Coordinate game_to_screen_coord(Coordinate game_coord)
    {
      return Coordinate(game_coord.x * row_width, game_coord.y * row_height);
    }

    Coordinate game_to_screen_coord(int x, int y)
    {
      return game_to_screen_coord(Coordinate(x, y));
    }
};
<commit_msg>too fast<commit_after>#include "SDL.h"
#include "SDL_image.h"
#include <iostream>
#include <assert.h>
#include "shared/path_creator.hpp"
#include "shared/tdmap.hpp"
#include "shared/sizes.h"
#include <map>
#include <set>
#include <boost/foreach.hpp>
#include "graphics/graphics_path.hpp"

using namespace std;

class GUI
{

private:

  void logSDLError(std::ostream &os, const std::string &msg)
  {
    os << msg << " error: " << SDL_GetError() << std::endl;
  }

  std::map<std::string, SDL_Texture *> loaded_textures;
  std::string resPath;

  SDL_Texture* loadTexture(const std::string &file, SDL_Renderer *ren)
  {
    SDL_Texture *texture;

    if(loaded_textures.find(file) != loaded_textures.end())
    {
      texture = loaded_textures[file];
    }
    else
    {
      texture = IMG_LoadTexture(ren, (resPath + file).c_str());
      if (texture == nullptr)
      {
        logSDLError(std::cout, "LoadTexture");
      }
      loaded_textures[file] = texture;
    }
    return texture;
  }

    /**
  * Draw an SDL_Texture to an SDL_Renderer at position x, y, preserving
  * the texture's width and height
  * @param tex The source texture we want to draw
  * @param ren The renderer we want to draw to
  * @param x The x Coordinate to draw to
  * @param y The y Coordinate to draw to
  */
  void renderTexture(SDL_Texture *tex, SDL_Renderer *ren, int x, int y, int rw, int rh)
  {
    //Setup the destination rectangle to be at the position we want
    SDL_Rect dst;
    dst.x = x;
    dst.y = y;
    dst.w = rw;
    dst.h = rh;
    SDL_RenderCopy(ren, tex, NULL, &dst);
  }

  int row_width;
  int row_height;
  SDL_Renderer * ren;
  Path * main_path;
  int numrows;
  int numcols;

  Coordinate screen_to_game_coord(Coordinate c)
  {
    return Coordinate(c.x / row_width, c.y / row_height);
  }

  void re_render()
  {
    std::set<Coordinate> s( diff_coords.begin(), diff_coords.end() );
    diff_coords.assign( diff_coords.begin(), diff_coords.end() );

    BOOST_FOREACH(Coordinate &screen_cord, diff_coords)
    {

      Coordinate game_coord = screen_to_game_coord(screen_cord);

      renderTexture(background, ren, screen_cord.x, screen_cord.y, row_width, row_height);

      if(main_path->in(game_coord.x, game_coord.y))
      {
        renderTexture(tile, ren, screen_cord.x, screen_cord.y, row_width, row_height);
      }

      Tile& t = map->at(game_coord.x, game_coord.y);

      if(t.tower != nullptr)
      {
        SDL_Texture * texture = loadTexture(t.tower->get_image_string(), ren);
        if(texture != nullptr)
        {
          renderTexture(texture, ren, screen_cord.x, screen_cord.y, row_width, row_height);
        }
      }

    }
  }

  void fill_screen_tiles()
  {

    for(int i = 0; i < numrows; i++)
    {
      for(int j = 0; j < numcols; j++)
      {

        Coordinate screen_cord = game_to_screen_coord(Coordinate(i, j));

        renderTexture(background, ren, screen_cord.x, screen_cord.y, row_width, row_height);

        if(main_path->in(i, j))
        {
          renderTexture(tile, ren, screen_cord.x, screen_cord.y, row_width, row_height);
        }

        Tile& t = map->at(i, j);

        if(t.tower != nullptr)
        {
          SDL_Texture * texture = loadTexture(t.tower->get_image_string(), ren);

          Coordinate current_cord = game_to_screen_coord(Coordinate(i, j));

          if(texture != nullptr)
          {
            renderTexture(texture, ren, current_cord.x, current_cord.y, row_width, row_height);
          }
        }
      }
    }

  }

  TDMap * map;
  int current_anim_frame;
  SDL_Texture * tile;
  SDL_Texture * background;

  public:
    GUI(int rows, int columns, Path * path, TDMap * map)
    {

        assert(rows > 0 && columns > 0 && path != nullptr && map != nullptr);

        current_anim_frame = 0;
        row_width = DEFAULT_WIDTH/rows;
        row_height = DEFAULT_HEIGHT/columns;
        resPath = GRAPHICS_PATH;
        numrows = rows;
        numcols = columns;
        this->map = map;
        SDL_Window *win;
        main_path = path;

        if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
        {
          logSDLError(std::cout, "SDL_Init");
          exit(1);
        }

        win = SDL_CreateWindow("Tower Defense",
          SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, DEFAULT_WIDTH, DEFAULT_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI);

        if (win == nullptr)
        {
          logSDLError(std::cout, "CreateWindow");
          SDL_Quit();
          exit(1);

        }
        ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);

        if (ren == nullptr)
        {
          logSDLError(std::cout, "CreateRenderer");
          //TODO free window
          SDL_Quit();
          exit(1);
        }

        background = loadTexture("grass.png", ren);
        tile = loadTexture("tile.png", ren);

        if (background == nullptr || tile == nullptr)
        {
          logSDLError(std::cout, "Getting Images");
          //TODO cleanup
          SDL_Quit();
          exit(1);
        }

        fill_screen_tiles();
        SDL_RenderPresent(ren);
    }

    typedef std::pair<std::pair<SDL_Texture *, Coordinate> , std::pair<Coordinate, Coordinate>> anim_type;

    std::vector<anim_type> animations;

    std::vector<Coordinate> diff_coords;

    // takes pixel coords.
    // pls take care while using.
    void set_up_animation(SDL_Texture * texture, Coordinate from, Coordinate to, bool addToDiff)
    {
        animations.push_back(anim_type(std::make_pair(texture, from), std::make_pair(from, to)));
        diff_coords.push_back(from);
        diff_coords.push_back(to);
    }

    void clear_attack_animations()
    {
        animations.clear();
    }

    #define ANIMATION_CONSTANT 10

    bool show_animations()
    {
        re_render();
        BOOST_FOREACH(anim_type & animation, animations)
        {
            SDL_Texture * tex = animation.first.first;
            auto from_to = animation.second;
            int hdiff = from_to.second.x - from_to.first.x;
            int vdiff = from_to.second.y - from_to.first.y;
            hdiff = hdiff/ANIMATION_CONSTANT;
            vdiff = vdiff/ANIMATION_CONSTANT;
            animation.first.second.x += hdiff;
            animation.first.second.y += vdiff;
            renderTexture(tex, ren, animation.first.second.x, animation.first.second.y, row_width, row_height);
        }
        if(++current_anim_frame < ANIMATION_CONSTANT)
        {
          //SDL_Delay(1);
          return false;
        }
        return true;
    }

    void Update()
    {
      current_anim_frame = 0;
      for(int i = 0; i < NUM_ROWS; i++)
      {
        for(int j = 0; j < NUM_COLS; j++)
        {
          Tile& t = map->at(i, j);
          if(t.tower != nullptr)
          {
            Coordinate current_cord = game_to_screen_coord(Coordinate(i, j));
            SDL_Texture * attack_texture = loadTexture(t.tower->get_attack_image_string(), ren);
            BOOST_FOREACH(Coordinate c, t.tower->get_attack_tiles())
            {
              Coordinate screen_cord = game_to_screen_coord(c);
              set_up_animation(attack_texture, current_cord, screen_cord, true);
            }
          }
          BOOST_FOREACH(Sprite * s, t.sprites)
          {

            SDL_Texture * sprite_texture = loadTexture(s->image_string, ren);
            Coordinate previous_cord = game_to_screen_coord(s->get_previous_position());
            set_up_animation(sprite_texture, previous_cord, game_to_screen_coord(s->get_coordinate()), true);
          }
        }
      }
      while(!show_animations())
      {
        SDL_RenderPresent(ren);
      }
      re_render();
      SDL_RenderPresent(ren);
      clear_attack_animations();
    }

    Coordinate game_to_screen_coord(Coordinate game_coord)
    {
      return Coordinate(game_coord.x * row_width, game_coord.y * row_height);
    }

    Coordinate game_to_screen_coord(int x, int y)
    {
      return game_to_screen_coord(Coordinate(x, y));
    }
};
<|endoftext|>


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

/*
 * Simple ranger example, using VL53L0X Time-of-flight range sensor I2C device.
 * This program uses FastArduino VL53L0X support API.
 * It first asks user to input (through USB console) various VL53L0X settings,
 * then it uses these settings to start continuous ranging and display distance
 * measurements conitnuously (until reset).
 *
 * Wiring:
 * - on ATmega328P based boards (including Arduino UNO):
 *   - A4 (PC4, SDA): connected to VL53L0X SDA pin
 *   - A5 (PC5, SCL): connected to VL53L0X SCL pin
 *   - direct USB access
 */

#include <fastarduino/time.h>
#include <fastarduino/uart.h>
#include <fastarduino/i2c_handler.h>
#include <fastarduino/devices/vl53l0x.h>

// #define FORCE_SYNC

static constexpr const i2c::I2CMode MODE = i2c::I2CMode::FAST;

static constexpr const board::USART UART = board::USART::USART0;
static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 128;
static char output_buffer[OUTPUT_BUFFER_SIZE];
static constexpr const uint8_t INPUT_BUFFER_SIZE = 32;
static char input_buffer[INPUT_BUFFER_SIZE];

REGISTER_UART_ISR(0)

#if I2C_TRUE_ASYNC and not defined(FORCE_SYNC)
using MANAGER = i2c::I2CAsyncManager<MODE, i2c::I2CErrorPolicy::CLEAR_ALL_COMMANDS>;
static constexpr const uint8_t I2C_BUFFER_SIZE = 32;
static MANAGER::I2CCOMMAND i2c_buffer[I2C_BUFFER_SIZE];
REGISTER_I2C_ISR(MANAGER)
#else
using MANAGER = i2c::I2CSyncManager<MODE>;
#endif

using streams::dec;
using streams::hex;
using streams::fixed;
using streams::endl;
using streams::flush;

using namespace devices::vl53l0x;
using TOF = VL53L0X<MANAGER>;

#define CHECK_OK(STATEMENT) if (! STATEMENT) out << F(#STATEMENT) << F(" ERROR!") << endl

static void display_status(streams::ostream& out, TOF& tof)
{
	DeviceStatus status;
	bool ok = tof.get_range_status(status);
	out << F("tof.get_range_status(status) = ") << ok
		<< F(", error = ") << dec << status.error()
		<< F(", data_ready = ") << status.data_ready() << endl;
}

static bool yes_no(streams::ostream& out, streams::istream& in, const flash::FlashStorage* label)
{
	while (true)
	{
		out << label << flush;
		char answer = 0;
		in >> answer;
		switch (answer)
		{
			case 'y':
			case 'Y':
			out << endl;
			return true;

			case 'n':
			case 'N':
			out << endl;
			return false;

			default:
			out << F("Only Y or N are allowed!") << endl;
		}
	}
}

static constexpr uint8_t PRE_RANGE_VCSEL_VALUES[] = {12, 14, 16, 18};
static constexpr uint8_t PRE_RANGE_VCSEL_COUNT = sizeof(PRE_RANGE_VCSEL_VALUES);
static constexpr uint8_t FINAL_RANGE_VCSEL_VALUES[] = {8, 10, 12, 14};
static constexpr uint8_t FINAL_RANGE_VCSEL_COUNT = sizeof(FINAL_RANGE_VCSEL_VALUES);

static uint8_t vcsel_period(streams::ostream& out, streams::istream& in, const flash::FlashStorage* label,
	uint8_t current, const uint8_t* values, uint8_t count)
{
	while (true)
	{
		out << label << F("(");
		for (uint8_t i = 0; i < count; ++i)
			out << values[i] << ", ";
		out << F("current = ") << current << F("): ") << flush;
		uint16_t answer = 0;
		in >> answer;
		for (uint8_t i = 0; i < count; ++i)
			if (answer == values[i])
			{
				out << endl;
				return answer;
			}
		out << F("Unauthorized value entered!") << endl;
	}
}

static float signal_rate(streams::ostream& out, streams::istream& in, float current)
{
	while (true)
	{
		out << F("Signal rate (float in ]0;1], current = ") << current << F("): ") << flush;
		double answer = 0;
		in >> answer;
		if (answer > 0.0 && answer <= 1.0)
		{
			out << endl;
			return answer;
		}
		out << F("Only floats in ]0;1] are allowed!") << endl;
	}
}

static uint32_t timing_budget(streams::ostream& out, streams::istream& in, uint32_t current)
{
	while (true)
	{
		out << F("Measurement timing budget in us (current = ") << current << F("us): ") << flush;
		uint32_t budget = 0;
		in >> budget;
		if (budget > 0)
		{
			out << endl;
			return budget;
		}
		out << F("Only positive numbers are allowed!") << endl;
	}
}

int main() __attribute__((OS_main));
int main()
{
	board::init();
	sei();

	// open UART for traces
	serial::hard::UART<UART> uart{input_buffer, output_buffer};
	streams::ostream out = uart.out();
	streams::istream in = uart.in();
	uart.begin(115200);
	out << streams::boolalpha;

	// Initialize I2C async handler
#if I2C_TRUE_ASYNC and not defined(FORCE_SYNC)
	MANAGER manager{i2c_buffer};
#else
	MANAGER manager;
#endif

	out << F("Instantiate VL53L0X") << endl;
	TOF tof{manager};

	out << F("Start I2C manager") << endl;
	manager.begin();

	out << F("Define VL53L0X parameters...\n") << endl;

	// Define steps for init_static_second()
	SequenceSteps steps = SequenceSteps::create();
	out << F("Sequence steps:") << endl;
	if (yes_no(out, in, F("  TCC (Y/N): "))) steps = steps.tcc();
	if (yes_no(out, in, F("  DSS (Y/N): "))) steps = steps.dss();
	if (yes_no(out, in, F("  MSRC (Y/N): "))) steps = steps.msrc();
	if (yes_no(out, in, F("  PRE-RANGE (Y/N): "))) steps = steps.pre_range();
	if (yes_no(out, in, F("  FINAL-RANGE (Y/N): "))) steps = steps.final_range();

	// Initialize VL53L0X chip
	out << F("Initialize VL53L0X chip...\n") << endl;
	CHECK_OK(tof.init_data_first());
	CHECK_OK(tof.init_static_second(GPIOSettings::sample_ready(), steps));
	CHECK_OK(tof.perform_ref_calibration());

	// set_vcsel_pulse_period PRE-RANGE/FINAL-RANGE
	out << F("VCSEL pulse period:") << endl;
	uint8_t current_period = 0;
	CHECK_OK(tof.get_vcsel_pulse_period<VcselPeriodType::PRE_RANGE>(current_period));
	uint8_t period = vcsel_period(
		out, in, F("  PRE-RANGE "), current_period, PRE_RANGE_VCSEL_VALUES, PRE_RANGE_VCSEL_COUNT);
	CHECK_OK(tof.set_vcsel_pulse_period<VcselPeriodType::PRE_RANGE>(period));
	current_period = 0;
	CHECK_OK(tof.get_vcsel_pulse_period<VcselPeriodType::FINAL_RANGE>(current_period));
	period = vcsel_period(
		out, in, F("  FINAL-RANGE "), current_period, FINAL_RANGE_VCSEL_VALUES, FINAL_RANGE_VCSEL_COUNT);
	CHECK_OK(tof.set_vcsel_pulse_period<VcselPeriodType::FINAL_RANGE>(period));

	float rate = 0.0;
	CHECK_OK(tof.get_signal_rate_limit(rate));
	rate = signal_rate(out, in, rate);
	CHECK_OK(tof.set_signal_rate_limit(rate));

	uint32_t budget = 0;
	CHECK_OK(tof.get_measurement_timing_budget(budget));
	budget = timing_budget(out, in, budget);
	CHECK_OK(tof.set_measurement_timing_budget(budget));

	display_status(out, tof);

	// Perform reference calibration
	CHECK_OK(tof.perform_ref_calibration());

	display_status(out, tof);

	// Start continuous ranging
	CHECK_OK(tof.start_continuous_ranging(1000U));

	while (true)
	{
		time::delay_ms(995U);
		// Read continuous ranges now
		uint16_t range = 0;
		if (tof.await_continuous_range(range))
			out << F("Range = ") << dec << range << F("mm") << endl;
		display_status(out, tof);
	}
}
<commit_msg>Display all settings in VL53L0X example<commit_after>//   Copyright 2016-2020 Jean-Francois Poilpret
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

/*
 * Simple ranger example, using VL53L0X Time-of-flight range sensor I2C device.
 * This program uses FastArduino VL53L0X support API.
 * It first asks user to input (through USB console) various VL53L0X settings,
 * then it uses these settings to start continuous ranging and display distance
 * measurements conitnuously (until reset).
 *
 * Wiring:
 * - on ATmega328P based boards (including Arduino UNO):
 *   - A4 (PC4, SDA): connected to VL53L0X SDA pin
 *   - A5 (PC5, SCL): connected to VL53L0X SCL pin
 *   - direct USB access
 */

#include <fastarduino/time.h>
#include <fastarduino/uart.h>
#include <fastarduino/i2c_handler.h>
#include <fastarduino/devices/vl53l0x.h>

// #define FORCE_SYNC

static constexpr const i2c::I2CMode MODE = i2c::I2CMode::FAST;

static constexpr const board::USART UART = board::USART::USART0;
static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 128;
static char output_buffer[OUTPUT_BUFFER_SIZE];
static constexpr const uint8_t INPUT_BUFFER_SIZE = 32;
static char input_buffer[INPUT_BUFFER_SIZE];

REGISTER_UART_ISR(0)

#if I2C_TRUE_ASYNC and not defined(FORCE_SYNC)
using MANAGER = i2c::I2CAsyncManager<MODE, i2c::I2CErrorPolicy::CLEAR_ALL_COMMANDS>;
static constexpr const uint8_t I2C_BUFFER_SIZE = 32;
static MANAGER::I2CCOMMAND i2c_buffer[I2C_BUFFER_SIZE];
REGISTER_I2C_ISR(MANAGER)
#else
using MANAGER = i2c::I2CSyncManager<MODE>;
#endif

using streams::dec;
using streams::hex;
using streams::fixed;
using streams::endl;
using streams::flush;

using namespace devices::vl53l0x;
using TOF = VL53L0X<MANAGER>;

#define CHECK_OK(STATEMENT) if (! STATEMENT) out << F(#STATEMENT) << F(" ERROR!") << endl

static void display_status(streams::ostream& out, TOF& tof)
{
	DeviceStatus status;
	bool ok = tof.get_range_status(status);
	out << F("tof.get_range_status(status) = ") << ok
		<< F(", error = ") << dec << status.error()
		<< F(", data_ready = ") << status.data_ready() << endl;
}

static bool yes_no(streams::ostream& out, streams::istream& in, const flash::FlashStorage* label)
{
	while (true)
	{
		out << label << flush;
		char answer = 0;
		in >> answer;
		switch (answer)
		{
			case 'y':
			case 'Y':
			out << endl;
			return true;

			case 'n':
			case 'N':
			out << endl;
			return false;

			default:
			out << F("Only Y or N are allowed!") << endl;
		}
	}
}

static constexpr uint8_t PRE_RANGE_VCSEL_VALUES[] = {12, 14, 16, 18};
static constexpr uint8_t PRE_RANGE_VCSEL_COUNT = sizeof(PRE_RANGE_VCSEL_VALUES);
static constexpr uint8_t FINAL_RANGE_VCSEL_VALUES[] = {8, 10, 12, 14};
static constexpr uint8_t FINAL_RANGE_VCSEL_COUNT = sizeof(FINAL_RANGE_VCSEL_VALUES);

static uint8_t vcsel_period(streams::ostream& out, streams::istream& in, const flash::FlashStorage* label,
	uint8_t current, const uint8_t* values, uint8_t count)
{
	while (true)
	{
		out << label << F("(");
		for (uint8_t i = 0; i < count; ++i)
			out << values[i] << ", ";
		out << F("current = ") << current << F("): ") << flush;
		uint16_t answer = 0;
		in >> answer;
		for (uint8_t i = 0; i < count; ++i)
			if (answer == values[i])
			{
				out << endl;
				return answer;
			}
		out << F("Unauthorized value entered!") << endl;
	}
}

static float signal_rate(streams::ostream& out, streams::istream& in, float current)
{
	while (true)
	{
		out << F("Signal rate (float in ]0;1], current = ") << current << F("): ") << flush;
		double answer = 0;
		in >> answer;
		if (answer > 0.0 && answer <= 1.0)
		{
			out << endl;
			return answer;
		}
		out << F("Only floats in ]0;1] are allowed!") << endl;
	}
}

static uint32_t timing_budget(streams::ostream& out, streams::istream& in, uint32_t current)
{
	while (true)
	{
		out << F("Measurement timing budget in us (current = ") << current << F("us): ") << flush;
		uint32_t budget = 0;
		in >> budget;
		if (budget > 0)
		{
			out << endl;
			return budget;
		}
		out << F("Only positive numbers are allowed!") << endl;
	}
}

int main() __attribute__((OS_main));
int main()
{
	board::init();
	sei();

	// open UART for traces
	serial::hard::UART<UART> uart{input_buffer, output_buffer};
	streams::ostream out = uart.out();
	streams::istream in = uart.in();
	uart.begin(115200);
	out << streams::boolalpha;

	// Initialize I2C async handler
#if I2C_TRUE_ASYNC and not defined(FORCE_SYNC)
	MANAGER manager{i2c_buffer};
#else
	MANAGER manager;
#endif

	out << F("Instantiate VL53L0X") << endl;
	TOF tof{manager};

	out << F("Start I2C manager") << endl;
	manager.begin();

	out << F("Define VL53L0X parameters...\n") << endl;

	// Define steps for init_static_second()
	SequenceSteps steps = SequenceSteps::create();
	out << F("Sequence steps:") << endl;
	if (yes_no(out, in, F("  TCC (Y/N): "))) steps = steps.tcc();
	if (yes_no(out, in, F("  DSS (Y/N): "))) steps = steps.dss();
	if (yes_no(out, in, F("  MSRC (Y/N): "))) steps = steps.msrc();
	if (yes_no(out, in, F("  PRE-RANGE (Y/N): "))) steps = steps.pre_range();
	if (yes_no(out, in, F("  FINAL-RANGE (Y/N): "))) steps = steps.final_range();

	// Initialize VL53L0X chip
	out << F("Initialize VL53L0X chip...\n") << endl;
	CHECK_OK(tof.init_data_first());
	CHECK_OK(tof.init_static_second(GPIOSettings::sample_ready(), steps));
	CHECK_OK(tof.perform_ref_calibration());

	// set_vcsel_pulse_period PRE-RANGE/FINAL-RANGE
	out << F("VCSEL pulse period:") << endl;
	uint8_t current_period = 0;
	CHECK_OK(tof.get_vcsel_pulse_period<VcselPeriodType::PRE_RANGE>(current_period));
	uint8_t period = vcsel_period(
		out, in, F("  PRE-RANGE "), current_period, PRE_RANGE_VCSEL_VALUES, PRE_RANGE_VCSEL_COUNT);
	CHECK_OK(tof.set_vcsel_pulse_period<VcselPeriodType::PRE_RANGE>(period));
	current_period = 0;
	CHECK_OK(tof.get_vcsel_pulse_period<VcselPeriodType::FINAL_RANGE>(current_period));
	period = vcsel_period(
		out, in, F("  FINAL-RANGE "), current_period, FINAL_RANGE_VCSEL_VALUES, FINAL_RANGE_VCSEL_COUNT);
	CHECK_OK(tof.set_vcsel_pulse_period<VcselPeriodType::FINAL_RANGE>(period));

	float rate = 0.0;
	CHECK_OK(tof.get_signal_rate_limit(rate));
	rate = signal_rate(out, in, rate);
	CHECK_OK(tof.set_signal_rate_limit(rate));

	uint32_t budget = 0;
	CHECK_OK(tof.get_measurement_timing_budget(budget));
	budget = timing_budget(out, in, budget);
	CHECK_OK(tof.set_measurement_timing_budget(budget));

	display_status(out, tof);

	// Perform reference calibration
	//TODO is that really useful?
	// CHECK_OK(tof.perform_ref_calibration());

	display_status(out, tof);

	// Feedback on all settings
	out << F("Final settings") << endl;
	out << F("Steps = ") << steps << endl;
	CHECK_OK(tof.get_vcsel_pulse_period<VcselPeriodType::PRE_RANGE>(current_period));
	out << F("VCSEL PRE-RANGE pulse period = ") << current_period << endl;
	CHECK_OK(tof.get_vcsel_pulse_period<VcselPeriodType::FINAL_RANGE>(current_period));
	out << F("VCSEL FINAL-RANGE pulse period = ") << current_period << endl;
	CHECK_OK(tof.get_signal_rate_limit(rate));
	out << F("Signal rate limit = ") << rate << endl;
	CHECK_OK(tof.get_measurement_timing_budget(budget));
	out << F("Measurement timing budget = ") << budget << F("us") << endl;
	SequenceStepsTimeout timeouts;
	CHECK_OK(tof.get_sequence_steps_timeout(timeouts));
	out << F("Timeouts for each step = ") << timeouts << endl;

	// Start continuous ranging
	CHECK_OK(tof.start_continuous_ranging(1000U));

	while (true)
	{
		time::delay_ms(995U);
		// Read continuous ranges now
		uint16_t range = 0;
		if (tof.await_continuous_range(range))
			out << F("Range = ") << dec << range << F("mm") << endl;
		display_status(out, tof);
	}
}
<|endoftext|>


<commit_before>
// Copyright (c) 2014 Quanta Research Cambridge, Inc.

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

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

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

#include <MmRequestProxy.h>
#include <MmIndicationWrapper.h>
#include <MmDebugIndicationWrapper.h>
#include <MmDebugRequestProxy.h>
#include <DmaConfigProxy.h>
#include <GeneratedTypes.h>
//#include <DmaIndicationWrapper.h>
#include <StdDmaIndication.h>
#include <stdio.h>
#include <sys/mman.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
#include <pthread.h>
#include <errno.h>
#include <math.h> // frexp(), fabs()
#include <assert.h>
#include "portalmat.h"
#include "mnist.h"

static int verbose = 0;

class SigmoidIndication;
class MmIndication;
class MmDebugIndication;

RbmRequestProxy *rbmdevice = 0;
MmRequestProxy *mmdevice = 0;
MmDebugRequestProxy *mmdebug = 0;
SigmoidIndication *sigmoidindication = 0;
SigmoidRequestProxy *sigmoiddevice = 0;
TimerRequestProxy *timerdevice = 0;
MmIndication *mmdeviceIndication = 0;
MmDebugIndication *mmDebugIndication = 0;
TimerIndication *timerdeviceIndication = 0;
DmaConfigProxy *dma = 0;
DmaIndicationWrapper *dmaIndication = 0;

long dotprod = 0;

void dump(const char *prefix, char *buf, size_t len)
{
    fprintf(stderr, "%s ", prefix);
    for (int i = 0; i < (len > 64 ? 64 : len) ; i++) {
	fprintf(stderr, "%02x", (unsigned char)buf[i]);
	if (i % 4 == 3)
	  fprintf(stderr, " ");
    }
    fprintf(stderr, "\n");
}

void *dbgThread(void *)
{
  while (1) {
    sleep(2);
    if (dma) {
      dma->getStateDbg(ChannelType_Read);
    }
    if (mmdebug) {
      fprintf(stderr, "Calling mmdebug->debug()\n");
      mmdebug->debug();
    }
  }
  return 0;
}

int main(int argc, const char **argv)
{
  unsigned int srcGen = 0;

  fprintf(stderr, "%s %s\n", __DATE__, __TIME__);
  mmdevice = new MmRequestProxy(IfcNames_MmRequestPortal);
  mmdebug = new MmDebugRequestProxy(IfcNames_MmDebugRequestPortal);
  mmdeviceIndication = new MmIndication(IfcNames_MmIndicationPortal);
  mmDebugIndication = new MmDebugIndication(IfcNames_MmDebugIndicationPortal);
  timerdevice = new TimerRequestProxy(IfcNames_TimerRequestPortal);
  timerdeviceIndication = new TimerIndication(IfcNames_TimerIndicationPortal);

  dma = new DmaConfigProxy(IfcNames_DmaConfigPortal);
  dmaIndication = new DmaIndication(dma, IfcNames_DmaIndicationPortal);

  if(sem_init(&mul_sem, 1, 0)){
    fprintf(stderr, "failed to init mul_sem\n");
    return -1;
  }

  pthread_t tid;
  fprintf(stderr, "creating exec thread\n");
  if(pthread_create(&tid, NULL,  portalExec, NULL)){
   fprintf(stderr, "error creating exec thread\n");
   exit(1);
  }

  pthread_t dbgtid;
  fprintf(stderr, "creating debug thread\n");
  if(pthread_create(&dbgtid, NULL,  dbgThread, NULL)){
   fprintf(stderr, "error creating debug thread\n");
   exit(1);
  }

  matAllocator = new PortalMatAllocator(dma);

#define LARGE_MAT
#ifdef LARGE_MAT
  int A = 32;
  int B = 16;
  if (argc > 1) {
    B = strtoul(argv[1], 0, 0);
    A = 2*B;
  }
  cv::Mat m1(A,B,CV_32F);
  cv::Mat m2(B,A,CV_32F);
  int v = 0;
  for(int a = 0; a < A; a++){
    for(int b = 0; b < B; b++){
      m2.at<float>(b,a) = v+(A*B);;
      m1.at<float>(a,b) = v++;
    }
  }
#else
  cv::Mat m1 = (cv::Mat_<float>(4,8) <<
		11,12,13,14,15,16,17,18,
		21,22,23,24,25,26,27,28,
		31,32,33,34,35,36,37,38,
		41,42,43,44,45,46,47,48
		);
  cv::Mat m2 = (cv::Mat_<float>(8,4) <<
		51,62,53,54,
		55,56,57,58,
		61,62,63,64,
		65,66,67,68,
		71,72,73,74,
		75,76,77,78,
		81,82,83,84,
		85,86,87,88
		);
#endif
  cv::Mat  m3 = m1 * m2;
  //dumpMatF<int>("m1", "%08x", m1, stdout);
  //dumpMatF<int>("m2", "%08x", m2, stdout);
  fflush(stdout);
  PortalMat pm1(m1);
  PortalMat pm2t(m2.t());
  PortalMat pm3;
  start_timer(0);
  pm3.multf(pm1, pm2t, mmdeviceIndication);
  uint64_t hw_cycles = lap_timer(0);
  uint64_t read_beats = dma->show_mem_stats(ChannelType_Read);
  uint64_t write_beats = dma->show_mem_stats(ChannelType_Write);
  float read_util = (float)read_beats/(float)mmdeviceIndication->ccnt;
  float write_util = (float)write_beats/(float)mmdeviceIndication->ccnt;
  fprintf(stderr, "memory read beats %ld utilization (beats/cycle): %f\n", read_beats, read_util);
  fprintf(stderr, "memory write beats %ld utilization (beats/cycle): %f\n", write_beats, write_util);

  if (0) {
    dumpMat<float>("pm1 * pm2", "%5.1f", pm3);
    dumpMat<float>("m1 * m2", "%5.1f", m3);
  }
  bool eq = std::equal(m3.begin<float>(), m3.end<float>(), pm3.begin<float>());
  //dumpMat<int>("pm3", "%08x", pm3);
  fprintf(stderr, "eq=%d\n", eq);
  //device->finish();
  exit(!eq);
}
<commit_msg>use PortalMat::compare and increase LARGE_MAT size on non-bluesim platforms<commit_after>
// Copyright (c) 2014 Quanta Research Cambridge, Inc.

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

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

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

#include <MmRequestProxy.h>
#include <MmIndicationWrapper.h>
#include <MmDebugIndicationWrapper.h>
#include <MmDebugRequestProxy.h>
#include <DmaConfigProxy.h>
#include <GeneratedTypes.h>
//#include <DmaIndicationWrapper.h>
#include <StdDmaIndication.h>
#include <stdio.h>
#include <sys/mman.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
#include <pthread.h>
#include <errno.h>
#include <math.h> // frexp(), fabs()
#include <assert.h>
#include "portalmat.h"
#include "mnist.h"

static int verbose = 0;

class SigmoidIndication;
class MmIndication;
class MmDebugIndication;

RbmRequestProxy *rbmdevice = 0;
MmRequestProxy *mmdevice = 0;
MmDebugRequestProxy *mmdebug = 0;
SigmoidIndication *sigmoidindication = 0;
SigmoidRequestProxy *sigmoiddevice = 0;
TimerRequestProxy *timerdevice = 0;
MmIndication *mmdeviceIndication = 0;
MmDebugIndication *mmDebugIndication = 0;
TimerIndication *timerdeviceIndication = 0;
DmaConfigProxy *dma = 0;
DmaIndicationWrapper *dmaIndication = 0;

long dotprod = 0;

void dump(const char *prefix, char *buf, size_t len)
{
    fprintf(stderr, "%s ", prefix);
    for (int i = 0; i < (len > 64 ? 64 : len) ; i++) {
	fprintf(stderr, "%02x", (unsigned char)buf[i]);
	if (i % 4 == 3)
	  fprintf(stderr, " ");
    }
    fprintf(stderr, "\n");
}

void *dbgThread(void *)
{
  while (1) {
    sleep(2);
    if (dma) {
      dma->getStateDbg(ChannelType_Read);
    }
    if (mmdebug) {
      fprintf(stderr, "Calling mmdebug->debug()\n");
      mmdebug->debug();
    }
  }
  return 0;
}

int main(int argc, const char **argv)
{
  unsigned int srcGen = 0;

  fprintf(stderr, "%s %s\n", __DATE__, __TIME__);
  mmdevice = new MmRequestProxy(IfcNames_MmRequestPortal);
  mmdebug = new MmDebugRequestProxy(IfcNames_MmDebugRequestPortal);
  mmdeviceIndication = new MmIndication(IfcNames_MmIndicationPortal);
  mmDebugIndication = new MmDebugIndication(IfcNames_MmDebugIndicationPortal);
  timerdevice = new TimerRequestProxy(IfcNames_TimerRequestPortal);
  timerdeviceIndication = new TimerIndication(IfcNames_TimerIndicationPortal);

  dma = new DmaConfigProxy(IfcNames_DmaConfigPortal);
  dmaIndication = new DmaIndication(dma, IfcNames_DmaIndicationPortal);

  if(sem_init(&mul_sem, 1, 0)){
    fprintf(stderr, "failed to init mul_sem\n");
    return -1;
  }

  pthread_t tid;
  fprintf(stderr, "creating exec thread\n");
  if(pthread_create(&tid, NULL,  portalExec, NULL)){
   fprintf(stderr, "error creating exec thread\n");
   exit(1);
  }

  pthread_t dbgtid;
  fprintf(stderr, "creating debug thread\n");
  if(pthread_create(&dbgtid, NULL,  dbgThread, NULL)){
   fprintf(stderr, "error creating debug thread\n");
   exit(1);
  }

  matAllocator = new PortalMatAllocator(dma);

#define LARGE_MAT
#ifdef LARGE_MAT
#ifdef BSIM
  int A = 32;
  int B = 16;
#else
  int A = 512;
  int B = 256;
#endif
  if (argc > 1) {
    B = strtoul(argv[1], 0, 0);
    A = 2*B;
  }
  cv::Mat m1(A,B,CV_32F);
  cv::Mat m2(B,A,CV_32F);
  int v = 0;
  for(int a = 0; a < A; a++){
    for(int b = 0; b < B; b++){
      m2.at<float>(b,a) = v+(A*B);;
      m1.at<float>(a,b) = v++;
    }
  }
#else
  cv::Mat m1 = (cv::Mat_<float>(4,8) <<
		11,12,13,14,15,16,17,18,
		21,22,23,24,25,26,27,28,
		31,32,33,34,35,36,37,38,
		41,42,43,44,45,46,47,48
		);
  cv::Mat m2 = (cv::Mat_<float>(8,4) <<
		51,62,53,54,
		55,56,57,58,
		61,62,63,64,
		65,66,67,68,
		71,72,73,74,
		75,76,77,78,
		81,82,83,84,
		85,86,87,88
		);
#endif
  cv::Mat  m3 = m1 * m2;
  //dumpMatF<int>("m1", "%08x", m1, stdout);
  //dumpMatF<int>("m2", "%08x", m2, stdout);
  fflush(stdout);
  PortalMat pm1(m1);
  PortalMat pm2t(m2.t());
  PortalMat pm3;
  start_timer(0);
  pm3.multf(pm1, pm2t, mmdeviceIndication);
  uint64_t hw_cycles = lap_timer(0);
  uint64_t read_beats = dma->show_mem_stats(ChannelType_Read);
  uint64_t write_beats = dma->show_mem_stats(ChannelType_Write);
  float read_util = (float)read_beats/(float)mmdeviceIndication->ccnt;
  float write_util = (float)write_beats/(float)mmdeviceIndication->ccnt;
  fprintf(stderr, "memory read beats %ld utilization (beats/cycle): %f\n", read_beats, read_util);
  fprintf(stderr, "memory write beats %ld utilization (beats/cycle): %f\n", write_beats, write_util);

  if (0) {
    dumpMat<float>("pm1 * pm2", "%5.1f", pm3);
    dumpMat<float>("m1 * m2", "%5.1f", m3);
  }
  //bool eq = std::equal(m3.begin<float>(), m3.end<float>(), pm3.begin<float>());
  bool eq = pm3.compare(m3);
  //dumpMat<int>("pm3", "%08x", pm3);
  fprintf(stderr, "eq=%d\n", eq);
  //device->finish();
  exit(!eq);
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2017 ScyllaDB
 *
 * Modified by ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include "make_random_string.hh"
#include "schema.hh"
#include "keys.hh"
#include "streamed_mutation.hh"
#include "mutation.hh"
#include "schema_builder.hh"
#include "streamed_mutation.hh"

// Helper for working with the following table:
//
//   CREATE TABLE ks.cf (pk text, ck text, v text, s1 text static, PRIMARY KEY (pk, ck));
//
class simple_schema {
    schema_ptr _s;
    api::timestamp_type _timestamp = api::min_timestamp;
    const column_definition& _v_def;
private:
    api::timestamp_type new_timestamp() {
        return _timestamp++;
    }
public:
    simple_schema()
        : _s(schema_builder("ks", "cf")
            .with_column("pk", utf8_type, column_kind::partition_key)
            .with_column("ck", utf8_type, column_kind::clustering_key)
            .with_column("s1", utf8_type, column_kind::static_column)
            .with_column("v", utf8_type)
            .build())
        , _v_def(*_s->get_column_definition(to_bytes("v")))
    { }

    clustering_key make_ckey(sstring ck) {
        return clustering_key::from_single_value(*_s, data_value(ck).serialize());
    }

    // Make a clustering_key which is n-th in some arbitrary sequence of keys
    clustering_key make_ckey(uint32_t n) {
        return make_ckey(sprint("ck%010d", n));
    }

    // Make a partition key which is n-th in some arbitrary sequence of keys.
    // There is no particular order for the keys, they're not in ring order.
    dht::decorated_key make_pkey(uint32_t n) {
        return make_pkey(sprint("pk%010d", n));
    }

    dht::decorated_key make_pkey(sstring pk) {
        auto key = partition_key::from_single_value(*_s, data_value(pk).serialize());
        return dht::global_partitioner().decorate_key(*_s, key);
    }

    void add_row(mutation& m, const clustering_key& key, sstring v) {
        m.set_clustered_cell(key, _v_def, atomic_cell::make_live(new_timestamp(), data_value(v).serialize()));
    }

    std::pair<sstring, api::timestamp_type> get_value(const clustering_row& row) {
        auto cell = row.cells().find_cell(_v_def.id);
        if (!cell) {
            throw std::runtime_error("cell not found");
        }
        atomic_cell_view ac = cell->as_atomic_cell();
        if (!ac.is_live()) {
            throw std::runtime_error("cell is dead");
        }
        return std::make_pair(value_cast<sstring>(utf8_type->deserialize(ac.value())), ac.timestamp());
    }

    mutation_fragment make_row(const clustering_key& key, sstring v) {
        auto row = clustering_row(key);
        row.cells().apply(*_s->get_column_definition(to_bytes(sstring("v"))),
            atomic_cell::make_live(new_timestamp(), data_value(v).serialize()));
        return mutation_fragment(std::move(row));
    }

    void add_static_row(mutation& m, sstring s1) {
        m.set_static_cell(to_bytes("s1"), data_value(s1), new_timestamp());
    }

    range_tombstone delete_range(mutation& m, const query::clustering_range& range) {
        auto rt = make_range_tombstone(range);
        m.partition().apply_delete(*_s, rt);
        return rt;
    }

    range_tombstone make_range_tombstone(const query::clustering_range& range) {
        auto bv_range = bound_view::from_range(range);
        range_tombstone rt(bv_range.first, bv_range.second, tombstone(new_timestamp(), gc_clock::now()));
        return rt;
    }

    mutation new_mutation(sstring pk) {
        return mutation(make_pkey(pk), _s);
    }

    schema_ptr schema() {
        return _s;
    }

    // Creates a sequence of keys in ring order
    std::vector<dht::decorated_key> make_pkeys(int n) {
        std::vector<dht::decorated_key> keys;
        for (int i = 0; i < n; ++i) {
            keys.push_back(make_pkey(i));
        }
        std::sort(keys.begin(), keys.end(), dht::decorated_key::less_comparator(_s));
        return keys;
    }
};
<commit_msg>tests: simple_schema: Introduce make_ckeys()<commit_after>/*
 * Copyright (C) 2017 ScyllaDB
 *
 * Modified by ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include "make_random_string.hh"
#include "schema.hh"
#include "keys.hh"
#include "streamed_mutation.hh"
#include "mutation.hh"
#include "schema_builder.hh"
#include "streamed_mutation.hh"

// Helper for working with the following table:
//
//   CREATE TABLE ks.cf (pk text, ck text, v text, s1 text static, PRIMARY KEY (pk, ck));
//
class simple_schema {
    schema_ptr _s;
    api::timestamp_type _timestamp = api::min_timestamp;
    const column_definition& _v_def;
private:
    api::timestamp_type new_timestamp() {
        return _timestamp++;
    }
public:
    simple_schema()
        : _s(schema_builder("ks", "cf")
            .with_column("pk", utf8_type, column_kind::partition_key)
            .with_column("ck", utf8_type, column_kind::clustering_key)
            .with_column("s1", utf8_type, column_kind::static_column)
            .with_column("v", utf8_type)
            .build())
        , _v_def(*_s->get_column_definition(to_bytes("v")))
    { }

    clustering_key make_ckey(sstring ck) {
        return clustering_key::from_single_value(*_s, data_value(ck).serialize());
    }

    // Make a clustering_key which is n-th in some arbitrary sequence of keys
    clustering_key make_ckey(uint32_t n) {
        return make_ckey(sprint("ck%010d", n));
    }

    // Make a partition key which is n-th in some arbitrary sequence of keys.
    // There is no particular order for the keys, they're not in ring order.
    dht::decorated_key make_pkey(uint32_t n) {
        return make_pkey(sprint("pk%010d", n));
    }

    dht::decorated_key make_pkey(sstring pk) {
        auto key = partition_key::from_single_value(*_s, data_value(pk).serialize());
        return dht::global_partitioner().decorate_key(*_s, key);
    }

    void add_row(mutation& m, const clustering_key& key, sstring v) {
        m.set_clustered_cell(key, _v_def, atomic_cell::make_live(new_timestamp(), data_value(v).serialize()));
    }

    std::pair<sstring, api::timestamp_type> get_value(const clustering_row& row) {
        auto cell = row.cells().find_cell(_v_def.id);
        if (!cell) {
            throw std::runtime_error("cell not found");
        }
        atomic_cell_view ac = cell->as_atomic_cell();
        if (!ac.is_live()) {
            throw std::runtime_error("cell is dead");
        }
        return std::make_pair(value_cast<sstring>(utf8_type->deserialize(ac.value())), ac.timestamp());
    }

    mutation_fragment make_row(const clustering_key& key, sstring v) {
        auto row = clustering_row(key);
        row.cells().apply(*_s->get_column_definition(to_bytes(sstring("v"))),
            atomic_cell::make_live(new_timestamp(), data_value(v).serialize()));
        return mutation_fragment(std::move(row));
    }

    void add_static_row(mutation& m, sstring s1) {
        m.set_static_cell(to_bytes("s1"), data_value(s1), new_timestamp());
    }

    range_tombstone delete_range(mutation& m, const query::clustering_range& range) {
        auto rt = make_range_tombstone(range);
        m.partition().apply_delete(*_s, rt);
        return rt;
    }

    range_tombstone make_range_tombstone(const query::clustering_range& range) {
        auto bv_range = bound_view::from_range(range);
        range_tombstone rt(bv_range.first, bv_range.second, tombstone(new_timestamp(), gc_clock::now()));
        return rt;
    }

    mutation new_mutation(sstring pk) {
        return mutation(make_pkey(pk), _s);
    }

    schema_ptr schema() {
        return _s;
    }

    // Creates a sequence of keys in ring order
    std::vector<dht::decorated_key> make_pkeys(int n) {
        std::vector<dht::decorated_key> keys;
        for (int i = 0; i < n; ++i) {
            keys.push_back(make_pkey(i));
        }
        std::sort(keys.begin(), keys.end(), dht::decorated_key::less_comparator(_s));
        return keys;
    }

    // Returns n clustering keys in their natural order
    std::vector<clustering_key> make_ckeys(int n) {
        std::vector<clustering_key> keys;
        for (int i = 0; i < n; ++i) {
            keys.push_back(make_ckey(i));
        }
        return keys;
    }
};
<|endoftext|>


<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// appleseed.renderer headers.
#include "renderer/modeling/project/project.h"
#include "renderer/modeling/project/projectfilereader.h"
#include "renderer/modeling/project/projectfilewriter.h"

// appleseed.foundation headers.
#include "foundation/utility/autoreleaseptr.h"
#include "foundation/utility/test.h"
#include "foundation/utility/testutils.h"

// Boost headers
#include "boost/filesystem.hpp"

// Standard headers
#include <exception>

using namespace foundation;
using namespace renderer;
namespace bf = boost::filesystem;

TEST_SUITE(Renderer_Modeling_Project_ProjectFileReader)
{
    TEST_CASE(ParsingOfConfigurationBlocks)
    {
        ProjectFileReader reader;
        auto_release_ptr<Project> project =
            reader.read(
                "unit tests/inputs/test_projectfilereader_configurationblocks.appleseed",
                "../../../schemas/project.xsd");    // path relative to input file

        ASSERT_NEQ(0, project.get());

        const bool success =
            ProjectFileWriter::write(
                project.ref(),
                "unit tests/outputs/test_projectfilereader_configurationblocks.appleseed",
                ProjectFileWriter::OmitHeaderComment);

        ASSERT_TRUE(success);

        const bool identical =
            compare_text_files(
                "unit tests/inputs/test_projectfilereader_configurationblocks.appleseed",
                "unit tests/outputs/test_projectfilereader_configurationblocks.appleseed");

        EXPECT_TRUE(identical);
    }

    TEST_CASE(ReadValidPackedProject)
    {
        const char* project = "unit tests/inputs/test_packed_project_valid.appleseedz";
        const char* project_unpacked = "unit tests/inputs/test_packed_project_valid.appleseedz.unpacked";

        try
        {
            ProjectFileReader reader;

            auto_release_ptr<Project> project_success =
                reader.read(
                    project,
                    "../../../../schemas/project.xsd");    // path relative to input file

            EXPECT_NEQ(0, project_success.get());

            bf::remove_all(bf::path(project_unpacked));
        }
        catch (std::exception e)
        {
            bf::remove_all(bf::path(project_unpacked));
            throw e;
        }
    }

    // Test waits for a brilliant solution of how to invoke it without emitting error message

    // TEST_CASE(ReadInvalidPackedProject)
    // {
    //     const char* project = "unit tests/inputs/test_packed_project_invalid.appleseedz";
    //     const char* project_unpacked = "unit tests/inputs/test_packed_project_invalid.appleseedz.unpacked";

    //     try
    //     {
    //         ProjectFileReader reader;

    //         auto_release_ptr<Project> project_fail =
    //                 reader.read(
    //                     project,
    //                     "../../../../schemas/project.xsd");    // path relative to input file

    //         EXPECT_EQ(0, project_fail.get());

    //         bf::remove_all(bf::path(project_unpacked));
    //     }
    //     catch (std::exception e)
    //     {
    //         bf::remove_all(bf::path(project_unpacked));
    //         throw e;
    //     }
    // }
}
<commit_msg>Change unpacked directory for test<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// appleseed.renderer headers.
#include "renderer/modeling/project/project.h"
#include "renderer/modeling/project/projectfilereader.h"
#include "renderer/modeling/project/projectfilewriter.h"

// appleseed.foundation headers.
#include "foundation/utility/autoreleaseptr.h"
#include "foundation/utility/test.h"
#include "foundation/utility/testutils.h"

// Boost headers
#include "boost/filesystem.hpp"

// Standard headers
#include <exception>

using namespace foundation;
using namespace renderer;
namespace bf = boost::filesystem;

TEST_SUITE(Renderer_Modeling_Project_ProjectFileReader)
{
    TEST_CASE(ParsingOfConfigurationBlocks)
    {
        ProjectFileReader reader;
        auto_release_ptr<Project> project =
            reader.read(
                "unit tests/inputs/test_projectfilereader_configurationblocks.appleseed",
                "../../../schemas/project.xsd");    // path relative to input file

        ASSERT_NEQ(0, project.get());

        const bool success =
            ProjectFileWriter::write(
                project.ref(),
                "unit tests/outputs/test_projectfilereader_configurationblocks.appleseed",
                ProjectFileWriter::OmitHeaderComment);

        ASSERT_TRUE(success);

        const bool identical =
            compare_text_files(
                "unit tests/inputs/test_projectfilereader_configurationblocks.appleseed",
                "unit tests/outputs/test_projectfilereader_configurationblocks.appleseed");

        EXPECT_TRUE(identical);
    }

    TEST_CASE(ReadValidPackedProject)
    {
        const char* project = "unit tests/inputs/test_packed_project_valid.appleseedz";
        const char* project_unpacked = "unit tests/inputs/test_packed_project_valid.unpacked";

        try
        {
            ProjectFileReader reader;

            auto_release_ptr<Project> project_success =
                reader.read(
                    project,
                    "../../../../schemas/project.xsd");    // path relative to input file

            EXPECT_NEQ(0, project_success.get());

            bf::remove_all(bf::path(project_unpacked));
        }
        catch (std::exception e)
        {
            bf::remove_all(bf::path(project_unpacked));
            throw e;
        }
    }

    // Test waits for a brilliant solution of how to invoke it without emitting error message

    // TEST_CASE(ReadInvalidPackedProject)
    // {
    //     const char* project = "unit tests/inputs/test_packed_project_invalid.appleseedz";
    //     const char* project_unpacked = "unit tests/inputs/test_packed_project_invalid.appleseedz.unpacked";

    //     try
    //     {
    //         ProjectFileReader reader;

    //         auto_release_ptr<Project> project_fail =
    //                 reader.read(
    //                     project,
    //                     "../../../../schemas/project.xsd");    // path relative to input file

    //         EXPECT_EQ(0, project_fail.get());

    //         bf::remove_all(bf::path(project_unpacked));
    //     }
    //     catch (std::exception e)
    //     {
    //         bf::remove_all(bf::path(project_unpacked));
    //         throw e;
    //     }
    // }
}
<|endoftext|>


<commit_before>// This file is part of the dune-hdd project:
//   http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_HDD_LINEARELLIPTIC_PROBLEMS_HH
#define DUNE_HDD_LINEARELLIPTIC_PROBLEMS_HH

#include <string>
#include <vector>
#include <memory>

#if HAVE_ALUGRID
# include <dune/grid/alugrid.hh>
#endif

#include <dune/stuff/common/configtree.hh>
#include <dune/stuff/common/exceptions.hh>

#include "problems/interfaces.hh"
#include "problems/default.hh"
#include "problems/ESV2007.hh"
#include "../playground/linearelliptic/problems/mixed-boundaries.hh"
#include "../playground/linearelliptic/problems/thermalblock.hh"

namespace Dune {
namespace HDD {
namespace internal {

void lib_exists();

} // namespace internal
namespace LinearElliptic {
namespace internal {

template< class E, class D, int d, class R, int r = 1 >
class ProblemProviderBase
{
public:
  typedef ProblemInterface< E, D, d, R, r > InterfaceType;

protected:
  template< class ProblemType >
  static std::unique_ptr< ProblemType > call_create(const Stuff::Common::ConfigTree& config)
  {
    if (config.empty())
      return ProblemType::create();
    else
      return ProblemType::create(config);
  } // ... call_create(...)

public:
  static std::vector< std::string > available()
  {
    return {
        Problems::Default< E, D, d, R, r >::static_id()
      , Problems::MixedBoundaries< E, D, d, R, r >::static_id()
      , Problems::Thermalblock< E, D, d, R, r >::static_id()
    };
  } // ... available(...)

  static Stuff::Common::ConfigTree default_config(const std::string type = available()[0],
                                                  const std::string sub_name = "")
  {
  if (type == Problems::Default< E, D, d, R, r >::static_id())
    return Problems::Default< E, D, d, R, r >::default_config(sub_name);
  else if (type == Problems::MixedBoundaries< E, D, d, R, r >::static_id())
    return Problems::MixedBoundaries< E, D, d, R, r >::default_config(sub_name);
  else if (type == Problems::Thermalblock< E, D, d, R, r >::static_id())
    return Problems::Thermalblock< E, D, d, R, r >::default_config(sub_name);
  else
    DUNE_THROW_COLORFULLY(Stuff::Exceptions::wrong_input_given,
                          "'" << type << "' is not a valid " << InterfaceType::static_id() << "!");
  } // ... default_config(...)

  static std::unique_ptr< InterfaceType > create(const std::string type = available()[0],
                                                 const Stuff::Common::ConfigTree config = default_config(available()[0]))
  {
    if (type == Problems::Default< E, D, d, R, r >::static_id())
      return call_create< Problems::Default< E, D, d, R, r > >(config);
    else if (type == Problems::MixedBoundaries< E, D, d, R, r >::static_id())
      return call_create< Problems::MixedBoundaries< E, D, d, R, r > >(config);
    else if (type == Problems::Thermalblock< E, D, d, R, r >::static_id())
      return call_create< Problems::Thermalblock< E, D, d, R, r > >(config);
    else
      DUNE_THROW_COLORFULLY(Stuff::Exceptions::wrong_input_given,
                            "'" << type << "' is not a valid " << InterfaceType::static_id() << "!");
  } // ... create(...)
}; // clas ProblemProviderBase

} // namespace internal

template< class E, class D, int d, class R, int r = 1 >
class ProblemProvider
  : public internal::ProblemProviderBase< E, D, d, R, r >
{};

template< class E, class D, class R >
class ProblemProvider< E, D, 2, R, 1 >
  : public internal::ProblemProviderBase< E, D, 2, R, 1 >
{
  static const unsigned int d = 2;
  static const unsigned int r = 1;
  typedef internal::ProblemProviderBase< E, D, d, R, r > BaseType;
public:
  using typename BaseType::InterfaceType;

  static std::vector< std::string > available()
  {
    auto base = BaseType::available();
    base.push_back(Problems::ESV2007< E, D, d, R, r >::static_id());
    return base;
  } // ... available(...)

  static Stuff::Common::ConfigTree default_config(const std::string type = available()[0],
                                                  const std::string sub_name = "")
  {
  if (type == Problems::ESV2007< E, D, d, R, r >::static_id())
    return Problems::ESV2007< E, D, d, R, r >::default_config(sub_name);
  else
    return BaseType::default_config(type, sub_name);
  } // ... default_config(...)

  static std::unique_ptr< InterfaceType > create(const std::string type = available()[0],
                                                 const Stuff::Common::ConfigTree config = Stuff::Common::ConfigTree())
  {
    if (type == Problems::ESV2007< E, D, d, R, r >::static_id())
      return BaseType::template call_create< Problems::ESV2007< E, D, d, R, r > >(config);
    else
      return BaseType::create(type, config);
  } // ... create(...)
}; // clas ProblemProvider< ..., 2, ... 1 >

#if HAVE_ALUGRID

extern template class ProblemProvider< typename ALUConformGrid< 2, 2 >::template Codim< 0 >::Entity,
                                       double, 2, double, 1 >;

#endif // HAVE_ALUGRID

} // namespace LinearElliptic
} // namespace HDD
} // namespace Dune

#endif // DUNE_HDD_LINEARELLIPTIC_PROBLEMS_HH
<commit_msg>[linearelliptic.problems] added OS2014<commit_after>// This file is part of the dune-hdd project:
//   http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_HDD_LINEARELLIPTIC_PROBLEMS_HH
#define DUNE_HDD_LINEARELLIPTIC_PROBLEMS_HH

#include <string>
#include <vector>
#include <memory>

#if HAVE_ALUGRID
# include <dune/grid/alugrid.hh>
#endif

#include <dune/stuff/common/configtree.hh>
#include <dune/stuff/common/exceptions.hh>

#include "problems/interfaces.hh"
#include "problems/default.hh"
#include "problems/ESV2007.hh"
#include "../playground/linearelliptic/problems/mixed-boundaries.hh"
#include "../playground/linearelliptic/problems/thermalblock.hh"
#include "../playground/linearelliptic/problems/OS2014.hh"

namespace Dune {
namespace HDD {
namespace internal {

void lib_exists();

} // namespace internal
namespace LinearElliptic {
namespace internal {

template< class E, class D, int d, class R, int r = 1 >
class ProblemProviderBase
{
public:
  typedef ProblemInterface< E, D, d, R, r > InterfaceType;

protected:
  template< class ProblemType >
  static std::unique_ptr< ProblemType > call_create(const Stuff::Common::ConfigTree& config)
  {
    if (config.empty())
      return ProblemType::create();
    else
      return ProblemType::create(config);
  } // ... call_create(...)

public:
  static std::vector< std::string > available()
  {
    return {
        Problems::Default< E, D, d, R, r >::static_id()
      , Problems::MixedBoundaries< E, D, d, R, r >::static_id()
      , Problems::Thermalblock< E, D, d, R, r >::static_id()
    };
  } // ... available(...)

  static Stuff::Common::ConfigTree default_config(const std::string type = available()[0],
                                                  const std::string sub_name = "")
  {
  if (type == Problems::Default< E, D, d, R, r >::static_id())
    return Problems::Default< E, D, d, R, r >::default_config(sub_name);
  else if (type == Problems::MixedBoundaries< E, D, d, R, r >::static_id())
    return Problems::MixedBoundaries< E, D, d, R, r >::default_config(sub_name);
  else if (type == Problems::Thermalblock< E, D, d, R, r >::static_id())
    return Problems::Thermalblock< E, D, d, R, r >::default_config(sub_name);
  else
    DUNE_THROW_COLORFULLY(Stuff::Exceptions::wrong_input_given,
                          "'" << type << "' is not a valid " << InterfaceType::static_id() << "!");
  } // ... default_config(...)

  static std::unique_ptr< InterfaceType > create(const std::string type = available()[0],
                                                 const Stuff::Common::ConfigTree config = default_config(available()[0]))
  {
    if (type == Problems::Default< E, D, d, R, r >::static_id())
      return call_create< Problems::Default< E, D, d, R, r > >(config);
    else if (type == Problems::MixedBoundaries< E, D, d, R, r >::static_id())
      return call_create< Problems::MixedBoundaries< E, D, d, R, r > >(config);
    else if (type == Problems::Thermalblock< E, D, d, R, r >::static_id())
      return call_create< Problems::Thermalblock< E, D, d, R, r > >(config);
    else
      DUNE_THROW_COLORFULLY(Stuff::Exceptions::wrong_input_given,
                            "'" << type << "' is not a valid " << InterfaceType::static_id() << "!");
  } // ... create(...)
}; // clas ProblemProviderBase

} // namespace internal

template< class E, class D, int d, class R, int r = 1 >
class ProblemProvider
  : public internal::ProblemProviderBase< E, D, d, R, r >
{};

template< class E, class D, class R >
class ProblemProvider< E, D, 2, R, 1 >
  : public internal::ProblemProviderBase< E, D, 2, R, 1 >
{
  static const unsigned int d = 2;
  static const unsigned int r = 1;
  typedef internal::ProblemProviderBase< E, D, d, R, r > BaseType;
public:
  using typename BaseType::InterfaceType;

  static std::vector< std::string > available()
  {
    auto base = BaseType::available();
    base.push_back(Problems::ESV2007< E, D, d, R, r >::static_id());
    base.push_back(Problems::OS2014< E, D, d, R, r >::static_id());
    return base;
  } // ... available(...)

  static Stuff::Common::ConfigTree default_config(const std::string type = available()[0],
                                                  const std::string sub_name = "")
  {
  if (type == Problems::ESV2007< E, D, d, R, r >::static_id())
    return Problems::ESV2007< E, D, d, R, r >::default_config(sub_name);
  else if (type == Problems::OS2014< E, D, d, R, r >::static_id())
    return Problems::OS2014< E, D, d, R, r >::default_config(sub_name);
  else
    return BaseType::default_config(type, sub_name);
  } // ... default_config(...)

  static std::unique_ptr< InterfaceType > create(const std::string type = available()[0],
                                                 const Stuff::Common::ConfigTree config = Stuff::Common::ConfigTree())
  {
    if (type == Problems::ESV2007< E, D, d, R, r >::static_id())
      return BaseType::template call_create< Problems::ESV2007< E, D, d, R, r > >(config);
    else if (type == Problems::OS2014< E, D, d, R, r >::static_id())
      return BaseType::template call_create< Problems::OS2014< E, D, d, R, r > >(config);
    else
      return BaseType::create(type, config);
  } // ... create(...)
}; // clas ProblemProvider< ..., 2, ... 1 >

#if HAVE_ALUGRID

extern template class ProblemProvider< typename ALUConformGrid< 2, 2 >::template Codim< 0 >::Entity,
                                       double, 2, double, 1 >;

#endif // HAVE_ALUGRID

} // namespace LinearElliptic
} // namespace HDD
} // namespace Dune

#endif // DUNE_HDD_LINEARELLIPTIC_PROBLEMS_HH
<|endoftext|>


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

#ifndef IOX_POSH_POPO_BUILDING_BLOCKS_EVENT_NOTIFIER_HPP
#define IOX_POSH_POPO_BUILDING_BLOCKS_EVENT_NOTIFIER_HPP

#include "iceoryx_posh/internal/popo/building_blocks/event_variable_data.hpp"

#include <cstdint>

namespace iox
{
namespace popo
{
class EventNotifier
{
  public:
    EventNotifier(EventVariableData& dataRef, const uint64_t index) noexcept
    {
    }
    void notify()
    {
    }
};
} // namespace popo
} // namespace iox

#endif

<commit_msg>iox-#350 implemented event notifier<commit_after>// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef IOX_POSH_POPO_BUILDING_BLOCKS_EVENT_NOTIFIER_HPP
#define IOX_POSH_POPO_BUILDING_BLOCKS_EVENT_NOTIFIER_HPP

#include "iceoryx_posh/internal/popo/building_blocks/event_variable_data.hpp"

#include <cstdint>

namespace iox
{
namespace popo
{
class EventNotifier
{
  public:
    EventNotifier(EventVariableData& dataRef, const uint64_t index) noexcept
        : m_pointerToEventVariableData(&dataRef)
        , m_notificationIndex(index)
    {
    }

    void notify()
    {
        m_pointerToEventVariableData->m_activeNotifications[m_notificationIndex] = true;
        m_pointerToEventVariableData->m_semaphore.post();
    }

  private:
    EventVariableData* m_pointerToEventVariableData{nullptr};
    uint64_t m_notificationIndex{0U};
};
} // namespace popo
} // namespace iox

#endif

<|endoftext|>


<commit_before>// Author: Akira Okumura 2012/11/26

// Examples for simple optical systems which use products by Edmund Optics.

// define useful units
static const Double_t cm = AOpticsManager::cm();
static const Double_t mm = AOpticsManager::mm();
static const Double_t um = AOpticsManager::um();
static const Double_t nm = AOpticsManager::nm();
static const Double_t  m = AOpticsManager::m();

void NT49665()
{
  // Aspherized achromatic lens.
  // http://www.edmundoptics.com/optics/optical-lenses/aspheric-lenses/aspherized-achromatic-lenses/2953

  // ZEMAX data is available at
  // http://www.edmundoptics.jp/techsupport/resource_center/product_docs/zmax_49665.zmx

  AOpticsManager* manager = new AOpticsManager("NT49665", "NT49665");

  // Make the world
  TGeoBBox* box = new TGeoBBox("box", 10*cm, 10*cm, 10*cm);
  AOpticalComponent *top = new AOpticalComponent("top", box);
  manager->SetTopVolume(top);

  Double_t rmax = 12.5*mm;
  Double_t rmin =   0.*mm;

  Double_t d1 = 9.0*mm;
  Double_t d2 = 2.5*mm;
  Double_t d3 = 8e-2*mm;
  Double_t d4 = 4.40605264801e1*mm;

  Double_t z1 = 0*mm;
  Double_t z2 = z1 + d1;
  Double_t z3 = z2 + d2;
  Double_t z4 = z3 + d3;
  Double_t z5 = z4 + d4;

  Double_t curv1 = 1./(28.5*mm);
  Double_t curv2 = 1./(-31.0*mm);
  Double_t curv3 = 1./(-66.0*mm);
  Double_t curv4 = 1./(-63.0*mm);

  AGeoAsphericDisk* disk1
    = new AGeoAsphericDisk("disk1", z1, curv1, z2, curv2, rmax, rmin);
  AGeoAsphericDisk* disk2
    = new AGeoAsphericDisk("disk2", z2, curv2, z3, curv3, rmax, rmin);
  AGeoAsphericDisk* disk3
    = new AGeoAsphericDisk("disk3", z3, curv3, z4, curv4, rmax, rmin);
  Double_t coefficients[3] = {0, 4.66252900195e-6/(mm*mm*mm), -8.02842124899e-9/(mm*mm*mm*mm*mm)};
  //Double_t coefficients[3] = {4.66252900195e-6/(mm*mm), -8.02842124899e-9/(mm*mm*mm*mm), 0};
  disk3->SetPolynomials(0, 0, 3, coefficients);

  // Ohara S-FSL5
  // http://www.ohara-inc.co.jp/jp/product/optical/dl/data/jsfsl05.pdf
  ASellmeierFormula* FSL5
    = new ASellmeierFormula(1.17447043e0,   1.40056154e-2, 1.19272435e0,
                            8.41855181e-3, -5.81790767e-2, 1.29599726e2);

  // should be 1.48749
  std::cout << FSL5->GetIndex(0.58756*um) << std::endl;

  // S-TIH13
  // http://www.ohara-inc.co.jp/jp/product/optical/dl/data/jstih13.pdf
  ASellmeierFormula* TIH13
    = new ASellmeierFormula(1.62224674e0, 2.93844589e-1, 1.99225164e0,
                            1.18368386e-2,5.90208025e-2, 1.71959976e2);

  // should be 1.74077
  std::cout << TIH13->GetIndex(0.58756*um) << std::endl;

  ALens* lens1 = new ALens("lens1", disk1);
  lens1->SetRefractiveIndex(FSL5);
  ALens* lens2 = new ALens("lens2", disk2);
  lens2->SetRefractiveIndex(TIH13);
  ALens* lens3 = new ALens("lens3", disk3);
  lens3->SetConstantRefractiveIndex(1.517);

  top->AddNode(lens1, 1);
  top->AddNode(lens2, 1);
  top->AddNode(lens3, 1);

  Double_t origin[3] = {0, 0, z5 + 1*um};
  TGeoBBox* box2 = new TGeoBBox("box2", 1*mm, 1*mm, 1*um, origin);
  AFocalSurface* screen = new AFocalSurface("screen", box2);
  top->AddNode(screen, 1);

  manager->CloseGeometry();

  top->Draw("ogl");

  TGeoRotation* rot = new TGeoRotation;
  rot->SetAngles(180., 0., 0.);

  TGeoTranslation* tr = new TGeoTranslation("tr", 0, 0, -15*mm);

  const Int_t nColor = 3;
  Double_t wavelength[nColor] = {486.1*nm, 587.6*nm, 656.3*nm}; // n_F, n_d, n_C
  TH2D* spot[nColor];

  for(Int_t j = 0; j < nColor; j++){
    ARayArray* array = ARayShooter::Circle(wavelength[j], rmax*1.1, 50, 4, rot, tr);

    manager->TraceNonSequential(*array);

    spot[j] = new TH2D(Form("spot%d", j), Form("Spot Diagram for #it{#lambda} = %5.1f (nm);X (#it{#mu}m);Y (#it{#mu}m)", wavelength[j]/nm), 500, -25, 25, 500, -25, 25);

    TObjArray* focused = array->GetFocused();

    for(Int_t i = 0; i <= focused->GetLast(); i++){
      ARay* ray = (ARay*)(*focused)[i];
      if(j == 1 && i%10 == 0){
        ray->MakePolyLine3D()->Draw();
      } // if

      Double_t p[4];
      ray->GetLastPoint(p);

      spot[j]->Fill(p[0]/um, p[1]/um);
    } // i

    delete array;
  } // j

  TCanvas* can = new TCanvas("can", "can", 1200, 400);
  can->Divide(3, 1, 1e-10, 1e-10);

  for(Int_t j = 0; j < nColor; j++){
    can->cd(j + 1);
    spot[j]->Draw("colz");
  } // j

}
<commit_msg>Change the function name<commit_after>// Author: Akira Okumura 2012/11/26

// Examples for simple optical systems which use products by Edmund Optics.

// define useful units
static const Double_t cm = AOpticsManager::cm();
static const Double_t mm = AOpticsManager::mm();
static const Double_t um = AOpticsManager::um();
static const Double_t nm = AOpticsManager::nm();
static const Double_t  m = AOpticsManager::m();

void EdmundOptics()
{
  // Aspherized achromatic lens.
  // http://www.edmundoptics.com/optics/optical-lenses/aspheric-lenses/aspherized-achromatic-lenses/2953

  // ZEMAX data is available at
  // http://www.edmundoptics.jp/techsupport/resource_center/product_docs/zmax_49665.zmx

  AOpticsManager* manager = new AOpticsManager("NT49665", "NT49665");

  // Make the world
  TGeoBBox* box = new TGeoBBox("box", 10*cm, 10*cm, 10*cm);
  AOpticalComponent *top = new AOpticalComponent("top", box);
  manager->SetTopVolume(top);

  Double_t rmax = 12.5*mm;
  Double_t rmin =   0.*mm;

  Double_t d1 = 9.0*mm;
  Double_t d2 = 2.5*mm;
  Double_t d3 = 8e-2*mm;
  Double_t d4 = 4.40605264801e1*mm;

  Double_t z1 = 0*mm;
  Double_t z2 = z1 + d1;
  Double_t z3 = z2 + d2;
  Double_t z4 = z3 + d3;
  Double_t z5 = z4 + d4;

  Double_t curv1 = 1./(28.5*mm);
  Double_t curv2 = 1./(-31.0*mm);
  Double_t curv3 = 1./(-66.0*mm);
  Double_t curv4 = 1./(-63.0*mm);

  AGeoAsphericDisk* disk1
    = new AGeoAsphericDisk("disk1", z1, curv1, z2, curv2, rmax, rmin);
  AGeoAsphericDisk* disk2
    = new AGeoAsphericDisk("disk2", z2, curv2, z3, curv3, rmax, rmin);
  AGeoAsphericDisk* disk3
    = new AGeoAsphericDisk("disk3", z3, curv3, z4, curv4, rmax, rmin);
  Double_t coefficients[3] = {0, 4.66252900195e-6/(mm*mm*mm), -8.02842124899e-9/(mm*mm*mm*mm*mm)};
  disk3->SetPolynomials(0, 0, 3, coefficients);

  // Ohara S-FSL5
  // http://www.ohara-inc.co.jp/jp/product/optical/dl/data/jsfsl05.pdf
  ASellmeierFormula* FSL5
    = new ASellmeierFormula(1.17447043e0,   1.40056154e-2, 1.19272435e0,
                            8.41855181e-3, -5.81790767e-2, 1.29599726e2);

  // should be 1.48749
  std::cout << FSL5->GetIndex(0.58756*um) << std::endl;

  // S-TIH13
  // http://www.ohara-inc.co.jp/jp/product/optical/dl/data/jstih13.pdf
  ASellmeierFormula* TIH13
    = new ASellmeierFormula(1.62224674e0, 2.93844589e-1, 1.99225164e0,
                            1.18368386e-2,5.90208025e-2, 1.71959976e2);

  // should be 1.74077
  std::cout << TIH13->GetIndex(0.58756*um) << std::endl;

  ALens* lens1 = new ALens("lens1", disk1);
  lens1->SetRefractiveIndex(FSL5);
  ALens* lens2 = new ALens("lens2", disk2);
  lens2->SetRefractiveIndex(TIH13);
  ALens* lens3 = new ALens("lens3", disk3);
  lens3->SetConstantRefractiveIndex(1.517);

  top->AddNode(lens1, 1);
  top->AddNode(lens2, 1);
  top->AddNode(lens3, 1);

  Double_t origin[3] = {0, 0, z5 + 1*um};
  TGeoBBox* box2 = new TGeoBBox("box2", 1*mm, 1*mm, 1*um, origin);
  AFocalSurface* screen = new AFocalSurface("screen", box2);
  top->AddNode(screen, 1);

  manager->CloseGeometry();

  top->Draw("ogl");

  TGeoRotation* rot = new TGeoRotation;
  rot->SetAngles(180., 0., 0.);

  TGeoTranslation* tr = new TGeoTranslation("tr", 0, 0, -15*mm);

  const Int_t nColor = 3;
  Double_t wavelength[nColor] = {486.1*nm, 587.6*nm, 656.3*nm}; // n_F, n_d, n_C
  TH2D* spot[nColor];

  for(Int_t j = 0; j < nColor; j++){
    ARayArray* array = ARayShooter::Circle(wavelength[j], rmax*1.1, 50, 4, rot, tr);

    manager->TraceNonSequential(*array);

    spot[j] = new TH2D(Form("spot%d", j), Form("Spot Diagram for #it{#lambda} = %5.1f (nm);X (#it{#mu}m);Y (#it{#mu}m)", wavelength[j]/nm), 500, -25, 25, 500, -25, 25);

    TObjArray* focused = array->GetFocused();

    for(Int_t i = 0; i <= focused->GetLast(); i++){
      ARay* ray = (ARay*)(*focused)[i];
      if(j == 1 && i%10 == 0){
        ray->MakePolyLine3D()->Draw();
      } // if

      Double_t p[4];
      ray->GetLastPoint(p);

      spot[j]->Fill(p[0]/um, p[1]/um);
    } // i

    delete array;
  } // j

  TCanvas* can = new TCanvas("can", "can", 1200, 400);
  can->Divide(3, 1, 1e-10, 1e-10);

  for(int i = 0; i < nColor; i++){
    can->cd(i + 1);
    spot[i]->Draw("colz");
  } // i
}
<|endoftext|>


<commit_before><commit_msg>android: An attempt to handle mouse events.<commit_after><|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <functional>

// template <class T>
// struct hash
//     : public unary_function<T, size_t>
// {
//     size_t operator()(T val) const;
// };

// Not very portable

#include <functional>
#include <cassert>
#include <type_traits>
#include <cstddef>
#include <limits>

template <class T>
void
test()
{
    typedef std::hash<T> H;
    static_assert((std::is_same<typename H::argument_type, T>::value), "" );
    static_assert((std::is_same<typename H::result_type, std::size_t>::value), "" );
    H h;

    for (int i = 0; i <= 5; ++i)
    {
        T t(i);
        if (sizeof(T) <= sizeof(std::size_t))
            assert(h(t) == t);
    }
}

int main()
{
    test<bool>();
    test<char>();
    test<signed char>();
    test<unsigned char>();
    test<char16_t>();
    test<char32_t>();
    test<wchar_t>();
    test<short>();
    test<unsigned short>();
    test<int>();
    test<unsigned int>();
    test<long>();
    test<unsigned long>();
    test<long long>();
    test<unsigned long long>();

//	LWG #2119
    test<std::ptrdiff_t>();
    test<size_t>();

	test<int8_t>();
	test<int16_t>();
	test<int32_t>();
	test<int64_t>();

	test<int_fast8_t>();
	test<int_fast16_t>();
	test<int_fast32_t>();
	test<int_fast64_t>();

	test<int_least8_t>();
	test<int_least16_t>();
	test<int_least32_t>();
	test<int_least64_t>();

    test<intmax_t>();
    test<intptr_t>();

	test<uint8_t>();
	test<uint16_t>();
	test<uint32_t>();
	test<uint64_t>();

	test<uint_fast8_t>();
	test<uint_fast16_t>();
	test<uint_fast32_t>();
	test<uint_fast64_t>();

	test<uint_least8_t>();
	test<uint_least16_t>();
	test<uint_least32_t>();
	test<uint_least64_t>();

    test<uintmax_t>();
    test<uintptr_t>();

#ifndef _LIBCPP_HAS_NO_INT128
    test<__int128_t>();
    test<__uint128_t>();
#endif
}
<commit_msg>Guard libc++ assumption about identity hashing in test. Patch from STL@microsoft.com<commit_after>//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <functional>

// template <class T>
// struct hash
//     : public unary_function<T, size_t>
// {
//     size_t operator()(T val) const;
// };

#include <functional>
#include <cassert>
#include <type_traits>
#include <cstddef>
#include <limits>

#include "test_macros.h"

template <class T>
void
test()
{
    typedef std::hash<T> H;
    static_assert((std::is_same<typename H::argument_type, T>::value), "" );
    static_assert((std::is_same<typename H::result_type, std::size_t>::value), "" );
    H h;

    for (int i = 0; i <= 5; ++i)
    {
        T t(i);
        if (sizeof(T) <= sizeof(std::size_t))
        {
            const std::size_t result = h(t);
            LIBCPP_ASSERT(result == t);
            ((void)result); // Prevent unused warning
        }
    }
}

int main()
{
    test<bool>();
    test<char>();
    test<signed char>();
    test<unsigned char>();
    test<char16_t>();
    test<char32_t>();
    test<wchar_t>();
    test<short>();
    test<unsigned short>();
    test<int>();
    test<unsigned int>();
    test<long>();
    test<unsigned long>();
    test<long long>();
    test<unsigned long long>();

//	LWG #2119
    test<std::ptrdiff_t>();
    test<size_t>();

	test<int8_t>();
	test<int16_t>();
	test<int32_t>();
	test<int64_t>();

	test<int_fast8_t>();
	test<int_fast16_t>();
	test<int_fast32_t>();
	test<int_fast64_t>();

	test<int_least8_t>();
	test<int_least16_t>();
	test<int_least32_t>();
	test<int_least64_t>();

    test<intmax_t>();
    test<intptr_t>();

	test<uint8_t>();
	test<uint16_t>();
	test<uint32_t>();
	test<uint64_t>();

	test<uint_fast8_t>();
	test<uint_fast16_t>();
	test<uint_fast32_t>();
	test<uint_fast64_t>();

	test<uint_least8_t>();
	test<uint_least16_t>();
	test<uint_least32_t>();
	test<uint_least64_t>();

    test<uintmax_t>();
    test<uintptr_t>();

#ifndef _LIBCPP_HAS_NO_INT128
    test<__int128_t>();
    test<__uint128_t>();
#endif
}
<|endoftext|>


<commit_before><commit_msg>coverity#1027396 : Logically dead code<commit_after><|endoftext|>