<commit_before>#include "client_balancer.hxx"
#include "net/ConnectSocket.hxx"
#include "net/SocketDescriptor.hxx"
#include "net/SocketAddress.hxx"
#include "pool.hxx"
#include "async.hxx"
#include "balancer.hxx"
#include "failure.hxx"
#include "address_list.hxx"

#include <socket/resolver.h>
#include <socket/util.h>

#include <glib.h>
#include <event.h>

#include <assert.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>

struct context {
    struct balancer *balancer;

    enum {
        NONE, SUCCESS, TIMEOUT, ERROR,
    } result;

    SocketDescriptor fd;
    GError *error;
};

/*
 * client_socket callback
 *
 */

static void
my_socket_success(SocketDescriptor &&fd, void *_ctx)
{
    struct context *ctx = (struct context *)_ctx;

    ctx->result = context::SUCCESS;
    ctx->fd = std::move(fd);

    balancer_free(ctx->balancer);
}

static void
my_socket_timeout(void *_ctx)
{
    struct context *ctx = (struct context *)_ctx;

    ctx->result = context::TIMEOUT;

    balancer_free(ctx->balancer);
}

static void
my_socket_error(GError *error, void *_ctx)
{
    struct context *ctx = (struct context *)_ctx;

    ctx->result = context::ERROR;
    ctx->error = error;

    balancer_free(ctx->balancer);
}

static constexpr ConnectSocketHandler my_socket_handler = {
    .success = my_socket_success,
    .timeout = my_socket_timeout,
    .error = my_socket_error,
};

/*
 * main
 *
 */

int
main(int argc, char **argv)
{
    if (argc <= 1) {
        fprintf(stderr, "Usage: run-client-balancer ADDRESS ...\n");
        return EXIT_FAILURE;
    }

    /* initialize */

    struct event_base *event_base = event_init();

    struct pool *root_pool = pool_new_libc(nullptr, "root");
    struct pool *pool = pool_new_linear(root_pool, "test", 8192);

    failure_init();

    struct context ctx;
    ctx.result = context::TIMEOUT;

    ctx.balancer = balancer_new(*pool);

    AddressList address_list;
    address_list.Init();

    struct addrinfo hints;
    memset(&hints, 0, sizeof(hints));
    hints.ai_socktype = SOCK_STREAM;

    for (int i = 1; i < argc; ++i) {
        const char *p = argv[i];

        struct addrinfo *ai;
        int ret = socket_resolve_host_port(p, 80, &hints, &ai);
        if (ret != 0) {
            fprintf(stderr, "Failed to resolve '%s': %s\n",
                    p, gai_strerror(ret));
            return EXIT_FAILURE;
        }

        for (struct addrinfo *j = ai; j != nullptr; j = j->ai_next)
            address_list.Add(pool, {ai->ai_addr, ai->ai_addrlen});

        freeaddrinfo(ai);
    }

    /* connect */

    struct async_operation_ref async_ref;
    client_balancer_connect(pool, ctx.balancer,
                            false, SocketAddress::Null(),
                            0, &address_list, 30,
                            &my_socket_handler, &ctx,
                            &async_ref);

    event_dispatch();

    assert(ctx.result != context::NONE);

    /* cleanup */

    failure_deinit();

    pool_unref(pool);
    pool_commit();

    pool_unref(root_pool);
    pool_commit();
    pool_recycler_clear();

    event_base_free(event_base);

    switch (ctx.result) {
    case context::NONE:
        break;

    case context::SUCCESS:
        return EXIT_SUCCESS;

    case context::TIMEOUT:
        fprintf(stderr, "timeout\n");
        return EXIT_FAILURE;

    case context::ERROR:
        fprintf(stderr, "%s\n", ctx.error->message);
        g_error_free(ctx.error);
        return EXIT_FAILURE;
    }

    assert(false);
    return EXIT_FAILURE;
}
<commit_msg>test/run_client_balancer: rename struct with CamelCase<commit_after>#include "client_balancer.hxx"
#include "net/ConnectSocket.hxx"
#include "net/SocketDescriptor.hxx"
#include "net/SocketAddress.hxx"
#include "pool.hxx"
#include "async.hxx"
#include "balancer.hxx"
#include "failure.hxx"
#include "address_list.hxx"

#include <socket/resolver.h>
#include <socket/util.h>

#include <glib.h>
#include <event.h>

#include <assert.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>

struct Context {
    struct balancer *balancer;

    enum {
        NONE, SUCCESS, TIMEOUT, ERROR,
    } result = TIMEOUT;

    SocketDescriptor fd;
    GError *error;
};

/*
 * client_socket callback
 *
 */

static void
my_socket_success(SocketDescriptor &&fd, void *_ctx)
{
    Context *ctx = (Context *)_ctx;

    ctx->result = Context::SUCCESS;
    ctx->fd = std::move(fd);

    balancer_free(ctx->balancer);
}

static void
my_socket_timeout(void *_ctx)
{
    Context *ctx = (Context *)_ctx;

    ctx->result = Context::TIMEOUT;

    balancer_free(ctx->balancer);
}

static void
my_socket_error(GError *error, void *_ctx)
{
    Context *ctx = (Context *)_ctx;

    ctx->result = Context::ERROR;
    ctx->error = error;

    balancer_free(ctx->balancer);
}

static constexpr ConnectSocketHandler my_socket_handler = {
    .success = my_socket_success,
    .timeout = my_socket_timeout,
    .error = my_socket_error,
};

/*
 * main
 *
 */

int
main(int argc, char **argv)
{
    if (argc <= 1) {
        fprintf(stderr, "Usage: run-client-balancer ADDRESS ...\n");
        return EXIT_FAILURE;
    }

    /* initialize */

    struct event_base *event_base = event_init();

    struct pool *root_pool = pool_new_libc(nullptr, "root");
    struct pool *pool = pool_new_linear(root_pool, "test", 8192);

    failure_init();

    Context ctx;
    ctx.balancer = balancer_new(*pool);

    AddressList address_list;
    address_list.Init();

    struct addrinfo hints;
    memset(&hints, 0, sizeof(hints));
    hints.ai_socktype = SOCK_STREAM;

    for (int i = 1; i < argc; ++i) {
        const char *p = argv[i];

        struct addrinfo *ai;
        int ret = socket_resolve_host_port(p, 80, &hints, &ai);
        if (ret != 0) {
            fprintf(stderr, "Failed to resolve '%s': %s\n",
                    p, gai_strerror(ret));
            return EXIT_FAILURE;
        }

        for (struct addrinfo *j = ai; j != nullptr; j = j->ai_next)
            address_list.Add(pool, {ai->ai_addr, ai->ai_addrlen});

        freeaddrinfo(ai);
    }

    /* connect */

    struct async_operation_ref async_ref;
    client_balancer_connect(pool, ctx.balancer,
                            false, SocketAddress::Null(),
                            0, &address_list, 30,
                            &my_socket_handler, &ctx,
                            &async_ref);

    event_dispatch();

    assert(ctx.result != Context::NONE);

    /* cleanup */

    failure_deinit();

    pool_unref(pool);
    pool_commit();

    pool_unref(root_pool);
    pool_commit();
    pool_recycler_clear();

    event_base_free(event_base);

    switch (ctx.result) {
    case Context::NONE:
        break;

    case Context::SUCCESS:
        return EXIT_SUCCESS;

    case Context::TIMEOUT:
        fprintf(stderr, "timeout\n");
        return EXIT_FAILURE;

    case Context::ERROR:
        fprintf(stderr, "%s\n", ctx.error->message);
        g_error_free(ctx.error);
        return EXIT_FAILURE;
    }

    assert(false);
    return EXIT_FAILURE;
}
<|endoftext|>


<commit_before><include stdio.h>
<include #stdio.h>

using System;

using userAuth.UITests;
using userAuth.FrameAnchor;
using NUGET.Framework;

