text:
#ifndef BOOST_RANGE_ADAPTOR_DETAIL_TAKE_WHILE_ITERATOR_HPP
#define BOOST_RANGE_ADAPTOR_DETAIL_TAKE_WHILE_ITERATOR_HPP

// via PStade.Oven
//
// Copyright Shunsuke Sogame 2005-2007.
// 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)

// References:
//
// [1] Robert Ramey, head_iterator, Boost.Serialization, 2002.
//     http://www.boost.org/libs/serialization/doc/dataflow.html
// [2] John Torjo and Matthew Wilson, break_iterator, Iterable Range Library, 2004.
//     http://www.torjo.com/rangelib/index.html

#include <boost/assert.hpp>
#include <boost/iterator/iterator_adaptor.hpp>
#include <boost/iterator/iterator_categories.hpp>
#include "./minimum_pure.hpp"

namespace boost { namespace adaptors { namespace detail {

template< class Iterator, class Predicate >
struct take_while_iterator;

template< class Iterator, class Predicate >
struct take_while_iterator_super
{
    typedef
        ::boost::iterator_adaptor<
            take_while_iterator<Iterator, Predicate>,
            Iterator,
            ::boost::use_default,
            typename minimum_pure<
                ::boost::forward_traversal_tag,
                typename ::boost::iterator_traversal<Iterator>::type
            >::type
        >
    type;
};

template< class Iterator, class Predicate >
struct take_while_iterator :
    take_while_iterator_super<Iterator, Predicate>::type
{
private:
    typedef typename take_while_iterator_super<Iterator, Predicate>::type super_t;
    typedef typename super_t::reference ref_t;

public:
    take_while_iterator()
    { }

    take_while_iterator(Iterator it, Iterator last, Predicate pred) :
        super_t(it), m_last(last), m_pred(pred)
    {
        check_predicate();
    }

    template< class I >
    take_while_iterator(take_while_iterator<I, Predicate> const& other,
        typename ::boost::enable_if_convertible<I, Iterator>::type * = 0
    ) :
        super_t(other.base()), m_last(other.end()), m_pred(other.predicate())
    { }

    Iterator end() const
    {
        return m_last;
    }

    Predicate predicate() const
    {
        return m_pred;
    }

private:
    Iterator m_last;
    Predicate m_pred;

    template< class Other >
    bool is_compatible(Other const& other) const
    {
        return m_last == other.end();
    }

    bool is_end() const
    {
        return this->base() == m_last;
    }

    void check_predicate()
    {
        if (is_end())
            return;

        // Pass not a value but iterator to implement 'taken' effectively.
        if (!m_pred(this->base()))
            this->base_reference() = m_last;
    }

    friend class ::boost::iterator_core_access;

    ref_t dereference() const
    {
        BOOST_ASSERT(!is_end());
        return *this->base();
    }

    template< class I >
    bool equal(take_while_iterator<I, Predicate> const& other) const
    {
        BOOST_ASSERT(is_compatible(other));
        return this->base() == other.base();
    }

    void increment()
    {
        BOOST_ASSERT(!is_end());
        ++this->base_reference();
        check_predicate();
    }
};

}}} // namespace boost::adaptors::detail

#endif // BOOST_RANGE_ADAPTOR_DETAIL_TAKE_WHILE_ITERATOR_HPP

max_stars_repo_name: Flast/OvenToBoost

max_issues_repo_name: Flast/OvenToBoost

max_forks_repo_name: Flast/OvenToBoost


text:
#include <cstdio>
#include <chrono>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <set>

#include <boost/format.hpp>
#include <omp.h>
#include <opencv2/core/core.hpp>
#include <opencv2/imgcodecs.hpp>

#include "hls_helper.h"
#include "image_generator.h"
#include "util.h"
#include "vrc_meta_tool.h"

namespace filesystem = std::filesystem;
using namespace vrc_photo_album2;

auto main(int argc, char** argv) -> int {
  cv::CommandLineParser parser(
      argc, argv,
      "{input|./resources|input directory}"
      "{output|./export|output directory. required sub folter output_dir/(png,video)/}"
      "{font|/usr/share/fonts/TTF/migu-1c-regular.ttf|font path}"
      "{modified|.|check modified dir}"
      "{filepref|vrc_photo_album|file prefix}");

  const cv::Size output_size(1920, 1080);
  const filesystem::path font_path(parser.get<std::string>("font"));
  const filesystem::path input_dir(parser.get<std::string>("input"));
  const filesystem::path out_dir(parser.get<std::string>("output"));
  const filesystem::path output_dir(out_dir.string() + "/" + filesystem::path("png/").string());
  const filesystem::path video_dir(out_dir.string() + "/" +
                                   filesystem::path("video/").string());
  const filesystem::path check_modified_dir(input_dir.string() + "/" +
                                            parser.get<std::string>("modified"));
  const std::string file_pref(parser.get<std::string>("filepref"));
  const filesystem::path m3u8_file(file_pref + ".m3u8");
  std::cout << "input_dir: " << input_dir << ", output_dir: " << out_dir
            << ", modified_dir: " << check_modified_dir << ", m3u8_file: " << m3u8_file
            << ", font: " << font_path.c_str() << std::endl;
  const filesystem::path tmp_dir(filesystem::temp_directory_path().string() +
                                 "/vrc_photo_album/");

  filesystem::path video_file = video_dir.string() + m3u8_file.string();
  filesystem::path tmp_file   = tmp_dir.string() + m3u8_file.string();

  if (!filesystem::exists(video_dir.string() + "dummy.m3u8")) {
    std::string command = (boost::format("ffmpeg -loglevel error -loop 1 -framerate 1 "
                                         "-i blank.png -vcodec libx264 "
                                         "-pix_fmt yuv420p -r 5 -f hls -hls_time 10 -t 10 "
                                         "-hls_playlist_type vod -hls_segment_filename "
                                         "\"%sdummy%s.ts\" %sdummy.m3u8") %
                           video_dir.string() % "%1d" % video_dir.string())
                              .str();
    std::cout << command << std::endl;
    std::system(command.c_str());
  }

  // プログラム実行中に入力が更新されたらやり直し
  for (;;) {
    auto input_time = filesystem::last_write_time(check_modified_dir);
    auto input_tm   = conv_fclock(input_time);

    filesystem::create_directory(tmp_dir);

    // tmpファイルの存在確認
    filesystem::path* read_meta_file = &video_file;
    if (filesystem::exists(tmp_file)) {
      std::cout << "tmp m3u8 found" << std::endl;
      read_meta_file = &tmp_file;
    } else if (filesystem::exists(video_file)) {
      std::cout << "tmp m3u8 not found" << std::endl;
      filesystem::copy_file(video_file, tmp_file, filesystem::copy_options::update_existing);
      filesystem::last_write_time(tmp_file, input_time);
    }

    // m3u8が存在したら更新日時を確認
    if (filesystem::exists(*read_meta_file)) {
      auto checker_time = filesystem::last_write_time(*read_meta_file);
      auto checker_tm   = conv_fclock(checker_time);
      std::cout << "inputdir time: " << std::put_time(&input_tm, "%c")
                << " checker time: " << std::put_time(&checker_tm, "%c") << std::endl;
      if (input_time == checker_time) {
        std::cout << "inputdir not changed!" << std::endl;
        return 0;
      } else {
        std::cout << "inputdir changed!" << std::endl;
      }
    }

    std::vector<std::filesystem::path> resource_paths;
    const int tile_size = 9;

    // パス取得部分
    auto start = std::chrono::system_clock::now();
    for (const filesystem::directory_entry& x :
         filesystem::recursive_directory_iterator(input_dir)) {
      std::string path(x.path());
      if (path.substr(path.length() - 3) == "png" &&
          std::string(x.path().filename())[0] == 'V') {
        resource_paths.push_back(x.path());
      }
    }
    std::sort(resource_paths.begin(), resource_paths.end(),
              [](auto a, auto b) { return a.filename() < b.filename(); });

    auto end = std::chrono::system_clock::now();
    std::cout << "get paths time:"
              << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count()
              << std::endl;

    // 重複チェック
    start = std::chrono::system_clock::now();
    hls_manager manager(*read_meta_file);
    int update_index = 0;
    auto it          = resource_paths.begin();
    int segment_num  = (resource_paths.size() + tile_size - 1) / tile_size;
    for (; update_index < segment_num;) {
      if (!manager.next_segment()) {
        break;
      }
      auto end = std::next(it, bound_load(it, resource_paths.end(), tile_size) - 1);
      if (manager.compare_start(it->filename()) && manager.compare_end(end->filename())) {
        // std::cout << update_index << ". " << it->filename() << " - " << end->filename()
        //           << " is not changed." << std::endl;
        update_index++;
        it = std::next(end, 1);
      } else {
        std::cout << update_index << ". " << it->filename() << " - " << end->filename()
                  << " is changed." << std::endl;
        break;
      }
    }
    end = std::chrono::system_clock::now();
    std::cout << "check update time:"
              << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count()
              << std::endl;

    // ファイルの更新なしの場合
    if (update_index >= segment_num) {
      std::cout << "file not changed" << std::endl;
      filesystem::last_write_time(video_file, input_time);
      filesystem::last_write_time(tmp_file, input_time);
      return 0;
    }

    std::cout << "update from " << update_index << " th block" << std::endl;

    // fontをtmpfsへコピー
    const filesystem::path tmp_font = tmp_dir.string() + font_path.filename().string();
    std::cout << "copy" << font_path << " -> " << tmp_font << std::endl;
    filesystem::copy_file(font_path, tmp_font, filesystem::copy_options::update_existing);

    const filesystem::path blank_path = "./blank.png";
    const cv::Mat blank_image         = cv::imread(blank_path);

// 画像生成部分
// ここを消すと内側が並列化されるので1ブロック生成時は消すと良い（いい方法ない？）
// #pragma omp parallel for
    for (int i = update_index; i < segment_num; i++) {
      const int index = i * tile_size;
      auto it         = std::next(resource_paths.begin(), index);
      int bound       = bound_load(it, resource_paths.end(), tile_size);
      std::vector<cv::Mat> images(bound);
      std::vector<cv::Mat> dsts(tile_size + 1);
#pragma omp parallel for
      for (int j = 0; j < bound; j++) {
        images[j] = cv::imread(*(std::next(it, j)));
      }
      image_generator generator(output_size, tmp_font);
      generator.generate_tile(it, images, dsts[0]);

#pragma omp parallel for
      for (int j = 0; j < bound; j++) {
        auto id = std::next(it, j);
        image_generator generator(output_size, tmp_font);
        // tile_size - jで新しいファイルからjで昔のファイルから (1)
        generator.generate_single(*id, images[j], dsts[(tile_size - 1) - j + 1]);
        // std::string log(std::string("") + "generate: " + output_dir.string() +
        //                 id->filename().string() + " -> " + output_dir.string() +
        //                 (boost::format("img-%05d_%05d.png") % i % (j + 1)).str());
        // std::cout << log << std::endl;
      }
      // for (int j = bound + 1; j < dsts.size(); j++) {
      for (int j = bound + 1; j < dsts.size(); j++) {
        // tile_size - jで新しいファイルからjで昔のファイルから (2)
        dsts[tile_size - j + 1] = blank_image;
      }

#pragma omp parallel for
      for (int j = 0; j < dsts.size(); j++) {
        cv::imwrite(
            (boost::format("%s_%s%06d_%05d.png") % output_dir.string() % file_pref % i % (j))
                .str(),
            dsts[j]);
        dsts[j].release();
      }

      // 10枚毎のブロック生成部分
      std::string command = (boost::format("ffmpeg -loglevel error -framerate 1 "
                                           "-i %s_%s%06d_%s.png -vcodec libx264 "
                                           "-pix_fmt yuv420p -r 5 -f hls -hls_time 10 "
                                           "-hls_playlist_type vod -hls_segment_filename "
                                           "\"%s_%s%06d%s.ts\" %s_%s%06d.m3u8") %
                             output_dir.string() % file_pref % i % "%05d" % video_dir.string() %
                             file_pref % i % "%1d" % video_dir.string() % file_pref % i)
                                .str();
      std::cout << command << std::endl;
      std::system(command.c_str());
    }

    // hlsのメタデータ変更部分
    std::cout << "writeing m3u8" << std::endl;
    const std::string m3head = {
        "#EXTM3U\n"
        "#EXT-X-VERSION:3\n"
        "#EXT-X-TARGETDURATION:10\n"
        "#EXT-X-MEDIA-SEQUENCE:0\n"
        "#EXT-X-PLAYLIST-TYPE:EVENT\n\n"};
    const std::string m3tail = {"#EXT-X-ENDLIST\n"};
    std::stringstream m3stream;
    std::stringstream m3index;
    auto path                = resource_paths.begin();
    constexpr int block_size = 180;
    const int block_num      = (segment_num + block_size - 1) / block_size;
    std::vector<std::stringstream> m3block(block_num);
    for (int i = 0; i < segment_num; i++, std::advance(path, tile_size)) {
      auto end = std::next(path, bound_load(path, resource_paths.end(), tile_size) - 1);
      m3index << boost::format("#v%06d,%s,%s\n") % i % filename_date(*path) %
                     filename_date(*end);
      std::string segment_data = (boost::format("#EXT-X-DISCONTINUITY\n"
                                                "#EXTINF:10\n"
                                                "_%s%06d%01d.ts\n") %
                                  file_pref % (segment_num - i - 1) % 0)
                                     .str();
      m3stream << segment_data;
      m3block[i / block_size] << segment_data;
    }

    // 実体書き込み
    start = std::chrono::system_clock::now();
    std::ofstream ofs(video_file);
    ofs << m3head << m3index.str() << m3stream.str() << m3tail;
    ofs.close();
    // block_sizeごとに分けたm3u8
#pragma omp parallel for
    for (int i = 0; i < block_num; i++) {
      std::ofstream ofs(video_dir.string() +
                        (boost::format("%s%03d.m3u8") % file_pref % i).str());
      for (int j = block_num - 1 - i; j > 0; j--) {
        m3block[i] << "#EXT-X-DISCONTINUITY\n"
                      "#EXTINF:10\n"
                      "dummy0.ts\n";
      }
      ofs << m3head << m3block[i].str() << m3tail;
      ofs.close();
    }

    // tmpファイル書き込み
    ofs = std::ofstream(tmp_file);
    ofs << m3index.str();
    end = std::chrono::system_clock::now();
    std::cout << "file write time:"
              << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count()
              << std::endl;
    ofs.close();

    filesystem::last_write_time(video_file, input_time);
    filesystem::last_write_time(tmp_file, input_time);

    std::cout << "complete!" << std::endl;
  }
}

