<commit_before>#include <kernel/os.hpp>
#include <liveupdate>
using namespace liu;

static std::vector<int64_t> timestamps;
static buffer_t bloberino;

static void boot_save(Storage& storage, const buffer_t* blob)
{
  timestamps.push_back(OS::nanos_since_boot());
  storage.add_vector(0, timestamps);
  assert(blob != nullptr);
  storage.add_buffer(2, *blob);
}
static void boot_resume_all(Restore& thing)
{
  timestamps = thing.as_vector<int64_t>(); thing.go_next();
  // calculate time spent
  auto t1 = timestamps.back();
  auto t2 = OS::nanos_since_boot();
  // set final time
  timestamps.back() = t2 - t1;
  // retrieve old blob
  bloberino = thing.as_buffer(); thing.go_next();

  thing.pop_marker();
}

LiveUpdate::storage_func begin_test_boot()
{
  if (LiveUpdate::resume("test", boot_resume_all))
  {
    if (timestamps.size() >= 30)
    {
      // calculate median by sorting
      std::sort(timestamps.begin(), timestamps.end());
      auto median = timestamps[timestamps.size()/2];
      // show information
      printf("Median boot time over %lu samples: %.2f millis\n",
              timestamps.size(), median / 1000000.0);
      /*
      for (auto& stamp : timestamps) {
        printf("%lld\n", stamp);
      }
      */
      printf("SUCCESS\n");
      OS::shutdown();
    }
    else {
      // immediately liveupdate
      LiveUpdate::exec(bloberino, "test", boot_save);
    }
  }
  // wait for update
  return boot_save;
}
<commit_msg>test: Verify timers are started after live update<commit_after>#include <kernel/os.hpp>
#include <liveupdate>
#include <timers>
using namespace liu;

static std::vector<int64_t> timestamps;
static buffer_t bloberino;

static void boot_save(Storage& storage, const buffer_t* blob)
{
  timestamps.push_back(OS::nanos_since_boot());
  storage.add_vector(0, timestamps);
  assert(blob != nullptr);
  storage.add_buffer(2, *blob);
}
static void boot_resume_all(Restore& thing)
{
  timestamps = thing.as_vector<int64_t>(); thing.go_next();
  // calculate time spent
  auto t1 = timestamps.back();
  auto t2 = OS::nanos_since_boot();
  // set final time
  timestamps.back() = t2 - t1;
  // retrieve old blob
  bloberino = thing.as_buffer(); thing.go_next();

  thing.pop_marker();
}

LiveUpdate::storage_func begin_test_boot()
{
  if (LiveUpdate::resume("test", boot_resume_all))
  {
    if (timestamps.size() >= 30)
    {
      // calculate median by sorting
      std::sort(timestamps.begin(), timestamps.end());
      auto median = timestamps[timestamps.size()/2];
      // show information
      printf("Median boot time over %lu samples: %.2f millis\n",
              timestamps.size(), median / 1000000.0);
      /*
      for (auto& stamp : timestamps) {
        printf("%lld\n", stamp);
      }
      */
      printf("Verifying that timers are started...\n");
      using namespace std::chrono;
      Timers::oneshot(5ms,[] (int) {
        printf("SUCCESS\n");
        OS::shutdown();
      });
    }
    else {
      // immediately liveupdate
      LiveUpdate::exec(bloberino, "test", boot_save);
    }
  }
  // wait for update
  return boot_save;
}
<|endoftext|>


<commit_before>//
// (c) Copyright 2017 DESY,ESS
//
// This file is part of h5pp.
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor
// Boston, MA  02110-1301 USA
// ===========================================================================
//
// Author: Jan Kotanski <jan.kotanski@desy.de>
// Created on: Nov 12, 2018
//

#include <gtest/gtest.h>
#include <h5cpp/file/functions.hpp>
#include <h5cpp/node/group.hpp>
#include <h5cpp/dataspace/hyperslab.hpp>
#include <sys/time.h>

using namespace hdf5;
namespace fs = boost::filesystem;

class DatasetReadSpeedTest : public testing::Test
{
 protected:
  virtual void SetUp()
  {
#if H5_VERSION_GE(1, 10, 0)
    property::FileCreationList fcpl;
    property::FileAccessList fapl;
    property::DatasetCreationList dcpl;
    property::LinkCreationList lcpl;
    property::DatasetAccessList dapl;
    fapl.library_version_bounds(property::LibVersion::LATEST,
                                property::LibVersion::LATEST);
    file::File f = file::create("dataset_read_speed.h5", file::AccessFlags::TRUNCATE, fcpl, fapl);
#else
    file::File f = file::create("dataset_read_speed.h5", file::AccessFlags::TRUNCATE);
#endif
    node::Group root = f.root();
    long long unsigned int xdim = 867;
    long long unsigned int ydim = 700;
    long long unsigned int nframe = 33;

     dataspace::Simple space {{0, xdim, ydim}, {dataspace::Simple::UNLIMITED,
	   dataspace::Simple::UNLIMITED,
	   dataspace::Simple::UNLIMITED}};
    dcpl.layout(property::DatasetLayout::CHUNKED);
    dcpl.chunk({1, xdim, ydim});
    node::Dataset data = node::Dataset(root,
				       "data",
				       datatype::create<unsigned short int>(),
				       space,lcpl,dcpl,dapl);
    std::vector<unsigned short int> frame(xdim*ydim);
    dataspace::Hyperslab framespace{{0, 0, 0}, {1, xdim, ydim}};
    for(long long unsigned int i = 0; i != nframe; i++){
      data.extent(0, 1);
      framespace.offset({i, 0, 0});
      data.write(frame, framespace);

    }
  }
};

TEST_F(DatasetReadSpeedTest, read)
{
  struct timeval stime1;
  struct timeval etime1;
  struct timeval stime0;
  struct timeval etime0;

  file::File f0 = file::open("dataset_read_speed.h5",
			    file::AccessFlags::READONLY);
  auto root0 = f0.root();
  auto dataset0 = root0.get_dataset("/data");
  hdf5::dataspace::Simple dataspace(dataset0.dataspace());
  const auto dims = dataspace.current_dimensions();
  std::vector<unsigned short int> buffer(dims[0]*dims[1]*dims[2]);
  auto datatype = dataset0.datatype();

  hdf5::Dimensions frameoffset{0, 0, 0};
  hdf5::Dimensions frameblock{dims[0], dims[1], dims[2]};
  hdf5::dataspace::Hyperslab selected_frames{frameoffset, frameblock};
  // time0
  gettimeofday(&stime0, NULL);
  dataset0.read(buffer, datatype, dataspace, selected_frames);
  gettimeofday(&etime0, NULL);
  f0.close();

  file::File f1 = file::open("dataset_read_speed.h5",
			    file::AccessFlags::READONLY);
  auto root1 = f1.root();
  auto dataset1 = root1.get_dataset("/data");
  // time1
  gettimeofday(&stime1, NULL);
  dataset1.read(buffer);
  gettimeofday(&etime1, NULL);
  f1.close();

  double time0 = (double)(etime0.tv_sec - stime0.tv_sec)
    + (double)(etime0.tv_usec - stime0.tv_usec)*0.000001;
  double time1 = (double)(etime1.tv_sec - stime1.tv_sec)
    + (double)(etime1.tv_usec - stime1.tv_usec)*0.000001;

  EXPECT_GT(2*time1, time0);
  EXPECT_GT(2*time0, time1);
}

TEST_F(DatasetReadSpeedTest, read_hyperslab)
{
  struct timeval stime1;
  struct timeval etime1;
  struct timeval stime0;
  struct timeval etime0;

  file::File f0 = file::open("dataset_read_speed.h5",
			    file::AccessFlags::READONLY);
  auto root0 = f0.root();
  auto dataset0 = root0.get_dataset("/data");
  hdf5::dataspace::Simple dataspace(dataset0.dataspace());
  const auto dims = dataspace.current_dimensions();
  std::vector<unsigned short int> buffer(11*dims[1]*dims[2]);
  auto datatype = dataset0.datatype();

  hdf5::Dimensions frameoffset{10, 0, 0};
  hdf5::Dimensions frameblock{11, dims[1], dims[2]};
  hdf5::dataspace::Hyperslab selected_frames{frameoffset, frameblock};
  dataspace::Simple dataspace0(Dimensions({11, dims[1], dims[2]}));
  // time0
  gettimeofday(&stime0, NULL);
  dataset0.read(buffer, datatype, dataspace0, selected_frames);
  gettimeofday(&etime0, NULL);
  f0.close();

  file::File f1 = file::open("dataset_read_speed.h5",
  			    file::AccessFlags::READONLY);
  auto root1 = f1.root();
  auto dataset1 = root1.get_dataset("/data");
  // time1
  gettimeofday(&stime1, NULL);
  dataset1.read(buffer, selected_frames);
  gettimeofday(&etime1, NULL);
  f1.close();

  double time0 = (double)(etime0.tv_sec - stime0.tv_sec)
    + (double)(etime0.tv_usec - stime0.tv_usec)*0.000001;
  double time1 = (double)(etime1.tv_sec - stime1.tv_sec)
    + (double)(etime1.tv_usec - stime1.tv_usec)*0.000001;

  EXPECT_GT(2*time1, time0);
  EXPECT_GT(2*time0, time1);
}
<commit_msg>relax tests<commit_after>//
// (c) Copyright 2017 DESY,ESS
//
// This file is part of h5pp.
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor
// Boston, MA  02110-1301 USA
// ===========================================================================
//
// Author: Jan Kotanski <jan.kotanski@desy.de>
// Created on: Nov 12, 2018
//

#include <gtest/gtest.h>
#include <h5cpp/file/functions.hpp>
#include <h5cpp/node/group.hpp>
#include <h5cpp/dataspace/hyperslab.hpp>
#include <sys/time.h>

using namespace hdf5;
namespace fs = boost::filesystem;

class DatasetReadSpeedTest : public testing::Test
{
 protected:
  virtual void SetUp()
  {
#if H5_VERSION_GE(1, 10, 0)
    property::FileCreationList fcpl;
    property::FileAccessList fapl;
    property::DatasetCreationList dcpl;
    property::LinkCreationList lcpl;
    property::DatasetAccessList dapl;
    fapl.library_version_bounds(property::LibVersion::LATEST,
                                property::LibVersion::LATEST);
    file::File f = file::create("dataset_read_speed.h5", file::AccessFlags::TRUNCATE, fcpl, fapl);
#else
    file::File f = file::create("dataset_read_speed.h5", file::AccessFlags::TRUNCATE);
#endif
    node::Group root = f.root();
    long long unsigned int xdim = 867;
    long long unsigned int ydim = 700;
    long long unsigned int nframe = 33;

     dataspace::Simple space {{0, xdim, ydim}, {dataspace::Simple::UNLIMITED,
	   dataspace::Simple::UNLIMITED,
	   dataspace::Simple::UNLIMITED}};
    dcpl.layout(property::DatasetLayout::CHUNKED);
    dcpl.chunk({1, xdim, ydim});
    node::Dataset data = node::Dataset(root,
				       "data",
				       datatype::create<unsigned short int>(),
				       space,lcpl,dcpl,dapl);
    std::vector<unsigned short int> frame(xdim*ydim);
    dataspace::Hyperslab framespace{{0, 0, 0}, {1, xdim, ydim}};
    for(long long unsigned int i = 0; i != nframe; i++){
      data.extent(0, 1);
      framespace.offset({i, 0, 0});
      data.write(frame, framespace);

    }
  }
};

