text:
/*!
@file
Defines `boost::hana::Sequence`.

@copyright Louis Dionne 2013-2017
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_HANA_CONCEPT_SEQUENCE_HPP
#define BOOST_HANA_CONCEPT_SEQUENCE_HPP

#include <boost/hana/fwd/concept/sequence.hpp>

#include <boost/hana/config.hpp>
#include <boost/hana/core/tag_of.hpp>
#include <boost/hana/core/when.hpp>
#include <boost/hana/detail/integral_constant.hpp>

BOOST_HANA_NAMESPACE_BEGIN
    namespace detail {
        template <typename S, typename Tag = typename hana::tag_of<S>::type>
        struct sequence_dispatch
            : hana::integral_constant<bool,
                hana::Sequence<Tag>::value
            >
        { };

        template <typename S>
        struct sequence_dispatch<S, S>
            : hana::integral_constant<bool, false>
        { };
    }

    //! @cond
    template <typename S, bool condition>
    struct Sequence<S, when<condition>>
        : detail::sequence_dispatch<S>
    { };
    //! @endcond
BOOST_HANA_NAMESPACE_END

#endif // !BOOST_HANA_CONCEPT_SEQUENCE_HPP

max_stars_repo_name: kindlychung/mediasoup-sfu-cpp

max_issues_repo_name: kindlychung/mediasoup-sfu-cpp

max_forks_repo_name: kindlychung/mediasoup-sfu-cpp


text:
// This file is part of SWGANH which is released under the MIT license.
// See file LICENSE or go to http://swganh.com/LICENSE

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>

#include <map>

#include "anh/hash_string.h"

using namespace anh;
using namespace std;

BOOST_AUTO_TEST_SUITE(ANHHashString)

/// This test shows how to create a hash string and check it's generated identifier.
BOOST_AUTO_TEST_CASE(CreatingEventTypeFromStringGeneratesUniqueIdentifier) {
    HashString hash_string("test_hash_string");

    BOOST_CHECK_MESSAGE(uint32_t(0x107D0089) == hash_string.ident(), "HashString did not create the expected identifier");
}

/// This test shows how to compare two hash strings.
BOOST_AUTO_TEST_CASE(CanCompareTwoHashStrings) {
    HashString hash_string1("test_string1");
    HashString hash_string2("another_hash_string");
    HashString hash_string3("another_hash_string");

    BOOST_CHECK_MESSAGE(hash_string1 != hash_string2, "hash_string1 and hash_string2 should not match.");
    BOOST_CHECK_MESSAGE(hash_string2 == hash_string3, "hash_string2 and hash_string3 should match");
}

/// This test shows how to use HashString as a key in std containers.
BOOST_AUTO_TEST_CASE(CanUseHashStringAsContainerKey) {
    // Create a simple std::map<HashString, int> map.
    map<HashString, int> hash_string_map;

    // Seed the map with some entries for testing.
    hash_string_map.insert(make_pair(HashString("my_key1"), 2000));
    hash_string_map.insert(make_pair(HashString("my_key2"), 9001));
    hash_string_map.insert(make_pair(HashString("my_key3"), 400));

    // Now make sure we can access the map appropriately.
    BOOST_CHECK_EQUAL(2000, hash_string_map[HashString("my_key1")]);
    BOOST_CHECK_EQUAL(9001, hash_string_map[HashString("my_key2")]);
    BOOST_CHECK_EQUAL(400, hash_string_map[HashString("my_key3")]);

    // Try searching the map by the key and make sure it returns the correct result.
    auto it = hash_string_map.find(HashString("my_key1"));
    BOOST_CHECK_MESSAGE(2000 == it->second, "Cannot find a map entry by a HashString");
}
BOOST_AUTO_TEST_SUITE_END()

ext: cc

max_stars_repo_name: JohnShandy/swganh

max_issues_repo_name: JohnShandy/swganh

max_forks_repo_name: JohnShandy/swganh


text:
/*****************************************************************************
* Dwarf Mine - The 13-11 Benchmark
*
* Copyright (c) 2013 Bünger, Thomas; Kieschnick, Christian; Kusber,
* Michael; Lohse, Henning; Wuttke, Nikolai; Xylander, Oliver; Yao, Gary;
* Zimmermann, Florian
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*****************************************************************************/

#include "SchedulerFactory.h"
#include "quadratic_sieve/QuadraticSieveScheduler.h"
#include "quadratic_sieve/smp/SmpQuadraticSieveElf.h"
#include "factorization_montecarlo/FactorizationScheduler.h"
#include "factorization_montecarlo/MonteCarloFactorizationElf.h"
#include "matrix/MatrixScheduler.h"
#include "matrix/MatrixOnlineScheduler.h"
#include "matrix/smp/SMPMatrixElf.h"
#include "othello_montecarlo/OthelloScheduler.h"
#include "othello_montecarlo/smp/SMPOthelloElf.h"

#ifdef HAVE_CUDA
#include "matrix/cuda/CudaMatrixElf.h"
#include "quadratic_sieve/cuda/CudaQuadraticSieveElf.h"
#include "othello_montecarlo/cuda/CudaOthelloElf.h"
#endif

#include <stdexcept>
#include <boost/range/algorithm/copy.hpp>
#include <boost/range/adaptor/map.hpp>

using namespace std;

#ifndef HAVE_CUDA
struct HasNoCudaDummy : public Elf {};

typedef HasNoCudaDummy CudaMatrixElf, CudaQuadraticSieveElf, CudaOthelloElf;
#endif

typedef SchedulerFactory::FactoryFunction FactoryFunction;

template<typename SchedulerType, typename ElfType>
static FactoryFunction innerCreateFactory()
{
    return [](const Communicator& communicator)
    {
        return new SchedulerType(communicator, []()
            {
                return new ElfType();
            }
        );
    };
}

template<typename SchedulerType, typename SmpElfType, typename CudaElfType>
static FactoryFunction createFactory(bool useCuda)
{
    if (useCuda)
    {
#ifdef HAVE_CUDA
        return innerCreateFactory<SchedulerType, CudaElfType>();
#else
        throw runtime_error("You have to build with Cuda support in order to create cuda elves in " __FILE__);
#endif
    }
    else
    {
        return innerCreateFactory<SchedulerType, SmpElfType>();
    }
}

template<typename SchedulerType, typename SmpElfType>
static FactoryFunction createFactory(bool useCuda)
{
    if (useCuda)
        throw runtime_error("This category has no Cuda implementation in " __FILE__);

    return innerCreateFactory<SchedulerType, SmpElfType>();
}

static map<string, function<FactoryFunction(bool)>> sFactoryFunctionsMap =
{
    {
        "matrix",
        &createFactory<MatrixScheduler, SMPMatrixElf, CudaMatrixElf>
    },
    {
        "matrix_online",
        &createFactory<MatrixOnlineScheduler, SMPMatrixElf, CudaMatrixElf>
    },
    {
        "factorization_montecarlo",
        &createFactory<FactorizationScheduler, MonteCarloFactorizationElf>
    },
    {
        "quadratic_sieve",
        &createFactory<QuadraticSieveScheduler, SmpQuadraticSieveElf, CudaQuadraticSieveElf>
    },
    {
        "montecarlo_tree_search",
        &createFactory<OthelloScheduler, SMPOthelloElf, CudaOthelloElf>
    }
};

static void validateType(const string& type)
{
    if (type != "cuda" && type != "smp")
        throw runtime_error("Unknown scheduler type " + type + " in " __FILE__);
}

static FactoryFunction createFactory(const string& type, const ElfCategory& category)
{
    validateType(type);

    auto factoryCreatorIt = sFactoryFunctionsMap.find(category);

    if (factoryCreatorIt == sFactoryFunctionsMap.end())
        throw runtime_error("Unknown elf category: " + category + " in " __FILE__);

    return factoryCreatorIt->second(type == "cuda");
}

vector<string> SchedulerFactory::getValidCategories()
{
    vector<string> categories;
    boost::copy(
            sFactoryFunctionsMap | boost::adaptors::map_keys,
            std::back_inserter(categories)
    );
    return categories;
}

unique_ptr<SchedulerFactory> SchedulerFactory::createFor(const string& type, const ElfCategory& category)
{
    return unique_ptr<SchedulerFactory>(
        new SchedulerFactory(createFactory(type, category))
    );
}

SchedulerFactory::SchedulerFactory(const FactoryFunction& factory) :
    factory(factory)
{
}

unique_ptr<Scheduler> SchedulerFactory::createScheduler(const Communicator& communicator) const
{
    return unique_ptr<Scheduler>(factory(communicator));
}

ext: cpp


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

#include <signal.h>

#include <boost/random.hpp>
#include <gtest/gtest.h>

#include <thrift/lib/cpp/async/TAsyncSocket.h>
#include <thrift/lib/cpp/async/TAsyncTransport.h>
#include <thrift/lib/cpp/async/TAsyncTimeout.h>
#include <thrift/lib/cpp/async/TBinaryAsyncChannel.h>
#include <thrift/lib/cpp/async/TEventBase.h>
#include <thrift/lib/cpp/async/TFramedAsyncChannel.h>
#include <thrift/lib/cpp/concurrency/Util.h>
#include <folly/io/async/test/SocketPair.h>
#include <folly/io/async/test/Util.h>

using namespace boost;
using namespace folly;
using namespace std::chrono;
using std::cerr;
using std::endl;
using std::string;
using std::vector;

using apache::thrift::async::TAsyncChannel;
using apache::thrift::async::TAsyncTransport;
using apache::thrift::async::TAsyncSocket;
using apache::thrift::async::TAsyncTimeout;
using apache::thrift::async::TBinaryAsyncChannel;
using apache::thrift::async::TEventBase;
using apache::thrift::async::TFramedAsyncChannel;
using apache::thrift::protocol::TBinaryProtocolT;
using apache::thrift::transport::TBufferBase;
using apache::thrift::transport::TFramedTransport;
using apache::thrift::transport::TMemoryBuffer;
using apache::thrift::transport::TTransportException;

///////////////////////////////////////////////////////////////////////////
// Utility code
//////////////////////////////////////////////////////////////////////////

class ChannelCallback {
 public:
  ChannelCallback()
    : sendDone_(0)
    , sendError_(0)
    , recvDone_(0)
    , recvError_(0)
    , timestamp_(false) {}

  void send(const std::shared_ptr<TAsyncChannel>& channel,
            TMemoryBuffer* message) {
    // helper function to get the correct callbacks
    channel->sendMessage(std::bind(&ChannelCallback::sendDone, this),
                         std::bind(&ChannelCallback::sendError, this), message);
  }

  void recv(const std::shared_ptr<TAsyncChannel>& channel,
            TMemoryBuffer* message) {
    // helper function to get the correct callbacks
    channel->recvMessage(std::bind(&ChannelCallback::recvDone, this),
                         std::bind(&ChannelCallback::recvError, this), message);
  }

  void sendDone() {
    ++sendDone_;
    timestamp_.reset();
  }
  void sendError() {
    ++sendError_;
    timestamp_.reset();
  }

  void recvDone() {
    ++recvDone_;
    timestamp_.reset();
  }
  void recvError() {
    ++recvError_;
    timestamp_.reset();
  }

  uint32_t getSendDone() const {
    return sendDone_;
  }
  uint32_t getSendError() const {
    return sendError_;
  }
  uint32_t getRecvDone() const {
    return recvDone_;
  }
  uint32_t getRecvError() const {
    return recvError_;
  }

  const TimePoint& getTimestamp() const {
    return timestamp_;
  }

 private:
  uint32_t sendDone_;
  uint32_t sendError_;
  uint32_t recvDone_;
  uint32_t recvError_;
  TimePoint timestamp_;
};

class Message {
 public:
  explicit Message(uint32_t len, bool addFrame = false)
    : framed_(addFrame)
    , buf_(new TMemoryBuffer(len + kPadding)) {
    init(len);
  }

  void init(uint32_t len) {
    string value;
    randomizeString(&value, len);

    // Generate a valid thrift TBinaryProtocol message,
    // containing a randomly generated string of the specified length
    std::shared_ptr<TBufferBase> transport;
    if (framed_) {
      transport.reset(new TFramedTransport(buf_));
    } else {
      transport = buf_;
    }
    TBinaryProtocolT<TBufferBase> prot(transport);

    prot.writeMessageBegin("foo", apache::thrift::protocol::T_CALL, 0);
    prot.writeStructBegin("bar");

    prot.writeFieldBegin("value", apache::thrift::protocol::T_STRING, 1);
    prot.writeString(value);
    prot.writeFieldEnd();

    prot.writeFieldStop();
    prot.writeStructEnd();
    prot.writeMessageEnd();

    transport->writeEnd();
    transport->flush();
  }

