text:
#include <algorithm>
#include <iostream>
#include <list>
#include <map>
#include <string>
#include <thread>
#include <vector>
using namespace std;

#include "ctrlclaw.hpp"
#include "log.hpp"
#include "zhiziword.hpp"
#include "textpump.hpp"

static std::shared_ptr<ZhiZiWord> gZhiZi;
bool loadMasterDB(void) {
  gZhiZi = std::make_shared<ZhiZiWord>("./db/zhizi/word","./db/zhizi/phrase");
  if (gZhiZi->loadMaster(false) == false) {
    return false;
  }
  return true;
}
void unloadMasterDB(void) {
  gZhiZi->unloadMaster();
  gZhiZi.reset();
}

#include "nlohmann/json.hpp"
using json = nlohmann::json;
#include <sstream>

string processWord(const string &text,const string &lang);

static bool gJapanese = false;
static string gLang = "ja";
string processText(const string &text) {
  try {
    json configJson = json::parse(text);
    configJson.find("lang");
    auto langOpt = configJson.find("lang");
    if (langOpt != configJson.end()) {
      gLang = langOpt->get<string>();
    }
    auto sentenceOpt = configJson.find("sentence");
    if (sentenceOpt!= configJson.end()) {
      auto text = sentenceOpt->get<string>();
      return processWord(text,gLang);

    }
  } catch (std::exception &e) {
    DUMP_VAR(e.what());
    return "";
  }
  return "";
}

string createTTSLink(json clipList);

string processWord(const string &text,const string &lang) {
  json resultTotal;
  json ttsTotal;
  auto learnZhiZi = [&](string wordStr, vector<string> word,bool multi) {
    //DUMP_VAR(gZhiZi);
    DUMP_VAR(wordStr);
    DUMP_VAR(multi);
    if(multi) {
      auto result = gZhiZi->cut(word, wordStr, lang);
      for (auto& element : result["tts"]) {
        ttsTotal.push_back(element);
      }
      resultTotal.push_back(result);
    } else {
      auto result = gZhiZi->cutSpace(word, wordStr, lang);
      for (auto& element : result["tts"]) {
        ttsTotal.push_back(element);
      }
      resultTotal.push_back(result);
    }
  };
  CtrlClaw claw;
  claw.claw(text);
  claw.eachSentenceMix(learnZhiZi);
  try {
    json result;
    result[u8"wai"] = resultTotal;
    result[u8"m3u8"] = createTTSLink(ttsTotal);
    return result.dump();
  } catch (std::exception &e) {
    DUMP_VAR(e.what());
  }
  return "";
}

#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/lexical_cast.hpp>
#include <fstream>

string createTTSLink(json clipList) {
  string m3u8;
  for (auto& clip : clipList) {
    DUMP_VAR(clip);
    string clipUrl("https://ipfs.io/ipfs/");
    clipUrl += clip;
    DUMP_VAR(clipUrl);
    m3u8 += clipUrl;
    m3u8 += "\r\n";
  }
  DUMP_VAR(m3u8);
  auto id = boost::uuids::random_generator()();
  auto fileName = boost::lexical_cast<std::string>(id);
  ::system("mkdir -p /watorvapor/autogen/wator/wai/audio/");
  string path("/watorvapor/autogen/wator/wai/audio/");
  path += fileName;
  path += ".m3u8";
  std::ofstream outfile (path,std::ofstream::binary);
  outfile << m3u8;

  string url = "/autogen/wai/audio/";
  url += fileName;
  url += ".m3u8";
  return url;
}


text:
//
// ssl/old/detail/stream_service.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2005 Voipster / Indrek dot Juhani at voipster dot com
// Copyright (c) 2005-2011 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef ASIO_SSL_OLD_DETAIL_OPENSSL_STREAM_SERVICE_HPP
#define ASIO_SSL_OLD_DETAIL_OPENSSL_STREAM_SERVICE_HPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)

#include "asio/detail/config.hpp"
#include <cstddef>
#include <climits>
#include <memory>
#include <boost/config.hpp>
#include <boost/noncopyable.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include "asio/detail/buffer_sequence_adapter.hpp"
#include "asio/error.hpp"
#include "asio/io_service.hpp"
#include "asio/ssl/basic_context.hpp"
#include "asio/ssl/stream_base.hpp"
#include "asio/ssl/old/detail/openssl_operation.hpp"
#include "asio/ssl/detail/openssl_types.hpp"
#include "asio/strand.hpp"
#include "asio/system_error.hpp"

#include "asio/detail/push_options.hpp"