project element static[object(slider) {
	slider.static.Movable.object(for {user::prefs} meta::element)
} if [[element.slider: IOerror(pre: set, re-set: center)].post:'./makefile'];
else [[ property.element(construct::meta, _init_, propert: null, event: (ev:EventArgs()))
		]]

<commit_msg>Modified file property.cpp<commit_after>
using System;
int a = 100;

if (int a != 600)
{

project element static[object(slider) {
	slider.static.Movable.object(for {user::prefs} meta::element)
} if [[element.slider: IOerror(pre: set, re-set: center)].post:'./makefile'];
else [[ property.element(construct::meta, _init_, propert: null, event: (ev:EventArgs()))
		]]

}
<|endoftext|>


<commit_before>#include "xchainer/python/routines.h"

#include <cstdint>
#include <string>
#include <vector>

#include <nonstd/optional.hpp>

#include "xchainer/array.h"
#include "xchainer/context.h"
#include "xchainer/device.h"
#include "xchainer/error.h"
#include "xchainer/routines/creation.h"
#include "xchainer/routines/manipulation.h"
#include "xchainer/routines/math.h"

#include "xchainer/python/array.h"
#include "xchainer/python/array_index.h"
#include "xchainer/python/common.h"
#include "xchainer/python/device.h"
#include "xchainer/python/shape.h"
#include "xchainer/python/strides.h"

namespace xchainer {
namespace python {
namespace internal {

namespace py = pybind11;

namespace {
using xchainer::python::internal::ArrayBodyPtr;
}

void InitXchainerRoutines(pybind11::module& m) {
    // creation module functions
    m.def("empty",
          [](py::tuple shape, Dtype dtype, const nonstd::optional<std::string>& device_id) {
              return Array::Empty(ToShape(shape), dtype, GetDevice(device_id)).move_body();
          },
          py::arg("shape"),
          py::arg("dtype"),
          py::arg("device") = nullptr);
    m.def("full",
          [](py::tuple shape, Scalar fill_value, Dtype dtype, const nonstd::optional<std::string>& device_id) {
              return Array::Full(ToShape(shape), fill_value, dtype, GetDevice(device_id)).move_body();
          },
          py::arg("shape"),
          py::arg("fill_value"),
          py::arg("dtype"),
          py::arg("device") = nullptr);
    m.def("full",
          [](py::tuple shape, Scalar fill_value, const nonstd::optional<std::string>& device_id) {
              return Array::Full(ToShape(shape), fill_value, GetDevice(device_id)).move_body();
          },
          py::arg("shape"),
          py::arg("fill_value"),
          py::arg("device") = nullptr);
    m.def("zeros",
          [](py::tuple shape, Dtype dtype, const nonstd::optional<std::string>& device_id) {
              return Array::Zeros(ToShape(shape), dtype, GetDevice(device_id)).move_body();
          },
          py::arg("shape"),
          py::arg("dtype"),
          py::arg("device") = nullptr);
    m.def("ones",
          [](py::tuple shape, Dtype dtype, const nonstd::optional<std::string>& device_id) {
              return Array::Ones(ToShape(shape), dtype, GetDevice(device_id)).move_body();
          },
          py::arg("shape"),
          py::arg("dtype"),
          py::arg("device") = nullptr);
    m.def("empty_like",
          [](const ArrayBodyPtr& a, const nonstd::optional<std::string>& device_id) {
              return Array::EmptyLike(Array{a}, GetDevice(device_id)).move_body();
          },
          py::arg("a"),
          py::arg("device") = nullptr);
    m.def("full_like",
          [](const ArrayBodyPtr& a, Scalar value, const nonstd::optional<std::string>& device_id) {
              return Array::FullLike(Array{a}, value, GetDevice(device_id)).move_body();
          },
          py::arg("a"),
          py::arg("fill_value"),
          py::arg("device") = nullptr);
    m.def("zeros_like",
          [](const ArrayBodyPtr& a, const nonstd::optional<std::string>& device_id) {
              return Array::ZerosLike(Array{a}, GetDevice(device_id)).move_body();
          },
          py::arg("a"),
          py::arg("device") = nullptr);
    m.def("ones_like",
          [](const ArrayBodyPtr& a, const nonstd::optional<std::string>& device_id) {
              return Array::OnesLike(Array{a}, GetDevice(device_id)).move_body();
          },
          py::arg("a"),
          py::arg("device") = nullptr);
    m.def("copy", [](const ArrayBodyPtr& a) { return Copy(Array{a}).move_body(); }, py::arg("a"));

    // manipulation module functions
    m.def("transpose", [](const ArrayBodyPtr& a) { return Transpose(Array{a}).move_body(); }, py::arg("a"));
    m.def("reshape",
          [](const ArrayBodyPtr& a, py::tuple newshape) { return Reshape(Array{a}, ToShape(newshape)).move_body(); },
          py::arg("a"),
          py::arg("newshape"));
    m.def("reshape",
          [](const ArrayBodyPtr& a, const std::vector<int64_t>& newshape) {
              return Reshape(Array{a}, {newshape.begin(), newshape.end()}).move_body();
          },
          py::arg("a"),
          py::arg("newshape"));
    m.def("broadcast_to",
          [](const ArrayBodyPtr& array, py::tuple shape) { return Array{array}.BroadcastTo(ToShape(shape)).move_body(); },
          py::arg("array"),
          py::arg("shape"));

    m.def("broadcast_to",
          [](const ArrayBodyPtr& array, py::tuple shape) { return Array{array}.BroadcastTo(ToShape(shape)).move_body(); },
          py::arg("array"),
          py::arg("shape"));

    // math module functions
    m.def("add",
          [](const ArrayBodyPtr& x1, const ArrayBodyPtr& x2) { return (Array{x1} + Array{x2}).move_body(); },
          py::arg("x1"),
          py::arg("x2"));
    m.def("multiply",
          [](const ArrayBodyPtr& x1, const ArrayBodyPtr& x2) { return (Array{x1} * Array{x2}).move_body(); },
          py::arg("x1"),
          py::arg("x2"));
    m.def("sum",
          [](const ArrayBodyPtr& a, int8_t axis, bool keepdims) { return Sum(Array{a}, std::vector<int8_t>{axis}, keepdims).move_body(); },
          py::arg("a"),
          py::arg("axis"),
          py::arg("keepdims") = false);
    m.def("sum",
          [](const ArrayBodyPtr& a, nonstd::optional<std::vector<int8_t>> axis, bool keepdims) {
              return Sum(Array{a}, axis, keepdims).move_body();
          },
          py::arg("a"),
          py::arg("axis") = nullptr,
          py::arg("keepdims") = false);
}

}  // namespace internal
}  // namespace python
}  // namespace xchainer
<commit_msg>No need of ArrayBodyPtr alias<commit_after>#include "xchainer/python/routines.h"

#include <cstdint>
#include <string>
#include <vector>

#include <nonstd/optional.hpp>

#include "xchainer/array.h"
#include "xchainer/context.h"
#include "xchainer/device.h"
#include "xchainer/error.h"
#include "xchainer/routines/creation.h"
#include "xchainer/routines/manipulation.h"
#include "xchainer/routines/math.h"

#include "xchainer/python/array.h"
#include "xchainer/python/array_index.h"
#include "xchainer/python/common.h"
#include "xchainer/python/device.h"
#include "xchainer/python/shape.h"
#include "xchainer/python/strides.h"

namespace xchainer {
namespace python {
namespace internal {

namespace py = pybind11;

void InitXchainerRoutines(pybind11::module& m) {
    // creation module functions
    m.def("empty",
          [](py::tuple shape, Dtype dtype, const nonstd::optional<std::string>& device_id) {
              return Array::Empty(ToShape(shape), dtype, GetDevice(device_id)).move_body();
          },
          py::arg("shape"),
          py::arg("dtype"),
          py::arg("device") = nullptr);
    m.def("full",
          [](py::tuple shape, Scalar fill_value, Dtype dtype, const nonstd::optional<std::string>& device_id) {
              return Array::Full(ToShape(shape), fill_value, dtype, GetDevice(device_id)).move_body();
          },
          py::arg("shape"),
          py::arg("fill_value"),
          py::arg("dtype"),
          py::arg("device") = nullptr);
    m.def("full",
          [](py::tuple shape, Scalar fill_value, const nonstd::optional<std::string>& device_id) {
              return Array::Full(ToShape(shape), fill_value, GetDevice(device_id)).move_body();
          },
          py::arg("shape"),
          py::arg("fill_value"),
          py::arg("device") = nullptr);
    m.def("zeros",
          [](py::tuple shape, Dtype dtype, const nonstd::optional<std::string>& device_id) {
              return Array::Zeros(ToShape(shape), dtype, GetDevice(device_id)).move_body();
          },
          py::arg("shape"),
          py::arg("dtype"),
          py::arg("device") = nullptr);
    m.def("ones",
          [](py::tuple shape, Dtype dtype, const nonstd::optional<std::string>& device_id) {
              return Array::Ones(ToShape(shape), dtype, GetDevice(device_id)).move_body();
          },
          py::arg("shape"),
          py::arg("dtype"),
          py::arg("device") = nullptr);
    m.def("empty_like",
          [](const ArrayBodyPtr& a, const nonstd::optional<std::string>& device_id) {
              return Array::EmptyLike(Array{a}, GetDevice(device_id)).move_body();
          },
          py::arg("a"),
          py::arg("device") = nullptr);
    m.def("full_like",
          [](const ArrayBodyPtr& a, Scalar value, const nonstd::optional<std::string>& device_id) {
              return Array::FullLike(Array{a}, value, GetDevice(device_id)).move_body();
          },
          py::arg("a"),
          py::arg("fill_value"),
          py::arg("device") = nullptr);
    m.def("zeros_like",
          [](const ArrayBodyPtr& a, const nonstd::optional<std::string>& device_id) {
              return Array::ZerosLike(Array{a}, GetDevice(device_id)).move_body();
          },
          py::arg("a"),
          py::arg("device") = nullptr);
    m.def("ones_like",
          [](const ArrayBodyPtr& a, const nonstd::optional<std::string>& device_id) {
              return Array::OnesLike(Array{a}, GetDevice(device_id)).move_body();
          },
          py::arg("a"),
          py::arg("device") = nullptr);
    m.def("copy", [](const ArrayBodyPtr& a) { return Copy(Array{a}).move_body(); }, py::arg("a"));

    // manipulation module functions
    m.def("transpose", [](const ArrayBodyPtr& a) { return Transpose(Array{a}).move_body(); }, py::arg("a"));
    m.def("reshape",
          [](const ArrayBodyPtr& a, py::tuple newshape) { return Reshape(Array{a}, ToShape(newshape)).move_body(); },
          py::arg("a"),
          py::arg("newshape"));
    m.def("reshape",
          [](const ArrayBodyPtr& a, const std::vector<int64_t>& newshape) {
              return Reshape(Array{a}, {newshape.begin(), newshape.end()}).move_body();
          },
          py::arg("a"),
          py::arg("newshape"));
    m.def("broadcast_to",
          [](const ArrayBodyPtr& array, py::tuple shape) { return Array{array}.BroadcastTo(ToShape(shape)).move_body(); },
          py::arg("array"),
          py::arg("shape"));

    m.def("broadcast_to",
          [](const ArrayBodyPtr& array, py::tuple shape) { return Array{array}.BroadcastTo(ToShape(shape)).move_body(); },
          py::arg("array"),
          py::arg("shape"));

    // math module functions
    m.def("add",
          [](const ArrayBodyPtr& x1, const ArrayBodyPtr& x2) { return (Array{x1} + Array{x2}).move_body(); },
          py::arg("x1"),
          py::arg("x2"));
    m.def("multiply",
          [](const ArrayBodyPtr& x1, const ArrayBodyPtr& x2) { return (Array{x1} * Array{x2}).move_body(); },
          py::arg("x1"),
          py::arg("x2"));
    m.def("sum",
          [](const ArrayBodyPtr& a, int8_t axis, bool keepdims) { return Sum(Array{a}, std::vector<int8_t>{axis}, keepdims).move_body(); },
          py::arg("a"),
          py::arg("axis"),
          py::arg("keepdims") = false);
    m.def("sum",
          [](const ArrayBodyPtr& a, nonstd::optional<std::vector<int8_t>> axis, bool keepdims) {
              return Sum(Array{a}, axis, keepdims).move_body();
          },
          py::arg("a"),
          py::arg("axis") = nullptr,
          py::arg("keepdims") = false);
}

}  // namespace internal
}  // namespace python
}  // namespace xchainer
<|endoftext|>


<commit_before>/*
** Author(s):
**  - Cedric GESTES <gestes@aldebaran-robotics.com>
**
** Copyright (C) 2010 Aldebaran Robotics
*/

#include <gtest/gtest.h>
#include <map>
#include <alcommon-ng/functor/functor.hpp>
#include <alcommon-ng/functor/makefunctor.hpp>
#include <alcommon-ng/tools/dataperftimer.hpp>

static const int gLoopCount   = 1000000;

using AL::Messaging::ReturnValue;
using AL::Messaging::ArgumentList;

int fun0()                                               { return 0; }
int fun1(int p0)                                         { return p0; }
int fun2(int p0, int p1)                                 { return p0 + p1; }
int fun3(int p0, int p1, int p2)                         { return p0 + p1 + p2; }
int fun4(int p0, int p1, int p2, int p3)                 { return p0 + p1 + p2 + p3; }
int fun5(int p0, int p1, int p2, int p3, int p4)         { return p0 + p1 + p2 + p3 + p4; }
int fun6(int p0, int p1, int p2, int p3, int p4, int p5) { return p0 + p1 + p2 + p3 + p4 + p5; }

struct Foo {
  void voidCall()                                          { return; }
  int intStringCall(const std::string &plouf)              { return plouf.size(); }

  int fun0()                                               { return 0; }
  int fun1(int p0)                                         { return p0; }
  int fun2(int p0, int p1)                                 { return p0 + p1; }
  int fun3(int p0, int p1, int p2)                         { return p0 + p1 + p2; }
  int fun4(int p0, int p1, int p2, int p3)                 { return p0 + p1 + p2 + p3; }
  int fun5(int p0, int p1, int p2, int p3, int p4)         { return p0 + p1 + p2 + p3 + p4; }
  int fun6(int p0, int p1, int p2, int p3, int p4, int p5) { return p0 + p1 + p2 + p3 + p4 + p5; }
};

TEST(TestBind, ArgumentNumber) {
  Foo     chiche;

  //AL::Functor *functor = AL::makeFunctor(&Foo, &Foo::fun0);
  //EXPECT_EQ(0, functor->call());

}

TEST(TestBind, VoidCallPerf) {
  Foo           chiche;
  Foo          *p = &chiche;
  ReturnValue   res;
  ArgumentList  cd;

  AL::Test::DataPerfTimer dp;
  AL::Functor    *functor = AL::makeFunctor(&chiche, &Foo::voidCall);
  std::cout << "AL::Functor call" << std::endl;
  dp.start(gLoopCount);
  for (int i = 0; i < gLoopCount; ++i)
  {
    functor->call(cd, res);
  }
  dp.stop();

  std::cout << "pointer call" << std::endl;
  dp.start(gLoopCount);
  for (int i = 0; i < gLoopCount; ++i)
  {
    p->voidCall();
  }
  dp.stop();
}

TEST(TestBind, IntStringCallPerf) {
  Foo           chiche;
  Foo          *p = &chiche;
  ReturnValue res;

  AL::Test::DataPerfTimer dp;

  std::cout << "AL::Functor call (string with a growing size)" << std::endl;

  for (int i = 0; i < 12; ++i)
  {
    unsigned int    numBytes = (unsigned int)pow(2.0f,(int)i);
    std::string     request = std::string(numBytes, 'B');
    ArgumentList  cd;
    AL::Functor    *functor = AL::makeFunctor(&chiche, &Foo::intStringCall);

    cd.push_back(request);
    dp.start(gLoopCount, numBytes);
    for (int j = 0; j < gLoopCount; ++j) {
      functor->call(cd, res);
    }
    dp.stop();
  }

  std::cout << "pointer call (string with a growing size)" << std::endl;
  for (int i = 0; i < 12; ++i)
  {
    unsigned int    numBytes = (unsigned int)pow(2.0f,(int)i);
    std::string     request = std::string(numBytes, 'B');

    dp.start(gLoopCount, numBytes);
    for (int j = 0; j < gLoopCount; ++j) {
      p->intStringCall(request);
    }
    dp.stop();
  }

}
<commit_msg>test_bind<commit_after>/*
** Author(s):
**  - Cedric GESTES <gestes@aldebaran-robotics.com>
**
** Copyright (C) 2010 Aldebaran Robotics
*/

#include <gtest/gtest.h>
#include <map>
#include <alcommon-ng/functor/functor.hpp>
#include <alcommon-ng/functor/makefunctor.hpp>
#include <alcommon-ng/tools/dataperftimer.hpp>
#include <cmath>

static const int gLoopCount   = 1000000;

using AL::Messaging::ReturnValue;
using AL::Messaging::ArgumentList;

int fun0()                                               { return 0; }
int fun1(int p0)                                         { return p0; }
int fun2(int p0, int p1)                                 { return p0 + p1; }
int fun3(int p0, int p1, int p2)                         { return p0 + p1 + p2; }
int fun4(int p0, int p1, int p2, int p3)                 { return p0 + p1 + p2 + p3; }
int fun5(int p0, int p1, int p2, int p3, int p4)         { return p0 + p1 + p2 + p3 + p4; }
int fun6(int p0, int p1, int p2, int p3, int p4, int p5) { return p0 + p1 + p2 + p3 + p4 + p5; }

struct Foo {
  void voidCall()                                          { return; }
  int intStringCall(const std::string &plouf)              { return plouf.size(); }

  int fun0()                                               { return 0; }
  int fun1(int p0)                                         { return p0; }
  int fun2(int p0, int p1)                                 { return p0 + p1; }
  int fun3(int p0, int p1, int p2)                         { return p0 + p1 + p2; }
  int fun4(int p0, int p1, int p2, int p3)                 { return p0 + p1 + p2 + p3; }
  int fun5(int p0, int p1, int p2, int p3, int p4)         { return p0 + p1 + p2 + p3 + p4; }
  int fun6(int p0, int p1, int p2, int p3, int p4, int p5) { return p0 + p1 + p2 + p3 + p4 + p5; }
};

TEST(TestBind, ArgumentNumber) {
  Foo          foo;
  AL::Functor *functor = AL::makeFunctor(&foo, &Foo::fun0);
  //EXPECT_EQ(0, functor->call());
}

TEST(TestBind, VoidCallPerf) {
  Foo           chiche;
  Foo          *p = &chiche;
  ReturnValue   res;
  ArgumentList  cd;

  AL::Test::DataPerfTimer dp;
  AL::Functor    *functor = AL::makeFunctor(&chiche, &Foo::voidCall);
  std::cout << "AL::Functor call" << std::endl;
  dp.start(gLoopCount);
  for (int i = 0; i < gLoopCount; ++i)
  {
    functor->call(cd, res);
  }
  dp.stop();

  std::cout << "pointer call" << std::endl;
  dp.start(gLoopCount);
  for (int i = 0; i < gLoopCount; ++i)
  {
    p->voidCall();
  }
  dp.stop();
}

TEST(TestBind, IntStringCallPerf) {
  Foo           chiche;
  Foo          *p = &chiche;
  ReturnValue res;

  AL::Test::DataPerfTimer dp;

  std::cout << "AL::Functor call (string with a growing size)" << std::endl;

  for (int i = 0; i < 12; ++i)
  {
    unsigned int    numBytes = (unsigned int)pow(2.0f,(int)i);
    std::string     request = std::string(numBytes, 'B');
    ArgumentList  cd;
    AL::Functor    *functor = AL::makeFunctor(&chiche, &Foo::intStringCall);

    cd.push_back(request);
    dp.start(gLoopCount, numBytes);
    for (int j = 0; j < gLoopCount; ++j) {
      functor->call(cd, res);
    }
    dp.stop();
  }

  std::cout << "pointer call (string with a growing size)" << std::endl;
  for (int i = 0; i < 12; ++i)
  {
    unsigned int    numBytes = (unsigned int)pow(2.0f,(int)i);
    std::string     request = std::string(numBytes, 'B');

    dp.start(gLoopCount, numBytes);
    for (int j = 0; j < gLoopCount; ++j) {
      p->intStringCall(request);
    }
    dp.stop();
  }

}
<|endoftext|>


<commit_before>/*
    This file is part of libkdepim.

    Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.
*/

#include "kconfigwizard.h"

#include <klocale.h>
#include <kdebug.h>
#include <kconfigskeleton.h>

#include <qlistview.h>
#include <qlayout.h>
#include <qtimer.h>

KConfigWizard::KConfigWizard( QWidget *parent,
                              char *name, bool modal )
  : KDialogBase( TreeList, i18n("Configuration Wizard"), Ok|Cancel, Ok, parent,
                 name, modal ),
    mPropagator( 0 ), mChangesPage( 0 )
{
  init();
}

KConfigWizard::KConfigWizard( KConfigPropagator *propagator, QWidget *parent,
                              char *name, bool modal )
  : KDialogBase( TreeList, i18n("Configuration Wizard"), Ok|Cancel, Ok, parent,
                 name, modal ),
    mPropagator( propagator ), mChangesPage( 0 )
{
  init();
}

KConfigWizard::~KConfigWizard()
{
  delete mPropagator;
}

void KConfigWizard::init()
{
  connect( this, SIGNAL( aboutToShowPage( QWidget * ) ),
           SLOT( slotAboutToShowPage( QWidget * ) ) );

  QTimer::singleShot( 0, this, SLOT( readConfig() ) );
}

void KConfigWizard::setPropagator( KConfigPropagator *p )
{
  mPropagator = p;
}

void KConfigWizard::slotAboutToShowPage( QWidget *page )
{
  if ( page == mChangesPage ) {
    updateChanges();
  }
}

QFrame *KConfigWizard::createWizardPage( const QString &title )
{
  return addPage( title );
}

void KConfigWizard::setupRulesPage()
{
  QFrame *topFrame = addPage( i18n("Rules") );
  QVBoxLayout *topLayout = new QVBoxLayout( topFrame );

  mRuleView = new QListView( topFrame );
  topLayout->addWidget( mRuleView );

  mRuleView->addColumn( i18n("Source") );
  mRuleView->addColumn( i18n("Target") );
  mRuleView->addColumn( i18n("Condition") );

  updateRules();
}

void KConfigWizard::updateRules()
{
  if ( !mPropagator ) {
    kdError() << "KConfigWizard: No KConfigPropagator set." << endl;
    return;
  }

  mRuleView->clear();

  KConfigPropagator::Rule::List rules = mPropagator->rules();
  KConfigPropagator::Rule::List::ConstIterator it;
  for( it = rules.begin(); it != rules.end(); ++it ) {
    KConfigPropagator::Rule r = *it;
    QString source = r.sourceFile + "/" + r.sourceGroup + "/" +
                     r.sourceEntry;
    QString target = r.targetFile + "/" + r.targetGroup + "/" +
                     r.targetEntry;
    QString condition;
    KConfigPropagator::Condition c = r.condition;
    if ( c.isValid ) {
      condition = c.file + "/" + c.group + "/" + c.key + " = " + c.value;
    }
    new QListViewItem( mRuleView, source, target, condition );
  }
}

void KConfigWizard::setupChangesPage()
{
  QFrame *topFrame = addPage( i18n("Changes") );
  QVBoxLayout *topLayout = new QVBoxLayout( topFrame );

  mChangeView = new QListView( topFrame );
  topLayout->addWidget( mChangeView );

  mChangeView->addColumn( i18n("Action") );
  mChangeView->addColumn( i18n("Option") );
  mChangeView->addColumn( i18n("Value") );

  mChangesPage = topFrame;
}

void KConfigWizard::updateChanges()
{
  kdDebug() << "KConfigWizard::updateChanges()" << endl;

  if ( !mPropagator ) {
    kdError() << "KConfigWizard: No KConfigPropagator set." << endl;
    return;
  }

  usrWriteConfig();

  mPropagator->updateChanges();

  mChangeView->clear();

  KConfigPropagator::Change::List changes = mPropagator->changes();
  KConfigPropagator::Change *c;
  for( c = changes.first(); c; c = changes.next() ) {
    new QListViewItem( mChangeView, c->title(), c->arg1(), c->arg2() );
  }
}

void KConfigWizard::readConfig()
{
  kdDebug() << "KConfigWizard::readConfig()" << endl;

  usrReadConfig();
}

void KConfigWizard::slotOk()
{
  usrWriteConfig();

  if ( !mPropagator ) {
    kdError() << "KConfigWizard: No KConfigPropagator set." << endl;
    return;
  } else {
    if ( mPropagator->skeleton() ) {
      mPropagator->skeleton()->writeConfig();
    }
    mPropagator->commit();
  }

  accept();
}

#include "kconfigwizard.moc"
<commit_msg>Add warning about running applications when running the wizard for the first time.<commit_after>/*
    This file is part of libkdepim.

    Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.
*/

#include "kconfigwizard.h"

#include <klocale.h>
#include <kdebug.h>
#include <kconfigskeleton.h>
#include <kmessagebox.h>
#include <kapplication.h>

#include <qlistview.h>
#include <qlayout.h>
#include <qtimer.h>

KConfigWizard::KConfigWizard( QWidget *parent,
                              char *name, bool modal )
  : KDialogBase( TreeList, i18n("Configuration Wizard"), Ok|Cancel, Ok, parent,
                 name, modal ),
    mPropagator( 0 ), mChangesPage( 0 )
{
  init();
}

KConfigWizard::KConfigWizard( KConfigPropagator *propagator, QWidget *parent,
                              char *name, bool modal )
  : KDialogBase( TreeList, i18n("Configuration Wizard"), Ok|Cancel, Ok, parent,
                 name, modal ),
    mPropagator( propagator ), mChangesPage( 0 )
{
  init();
}

KConfigWizard::~KConfigWizard()
{
  delete mPropagator;
}

void KConfigWizard::init()
{
  connect( this, SIGNAL( aboutToShowPage( QWidget * ) ),
           SLOT( slotAboutToShowPage( QWidget * ) ) );

  QTimer::singleShot( 0, this, SLOT( readConfig() ) );
}

void KConfigWizard::setPropagator( KConfigPropagator *p )
{
  mPropagator = p;
}

void KConfigWizard::slotAboutToShowPage( QWidget *page )
{
  if ( page == mChangesPage ) {
    updateChanges();
  }
}

QFrame *KConfigWizard::createWizardPage( const QString &title )
{
  return addPage( title );
}

void KConfigWizard::setupRulesPage()
{
  QFrame *topFrame = addPage( i18n("Rules") );
  QVBoxLayout *topLayout = new QVBoxLayout( topFrame );

  mRuleView = new QListView( topFrame );
  topLayout->addWidget( mRuleView );

  mRuleView->addColumn( i18n("Source") );
  mRuleView->addColumn( i18n("Target") );
  mRuleView->addColumn( i18n("Condition") );

  updateRules();
}

void KConfigWizard::updateRules()
{
  if ( !mPropagator ) {
    kdError() << "KConfigWizard: No KConfigPropagator set." << endl;
    return;
  }

  mRuleView->clear();

  KConfigPropagator::Rule::List rules = mPropagator->rules();
  KConfigPropagator::Rule::List::ConstIterator it;
  for( it = rules.begin(); it != rules.end(); ++it ) {
    KConfigPropagator::Rule r = *it;
    QString source = r.sourceFile + "/" + r.sourceGroup + "/" +
                     r.sourceEntry;
    QString target = r.targetFile + "/" + r.targetGroup + "/" +
                     r.targetEntry;
    QString condition;
    KConfigPropagator::Condition c = r.condition;
    if ( c.isValid ) {
      condition = c.file + "/" + c.group + "/" + c.key + " = " + c.value;
    }
    new QListViewItem( mRuleView, source, target, condition );
  }
}

void KConfigWizard::setupChangesPage()
{
  QFrame *topFrame = addPage( i18n("Changes") );
  QVBoxLayout *topLayout = new QVBoxLayout( topFrame );

  mChangeView = new QListView( topFrame );
  topLayout->addWidget( mChangeView );

  mChangeView->addColumn( i18n("Action") );
  mChangeView->addColumn( i18n("Option") );
  mChangeView->addColumn( i18n("Value") );

  mChangesPage = topFrame;
}

void KConfigWizard::updateChanges()
{
  kdDebug() << "KConfigWizard::updateChanges()" << endl;

  if ( !mPropagator ) {
    kdError() << "KConfigWizard: No KConfigPropagator set." << endl;
    return;
  }

  usrWriteConfig();

  mPropagator->updateChanges();

  mChangeView->clear();

  KConfigPropagator::Change::List changes = mPropagator->changes();
  KConfigPropagator::Change *c;
  for( c = changes.first(); c; c = changes.next() ) {
    new QListViewItem( mChangeView, c->title(), c->arg1(), c->arg2() );
  }
}

void KConfigWizard::readConfig()
{
  kdDebug() << "KConfigWizard::readConfig()" << endl;

  int result = KMessageBox::warningContinueCancel( this,
      i18n("Please make sure that the programs which are "
           "configured by the wizard don't run in parallel to the wizard. "
           "Otherwise changes done by the wizard could be lost."),
      i18n("Warning"), i18n("Run wizard now"), "warning_running_instances" );
  if ( result != KMessageBox::Continue ) kapp->quit();

  usrReadConfig();
}

void KConfigWizard::slotOk()
{
  usrWriteConfig();

  if ( !mPropagator ) {
    kdError() << "KConfigWizard: No KConfigPropagator set." << endl;
    return;
  } else {
    if ( mPropagator->skeleton() ) {
      mPropagator->skeleton()->writeConfig();
    }
    mPropagator->commit();
  }

  accept();
}

#include "kconfigwizard.moc"
<|endoftext|>


<commit_before>#include "catch.hpp"

// mapnik vector tile tile class
#include "vector_tile_tile.hpp"

TEST_CASE("Vector tile base class")
{
    mapnik::box2d<double> global_extent(-20037508.342789,-20037508.342789,20037508.342789,20037508.342789);

    SECTION("default constructed")
    {
        mapnik::vector_tile_impl::tile default_tile(global_extent);

        CHECK(default_tile.size() == 0);
        CHECK(default_tile.data()[0] == '\0');
        CHECK(std::abs(default_tile.scale() - 9783.9396205024) < 0.00001);

        std::string str;
        default_tile.serialize_to_string(str);
        CHECK(str == "");
        CHECK(default_tile.is_painted() == false);
        CHECK(default_tile.is_empty() == true);

        CHECK(default_tile.extent() == global_extent);
        CHECK(default_tile.get_buffered_extent() == global_extent);
        CHECK(default_tile.tile_size() == 4096);

        CHECK(default_tile.get_painted_layers().empty() == true);
        CHECK(default_tile.get_empty_layers().empty() == true);
        CHECK(default_tile.get_layers().empty() == true);
        CHECK(default_tile.get_layers_set().empty() == true);

        CHECK(default_tile.has_layer("anything") == false);

        vector_tile::Tile t;
        t = default_tile.get_tile();
        CHECK(t.layers_size() == 0);
    }
}
<commit_msg>Add more edge case constructions<commit_after>#include "catch.hpp"

// mapnik vector tile tile class
#include "vector_tile_tile.hpp"

TEST_CASE("Vector tile base class")
{
    mapnik::box2d<double> global_extent(-20037508.342789,-20037508.342789,20037508.342789,20037508.342789);

    SECTION("default constructed")
    {
        mapnik::vector_tile_impl::tile default_tile(global_extent);

        CHECK(default_tile.size() == 0);
        CHECK(default_tile.data()[0] == '\0');
        CHECK(std::abs(default_tile.scale() - 9783.9396205024) < 0.00001);

        std::string str;
        default_tile.serialize_to_string(str);
        CHECK(str == "");
        CHECK(default_tile.is_painted() == false);
        CHECK(default_tile.is_empty() == true);

        CHECK(default_tile.extent() == global_extent);
        CHECK(default_tile.get_buffered_extent() == global_extent);
        CHECK(default_tile.tile_size() == 4096);

        CHECK(default_tile.get_painted_layers().empty() == true);
        CHECK(default_tile.get_empty_layers().empty() == true);
        CHECK(default_tile.get_layers().empty() == true);
        CHECK(default_tile.get_layers_set().empty() == true);

        CHECK(default_tile.has_layer("anything") == false);

        vector_tile::Tile t;
        t = default_tile.get_tile();
        CHECK(t.layers_size() == 0);
    }

    SECTION("construction with zero tile_size")
    {
        mapnik::vector_tile_impl::tile zero_size_tile(global_extent, 0);

        CHECK(zero_size_tile.tile_size() == 0);
        CHECK(std::abs(zero_size_tile.scale() - 40075016.6855780035) < 0.00001);
        CHECK(zero_size_tile.get_buffered_extent() == global_extent);
    }

    SECTION("construction with negative tile_size")
    {
        mapnik::vector_tile_impl::tile negative_size_tile(global_extent, -1);

        CHECK(negative_size_tile.tile_size() == 4294967295);
        CHECK(std::abs(negative_size_tile.scale() - 0.0093306919) < 0.0000001);
        CHECK(negative_size_tile.get_buffered_extent() == global_extent);
    }

    SECTION("construction with positive buffer size")
    {
        mapnik::vector_tile_impl::tile positive_buffer_tile(global_extent, 4096, 10);

        mapnik::box2d<double> buffered_extent(-20135347.7389940246939659,-20135347.7389940246939659,20135347.7389940246939659,20135347.7389940246939659);
        CHECK(positive_buffer_tile.get_buffered_extent() == buffered_extent);
        CHECK(positive_buffer_tile.buffer_size() == 10);
    }

    SECTION("construction with very negative buffer size")
    {
        mapnik::vector_tile_impl::tile negative_buffer_tile(global_extent, 4096, -4000);
        mapnik::box2d<double> buffered_extent(0.0, 0.0, 0.0, 0.0);
        CHECK(negative_buffer_tile.get_buffered_extent() == buffered_extent);
        CHECK(negative_buffer_tile.buffer_size() == -4000);
    }
}
<|endoftext|>


<commit_before>#include "catch.hpp"

#include <cstdint>
#include "memory_arena.hpp"

struct alignas(32) SomeType {
    int64_t x;
    int64_t y;
    int64_t z;
};

// Make sure that subsequent allocations that should fit into a single
// chunk are actually allocated sequentially.
TEST_CASE("Sequential memory addresses", "[memory_arena]")
{
	MemoryArena<16> arena;

	int32_t* a = arena.alloc<int32_t>();
	int32_t* b = arena.alloc<int32_t>();
	int32_t* c = arena.alloc<int32_t>();
	int32_t* d = arena.alloc<int32_t>();

	REQUIRE((a+1) == b);
	REQUIRE((a+2) == c);
	REQUIRE((a+3) == d);
}

// Make sure that types are allocated with proper memory alignment
TEST_CASE("Memory alignment requirements", "[memory_arena]")
{
	MemoryArena<128> arena;

	arena.alloc<char>();
	uintptr_t a = (uintptr_t)(arena.alloc<SomeType>());
	uintptr_t b = (uintptr_t)(arena.alloc<SomeType>());
	arena.alloc<char>();
	arena.alloc<char>();
	arena.alloc<char>();
	uintptr_t c = (uintptr_t)(arena.alloc<SomeType>());

	REQUIRE((a % alignof(SomeType)) == 0);
	REQUIRE((b % alignof(SomeType)) == 0);
	REQUIRE((c % alignof(SomeType)) == 0);
}<commit_msg>Added more unit tests for MemoryArena.<commit_after>#include "catch.hpp"

#include <cstdint>
#include <vector>
#include <list>
#include "slice.hpp"

#include "memory_arena.hpp"

struct alignas(32) SomeType {
    int64_t x;
    int64_t y;
    int64_t z;
};

// Make sure that subsequent allocations that should fit into a single
// chunk are actually allocated sequentially.
TEST_CASE("Sequential memory addresses", "[memory_arena]")
{
	MemoryArena<16> arena;

	int32_t* a = arena.alloc<int32_t>();
	int32_t* b = arena.alloc<int32_t>();
	int32_t* c = arena.alloc<int32_t>();
	int32_t* d = arena.alloc<int32_t>();

	REQUIRE((a+1) == b);
	REQUIRE((a+2) == c);
	REQUIRE((a+3) == d);
}

// Make sure alloc() initializes things properly if given a value
TEST_CASE("alloc() init", "[memory_arena]")
{
	MemoryArena<> arena;

	int32_t* a = arena.alloc<int32_t>(42);
	int32_t* b = arena.alloc<int32_t>(64);

	REQUIRE((*a) == 42);
	REQUIRE((*b) == 64);
}

// Make sure alloc_array() creates a slice of the appropriate length
TEST_CASE("alloc_from_array() length", "[memory_arena]")
{
	MemoryArena<> arena;

	Slice<int32_t> s = arena.alloc_array<int32_t>(123);

	REQUIRE(s.size() == 123);
}

// Make sure alloc_from_iters() initializes things properly
TEST_CASE("alloc_from_iters() init", "[memory_arena]")
{
	MemoryArena<64> arena;

	std::vector<int32_t> v {1, 0, 2, 9, 3, 8, 4, 7, 5, 6};
	std::list<int32_t> l {1, 0, 2, 9, 3, 8, 4, 7, 5, 6};

	Slice<int32_t> s1 = arena.alloc_from_iters(v.begin(), v.end());
	Slice<int32_t> s2 = arena.alloc_from_iters(l.begin(), l.end());

	REQUIRE(v.size() == s1.size());
	REQUIRE(l.size() == s2.size());

	auto i1 = v.begin();
	auto i2 = l.begin();
	auto i3 = s1.begin();
	auto i4 = s2.begin();

	for (size_t i = 0; i < s1.size(); ++i) {
		REQUIRE((*i1) == (*i3));
		REQUIRE((*i2) == (*i4));

		++i1;
		++i2;
		++i3;
		++i4;
	}
}

// Make sure that types are allocated with proper memory alignment
TEST_CASE("Memory alignment requirements", "[memory_arena]")
{
	MemoryArena<128> arena;

	arena.alloc<char>();
	uintptr_t a = (uintptr_t)(arena.alloc<SomeType>());
	uintptr_t b = (uintptr_t)(arena.alloc<SomeType>());
	arena.alloc<char>();
	arena.alloc<char>();
	arena.alloc<char>();
	uintptr_t c = (uintptr_t)(arena.alloc<SomeType>());

	REQUIRE((a % alignof(SomeType)) == 0);
	REQUIRE((b % alignof(SomeType)) == 0);
	REQUIRE((c % alignof(SomeType)) == 0);
}<|endoftext|>


<commit_before>// Catch
#include <catch.hpp>
#include <helper.hpp>

// Mantella
#include <mantella>

TEST_CASE("quasiRandomSequence: getHaltonSequence", "") {
  arma::Mat<double>::fixed<2, 5> expected;

  expected = {
    0.0, 0.0,
    1.0/2.0, 1.0/3.0,
    1.0/4.0, 2.0/3.0,
    3.0/4.0, 1.0/9.0,
    1.0/8.0, 4.0/9.0,
  };
  compare(mant::getHaltonSequence({2, 3}, {0, 0}, 5), expected);

  expected = {
    3.0/4.0, 1.0/9.0,
    1.0/8.0, 4.0/9.0,
    5.0/8.0, 7.0/9.0,
    3.0/8.0, 2.0/9.0,
    7.0/8.0, 5.0/9.0,
  };
  compare(mant::getHaltonSequence({2, 3}, {3, 3}, 5), expected);

  CHECK_THROWS_AS(mant::getHaltonSequence({1}, {3, 3}, 5), std::logic_error);
  CHECK_THROWS_AS(mant::getHaltonSequence({4, 5}, {3}, 6), std::logic_error);
}

TEST_CASE("quasiRandomSequence: getVanDerCorputSequence", "") {
  compare(mant::getVanDerCorputSequence(2, 0, 5), {0.0, 1.0/2.0, 1.0/4.0, 3.0/4.0, 1.0/8.0});
  compare(mant::getVanDerCorputSequence(3, 3, 5), {1.0/9.0, 4.0/9.0, 7.0/9.0, 2.0/9.0, 5.0/9.0});
}
<commit_msg>test: Reorganised quasiRandomSequence.hpp test cases<commit_after>// Catch
#include <catch.hpp>
#include <helper.hpp>

// Mantella
#include <mantella>

TEST_CASE("quasiRandomSequence: getHaltonSequence(...)", "") {
  arma::Mat<double>::fixed<2, 5> expected;

  expected = {
    0.0, 0.0,
    1.0/2.0, 1.0/3.0,
    1.0/4.0, 2.0/3.0,
    3.0/4.0, 1.0/9.0,
    1.0/8.0, 4.0/9.0,
  };
  compare(mant::getHaltonSequence({2, 3}, {0, 0}, 5), expected);

  expected = {
    3.0/4.0, 1.0/9.0,
    1.0/8.0, 4.0/9.0,
    5.0/8.0, 7.0/9.0,
    3.0/8.0, 2.0/9.0,
    7.0/8.0, 5.0/9.0,
  };
  compare(mant::getHaltonSequence({2, 3}, {3, 3}, 5), expected);

  CHECK_THROWS_AS(mant::getHaltonSequence({1}, {3, 3}, 5), std::logic_error);
  CHECK_THROWS_AS(mant::getHaltonSequence({4, 5}, {3}, 6), std::logic_error);
}

TEST_CASE("quasiRandomSequence: getVanDerCorputSequence(...)", "") {
  compare(mant::getVanDerCorputSequence(2, 0, 5), {0.0, 1.0/2.0, 1.0/4.0, 3.0/4.0, 1.0/8.0});
  compare(mant::getVanDerCorputSequence(3, 3, 5), {1.0/9.0, 4.0/9.0, 7.0/9.0, 2.0/9.0, 5.0/9.0});
}
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// decimal_functions_sql_test.cpp
//
// Identification: test/sql/decimal_functions_sql_test.cpp
//
// Copyright (c) 2015-2017, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include <memory>

#include "sql/testing_sql_util.h"
#include "catalog/catalog.h"
#include "common/harness.h"
#include "concurrency/transaction_manager_factory.h"

namespace peloton {
namespace test {

class DecimalFunctionsSQLTest : public PelotonTest {};

  TEST_F(DecimalFunctionsSQLTest, FloorTest) {
    auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
    auto txn = txn_manager.BeginTransaction();
    catalog::Catalog::GetInstance()->CreateDatabase(DEFAULT_DB_NAME, txn);
    catalog::Catalog::GetInstance()->Bootstrap();
    txn_manager.CommitTransaction(txn);
    // Create a t
    txn = txn_manager.BeginTransaction();

    TestingSQLUtil::ExecuteSQLQuery(
            "CREATE TABLE foo(id integer, income decimal);");
    // Adding in 2500 random decimal inputs between [-500, 500]
    int i;
    std::vector<double> inputs;
    int lo = -500;
    int hi = 500;
    int numEntries = 500;
    // Setting a seed
    std::srand(std::time(0));
    for (i = 0; i < numEntries; i++) {
      double num = 0.45 + (std::rand() % (hi - lo));
      inputs.push_back(num);
      std::ostringstream os;
      os << "insert into foo values(" << i << ", " << num << ");";
      TestingSQLUtil::ExecuteSQLQuery(os.str());
    }
    EXPECT_EQ(i, numEntries);

    txn_manager.CommitTransaction(txn);
    // Fetch values from the table
    std::vector<StatementResult> result;
    std::vector<FieldInfo> tuple_descriptor;
    std::string error_message;
    int rows_affected;
    std::string testQuery = "select id, floor(income) from foo;";

    TestingSQLUtil::ExecuteSQLQuery(testQuery.c_str(), result, tuple_descriptor,
                                    rows_affected, error_message);
    for (i = 0; i < numEntries; i++) {
      std::string result_id(
              TestingSQLUtil::GetResultValueAsString(result, (2 * i)));
      std::string result_income(
              TestingSQLUtil::GetResultValueAsString(result, (2 * i) + 1));
      int id = std::stoi(result_id);
      double income = std::stod(result_income);
      EXPECT_EQ(id, i);
      EXPECT_DOUBLE_EQ(income, floor(inputs[i]));
    }

    // free the database just created
    txn = txn_manager.BeginTransaction();
    catalog::Catalog::GetInstance()->DropDatabaseWithName(DEFAULT_DB_NAME, txn);
    txn_manager.CommitTransaction(txn);
  }

}  // namespace test
}  // namespace peloton
<commit_msg>Added EndTransaction<commit_after>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// decimal_functions_sql_test.cpp
//
// Identification: test/sql/decimal_functions_sql_test.cpp
//
// Copyright (c) 2015-2017, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include <memory>

#include "sql/testing_sql_util.h"
#include "catalog/catalog.h"
#include "common/harness.h"
#include "concurrency/transaction_manager_factory.h"

namespace peloton {
namespace test {

class DecimalFunctionsSQLTest : public PelotonTest {};

  TEST_F(DecimalFunctionsSQLTest, FloorTest) {
    auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
    auto txn = txn_manager.BeginTransaction();
    catalog::Catalog::GetInstance()->CreateDatabase(DEFAULT_DB_NAME, txn);
    catalog::Catalog::GetInstance()->Bootstrap();
    txn_manager.CommitTransaction(txn);
    // Create a t
    txn = txn_manager.BeginTransaction();

    TestingSQLUtil::ExecuteSQLQuery(
            "CREATE TABLE foo(id integer, income decimal);");
    // Adding in 2500 random decimal inputs between [-500, 500]
    int i;
    std::vector<double> inputs;
    int lo = -500;
    int hi = 500;
    int numEntries = 500;
    // Setting a seed
    std::srand(std::time(0));
    for (i = 0; i < numEntries; i++) {
      double num = 0.45 + (std::rand() % (hi - lo));
      inputs.push_back(num);
      std::ostringstream os;
      os << "insert into foo values(" << i << ", " << num << ");";
      TestingSQLUtil::ExecuteSQLQuery(os.str());
    }
    EXPECT_EQ(i, numEntries);

    txn_manager.CommitTransaction(txn);
    // Fetch values from the table
    std::vector<StatementResult> result;
    std::vector<FieldInfo> tuple_descriptor;
    std::string error_message;
    int rows_affected;
    std::string testQuery = "select id, floor(income) from foo;";

    TestingSQLUtil::ExecuteSQLQuery(testQuery.c_str(), result, tuple_descriptor,
                                    rows_affected, error_message);
    for (i = 0; i < numEntries; i++) {
      std::string result_id(
              TestingSQLUtil::GetResultValueAsString(result, (2 * i)));
      std::string result_income(
              TestingSQLUtil::GetResultValueAsString(result, (2 * i) + 1));
      int id = std::stoi(result_id);
      double income = std::stod(result_income);
      EXPECT_EQ(id, i);
      EXPECT_DOUBLE_EQ(income, floor(inputs[i]));
    }

    // free the database just created
    txn = txn_manager.BeginTransaction();
    catalog::Catalog::GetInstance()->DropDatabaseWithName(DEFAULT_DB_NAME, txn);
    txn_manager.CommitTransaction(txn);
    txn = txn_manager.EndTransaction();
  }

}  // namespace test
}  // namespace peloton
<|endoftext|>


<commit_before>#ifndef MJOLNIR_TEST_UTIL_CHECK_FORCE_ENERGY_VIRIAL_HPP
#define MJOLNIR_TEST_UTIL_CHECK_FORCE_ENERGY_VIRIAL_HPP
#include <mjolnir/math/Vector.hpp>
#include <mjolnir/core/System.hpp>

#include <mjolnir/core/LocalInteractionBase.hpp>
#include <mjolnir/core/GlobalInteractionBase.hpp>
#include <type_traits>

#ifdef BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#else
#include <boost/test/included/unit_test.hpp>
#endif

namespace mjolnir
{
namespace test
{
template<typename traitsT, typename Interaction>
typename std::enable_if<
    std::is_base_of< LocalInteractionBase<traitsT>, Interaction>::value ||
    std::is_base_of<GlobalInteractionBase<traitsT>, Interaction>::value>::type
check_virial_in_force_energy_virial(System<traitsT> ref,
                                    const Interaction& interaction,
                                    const typename traitsT::real_type tol)
{
    using coordinate_type = typename traitsT::coordinate_type;
    using matrix33_type   = typename traitsT::matrix33_type;

    for(std::size_t i=0; i<ref.size(); ++i)
    {
        ref.force(i) = math::make_coordinate<coordinate_type>(0,0,0);
    }
    ref.virial() = matrix33_type(0,0,0, 0,0,0, 0,0,0);

    System<traitsT> sys(ref);

    // ------------------------------------------------------------------------
    // check virial calculated in calc_force_and_energy

    sys.preprocess_forces();
    interaction.calc_force_and_energy(sys);
    sys.postprocess_forces();

    ref.preprocess_forces();
    interaction.calc_force_and_virial(ref);
    ref.postprocess_forces();

    for(std::size_t i=0; i<9; ++i)
    {
        BOOST_TEST(sys.virial()[i] == ref.virial()[i], boost::test_tools::tolerance(tol));
    }
    return;
}
template<typename traitsT, typename Interaction>
typename std::enable_if<
    ! std::is_base_of< LocalInteractionBase<traitsT>, Interaction>::value &&
    ! std::is_base_of<GlobalInteractionBase<traitsT>, Interaction>::value>::type
check_virial_in_force_energy_virial(System<traitsT>,
                                    const Interaction&,
                                    const typename traitsT::real_type)
{
    // ------------------------------------------------------------------------
    // does not have virial.
    return;
}

// This checks the consistency between `calc_force` and `calc_force_and_energy`.

template<typename traitsT, typename Interaction>
void check_force_energy_virial(System<traitsT> ref,
                               const Interaction& interaction,
                               const typename traitsT::real_type tol)
{
    using coordinate_type = typename traitsT::coordinate_type;
    using matrix33_type   = typename traitsT::matrix33_type;

    for(std::size_t i=0; i<ref.size(); ++i)
    {
        ref.force(i) = math::make_coordinate<coordinate_type>(0,0,0);
    }
    ref.virial() = matrix33_type(0,0,0, 0,0,0, 0,0,0);

    System<traitsT> sys(ref);

    ref.preprocess_forces();
    interaction.calc_force(ref);
    ref.postprocess_forces();
    const auto ref_ene = interaction.calc_energy(ref);

    sys.preprocess_forces();
    const auto ene = interaction.calc_force_and_energy(sys);
    sys.postprocess_forces();

    BOOST_TEST(ref_ene == ene, boost::test_tools::tolerance(tol));

    for(std::size_t idx=0; idx<sys.size(); ++idx)
    {
        BOOST_TEST(math::X(sys.force(idx)) == math::X(ref.force(idx)), boost::test_tools::tolerance(tol));
        BOOST_TEST(math::Y(sys.force(idx)) == math::Y(ref.force(idx)), boost::test_tools::tolerance(tol));
        BOOST_TEST(math::Z(sys.force(idx)) == math::Z(ref.force(idx)), boost::test_tools::tolerance(tol));
    }

    check_virial_in_force_energy_virial(sys, interaction, tol);

    return;
}

} // test
} // mjolnir
#endif// MJOLNIR_TEST_UTIL_CHECK_FORCE_HPP
<commit_msg>fix: calc virial properly in force_energy_virial<commit_after>#ifndef MJOLNIR_TEST_UTIL_CHECK_FORCE_ENERGY_VIRIAL_HPP
#define MJOLNIR_TEST_UTIL_CHECK_FORCE_ENERGY_VIRIAL_HPP
#include <mjolnir/math/Vector.hpp>
#include <mjolnir/core/System.hpp>

#include <mjolnir/core/LocalInteractionBase.hpp>
#include <mjolnir/core/GlobalInteractionBase.hpp>
#include <type_traits>

#ifdef BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#else
#include <boost/test/included/unit_test.hpp>
#endif

namespace mjolnir
{
namespace test
{

// This checks the consistency between `calc_force` and `calc_force_and_energy`.

template<typename traitsT, typename Interaction>
void check_force_energy_virial(System<traitsT> ref,
                               const Interaction& interaction,
                               const typename traitsT::real_type tol)
{
    using coordinate_type = typename traitsT::coordinate_type;
    using matrix33_type   = typename traitsT::matrix33_type;

    for(std::size_t i=0; i<ref.size(); ++i)
    {
        ref.force(i) = math::make_coordinate<coordinate_type>(0,0,0);
    }
    ref.virial() = matrix33_type(0,0,0, 0,0,0, 0,0,0);

    System<traitsT> sys(ref);

    ref.preprocess_forces();
    interaction.calc_force(ref);
    ref.postprocess_forces();
    const auto ref_ene = interaction.calc_energy(ref);

    sys.preprocess_forces();
    const auto ene = interaction.calc_force_virial_energy(sys);
    sys.postprocess_forces();

    BOOST_TEST(ref_ene == ene, boost::test_tools::tolerance(tol));

    for(std::size_t idx=0; idx<sys.size(); ++idx)
    {
        BOOST_TEST(math::X(sys.force(idx)) == math::X(ref.force(idx)), boost::test_tools::tolerance(tol));
        BOOST_TEST(math::Y(sys.force(idx)) == math::Y(ref.force(idx)), boost::test_tools::tolerance(tol));
        BOOST_TEST(math::Z(sys.force(idx)) == math::Z(ref.force(idx)), boost::test_tools::tolerance(tol));
    }

    // external forcefield does not support virial because they depends absolute
    // coordinate
    if(std::is_base_of< LocalInteractionBase<traitsT>, Interaction>::value ||
       std::is_base_of<GlobalInteractionBase<traitsT>, Interaction>::value)
    {
        for(std::size_t i=0; i<ref.size(); ++i)
        {
            ref.force(i) = math::make_coordinate<coordinate_type>(0,0,0);
        }
        ref.virial() = matrix33_type(0,0,0, 0,0,0, 0,0,0);

        // calc virial
        interaction.calc_force_and_virial(ref);

        // compare ref virial with calc_force_energy_virial
        for(std::size_t i=0; i<9; ++i)
        {
            BOOST_TEST(sys.virial()[i] == ref.virial()[i], boost::test_tools::tolerance(tol));
        }
    }

    return;
}

} // test
} // mjolnir
#endif// MJOLNIR_TEST_UTIL_CHECK_FORCE_HPP
<|endoftext|>


<commit_before>#include <itkImageRegionConstIterator.h>
#include <itkPasteImageFilter.h>

#include "rtkTestConfiguration.h"
#include "rtkRayEllipsoidIntersectionImageFilter.h"
#include "rtkDrawEllipsoidImageFilter.h"
#include "rtkConstantImageSource.h"
#include "rtkFieldOfViewImageFilter.h"
#include "rtkFDKConeBeamReconstructionFilter.h"
#include "rtkFDKWarpBackProjectionImageFilter.h"
#include "rtkCyclicDeformationImageFilter.h"

template<class TImage>
void CheckImageQuality(typename TImage::Pointer recon, typename TImage::Pointer ref)
{
#if !(FAST_TESTS_NO_CHECKS)
  typedef itk::ImageRegionConstIterator<TImage> ImageIteratorType;
  ImageIteratorType itTest( recon, recon->GetBufferedRegion() );
  ImageIteratorType itRef( ref, ref->GetBufferedRegion() );

  typedef double ErrorType;
  ErrorType TestError = 0.;
  ErrorType EnerError = 0.;

  itTest.GoToBegin();
  itRef.GoToBegin();

  while( !itRef.IsAtEnd() )
    {
    typename TImage::PixelType TestVal = itTest.Get();
    typename TImage::PixelType RefVal = itRef.Get();
    TestError += vcl_abs(RefVal - TestVal);
    EnerError += vcl_pow(ErrorType(RefVal - TestVal), 2.);
    ++itTest;
    ++itRef;
    }
  // Error per Pixel
  ErrorType ErrorPerPixel = TestError/ref->GetBufferedRegion().GetNumberOfPixels();
  std::cout << "\nError per Pixel = " << ErrorPerPixel << std::endl;
  // MSE
  ErrorType MSE = EnerError/ref->GetBufferedRegion().GetNumberOfPixels();
  std::cout << "MSE = " << MSE << std::endl;
  // PSNR
  ErrorType PSNR = 20*log10(2.0) - 10*log10(MSE);
  std::cout << "PSNR = " << PSNR << "dB" << std::endl;
  // QI
  ErrorType QI = (2.0-ErrorPerPixel)/2.0;
  std::cout << "QI = " << QI << std::endl;

  // Checking results
  if (ErrorPerPixel > 0.05)
  {
    std::cerr << "Test Failed, Error per pixel not valid! "
              << ErrorPerPixel << " instead of 0.05." << std::endl;
    exit( EXIT_FAILURE);
  }
  if (PSNR < 22.)
  {
    std::cerr << "Test Failed, PSNR not valid! "
              << PSNR << " instead of 23" << std::endl;
    exit( EXIT_FAILURE);
  }
#endif
}

int main(int, char** )
{
  const unsigned int Dimension = 3;
  typedef float                                    OutputPixelType;
  typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
#if FAST_TESTS_NO_CHECKS
  const unsigned int NumberOfProjectionImages = 3;
#else
  const unsigned int NumberOfProjectionImages = 128;
#endif

  // Constant image sources
  typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType;
  ConstantImageSourceType::PointType origin;
  ConstantImageSourceType::SizeType size;
  ConstantImageSourceType::SpacingType spacing;

  ConstantImageSourceType::Pointer tomographySource  = ConstantImageSourceType::New();
  origin[0] = -63.;
  origin[1] = -31.;
  origin[2] = -63.;
#if FAST_TESTS_NO_CHECKS
  size[0] = 32;
  size[1] = 32;
  size[2] = 32;
  spacing[0] = 8.;
  spacing[1] = 8.;
  spacing[2] = 8.;
#else
  size[0] = 64;
  size[1] = 32;
  size[2] = 64;
  spacing[0] = 2.;
  spacing[1] = 2.;
  spacing[2] = 2.;
#endif
  tomographySource->SetOrigin( origin );
  tomographySource->SetSpacing( spacing );
  tomographySource->SetSize( size );
  tomographySource->SetConstant( 0. );

  ConstantImageSourceType::Pointer projectionsSource = ConstantImageSourceType::New();
  origin[0] = -254.;
  origin[1] = -254.;
  origin[2] = -254.;
#if FAST_TESTS_NO_CHECKS
  size[0] = 32;
  size[1] = 32;
  size[2] = NumberOfProjectionImages;
  spacing[0] = 32.;
  spacing[1] = 32.;
  spacing[2] = 32.;
#else
  size[0] = 128;
  size[1] = 128;
  size[2] = NumberOfProjectionImages;
  spacing[0] = 4.;
  spacing[1] = 4.;
  spacing[2] = 4.;
#endif
  projectionsSource->SetOrigin( origin );
  projectionsSource->SetSpacing( spacing );
  projectionsSource->SetSize( size );
  projectionsSource->SetConstant( 0. );

  ConstantImageSourceType::Pointer oneProjectionSource = ConstantImageSourceType::New();
  size[2] = 1;
  oneProjectionSource->SetOrigin( origin );
  oneProjectionSource->SetSpacing( spacing );
  oneProjectionSource->SetSize( size );
  oneProjectionSource->SetConstant( 0. );

  // Geometry object
  typedef rtk::ThreeDCircularProjectionGeometry GeometryType;
  GeometryType::Pointer geometry = GeometryType::New();

  // Projections
  typedef rtk::RayEllipsoidIntersectionImageFilter<OutputImageType, OutputImageType> REIType;
  typedef itk::PasteImageFilter <OutputImageType, OutputImageType, OutputImageType > PasteImageFilterType;
  OutputImageType::IndexType destinationIndex;
  destinationIndex[0] = 0;
  destinationIndex[1] = 0;
  destinationIndex[2] = 0;
  PasteImageFilterType::Pointer pasteFilter = PasteImageFilterType::New();

  std::ofstream signalFile("signal.txt");
  OutputImageType::Pointer wholeImage = projectionsSource->GetOutput();
  for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++)
    {
    geometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages, 0, 0, 0, 0, 20, 15);

    // Geometry object
    GeometryType::Pointer oneProjGeometry = GeometryType::New();
    oneProjGeometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages, 0, 0, 0, 0, 20, 15);

    // Ellipse 1
    REIType::Pointer e1 = REIType::New();
    e1->SetInput(oneProjectionSource->GetOutput());
    e1->SetGeometry(oneProjGeometry);
    e1->SetMultiplicativeConstant(2.);
    e1->SetSemiPrincipalAxisX(60.);
    e1->SetSemiPrincipalAxisY(60.);
    e1->SetSemiPrincipalAxisZ(60.);
    e1->SetCenterX(0.);
    e1->SetCenterY(0.);
    e1->SetCenterZ(0.);
    e1->SetRotationAngle(0.);
    e1->InPlaceOff();
    e1->Update();

    // Ellipse 2
    REIType::Pointer e2 = REIType::New();
    e2->SetInput(e1->GetOutput());
    e2->SetGeometry(oneProjGeometry);
    e2->SetMultiplicativeConstant(-1.);
    e2->SetSemiPrincipalAxisX(8.);
    e2->SetSemiPrincipalAxisY(8.);
    e2->SetSemiPrincipalAxisZ(8.);
    e2->SetCenterX( 4*(vcl_abs( (4+noProj) % 8 - 4.) - 2.) );
    e2->SetCenterY(0.);
    e2->SetCenterZ(0.);
    e2->SetRotationAngle(0.);
    e2->Update();

    // Adding each projection to volume
    pasteFilter->SetSourceImage(e2->GetOutput());
    pasteFilter->SetDestinationImage(wholeImage);
    pasteFilter->SetSourceRegion(e2->GetOutput()->GetLargestPossibleRegion());
    pasteFilter->SetDestinationIndex(destinationIndex);
    pasteFilter->Update();
    wholeImage = pasteFilter->GetOutput();
    destinationIndex[2]++;

    // Signal
    signalFile << (noProj % 8) / 8. << std::endl;
    }

  // Create vector field
  typedef itk::Vector<float,3>                                                 DVFPixelType;
  typedef itk::Image< DVFPixelType, 3 >                                        DVFImageType;
  typedef rtk::CyclicDeformationImageFilter< DVFImageType >                    DeformationType;
  typedef itk::ImageRegionIteratorWithIndex< DeformationType::InputImageType > IteratorType;

  DeformationType::InputImageType::Pointer deformationField;
  deformationField = DeformationType::InputImageType::New();

  DeformationType::InputImageType::IndexType startMotion;
  startMotion[0] = 0; // first index on X
  startMotion[1] = 0; // first index on Y
  startMotion[2] = 0; // first index on Z
  startMotion[3] = 0; // first index on t
  DeformationType::InputImageType::SizeType sizeMotion;
  sizeMotion[0] = 64; // size along X
  sizeMotion[1] = 64; // size along Y
  sizeMotion[2] = 64; // size along Z
  sizeMotion[3] = 2;  // size along t
  DeformationType::InputImageType::PointType originMotion;
  originMotion[0] = (sizeMotion[0]-1)*(-0.5); // size along X
  originMotion[1] = (sizeMotion[1]-1)*(-0.5); // size along Y
  originMotion[2] = (sizeMotion[2]-1)*(-0.5); // size along Z
  originMotion[3] = 0.;
  DeformationType::InputImageType::RegionType regionMotion;
  regionMotion.SetSize( sizeMotion );
  regionMotion.SetIndex( startMotion );
  deformationField->SetRegions( regionMotion );
  deformationField->SetOrigin(originMotion);
  deformationField->Allocate();

  // Vector Field initilization
  DVFPixelType vec;
  vec.Fill(0.);
  IteratorType inputIt( deformationField, deformationField->GetLargestPossibleRegion() );
  for ( inputIt.GoToBegin(); !inputIt.IsAtEnd(); ++inputIt)
    {
    if(inputIt.GetIndex()[3]==0)
      vec[0] = -8.;
    else
      vec[0] = 8.;
    inputIt.Set(vec);
    }

  // Create cyclic deformation
  DeformationType::Pointer def = DeformationType::New();
  def->SetInput(deformationField);
  typedef rtk::FDKWarpBackProjectionImageFilter<OutputImageType, OutputImageType, DeformationType> WarpBPType;
  WarpBPType::Pointer bp = WarpBPType::New();
  bp->SetDeformation(def);
  bp->SetGeometry( geometry.GetPointer() );

  // FDK reconstruction filtering