  void copyTo(TMemoryBuffer* membuf) {
    memcpy(membuf->getWritePtr(getLength()), getBuffer(), getLength());
    membuf->wroteBytes(getLength());
  }

  void checkEqual(TMemoryBuffer* membuf) const {
    // If we have a frame header, skip it when comparing
    uint32_t length = getLength();
    const uint8_t* myBuf = getBuffer();
    if (framed_) {
      length -= sizeof(uint32_t);
      myBuf += sizeof(uint32_t);
    }

    CHECK_EQ(membuf->available_read(), length);

    uint32_t borrowLen = length;
    const uint8_t* otherBuf = membuf->borrow(nullptr, &borrowLen);
    CHECK(otherBuf != nullptr);
    CHECK_EQ(borrowLen, length);

    CHECK_EQ(memcmp(otherBuf, myBuf, length), 0);
  }

  uint32_t getLength() const {
    return buf_->available_read();
  }

  const uint8_t* getBuffer() const {
    uint32_t borrowLen = getLength();
    const uint8_t* buf = buf_->borrow(nullptr, &borrowLen);
    assert(buf != nullptr);
    return buf;
  }

 private:
  void randomizeString(string* ret, uint32_t len) {
    ret->resize(len);

    // Randomly initialize the string
    // TODO: we don't currently seed the RNG.
    boost::mt19937 rng;
    for (uint32_t n = 0; n < len; ++n) {
      // The RNG gives us more than 1 byte of randomness, but
      // we don't currently take advantage of it.  It's easier for now
      // just to proceed 1 byte at a time.
      (*ret)[n] = rng();
    }
  }

  static uint32_t const kPadding = 256; // extra room for serialization overhead

  bool framed_;
  std::shared_ptr<TMemoryBuffer> buf_;
};

struct ChunkInfo {
  ChunkInfo(int b, milliseconds d)
    : bytes(b)
    , delayMS(d) {}

  int bytes;
  milliseconds delayMS;
};

class ChunkSchedule : public vector<ChunkInfo> {
 public:
  /*
   * Constructor to allow ChunkSchedules to be easily specified
   * in the code.  The arguments are parsed in pairs as (bytes, delay).
   *
   * The arguments must end with a pair that has a non-positive bytes value.
   * A negative bytes value means to send the rest of the data, a value of 0
   * means to close the socket.
   */
  ChunkSchedule(int bytes, milliseconds delayMS, ...) {
    push_back(ChunkInfo(bytes, delayMS));

    if (bytes <= 0)
      return;

    va_list ap;
    va_start(ap, delayMS);

    while (true) {
      int b = va_arg(ap, int);
      milliseconds d = va_arg(ap, milliseconds);

      push_back(ChunkInfo(b, d));
      if (b <= 0) {
        break;
      }
    }

    va_end(ap);
  }
};

class ChunkSender : private TAsyncTransport::WriteCallback,
                    private TAsyncTimeout {
 public:
  ChunkSender(TEventBase* evb, TAsyncSocket* socket,
              const Message* msg, const ChunkSchedule& schedule)
    : TAsyncTimeout(evb)
    , bufOffset_(0)
    , scheduleIndex_(0)
    , currentChunkLen_(0)
    , error_(false)
    , eventBase_(evb)
    , socket_(socket)
    , message_(msg)
    , schedule_(schedule) {
  }

  void start() {
    scheduleNext();
  }

  const ChunkSchedule* getSchedule() const {
    return &schedule_;
  }

  bool error() const {
    return error_;
  }

 private:
  void scheduleNext() {
    assert(scheduleIndex_ < schedule_.size());
    const ChunkInfo& info = schedule_[scheduleIndex_];
    if (info.delayMS.count() <= 0) {
      sendNow();
    } else {
      scheduleTimeout(info.delayMS);
    }
  }

  void sendNow() {
    assert(scheduleIndex_ < schedule_.size());
    const ChunkInfo& info = schedule_[scheduleIndex_];

    assert(bufOffset_ <= message_->getLength());

    uint32_t len;
    if (info.bytes == 0) {
      // close the socket
      socket_->close();
      return;
    } else if (info.bytes < 0) {
      // write the rest of the data
      if (bufOffset_ >= message_->getLength()) {
        // nothing more to write
        return;
      }
      len = message_->getLength() - bufOffset_;
    } else {
      len = info.bytes;
      if (len + bufOffset_ > message_->getLength()) {
        // bug in the test code: ChunkSchedule lists more data than available
        FAIL() << "bad ChunkSchedule";

        len = message_->getLength() - bufOffset_;
        if (len == 0) {
          ++scheduleIndex_;
          if (scheduleIndex_ < schedule_.size()) {
            scheduleNext();
          }
          return;
        }
      }
    }

    currentChunkLen_ = len;
    const uint8_t* buf = message_->getBuffer() + bufOffset_;
    socket_->write(this, buf, len);
  }

  void writeSuccess() noexcept {
    bufOffset_ += currentChunkLen_;

    ++scheduleIndex_;
    if (scheduleIndex_ < schedule_.size()) {
      scheduleNext();
    }
  }

  void writeError(size_t bytesWritten,
                  const TTransportException& ex) noexcept {
    error_ = true;
  }

  virtual void timeoutExpired() noexcept {
    sendNow();
  }

  uint32_t bufOffset_;
  uint32_t scheduleIndex_;
  uint32_t currentChunkLen_;
  bool error_;
  TEventBase* eventBase_;
  TAsyncSocket* socket_;
  const Message* message_;
  ChunkSchedule schedule_;
};

class MultiMessageSize : public vector<int> {
  public:
    MultiMessageSize(int len, ...) {
      push_back(len);

      va_list ap;
      va_start(ap, len);

      while (true) {
        int b = va_arg(ap, int);
        if (b <= 0) {
          break;
        } else {
          push_back(b);
        }
      }

      va_end(ap);
    }
};

class MultiMessageSenderReceiver : private TAsyncTransport::WriteCallback,
                                   private TAsyncTimeout {
  public:
    MultiMessageSenderReceiver(TEventBase* evb,
                               TAsyncSocket* socket,
                               const MultiMessageSize& multiMessage,
                               bool framed,
                               uint32_t writeTimes,
                               bool queued = false,
                               milliseconds delayMS = milliseconds(2))
    : TAsyncTimeout(evb)
    , writeError_(false)
    , readError_(false)
    , eventBase_(evb)
    , socket_(socket)
    , queued_(queued)
    , delayMS_(delayMS) {
      uint32_t totalSize = 0;
      for (vector<int>::const_iterator it = multiMessage.begin();
           it != multiMessage.end();
           it++) {
        Message message(*it, framed);
        writeMessages_.push_back(message);
        writeMemoryBuffer_.write(message.getBuffer(), message.getLength());
        totalSize += message.getLength();
      }

      assert(writeMessages_.size() > 0);
      writeSize_ = totalSize / writeTimes;
    }

    void initialize(const std::shared_ptr<TAsyncChannel>& channel) {
      int n_msgs = writeMessages_.size();
      uint32_t n_recvs = (queued_) ? n_msgs : 1;
      for (uint32_t i = 0; i < n_recvs; i++) {
        channel->recvMessage(
          std::bind(&MultiMessageSenderReceiver::recvDone, this),
          std::bind(&MultiMessageSenderReceiver::recvError, this),
          &readMemoryBuffer_);
      }
      scheduleNext();
      recvChannel_ = channel;
    }

    bool getReadError() const {
      return readError_;
    }

    bool getWriteError() const {
      return writeError_;
    }

    vector<std::shared_ptr<TMemoryBuffer> >& getReadBuffers() {
      return readBuffers_;
    }

    vector<Message>& getWriteMessages() {
      return writeMessages_;
    }

    void recvDone() {
      uint8_t* request;
      uint32_t requestLen;
      readMemoryBuffer_.extractReadBuffer(&request, &requestLen);
      if (requestLen > 0) {
        std::shared_ptr<TMemoryBuffer> recvBuffer(new TMemoryBuffer(
                                  request,
                                  requestLen,
                                  TMemoryBuffer::TAKE_OWNERSHIP));
        readBuffers_.push_back(recvBuffer);
      } else if (request) {
        delete request;
      }

      // Read another message if we haven't read all of the messages yet
      if (!queued_ && readBuffers_.size() < writeMessages_.size()) {
        recvChannel_->recvMessage(
            std::bind(&MultiMessageSenderReceiver::recvDone, this),
            std::bind(&MultiMessageSenderReceiver::recvError, this),
            &readMemoryBuffer_);
      }
    }

    void recvError() {
      readError_ = true;
    }

    void writeSuccess() noexcept {
      uint32_t sentSize = std::min(writeSize_,
                                   writeMemoryBuffer_.available_read());
      writeMemoryBuffer_.consume(sentSize);
      if (writeMemoryBuffer_.available_read() > 0) {
        scheduleNext();
      }
    }

    void writeError(size_t bytesWritten,
                  const TTransportException& ex) noexcept {
      writeError_ = true;
    }

 private:
   void scheduleNext() {
     if (delayMS_.count() <= 0) {
       send();
     } else {
       scheduleTimeout(delayMS_);
     }
   }

   virtual void timeoutExpired() noexcept {
     send();
   }

  void send() {
    uint32_t availableSize = writeMemoryBuffer_.available_read();
    const uint8_t* sendBufPtr = writeMemoryBuffer_.borrow(nullptr,
                                                          &availableSize);
    uint32_t sendSize = std::min(writeSize_, availableSize);
    if (sendSize > 0) {
      socket_->write(this, sendBufPtr, sendSize);
    }
  }

  bool writeError_;
  bool readError_;
  TEventBase* eventBase_;
  TAsyncSocket* socket_;
  vector<Message> writeMessages_;
  vector<std::shared_ptr<TMemoryBuffer> > readBuffers_;
  TMemoryBuffer writeMemoryBuffer_;
  TMemoryBuffer readMemoryBuffer_;
  uint32_t writeSize_;
  bool queued_;
  milliseconds delayMS_;
  std::shared_ptr<TAsyncChannel> recvChannel_;
};

class EventBaseAborter : public TAsyncTimeout {
 public:
  EventBaseAborter(TEventBase* eventBase, uint32_t timeoutMS)
    : TAsyncTimeout(eventBase,
                    TAsyncTimeout::InternalEnum::INTERNAL)
    , eventBase_(eventBase) {
    scheduleTimeout(timeoutMS);
  }

  virtual void timeoutExpired() noexcept {
    FAIL() << "test timed out";
    eventBase_->terminateLoopSoon();
  }

 private:
  TEventBase* eventBase_;
};

template<typename ChannelT>
class SocketPairTest {
 public:
  SocketPairTest()
    : eventBase_()
    , socketPair_() {
    socket0_ = TAsyncSocket::newSocket(&eventBase_, socketPair_[0]);
    socketPair_.extractFD0();

    socket1_ = TAsyncSocket::newSocket(&eventBase_, socketPair_[1]);
    socketPair_.extractFD1();

    channel0_ = ChannelT::newChannel(socket0_);
    channel1_ = ChannelT::newChannel(socket1_);
  }
  virtual ~SocketPairTest() {}

  void loop(uint32_t timeoutMS = 3000) {
    EventBaseAborter aborter(&eventBase_, timeoutMS);
    eventBase_.loop();
  }

  virtual void run() {
    runWithTimeout(3000);
  }

  virtual void runWithTimeout(uint32_t timeoutMS) {
    preLoop();
    loop(timeoutMS);
    postLoop();
  }

  virtual void preLoop() {}
  virtual void postLoop() {}

 protected:
  TEventBase eventBase_;
  SocketPair socketPair_;
  std::shared_ptr<TAsyncSocket> socket0_;
  std::shared_ptr<TAsyncSocket> socket1_;
  std::shared_ptr<ChannelT> channel0_;
  std::shared_ptr<ChannelT> channel1_;
};

template<typename ChannelT>
class NeedsFrame {
};

template<>
class NeedsFrame<TFramedAsyncChannel> {
 public:
  static bool value() {
    return true;
  }
};

template<>
class NeedsFrame<TBinaryAsyncChannel> {
 public:
  static bool value() {
    return false;
  }
};

///////////////////////////////////////////////////////////////////////////
// Test cases
//////////////////////////////////////////////////////////////////////////

template<typename ChannelT>
class SendRecvTest : public SocketPairTest<ChannelT> {
 public:
  explicit SendRecvTest(uint32_t msgLen)
    : msg_(msgLen) {
  }

  void preLoop() {
    msg_.copyTo(&sendBuf_);
    sendCallback_.send(this->channel0_, &sendBuf_);
    recvCallback_.recv(this->channel1_, &recvBuf_);
  }