namespace asio {
namespace ssl {
namespace old {
namespace detail {

class openssl_stream_service
  : public asio::detail::service_base<openssl_stream_service>
{
private:
  enum { max_buffer_size = INT_MAX };

  //Base handler for asyncrhonous operations
  template <typename Stream>
  class base_handler
  {
  public:
    typedef boost::function<
      void (const asio::error_code&, size_t)> func_t;

    base_handler(asio::io_service& io_service)
      : op_(NULL)
      , io_service_(io_service)
      , work_(io_service)
    {}

    void do_func(const asio::error_code& error, size_t size)
    {
      func_(error, size);
    }

    void set_operation(openssl_operation<Stream>* op) { op_ = op; }
    void set_func(func_t func) { func_ = func; }

    ~base_handler()
    {
      delete op_;
    }

  private:
    func_t func_;
    openssl_operation<Stream>* op_;
    asio::io_service& io_service_;
    asio::io_service::work work_;
  };  // class base_handler

  // Handler for asynchronous IO (write/read) operations
  template<typename Stream, typename Handler>
  class io_handler
    : public base_handler<Stream>
  {
  public:
    io_handler(Handler handler, asio::io_service& io_service)
      : base_handler<Stream>(io_service)
      , handler_(handler)
    {
      this->set_func(boost::bind(
        &io_handler<Stream, Handler>::handler_impl,
        this, boost::arg<1>(), boost::arg<2>() ));
    }

  private:
    Handler handler_;
    void handler_impl(const asio::error_code& error, size_t size)
    {
      std::auto_ptr<io_handler<Stream, Handler> > this_ptr(this);
      handler_(error, size);
    }
  };  // class io_handler

  // Handler for asyncrhonous handshake (connect, accept) functions
  template <typename Stream, typename Handler>
  class handshake_handler
    : public base_handler<Stream>
  {
  public:
    handshake_handler(Handler handler, asio::io_service& io_service)
      : base_handler<Stream>(io_service)
      , handler_(handler)
    {
      this->set_func(boost::bind(
        &handshake_handler<Stream, Handler>::handler_impl,
        this, boost::arg<1>(), boost::arg<2>() ));
    }

  private:
    Handler handler_;
    void handler_impl(const asio::error_code& error, size_t)
    {
      std::auto_ptr<handshake_handler<Stream, Handler> > this_ptr(this);
      handler_(error);
    }

  };  // class handshake_handler

  // Handler for asyncrhonous shutdown
  template <typename Stream, typename Handler>
  class shutdown_handler
    : public base_handler<Stream>
  {
  public:
    shutdown_handler(Handler handler, asio::io_service& io_service)
      : base_handler<Stream>(io_service),
        handler_(handler)
    {
      this->set_func(boost::bind(
        &shutdown_handler<Stream, Handler>::handler_impl,
        this, boost::arg<1>(), boost::arg<2>() ));
    }

  private:
    Handler handler_;
    void handler_impl(const asio::error_code& error, size_t)
    {
      std::auto_ptr<shutdown_handler<Stream, Handler> > this_ptr(this);
      handler_(error);
    }
  };  // class shutdown_handler

public:
  // The implementation type.
  typedef struct impl_struct
  {
    ::SSL* ssl;
    ::BIO* ext_bio;
    net_buffer recv_buf;
  } * impl_type;

  // Construct a new stream socket service for the specified io_service.
  explicit openssl_stream_service(asio::io_service& io_service)
    : asio::detail::service_base<openssl_stream_service>(io_service),
      strand_(io_service)
  {
  }

  // Destroy all user-defined handler objects owned by the service.
  void shutdown_service()
  {
  }

  // Return a null stream implementation.
  impl_type null() const
  {
    return 0;
  }

  // Create a new stream implementation.
  template <typename Stream, typename Context_Service>
  void create(impl_type& impl, Stream& /*next_layer*/,
      basic_context<Context_Service>& context)
  {
    impl = new impl_struct;
    impl->ssl = ::SSL_new(context.impl());
    ::SSL_set_mode(impl->ssl, SSL_MODE_ENABLE_PARTIAL_WRITE);
    ::SSL_set_mode(impl->ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
    ::BIO* int_bio = 0;
    impl->ext_bio = 0;
    ::BIO_new_bio_pair(&int_bio, 8192, &impl->ext_bio, 8192);
    ::SSL_set_bio(impl->ssl, int_bio, int_bio);
  }

  // Destroy a stream implementation.
  template <typename Stream>
  void destroy(impl_type& impl, Stream& /*next_layer*/)
  {
    if (impl != 0)
    {
      ::BIO_free(impl->ext_bio);
      ::SSL_free(impl->ssl);
      delete impl;
      impl = 0;
    }
  }

  // Perform SSL handshaking.
  template <typename Stream>
  asio::error_code handshake(impl_type& impl, Stream& next_layer,
      stream_base::handshake_type type, asio::error_code& ec)
  {
    try
    {
      openssl_operation<Stream> op(
        type == stream_base::client ?
          &ssl_wrap<mutex_type>::SSL_connect:
          &ssl_wrap<mutex_type>::SSL_accept,
        next_layer,
        impl->recv_buf,
        impl->ssl,
        impl->ext_bio);
      op.start();
    }
    catch (asio::system_error& e)
    {
      ec = e.code();
      return ec;
    }

    ec = asio::error_code();
    return ec;
  }

  // Start an asynchronous SSL handshake.
  template <typename Stream, typename Handler>
  void async_handshake(impl_type& impl, Stream& next_layer,
      stream_base::handshake_type type, Handler handler)
  {
    typedef handshake_handler<Stream, Handler> connect_handler;

    connect_handler* local_handler =
      new connect_handler(handler, get_io_service());

    openssl_operation<Stream>* op = new openssl_operation<Stream>
    (
      type == stream_base::client ?
        &ssl_wrap<mutex_type>::SSL_connect:
        &ssl_wrap<mutex_type>::SSL_accept,
      next_layer,
      impl->recv_buf,
      impl->ssl,
      impl->ext_bio,
      boost::bind
      (
        &base_handler<Stream>::do_func,
        local_handler,
        boost::arg<1>(),
        boost::arg<2>()
      ),
      strand_
    );
    local_handler->set_operation(op);

    strand_.post(boost::bind(&openssl_operation<Stream>::start, op));
  }

  // Shut down SSL on the stream.
  template <typename Stream>
  asio::error_code shutdown(impl_type& impl, Stream& next_layer,
      asio::error_code& ec)
  {
    try
    {
      openssl_operation<Stream> op(
        &ssl_wrap<mutex_type>::SSL_shutdown,
        next_layer,
        impl->recv_buf,
        impl->ssl,
        impl->ext_bio);
      op.start();
    }
    catch (asio::system_error& e)
    {
      ec = e.code();
      return ec;
    }

    ec = asio::error_code();
    return ec;
  }

  // Asynchronously shut down SSL on the stream.
  template <typename Stream, typename Handler>
  void async_shutdown(impl_type& impl, Stream& next_layer, Handler handler)
  {
    typedef shutdown_handler<Stream, Handler> disconnect_handler;

    disconnect_handler* local_handler =
      new disconnect_handler(handler, get_io_service());

    openssl_operation<Stream>* op = new openssl_operation<Stream>
    (
      &ssl_wrap<mutex_type>::SSL_shutdown,
      next_layer,
      impl->recv_buf,
      impl->ssl,
      impl->ext_bio,
      boost::bind
      (
        &base_handler<Stream>::do_func,
        local_handler,
        boost::arg<1>(),
        boost::arg<2>()
      ),
      strand_
    );
    local_handler->set_operation(op);

    strand_.post(boost::bind(&openssl_operation<Stream>::start, op));
  }

  // Write some data to the stream.
  template <typename Stream, typename Const_Buffers>
  std::size_t write_some(impl_type& impl, Stream& next_layer,
      const Const_Buffers& buffers, asio::error_code& ec)
  {
    size_t bytes_transferred = 0;
    try
    {
      asio::const_buffer buffer =
        asio::detail::buffer_sequence_adapter<
          asio::const_buffer, Const_Buffers>::first(buffers);

      std::size_t buffer_size = asio::buffer_size(buffer);
      if (buffer_size > max_buffer_size)
        buffer_size = max_buffer_size;
      else if (buffer_size == 0)
      {
        ec = asio::error_code();
        return 0;
      }

      boost::function<int (SSL*)> send_func =
        boost::bind(boost::type<int>(), &::SSL_write, boost::arg<1>(),
            asio::buffer_cast<const void*>(buffer),
            static_cast<int>(buffer_size));
      openssl_operation<Stream> op(
        send_func,
        next_layer,
        impl->recv_buf,
        impl->ssl,
        impl->ext_bio
      );
      bytes_transferred = static_cast<size_t>(op.start());
    }
    catch (asio::system_error& e)
    {
      ec = e.code();
      return 0;
    }

    ec = asio::error_code();
    return bytes_transferred;
  }

  // Start an asynchronous write.
  template <typename Stream, typename Const_Buffers, typename Handler>
  void async_write_some(impl_type& impl, Stream& next_layer,
      const Const_Buffers& buffers, Handler handler)
  {
    typedef io_handler<Stream, Handler> send_handler;

    asio::const_buffer buffer =
      asio::detail::buffer_sequence_adapter<
        asio::const_buffer, Const_Buffers>::first(buffers);

    std::size_t buffer_size = asio::buffer_size(buffer);
    if (buffer_size > max_buffer_size)
      buffer_size = max_buffer_size;
    else if (buffer_size == 0)
    {
      get_io_service().post(asio::detail::bind_handler(
            handler, asio::error_code(), 0));
      return;
    }

    send_handler* local_handler = new send_handler(handler, get_io_service());

    boost::function<int (SSL*)> send_func =
      boost::bind(boost::type<int>(), &::SSL_write, boost::arg<1>(),
          asio::buffer_cast<const void*>(buffer),
          static_cast<int>(buffer_size));

    openssl_operation<Stream>* op = new openssl_operation<Stream>
    (
      send_func,
      next_layer,
      impl->recv_buf,
      impl->ssl,
      impl->ext_bio,
      boost::bind
      (
        &base_handler<Stream>::do_func,
        local_handler,
        boost::arg<1>(),
        boost::arg<2>()
      ),
      strand_
    );
    local_handler->set_operation(op);

    strand_.post(boost::bind(&openssl_operation<Stream>::start, op));
  }

  // Read some data from the stream.
  template <typename Stream, typename Mutable_Buffers>
  std::size_t read_some(impl_type& impl, Stream& next_layer,
      const Mutable_Buffers& buffers, asio::error_code& ec)
  {
    size_t bytes_transferred = 0;
    try
    {
      asio::mutable_buffer buffer =
        asio::detail::buffer_sequence_adapter<
          asio::mutable_buffer, Mutable_Buffers>::first(buffers);

      std::size_t buffer_size = asio::buffer_size(buffer);
      if (buffer_size > max_buffer_size)
        buffer_size = max_buffer_size;
      else if (buffer_size == 0)
      {
        ec = asio::error_code();
        return 0;
      }

      boost::function<int (SSL*)> recv_func =
        boost::bind(boost::type<int>(), &::SSL_read, boost::arg<1>(),
            asio::buffer_cast<void*>(buffer),
            static_cast<int>(buffer_size));
      openssl_operation<Stream> op(recv_func,
        next_layer,
        impl->recv_buf,
        impl->ssl,
        impl->ext_bio
      );

      bytes_transferred = static_cast<size_t>(op.start());
    }
    catch (asio::system_error& e)
    {
      ec = e.code();
      return 0;
    }

    ec = asio::error_code();
    return bytes_transferred;
  }

  // Start an asynchronous read.
  template <typename Stream, typename Mutable_Buffers, typename Handler>
  void async_read_some(impl_type& impl, Stream& next_layer,
      const Mutable_Buffers& buffers, Handler handler)
  {
    typedef io_handler<Stream, Handler> recv_handler;

    asio::mutable_buffer buffer =
      asio::detail::buffer_sequence_adapter<
        asio::mutable_buffer, Mutable_Buffers>::first(buffers);

    std::size_t buffer_size = asio::buffer_size(buffer);
    if (buffer_size > max_buffer_size)
      buffer_size = max_buffer_size;
    else if (buffer_size == 0)
    {
      get_io_service().post(asio::detail::bind_handler(
            handler, asio::error_code(), 0));
      return;
    }

    recv_handler* local_handler = new recv_handler(handler, get_io_service());

    boost::function<int (SSL*)> recv_func =
      boost::bind(boost::type<int>(), &::SSL_read, boost::arg<1>(),
          asio::buffer_cast<void*>(buffer),
          static_cast<int>(buffer_size));

    openssl_operation<Stream>* op = new openssl_operation<Stream>
    (
      recv_func,
      next_layer,
      impl->recv_buf,
      impl->ssl,
      impl->ext_bio,
      boost::bind
      (
        &base_handler<Stream>::do_func,
        local_handler,
        boost::arg<1>(),
        boost::arg<2>()
      ),
      strand_
    );
    local_handler->set_operation(op);

    strand_.post(boost::bind(&openssl_operation<Stream>::start, op));
  }

  // Peek at the incoming data on the stream.
  template <typename Stream, typename Mutable_Buffers>
  std::size_t peek(impl_type& /*impl*/, Stream& /*next_layer*/,
      const Mutable_Buffers& /*buffers*/, asio::error_code& ec)
  {
    ec = asio::error_code();
    return 0;
  }

  // Determine the amount of data that may be read without blocking.
  template <typename Stream>
  std::size_t in_avail(impl_type& /*impl*/, Stream& /*next_layer*/,
      asio::error_code& ec)
  {
    ec = asio::error_code();
    return 0;
  }

private:
  asio::io_service::strand strand_;

  typedef asio::detail::mutex mutex_type;

  template<typename Mutex>
  struct ssl_wrap
  {
    static Mutex ssl_mutex_;

    static int SSL_accept(SSL *ssl)
    {
      typename Mutex::scoped_lock lock(ssl_mutex_);
      return ::SSL_accept(ssl);
    }

    static int SSL_connect(SSL *ssl)
    {
      typename Mutex::scoped_lock lock(ssl_mutex_);
      return ::SSL_connect(ssl);
    }

    static int SSL_shutdown(SSL *ssl)
    {
      typename Mutex::scoped_lock lock(ssl_mutex_);
      return ::SSL_shutdown(ssl);
    }
  };
};

template<typename Mutex>
Mutex openssl_stream_service::ssl_wrap<Mutex>::ssl_mutex_;

} // namespace detail
} // namespace old
} // namespace ssl
} // namespace asio

#include "asio/detail/pop_options.hpp"

#endif // ASIO_SSL_OLD_DETAIL_OPENSSL_STREAM_SERVICE_HPP

ext: hpp


text:
/** dirty_page_table_test.cc                                 -*- C++ -*-
    Rémi Attab, 29 Aug 2012
    Copyright (c) 2012 Datacratic.  All rights reserved.

    Tests for the dirty page table thingy.

*/

#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK

#include "mmap/dirty_page_table.h"

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

using namespace std;
using namespace Datacratic;
using namespace Datacratic::MMap;

uint64_t makeAddr(int group, int64_t page)
{
    uint64_t word = 1ULL << (group + 9);
    word |= word + page;
    return (word << page_shift) | ((1ULL << page_shift) - 1);
};

BOOST_AUTO_TEST_CASE( test_table_basics )
{
    DirtyPageTable table;

    auto markGroup = [&](int group) {
        // cerr << "--- MARK " << group << " ---" << endl;

        table.markPage(makeAddr(group, 0));
        table.markPage(makeAddr(group, -1));

        // cerr << "=> " << table.print() << endl << endl;
    };

    auto clearGroup = [&](int group) {
        // cerr << "--- CLEAR " << group << " ---" << endl;

        BOOST_CHECK(table.clearPage(makeAddr(group, 0)));
        BOOST_CHECK(!table.clearPage(makeAddr(group, 0)));

        BOOST_CHECK(!table.clearPage(makeAddr(group, -2)));
        BOOST_CHECK(table.clearPage(makeAddr(group, -1)));
        BOOST_CHECK(!table.clearPage(makeAddr(group, -1)));

        // cerr << "=> " << table.print() << endl << endl;
    };

    auto testGroup = [&](int group) {
        markGroup(group);
        markGroup(group+1);
        markGroup(group-1);

        clearGroup(group);
        clearGroup(group+1);
        clearGroup(group-1);
    };

    for (int i = 0; i < 10; ++i)
        testGroup(i);
}

BOOST_AUTO_TEST_CASE( test_table_find )
{
    DirtyPageTable table;

    BOOST_CHECK_LT(table.nextPage(0ULL), 0);
    BOOST_CHECK_LT(table.nextPage(makeAddr(10, 0xFF)), 0);

    vector<uint64_t> addr = {
        makeAddr(-1, 0),   makeAddr(-1, 1),   makeAddr(-1, 0xFF),

        makeAddr(0, 0),    makeAddr(0, 1),    makeAddr(0, 2),
        makeAddr(0, 0xAA), makeAddr(0, 0xAB), makeAddr(0, 0xAD),
        makeAddr(0, 0xFE), makeAddr(0, 0xFF),

        makeAddr(1, 0),    makeAddr(1, 1),    makeAddr(1, 2),
        makeAddr(1, 0xCB), makeAddr(1, 0xCC), makeAddr(1, 0xCD),
        makeAddr(1, 0xFE), makeAddr(1, 0xFF),

        makeAddr(4, 0),    makeAddr(4, 1),    makeAddr(4, 2),
        makeAddr(4, 0xCB), makeAddr(4, 0xCC), makeAddr(4, 0xCD),
        makeAddr(4, 0xFE), makeAddr(4, 0xFF),

        makeAddr(10, 0xFF)
    };

    for (int i = 0; i < addr.size(); ++i)
        table.markPage(addr[i]);

    int64_t page = table.nextPage(0);
    for (int i = 0; i < addr.size(); ++i) {
        BOOST_CHECK_GE(page, 0);
        BOOST_CHECK_EQUAL(page, addr[i] >> page_shift << page_shift);

        page = table.nextPage(page + page_size);
    }

    BOOST_CHECK_LT(page, 0);
}

ext: cc

max_stars_repo_name: datacratic/DasDB

max_issues_repo_name: datacratic/DasDB

max_forks_repo_name: datacratic/DasDB


text:
//==============================================================================
//         Copyright 2003 - 2013   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2013   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#include <nt2/include/functions/abs.hpp>

#include <boost/dispatch/functor/meta/call.hpp>
#include <nt2/sdk/functor/meta/call.hpp>
#include <nt2/sdk/unit/tests/relation.hpp>
#include <nt2/sdk/unit/tests/type_expr.hpp>
#include <boost/simd/sdk/simd/io.hpp>
#include <boost/simd/sdk/simd/native.hpp>
#include <complex>
#include <nt2/sdk/complex/complex.hpp>
#include <nt2/sdk/complex/dry.hpp>
#include <nt2/sdk/unit/tests/ulp.hpp>
#include <nt2/sdk/meta/as_integer.hpp>
#include <nt2/include/functions/splat.hpp>
#include <nt2/sdk/unit/module.hpp>
#include <boost/simd/sdk/config.hpp>

#include <nt2/include/constants/five.hpp>
#include <nt2/include/constants/four.hpp>
#include <nt2/include/constants/mone.hpp>
#include <nt2/include/constants/one.hpp>
#include <nt2/include/constants/sqrt_2.hpp>
#include <nt2/include/constants/three.hpp>
#include <nt2/include/constants/valmax.hpp>
#include <nt2/include/constants/valmin.hpp>
#include <nt2/include/constants/zero.hpp>
#include <nt2/include/constants/inf.hpp>
#include <nt2/include/constants/minf.hpp>
#include <nt2/include/constants/nan.hpp>

NT2_TEST_CASE_TPL ( abs_cplx,   BOOST_SIMD_SIMD_REAL_TYPES)
{
  using nt2::abs;
  using nt2::tag::abs_;
  typedef typename std::complex<T> cT;
  using boost::simd::native;
  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;
  typedef native<T,ext_t>                  vT;
  typedef native<cT,ext_t>                vcT;
  typedef typename nt2::dry<T>             dT;
  typedef native<dT,ext_t>                vdT;

  // specific values tests
#ifndef BOOST_SIMD_NO_INVALIDS
  NT2_TEST_ULP_EQUAL(nt2::abs(vcT(nt2::Inf<vT>(),nt2::Nan<vT>())), nt2::Inf<vT>(), 0.5);
  NT2_TEST_ULP_EQUAL(nt2::abs(vcT(nt2::Inf<vT>(), nt2::Zero<vT>())), nt2::Inf<vT>(), 0.5);
  NT2_TEST_ULP_EQUAL(nt2::abs(vcT(nt2::Minf<vT>(), nt2::Zero<vT>())), nt2::Inf<vT>(), 0.5);
  NT2_TEST_ULP_EQUAL(nt2::abs(vcT(nt2::Nan<vT>(), nt2::Zero<vT>())), nt2::Nan<vT>(), 0.5);
  NT2_TEST_ULP_EQUAL(nt2::abs(vdT(nt2::Inf<vdT>())   ), nt2::Inf<vT>(), 0.5);
  NT2_TEST_ULP_EQUAL(nt2::abs(vdT(nt2::Inf<vdT>())   ), nt2::Inf<vT>(), 0.5);
  NT2_TEST_ULP_EQUAL(nt2::abs(vdT(nt2::Minf<vdT>())  ), nt2::Inf<vT>(), 0.5);
  NT2_TEST_ULP_EQUAL(nt2::abs(vdT(nt2::Nan<vdT>())   ), nt2::Nan<vT>(), 0.5);
#endif
  NT2_TEST_ULP_EQUAL(nt2::abs(vcT(nt2::Mone<vT>(), nt2::Zero<vT>())), nt2::One<vT>(), 0.5);
  NT2_TEST_ULP_EQUAL(nt2::abs(vcT(nt2::One<vT>(), nt2::Zero<vT>())), nt2::One<vT>(), 0.5);
  NT2_TEST_ULP_EQUAL(nt2::abs(vcT(nt2::Valmax<vT>(), nt2::Zero<vT>())), nt2::Valmax<vT>(), 0.5);
  NT2_TEST_ULP_EQUAL(nt2::abs(vcT(nt2::Valmin<vT>(), nt2::Zero<vT>())), nt2::Valmax<vT>(), 0.5);
  NT2_TEST_ULP_EQUAL(nt2::abs(vcT(nt2::Zero<vT>(), nt2::Zero<vT>())), nt2::Zero<vT>(), 0.5);
  NT2_TEST_ULP_EQUAL(nt2::abs(vcT(nt2::One<vT>(), nt2::One<vT>())), nt2::Sqrt_2<vT>(), 1);
  NT2_TEST_ULP_EQUAL(nt2::abs(vcT(nt2::Four<vT>(), nt2::Three<vT>())), nt2::Five<vT>(), 0.5);
  NT2_TEST_ULP_EQUAL(nt2::abs(vdT(nt2::Mone<vdT>())  ), nt2::One<vT>(), 0.5);
  NT2_TEST_ULP_EQUAL(nt2::abs(vdT(nt2::One<vdT>())   ), nt2::One<vT>(), 0.5);
  NT2_TEST_ULP_EQUAL(nt2::abs(vdT(nt2::Valmax<vdT>())), nt2::Valmax<vT>(), 0.5);
  NT2_TEST_ULP_EQUAL(nt2::abs(vdT(nt2::Valmin<vdT>())), nt2::Valmax<vT>(), 0.5);
  NT2_TEST_ULP_EQUAL(nt2::abs(vdT(nt2::Zero<vdT>())  ), nt2::Zero<vT>(), 0.5);
  NT2_TEST_ULP_EQUAL(nt2::abs(vdT(nt2::One<vdT>())   ), nt2::One<vT>(), 0.5);
  NT2_TEST_ULP_EQUAL(nt2::abs(vdT(nt2::Four<vdT>())  ), nt2::Four<vT>(), 0.5);
}

ext: cpp


text:
#include <stdio.h>

#include <boost/bind.hpp>
#include <cetty/buffer/Unpooled.h>
#include <cetty/logging/LoggerHelper.h>
#include <cetty/service/ClientService.h>
#include <cetty/gearman/builder/GearmanClientBuilder.h>
#include <cetty/gearman/GearmanClient.h>
#include <cetty/gearman/protocol/GearmanMessage.h>
#include <cetty/gearman/protocol/commands/Client.h>

using namespace cetty::buffer;
using namespace cetty::channel;
using namespace cetty::bootstrap;
using namespace cetty::service;
using namespace cetty::gearman;
using namespace cetty::gearman::builder;
using namespace cetty::gearman::protocol;

class GearmanEchoClient {
private:
    typedef ::cetty::service::ServiceFuture<GearmanMessagePtr> GearmanServiceFuture;
    typedef boost::intrusive_ptr<GearmanServiceFuture> GearmanServiceFuturePtr;

public:
    GearmanEchoClient(const ChannelPtr& s)
        : count(0),
          service(s) {
        future = new GearmanServiceFuture();
        future->addListener(boost::bind(&GearmanEchoClient::replied,
                                        this,
                                        _1,
                                        _2));
    }