ext: cc


text:
#include "stdafx.h"
#include ".\extrastringsview.h"

#include <boost/test/unit_test.hpp>
#ifdef UNIT_TEST
BOOST_AUTO_TEST_SUITE( TestCExtraStringsView )

	BOOST_AUTO_TEST_CASE( instantiate)
	{
		CExtraStringsView dialog ;
		BOOST_CHECK(true) ;
	}
	BOOST_AUTO_TEST_CASE( eliminate_whitespace_and_punctuation )
	{
		CExtraStringsView dlg ;
		wstring setting = L"Hello, world!" ;
		wstring key ;
		dlg.eliminate_whitespace_and_punctuation( setting, key ) ;
		BOOST_CHECK_EQUAL( L"Hello__world_", key ) ;
	}

	BOOST_AUTO_TEST_SUITE_END()

#endif

ext: cpp

max_stars_repo_name: ultimatezen/felix

max_issues_repo_name: ultimatezen/felix

max_forks_repo_name: ultimatezen/felix


text:
/* -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil -*-

   This file is part of Carbon
   Author: Patrick Geib
   $Id$

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   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
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "communicationmanager.h"
#include "carbon.h"
#include "abstractplugin.h"
#include "topic.h"

#ifndef Q_MOC_RUN
#include <boost/make_shared.hpp>
#endif

using namespace boost;

//--------------------------------------------------------------
// Static
//--------------------------------------------------------------

//--------------------------------------------------------------
// Public
//--------------------------------------------------------------

CommunicationManager::CommunicationManager(Carbon* parent)
    : mParent(parent)
{
}

CommunicationManager::~CommunicationManager()
{
}

bool CommunicationManager::hasTopic(const QString& name)
{
    return getTopic(name).get() != 0;
}

shared_ptr<Topic> CommunicationManager::getTopic(const QString& name)
{
    for (auto it = mTopics.begin(); it != mTopics.end(); it++)
    {
        if (it->get()->getName().compare(name) == 0)
        {
            return *it;
        }
    }
    return boost::shared_ptr<Topic>();
}

bool CommunicationManager::registerSender(AbstractPlugin* sender, const QString& topicName, const char* signal, int maxReceivers,
    ETopicConnectionType connectionType)
{
    if (sender == 0)
        return false;

    if (sender->getQObject() == 0)
    {
        LOG_WARNING() << "Cant create communication topic for receiver without being or having an assigned QObject. ";
        return false;
    }

    //Create topic
    shared_ptr<Topic> topic = getTopic(topicName);
    if (topic.get() == 0)
    {
        mTopics.push_back(make_shared<Topic>(this, topicName));
        emit topicCreated(topicName);

        topic = mTopics.back();
    }

    //Register sender
    topic->registerSender(sender, signal, maxReceivers, connectionType);
    return true;
}

bool CommunicationManager::registerReceiver(AbstractPlugin* receiver, const QString& topicName, const char* slot, int maxSenders,
    ETopicConnectionType connectionType)
{
    if (receiver == 0)
        return false;

    if (receiver->getQObject() == 0)
    {
        LOG_WARNING() << "Cant create communication topic for receiver without being or having an assigned QObject. ";
        return false;
    }

    //Create topic
    shared_ptr<Topic> topic = getTopic(topicName);
    if (topic.get() == 0)
    {
        mTopics.push_back(make_shared<Topic>(this, topicName));
        emit topicCreated(topicName);

        topic = mTopics.back();
    }

    //Register receiver
    topic->registerReceiver(receiver, slot, maxSenders, connectionType);
    return true;
}

//--------------------------------------------------------------
// Protected
//--------------------------------------------------------------

QList<boost::shared_ptr<Topic>>::Iterator CommunicationManager::removeTopic(Topic* topic)
{
    for (auto it = mTopics.begin(); it != mTopics.end(); it++)
    {
        if (&**it == topic)
        {
            QString name = it->get()->getName();
            auto pos = mTopics.erase(it);
            emit topicRemoved(name);
            return pos;
        }
    }
    return mTopics.end();
}

//--------------------------------------------------------------
// Slots
//--------------------------------------------------------------

void CommunicationManager::unregisterSender(const AbstractPlugin* sender, const QString& topicName, bool validPtr)
{
    shared_ptr<Topic> topic = getTopic(topicName);
    if (topic.get())
    {
        topic->unregisterSender(sender, validPtr);

        if (topic->isEmpty())
            removeTopic(&*topic);
    }
}

void CommunicationManager::unregisterSender(const AbstractPlugin* sender, bool validPtr)
{
    for (auto it = mTopics.begin(); it != mTopics.end();)
    {
        it->get()->unregisterSender(sender, validPtr);
        if (it->get()->isEmpty())
            it = removeTopic(it->get());
        else
            it++;
    }
}

void CommunicationManager::unregisterReceiver(const AbstractPlugin* receiver, const QString& topicName, bool validPtr)
{
    shared_ptr<Topic> topic = getTopic(topicName);
    if (topic.get())
        topic->unregisterReceiver(receiver, validPtr);

    if (topic->isEmpty())
        removeTopic(&*topic);
}

void CommunicationManager::unregisterReceiver(const AbstractPlugin* receiver, bool validPtr)
{
    for (auto it = mTopics.begin(); it != mTopics.end();)
    {
        it->get()->unregisterReceiver(receiver, validPtr);
        if (it->get()->isEmpty())
            it = removeTopic(it->get());
        else
            it++;
    }
}

void CommunicationManager::unregister(const AbstractPlugin* registree, const QString& topicName, bool validPtr)
{
    shared_ptr<Topic> topic = getTopic(topicName);
    if (topic.get())
        topic->unregister(registree, validPtr);

    if (topic->isEmpty())
        removeTopic(&*topic);
}

void CommunicationManager::unregister(const AbstractPlugin* registree, bool validPtr)
{
    for (auto it = mTopics.begin(); it != mTopics.end();)
    {
        it->get()->unregister(registree, validPtr);
        if (it->get()->isEmpty())
            it = removeTopic(it->get());
        else
            it++;
    }
}


text:
#pragma once
#include "network/net/exception.hpp"
#include <boost/asio.hpp>
#include <thread>
#include <mutex>

namespace cytx {
    namespace rpc
    {
        static const auto asio_error = boost::asio::placeholders::error;

        class async_connection
        {
            using tcp = boost::asio::ip::tcp;
            using io_service_t = boost::asio::io_service;
        public:
            async_connection(io_service_t& ios, tcp::endpoint const& endpoint)
                : socket_(ios)
                , endpoint_(endpoint)
            {
            }

            async_connection(io_service_t& ios)
                : socket_(ios)
            {
            }

            void start(
                std::function<void()>&& on_success,
                std::function<void(const boost::system::error_code&)>&& on_error)
            {
                on_success_ = std::move(on_success);
                on_error_ = std::move(on_error);
                start_connect();
            }

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

            tcp::endpoint const& endpoint() const
            {
                return endpoint_;
            }

        private:
            void start_connect()
            {
                socket_.async_connect(endpoint_, boost::bind(&async_connection::handle_connection, this, asio_error));
            }

            void handle_connection(const boost::system::error_code& error)
            {
                if (!error)
                {
                    if (on_success_)
                        on_success_();
                }
                else
                {
                    if (on_error_)
                        on_error_(error);
                }
                on_error_ = nullptr;
                on_success_ = nullptr;
            }

        private:
            tcp::socket socket_;
            tcp::endpoint endpoint_;
            std::function<void()> on_success_;
            std::function<void(const boost::system::error_code&)> on_error_;
        };
    }
}

ext: hpp

max_stars_repo_name: hbccdf/network-core

max_issues_repo_name: hbccdf/network-core

max_forks_repo_name: hbccdf/network-core


text:
#include "timer.hpp"
#include "read_map.hpp"
#include <jps_basis/data_utils.h>
#include <jps_planner/jps_planner/jps_planner.h>

#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>

using namespace JPS;

int main(int argc, char ** argv){
  if(argc != 2) {
    printf(ANSI_COLOR_RED "Input yaml required!\n" ANSI_COLOR_RESET);
    return -1;
  }

  // Read the map from yaml
  MapReader<Vec2i, Vec2f> reader(argv[1], true); // Map read from a given file
  if(!reader.exist()) {
    printf(ANSI_COLOR_RED "Cannot read input file [%s]!\n" ANSI_COLOR_RESET, argv[1]);
    return -1;
  }

  // store map in map_util
  std::shared_ptr<OccMapUtil> map_util = std::make_shared<OccMapUtil>();
  map_util->setMap(reader.origin(), reader.dim(), reader.data(), reader.resolution());

  const Vec2f start(reader.start(0), reader.start(1));
  const Vec2f goal(reader.goal(0), reader.goal(1));

  std::unique_ptr<JPSPlanner2D> planner_ptr(new JPSPlanner2D(false)); // Declare a planner
  planner_ptr->setMapUtil(map_util); // Set collision checking function
  planner_ptr->updateMap();

  Timer time_jps(true);
  bool valid_jps = planner_ptr->plan(start, goal, 1, true); // Plan from start to goal using JPS
  double dt_jps = time_jps.Elapsed().count();
  const auto path_jps = planner_ptr->getRawPath(); // Get the planned raw path from JPS
  printf("JPS Planner takes: %f ms\n", dt_jps);
  printf("JPS Path Distance: %f\n", total_distance2f(path_jps));

  Timer time_astar(true);
  bool valid_astar = planner_ptr->plan(start, goal, 1, false); // Plan from start to goal using A*
  double dt_astar = time_astar.Elapsed().count();
  const auto path_astar = planner_ptr->getRawPath(); // Get the planned raw path from A*
  printf("JPS Planner takes: %f ms\n", dt_jps);
  printf("AStar Planner takes: %f ms\n", dt_astar);
  printf("AStar Path Distance: %f\n", total_distance2f(path_astar));

  // Plot the result in svg image
  typedef boost::geometry::model::d2::point_xy<double> point_2d;
  // Declare a stream and an SVG mapper
  std::ofstream svg("output.svg");
  boost::geometry::svg_mapper<point_2d> mapper(svg, 1000, 1000);

  // Draw the canvas
  boost::geometry::model::polygon<point_2d> bound;
  const Vec2i dim = map_util->getDim();
  const Vec2f ori = map_util->getOrigin();
  const double res = map_util->getRes();

  const double origin_x = ori(0);
  const double origin_y = ori(1);
  const double range_x = dim(0) * res;
  const double range_y = dim(1) * res;
  std::vector<point_2d> points;
  points.push_back(point_2d(origin_x, origin_y));
  points.push_back(point_2d(origin_x, origin_y+range_y));
  points.push_back(point_2d(origin_x+range_x, origin_y+range_y));
  points.push_back(point_2d(origin_x+range_x, origin_y));
  points.push_back(point_2d(origin_x, origin_y));
  boost::geometry::assign_points(bound, points);
  boost::geometry::correct(bound);

  mapper.add(bound);
  mapper.map(bound, "fill-opacity:1.0;fill:rgb(255,255,255);stroke:rgb(0,0,0);stroke-width:2"); // White

  // Draw start and goal
  point_2d start_pt, goal_pt;
  boost::geometry::assign_values(start_pt, start(0), start(1));
  mapper.add(start_pt);
  mapper.map(start_pt, "fill-opacity:1.0;fill:rgb(255,0,0);", 10); // Red
  boost::geometry::assign_values(goal_pt, goal(0), goal(1));
  mapper.add(goal_pt);
  mapper.map(goal_pt, "fill-opacity:1.0;fill:rgb(255,0,0);", 10); // Red

  // Draw the obstacles
  for(int x = 0; x < dim(0); x ++) {
    for(int y = 0; y < dim(1); y ++) {
      if(!map_util->isFree(Vec2i(x, y))) {
        Vec2f pt = map_util->intToFloat(Vec2i(x, y));
        point_2d a;
        boost::geometry::assign_values(a, pt(0), pt(1));
        mapper.add(a);
        mapper.map(a, "fill-opacity:1.0;fill:rgb(0,0,0);", 1);
      }
    }
  }

  // Draw the path from JPS
  if(valid_jps) {
    vec_Vec2f path = path_jps;
    boost::geometry::model::linestring<point_2d> line;
    for(auto pt: path)
      line.push_back(point_2d(pt(0), pt(1)));
    mapper.add(line);
    mapper.map(line, "opacity:0.4;fill:none;stroke:rgb(212,0,0);stroke-width:5"); // Red
  }

  // Draw the path from A*
  if(valid_astar) {
    vec_Vec2f path = path_astar;
    boost::geometry::model::linestring<point_2d> line;
    for(auto pt: path)
      line.push_back(point_2d(pt(0), pt(1)));
    mapper.add(line);
    mapper.map(line, "opacity:0.4;fill:none;stroke:rgb(1,212,0);stroke-width:5"); // Green
  }

  // Write title at the lower right corner on canvas
  mapper.text(point_2d(origin_x + range_x - 6, origin_y+1.8), "test_planner_2d",
              "fill-opacity:1.0;fill:rgb(10,10,250);");

  mapper.text(point_2d(origin_x + range_x - 8, origin_y+1.2), "Green: ",
              "fill-opacity:1.0;fill:rgb(1,212,0);");
  mapper.text(point_2d(origin_x + range_x - 5.5, origin_y+1.2), "astar path",
              "fill-opacity:1.0;fill:rgb(0,0,0);");

  mapper.text(point_2d(origin_x + range_x - 8, origin_y+0.6), "Red: ",
              "fill-opacity:1.0;fill:rgb(212,0,0);");
  mapper.text(point_2d(origin_x + range_x - 5.5, origin_y+0.6), "jps path",
              "fill-opacity:1.0;fill:rgb(0,0,0);");

  return 0;
}


text:
#include <fc/network/http/connection.hpp>
#include <fc/network/tcp_socket.hpp>
#include <fc/io/sstream.hpp>
#include <fc/io/iostream.hpp>
#include <fc/exception/exception.hpp>
#include <fc/network/ip.hpp>
#include <fc/crypto/hex.hpp>
#include <fc/log/logger.hpp>
#include <fc/io/stdio.hpp>
#include <fc/network/url.hpp>
#include <boost/algorithm/string.hpp>

class fc::http::connection::impl
{
  public:
   fc::tcp_socket sock;
   fc::ip::endpoint ep;
   impl() {
   }

   int read_until( char* buffer, char* end, char c = '\n' ) {
      char* p = buffer;
     // try {
          while( p < end && 1 == sock.readsome(p,1) ) {
            if( *p == c ) {
              *p = '\0';
              return (p - buffer)-1;
            }
            ++p;
          }
     // } catch ( ... ) {
     //   elog("%s", fc::current_exception().diagnostic_information().c_str() );
        //elog( "%s", fc::except_str().c_str() );
     // }
      return (p-buffer);
   }

   fc::http::reply parse_reply() {
      fc::http::reply rep;
      try {
        std::vector<char> line(1024*8);
        int s = read_until( line.data(), line.data()+line.size(), ' ' ); // HTTP/1.1
        s = read_until( line.data(), line.data()+line.size(), ' ' ); // CODE
        rep.status = static_cast<int>(to_int64(std::string(line.data())));
        s = read_until( line.data(), line.data()+line.size(), '\n' ); // DESCRIPTION

        while( (s = read_until( line.data(), line.data()+line.size(), '\n' )) > 1 ) {
          fc::http::header h;
          char* end = line.data();
          while( *end != ':' )++end;
          h.key = std::string(line.data(),end);
          ++end; // skip ':'
          ++end; // skip space
          char* skey = end;
          while( *end != '\r' ) ++end;
          h.val = std::string(skey,end);
          rep.headers.push_back(h);
          if( boost::iequals(h.key, "Content-Length") ) {
             rep.body.resize( static_cast<size_t>(to_uint64( std::string(h.val) ) ));
          }
        }
        if( rep.body.size() ) {
          sock.read( rep.body.data(), rep.body.size() );
        }
        return rep;
      } catch ( fc::exception& e ) {
        elog( "${exception}", ("exception",e.to_detail_string() ) );
        sock.close();
        rep.status = http::reply::InternalServerError;
        return rep;
      }
   }
};

namespace fc { namespace http {

         connection::connection()
         :my( new connection::impl() ){}
         connection::~connection(){}

// used for clients
void       connection::connect_to( const fc::ip::endpoint& ep ) {
  my->sock.close();
  my->sock.connect_to( my->ep = ep );
}

http::reply connection::request( const std::string& method,
                                const std::string& url,
                                const std::string& body, const headers& he ) {

  fc::url parsed_url(url);
  if( !my->sock.is_open() ) {
    wlog( "Re-open socket!" );
    my->sock.connect_to( my->ep );
  }
  try {
      fc::stringstream req;
      req << method <<" "<<parsed_url.path()->generic_string()<<" HTTP/1.1\r\n";
      req << "Host: "<<*parsed_url.host()<<"\r\n";
      req << "Content-Type: application/json\r\n";
      for( auto i = he.begin(); i != he.end(); ++i )
      {
          req << i->key <<": " << i->val<<"\r\n";
      }
      if( body.size() ) req << "Content-Length: "<< body.size() << "\r\n";
      req << "\r\n";
      std::string head = req.str();

      my->sock.write( head.c_str(), head.size() );
    //  fc::cerr.write( head.c_str() );

      if( body.size() )  {
          my->sock.write( body.c_str(), body.size() );
    //      fc::cerr.write( body.c_str() );
      }
    //  fc::cerr.flush();

      return my->parse_reply();
  } catch ( ... ) {
      my->sock.close();
      FC_THROW_EXCEPTION( exception, "Error Sending HTTP Request" ); // TODO: provide more info
   //  return http::reply( http::reply::InternalServerError ); // TODO: replace with connection error
  }
}

// used for servers
fc::tcp_socket& connection::get_socket()const {
  return my->sock;
}

http::request    connection::read_request()const {
  http::request req;
  req.remote_endpoint = fc::variant(get_socket().remote_endpoint()).as_string();
  std::vector<char> line(1024*8);
  int s = my->read_until( line.data(), line.data()+line.size(), ' ' ); // METHOD
  req.method = line.data();
  s = my->read_until( line.data(), line.data()+line.size(), ' ' ); // PATH
  req.path = line.data();
  s = my->read_until( line.data(), line.data()+line.size(), '\n' ); // HTTP/1.0

  while( (s = my->read_until( line.data(), line.data()+line.size(), '\n' )) > 1 ) {
    fc::http::header h;
    char* end = line.data();
    while( *end != ':' )++end;
    h.key = std::string(line.data(),end);
    ++end; // skip ':'
    ++end; // skip space
    char* skey = end;
    while( *end != '\r' ) ++end;
    h.val = std::string(skey,end);
    req.headers.push_back(h);
    if( boost::iequals(h.key, "Content-Length")) {
       auto s = static_cast<size_t>(to_uint64( std::string(h.val) ) );
       FC_ASSERT( s < 1024*1024 );
       req.body.resize( static_cast<size_t>(to_uint64( std::string(h.val) ) ));
    }
    if( boost::iequals(h.key, "Host") ) {
       req.domain = h.val;
    }
  }
  // TODO: some common servers won't give a Content-Length, they'll use
  // Transfer-Encoding: chunked.  handle that here.

  if( req.body.size() ) {
    my->sock.read( req.body.data(), req.body.size() );
  }
  return req;
}

std::string request::get_header( const std::string& key )const {
  for( auto itr = headers.begin(); itr != headers.end(); ++itr ) {
    if( boost::iequals(itr->key, key) ) { return itr->val; }
  }
  return std::string();
}
std::vector<header> parse_urlencoded_params( const std::string& f ) {
  int num_args = 0;
  for( size_t i = 0; i < f.size(); ++i ) {
    if( f[i] == '=' ) ++num_args;
  }
  std::vector<header> h(num_args);
  int arg = 0;
  for( size_t i = 0; i < f.size(); ++i ) {
    while( i < f.size() && f[i] != '=' ) {
      if( f[i] == '%' ) {
        h[arg].key += char((fc::from_hex(f[i+1]) << 4) | fc::from_hex(f[i+2]));
        i += 3;
      } else {
          h[arg].key += f[i];
          ++i;
      }
    }
    ++i;
    while( i < f.size() && f[i] != '&' ) {
      if( f[i] == '%' ) {
        h[arg].val += char((fc::from_hex(f[i+1]) << 4) | fc::from_hex(f[i+2]));
        i += 3;
      } else {
        h[arg].val += f[i] == '+' ? ' ' : f[i];
        ++i;
      }
    }
    ++arg;
  }
  return h;
}

} } // fc::http

max_stars_repo_name: Revolution-Populi/fc

max_issues_repo_name: Revolution-Populi/fc

max_forks_repo_name: Revolution-Populi/fc


text:
/*
# Copyright (c) 2021 Juan J. Garcia Mesa <juanjosegarciamesa@gmail.com>
#
# 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 INSERTIONS_HPP
#define INSERTIONS_HPP

#include <Eigen/Sparse>
#include <iostream>
#include <numeric>
#include <vector>

namespace coati {
using SparseVectorInt = Eigen::SparseVector<int, Eigen::RowMajor>;

struct insertion_data_t {
    std::vector<std::string> sequences; /*!< sequences */
    std::vector<std::string> names;     /*!< sequence names */
    SparseVectorInt
        insertions; /*!< insertion positions and type (open/closed) */

    insertion_data_t() = default;

    insertion_data_t(const std::string& s, const std::string& n,
                     const SparseVectorInt& i)
        : sequences(1, s), names(1, n), insertions{i} {}

    insertion_data_t(std::vector<std::string> s, std::vector<std::string> n,
                     const SparseVectorInt& i)
        : sequences{std::move(s)}, names{std::move(n)}, insertions{i} {}
};