  void postLoop() {
    CHECK_EQ(sendCallback_.getSendError(), 0);
    CHECK_EQ(sendCallback_.getSendDone(), 1);
    CHECK_EQ(recvCallback_.getRecvError(), 0);
    CHECK_EQ(recvCallback_.getRecvDone(), 1);
    msg_.checkEqual(&recvBuf_);
  }

 private:
  Message msg_;
  TMemoryBuffer sendBuf_;
  TMemoryBuffer recvBuf_;
  ChannelCallback sendCallback_;
  ChannelCallback recvCallback_;
};

TEST(TAsyncChannelTest, TestSendRecvFramed) {
  SendRecvTest<TFramedAsyncChannel>(1).run();
  SendRecvTest<TFramedAsyncChannel>(100).run();
  SendRecvTest<TFramedAsyncChannel>(1024*1024).run();
}

TEST(TAsyncChannelTest, TestSendRecvBinary) {
  SendRecvTest<TBinaryAsyncChannel>(1).run();
  SendRecvTest<TBinaryAsyncChannel>(100).run();
  SendRecvTest<TBinaryAsyncChannel>(1024*1024).run();
}

template<typename ChannelT>
class MultiSendRecvTest : public SocketPairTest<ChannelT> {
  public:
    MultiSendRecvTest(const MultiMessageSize& multiMessage,
                      uint32_t writeTimes,
                      bool queued = false,
                      milliseconds delayMS = milliseconds(0))
    : multiMessageSenderReceiver_(&this->eventBase_,
                                  this->socket0_.get(),
                                  multiMessage,
                                  NeedsFrame<ChannelT>::value(),
                                  writeTimes,
                                  queued,
                                  delayMS) {
  }

  void preLoop() {
    multiMessageSenderReceiver_.initialize(this->channel1_);
  }

  void postLoop() {
    CHECK_EQ(multiMessageSenderReceiver_.getReadError(), false);
    CHECK_EQ(multiMessageSenderReceiver_.getWriteError(), false);

    vector<std::shared_ptr<TMemoryBuffer> >& readBuffers
                      = multiMessageSenderReceiver_.getReadBuffers();
    vector<Message>& writeMessages
                      = multiMessageSenderReceiver_.getWriteMessages();
    CHECK_EQ(readBuffers.size(), writeMessages.size());
    for (int i = 0; i < writeMessages.size(); i++) {
      writeMessages[i].checkEqual(readBuffers[i].get());
    }
  }

  private:
    MultiMessageSenderReceiver multiMessageSenderReceiver_;
};

TEST(TAsyncChannelTest, TestMultiSendRecvBinary) {
  typedef MultiSendRecvTest<TBinaryAsyncChannel> MultiSendRecvBinaryTest;

  //size below 1024 for each message
  MultiMessageSize sizes(911, 911, 911, -1);

  // each time send one whole message below 1024
  MultiSendRecvBinaryTest(sizes, 3, 0).run();
  MultiSendRecvBinaryTest(sizes, 3, 2).run();

  // send all messages for one time
  MultiSendRecvBinaryTest(sizes, 1, 0).run();

  // each time send one and half message.
  MultiSendRecvBinaryTest(sizes, 2).run();
  MultiSendRecvBinaryTest(sizes, 2, 2).run();

  //size above 1024 for each message
  MultiMessageSize bigSizes(1911 * 1911,
                            1911 * 1911,
                            1911 * 1911,
                            -1);

  // each time send one whole message above 1024
  MultiSendRecvBinaryTest(bigSizes, 3, 0).run();
  MultiSendRecvBinaryTest(bigSizes, 3, 2).run();

  // send all messages for one time
  MultiSendRecvBinaryTest(bigSizes, 1, 0).run();

  // each time send one and half message
  MultiSendRecvBinaryTest(bigSizes, 2).run();
  MultiSendRecvBinaryTest(bigSizes, 2, 2).run();
}

TEST(TAsyncChannelTest, TestMultiSendRecvBinaryQueued) {
  typedef MultiSendRecvTest<TBinaryAsyncChannel> MultiSendRecvBinaryTest;

  //size below 1024 for each message
  MultiMessageSize sizes(911, 911, 911, -1);

  // each time send one whole message below 1024
  MultiSendRecvBinaryTest(sizes, 3, true, milliseconds(0)).run();
  MultiSendRecvBinaryTest(sizes, 3, true, milliseconds(2)).run();

  // send all messages for one time
  MultiSendRecvBinaryTest(sizes, 1, true, milliseconds(0)).run();

  // each time send one and half message.
  MultiSendRecvBinaryTest(sizes, 2, true).run();
  MultiSendRecvBinaryTest(sizes, 2, true, milliseconds(2)).run();

  //size above 1024 for each message
  MultiMessageSize bigSizes(1911 * 1911,
                            1911 * 1911,
                            1911 * 1911,
                            -1);

  // each time send one whole message above 1024
  MultiSendRecvBinaryTest(bigSizes, 3, true, milliseconds(0)).run();
  MultiSendRecvBinaryTest(bigSizes, 3, true, milliseconds(2)).run();

  // send all messages for one time
  MultiSendRecvBinaryTest(bigSizes, 1, true, milliseconds(0)).run();

  // each time send one and half message
  MultiSendRecvBinaryTest(bigSizes, 2, true).run();
  MultiSendRecvBinaryTest(bigSizes, 2, true, milliseconds(2)).run();
}

TEST(TAsyncChannelTest, TestMultiSendRecvFramed) {
  typedef MultiSendRecvTest<TFramedAsyncChannel> MultiSendRecvFramedTest;

  //size below 1024 for each message
  MultiMessageSize sizes(911, 911, 911, -1);

  // each time send one whole message below 1024
  MultiSendRecvFramedTest(sizes, 3, 0).run();
  MultiSendRecvFramedTest(sizes, 3, 2).run();

  // send all messages for one time
  MultiSendRecvFramedTest(sizes, 1, 0).run();

  // each time send one and half message.
  MultiSendRecvFramedTest(sizes, 2).run();
  MultiSendRecvFramedTest(sizes, 2, 2).run();

  //size above 1024 for each message
  MultiMessageSize bigSizes(1911 * 1911,
                            1911 * 1911,
                            1911 * 1911,
                            -1);

  // each time send one whole message above 1024
  MultiSendRecvFramedTest(bigSizes, 3, 0).run();
  MultiSendRecvFramedTest(bigSizes, 3, 2).run();

  // send all messages for one time
  MultiSendRecvFramedTest(bigSizes, 1, 0).run();

  // each time send one and half message
  MultiSendRecvFramedTest(bigSizes, 2).run();
  MultiSendRecvFramedTest(bigSizes, 2, 2).run();
}

TEST(TAsyncChannelTest, TestMultiSendRecvFramedQueued) {
  typedef MultiSendRecvTest<TFramedAsyncChannel> MultiSendRecvBinaryTest;

  //size below 1024 for each message
  MultiMessageSize sizes(911, 911, 911, -1);

  // each time send one whole message below 1024
  MultiSendRecvBinaryTest(sizes, 3, true, milliseconds(0)).run();
  MultiSendRecvBinaryTest(sizes, 3, true, milliseconds(2)).run();

  // send all messages for one time
  MultiSendRecvBinaryTest(sizes, 1, true, milliseconds(0)).run();

  // each time send one and half message.
  MultiSendRecvBinaryTest(sizes, 2, true).run();
  MultiSendRecvBinaryTest(sizes, 2, true, milliseconds(2)).run();

  //size above 1024 for each message
  MultiMessageSize bigSizes(1911 * 1911,
                            1911 * 1911,
                            1911 * 1911,
                            -1);

  // each time send one whole message above 1024
  MultiSendRecvBinaryTest(bigSizes, 3, true, milliseconds(0)).run();
  MultiSendRecvBinaryTest(bigSizes, 3, true, milliseconds(2)).run();

  // send all messages for one time
  MultiSendRecvBinaryTest(bigSizes, 1, true, milliseconds(0)).run();

  // each time send one and half message
  MultiSendRecvBinaryTest(bigSizes, 2, true).run();
  MultiSendRecvBinaryTest(bigSizes, 2, true, milliseconds(2)).run();
}

const int kRecvDelay = 200;
const int kTimeout = 50;

template<typename ChannelT>
class TimeoutQueuedTest : public SocketPairTest<ChannelT> {
 public:

  explicit TimeoutQueuedTest(int n_msgs = 3)
      : n_msgs_(n_msgs)
      , start_(false)
      , msg_(911) {
  }

  void preLoop() {

    this->channel1_->setRecvTimeout(kRecvDelay * n_msgs_ + kTimeout);

    for (int i = 0; i < n_msgs_; i++ ) {
      // queue some reads 200ms apart
      this->eventBase_.runAfterDelay(
        std::bind(&TimeoutQueuedTest<ChannelT>::recvMe, this),
        kRecvDelay * i);
    }

    this->eventBase_.runAfterDelay(
      std::bind(&TimeoutQueuedTest<ChannelT>::sendMe, this),
      kRecvDelay * n_msgs_);

  }

  void sendMe() {
    // Send one message to test that the timeout for queued reads
    // adjusts based time recv was called.  Also tests that all queued
    // readers receive errors on the first timeout
    msg_.copyTo(&sendBuf_);
    sendCallback_.send(this->channel0_, &sendBuf_);
    start_.reset();
  }

  void recvMe() {
    recvCallback_.recv(this->channel1_, &readMemoryBuffer_);
  }

  void postLoop() {
    CHECK_EQ(recvCallback_.getRecvError(), 2);
    CHECK_EQ(recvCallback_.getRecvDone(), 1);

    T_CHECK_TIMEOUT(start_, recvCallback_.getTimestamp(),
                    milliseconds(n_msgs_ * kRecvDelay + kTimeout));
  }

 private:
  uint32_t n_msgs_;
  TimePoint start_;
  Message msg_;
  TMemoryBuffer sendBuf_;
  TMemoryBuffer readMemoryBuffer_;
  ChannelCallback sendCallback_;
  ChannelCallback recvCallback_;
};

TEST(TAsyncChannelTest, TestTimeoutQueued) {
  TimeoutQueuedTest<TFramedAsyncChannel>().run();
  TimeoutQueuedTest<TBinaryAsyncChannel>().run();
}

template<typename ChannelT>
class RecvChunksTest : public SocketPairTest<ChannelT> {
 public:
  explicit RecvChunksTest(const ChunkSchedule& schedule,
                          milliseconds timeout = milliseconds(0),
                          uint32_t msgLen = 1024*1024)
    : start_(false)
    , timeout_(timeout)
    , msg_(msgLen, NeedsFrame<ChannelT>::value())
    , sender_(&this->eventBase_, this->socket0_.get(), &msg_, schedule) {
  }

  void preLoop() {
    if (timeout_ > milliseconds(0)) {
      this->channel1_->setRecvTimeout(timeout_.count());
    }
    start_.reset();
    recvCallback_.recv(this->channel1_, &recvBuf_);
    sender_.start();
  }

