<commit_before>#include <gtest/gtest.h>
#include <test/unit/lang/utility.hpp>

TEST(parserFunctions, funsGood0) {
  test_parsable("validate_functions"); // tests proper definitions and use
}

// TEST(parserFunctions, funsGood1) {
//   test_parsable("functions-good1");
// }

TEST(parserFunctions, funsGood2) {
  test_parsable("functions-good2");
}

TEST(parserFunctions, funsGood3) {
  test_parsable("functions-good3");
}

TEST(parserFunctions, funsGood4) {
  test_parsable("functions-good-void");
  test_parsable("functions-good-void"); // test twice to ensure
                                        // symbols are not saved
}

TEST(parserFunctions, funsBad18) {
  test_throws("functions-bad18","variable identifier (name) may not be reserved word");
}

TEST(parserFunctions, funsBad0) {
  test_throws("functions-bad0","Functions cannot contain void argument types");
}

TEST(parserFunctions, funsBad1) {
  test_throws("functions-bad1","Function already declared");
}

TEST(parserFunctions, funsBad2) {
  test_throws("functions-bad2","Function declared, but not defined");
}

TEST(parserFunctions, funsBad2_good) {
  is_parsable("src/test/test-models/bad/functions-bad2.stan",0, true);
}

TEST(parserFunctions, funsBad3) {
  test_throws("functions-bad3","SYNTAX ERROR, MESSAGE(S) FROM PARSER:");
}

TEST(parserFunctions,funsBad4) {
  test_throws("functions-bad4",
              "Functions used as statements must be declared to have void returns");
}

TEST(parserFunctions,funsBad5) {
  test_throws("functions-bad5",
              "Base type mismatch in assignment");
}

TEST(parserFunctions,funsBad6) {
  test_throws("functions-bad6",
              "Function target() or functions suffixed with _lp only"
              " allowed in transformed parameter block, model block");
}

TEST(parserFunctions,funsBad7) {
  test_throws("functions-bad7",
              "Function target() or functions suffixed with _lp only"
              " allowed in transformed parameter block, model block");
}

TEST(parserFunctions,funsBad11) {
  test_throws("functions-bad11",
              "Sampling statements (~) and increment_log_prob()");
}

TEST(parserFunctions,funsBad12) {
  test_throws("functions-bad12",
              "Sampling statements (~) and increment_log_prob()");
}

TEST(parserFunctions,funsBad13) {
  test_throws("functions-bad13",
              "Cannot assign to function argument variables.");
}

TEST(parserFunctions,funsBad14) {
  test_throws("functions-bad14",
              "Function already defined");
}

TEST(parserFunctions,funsBad15) {
  test_throws("functions-bad15",
              "attempt to increment log prob with void expression");
}

TEST(parserFunctions,funsBad16) {
  test_throws("functions-bad16",
              "Function system defined");
}

TEST(parserFunctions,funsBad17) {
  test_throws("functions-bad17",
              "Require real return type for probability functions"
              " ending in _log, _lpdf, _lpmf, _lcdf, or _lccdf.");
}

TEST(parserFunctions, badProbFunSuffix) {
  test_throws("bad_prob_fun_Suffix",
              "Probability function must end in _lpdf or _lpmf");
}
<commit_msg>fix typo - stray cap in test model name<commit_after>#include <gtest/gtest.h>
#include <test/unit/lang/utility.hpp>

TEST(parserFunctions, funsGood0) {
  test_parsable("validate_functions"); // tests proper definitions and use
}

// TEST(parserFunctions, funsGood1) {
//   test_parsable("functions-good1");
// }

TEST(parserFunctions, funsGood2) {
  test_parsable("functions-good2");
}

TEST(parserFunctions, funsGood3) {
  test_parsable("functions-good3");
}

TEST(parserFunctions, funsGood4) {
  test_parsable("functions-good-void");
  test_parsable("functions-good-void"); // test twice to ensure
                                        // symbols are not saved
}

TEST(parserFunctions, funsBad18) {
  test_throws("functions-bad18","variable identifier (name) may not be reserved word");
}

TEST(parserFunctions, funsBad0) {
  test_throws("functions-bad0","Functions cannot contain void argument types");
}

TEST(parserFunctions, funsBad1) {
  test_throws("functions-bad1","Function already declared");
}

TEST(parserFunctions, funsBad2) {
  test_throws("functions-bad2","Function declared, but not defined");
}

TEST(parserFunctions, funsBad2_good) {
  is_parsable("src/test/test-models/bad/functions-bad2.stan",0, true);
}

TEST(parserFunctions, funsBad3) {
  test_throws("functions-bad3","SYNTAX ERROR, MESSAGE(S) FROM PARSER:");
}

TEST(parserFunctions,funsBad4) {
  test_throws("functions-bad4",
              "Functions used as statements must be declared to have void returns");
}

TEST(parserFunctions,funsBad5) {
  test_throws("functions-bad5",
              "Base type mismatch in assignment");
}

TEST(parserFunctions,funsBad6) {
  test_throws("functions-bad6",
              "Function target() or functions suffixed with _lp only"
              " allowed in transformed parameter block, model block");
}

TEST(parserFunctions,funsBad7) {
  test_throws("functions-bad7",
              "Function target() or functions suffixed with _lp only"
              " allowed in transformed parameter block, model block");
}

TEST(parserFunctions,funsBad11) {
  test_throws("functions-bad11",
              "Sampling statements (~) and increment_log_prob()");
}

TEST(parserFunctions,funsBad12) {
  test_throws("functions-bad12",
              "Sampling statements (~) and increment_log_prob()");
}

TEST(parserFunctions,funsBad13) {
  test_throws("functions-bad13",
              "Cannot assign to function argument variables.");
}

TEST(parserFunctions,funsBad14) {
  test_throws("functions-bad14",
              "Function already defined");
}

TEST(parserFunctions,funsBad15) {
  test_throws("functions-bad15",
              "attempt to increment log prob with void expression");
}

TEST(parserFunctions,funsBad16) {
  test_throws("functions-bad16",
              "Function system defined");
}

TEST(parserFunctions,funsBad17) {
  test_throws("functions-bad17",
              "Require real return type for probability functions"
              " ending in _log, _lpdf, _lpmf, _lcdf, or _lccdf.");
}