#ifdef USE_CUDA
  typedef rtk::CudaFDKConeBeamReconstructionFilter                FDKType;
#elif USE_OPENCL
  typedef rtk::OpenCLFDKConeBeamReconstructionFilter              FDKType;
#else
  typedef rtk::FDKConeBeamReconstructionFilter< OutputImageType > FDKType;
#endif
  FDKType::Pointer feldkamp = FDKType::New();
  feldkamp->SetInput( 0, tomographySource->GetOutput() );
  feldkamp->SetInput( 1, wholeImage );
  feldkamp->SetGeometry( geometry );
  def->SetSignalFilename("signal.txt");
  feldkamp.GetPointer()->SetBackProjectionFilter( bp.GetPointer() );
  TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->Update() );

  // FOV
  typedef rtk::FieldOfViewImageFilter<OutputImageType, OutputImageType> FOVFilterType;
  FOVFilterType::Pointer fov=FOVFilterType::New();
  fov->SetInput(0, feldkamp->GetOutput());
  fov->SetProjectionsStack( wholeImage.GetPointer() );
  fov->SetGeometry( geometry );
  TRY_AND_EXIT_ON_ITK_EXCEPTION( fov->Update() );

  // Create a reference object (in this case a 3D phantom reference).
  // Ellipse 1
  typedef rtk::DrawEllipsoidImageFilter<OutputImageType, OutputImageType> DEType;
  DEType::Pointer e1 = DEType::New();
  e1->SetInput( tomographySource->GetOutput() );
  e1->SetAttenuation(2.);
  DEType::VectorType axis(3, 60.);
  e1->SetAxis(axis);
  DEType::VectorType center(3, 0.);
  e1->SetCenter(center);
  e1->SetAngle(0.);
  e1->InPlaceOff();
  TRY_AND_EXIT_ON_ITK_EXCEPTION( e1->Update() )

  // Ellipse 2
  DEType::Pointer e2 = DEType::New();
  e2->SetInput(e1->GetOutput());
  e2->SetAttenuation(-1.);
  DEType::VectorType axis2(3, 8.);
  e2->SetAxis(axis2);
  DEType::VectorType center2(3, 0.);
  e2->SetCenter(center2);
  e2->SetAngle(0.);
  e2->InPlaceOff();
  TRY_AND_EXIT_ON_ITK_EXCEPTION( e2->Update() )

  CheckImageQuality<OutputImageType>(fov->GetOutput(), e2->GetOutput());

  std::cout << "Test PASSED! " << std::endl;

  itksys::SystemTools::RemoveFile("signal.txt");

  return EXIT_SUCCESS;
}
<commit_msg>Added missing include<commit_after>#include <itkImageRegionConstIterator.h>
#include <itkPasteImageFilter.h>
#include <itksys/SystemTools.hxx>