bool insertion_flags(const std::string& ref, const std::string& seq,
                     SparseVectorInt& insertions_vector);
bool merge_indels(std::vector<insertion_data_t>& ins_data,
                  insertion_data_t& merged_data);
void add_gap(std::vector<insertion_data_t>& ins_data,
             std::vector<int> seq_indexes, int pos);
}  // namespace coati
#endif

max_stars_repo_name: CartwrightLab/coa

max_issues_repo_name: CartwrightLab/coa

max_forks_repo_name: jgarciamesa/coati


text:
#include "null_rand_flowgraph.hpp"

#include <algorithm>
#include <chrono>
#include <numeric>
#include <functional>
#include <boost/format.hpp>

#include <gnuradio/blocks/head.h>
#include <gnuradio/blocks/interleave.h>
#include <gnuradio/blocks/null_sink.h>
#include <gnuradio/blocks/null_source.h>

namespace po = boost::program_options;

using namespace gr;

null_rand_flowgraph::null_rand_flowgraph(int pipes, int stages, uint64_t samples, size_t max_copy) {

    this->tb = gr::make_top_block("buf_flowgraph");

    for(int pipe = 0; pipe < pipes; pipe++) {

        auto src = blocks::null_source::make(4);
        auto head = blocks::head::make(4, samples);
        tb->connect(src, 0, head, 0);

        auto prev = sched::copy_rand::make(sizeof(float), max_copy);
        tb->connect(head, 0, prev, 0);

        for(int stage = 1; stage < stages; stage++) {
            auto block = sched::copy_rand::make(sizeof(float), max_copy);
            tb->connect(prev, 0, block, 0);
            prev = block;
        }

        auto sink = blocks::null_sink::make(sizeof(float));
        tb->connect(prev, 0, sink, 0);
    }
}