    virtual ~GearmanEchoClient() {}

    void sendRequest() {
        ChannelBufferPtr buf = Unpooled::buffer(10);
        buf->writeBytes("hello");

        callMethod(service,
                   commands::submitJobMessage("echo", "1234", buf),
                   future);
    }

    void replied(const GearmanServiceFuture& f, const GearmanMessagePtr& resp) {
        std::string ret;
        resp->data()->readBytes(&ret);
        LOG_INFO << "the msg is  " << ret;
        ++count;

        if (count < 10000) {
            sendRequest();
        }
    }

private:
    int count;
    ChannelPtr service;
    GearmanServiceFuturePtr future;
};

int main(int argc, char* argv[]) {
    GearmanClientBuilder builder;
    builder.addConnection("192.168.1.108", 4730);

    GearmanClientPtr gearman = builder.build();

    GearmanEchoClient client(gearman->channel());
    client.sendRequest();

    getchar();
    //service->closeFuture()->awaitUninterruptibly();
}


text:
#include <boost/test/unit_test.hpp>

#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/ref.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/random.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

#include <iostream>
#include <fstream>
#include <map>

#include <ir/index_manager/utility/PriorityQueue.h>

using namespace std;
using namespace boost;

boost::mt19937 engine ;
boost::uniform_real<float> distribution(0.0, 1.0);
boost::variate_generator<boost::mt19937&, boost::uniform_real<float> > gen(engine, distribution);

struct ScoreDoc
{
    unsigned int id;
    float score;
};

class ScoreDocQueue: public izenelib::ir::indexmanager::PriorityQueue<ScoreDoc*>{
public:
	ScoreDocQueue(int32_t count)
	{
		initialize(count,false);
	}
protected:
	bool lessThan(ScoreDoc* a, ScoreDoc* b) {
		return (a->score < b->score);
	}
};

BOOST_AUTO_TEST_SUITE( t_priorityqueue )

BOOST_AUTO_TEST_CASE(prorityqueue)
{
    size_t count = 1000;
    ScoreDocQueue queue(count);

    for (size_t i = 0; i < count; i++)
    {
        ScoreDoc* doc = new ScoreDoc;
        doc->id = i;
        doc->score = gen();
        queue.put( doc );
    }
    float last = -1.0F;
    for (size_t j = 0; j < count; j++) {
        ScoreDoc* doc = queue.pop();
        float next = doc->score;
        delete doc;
        BOOST_CHECK(next>=last);
        last = next;
    }

}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: izenecloud/izenelib

max_issues_repo_name: izenecloud/izenelib

max_forks_repo_name: izenecloud/izenelib


text:
#define BOOST_TEST_MODULE fscore

#include <boost/test/unit_test.hpp>
#include "fscore.h"
#include "fsmem.h"
#include "fslog.h"
#include "fsutil.h"

using namespace fs;

class GlobalFixture
{
public:
    GlobalFixture()
    {
    }

    ~GlobalFixture()
    {
    }
};

BOOST_GLOBAL_FIXTURE(GlobalFixture);

max_stars_repo_name: hfarrow/Fissura

max_issues_repo_name: hfarrow/Fissura

max_forks_repo_name: hfarrow/Fissura


text:
/*
   Copyright 2015 Kai Huebl (kai@huebl-sgh.de)

   Lizenziert gemäß Apache Licence Version 2.0 (die „Lizenz“); Nutzung dieser
   Datei nur in Übereinstimmung mit der Lizenz erlaubt.
   Eine Kopie der Lizenz erhalten Sie auf http://www.apache.org/licenses/LICENSE-2.0.

   Sofern nicht gemäß geltendem Recht vorgeschrieben oder schriftlich vereinbart,
   erfolgt die Bereitstellung der im Rahmen der Lizenz verbreiteten Software OHNE
   GEWÄHR ODER VORBEHALTE – ganz gleich, ob ausdrücklich oder stillschweigend.

   Informationen über die jeweiligen Bedingungen für Genehmigungen und Einschränkungen
   im Rahmen der Lizenz finden Sie in der Lizenz.

   Autor: Kai Huebl (kai@huebl-sgh.de)
 */

#include "OpcUaStackCore/BuildInTypes/Json.h"
#include <boost/property_tree/json_parser.hpp>

namespace OpcUaStackCore
{

	bool
	Json::toDocumentString(boost::property_tree::ptree& pt, std::string& string)
	{
		std::stringstream ss;

		boost::property_tree::ptree document;
		document.add_child("Document", pt);
		boost::property_tree::json_parser::write_json(ss, document);
		string = ss.str();
		return true;
	}

	bool
	Json::toString(boost::property_tree::ptree& pt, std::string& string)
	{
		std::stringstream ss;

		//boost::property_tree::ptree document;
		//document.add_child("Document", pt);
		boost::property_tree::json_parser::write_json(ss, pt);
		string = ss.str();
		return true;
	}

	bool
	Json::fromString(const std::string& string, boost::property_tree::ptree& pt)
	{
		std::stringstream ss;
		ss.str(string);

		try {
			boost::property_tree::json_parser::read_json(ss, pt);
		}
		catch (...)
		{
			return false;
		}

		return true;
	}

	bool
	Json::encode(boost::property_tree::ptree& pt, const OpcUaBoolean& value)
	{
		if (value) pt.put_value<bool>(true);
		else pt.put_value(false);
		return true;
	}

	bool
	Json::decode(boost::property_tree::ptree& pt, OpcUaBoolean& value)
	{
		value = pt.get_value<bool>();
		return true;
	}

	bool
	Json::encode(boost::property_tree::ptree& pt, const OpcUaSByte& value)
	{
		pt.put_value<int8_t>(value);
		return true;
	}

	bool
	Json::decode(boost::property_tree::ptree& pt, OpcUaSByte& value)
	{
		value = pt.get_value<int8_t>();
		return true;
	}

	bool
	Json::encode(boost::property_tree::ptree& pt, const OpcUaByte& value)
	{
		pt.put_value<uint8_t>(value);
		return true;
	}

	bool
	Json::decode(boost::property_tree::ptree& pt, OpcUaByte& value)
	{
		value = pt.get_value<uint8_t>();
		return true;
	}

	bool
	Json::encode(boost::property_tree::ptree& pt, const OpcUaInt16& value)
	{
		pt.put_value<int16_t>(value);
		return true;
	}

	bool
	Json::decode(boost::property_tree::ptree& pt, OpcUaInt16& value)
	{
		value = pt.get_value<int16_t>();
		return true;
	}

	bool
	Json::encode(boost::property_tree::ptree& pt, const OpcUaUInt16& value)
	{
		pt.put_value<uint16_t>(value);
		return true;
	}

	bool
	Json::decode(boost::property_tree::ptree& pt, OpcUaUInt16& value)
	{
		value = pt.get_value<uint16_t>();
		return true;
	}

	bool
	Json::encode(boost::property_tree::ptree& pt, const OpcUaInt32& value)
	{
		pt.put_value<int32_t>(value);
		return true;
	}

	bool
	Json::decode(boost::property_tree::ptree& pt, OpcUaInt32& value)
	{
		value = pt.get_value<int32_t>();
		return true;
	}

	bool
	Json::encode(boost::property_tree::ptree& pt, const OpcUaUInt32& value)
	{
		pt.put_value<uint32_t>(value);
		return true;
	}

	bool
	Json::decode(boost::property_tree::ptree& pt, OpcUaUInt32& value)
	{
		value = pt.get_value<uint32_t>();
		return true;
	}

	bool
	Json::encode(boost::property_tree::ptree& pt, const OpcUaInt64& value)
	{
		pt.put_value<int64_t>(value);
		return true;
	}

	bool
	Json::decode(boost::property_tree::ptree& pt, OpcUaInt64& value)
	{
		value = pt.get_value<int64_t>();
		return true;
	}