#ifndef _MSC_VER
TEST_F(DatasetReadSpeedTest, read)
{
  struct timeval stime1;
  struct timeval etime1;
  struct timeval stime0;
  struct timeval etime0;

  file::File f0 = file::open("dataset_read_speed.h5",
			    file::AccessFlags::READONLY);
  auto root0 = f0.root();
  auto dataset0 = root0.get_dataset("/data");
  hdf5::dataspace::Simple dataspace(dataset0.dataspace());
  const auto dims = dataspace.current_dimensions();
  std::vector<unsigned short int> buffer(dims[0]*dims[1]*dims[2]);
  auto datatype = dataset0.datatype();

  hdf5::Dimensions frameoffset{0, 0, 0};
  hdf5::Dimensions frameblock{dims[0], dims[1], dims[2]};
  hdf5::dataspace::Hyperslab selected_frames{frameoffset, frameblock};
  // time0
  gettimeofday(&stime0, NULL);
  dataset0.read(buffer, datatype, dataspace, selected_frames);
  gettimeofday(&etime0, NULL);
  f0.close();

  file::File f1 = file::open("dataset_read_speed.h5",
			    file::AccessFlags::READONLY);
  auto root1 = f1.root();
  auto dataset1 = root1.get_dataset("/data");
  // time1
  gettimeofday(&stime1, NULL);
  dataset1.read(buffer);
  gettimeofday(&etime1, NULL);
  f1.close();

  double time0 = (double)(etime0.tv_sec - stime0.tv_sec)
    + (double)(etime0.tv_usec - stime0.tv_usec)*0.000001;
  double time1 = (double)(etime1.tv_sec - stime1.tv_sec)
    + (double)(etime1.tv_usec - stime1.tv_usec)*0.000001;

  EXPECT_GT(8*time1, time0);
  EXPECT_GT(8*time0, time1);
}

TEST_F(DatasetReadSpeedTest, read_hyperslab)
{
  struct timeval stime1;
  struct timeval etime1;
  struct timeval stime0;
  struct timeval etime0;

  file::File f0 = file::open("dataset_read_speed.h5",
			    file::AccessFlags::READONLY);
  auto root0 = f0.root();
  auto dataset0 = root0.get_dataset("/data");
  hdf5::dataspace::Simple dataspace(dataset0.dataspace());
  const auto dims = dataspace.current_dimensions();
  std::vector<unsigned short int> buffer(11*dims[1]*dims[2]);
  auto datatype = dataset0.datatype();

  hdf5::Dimensions frameoffset{10, 0, 0};
  hdf5::Dimensions frameblock{11, dims[1], dims[2]};
  hdf5::dataspace::Hyperslab selected_frames{frameoffset, frameblock};
  dataspace::Simple dataspace0(Dimensions({11, dims[1], dims[2]}));
  // time0
  gettimeofday(&stime0, NULL);
  dataset0.read(buffer, datatype, dataspace0, selected_frames);
  gettimeofday(&etime0, NULL);
  f0.close();

  file::File f1 = file::open("dataset_read_speed.h5",
  			    file::AccessFlags::READONLY);
  auto root1 = f1.root();
  auto dataset1 = root1.get_dataset("/data");
  // time1
  gettimeofday(&stime1, NULL);
  dataset1.read(buffer, selected_frames);
  gettimeofday(&etime1, NULL);
  f1.close();

  double time0 = (double)(etime0.tv_sec - stime0.tv_sec)
    + (double)(etime0.tv_usec - stime0.tv_usec)*0.000001;
  double time1 = (double)(etime1.tv_sec - stime1.tv_sec)
    + (double)(etime1.tv_usec - stime1.tv_usec)*0.000001;

  EXPECT_GT(8*time1, time0);
  EXPECT_GT(8*time0, time1);
}
#endif
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include <test/unit/math/rev/fun/util.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/rev/fun/sin.hpp>

namespace stan {
namespace math {

class test_vari : public vari {
 public:
  explicit test_vari() : vari(0.0) {
  }

  virtual void chain() {
    stan::math::nested_rev_autodiff nested;

    // Add enough vars to make the the var_stack_ vector reallocate
    int N_new_vars = ChainableStack::instance_->var_stack_.capacity() + 1;

    var total = 0.0;
    for (int i = 0; i < N_new_vars; ++i) {
      total += i;
    }

    total.grad();
  }
};

}
}

TEST(AgradRev, grad_in_reverse_mode) {
  using stan::math::var;

  var total = 0.0;
  for (int i = 0; i < 2; ++i) {
    total += i;
  }

  var test_var(new stan::math::test_vari());

  test_var.grad();
}
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0<commit_after>#include <gtest/gtest.h>
#include <test/unit/math/rev/fun/util.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/rev/fun/sin.hpp>

namespace stan {
namespace math {

class test_vari : public vari {
 public:
  explicit test_vari() : vari(0.0) {}

  virtual void chain() {
    stan::math::nested_rev_autodiff nested;

    // Add enough vars to make the the var_stack_ vector reallocate
    int N_new_vars = ChainableStack::instance_->var_stack_.capacity() + 1;

    var total = 0.0;
    for (int i = 0; i < N_new_vars; ++i) {
      total += i;
    }

    total.grad();
  }
};

}  // namespace math
}  // namespace stan

TEST(AgradRev, grad_in_reverse_mode) {
  using stan::math::var;

  var total = 0.0;
  for (int i = 0; i < 2; ++i) {
    total += i;
  }

  var test_var(new stan::math::test_vari());

  test_var.grad();
}
<|endoftext|>


<commit_before>#include "test_helper.h"

#include <disir/fslib/util.h>
#include <disir/fslib/toml.h>
#include <disir/fslib/json.h>

#include "log.h"

const char *molds[] = {
    "basic_keyval",
    "basic_section",
    "json_test_mold",
    "restriction_keyval_numeric_types",
    "restriction_entries",
    "restriction_config_parent_keyval_min_entry",
    "restriction_config_parent_keyval_max_entry",
    "restriction_config_parent_section_max_entry",
    "restriction_section_parent_keyval_max_entry",
    "basic_version_difference",
    "complex_section",
    "config_query_permutations",
};

class SerializeUnserializeTest : public ::testing::DisirTestTestPlugin,
                                 public ::testing::WithParamInterface<const char *>
{
public:
    void serialize_unserialize_config (const char *entry,
                                       dio_serialize_config func_serialize,
                                       dio_unserialize_config func_unserialize)
    {
        struct disir_config *config_original = NULL;
        struct disir_config *config_parsed = NULL;
        struct disir_context *context_config1 = NULL;
        struct disir_context *context_config2 = NULL;
        FILE *file = NULL;
        struct disir_mold *mold = NULL;

        log_test ("SerializeUnserialize %s", entry);

        // read the current entry
        status = disir_config_read (instance, "test", entry,
                                    NULL, &config_original);
        EXPECT_STATUS (DISIR_STATUS_OK, status);
        if (status != DISIR_STATUS_OK)
        {
            log_test ("config_read failed: %s", disir_status_string (status));
            goto out;
        }

        // open file for reading and writing
        char filepath[4098];
        snprintf (filepath, 4098, "/tmp/disir_plugin_serialize_unserialize_%s.toml", entry);
        file = fopen (filepath, "w+");
        EXPECT_TRUE (file != NULL);
        if (file == NULL)
        {
            log_test ("Failed to open file...");
            goto out;
        }

        // Serialize the current entry config
        status = func_serialize (instance, config_original, file);
        EXPECT_STATUS (DISIR_STATUS_OK, status);
        if (status != DISIR_STATUS_OK)
            goto out;

        // Unserialize the previously serialized config
        // XXX: Cheat by extracting the mold directly from the config.
        mold = config_original->cf_mold;
        fseek (file, 0, SEEK_SET);
        status = func_unserialize (instance, file, mold, &config_parsed);
        EXPECT_STATUS (DISIR_STATUS_OK, status);
        if (status != DISIR_STATUS_OK)
            goto out;

        // compare the two
        context_config1 = dc_config_getcontext (config_original);
        context_config2 = dc_config_getcontext (config_parsed);
        EXPECT_TRUE (context_config1 != NULL);
        EXPECT_TRUE (context_config2 != NULL);
        if (context_config1 == NULL || context_config2 == NULL)
            goto out;
        status = dc_compare (context_config1, context_config2, NULL);
        EXPECT_STATUS (DISIR_STATUS_OK, status)

    out:
        log_test ("compare serialize-unserialize out clause");
        // Cleanup this entry and move to the next
        if (file != NULL)
        {
            fclose (file);
        }
        dc_putcontext (&context_config1);
        dc_putcontext (&context_config2);
        disir_config_finished (&config_original);
        disir_config_finished (&config_parsed);
    }
};

TEST_P(SerializeUnserializeTest, toml)
{
    const char *key= GetParam();

    ASSERT_NO_FATAL_FAILURE (
        serialize_unserialize_config (key, dio_toml_serialize_config, dio_toml_unserialize_config);
    );
}

TEST_P(SerializeUnserializeTest, config_json)
{
    const char *key= GetParam();

    ASSERT_NO_FATAL_FAILURE (
        serialize_unserialize_config (key, dio_json_serialize_config, dio_json_unserialize_config);
    );
}

INSTANTIATE_TEST_CASE_P(MoldKey, SerializeUnserializeTest, ::testing::ValuesIn(molds));

<commit_msg>plugin test: Mold serialize/unserialize test<commit_after>#include "test_helper.h"

#include <disir/fslib/util.h>
#include <disir/fslib/toml.h>
#include <disir/fslib/json.h>

#include "log.h"

const char *molds[] = {
    "basic_keyval",
    "basic_section",
    "json_test_mold",
    "restriction_keyval_numeric_types",
    "restriction_entries",
    "restriction_config_parent_keyval_min_entry",
    "restriction_config_parent_keyval_max_entry",
    "restriction_config_parent_section_max_entry",
    "restriction_section_parent_keyval_max_entry",
    "basic_version_difference",
    "complex_section",
    "config_query_permutations",
};