  void postLoop() {
    bool expectTimeout = false;
    milliseconds expectedMS = milliseconds(0);
    milliseconds tolerance = milliseconds(0);
    uint32_t expectedBytes = 0;
    for (ChunkSchedule::const_iterator it = sender_.getSchedule()->begin();
         it != sender_.getSchedule()->end();
         ++it) {
      // Allow 2ms of processing overhead for every scheduled event.
      tolerance += milliseconds(2);

      if (milliseconds(0) < timeout_ && timeout_ < it->delayMS) {
        // We expect to time out waiting for this chunk of data
        expectedMS += timeout_;
        expectTimeout = true;
        break;
      }

      expectedMS += it->delayMS;
      if (it->bytes < 0) {
        // The full message should be written
        expectedBytes = msg_.getLength();
      } else {
        expectedBytes += it->bytes;
      }
    }

    // Unframed transports require many more read callbacks to fully read the
    // data.  Add extra tolerance for the overhead in this case.
    //
    // The number of calls is roughly log(size/4096) / log(1.5)
    // (Since the code starts with an initial buffer size of 4096, and grows by
    // a factor of 1.5 each time it reallocates.)  Add an extra millisecond of
    // tolerance for every expected call.
    if (!NeedsFrame<ChannelT>::value() && expectedBytes > 4096) {
      double numCalls = log(expectedBytes / 4096) / log(1.5);
      printf("expected %f calls for %u bytes\n", numCalls, expectedBytes);
      tolerance += milliseconds(static_cast<int64_t>(numCalls));
    }

    if (expectTimeout) {
      // We should time out after expectedMS
      LOG(INFO) << "RecvChunksTest: testing for timeout";
      CHECK_EQ(sender_.error(), true);
      CHECK_EQ(recvCallback_.getRecvError(), 1);
      CHECK_EQ(recvCallback_.getRecvDone(), 0);
      CHECK_EQ(this->channel1_->timedOut(), true);
      CHECK_EQ(this->channel1_->error(), true);
      CHECK_EQ(this->channel1_->good(), false);

      T_CHECK_TIMEOUT(start_, recvCallback_.getTimestamp(), expectedMS,
                      tolerance);
    } else if (expectedBytes == 0) {
      // We should get EOF after expectedMS, before any data was ever sent
      //
      // This seems like a weird special case.  TAsyncChannel calls the normal
      // callback in this case, even though no message was received.  Maybe we
      // should consider changing this TAsyncChannel behavior?
      LOG(INFO) << "RecvChunksTest: testing for EOF with no data";
      CHECK_EQ(sender_.error(), false);
      CHECK_EQ(recvCallback_.getRecvError(), 0);
      CHECK_EQ(recvCallback_.getRecvDone(), 1);
      CHECK_EQ(this->channel1_->timedOut(), false);
      CHECK_EQ(this->channel1_->error(), false);
      CHECK_EQ(this->channel1_->good(), false);
      CHECK_EQ(recvBuf_.available_read(), 0);

      T_CHECK_TIMEOUT(start_, recvCallback_.getTimestamp(), expectedMS,
                      tolerance);
    } else if (expectedBytes < msg_.getLength()) {
      // We should get EOF after expectedMS
      LOG(INFO) << "RecvChunksTest: testing for EOF";
      CHECK_EQ(sender_.error(), false);
      CHECK_EQ(recvCallback_.getRecvError(), 1);
      CHECK_EQ(recvCallback_.getRecvDone(), 0);
      CHECK_EQ(this->channel1_->timedOut(), false);
      CHECK_EQ(this->channel1_->error(), false);
      CHECK_EQ(this->channel1_->good(), false);

      T_CHECK_TIMEOUT(start_, recvCallback_.getTimestamp(), expectedMS,
                      tolerance);
    } else {
      // We expect success after expectedMS
      LOG(INFO) << "RecvChunksTest: testing for success";
      CHECK_EQ(sender_.error(), false);
      CHECK_EQ(recvCallback_.getRecvError(), 0);
      CHECK_EQ(recvCallback_.getRecvDone(), 1);
      CHECK_EQ(this->channel1_->timedOut(), false);
      CHECK_EQ(this->channel1_->error(), false);
      CHECK_EQ(this->channel1_->good(), true);
      msg_.checkEqual(&recvBuf_);

      T_CHECK_TIMEOUT(start_, recvCallback_.getTimestamp(), expectedMS,
                      tolerance);
    }
  }

 private:
  TimePoint start_;
  milliseconds timeout_;
  Message msg_;
  ChunkSender sender_;
  TMemoryBuffer recvBuf_;
  ChannelCallback recvCallback_;
};

TEST(TAsyncChannelTest, TestRecvFrameChunks) {
  typedef RecvChunksTest<TFramedAsyncChannel> RecvFrameTest;

  // The frame header is 4 bytes.  Test sending each byte separately,
  // 5ms apart, followed by the body.
  ChunkSchedule s1(1, milliseconds(5),
                   1, milliseconds(5),
                   1, milliseconds(5),
                   1, milliseconds(5),
                   100, milliseconds(10),
                   -1, milliseconds(10));
  // Test reading the whole message
  RecvFrameTest(s1).run();
  // Setting the timeout to 15ms should still succeed--the code only times out
  // if no data is received for the specified period
  RecvFrameTest(s1, milliseconds(15)).run();

  // Test timing out before any data is sent
  RecvFrameTest(ChunkSchedule(-1, milliseconds(50)),
                milliseconds(20)).run();
  // Test timing out after part of the frame header is sent
  RecvFrameTest(ChunkSchedule(2, milliseconds(10),
                              -1, milliseconds(50)),
                milliseconds(20)).run();
  // Test timing out after the frame header is sent
  RecvFrameTest(ChunkSchedule(4, milliseconds(10),
                              -1, milliseconds(50)),
                milliseconds(20)).run();
  // Test timing out after part of the body is snet
  RecvFrameTest(ChunkSchedule(100, milliseconds(10),
                              -1, milliseconds(50)),
                milliseconds(20)).run();

  // Test closing the connection before any data is sent
  RecvFrameTest(ChunkSchedule(0, milliseconds(5))).run();
  // Test closing the connection after part of the frame header is sent
  RecvFrameTest(ChunkSchedule(2, milliseconds(10),
                              0, milliseconds(5))).run();
  // Test closing the connection after the frame header is sent
  RecvFrameTest(ChunkSchedule(4, milliseconds(10),
                              0, milliseconds(5))).run();
  // Test closing the connection after part of the body is snet
  RecvFrameTest(ChunkSchedule(100, milliseconds(10),
                              0, milliseconds(5))).run();

  // Some various other schedules
  RecvFrameTest(ChunkSchedule(1, milliseconds(10),
                              1, milliseconds(10),
                              100, milliseconds(10),
                              -1, milliseconds(5))).run();
}

TEST(TAsyncChannelTest, TestRecvBinaryChunks) {
  typedef RecvChunksTest<TBinaryAsyncChannel> RecvBinaryTest;

  // Test sending the first four bytes byte separately,
  // 5ms apart, followed by the rest of the message.
  ChunkSchedule s1(1, milliseconds(5),
                   1, milliseconds(5),
                   1, milliseconds(5),
                   1, milliseconds(5),
                   100, milliseconds(10),
                   -1, milliseconds(10));
  // Test reading the whole message
  RecvBinaryTest(s1).run();
  // Setting the timeout to 15ms should still succeed--the code only times out
  // if no data is received for the specified period
  RecvBinaryTest(s1, milliseconds(15)).run();

  // Test timing out before any data is sent
  RecvBinaryTest(ChunkSchedule(-1, milliseconds(50)),
                 milliseconds(20)).run();
  // Test timing out after part of the frame header is sent
  RecvBinaryTest(ChunkSchedule(2, milliseconds(10),
                               -1, milliseconds(50)),
                 milliseconds(20)).run();
  // Test timing out after the frame header is sent
  RecvBinaryTest(ChunkSchedule(4, milliseconds(10),
                               -1, milliseconds(50)),
                 milliseconds(20)).run();
  // Test timing out after part of the body is snet
  RecvBinaryTest(ChunkSchedule(100, milliseconds(10),
                               -1, milliseconds(50)),
                 milliseconds(20)).run();

  // Test closing the connection before any data is sent
  RecvBinaryTest(ChunkSchedule(0, milliseconds(5))).run();
  // Test closing the connection after sending 4 bytes
  RecvBinaryTest(ChunkSchedule(2, milliseconds(10),
                               0, milliseconds(5))).run();
  // Test closing the connection after sending 100 bytes
  RecvBinaryTest(ChunkSchedule(100, milliseconds(10),
                               0, milliseconds(5))).run();

  // Some various other schedules
  RecvBinaryTest(ChunkSchedule(1, milliseconds(10),
                               1, milliseconds(10),
                               100, milliseconds(10),
                               -1, milliseconds(5))).run();
}

template<typename ChannelT>
class SendTimeoutTest : public SocketPairTest<ChannelT> {
 public:
  explicit SendTimeoutTest(milliseconds timeout)
    : timeout_(timeout)
    , start_(false)
    , msg_(1024*1024) {
  }

  void preLoop() {
    this->socket0_->setSendTimeout(timeout_.count());
    msg_.copyTo(&sendBuf_);
    sendCallback_.send(this->channel0_, &sendBuf_);
    // don't receive on the other socket

    start_.reset();
  }

  void postLoop() {
    CHECK_EQ(sendCallback_.getSendError(), 1);
    CHECK_EQ(sendCallback_.getSendDone(), 0);
    T_CHECK_TIMEOUT(start_, sendCallback_.getTimestamp(), timeout_);
  }

 private:
  milliseconds timeout_;
  TimePoint start_;
  Message msg_;
  TMemoryBuffer sendBuf_;
  ChannelCallback sendCallback_;
};

TEST(TAsyncChannelTest, TestSendTimeoutFramed) {
  SendTimeoutTest<TFramedAsyncChannel>(milliseconds(25)).run();
  SendTimeoutTest<TFramedAsyncChannel>(milliseconds(100)).run();
  SendTimeoutTest<TFramedAsyncChannel>(milliseconds(250)).run();
}

TEST(TAsyncChannelTest, TestSendTimeoutBinary) {
  SendTimeoutTest<TBinaryAsyncChannel>(milliseconds(25)).run();
  SendTimeoutTest<TBinaryAsyncChannel>(milliseconds(100)).run();
  SendTimeoutTest<TBinaryAsyncChannel>(milliseconds(250)).run();
}

template<typename ChannelT>
class SendClosedTest : public SocketPairTest<ChannelT> {
 public:
  explicit SendClosedTest(milliseconds closeTimeout = milliseconds(5))
    : closeTimeout_(closeTimeout)
    , start_(false)
    , msg_(1024*1024) {
  }

  void preLoop() {
    msg_.copyTo(&sendBuf_);
    sendCallback_.send(this->channel0_, &sendBuf_);

    // Close the other socket after 25ms
    this->eventBase_.runAfterDelay(
        std::bind(&TAsyncSocket::close, this->socket1_.get()),
        closeTimeout_.count());

    start_.reset();
  }

  void postLoop() {
    CHECK_EQ(sendCallback_.getSendError(), 1);
    CHECK_EQ(sendCallback_.getSendDone(), 0);
    T_CHECK_TIMEOUT(start_, sendCallback_.getTimestamp(), closeTimeout_);
  }

 private:
  milliseconds closeTimeout_;
  TimePoint start_;
  Message msg_;
  TMemoryBuffer sendBuf_;
  ChannelCallback sendCallback_;
};

TEST(TAsyncChannelTest, TestSendClosed) {
  SendClosedTest<TFramedAsyncChannel>().run();
  SendClosedTest<TBinaryAsyncChannel>().run();
}

max_stars_repo_name: jesboat/fbthrift

max_issues_repo_name: jesboat/fbthrift

max_forks_repo_name: jesboat/fbthrift


text: #include <boost/mpl/remove_if.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include <iostream>
#include <entityplus/entity.h>

#include <boost/variant/get.hpp>
#include <common/EntityComponentSystem.h>

#include "doctest.h"

// Pripadne abychom je synchronizovali.
TEST_CASE("Entity component system") {
	using ECS = BaseEntityComponentSystem<int, float>;
	using Entity = ECS::entity_t;
	ECS ecs;
	Entity e = ecs.entityManager.create_entity(int(5));
	e.add_component<float>(4.2f);
	CHECK(e.get_component<int>() == 5);
	CHECK(e.get_component<float>() == 4.2f);

	// Copy all components
	auto all = ECS::all_components(e);
	CHECK(all.size() == 2);
	Entity e2 = ecs.entityManager.create_entity();
	ECS::add_component(e2, all[0]);
	ECS::add_component(e2, all[1]);
	CHECK(e2.get_status() == entityplus::entity_status::OK);
	CHECK(e2.get_component<int>() == 5);
	CHECK(e2.get_component<float>() == 4.2f);

	// Modify one of them and update it back
	e2.get_component<float>() = 3.14f;
	ECS::update_components(e, ECS::all_components(e2));
	CHECK(e.get_component<float>() == 3.14f);
}

TEST_CASE("Entities: add existing component") {
	using ECS = BaseEntityComponentSystem<int, float>;
	using Entity = ECS::entity_t;
	ECS ecs;
	Entity e = ecs.entityManager.create_entity(int(5));
#if 0
	e.add_component<int>(6);
	e.sync();
#else
	e.get_component<int>() = 6;
#endif
	CHECK(e.get_component<int>() == 6);

}


text: #include <boost/spirit/home/x3/string/symbols.hpp>


text:
#include "AinurState.h"
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>