	bool
	Json::encode(boost::property_tree::ptree& pt, const OpcUaUInt64& value)
	{
		pt.put_value<uint64_t>(value);
		return true;
	}

	bool
	Json::decode(boost::property_tree::ptree& pt, OpcUaUInt64& value)
	{
		value = pt.get_value<uint64_t>();
		return true;
	}

	bool
	Json::encode(boost::property_tree::ptree& pt, const OpcUaFloat& value)
	{
		pt.put_value<float>(value);
		return true;
	}

	bool
	Json::decode(boost::property_tree::ptree& pt, OpcUaFloat& value)
	{
		value = pt.get_value<float>();
		return true;
	}

	bool
	Json::encode(boost::property_tree::ptree& pt, const OpcUaDouble& value)
	{
		pt.put_value<double>(value);
		return true;
	}

	bool
	Json::decode(boost::property_tree::ptree& pt, OpcUaDouble& value)
	{
		value = pt.get_value<double>();
		return true;
	}

}

max_stars_repo_name: gianricardo/OpcUaStack

max_issues_repo_name: gianricardo/OpcUaStack

max_forks_repo_name: gianricardo/OpcUaStack


text:
#include "sample_models.hpp"

#include "model_distribution.hpp"
#include "types.hpp"
#include "utils.hpp"

#include <algorithm>
#include <boost/log/trivial.hpp>
#include <random>
#include <unordered_map>
#include <utility>
#include <vector>

namespace FilterModel {

ModelSampler::ModelSampler(const std::vector<category_counts_t> &data,
                           std::default_random_engine &generator, const Options &options)
    : model_distribution(data, generator, options),
      generator(generator),
      alphas(ModelSampler::generate_alphas(data.at(0).size(), options)),
      n_objects(data.size()),
      n_categories(data.at(0).size()){};

std::vector<alpha_t> ModelSampler::sample(double epsilon, const delta_t &delta) {
    std::vector<double> priors(alphas.size(), 1.0 / alphas.size());

    std::vector<std::vector<double>> log_alpha_likelyhoods =
        model_distribution.distribution(alphas, epsilon, delta);

    std::vector<alpha_t> models;
    for (int object_index = 0; object_index < n_objects; ++object_index) {
        std::vector<double> alpha_weights(alphas.size(), 0.0);
        double total_weight = 0.0;
        for (int i = 0; i < alphas.size(); ++i) {
            alpha_weights.at(i) = log_alpha_likelyhoods.at(object_index).at(i);
            // check that log_alpha_likelyhoods is sane.
            // shouldn't be uniform.
            total_weight += std::exp(alpha_weights.at(i));
        }

        for (int i = 0; i < alphas.size(); ++i) {
            alpha_weights.at(i) -= std::log(total_weight);
        }

        std::vector<double> probabilities = exp(alpha_weights);

        assert_probability(probabilities);
        // look at probabilities

        // Select an alpha at random for the current object.
        std::uniform_real_distribution<double> distribution(0.0, 1.0);
        double random = distribution(generator);
        double probability_sum = 0.0;
        int i = 0;
        while (probability_sum < random) {
            probability_sum += probabilities.at(i);
            ++i;
        }
        models.push_back(alphas.at(i - 1));
    }
    return models;
};

std::vector<alpha_t> ModelSampler::generate_alphas(int n_categories, const Options &options) {
    if (options.use_smaller_alphas) {
        return generate_real_alphas();
    } else {
        return generate_all_alphas(n_categories);
    }
}

std::vector<alpha_t> ModelSampler::generate_all_alphas(int n_categories) {
    alpha_t current = std::vector<category_t>(n_categories, 0);
    std::vector<alpha_t> alphas;
    alpha_t end = std::vector<category_t>(n_categories, 1);
    while (current != end) {
        current = alpha_t(current);
        int i = 0;
        while (current.at(i) == 1) {
            current.at(i) = 0;
            ++i;
        }
        current.at(i) = 1;
        alphas.push_back(current);
    }
    return alphas;
}

std::vector<alpha_t> ModelSampler::generate_real_alphas() {
    return {{0, 0, 1}, {0, 1, 0}, {1, 1, 1}, {1, 0, 1}};
}
}  // namespace FilterModel

max_stars_repo_name: skinnersBoxy/input-filter

max_issues_repo_name: skinnersBoxy/input-filter

max_forks_repo_name: skinnersBoxy/input-filter


text:
#include <cmath>
#include <limits>
#include <memory>

#include <Eigen/Dense>
#include <boost/filesystem.hpp>

#include "catch.hpp"
// MPI
#ifdef USE_MPI
#include "mpi.h"
#endif

#include "constraints.h"
#include "element.h"
#include "function_base.h"
#include "hexahedron_element.h"
#include "linear_function.h"
#include "mesh.h"
#include "node.h"
#include "partio_writer.h"
#include "quadrilateral_element.h"

//! Check mesh class for 2D case
TEST_CASE("Mesh is checked for 2D case", "[mesh][2D]") {
  // Dimension
  const unsigned Dim = 2;
  // Degrees of freedom
  const unsigned Dof = 2;
  // Number of phases
  const unsigned Nphases = 1;
  // Number of nodes per cell
  const unsigned Nnodes = 4;
  // Tolerance
  const double Tolerance = 1.E-9;
  // Json property
  Json jfunctionproperties;
  jfunctionproperties["id"] = 0;
  std::vector<double> x_values{{0.0, 0.5, 1.0}};
  std::vector<double> fx_values{{0.0, 1.0, 1.0}};
  jfunctionproperties["xvalues"] = x_values;
  jfunctionproperties["fxvalues"] = fx_values;

  // math function
  std::shared_ptr<mpm::FunctionBase> mfunction =
      std::make_shared<mpm::LinearFunction>(0, jfunctionproperties);

  // 4-noded quadrilateral element
  std::shared_ptr<mpm::Element<Dim>> element =
      Factory<mpm::Element<Dim>>::instance()->create("ED2Q4");

  // Assign material
  unsigned mid = 0;
  std::vector<unsigned> mids(1, mid);
  // Initialise material
  Json jmaterial;
  jmaterial["density"] = 1000.;
  jmaterial["youngs_modulus"] = 1.0E+7;
  jmaterial["poisson_ratio"] = 0.3;

  auto le_material =
      Factory<mpm::Material<Dim>, unsigned, const Json&>::instance()->create(
          "LinearElastic2D", std::move(0), jmaterial);

  std::map<unsigned, std::shared_ptr<mpm::Material<Dim>>> materials;
  materials[mid] = le_material;

  //! Check Mesh IDs
  SECTION("Check mesh ids") {
    //! Check for id = 0
    SECTION("Mesh id is zero") {
      unsigned id = 0;
      auto mesh = std::make_shared<mpm::Mesh<Dim>>(id);
      REQUIRE(mesh->id() == 0);
      REQUIRE(mesh->is_isoparametric() == true);
    }

    SECTION("Mesh id is zero and cartesian") {
      unsigned id = 0;
      auto mesh = std::make_shared<mpm::Mesh<Dim>>(id, false);
      REQUIRE(mesh->id() == 0);
      REQUIRE(mesh->is_isoparametric() == false);
    }

    SECTION("Mesh id is positive") {
      //! Check for id is a positive value
      unsigned id = std::numeric_limits<unsigned>::max();
      auto mesh = std::make_shared<mpm::Mesh<Dim>>(id);
      REQUIRE(mesh->id() == std::numeric_limits<unsigned>::max());
    }
  }

  SECTION("Add neighbours") {
    auto mesh = std::make_shared<mpm::Mesh<Dim>>(0);
    auto neighbourmesh = std::make_shared<mpm::Mesh<Dim>>(1);
    REQUIRE(mesh->nneighbours() == 0);
    mesh->add_neighbour(0, neighbourmesh);
    REQUIRE(mesh->nneighbours() == 1);
  }

  // Check add / remove particle
  SECTION("Check add / remove particle functionality") {
    // Particle 1
    mpm::Index id1 = 0;
    Eigen::Vector2d coords;
    coords.setZero();
    std::shared_ptr<mpm::ParticleBase<Dim>> particle1 =
        std::make_shared<mpm::Particle<Dim>>(id1, coords);

    // Particle 2
    mpm::Index id2 = 1;
    coords << 2., 2.;
    std::shared_ptr<mpm::ParticleBase<Dim>> particle2 =
        std::make_shared<mpm::Particle<Dim>>(id2, coords);

    auto mesh = std::make_shared<mpm::Mesh<Dim>>(0);
    // Check mesh is active
    REQUIRE(mesh->status() == false);

    // Check nodal coordinates size
    REQUIRE(mesh->nodal_coordinates().size() == 0);
    // Check node pairs size
    REQUIRE(mesh->node_pairs().size() == 0);

    // Define nodes
    coords << 0., 0.;
    std::shared_ptr<mpm::NodeBase<Dim>> node0 =
        std::make_shared<mpm::Node<Dim, Dof, Nphases>>(0, coords);

    // Add node 0 and check
    REQUIRE(mesh->add_node(node0) == true);

    coords << 2., 0.;
    std::shared_ptr<mpm::NodeBase<Dim>> node1 =
        std::make_shared<mpm::Node<Dim, Dof, Nphases>>(1, coords);

    // Add node 1 and check
    REQUIRE(mesh->add_node(node1) == true);

    coords << 2., 2.;
    std::shared_ptr<mpm::NodeBase<Dim>> node2 =
        std::make_shared<mpm::Node<Dim, Dof, Nphases>>(2, coords);

    // Add node 2 and check
    REQUIRE(mesh->add_node(node2) == true);

    coords << 0., 2.;
    std::shared_ptr<mpm::NodeBase<Dim>> node3 =
        std::make_shared<mpm::Node<Dim, Dof, Nphases>>(3, coords);

    // Add node 3 and check
    REQUIRE(mesh->add_node(node3) == true);

    // Create cell1
    coords.setZero();
    auto cell1 = std::make_shared<mpm::Cell<Dim>>(id1, Nnodes, element);

    // Add nodes to cell
    cell1->add_node(0, node0);
    cell1->add_node(1, node1);
    cell1->add_node(2, node2);
    cell1->add_node(3, node3);

    int mpi_size;
    MPI_Comm_size(MPI_COMM_WORLD, &mpi_size);
    if (mpi_size == 1) cell1->rank(1);

    // Initialize cell
    REQUIRE(cell1->initialise() == true);

    // Add cell 1 and check
    REQUIRE(mesh->add_cell(cell1) == true);

    // Check nodal coordinates size
    REQUIRE(mesh->nodal_coordinates().size() == 4);
    // Check node pairs size
    REQUIRE(mesh->node_pairs().size() == 4);

    // Add particle 1 and check
    REQUIRE(mesh->add_particle(particle1) == true);
    // Add particle 2 and check
    REQUIRE(mesh->add_particle(particle2) == true);
    // Add particle 2 again and check
    REQUIRE(mesh->add_particle(particle2) == false);

    // Check mesh is active
    REQUIRE(mesh->status() == true);
    // Check number of particles in mesh
    REQUIRE(mesh->nparticles() == 2);

    // Update coordinates
    Eigen::Vector2d coordinates;
    coordinates << 1., 1.;
    // Check iterate over functionality
    mesh->iterate_over_particles(
        std::bind(&mpm::ParticleBase<Dim>::assign_coordinates,
                  std::placeholders::_1, coordinates));

    // Particle 1
    {
      // Check if nodal coordinate update has gone through
      auto check_coords = particle1->coordinates();
      // Check if coordinates for each particle is zero
      for (unsigned i = 0; i < check_coords.size(); ++i)
        REQUIRE(check_coords[i] == Approx(1.).epsilon(Tolerance));
    }
    // Particle 2
    {
      // Check if nodal coordinate update has gone through
      auto check_coords = particle2->coordinates();
      // Check if coordinates for each particle is zero
      for (unsigned i = 0; i < check_coords.size(); ++i)
        REQUIRE(check_coords[i] == Approx(1.).epsilon(Tolerance));
    }

    // Remove particle 2 and check
    REQUIRE(mesh->remove_particle(particle2) == true);
    // Check number of particles in mesh
    REQUIRE(mesh->nparticles() == 1);

    // Remove all non-rank particles in mesh
    mesh->remove_all_nonrank_particles();
    // Check number of particles in mesh
    REQUIRE(mesh->nparticles() == 0);

    // Add and use remove all particles
    REQUIRE(mesh->add_particle(particle1) == true);
    REQUIRE(mesh->add_particle(particle2) == true);

    // Check number of particles in mesh
    REQUIRE(mesh->nparticles() == 2);
    std::vector<mpm::Index> remove_pids = {{0, 1}};
    // Remove all particles
    mesh->remove_particles(remove_pids);
    // Check number of particles in mesh
    REQUIRE(mesh->nparticles() == 0);

    // Test assign node concentrated force
    SECTION("Check assign node concentrated force") {
      unsigned Nphase = 0;
      // Set external force to zero
      Eigen::Matrix<double, Dim, 1> force;
      force.setZero();
      REQUIRE_NOTHROW(node0->update_external_force(false, Nphase, force));
      REQUIRE_NOTHROW(node1->update_external_force(false, Nphase, force));

      const unsigned Direction = 0;
      // Check external force
      for (unsigned i = 0; i < Dim; ++i) {
        REQUIRE(node0->external_force(Nphase)(i) ==
                Approx(0.).epsilon(Tolerance));
        REQUIRE(node1->external_force(Nphase)(i) ==
                Approx(0.).epsilon(Tolerance));
      }

      tsl::robin_map<mpm::Index, std::vector<mpm::Index>> node_sets;
      node_sets[0] = std::vector<mpm::Index>{0, 1};

      REQUIRE(mesh->create_node_sets(node_sets, true) == true);

      REQUIRE(mesh->assign_nodal_concentrated_forces(mfunction, 0, 0, 10.5) ==
              true);
      REQUIRE(mesh->assign_nodal_concentrated_forces(mfunction, -1, 0, 0.5) ==
              true);
      REQUIRE(mesh->assign_nodal_concentrated_forces(mfunction, 5, 0, 0.5) ==
              false);
      REQUIRE(mesh->assign_nodal_concentrated_forces(mfunction, -5, 1, 0.5) ==
              false);

      double current_time = 0.0;
      node0->apply_concentrated_force(Nphase, current_time);
      node1->apply_concentrated_force(Nphase, current_time);
      // Check external force
      for (unsigned i = 0; i < Dim; ++i) {
        REQUIRE(node0->external_force(Nphase)(i) ==
                Approx(0.).epsilon(Tolerance));
        REQUIRE(node1->external_force(Nphase)(i) ==
                Approx(0.).epsilon(Tolerance));
      }

      current_time = 0.25;
      node0->apply_concentrated_force(Nphase, current_time);
      node1->apply_concentrated_force(Nphase, current_time);
      std::vector<double> ext_forces = {0.25, 0., 0.};
      // Check external force
      for (unsigned i = 0; i < Dim; ++i) {
        REQUIRE(node0->external_force(Nphase)(i) ==
                Approx(ext_forces.at(i)).epsilon(Tolerance));
        REQUIRE(node1->external_force(Nphase)(i) ==
                Approx(ext_forces.at(i)).epsilon(Tolerance));
      }

      current_time = 5.0;
      node0->apply_concentrated_force(Nphase, current_time);
      node1->apply_concentrated_force(Nphase, current_time);
      ext_forces = {0.75, 0., 0.};
      // Check external force
      for (unsigned i = 0; i < Dim; ++i) {
        REQUIRE(node0->external_force(Nphase)(i) ==
                Approx(ext_forces.at(i)).epsilon(Tolerance));
        REQUIRE(node1->external_force(Nphase)(i) ==
                Approx(ext_forces.at(i)).epsilon(Tolerance));
      }
    }
  }

  // Check add / remove node
  SECTION("Check add / remove node functionality") {
    // Node 1
    mpm::Index id1 = 0;
    Eigen::Vector2d coords;
    coords.setZero();
    std::shared_ptr<mpm::NodeBase<Dim>> node1 =
        std::make_shared<mpm::Node<Dim, Dof, Nphases>>(id1, coords);

    // Node 2
    mpm::Index id2 = 1;
    std::shared_ptr<mpm::NodeBase<Dim>> node2 =
        std::make_shared<mpm::Node<Dim, Dof, Nphases>>(id2, coords);

    // Create a mesh
    auto mesh = std::make_shared<mpm::Mesh<Dim>>(0);
    // Check mesh is active
    REQUIRE(mesh->status() == false);

    // Check nodal coordinates size
    REQUIRE(mesh->nodal_coordinates().size() == 0);
    // Check node pairs size
    REQUIRE(mesh->node_pairs().size() == 0);

    // Add node 1 and check
    REQUIRE(mesh->add_node(node1) == true);
    // Add node 2 and check
    REQUIRE(mesh->add_node(node2) == true);
    // Add node 2 again and check
    REQUIRE(mesh->add_node(node2) == false);

    // Check number of nodes in mesh
    REQUIRE(mesh->nnodes() == 2);

    // Check nodal coordinates size
    REQUIRE(mesh->nodal_coordinates().size() == 2);

    // Update coordinates
    Eigen::Vector2d coordinates;
    coordinates << 1., 1.;

    // Set only node2 to be active
    node2->assign_status(true);

    // Check iterate over functionality if nodes are active
    mesh->iterate_over_nodes_predicate(
        std::bind(&mpm::NodeBase<Dim>::assign_coordinates,
                  std::placeholders::_1, coordinates),
        std::bind(&mpm::NodeBase<Dim>::status, std::placeholders::_1));

    // Node 1
    {
      // Check if nodal coordinate update has gone through
      auto check_coords = node1->coordinates();
      // Check if coordinates for each node is zero
      for (unsigned i = 0; i < check_coords.size(); ++i)
        REQUIRE(check_coords[i] == Approx(0.).epsilon(Tolerance));
    }
    // Node 2
    {
      // Check if nodal coordinate update has gone through
      auto check_coords = node2->coordinates();
      // Check if coordinates for each node is zero
      for (unsigned i = 0; i < check_coords.size(); ++i)
        REQUIRE(check_coords[i] == Approx(1.).epsilon(Tolerance));
    }

    coordinates.setZero();
    node1->assign_coordinates(coordinates);
    node2->assign_coordinates(coordinates);
    for (unsigned i = 0; i < coordinates.size(); ++i) {
      REQUIRE(node1->coordinates()[i] == Approx(0.).epsilon(Tolerance));
      REQUIRE(node2->coordinates()[i] == Approx(0.).epsilon(Tolerance));
    }

    REQUIRE(node1->status() == false);
    REQUIRE(node2->status() == true);

    mesh->find_active_nodes();

    // Check iterate over functionality if nodes are active
    coordinates.fill(5.3);

    mesh->iterate_over_active_nodes(
        std::bind(&mpm::NodeBase<Dim>::assign_coordinates,
                  std::placeholders::_1, coordinates));

    // Node 1
    {
      // Check if nodal coordinate update has gone through
      auto check_coords = node1->coordinates();
      for (unsigned i = 0; i < check_coords.size(); ++i)
        REQUIRE(check_coords[i] == Approx(0.).epsilon(Tolerance));
    }
    // Node 2
    {
      // Check if nodal coordinate update has gone through
      auto check_coords = node2->coordinates();
      for (unsigned i = 0; i < check_coords.size(); ++i)
        REQUIRE(check_coords[i] == Approx(5.3).epsilon(Tolerance));
    }

    coordinates.fill(1.0);
    // Check iterate over functionality
    mesh->iterate_over_nodes(std::bind(&mpm::NodeBase<Dim>::assign_coordinates,
                                       std::placeholders::_1, coordinates));

    // Node 1
    {
      // Check if nodal coordinate update has gone through
      auto check_coords = node1->coordinates();
      // Check if coordinates for each node is zero
      for (unsigned i = 0; i < check_coords.size(); ++i)
        REQUIRE(check_coords[i] == Approx(1.).epsilon(Tolerance));
    }
    // Node 2
    {
      // Check if nodal coordinate update has gone through
      auto check_coords = node2->coordinates();
      // Check if coordinates for each node is zero
      for (unsigned i = 0; i < check_coords.size(); ++i)
        REQUIRE(check_coords[i] == Approx(1.).epsilon(Tolerance));
    }

    // Remove node 2 and check
    REQUIRE(mesh->remove_node(node2) == true);
    // Check number of nodes in mesh
    REQUIRE(mesh->nnodes() == 1);
  }

  // Check add / remove cell
  SECTION("Check add / remove cell functionality") {

    // Cell 1
    mpm::Index id1 = 0;
    Eigen::Vector2d coords;
    coords.setZero();
    auto cell1 = std::make_shared<mpm::Cell<Dim>>(id1, Nnodes, element);

    // Cell 2
    mpm::Index id2 = 1;
    auto cell2 = std::make_shared<mpm::Cell<Dim>>(id2, Nnodes, element);

    auto mesh = std::make_shared<mpm::Mesh<Dim>>(0);
    // Check mesh is active
    REQUIRE(mesh->status() == false);

    // Add cell 1 and check
    REQUIRE(mesh->add_cell(cell1) == true);
    // Add cell 2 and check
    REQUIRE(mesh->add_cell(cell2) == true);
    // Add cell 2 again and check
    REQUIRE(mesh->add_cell(cell2) == false);

    // Check number of cells in mesh
    REQUIRE(mesh->ncells() == 2);

    // Check iterate over functionality
    mesh->iterate_over_cells(
        std::bind(&mpm::Cell<Dim>::nnodes, std::placeholders::_1));

    // Remove cell 2 and check
    REQUIRE(mesh->remove_cell(cell2) == true);
    // Check number of cells in mesh
    REQUIRE(mesh->ncells() == 1);
  }

  SECTION("Check particle is in cell") {
    // Cell 1
    mpm::Index id1 = 0;
    Eigen::Vector2d coords;
    coords.setZero();

    // Mesh
    auto mesh = std::make_shared<mpm::Mesh<Dim>>(0);
    // Check mesh is inactive (false)
    REQUIRE(mesh->status() == false);

    // Define nodes
    std::shared_ptr<mpm::NodeBase<Dim>> node0 =
        std::make_shared<mpm::Node<Dim, Dof, Nphases>>(0, coords);

    // Add node 0 and check
    REQUIRE(mesh->add_node(node0) == true);

    coords << 2., 0.;
    std::shared_ptr<mpm::NodeBase<Dim>> node1 =
        std::make_shared<mpm::Node<Dim, Dof, Nphases>>(1, coords);

    // Add node 1 and check
    REQUIRE(mesh->add_node(node1) == true);

    coords << 2., 2.;
    std::shared_ptr<mpm::NodeBase<Dim>> node2 =
        std::make_shared<mpm::Node<Dim, Dof, Nphases>>(2, coords);

    // Add node 2 and check
    REQUIRE(mesh->add_node(node2) == true);

    coords << 0., 2.;
    std::shared_ptr<mpm::NodeBase<Dim>> node3 =
        std::make_shared<mpm::Node<Dim, Dof, Nphases>>(3, coords);

    // Add node 3 and check
    REQUIRE(mesh->add_node(node3) == true);

    // Create cell1
    coords.setZero();
    auto cell1 = std::make_shared<mpm::Cell<Dim>>(id1, Nnodes, element);

    // Add nodes to cell
    cell1->add_node(0, node0);
    cell1->add_node(1, node1);
    cell1->add_node(2, node2);
    cell1->add_node(3, node3);

    // Initialize cell
    REQUIRE(cell1->initialise() == true);
    // Particle type 2D
    const std::string particle_type = "P2D";

    // Initialise material models
    mesh->initialise_material_models(materials);

    // Generate material points in cell
    REQUIRE(mesh->nparticles() == 0);

    REQUIRE(mesh->generate_material_points(1, particle_type, mids, -1, 0) ==
            false);
    REQUIRE(mesh->nparticles() == 0);

    // Add cell 1 and check
    REQUIRE(mesh->add_cell(cell1) == true);

    SECTION("Check generating 1 particle / cell") {
      // Generate material points in cell
      REQUIRE(mesh->generate_material_points(1, particle_type, mids, -1, 0) ==
              true);
      REQUIRE(mesh->nparticles() == 1);
    }

    SECTION("Check generating 2 particle / cell") {
      REQUIRE(mesh->generate_material_points(2, particle_type, mids, -1, 0) ==
              true);
      REQUIRE(mesh->nparticles() == 4);
    }

    SECTION("Check generating 3 particle / cell") {
      REQUIRE(mesh->generate_material_points(3, particle_type, mids, -1, 0) ==
              true);
      REQUIRE(mesh->nparticles() == 9);
    }

    SECTION("Check material point generation") {
      // Assign argc and argv to nput arguments of MPM
      int argc = 7;
      char* argv[] = {(char*)"./mpm",   (char*)"-f", (char*)"./",
                      (char*)"-p",      (char*)"8",  (char*)"-i",
                      (char*)"mpm.json"};

      // Create an IO object
      auto io = std::make_shared<mpm::IO>(argc, argv);

      tsl::robin_map<mpm::Index, std::vector<mpm::Index>> cell_sets;
      cell_sets[1] = std::vector<mpm::Index>{0};

      REQUIRE(mesh->create_cell_sets(cell_sets, true) == true);

      REQUIRE(mesh->nparticles() == 0);

      SECTION("Gauss point generation") {
        // Gauss point generation
        Json jgen;
        jgen["type"] = "gauss";
        jgen["material_id"] = {0};
        jgen["cset_id"] = 1;
        jgen["particle_type"] = "P2D";
        jgen["check_duplicates"] = false;
        jgen["nparticles_per_dir"] = 2;
        jgen["pset_id"] = 2;

        // Generate
        REQUIRE(mesh->generate_particles(io, jgen) == true);
        // Number of particles
        REQUIRE(mesh->nparticles() == 4);
      }

      SECTION("Inject points") {
        // Gauss point generation
        Json jgen;
        jgen["type"] = "inject";
        jgen["material_id"] = {0};
        jgen["cset_id"] = 1;
        jgen["particle_type"] = "P2D";
        jgen["check_duplicates"] = false;
        jgen["nparticles_per_dir"] = 2;
        jgen["velocity"] = {0., 0.};
        jgen["duration"] = {0.1, 0.2};

        // Generate
        REQUIRE(mesh->generate_particles(io, jgen) == true);
        // Inject particles
        REQUIRE_NOTHROW(mesh->inject_particles(0.05));
        // Number of particles
        REQUIRE(mesh->nparticles() == 0);
        // Inject particles
        REQUIRE_NOTHROW(mesh->inject_particles(0.25));
        // Number of particles
        REQUIRE(mesh->nparticles() == 0);
        // Inject particles
        REQUIRE_NOTHROW(mesh->inject_particles(0.15));
        // Number of particles
        REQUIRE(mesh->nparticles() == 4);
      }
    }

    // Particle 1
    coords << 1.0, 1.0;
    std::shared_ptr<mpm::ParticleBase<Dim>> particle1 =
        std::make_shared<mpm::Particle<Dim>>(100, coords);

    // Particle 2
    coords << 1.5, 1.5;
    std::shared_ptr<mpm::ParticleBase<Dim>> particle2 =
        std::make_shared<mpm::Particle<Dim>>(101, coords);

    // Add particle 1 and check
    REQUIRE(mesh->add_particle(particle1) == true);
    // Add particle 2 and check
    REQUIRE(mesh->add_particle(particle2) == true);

    // Check mesh is active
    REQUIRE(mesh->status() == true);

    // Locate particles in a mesh
    auto particles = mesh->locate_particles_mesh();

    // Should find all particles in mesh
    REQUIRE(particles.size() == 0);

    // Check location of particle 1
    REQUIRE(particle1->cell_id() == 0);
    // Check location of particle 2
    REQUIRE(particle2->cell_id() == 0);
  }

  //! Check create nodes and cells in a mesh
  SECTION("Check create nodes and cells") {
    // Vector of nodal coordinates
    std::vector<Eigen::Matrix<double, Dim, 1>> coordinates;

    // Nodal coordinates
    Eigen::Matrix<double, Dim, 1> node;

    // Cell 0
    // Node 0
    node << 0., 0.;
    coordinates.emplace_back(node);
    // Node 1
    node << 0.5, 0.;
    coordinates.emplace_back(node);
    // Node 2
    node << 0.5, 0.5;
    coordinates.emplace_back(node);
    // Node 3
    node << 0., 0.5;
    coordinates.emplace_back(node);

    // Cell 1
    // Node 4
    node << 1.0, 0.;
    coordinates.emplace_back(node);
    // Node 5
    node << 1.0, 0.5;
    coordinates.emplace_back(node);

    // Create a new mesh
    unsigned meshid = 0;
    auto mesh = std::make_shared<mpm::Mesh<Dim>>(meshid);

    SECTION("Check creation of nodes") {
      // Node type 2D
      const std::string node_type = "N2D";
      // Global node index
      mpm::Index gnid = 0;
      mesh->create_nodes(gnid, node_type, coordinates, false);
      // Check if mesh has added nodes
      REQUIRE(mesh->nnodes() == coordinates.size());
      // Try again this shouldn't add more coordinates
      mesh->create_nodes(gnid, node_type, coordinates);
      // Check if mesh has added nodes
      REQUIRE(mesh->nnodes() == coordinates.size());
      // Clear coordinates and try creating a list of nodes with an empty list
      unsigned nnodes = coordinates.size();
      coordinates.clear();
      // This fails with empty list error in node creation
      mesh->create_nodes(gnid, node_type, coordinates);
      REQUIRE(mesh->nnodes() == nnodes);

      SECTION("Check creation of cells") {
        // Cell with node ids
        std::vector<std::vector<mpm::Index>> cells{// cell #0
                                                   {0, 1, 2, 3},
                                                   // cell #1
                                                   {1, 4, 5, 2}};
        // Assign 4-noded quadrilateral element to cell
        std::shared_ptr<mpm::Element<Dim>> element =
            Factory<mpm::Element<Dim>>::instance()->create("ED2Q4");

        // Global cell index
        mpm::Index gcid = 0;
        mesh->create_cells(gcid, element, cells, false);
        // Check if mesh has added cells
        REQUIRE(mesh->ncells() == cells.size());
        // Try again this shouldn't add more cells
        mesh->create_cells(gcid, element, cells);
        // Check if mesh has added cells
        REQUIRE(mesh->ncells() == cells.size());
        // Clear cells and try creating a list of empty cells
        unsigned ncells = cells.size();
        cells.clear();
        // This fails with empty list error in node creation
        gcid = 10;
        mesh->create_cells(gcid, element, cells);
        REQUIRE(mesh->ncells() == ncells);

        // Try with invalid node ids
        cells = {// cell #0
                 {10, 11, 12, 13},
                 // cell #1
                 {11, 14, 15, 12}};
        gcid = 20;
        mesh->create_cells(gcid, element, cells);
        REQUIRE(mesh->ncells() == ncells);

        SECTION("Check creation of particles") {
          // Vector of particle coordinates
          std::vector<Eigen::Matrix<double, Dim, 1>> coordinates;
          coordinates.clear();

          // Particle coordinates
          Eigen::Matrix<double, Dim, 1> particle;

          // Cell 0
          // Particle 0
          particle << 0.125, 0.125;
          coordinates.emplace_back(particle);
          // Particle 1
          particle << 0.25, 0.125;
          coordinates.emplace_back(particle);
          // Particle 2
          particle << 0.25, 0.25;
          coordinates.emplace_back(particle);
          // Particle 3
          particle << 0.125, 0.25;
          coordinates.emplace_back(particle);

          // Cell 1
          // Particle 4
          particle << 0.675, 0.125;
          coordinates.emplace_back(particle);
          // Particle 5
          particle << 0.85, 0.125;
          coordinates.emplace_back(particle);
          // Particle 6
          particle << 0.85, 0.25;
          coordinates.emplace_back(particle);
          // Particle 7
          particle << 0.675, 0.25;
          coordinates.emplace_back(particle);

          // Initialise material models in mesh
          mesh->initialise_material_models(materials);

          SECTION("Check addition of particles to mesh") {
            // Particle type 2D
            const std::string particle_type = "P2D";
            // Create particles from file
            mesh->create_particles(particle_type, coordinates, mids, 0, false);
            // Check if mesh has added particles
            REQUIRE(mesh->nparticles() == coordinates.size());

            // Test assign particles cells
            SECTION("Check assign particles cells") {
              // Vector of particle cells
              std::vector<std::array<mpm::Index, 2>> particles_cells;
              // Particle cells
              particles_cells.emplace_back(std::array<mpm::Index, 2>({0, 0}));
              particles_cells.emplace_back(std::array<mpm::Index, 2>({1, 0}));
              particles_cells.emplace_back(std::array<mpm::Index, 2>({2, 0}));
              particles_cells.emplace_back(std::array<mpm::Index, 2>({3, 0}));

              particles_cells.emplace_back(std::array<mpm::Index, 2>({4, 1}));
              particles_cells.emplace_back(std::array<mpm::Index, 2>({5, 1}));
              particles_cells.emplace_back(std::array<mpm::Index, 2>({6, 1}));
              particles_cells.emplace_back(std::array<mpm::Index, 2>({7, 1}));

              REQUIRE(mesh->assign_particles_cells(particles_cells) == true);

              // Locate particles
              auto missing_particles = mesh->locate_particles_mesh();
              REQUIRE(missing_particles.size() == 0);

              auto check_particles_cells = mesh->particles_cells();

              REQUIRE(check_particles_cells.size() == mesh->nparticles());

              for (unsigned i = 0; i < particles_cells.size(); ++i)
                for (unsigned j = 0; j < 2; ++j)
                  REQUIRE(check_particles_cells.at(i).at(j) ==
                          particles_cells.at(i).at(j));
            }

            // Locate particles
            auto missing_particles = mesh->locate_particles_mesh();
            REQUIRE(missing_particles.size() == 0);

            // Test assign particles cells again should fail
            SECTION("Check assign particles cells") {
              // Vector of particle cells
              std::vector<std::array<mpm::Index, 2>> particles_cells;
              // Particle cells
              particles_cells.emplace_back(std::array<mpm::Index, 2>({0, 0}));
              particles_cells.emplace_back(std::array<mpm::Index, 2>({1, 0}));
              particles_cells.emplace_back(std::array<mpm::Index, 2>({2, 0}));
              particles_cells.emplace_back(std::array<mpm::Index, 2>(
                  {3, std::numeric_limits<mpm::Index>::max()}));
              particles_cells.emplace_back(std::array<mpm::Index, 2>({50, 0}));

              REQUIRE(mesh->assign_particles_cells(particles_cells) == false);
            }

            // Clear coordinates and try creating a list of particles with
            // an empty list
            unsigned nparticles = coordinates.size();
            coordinates.clear();
            // This fails with empty list error in particle creation
            mesh->create_particles(particle_type, coordinates, mids, 0, false);
            REQUIRE(mesh->nparticles() == nparticles);

            const unsigned phase = 0;
            // Particles coordinates
            REQUIRE(mesh->particle_coordinates().size() == mesh->nparticles());
            // Particle stresses
            std::string attribute = "stresses";
            REQUIRE(mesh->template particles_tensor_data<6>(attribute).size() ==
                    mesh->nparticles());
            // Particle strains
            attribute = "strains";
            REQUIRE(mesh->template particles_tensor_data<6>(attribute).size() ==
                    mesh->nparticles());
            // Particle velocities
            attribute = "velocities";
            REQUIRE(mesh->template particles_tensor_data<3>(attribute).size() ==
                    mesh->nparticles());
            // Particle invalid data
            attribute = "invalid";
            REQUIRE(mesh->template particles_tensor_data<3>(attribute).size() ==
                    0);

            // State variable
            attribute = "pdstrain";
            REQUIRE(mesh->particles_statevars_data(attribute).size() ==
                    mesh->nparticles());

            // Locate particles in mesh
            SECTION("Locate particles in mesh") {
              // Locate particles in a mesh
              auto particles = mesh->locate_particles_mesh();

              // Should find all particles in mesh
              REQUIRE(particles.size() == 0);

              // Create particle 100
              Eigen::Vector2d coords;
              coords << 100., 100.;

              mpm::Index pid = 100;
              std::shared_ptr<mpm::ParticleBase<Dim>> particle100 =
                  std::make_shared<mpm::Particle<Dim>>(pid, coords);

              // Add particle100 and check
              REQUIRE(mesh->add_particle(particle100) == false);

              // Locate particles in a mesh
              particles = mesh->locate_particles_mesh();
              // Should miss particle100
              REQUIRE(particles.size() == 0);
            }

            // Test HDF5
            SECTION("Write particles HDF5") {
              REQUIRE(mesh->write_particles_hdf5(0, "particles-2d.h5") == true);

              auto phdf5 = mesh->particles_hdf5();
              REQUIRE(phdf5.size() == mesh->nparticles());

#ifdef USE_PARTIO
              REQUIRE_NOTHROW(mpm::partio::write_particles(
                  "partio-2d.bgeo", mesh->particles_hdf5()));
              // Check if .bgeo exists
              REQUIRE(boost::filesystem::exists("./partio-2d.bgeo") == true);
#endif
            }

            // Test assign particles volumes
            SECTION("Check assign particles volumes") {
              // Vector of particle coordinates
              std::vector<std::tuple<mpm::Index, double>> particles_volumes;
              // Volumes
              particles_volumes.emplace_back(std::make_tuple(0, 10.5));
              particles_volumes.emplace_back(std::make_tuple(1, 10.5));

              REQUIRE(mesh->nparticles() == 8);

              REQUIRE(mesh->assign_particles_volumes(particles_volumes) ==
                      true);

              // When volume assignment fails
              particles_volumes.emplace_back(std::make_tuple(2, 0.0));
              particles_volumes.emplace_back(std::make_tuple(3, -10.0));

              REQUIRE(mesh->assign_particles_volumes(particles_volumes) ==
                      false);
            }

            // Test assign particles tractions
            SECTION("Check assign particles tractions") {
              tsl::robin_map<mpm::Index, std::vector<mpm::Index>> particle_sets;
              particle_sets[0] = std::vector<mpm::Index>{0};
              particle_sets[1] = std::vector<mpm::Index>{1};
              particle_sets[2] = std::vector<mpm::Index>{2};
              particle_sets[3] = std::vector<mpm::Index>{3};

              REQUIRE(mesh->create_particle_sets(particle_sets, true) == true);

              REQUIRE(mesh->nparticles() == 8);

              REQUIRE(mesh->create_particles_tractions(mfunction, 0, 0, 10.5) ==
                      true);
              REQUIRE(mesh->create_particles_tractions(mfunction, 1, 1,
                                                       -10.5) == true);
              REQUIRE(mesh->create_particles_tractions(mfunction, 2, 0,
                                                       -12.5) == true);
              REQUIRE(mesh->create_particles_tractions(mfunction, 3, 1, 0.5) ==
                      true);

              REQUIRE(mesh->create_particles_tractions(mfunction, -1, 1, 0.5) ==
                      true);
              REQUIRE(mesh->create_particles_tractions(mfunction, 5, 0, 0.5) ==
                      false);
              REQUIRE(mesh->create_particles_tractions(mfunction, -5, 1, 0.5) ==
                      false);

              // Locate particles in a mesh
              auto particles = mesh->locate_particles_mesh();
              REQUIRE(particles.size() == 0);
              mesh->iterate_over_particles(
                  std::bind(&mpm::ParticleBase<Dim>::compute_shapefn,
                            std::placeholders::_1));

              // Compute volume
              mesh->iterate_over_particles(
                  std::bind(&mpm::ParticleBase<Dim>::compute_volume,
                            std::placeholders::_1));

              mesh->apply_traction_on_particles(10);
            }

            // Test assign particles stresses
            SECTION("Check assign particles stresses") {
              // Vector of particle stresses
              std::vector<Eigen::Matrix<double, 6, 1>> particles_stresses;

              REQUIRE(mesh->nparticles() == 8);

              // Stresses
              particles_stresses.emplace_back(
                  Eigen::Matrix<double, 6, 1>::Constant(0.0));
              particles_stresses.emplace_back(
                  Eigen::Matrix<double, 6, 1>::Constant(0.1));
              particles_stresses.emplace_back(
                  Eigen::Matrix<double, 6, 1>::Constant(-0.2));
              particles_stresses.emplace_back(
                  Eigen::Matrix<double, 6, 1>::Constant(0.3));
              particles_stresses.emplace_back(
                  Eigen::Matrix<double, 6, 1>::Constant(-0.4));
              particles_stresses.emplace_back(
                  Eigen::Matrix<double, 6, 1>::Constant(0.5));
              particles_stresses.emplace_back(
                  Eigen::Matrix<double, 6, 1>::Constant(-0.6));
              particles_stresses.emplace_back(
                  Eigen::Matrix<double, 6, 1>::Constant(-0.7));

              REQUIRE(mesh->assign_particles_stresses(particles_stresses) ==
                      true);
              // When stresses fail
              particles_stresses.emplace_back(
                  Eigen::Matrix<double, 6, 1>::Constant(0.8));
              REQUIRE(mesh->assign_particles_stresses(particles_stresses) ==
                      false);
              unsigned id = 1;
              auto mesh_fail = std::make_shared<mpm::Mesh<Dim>>(id);
              REQUIRE(mesh_fail->assign_particles_stresses(
                          particles_stresses) == false);
            }

            // Test assign particles velocity constraints
            SECTION("Check assign particles velocity constraints") {
              tsl::robin_map<mpm::Index, std::vector<mpm::Index>> particle_sets;
              particle_sets[0] = std::vector<mpm::Index>{0};
              particle_sets[1] = std::vector<mpm::Index>{1};
              particle_sets[2] = std::vector<mpm::Index>{2};
              particle_sets[3] = std::vector<mpm::Index>{3};

              REQUIRE(mesh->create_particle_sets(particle_sets, true) == true);

              REQUIRE(mesh->nparticles() == 8);

              int set_id = 0;
              int dir = 0;
              double constraint = 10.5;
              // Add velocity constraint to mesh
              auto velocity_constraint =
                  std::make_shared<mpm::VelocityConstraint>(set_id, dir,
                                                            constraint);
              REQUIRE(mesh->create_particle_velocity_constraint(
                          set_id, velocity_constraint) == true);

              // Add velocity constraint to all nodes in mesh
              velocity_constraint = std::make_shared<mpm::VelocityConstraint>(
                  -1, dir, constraint);
              REQUIRE(mesh->create_particle_velocity_constraint(
                          set_id, velocity_constraint) == true);

              // When constraints fail
              dir = 2;
              // Add velocity constraint to mesh
              velocity_constraint = std::make_shared<mpm::VelocityConstraint>(
                  set_id, dir, constraint);
              REQUIRE(mesh->create_particle_velocity_constraint(
                          set_id, velocity_constraint) == false);

              mesh->apply_particle_velocity_constraints();
            }
          }
        }
        // Test assign velocity constraints to nodes
        SECTION("Check assign velocity constraints to nodes") {
          tsl::robin_map<mpm::Index, std::vector<mpm::Index>> node_sets;
          node_sets[0] = std::vector<mpm::Index>{0, 2};
          node_sets[1] = std::vector<mpm::Index>{1, 3};

          REQUIRE(mesh->create_node_sets(node_sets, true) == true);

          //! Constraints object
          auto constraints = std::make_shared<mpm::Constraints<Dim>>(mesh);

          int set_id = 0;
          int dir = 0;
          double constraint = 10.5;
          // Add velocity constraint to mesh
          auto velocity_constraint = std::make_shared<mpm::VelocityConstraint>(
              set_id, dir, constraint);
          REQUIRE(constraints->assign_nodal_velocity_constraint(
                      set_id, velocity_constraint) == true);

          set_id = 1;
          dir = 1;
          constraint = -12.5;
          // Add velocity constraint to mesh
          velocity_constraint = std::make_shared<mpm::VelocityConstraint>(
              set_id, dir, constraint);
          REQUIRE(constraints->assign_nodal_velocity_constraint(
                      set_id, velocity_constraint) == true);

          // Add velocity constraint to all nodes in mesh
          velocity_constraint =
              std::make_shared<mpm::VelocityConstraint>(-1, dir, constraint);
          REQUIRE(constraints->assign_nodal_velocity_constraint(
                      set_id, velocity_constraint) == true);

          // When constraints fail
          dir = 2;
          // Add velocity constraint to mesh
          velocity_constraint = std::make_shared<mpm::VelocityConstraint>(
              set_id, dir, constraint);
          REQUIRE(constraints->assign_nodal_velocity_constraint(
                      set_id, velocity_constraint) == false);
        }

        SECTION("Check assign friction constraints to nodes") {
          tsl::robin_map<mpm::Index, std::vector<mpm::Index>> node_sets;
          node_sets[0] = std::vector<mpm::Index>{0, 2};
          node_sets[1] = std::vector<mpm::Index>{1, 3};

          REQUIRE(mesh->create_node_sets(node_sets, true) == true);

          //! Constraints object
          auto constraints = std::make_shared<mpm::Constraints<Dim>>(mesh);

          int set_id = 0;
          int dir = 0;
          int sign_n = 1;
          double friction = 0.5;
          // Add friction constraint to mesh
          auto friction_constraint = std::make_shared<mpm::FrictionConstraint>(
              set_id, dir, sign_n, friction);
          REQUIRE(constraints->assign_nodal_frictional_constraint(
                      set_id, friction_constraint) == true);

          set_id = 1;
          dir = 1;
          sign_n = -1;
          friction = -0.25;
          // Add friction constraint to mesh
          friction_constraint = std::make_shared<mpm::FrictionConstraint>(
              set_id, dir, sign_n, friction);
          REQUIRE(constraints->assign_nodal_frictional_constraint(
                      set_id, friction_constraint) == true);

          // Add friction constraint to all nodes in mesh
          friction_constraint = std::make_shared<mpm::FrictionConstraint>(
              -1, dir, sign_n, friction);
          REQUIRE(constraints->assign_nodal_frictional_constraint(
                      set_id, friction_constraint) == true);

          // When constraints fail
          dir = 2;
          // Add friction constraint to mesh
          friction_constraint = std::make_shared<mpm::FrictionConstraint>(
              set_id, dir, sign_n, friction);
          REQUIRE(constraints->assign_nodal_frictional_constraint(
                      set_id, friction_constraint) == false);
        }

        // Test assign velocity constraints to nodes
        SECTION("Check assign velocity constraints to nodes") {
          // Vector of particle coordinates
          std::vector<std::tuple<mpm::Index, unsigned, double>>
              velocity_constraints;
          //! Constraints object
          auto constraints = std::make_shared<mpm::Constraints<Dim>>(mesh);
          // Constraint
          velocity_constraints.emplace_back(std::make_tuple(0, 0, 10.5));
          velocity_constraints.emplace_back(std::make_tuple(1, 1, -10.5));
          velocity_constraints.emplace_back(std::make_tuple(2, 0, -12.5));
          velocity_constraints.emplace_back(std::make_tuple(3, 1, 0.0));

          REQUIRE(constraints->assign_nodal_velocity_constraints(
                      velocity_constraints) == true);
          // When constraints fail
          velocity_constraints.emplace_back(std::make_tuple(3, 2, 0.0));
          REQUIRE(constraints->assign_nodal_velocity_constraints(
                      velocity_constraints) == false);
        }

        // Test assign friction constraints to nodes
        SECTION("Check assign friction constraints to nodes") {
          // Vector of particle coordinates
          std::vector<std::tuple<mpm::Index, unsigned, int, double>>
              friction_constraints;
          //! Constraints object
          auto constraints = std::make_shared<mpm::Constraints<Dim>>(mesh);
          // Constraint
          friction_constraints.emplace_back(std::make_tuple(0, 0, 1, 0.5));
          friction_constraints.emplace_back(std::make_tuple(1, 1, -1, 0.5));
          friction_constraints.emplace_back(std::make_tuple(2, 0, 1, 0.25));
          friction_constraints.emplace_back(std::make_tuple(3, 1, -1, 0.0));

          REQUIRE(constraints->assign_nodal_friction_constraints(
                      friction_constraints) == true);
          // When constraints fail
          friction_constraints.emplace_back(std::make_tuple(3, 2, -1, 0.0));
          REQUIRE(constraints->assign_nodal_friction_constraints(
                      friction_constraints) == false);
        }

        // Test assign nodes concentrated_forces
        SECTION("Check assign nodes concentrated_forces") {
          // Vector of node coordinates
          std::vector<std::tuple<mpm::Index, unsigned, double>>
              nodes_concentrated_forces;
          // Concentrated_Forces
          nodes_concentrated_forces.emplace_back(std::make_tuple(0, 0, 10.5));
          nodes_concentrated_forces.emplace_back(std::make_tuple(1, 1, -10.5));
          nodes_concentrated_forces.emplace_back(std::make_tuple(2, 0, -12.5));
          nodes_concentrated_forces.emplace_back(std::make_tuple(3, 1, 0.0));

          REQUIRE(mesh->nnodes() == 6);

          REQUIRE(mesh->assign_nodal_concentrated_forces(
                      nodes_concentrated_forces) == true);
          // When concentrated_forces fail
          nodes_concentrated_forces.emplace_back(std::make_tuple(3, 2, 0.0));
          REQUIRE(mesh->assign_nodal_concentrated_forces(
                      nodes_concentrated_forces) == false);
          nodes_concentrated_forces.emplace_back(std::make_tuple(300, 0, 0.0));
          REQUIRE(mesh->assign_nodal_concentrated_forces(
                      nodes_concentrated_forces) == false);
        }

        // Test assign rotation matrices to nodes
        SECTION("Check assign rotation matrices to nodes") {
          // Map of nodal id and euler angles
          std::map<mpm::Index, Eigen::Matrix<double, Dim, 1>> euler_angles;
          // Node 0 with Euler angles of 10 and 20 deg
          euler_angles.emplace(std::make_pair(
              0, (Eigen::Matrix<double, Dim, 1>() << 10. * M_PI / 180,
                  20. * M_PI / 180)
                     .finished()));
          // Node 1 with Euler angles of 30 and 40 deg
          euler_angles.emplace(std::make_pair(
              1, (Eigen::Matrix<double, Dim, 1>() << 30. * M_PI / 180,
                  40. * M_PI / 180)
                     .finished()));
          // Node 2 with Euler angles of 50 and 60 deg
          euler_angles.emplace(std::make_pair(
              2, (Eigen::Matrix<double, Dim, 1>() << 50. * M_PI / 180,
                  60. * M_PI / 180)
                     .finished()));
          // Node 3 with Euler angles of 70 and 80 deg
          euler_angles.emplace(std::make_pair(
              3, (Eigen::Matrix<double, Dim, 1>() << 70. * M_PI / 180,
                  80. * M_PI / 180)
                     .finished()));

          // Check compute and assign rotation matrix
          REQUIRE(mesh->compute_nodal_rotation_matrices(euler_angles) == true);

          // Check for failure when missing node id
          // Node 100 (non-existent) with Euler angles of 90 and 100 deg
          euler_angles.emplace(std::make_pair(
              100, (Eigen::Matrix<double, Dim, 1>() << 90. * M_PI / 180,
                    100. * M_PI / 180)
                       .finished()));
          REQUIRE(mesh->compute_nodal_rotation_matrices(euler_angles) == false);

          // Check for failure of empty input
          std::map<mpm::Index, Eigen::Matrix<double, Dim, 1>>
              empty_euler_angles;
          REQUIRE(mesh->compute_nodal_rotation_matrices(empty_euler_angles) ==
                  false);

          // Check for failure when no nodes are assigned
          auto mesh_fail = std::make_shared<mpm::Mesh<Dim>>(1);
          REQUIRE(mesh_fail->compute_nodal_rotation_matrices(euler_angles) ==
                  false);
        }
      }
    }
  }

  //! Check if nodal properties is initialised
  SECTION("Check nodal properties initialisation") {
    // Create the different meshes
    std::shared_ptr<mpm::Mesh<Dim>> mesh = std::make_shared<mpm::Mesh<Dim>>(0);

    // Define nodes
    Eigen::Vector2d coords;
    coords << 0., 0.;
    std::shared_ptr<mpm::NodeBase<Dim>> node0 =
        std::make_shared<mpm::Node<Dim, Dof, Nphases>>(0, coords);

    coords << 2., 0.;
    std::shared_ptr<mpm::NodeBase<Dim>> node1 =
        std::make_shared<mpm::Node<Dim, Dof, Nphases>>(1, coords);

    coords << 2., 2.;
    std::shared_ptr<mpm::NodeBase<Dim>> node2 =
        std::make_shared<mpm::Node<Dim, Dof, Nphases>>(2, coords);

    coords << 0., 2.;
    std::shared_ptr<mpm::NodeBase<Dim>> node3 =
        std::make_shared<mpm::Node<Dim, Dof, Nphases>>(3, coords);

    // Add nodes 0 to 3 to the mesh
    REQUIRE(mesh->add_node(node0) == true);
    REQUIRE(mesh->add_node(node1) == true);
    REQUIRE(mesh->add_node(node2) == true);
    REQUIRE(mesh->add_node(node3) == true);

    // Initialise material models
    mesh->initialise_material_models(materials);

    // Check nodal properties creation
    REQUIRE_NOTHROW(mesh->create_nodal_properties());

    // Check nodal properties initialisation
    REQUIRE_NOTHROW(mesh->initialise_nodal_properties());
  }
}

max_stars_repo_name: parduino/mpm

max_issues_repo_name: parduino/mpm

max_forks_repo_name: parduino/mpm


text:
//
// Created by Roman on 30/08/2019.
//

#ifndef RSOCKS_RSOCKS_SESSION_HPP
#define RSOCKS_RSOCKS_SESSION_HPP

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <map>
#include <algorithm>

#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>

#include <netinet/in.h>

namespace RSocks
{
    class session;
    typedef boost::shared_ptr<session> session_ptr;
}

#include "rsocks_frame.hpp"
#include "rsocks_connection.hpp"

#include "base64/base64.hpp"
#include "sha1/sha1.hpp"

using boost::asio::ip::tcp;

namespace RSocks
{
    // TODO : Write session network logic.
    class session : public boost::enable_shared_from_this<session>
    {
    public:
        enum ws_status
        {
            CONNECTING,
            OPEN,
            CLOSING,
            CLOSED
        };

