text:
/**********************************************************\
Original Author: Richard Bateman

Created:    Jan 24, 2011
License:    Dual license model; choose one of two:
            New BSD License
            http://www.opensource.org/licenses/bsd-license.php
            - or -
            GNU Lesser General Public License, version 2.1
            http://www.gnu.org/licenses/lgpl-2.1.html

Copyright 2011 Richard Bateman,
               Firebreath development team
\**********************************************************/

#include "BrowserHost.h"
#include <boost/algorithm/string.hpp>
#include <boost/bind.hpp>
#include "precompiled_headers.h" // On windows, everything above this line in PCH

#include "SimpleStreamHelper.h"

static const int MEGABYTE = 1024 * 1024;

FB::SimpleStreamHelperPtr FB::SimpleStreamHelper::AsyncGet( const FB::BrowserHostPtr& host, const FB::URI& uri,
    const HttpCallback& callback, bool cache /*= true*/, size_t bufferSize /*= 256*1024*/ )
{
    if (!host->isMainThread()) {
        // This must be run from the main thread
        return host->CallOnMainThread(boost::bind(&FB::SimpleStreamHelper::AsyncGet, host, uri, callback, cache, bufferSize));
    }
    FB::SimpleStreamHelperPtr ptr(boost::make_shared<FB::SimpleStreamHelper>(host, callback, bufferSize));
    // This is kinda a weird trick; it's responsible for freeing itself, unless something decides
    // to hold a reference to it.
    ptr->keepReference(ptr);
    FB::BrowserStreamPtr stream(host->createStream(uri.toString(), ptr, cache, false, bufferSize));
    return ptr;
}

FB::SimpleStreamHelperPtr FB::SimpleStreamHelper::AsyncPost( const FB::BrowserHostPtr& host, const FB::URI& uri, const std::string& postdata,
                                                           const HttpCallback& callback, bool cache /*= true*/, size_t bufferSize /*= 256*1024*/ )
{
    if (!host->isMainThread()) {
        // This must be run from the main thread
        return host->CallOnMainThread(boost::bind(&FB::SimpleStreamHelper::AsyncPost, host, uri, postdata, callback, cache, bufferSize));
    }
    FB::SimpleStreamHelperPtr ptr(boost::make_shared<FB::SimpleStreamHelper>(host, callback, bufferSize));
    // This is kinda a weird trick; it's responsible for freeing itself, unless something decides
    // to hold a reference to it.
    ptr->keepReference(ptr);
    FB::BrowserStreamPtr stream(host->createPostStream(uri.toString(), ptr, postdata, cache, false, bufferSize));
    return ptr;
}

struct SyncHTTPHelper
{
public:
    SyncHTTPHelper()
        : done(false) { }
    void setPtr(const FB::SimpleStreamHelperPtr& inPtr) { ptr = inPtr; }

    void getURLCallback(bool success, const FB::HeaderMap& headers,
        const boost::shared_array<uint8_t>& data, const size_t size)
    {
        boost::lock_guard<boost::mutex> lock(m_mutex);
        m_response = boost::make_shared<FB::HttpStreamResponse>(success, headers, data, size);
        done = true;
        m_cond.notify_all();
    }
    void waitForDone() {
        boost::unique_lock<boost::mutex> lock(m_mutex);
        while (!done) {
            m_cond.wait(lock);
        }
    }

    bool done;
    FB::SimpleStreamHelperPtr ptr;
    boost::condition_variable m_cond;
    boost::mutex m_mutex;
    FB::HttpStreamResponsePtr m_response;
};

FB::HttpStreamResponsePtr FB::SimpleStreamHelper::SynchronousGet( const FB::BrowserHostPtr& host,
    const FB::URI& uri, const bool cache /*= true*/, const size_t bufferSize /*= 128*1024*/ )
{
    // We can't ever block on the main thread, so SynchronousGet can't be called from there.
    // Also, if you could block the main thread, that still wouldn't work because the request
    // is processed on the main thread!
    assert(!host->isMainThread());
    SyncHTTPHelper helper;
    try {
        FB::HttpCallback cb(boost::bind(&SyncHTTPHelper::getURLCallback, &helper, _1, _2, _3, _4));
        FB::SimpleStreamHelperPtr ptr = AsyncGet(host, uri, cb, cache, bufferSize);
        helper.setPtr(ptr);
        helper.waitForDone();
    } catch (const std::exception&) {
        // If anything weird happens, just return NULL (to indicate failure)
        return FB::HttpStreamResponsePtr();
    }
    return helper.m_response;
}

FB::HttpStreamResponsePtr FB::SimpleStreamHelper::SynchronousPost( const FB::BrowserHostPtr& host,
    const FB::URI& uri, const std::string& postdata, const bool cache /*= true*/, const size_t bufferSize /*= 128*1024*/ )
{
    // Do not call this on the main thread.
    assert(!host->isMainThread());
    SyncHTTPHelper helper;
    try {
        FB::HttpCallback cb(boost::bind(&SyncHTTPHelper::getURLCallback, &helper, _1, _2, _3, _4));
        FB::SimpleStreamHelperPtr ptr = AsyncPost(host, uri, postdata, cb, cache, bufferSize);
        helper.setPtr(ptr);
        helper.waitForDone();
    } catch (const std::exception&) {
        // If anything weird happens, just return NULL (to indicate failure)
        return FB::HttpStreamResponsePtr();
    }
    return helper.m_response;
}

FB::SimpleStreamHelper::SimpleStreamHelper( const BrowserHostPtr& host, const HttpCallback& callback, const size_t blockSize )
    : host(host), blockSize(blockSize), received(0), callback(callback)
{

}

bool FB::SimpleStreamHelper::onStreamCompleted( FB::StreamCompletedEvent *evt, FB::BrowserStream *stream )
{
    if (!evt->success) {
        if (callback)
            callback(false, FB::HeaderMap(), boost::shared_array<uint8_t>(), received);
        callback.clear();
        self.reset();
        return false;
    }
    if (!data) {
        data = boost::shared_array<uint8_t>(new uint8_t[received]);
        int i = 0;
        for (BlockList::const_iterator it = blocks.begin();
            it != blocks.end(); ++it) {
            size_t offset(i * blockSize);
            size_t len(received - offset);
            if (len > blockSize)
                len = blockSize;

            std::copy(it->get(), it->get()+len, data.get()+offset);
            ++i;
        }
        // Free all the old blocks
        blocks.clear();
    }
    if (callback && stream) {
        std::multimap<std::string, std::string> headers;
        headers = parse_http_headers(stream->getHeaders());
        callback(true, headers, data, received);
    }
    callback.clear();
    self.reset();
    return false; // Always return false to make sure the browserhost knows to let go of the object
}

bool FB::SimpleStreamHelper::onStreamOpened( FB::StreamOpenedEvent *evt, FB::BrowserStream * )
{
    // We can't reliably find the actual length, so we won't try
    return false;
}

bool FB::SimpleStreamHelper::onStreamDataArrived( FB::StreamDataArrivedEvent *evt, FB::BrowserStream * )
{
    received += evt->getLength();
    const uint8_t* buf = reinterpret_cast<const uint8_t*>(evt->getData());
    const uint8_t* endbuf = buf + evt->getLength();

    int len = evt->getLength();
    int offset = evt->getDataPosition();
    while (buf < endbuf) {
        size_t n = offset / blockSize;
        size_t pos = offset % blockSize;
        if (blocks.size() < n+1) {
            blocks.push_back(boost::shared_array<uint8_t>(new uint8_t[blockSize]));
        }
        uint8_t *destBuf = blocks.back().get();
        //if (pos + len > )
        int curLen = len;
        if (pos + len >= blockSize) {
            // If there isn't room in the current block, copy what there is room for
            // and loop
            curLen = blockSize-pos;
        }
        // Copy the bytes that fit in this buffer
        std::copy(buf, buf+curLen, destBuf+pos);
        buf += curLen;
        offset += curLen;
        len -= curLen;
    }
    return false;
}

FB::HeaderMap FB::SimpleStreamHelper::parse_http_headers(const std::string& headers )
{
    FB::HeaderMap res;
    std::vector<std::string> lines;
    boost::split(lines, headers, boost::is_any_of("\r\n"));
    for (std::vector<std::string>::const_iterator it = lines.begin(); it != lines.end(); ++it) {
        std::string line = boost::trim_copy(*it);
        if (line.empty()) continue;
        size_t loc = line.find(':');
        if (loc == std::string::npos) {
            // Weird; bad header
            continue;
        }
        res.insert(std::make_pair(boost::trim_copy(line.substr(0, loc)),
            boost::trim_copy(line.substr(loc + 1))));
    }
    return res;
}

void FB::SimpleStreamHelper::keepReference( const SimpleStreamHelperPtr& ptr )
{
    self = ptr;
}

max_stars_repo_name: Faham/bric-n-brac

max_issues_repo_name: Faham/bric-n-brac

max_forks_repo_name: Faham/bric-n-brac


text:
#include <boost/log/trivial.hpp>
#include <iostream>
#include <cstdint>
#include <sstream>

#include "HttpServer.h"

const std::string cHttpServer = "[HttpServer]";

HttpServer::CallbackInterface::CallbackInterface()
{
}

HttpServer::CallbackInterface::~CallbackInterface()
{
}

HttpServer::HttpServer(CallbackInterface &callbackInterface)
  : callbackInterface_(callbackInterface)
{
}

void
HttpServer::Run()
{
  try {
    boost::network::http::server<HttpServer>::options options(*this);
    boost::network::http::server<HttpServer> server(options.address("0.0.0.0").port("8080"));
    BOOST_LOG_TRIVIAL(debug) << cHttpServer << ": Running...";
    server.run();
  }
  catch (std::exception &error) {
    std::cerr << error.what() << std::endl;
    return;
  }
}

void
HttpServer::HttpServer::operator()(
  const boost::network::http::server<HttpServer>::request& request,
  boost::network::http::server<HttpServer>::connection_ptr connection)
{
  callbackInterface_.HandleHttpRequest(request);
}

void
HttpServer::HttpServer::SendResponse(const std::string& response)
{
  // TODO Let the HttpClient callback return here
  /*
  boost::network::http::server<HttpRequestHandler>::string_type ip = source(request);
  uint16_t port = request.source_port;
  std::ostringstream data;
  data << "Hello, " << ip << ':' << port << '!';
  connection->write(data.str());
  */
}

ext: cpp

max_stars_repo_name: itsbriany/WebFuzzer-Engine

max_issues_repo_name: itsbriany/WebFuzzer-Engine

max_forks_repo_name: itsbriany/WebFuzzer-Engine


text:
#include "hello.h"
#include <boost/python.hpp>