namespace PsimagLite {

template<typename T>
boost::spirit::qi::rule<std::string::iterator,
std::vector<T>(),
boost::spirit::qi::space_type>
ruleRows();

template<>
boost::spirit::qi::rule<std::string::iterator,
std::vector<double>(),
boost::spirit::qi::space_type>
ruleRows<double>()
{
	return "[" >> -(boost::spirit::double_ % ",") >> "]";
}

template<>
boost::spirit::qi::rule<std::string::iterator,
std::vector<SizeType>(),
boost::spirit::qi::space_type>
ruleRows<SizeType>()
{
	return "[" >> -(boost::spirit::int_ % ",") >> "]";
}

//---------
template<typename T>
boost::spirit::qi::rule<std::string::iterator,
T(),
boost::spirit::qi::space_type>
ruleElipsis();

template<>
boost::spirit::qi::rule<std::string::iterator,
double(),
boost::spirit::qi::space_type>
ruleElipsis<double>()
{
	return  "[" >> boost::spirit::double_  >> "," >> "..." >> "]";
}

template<>
boost::spirit::qi::rule<std::string::iterator,
SizeType(),
boost::spirit::qi::space_type>
ruleElipsis<SizeType>()
{
	return "[" >> boost::spirit::int_ >> "," >> "..." >> "]";
}

void AinurState::assign(String k, String v)
{
	int x = storageIndexByName(k);
	if (x < 0)
		err(errLabel(ERR_PARSE_UNDECLARED, k));

	assert(static_cast<SizeType>(x) < values_.size());
	values_[x] = v;
}

template <typename T>
template <typename A, typename ContextType>
typename EnableIf<!TypesEqual<std::vector<std::vector<T> >, A>::True,void>::Type
AinurState::ActionMatrix<T>::operator()(A& attr,
                                        ContextType&,
                                        bool&) const
{
	err("Ainur: Not sure how to handle this\n");
}

template <typename T>
template <typename A, typename ContextType>
typename EnableIf<TypesEqual<std::vector<std::vector<T> >, A>::True,void>::Type
AinurState::ActionMatrix<T>::operator()(A& attr,
                                        ContextType&,
                                        bool&) const
{
	SizeType rows = attr.size();
	if (rows == 0) return;
	SizeType cols = attr[0].size();
	t_.resize(rows, cols);
	for (SizeType i = 0; i < rows; ++i) {
		if (attr[i].size() != cols)
			err("Ainur: Problem reading matrix\n");
		for (SizeType j = 0; j < cols; ++j)
			t_(i, j) = attr[i][j];
	}
}

template <typename T>
template <typename A, typename ContextType>
typename EnableIf<TypesEqual<A,T>::True,void>::Type
AinurState::Action<T>::operator()(A& attr,
                                  ContextType&,
                                  bool&) const
{
	if (name_ == "elipsis") {
		SizeType total = t_.size();
		if (total == 0)
			err("Elipsis cannot be used for this vector, because size is unknown\n");

		for (SizeType i = 0; i < total; ++i)
			t_[i] = attr;
		return;
	}

	t_.push_back(attr);
}

template <typename T>
template <typename A, typename ContextType>
typename EnableIf<!TypesEqual<A,T>::True, void>::Type
AinurState::Action<T>::operator()(A& attr,
                                  ContextType&,
                                  bool&) const
{
	t_ = attr;
}

template <typename A, typename ContextType>
typename EnableIf<TypesEqual<A, double>::True, void>::Type
AinurState::ActionCmplx::operator()(A& attr,
                                         ContextType&,
                                         bool&) const
{
	if (name_ == "rows2")
		t_.push_back(std::complex<double>(0.0, attr));
	else if (name_ == "rows3")
		t_.push_back(attr);
	else
		err("Error parsing complex number\n");
}

template <typename A, typename ContextType>
typename EnableIf<!TypesEqual<A, double>::True, void>::Type
AinurState::ActionCmplx::operator()(A& attr,
                                         ContextType&,
                                         bool&) const
{
	if (name_ == "rows1") {
		t_.push_back(std::complex<double>(
		                 boost::fusion::at_c<0>(attr),
		                 boost::fusion::at_c<1>(attr)));
	} else {
		err("Error parsing complex number\n");
	}
}

template<typename T>
void AinurState::convertInternal(Matrix<T>& t,
                                 String value,
                                 typename EnableIf<Loki::TypeTraits<T>::isArith,
                                 int>::Type) const
{
	namespace qi = boost::spirit::qi;
	typedef std::string::iterator IteratorType;
	typedef std::vector<T> LocalVectorType;
	typedef std::vector<LocalVectorType> LocalVectorVectorType;

	IteratorType it = value.begin();
	qi::rule<IteratorType, LocalVectorType(), qi::space_type> ruRows = ruleRows<T>();

	qi::rule<IteratorType, LocalVectorVectorType(), qi::space_type> full =
	        "[" >> -(ruRows  % ",") >> "]";

	ActionMatrix<T> actionMatrix("matrix", t);
	bool r = qi::phrase_parse(it,
	                          value.end(),
	                          full [actionMatrix],
	                          qi::space);

	//check if we have a match
	if (!r)
		err("matrix parsing failed\n");

	if (it != value.end())
		std::cerr << "matrix parsing: unmatched part exists\n";
}

template<typename T>
void AinurState::convertInternal(std::vector<T>& t,
                                 String value,
                                 typename EnableIf<Loki::TypeTraits<T>::isArith,
                                 int>::Type) const
{
	namespace qi = boost::spirit::qi;
	typedef std::string::iterator IteratorType;
	typedef std::vector<T> LocalVectorType;

	IteratorType it = value.begin();
	qi::rule<IteratorType, LocalVectorType(), qi::space_type> ruRows = ruleRows<T>();
	qi::rule<IteratorType, T(), qi::space_type> ruElipsis = ruleElipsis<T>();

	Action<T> actionRows("rows", t);
	Action<T> actionElipsis("elipsis", t);

	bool r = qi::phrase_parse(it,
	                          value.end(),
	                          ruRows [actionRows] | ruElipsis[actionElipsis],
	                          qi::space);

	//check if we have a match
	if (!r)
		err("vector parsing failed\n");

	if (it != value.end())
		std::cerr << "vector parsing: unmatched part exists\n";
}

template<typename T>
void AinurState::convertInternal(std::vector<std::complex<T> >& t,
                                 String value,
                                 typename EnableIf<Loki::TypeTraits<T>::isArith,
                                 int>::Type) const
{
	namespace qi = boost::spirit::qi;
	ActionCmplx actionRows1("rows1", t);
	ActionCmplx actionRows2("rows2", t);
	ActionCmplx actionRows3("rows3", t);
#define MY_COMPLEX (qi::double_ >> qi::double_ >>  "i") [actionRows1] | (qi::double_ >> "i") [actionRows2] | qi::double_ [actionRows3]

	typedef BOOST_TYPEOF(MY_COMPLEX) OneType;
	typedef std::string::iterator IteratorType;

	IteratorType it = value.begin();

	OneType cmplxN =  MY_COMPLEX;
#define MY_V_OF_COMPLEX "[" >> -(cmplxN  % ",") >> "]"
	typedef BOOST_TYPEOF(MY_V_OF_COMPLEX) ManyTypes;
	ManyTypes ruRows = MY_V_OF_COMPLEX;
	//	qi::rule<IteratorType, std::complex<T>(), qi::space_type> ruElipsis =
	//	        ruleElipsis<std::complex<T> >();

	//Action<std::complex<T> > actionElipsis("elipsis", t);

	bool r = qi::phrase_parse(it,
	                          value.end(),
	                          ruRows,// | ruElipsis[actionElipsis],
	                          qi::space);

	//check if we have a match
	if (!r)
		err("vector parsing failed\n");

	if (it != value.end())
		std::cerr << "vector parsing: unmatched part exists\n";
}

template void AinurState::convertInternal(Matrix<double>&,String, int) const;

template void AinurState::convertInternal(std::vector<double>&, String, int) const;
template void AinurState::convertInternal(std::vector<SizeType>&, String, int) const;

template void AinurState::convertInternal(std::vector<std::complex<double> >&,
String, int) const;
} // namespace PsimagLite


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_FUNCTION_ILOG2_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_ILOG2_HPP_INCLUDED

#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{

  /*!
    @ingroup group-bitwise
    This function object returns the integer part of the base 2
    logarithm of the input.

    @par Header <boost/simd/function/ilog2.hpp>

    @par Note
    This function asserts for negative or null values.

    @see  twopower, exponent

    @par Example:

      @snippet ilog2.cpp ilog2

    @par Possible output:

      @snippet ilog2.txt ilog2

  **/
  as_integer_t<Value> ilog2(Value const& x);
} }
#endif

#include <boost/simd/function/scalar/ilog2.hpp>
#include <boost/simd/function/simd/ilog2.hpp>

#endif

max_stars_repo_name: SylvainCorlay/pythran

max_issues_repo_name: SylvainCorlay/pythran

max_forks_repo_name: SylvainCorlay/pythran


text:
//
// Copyright (c) 2021 Richard Hodges (hodges.r@gmail.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)
//
// Official repository: https://github.com/madmongo1/boost_channels
//

#ifndef BOOST_CHANNELS_INCLUDE_BOOST_CHANNELS_CONCEPTS_COMMON_REFERENCE_WITH_HPP
#define BOOST_CHANNELS_INCLUDE_BOOST_CHANNELS_CONCEPTS_COMMON_REFERENCE_WITH_HPP

#include <boost/channels/concepts/convertible_to.hpp>
#include <boost/channels/concepts/same_as.hpp>

#include <type_traits>

namespace boost::channels::concepts {
namespace detail {
// clang-format off
template < class T, class U >
concept SameHelper =
    std::is_same_v<T, U>;
// clang-format on
}   // namespace detail

// clang-format off
template < class T, class U >
concept same_as =
    detail::SameHelper<T, U> &&
    detail::SameHelper<U, T>;
// clang-format on

}   // namespace boost::channels::concepts

#endif   // BOOST_CHANNELS_INCLUDE_BOOST_CHANNELS_CONCEPTS_COMMON_REFERENCE_WITH_HPP


text:
// Copyright (c) 2006-2007 Michael B. Edwin Rickert
//
// 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 )
//
// $LastChangedBy$ - $LastChangedDate$
//
// Jan 15, 2007 - Replaced diamond exception trees
// Jan  9, 2007 - Added to SVN, cleaned up
// Oct 28, 2006 - Created

#include <industry/config.hpp>

#if !defined( INDUSTRY_OS_WINDOWS )
//Nothing

#elif defined( _MSC_VER ) && !defined( _MSC_EXTENSIONS )
#include <boost/preprocessor/stringize.hpp>
#pragma message( __FILE__ "(" BOOST_PP_STRINGIZE(__LINE__) ") : warning: industry/api/windows/* will not be compiled without language extensions (windows.h pukes)" )

#else
#include <industry/api/windows/registry/errors.hpp>

namespace industry {
	namespace api {
		namespace windows {
			void throw_error( LONG error ) {
				switch( error ) {
					case ERROR_SUCCESS:        return;
					case ERROR_ACCESS_DENIED:  throw access_error();
					case ERROR_FILE_NOT_FOUND: throw missing_error();
					default:                   throw windows::error();
				}
			}
			namespace registry {
				void throw_key_error( LONG error ) {
					switch ( error ) {
						case ERROR_SUCCESS:        return;
						case ERROR_ACCESS_DENIED:  throw key_access_error();
						case ERROR_FILE_NOT_FOUND: throw missing_key_error();
						default:                   throw_error( error );
					}
				}
				void throw_value_error( LONG error ) {
					switch ( error ) {
						case ERROR_SUCCESS:        return;
						case ERROR_ACCESS_DENIED:  throw value_access_error();
						case ERROR_FILE_NOT_FOUND: throw missing_value_error();
						default:                   throw_error( error );
					}
				}
			}
		}
	}
}
#endif //defined( INDUSTRY_OS_WINDOWS )

max_stars_repo_name: MaulingMonkey/libindustry

max_issues_repo_name: MaulingMonkey/libindustry

max_forks_repo_name: MaulingMonkey/libindustry


text:
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "DQMServices/Core/interface/DQMEDHarvester.h"
#include "FWCore/Framework/interface/Event.h"

#include "DQMServices/Core/interface/DQMStore.h"
#include "FWCore/ServiceRegistry/interface/Service.h"
#include "DQMServices/Core/interface/MonitorElement.h"

#include "FWCore/ParameterSet/interface/ParameterSet.h"

#include "FWCore/ServiceRegistry/interface/Service.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"

#include <set>
#include <string>
#include <vector>
#include <TPRegexp.h>
#include <cmath>
#include <climits>
#include <boost/tokenizer.hpp>
#include <boost/regex.hpp>

#include <TH1.h>
#include <TEfficiency.h>

using namespace edm;
using namespace std;

class HLTMuonRefMethod : public DQMEDHarvester {
public:
  explicit HLTMuonRefMethod(const edm::ParameterSet& set);
  ~HLTMuonRefMethod() override = default;
  ;

  void beginJob() override;
  void beginRun(const edm::Run&, const edm::EventSetup&) override;
  void dqmEndJob(DQMStore::IBooker&, DQMStore::IGetter&) override;

private:
  // DQMStore* theDQM;