#include "rtkTestConfiguration.h"
#include "rtkRayEllipsoidIntersectionImageFilter.h"
#include "rtkDrawEllipsoidImageFilter.h"
#include "rtkConstantImageSource.h"
#include "rtkFieldOfViewImageFilter.h"
#include "rtkFDKConeBeamReconstructionFilter.h"
#include "rtkFDKWarpBackProjectionImageFilter.h"
#include "rtkCyclicDeformationImageFilter.h"

template<class TImage>
void CheckImageQuality(typename TImage::Pointer recon, typename TImage::Pointer ref)
{
#if !(FAST_TESTS_NO_CHECKS)
  typedef itk::ImageRegionConstIterator<TImage> ImageIteratorType;
  ImageIteratorType itTest( recon, recon->GetBufferedRegion() );
  ImageIteratorType itRef( ref, ref->GetBufferedRegion() );

  typedef double ErrorType;
  ErrorType TestError = 0.;
  ErrorType EnerError = 0.;

  itTest.GoToBegin();
  itRef.GoToBegin();

  while( !itRef.IsAtEnd() )
    {
    typename TImage::PixelType TestVal = itTest.Get();
    typename TImage::PixelType RefVal = itRef.Get();
    TestError += vcl_abs(RefVal - TestVal);
    EnerError += vcl_pow(ErrorType(RefVal - TestVal), 2.);
    ++itTest;
    ++itRef;
    }
  // Error per Pixel
  ErrorType ErrorPerPixel = TestError/ref->GetBufferedRegion().GetNumberOfPixels();
  std::cout << "\nError per Pixel = " << ErrorPerPixel << std::endl;
  // MSE
  ErrorType MSE = EnerError/ref->GetBufferedRegion().GetNumberOfPixels();
  std::cout << "MSE = " << MSE << std::endl;
  // PSNR
  ErrorType PSNR = 20*log10(2.0) - 10*log10(MSE);
  std::cout << "PSNR = " << PSNR << "dB" << std::endl;
  // QI
  ErrorType QI = (2.0-ErrorPerPixel)/2.0;
  std::cout << "QI = " << QI << std::endl;

  // Checking results
  if (ErrorPerPixel > 0.05)
  {
    std::cerr << "Test Failed, Error per pixel not valid! "
              << ErrorPerPixel << " instead of 0.05." << std::endl;
    exit( EXIT_FAILURE);
  }
  if (PSNR < 22.)
  {
    std::cerr << "Test Failed, PSNR not valid! "
              << PSNR << " instead of 23" << std::endl;
    exit( EXIT_FAILURE);
  }
#endif
}