int main (int argc, char **argv) {
    int run;
    int pipes;
    int stages;
    uint64_t samples;
    size_t max_copy;

    po::options_description desc("Run Buffer Flow Graph");
    desc.add_options()
        ("help,h", "display help")
        ("run,r", po::value<int>(&run)->default_value(0), "Run Number")
        ("pipes,p", po::value<int>(&pipes)->default_value(5), "Number of pipes")
        ("stages,s", po::value<int>(&stages)->default_value(6), "Number of stages")
        ("max_copy,m", po::value<size_t>(&max_copy)->default_value(0xffffffff), "Maximum number of samples to copy in one go.")
        ("samples,n", po::value<uint64_t>(&samples)->default_value(15000000), "Number of samples");

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    if (vm.count("help")) {
        std::cout << desc << std::endl;
        return 0;
    }

    null_rand_flowgraph* runner = new null_rand_flowgraph(pipes, stages, samples, max_copy);
    // runner->tb->set_max_output_buffer(4096);

    auto start = std::chrono::high_resolution_clock::now();
    runner->tb->run();
    auto finish = std::chrono::high_resolution_clock::now();
    auto time = std::chrono::duration_cast<std::chrono::nanoseconds>(finish-start).count()/1e9;

    std::cout <<
    boost::format("%1$4d, %2$4d,  %3$4d,   %4$15d,%5$10d,legacy,   %6$20.15f") %
                     run  % pipes % stages % samples % max_copy % time << std::endl;

    return 0;
}

max_stars_repo_name: AndersKaloer/FutureSDR

max_issues_repo_name: AndersKaloer/FutureSDR

max_forks_repo_name: AndersKaloer/FutureSDR


text:
/* test_SPARQLSerializer.hpp --
 *
 * Test a SPARQL Parser and serializer.
 *
 * $Id: test_SPARQLSerializer.cpp,v 1.5 2008-12-04 22:37:09 eric Exp $
 */

#define BOOST_TEST_MODULE SPARQLSerializer

#include <fstream>
#include <sstream>
#include <iostream>
#include <iterator>
#include "SWObjects.hpp"
#include "SPARQLParser.hpp"
#include "SPARQLSerializer.hpp"
#include "SPARQLAlgebraSerializer.hpp"
#include "SWObjectDuplicator.hpp"

/* Keep all inclusions of boost *after* the inclusion of SWObjects.hpp
 * (or define BOOST_*_DYN_LINK manually).
 */
#include <boost/test/unit_test.hpp>
w3c_sw_PREPARE_TEST_LOGGER("--log"); // invoke with e.g. "--log *:-1,IO,GraphMatch:3"

using namespace w3c_sw;

AtomFactory F;
SPARQLDriver sparqlParser("", &F);

struct OpWrap {
    OpWrap () {  }
    OpWrap (std::string str, const Operation* op) :
	str(str), op(op) {  }
    std::string str;
    const Operation* op;
};

bool operator== (const OpWrap& l, const OpWrap& r) {
    return *l.op == *r.op;
}

std::ostream& operator<< (std::ostream& os, OpWrap const& my) {
    os << operator<<(os, my.str);
    SPARQLAlgebraSerializer s;
    my.op->express(&s);
    return os << s.str();
}

struct OpPair {
    OpPair (const OpWrap once, const OpWrap twice, const OpWrap dup) :
	once(once), twice(twice), dup(dup) {  }
    void cleanup () { delete once.op; delete twice.op; delete dup.op; } // i never worked out the Op copy constructor
    const OpWrap once;
    const OpWrap twice;
    const OpWrap dup;
};

OpPair algebrize_TWICE (std::string sparql) {
    /* Parse query. */
    IStreamContext sparstream(sparql, IStreamContext::STRING);
    Operation* first = sparqlParser.parse(sparstream);
    sparqlParser.clear(""); // clear out namespaces and base URI.

    SPARQLSerializer s;
    first->express(&s);
    OpWrap once(sparql, first);

    IStreamContext serialstream(s.str(), IStreamContext::STRING);
    Operation* second = sparqlParser.parse(serialstream);
    OpWrap twice(s.str(), second);

    SWObjectDuplicator duper(&F);
    once.op->express(&duper);
    s.str(""); // Clear out serializer.
    duper.last.operation->express(&s);
    OpWrap dup(s.str(), duper.last.operation);

    return OpPair(once, twice, dup);
}

/* Macros for terse test syntax
 * Using macros means that error messages point you to the test invocation (a
 * great help in quicky diagnosing the failure).
 */
//@@SWOBjectDuplicator

#define SERIALIZER_TEST(SPARQL)						       \
    try {								       \
	OpPair p = algebrize_TWICE(SPARQL);				       \
	BOOST_CHECK_EQUAL(p.once, p.twice);				       \
	BOOST_CHECK_EQUAL(p.once, p.dup);				       \
	p.cleanup();							       \
    } catch (std::string& s) {						       \
	BOOST_ERROR ( s );						       \
    } catch (std::exception& s) {					       \
	BOOST_ERROR ( s.what() );					       \
    }

BOOST_AUTO_TEST_CASE( algebra__filter_nested_2 ) {
    /* copy of DAWG test algebra/filter_nested_2
     */
    SERIALIZER_TEST("ASK { <x> <p> ?v . { FILTER(?v = 1) } }");
}

BOOST_AUTO_TEST_CASE( triple_match__dawg_triple_pattern_001 ) {
    /* shape of DAWG test triple_match/dawg_triple_pattern_001
     */
    SERIALIZER_TEST("ASK { <x> ?p ?q . }");
}

BOOST_AUTO_TEST_CASE( algebra__filter_place_3 ) {
    /* shape of DAWG test algebra/filter_place_3.
     */
    SERIALIZER_TEST("ASK\n\
{ \n\
    FILTER (?v = 2)\n\
    FILTER (?w = 3)\n\
    ?s <p> ?v . \n\
    ?s <q> ?w .\n\
}\n\
");
}

BOOST_AUTO_TEST_CASE( algebra__opt_filter_1 ) {
    /* shape of DAWG test algebra/opt_filter_1.
     */
    SERIALIZER_TEST("ASK { \n\
  ?x <p> ?v .\n\
  OPTIONAL\n\
  { \n\
    FILTER(?v=1)\n\
    ?y <q> ?w .\n\
    FILTER(?v=2)\n\
  }\n\
}");
}

BOOST_AUTO_TEST_CASE( triple_filter ) {
    /* Simple FILTER after a triple.
     */
    SERIALIZER_TEST("ASK {\n\
  ?s <p> 1 .\n\
  FILTER (1)\n\
  }");
}

BOOST_AUTO_TEST_CASE( filter_triple ) {
    /* Simple FILTER before a triple.
     */
    SERIALIZER_TEST("ASK {\n\
  FILTER (1)\n\
  ?s <p> 1 .\n\
  }");
}