  std::vector<std::string> subDirs_;
  std::vector<std::string> hltTriggers_;
  std::vector<std::string> efficiency_;
  std::vector<std::string> refEff_;
  std::string refTriggers_;

  std::string outputFileName_;

  void findAllSubdirectories(DQMStore::IBooker& ibooker,
                             DQMStore::IGetter& igetter,
                             const std::string& dir,
                             std::set<std::string>* myList,
                             const TString& pattern);
};

HLTMuonRefMethod::HLTMuonRefMethod(const edm::ParameterSet& pset) {
  using VPSet = std::vector<edm::ParameterSet>;
  using vstring = std::vector<std::string>;
  using elsc = boost::escaped_list_separator<char>;

  subDirs_ = pset.getUntrackedParameter<vstring>("subDirs");
  hltTriggers_ = pset.getUntrackedParameter<vstring>("hltTriggers");
  refTriggers_ = pset.getUntrackedParameter<string>("refTriggers");
  efficiency_ = pset.getUntrackedParameter<vstring>("efficiency");
  refEff_ = pset.getUntrackedParameter<vstring>("refEff");
}

void HLTMuonRefMethod::beginJob() {}

void HLTMuonRefMethod::dqmEndJob(DQMStore::IBooker& ibooker, DQMStore::IGetter& igetter) {
  using vstring = std::vector<std::string>;
  boost::regex metacharacters{"[\\^\\$\\.\\*\\+\\?\\|\\(\\)\\{\\}\\[\\]]"};
  boost::smatch what;

  // theDQM = 0;
  // theDQM = Service<DQMStore>().operator->();

  ibooker.cd();
  set<string> subDirSet;

  for (auto iSubDir = subDirs_.begin(); iSubDir != subDirs_.end(); ++iSubDir) {
    string subDir = *iSubDir;

    if (subDir[subDir.size() - 1] == '/')
      subDir.erase(subDir.size() - 1);

    if (boost::regex_search(subDir, what, metacharacters)) {
      const string::size_type shiftPos = subDir.rfind('/');
      const string searchPath = subDir.substr(0, shiftPos);
      const string pattern = subDir.substr(shiftPos + 1, subDir.length());
      //std::cout << "\n\n\n\nLooking for all subdirs of " << subDir << std::endl;

      findAllSubdirectories(ibooker, igetter, searchPath, &subDirSet, pattern);

    } else {
      subDirSet.insert(subDir);
    }
  }

  for (auto const& subDir : subDirSet) {
    for (unsigned int iEff = 0; iEff != efficiency_.size(); ++iEff) {
      string eff = efficiency_[iEff];

      // Getting reference trigger efficiency
      MonitorElement* refEff = igetter.get(subDir + "/" + refTriggers_ + "/" + refEff_[iEff]);

      if (!refEff)
        continue;

      // looping over all reference triggers
      for (auto iTrigger = hltTriggers_.begin(); iTrigger != hltTriggers_.end(); ++iTrigger) {
        string trig = *iTrigger;
        MonitorElement* trigEff = igetter.get(subDir + "/" + trig + "/" + eff);
        if (!trigEff)
          continue;
        TH1* hRef = refEff->getTH1();
        TH1* hTrig = trigEff->getTH1();
        TH1* hEff = (TH1*)hTrig->Clone(("eff_" + eff + "_ref").c_str());
        hEff->SetTitle("Efficiency obtained with reference method");
        TClass* myHistClass = hTrig->IsA();
        TString histClassName = myHistClass->GetName();

        if (histClassName == "TH1F") {
          for (int bin = 0; bin < hEff->GetNbinsX(); ++bin) {
            hEff->SetBinContent(bin + 1, hEff->GetBinContent(bin + 1) * hRef->GetBinContent(bin + 1));
            hEff->SetBinError(bin + 1,
                              hEff->GetBinContent(bin + 1) * hRef->GetBinError(bin + 1) +
                                  hEff->GetBinError(bin + 1) * hRef->GetBinContent(bin + 1));
          }
          ibooker.cd(subDir + "/" + trig);
          ibooker.book1D(hEff->GetName(), (TH1F*)hEff);

        } else if (histClassName == "TH2F") {
          for (int i = 0; i < hRef->GetXaxis()->GetNbins(); ++i) {
            for (int j = 0; j < hRef->GetYaxis()->GetNbins(); ++j) {
              int bin = hEff->GetBin(i + 1, j + 1);
              hEff->SetBinContent(bin, hRef->GetBinContent(i + 1, j + 1) * hTrig->GetBinContent(i + 1));
            }
          }
          ibooker.cd(subDir + "/" + trig);
          ibooker.book2D(hEff->GetName(), (TH2F*)hEff);
        } else {
          LogInfo("HLTMuonRefMethod") << "Histo class type << " << histClassName << " not implemented";
        }

        delete hEff;
      }
    }
  }
}

void HLTMuonRefMethod::beginRun(const edm::Run& run, const edm::EventSetup& c) {}

void HLTMuonRefMethod::findAllSubdirectories(DQMStore::IBooker& ibooker,
                                             DQMStore::IGetter& igetter,
                                             const std::string& dir,
                                             std::set<std::string>* myList,
                                             const TString& _pattern = TString("")) {
  TString pattern = _pattern;
  TPRegexp nonPerlWildcard("\\w\\*|^\\*");

  if (!igetter.dirExists(dir)) {
    LogError("DQMGenericClient") << " DQMGenericClient::findAllSubdirectories ==> Missing folder " << dir << " !!!";
    return;
  }
  if (pattern != "") {
    if (pattern.Contains(nonPerlWildcard))
      pattern.ReplaceAll("*", ".*");
    TPRegexp regexp(pattern);
    ibooker.cd(dir);
    vector<string> foundDirs = igetter.getSubdirs();
    for (auto iDir = foundDirs.begin(); iDir != foundDirs.end(); ++iDir) {
      TString dirName = iDir->substr(iDir->rfind('/') + 1, iDir->length());
      if (dirName.Contains(regexp))
        findAllSubdirectories(ibooker, igetter, *iDir, myList);
    }
  }
  //std::cout << "Looking for directory " << dir ;
  else if (igetter.dirExists(dir)) {
    //std::cout << "... it exists! Inserting it into the list ";
    myList->insert(dir);
    //std::cout << "... now list has size " << myList->size() << std::endl;
    ibooker.cd(dir);
    findAllSubdirectories(ibooker, igetter, dir, myList, "*");
  } else {
    //std::cout << "... DOES NOT EXIST!!! Skip bogus dir" << std::endl;

    LogInfo("DQMGenericClient") << "Trying to find sub-directories of " << dir << " failed because " << dir
                                << " does not exist";
  }
  return;
}

DEFINE_FWK_MODULE(HLTMuonRefMethod);

max_stars_repo_name: eric-moreno/cmssw

max_issues_repo_name: eric-moreno/cmssw

max_forks_repo_name: eric-moreno/cmssw


text:
/**
 * @file DynamicsOptimizer.hpp
 * @author Brahayam Ponton (brahayam.ponton@tuebingen.mpg.de)
 * @license License BSD-3-Clause
 * @copyright Copyright (c) 2019, New York University and Max Planck Gesellschaft.
 * @date 2019-10-08
 */

#pragma once

#include <string>
#include <vector>
#include <iostream>
#include <Eigen/Eigen>

#include <solver/interface/Solver.hpp>
#include <momentumopt/utilities/Clock.hpp>
#include <momentumopt/setting/PlannerSetting.hpp>
#include <momentumopt/kinopt/KinematicsState.hpp>
#include <momentumopt/cntopt/ContactPlanInterface.hpp>

namespace momentumopt {

  /**
   * Helper class to define a linear approximation of a friction cone.
   */
  struct FrictionCone
  {
    typedef Eigen::Matrix< double, 4, 3> ConeMat;
    void getCone(double fcoeff, FrictionCone::ConeMat& cone_mat)
    {
      if (fcoeff <= 0.001) { fcoeff = 0.001; }
      Eigen::Vector3d fconevec = Eigen::Vector3d(0.5*sqrt(2.0), 0.5*sqrt(2.0), -fcoeff); fconevec.normalize();
      Eigen::Matrix3d fconemat = Eigen::Matrix3d::Identity();
      double angle = 2*M_PI/4;
      fconemat(0,0) = cos(angle);    fconemat(0,1) = -sin(angle);
      fconemat(1,0) = sin(angle);    fconemat(1,1) =  cos(angle);
      for (int i=0; i<4; i++) {
        cone_mat.row(i) = fconevec;
        fconevec = fconemat * fconevec;
      }
    }
  };

  /*! main class of the dynamics optimization problem  */
  class DynamicsOptimizer
  {
    public:
      EIGEN_MAKE_ALIGNED_OPERATOR_NEW

    public:
      /*! default class constructor and destructor */
	  DynamicsOptimizer(){}
      ~DynamicsOptimizer(){}

      /**
       * function to initialize and configure the optimization
       * @param[in]  PlannerSetting               setting of planner configuration variables
       */
      void initialize(PlannerSetting& planner_setting);

      /**
       * function to parse equations and objective into optimization problem and attempt to find a solution
       * @param[in]  ini_state                    initial state of the robot
       * @param[in]  contact_plan                 container of contact sequence to be used for dynamics planning
       * @param[in]  kin_sequence                 kinematics sequence to be used as momentum tracking reference (can be zeros).
       * @param[in]  update_tracking_objective    changes weights from regulation to tracking of momentum in ref_sequence
       * @return     ExitCode                     flag that indicates the optimization result (for example: optimal, infeasible)
       */
      solver::ExitCode optimize(const DynamicsState& ini_state, ContactPlanInterface* contact_plan,
                                const KinematicsSequence& kin_sequence, bool update_tracking_objective = false);

      /**
       * this function gives access to the optimized motion plan
       * @return     DynamicsSequence             reference to dynamics sequence, which is a collection of dynamic states,
       *                                          each of which contains information about all variables, all end-effectors
       *                                          of the motion plan for one time step
       */
      DynamicsSequence& dynamicsSequence() { return dyn_sequence_; }
      const DynamicsSequence& dynamicsSequence() const { return dyn_sequence_; }

      /*! function to have access to time required to solve the optimization problem */
      const double& solveTime() const { return solve_time_; }

    private:
      /*! Getter and setter methods for getting the planner variables  */
      inline PlannerSetting& getSetting() { return *planner_setting_; }
      inline const PlannerSetting& getSetting() const { return *planner_setting_; }

      /*! helper functions for the optimization problem */
      const ContactType& contactType(int time_id, int eff_id) const;
      Eigen::Matrix3d contactRotation(int time_id, int eff_id) const;
      double contactLocation(int time_id, int eff_id, int axis_id) const;

      /**
       * function to initialize optimization variables: type [continuous or binary],
       * guess value [if any], upper and lower bounds for the variable
       */
      void initializeOptimizationVariables();

      /**
       * function to add each variable to the Model and assign a unique identifier
       * to it, to be used by the optimizer to construct the problem
       * @param[in]  opt_var                      helper optimization variable for model predictive control
       * @param[in]  model                        instance of solver interface to collect constraints, objective and solve problem
       * @param[in]  vars                         vector of optimization variables
       */
      void addVariableToModel(const solver::OptimizationVariable& opt_var, solver::Model& model, std::vector<solver::Var>& vars);

      /**
       * functions to update tracking objective for momentum from penalty to tracking
       * and attempt to find a solution to the optimization problem
       * @param[in]  ref_sequence                 dynamics sequence to be used as momentum tracking reference (can be zeros).
       * @param[in]  is_first_time                flag to indicate if this is the first time the solution is being constructed
       */
      void internalOptimize(const KinematicsSequence& kin_sequence, bool is_first_time = false);
      void updateTrackingObjective();

      /**
       * functions that transfers optimal solution from model to helper class OptimizationVariable,
       * from helper class OptimizationVariable to dynamics sequence to be accessed by the user, and
       * from dynamics sequence to a file.
       * @param[in]  opt_var                      helper optimization variable for model predictive control
       * @param[in]  ref_sequence                 dynamics sequence to be used as momentum tracking reference (can be zeros).
       */
      void saveSolution(solver::OptimizationVariable& opt_var);
      void storeSolution();
      void saveToFile(const KinematicsSequence& kin_sequence);

    private:
      /*! Variables required for optimization */
      PlannerSetting* planner_setting_;

      /**
       * class that stores all information about the problem, interfaces between high level definition
       * of the problem and its corresponding mathematical construction to solve it with a solver instance
       */
      solver::Model model_;

      /*! helper variables to construct linear and quadratic expressions */
      solver::LinExpr lin_cons_;
      solver::DCPQuadExpr quad_objective_, quad_cons_;