int main(int, char** )
{
  const unsigned int Dimension = 3;
  typedef float                                    OutputPixelType;
  typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
#if FAST_TESTS_NO_CHECKS
  const unsigned int NumberOfProjectionImages = 3;
#else
  const unsigned int NumberOfProjectionImages = 128;
#endif

  // Constant image sources
  typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType;
  ConstantImageSourceType::PointType origin;
  ConstantImageSourceType::SizeType size;
  ConstantImageSourceType::SpacingType spacing;

  ConstantImageSourceType::Pointer tomographySource  = ConstantImageSourceType::New();
  origin[0] = -63.;
  origin[1] = -31.;
  origin[2] = -63.;
#if FAST_TESTS_NO_CHECKS
  size[0] = 32;
  size[1] = 32;
  size[2] = 32;
  spacing[0] = 8.;
  spacing[1] = 8.;
  spacing[2] = 8.;
#else
  size[0] = 64;
  size[1] = 32;
  size[2] = 64;
  spacing[0] = 2.;
  spacing[1] = 2.;
  spacing[2] = 2.;
#endif
  tomographySource->SetOrigin( origin );
  tomographySource->SetSpacing( spacing );
  tomographySource->SetSize( size );
  tomographySource->SetConstant( 0. );

  ConstantImageSourceType::Pointer projectionsSource = ConstantImageSourceType::New();
  origin[0] = -254.;
  origin[1] = -254.;
  origin[2] = -254.;
#if FAST_TESTS_NO_CHECKS
  size[0] = 32;
  size[1] = 32;
  size[2] = NumberOfProjectionImages;
  spacing[0] = 32.;
  spacing[1] = 32.;
  spacing[2] = 32.;
#else
  size[0] = 128;
  size[1] = 128;
  size[2] = NumberOfProjectionImages;
  spacing[0] = 4.;
  spacing[1] = 4.;
  spacing[2] = 4.;
#endif
  projectionsSource->SetOrigin( origin );
  projectionsSource->SetSpacing( spacing );
  projectionsSource->SetSize( size );
  projectionsSource->SetConstant( 0. );

  ConstantImageSourceType::Pointer oneProjectionSource = ConstantImageSourceType::New();
  size[2] = 1;
  oneProjectionSource->SetOrigin( origin );
  oneProjectionSource->SetSpacing( spacing );
  oneProjectionSource->SetSize( size );
  oneProjectionSource->SetConstant( 0. );

  // Geometry object
  typedef rtk::ThreeDCircularProjectionGeometry GeometryType;
  GeometryType::Pointer geometry = GeometryType::New();

  // Projections
  typedef rtk::RayEllipsoidIntersectionImageFilter<OutputImageType, OutputImageType> REIType;
  typedef itk::PasteImageFilter <OutputImageType, OutputImageType, OutputImageType > PasteImageFilterType;
  OutputImageType::IndexType destinationIndex;
  destinationIndex[0] = 0;
  destinationIndex[1] = 0;
  destinationIndex[2] = 0;
  PasteImageFilterType::Pointer pasteFilter = PasteImageFilterType::New();

  std::ofstream signalFile("signal.txt");
  OutputImageType::Pointer wholeImage = projectionsSource->GetOutput();
  for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++)
    {
    geometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages, 0, 0, 0, 0, 20, 15);

    // Geometry object
    GeometryType::Pointer oneProjGeometry = GeometryType::New();
    oneProjGeometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages, 0, 0, 0, 0, 20, 15);

    // Ellipse 1
    REIType::Pointer e1 = REIType::New();
    e1->SetInput(oneProjectionSource->GetOutput());
    e1->SetGeometry(oneProjGeometry);
    e1->SetMultiplicativeConstant(2.);
    e1->SetSemiPrincipalAxisX(60.);
    e1->SetSemiPrincipalAxisY(60.);
    e1->SetSemiPrincipalAxisZ(60.);
    e1->SetCenterX(0.);
    e1->SetCenterY(0.);
    e1->SetCenterZ(0.);
    e1->SetRotationAngle(0.);
    e1->InPlaceOff();
    e1->Update();

    // Ellipse 2
    REIType::Pointer e2 = REIType::New();
    e2->SetInput(e1->GetOutput());
    e2->SetGeometry(oneProjGeometry);
    e2->SetMultiplicativeConstant(-1.);
    e2->SetSemiPrincipalAxisX(8.);
    e2->SetSemiPrincipalAxisY(8.);
    e2->SetSemiPrincipalAxisZ(8.);
    e2->SetCenterX( 4*(vcl_abs( (4+noProj) % 8 - 4.) - 2.) );
    e2->SetCenterY(0.);
    e2->SetCenterZ(0.);
    e2->SetRotationAngle(0.);
    e2->Update();

    // Adding each projection to volume
    pasteFilter->SetSourceImage(e2->GetOutput());
    pasteFilter->SetDestinationImage(wholeImage);
    pasteFilter->SetSourceRegion(e2->GetOutput()->GetLargestPossibleRegion());
    pasteFilter->SetDestinationIndex(destinationIndex);
    pasteFilter->Update();
    wholeImage = pasteFilter->GetOutput();
    destinationIndex[2]++;

    // Signal
    signalFile << (noProj % 8) / 8. << std::endl;
    }

  // Create vector field
  typedef itk::Vector<float,3>                                                 DVFPixelType;
  typedef itk::Image< DVFPixelType, 3 >                                        DVFImageType;
  typedef rtk::CyclicDeformationImageFilter< DVFImageType >                    DeformationType;
  typedef itk::ImageRegionIteratorWithIndex< DeformationType::InputImageType > IteratorType;

  DeformationType::InputImageType::Pointer deformationField;
  deformationField = DeformationType::InputImageType::New();

  DeformationType::InputImageType::IndexType startMotion;
  startMotion[0] = 0; // first index on X
  startMotion[1] = 0; // first index on Y
  startMotion[2] = 0; // first index on Z
  startMotion[3] = 0; // first index on t
  DeformationType::InputImageType::SizeType sizeMotion;
  sizeMotion[0] = 64; // size along X
  sizeMotion[1] = 64; // size along Y
  sizeMotion[2] = 64; // size along Z
  sizeMotion[3] = 2;  // size along t
  DeformationType::InputImageType::PointType originMotion;
  originMotion[0] = (sizeMotion[0]-1)*(-0.5); // size along X
  originMotion[1] = (sizeMotion[1]-1)*(-0.5); // size along Y
  originMotion[2] = (sizeMotion[2]-1)*(-0.5); // size along Z
  originMotion[3] = 0.;
  DeformationType::InputImageType::RegionType regionMotion;
  regionMotion.SetSize( sizeMotion );
  regionMotion.SetIndex( startMotion );
  deformationField->SetRegions( regionMotion );
  deformationField->SetOrigin(originMotion);
  deformationField->Allocate();

  // Vector Field initilization
  DVFPixelType vec;
  vec.Fill(0.);
  IteratorType inputIt( deformationField, deformationField->GetLargestPossibleRegion() );
  for ( inputIt.GoToBegin(); !inputIt.IsAtEnd(); ++inputIt)
    {
    if(inputIt.GetIndex()[3]==0)
      vec[0] = -8.;
    else
      vec[0] = 8.;
    inputIt.Set(vec);
    }

  // Create cyclic deformation
  DeformationType::Pointer def = DeformationType::New();
  def->SetInput(deformationField);
  typedef rtk::FDKWarpBackProjectionImageFilter<OutputImageType, OutputImageType, DeformationType> WarpBPType;
  WarpBPType::Pointer bp = WarpBPType::New();
  bp->SetDeformation(def);
  bp->SetGeometry( geometry.GetPointer() );

  // FDK reconstruction filtering