        typedef enum ws_status status_code;

        // ctor
        session(boost::asio::io_service &io_service,
                const std::string &host,
                connection_handler_ptr defc)
                : m_host(host),
                  m_socket(io_service),
                  m_status(CONNECTING),
                  m_http_error_code(0),
                  m_local_interface(defc) {}

        tcp::socket &socket()
        {
            return m_socket;
        }

        // This function is called to begin the session loop. This method and all
        // that come after it are called as a result of an async event completing.
        // if any method in this chain returns before adding a new async event the
        // session will end.
        void start()
        {
            // async read to handle_read_handshake
            boost::asio::async_read_until(
                    m_socket,
                    m_buf,
                    "\r\n\r\n",
                    boost::bind(
                            &session::handle_read_handshake,
                            shared_from_this(),
                            boost::asio::placeholders::error,
                            boost::asio::placeholders::bytes_transferred
                    )
            );
        }

        // Sets the internal connection handler of this connection to new_con.
        // This is useful if you want to switch handler objects during a connection
        // Example: a generic lobby handler could validate the handshake negotiate a
        // sub protocol to talk to and then pass the connection off to a handler for
        // that sub protocol.
        void set_handler(connection_handler_ptr new_con);

        // Public handshake interface

        // By default a failed handshake validation will return an HTTP 400 Bad
        // Request error. If your application wants to reject the connection for
        // another reason it can be set here. Example: 404 if the resource request
        // is not recognized or 403 forbidden if the origin does not match. If only
        // a code is supplied a msg will be generated automatically.
        void set_http_error(int code, std::string msg = "");