      /*! exit code of the optimization problem */
      solver::ExitCode exitcode_;

      /**
       * c++ vector containing all problem variables defined by the user. Does not include extra
       * variables required to write the problem in standard conic form.
       */
      std::vector<solver::Var> vars_;

      /**
       * initial configuration of the robot, including center of mass position, linear and angular momenta,
       * end-effectors configurations: activation, position, orientation
       */
      DynamicsState ini_state_;

      /*! simple helper class to build a linear approximation of a friction cone */
      FrictionCone friction_cone_;
      FrictionCone::ConeMat cone_matrix_;

      /**
       * dynamics sequence of dynamic states. This is the main interface between the user
       * and the planner. The user can find in this variable all the optimization results
       */
      DynamicsSequence dyn_sequence_;

      /**
       * helper class to store information about the contact plan, such as surfaces,
       * position and orientation of a sequence of contacts
       */
      ContactPlanInterface* contact_plan_;

      /*! clock for timing purposes */
      Clock timer_;

      /*! type for optimization variable: continuous 'C' or binary 'B' and type of heuristic */
      char variable_type_;

      /*! helper boolean variables for the optimization problem */
      bool has_converged_;

      /*! helper integer variables for the optimization problem */
      int size_, num_vars_;

      /*! helper double variables for the optimization problem */
      double solve_time_, convergence_err_, last_convergence_err_;

      /*! helper vector variables for the optimization problem */
      Eigen::Vector3d com_pos_goal_, weight_desired_com_tracking_;

      /*! helper optimization variables for the optimization problem */
      solver::OptimizationVariable dt_, com_, lmom_, amom_, lmomd_, amomd_;
      std::array<solver::OptimizationVariable, Problem::n_endeffs_> frc_world_, trq_local_, cop_local_, ub_var_, lb_var_;

      /*! helper matrices and vectors for the optimization problem */
      solver::OptimizationVariable::OptVector solution_;
      solver::OptimizationVariable::OptMatrix mat_lb_, mat_ub_, mat_guess_, com_guess_, lmom_guess_, amom_guess_;
  };

}

max_stars_repo_name: machines-in-motion/kino-dynamic-opt

max_forks_repo_name: machines-in-motion/kino-dynamic-opt


text:
#pragma once

#include <boost/multiprecision/gmp.hpp>
#include <math.h>
#include <time.h>

#include "FiniteFields.hpp"
#include "FastFourierTransform.hpp"

namespace ligero {
template <typename FieldT>
class 		SecretSharing {
	public:
		/* Constructors allowing some flexibility in the choice of domains */
		SecretSharing(size_t lSecretLength, size_t kDegree, size_t nShares) : lSecretLength_(lSecretLength), kDegree_(kDegree), nNumberShares_(nShares) {
			// In this implementation, we use an evaluation domain that is twice the size of the number of shares, and we discard
			this->dCompositeDomainSize_ = nShares;
		};

		int share(FieldT *secret);
		int reconstruct(FieldT *eval, bool expanded = false);

		int padMany(FieldT *secrets, size_t lrows);
		int padIntrablocRandomnessMany(FieldT *secret, size_t lrows);
		int shareMany(FieldT *secrets, size_t lrows);
		int reconstructMany(FieldT *secrets, size_t lrows);

		bool degreeTest(FieldT *eval);
		bool zeroTest(FieldT *eval, bool expanded = false);
		bool zeroSumTest(FieldT *eval);

	protected:
		int padSecret(FieldT *secret);
		int padPolynominal(FieldT *secret);
		int padShares(FieldT *secret);
		int padIntrablocRandomness(FieldT *secret);

		size_t	lSecretLength_;
		size_t	kDegree_;
		size_t	nNumberShares_;
		size_t	dCompositeDomainSize_;
		std::vector<FieldT> rootsOfUnity_;
};

template <typename FieldT>
int SecretSharing<FieldT>::padSecret(FieldT *secret) {
	FieldT::randomVector(secret + this->lSecretLength_, this->kDegree_ - this->lSecretLength_, true);
	return 0;
}

template <typename FieldT>
int SecretSharing<FieldT>::padIntrablocRandomness(FieldT *secret) {
	for (size_t i = this->lSecretLength_; i < kDegree_ ;i++) {
		secret[i] = FieldT(0);
	}

	return 0;
}

template <typename FieldT>
int SecretSharing<FieldT>::padPolynominal(FieldT *secret) {
	for (size_t i = this->kDegree_; i < nNumberShares_;i++) {
		secret[i] = FieldT(0);
	}

	return 0;
}

template <typename FieldT>
int SecretSharing<FieldT>::padShares(FieldT *secret) {
	for (size_t i = this->nNumberShares_; i < dCompositeDomainSize_ ;i++) {
		secret[i] = FieldT(0);
	}

	return 0;
}

template <typename FieldT>
int SecretSharing<FieldT>::padMany(FieldT *secret, size_t lrows) {

	// Add randomness for padding
	for (size_t i = 0; i < lrows; i++) {
		this->padSecret(secret + i * this->nNumberShares_);
	}

	return 0;
}

template <typename FieldT>
int SecretSharing<FieldT>::padIntrablocRandomnessMany(FieldT *secret, size_t lrows) {

	// Add randomness for padding
	for (size_t i = 0; i < lrows; i++) {
		this->padIntrablocRandomness(secret + i * this->nNumberShares_);
	}

	return 0;
}

template <typename FieldT>
int SecretSharing<FieldT>::share(FieldT *secret) {

	// Interpolate a polynomial of degree k for the secret
    iFFT<FieldT>(secret, kDegree_, rootsOfUnity_);

	// Evaluate the polynomial on a coset within the composite domain (size numberShares)
	this->padPolynominal(secret);
	FFT<FieldT>(secret, nNumberShares_, FieldT(FieldT::getOmega(nNumberShares_)), rootsOfUnity_);

	return 0;
}

template <typename FieldT>
inline int SecretSharing<FieldT>::reconstruct(FieldT *eval, bool expandedDegree) {
	size_t degree = kDegree_;
	iFFT<FieldT>(eval, nNumberShares_, FieldT(FieldT::getOmega(nNumberShares_)), rootsOfUnity_);

	if (expandedDegree) {
		for (size_t i = 0; i < kDegree_; i++) {eval[i] = eval[i] + eval[i + kDegree_];}
	}

    FFT<FieldT>(eval, degree, rootsOfUnity_);

	return 0;
}

template <typename FieldT>
bool SecretSharing<FieldT>::degreeTest(FieldT *eval) {

	std::vector<FieldT> localCopy(eval, eval + this->nNumberShares_);
	iFFT<FieldT>(&localCopy[0], nNumberShares_, FieldT::getOmega(nNumberShares_), rootsOfUnity_);

	for (size_t i = kDegree_; i < nNumberShares_; i++) {
		if (!(localCopy[i] == FieldT(0))) {
			DBG("val:"<< localCopy[i].getValue() << ",degree>" << i);
			return false;
		}
	}

	return true;
}

template <typename FieldT>
bool SecretSharing<FieldT>::zeroTest(FieldT *eval, bool largerDegree) {

	std::vector<FieldT> localCopy(eval, eval + this->nNumberShares_);
	reconstruct(&localCopy[0], largerDegree);

	for (size_t i = 0; i < this->lSecretLength_; i++) {
		if (!(localCopy[i] == FieldT(0))) return false;
	}

	return true;
}

template <typename FieldT>
bool SecretSharing<FieldT>::zeroSumTest(FieldT *eval) {

	std::vector<FieldT> localCopy(eval, eval+ this->nNumberShares_);
	reconstruct(&localCopy[0], true);

	FieldT sum = FieldT(0);
	for (size_t i = 0; i < this->lSecretLength_; i++) {
		sum += localCopy[i];
	}

	if (sum == FieldT(0)) return true;
	else return false;
}

template <typename FieldT>
int SecretSharing<FieldT>::shareMany(FieldT *secret, size_t lrows) {

	// std::cout << "Performing FFTs: " << lrows << std::endl;
	for (size_t i = 0; i < lrows; i++) {
		share(secret + i * this->nNumberShares_);
	}

	return 0;
}

template <typename FieldT>
int SecretSharing<FieldT>::reconstructMany(FieldT *secret, size_t lrows) {

	for (size_t i = 0; i < lrows; i++) {
		reconstruct(secret + i * this->nNumberShares_);
	}

	return 0;
}

}

max_stars_repo_name: Eleven-Z/LigeroRSA

max_issues_repo_name: Eleven-Z/LigeroRSA

max_forks_repo_name: Eleven-Z/LigeroRSA


text:
#include <cradle/thinknode/iss.h>

#include <cstring>

#include <boost/format.hpp>

#include <cppcoro/sync_wait.hpp>

#include <cradle/core/monitoring.h>
#include <cradle/encodings/msgpack.h>
#include <cradle/io/mock_http.h>
#include <cradle/service/core.h>
#include <cradle/utilities/testing.h>

using namespace cradle;

TEST_CASE("ISS object resolution", "[thinknode][iss]")
{
    service_core service;
    init_test_service(service);

    auto& mock_http = enable_http_mocking(service);
    mock_http.set_script(
        {{make_get_request(
              "https://mgh.thinknode.io/api/v1.0/iss/abc/"
              "immutable?context=123"
              "&ignore_upgrades=false",
              {{"Authorization", "Bearer xyz"},
               {"Accept", "application/json"}}),
          make_http_200_response("{ \"id\": \"def\" }")}});

    thinknode_session session;
    session.api_url = "https://mgh.thinknode.io/api/v1.0";
    session.access_token = "xyz";

    auto id = cppcoro::sync_wait(resolve_iss_object_to_immutable(
        service, session, "123", "abc", false));
    REQUIRE(id == "def");

    REQUIRE(mock_http.is_complete());
    REQUIRE(mock_http.is_in_order());
}

TEST_CASE("ISS object metadata", "[thinknode][iss]")
{
    service_core service;
    init_test_service(service);

    auto& mock_http = enable_http_mocking(service);
    mock_http.set_script(
        {{make_http_request(
              http_request_method::HEAD,
              "https://mgh.thinknode.io/api/v1.0/iss/abc?context=123",
              {{"Authorization", "Bearer xyz"}},
              blob()),
          make_http_response(
              200,
              {{"Access-Control-Allow-Origin", "*"},
               {"Cache-Control", "max-age=60"}},
              blob())}});

    thinknode_session session;
    session.api_url = "https://mgh.thinknode.io/api/v1.0";
    session.access_token = "xyz";

    auto metadata = cppcoro::sync_wait(
        get_iss_object_metadata(service, session, "123", "abc"));
    REQUIRE(
        metadata
        == (std::map<string, string>(
            {{"Access-Control-Allow-Origin", "*"},
             {"Cache-Control", "max-age=60"}})));

    REQUIRE(mock_http.is_complete());
    REQUIRE(mock_http.is_in_order());
}

TEST_CASE("ISS immutable retrieval", "[thinknode][iss]")
{
    service_core service;
    init_test_service(service);

    auto& mock_http = enable_http_mocking(service);
    mock_http.set_script(
        {{make_get_request(
              "https://mgh.thinknode.io/api/v1.0/iss/immutable/"
              "abc?context=123",
              {{"Authorization", "Bearer xyz"},
               {"Accept", "application/octet-stream"}}),
          make_http_200_response(
              value_to_msgpack_string(dynamic("the-data")))}});

    thinknode_session session;
    session.api_url = "https://mgh.thinknode.io/api/v1.0";
    session.access_token = "xyz";

    auto data = cppcoro::sync_wait(
        retrieve_immutable(service, session, "123", "abc"));
    REQUIRE(data == dynamic("the-data"));

    REQUIRE(mock_http.is_complete());
    REQUIRE(mock_http.is_in_order());
}

// Check that both directions of URL type string conversion works for the
// given case.
static void
check_url_type_string(
    thinknode_session const& session,
    thinknode_type_info const& type,
    string const& url_string)
{
    INFO(url_string)
    INFO(type)
    REQUIRE(get_url_type_string(session, type) == url_string);
    REQUIRE(parse_url_type_string(url_string) == type);
}