BOOST_PYTHON_MODULE(hello) {
	boost::python::def("greet", greet;
}

max_stars_repo_name: satya-das/yawg

max_issues_repo_name: satya-das/yawg

max_forks_repo_name: satya-das/yawg


text:
/*
 *
 * Copyright (c) 2004
 * John Maddock
 *
 * Use, modification and distribution are subject to 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)
 *
 */

 /*
  *   LOCATION:    see http://www.boost.org for most recent version.
  *   FILE         unicode_iterator.hpp
  *   VERSION      see <boost/version.hpp>
  *   DESCRIPTION: Iterator adapters for converting between different Unicode encodings.
  */

/****************************************************************************

Contents:
~~~~~~~~~

1) Read Only, Input Adapters:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

template <class BaseIterator, class U8Type = ::boost::uint8_t>
class u32_to_u8_iterator;

Adapts sequence of UTF-32 code points to "look like" a sequence of UTF-8.

template <class BaseIterator, class U32Type = ::boost::uint32_t>
class u8_to_u32_iterator;

Adapts sequence of UTF-8 code points to "look like" a sequence of UTF-32.

template <class BaseIterator, class U16Type = ::boost::uint16_t>
class u32_to_u16_iterator;

Adapts sequence of UTF-32 code points to "look like" a sequence of UTF-16.

template <class BaseIterator, class U32Type = ::boost::uint32_t>
class u16_to_u32_iterator;

Adapts sequence of UTF-16 code points to "look like" a sequence of UTF-32.

2) Single pass output iterator adapters:

template <class BaseIterator>
class utf8_output_iterator;

Accepts UTF-32 code points and forwards them on as UTF-8 code points.

template <class BaseIterator>
class utf16_output_iterator;

Accepts UTF-32 code points and forwards them on as UTF-16 code points.

****************************************************************************/

#ifndef BOOST_REGEX_UNICODE_ITERATOR_HPP
#define BOOST_REGEX_UNICODE_ITERATOR_HPP
#include <boost/cstdint.hpp>
#include <boost/assert.hpp>
#include <boost/iterator/iterator_facade.hpp>
#include <boost/static_assert.hpp>
#include <boost/throw_exception.hpp>
#include <stdexcept>
#ifndef BOOST_NO_STD_LOCALE
#include <sstream>
#endif
#include <limits.h> // CHAR_BIT

namespace boost{

namespace detail{

static const ::boost::uint16_t high_surrogate_base = 0xD7C0u;
static const ::boost::uint16_t low_surrogate_base = 0xDC00u;
static const ::boost::uint32_t ten_bit_mask = 0x3FFu;

inline bool is_high_surrogate(::boost::uint16_t v)
{
   return (v & 0xFC00u) == 0xd800u;
}
inline bool is_low_surrogate(::boost::uint16_t v)
{
   return (v & 0xFC00u) == 0xdc00u;
}
template <class T>
inline bool is_surrogate(T v)
{
   return (v & 0xF800u) == 0xd800;
}

inline unsigned utf8_byte_count(boost::uint8_t c)
{
   // if the most significant bit with a zero in it is in position
   // 8-N then there are N bytes in this UTF-8 sequence:
   boost::uint8_t mask = 0x80u;
   unsigned result = 0;
   while(c & mask)
   {
      ++result;
      mask >>= 1;
   }
   return (result == 0) ? 1 : ((result > 4) ? 4 : result);
}

inline unsigned utf8_trailing_byte_count(boost::uint8_t c)
{
   return utf8_byte_count(c) - 1;
}

inline void invalid_utf32_code_point(::boost::uint32_t val)
{
#ifndef BOOST_NO_STD_LOCALE
   std::stringstream ss;
   ss << "Invalid UTF-32 code point U+" << std::showbase << std::hex << val << " encountered while trying to encode UTF-16 sequence";
   std::out_of_range e(ss.str());
#else
   std::out_of_range e("Invalid UTF-32 code point encountered while trying to encode UTF-16 sequence");
#endif
   boost::throw_exception(e);
}

} // namespace detail

template <class BaseIterator, class U16Type = ::boost::uint16_t>
class u32_to_u16_iterator
   : public boost::iterator_facade<u32_to_u16_iterator<BaseIterator, U16Type>, U16Type, std::bidirectional_iterator_tag, const U16Type>
{
   typedef boost::iterator_facade<u32_to_u16_iterator<BaseIterator, U16Type>, U16Type, std::bidirectional_iterator_tag, const U16Type> base_type;

#if !defined(BOOST_NO_STD_ITERATOR_TRAITS) && !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
   typedef typename std::iterator_traits<BaseIterator>::value_type base_value_type;

   BOOST_STATIC_ASSERT(sizeof(base_value_type)*CHAR_BIT == 32);
   BOOST_STATIC_ASSERT(sizeof(U16Type)*CHAR_BIT == 16);
#endif

public:
   typename base_type::reference
      dereference()const
   {
      if(m_current == 2)
         extract_current();
      return m_values[m_current];
   }
   bool equal(const u32_to_u16_iterator& that)const
   {
      if(m_position == that.m_position)
      {
         // Both m_currents must be equal, or both even
         // this is the same as saying their sum must be even:
         return (m_current + that.m_current) & 1u ? false : true;
      }
      return false;
   }
   void increment()
   {
      // if we have a pending read then read now, so that we know whether
      // to skip a position, or move to a low-surrogate:
      if(m_current == 2)
      {
         // pending read:
         extract_current();
      }
      // move to the next surrogate position:
      ++m_current;
      // if we've reached the end skip a position:
      if(m_values[m_current] == 0)
      {
         m_current = 2;
         ++m_position;
      }
   }
   void decrement()
   {
      if(m_current != 1)
      {
         // decrementing an iterator always leads to a valid position:
         --m_position;
         extract_current();
         m_current = m_values[1] ? 1 : 0;
      }
      else
      {
         m_current = 0;
      }
   }
   BaseIterator base()const
   {
      return m_position;
   }
   // construct:
   u32_to_u16_iterator() : m_position(), m_current(0)
   {
      m_values[0] = 0;
      m_values[1] = 0;
      m_values[2] = 0;
   }
   u32_to_u16_iterator(BaseIterator b) : m_position(b), m_current(2)
   {
      m_values[0] = 0;
      m_values[1] = 0;
      m_values[2] = 0;
   }
private:

   void extract_current()const
   {
      // begin by checking for a code point out of range:
      ::boost::uint32_t v = *m_position;
      if(v >= 0x10000u)
      {
         if(v > 0x10FFFFu)
            detail::invalid_utf32_code_point(*m_position);
         // split into two surrogates:
         m_values[0] = static_cast<U16Type>(v >> 10) + detail::high_surrogate_base;
         m_values[1] = static_cast<U16Type>(v & detail::ten_bit_mask) + detail::low_surrogate_base;
         m_current = 0;
         BOOST_ASSERT(detail::is_high_surrogate(m_values[0]));
         BOOST_ASSERT(detail::is_low_surrogate(m_values[1]));
      }
      else
      {
         // 16-bit code point:
         m_values[0] = static_cast<U16Type>(*m_position);
         m_values[1] = 0;
         m_current = 0;
         // value must not be a surrogate:
         if(detail::is_surrogate(m_values[0]))
            detail::invalid_utf32_code_point(*m_position);
      }
   }
   BaseIterator m_position;
   mutable U16Type m_values[3];
   mutable unsigned m_current;
};

template <class BaseIterator, class U32Type = ::boost::uint32_t>
class u16_to_u32_iterator
   : public boost::iterator_facade<u16_to_u32_iterator<BaseIterator, U32Type>, U32Type, std::bidirectional_iterator_tag, const U32Type>
{
   typedef boost::iterator_facade<u16_to_u32_iterator<BaseIterator, U32Type>, U32Type, std::bidirectional_iterator_tag, const U32Type> base_type;
   // special values for pending iterator reads:
   BOOST_STATIC_CONSTANT(U32Type, pending_read = 0xffffffffu);

#if !defined(BOOST_NO_STD_ITERATOR_TRAITS) && !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
   typedef typename std::iterator_traits<BaseIterator>::value_type base_value_type;

   BOOST_STATIC_ASSERT(sizeof(base_value_type)*CHAR_BIT == 16);
   BOOST_STATIC_ASSERT(sizeof(U32Type)*CHAR_BIT == 32);
#endif

public:
   typename base_type::reference
      dereference()const
   {
      if(m_value == pending_read)
         extract_current();
      return m_value;
   }
   bool equal(const u16_to_u32_iterator& that)const
   {
      return m_position == that.m_position;
   }
   void increment()
   {
      // skip high surrogate first if there is one:
      if(detail::is_high_surrogate(*m_position)) ++m_position;
      ++m_position;
      m_value = pending_read;
   }
   void decrement()
   {
      --m_position;
      // if we have a low surrogate then go back one more:
      if(detail::is_low_surrogate(*m_position))
         --m_position;
      m_value = pending_read;
   }
   BaseIterator base()const
   {
      return m_position;
   }
   // construct:
   u16_to_u32_iterator() : m_position()
   {
      m_value = pending_read;
   }
   u16_to_u32_iterator(BaseIterator b) : m_position(b)
   {
      m_value = pending_read;
   }
private:
   static void invalid_code_point(::boost::uint16_t val)
   {
#ifndef BOOST_NO_STD_LOCALE
      std::stringstream ss;
      ss << "Misplaced UTF-16 surrogate U+" << std::showbase << std::hex << val << " encountered while trying to encode UTF-32 sequence";
      std::out_of_range e(ss.str());
#else
      std::out_of_range e("Misplaced UTF-16 surrogate encountered while trying to encode UTF-32 sequence");
#endif
      boost::throw_exception(e);
   }
   void extract_current()const
   {
      m_value = static_cast<U32Type>(static_cast< ::boost::uint16_t>(*m_position));
      // if the last value is a high surrogate then adjust m_position and m_value as needed:
      if(detail::is_high_surrogate(*m_position))
      {
         // precondition; next value must have be a low-surrogate:
         BaseIterator next(m_position);
         ::boost::uint16_t t = *++next;
         if((t & 0xFC00u) != 0xDC00u)
            invalid_code_point(t);
         m_value = (m_value - detail::high_surrogate_base) << 10;
         m_value |= (static_cast<U32Type>(static_cast< ::boost::uint16_t>(t)) & detail::ten_bit_mask);
      }
      // postcondition; result must not be a surrogate:
      if(detail::is_surrogate(m_value))
         invalid_code_point(static_cast< ::boost::uint16_t>(m_value));
   }
   BaseIterator m_position;
   mutable U32Type m_value;
};

template <class BaseIterator, class U8Type = ::boost::uint8_t>
class u32_to_u8_iterator
   : public boost::iterator_facade<u32_to_u8_iterator<BaseIterator, U8Type>, U8Type, std::bidirectional_iterator_tag, const U8Type>
{
   typedef boost::iterator_facade<u32_to_u8_iterator<BaseIterator, U8Type>, U8Type, std::bidirectional_iterator_tag, const U8Type> base_type;

#if !defined(BOOST_NO_STD_ITERATOR_TRAITS) && !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
   typedef typename std::iterator_traits<BaseIterator>::value_type base_value_type;

   BOOST_STATIC_ASSERT(sizeof(base_value_type)*CHAR_BIT == 32);
   BOOST_STATIC_ASSERT(sizeof(U8Type)*CHAR_BIT == 8);
#endif

public:
   typename base_type::reference
      dereference()const
   {
      if(m_current == 4)
         extract_current();
      return m_values[m_current];
   }
   bool equal(const u32_to_u8_iterator& that)const
   {
      if(m_position == that.m_position)
      {
         // either the m_current's must be equal, or one must be 0 and
         // the other 4: which means neither must have bits 1 or 2 set:
         return (m_current == that.m_current)
            || (((m_current | that.m_current) & 3) == 0);
      }
      return false;
   }
   void increment()
   {
      // if we have a pending read then read now, so that we know whether
      // to skip a position, or move to a low-surrogate:
      if(m_current == 4)
      {
         // pending read:
         extract_current();
      }
      // move to the next surrogate position:
      ++m_current;
      // if we've reached the end skip a position:
      if(m_values[m_current] == 0)
      {
         m_current = 4;
         ++m_position;
      }
   }
   void decrement()
   {
      if((m_current & 3) == 0)
      {
         --m_position;
         extract_current();
         m_current = 3;
         while(m_current && (m_values[m_current] == 0))
            --m_current;
      }
      else
         --m_current;
   }
   BaseIterator base()const
   {
      return m_position;
   }
   // construct:
   u32_to_u8_iterator() : m_position(), m_current(0)
   {
      m_values[0] = 0;
      m_values[1] = 0;
      m_values[2] = 0;
      m_values[3] = 0;
      m_values[4] = 0;
   }
   u32_to_u8_iterator(BaseIterator b) : m_position(b), m_current(4)
   {
      m_values[0] = 0;
      m_values[1] = 0;
      m_values[2] = 0;
      m_values[3] = 0;
      m_values[4] = 0;
   }
private:

   void extract_current()const
   {
      boost::uint32_t c = *m_position;
      if(c > 0x10FFFFu)
         detail::invalid_utf32_code_point(c);
      if(c < 0x80u)
      {
         m_values[0] = static_cast<unsigned char>(c);
         m_values[1] = static_cast<unsigned char>(0u);
         m_values[2] = static_cast<unsigned char>(0u);
         m_values[3] = static_cast<unsigned char>(0u);
      }
      else if(c < 0x800u)
      {
         m_values[0] = static_cast<unsigned char>(0xC0u + (c >> 6));
         m_values[1] = static_cast<unsigned char>(0x80u + (c & 0x3Fu));
         m_values[2] = static_cast<unsigned char>(0u);
         m_values[3] = static_cast<unsigned char>(0u);
      }
      else if(c < 0x10000u)
      {
         m_values[0] = static_cast<unsigned char>(0xE0u + (c >> 12));
         m_values[1] = static_cast<unsigned char>(0x80u + ((c >> 6) & 0x3Fu));
         m_values[2] = static_cast<unsigned char>(0x80u + (c & 0x3Fu));
         m_values[3] = static_cast<unsigned char>(0u);
      }
      else
      {
         m_values[0] = static_cast<unsigned char>(0xF0u + (c >> 18));
         m_values[1] = static_cast<unsigned char>(0x80u + ((c >> 12) & 0x3Fu));
         m_values[2] = static_cast<unsigned char>(0x80u + ((c >> 6) & 0x3Fu));
         m_values[3] = static_cast<unsigned char>(0x80u + (c & 0x3Fu));
      }
      m_current= 0;
   }
   BaseIterator m_position;
   mutable U8Type m_values[5];
   mutable unsigned m_current;
};

template <class BaseIterator, class U32Type = ::boost::uint32_t>
class u8_to_u32_iterator
   : public boost::iterator_facade<u8_to_u32_iterator<BaseIterator, U32Type>, U32Type, std::bidirectional_iterator_tag, const U32Type>
{
   typedef boost::iterator_facade<u8_to_u32_iterator<BaseIterator, U32Type>, U32Type, std::bidirectional_iterator_tag, const U32Type> base_type;
   // special values for pending iterator reads:
   BOOST_STATIC_CONSTANT(U32Type, pending_read = 0xffffffffu);

#if !defined(BOOST_NO_STD_ITERATOR_TRAITS) && !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
   typedef typename std::iterator_traits<BaseIterator>::value_type base_value_type;

   BOOST_STATIC_ASSERT(sizeof(base_value_type)*CHAR_BIT == 8);
   BOOST_STATIC_ASSERT(sizeof(U32Type)*CHAR_BIT == 32);
#endif

public:
   typename base_type::reference
      dereference()const
   {
      if(m_value == pending_read)
         extract_current();
      return m_value;
   }
   bool equal(const u8_to_u32_iterator& that)const
   {
      return m_position == that.m_position;
   }
   void increment()
   {
      // skip high surrogate first if there is one:
      unsigned c = detail::utf8_byte_count(*m_position);
      std::advance(m_position, c);
      m_value = pending_read;
   }
   void decrement()
   {
      // Keep backtracking until we don't have a trailing character:
      unsigned count = 0;
      while((*--m_position & 0xC0u) == 0x80u) ++count;
      // now check that the sequence was valid:
      if(count != detail::utf8_trailing_byte_count(*m_position))
         invalid_sequnce();
      m_value = pending_read;
   }
   BaseIterator base()const
   {
      return m_position;
   }
   // construct:
   u8_to_u32_iterator() : m_position()
   {
      m_value = pending_read;
   }
   u8_to_u32_iterator(BaseIterator b) : m_position(b)
   {
      m_value = pending_read;
   }
private:
   static void invalid_sequnce()
   {
      std::out_of_range e("Invalid UTF-8 sequence encountered while trying to encode UTF-32 character");
      boost::throw_exception(e);
   }
   void extract_current()const
   {
      m_value = static_cast<U32Type>(static_cast< ::boost::uint8_t>(*m_position));
      // we must not have a continuation character:
      if((m_value & 0xC0u) == 0x80u)
         invalid_sequnce();
      // see how many extra byts we have:
      unsigned extra = detail::utf8_trailing_byte_count(*m_position);
      // extract the extra bits, 6 from each extra byte:
      BaseIterator next(m_position);
      for(unsigned c = 0; c < extra; ++c)
      {
         ++next;
         m_value <<= 6;
         m_value += static_cast<boost::uint8_t>(*next) & 0x3Fu;
      }
      // we now need to remove a few of the leftmost bits, but how many depends
      // upon how many extra bytes we've extracted:
      static const boost::uint32_t masks[4] =
      {
         0x7Fu,
         0x7FFu,
         0xFFFFu,
         0x1FFFFFu,
      };
      m_value &= masks[extra];
      // check the result:
      if(m_value > static_cast<U32Type>(0x10FFFFu))
         invalid_sequnce();
   }
   BaseIterator m_position;
   mutable U32Type m_value;
};

template <class BaseIterator>
class utf16_output_iterator
{
public:
   typedef void                                   difference_type;
   typedef void                                   value_type;
   typedef boost::uint32_t*                       pointer;
   typedef boost::uint32_t&                       reference;
   typedef std::output_iterator_tag               iterator_category;

   utf16_output_iterator(const BaseIterator& b)
      : m_position(b){}
   utf16_output_iterator(const utf16_output_iterator& that)
      : m_position(that.m_position){}
   utf16_output_iterator& operator=(const utf16_output_iterator& that)
   {
      m_position = that.m_position;
      return *this;
   }
   const utf16_output_iterator& operator*()const
   {
      return *this;
   }
   void operator=(boost::uint32_t val)const
   {
      push(val);
   }
   utf16_output_iterator& operator++()
   {
      return *this;
   }
   utf16_output_iterator& operator++(int)
   {
      return *this;
   }
   BaseIterator base()const
   {
      return m_position;
   }
private:
   void push(boost::uint32_t v)const
   {
      if(v >= 0x10000u)
      {
         // begin by checking for a code point out of range:
         if(v > 0x10FFFFu)
            detail::invalid_utf32_code_point(v);
         // split into two surrogates:
         *m_position++ = static_cast<boost::uint16_t>(v >> 10) + detail::high_surrogate_base;
         *m_position++ = static_cast<boost::uint16_t>(v & detail::ten_bit_mask) + detail::low_surrogate_base;
      }
      else
      {
         // 16-bit code point:
         // value must not be a surrogate:
         if(detail::is_surrogate(v))
            detail::invalid_utf32_code_point(v);
         *m_position++ = static_cast<boost::uint16_t>(v);
      }
   }
   mutable BaseIterator m_position;
};

template <class BaseIterator>
class utf8_output_iterator
{
public:
   typedef void                                   difference_type;
   typedef void                                   value_type;
   typedef boost::uint32_t*                       pointer;
   typedef boost::uint32_t&                       reference;
   typedef std::output_iterator_tag               iterator_category;

   utf8_output_iterator(const BaseIterator& b)
      : m_position(b){}
   utf8_output_iterator(const utf8_output_iterator& that)
      : m_position(that.m_position){}
   utf8_output_iterator& operator=(const utf8_output_iterator& that)
   {
      m_position = that.m_position;
      return *this;
   }
   const utf8_output_iterator& operator*()const
   {
      return *this;
   }
   void operator=(boost::uint32_t val)const
   {
      push(val);
   }
   utf8_output_iterator& operator++()
   {
      return *this;
   }
   utf8_output_iterator& operator++(int)
   {
      return *this;
   }
   BaseIterator base()const
   {
      return m_position;
   }
private:
   void push(boost::uint32_t c)const
   {
      if(c > 0x10FFFFu)
         detail::invalid_utf32_code_point(c);
      if(c < 0x80u)
      {
         *m_position++ = static_cast<unsigned char>(c);
      }
      else if(c < 0x800u)
      {
         *m_position++ = static_cast<unsigned char>(0xC0u + (c >> 6));
         *m_position++ = static_cast<unsigned char>(0x80u + (c & 0x3Fu));
      }
      else if(c < 0x10000u)
      {
         *m_position++ = static_cast<unsigned char>(0xE0u + (c >> 12));
         *m_position++ = static_cast<unsigned char>(0x80u + ((c >> 6) & 0x3Fu));
         *m_position++ = static_cast<unsigned char>(0x80u + (c & 0x3Fu));
      }
      else
      {
         *m_position++ = static_cast<unsigned char>(0xF0u + (c >> 18));
         *m_position++ = static_cast<unsigned char>(0x80u + ((c >> 12) & 0x3Fu));
         *m_position++ = static_cast<unsigned char>(0x80u + ((c >> 6) & 0x3Fu));
         *m_position++ = static_cast<unsigned char>(0x80u + (c & 0x3Fu));
      }
   }
   mutable BaseIterator m_position;
};

} // namespace boost

#endif // BOOST_REGEX_UNICODE_ITERATOR_HPP

ext: hpp


text:
//
//  Copyright 2012 Alin Dobra and Christopher Jermaine
//
//  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 "LT_TextLoader.h"
#include "AttributeManager.h"
#include "WayPointConfigureData.h"
#include "ContainerTypes.h"
#include <boost/algorithm/string.hpp>

using namespace std;

bool LT_TextLoader :: GetConfig (WayPointConfigureData& where) {

    // Name of waypoint
    string relation = GetWPName();

    // all query exit pairs
    QueryExitContainer queryExits;

    // dropped queries
    QueryExitContainer qExitsDone;
    // Alin: not working properly. Returns current queries          GetDroppedQueries(qExitsDone);

    // query to slot map
    QueryExitToSlotsMap queryColumnsMap;
    GetQuerExitToSlotMap(queryColumnsMap);

    WayPointID tableID = GetId ();
    /* crap from common inheritance from waypoint*/
    WorkFuncContainer myWorkFuncs;
    WorkFunc tempFunc = NULL; // NULL, will be populated in codeloader
    TextLoaderWorkFunc myWorkFunc (tempFunc);
    myWorkFuncs.Insert(myWorkFunc);

    QueryExitContainer myEndingQueryExits;
    QueryExitContainer myFlowThroughQueryExits;
    GetQueryExits(queryExits, myEndingQueryExits);

    PDEBUG("Printing query exits for TEXTLOADER WP ID = %s", GetId().getName().c_str());

    // scan the json to
    StringContainer filesCont;
    Json::Value files = expression[J_FILE];
    for (int i=0; i<files.size(); ++i)
        filesCont.push_back (files[i].asString());

    TextLoaderConfigureData loaderConfig( GetId(), myWorkFuncs, myEndingQueryExits,
            myFlowThroughQueryExits, filesCont, queryExits);

    where.swap(loaderConfig);

    return true;

}

bool LT_TextLoader::PropagateDown(QueryID query, const SlotSet& atts, SlotSet& rez, QueryExit qe)
{
    CheckQueryAndUpdate(newQueryToSlotSetMap, used);
    newQueryToSlotSetMap.clear();

    if (!IsSubSet(atts, used[query]))
    {
        cout << "TextLoader WP : Attributes coming from above should be subset of used\n";
        return false;
    }
    // nothing to be done for rez (result) because we have no-one to propagate down, we are bottommost
    queryExit.Insert(qe);
    return true;
}

Json::Value LT_TextLoader :: GetJson(){
    Json::Value out(Json::objectValue);// overall object to be return

    IDInfo info;
    GetId().getInfo(info);
    out[J_NAME] = info.getName();
    out[J_TYPE] = JN_TL_WP;
    out[J_EXPR] = expression;

    return out;
}

ext: cc

max_stars_repo_name: nishantmehta/mainGrokit

max_issues_repo_name: nishantmehta/mainGrokit

max_forks_repo_name: nishantmehta/mainGrokit


text:
/****************************************************************************
**
** Copyright (C) 2009-2014 TEGESO/TEGESOFT and/or its subsidiary(-ies) and mother company.
** Contact: Tegesoft Information (contact@tegesoft.com)
**
** This file is part of the CAMP library.
**
** The MIT License (MIT)
**
** Copyright (C) 2009-2014 TEGESO/TEGESOFT and/or its subsidiary(-ies) and mother company.
**
** 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.
**
****************************************************************************/

#ifndef CAMP_DETAIL_FUNCTIONTRAITS_HPP
#define CAMP_DETAIL_FUNCTIONTRAITS_HPP

#include <camp/detail/yesnotype.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/function_types/is_callable_builtin.hpp>
#include <boost/function_types/result_type.hpp>

namespace camp
{
namespace detail
{
/**
 * \brief Helper structure to check at compile time if a type is a functor
 *
 * This structure checks if the provided type defines a result_type type.
 */
template <typename T>
struct HasResultType
{
    template <typename U, typename V> struct TestForMember {};
    template <typename U> static TypeYes check(TestForMember<U, typename U::result_type>*);
    template <typename U> static TypeNo  check(...);

    enum {value = sizeof(check<T>(0)) == sizeof(TypeYes)};
};

/**
 * \class FunctionTraits
 *
 * \brief Utility class which gives compile-time informations about function types
 *
 * The FunctionTraits provides two informations about a type T:
 * \li A compile-time constant \c isFunction which tells if T is any callable type
 * \li A type \c ReturnType which is the type returned by T
 */

/**
 * General case for all unspecified types: not a function
 */
template <typename T, typename E = void>
struct FunctionTraits
{
    enum {isFunction = false};
};

/**
 * Specialization for native callable types (function and pointer-to-member types)
 */
template <typename T>
struct FunctionTraits<T, typename boost::enable_if<boost::function_types::is_callable_builtin<T> >::type>
{
    enum {isFunction = true};
    typedef typename boost::function_types::result_type<T>::type ReturnType;
};

/**
 * Specialization for functors (classes exporting a result_type type)
 */
template <typename T>
struct FunctionTraits<T, typename boost::enable_if<HasResultType<T> >::type>
{
    enum {isFunction = true};
    typedef typename T::result_type ReturnType;
};

} // namespace detail

} // namespace camp

#endif // CAMP_DETAIL_FUNCTIONTRAITS_HPP

max_stars_repo_name: IRCAD/camp

max_forks_repo_name: IRCAD/camp


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

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

#include "Common.h"
#include "Tub.h"

namespace {

/**
 * Replaces gtest's PrettyUnitTestResultPrinter with something less verbose.
 * This forwards callbacks to the default printer if and when they might be
 * interesting.
 */
class QuietUnitTestResultPrinter : public testing::TestEventListener {
  public:
    /**
     * Constructor.
     * \param prettyPrinter
     *      gtest's default unit test result printer. This object takes
     *      ownership of prettyPrinter and will delete it later.
     */
    explicit QuietUnitTestResultPrinter(TestEventListener* prettyPrinter)
        : prettyPrinter(prettyPrinter)
        , currentTestCase(NULL)
        , currentTestInfo(NULL)
    {}
    void OnTestProgramStart(const testing::UnitTest& unit_test) {
        prettyPrinter->OnTestProgramStart(unit_test);
    }
    void OnTestIterationStart(const testing::UnitTest& unit_test,
                              int iteration) {
        prettyPrinter->OnTestIterationStart(unit_test, iteration);
    }
    void OnEnvironmentsSetUpStart(const testing::UnitTest& unit_test) {}
    void OnEnvironmentsSetUpEnd(const testing::UnitTest& unit_test) {}
    void OnTestCaseStart(const testing::TestCase& test_case) {
        currentTestCase = &test_case;
    }
    void OnTestStart(const testing::TestInfo& test_info) {
        currentTestInfo = &test_info;
    }
    void OnTestPartResult(const testing::TestPartResult& test_part_result) {
        if (test_part_result.type() != testing::TestPartResult::kSuccess) {
            if (currentTestCase != NULL) {
                prettyPrinter->OnTestCaseStart(*currentTestCase);
                currentTestCase = NULL;
            }
            if (currentTestInfo != NULL) {
                prettyPrinter->OnTestStart(*currentTestInfo);
                currentTestInfo = NULL;
            }
            prettyPrinter->OnTestPartResult(test_part_result);
        }
    }
    void OnTestEnd(const testing::TestInfo& test_info) {
        currentTestInfo = NULL;
    }
    void OnTestCaseEnd(const testing::TestCase& test_case) {
        currentTestCase = NULL;
    }
    void OnEnvironmentsTearDownStart(const testing::UnitTest& unit_test) {}
    void OnEnvironmentsTearDownEnd(const testing::UnitTest& unit_test) {}
    void OnTestIterationEnd(const testing::UnitTest& unit_test,
                            int iteration) {
        prettyPrinter->OnTestIterationEnd(unit_test, iteration);
    }
    void OnTestProgramEnd(const testing::UnitTest& unit_test) {
        prettyPrinter->OnTestProgramEnd(unit_test);
    }
  private:
    /// gtest's default unit test result printer.
    std::unique_ptr<TestEventListener> prettyPrinter;
    /// The currently running TestCase that hasn't been printed, or NULL.
    const testing::TestCase* currentTestCase;
    /// The currently running TestInfo that hasn't been printed, or NULL.
    const testing::TestInfo* currentTestInfo;
    DISALLOW_COPY_AND_ASSIGN(QuietUnitTestResultPrinter);
};

bool progress = false;

} // anonymous namespace

int
main(int argc, char *argv[])
{
    namespace po = boost::program_options;
    po::options_description configOptions("TestRunner");
    configOptions.add_options()
        ("help,h", "Produce this help message")
        ("verbose,v", "Show test progress");
    po::variables_map vm;
    po::parsed_options parsed = po::command_line_parser(argc, argv).options(
        configOptions).allow_unregistered().run();
    po::store(parsed, vm);
    po::notify(vm);
    std::vector<std::string> unrecognizedOptions = po::collect_unrecognized(
        parsed.options, po::include_positional);
    if (vm.count("help")) {
        std::cerr << configOptions << std::endl;

        std::cerr << "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-" << std::endl;
        std::cerr << "The following arguments are passed to gtest" << std::endl;
        std::cerr << "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-" << std::endl;

        int googleArgc = 2;
        char* googleArgv[] = {
            strdup(argv[0]),    // Expects an executable name in argv[0] to skip
            strdup("--help"),
            NULL
        };
        ::testing::InitGoogleTest(&googleArgc, googleArgv);

        exit(1);
    }
    progress = vm.count("verbose");

    int googleArgc = 1 + static_cast<int>(unrecognizedOptions.size());
    char** googleArgv = new char*[googleArgc + 1];
    googleArgv[0] = strdup(argv[0]);

    char** nextArgv = &googleArgv[1];
    foreach (std::string& gtestOption, unrecognizedOptions) {
        *nextArgv++ = strdup(gtestOption.c_str());
    }
    googleArgv[googleArgc] = NULL;

    ::testing::InitGoogleTest(&googleArgc, googleArgv);

    auto unitTest = ::testing::UnitTest::GetInstance();
    auto& listeners = unitTest->listeners();

    // set up the environment for unit tests
    struct GTestSetupListener : public ::testing::EmptyTestEventListener {
        GTestSetupListener() {}
        // this fires before each test fixture's constructor
        void OnTestStart(const ::testing::TestInfo& testInfo) {
            RAMCloud::Logger::get().setLogLevels(RAMCloud::WARNING);
        }
        // this fires after each test fixture's destructor
        void OnTestEnd(const ::testing::TestInfo& testInfo) {
            // Currently does nothing.
        }
    };
    listeners.Append(new GTestSetupListener());

    if (!progress) {
        // replace default output printer with quiet one
        auto defaultPrinter = listeners.Release(
                                listeners.default_result_printer());
        listeners.Append(new QuietUnitTestResultPrinter(defaultPrinter));
    }

    return RUN_ALL_TESTS();
}

max_stars_repo_name: taschik/ramcloud

max_issues_repo_name: taschik/ramcloud

max_forks_repo_name: taschik/ramcloud


text:
//  (C) Copyright Howard Hinnant
//  (C) Copyright 2011 Vicente J. Botet Escriba
//  Use, modification and distribution are subject to 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).
//
// This code was adapted by Vicente from Howard Hinnant's experimental work
// on chrono i/o to Boost

#ifndef BOOST_CHRONO_IO_DURATION_STYLE_HPP
#define BOOST_CHRONO_IO_DURATION_STYLE_HPP

#include <boost/detail/scoped_enum_emulation.hpp>

namespace boost {
namespace chrono {
/**
 * Scoped enumeration emulation stating whether the duration I/O style is long
 * or short. prefix means duration::rep with whatever stream/locale settings are
 * set for it followed by a long name representing the unit symbol means
 * duration::rep with whatever stream/locale settings are set for it followed by
 * a SI unit abbreviation
 */
BOOST_SCOPED_ENUM_DECLARE_BEGIN(duration_style){
    prefix, symbol} BOOST_SCOPED_ENUM_DECLARE_END(duration_style)

} // namespace chrono

} // namespace boost

#endif // header

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
// Copyright (C) 2017 Electronic Arts Inc.  All rights reserved.

#include "capturenode.hpp"
#include "ximeacameras.hpp"
#include "hardwaresync.hpp"
#include "drivebench.hpp"
#include "json.hpp"
#include "embedded_python.hpp"

#include <boost/filesystem.hpp>

#include <iomanip>
#include <iostream>
#include <iterator>

CaptureNode::CaptureNode(
	bool initializeWebcams, bool initializeAudio, bool initializeDummyCam,
	const std::vector<std::string>& recording_folders)
	: StateMachine<CaptureNodeState>(STATE_UNKNOWN), m_sync_active(false), m_shutdownrequested(false)
{
	m_external_sync_preview = false;
	m_external_sync_recording = false;

	m_first_update_sent = false;

	m_minimim_drive_speed = 40; // Do not use drives slower than this (MB/s)
	m_bandwidth_per_thread = 200; // MB/s
	m_global_framerate = 30; // frames/second
	m_global_pulse_duration = 2000; // us

	m_bitdepth_default = 8;
	m_bitdepth_maximum = 8;
	m_image_format_raw = false;

	std::cout << "Initializing hardware sync..." << std::endl;

	// Hardware Synch
	{
		// Initialize Hardware sync with default framerate
		if (PythonEngine::Instance().m_sync.get())
		{
			m_sync = PythonEngine::Instance().m_sync;
			PythonEngine::Instance().m_sync.reset();
		}

		if (m_sync.get() && m_sync->isOK())
		{
			m_sync->start(m_global_framerate, m_global_pulse_duration, false);
			m_sync_active = true;
			std::cout << "Initialized Hardware Synch on " << m_sync->port() << " to " << m_global_framerate << " Hz... (Pulse duration " << m_global_pulse_duration << " us)" << std::endl;
		}
		else
		{
			std::cout << "No Hardware Sync found" << std::endl;
		}
	}

	std::cout << "Computing drive speed..." << std::endl;

	// Benchmark disks, gather list of folders
	if (recording_folders.empty())
	{
		m_capture_folders = get_recording_folder_list();

		if (m_capture_folders.size()>1)
		{
			// Remove drives that are too slow to capture
			m_capture_folders.erase(std::remove_if(m_capture_folders.begin(),
				m_capture_folders.end(),
				[&](std::pair<std::string, size_t> x) {return x.second < m_minimim_drive_speed; }),
				m_capture_folders.end());
		}
	}
	else
	{
		for (auto folder : recording_folders)
		{
			size_t speed = get_drive_speed(folder);
			if (speed)
			{
				m_capture_folders.push_back(std::make_pair(folder, speed));
				std::cout << "Recording folder: " << folder << " " << speed << " MB/s" << std::endl;
			}
		}
	}

	if (m_capture_folders.empty()) {
		std::cerr << "No suitable recording drives found" << std::endl;
		exit(1);
	}

	std::cout << "Initializing cameras..." << std::endl;

	// Initialize a webcam if it exists
	if (initializeWebcams)
	{
		std::vector<std::shared_ptr<Camera> > webcam_cameras = WebcamCamera::get_webcam_cameras();
		std::copy(webcam_cameras.begin(), webcam_cameras.end(), std::back_inserter(m_cameras));
	}

	// Initialize a dummy camera for testing
	if (initializeDummyCam)
	{
		std::vector<std::shared_ptr<Camera> > dummy_cameras = DummyCamera::get_dummy_cameras(2);
		std::copy(dummy_cameras.begin(), dummy_cameras.end(), std::back_inserter(m_cameras));
	}

#ifdef WITH_PORTAUDIO
	// Enable first audio device
	if (initializeAudio)
	{
		m_cameras.push_back(std::make_shared<AudioCamera>());
	}
#endif

	CaptureNode::scan_for_new_devices();

	GotoState(STATE_PREVIEW);
}

CaptureNode::~CaptureNode()
{
	for (std::shared_ptr<Camera>& cam : m_cameras)
		cam->stop_capture();
}

bool CaptureNode::sync_connected() const
{
	return (m_sync.get() && m_sync->isOK());
}

void CaptureNode::remove_invalid_devices()
{
	std::lock_guard<std::mutex> lock(m_mutex);

	// Remove any camera that has become invalid (and is not recording)
	m_cameras.erase(
		std::remove_if(m_cameras.begin(), m_cameras.end(), [](std::shared_ptr<Camera>& it) {return !it->is_valid(); }),
		m_cameras.end());
}

size_t CaptureNode::scan_for_new_devices()
{
	size_t new_count = 0;

	// Ximea Cameras
	std::vector<std::shared_ptr<Camera> > new_ximea_cameras;
	std::vector<std::string> removed_ximea_cameras;

	XimeaCamera::get_ximea_cameras(new_ximea_cameras, removed_ximea_cameras);

	if (!new_ximea_cameras.empty() || !removed_ximea_cameras.empty())
	{
		std::lock_guard<std::mutex> lock(m_mutex);

		// Cameras to invalidate
		std::for_each(removed_ximea_cameras.begin(), removed_ximea_cameras.end(), [this](const std::string& it) {

			std::shared_ptr<Camera> cam = cameraById(it.c_str());

			if (cam.get())
			{
				printf("Camera Disconnected : %s\n", cam->unique_id().c_str());
				cam->invalidate();
			}
		});

		// New cameras
		new_count = new_ximea_cameras.size();
		std::copy(new_ximea_cameras.begin(), new_ximea_cameras.end(), std::back_inserter(m_cameras));
	}

	return new_count;
}

void CaptureNode::setGlobalParams(const std::string& json)
{
	if (json.empty())
		return;

	// Parse global settings recieved from server at launch

	rapidjson::Document doc;
	doc.Parse(json.c_str());

	if (doc.HasMember("display_focus_peak"))
	{
		std::lock_guard<std::mutex> lock(m_mutex);
		for (auto& cam : m_cameras)
			cam->set_display_focus_peak(doc["display_focus_peak"].GetBool());
	}
	if (doc.HasMember("display_overexposed"))
	{
		std::lock_guard<std::mutex> lock(m_mutex);
		for (auto& cam : m_cameras)
			cam->set_display_overexposed(doc["display_overexposed"].GetBool());
	}
	if (doc.HasMember("display_histogram"))
	{
		std::lock_guard<std::mutex> lock(m_mutex);
		for (auto& cam : m_cameras)
			cam->set_display_histogram(doc["display_histogram"].GetBool());
	}
	if (doc.HasMember("bitdepth_avi"))
	{
		if (doc["bitdepth_avi"].GetInt() != m_bitdepth_default)
		{
			m_bitdepth_default = doc["bitdepth_avi"].GetInt();

			std::lock_guard<std::mutex> lock(m_mutex);
			for (auto& cam : m_cameras)
				if (!cam->recording())
					cam->set_bitdepth(m_bitdepth_default);
		}
	}
	if (doc.HasMember("bitdepth_single"))
	{
		m_bitdepth_maximum = doc["bitdepth_single"].GetInt();
	}
	if (doc.HasMember("image_format") && doc["image_format"].IsString())
	{
		m_image_format_raw = strcmp(doc["image_format"].GetString(),"raw")==0;
	}
	if (doc.HasMember("wb_R") && doc.HasMember("wb_G") && doc.HasMember("wb_B"))
	{
		std::lock_guard<std::mutex> lock(m_mutex);
		for (auto& cam : m_cameras)
			cam->updateColorBalance(doc["wb_R"].GetDouble(), doc["wb_G"].GetDouble(), doc["wb_B"].GetDouble());
	}

	if (doc.HasMember("frequency"))
	{
		int freq = 0;
		if (doc["frequency"].IsInt())
			freq = doc["frequency"].GetInt();
		if (doc["frequency"].IsString())
			freq = atoi(doc["frequency"].GetString()); // fix for bad JSON from server

		set_global_framerate(freq,
			doc.HasMember("pulse_duration") ? doc["pulse_duration"].GetInt() : 0,
			doc.HasMember("external_sync") ? doc["external_sync"].GetBool() : false);

		std::lock_guard<std::mutex> lock(m_mutex);

		// Enable sync on all cameras
		for (auto& cam : m_cameras)
			cam->set_hardware_sync_freq(freq);
	}

	if (doc.HasMember("sync_freq") && doc.HasMember("pulse_duration"))
	{
		// Set hardware sync frequency
		int sync_freq = doc["sync_freq"].GetInt();
		int duration = doc["pulse_duration"].GetInt();

		set_global_framerate(sync_freq, duration,
			doc.HasMember("external_sync") ? doc["external_sync"].GetBool() : false);

		std::lock_guard<std::mutex> lock(m_mutex);

		// Activate sync on all cameras
		for (auto& cam : m_cameras)
			cam->set_hardware_sync_freq(sync_freq);
	}

	if (doc.HasMember("camera_params") && doc["camera_params"].IsArray())
	{
		const rapidjson::Value& params = doc["camera_params"];
		for (rapidjson::SizeType i = 0; i < params.Size(); i++)
		{
			if (params[i].HasMember("unique_id"))
			{
				std::string camera_name = params[i]["unique_id"].GetString();

				// TODO Camera ROI

				auto it = cameraById(camera_name.c_str());
				if (it)
				{
					for (rapidjson::Value::ConstMemberIterator itr = params[i].MemberBegin(); itr != params[i].MemberEnd(); ++itr)
					{
						// Apply each parameter to the camera

						if (itr->value.IsBool() && (strcmp(itr->name.GetString(),"using_sync"))==0) // special case
						{
							it->set_hardware_sync(itr->value.GetBool(), global_framerate());
						}
						else if (itr->value.IsDouble())
						{
							it->param_set(itr->name.GetString(), itr->value.GetDouble());
						}
						else if (itr->value.IsInt())
						{
							// generic parameters passed as Inegers are converted to float for param_set
							it->param_set(itr->name.GetString(), itr->value.GetInt());
						}
					}
				}
			}
		}
	}
}

std::shared_ptr<Camera> CaptureNode::cameraById(const char * unique_id)
{
	for (auto c : m_cameras)
	{
		if (c->unique_id() == unique_id)
			return c;
	}
	return std::shared_ptr<Camera>();
}

const std::vector<std::shared_ptr<Camera> > CaptureNode::cameraList()
{
	std::lock_guard<std::mutex> lock(m_mutex);

	return  std::vector<std::shared_ptr<Camera> >(m_cameras);
}

std::string CaptureNode::sync_port() const
{
	if (m_sync.get())
		return m_sync->port();
	return "";
}

void CaptureNode::set_global_framerate(int freq, int duration_us, bool external_sync)
{
	// Cannot be called while recording

	if (duration_us)
		m_global_pulse_duration = duration_us;
	m_global_framerate = freq;

	m_external_sync_preview = false; // TODO: option to be added to UI
	m_external_sync_recording = external_sync;

	if (m_sync_active && m_sync.get())
	{
		std::cout << "Set global framerate to " << freq << std::endl;
		if (duration_us)
			std::cout << "Set global pulse duration to " << duration_us << std::endl;
		if (m_external_sync_preview)
			std::cout << "Using external sync: Preview" << std::endl;
		if (m_external_sync_recording)
			std::cout << "Using external sync: Recording" << std::endl;

		m_sync->start(m_global_framerate, m_global_pulse_duration, m_external_sync_preview);
	}
}

bool CaptureNode::can_record() const
{
	return m_recording_cameras.empty() && !m_capture_folders.empty();
}

std::vector<std::string> CaptureNode::get_take_recording_folders()
{
	namespace fs = boost::filesystem;

	std::vector<std::string> folders;

	std::string timestamp;
	{
		auto t = std::time(nullptr);
		auto tm = *std::localtime(&t);

		std::ostringstream oss;
		oss << std::put_time(&tm, "%Y%m%d_%H%M%S");
		timestamp = oss.str();
	}

	for (auto& it : m_capture_folders)
	{
		fs::path new_folder = fs::path(it.first) / timestamp;
		folders.push_back(new_folder.string());

		if (!fs::exists(new_folder))
			fs::create_directories(new_folder);
	}

	return folders;
}

void CaptureNode::record_image_sequence(int frame_count)
{
	setBurstCount(frame_count);
	if (frame_count>1)
	{
		GotoState(STATE_BURST_PREPARE1);
		GotoState(STATE_BURST_PREPARE2);
		GotoState(STATE_BURST_START);
		GotoState(STATE_BURST_FINALIZE);
	}
	else
	{
		GotoState(STATE_SINGLESHOT_PREPARE1);
		GotoState(STATE_SINGLESHOT_PREPARE2);
		GotoState(STATE_SINGLESHOT_START);
		GotoState(STATE_SINGLESHOT_FINALIZE);
	}
	GotoState(STATE_PREVIEW);
}

void CaptureNode::start_recording_all()
{
	GotoState(STATE_CONTINUOUS_PREPARE1);
	GotoState(STATE_CONTINUOUS_PREPARE2);
	GotoState(STATE_CONTINUOUS_START);
}

void CaptureNode::prepare_single()
{
	std::cout << "STATUS> Prepare Single" << std::endl;

	namespace fs = boost::filesystem;

	// Record to the fastest drive found
	const std::vector<std::string> all_folders = get_take_recording_folders();

	std::cout << "Recording " << m_burstCount << " frame(s)" << std::endl;

	m_recording_cameras.clear();

	std::lock_guard<std::mutex> lock(m_mutex);

	for (auto& cam : m_cameras)
	{
		if (cam->capturing() && !cam->is_audio_only()) // Audio only devices not recorded in single-frame
		{
			cam->m_debug_in_capture_cycle = true;
			m_recording_cameras.push_back(cam);
		}
	}

	for (auto& cam : m_recording_cameras)
	{
		cam->m_debug_timings = true;
		cam->m_prepare_recording = true;
	}

	// Change bitdepth for single capture
	for (auto& cam : m_recording_cameras)
	{
		if (cam->set_bitdepth(m_bitdepth_maximum))
			cam->block_until_next_frame(0.240);
		cam->set_record_as_raw(m_image_format_raw);
	}

	// Begin recording
	int i=0;
	for (auto& cam : m_recording_cameras)
	{
		if (m_burstCount>1)
		{
			// Burst: send all folders, so that each frame gets written to a different drive

			cam->start_recording(all_folders, true, m_burstCount); // Wait for trigger
		}
		else
		{
			// Single frame: send one folder, different for each camera

			std::vector<std::string> folders;
			folders.push_back(all_folders[(i++)%all_folders.size()]);

			cam->start_recording(folders, true, m_burstCount); // Wait for trigger
		}
	}
}

void CaptureNode::recording_trigger()
{
	std::cout << "STATUS> Trigger" << std::endl;

	// Trigger Recording on all cameras that have no hardware sync
	for (auto& cam : m_recording_cameras)
	{
		if (!cam->using_hardware_sync())
			cam->software_trigger();
	}

	// Make sure there is a 250ms gap and restart sync
	if (sync_connected())
	{
		boost::this_thread::sleep_for(boost::chrono::milliseconds(250));
		start_recording_sync();
	}
}

void CaptureNode::finalize_single()
{
	std::cout << "STATUS> Finalize Single" << std::endl;

	// Create new json document, to contain summary from all cameras
	shared_json_doc all_cameras_doc(new rapidjson::Document());
	all_cameras_doc->SetObject();
	rapidjson::Value cameras(rapidjson::kArrayType);

	// Block until cameras have stopped recording
	{
		for (auto& cam : m_recording_cameras)
		{
			while (cam->recording()) {
				boost::this_thread::sleep_for(boost::chrono::milliseconds(10));
			}
		}
	}

	for (auto& cam : m_recording_cameras)
		cam->m_debug_timings = false;

	// Get last recording summary from all cameras
	{
		for (auto& cam : m_recording_cameras)
		{
			shared_json_doc cam_summary = cam->last_summary();
			if (cam_summary)
			{
				// Merge this camera's json data into the common document
				rapidjson::Value cam_root(rapidjson::kObjectType);
				cam_root.CopyFrom(*cam_summary.get(), all_cameras_doc->GetAllocator());
				cameras.PushBack(cam_root, all_cameras_doc->GetAllocator());
			}

			cam->m_debug_in_capture_cycle = false;
			cam->set_bitdepth(m_bitdepth_default);
		}
	}

	// Finalize json structure
	all_cameras_doc->AddMember("cameras", cameras, all_cameras_doc->GetAllocator());

	m_recording_cameras.clear();

	m_last_summary = all_cameras_doc;
}

void CaptureNode::prepare_multi_stage1()
{
	std::cout << "STATUS> Prepare Multi" << std::endl;

	m_recording_cameras.clear();

	std::vector<std::pair<std::shared_ptr<Camera>, int> > to_record;

	{
		std::lock_guard<std::mutex> lock(m_mutex);

		// List of cameras to record, with estimated bandwidth
		for (auto& cam : m_cameras)
		{
			if (cam->capturing())
			{
				cam->m_debug_in_capture_cycle = true;

				// Bitdepth is the same as the continuous preview, we don't need to change it
				//cam->set_bitdepth(m_bitdepth_default);

				cam->set_record_as_raw(true); // TODO Option to choose between .ava and .avi

				int nthreads = (int)(1 + (cam->bandwidth() / 1024 / 1024 / m_bandwidth_per_thread));

				std::cout << "RECORD " << cam->unique_id() << " BW:" << (cam->bandwidth()/1024/1024) << "MB/s Threads:" << nthreads << std::endl; // DEBUG

				to_record.push_back(std::make_pair(cam, nthreads));
			}
		}
	}

	std::sort(to_record.begin(), to_record.end(), [](std::pair < std::shared_ptr<Camera>, int>& a, std::pair < std::shared_ptr<Camera>, int>& b) {return a.second > b.second; });

	// Sort list of folders
	auto folders = get_take_recording_folders();

	// Start record on each camera, passing the folder to use
	int i = 0;
	for (auto it : to_record)
	{
		std::vector<std::string> cam_folders;
		for (int t = 0;t < it.second;t++, i++)
			cam_folders.push_back(folders[i%folders.size()]);

		for (auto f : cam_folders)
			std::cout << "Recording " << it.first->unique_id() << " to " << f << std::endl; // DEBUG

		it.first->start_recording(cam_folders, true);
		m_recording_cameras.push_back(it.first);
	}

	for (auto& cam : m_recording_cameras)
		cam->m_debug_timings = true;
}

void CaptureNode::prepare_multi_stage2()
{
	for (auto& cam : m_recording_cameras)
	{
		cam->remove_recording_hold();
	}

	if (sync_connected())
	{
		stop_sync(); // Stop preview pulses
	}
}

void CaptureNode::stop_recording_all()
{
	std::cout << "STATUS> Stop Recording" << std::endl;

	// Create new json document, to contain summary from all cameras
	shared_json_doc all_cameras_doc(new rapidjson::Document());
	all_cameras_doc->SetObject();
	rapidjson::Value cameras(rapidjson::kArrayType);

	for (auto& cam : m_recording_cameras)
	{
		cam->stop_recording();
	}

	for (auto& cam : m_recording_cameras)
	{
		shared_json_doc cam_summary = cam->last_summary();

		if (cam_summary)
		{
			// Merge this camera's json data into the common document
			rapidjson::Value cam_root(rapidjson::kObjectType);
			cam_root.CopyFrom(*cam_summary.get(), all_cameras_doc->GetAllocator());
			cameras.PushBack(cam_root, all_cameras_doc->GetAllocator());
		}
	}

	for (auto& cam : m_recording_cameras)
	{
		cam->m_debug_in_capture_cycle = false;
		cam->set_bitdepth(m_bitdepth_default);
	}

	for (auto& cam : m_recording_cameras)
		cam->m_debug_timings = false;

	// Finalize json structure
	all_cameras_doc->AddMember("cameras", cameras, all_cameras_doc->GetAllocator());

	m_recording_cameras.clear();

	m_last_summary = all_cameras_doc;
}

void CaptureNode::stop_sync()
{
	if (m_sync.get() && m_sync_active)
	{
		m_sync->stop();
		m_sync_active = false;
	}
}

void CaptureNode::start_recording_sync()
{
	if (m_sync.get())
	{
		m_sync->start(m_global_framerate, m_global_pulse_duration, m_external_sync_recording);
		m_sync_active = true;
	}
}

void CaptureNode::start_preview_sync()
{
	if (m_sync.get())
	{
		m_sync->start(m_global_framerate, m_global_pulse_duration, m_external_sync_preview);
		m_sync_active = true;
	}
}

void CaptureNode::GenericMessage(const std::string& msg)
{
	//printf("DEBUG> Generic Message Received: %s\n", msg.c_str());

	for (auto listener : PythonEngine::Instance().m_notification_listeners)
	{
		listener->receiveMessage(msg.c_str());
	}
}

void CaptureNode::ChangeState(CaptureNodeState fromState, CaptureNodeState toState)
{
	printf("DEBUG> State Change from %s to %s\n", stateToString(fromState), stateToString(toState));

	for (auto listener : PythonEngine::Instance().m_notification_listeners)
	{
		listener->changeState(stateToString(toState));
	}

	switch (toState) {
	case STATE_PREVIEW:
		start_preview_sync();
		break;

	case STATE_SINGLESHOT_PREPARE1:
	case STATE_BURST_PREPARE1:
		prepare_single();
		break;
	case STATE_SINGLESHOT_PREPARE2:
	case STATE_BURST_PREPARE2:
		prepare_multi_stage2();
		break;
	case STATE_SINGLESHOT_START:
	case STATE_BURST_START:
		recording_trigger();
		break;
	case STATE_SINGLESHOT_FINALIZE:
	case STATE_BURST_FINALIZE:
		finalize_single();
		break;

	case STATE_CONTINUOUS_PREPARE1:
		prepare_multi_stage1();
		break;
	case STATE_CONTINUOUS_PREPARE2:
		prepare_multi_stage2();
		break;
	case STATE_CONTINUOUS_START:
		recording_trigger();
		break;
	case STATE_STOP_SYNC:
		stop_sync(); // Stop recording pulses
		break;
	case STATE_STOP:
		stop_recording_all();
		break;
	}
}

static const char * stateToString(CaptureNodeState s)
{
	switch (s) {
#define BUILD_ENUM_CASE(s) case s: return #s
	BUILD_ENUM_CASE(STATE_PREVIEW);
	BUILD_ENUM_CASE(STATE_SINGLESHOT_PREPARE1);
	BUILD_ENUM_CASE(STATE_SINGLESHOT_PREPARE2);
	BUILD_ENUM_CASE(STATE_SINGLESHOT_START);
	BUILD_ENUM_CASE(STATE_SINGLESHOT_FINALIZE);
	BUILD_ENUM_CASE(STATE_BURST_PREPARE1);
	BUILD_ENUM_CASE(STATE_BURST_PREPARE2);
	BUILD_ENUM_CASE(STATE_BURST_START);
	BUILD_ENUM_CASE(STATE_BURST_FINALIZE);
	BUILD_ENUM_CASE(STATE_CONTINUOUS_PREPARE1);
	BUILD_ENUM_CASE(STATE_CONTINUOUS_PREPARE2);
	BUILD_ENUM_CASE(STATE_CONTINUOUS_START);
	BUILD_ENUM_CASE(STATE_STOP_SYNC);
	BUILD_ENUM_CASE(STATE_STOP);
	BUILD_ENUM_CASE(STATE_EXIT);
#undef BUILD_ENUM_CASE
	default: return "UNKNOWN";
	}
}

max_issues_repo_name: edanvoye/ava-capture


text:
// (C) 2016 Marvin Sielenkemper

#pragma once

#include <boost/signals2.hpp>
#include <boost/noncopyable.hpp>
#include <string>
#include <memory>

class Serial : boost::noncopyable {
public:
  typedef boost::signals2::signal<void(std::string const&)>
      LineReceived;

  Serial();
  ~Serial();

  LineReceived lineReceived;

private:
  struct Impl;

  std::unique_ptr<Impl> m_implPtr;
};

max_stars_repo_name: sielenk/furnace

max_issues_repo_name: sielenk/furnace

max_forks_repo_name: sielenk/furnace


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

#include <boost/gil/gil_all.hpp>
#include <boost/gil/extension/toolbox/metafunctions/pixel_bit_size.hpp>

using namespace boost;
using namespace gil;

BOOST_AUTO_TEST_SUITE( pixel_bit_size_test )

BOOST_AUTO_TEST_CASE( pixel_bit_size_test )
{
    typedef bit_aligned_image5_type< 16, 16, 16, 8, 8, devicen_layout_t< 5 > >::type image_t;
    BOOST_STATIC_ASSERT(( pixel_bit_size<image_t::view_t::reference>::value == 64 ));
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: smart-make/boost

max_issues_repo_name: smart-make/boost

max_forks_repo_name: smart-make/boost


text:
/*
 * Copyright (c) 2013, The University of Oxford
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 3. Neither the name of the University of Oxford nor the names of its
 *    contributors may be used to endorse or promote products derived from this
 *    software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * A DataBlob relay supporting the basic Pelican Output types
 */
#include <QtCore/QCoreApplication>
#include <boost/program_options.hpp>
#include "utility/Config.h"
#include <iostream>
#include "DataBlobRelay.h"

namespace opts = boost::program_options;
using namespace pelican;

Config createConfig(const opts::variables_map&);
opts::variables_map process_options(int argc, char** argv);

int main( int argc, char** argv ) {
    // parse the args
    opts::variables_map options = process_options(argc,argv);

    // start up the relay
    int rv = 0;
    DataBlobRelay* relay = 0;
    try {
        Config config = createConfig(options);
        Config::TreeAddress address;
        address << Config::NodeId("PelicanRelay", "");

        QCoreApplication app(argc, argv );
        relay = new DataBlobRelay( &config, address );
        rv = app.exec();
    }
    catch(const boost::program_options::error& err) {
        std::cerr << "pelicanRelay ERROR: " << err.what() << std::endl;
    }
    catch (const QString& err)
    {
        std::cerr << "pelicanRelay ERROR: " << err.toStdString() << std::endl;
        rv = 1;
    }
    delete relay;
    return rv;

}

/**
 * @details
 * Create a Configuration XML document for the relay
 */
opts::variables_map process_options(int argc, char** argv)
{
    // Check that argc and argv are nonzero
    if (argc == 0 || argv == NULL) throw QString("No command line.");

    // Declare the supported options.
    opts::options_description desc("Allowed options");
    desc.add_options()
        ("help,h", "Produce help message.")
        ("config,c", opts::value<std::string>(), "Set configuration file.");

    // Parse the command line arguments.
    opts::variables_map varMap;
    opts::store(opts::command_line_parser(argc, argv).options(desc)
            .run(), varMap);
    opts::notify(varMap);

    // Check for help message.
    if (varMap.count("help")) {
        std::cout << desc << std::endl;
        exit(0);
    }
    return varMap;
}

Config createConfig(const opts::variables_map& varMap)
{
    // Get the configuration file name.
    std::string configFilename = "";
    if (varMap.count("config"))
        configFilename = varMap["config"].as<std::string>();

    pelican::Config config;
    if (!configFilename.empty()) {
        config = pelican::Config(QString(configFilename.c_str()));
    } else {
        throw QString("must specify a configuration file");
    }
    return config;
}

max_stars_repo_name: pelican/pelican

max_issues_repo_name: pelican/pelican

max_forks_repo_name: pelican/pelican


text:
#include <boost/range/adaptor/indexed.hpp>
#include <gtest/gtest.h>
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <vector>
#include <optional>

#include "byte_stream.h"
#include "crypto/hash.h"
#include "cryptonote_basic/account.h"
#include "cryptonote_basic/cryptonote_basic.h"
#include "cryptonote_basic/cryptonote_format_utils.h"
#include "cryptonote_core/cryptonote_tx_utils.h"
#include "serialization/json_object.h"

namespace test
{
    cryptonote::transaction
    make_miner_transaction(cryptonote::account_public_address const& to)
    {
        cryptonote::transaction tx{};
        if (!cryptonote::construct_miner_tx(cryptonote::network_type::MAINNET, 0, 0, 5000, 500, 500, to, tx))
            throw std::runtime_error{"transaction construction error"};

        crypto::hash id{0};
        if (!cryptonote::get_transaction_hash(tx, id))
            throw std::runtime_error{"could not get transaction hash"};

        return tx;
    }

    cryptonote::transaction
    make_transaction(
        cryptonote::account_keys const& from,
        std::vector<cryptonote::transaction> const& sources,
        std::vector<cryptonote::account_public_address> const& destinations,
        bool rct,
        bool bulletproof)
    {
        std::uint64_t source_amount = 0;
        std::vector<cryptonote::tx_source_entry> actual_sources;
        for (auto const& source : sources)
        {
            std::vector<cryptonote::tx_extra_field> extra_fields;
            if (!cryptonote::parse_tx_extra(source.extra, extra_fields))
                throw std::runtime_error{"invalid transaction"};

            cryptonote::tx_extra_pub_key key_field{};
            if (!cryptonote::find_tx_extra_field_by_type(extra_fields, key_field))
                throw std::runtime_error{"invalid transaction"};

            for (auto const& input : boost::adaptors::index(source.vout))
            {
                source_amount += input.value().amount;
                auto const& key = boost::get<cryptonote::txout_to_key>(input.value().target);

                actual_sources.push_back(
                    {{}, 0, key_field.pub_key, {}, std::size_t(input.index()), input.value().amount, rct, rct::identity()}
                );

                for (unsigned ring = 0; ring < 10; ++ring)
                    actual_sources.back().push_output(input.index(), key.key, input.value().amount);
            }
        }

        std::vector<cryptonote::tx_destination_entry> to;
        for (auto const& destination : destinations)
            to.push_back({(source_amount / destinations.size()), destination, false});

        cryptonote::transaction tx{};

        crypto::secret_key tx_key{};
        std::vector<crypto::secret_key> extra_keys{};

        std::unordered_map<crypto::public_key, cryptonote::subaddress_index> subaddresses;
        subaddresses[from.m_account_address.m_spend_public_key] = {0,0};

        if (!cryptonote::construct_tx_and_get_tx_key(from, subaddresses, actual_sources, to, std::nullopt, {}, tx, 0, tx_key, extra_keys, rct, { bulletproof ? rct::RangeProofBulletproof : rct::RangeProofBorromean, bulletproof ? 2 : 0 }))
            throw std::runtime_error{"transaction construction error"};

        return tx;
    }
}

namespace
{
    template<typename T>
    T test_json(const T& value)
    {
      epee::byte_stream buffer;
      {
        rapidjson::Writer<epee::byte_stream> dest{buffer};
        cryptonote::json::toJsonValue(dest, value);
      }

      rapidjson::Document doc;
      doc.Parse(reinterpret_cast<const char*>(buffer.data()), buffer.size());
      if (doc.HasParseError())
      {
        throw cryptonote::json::PARSE_FAIL();
      }

      T out{};
      cryptonote::json::fromJsonValue(doc, out);
      return out;
    }
} // anonymous

TEST(JsonSerialization, VectorBytes)
{
    EXPECT_EQ(std::vector<std::uint8_t>{}, test_json(std::vector<std::uint8_t>{}));
    EXPECT_EQ(std::vector<std::uint8_t>{0x00}, test_json(std::vector<std::uint8_t>{0x00}));
}

TEST(JsonSerialization, InvalidVectorBytes)
{
    rapidjson::Document doc;
    doc.SetString("1");

    std::vector<std::uint8_t> out;
    EXPECT_THROW(cryptonote::json::fromJsonValue(doc, out), cryptonote::json::BAD_INPUT);
}

TEST(JsonSerialization, MinerTransaction)
{
    cryptonote::account_base acct;
    acct.generate();
    const auto miner_tx = test::make_miner_transaction(acct.get_keys().m_account_address);

    crypto::hash tx_hash{};
    ASSERT_TRUE(cryptonote::get_transaction_hash(miner_tx, tx_hash));

    cryptonote::transaction miner_tx_copy = test_json(miner_tx);

    crypto::hash tx_copy_hash{};
    ASSERT_TRUE(cryptonote::get_transaction_hash(miner_tx_copy, tx_copy_hash));
    EXPECT_EQ(tx_hash, tx_copy_hash);

    cryptonote::blobdata tx_bytes{};
    cryptonote::blobdata tx_copy_bytes{};

    ASSERT_TRUE(cryptonote::t_serializable_object_to_blob(miner_tx, tx_bytes));
    ASSERT_TRUE(cryptonote::t_serializable_object_to_blob(miner_tx_copy, tx_copy_bytes));

    EXPECT_EQ(tx_bytes, tx_copy_bytes);
}

// Sumo doesnot have any non-encrypted transactions
/*
TEST(JsonSerialization, RegularTransaction)
{
    cryptonote::account_base acct1;
    acct1.generate();

    cryptonote::account_base acct2;
    acct2.generate();

    const auto miner_tx = test::make_miner_transaction(acct1.get_keys().m_account_address);
    const auto tx = test::make_transaction(
        acct1.get_keys(), {miner_tx}, {acct2.get_keys().m_account_address}, false, false
    );

    crypto::hash tx_hash{};
    ASSERT_TRUE(cryptonote::get_transaction_hash(tx, tx_hash));

    cryptonote::transaction tx_copy = test_json(tx);

    crypto::hash tx_copy_hash{};
    ASSERT_TRUE(cryptonote::get_transaction_hash(tx_copy, tx_copy_hash));
    EXPECT_EQ(tx_hash, tx_copy_hash);

    cryptonote::blobdata tx_bytes{};
    cryptonote::blobdata tx_copy_bytes{};

    ASSERT_TRUE(cryptonote::t_serializable_object_to_blob(tx, tx_bytes));
    ASSERT_TRUE(cryptonote::t_serializable_object_to_blob(tx_copy, tx_copy_bytes));

    EXPECT_EQ(tx_bytes, tx_copy_bytes);
}
*/

TEST(JsonSerialization, RingctTransaction)
{
    cryptonote::account_base acct1;
    acct1.generate();

    cryptonote::account_base acct2;
    acct2.generate();

    const auto miner_tx = test::make_miner_transaction(acct1.get_keys().m_account_address);
    const auto tx = test::make_transaction(
        acct1.get_keys(), {miner_tx}, {acct2.get_keys().m_account_address}, true, false
    );

    crypto::hash tx_hash{};
    ASSERT_TRUE(cryptonote::get_transaction_hash(tx, tx_hash));

    cryptonote::transaction tx_copy = test_json(tx);

    crypto::hash tx_copy_hash{};
    ASSERT_TRUE(cryptonote::get_transaction_hash(tx_copy, tx_copy_hash));
    EXPECT_EQ(tx_hash, tx_copy_hash);

    cryptonote::blobdata tx_bytes{};
    cryptonote::blobdata tx_copy_bytes{};

    ASSERT_TRUE(cryptonote::t_serializable_object_to_blob(tx, tx_bytes));
    ASSERT_TRUE(cryptonote::t_serializable_object_to_blob(tx_copy, tx_copy_bytes));

    EXPECT_EQ(tx_bytes, tx_copy_bytes);
}

TEST(JsonSerialization, BulletproofTransaction)
{
    cryptonote::account_base acct1;
    acct1.generate();

    cryptonote::account_base acct2;
    acct2.generate();

    const auto miner_tx = test::make_miner_transaction(acct1.get_keys().m_account_address);
    const auto tx = test::make_transaction(
        acct1.get_keys(), {miner_tx}, {acct2.get_keys().m_account_address}, true, true
    );

    crypto::hash tx_hash{};
    ASSERT_TRUE(cryptonote::get_transaction_hash(tx, tx_hash));

    cryptonote::transaction tx_copy = test_json(tx);

    crypto::hash tx_copy_hash{};
    ASSERT_TRUE(cryptonote::get_transaction_hash(tx_copy, tx_copy_hash));
    EXPECT_EQ(tx_hash, tx_copy_hash);

    cryptonote::blobdata tx_bytes{};
    cryptonote::blobdata tx_copy_bytes{};

    ASSERT_TRUE(cryptonote::t_serializable_object_to_blob(tx, tx_bytes));
    ASSERT_TRUE(cryptonote::t_serializable_object_to_blob(tx_copy, tx_copy_bytes));

    EXPECT_EQ(tx_bytes, tx_copy_bytes);
}

max_stars_repo_name: thelameuser/sumoexplorer

max_issues_repo_name: thelameuser/sumoexplorer

max_forks_repo_name: thelameuser/sumoexplorer


text:
// Copyright (c) 2015
// Author: Chrono Law
#include <sstream>
#include <std.hpp>
using namespace std;

// disable pragma warning
#define BOOST_ALLOW_DEPRECATED_HEADERS

#include <boost/progress.hpp>
using namespace boost;

//////////////////////////////////////////

int main()
{
    {
        boost::progress_timer t;

    }
    {
        boost::progress_timer t;
    }

    stringstream ss;
    {
        progress_timer t(ss);
    }
    cout << ss.str();
}


text:
/*
 * File:   RawClient.cpp
 * Author: Paolo D'Apice
 *
 * Created on December 31, 2011, 2:46 PM
 */

#include "net/sf1r/Errors.hpp"
#include "RawClient.hpp"
#include <boost/array.hpp>
#include <glog/logging.h>
#include <sys/time.h>
#include <boost/bind.hpp>

NS_IZENELIB_SF1R_BEGIN

namespace bs = boost::system;

using ba::ip::tcp;
using std::string;

#define CONNECT_TIMEOUT 5
#define WRITE_TIMEOUT 5
#define READ_TIMEOUT 30

namespace {

/**
 * Size of unsigned integer (32 bits).
 */
const size_t UINT_SIZE = sizeof(uint32_t);

/**
 * Header size, i.e. two unsigned values for:
 * - sequence number
 * - message length
 */
const size_t HEADER_SIZE = 2 * UINT_SIZE;

}

uint32_t
RawClient::idSequence = 0;

RawClient::RawClient(ba::io_service& service,
                     const string& zkpath)
        : socket(service), deadline_(service), io_service_(service),
        status(Idle), is_aborted_(false), path(zkpath), id(++idSequence) {
    try {
        deadline_.expires_at(boost::posix_time::pos_infin);
    } catch (bs::system_error& e) {
    }

    CHECK_EQ(Idle, status) << "not Idle (" << id << ")";
    DLOG(INFO) << "Correctly instantiated (" << id << ")";
}

RawClient::~RawClient() {
    //clear_timeout();
    CHECK_NE(Busy, status);
    try {
        DLOG(INFO) << "closing (" << id << ") ...";

        if (socket.is_open())
            socket.shutdown(socket.shutdown_both);
        socket.close();

        LOG(INFO) << "connection closed (" << id << ")";
    } catch (bs::system_error& e) {
        LOG(WARNING) << e.what();
    }

    LOG(INFO) << "Correctly destroyed (" << id << ")";
}

void RawClient::do_connect(const std::string& host, const std::string& port,
    const size_t timeout)
{
    try {
        DLOG(INFO) << "configuring socket ...";
        // TODO: windows?
        struct timeval tv;
        tv.tv_sec = timeout;
        tv.tv_usec = 0;
        setsockopt(socket.native(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof (tv));
        setsockopt(socket.native(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof (tv));

        DLOG(INFO) << "connecting to [" << host << ":" << port << "] (" << id << ") ...";
        connect_with_timeout(host, port);

        DLOG(INFO) << "connected (" << id << ")";
    } catch (bs::system_error& e) {
        status = Invalid;
        LOG(ERROR) << "create rawclient error";
        LOG(ERROR) << e.what();
        throw NetworkError(e.what());
    }
}

void async_cb(const bs::error_code& error, std::size_t bytes, bs::error_code* ret_ec)
{
    *ret_ec = error;
}

void RawClient::prepare_timeout(int sec)
{
    is_aborted_ = false;
    deadline_.expires_from_now(boost::posix_time::seconds(sec));
    check_deadline();
}

void RawClient::clear_timeout()
{
    // delete while socket is still open, we need wake up timeout event
    // to make sure timeout handler removed.
    is_aborted_ = true;
    deadline_.expires_at(deadline_timer::traits_type::now());
    while (io_service_.poll_one() > 0)
        ;
    io_service_.reset();
}

void RawClient::connect_with_timeout(const std::string& host, const std::string& port)
{
    try
    {
        ba::ip::tcp::resolver resolver(io_service_);
        ba::ip::tcp::resolver::query query(host, port);
        tcp::resolver::iterator iter = resolver.resolve(query);

        prepare_timeout(CONNECT_TIMEOUT);

        bs::error_code ec = ba::error::would_block;

        ba::async_connect(socket, iter,
            boost::bind(&async_cb, _1, 0, &ec));

        do io_service_.run_one(); while (ec == ba::error::would_block);

        if (ec || !socket.is_open())
        {
            throw bs::system_error(ec ? ec : ba::error::operation_aborted);
        }
        clear_timeout();
    }
    catch(const bs::system_error& e)
    {
        clear_timeout();
        throw;
    }
}

size_t RawClient::read_with_timeout(const ba::mutable_buffers_1& buf)
{
    prepare_timeout(READ_TIMEOUT + ba::buffer_size(buf)/1024/1024);

    bs::error_code ec = ba::error::would_block;
    ba::async_read(socket, buf, boost::bind(&async_cb, _1, _2, &ec));
    do io_service_.run_one(); while(ec == ba::error::would_block);

    clear_timeout();
    if (ec)
    {
        throw bs::system_error(ec);
    }
    return ba::buffer_size(buf);
}

size_t RawClient::write_with_timeout(const boost::array<ba::const_buffer,3>& buffers)
{
    prepare_timeout(WRITE_TIMEOUT);

    bs::error_code ec = ba::error::would_block;
    ba::async_write(socket, buffers, boost::bind(&async_cb, _1, _2, &ec));
    do io_service_.run_one(); while(ec == ba::error::would_block);

    clear_timeout();
    if (ec)
    {
        throw bs::system_error(ec);
    }
    return ba::buffer_size(buffers);
}

void RawClient::check_deadline()
{
    if (is_aborted_)
    {
        //Clear timeout by hand here. Not a deadline.
        return;
    }
    if (deadline_.expires_at() <= deadline_timer::traits_type::now())
    {
        LOG(INFO) << "deadline for " ;
        boost::system::error_code ignored_ec;
        try
        {
            if (socket.is_open() && status != Invalid)
            {
                status = Invalid;
                socket.shutdown(ba::ip::tcp::socket::shutdown_both, ignored_ec);
                socket.close(ignored_ec);
                //socket.cancel();
            }
            // There is no longer an active deadline. The expiry is set to infinity.
            deadline_.expires_at(boost::posix_time::pos_infin);
        }
        catch(const bs::system_error& e)
        {
            LOG(ERROR) << "check_deadline error : " << e.what();
        }
    }
    deadline_.async_wait(boost::bind(&RawClient::check_deadline, this));
}

bool
RawClient::isConnected() {
    // is the socket open?
    if (not socket.is_open()) {
        LOG(WARNING) << "Socket is not open";
        return false;
    }

    // is the endpoint active?
    try {
        socket.remote_endpoint();
    } catch (bs::system_error& e) {
        LOG(WARNING) << "Endpoint error: " << e.what();
        return false;
    }

    return true;
}

void
RawClient::sendRequest(const uint32_t& sequence, const string& data) {
    if (not isConnected()) {
        // TODO: keep alive?
        status = Invalid;
        throw NetworkError("Not connected in RawClient");
    }

    CHECK_EQ(Idle, status) << "not Idle (" << id << ")";
    status = Busy;

    DLOG(INFO) << "Sending raw request (" << id << "): ["
               << sequence << ", "
               << data.length() << ", "
               << data << "] ...";

    uint32_t seq = htonl(sequence);
    uint32_t len = htonl(data.length());

    boost::array<ba::const_buffer,3> buffers;
    buffers[0] = ba::buffer(&seq, UINT_SIZE);
    buffers[1] = ba::buffer(&len, UINT_SIZE);
    buffers[2] = ba::buffer(data);

    size_t n = 0;
    try {
        n += write_with_timeout(buffers);
    } catch (bs::system_error& e) {
        status = Invalid;
        LOG(ERROR) << "write request to socket error";
        LOG(ERROR) << e.what();
        throw NetworkError(e.what());
    }

    if (n != HEADER_SIZE + data.length()) {
        status = Invalid;
        throw ServerError("write: Write size mismatch");
    }

    // do not change the status
    CHECK_EQ(Busy, status) << "not Busy (" << id << ")";
    DLOG(INFO) << "Request sent (" << n << " bytes).";
}

Response
RawClient::getResponse() {
    if (not isConnected()) {
        // TODO: keep alive?
        status = Invalid;
        throw NetworkError("Not connected in RawClient");
    }

    CHECK_EQ(Busy, status) << "not Busy (" << id << ")";
    // do not change the status
    DLOG(INFO) << "Receiving response (" << id << ") ...";

    char header[HEADER_SIZE];
    size_t n = 0;

    try {
        n += read_with_timeout(ba::buffer(header));
    } catch (bs::system_error& e) {
        status = Invalid;
        LOG(ERROR) << "get response head from socket error";
        LOG(ERROR) << e.what();
        throw NetworkError(e.what());
    }

    if (n != sizeof(HEADER_SIZE)) {
        status = Invalid;
        throw ServerError("Read size mismatch");
    }

    uint32_t sequence, length;
    memcpy(&sequence, header, UINT_SIZE);
    memcpy(&length, header + UINT_SIZE, UINT_SIZE);

    sequence = ntohl(sequence);
    length = ntohl(length);

    static const uint32_t small_response_size = 1024*4;
    static char stack_array[small_response_size];
    char *data = NULL;
    if (length > small_response_size)
    {
        data = new char[length];
    }
    else
    {
        data = stack_array;
    }

    try {
        n = read_with_timeout(ba::buffer(data, length));
    } catch (bs::system_error& e) {
        status = Invalid;
        LOG(ERROR) << "get response body from socket error";
        LOG(ERROR) << e.what();
        if (length > small_response_size)
            delete[] data;
        throw NetworkError(e.what());
    } catch(...)
    {
        if (length > small_response_size)
            delete[] data;
        throw;
    }

    if (n != length) {
        status = Invalid;
        if (length > small_response_size)
            delete[] data;
        throw ServerError("Read size mismatch");
    }

    string response(data, length - 1); // skip the final '\0'
    DLOG(INFO) << "Response (" << id << "): ["
               << sequence << ", "
               << length << ", "
               << response << "]";

    LOG(INFO) << "Response received (" << n + HEADER_SIZE << " bytes)";

    if (length > small_response_size)
        delete[] data;

    status = Idle;
    return boost::make_tuple(sequence, response);
}

NS_IZENELIB_SF1R_END

max_stars_repo_name: izenecloud/izenelib

max_issues_repo_name: izenecloud/izenelib

max_forks_repo_name: izenecloud/izenelib


text:
#include <vector>
#include <type_traits>

#include <Eigen/Eigen>
#include <xtensor/xtensor.hpp>
#include <xtensor/xarray.hpp>

#include <iostream>

namespace detail
{
    template <class T>
    struct is_xtensor : std::false_type
    {
    };

    template <class T>
    struct is_xtensor<xt::xarray<T>> : std::true_type
    {
    };

    template <class T, size_t N>
    struct is_xtensor<xt::xtensor<T, N>> : std::true_type
    {
    };

    template <class T, typename = void>
    struct io_impl
    {
        static T load()
        {
            std::cout << "load generic" << std::endl;
            return T();
        }

        static void dump(const T& data){
            std::cout << "dump generic" << std::endl;
        }
    };

    template <class T>
    struct io_impl<T, typename std::enable_if<std::is_base_of<Eigen::DenseBase<T>, T>::value>::type>
    {
        static T load()
        {
            std::cout << "load Eigen::DenseBase" << std::endl;
            return T();
        }

        static void dump(const T& data)
        {
            std::cout << "dump Eigen::DenseBase" << std::endl;
        }
    };

    template <class T>
    struct io_impl<T, typename std::enable_if<is_xtensor<T>::value>::type>
    {
        static T load()
        {
            std::cout << "load xt::xarray<T> or xt::xtensor<T, N>" << std::endl;
            return T();
        }

        static void dump(const T& data){
            std::cout << "dump xt::xarray<T> or xt::xtensor<T, N>" << std::endl;
        }
    };

    template <class T>
    struct io_impl<T, typename std::enable_if<std::is_same<std::vector<typename T::value_type>, T>::value>::type>
    {
        static T load()
        {
            std::cout << "load std::vector" << std::endl;
            return T();
        }

        static void dump(const T& data){
            std::cout << "dump std::vector" << std::endl;
        }
    };
};

template <class T>
inline void dump(const T& data)
{
    return detail::io_impl<std::decay_t<T>>::dump(data);
}

template <class T>
inline T load()
{
    return detail::io_impl<std::decay_t<T>>::load();
}

int main()
{
    Eigen::ArrayXf A = Eigen::ArrayXf::Random(50);
    Eigen::MatrixXd B = Eigen::MatrixXd::Random(20, 5);
    xt::xarray<double> C = {{1, 2, 3}, {4, 5, 6}};
    xt::xtensor<double,2> D = {{1, 2, 3}, {4, 5, 6}};
    std::vector<double> E = {1, 2, 3};
    int F = 0;

    dump(A);
    dump(B);
    dump(C);
    dump(D);
    dump(E);
    dump(F);

    load<decltype(A)>();
    load<decltype(B)>();
    load<decltype(C)>();
    load<decltype(D)>();
    load<decltype(E)>();
    load<decltype(F)>();

    return 0;
}