        // Gets the value of a header or the empty string if not present.
        std::string get_header(const std::string &key) const;

        // Adds an arbitrary header to the server handshake HTTP response.
        void add_header(const std::string &key, const std::string &value);

        std::string get_request() const;

        // Sets the subprotocol being used. This will result in the appropriate
        // Sec-WebSocket-Protocol header being sent back to the client. The value
        // here must have been present in the client's opening handshake.
        void set_subprotocol(const std::string &protocol);

        // Public session interface

        // Send basic frame types
        void send(const std::string &msg); // text
        void send(const std::vector<unsigned char> &data); // binary
        void ping(const std::string &msg);

        void pong(const std::string &msg);

        void disconnect(const std::string &reason);

    private:
        // Handle_read_handshake reads the HTTP headers of the initial websocket
        // handshake, parses out the request and headers, and does error checking
        // TODO: Generalize a lot of the hard coded things in this method.
        void handle_read_handshake(const boost::system::error_code &e,
                                   std::size_t bytes_transferred);

        // Write_handshake calculates the server portion of the handshake and
        // sends it back.
        // TODO: Generalize this to include things like protocols, cookies, etc
        void write_handshake();

        // Handle_write_handshake checks for errors writing the server handshake,
        // officially declares a connection open, notifies the local interface,
        // and starts the frame reading loop.
        void handle_write_handshake(const boost::system::error_code &error);