#ifdef USE_CUDA
  typedef rtk::CudaFDKConeBeamReconstructionFilter                FDKType;
#elif USE_OPENCL
  typedef rtk::OpenCLFDKConeBeamReconstructionFilter              FDKType;
#else
  typedef rtk::FDKConeBeamReconstructionFilter< OutputImageType > FDKType;
#endif
  FDKType::Pointer feldkamp = FDKType::New();
  feldkamp->SetInput( 0, tomographySource->GetOutput() );
  feldkamp->SetInput( 1, wholeImage );
  feldkamp->SetGeometry( geometry );
  def->SetSignalFilename("signal.txt");
  feldkamp.GetPointer()->SetBackProjectionFilter( bp.GetPointer() );
  TRY_AND_EXIT_ON_ITK_EXCEPTION( feldkamp->Update() );

  // FOV
  typedef rtk::FieldOfViewImageFilter<OutputImageType, OutputImageType> FOVFilterType;
  FOVFilterType::Pointer fov=FOVFilterType::New();
  fov->SetInput(0, feldkamp->GetOutput());
  fov->SetProjectionsStack( wholeImage.GetPointer() );
  fov->SetGeometry( geometry );
  TRY_AND_EXIT_ON_ITK_EXCEPTION( fov->Update() );

  // Create a reference object (in this case a 3D phantom reference).
  // Ellipse 1
  typedef rtk::DrawEllipsoidImageFilter<OutputImageType, OutputImageType> DEType;
  DEType::Pointer e1 = DEType::New();
  e1->SetInput( tomographySource->GetOutput() );
  e1->SetAttenuation(2.);
  DEType::VectorType axis(3, 60.);
  e1->SetAxis(axis);
  DEType::VectorType center(3, 0.);
  e1->SetCenter(center);
  e1->SetAngle(0.);
  e1->InPlaceOff();
  TRY_AND_EXIT_ON_ITK_EXCEPTION( e1->Update() )

  // Ellipse 2
  DEType::Pointer e2 = DEType::New();
  e2->SetInput(e1->GetOutput());
  e2->SetAttenuation(-1.);
  DEType::VectorType axis2(3, 8.);
  e2->SetAxis(axis2);
  DEType::VectorType center2(3, 0.);
  e2->SetCenter(center2);
  e2->SetAngle(0.);
  e2->InPlaceOff();
  TRY_AND_EXIT_ON_ITK_EXCEPTION( e2->Update() )

  CheckImageQuality<OutputImageType>(fov->GetOutput(), e2->GetOutput());

  std::cout << "Test PASSED! " << std::endl;

  itksys::SystemTools::RemoveFile("signal.txt");

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*
 * Part of HTTPP.
 *
 * Distributed under the 3-clause BSD licence (See LICENCE.TXT file at the
 * project root).
 *
 * Copyright (c) 2014 Thomas Sanchez.  All rights reserved.
 *
 */