TEST_CASE("URL type string", "[thinknode][iss]")
{
    thinknode_session session;
    session.api_url = "https://mgh.thinknode.io/api/v1.0";
    session.access_token = "xyz";

    thinknode_named_type_reference named_info;
    named_info.account = string("my_account");
    named_info.app = "my_app";
    named_info.name = "my_type";
    auto named_type = make_thinknode_type_info_with_named_type(named_info);
    check_url_type_string(
        session, named_type, "named/my_account/my_app/my_type");
    named_info.account = none;
    auto named_type_without_account
        = make_thinknode_type_info_with_named_type(named_info);
    REQUIRE(
        get_url_type_string(session, named_type_without_account)
        == "named/mgh/my_app/my_type");

    auto integer_type
        = make_thinknode_type_info_with_integer_type(thinknode_integer_type());
    check_url_type_string(session, integer_type, "integer");

    auto float_type
        = make_thinknode_type_info_with_float_type(thinknode_float_type());
    check_url_type_string(session, float_type, "float");

    auto string_type
        = make_thinknode_type_info_with_string_type(thinknode_string_type());
    check_url_type_string(session, string_type, "string");

    auto boolean_type
        = make_thinknode_type_info_with_boolean_type(thinknode_boolean_type());
    check_url_type_string(session, boolean_type, "boolean");

    auto blob_type
        = make_thinknode_type_info_with_blob_type(thinknode_blob_type());
    check_url_type_string(session, blob_type, "blob");

    auto dynamic_type
        = make_thinknode_type_info_with_dynamic_type(thinknode_dynamic_type());
    check_url_type_string(session, dynamic_type, "dynamic");

    auto nil_type
        = make_thinknode_type_info_with_nil_type(thinknode_nil_type());
    check_url_type_string(session, nil_type, "nil");

    auto datetime_type = make_thinknode_type_info_with_datetime_type(
        thinknode_datetime_type());
    check_url_type_string(session, datetime_type, "datetime");

    thinknode_array_info array_info;
    array_info.element_schema = boolean_type;
    auto array_type = make_thinknode_type_info_with_array_type(array_info);
    check_url_type_string(session, array_type, "array/boolean");

    thinknode_map_info map_info;
    map_info.key_schema = array_type;
    map_info.value_schema = blob_type;
    auto map_type = make_thinknode_type_info_with_map_type(map_info);
    check_url_type_string(session, map_type, "map/array/boolean/blob");

    thinknode_structure_info struct_info;
    struct_info.fields["def"].schema = array_type;
    struct_info.fields["abc"].schema = blob_type;
    auto struct_type
        = make_thinknode_type_info_with_structure_type(struct_info);
    check_url_type_string(
        session, struct_type, "structure/2/abc/blob/def/array/boolean");

    thinknode_union_info union_info;
    union_info.members["def"].schema = array_type;
    union_info.members["abc"].schema = blob_type;
    union_info.members["ghi"].schema = string_type;
    auto union_type = make_thinknode_type_info_with_union_type(union_info);
    check_url_type_string(
        session, union_type, "union/3/abc/blob/def/array/boolean/ghi/string");

    auto optional_type = make_thinknode_type_info_with_optional_type(map_type);
    check_url_type_string(
        session, optional_type, "optional/map/array/boolean/blob");

    thinknode_enum_info enum_info;
    enum_info.values["def"] = thinknode_enum_value_info();
    enum_info.values["abc"] = thinknode_enum_value_info();
    auto enum_type = make_thinknode_type_info_with_enum_type(enum_info);
    check_url_type_string(session, enum_type, "enum/2/abc/def");

    auto ref_type = make_thinknode_type_info_with_reference_type(named_type);
    check_url_type_string(
        session, ref_type, "reference/named/my_account/my_app/my_type");
}

TEST_CASE("ISS POST", "[thinknode][iss]")
{
    service_core service;
    init_test_service(service);

    auto& mock_http = enable_http_mocking(service);
    mock_http.set_script(
        {{make_http_request(
              http_request_method::POST,
              "https://mgh.thinknode.io/api/v1.0/iss/string?context=123",
              {{"Authorization", "Bearer xyz"},
               {"Accept", "application/json"},
               {"Content-Type", "application/octet-stream"}},
              value_to_msgpack_blob(dynamic("payload"))),
          make_http_200_response("{ \"id\": \"def\" }")}});

    thinknode_session session;
    session.api_url = "https://mgh.thinknode.io/api/v1.0";
    session.access_token = "xyz";

    auto id = cppcoro::sync_wait(post_iss_object(
        service,
        session,
        "123",
        make_thinknode_type_info_with_string_type(thinknode_string_type()),
        dynamic("payload")));
    REQUIRE(id == "def");

    REQUIRE(mock_http.is_complete());
    REQUIRE(mock_http.is_in_order());
}

TEST_CASE("ISS object copy", "[thinknode][iss]")
{
    service_core service;
    init_test_service(service);

    auto& mock_http = enable_http_mocking(service);
    mock_http.set_script(
        {{make_http_request(
              http_request_method::POST,
              "https://mgh.thinknode.io/api/v1.0/iss/def/buckets/"
              "abc?context=123",
              {{"Authorization", "Bearer xyz"}},
              blob()),
          make_http_200_response("")}});

    thinknode_session session;
    session.api_url = "https://mgh.thinknode.io/api/v1.0";
    session.access_token = "xyz";

    cppcoro::sync_wait(
        shallowly_copy_iss_object(service, session, "abc", "123", "def"));

    REQUIRE(mock_http.is_complete());
    REQUIRE(mock_http.is_in_order());
}

max_stars_repo_name: urlofmar/cradle

max_issues_repo_name: urlofmar/cradle

max_forks_repo_name: urlofmar/cradle


text:
#include <test_common.h>
#include <Eigen/Dense>

#include <igl/copyleft/cgal/remesh_self_intersections.h>
#include <igl/copyleft/cgal/RemeshSelfIntersectionsParam.h>

#include <CGAL/Exact_predicates_exact_constructions_kernel.h>

TEST_CASE("RemeshSelfIntersections: CubeWithFold", "[igl/copyleft/cgal]")
{
    Eigen::MatrixXd V;
    Eigen::MatrixXi F;
    igl::read_triangle_mesh(test_common::data_path("cube_with_fold.ply"), V, F);

    typedef CGAL::Exact_predicates_exact_constructions_kernel K;
    typedef Eigen::Matrix<K::FT, Eigen::Dynamic, Eigen::Dynamic> MatrixXe;

    MatrixXe VV;
    Eigen::MatrixXi FF, IF;
    Eigen::VectorXi J, IM;
    igl::copyleft::cgal::RemeshSelfIntersectionsParam param;
    igl::copyleft::cgal::remesh_self_intersections(V, F, param, VV, FF, IF, J, IM);
}

max_stars_repo_name: V-Sekai/godot-tri

max_issues_repo_name: V-Sekai/godot-tri

max_forks_repo_name: V-Sekai/godot-tri


text:
#include "Offline/DbService/inc/DbIdList.hh"
#include "Offline/ConfigTools/inc/ConfigFileLookupPolicy.hh"
#include "cetlib_except/exception.h"
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <fstream>
#include <iostream>

mu2e::DbIdList::DbIdList() {
  // read a file listing the connections so jobs can be steered
  // to new connections in almost real time

  ConfigFileLookupPolicy configFile;
  std::string fn = configFile("Database/connections.txt");

  std::ifstream in(fn);
  if (!in) {
    throw cet::exception("DBID_NO_CONNECTION")
        << "DbIdList::DbIdList could not open connections file " << fn
        << std::endl;
  }

  std::string line;
  std::vector<std::string> words;
  std::string name, host, port, url, urlNoCache;
  while (in) {
    std::getline(in, line);
    line = line.substr(0, line.find_first_of("#"));
    boost::trim(line);
    boost::split(words, line, boost::is_any_of(" \t"),
                 boost::token_compress_on);
    // if eof, or starting a new database stanza with a previous database name
    // filled
    if (in.eof() ||
        (words.size() == 2 && words[0] == "database" && !name.empty())) {
      // have read a stanza, check and store it
      bool fail =
          host.empty() || port.empty() || url.empty() || urlNoCache.empty();
      if (fail) {
        throw cet::exception("DBIDFILE_DATABASE_NOT_LOADED")
            << "DbIdList::DbIdList could not load database " << name
            << " in connections file" << std::endl;
      }
      _ids.emplace_back(name, host, port, url, urlNoCache);
      name = host = port = url = urlNoCache = "";
    }  // if database
    if (words.size() == 2) {
      if (words[0] == "database") {
        name = words[1];
      } else if (words[0] == "host") {
        host = words[1];
      } else if (words[0] == "port") {
        port = words[1];
      } else if (words[0] == "cache") {
        url = words[1];
      } else if (words[0] == "nocache") {
        urlNoCache = words[1];
      } else {
        throw cet::exception("DBIDFILE_BAD_KEYWORD")
            << "DbIdList::DbIdList unknown keyword: " << words[0] << std::endl;
      }
    } else if (!line.empty()) {
      throw cet::exception("DBIDFILE_BAD_LINE")
          << "DbIdList::DbIdList poorly formed line: " << line << std::endl;
    }
  }

  in.close();
}

mu2e::DbId mu2e::DbIdList::getDbId(const std::string& name) {
  for (auto const& id : _ids) {
    if (id.name() == name) {
      return id;
    }
  }
  throw cet::exception("DBIDFILE_DATABASE_NOT_FOUND")
      << "DbIdList::getDbId could not load database " << name << std::endl;
}


text:
/*
 Copyright (C) 2014 Eric Ehlers

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

#include <qlo/serialization/serializationfactory.hpp>
#include <qlo/serialization/create/create_all.hpp>
#include <qlo/serialization/processor.hpp>

#include <qlo/serialization/register/serialization_register.hpp>

#include <boost/serialization/vector.hpp>
#include <boost/serialization/shared_ptr.hpp>

namespace QuantLibAddin {

    SerializationFactory::SerializationFactory() {

        registerCreators();

        //reposit::ProcessorPtr relinkableHandleProcessor(
        //    new RelinkableHandleProcessor());
        //reposit::ProcessorFactory::instance().storeProcessor(
        //    "RelinkableHandleProcessor", relinkableHandleProcessor);

        //reposit::ProcessorPtr instrumentProcessor(
        //    new InstrumentProcessor());
        //reposit::ProcessorFactory::instance().storeProcessor(
        //    "InstrumentProcessor", instrumentProcessor);

        //reposit::ProcessorPtr legProcessor(
        //    new LegProcessor());
        //reposit::ProcessorFactory::instance().storeProcessor(
        //    "LegProcessor", legProcessor);

        //reposit::ProcessorPtr indexProcessor(
        //    new IndexProcessor());
        //reposit::ProcessorFactory::instance().storeProcessor(
        //    "IndexProcessor", indexProcessor);

        //reposit::ProcessorPtr extrapolatorProcessor(
        //    new ExtrapolatorProcessor());
        //reposit::ProcessorFactory::instance().storeProcessor(
        //    "ExtrapolatorProcessor", extrapolatorProcessor);
    }

    void SerializationFactory::register_out(boost::archive::xml_oarchive &ar,
        std::vector<boost::shared_ptr<reposit::ValueObject> >& valueObjects){

            tpl_register_classes(ar);
            ar << boost::serialization::make_nvp("object_list", valueObjects);
    }

    void SerializationFactory::register_in(boost::archive::xml_iarchive &ar,
        std::vector<boost::shared_ptr<reposit::ValueObject> >& valueObjects){

            tpl_register_classes(ar);
            ar >> boost::serialization::make_nvp("object_list", valueObjects);
    }

}

max_stars_repo_name: eehlers/QuantLibAddin

max_issues_repo_name: eehlers/QuantLibAddin

max_forks_repo_name: eehlers/QuantLibAddin


text:
//---------------------------------------------------------------------------//
// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.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
//
// See http://kylelutz.github.com/compute for more information.
//---------------------------------------------------------------------------//

//[transform_sqrt_example

#include <vector>
#include <algorithm>

#include <boost/compute/algorithm/transform.hpp>
#include <boost/compute/container/vector.hpp>
#include <boost/compute/functional/math.hpp>

namespace compute = boost::compute;

int main()
{
    // get default device and setup context
    compute::device device = compute::system::default_device();
    compute::context context(device);
    compute::command_queue queue(context, device);

    // generate random data on the host
    std::vector<float> host_vector(10000);
    std::generate(host_vector.begin(), host_vector.end(), rand);

    // create a vector on the device
    compute::vector<float> device_vector(host_vector.size(), context);

    // transfer data from the host to the device
    compute::copy(
        host_vector.begin(), host_vector.end(), device_vector.begin(), queue
    );

    // calculate the square-root of each element in-place
    compute::transform(
        device_vector.begin(),
        device_vector.end(),
        device_vector.begin(),
        compute::sqrt<float>(),
        queue
    );

    // copy values back to the host
    compute::copy(
        device_vector.begin(), device_vector.end(), host_vector.begin(), queue
    );

    return 0;
}

//]

max_stars_repo_name: bastiankoe/compute

max_issues_repo_name: bastiankoe/compute

max_forks_repo_name: bastiankoe/compute