TEST(parserFunctions, badProbFunSuffix) {
  test_throws("bad_prob_fun_suffix",
              "Probability function must end in _lpdf or _lpmf");
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <vector>
#include <stack>
#include <algorithm>
#include <memory>

namespace Frogs
{
    enum class Frog  { None, Brown, Green };
    enum class Step  { None, JumpLeft, LeapLeft, JumpRight, LeapRight };

    class State
    {
        std::vector<Frog> lilies;
        int count, blankPos;

    public:
        State(): count(0), blankPos(-1)
        {
        }
        State(int count): lilies(2 * count + 1), count(count), blankPos(count)
        {
            for (int i = 0; i < count; ++i)
            {
                lilies[i] = Frog::Brown;
                lilies[2 * count - i] = Frog::Green;
            }

            lilies[blankPos] = Frog::None;
        }

        bool operator==(const State& other) const
        {
            return count == other.count && lilies == other.lilies && blankPos == other.blankPos;
        }

        bool IsStuckJumpLeft()  const  { return blankPos >= (int)lilies.size() - 1 || lilies[blankPos + 1] != Frog::Green; }
        bool IsStuckLeapLeft()  const  { return blankPos >= (int)lilies.size() - 2 || lilies[blankPos + 2] != Frog::Green; }
        bool IsStuckJumpRight() const  { return blankPos < 1                       || lilies[blankPos - 1] != Frog::Brown; }
        bool IsStuckLeapRight() const  { return blankPos < 2                       || lilies[blankPos - 2] != Frog::Brown; }

        bool WasTargetReached() const
        {
            for (int i = 0; i < count; ++i)
                if (lilies[i] != Frog::Green || lilies[2 * count - i] != Frog::Brown)
                    return false;

            return lilies[count] == Frog::None;
        }

        std::shared_ptr<State> Move(Step step) const
        {
            bool canMove = false;
            auto moved = std::make_shared<State>(*this);

            switch (step)
            {
                case Step::JumpLeft:
                    if (!moved->IsStuckJumpLeft())
                    {
                        moved->lilies[moved->blankPos] = Frog::Green;
                        moved->blankPos++;
                        canMove = true;
                    }
                    break;

                case Step::LeapLeft:
                    if (!moved->IsStuckLeapLeft())
                    {
                        moved->lilies[moved->blankPos] = Frog::Green;
                        moved->blankPos += 2;
                        canMove = true;
                    }
                    break;

                case Step::JumpRight:
                    if (!moved->IsStuckJumpRight())
                    {
                        moved->lilies[moved->blankPos] = Frog::Brown;
                        moved->blankPos--;
                        canMove = true;
                    }
                    break;

                case Step::LeapRight:
                    if (!moved->IsStuckLeapRight())
                    {
                        moved->lilies[moved->blankPos] = Frog::Brown;
                        moved->blankPos -= 2;
                        canMove = true;
                    }
                    break;

                default:
                    break;
            }

            if (canMove)
                moved->lilies[moved->blankPos] = Frog::None;
            return canMove ? moved : nullptr;
        }

        void Print() const
        {
            for (auto frog: lilies)
                switch (frog)
                {
                    case Frog::Brown:
                        printf(">");
                        break;

                    case Frog::Green:
                        printf("<");
                        break;

                    case Frog::None:
                        printf("_");
                        break;
                }

            printf("\n");
        }
    };
}

int main()
{
    int count;
    scanf("%d", &count);

    if (count < 0)
        return 1;

    std::vector<std::shared_ptr<Frogs::State> > visited;
    std::stack<std::shared_ptr<Frogs::State> > trace;
    trace.push(std::make_shared<Frogs::State>(count));

    while (!trace.empty() && !trace.top()->WasTargetReached())
    {
        auto state = trace.top();
        trace.pop();

        if (visited.crend() == std::find(visited.crbegin(), visited.crend(), state))
        {
            visited.push_back(state);

            auto move = [&trace, state](Frogs::Step step)
            {
                auto newState = state->Move(step);
                if (newState)
                    trace.push(newState);
            };

            move(Frogs::Step::JumpLeft);
            move(Frogs::Step::LeapLeft);
            move(Frogs::Step::JumpRight);
            move(Frogs::Step::LeapRight);

            state->Print();
        }
    }

    if (!trace.empty())
        trace.top()->Print();

    return 0;
}
<commit_msg>frogs: dropped a redundant constructor<commit_after>#include <cstdio>
#include <vector>
#include <stack>
#include <algorithm>
#include <memory>

namespace Frogs
{
    enum class Frog  { None, Brown, Green };
    enum class Step  { None, JumpLeft, LeapLeft, JumpRight, LeapRight };

    class State
    {
        std::vector<Frog> lilies;
        int count, blankPos;

    public:
        State(int count): lilies(2 * count + 1), count(count), blankPos(count)
        {
            for (int i = 0; i < count; ++i)
            {
                lilies[i] = Frog::Brown;
                lilies[2 * count - i] = Frog::Green;
            }

            lilies[blankPos] = Frog::None;
        }

        bool operator==(const State& other) const
        {
            return count == other.count && lilies == other.lilies && blankPos == other.blankPos;
        }

        bool IsStuckJumpLeft()  const  { return blankPos >= (int)lilies.size() - 1 || lilies[blankPos + 1] != Frog::Green; }
        bool IsStuckLeapLeft()  const  { return blankPos >= (int)lilies.size() - 2 || lilies[blankPos + 2] != Frog::Green; }
        bool IsStuckJumpRight() const  { return blankPos < 1                       || lilies[blankPos - 1] != Frog::Brown; }
        bool IsStuckLeapRight() const  { return blankPos < 2                       || lilies[blankPos - 2] != Frog::Brown; }

        bool WasTargetReached() const
        {
            for (int i = 0; i < count; ++i)
                if (lilies[i] != Frog::Green || lilies[2 * count - i] != Frog::Brown)
                    return false;

            return lilies[count] == Frog::None;
        }

        std::shared_ptr<State> Move(Step step) const
        {
            bool canMove = false;
            auto moved = std::make_shared<State>(*this);

            switch (step)
            {
                case Step::JumpLeft:
                    if (!moved->IsStuckJumpLeft())
                    {
                        moved->lilies[moved->blankPos] = Frog::Green;
                        moved->blankPos++;
                        canMove = true;
                    }
                    break;

                case Step::LeapLeft:
                    if (!moved->IsStuckLeapLeft())
                    {
                        moved->lilies[moved->blankPos] = Frog::Green;
                        moved->blankPos += 2;
                        canMove = true;
                    }
                    break;

                case Step::JumpRight:
                    if (!moved->IsStuckJumpRight())
                    {
                        moved->lilies[moved->blankPos] = Frog::Brown;
                        moved->blankPos--;
                        canMove = true;
                    }
                    break;

                case Step::LeapRight:
                    if (!moved->IsStuckLeapRight())
                    {
                        moved->lilies[moved->blankPos] = Frog::Brown;
                        moved->blankPos -= 2;
                        canMove = true;
                    }
                    break;

                default:
                    break;
            }

            if (canMove)
                moved->lilies[moved->blankPos] = Frog::None;
            return canMove ? moved : nullptr;
        }

        void Print() const
        {
            for (auto frog: lilies)
                switch (frog)
                {
                    case Frog::Brown:
                        printf(">");
                        break;

                    case Frog::Green:
                        printf("<");
                        break;

                    case Frog::None:
                        printf("_");
                        break;
                }

            printf("\n");
        }
    };
}

int main()
{
    int count;
    scanf("%d", &count);

    if (count < 0)
        return 1;

    std::vector<std::shared_ptr<Frogs::State> > visited;
    std::stack<std::shared_ptr<Frogs::State> > trace;
    trace.push(std::make_shared<Frogs::State>(count));

    while (!trace.empty() && !trace.top()->WasTargetReached())
    {
        auto state = trace.top();
        trace.pop();

        if (visited.crend() == std::find(visited.crbegin(), visited.crend(), state))
        {
            visited.push_back(state);

            auto move = [&trace, state](Frogs::Step step)
            {
                auto newState = state->Move(step);
                if (newState)
                    trace.push(newState);
            };

            move(Frogs::Step::JumpLeft);
            move(Frogs::Step::LeapLeft);
            move(Frogs::Step::JumpRight);
            move(Frogs::Step::LeapRight);

            state->Print();
        }
    }

    if (!trace.empty())
        trace.top()->Print();

    return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2016, Google Inc.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.

#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
#include <unistd.h>

#include <sstream>
#include <string>
#include <utility>

#define ESC "\x1B"

namespace term {
namespace {

int cols = 0;
int rows = 0;

}  // namespace

constexpr char kSaveScreen[] = ESC "[?47h";
constexpr char kRestoreScreen[] = ESC "[?47l";
constexpr char kEraseScreen[] = ESC "[2J";
constexpr char kEraseToEndOfLine[] = ESC "[K";
// constexpr char kClearCharacterAttributes[] = ESC "[0m";
// constexpr char kSetBold[] = ESC "[1m";
// constexpr char kSetLowIntensity[] = ESC "[2m";
// constexpr char kSetUnderline[] = ESC "[4m";
// constexpr char kSetReverseVideo[] = ESC "[7m";
// constexpr char kSetInvisibleText[] = ESC "[8m";

template <size_t n>
void Put(const char (&message)[n]) {
  write(STDOUT_FILENO, message, n);
}

void Put(const std::string& message) {
  write(STDOUT_FILENO, message.data(), message.size());
}

bool GetSize() {
  struct winsize screen_size;
  int result = ioctl(STDIN_FILENO, TIOCGWINSZ, &screen_size);
  if (result == -1)
    return false;
  cols = screen_size.ws_col;
  rows = screen_size.ws_row;
  return true;
}

enum class Color { Black, Red, Green, Yellow, Blue, Magenta, Cyan, White };

const char* kForegroundColors[] = {
    "30", "31", "32", "33", "34", "35", "36", "37",
};

const char* kBackgroundColors[] = {
    "40", "41", "42", "43", "44", "45", "46", "47",
};

}  // namespace

namespace zi {

class CommandBuffer {
 public:
  template <typename T>
  CommandBuffer& operator<<(T&& value) {
    stream_ << value;
    return *this;
  }

  void MoveCursorTo(int x, int y);
  void Execute();

 private:
  std::ostringstream stream_;
};

void CommandBuffer::MoveCursorTo(int x, int y) {
  stream_ << ESC "[" << y << ";" << x << "H";
}

void CommandBuffer::Execute() {
  term::Put(stream_.str());
}

class Shell {
 public:
  void set_status(std::string status) { status_ = std::move(status); }

  void Display();
  void Run();

 private:
  std::string status_;
};

void Shell::Display() {
  CommandBuffer commands;
  commands << term::kEraseScreen;
  commands.MoveCursorTo(0, term::rows - 1);
  commands << status_ << term::kEraseToEndOfLine;
  commands.Execute();
}

void Shell::Run() {
  for (;;) {
    Display();

    int c = getchar();
    if (c == 'q')
      return;
  }
}

}  // zi

int main(int, char**) {
  if (!term::GetSize()) {
    fprintf(stderr, "error: Unable to get terminal size.\n");
    return 1;
  }
  term::Put(term::kSaveScreen);
  zi::Shell shell;
  shell.set_status("Hello, world.");
  shell.Run();
  term::Put(term::kRestoreScreen);
  return 0;
}
<commit_msg>Switch input to raw mode<commit_after>// Copyright (c) 2016, Google Inc.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.

#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>

#include <sstream>
#include <string>
#include <utility>

#define ESC "\x1B"

namespace term {
namespace {

struct termios g_original_termios;

int cols = 0;
int rows = 0;

}  // namespace

constexpr char kSaveScreen[] = ESC "[?47h";
constexpr char kRestoreScreen[] = ESC "[?47l";
constexpr char kEraseScreen[] = ESC "[2J";
constexpr char kEraseToEndOfLine[] = ESC "[K";
// constexpr char kClearCharacterAttributes[] = ESC "[0m";
// constexpr char kSetBold[] = ESC "[1m";
// constexpr char kSetLowIntensity[] = ESC "[2m";
// constexpr char kSetUnderline[] = ESC "[4m";
// constexpr char kSetReverseVideo[] = ESC "[7m";
// constexpr char kSetInvisibleText[] = ESC "[8m";

enum class Color { Black, Red, Green, Yellow, Blue, Magenta, Cyan, White };

const char* kForegroundColors[] = {
    "30", "31", "32", "33", "34", "35", "36", "37",
};

const char* kBackgroundColors[] = {
    "40", "41", "42", "43", "44", "45", "46", "47",
};

template <size_t n>
void Put(const char (&message)[n]) {
  write(STDOUT_FILENO, message, n);
}

void Put(const std::string& message) {
  write(STDOUT_FILENO, message.data(), message.size());
}

bool GetSize() {
  struct winsize screen_size;
  int result = ioctl(STDIN_FILENO, TIOCGWINSZ, &screen_size);
  if (result == -1) {
    fprintf(stderr, "error: Unable to get terminal size.\n");
    return false;
  }
  cols = screen_size.ws_col;
  rows = screen_size.ws_row;
  return true;
}

void RestoreOriginalTermios() {
  if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &g_original_termios) == -1)
    fprintf(stderr, "error: Failed to restore original terminal attributes.\n");
}

bool EnableRaw() {
  if (!isatty(STDIN_FILENO)) {
    fprintf(stderr, "error: stdin is not a tty.\n");
    return false;
  }
  if (tcgetattr(STDIN_FILENO, &g_original_termios) == -1) {
    fprintf(stderr, "error: Cannot get terminal attributes.\n");
    return false;
  }
  if (atexit(RestoreOriginalTermios) != 0) {
    fprintf(stderr, "error: Cannot register cleaup handler.\n");
    return false;
  }
  struct termios raw = g_original_termios;
  raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
  raw.c_oflag &= ~(OPOST);
  raw.c_cflag |= (CS8);
  raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
  raw.c_cc[VMIN] = 0;
  raw.c_cc[VTIME] = 1;
  if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1) {
    fprintf(stderr, "error: Cannot enable raw terminal input.\n");
    return false;
  }
  return true;
}

bool Init() {
  return term::GetSize() && term::EnableRaw();
}

}  // namespace term

namespace zi {

class CommandBuffer {
 public:
  template <typename T>
  CommandBuffer& operator<<(T&& value) {
    stream_ << value;
    return *this;
  }

  void MoveCursorTo(int x, int y);
  void Execute();

 private:
  std::ostringstream stream_;
};

void CommandBuffer::MoveCursorTo(int x, int y) {
  stream_ << ESC "[" << y << ";" << x << "H";
}

void CommandBuffer::Execute() {
  term::Put(stream_.str());
}

class Shell {
 public:
  Shell();
  ~Shell();

  int Run();

  void set_status(std::string status) { status_ = std::move(status); }

 private:
  void Display();

  std::string status_;
};

Shell::Shell() {
  term::Put(term::kSaveScreen);
}

Shell::~Shell() {
  term::Put(term::kRestoreScreen);
}

void Shell::Display() {
  CommandBuffer commands;
  commands << term::kEraseScreen;
  commands.MoveCursorTo(1, term::rows);
  commands << status_ << term::kEraseToEndOfLine;
  commands.Execute();
}

int Shell::Run() {
  Display();
  for (;;) {
    char c = '\0';
    int count = read(STDIN_FILENO, &c, 1);
    if (count == -1)
      return 1;
    if (count == 0)
      continue;
    if (c == 'q')
      return 0;
    Display();
  }
  return 0;
}

}  // namespace zi

int main(int, char**) {
  if (!term::Init())
    return 1;
  zi::Shell shell;
  shell.set_status("Hello, world.");
  return shell.Run();
}
<|endoftext|>


<commit_before>#include <cmath>
#include <Eigen/Eigenvalues>
#include <Eigen/SVD>
#include <float.h>
#include "Ellipse.h"

static std::ranlux24 G_engine(271828);

std::ostream& operator<<(std::ostream& os, const EllipseGeometry& eg)
{
  os << "{ C:" << eg.center.transpose() << "; R:" << eg.radius.transpose() << "; A:" << eg.angle << " }";
  return os;
}

Eigen::Vector2f EllipseGenerator::operator()()
{
  float phi = _arc_dist(G_engine);
  Eigen::Array2f circle_point(std::cos(phi), std::sin(phi));
  Eigen::Array2f ellipse_point = _geometry.radius.array() * circle_point;
  Eigen::Vector2f noise(_noise_dist(G_engine), _noise_dist(G_engine));
  Eigen::Vector2f rotated_ellipse_point = _rotation * (ellipse_point.matrix() + noise);
  return rotated_ellipse_point + _geometry.center;
}

// eccentricity: 0->circle, limit->1: line
EllipseGenerator get_ellipse_generator(float max_center, float min_arc_angle, float sigma,
    Eigen::Vector2f radiusSpan, float max_eccentricity)
{
  std::uniform_real_distribution<float> center_dist(0, max_center);
  std::uniform_real_distribution<float> radius_dist(radiusSpan(0), radiusSpan(1));
  std::uniform_real_distribution<float> angle_dist(0, 2*M_PI);

  // Center.
  float cx = center_dist(G_engine);
  float cy = center_dist(G_engine);

  // Rotation.
  float angle = angle_dist(G_engine);

  // Radii; eccentricity must not be below min_eccentricity.
  float a, b;
  do {
    a = radius_dist(G_engine);
    b = radius_dist(G_engine);
    if (a < b)
      std::swap(a, b);
  } while (std::sqrt(a*a-b*b) >= max_eccentricity);

  // Arc span; must be at least min_arc_angle
  float phi_min, phi_max;
  do {
    phi_min = angle_dist(G_engine);
    phi_max = angle_dist(G_engine);
    if (phi_max < phi_min)
      std::swap(phi_max, phi_min);
  } while (phi_max - phi_min < min_arc_angle);

  EllipseGeometry geometry{Eigen::Vector2f(cx, cy), Eigen::Vector2f(a, b), angle};
  return EllipseGenerator(geometry, Eigen::Vector2f(phi_min, phi_max), sigma);
}