class SerializeUnserializeTest : public ::testing::DisirTestTestPlugin,
                                 public ::testing::WithParamInterface<const char *>
{
public:
    void serialize_unserialize_mold (const char *entry,
                                     const char *suffix,
                                     dio_serialize_mold func_serialize,
                                     dio_unserialize_mold func_unserialize)
    {
        struct disir_mold *mold_original = NULL;
        struct disir_mold *mold_parsed = NULL;
        struct disir_context *context_mold1 = NULL;
        struct disir_context *context_mold2 = NULL;
        FILE *file = NULL;

        log_test ("SerializeUnserialize mold %s", entry);

        status = disir_mold_read (instance, "test", entry, &mold_original);
        EXPECT_STATUS (DISIR_STATUS_OK, status);
        if (status != DISIR_STATUS_OK)
        {
            log_test ("mold_read failed: %s", disir_status_string (status));
            goto out;
        }

        char filepath[4098];
        snprintf (filepath, 4098, "/tmp/disir_plugin_serialize_unserialize_%s.%s", entry, suffix);
        file = fopen (filepath, "w+");
        EXPECT_TRUE (file != NULL);
        if (file == NULL)
        {
            log_test ("Failed to open file...");
            goto out;
        }
        status = func_serialize (instance, mold_original, file);
        EXPECT_STATUS (DISIR_STATUS_OK, status);
        if (status != DISIR_STATUS_OK)
            goto out;

        fseek (file, 0, SEEK_SET);

        status = func_unserialize (instance, file, &mold_parsed);
        EXPECT_STATUS (DISIR_STATUS_OK, status);
        if (status != DISIR_STATUS_OK)
            goto out;

        context_mold1 = dc_mold_getcontext (mold_original);
        context_mold2 = dc_mold_getcontext (mold_parsed);
        EXPECT_TRUE (context_mold1 != NULL);
        EXPECT_TRUE (context_mold2 != NULL);
        if (context_mold1 == NULL || context_mold2 == NULL)
            goto out;

        status = dc_compare (context_mold1, context_mold2, NULL);
        EXPECT_STATUS (DISIR_STATUS_OK, status)
    out:
        log_test ("compare serialize-unserialize mold out clause");
        // Cleanup this entry and move to the next
        if (file != NULL)
        {
            fclose (file);
        }
        dc_putcontext (&context_mold1);
        dc_putcontext (&context_mold2);
        disir_mold_finished (&mold_original);
        disir_mold_finished (&mold_parsed);
    }

    void serialize_unserialize_config (const char *entry,
                                       dio_serialize_config func_serialize,
                                       dio_unserialize_config func_unserialize)
    {
        struct disir_config *config_original = NULL;
        struct disir_config *config_parsed = NULL;
        struct disir_context *context_config1 = NULL;
        struct disir_context *context_config2 = NULL;
        FILE *file = NULL;
        struct disir_mold *mold = NULL;

        log_test ("SerializeUnserialize %s", entry);

        // read the current entry
        status = disir_config_read (instance, "test", entry,
                                    NULL, &config_original);
        EXPECT_STATUS (DISIR_STATUS_OK, status);
        if (status != DISIR_STATUS_OK)
        {
            log_test ("config_read failed: %s", disir_status_string (status));
            goto out;
        }

        // open file for reading and writing
        char filepath[4098];
        snprintf (filepath, 4098, "/tmp/disir_plugin_serialize_unserialize_%s.toml", entry);
        file = fopen (filepath, "w+");
        EXPECT_TRUE (file != NULL);
        if (file == NULL)
        {
            log_test ("Failed to open file...");
            goto out;
        }

        // Serialize the current entry config
        status = func_serialize (instance, config_original, file);
        EXPECT_STATUS (DISIR_STATUS_OK, status);
        if (status != DISIR_STATUS_OK)
            goto out;

        // Unserialize the previously serialized config
        // XXX: Cheat by extracting the mold directly from the config.
        mold = config_original->cf_mold;
        fseek (file, 0, SEEK_SET);
        status = func_unserialize (instance, file, mold, &config_parsed);
        EXPECT_STATUS (DISIR_STATUS_OK, status);
        if (status != DISIR_STATUS_OK)
            goto out;

        // compare the two
        context_config1 = dc_config_getcontext (config_original);
        context_config2 = dc_config_getcontext (config_parsed);
        EXPECT_TRUE (context_config1 != NULL);
        EXPECT_TRUE (context_config2 != NULL);
        if (context_config1 == NULL || context_config2 == NULL)
            goto out;
        status = dc_compare (context_config1, context_config2, NULL);
        EXPECT_STATUS (DISIR_STATUS_OK, status)

    out:
        log_test ("compare serialize-unserialize out clause");
        // Cleanup this entry and move to the next
        if (file != NULL)
        {
            fclose (file);
        }
        dc_putcontext (&context_config1);
        dc_putcontext (&context_config2);
        disir_config_finished (&config_original);
        disir_config_finished (&config_parsed);
    }
};

TEST_P(SerializeUnserializeTest, toml)
{
    const char *key= GetParam();

    ASSERT_NO_FATAL_FAILURE (
        serialize_unserialize_config (key, dio_toml_serialize_config, dio_toml_unserialize_config);
    );
}

TEST_P(SerializeUnserializeTest, config_json)
{
    const char *key= GetParam();

    ASSERT_NO_FATAL_FAILURE (
        serialize_unserialize_config (key, dio_json_serialize_config, dio_json_unserialize_config);
    );
}

TEST_P(SerializeUnserializeTest, mold_json)
{
    const char *key= GetParam();

    ASSERT_NO_FATAL_FAILURE (
        serialize_unserialize_mold (key, "json", dio_json_serialize_mold, dio_json_unserialize_mold);
    );
}

INSTANTIATE_TEST_CASE_P(MoldKey, SerializeUnserializeTest, ::testing::ValuesIn(molds));

<|endoftext|>


<commit_before>#include <cnc/cnc.h>

#define CATCH_CONFIG_MAIN
#include <catch.hpp>

struct FibContext;

// declare data type for fibonacci
typedef unsigned long long fib_type;

struct FibStep
{
    int execute(const int &tag, FibContext &context) const;
};

struct FibContext : public CnC::Context<FibContext>
{
    CnC::StepCollection<int, FibStep> steps;
    CnC::ItemCollection<int, fib_type> fibs;

    FibContext() : CnC::Context<FibContext>(),
        steps(*this),
        fibs()
    {
    }
};

int FibStep::execute(const int &tag, FibContext &context) const
{
    // std::cout << "start " << tag << std::endl;

    // get previous 2 results
    fib_type f_1; context.fibs.get(tag - 1, f_1);
    fib_type f_2; context.fibs.get(tag - 2, f_2);

    // std::cout << f_1 << " + " << f_2 << " = " << (f_1 + f_2) << std::endl;

    // put our result
    context.fibs.put(tag, f_1 + f_2);

    // std::cout << "end " << tag << std::endl;

    return 0;
}

TEST_CASE("Get fibonacci number", "[fib]")
{
    int n = 42;

    // create context
    FibContext context;

    // seed
    context.fibs.put(0, 0);
    context.fibs.put(1, 1);

    // put tags to initiate evaluation
    for (int i = 2; i <= n; ++i)
        context.steps.put(i);

    // wait for completion
    uv_run(uv_default_loop(), UV_RUN_DEFAULT);

    // get result
    fib_type result;
    context.fibs.get(n, result);

    // check result
    REQUIRE(result == 267914296);
}<commit_msg>fib example (not test)<commit_after>#include <cnc/cnc.h>

struct FibContext;

// declare data type for fibonacci
typedef unsigned long long fib_type;

struct FibStep
{
    int execute(const int &tag, FibContext &context) const;
};

struct FibContext : public CnC::Context<FibContext>
{
    CnC::StepCollection<int, FibStep> steps;
    CnC::ItemCollection<int, fib_type> fibs;

    FibContext() : CnC::Context<FibContext>(),
        steps(*this),
        fibs()
    {
    }
};

int FibStep::execute(const int &tag, FibContext &context) const
{
    // std::cout << "start " << tag << std::endl;

    // get previous 2 results
    fib_type f_1; context.fibs.get(tag - 1, f_1);
    fib_type f_2; context.fibs.get(tag - 2, f_2);

    // std::cout << f_1 << " + " << f_2 << " = " << (f_1 + f_2) << std::endl;

    // put our result
    context.fibs.put(tag, f_1 + f_2);

    // std::cout << "end " << tag << std::endl;

    return 0;
}

int main()
{
    const int n = 42;

    // create context
    FibContext context;

    // seed
    context.fibs.put(0, 0);
    context.fibs.put(1, 1);

    // put tags to initiate evaluation
    for (int i = 2; i <= n; ++i)
        context.steps.put(i);

    // wait for completion
    uv_run(uv_default_loop(), UV_RUN_DEFAULT);

    // get result
    fib_type result;
    context.fibs.get(n, result);

    // check result
	if (result == 267914296)
		std::cout << "fib(" << n << ") = " << result << std::endl;
	else
		std::cout << "wrong answer: " << result << std::endl;
}<|endoftext|>


<commit_before>//
//  ASTInstructionBlockNode.cpp
//  lut-lang
//
//  Created by Robin Ricard on 22/03/15.
//  Copyright (c) 2015 INSA Lyon. All rights reserved.
//

#include "ASTInstructionBlockNode.h"

#include <iostream>

using std::cout;
using std::endl;

ASTInstructionBlockNode::ASTInstructionBlockNode(ASTFirstLevelExpressionNode* expression,
                                                 ASTInstructionBlockNode* prev,
                                                 TokenType type) : ASTNode(type) {
  this->expression = expression;
  this->identifier = NULL;
  this->prev = prev;
}

ASTInstructionBlockNode::ASTInstructionBlockNode(ASTTokenNode* identifier,
                                                 ASTInstructionBlockNode* prev,
                                                 TokenType type) : ASTNode(type) {
  this->expression = NULL;
  this->identifier = identifier;
  this->prev = prev;
}

ASTInstructionBlockNode::ASTInstructionBlockNode(ASTFirstLevelExpressionNode* expression,
                                                 ASTTokenNode* identifier,
                                                 ASTInstructionBlockNode* prev,
                                                 TokenType type) : ASTNode(type) {
  this->expression = expression;
  this->identifier = identifier;
  this->prev = prev;
}

ASTFirstLevelExpressionNode* ASTInstructionBlockNode::getExpression() {
  return this->expression;
}

ASTTokenNode* ASTInstructionBlockNode::getIdentifier() {
  return this->identifier;
}

ASTInstructionBlockNode* ASTInstructionBlockNode::getPrev() {
  return this->prev;
}

bool ASTInstructionBlockNode::analyze(analyze_table* table) {
  return true;
}

int64_t ASTInstructionBlockNode::exec(exec_table* table) {
  return 0;
}

void ASTInstructionBlockNode::print() {
  if (this->expression != NULL && this->identifier != NULL) {  // Assignment
    this->identifier->print();
    cout << " := ";
    this->expression->print();
  } else if (this->expression != NULL) {  // Write
    cout << "ecrire ";
    this->expression->print();
  } else if (this->identifier != NULL) {  // Read
    cout << "lire ";
    this->identifier->print();
  }
  cout << ";" << endl;
}
<commit_msg>Prev inst print<commit_after>//
//  ASTInstructionBlockNode.cpp
//  lut-lang
//
//  Created by Robin Ricard on 22/03/15.
//  Copyright (c) 2015 INSA Lyon. All rights reserved.
//

#include "ASTInstructionBlockNode.h"

#include <iostream>

using std::cout;
using std::endl;

ASTInstructionBlockNode::ASTInstructionBlockNode(ASTFirstLevelExpressionNode* expression,
                                                 ASTInstructionBlockNode* prev,
                                                 TokenType type) : ASTNode(type) {
  this->expression = expression;
  this->identifier = NULL;
  this->prev = prev;
}

ASTInstructionBlockNode::ASTInstructionBlockNode(ASTTokenNode* identifier,
                                                 ASTInstructionBlockNode* prev,
                                                 TokenType type) : ASTNode(type) {
  this->expression = NULL;
  this->identifier = identifier;
  this->prev = prev;
}

ASTInstructionBlockNode::ASTInstructionBlockNode(ASTFirstLevelExpressionNode* expression,
                                                 ASTTokenNode* identifier,
                                                 ASTInstructionBlockNode* prev,
                                                 TokenType type) : ASTNode(type) {
  this->expression = expression;
  this->identifier = identifier;
  this->prev = prev;
}

ASTFirstLevelExpressionNode* ASTInstructionBlockNode::getExpression() {
  return this->expression;
}

ASTTokenNode* ASTInstructionBlockNode::getIdentifier() {
  return this->identifier;
}

ASTInstructionBlockNode* ASTInstructionBlockNode::getPrev() {
  return this->prev;
}

bool ASTInstructionBlockNode::analyze(analyze_table* table) {
  return true;
}

int64_t ASTInstructionBlockNode::exec(exec_table* table) {
  return 0;
}

void ASTInstructionBlockNode::print() {
  if (this->prev != NULL) {
    this->prev->print();
  }
  if (this->expression != NULL && this->identifier != NULL) {  // Assignment
    this->identifier->print();
    cout << " := ";
    this->expression->print();
  } else if (this->expression != NULL) {  // Write
    cout << "ecrire ";
    this->expression->print();
  } else if (this->identifier != NULL) {  // Read
    cout << "lire ";
    this->identifier->print();
  }
  cout << ";" << endl;
}
<|endoftext|>


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