#include <boost/test/unit_test.hpp>
#include <iostream>

#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>

#include "httpp/HttpServer.hpp"
#include "httpp/HttpClient.hpp"

using namespace HTTPP;

using HTTPP::HTTP::Request;
using HTTPP::HTTP::Response;
using HTTPP::HTTP::Connection;

static Connection* gconn = nullptr;
void handler(Connection* connection, Request&&)
{
    gconn = connection;
}

BOOST_AUTO_TEST_CASE(cancel_async_operation)
{
    HttpClient client;

    HttpServer server;
    server.start();
    server.setSink(&handler);
    server.bind("localhost", "8080");

    HttpClient::Request request;
    request
        .url("http://localhost:8080")
        .joinUrlPath("test")
        .joinUrlPath("kiki", true);

    auto handler = client.async_get(
            std::move(request),
            [](HttpClient::Future&& fut)
            { BOOST_CHECK_THROW(fut.get(), HTTPP::UTILS::OperationAborted); });

    std::this_thread::sleep_for(std::chrono::seconds(1));
    handler.cancelOperation();
    std::this_thread::sleep_for(std::chrono::seconds(1));

    Connection::releaseFromHandler(gconn);
    server.stop();
    BOOST_LOG_TRIVIAL(error) << "operation cancelled";
}