        // Construct and write an HTTP error in the case the handshake goes poorly
        void write_http_error();

        void handle_write_http_error(const boost::system::error_code &error);

        // Start async read for a websocket frame (2 bytes) to handle_frame_header
        void read_frame();

        // Reads frame header and devices if it needs to read more header or go
        // straight to the payload.
        void handle_frame_header(const boost::system::error_code &error);

        // Process extra headers and start payload read
        void handle_extended_frame_header(const boost::system::error_code &error);

        // Initiate payload read
        void read_payload();

        // Now the frame object should be complete. Process and send it on then
        // reset for new frame
        void handle_read_payload(const boost::system::error_code &error);

        // Checks for errors writing frames
        void handle_write_frame(const boost::system::error_code &error);

        // Helper functions for processing each opcode
        void process_ping();

        void process_pong();

        void process_text();

        void process_binary();

        void process_continuation();

        void process_close();

        // Deliver message if we have a local interface attached
        void deliver_message();

        // Copies the current read frame payload into the session so that the read
        // frame can be cleared for the next read. This is done when fragmented
        // messages are recieved.
        void extract_payload();

        // Write m_write_frame out to the socket.
        void write_frame();

        // Reset session for a new message
        void reset_message();

        // Prints a diagnostic message and disconnects the local interface
        void handle_error(std::string msg, const boost::system::error_code &error);