/////////////////////////////////////////////////////////////////////////////
// FITTING based on the following paper: http://autotrace.sourceforge.net/WSCG98.pdf

static Eigen::Vector2f get_offset(const Eigen::MatrixX2f& points)
{
  auto sum = points.colwise().sum();
  return sum / points.rows();
}

static std::tuple<Eigen::Matrix3f,Eigen::Matrix3f,Eigen::Matrix3f>
get_scatter_matrix(const Eigen::MatrixX2f& points, const Eigen::Vector2f& offset)
{
  using namespace Eigen;

  const auto qf = [&](size_t i) {
    Vector2f p = points.row(i);
    auto pc = p - offset;
    return Vector3f(pc(0)*pc(0), pc(0)*pc(1), pc(1)*pc(1));
  };
  const auto lf = [&](size_t i) {
    Vector2f p = points.row(i);
    auto pc = p - offset;
    return Vector3f(pc(0), pc(1), 1);
  };

  const size_t n = points.rows();
  MatrixX3f D1(n,3), D2(n,3);

  // Construct the quadratic and linear parts.  Doing it in two loops has better cache locality.
  for (size_t i = 0; i < n; ++i)
    D1.row(i) = qf(i);
  for (size_t i = 0; i < n; ++i)
    D2.row(i) = lf(i);

  // Construct the three parts of the symmetric scatter matrix.
  auto S1 = D1.transpose() * D1;
  auto S2 = D1.transpose() * D2;
  auto S3 = D2.transpose() * D2;
  return std::make_tuple(S1, S2, S3);
}

std::tuple<Eigen::Vector6f, Eigen::Vector2f>
fit_solver(const Eigen::MatrixX2f& points)
{
  using namespace Eigen;
  using std::get;

  static const struct C1_Initializer {
    Matrix3f matrix;
    Matrix3f inverse;
    C1_Initializer()
    {
      matrix <<
          0,  0, 2,
          0, -1, 0,
          2,  0, 0;
      inverse <<
            0,  0, 0.5,
            0, -1,   0,
          0.5,  0,   0;
    };
  } C1;

  const auto offset = get_offset(points);
  const auto St = get_scatter_matrix(points, offset);
  const auto& S1 = std::get<0>(St);
  const auto& S2 = std::get<1>(St);
  const auto& S3 = std::get<2>(St);
  const auto T = -S3.inverse() * S2.transpose();
  const auto M = C1.inverse * (S1 + S2*T);

  EigenSolver<Matrix3f> M_ev(M);
  Vector3f cond;
  {
    const auto evr = M_ev.eigenvectors().real().array();
    cond = 4*evr.row(0)*evr.row(2) - evr.row(1)*evr.row(1);
  }

  float min = FLT_MAX;
  int imin = -1;
  for (int i = 0; i < 3; ++i)
  if (cond(i) > 0 && cond(i) < min) {
    imin = i; min = cond(i);
  }

  Vector6f ret = Matrix<float, 6, 1>::Zero();
  if (imin >= 0) {
    Vector3f a1 = M_ev.eigenvectors().real().row(imin);
    Vector3f a2 = T*a1;
    ret.block<3,1>(0,0) = a1;
    ret.block<3,1>(3,0) = a2;
  }
  return std::make_tuple(ret, offset);
}

// Taken from OpenCV old code; see
// https://github.com/Itseez/opencv/commit/4eda1662aa01a184e0391a2bb2e557454de7eb86#diff-97c8133c3c171e64ea0df0db4abd033c
EllipseGeometry to_ellipse(const Conic& conic)
{
  using namespace Eigen;
  auto coef = std::get<0>(conic);

  float idet = coef(0)*coef(2) - coef(1)*coef(1)/4; // ac-b^2/4
  idet = idet > FLT_EPSILON ? 1.f/idet : 0;

  float scale = std::sqrt(idet/4);
  if (scale < FLT_EPSILON)
    throw std::domain_error("to_ellipse_2: singularity 1");

  coef *= scale;
  float aa = coef(0), bb = coef(1), cc = coef(2), dd = coef(3), ee = coef(4), ff = coef(5);

  const Vector2f c = Vector2f(-dd*cc + ee*bb/2, -aa*ee + dd*bb/2) * 2;

  // offset ellipse to (x0,y0)
  ff += aa*c(0)*c(0) + bb*c(0)*c(1) + cc*c(1)*c(1) + dd*c(0) + ee*c(1);
  if (std::fabs(ff) < FLT_EPSILON)
    throw std::domain_error("to_ellipse_2: singularity 2");

  Matrix2f S;
  S << aa, bb/2, bb/2, cc;
  S /= -ff;

  // SVs are sorted from largest to smallest
  JacobiSVD<Matrix2f> svd(S, ComputeFullU);
  const auto& vals = svd.singularValues();
  const auto& mat_u = svd.matrixU();

  Vector2f center = c + std::get<1>(conic);
  Vector2f radius = Vector2f(std::sqrt(1.f/vals(1)), std::sqrt(1.f/vals(0)));
  float angle = M_PI - std::atan2(mat_u(1,0), mat_u(0,0));
  return EllipseGeometry{center, radius, angle};
}
<commit_msg>Ellipse generator: restrict angle to at most pi.<commit_after>#include <cmath>
#include <Eigen/Eigenvalues>
#include <Eigen/SVD>
#include <float.h>
#include "Ellipse.h"

static std::ranlux24 G_engine(271828);

std::ostream& operator<<(std::ostream& os, const EllipseGeometry& eg)
{
  os << "{ C:" << eg.center.transpose() << "; R:" << eg.radius.transpose() << "; A:" << eg.angle << " }";
  return os;
}

Eigen::Vector2f EllipseGenerator::operator()()
{
  float phi = _arc_dist(G_engine);
  Eigen::Array2f circle_point(std::cos(phi), std::sin(phi));
  Eigen::Array2f ellipse_point = _geometry.radius.array() * circle_point;
  Eigen::Vector2f noise(_noise_dist(G_engine), _noise_dist(G_engine));
  Eigen::Vector2f rotated_ellipse_point = _rotation * (ellipse_point.matrix() + noise);
  return rotated_ellipse_point + _geometry.center;
}

// eccentricity: 0->circle, limit->1: line
EllipseGenerator get_ellipse_generator(float max_center, float min_arc_angle, float sigma,
    Eigen::Vector2f radiusSpan, float max_eccentricity)
{
  std::uniform_real_distribution<float> center_dist(0, max_center);
  std::uniform_real_distribution<float> radius_dist(radiusSpan(0), radiusSpan(1));
  std::uniform_real_distribution<float> angle_dist(0, 2*M_PI);

  // Center.
  float cx = center_dist(G_engine);
  float cy = center_dist(G_engine);

  // Rotation. Doesn't make sense to rotate ellipse more than 180 deg.
  float angle = angle_dist(G_engine);
  if (angle > M_PI)
    angle -= M_PI;

  // Radii; eccentricity must not be below min_eccentricity.
  float a, b;
  do {
    a = radius_dist(G_engine);
    b = radius_dist(G_engine);
    if (a < b)
      std::swap(a, b);
  } while (std::sqrt(a*a-b*b) >= max_eccentricity);

  // Arc span; must be at least min_arc_angle
  float phi_min, phi_max;
  do {
    phi_min = angle_dist(G_engine);
    phi_max = angle_dist(G_engine);
    if (phi_max < phi_min)
      std::swap(phi_max, phi_min);
  } while (phi_max - phi_min < min_arc_angle);

  EllipseGeometry geometry{Eigen::Vector2f(cx, cy), Eigen::Vector2f(a, b), angle};
  return EllipseGenerator(geometry, Eigen::Vector2f(phi_min, phi_max), sigma);
}

/////////////////////////////////////////////////////////////////////////////
// FITTING based on the following paper: http://autotrace.sourceforge.net/WSCG98.pdf

static Eigen::Vector2f get_offset(const Eigen::MatrixX2f& points)
{
  auto sum = points.colwise().sum();
  return sum / points.rows();
}

static std::tuple<Eigen::Matrix3f,Eigen::Matrix3f,Eigen::Matrix3f>
get_scatter_matrix(const Eigen::MatrixX2f& points, const Eigen::Vector2f& offset)
{
  using namespace Eigen;

  const auto qf = [&](size_t i) {
    Vector2f p = points.row(i);
    auto pc = p - offset;
    return Vector3f(pc(0)*pc(0), pc(0)*pc(1), pc(1)*pc(1));
  };
  const auto lf = [&](size_t i) {
    Vector2f p = points.row(i);
    auto pc = p - offset;
    return Vector3f(pc(0), pc(1), 1);
  };

  const size_t n = points.rows();
  MatrixX3f D1(n,3), D2(n,3);

  // Construct the quadratic and linear parts.  Doing it in two loops has better cache locality.
  for (size_t i = 0; i < n; ++i)
    D1.row(i) = qf(i);
  for (size_t i = 0; i < n; ++i)
    D2.row(i) = lf(i);

  // Construct the three parts of the symmetric scatter matrix.
  auto S1 = D1.transpose() * D1;
  auto S2 = D1.transpose() * D2;
  auto S3 = D2.transpose() * D2;
  return std::make_tuple(S1, S2, S3);
}

std::tuple<Eigen::Vector6f, Eigen::Vector2f>
fit_solver(const Eigen::MatrixX2f& points)
{
  using namespace Eigen;
  using std::get;

  static const struct C1_Initializer {
    Matrix3f matrix;
    Matrix3f inverse;
    C1_Initializer()
    {
      matrix <<
          0,  0, 2,
          0, -1, 0,
          2,  0, 0;
      inverse <<
            0,  0, 0.5,
            0, -1,   0,
          0.5,  0,   0;
    };
  } C1;

  const auto offset = get_offset(points);
  const auto St = get_scatter_matrix(points, offset);
  const auto& S1 = std::get<0>(St);
  const auto& S2 = std::get<1>(St);
  const auto& S3 = std::get<2>(St);
  const auto T = -S3.inverse() * S2.transpose();
  const auto M = C1.inverse * (S1 + S2*T);

  EigenSolver<Matrix3f> M_ev(M);
  Vector3f cond;
  {
    const auto evr = M_ev.eigenvectors().real().array();
    cond = 4*evr.row(0)*evr.row(2) - evr.row(1)*evr.row(1);
  }

  float min = FLT_MAX;
  int imin = -1;
  for (int i = 0; i < 3; ++i)
  if (cond(i) > 0 && cond(i) < min) {
    imin = i; min = cond(i);
  }

  Vector6f ret = Matrix<float, 6, 1>::Zero();
  if (imin >= 0) {
    Vector3f a1 = M_ev.eigenvectors().real().row(imin);
    Vector3f a2 = T*a1;
    ret.block<3,1>(0,0) = a1;
    ret.block<3,1>(3,0) = a2;
  }
  return std::make_tuple(ret, offset);
}