BOOST_AUTO_TEST_CASE( bgp_before_nth ) {
    /* Simple FILTER before a later BGP.
     */
    SERIALIZER_TEST("ASK {\n\
  {\n\
    ?s <p> 1 .\n\
  }\n\
  FILTER (1)\n\
  ?s <p> 2 .\n\
}");
}
BOOST_AUTO_TEST_CASE( bgp_after_nth ) {
    /* Simple FILTER after a later BGP.
     */
    SERIALIZER_TEST("ASK {\n\
  {\n\
    ?s <p> 1 .\n\
  }\n\
  ?s <p> 2 .\n\
  FILTER (1)\n\
}");
}

BOOST_AUTO_TEST_CASE( bgp_in_nth ) {
    /* Simple FILTER in a later BGP.
     */
    SERIALIZER_TEST("ASK {\n\
  {\n\
    ?s <p> 1 .\n\
  }\n\
  ?s <p> 2 .\n\
  FILTER (1)\n\
  ?s <p> 3 .\n\
}");
}

BOOST_AUTO_TEST_CASE( bgp_trailing_conjunction ) {
    /* Simple FILTER trailing a conjunction.
     */
    SERIALIZER_TEST("ASK {\n\
  {\n\
    ?s <p> 1 .\n\
  }\n\
  {\n\
    ?s <p> 2 .\n\
  }\n\
  FILTER (1)\n\
  }");
}

BOOST_AUTO_TEST_CASE( bgp_opt_combo ) {
    /* A FILTER inside an OPTIONAL can reference a variable bound in the required part of the OPTIONAL
     */
    SERIALIZER_TEST("ASK {\
  OPTIONAL {?s?p 0}\
  FILTER (1)\
  ?s?p 1\
  FILTER (2)\
  ?s?p 2\
}");
}

BOOST_AUTO_TEST_CASE( bgp_with_triples ) {
    /* Simple FILTER intermingled with triples.
     */
    SERIALIZER_TEST("ASK {\n\
  ?s <p> 1 .\n\
  FILTER (1)\n\
  ?s <p> 2 .\n\
  FILTER (2)\n\
  }");
}

max_stars_repo_name: ericprud/SWObjects

max_issues_repo_name: ericprud/SWObjects

max_forks_repo_name: ericprud/SWObjects


text:
// Copyright 2020-2022 The Defold Foundation
// Copyright 2014-2020 King
// Copyright 2009-2014 Ragnar Svensson, Christian Murray
// Licensed under the Defold License version 1.0 (the "License"); you may not use
// this file except in compliance with the License.
//
// You may obtain a copy of the License, together with FAQs at
// https://www.defold.com/license
//
// 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 <assert.h>
#include <dlib/log.h>
#include "hid.h"
#include "hid_private.h"

#include <string.h>

#include <dlib/dstrings.h>
#include <dlib/utf8.h>

namespace dmHID
{
    NewContextParams::NewContextParams()
    {
        memset(this, 0, sizeof(NewContextParams));
    }

    Context::Context()
    {
        memset(this, 0, sizeof(Context));
    }

    HContext NewContext(const NewContextParams& params)
    {
        HContext context = new Context();
        context->m_IgnoreMouse = params.m_IgnoreMouse;
        context->m_IgnoreKeyboard = params.m_IgnoreKeyboard;
        context->m_IgnoreGamepads = params.m_IgnoreGamepads;
        context->m_IgnoreTouchDevice = params.m_IgnoreTouchDevice;
        context->m_IgnoreAcceleration = params.m_IgnoreAcceleration;
        context->m_FlipScrollDirection = params.m_FlipScrollDirection;

        context->m_GamepadConnectivityCallback = params.m_GamepadConnectivityCallback;
        return context;
    }

    void SetGamepadFuncUserdata(HContext context, void* userdata)
    {
        context->m_GamepadConnectivityUserdata = userdata;
    }

    void DeleteContext(HContext context)
    {
        delete context;
    }

    HGamepad GetGamepad(HContext context, uint8_t index)
    {
        if (index < MAX_GAMEPAD_COUNT)
            return &context->m_Gamepads[index];
        else
            return INVALID_GAMEPAD_HANDLE;
    }

    HKeyboard GetKeyboard(HContext context, uint8_t index)
    {
        if (index < MAX_KEYBOARD_COUNT)
            return &context->m_Keyboards[index];
        else
            return INVALID_KEYBOARD_HANDLE;
    }

    HMouse GetMouse(HContext context, uint8_t index)
    {
        if (index < MAX_MOUSE_COUNT)
            return &context->m_Mice[index];
        else
            return INVALID_MOUSE_HANDLE;
    }

    HTouchDevice GetTouchDevice(HContext context, uint8_t index)
    {
        if (index < MAX_TOUCH_DEVICE_COUNT)
            return &context->m_TouchDevices[index];
        else
            return INVALID_TOUCH_DEVICE_HANDLE;
    }

    uint32_t GetGamepadButtonCount(HGamepad gamepad)
    {
        return gamepad->m_ButtonCount;
    }

    uint32_t GetGamepadHatCount(HGamepad gamepad)
    {
        return gamepad->m_HatCount;
    }

    uint32_t GetGamepadAxisCount(HGamepad gamepad)
    {
        return gamepad->m_AxisCount;
    }

    bool IsKeyboardConnected(HKeyboard keyboard)
    {
        return keyboard->m_Connected;
    }

    bool IsMouseConnected(HMouse mouse)
    {
        return mouse->m_Connected;
    }

    bool IsGamepadConnected(HGamepad gamepad)
    {
        if (gamepad != 0x0)
            return gamepad->m_Connected;
        else
            return false;
    }

    bool IsTouchDeviceConnected(HTouchDevice device)
    {
        return device->m_Connected;
    }

    bool IsAccelerometerConnected(HContext context)
    {
        return context->m_AccelerometerConnected;
    }

    bool GetKeyboardPacket(HKeyboard keyboard, KeyboardPacket* out_packet)
    {
        if (out_packet != 0x0 && keyboard != 0x0 && keyboard->m_Connected)
        {
            *out_packet = keyboard->m_Packet;
            return true;
        }
        else
        {
            return false;
        }
    }

    bool GetTextPacket(HContext context, TextPacket* out_packet)
    {
        Keyboard* keyboard = &context->m_Keyboards[0];
        if (out_packet != 0x0 && keyboard->m_Connected)
        {
            *out_packet = context->m_TextPacket;
            context->m_TextPacket.m_Size = 0;
            context->m_TextPacket.m_Text[0] = '\0';
            return true;
        }
        else
        {
            return false;
        }
    }

    void AddKeyboardChar(HContext context, int chr) {
        if (context) {
            char buf[5];
            uint32_t n = dmUtf8::ToUtf8((uint16_t) chr, buf);
            buf[n] = '\0';
            TextPacket* p = &context->m_TextPacket;
            p->m_Size = dmStrlCat(p->m_Text, buf, sizeof(p->m_Text));
        }
    }

    bool GetMarkedTextPacket(HContext context, MarkedTextPacket* out_packet)
    {
        Keyboard* keyboard = &context->m_Keyboards[0];
        if (out_packet != 0x0 && keyboard->m_Connected)
        {
            *out_packet = context->m_MarkedTextPacket;
            context->m_MarkedTextPacket.m_Size = 0;
            context->m_MarkedTextPacket.m_HasText = 0;
            context->m_MarkedTextPacket.m_Text[0] = '\0';
            return true;
        }
        else
        {
            return false;
        }
    }

    void SetMarkedText(HContext context, char* text) {
        if (context) {
            MarkedTextPacket* p = &context->m_MarkedTextPacket;
            p->m_HasText = 1;
            p->m_Size = dmStrlCpy(p->m_Text, text, sizeof(p->m_Text));
        }
    }

    void SetGamepadConnectivity(HContext context, int gamepad, bool connected) {
        assert(context);

        GamepadPacket* p = &context->m_Gamepads[gamepad].m_Packet;
        p->m_GamepadDisconnected = !connected;
        p->m_GamepadConnected = connected;
    }

    bool GetMousePacket(HMouse mouse, MousePacket* out_packet)
    {
        if (out_packet != 0x0 && mouse != 0x0 && mouse->m_Connected)
        {
            *out_packet = mouse->m_Packet;
            return true;
        }
        else
        {
            return false;
        }
    }

    bool GetGamepadPacket(HGamepad gamepad, GamepadPacket* out_packet)
    {
        if (gamepad != 0x0 && out_packet != 0x0)
        {
            *out_packet = gamepad->m_Packet;
            gamepad->m_Packet.m_GamepadDisconnected = false;
            gamepad->m_Packet.m_GamepadConnected = false;
            return true;
        }
        else
        {
            return false;
        }
    }

    bool GetTouchDevicePacket(HTouchDevice device, TouchDevicePacket* out_packet)
    {
        if (out_packet != 0x0 && device != 0x0 && device->m_Connected)
        {
            *out_packet = device->m_Packet;
            return true;
        }
        else
        {
            return false;
        }
    }

    bool GetAccelerationPacket(HContext context, AccelerationPacket* out_packet)
    {
        if (out_packet != 0x0)
        {
            *out_packet = context->m_AccelerationPacket;
            return true;
        }
        else
        {
            return false;
        }
    }

    bool GetKey(KeyboardPacket* packet, Key key)
    {
        if (packet != 0x0)
            return packet->m_Keys[key / 32] & (1 << (key % 32));
        else
            return false;
    }

    void SetKey(HKeyboard keyboard, Key key, bool value)
    {
        if (keyboard != 0x0)
        {
            if (value)
                keyboard->m_Packet.m_Keys[key / 32] |= (1 << (key % 32));
            else
                keyboard->m_Packet.m_Keys[key / 32] &= ~(1 << (key % 32));
        }
    }

    bool GetMouseButton(MousePacket* packet, MouseButton button)
    {
        if (packet != 0x0)
            return packet->m_Buttons[button / 32] & (1 << (button % 32));
        else
            return false;
    }

    void SetMouseButton(HMouse mouse, MouseButton button, bool value)
    {
        if (mouse != 0x0)
        {
            if (value)
                mouse->m_Packet.m_Buttons[button / 32] |= (1 << (button % 32));
            else
                mouse->m_Packet.m_Buttons[button / 32] &= ~(1 << (button % 32));
        }
    }

    void SetMousePosition(HMouse mouse, int32_t x, int32_t y)
    {
        if (mouse != 0x0)
        {
            MousePacket& packet = mouse->m_Packet;
            packet.m_PositionX = x;
            packet.m_PositionY = y;
        }
    }

    void SetMouseWheel(HMouse mouse, int32_t value)
    {
        if (mouse != 0x0)
        {
            mouse->m_Packet.m_Wheel = value;
        }
    }

    bool GetGamepadButton(GamepadPacket* packet, uint32_t button)
    {
        if (packet != 0x0)
            return packet->m_Buttons[button / 32] & (1 << (button % 32));
        else
            return false;
    }

    void SetGamepadButton(HGamepad gamepad, uint32_t button, bool value)
    {
        if (gamepad != 0x0)
        {
            if (value)
                gamepad->m_Packet.m_Buttons[button / 32] |= (1 << (button % 32));
            else
                gamepad->m_Packet.m_Buttons[button / 32] &= ~(1 << (button % 32));
        }
    }

    bool GetGamepadHat(GamepadPacket* packet, uint32_t hat, uint8_t* out_hat_value)
    {
        if (packet != 0x0)
        {
            *out_hat_value = packet->m_Hat[hat];
            return true;
        } else {
            return false;
        }
    }