#include "iree/compiler/Dialect/HAL/Conversion/StandardToHAL/ConvertStandardToHAL.h"
#include "iree/compiler/Dialect/HAL/IR/HALOps.h"
#include "iree/compiler/Dialect/HAL/IR/HALTypes.h"
#include "llvm/ADT/DenseMap.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/BlockAndValueMapping.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/Matchers.h"
#include "mlir/Transforms/DialectConversion.h"

namespace mlir {
namespace iree_compiler {
namespace {

class FuncOpSignatureConversion : public OpConversionPattern<mlir::FuncOp> {
 public:
  using OpConversionPattern::OpConversionPattern;

  LogicalResult matchAndRewrite(
      mlir::FuncOp funcOp, llvm::ArrayRef<Value> operands,
      ConversionPatternRewriter &rewriter) const override {
    auto &typeConverter = *getTypeConverter();

    // Convert the input signature types.
    // TODO(benvanik): dynamic shapes by passing in tensor dynamic dims.
    auto originalType = funcOp.getType();
    TypeConverter::SignatureConversion newSignature(
        originalType.getNumInputs());
    for (auto argType : llvm::enumerate(originalType.getInputs())) {
      if (failed(typeConverter.convertSignatureArg(
              argType.index(), argType.value(), newSignature))) {
        return failure();
      }
    }
    SmallVector<Type, 4> newResultTypes;
    if (failed(typeConverter.convertTypes(originalType.getResults(),
                                          newResultTypes))) {
      return failure();
    }

    // Replace function.
    auto newFuncOp = rewriter.cloneWithoutRegions(funcOp);
    newFuncOp.getBlocks().clear();
    rewriter.inlineRegionBefore(funcOp.getBody(), newFuncOp.getBody(),
                                newFuncOp.end());
    newFuncOp.setType(rewriter.getFunctionType(newSignature.getConvertedTypes(),
                                               newResultTypes));
    if (failed(rewriter.convertRegionTypes(&newFuncOp.getBody(), typeConverter,
                                           &newSignature))) {
      return failure();
    }

    rewriter.eraseOp(funcOp);
    return success();
  }
};

class CallOpConversion : public OpConversionPattern<mlir::CallOp> {
 public:
  using OpConversionPattern::OpConversionPattern;

  LogicalResult matchAndRewrite(
      mlir::CallOp op, llvm::ArrayRef<Value> operands,
      ConversionPatternRewriter &rewriter) const override {
    mlir::CallOpAdaptor adaptor(operands);
    SmallVector<Type, 4> resultTypes;
    if (failed(getTypeConverter()->convertTypes(op.getResultTypes(),
                                                resultTypes))) {
      return rewriter.notifyMatchFailure(op, "unable to convert result types");
    }
    rewriter.replaceOpWithNewOp<mlir::CallOp>(op, resultTypes, op.callee(),
                                              adaptor.operands());
    return success();
  }
};

class BranchOpConversion : public OpConversionPattern<mlir::BranchOp> {
 public:
  using OpConversionPattern::OpConversionPattern;

  LogicalResult matchAndRewrite(
      mlir::BranchOp op, llvm::ArrayRef<Value> operands,
      ConversionPatternRewriter &rewriter) const override {
    mlir::BranchOpAdaptor adaptor(operands);
    rewriter.replaceOpWithNewOp<mlir::BranchOp>(op, op.dest(),
                                                adaptor.destOperands());
    return success();
  }
};

class CondBranchOpConversion : public OpConversionPattern<mlir::CondBranchOp> {
 public:
  using OpConversionPattern::OpConversionPattern;

  LogicalResult matchAndRewrite(
      mlir::CondBranchOp op, llvm::ArrayRef<Value> operands,
      ConversionPatternRewriter &rewriter) const override {
    mlir::CondBranchOpAdaptor adaptor(operands,
                                      op.getOperation()->getAttrDictionary());
    rewriter.replaceOpWithNewOp<mlir::CondBranchOp>(
        op, adaptor.condition(), op.trueDest(), adaptor.trueDestOperands(),
        op.falseDest(), op.falseDestOperands());
    return success();
  }
};

class ReturnOpConversion : public OpConversionPattern<mlir::ReturnOp> {
 public:
  using OpConversionPattern::OpConversionPattern;

  LogicalResult matchAndRewrite(
      mlir::ReturnOp returnOp, llvm::ArrayRef<Value> operands,
      ConversionPatternRewriter &rewriter) const override {
    rewriter.replaceOpWithNewOp<mlir::ReturnOp>(returnOp, operands);
    return success();
  }
};

}  // namespace

void populateStandardStructuralToHALPatterns(MLIRContext *context,
                                             OwningRewritePatternList &patterns,
                                             TypeConverter &converter) {
  patterns
      .insert<FuncOpSignatureConversion, CallOpConversion, BranchOpConversion,
              CondBranchOpConversion, ReturnOpConversion>(converter, context);
}

}  // namespace iree_compiler
}  // namespace mlir
<commit_msg>Use adaptor when converting cond_br (latent bug). (#5875)<commit_after>// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "iree/compiler/Dialect/HAL/Conversion/StandardToHAL/ConvertStandardToHAL.h"
#include "iree/compiler/Dialect/HAL/IR/HALOps.h"
#include "iree/compiler/Dialect/HAL/IR/HALTypes.h"
#include "llvm/ADT/DenseMap.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/BlockAndValueMapping.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/Matchers.h"
#include "mlir/Transforms/DialectConversion.h"

namespace mlir {
namespace iree_compiler {
namespace {

class FuncOpSignatureConversion : public OpConversionPattern<mlir::FuncOp> {
 public:
  using OpConversionPattern::OpConversionPattern;

  LogicalResult matchAndRewrite(
      mlir::FuncOp funcOp, llvm::ArrayRef<Value> operands,
      ConversionPatternRewriter &rewriter) const override {
    auto &typeConverter = *getTypeConverter();

    // Convert the input signature types.
    // TODO(benvanik): dynamic shapes by passing in tensor dynamic dims.
    auto originalType = funcOp.getType();
    TypeConverter::SignatureConversion newSignature(
        originalType.getNumInputs());
    for (auto argType : llvm::enumerate(originalType.getInputs())) {
      if (failed(typeConverter.convertSignatureArg(
              argType.index(), argType.value(), newSignature))) {
        return failure();
      }
    }
    SmallVector<Type, 4> newResultTypes;
    if (failed(typeConverter.convertTypes(originalType.getResults(),
                                          newResultTypes))) {
      return failure();
    }

    // Replace function.
    auto newFuncOp = rewriter.cloneWithoutRegions(funcOp);
    newFuncOp.getBlocks().clear();
    rewriter.inlineRegionBefore(funcOp.getBody(), newFuncOp.getBody(),
                                newFuncOp.end());
    newFuncOp.setType(rewriter.getFunctionType(newSignature.getConvertedTypes(),
                                               newResultTypes));
    if (failed(rewriter.convertRegionTypes(&newFuncOp.getBody(), typeConverter,
                                           &newSignature))) {
      return failure();
    }

    rewriter.eraseOp(funcOp);
    return success();
  }
};

class CallOpConversion : public OpConversionPattern<mlir::CallOp> {
 public:
  using OpConversionPattern::OpConversionPattern;

  LogicalResult matchAndRewrite(
      mlir::CallOp op, llvm::ArrayRef<Value> operands,
      ConversionPatternRewriter &rewriter) const override {
    mlir::CallOpAdaptor adaptor(operands);
    SmallVector<Type, 4> resultTypes;
    if (failed(getTypeConverter()->convertTypes(op.getResultTypes(),
                                                resultTypes))) {
      return rewriter.notifyMatchFailure(op, "unable to convert result types");
    }
    rewriter.replaceOpWithNewOp<mlir::CallOp>(op, resultTypes, op.callee(),
                                              adaptor.operands());
    return success();
  }
};

class BranchOpConversion : public OpConversionPattern<mlir::BranchOp> {
 public:
  using OpConversionPattern::OpConversionPattern;

  LogicalResult matchAndRewrite(
      mlir::BranchOp op, llvm::ArrayRef<Value> operands,
      ConversionPatternRewriter &rewriter) const override {
    mlir::BranchOpAdaptor adaptor(operands);
    rewriter.replaceOpWithNewOp<mlir::BranchOp>(op, op.dest(),
                                                adaptor.destOperands());
    return success();
  }
};

class CondBranchOpConversion : public OpConversionPattern<mlir::CondBranchOp> {
 public:
  using OpConversionPattern::OpConversionPattern;

  LogicalResult matchAndRewrite(
      mlir::CondBranchOp op, llvm::ArrayRef<Value> operands,
      ConversionPatternRewriter &rewriter) const override {
    mlir::CondBranchOpAdaptor adaptor(operands,
                                      op.getOperation()->getAttrDictionary());
    rewriter.replaceOpWithNewOp<mlir::CondBranchOp>(
        op, adaptor.condition(), op.trueDest(), adaptor.trueDestOperands(),
        op.falseDest(), adaptor.falseDestOperands());
    return success();
  }
};

class ReturnOpConversion : public OpConversionPattern<mlir::ReturnOp> {
 public:
  using OpConversionPattern::OpConversionPattern;

  LogicalResult matchAndRewrite(
      mlir::ReturnOp returnOp, llvm::ArrayRef<Value> operands,
      ConversionPatternRewriter &rewriter) const override {
    rewriter.replaceOpWithNewOp<mlir::ReturnOp>(returnOp, operands);
    return success();
  }
};

}  // namespace

void populateStandardStructuralToHALPatterns(MLIRContext *context,
                                             OwningRewritePatternList &patterns,
                                             TypeConverter &converter) {
  patterns
      .insert<FuncOpSignatureConversion, CallOpConversion, BranchOpConversion,
              CondBranchOpConversion, ReturnOpConversion>(converter, context);
}

}  // namespace iree_compiler
}  // namespace mlir
<|endoftext|>


<commit_before>/* -*- mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
// vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s

/* Copyright (c) FFLAS-FFPACK
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK is free software: you can redistribute it and/or modify
* it under the terms of the  GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
* ========LICENCE========
*/

#include <iostream>
#include <givaro/modular.h>
#include "fflas-ffpack/fflas-ffpack-config.h"
#include "fflas-ffpack/fflas-ffpack.h"
#include "fflas-ffpack/utils/fflas_io.h"

using namespace std;

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

    if (argc != 3){
        std::cerr<<"Usage: pluq <p> <matrix>"<<std::endl;
        return -1;
    }

    int p = atoi(argv[1]);
    std::string file = argv[2];
    size_t m,n;

        // Creating the finite field Z/qZ
    Givaro::Modular<double> F(p);

        // Reading the matrix from a file
    double *A;
    FFLAS::ReadMatrix (file.c_str(),F,m,n,A);

    size_t * P = FFLAS::fflas_new<size_t>(m);
    size_t * Q = FFLAS::fflas_new<size_t>(n);

    size_t r = FFPACK::PLUQ (F, FFLAS::FflasNonUnit, m, n, A, n, P, Q);

    FFLAS::WritePermutation (std::cout<<"P = "<<std::endl,P,m);

        // Displays L and U separately
    double * L = FFLAS::fflas_new<double>(m * r);
    double * U = FFLAS::fflas_new<double>(r * n);
    FFPACK::getTriangular(F, FFLAS::FflasLower, FFLAS::FflasUnit, m, n, r, A, n, L, r);
    FFPACK::getTriangular(F, FFLAS::FflasUpper, FFLAS::FflasNonUnit, m, n, r, A, n, U, n);
    FFLAS::WriteMatrix(std::cout<<"L = "<<std::endl, F, m, r, L, r);
    std::cout<<"modulo "<<p<<std::endl;
    FFLAS::WriteMatrix(std::cout<<"U = "<<std::endl, F, r, n, U, n);
    std::cout<<"modulo "<<p<<std::endl;

    FFLAS::WritePermutation (std::cout<<"Q = "<<std::endl,Q,n);

    FFLAS::fflas_delete( P);
    FFLAS::fflas_delete( Q);
    FFLAS::fflas_delete( A);

    return 0;
}