// Taken from OpenCV old code; see
// https://github.com/Itseez/opencv/commit/4eda1662aa01a184e0391a2bb2e557454de7eb86#diff-97c8133c3c171e64ea0df0db4abd033c
EllipseGeometry to_ellipse(const Conic& conic)
{
  using namespace Eigen;
  auto coef = std::get<0>(conic);

  float idet = coef(0)*coef(2) - coef(1)*coef(1)/4; // ac-b^2/4
  idet = idet > FLT_EPSILON ? 1.f/idet : 0;

  float scale = std::sqrt(idet/4);
  if (scale < FLT_EPSILON)
    throw std::domain_error("to_ellipse_2: singularity 1");

  coef *= scale;
  float aa = coef(0), bb = coef(1), cc = coef(2), dd = coef(3), ee = coef(4), ff = coef(5);

  const Vector2f c = Vector2f(-dd*cc + ee*bb/2, -aa*ee + dd*bb/2) * 2;

  // offset ellipse to (x0,y0)
  ff += aa*c(0)*c(0) + bb*c(0)*c(1) + cc*c(1)*c(1) + dd*c(0) + ee*c(1);
  if (std::fabs(ff) < FLT_EPSILON)
    throw std::domain_error("to_ellipse_2: singularity 2");

  Matrix2f S;
  S << aa, bb/2, bb/2, cc;
  S /= -ff;

  // SVs are sorted from largest to smallest
  JacobiSVD<Matrix2f> svd(S, ComputeFullU);
  const auto& vals = svd.singularValues();
  const auto& mat_u = svd.matrixU();

  Vector2f center = c + std::get<1>(conic);
  Vector2f radius = Vector2f(std::sqrt(1.f/vals(1)), std::sqrt(1.f/vals(0)));
  float angle = M_PI - std::atan2(mat_u(1,0), mat_u(0,0));
  return EllipseGeometry{center, radius, angle};
}
<|endoftext|>


<commit_before>/*
Author: 	Anfego
Date:		04/11/14
Class: 		CSCI 6430
Professor:	Dr. Buttler
University: MTSU
Desciption:
	This program is an implementation of a MPI tupple space
	Support for:
		PP_Init()
		PP_Put()
		PP_Get()
		PP_Reserve()
		PP_Finalize()

*/
#include <vector>          // stack
#include <utility>
#include <pthread.h>
#include <iostream>
#include <stack>

#include "/nfshome/rbutler/public/courses/pp6430/mpich3i/include/mpi.h"
#include "pp.h"
#include "lindaStuff.h"

using namespace std;

	struct pass_struct
	{
		int size;
		int num_types;
		vector<int> types;
		int local_index;
	}__attribute__ ((packed));

/*<sumary>
	</sumary>*/
lindaStuff lindaSpace;

/*<sumary>
    int num_user_types;
    Any valid integer can be a user type.
	Wildcards will be described below.
    int user_types[PP_MAX_USER_TYPES];
    int server_flag;  // I begin to execute server code if true
    Discussion:
	The user should do MPI_Init and MPI_Finalize.
	</sumary>*/