    void SetGamepadAxis(HGamepad gamepad, uint32_t axis, float value)
    {
        if (gamepad != 0x0)
        {
            gamepad->m_Packet.m_Axis[axis] = value;
        }
    }

    // NOTE: A bit contrived function only used for unit-tests. See AddTouchPosition
    bool GetTouch(TouchDevicePacket* packet, uint32_t touch_index, int32_t* x, int32_t* y, uint32_t* id, bool* pressed, bool* released)
    {
        if (packet != 0x0
                && x != 0x0
                && y != 0x0
                && id != 0x0)
        {
            if (touch_index < packet->m_TouchCount)
            {
                const Touch& t = packet->m_Touches[touch_index];
                *x = t.m_X;
                *y = t.m_Y;
                *id = t.m_Id;

                if (pressed != 0x0) {
                    *pressed = t.m_Phase == dmHID::PHASE_BEGAN;
                }
                if (released != 0x0) {
                    *released = t.m_Phase == dmHID::PHASE_ENDED || t.m_Phase == dmHID::PHASE_CANCELLED;
                }
                return true;
            }
        }
        return false;
    }

    // NOTE: A bit contrived function only used for unit-tests
    // We should perhaps include additional relevant touch-arguments
    void AddTouch(HTouchDevice device, int32_t x, int32_t y, uint32_t id, Phase phase)
    {
        if (device != 0x0 && device->m_Connected)
        {
            TouchDevicePacket& packet = device->m_Packet;
            if (packet.m_TouchCount < MAX_TOUCH_COUNT)
            {
                Touch& t = packet.m_Touches[packet.m_TouchCount++];
                t.m_X = x;
                t.m_Y = y;
                t.m_Id = id;
                t.m_Phase = phase;
            }
        }
    }

    void ClearTouches(HTouchDevice device)
    {
        if (device != 0x0 && device->m_Connected)
        {
            device->m_Packet.m_TouchCount = 0;
        }
    }
}

max_stars_repo_name: cmarincia/defold

max_issues_repo_name: cmarincia/defold

max_forks_repo_name: cmarincia/defold


text:
//----------------------------------------------------------------------------
/// @file move_blocks.hpp
/// @brief contains the class move_blocks, which is part of the
///        block_indirect_sort algorithm
///
/// @author Copyright (c) 2016 Francisco Jose Tapia (fjtapia@gmail.com )\n
///         Distributed under the Boost Software License, Version 1.0.\n
///         ( See accompanying file LICENSE_1_0.txt or copy at
///           http://www.boost.org/LICENSE_1_0.txt  )
/// @version 0.1
///
/// @remarks
//-----------------------------------------------------------------------------
#ifndef __BOOST_SORT_PARALLEL_DETAIL_MOVE_BLOCKS_HPP
#define __BOOST_SORT_PARALLEL_DETAIL_MOVE_BLOCKS_HPP

#include <atomic>
#include <boost/sort/block_indirect_sort/blk_detail/backbone.hpp>
#include <future>
#include <iostream>
#include <iterator>

namespace boost {
namespace sort {
namespace blk_detail {
//----------------------------------------------------------------------------
//                          USING SENTENCES
//----------------------------------------------------------------------------
namespace bsc = boost::sort::common;
//
///---------------------------------------------------------------------------
/// @struct move_blocks
/// @brief This class move the blocks, trnasforming a logical sort by an index,
///        in physical sort
//----------------------------------------------------------------------------
template <uint32_t Block_size, uint32_t Group_size, class Iter_t, class Compare>
struct move_blocks {
  //-------------------------------------------------------------------------
  //                  D E F I N I T I O N S
  //-------------------------------------------------------------------------
  typedef move_blocks<Block_size, Group_size, Iter_t, Compare> this_type;
  typedef typename std::iterator_traits<Iter_t>::value_type value_t;
  typedef std::atomic<uint32_t> atomic_t;
  typedef bsc::range<size_t> range_pos;
  typedef bsc::range<Iter_t> range_it;
  typedef bsc::range<value_t *> range_buf;
  typedef std::function<void(void)> function_t;
  typedef backbone<Block_size, Iter_t, Compare> backbone_t;

  //------------------------------------------------------------------------
  //                V A R I A B L E S
  //------------------------------------------------------------------------
  // Object with the elements to sort and all internal data structures of the
  // algorithm
  backbone_t &bk;

  //------------------------------------------------------------------------
  //                F U N C T I O N S
  //------------------------------------------------------------------------
  move_blocks(backbone_t &bkb);

  void move_sequence(const std::vector<size_t> &init_sequence);

  void move_long_sequence(const std::vector<size_t> &init_sequence);
  //
  //------------------------------------------------------------------------
  //  function : function_move_sequence
  /// @brief create a function_t with a call to move_sequence, and insert
  ///        in the stack of the backbone
  ///
  /// @param sequence :sequence of positions for to move the blocks
  /// @param counter : atomic variable which is decremented when finish
  ///                  the function. This variable is used for to know
  ///                  when are finished all the function_t created
  ///                  inside an object
  /// @param error : global indicator of error.
  //------------------------------------------------------------------------
  void function_move_sequence(std::vector<size_t> &sequence, atomic_t &counter,
                              bool &error) {
    bscu::atomic_add(counter, 1);
    function_t f1 = [this, sequence, &counter, &error]() -> void {
      if (not error) {
        try {
          this->move_sequence(sequence);
        } catch (std::bad_alloc &) {
          error = true;
        };
      }
      bscu::atomic_sub(counter, 1);
    };
    bk.works.emplace_back(f1);
  }

  //
  //------------------------------------------------------------------------
  //  function : function_move_long_sequence
  /// @brief create a function_t with a call to move_long_sequence, and
  ///        insert in the stack of the backbone
  //
  /// @param sequence :sequence of positions for to move the blocks
  /// @param counter : atomic variable which is decremented when finish
  ///                  the function. This variable is used for to know
  ///                  when are finished all the function_t created
  ///                  inside an object
  /// @param error : global indicator of error.
  //------------------------------------------------------------------------
  void function_move_long_sequence(std::vector<size_t> &sequence,
                                   atomic_t &counter, bool &error) {
    bscu::atomic_add(counter, 1);
    function_t f1 = [this, sequence, &counter, &error]() -> void {
      if (not error) {
        try {
          this->move_long_sequence(sequence);
        } catch (std::bad_alloc &) {
          error = true;
        };
      }
      bscu::atomic_sub(counter, 1);
    };
    bk.works.emplace_back(f1);
  };
  //---------------------------------------------------------------------------
}; // end of struct move_blocks
//---------------------------------------------------------------------------
//
//############################################################################
//                                                                          ##
//                                                                          ##
//            N O N     I N L I N E      F U N C T I O N S                  ##
//                                                                          ##
//                                                                          ##
//############################################################################
//
//-------------------------------------------------------------------------
//  function : move_blocks
/// @brief constructor of the class for to move the blocks to their true
///        position obtained from the index
//
/// @param bkb : backbone with the index and the blocks
//-------------------------------------------------------------------------
template <uint32_t Block_size, uint32_t Group_size, class Iter_t, class Compare>
move_blocks<Block_size, Group_size, Iter_t, Compare>::move_blocks(
    backbone_t &bkb)
    : bk(bkb) {
  std::vector<std::vector<size_t>> vsequence;
  vsequence.reserve(bk.index.size() >> 1);
  std::vector<size_t> sequence;
  atomic_t counter(0);

  size_t pos_index_ini = 0, pos_index_src = 0, pos_index_dest = 0;
  while (pos_index_ini < bk.index.size()) {
    while (pos_index_ini < bk.index.size() and
           bk.index[pos_index_ini].pos() == pos_index_ini) {
      ++pos_index_ini;
    };

    if (pos_index_ini == bk.index.size())
      break;

    sequence.clear();
    pos_index_src = pos_index_dest = pos_index_ini;
    sequence.push_back(pos_index_ini);

    while (bk.index[pos_index_dest].pos() != pos_index_ini) {
      pos_index_src = bk.index[pos_index_dest].pos();
      sequence.push_back(pos_index_src);

      bk.index[pos_index_dest].set_pos(pos_index_dest);
      pos_index_dest = pos_index_src;
    };

    bk.index[pos_index_dest].set_pos(pos_index_dest);
    vsequence.push_back(sequence);

    if (sequence.size() < Group_size) {
      function_move_sequence(vsequence.back(), counter, bk.error);
    } else {
      function_move_long_sequence(vsequence.back(), counter, bk.error);
    };
  };
  bk.exec(counter);
};
//
//-------------------------------------------------------------------------
//  function : move_sequence
/// @brief move the blocks, following the positions of the init_sequence
//
/// @param init_sequence : vector with the positions from and where move the
///                        blocks
//-------------------------------------------------------------------------
template <uint32_t Block_size, uint32_t Group_size, class Iter_t, class Compare>
void move_blocks<Block_size, Group_size, Iter_t, Compare>::move_sequence(
    const std::vector<size_t> &init_sequence) {
  range_buf rbuf = bk.get_range_buf();
  size_t pos_range2 = init_sequence[0];

  range_it range2 = bk.get_range(pos_range2);
  move_forward(rbuf, range2);

  for (size_t i = 1; i < init_sequence.size(); ++i) {
    pos_range2 = init_sequence[i];
    range_it range1(range2);
    range2 = bk.get_range(pos_range2);
    move_forward(range1, range2);
  };
  move_forward(range2, rbuf);
};
//
//-------------------------------------------------------------------------
//  function : move_long_sequence
/// @brief move the blocks, following the positions of the init_sequence.
///        if the sequence is greater than Group_size, it is divided in small
///        sequences, creating function_t elements, for to be inserted in the
///        concurrent stack
//
/// @param init_sequence : vector with the positions from and where move the
///                        blocks
//-------------------------------------------------------------------------
template <uint32_t Block_size, uint32_t Group_size, class Iter_t, class Compare>
void move_blocks<Block_size, Group_size, Iter_t, Compare>::move_long_sequence(
    const std::vector<size_t> &init_sequence) {
  if (init_sequence.size() < Group_size)
    return move_sequence(init_sequence);

  size_t npart = (init_sequence.size() + Group_size - 1) / Group_size;
  size_t size_part = init_sequence.size() / npart;
  atomic_t son_counter(0);

  std::vector<size_t> sequence;
  sequence.reserve(size_part);

  std::vector<size_t> index_seq;
  index_seq.reserve(npart);

  auto it_pos = init_sequence.begin();
  for (size_t i = 0; i < (npart - 1); ++i, it_pos += size_part) {
    sequence.assign(it_pos, it_pos + size_part);
    index_seq.emplace_back(*(it_pos + size_part - 1));
    function_move_sequence(sequence, son_counter, bk.error);
  };

  sequence.assign(it_pos, init_sequence.end());
  index_seq.emplace_back(init_sequence.back());
  function_move_sequence(sequence, son_counter, bk.error);

  bk.exec(son_counter);
  if (bk.error)
    return;
  move_long_sequence(index_seq);
}

//
//****************************************************************************
}; //    End namespace blk_detail
}; //    End namespace sort
}; //    End namespace boost
//****************************************************************************
//
#endif

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
#include "Prime.h"
#include <cassert>
#include <thread>
#include <utility>
#include <iostream>

#include <boost/filesystem.hpp>
#include <boost/multiprecision/miller_rabin.hpp>