<commit_msg>delete L and U<commit_after>/* -*- mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
// vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s

/* Copyright (c) FFLAS-FFPACK
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK is free software: you can redistribute it and/or modify
* it under the terms of the  GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
* ========LICENCE========
*/

#include <iostream>
#include <givaro/modular.h>
#include "fflas-ffpack/fflas-ffpack-config.h"
#include "fflas-ffpack/fflas-ffpack.h"
#include "fflas-ffpack/utils/fflas_io.h"

using namespace std;

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

    if (argc != 3){
        std::cerr<<"Usage: pluq <p> <matrix>"<<std::endl;
        return -1;
    }

    int p = atoi(argv[1]);
    std::string file = argv[2];
    size_t m,n;

        // Creating the finite field Z/qZ
    Givaro::Modular<double> F(p);

        // Reading the matrix from a file
    double *A;
    FFLAS::ReadMatrix (file.c_str(),F,m,n,A);

    size_t * P = FFLAS::fflas_new<size_t>(m);
    size_t * Q = FFLAS::fflas_new<size_t>(n);

    size_t r = FFPACK::PLUQ (F, FFLAS::FflasNonUnit, m, n, A, n, P, Q);

    FFLAS::WritePermutation (std::cout<<"P = "<<std::endl,P,m);

        // Displays L and U separately
    double * L = FFLAS::fflas_new<double>(m * r);
    double * U = FFLAS::fflas_new<double>(r * n);
    FFPACK::getTriangular(F, FFLAS::FflasLower, FFLAS::FflasUnit, m, n, r, A, n, L, r);
    FFPACK::getTriangular(F, FFLAS::FflasUpper, FFLAS::FflasNonUnit, m, n, r, A, n, U, n);
    FFLAS::WriteMatrix(std::cout<<"L = "<<std::endl, F, m, r, L, r);
    std::cout<<"modulo "<<p<<std::endl;
    FFLAS::WriteMatrix(std::cout<<"U = "<<std::endl, F, r, n, U, n);
    std::cout<<"modulo "<<p<<std::endl;

    FFLAS::WritePermutation (std::cout<<"Q = "<<std::endl,Q,n);

    FFLAS::fflas_delete( P);
    FFLAS::fflas_delete( Q);
    FFLAS::fflas_delete( A);
	FFLAS::fflas_delete( L);
	FFLAS::fflas_delete( U);

    return 0;
}

<|endoftext|>


<commit_before>#include "stdafx.h"
/*
* Copyright (c) 2007-2010 SlimDX Group
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

using namespace testing;
using namespace System;
using namespace SlimDX;

TEST( Vector3Tests, ConstructDefault )
{
	Vector3 vector = Vector3();

	ASSERT_EQ( 0.0f, vector.X );
	ASSERT_EQ( 0.0f, vector.Y );
	ASSERT_EQ( 0.0f, vector.Z );
}

TEST( Vector3Tests, ConstructWithX )
{
	Vector3 vector = Vector3( 0.75f );

	ASSERT_EQ( 0.75f, vector.X );
	ASSERT_EQ( 0.75f, vector.Y );
	ASSERT_EQ( 0.75f, vector.Z );
}

TEST( Vector3Tests, ConstructWithXYZ )
{
	Vector3 vector = Vector3( 0.75f, 1.25f, 1.75f );

	ASSERT_EQ( 0.75f, vector.X );
	ASSERT_EQ( 1.25f, vector.Y );
	ASSERT_EQ( 1.75f, vector.Z );
}

TEST( Vector3Tests, ConstructWithVector2 )
{
	Vector2 source = Vector2( 1.0f, 2.0f );
	Vector3 vector = Vector3( source, 3.0f );

	ASSERT_EQ( 1.0f, vector.X );
	ASSERT_EQ( 2.0f, vector.Y );
	ASSERT_EQ( 3.0f, vector.Z );
}
<commit_msg>Testing parameterized build.<commit_after>#include "stdafx.h"
/*
* Copyright (c) 2007-2010 SlimDX Group
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

using namespace testing;
using namespace System;
using namespace SlimDX;

TEST( Vector3Tests, ConstructDefault )
{
	Vector3 vector = Vector3();

	ASSERT_EQ( 0.0f, vector.X );
	ASSERT_EQ( 0.0f, vector.Y );
	ASSERT_EQ( 0.0f, vector.Z );
}

TEST( Vector3Tests, ConstructWithX )
{
	Vector3 vector = Vector3( 0.75f );

	ASSERT_EQ( 0.75f, vector.X );
	ASSERT_EQ( 0.75f, vector.Y );
	ASSERT_EQ( 0.75f, vector.Z );
}

TEST( Vector3Tests, ConstructWithXYZ )
{
	Vector3 vector = Vector3( 0.75f, 1.25f, 1.75f );

	ASSERT_EQ( 0.75f, vector.X );
	ASSERT_EQ( 1.25f, vector.Y );
	ASSERT_EQ( 1.75f, vector.Z );
}

TEST( Vector3Tests, ConstructWithVector2 )
{
	Vector2 source = Vector2( 1.0f, 2.0f );
	Vector3 vector = Vector3( source, 3.0f );

	ASSERT_EQ( 1.0f, vector.X );
	ASSERT_EQ( 2.0f, vector.Y );
	ASSERT_EQ( 3.0f, vector.Z );
}

TEST( Vector3Tests, Add)
{
	Vector3 v1(5.6f, 2.1f, 8.3f);
	Vector3 v2(3.4f, 7.9f, 7.7f);
	Vector3 v3 = v1 + v2;

	ASSERT_EQ(9.0f, v3.X);
	ASSERT_EQ(10.0f, v3.Y);
	ASSERT_EQ(16.0f, v3.Z);
}<|endoftext|>


<commit_before>// BELONG TO \REVIEW
#include <itkVTKPolyDataReader.h>
#include <itkVTKPolyDataWriter.h>
#include <itkQuadEdgeMesh.h>

// NEW
#include "itkQuadEdgeMeshBorderTransform.h"
#include "itkQuadEdgeMeshParamMatrixCoefficients.h"

// TIMING
#include <ctime>

#ifdef QuadEdgePARAM_TAUCS
    #include "TAUCSSparseSolverTraits.h"
#else
    #include "VNLIterativeSparseSolverTraits.h"
#endif

#include "itkQuadEdgeMeshParam.h"

using namespace itk;

int itkQuadEdgeMeshLinearParameterizationTest( int argc, char** argv )
{
    // ** ERROR MESSAGE AND HELP ** //
    if( argc < 5 )
    {
        std::cout <<"Requires 4 arguments: " <<std::endl;
        std::cout <<"1-Input file name " <<std::endl;
        std::cout <<"2-Border Type" <<std::endl;
        std::cout <<"   * 0: SQUARE" <<std::endl;
        std::cout <<"   * 1: DISK" <<std::endl;
        std::cout <<"3-CoefficientType Type" <<std::endl;
        std::cout <<"   * 0: OnesMatrixCoefficients" <<std::endl;
        std::cout <<"   * 1: InverseEuclideanDistanceMatrixCoefficients"
          <<std::endl;
        std::cout <<"   * 2: ConformalMatrixCoefficients" <<std::endl;
        std::cout <<"   * 3: AuthalicMatrixCoefficients" <<std::endl;
        std::cout <<"   * 4: HarmonicMatrixCoefficients" <<std::endl;
        std::cout <<"4-Output file name " <<std::endl;

        return EXIT_FAILURE;
    }

    // ** TYPEDEF **
    typedef double Coord;

    typedef QuadEdgeMesh< Coord, 3 >                      MeshType;
    typedef VTKPolyDataReader< MeshType >                 ReaderType;
    typedef VTKPolyDataWriter< MeshType >                 WriterType;
    typedef QuadEdgeMeshBorderTransform< MeshType, MeshType >     BorderTransformType;
#ifdef QuadEdgePARAM_TAUCS
    typedef TAUCSSolverTraits< Coord >                    SolverTraits;
#else
    typedef VNLIterativeSparseSolverTraits< Coord >       SolverTraits;
#endif
    typedef QuadEdgeMeshParam< MeshType, MeshType, SolverTraits > ParametrizationType;

    // ** READ THE FILE IN **
    ReaderType::Pointer reader = ReaderType::New( );
    reader->SetFileName( argv[1] );
    try
    {
      reader->Update( );
    }
    catch( itk::ExceptionObject & exp )
    {
      std::cerr << "Exception thrown while reading the input file " << std::endl;
      std::cerr << exp << std::endl;
      return EXIT_FAILURE;
    }

    MeshType::Pointer mesh = reader->GetOutput( );

    // ** CHOSE< COMPUTE AND SET BORDER TRANSFORM **
    // clock_t start = clock( );
    BorderTransformType::Pointer border_transform = BorderTransformType::New( );
    border_transform->SetInput( mesh );

    int border;
    std::stringstream ssout( argv[2] );
    ssout >>border;
    switch( border )  // choose border type
    {
        case 0: // square shaped domain
            border_transform->SetTransformType(
                BorderTransformType::SQUARE_BORDER_TRANSFORM );
            break;
        case 1: // disk shaped domain
            border_transform->SetTransformType(
                BorderTransformType::DISK_BORDER_TRANSFORM );
            break;
        default: // handle .... user ....
            std::cerr <<"2nd argument must be "<<std::endl;
            std::cerr <<"0 for SQUARE BORDER TRANSFORM or "
              <<"1 for DISK BORDER TRANSFORM" <<std::endl;
            return EXIT_FAILURE;
    }

    // ** CHOOSE AND SET BARYCENTRIC WEIGHTS **
    OnesMatrixCoefficients< MeshType >                     coeff0;
    InverseEuclideanDistanceMatrixCoefficients< MeshType > coeff1;
    ConformalMatrixCoefficients< MeshType >                coeff2;
    AuthalicMatrixCoefficients< MeshType >                 coeff3;
    HarmonicMatrixCoefficients< MeshType >                 coeff4;

    ParametrizationType::Pointer param = ParametrizationType::New( );
    param->SetInput( mesh );
    param->SetBorderTransform( border_transform );

    int param_type;
    std::stringstream ssout3( argv[3] );
    ssout3 >>param_type;

    switch( param_type )
    {
        case 0:
            param->SetCoefficientsMethod( &coeff0 );
            break;
        case 1:
            param->SetCoefficientsMethod( &coeff1 );
            break;
        case 2:
            param->SetCoefficientsMethod( &coeff2 );
            break;
        case 3:
            param->SetCoefficientsMethod( &coeff3 );
            break;
        case 4:
            param->SetCoefficientsMethod( &coeff4 );
            break;
        default:
            std::cerr <<"3rd argument must be "<<std::endl;
            std::cerr <<"0, 1, 2, 3 or 4" <<std::endl;
            std::cerr <<"Here it is: " << param_type << std::endl;
            return EXIT_FAILURE;
    }

    // ** PROCESS **
    param->Update( );
    MeshType::Pointer output = param->GetOutput( );

    // ** TIMING **
    // clock_t end = clock( );
    // std::cout <<"Time: ";
    // std::cout <<static_cast< double >( end - start ) /
    //        static_cast< double >( CLOCKS_PER_SEC ) <<" s" <<std::endl;

    // ** WRITE OUTPUT **
    WriterType::Pointer writer = WriterType::New( );
    writer->SetInput( param->GetOutput( ) );
    writer->SetFileName( argv[4] );
    writer->Update( );

    // GET OUT OF HERE AND GET (YET ANOTHER) COFFEE
    return EXIT_SUCCESS;
}
<commit_msg>BUG: wrong signature for main program.<commit_after>// BELONG TO \REVIEW
#include <itkVTKPolyDataReader.h>
#include <itkVTKPolyDataWriter.h>
#include <itkQuadEdgeMesh.h>

// NEW
#include "itkQuadEdgeMeshBorderTransform.h"
#include "itkQuadEdgeMeshParamMatrixCoefficients.h"

// TIMING
#include <ctime>

#ifdef QuadEdgePARAM_TAUCS
    #include "TAUCSSparseSolverTraits.h"
#else
    #include "VNLIterativeSparseSolverTraits.h"
#endif

#include "itkQuadEdgeMeshParam.h"

using namespace itk;

int itkQuadEdgeMeshLinearParameterizationTest( int argc, char* argv[] )
{
    // ** ERROR MESSAGE AND HELP ** //
    if( argc < 5 )
    {
        std::cout <<"Requires 4 arguments: " <<std::endl;
        std::cout <<"1-Input file name " <<std::endl;
        std::cout <<"2-Border Type" <<std::endl;
        std::cout <<"   * 0: SQUARE" <<std::endl;
        std::cout <<"   * 1: DISK" <<std::endl;
        std::cout <<"3-CoefficientType Type" <<std::endl;
        std::cout <<"   * 0: OnesMatrixCoefficients" <<std::endl;
        std::cout <<"   * 1: InverseEuclideanDistanceMatrixCoefficients"
          <<std::endl;
        std::cout <<"   * 2: ConformalMatrixCoefficients" <<std::endl;
        std::cout <<"   * 3: AuthalicMatrixCoefficients" <<std::endl;
        std::cout <<"   * 4: HarmonicMatrixCoefficients" <<std::endl;
        std::cout <<"4-Output file name " <<std::endl;

        return EXIT_FAILURE;
    }

    // ** TYPEDEF **
    typedef double Coord;

    typedef QuadEdgeMesh< Coord, 3 >                      MeshType;
    typedef VTKPolyDataReader< MeshType >                 ReaderType;
    typedef VTKPolyDataWriter< MeshType >                 WriterType;
    typedef QuadEdgeMeshBorderTransform< MeshType, MeshType >     BorderTransformType;
#ifdef QuadEdgePARAM_TAUCS
    typedef TAUCSSolverTraits< Coord >                    SolverTraits;
#else
    typedef VNLIterativeSparseSolverTraits< Coord >       SolverTraits;
#endif
    typedef QuadEdgeMeshParam< MeshType, MeshType, SolverTraits > ParametrizationType;

    // ** READ THE FILE IN **
    ReaderType::Pointer reader = ReaderType::New( );
    reader->SetFileName( argv[1] );
    try
    {
      reader->Update( );
    }
    catch( itk::ExceptionObject & exp )
    {
      std::cerr << "Exception thrown while reading the input file " << std::endl;
      std::cerr << exp << std::endl;
      return EXIT_FAILURE;
    }

    MeshType::Pointer mesh = reader->GetOutput( );

    // ** CHOSE< COMPUTE AND SET BORDER TRANSFORM **
    // clock_t start = clock( );
    BorderTransformType::Pointer border_transform = BorderTransformType::New( );
    border_transform->SetInput( mesh );

    int border;
    std::stringstream ssout( argv[2] );
    ssout >>border;
    switch( border )  // choose border type
    {
        case 0: // square shaped domain
            border_transform->SetTransformType(
                BorderTransformType::SQUARE_BORDER_TRANSFORM );
            break;
        case 1: // disk shaped domain
            border_transform->SetTransformType(
                BorderTransformType::DISK_BORDER_TRANSFORM );
            break;
        default: // handle .... user ....
            std::cerr <<"2nd argument must be "<<std::endl;
            std::cerr <<"0 for SQUARE BORDER TRANSFORM or "
              <<"1 for DISK BORDER TRANSFORM" <<std::endl;
            return EXIT_FAILURE;
    }

    // ** CHOOSE AND SET BARYCENTRIC WEIGHTS **
    OnesMatrixCoefficients< MeshType >                     coeff0;
    InverseEuclideanDistanceMatrixCoefficients< MeshType > coeff1;
    ConformalMatrixCoefficients< MeshType >                coeff2;
    AuthalicMatrixCoefficients< MeshType >                 coeff3;
    HarmonicMatrixCoefficients< MeshType >                 coeff4;

    ParametrizationType::Pointer param = ParametrizationType::New( );
    param->SetInput( mesh );
    param->SetBorderTransform( border_transform );

    int param_type;
    std::stringstream ssout3( argv[3] );
    ssout3 >>param_type;

    switch( param_type )
    {
        case 0:
            param->SetCoefficientsMethod( &coeff0 );
            break;
        case 1:
            param->SetCoefficientsMethod( &coeff1 );
            break;
        case 2:
            param->SetCoefficientsMethod( &coeff2 );
            break;
        case 3:
            param->SetCoefficientsMethod( &coeff3 );
            break;
        case 4:
            param->SetCoefficientsMethod( &coeff4 );
            break;
        default:
            std::cerr <<"3rd argument must be "<<std::endl;
            std::cerr <<"0, 1, 2, 3 or 4" <<std::endl;
            std::cerr <<"Here it is: " << param_type << std::endl;
            return EXIT_FAILURE;
    }

    // ** PROCESS **
    param->Update( );
    MeshType::Pointer output = param->GetOutput( );

    // ** TIMING **
    // clock_t end = clock( );
    // std::cout <<"Time: ";
    // std::cout <<static_cast< double >( end - start ) /
    //        static_cast< double >( CLOCKS_PER_SEC ) <<" s" <<std::endl;

    // ** WRITE OUTPUT **
    WriterType::Pointer writer = WriterType::New( );
    writer->SetInput( param->GetOutput( ) );
    writer->SetFileName( argv[4] );
    writer->Update( );

    // GET OUT OF HERE AND GET (YET ANOTHER) COFFEE
    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2010-2011, Willow Garage, Inc.
 *
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of the copyright holder(s) nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id: test_segmentation.cpp 3564 2011-12-16 06:11:13Z rusu $
 *
 */