int PP_Init(int num_user_types, int * user_types, int * am_server_flag)
{
	int server = *am_server_flag;
	int my_inter_rank;
	int my_side_rank;
	int my_world_rank;
	int world_size;
	int my_side_size;
	int inter_size;
	int other_side_size;
	int other_side_leader;

	MPI_Comm_dup(MPI_COMM_WORLD, &(lindaSpace.WORLD_COMM_DUP));
	MPI_Comm_rank(lindaSpace.WORLD_COMM_DUP,&my_world_rank);
	MPI_Comm_size(lindaSpace.WORLD_COMM_DUP,&world_size);

	MPI_Comm_split(MPI_COMM_WORLD, *am_server_flag, 0,&(lindaSpace.MY_SIDE_COMM));
	MPI_Comm_rank(lindaSpace.MY_SIDE_COMM,&my_side_rank);
	MPI_Comm_size(lindaSpace.MY_SIDE_COMM,&my_side_size);

	char * work_unit_buf = (char *) malloc(work_unit_size);

	// store usefull information
	lindaSpace.my_world_rank = my_world_rank;
	lindaSpace.my_side_rank = my_side_rank;

	lindaSpace.world_size = world_size;
	lindaSpace.my_side_size = my_side_size;
	if (server ==0)
	{
		lindaSpace.other_side_leader = my_side_size; 		// assing as leader of servers the next
															// rank after app ranks.
	}
	else
	{
		lindaSpace.other_side_leader = 0; 					// Leader of app is Rank 0;
	}
	MPI_Intercomm_create(
		lindaSpace.MY_SIDE_COMM,
		0,
		lindaSpace.WORLD_COMM_DUP,
		lindaSpace.other_side_leader,
		666,
		&(lindaSpace.INTER_COMM));

	MPI_Comm_rank(lindaSpace.INTER_COMM,&my_inter_rank);
	MPI_Comm_size(lindaSpace.INTER_COMM,&inter_size);
	MPI_Comm_remote_size(lindaSpace.INTER_COMM,&other_side_size);
	lindaSpace.other_side_size = other_side_size;

	if(server == 0)
	{
		return PP_SUCCESS;
	}

	vector<int> uTypes;
	// create stack for user types
	int done = 0;
	int mpi_flag = 0;
	pass_struct put_struct;
	MPI_Status status;

	while(!done)
	{
		// checks if there is a "to finish"
		MPI_Iprobe(lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &mpi_flag, &status);
		if (mpi_flag == 1)		// if true there is a message, PP_Finalize
		{
			MPI_Recv(&done, 1, MPI_INT, lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
		}
		else if( mpi_flag == 2 )//received PUT
		{
			memset(put_struct, '\0', sizeof(put_struct) );

			MPI_Recv(&put_struct, 1, sizeof(put_struct), lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
			// if(type_rec == good rec) - receive
			resp = allocate(put_struct.type, put_struct.size);
			MPI_Send(&resp,1, MPI_INT, i, 666, lindaSpace.INTER_COMM);
			//get the data
			if (resp != PP_FAIL)
			{
				MPI_Recv(&put_struct, 1, sizeof(put_struct), lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
				resp = store();
				MPI_Send(&resp,1, MPI_INT, i, 666, lindaSpace.INTER_COMM);
			}
		}
		else if( mpi_flag == 3)//received reserve
		{
			MPI_Recv(&type_rec, 1, MPI_INT, lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
			resp = reserver(int &num_types, int type[], int &size);
		}
		else if( mpi_flag == 4)//received reserve
		{
			MPI_Recv(&type_rec, 1, MPI_INT, lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
			resp = reserver(int &num_types, int type[], int &size);
		}
	}
	printf("tuppleSpace Exit\n");

	return PP_SUCCESS;
}
/*<sumary>
	</sumary>*/

int PP_Finalize()
{
	MPI_Status status;
	//Send "To finish" signal
	int done = 1;
	int my_side_rank;
	int my_inter_rank;

	// wait until all app's get until this point
	MPI_Barrier(lindaSpace.MY_SIDE_COMM);
	if(lindaSpace.am_i_server() == false)
	{
		if(lindaSpace.my_side_rank == 0) 			// if Im rank 0 in app side do Bcast
		{
			// Sends to every server a "to finish" signal
			for(int i = 0; i < lindaSpace.other_side_size; i++)
			{
				MPI_Send(&done,1, MPI_INT, i, 666, lindaSpace.INTER_COMM);
			}
		}

	}
	// printf("Im out: %d\n",my_inter_rank);

	MPI_Barrier(lindaSpace.WORLD_COMM_DUP);			//Wait for all processes hit this point

	// free LindaSpace communicators
	MPI_Comm_free(&(lindaSpace.INTER_COMM));
	MPI_Comm_free(&(lindaSpace.MY_SIDE_COMM));
	MPI_Comm_free(&(lindaSpace.WORLD_COMM_DUP));
	if (lindaSpace.my_world_rank == 0)
	{
		printf("PP_Finalize = PP_SUCCESS\n");
	}
	return PP_SUCCESS;
}
/*<sumary>
	</sumary>*/

int PP_Put(int type, int size, void * buffer )
{
	int picked_server = random()%other_side_size;
	int resp = -1;

	pass_struct temp_buf;
	temp_buf.size = size;
	temp_buf.type = type;

	MPI_Send(&temp_buf,1, sizeof(temp_buf), picked_server, 666, lindaSpace.INTER_COMM);
	MPI_Recv(&resp, 1, MPI_INT, lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
	//because of using resp we do not care about status.
	//it may mean memory or network problem, we just send to the next random server
	if (resp != -1)
	{//then we feel very good and just send it
		MPI_Send(buffer,1, size, picked_server, 666, lindaSpace.INTER_COMM);
		resp = -1;
		MPI_Recv(&resp, 1, MPI_INT, lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
		if (resp == 0)
			return PP_SUCCESS;//else PP_FAIL
	}
	return PP_FAIL;
}
/*<sumary>
	</sumary>*/
int PP_Reserve(int& num_types, int types[], int &size, int& type, int& local_index )
{
	pass_struct temp_buf;
	int resp = -1;

	temp_buf.size = size;
	temp_buf.type = type;

	MPI_Send(&temp_buf,1, sizeof(temp_buf), picked_server, 666, lindaSpace.INTER_COMM);
	MPI_Recv(&resp, 1, MPI_INT, lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
	if(resp != -1)
	{
		return PP_SUCCESS;
	}
	else
		return NOT_FOUND;
}
/*<sumary>
	</sumary>*/

int PP_Get(handler)
{
	MPI_Send(&temp_buf,1, MPI_INT, picked_server, 666, lindaSpace.INTER_COMM);
	MPI_Recv(&put_struct, 1, sizeof(put_struct), lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);

	if (resp != -1)
	{
		size =(pass_struct)temp_buf.size;
		type =(pass_struct)temp_buf.type;
		local_index = (pass_struct)temp_buf.local_index;
		return PP_SUCCESS;
	}
	return FAIL;
}
/*<sumary>
	</sumary>*/

int PP_Set_problem_done()
{
	return PP_SUCCESS;
}
/*<sumary>
	</sumary>*/

int PP_Abort()
{
	return PP_SUCCESS;
}

<commit_msg>changes<commit_after>/*
Author: 	Anfego
Date:		04/11/14
Class: 		CSCI 6430
Professor:	Dr. Buttler
University: MTSU
Desciption:
	This program is an implementation of a MPI tupple space
	Support for:
		PP_Init()
		PP_Put()
		PP_Get()
		PP_Reserve()
		PP_Finalize()

*/
#include <vector>          // stack
#include <utility>
#include <pthread.h>
#include <iostream>
#include <stack>

#include "/nfshome/rbutler/public/courses/pp6430/mpich3i/include/mpi.h"
#include "pp.h"
#include "lindaStuff.h"

using namespace std;

	struct pass_struct
	{
		int size;
		int num_types;
		vector<int> types;
		int local_index;
	}__attribute__ ((packed));

/*<sumary>
	</sumary>*/
lindaStuff lindaSpace;

/*<sumary>
    int num_user_types;
    Any valid integer can be a user type.
	Wildcards will be described below.
    int user_types[PP_MAX_USER_TYPES];
    int server_flag;  // I begin to execute server code if true
    Discussion:
	The user should do MPI_Init and MPI_Finalize.
	</sumary>*/
int PP_Init(int num_user_types, int * user_types, int * am_server_flag)
{
	int server = *am_server_flag;
	int my_inter_rank;
	int my_side_rank;
	int my_world_rank;
	int world_size;
	int my_side_size;
	int inter_size;
	int other_side_size;
	int other_side_leader;

	MPI_Comm_dup(MPI_COMM_WORLD, &(lindaSpace.WORLD_COMM_DUP));
	MPI_Comm_rank(lindaSpace.WORLD_COMM_DUP,&my_world_rank);
	MPI_Comm_size(lindaSpace.WORLD_COMM_DUP,&world_size);

	MPI_Comm_split(MPI_COMM_WORLD, *am_server_flag, 0,&(lindaSpace.MY_SIDE_COMM));
	MPI_Comm_rank(lindaSpace.MY_SIDE_COMM,&my_side_rank);
	MPI_Comm_size(lindaSpace.MY_SIDE_COMM,&my_side_size);

	char * work_unit_buf = (char *) malloc(work_unit_size);

	// store usefull information
	lindaSpace.my_world_rank = my_world_rank;
	lindaSpace.my_side_rank = my_side_rank;

	lindaSpace.world_size = world_size;
	lindaSpace.my_side_size = my_side_size;
	if (server ==0)
	{
		lindaSpace.other_side_leader = my_side_size; 		// assing as leader of servers the next
															// rank after app ranks.
	}
	else
	{
		lindaSpace.other_side_leader = 0; 					// Leader of app is Rank 0;
	}
	MPI_Intercomm_create(
		lindaSpace.MY_SIDE_COMM,
		0,
		lindaSpace.WORLD_COMM_DUP,
		lindaSpace.other_side_leader,
		666,
		&(lindaSpace.INTER_COMM));

	MPI_Comm_rank(lindaSpace.INTER_COMM,&my_inter_rank);
	MPI_Comm_size(lindaSpace.INTER_COMM,&inter_size);
	MPI_Comm_remote_size(lindaSpace.INTER_COMM,&other_side_size);
	lindaSpace.other_side_size = other_side_size;

	if(server == 0)
	{
		return PP_SUCCESS;
	}

	vector<int> uTypes;
	// create stack for user types
	int done = 0;
	int mpi_flag = 0;
	pass_struct put_struct;
	MPI_Status status;

	while(!done)
	{
		// checks if there is a "to finish"
		MPI_Iprobe(lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &mpi_flag, &status);
		if (mpi_flag == 1)		// if true there is a message, PP_Finalize
		{
			MPI_Recv(&done, 1, MPI_INT, lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
		}
		else if( mpi_flag == 2 )//received PUT
		{
			memset(put_struct, '\0', sizeof(put_struct) );

			MPI_Recv(&put_struct, 1, sizeof(put_struct), lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
			// if(type_rec == good rec) - receive
			resp = allocate(put_struct.type, put_struct.size);
			MPI_Send(&resp,1, MPI_INT, i, 666, lindaSpace.INTER_COMM);
			//get the data
			if (resp != PP_FAIL)
			{
				MPI_Recv(&put_struct, 1, sizeof(put_struct), lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
				resp = store();
				MPI_Send(&resp,1, MPI_INT, i, 666, lindaSpace.INTER_COMM);
			}
		}
		else if( mpi_flag == 3)//received reserve
		{
			MPI_Recv(&type_rec, 1, MPI_INT, lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
			resp = reserver(int &num_types, int type[], int &size);
		}
		else if( mpi_flag == 4)//received reserve
		{
			MPI_Recv(&type_rec, 1, MPI_INT, lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
			resp = reserver(int &num_types, int type[], int &size);
		}
	}
	printf("tuppleSpace Exit\n");

	return PP_SUCCESS;
}
/*<sumary>
	</sumary>*/

int PP_Finalize()
{
	MPI_Status status;
	//Send "To finish" signal
	int done = 1;
	int my_side_rank;
	int my_inter_rank;

	// wait until all app's get until this point
	MPI_Barrier(lindaSpace.MY_SIDE_COMM);
	if(lindaSpace.am_i_server() == false)
	{
		if(lindaSpace.my_side_rank == 0) 			// if Im rank 0 in app side do Bcast
		{
			// Sends to every server a "to finish" signal
			for(int i = 0; i < lindaSpace.other_side_size; i++)
			{
				MPI_Send(&done,1, MPI_INT, i, 666, lindaSpace.INTER_COMM);
			}
		}

	}
	// printf("Im out: %d\n",my_inter_rank);

	MPI_Barrier(lindaSpace.WORLD_COMM_DUP);			//Wait for all processes hit this point

	// free LindaSpace communicators
	MPI_Comm_free(&(lindaSpace.INTER_COMM));
	MPI_Comm_free(&(lindaSpace.MY_SIDE_COMM));
	MPI_Comm_free(&(lindaSpace.WORLD_COMM_DUP));
	if (lindaSpace.my_world_rank == 0)
	{
		printf("PP_Finalize = PP_SUCCESS\n");
	}
	return PP_SUCCESS;
}
/*<sumary>
	</sumary>*/

int PP_Put(int type, int size, void * buffer )
{
	int picked_server = random()%other_side_size;
	int resp = -1;
	pass_struct temp_buf;

	temp_buf.size = size;
	temp_buf.types.push_back(type);

	MPI_Send(&temp_buf,1, sizeof(temp_buf), picked_server, 666, lindaSpace.INTER_COMM);
	MPI_Recv(&resp, 1, MPI_INT, lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
	//because of using resp we do not care about status.
	//it may mean memory or network problem, we just send to the next random server
	if (resp != -1)
	{//then we feel very good and just send it
		MPI_Send(buffer,1, size, picked_server, 666, lindaSpace.INTER_COMM);
		resp = -1;
		MPI_Recv(&resp, 1, MPI_INT, lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
		if (resp == 0)
			return PP_SUCCESS;//else PP_FAIL
	}
	return PP_FAIL;
}
/*<sumary>
	</sumary>*/
int PP_Reserve(int& num_types, int types[], int &size, int& type, int& local_index )
{
	pass_struct temp_buf;
	int resp = -1;

	temp_buf.size = size;
	for (int i = 0; i < num_types; ++i)
	{
		temp_buf.types.push_back(types[i]);
	}

	MPI_Send(&temp_buf,1, sizeof(temp_buf), picked_server, 666, lindaSpace.INTER_COMM);
	MPI_Recv(&resp, 1, MPI_INT, lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);
	if(resp != -1)
	{
		return PP_SUCCESS;
	}
	else
		return NOT_FOUND;
}
/*<sumary>
	</sumary>*/

int PP_Get(handler)
{
	MPI_Send(&temp_buf,1, MPI_INT, picked_server, 666, lindaSpace.INTER_COMM);
	MPI_Recv(&put_struct, 1, sizeof(put_struct), lindaSpace.other_side_leader, 666, lindaSpace.INTER_COMM, &status);

	if (resp != -1)
	{
		size =(pass_struct)temp_buf.size;
		type =(pass_struct)temp_buf.type;
		local_index = (pass_struct)temp_buf.local_index;
		return PP_SUCCESS;
	}
	return FAIL;
}
/*<sumary>
	</sumary>*/

int PP_Set_problem_done()
{
	return PP_SUCCESS;
}
/*<sumary>
	</sumary>*/

int PP_Abort()
{
	return PP_SUCCESS;
}

<|endoftext|>


<commit_before>#include "ledger.h"
#include "qif.h"
#include "datetime.h"
#include "error.h"
#include "util.h"

#include <cstring>

namespace ledger {

#define MAX_LINE 1024

static char         line[MAX_LINE + 1];
static std::string  path;
static unsigned int linenum;

static inline char * get_line(std::istream& in) {
  in.getline(line, MAX_LINE);
  int len = std::strlen(line);
  if (line[len - 1] == '\r')
    line[len - 1] = '\0';
  linenum++;
  return line;
}

bool qif_parser_t::test(std::istream& in) const
{
  char magic[sizeof(unsigned int) + 1];
  in.read(magic, sizeof(unsigned int));
  magic[sizeof(unsigned int)] = '\0';
  in.seekg(0);

  return (std::strcmp(magic, "!Typ") == 0 ||
	  std::strcmp(magic, "\n!Ty") == 0 ||
	  std::strcmp(magic, "\r\n!T") == 0);
}

unsigned int qif_parser_t::parse(std::istream&	     in,
				 journal_t *	     journal,
				 account_t *	     master,
				 const std::string * original_file)
{
  std::auto_ptr<entry_t>  entry;
  std::auto_ptr<amount_t> amount;
  transaction_t *	  xact;
  unsigned int            count;
  account_t *             misc = NULL;
  commodity_t *           def_commodity = NULL;

  entry.reset(new entry_t);
  xact = new transaction_t(master);
  entry->add_transaction(xact);

  path	  = journal->sources.back();
  linenum = 1;

  while (! in.eof()) {
    char c;
    in.get(c);
    switch (c) {
    case ' ':
    case '\t':
      if (peek_next_nonws(in) != '\n') {
	get_line(in);
	throw parse_error(path, linenum, "Line begins with whitespace");
      }
      // fall through...

    case '\n':
      linenum++;
    case '\r':                  // skip blank lines
      break;

    case '!':
      in >> line;

      // jww (2004-08-19): these types are not supported yet
      assert(std::strcmp(line, "Type:Invst") != 0 &&
	     std::strcmp(line, "Account") != 0 &&
	     std::strcmp(line, "Type:Cat") != 0 &&
	     std::strcmp(line, "Type:Class") != 0 &&
	     std::strcmp(line, "Type:Memorized") != 0);

      get_line(in);
      break;

    case 'D':
      in >> line;
      if (! parse_date(line, &entry->date))
	throw parse_error(path, linenum, "Failed to parse date");
      break;

    case 'T':
    case '$':
      in >> line;
      xact->amount.parse(line);
      if (! def_commodity)
	def_commodity = commodity_t::find_commodity("$", true);
	xact->amount.commodity = def_commodity;
      if (c == '$')
	xact->amount.negate();
      xact->cost = xact->amount;
      break;

    case 'C':
      if (in.peek() == '*') {
	in.get(c);
	entry->state = entry_t::CLEARED;
      }
      break;

    case 'N':
      if (std::isdigit(in.peek())) {
	in >> line;
	entry->code = line;
      }
      break;

    case 'P':
    case 'M':
    case 'L':
    case 'S':
    case 'E': {
      char b = c;
      int len;
      c = in.peek();
      if (! std::isspace(c) && c != '\n') {
	get_line(in);

	switch (b) {
	case 'P':
	  entry->payee = line;
	  break;

	case 'S':
	  xact = new transaction_t(NULL);
	  entry->add_transaction(xact);
	  // fall through...
	case 'L':
	  len = std::strlen(line);
	  if (line[len - 1] == ']')
	    line[len - 1] = '\0';
	  xact->account = journal->find_account(line[0] == '[' ?
						line + 1 : line);
	  break;

	case 'M':
	case 'E':
	  xact->note = line;
	  break;
	}
      }
      break;
    }

    case 'A':
      // jww (2004-08-19): these are ignored right now
      get_line(in);
      break;

    case '^':
      if (xact->account == master) {
	if (! misc)
	  misc = master->find_account("Miscellaneous");
	transaction_t * nxact = new transaction_t(misc);
	entry->add_transaction(nxact);
	nxact->amount = nxact->cost = - xact->amount;
      }

      if (journal->add_entry(entry.release()))
	count++;

      entry.reset(new entry_t);
      xact = new transaction_t(master);
      entry->add_transaction(xact);
      break;
    }
  }

  return count;
}

} // namespace ledger
<commit_msg>quick fix<commit_after>#include "ledger.h"
#include "qif.h"
#include "datetime.h"
#include "error.h"
#include "util.h"

#include <cstring>

namespace ledger {

#define MAX_LINE 1024

static char         line[MAX_LINE + 1];
static std::string  path;
static unsigned int linenum;

static inline char * get_line(std::istream& in) {
  in.getline(line, MAX_LINE);
  int len = std::strlen(line);
  if (line[len - 1] == '\r')
    line[len - 1] = '\0';
  linenum++;
  return line;
}

bool qif_parser_t::test(std::istream& in) const
{
  char magic[sizeof(unsigned int) + 1];
  in.read(magic, sizeof(unsigned int));
  magic[sizeof(unsigned int)] = '\0';
  in.seekg(0);

  return (std::strcmp(magic, "!Typ") == 0 ||
	  std::strcmp(magic, "\n!Ty") == 0 ||
	  std::strcmp(magic, "\r\n!T") == 0);
}

unsigned int qif_parser_t::parse(std::istream&	     in,
				 journal_t *	     journal,
				 account_t *	     master,
				 const std::string * original_file)
{
  std::auto_ptr<entry_t>  entry;
  std::auto_ptr<amount_t> amount;
  transaction_t *	  xact;
  unsigned int            count;
  account_t *             misc = NULL;
  commodity_t *           def_commodity = NULL;

  entry.reset(new entry_t);
  xact = new transaction_t(master);
  entry->add_transaction(xact);

  path	  = journal->sources.back();
  linenum = 1;

  while (! in.eof()) {
    char c;
    in.get(c);
    switch (c) {
    case ' ':
    case '\t':
      if (peek_next_nonws(in) != '\n') {
	get_line(in);
	throw parse_error(path, linenum, "Line begins with whitespace");
      }
      // fall through...

    case '\n':
      linenum++;
    case '\r':                  // skip blank lines
      break;

    case '!':
      in >> line;

      // jww (2004-08-19): these types are not supported yet
      assert(std::strcmp(line, "Type:Invst") != 0 &&
	     std::strcmp(line, "Account") != 0 &&
	     std::strcmp(line, "Type:Cat") != 0 &&
	     std::strcmp(line, "Type:Class") != 0 &&
	     std::strcmp(line, "Type:Memorized") != 0);

      get_line(in);
      break;

    case 'D':
      in >> line;
      if (! parse_date(line, &entry->date))
	throw parse_error(path, linenum, "Failed to parse date");
      break;

    case 'T':
    case '$':
      in >> line;
      xact->amount.parse(line);
      if (! def_commodity)
	def_commodity = commodity_t::find_commodity("$", true);
	xact->amount.commodity = def_commodity;
      if (c == '$')
	xact->amount.negate();
      xact->cost = xact->amount;
      break;

    case 'C':
      if (in.peek() == '*') {
	in.get(c);
	entry->state = entry_t::CLEARED;
      }
      break;

    case 'N':
      if (std::isdigit(in.peek())) {
	in >> line;
	entry->code = line;
      }
      break;

    case 'P':
    case 'M':
    case 'L':
    case 'S':
    case 'E': {
      char b = c;
      int len;
      c = in.peek();
      if (! std::isspace(c) && c != '\n') {
	get_line(in);

	switch (b) {
	case 'P':
	  entry->payee = line;
	  break;

	case 'S':
	  xact = new transaction_t(NULL);
	  entry->add_transaction(xact);
	  // fall through...
	case 'L':
	  len = std::strlen(line);
	  if (line[len - 1] == ']')
	    line[len - 1] = '\0';
	  xact->account = journal->find_account(line[0] == '[' ?
						line + 1 : line);
	  break;

	case 'M':
	case 'E':
	  xact->note = line;
	  break;
	}
      }
      break;
    }

    case 'A':
      // jww (2004-08-19): these are ignored right now
      get_line(in);
      break;

    case '^':
      if (xact->account == master) {
	if (! misc)
	  misc = journal->find_account("Miscellaneous");
	transaction_t * nxact = new transaction_t(misc);
	entry->add_transaction(nxact);
	nxact->amount = nxact->cost = - xact->amount;
      }

      if (journal->add_entry(entry.release()))
	count++;

      entry.reset(new entry_t);
      xact = new transaction_t(master);
      entry->add_transaction(xact);
      break;
    }
  }

  return count;
}

} // namespace ledger
<|endoftext|>


<commit_before>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/shell/shell_devtools_frontend.h"

#include "base/command_line.h"
#include "base/path_service.h"
#include "content/public/browser/devtools_http_handler.h"
#include "content/public/browser/devtools_manager.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h"
#include "content/public/common/content_client.h"
#include "content/shell/shell.h"
#include "content/shell/shell_browser_context.h"
#include "content/shell/shell_browser_main_parts.h"
#include "content/shell/shell_content_browser_client.h"
#include "content/shell/shell_devtools_delegate.h"
#include "content/shell/shell_switches.h"
#include "net/base/net_util.h"

namespace content {

namespace {

// DevTools frontend path for inspector LayoutTests.
GURL GetDevToolsPathAsURL() {
  base::FilePath dir_exe;
  if (!PathService::Get(base::DIR_EXE, &dir_exe)) {
    NOTREACHED();
    return GURL();
  }
#if defined(OS_MACOSX)
  dir_exe = dir_exe.AppendASCII("../../..");
#endif
  base::FilePath dev_tools_path = dir_exe.AppendASCII(
      "resources/inspector/devtools.html");
  return net::FilePathToFileURL(dev_tools_path);
}

}  // namespace

// static
ShellDevToolsFrontend* ShellDevToolsFrontend::Show(
    WebContents* inspected_contents) {
  Shell* shell = Shell::CreateNewWindow(inspected_contents->GetBrowserContext(),
                                        GURL(),
                                        NULL,
                                        MSG_ROUTING_NONE,
                                        gfx::Size());
  ShellDevToolsFrontend* devtools_frontend = new ShellDevToolsFrontend(
      shell,
      DevToolsAgentHost::GetFor(inspected_contents->GetRenderViewHost()));

  ShellContentBrowserClient* browser_client =
      static_cast<ShellContentBrowserClient*>(
          GetContentClient()->browser());
  ShellDevToolsDelegate* delegate =
      browser_client->shell_browser_main_parts()->devtools_delegate();
  if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree))
    shell->LoadURL(GetDevToolsPathAsURL());
  else
    shell->LoadURL(delegate->devtools_http_handler()->GetFrontendURL(NULL));

  return devtools_frontend;
}

void ShellDevToolsFrontend::Focus() {
  web_contents()->GetView()->Focus();
}

void ShellDevToolsFrontend::Close() {
  frontend_shell_->Close();
}

ShellDevToolsFrontend::ShellDevToolsFrontend(Shell* frontend_shell,
                                             DevToolsAgentHost* agent_host)
    : WebContentsObserver(frontend_shell->web_contents()),
      frontend_shell_(frontend_shell),
      agent_host_(agent_host) {
  frontend_host_.reset(
      DevToolsClientHost::CreateDevToolsFrontendHost(web_contents(), this));
}

ShellDevToolsFrontend::~ShellDevToolsFrontend() {
}

void ShellDevToolsFrontend::RenderViewCreated(
    RenderViewHost* render_view_host) {
  DevToolsClientHost::SetupDevToolsFrontendClient(
      web_contents()->GetRenderViewHost());
  DevToolsManager* manager = DevToolsManager::GetInstance();
  manager->RegisterDevToolsClientHostFor(agent_host_.get(),
                                         frontend_host_.get());
}

void ShellDevToolsFrontend::WebContentsDestroyed(WebContents* web_contents) {
  DevToolsManager::GetInstance()->ClientHostClosing(frontend_host_.get());
  delete this;
}

void ShellDevToolsFrontend::InspectedContentsClosing() {
  frontend_shell_->Close();
}

}  // namespace content
<commit_msg>[content shell] fix inspector layout tests on mac<commit_after>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/shell/shell_devtools_frontend.h"

#include "base/command_line.h"
#include "base/path_service.h"
#include "content/public/browser/devtools_http_handler.h"
#include "content/public/browser/devtools_manager.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h"
#include "content/public/common/content_client.h"
#include "content/shell/shell.h"
#include "content/shell/shell_browser_context.h"
#include "content/shell/shell_browser_main_parts.h"
#include "content/shell/shell_content_browser_client.h"
#include "content/shell/shell_devtools_delegate.h"
#include "content/shell/shell_switches.h"
#include "net/base/net_util.h"

namespace content {

namespace {

// DevTools frontend path for inspector LayoutTests.
GURL GetDevToolsPathAsURL() {
  base::FilePath dir_exe;
  if (!PathService::Get(base::DIR_EXE, &dir_exe)) {
    NOTREACHED();
    return GURL();
  }
#if defined(OS_MACOSX)
  // On Mac, the executable is in out/Release/Content
  // Shell.app/Frameworks/Content Shell Helper.app/Contents/MacOS/Content. We
  // need to go up 6 directories to get to out/Release.
    Shell Helper
  dir_exe = dir_exe.AppendASCII("../../../../../..");
#endif
  base::FilePath dev_tools_path = dir_exe.AppendASCII(
      "resources/inspector/devtools.html");
  return net::FilePathToFileURL(dev_tools_path);
}

}  // namespace

// static
ShellDevToolsFrontend* ShellDevToolsFrontend::Show(
    WebContents* inspected_contents) {
  Shell* shell = Shell::CreateNewWindow(inspected_contents->GetBrowserContext(),
                                        GURL(),
                                        NULL,
                                        MSG_ROUTING_NONE,
                                        gfx::Size());
  ShellDevToolsFrontend* devtools_frontend = new ShellDevToolsFrontend(
      shell,
      DevToolsAgentHost::GetFor(inspected_contents->GetRenderViewHost()));

  ShellContentBrowserClient* browser_client =
      static_cast<ShellContentBrowserClient*>(
          GetContentClient()->browser());
  ShellDevToolsDelegate* delegate =
      browser_client->shell_browser_main_parts()->devtools_delegate();
  if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree))
    shell->LoadURL(GetDevToolsPathAsURL());
  else
    shell->LoadURL(delegate->devtools_http_handler()->GetFrontendURL(NULL));

  return devtools_frontend;
}

void ShellDevToolsFrontend::Focus() {
  web_contents()->GetView()->Focus();
}

void ShellDevToolsFrontend::Close() {
  frontend_shell_->Close();
}

ShellDevToolsFrontend::ShellDevToolsFrontend(Shell* frontend_shell,
                                             DevToolsAgentHost* agent_host)
    : WebContentsObserver(frontend_shell->web_contents()),
      frontend_shell_(frontend_shell),
      agent_host_(agent_host) {
  frontend_host_.reset(
      DevToolsClientHost::CreateDevToolsFrontendHost(web_contents(), this));
}

ShellDevToolsFrontend::~ShellDevToolsFrontend() {
}

void ShellDevToolsFrontend::RenderViewCreated(
    RenderViewHost* render_view_host) {
  DevToolsClientHost::SetupDevToolsFrontendClient(
      web_contents()->GetRenderViewHost());
  DevToolsManager* manager = DevToolsManager::GetInstance();
  manager->RegisterDevToolsClientHostFor(agent_host_.get(),
                                         frontend_host_.get());
}

void ShellDevToolsFrontend::WebContentsDestroyed(WebContents* web_contents) {
  DevToolsManager::GetInstance()->ClientHostClosing(frontend_host_.get());
  delete this;
}

void ShellDevToolsFrontend::InspectedContentsClosing() {
  frontend_shell_->Close();
}

}  // namespace content
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(XALAN_ELEMNUMBER_HEADER_GUARD)
#define XALAN_ELEMNUMBER_HEADER_GUARD

/**
 * $Id$
 *
 * $State$
 *
 * @author Myriam Midy (Myriam_Midy @lotus.com
 */

// Base include file.  Must be first.
#include "XSLTDefinitions.hpp"

// Base class header file.
#include "ElemTemplateElement.hpp"

// Just locale.h in G++
#if ! defined(__GNUC__)
#include <locale>
#endif

#include <dom/DOMString.hpp>

#include "DecimalToRoman.hpp"

class NumberFormat;
class QName;
class XPath;
class XPathExecutionContext;

class ElemNumber: public ElemTemplateElement
{
public:

#if defined(XALAN_NO_NAMESPACES)
#     define XALAN_STD
#else
#     define XALAN_STD std::
#endif
	typedef XALAN_STD vector<int> IntArrayType;
	typedef XALAN_STD locale LocaleType;
#undef XALAN_STD

	/**
	 * Construct an object corresponding to an "xsl:number" element
	 *
	 * @param constructionContext context for construction of object
	 * @param stylesheetTree      stylesheet containing element
	 * @param name                name of element
	 * @param atts                list of attributes for element
	 * @param lineNumber				line number in document
	 * @param columnNumber			column number in document
	 */
	ElemNumber(
			StylesheetConstructionContext&	constructionContext,
			Stylesheet&						stylesheetTree,
			const DOMString&				name,
			const AttributeList&			atts,
			int								lineNumber,
			int								columnNumber);

	// These methods are inherited from ElemTemplateElement ...

	virtual int
	getXSLToken() const;

	virtual void
	execute(
			StylesheetExecutionContext&		executionContext,
			const DOM_Node&					sourceTree,
			const DOM_Node&					sourceNode,
			const QName&					mode) const;

	virtual NodeImpl*
	appendChild(NodeImpl*	newChild);

protected:

	/**
	 * Given a 'from' pattern (ala xsl:number), a match pattern
	 * and a context, find the first ancestor that matches the
	 * pattern (including the context handed in).
	 * @param matchPatternString The match pattern.
	 * @param node The node that "." expresses.
	 * @param namespaceContext The context in which namespaces in the
	 * queries are supposed to be expanded.
	 */
	DOM_Node
	findAncestor(
			StylesheetExecutionContext&		executionContext,
			const XPath*					fromMatchPattern,
			const XPath*					countMatchPattern,
			const DOM_Node&					context,
			const DOM_Element&				namespaceContext) const;

	  /**
	   * Given a 'from' pattern (ala xsl:number), a match pattern
	   * and a context, find the first ancestor that matches the
	   * pattern (including the context handed in).
	   * @param matchPatternString The match pattern.
	   * @param node The node that "." expresses.
	   * @param namespaceContext The context in which namespaces in the
	   * queries are supposed to be expanded.
	   */
	DOM_Node findPrecedingOrAncestorOrSelf(
			StylesheetExecutionContext&		executionContext,
			const XPath*					fromMatchPattern,
			const XPath*					countMatchPattern,
			const DOM_Node&					context,
			const DOM_Element&				namespaceContext) const;

	/**
	 * Get the count match pattern, or a default value.
	 */
	const XPath*
	getCountMatchPattern(
			StylesheetExecutionContext&		executionContext,
			const DOM_Node&					contextNode) const;

	/**
	 * Given an XML source node, get the count according to the
	 * parameters set up by the xsl:number attributes.
	 */
	DOMString
	getCountString(
			StylesheetExecutionContext&		executionContext,
			const DOM_Node&					sourceTree,
			const DOM_Node&					sourceNode) const;

	/**
	 * from any position in the tree, return the
	 * next node in the tree, assuming preorder
	 * traversal preceded, or null if at the end.
	 */
	static DOM_Node
	getNextInTree(
			const DOM_Node&		pos,
			const DOM_Node&		from);

	/**
	 * Get a number that represents a node based on the
	 * position of that node among within the document tree,
	 * and taking into account the count and from patterns as
	 * specified in the XSL specification.
	 * @param fromMatchPattern if non-null, where to
	 * start counting from.
	 * @param countMatchPattern if non-null, count only nodes
	 * that match this pattern.
	 * @param target count this node and preceding nodes.
	 * @return A number that counts target and preceding
	 * nodes that qualify.
	 */
	int
	getNumberInTree(
			XPathExecutionContext&	executionContext,
			const XPath*			countMatchPattern,
			const DOM_Node&			pos,
			const DOM_Node&			from,
			const DOM_Node&			target,
			int						countFrom) const;

	/**
	 * Get a number that represents a node based on the
	 * position of that node among it's siblings, and
	 * taking into account the count and from patterns.
	 * @param fromMatchPattern if non-null, where to
	 * start counting from.
	 * @param countMatchPattern if non-null, count only nodes
	 * that match this pattern.
	 * @param target count this node and preceding siblings.
	 * @return A number that counts target and preceding
	 * siblings that qualify.
	 */
	int
	getSiblingNumber(
			StylesheetExecutionContext&		executionContext,
			const XPath*					countMatchPattern,
			const DOM_Node&					target) const;

	/**
	 * Count the ancestors, up to the root, that match the
	 * pattern.
	 * @param patterns if non-null, count only nodes
	 * that match this pattern, if null count all ancestors.
	 * @param node Count this node and it's ancestors.
	 * @return The number of ancestors that match the pattern.
	 */
	int
	countMatchingAncestors(
			StylesheetExecutionContext&		executionContext,
			const XPath*					patterns,
			const DOM_Node&					node) const;

	/**
	 * Climb up the ancestor tree, collecting sibling position
	 * numbers (as modified by the fromMatchPattern and
	 * countMatchPattern patterns).
	 * @param fromMatchPattern if non-null, where to
	 * start counting from in each sibling list.
	 * @param countMatchPattern if non-null, count only ancestors
	 * and siblings that match this pattern.
	 * @param node count this node and ancestors that match the countMatchPattern.
	 * @return An array of ints of length that matches exactly the number
	 * of ancestors that match countMatchPattern.
	 * @exception XSLProcessorException thrown if the active ProblemListener and XMLParserLiaison decide
	 * the error condition is severe enough to halt processing.
	 */
	IntArrayType
	getAncestorNumbers(
			StylesheetExecutionContext&		executionContext,
			const XPath*					fromMatchPattern,
			const XPath*					countMatchPattern,
			const DOM_Node&					node) const;

#if ! defined(__GNUC__)
	/**
	 * Get the locale we should be using.
	 */
	LocaleType
	getLocale(
			StylesheetExecutionContext&		executionContext,
			const DOM_Node&					contextNode) const;
#endif

	NumberFormat*
	getNumberFormatter(
			StylesheetExecutionContext&		executionContext,
			const DOM_Node&					contextNode) const;

	/**
	 * Format a vector of numbers into a formatted string.
	 * @param xslNumberElement Element that takes %conversion-atts; attributes.
	 * @param list Array of one or more integer numbers.
	 * @return String that represents list according to
	 * %conversion-atts; attributes.
	 * TODO: Optimize formatNumberList so that it caches the last count and
	 * reuses that info for the next count.
	 */
	DOMString
	formatNumberList(
			StylesheetExecutionContext&		executionContext,
			const IntArrayType&				theList,
			const DOM_Node&					contextNode) const;

	/**
	 * Convert a long integer into alphabetic counting, in other words
	 * count using the sequence A B C ... Z AA AB AC.... etc.
	 * @param val Value to convert -- must be greater than zero.
	 * @param table a table containing one character for each digit in the radix
	 * @return String representing alpha count of number.
	 * @see XSLTEngineImpl#DecimalToRoman
	 *
	 * Note that the radix of the conversion is inferred from the size
	 * of the table.
	 */
	static DOMString
	int2alphaCount(
			int					val,
			const DOMString&	table);

	/**
	 * Convert a long integer into roman numerals.
	 * @param val Value to convert.
	 * @param prefixesAreOK true_ to enable prefix notation (e.g. 4 = "IV"),
	 * false_ to disable prefix notation (e.g. 4 = "IIII").
	 * @return Roman numeral string.
	 * @see DecimalToRoman
	 * @see m_romanConvertTable
	 */
	static DOMString
	long2roman(
			long	val,
			bool	prefixesAreOK);

private:

	/*
	 * Get Formatted number
	 */
	DOMString
	getFormattedNumber(
			StylesheetExecutionContext&		executionContext,
			const DOM_Node&					contextNode,
			XMLCh							numberType,
			int								numberWidth,
			int								listElement) const;

	const XPath*	m_countMatchPattern;
	const XPath*	m_fromMatchPattern;
	const XPath*	m_valueExpr;

	int				m_level; // = Constants.NUMBERLEVEL_SINGLE;

	DOMString		m_format_avt;
	DOMString		m_lang_avt;
	DOMString		m_lettervalue_avt;
	DOMString		m_groupingSeparator_avt;
	DOMString		m_groupingSize_avt;

	/**
	* Chars for converting integers into alpha counts.
	* @see XSLTEngineImpl#int2alphaCount
	*/
	static const DOMString			s_alphaCountTable;

	/**
	 * Table to help in converting decimals to roman numerals.
	 * @see XSLTEngineImpl#DecimalToRoman
	 * @see XSLTEngineImpl#long2roman
	 */
	static const DecimalToRoman		s_romanConvertTable[];
};

#endif	// XALAN_ELEMNUMBER_HEADER_GUARD
<commit_msg>Changes for linux<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(XALAN_ELEMNUMBER_HEADER_GUARD)
#define XALAN_ELEMNUMBER_HEADER_GUARD

/**
 * $Id$
 *
 * $State$
 *
 * @author Myriam Midy (Myriam_Midy @lotus.com
 */

// Base include file.  Must be first.
#include "XSLTDefinitions.hpp"

// Base class header file.
#include "ElemTemplateElement.hpp"

// Just locale.h in G++
#if ! defined(__GNUC__)
#include <locale>
#endif

#include <dom/DOMString.hpp>

#include "DecimalToRoman.hpp"

class NumberFormat;
class QName;
class XPath;
class XPathExecutionContext;

class ElemNumber: public ElemTemplateElement
{
public:

#if defined(XALAN_NO_NAMESPACES)
#     define XALAN_STD
#else
#     define XALAN_STD std::
#endif
	typedef XALAN_STD vector<int> IntArrayType;
#	if ! defined(__GNUC__)
		typedef XALAN_STD locale LocaleType;
#	endif
#undef XALAN_STD

	/**
	 * Construct an object corresponding to an "xsl:number" element
	 *
	 * @param constructionContext context for construction of object
	 * @param stylesheetTree      stylesheet containing element
	 * @param name                name of element
	 * @param atts                list of attributes for element
	 * @param lineNumber				line number in document
	 * @param columnNumber			column number in document
	 */
	ElemNumber(
			StylesheetConstructionContext&	constructionContext,
			Stylesheet&						stylesheetTree,
			const DOMString&				name,
			const AttributeList&			atts,
			int								lineNumber,
			int								columnNumber);

	// These methods are inherited from ElemTemplateElement ...

	virtual int
	getXSLToken() const;

	virtual void
	execute(
			StylesheetExecutionContext&		executionContext,
			const DOM_Node&					sourceTree,
			const DOM_Node&					sourceNode,
			const QName&					mode) const;

	virtual NodeImpl*
	appendChild(NodeImpl*	newChild);

protected:

	/**
	 * Given a 'from' pattern (ala xsl:number), a match pattern
	 * and a context, find the first ancestor that matches the
	 * pattern (including the context handed in).
	 * @param matchPatternString The match pattern.
	 * @param node The node that "." expresses.
	 * @param namespaceContext The context in which namespaces in the
	 * queries are supposed to be expanded.
	 */
	DOM_Node
	findAncestor(
			StylesheetExecutionContext&		executionContext,
			const XPath*					fromMatchPattern,
			const XPath*					countMatchPattern,
			const DOM_Node&					context,
			const DOM_Element&				namespaceContext) const;

	  /**
	   * Given a 'from' pattern (ala xsl:number), a match pattern
	   * and a context, find the first ancestor that matches the
	   * pattern (including the context handed in).
	   * @param matchPatternString The match pattern.
	   * @param node The node that "." expresses.
	   * @param namespaceContext The context in which namespaces in the
	   * queries are supposed to be expanded.
	   */
	DOM_Node findPrecedingOrAncestorOrSelf(
			StylesheetExecutionContext&		executionContext,
			const XPath*					fromMatchPattern,
			const XPath*					countMatchPattern,
			const DOM_Node&					context,
			const DOM_Element&				namespaceContext) const;

	/**
	 * Get the count match pattern, or a default value.
	 */
	const XPath*
	getCountMatchPattern(
			StylesheetExecutionContext&		executionContext,
			const DOM_Node&					contextNode) const;

	/**
	 * Given an XML source node, get the count according to the
	 * parameters set up by the xsl:number attributes.
	 */
	DOMString
	getCountString(
			StylesheetExecutionContext&		executionContext,
			const DOM_Node&					sourceTree,
			const DOM_Node&					sourceNode) const;

	/**
	 * from any position in the tree, return the
	 * next node in the tree, assuming preorder
	 * traversal preceded, or null if at the end.
	 */
	static DOM_Node
	getNextInTree(
			const DOM_Node&		pos,
			const DOM_Node&		from);

	/**
	 * Get a number that represents a node based on the
	 * position of that node among within the document tree,
	 * and taking into account the count and from patterns as
	 * specified in the XSL specification.
	 * @param fromMatchPattern if non-null, where to
	 * start counting from.
	 * @param countMatchPattern if non-null, count only nodes
	 * that match this pattern.
	 * @param target count this node and preceding nodes.
	 * @return A number that counts target and preceding
	 * nodes that qualify.
	 */
	int
	getNumberInTree(
			XPathExecutionContext&	executionContext,
			const XPath*			countMatchPattern,
			const DOM_Node&			pos,
			const DOM_Node&			from,
			const DOM_Node&			target,
			int						countFrom) const;

	/**
	 * Get a number that represents a node based on the
	 * position of that node among it's siblings, and
	 * taking into account the count and from patterns.
	 * @param fromMatchPattern if non-null, where to
	 * start counting from.
	 * @param countMatchPattern if non-null, count only nodes
	 * that match this pattern.
	 * @param target count this node and preceding siblings.
	 * @return A number that counts target and preceding
	 * siblings that qualify.
	 */
	int
	getSiblingNumber(
			StylesheetExecutionContext&		executionContext,
			const XPath*					countMatchPattern,
			const DOM_Node&					target) const;

	/**
	 * Count the ancestors, up to the root, that match the
	 * pattern.
	 * @param patterns if non-null, count only nodes
	 * that match this pattern, if null count all ancestors.
	 * @param node Count this node and it's ancestors.
	 * @return The number of ancestors that match the pattern.
	 */
	int
	countMatchingAncestors(
			StylesheetExecutionContext&		executionContext,
			const XPath*					patterns,
			const DOM_Node&					node) const;

	/**
	 * Climb up the ancestor tree, collecting sibling position
	 * numbers (as modified by the fromMatchPattern and
	 * countMatchPattern patterns).
	 * @param fromMatchPattern if non-null, where to
	 * start counting from in each sibling list.
	 * @param countMatchPattern if non-null, count only ancestors
	 * and siblings that match this pattern.
	 * @param node count this node and ancestors that match the countMatchPattern.
	 * @return An array of ints of length that matches exactly the number
	 * of ancestors that match countMatchPattern.
	 * @exception XSLProcessorException thrown if the active ProblemListener and XMLParserLiaison decide
	 * the error condition is severe enough to halt processing.
	 */
	IntArrayType
	getAncestorNumbers(
			StylesheetExecutionContext&		executionContext,
			const XPath*					fromMatchPattern,
			const XPath*					countMatchPattern,
			const DOM_Node&					node) const;

#if ! defined(__GNUC__)
	/**
	 * Get the locale we should be using.
	 */
	LocaleType
	getLocale(
			StylesheetExecutionContext&		executionContext,
			const DOM_Node&					contextNode) const;
#endif

	NumberFormat*
	getNumberFormatter(
			StylesheetExecutionContext&		executionContext,
			const DOM_Node&					contextNode) const;

	/**
	 * Format a vector of numbers into a formatted string.
	 * @param xslNumberElement Element that takes %conversion-atts; attributes.
	 * @param list Array of one or more integer numbers.
	 * @return String that represents list according to
	 * %conversion-atts; attributes.
	 * TODO: Optimize formatNumberList so that it caches the last count and
	 * reuses that info for the next count.
	 */
	DOMString
	formatNumberList(
			StylesheetExecutionContext&		executionContext,
			const IntArrayType&				theList,
			const DOM_Node&					contextNode) const;

	/**
	 * Convert a long integer into alphabetic counting, in other words
	 * count using the sequence A B C ... Z AA AB AC.... etc.
	 * @param val Value to convert -- must be greater than zero.
	 * @param table a table containing one character for each digit in the radix
	 * @return String representing alpha count of number.
	 * @see XSLTEngineImpl#DecimalToRoman
	 *
	 * Note that the radix of the conversion is inferred from the size
	 * of the table.
	 */
	static DOMString
	int2alphaCount(
			int					val,
			const DOMString&	table);

	/**
	 * Convert a long integer into roman numerals.
	 * @param val Value to convert.
	 * @param prefixesAreOK true_ to enable prefix notation (e.g. 4 = "IV"),
	 * false_ to disable prefix notation (e.g. 4 = "IIII").
	 * @return Roman numeral string.
	 * @see DecimalToRoman
	 * @see m_romanConvertTable
	 */
	static DOMString
	long2roman(
			long	val,
			bool	prefixesAreOK);

private:

	/*
	 * Get Formatted number
	 */
	DOMString
	getFormattedNumber(
			StylesheetExecutionContext&		executionContext,
			const DOM_Node&					contextNode,
			XMLCh							numberType,
			int								numberWidth,
			int								listElement) const;

	const XPath*	m_countMatchPattern;
	const XPath*	m_fromMatchPattern;
	const XPath*	m_valueExpr;

	int				m_level; // = Constants.NUMBERLEVEL_SINGLE;

	DOMString		m_format_avt;
	DOMString		m_lang_avt;
	DOMString		m_lettervalue_avt;
	DOMString		m_groupingSeparator_avt;
	DOMString		m_groupingSize_avt;

	/**
	* Chars for converting integers into alpha counts.
	* @see XSLTEngineImpl#int2alphaCount
	*/
	static const DOMString			s_alphaCountTable;

	/**
	 * Table to help in converting decimals to roman numerals.
	 * @see XSLTEngineImpl#DecimalToRoman
	 * @see XSLTEngineImpl#long2roman
	 */
	static const DecimalToRoman		s_romanConvertTable[];
};

#endif	// XALAN_ELEMNUMBER_HEADER_GUARD
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <deque>

#include "catch.hpp"

#include "dll/dense_layer.hpp"
#include "dll/dbn.hpp"
#include "dll/dense_stochastic_gradient_descent.hpp"

#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"

namespace {

template<typename Dataset>
void mnist_scale(Dataset& dataset){
    for(auto& image : dataset.training_images){
        for(auto& pixel : image){
            pixel *= (1.0 / 256.0);
        }
    }

    for(auto& image : dataset.test_images){
        for(auto& pixel : image){
            pixel *= (1.0 / 256.0);
        }
    }
}

} //end of anonymous namespace

TEST_CASE( "dense/sgd/1", "[dense][dbn][mnist][sgd]" ) {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::dense_desc<28 * 28, 100>::layer_t,
            dll::dense_desc<100, 10>::layer_t
        >,
        dll::trainer<dll::dense_sgd_trainer>
    >::dbn_t dbn_t;

    auto dataset = mnist::read_dataset<std::vector, std::vector, double>(1000);
    REQUIRE(!dataset.training_images.empty());

    auto dbn = std::make_unique<dbn_t>();

    dbn->learning_rate = 0.05;

    auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100, 10);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.2);
}

TEST_CASE( "dense/sgd/2", "[dense][dbn][mnist][sgd]" ) {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::dense_desc<28 * 28, 100, dll::activation<dll::function::TANH>>::layer_t,
            dll::dense_desc<100, 10, dll::activation<dll::function::TANH>>::layer_t
        >,
        dll::trainer<dll::dense_sgd_trainer>
    >::dbn_t dbn_t;

    auto dataset = mnist::read_dataset<std::vector, std::vector, double>(1000);
    REQUIRE(!dataset.training_images.empty());

    mnist_scale(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->learning_rate = 0.05;

    auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100, 10);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.2);
}

TEST_CASE( "dense/sgd/3", "[dense][dbn][mnist][sgd]" ) {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::dense_desc<28 * 28, 100>::layer_t,
            dll::dense_desc<100, 10>::layer_t
        >
        , dll::momentum
        , dll::trainer<dll::dense_sgd_trainer>
    >::dbn_t dbn_t;

    auto dataset = mnist::read_dataset<std::vector, std::vector, double>(1000);
    REQUIRE(!dataset.training_images.empty());

    mnist_scale(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->initial_momentum = 0.9;
    dbn->final_momentum = 0.9;
    dbn->learning_rate = 0.01;

    auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100, 10);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.2);
}

TEST_CASE( "dense/sgd/4", "[dense][dbn][mnist][sgd]" ) {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::dense_desc<28 * 28, 100>::layer_t,
            dll::dense_desc<100, 10>::layer_t
        >
        , dll::momentum
        , dll::weight_decay<>
        , dll::trainer<dll::dense_sgd_trainer>
    >::dbn_t dbn_t;

    auto dataset = mnist::read_dataset<std::vector, std::vector, double>(1000);
    REQUIRE(!dataset.training_images.empty());

    mnist_scale(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->initial_momentum = 0.9;
    dbn->final_momentum = 0.9;
    dbn->learning_rate = 0.01;

    auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100, 10);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.2);
}
<commit_msg>New test<commit_after>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <deque>

#include "catch.hpp"

#include "dll/dense_layer.hpp"
#include "dll/dbn.hpp"
#include "dll/dense_stochastic_gradient_descent.hpp"

#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"

namespace {

template<typename Dataset>
void mnist_scale(Dataset& dataset){
    for(auto& image : dataset.training_images){
        for(auto& pixel : image){
            pixel *= (1.0 / 256.0);
        }
    }

    for(auto& image : dataset.test_images){
        for(auto& pixel : image){
            pixel *= (1.0 / 256.0);
        }
    }
}

} //end of anonymous namespace

TEST_CASE( "dense/sgd/1", "[dense][dbn][mnist][sgd]" ) {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::dense_desc<28 * 28, 100>::layer_t,
            dll::dense_desc<100, 10>::layer_t
        >,
        dll::trainer<dll::dense_sgd_trainer>
    >::dbn_t dbn_t;

    auto dataset = mnist::read_dataset<std::vector, std::vector, double>(1000);
    REQUIRE(!dataset.training_images.empty());

    auto dbn = std::make_unique<dbn_t>();

    dbn->learning_rate = 0.05;

    auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100, 10);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.2);
}

TEST_CASE( "dense/sgd/2", "[dense][dbn][mnist][sgd]" ) {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::dense_desc<28 * 28, 100, dll::activation<dll::function::TANH>>::layer_t,
            dll::dense_desc<100, 10, dll::activation<dll::function::TANH>>::layer_t
        >,
        dll::trainer<dll::dense_sgd_trainer>
    >::dbn_t dbn_t;

    auto dataset = mnist::read_dataset<std::vector, std::vector, double>(1000);
    REQUIRE(!dataset.training_images.empty());

    mnist_scale(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->learning_rate = 0.05;

    auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100, 10);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.2);
}

TEST_CASE( "dense/sgd/3", "[dense][dbn][mnist][sgd]" ) {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::dense_desc<28 * 28, 100>::layer_t,
            dll::dense_desc<100, 10>::layer_t
        >
        , dll::momentum
        , dll::trainer<dll::dense_sgd_trainer>
    >::dbn_t dbn_t;

    auto dataset = mnist::read_dataset<std::vector, std::vector, double>(1000);
    REQUIRE(!dataset.training_images.empty());

    mnist_scale(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->initial_momentum = 0.9;
    dbn->final_momentum = 0.9;
    dbn->learning_rate = 0.01;

    auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100, 10);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.2);
}

TEST_CASE( "dense/sgd/4", "[dense][dbn][mnist][sgd]" ) {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::dense_desc<28 * 28, 100>::layer_t,
            dll::dense_desc<100, 10>::layer_t
        >
        , dll::momentum
        , dll::weight_decay<>
        , dll::trainer<dll::dense_sgd_trainer>
    >::dbn_t dbn_t;

    auto dataset = mnist::read_dataset<std::vector, std::vector, double>(1000);
    REQUIRE(!dataset.training_images.empty());

    mnist_scale(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->initial_momentum = 0.9;
    dbn->final_momentum = 0.9;
    dbn->learning_rate = 0.01;

    auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100, 10);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.2);
}

TEST_CASE( "dense/sgd/5", "[dense][dbn][mnist][sgd]" ) {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::dense_desc<28 * 28, 100, dll::activation<dll::function::TANH>>::layer_t,
            dll::dense_desc<100, 10, dll::activation<dll::function::TANH>>::layer_t
        >
        , dll::momentum
        , dll::weight_decay<>
        , dll::trainer<dll::dense_sgd_trainer>
    >::dbn_t dbn_t;

    auto dataset = mnist::read_dataset<std::vector, std::vector, double>(1000);
    REQUIRE(!dataset.training_images.empty());

    mnist_scale(dataset);

    auto dbn = std::make_unique<dbn_t>();

    dbn->initial_momentum = 0.9;
    dbn->final_momentum = 0.9;
    dbn->learning_rate = 0.01;

    auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100, 10);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.2);
}
<|endoftext|>