static std::atomic_int nb_gconns = { 0 };
static std::vector<Connection*> gconns;
void handler_push(Connection* connection, Request&&)
{
    gconns.push_back(connection);
}

BOOST_AUTO_TEST_CASE(delete_pending_connection)
{
    HttpServer server;
    server.start();
    server.setSink(&handler_push);
    server.bind("localhost", "8080");

    std::atomic_int nb_cb {0};

    {
        HttpClient client;

        HttpClient::Request request;
        request.url("http://localhost:8080");

        for (int i = 0; i < 1000; ++i)
        {
            client.async_get(HttpClient::Request{ request },
                             [&nb_cb](HttpClient::Future&& fut)
                             {
                ++nb_cb;
                BOOST_CHECK_THROW(fut.get(), HTTPP::UTILS::OperationAborted);
            });
        }

        //std::this_thread::sleep_for(std::chrono::seconds(1));
    }

    boost::log::core::get()->set_filter
    (
        boost::log::trivial::severity > boost::log::trivial::error
    );
    server.stopListeners();
    std::for_each(
        std::begin(gconns), std::end(gconns), &Connection::releaseFromHandler);
    server.stop();

    BOOST_CHECK_EQUAL(nb_cb.load(), 1000);
}

BOOST_AUTO_TEST_CASE(delete_pending_connection_google)
{
    boost::log::core::get()->set_filter
    (
        boost::log::trivial::severity >= boost::log::trivial::debug
    );

    HttpClient client;

    HttpClient::Request request;
    request.url("http://google.com").followRedirect(true);

    for (int i = 0; i < 10; ++i)
    {
        client.async_get(HttpClient::Request{ request },
                         [](HttpClient::Future&& fut)
                         {
            BOOST_LOG_TRIVIAL(debug) << "Hello world";
            BOOST_CHECK_THROW(fut.get(), HTTPP::UTILS::OperationAborted);
        });
    }
}

void handler2(Connection* c, Request&&)
{
    c->response().setCode(HTTPP::HTTP::HttpCode::Ok);
    c->sendResponse();
}

BOOST_AUTO_TEST_CASE(late_cancel)
{
    HttpServer server;
    server.start();
    server.setSink(&handler2);
    server.bind("localhost", "8080");

    HttpClient client;

    HttpClient::Request request;
    request.url("http://localhost:8080");

    auto handler = client.async_get(std::move(request),
                                    [](HttpClient::Future&& fut)
                                    {
        BOOST_LOG_TRIVIAL(debug) << "Response received";
        fut.get();
    });

    std::this_thread::sleep_for(std::chrono::milliseconds(500));
    handler.cancelOperation();
    BOOST_LOG_TRIVIAL(error) << "operation cancelled";
}

<commit_msg>Add minor check<commit_after>/*
 * Part of HTTPP.
 *
 * Distributed under the 3-clause BSD licence (See LICENCE.TXT file at the
 * project root).
 *
 * Copyright (c) 2014 Thomas Sanchez.  All rights reserved.
 *
 */

#include <boost/test/unit_test.hpp>
#include <iostream>

#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>

#include "httpp/HttpServer.hpp"
#include "httpp/HttpClient.hpp"

using namespace HTTPP;

using HTTPP::HTTP::Request;
using HTTPP::HTTP::Response;
using HTTPP::HTTP::Connection;

static Connection* gconn = nullptr;
void handler(Connection* connection, Request&&)
{
    gconn = connection;
}

BOOST_AUTO_TEST_CASE(cancel_async_operation)
{
    HttpClient client;

    HttpServer server;
    server.start();
    server.setSink(&handler);
    server.bind("localhost", "8080");

    HttpClient::Request request;
    request
        .url("http://localhost:8080")
        .joinUrlPath("test")
        .joinUrlPath("kiki", true);

    auto handler = client.async_get(
            std::move(request),
            [](HttpClient::Future&& fut)
            { BOOST_CHECK_THROW(fut.get(), HTTPP::UTILS::OperationAborted); });

    std::this_thread::sleep_for(std::chrono::seconds(1));
    handler.cancelOperation();
    std::this_thread::sleep_for(std::chrono::seconds(1));

    Connection::releaseFromHandler(gconn);
    server.stop();
    BOOST_LOG_TRIVIAL(error) << "operation cancelled";
}

static std::atomic_int nb_gconns = { 0 };
static std::vector<Connection*> gconns;
void handler_push(Connection* connection, Request&&)
{
    gconns.push_back(connection);
}

BOOST_AUTO_TEST_CASE(delete_pending_connection)
{
    HttpServer server;
    server.start();
    server.setSink(&handler_push);
    server.bind("localhost", "8080");

    std::atomic_int nb_cb {0};

    {
        HttpClient client;

        HttpClient::Request request;
        request.url("http://localhost:8080");

        for (int i = 0; i < 1000; ++i)
        {
            client.async_get(HttpClient::Request{ request },
                             [&nb_cb](HttpClient::Future&& fut)
                             {
                ++nb_cb;
                BOOST_CHECK_THROW(fut.get(), HTTPP::UTILS::OperationAborted);
            });
        }

        //std::this_thread::sleep_for(std::chrono::seconds(1));
    }

    boost::log::core::get()->set_filter
    (
        boost::log::trivial::severity > boost::log::trivial::error
    );
    server.stopListeners();
    std::for_each(
        std::begin(gconns), std::end(gconns), &Connection::releaseFromHandler);
    server.stop();

    BOOST_CHECK_EQUAL(nb_cb.load(), 1000);
}

BOOST_AUTO_TEST_CASE(delete_pending_connection_google)
{
    boost::log::core::get()->set_filter
    (
        boost::log::trivial::severity >= boost::log::trivial::debug
    );

    HttpClient client;

    HttpClient::Request request;
    request.url("http://google.com").followRedirect(true);

    for (int i = 0; i < 10; ++i)
    {
        client.async_get(HttpClient::Request{ request },
                         [](HttpClient::Future&& fut)
                         {
            BOOST_LOG_TRIVIAL(debug) << "Hello world";
            BOOST_CHECK_THROW(fut.get(), HTTPP::UTILS::OperationAborted);
        });
    }
}

void handler2(Connection* c, Request&&)
{
    c->response().setCode(HTTPP::HTTP::HttpCode::Ok);
    c->sendResponse();
}

BOOST_AUTO_TEST_CASE(late_cancel)
{
    HttpServer server;
    server.start();
    server.setSink(&handler2);
    server.bind("localhost", "8080");

    HttpClient client;

    HttpClient::Request request;
    request.url("http://localhost:8080");

    bool ok = false;
    auto handler = client.async_get(std::move(request),
                                    [&ok](HttpClient::Future&& fut)
                                    {
        ok = true;
        BOOST_LOG_TRIVIAL(debug) << "Response received";
        fut.get();
    });

    std::this_thread::sleep_for(std::chrono::milliseconds(500));
    BOOST_CHECK(ok);
    handler.cancelOperation();
    BOOST_LOG_TRIVIAL(error) << "operation cancelled";
}

<|endoftext|>