#include <gtest/gtest.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/io/pcd_io.h>
#include <pcl/ModelCoefficients.h>
#include <pcl/PointIndices.h>
#include <pcl/sample_consensus/model_types.h>
#include <pcl/sample_consensus/method_types.h>
#include <pcl/segmentation/sac_segmentation.h>

using namespace pcl;
using namespace pcl::io;

PointCloud<PointXYZ>::Ptr cloud_;

//////////////////////////////////////////////////////////////////////////////////////////////
TEST (SACSegmentation, Segmentation)
{
  ModelCoefficients::Ptr sphere_coefficients (new ModelCoefficients);
  PointIndices::Ptr inliers (new PointIndices);

  SACSegmentation<PointXYZ> seg;
  seg.setOptimizeCoefficients (true);
  seg.setModelType (SACMODEL_SPHERE);
  seg.setMethodType (SAC_RANSAC);
  seg.setMaxIterations (10000);
  seg.setDistanceThreshold (0.01);
  seg.setRadiusLimits (0.03, 0.07); // true radius is 0.05
  seg.setInputCloud (cloud_);
  seg.segment (*inliers, *sphere_coefficients);

  EXPECT_NEAR (sphere_coefficients->values[0], 0.998776,  1e-2);
  EXPECT_NEAR (sphere_coefficients->values[1], 0.752023,  1e-2);
  EXPECT_NEAR (sphere_coefficients->values[2], 1.24558,   1e-2);
  EXPECT_NEAR (sphere_coefficients->values[3], 0.0536238, 1e-2);

  EXPECT_NEAR (static_cast<int> (inliers->indices.size ()), 3516, 10);
}

//* ---[ */
int
  main (int argc, char** argv)
{
  if (argc < 2)
  {
    std::cerr << "No test file given. Please download `noisy_slice_displaced.pcd` and pass its path to the test." << std::endl;
    return (-1);
  }

  // Load a standard PCD file from disk
  PointCloud<PointXYZ> cloud;
  if (loadPCDFile (argv[1], cloud) < 0)
  {
    std::cerr << "Failed to read test file. Please download `noisy_slice_displaced.pcd` and pass its path to the test." << std::endl;
    return (-1);
  }

  cloud_   = cloud.makeShared ();

  testing::InitGoogleTest (&argc, argv);
  return (RUN_ALL_TESTS ());
}
/* ]--- */
<commit_msg>Increase threshold for expected value in test_non_linear<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2010-2011, Willow Garage, Inc.
 *
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of the copyright holder(s) nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id: test_segmentation.cpp 3564 2011-12-16 06:11:13Z rusu $
 *
 */

#include <gtest/gtest.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/io/pcd_io.h>
#include <pcl/ModelCoefficients.h>
#include <pcl/PointIndices.h>
#include <pcl/sample_consensus/model_types.h>
#include <pcl/sample_consensus/method_types.h>
#include <pcl/segmentation/sac_segmentation.h>

using namespace pcl;
using namespace pcl::io;

PointCloud<PointXYZ>::Ptr cloud_;

//////////////////////////////////////////////////////////////////////////////////////////////
TEST (SACSegmentation, Segmentation)
{
  ModelCoefficients::Ptr sphere_coefficients (new ModelCoefficients);
  PointIndices::Ptr inliers (new PointIndices);

  SACSegmentation<PointXYZ> seg;
  seg.setOptimizeCoefficients (true);
  seg.setModelType (SACMODEL_SPHERE);
  seg.setMethodType (SAC_RANSAC);
  seg.setMaxIterations (10000);
  seg.setDistanceThreshold (0.01);
  seg.setRadiusLimits (0.03, 0.07); // true radius is 0.05
  seg.setInputCloud (cloud_);
  seg.segment (*inliers, *sphere_coefficients);

  EXPECT_NEAR (sphere_coefficients->values[0], 0.998776,  1e-2);
  EXPECT_NEAR (sphere_coefficients->values[1], 0.752023,  1e-2);
  EXPECT_NEAR (sphere_coefficients->values[2], 1.24558,   1e-2);
  EXPECT_NEAR (sphere_coefficients->values[3], 0.0536238, 1e-2);

  EXPECT_NEAR (static_cast<int> (inliers->indices.size ()), 3516, 15);
}

//* ---[ */
int
  main (int argc, char** argv)
{
  if (argc < 2)
  {
    std::cerr << "No test file given. Please download `noisy_slice_displaced.pcd` and pass its path to the test." << std::endl;
    return (-1);
  }

  // Load a standard PCD file from disk
  PointCloud<PointXYZ> cloud;
  if (loadPCDFile (argv[1], cloud) < 0)
  {
    std::cerr << "Failed to read test file. Please download `noisy_slice_displaced.pcd` and pass its path to the test." << std::endl;
    return (-1);
  }

  cloud_   = cloud.makeShared ();

  testing::InitGoogleTest (&argc, argv);
  return (RUN_ALL_TESTS ());
}
/* ]--- */
<|endoftext|>


<commit_before>// RUN: %clang_cc1 -fms-extensions -fsyntax-only -verify %s
// RUN: %clang_cc1 -fms-extensions -fdelayed-template-parsing -fsyntax-only -verify %s

class A {
public:
  template<class U> A(U p) {}
  template<> A(int p) {
    // expected-warning@-1 {{explicit specialization of 'A' within class scope is a Microsoft extension}}
  }

  template<class U> void f(U p) {}

  template<> void f(int p) {
    // expected-warning@-1 {{explicit specialization of 'f' within class scope is a Microsoft extension}}
  }