        std::string lookup_http_error_string(int code);

    private:
        std::string m_host;
        tcp::socket m_socket;
        status_code m_status;

        int m_http_error_code;
        std::string m_http_error_string;

        boost::asio::streambuf m_buf;
        std::string m_handshake;

        std::string m_request;
        std::map <std::string, std::string> m_headers;

        frame m_read_frame;
        frame m_write_frame;

        std::vector<unsigned char> m_current_message;

        bool m_error;
        bool m_fragmented;
        frame::opcode m_current_opcode;

        connection_ptr m_local_interface;
    };
}

#endif //RSOCKS_RSOCKS_SESSION_HPP


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

  @copyright 2016 NumScale SAS

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

#include <boost/simd/constant/one.hpp>
#include <boost/simd/constant/valmax.hpp>
#include <boost/simd/constant/valmin.hpp>
#include <boost/simd/constant/zero.hpp>
#include <boost/simd/function/genmask.hpp>
#include <boost/simd/detail/dispatch/function/overload.hpp>
#include <boost/simd/detail/dispatch/meta/as_unsigned.hpp>
#include <boost/config.hpp>

namespace boost { namespace simd { namespace ext
{
  namespace bd = boost::dispatch;
#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable: 4723) // potential divide by 0
#endif

  BOOST_DISPATCH_OVERLOAD ( divides_
                          , (typename A0)
                          , bd::cpu_
                          , bs::saturated_tag
                          , bd::scalar_< bd::floating_<A0> >
                          , bd::scalar_< bd::floating_<A0> >
                          )
  {
    BOOST_FORCEINLINE A0 operator() (const saturated_tag &,  A0 a0, A0 a1
                                    ) const BOOST_NOEXCEPT
    {
      return a0/a1;
    }
  };
  BOOST_DISPATCH_OVERLOAD ( divides_
                          , (typename A0)
                          , bd::cpu_
                          , bs::saturated_tag
                          , bd::scalar_< bd::int_<A0> >
                          , bd::scalar_< bd::int_<A0> >
                          )
  {
    BOOST_FORCEINLINE A0 operator() (const saturated_tag &,  A0 a0, A0 a1
                                    ) const BOOST_NOEXCEPT
    {
      typedef bd::as_unsigned_t<A0> utype;
      A0 const aa0 = a0 + !((a1 + One<A0>()) | ((utype)a0 + Valmin<A0>()));
      if (a1)
        return aa0/a1;
      else if (a0)
        return Valmax<A0>() + ((utype)a0 >> (sizeof(A0)*CHAR_BIT-1));
      else
        return Zero<A0>();
    }
  };
  BOOST_DISPATCH_OVERLOAD ( divides_
                          , (typename A0)
                          , bd::cpu_
                          , bs::saturated_tag
                          , bd::scalar_< bd::uint_<A0> >
                          , bd::scalar_< bd::uint_<A0> >
                          )
  {
    BOOST_FORCEINLINE A0 operator() (const saturated_tag &,  A0 a0, A0 a1
                                    ) const BOOST_NOEXCEPT
    {
      return a1 ? a0/a1 : genmask(a0);
    }
  };

#ifdef BOOST_MSVC
#pragma warning(pop)
#endif

} } }

#endif

max_stars_repo_name: SylvainCorlay/pythran

max_issues_repo_name: SylvainCorlay/pythran

max_forks_repo_name: SylvainCorlay/pythran