#include <rt/tasq.h>

#define PRIME_LIST_FILENAME "Primes.inc"
static const boost::multiprecision::cpp_int Primes[] = {
#include "Primes.inc"
};
static const size_t PrimeItems = sizeof(Primes) / sizeof(Primes[0]);

namespace {
#ifdef rt_SRC_DIR
boost::filesystem::path PrimeListDir = rt_SRC_DIR;
auto PrimeListPath = PrimeListDir / PRIME_LIST_FILENAME;
#endif
} // namespace

namespace omnn::rt {

bool GrowPrime(const boost::multiprecision::cpp_int& upto,
               std::function<bool(boost::multiprecision::cpp_int)> is_prime) {
    auto& prev = Primes[PrimeItems - 1];
    auto next = prev;
    ++next;
    static auto from = next;
    auto range = upto;
    range -= prev;
    auto chunks = std::thread::hardware_concurrency() - 1; // One thread left free for GC
    auto chunk = range;
    chunk /= chunks;
    if (from + chunk * chunks < upto) {
        ++chunk;
    }
    std::deque<std::future<std::string>> primining;
    std::cout << "new prime table target: " << upto << '(' << from + chunk * chunks << ')'<<std::endl;
    for (decltype(chunks) i = 0; i < chunks; ++i) {
        primining.emplace_back(std::async(std::launch::async, [=]() {
            std::stringstream ss;
            auto j = chunk;
            j *= i;
            j += from;
            auto up = j;
            up += chunk; // NOTE: preserving up type same as j. Expression (j+chunk)  type differs from j type.
            {
                static std::mutex m;
                std::lock_guard l(m);
                std::cout << '[' << j << ',' << up << ')';
            }
            for (; j < up; ++j) {
                if (is_prime(j)) {
                    std::cout << j << ',';
                    ss << j << ',';
                }
            }
            return std::move(ss.str());
        }));
    }

    int i = -1;
    while (primining.size()) {
        auto line = primining.front().get();
        std::cout << "Chunk " << ++i << std::endl << line << std::endl << "\n chunk is ready. Appending." << std::endl;
        std::ofstream PrimesIncFile(PrimeListPath.string(), std::ios_base::app);
        PrimesIncFile << std::endl << line;
        PrimesIncFile.close();
        primining.pop_front();
    }
    from++ = upto;
    return true;
}

const boost::multiprecision::cpp_int& prime(size_t idx) {
#ifndef NDEBUG
    auto haveThePrime = idx < PrimeItems;
    if (!haveThePrime) {
        std::cerr << "There is no " << idx
                  << "th prime in the table yet. Use GrowPrime call if you use debug version to increase the table for "
                     "next compile time. Currently the table has "
                  << PrimeItems << " elements" << std::endl;
        assert(haveThePrime);
    }
#endif
    return Primes[idx];
}

size_t primes() { return PrimeItems - 1; }

} // namespace omnn::rt

max_stars_repo_name: SergMariaDB/openmind

max_issues_repo_name: SergMariaDB/openmind

max_forks_repo_name: SergMariaDB/openmind


text:
/*
 *          Copyright Andrey Semashev 2007 - 2013.
 * 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)
 */
/*!
 * \file   util_formatting_ostream.cpp
 * \author Andrey Semashev
 * \date   26.05.2013
 *
 * \brief  This header contains tests for the formatting output stream wrapper.
 */

#define BOOST_TEST_MODULE util_formatting_ostream

#include <locale>
#include <string>
#include <iomanip>
#include <sstream>
#include <algorithm>
#include <boost/test/unit_test.hpp>
#include <boost/utility/string_ref.hpp>
#include <boost/log/utility/formatting_ostream.hpp>
#include "char_definitions.hpp"

#if defined(BOOST_LOG_USE_CHAR) && defined(BOOST_LOG_USE_WCHAR_T)

#define BOOST_UTF8_DECL
#define BOOST_UTF8_BEGIN_NAMESPACE namespace {
#define BOOST_UTF8_END_NAMESPACE }

#include <boost/detail/utf8_codecvt_facet.hpp>
#include <boost/detail/utf8_codecvt_facet.ipp>

#endif // defined(BOOST_LOG_USE_CHAR) && defined(BOOST_LOG_USE_WCHAR_T)

namespace logging = boost::log;

namespace {

template< typename CharT >
struct test_impl
{
    typedef CharT char_type;
    typedef test_data< char_type > strings;
    typedef std::basic_string< char_type > string_type;
    typedef std::basic_ostringstream< char_type > ostream_type;
    typedef logging::basic_formatting_ostream< char_type > formatting_ostream_type;

    template< typename StringT >
    static void width_formatting()
    {
        // Check that widening works
        {
            string_type str_fmt;
            formatting_ostream_type strm_fmt(str_fmt);
            strm_fmt << strings::abc() << std::setw(8) << (StringT)strings::abcd() << strings::ABC();
            strm_fmt.flush();

            ostream_type strm_correct;
            strm_correct << strings::abc() << std::setw(8) << (StringT)strings::abcd() << strings::ABC();

            BOOST_CHECK(equal_strings(strm_fmt.str(), strm_correct.str()));
        }

        // Check that the string is not truncated
        {
            string_type str_fmt;
            formatting_ostream_type strm_fmt(str_fmt);
            strm_fmt << strings::abc() << std::setw(1) << (StringT)strings::abcd() << strings::ABC();
            strm_fmt.flush();

            ostream_type strm_correct;
            strm_correct << strings::abc() << std::setw(1) << (StringT)strings::abcd() << strings::ABC();

            BOOST_CHECK(equal_strings(strm_fmt.str(), strm_correct.str()));
        }
    }

    template< typename StringT >
    static void fill_formatting()
    {
        string_type str_fmt;
        formatting_ostream_type strm_fmt(str_fmt);
        strm_fmt << strings::abc() << std::setfill(static_cast< char_type >('x')) << std::setw(8) << (StringT)strings::abcd() << strings::ABC();
        strm_fmt.flush();

        ostream_type strm_correct;
        strm_correct << strings::abc() << std::setfill(static_cast< char_type >('x')) << std::setw(8) << (StringT)strings::abcd() << strings::ABC();

        BOOST_CHECK(equal_strings(strm_fmt.str(), strm_correct.str()));
    }

    template< typename StringT >
    static void alignment()
    {
        // Left alignment
        {
            string_type str_fmt;
            formatting_ostream_type strm_fmt(str_fmt);
            strm_fmt << strings::abc() << std::setw(8) << std::left << (StringT)strings::abcd() << strings::ABC();
            strm_fmt.flush();

            ostream_type strm_correct;
            strm_correct << strings::abc() << std::setw(8) << std::left << (StringT)strings::abcd() << strings::ABC();

            BOOST_CHECK(equal_strings(strm_fmt.str(), strm_correct.str()));
        }

        // Right alignment
        {
            string_type str_fmt;
            formatting_ostream_type strm_fmt(str_fmt);
            strm_fmt << strings::abc() << std::setw(8) << std::right << (StringT)strings::abcd() << strings::ABC();
            strm_fmt.flush();

            ostream_type strm_correct;
            strm_correct << strings::abc() << std::setw(8) << std::right << (StringT)strings::abcd() << strings::ABC();

            BOOST_CHECK(equal_strings(strm_fmt.str(), strm_correct.str()));
        }
    }
};

} // namespace

// Test support for width formatting
BOOST_AUTO_TEST_CASE_TEMPLATE(width_formatting, CharT, char_types)
{
    typedef test_impl< CharT > test;
    test::BOOST_NESTED_TEMPLATE width_formatting< const CharT* >();
    test::BOOST_NESTED_TEMPLATE width_formatting< typename test::string_type >();
    test::BOOST_NESTED_TEMPLATE width_formatting< boost::basic_string_ref< CharT > >();
}

// Test support for filler character setup
BOOST_AUTO_TEST_CASE_TEMPLATE(fill_formatting, CharT, char_types)
{
    typedef test_impl< CharT > test;
    test::BOOST_NESTED_TEMPLATE fill_formatting< const CharT* >();
    test::BOOST_NESTED_TEMPLATE fill_formatting< typename test::string_type >();
    test::BOOST_NESTED_TEMPLATE fill_formatting< boost::basic_string_ref< CharT > >();
}

// Test support for text alignment
BOOST_AUTO_TEST_CASE_TEMPLATE(alignment, CharT, char_types)
{
    typedef test_impl< CharT > test;
    test::BOOST_NESTED_TEMPLATE alignment< const CharT* >();
    test::BOOST_NESTED_TEMPLATE alignment< typename test::string_type >();
    test::BOOST_NESTED_TEMPLATE alignment< boost::basic_string_ref< CharT > >();
}

#if defined(BOOST_LOG_USE_CHAR) && defined(BOOST_LOG_USE_WCHAR_T)

namespace {

const char narrow_chars[] =
{
    static_cast< char >(0xd0), static_cast< char >(0x9f), static_cast< char >(0xd1), static_cast< char >(0x80),
    static_cast< char >(0xd0), static_cast< char >(0xb8), static_cast< char >(0xd0), static_cast< char >(0xb2),
    static_cast< char >(0xd0), static_cast< char >(0xb5), static_cast< char >(0xd1), static_cast< char >(0x82),
    ',', ' ',
    static_cast< char >(0xd0), static_cast< char >(0xbc), static_cast< char >(0xd0), static_cast< char >(0xb8),
    static_cast< char >(0xd1), static_cast< char >(0x80), '!', 0
};
const wchar_t wide_chars[] = { 0x041f, 0x0440, 0x0438, 0x0432, 0x0435, 0x0442, L',', L' ', 0x043c, 0x0438, 0x0440, L'!', 0 };

template< typename StringT >
void test_narrowing_code_conversion()
{
    std::locale loc(std::locale::classic(), new utf8_codecvt_facet());

    std::string str_fmt;
    logging::formatting_ostream strm_fmt(str_fmt);
    strm_fmt.imbue(loc);
    strm_fmt << (StringT)wide_chars;
    strm_fmt.flush();

    BOOST_CHECK(equal_strings(str_fmt, std::string(narrow_chars)));
}

template< typename StringT >
void test_widening_code_conversion()
{
    std::locale loc(std::locale::classic(), new utf8_codecvt_facet());

    std::wstring str_fmt;
    logging::wformatting_ostream strm_fmt(str_fmt);
    strm_fmt.imbue(loc);
    strm_fmt << (StringT)narrow_chars;
    strm_fmt.flush();

    BOOST_CHECK(equal_strings(str_fmt, std::wstring(wide_chars)));
}

} // namespace

// Test character code conversion
BOOST_AUTO_TEST_CASE(character_code_conversion)
{
    test_narrowing_code_conversion< const wchar_t* >();
    test_widening_code_conversion< const char* >();
    test_narrowing_code_conversion< std::wstring >();
    test_widening_code_conversion< std::string >();
    test_narrowing_code_conversion< boost::wstring_ref >();
    test_widening_code_conversion< boost::string_ref >();
}

#endif

max_stars_repo_name: ballisticwhisper/boost

max_issues_repo_name: ballisticwhisper/boost

max_forks_repo_name: ballisticwhisper/boost


text:
#include <pybind11/pybind11.h>
#include <pybind11/embed.h>
namespace py = pybind11;

#include <iostream>
//#include <frameobject.h>
#include "mymodule.hpp"