  void f(int p) {}
};

void test1() {
  A a(3);
  char *b;
  a.f(b);
  a.f<int>(99);
  a.f(100);
}

template<class T> class B {
public:
  template<class U> B(U p) {}
  template<> B(int p) {
    // expected-warning@-1 {{explicit specialization of 'B<T>' within class scope is a Microsoft extension}}
  }

  template<class U> void f(U p) { T y = 9; }

  template<> void f(int p) {
    // expected-warning@-1 {{explicit specialization of 'f' within class scope is a Microsoft extension}}
    T a = 3;
  }

  void f(int p) { T a = 3; }
};

void test2() {
  B<char> b(3);
  char *ptr;
  b.f(ptr);
  b.f<int>(99);
  b.f(100);
}

namespace PR12709 {

template<class T> class TemplateClass {
  void member_function() { specialized_member_template<false>(); }

  template<bool b> void specialized_member_template() {}

  template<> void specialized_member_template<false>() {
    // expected-warning@-1 {{explicit specialization of 'specialized_member_template' within class scope is a Microsoft extension}}
  }
};

void f() { TemplateClass<int> t; }
}
<commit_msg>Add a testcase and a FIXME for an accepts-invalid.<commit_after>// RUN: %clang_cc1 -fms-extensions -fsyntax-only -verify %s
// RUN: %clang_cc1 -fms-extensions -fdelayed-template-parsing -fsyntax-only -verify %s

class A {
public:
  template<class U> A(U p) {}
  template<> A(int p) {
    // expected-warning@-1 {{explicit specialization of 'A' within class scope is a Microsoft extension}}
  }

  template<class U> void f(U p) {}

  template<> void f(int p) {
    // expected-warning@-1 {{explicit specialization of 'f' within class scope is a Microsoft extension}}
  }

  void f(int p) {}
};

void test1() {
  A a(3);
  char *b;
  a.f(b);
  a.f<int>(99);
  a.f(100);
}

template<class T> class B {
public:
  template<class U> B(U p) {}
  template<> B(int p) {
    // expected-warning@-1 {{explicit specialization of 'B<T>' within class scope is a Microsoft extension}}
  }

  template<class U> void f(U p) { T y = 9; }

  template<> void f(int p) {
    // expected-warning@-1 {{explicit specialization of 'f' within class scope is a Microsoft extension}}
    T a = 3;
  }

  void f(int p) { T a = 3; }
};

void test2() {
  B<char> b(3);
  char *ptr;
  b.f(ptr);
  b.f<int>(99);
  b.f(100);
}

namespace PR12709 {
  template<class T> class TemplateClass {
    void member_function() { specialized_member_template<false>(); }

    template<bool b> void specialized_member_template() {}

    template<> void specialized_member_template<false>() {
      // expected-warning@-1 {{explicit specialization of 'specialized_member_template' within class scope is a Microsoft extension}}
    }
  };

  void f() { TemplateClass<int> t; }
}

namespace Duplicates {
  template<typename T> struct A {
    template<typename U> void f();
    template<> void f<int>() {} // expected-warning {{Microsoft extension}}
    template<> void f<T>() {} // expected-warning {{Microsoft extension}}
  };

  // FIXME: We should diagnose the duplicate explicit specialization definitions
  // here.
  template struct A<int>;
}
<|endoftext|>


<commit_before>/*	____________________________________________________________________________

	                 Scanner Component for the Micro A Compiler

	                                mscan.h

	                              Version 2007 - 2016

	                           James L. Richards
	                     Last Update: August 28, 2007
	                      	   Nelson A Castillo
	                     Last Update: January 31, 2016

	The routines in this unit are based on those provided in the book
	"Crafting A Compiler" by Charles N. Fischer and Richard J. LeBlanc, Jr.,
	Benjamin Cummings Publishing Co. (1991).

	See Section 2.2, pp. 25-29.
	____________________________________________________________________________
*/

#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;

extern ifstream sourceFile;
extern ofstream outFile, listFile;

#include "mscan.h"

// *******************
// **  Constructor  **
// *******************

Scanner::Scanner()
{
	tokenBuffer = "";
	lineBuffer = "";
	lineNumber = 0;
}

// ********************************
// **  Private Member Functions  **
// ********************************

void Scanner::BufferChar(char c)
{
	if (tokenBuffer.length() < ID_STRING_LEN){
		tokenBuffer += c;
	}
	//cerr << tokenBuffer << endl;
}
void Scanner::BufferString(char c)
{
	stringBuffer += c;
	//cerr << tokenBuffer << endl;
}

Token Scanner::CheckReserved()
{
	/* Convert the string to lower case */
	transform(tokenBuffer.begin(), tokenBuffer.end(), \
				tokenBuffer.begin(), ::tolower);
	/* Check the converted words */
	if ((tokenBuffer) == "bool") return BOOL_SYM;
	if ((tokenBuffer) == "break") return BREAK_SYM;
	if ((tokenBuffer) == "case") return CASE_SYM;
	if ((tokenBuffer) == "cheese") return CHEESE_SYM;
	if ((tokenBuffer) == "decs") return DECS_SYM;
	if ((tokenBuffer) == "do") return DO_SYM;
	if ((tokenBuffer) == "else") return ELSE_SYM;
	if ((tokenBuffer) == "end") return END_SYM;
	if ((tokenBuffer) == "false") return FALSE_SYM;
	if ((tokenBuffer) == "float") return FLOAT_SYM;
	if ((tokenBuffer) == "for") return FOR_SYM;
	if ((tokenBuffer) == "hiphip") return HIPHIP_SYM;
	if ((tokenBuffer) == "if") return IF_SYM;
	if ((tokenBuffer) == "int") return INT_SYM;
	if ((tokenBuffer) == "listen") return LISTEN_SYM;
	if ((tokenBuffer) == "otherwise") return OTHERWISE_SYM;
	if ((tokenBuffer) == "select") return SELECT_SYM;
	if ((tokenBuffer) == "shout") return SHOUT_SYM;
	if ((tokenBuffer) == "then") return THEN_SYM;
	if ((tokenBuffer) == "true") return TRUE_SYM;
	if ((tokenBuffer) == "while") return WHILE_SYM;

	return ID;
}

void Scanner::ClearBuffer()
{
	tokenBuffer = "";
	stringBuffer = "";
}

void Scanner::LexicalError(char& c)
{
	cout << " *** Lexical Error: '" << c
		<< "' ignored at position " << int(lineBuffer.size())
		<< " on line #" << lineNumber + 1 << '.' << endl;
	listFile << " *** Lexical Error: '" << c
		<< "' ignored at position " << int(lineBuffer.size())
		<< " on line #" << lineNumber + 1 << '.' << endl;

	c = NextChar();
}
void Scanner::LexicalError(char& c, const string& errorExp)
{
	cout << " *** Lexical Error: '" << c
		<< "' ignored at position " << int(lineBuffer.size())
		<< " on line #" << lineNumber + 1 << '.' << '\n'
		<< errorExp << endl;
	listFile << " *** Lexical Error: '" << c
		<< "' ignored at position " << int(lineBuffer.size())
		<< " on line #" << lineNumber + 1 << '.' << '\n'
		<< errorExp << endl;

	c = NextChar();
}

char Scanner::NextChar()
{
	char c;

	sourceFile.get(c);
	if (c == '\n')
	{
		listFile.width(6);
		listFile << ++lineNumber << "  " << lineBuffer << endl;
		lineBuffer = "";
	} else{
		lineBuffer += c;
	}
	return c;
}

// *******************************
// **  Public Member Functions  **
// *******************************

Token Scanner::GetNextToken()
{
	char currentChar, c;

	ClearBuffer();
	currentChar = NextChar();
	while (!sourceFile.eof())
	{
		if (isspace(currentChar)) {
			/* do nothing */
			currentChar = NextChar();
		} else if (isalpha(currentChar)) {
			/* identifier */
			BufferChar(currentChar);
			c = sourceFile.peek();
			while (isalnum(c) || c == '_') {
				currentChar = NextChar();
				BufferChar(currentChar);
				c = sourceFile.peek();
			}
			return CheckReserved();
		} else if (isdigit(currentChar)) {
			/* integer or float literals */
			BufferChar(currentChar);
			c = sourceFile.peek();
			while (isdigit(c)) {
				currentChar = NextChar();
				BufferChar(currentChar);
				c = sourceFile.peek();
			}
			/* check if it is a float */
			if (c == '.') {
				currentChar = NextChar();
				c = sourceFile.peek();
				/* check for a digit after the '.' */
				if (!isdigit(c))
					LexicalError(currentChar, to_string(c)+" Boolean needs a digit after the '.'");
				BufferChar(currentChar);
				while (isdigit(c)) {
					currentChar = NextChar();
					BufferChar(currentChar);
					c = sourceFile.peek();
				}
				/* check for power of 10 multipliers */
				if (c == 'e' || c == 'E') {
					currentChar = NextChar();
					c = sourceFile.peek();
					if (c != '+' && c!= '-') {
						LexicalError(currentChar, to_string(c)+" Boolean needs a '+' or a '-' after 'E' ");
					}
					BufferChar(currentChar);
					currentChar = NextChar();
					c = sourceFile.peek();
					if (!isdigit(c))
						LexicalError(currentChar, to_string(c)+"Boolean needs a  digit after '+' or '-'");
					BufferChar(currentChar);
					while (isdigit(c)) {
						currentChar = NextChar();
						BufferChar(currentChar);
						c = sourceFile.peek();
					}
				}
				return FLOAT_LIT;
			}
			return INT_LIT;
		} else if (currentChar == '"') {
			// string literal
			// BufferString(currentChar);
			do {
				currentChar = NextChar();
				// cout << currentChar <<endl;
				if (currentChar == '"' \
						& sourceFile.peek() != '"') {
					// BufferString(currentChar);
					// cout << "________________________" <<endl;
					// cout << stringBuffer <<endl;
					// cout << "________________________" <<endl;
					return CHEESE_LIT;
				} else if (currentChar == '"' \
						& sourceFile.peek() == '"') {
					currentChar = NextChar();
				}
				BufferString(currentChar);
			} while (sourceFile.peek()!='\n');
			return CHEESE_LIT;
		} else if (currentChar == '(') {
			BufferChar(currentChar);
			return LBANANA;
		} else if (currentChar == ')') {
			BufferChar(currentChar);
			return RBANANA;
		} else if (currentChar == '[') {
			BufferChar(currentChar);
			return LSTAPLE;
		} else if (currentChar == ']') {
			BufferChar(currentChar);
			return RSTAPLE;
		} else if (currentChar == '{') {
			BufferChar(currentChar);
			return LMUSTACHE;
		} else if (currentChar == '}') {
			BufferChar(currentChar);
			return RMUSTACHE;
		} else if (currentChar == ';') {
			BufferChar(currentChar);
			return SEMICOLON;
		} else if (currentChar == ':') {
			BufferChar(currentChar);
			return COLON;
		} else if (currentChar == ',') {
			BufferChar(currentChar);
			return COMMA;
		} else if (currentChar == '+') {
			BufferChar(currentChar);
			return PLUS_OP;
		} else if (currentChar == '*') {
			BufferChar(currentChar);
			return MULT_OP;
		} else if (currentChar == '/') {
			/* check if it is a multiline comment */
			if (sourceFile.peek() == ':') {
				do { /* skip comment */
					currentChar = NextChar();
					if (currentChar == ':') {
						currentChar = NextChar();
						if (currentChar == '/') {
							currentChar = NextChar();
							break;
						}
					}
				} while (!sourceFile.eof());
			} else {
				/* if it is a division operator */
				BufferChar(currentChar);
				return DIV_OP;
			}
		} else if (currentChar == '=') {
			if (sourceFile.peek() == '=') {
				currentChar = NextChar();
				return EQ_OP1;
			}
			currentChar = NextChar();
			return ASSIGN_OP;
		} else if (currentChar == '!') {
			if (sourceFile.peek() == '!') {
				currentChar = NextChar();
				return EQ_OP2;
			} else if (sourceFile.peek() == '=') {
				currentChar = NextChar();
				return NE_OP;
			} else {
				LexicalError(currentChar, to_string(c) + \
						" not operator is not" \
						" supported by MnC");
			}
		} else if (currentChar == '<') {
			if (sourceFile.peek() == '=') {
				currentChar = NextChar();
				return LE_OP;
			}
			currentChar = NextChar();
			return LT_OP;
		} else if (currentChar == '>') {
			if (sourceFile.peek() == '=') {
				currentChar = NextChar();
				return GE_OP;
			}
			currentChar = NextChar();
			return GT_OP;
		} else if (currentChar == '-') {
			/* check if it is a comment or a minus symbol */
			if (sourceFile.peek() == '-') { /* comment */
				do { /* skip comment */
					currentChar = NextChar();
				} while (currentChar != '\n');
			} else { /* minus operator */
				BufferChar(currentChar);
				return MINUS_OP;
			}
		} else {
			/* Unrecognized character */
			LexicalError(currentChar, to_string(c)+" Unrecognized character");
		}
	} /* end while */

	return EOF_SYM;
}
<commit_msg>scan: consume and buffer chars properly.<commit_after>/*	____________________________________________________________________________

	                 Scanner Component for the Micro A Compiler

	                                mscan.h

	                              Version 2007 - 2016

	                           James L. Richards
	                     Last Update: August 28, 2007
	                      	   Nelson A Castillo
	                     Last Update: January 31, 2016

	The routines in this unit are based on those provided in the book
	"Crafting A Compiler" by Charles N. Fischer and Richard J. LeBlanc, Jr.,
	Benjamin Cummings Publishing Co. (1991).

	See Section 2.2, pp. 25-29.
	____________________________________________________________________________
*/

#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;

extern ifstream sourceFile;
extern ofstream outFile, listFile;

#include "mscan.h"

// *******************
// **  Constructor  **
// *******************

Scanner::Scanner()
{
	tokenBuffer = "";
	lineBuffer = "";
	lineNumber = 0;
}

// ********************************
// **  Private Member Functions  **
// ********************************

void Scanner::BufferChar(char c)
{
	if (tokenBuffer.length() < ID_STRING_LEN){
		tokenBuffer += c;
	}
	//cerr << tokenBuffer << endl;
}
void Scanner::BufferString(char c)
{
	stringBuffer += c;
	//cerr << tokenBuffer << endl;
}

Token Scanner::CheckReserved()
{
	/* Convert the string to lower case */
	transform(tokenBuffer.begin(), tokenBuffer.end(), \
				tokenBuffer.begin(), ::tolower);
	/* Check the converted words */
	if ((tokenBuffer) == "bool") return BOOL_SYM;
	if ((tokenBuffer) == "break") return BREAK_SYM;
	if ((tokenBuffer) == "case") return CASE_SYM;
	if ((tokenBuffer) == "cheese") return CHEESE_SYM;
	if ((tokenBuffer) == "decs") return DECS_SYM;
	if ((tokenBuffer) == "do") return DO_SYM;
	if ((tokenBuffer) == "else") return ELSE_SYM;
	if ((tokenBuffer) == "end") return END_SYM;
	if ((tokenBuffer) == "false") return FALSE_SYM;
	if ((tokenBuffer) == "float") return FLOAT_SYM;
	if ((tokenBuffer) == "for") return FOR_SYM;
	if ((tokenBuffer) == "hiphip") return HIPHIP_SYM;
	if ((tokenBuffer) == "if") return IF_SYM;
	if ((tokenBuffer) == "int") return INT_SYM;
	if ((tokenBuffer) == "listen") return LISTEN_SYM;
	if ((tokenBuffer) == "otherwise") return OTHERWISE_SYM;
	if ((tokenBuffer) == "select") return SELECT_SYM;
	if ((tokenBuffer) == "shout") return SHOUT_SYM;
	if ((tokenBuffer) == "then") return THEN_SYM;
	if ((tokenBuffer) == "true") return TRUE_SYM;
	if ((tokenBuffer) == "while") return WHILE_SYM;

	return ID;
}

void Scanner::ClearBuffer()
{
	tokenBuffer = "";
	stringBuffer = "";
}

void Scanner::LexicalError(char& c)
{
	cout << " *** Lexical Error: '" << c
		<< "' ignored at position " << int(lineBuffer.size())
		<< " on line #" << lineNumber + 1 << '.' << endl;
	listFile << " *** Lexical Error: '" << c
		<< "' ignored at position " << int(lineBuffer.size())
		<< " on line #" << lineNumber + 1 << '.' << endl;

	c = NextChar();
}
void Scanner::LexicalError(char& c, const string& errorExp)
{
	cout << " *** Lexical Error: '" << c
		<< "' ignored at position " << int(lineBuffer.size())
		<< " on line #" << lineNumber + 1 << '.' << '\n'
		<< errorExp << endl;
	listFile << " *** Lexical Error: '" << c
		<< "' ignored at position " << int(lineBuffer.size())
		<< " on line #" << lineNumber + 1 << '.' << '\n'
		<< errorExp << endl;

	c = NextChar();
}

char Scanner::NextChar()
{
	char c;

	sourceFile.get(c);
	if (c == '\n')
	{
		listFile.width(6);
		listFile << ++lineNumber << "  " << lineBuffer << endl;
		lineBuffer = "";
	} else{
		lineBuffer += c;
	}
	return c;
}

// *******************************
// **  Public Member Functions  **
// *******************************

Token Scanner::GetNextToken()
{
	char currentChar, c;

	ClearBuffer();
	currentChar = NextChar();
	while (!sourceFile.eof())
	{
		if (isspace(currentChar)) {
			/* do nothing */
			currentChar = NextChar();
		} else if (isalpha(currentChar)) {
			/* identifier */
			BufferChar(currentChar);
			c = sourceFile.peek();
			while (isalnum(c) || c == '_') {
				currentChar = NextChar();
				BufferChar(currentChar);
				c = sourceFile.peek();
			}
			return CheckReserved();
		} else if (isdigit(currentChar)) {
			/* integer or float literals */
			BufferChar(currentChar);
			c = sourceFile.peek();
			while (isdigit(c)) {
				currentChar = NextChar();
				BufferChar(currentChar);
				c = sourceFile.peek();
			}
			/* check if it is a float */
			if (c == '.') {
				currentChar = NextChar();
				c = sourceFile.peek();
				/* check for a digit after the '.' */
				if (!isdigit(c))
					LexicalError(currentChar, to_string(c)+" Boolean needs a digit after the '.'");
				BufferChar(currentChar);
				while (isdigit(c)) {
					currentChar = NextChar();
					BufferChar(currentChar);
					c = sourceFile.peek();
				}
				/* check for power of 10 multipliers */
				if (c == 'e' || c == 'E') {
					currentChar = NextChar();
					c = sourceFile.peek();
					if (c != '+' && c!= '-') {
						LexicalError(currentChar, to_string(c)+" Boolean needs a '+' or a '-' after 'E' ");
					}
					BufferChar(currentChar);
					currentChar = NextChar();
					c = sourceFile.peek();
					if (!isdigit(c))
						LexicalError(currentChar, to_string(c)+"Boolean needs a  digit after '+' or '-'");
					BufferChar(currentChar);
					while (isdigit(c)) {
						currentChar = NextChar();
						BufferChar(currentChar);
						c = sourceFile.peek();
					}
				}
				return FLOAT_LIT;
			}
			return INT_LIT;
		} else if (currentChar == '"') {
			// string literal
			// BufferString(currentChar);
			do {
				currentChar = NextChar();
				// cout << currentChar <<endl;
				if (currentChar == '"' \
						& sourceFile.peek() != '"') {
					// BufferString(currentChar);
					// cout << "________________________" <<endl;
					// cout << stringBuffer <<endl;
					// cout << "________________________" <<endl;
					return CHEESE_LIT;
				} else if (currentChar == '"' \
						& sourceFile.peek() == '"') {
					currentChar = NextChar();
				}
				BufferString(currentChar);
			} while (sourceFile.peek()!='\n');
			return CHEESE_LIT;
		} else if (currentChar == '(') {
			BufferChar(currentChar);
			return LBANANA;
		} else if (currentChar == ')') {
			BufferChar(currentChar);
			return RBANANA;
		} else if (currentChar == '[') {
			BufferChar(currentChar);
			return LSTAPLE;
		} else if (currentChar == ']') {
			BufferChar(currentChar);
			return RSTAPLE;
		} else if (currentChar == '{') {
			BufferChar(currentChar);
			return LMUSTACHE;
		} else if (currentChar == '}') {
			BufferChar(currentChar);
			return RMUSTACHE;
		} else if (currentChar == ';') {
			BufferChar(currentChar);
			return SEMICOLON;
		} else if (currentChar == ':') {
			BufferChar(currentChar);
			return COLON;
		} else if (currentChar == ',') {
			BufferChar(currentChar);
			return COMMA;
		} else if (currentChar == '+') {
			BufferChar(currentChar);
			return PLUS_OP;
		} else if (currentChar == '*') {
			BufferChar(currentChar);
			return MULT_OP;
		} else if (currentChar == '/') {
			/* check if it is a multiline comment */
			if (sourceFile.peek() == ':') {
				do { /* skip comment */
					currentChar = NextChar();
					if (currentChar == ':') {
						currentChar = NextChar();
						if (currentChar == '/') {
							currentChar = NextChar();
							break;
						}
					}
				} while (!sourceFile.eof());
			} else {
				/* if it is a division operator */
				BufferChar(currentChar);
				return DIV_OP;
			}
		} else if (currentChar == '=') {
			BufferChar(currentChar);
			if (sourceFile.peek() == '=') {
				currentChar = NextChar();
				BufferChar(currentChar);
				return EQ_OP1;
			}
			currentChar = NextChar();
			return ASSIGN_OP;
		} else if (currentChar == '!') {
			BufferChar(currentChar);
			if (sourceFile.peek() == '!') {
				currentChar = NextChar();
				BufferChar(currentChar);
				return EQ_OP2;
			} else if (sourceFile.peek() == '=') {
				currentChar = NextChar();
				BufferChar(currentChar);
				return NE_OP;
			} else {
				LexicalError(currentChar, to_string(c) + \
						" not operator is not" \
						" supported by MnC");
			}
			currentChar = NextChar();
		} else if (currentChar == '<') {
			BufferChar(currentChar);
			if (sourceFile.peek() == '=') {
				currentChar = NextChar();
				BufferChar(currentChar);
				return LE_OP;
			}
			currentChar = NextChar();
			return LT_OP;
		} else if (currentChar == '>') {
			BufferChar(currentChar);
			if (sourceFile.peek() == '=') {
				currentChar = NextChar();
				BufferChar(currentChar);
				return GE_OP;
			}
			currentChar = NextChar();
			return GT_OP;
		} else if (currentChar == '-') {
			/* check if it is a comment or a minus symbol */
			if (sourceFile.peek() == '-') { /* comment */
				do { /* skip comment */
					currentChar = NextChar();
				} while (currentChar != '\n');
			} else { /* minus operator */
				BufferChar(currentChar);
				currentChar = NextChar();
				return MINUS_OP;
			}
		} else {
			/* Unrecognized character */
			LexicalError(currentChar, to_string(c)+" Unrecognized character");
		}
	} /* end while */

	return EOF_SYM;
}
<|endoftext|>