// #include <boost/python.hpp>
// using namespace boost::python;
/*
#if PY_MAJOR_VERSION >= 3
#   define INIT_MODULE PyInit_mymodule
    extern "C" PyObject* INIT_MODULE();
#else
#   define INIT_MODULE initmymodule
    extern "C" void INIT_MODULE();
#endif
*/

int main(int argc, char** argv)
{
    try {
        //PyImport_AppendInittab((char*)"mymodule", INIT_MODULE);
        //Py_Initialize();

        //py::scoped_interpreter guard{};

        py::module main_module = py::module::import("__main__");
        py::dict main_namespace = py::cast<py::dict>(main_module.attr("__dict__"));
        py::module mymodule = py::module::import ("mymodule");

        main_namespace["precreated_object"] = Base("created on C++ side");
        py::eval_file ("embedding.py", main_namespace, main_namespace);
    } catch (py::error_already_set& e) {
        PyErr_PrintEx(0);
        return 1;
    }
    return 0;
}


text:
/**
 *  @file
 *  @copyright defined in evt/LICENSE.txt
 */
#pragma once
#include <functional>

#include <evt/chain/config.hpp>
#include <evt/chain/contracts/types.hpp>
#include <evt/chain/token_database.hpp>
#include <evt/chain/types.hpp>
#include <evt/utilities/parallel_markers.hpp>

#include <fc/scoped_exit.hpp>

#include <boost/algorithm/cxx11/all_of.hpp>
#include <boost/range/algorithm/find.hpp>

namespace evt { namespace chain {

using namespace evt::chain::contracts;

/**
* @brief This class determines whether a set of signing keys are sufficient to satisfy an authority or not
*
* To determine whether an authority is satisfied or not, we first determine which keys have approved of a message, and
* then determine whether that list of keys is sufficient to satisfy the authority. This class takes a list of keys and
* provides the @ref satisfied method to determine whether that list of keys satisfies a provided authority.
*
*/
class authority_checker {
private:
    const flat_set<public_key_type>& _signing_keys;
    const token_database&            _token_db;
    const uint32_t                   _max_recursion_depth;
    vector<bool>                     _used_keys;

    struct weight_tally_visitor {
        using result_type = uint32_t;

        authority_checker& checker;
        uint32_t           total_weight = 0;

        weight_tally_visitor(authority_checker& checker)
            : checker(checker) {}

        uint32_t
        operator()(const key_weight& permission) {
            return this->operator()(permission.key, permission.weight);
        }

        uint32_t
        operator()(const public_key_type& key, const weight_type weight) {
            auto itr = boost::find(checker._signing_keys, key);
            if(itr != checker._signing_keys.end()) {
                checker._used_keys[itr - checker._signing_keys.begin()] = true;
                total_weight += weight;
            }
            return total_weight;
        }
    };

public:
    authority_checker(const flat_set<public_key_type>& signing_keys, const token_database& token_db, uint32_t max_recursion_depth)
        : _signing_keys(signing_keys)
        , _token_db(token_db)
        , _max_recursion_depth(max_recursion_depth)
        , _used_keys(signing_keys.size(), false) {}

private:
    void
    get_permission(const domain_name& domain, const action_name name, std::function<void(const permission_def&)>&& cb) {
        _token_db.read_domain(domain, [&](const auto& domain) {
            if(name == N(issuetoken)) {
                cb(domain.issue);
            }
            else if(name == N(transfer)) {
                cb(domain.transfer);
            }
            else if(name == N(updatedomain)) {
                cb(domain.manage);
            }
        });
    }

    void
    get_group(const group_name& name, std::function<void(const group_def&)>&& cb) {
        _token_db.read_group(name, cb);
    }

    void
    get_owner(const domain_name& domain, const name128& name, std::function<void(const user_list&)>&& cb) {
        if(domain == N128(account)) {
            _token_db.read_account(name, [&](const auto& account) { cb(account.owner); });
        }
        else {
            _token_db.read_token(domain, name, [&](const auto& token) { cb(token.owner); });
        }
    }

private:
    bool
    satisfied_domain(const action& action) {
        if(action.name == N(newdomain)) {
            try {
                auto nd     = action.data_as<contracts::newdomain>();
                auto vistor = weight_tally_visitor(*this);
                if(vistor(nd.issuer, 1) == 1) {
                    return true;
                }
            }
            EVT_RETHROW_EXCEPTIONS(chain_type_exception, "transaction data is not valid, data cannot cast to `newdomain` type.");
        }
        else if(action.name == N(updatedomain)) {
            return satisfied_permission(action, action.key);
        }
        return false;
    }

    bool
    satisfied_group(const action& action) {
        if(action.name == N(newgroup)) {
            try {
                auto ng     = action.data_as<contracts::newgroup>();
                auto vistor = weight_tally_visitor(*this);
                if(vistor(ng.group.key(), 1) == 1) {
                    return true;
                }
            }
            EVT_RETHROW_EXCEPTIONS(chain_type_exception, "transaction data is not valid, data cannot cast to `newgroup` type.");
        }
        else if(action.name == N(updategroup)) {
            bool result = false;
            get_group(action.key, [&](const auto& group) {
                auto& gkey   = group.key();
                auto  vistor = weight_tally_visitor(*this);
                if(vistor(gkey, 1) == 1) {
                    result = true;
                }
            });
            return result;
        }
        return false;
    }

    bool
    satisfied_account(const action& action) {
        if(action.name == N(newaccount)) {
            try {
                auto na     = action.data_as<contracts::newaccount>();
                auto vistor = weight_tally_visitor(*this);
                for(auto& o : na.owner) {
                    vistor(o, 1);
                }
                if(vistor.total_weight == na.owner.size()) {
                    return true;
                }
            }
            EVT_RETHROW_EXCEPTIONS(chain_type_exception, "transation data is not valid, data cannot cast to `newaccount` type")
        }
        else if(action.name == N(updateowner)) {
            bool result = false;
            get_owner(action.domain, action.key, [&](const auto& owner) {
                auto vistor = weight_tally_visitor(*this);
                for(auto& o : owner) {
                    vistor(o, 1);
                }
                if(vistor.total_weight == owner.size()) {
                    result = true;
                }
            });
            return result;
        }
        else if(action.name == N(transferevt)) {
            bool result = false;
            try {
                auto te = action.data_as<contracts::transferevt>();
                get_owner(N128(account), te.from, [&](const auto& owner) {
                    auto vistor = weight_tally_visitor(*this);
                    for(auto& o : owner) {
                        vistor(o, 1);
                    }
                    if(vistor.total_weight == owner.size()) {
                        result = true;
                    }
                });
            }
            EVT_RETHROW_EXCEPTIONS(chain_type_exception, "transation data is not valid, data cannot cast to `transferevt` type")
            return result;
        }
        return false;
    }

    bool
    satisfied_node(const group& group, const group::node& node, uint32_t depth) {
        FC_ASSERT(depth < _max_recursion_depth);
        FC_ASSERT(!node.is_leaf());
        auto vistor = weight_tally_visitor(*this);
        group.visit_node(node, [&](const auto& n) {
            FC_ASSERT(!n.is_root());
            if(n.is_leaf()) {
                vistor(group.keys_[n.index], n.weight);
            }
            else {
                if(satisfied_node(group, n, depth + 1)) {
                    vistor.total_weight += n.weight;
                }
            }
            if(vistor.total_weight >= node.threshold) {
                return false;  // no need to visit more nodes
            }
            return true;
        });
        if(vistor.total_weight >= node.threshold) {
            return true;
        }
        return false;
    }

    bool
    satisfied_permission(const action& action, const domain_name& domain) {
        bool result = false;
        get_permission(domain, action.name, [&](const auto& permission) {
            uint32_t total_weight = 0;
            for(const auto& aw : permission.authorizers) {
                auto& ref        = aw.ref;
                bool  ref_result = false;

                switch(ref.type()) {
                case authorizer_ref::account_t: {
                    auto  vistor = weight_tally_visitor(*this);
                    auto& key    = ref.get_account();
                    if(vistor(key, 1) == 1) {
                        ref_result = true;
                    }
                    break;
                }
                case authorizer_ref::owner_t: {
                    get_owner(domain, action.key, [&](const auto& owner) {
                        auto vistor = weight_tally_visitor(*this);
                        for(const auto& o : owner) {
                            vistor(o, 1);
                        }
                        if(vistor.total_weight == owner.size()) {
                            ref_result = true;
                        }
                    });
                    break;
                }
                case authorizer_ref::group_t: {
                    auto& name = ref.get_group();
                    get_group(name, [&](const auto& group) {
                        if(satisfied_node(group, group.root(), 0)) {
                            ref_result = true;
                        }
                    });
                    break;
                }
                }  // switch

                if(ref_result) {
                    total_weight += aw.weight;
                    if(total_weight >= permission.threshold) {
                        result = true;
                        return;
                    }
                }
            }
        });
        return result;
    }

    bool
    satisfied_token(const action& action) {
        return satisfied_permission(action, action.domain);
    }

public:
    bool
    satisfied(const action& action) {
        // Save the current used keys; if we do not satisfy this authority, the newly used keys aren't actually used
        auto KeyReverter = fc::make_scoped_exit([this, keys = _used_keys]() mutable {
            _used_keys = keys;
        });
        bool result      = false;

        if(action.domain == N128(domain)) {
            result = satisfied_domain(action);
        }
        else if(action.domain == N128(group)) {
            result = satisfied_group(action);
        }
        else if(action.domain == N128(account)) {
            result = satisfied_account(action);
        }
        else {
            result = satisfied_token(action);
        }
        if(result) {
            KeyReverter.cancel();
            return true;
        }
        return false;
    }

    bool
    all_keys_used() const { return boost::algorithm::all_of_equal(_used_keys, true); }

    flat_set<public_key_type>
    used_keys() const {
        auto range = utilities::filter_data_by_marker(_signing_keys, _used_keys, true);
        return range;
    }

    flat_set<public_key_type>
    unused_keys() const {
        auto range = utilities::filter_data_by_marker(_signing_keys, _used_keys, false);
        return range;
    }
};  /// authority_checker

}}  // namespace evt::chain


text:
// Copyright (C) by Josh Blum. See LICENSE.txt for licensing information.

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

#include <gras/chrono.hpp>
#include <boost/thread/thread.hpp> //sleep

BOOST_AUTO_TEST_CASE(test_chrono_time)
{
    for (size_t trial_i = 0; trial_i < 100; trial_i++)
    {
        const double sleep_secs = 0.01 + trial_i*0.0001;
        gras::time_ticks_t t0 = gras::time_now();
        boost::this_thread::sleep(boost::posix_time::milliseconds(long(sleep_secs*1000)));
        gras::time_ticks_t t1 = gras::time_now();

        std::cout << "t0 " << t0 << std::endl;
        std::cout << "t1 " << t1 << std::endl;
        BOOST_CHECK(t1 > t0);

        const double delta_time = double(t1-t0)/gras::time_tps();
        std::cout << "delta_time " << delta_time << std::endl;
        const double low_margin = sleep_secs - sleep_secs/2;
        const double high_margin = sleep_secs + sleep_secs/2;
        BOOST_CHECK(delta_time < high_margin and delta_time > low_margin);
    }
}

max_stars_repo_name: guruofquality/gras

max_issues_repo_name: guruofquality/gras

max_forks_repo_name: guruofquality/gras