text:
// *****************************************************************************
//
// cppgit/parse/ls_files.cpp
//
// Copyright Chris Glover 2017
//
// 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
//
// *****************************************************************************
#include "parse/parse.hpp"
#include "parse/parse_common.hpp"
#include "cppgit/result/lfs/ls_files.hpp"
#include <boost/spirit/home/x3.hpp>

#include <boost/fusion/adapted/struct/adapt_struct.hpp>

BOOST_FUSION_ADAPT_STRUCT(
    cppgit::result::lfs::ls_files::status,
    sha1,
    file
);

// -----------------------------------------------------------------------------
//
namespace cppgit { namespace parse { namespace lfs
{
    void ls_files(boost::asio::basic_streambuf<> const& result_buffer, result::lfs::ls_files& result)
    {
        boost::asio::streambuf::const_buffers_type bufs = result_buffer.data();
        auto range = extract_iterators(result_buffer);
        buffer_iterator current = range.begin();

        namespace x3 = boost::spirit::x3;
        using x3::char_;
        using x3::eol;
        using x3::space;
        using x3::lit;

        //auto inserter = [&result](auto ctx)
        //{
        //    auto&& attrib = _attr(ctx);
        //    result.files.push_back(
        //    {
        //        std::move(boost::fusion::at_c<0>(attrib)),
        //        std::move(boost::fusion::at_c<1>(attrib))
        //    });
        //};

        auto sha1 = x3::repeat(64)[char_ - space];
        auto file = (+(char_ - eol));
        auto line = (sha1 >> lit(' ') >> (lit('*') | lit('-')) >> lit(' ') >> file); //[inserter];

        bool r = x3::parse(current, range.end(),
            //  Begin grammar
            (
                line >> *(eol >> line)
            )
            //  End grammar
            , result.files
        );

        if (!r)
            throw exception("Failed to parse list result", std::string(range.begin(), range.end()));
    }
}}}

max_stars_repo_name: cdglove/git-qt

max_issues_repo_name: cdglove/git-qt

max_forks_repo_name: cdglove/git-qt


text:
#pragma once

#include <Eigen/Dense>
#include <vector>
#include "../flux_worker.hpp"
#include "../outflow_helper.hpp"
#include "aux/eigen2hdf.hpp"
#include "base/numbers.hpp"

namespace boltzmann {
namespace impl_mls {

class DiffusiveReflection : public boltzmann::impl::flux_worker
{
 public:
  /**
   * @param hw Hermite quad. weights (from @see QHermiteW)
   * @param hx Hermite quad. nodes
   * @param vt tangential velocity (moving wall)
   * @param Tw wall temperature
   * @param rho scaling factor
   *
   */
  DiffusiveReflection(const vec_t& hw, const vec_t& hx, double vt, double Tw, double rho = 1.0);

  virtual void apply(mat_t& out,
                     const mat_t& in,
                     const dealii::Point<2>& dummy = dealii::Point<2>(0, 0)) const;

 private:
  boltzmann::impl::outflow_helper outflow_;
  const vec_t w_;
  const vec_t x_;
  double rho_;

  // Eigen::MatrixXd rho_minus_;
  Eigen::MatrixXd Mw_;
};

// --------------------------------------------------------------------------------
DiffusiveReflection::DiffusiveReflection(
    const vec_t& hw, const vec_t& hx, double vt, double Tw, double rho)
    : outflow_(hw, hx)
    , w_(hw)
    , x_(hx)
    , rho_(rho)
{
  unsigned int K = hx.size();
  Mw_.resize(K, K);

  unsigned int khalf = K / 2;

  // normalization factor
  const double fMw = rho_ / std::sqrt(2 * numbers::PI) / std::pow(Tw, 1.5);

  // initialize maxwellian
  for (unsigned int i = 0; i < K; ++i) {
    for (unsigned int j = 0; j < K; ++j) {
      if (i < khalf) {  // inflow boundary
        double x2h = std::pow(x_[i], 2) + std::pow(x_[j] - vt, 2);
        Mw_(i, j) = fMw * std::exp(0.5 * x2h * (-1. / Tw)) * std::sqrt(w_[i] * w_[j]) * x_[i];
      } else {  // outflow
        Mw_(i, j) = 0;
      }
    }
  }

}

// --------------------------------------------------------------------------------
void
DiffusiveReflection::apply(mat_t& out, const mat_t& in, const dealii::Point<2>& dummy) const
{
  int K = out.cols();

  // compute outflow
  double rhom = 0;
  for (int i = 0; i < K; ++i) {
    for (int j = 0; j < K; ++j) {
      rhom += in(i, j) * outflow_.get_y(i) * outflow_.get_x(j);
    }
  }

  int khalf = K / 2;

  out.setZero();

  // outflow
  for (int i = khalf; i < K; ++i) {
    for (int j = 0; j < K; ++j) {
      out(i, j) = in(i, j) * x_[i];
    }
  }

  // inflow M_w
  out += Mw_ * rhom;
}

}  // namespace impl_mls
}  // end namespace boltzmann

ext: hpp


text:
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE parser

#include <chrono>
#include <memory_resource>
#include <boost/test/unit_test.hpp>
#include <http_parser/parser.hpp>
#include <http_parser.hpp>

using namespace std::literals;

BOOST_AUTO_TEST_SUITE(core)
BOOST_AUTO_TEST_SUITE(acceptor)
BOOST_AUTO_TEST_SUITE(request)
using parser_t = http_parser::http1_req_parser<std::pmr::vector, std::pmr::string, 100, 100>;
using http1_msg_t = parser_t::message_t;
struct test_acceptor : parser_t::traits_type {
	std::pmr::memory_resource* mem = std::pmr::get_default_resource();
	std::size_t count = 0;
	std::size_t head_count = 0;
	std::size_t error_count = 0;
	std::size_t data_created_count = 0;
	std::size_t headers_created_count = 0;
	std::function<void(const http1_msg_t& req_head_message)> head_check;
	std::function<void(const http1_msg_t& req_head_message, const data_view& body)> check, error_check;

	std::pmr::string create_data_container() override { ++data_created_count; return std::pmr::string{ mem }; }
	http1_msg_t::headers_container create_headers_container() override {
		++headers_created_count;
		return http1_msg_t::headers_container{ mem };
	}

	void on_head(const http1_msg_t& head) override { ++head_count; if(head_check) head_check(head); }
	void on_message(const http1_msg_t& head, const data_view& body) override {
		++count;
		if(check) check(head, body);
	}
	void on_error(const http1_msg_t& head, const data_view& body) override {
		if(!error_check) BOOST_FAIL("some error detected");
		else {
			++error_count;
			error_check(head, body);
		}
	}
};

BOOST_AUTO_TEST_CASE(head)
{
	test_acceptor traits;
	parser_t acceptor( &traits );
	traits.check = [](const http1_msg_t& header, const auto& body) {
		BOOST_TEST(header.head().method() == "DELETE"sv);
		BOOST_TEST(header.head().url().uri() == "/path"sv);
		BOOST_TEST(header.find_header("H1").value() == "v1"sv);
		BOOST_TEST(header.headers().headers().size() == 1);
		BOOST_TEST(body.size() == 0);
	};
	acceptor("DELETE /path HTTP/1.1\r\nH1:v1\r\n\r\n"sv);
	BOOST_TEST(traits.count == 1);
	BOOST_TEST(traits.head_count == 0);
}
BOOST_AUTO_TEST_CASE(simple_body)
{
	test_acceptor traits;
	parser_t acceptor( &traits );
	traits.check = [&traits](const http1_msg_t& header, const auto& body) {
		BOOST_TEST(traits.head_count == 1);
		BOOST_TEST(header.head().method() == "POST"sv);
		BOOST_TEST(header.head().url().uri() == "/pa/th?a=b"sv);
		BOOST_TEST(header.find_header("H1").value() == "v1"sv);
		BOOST_TEST(header.headers().headers().size() == 2);
		BOOST_TEST(body.size() == 2);
		BOOST_TEST(body == "ok"sv);
	};
	traits.head_check = [&traits](const http1_msg_t& header) {
		BOOST_TEST(traits.count == 0);
		BOOST_TEST(header.head().method() == "POST"sv);
		BOOST_TEST(header.head().url().uri() == "/pa/th?a=b"sv);
		BOOST_TEST(header.find_header("H1").value() == "v1"sv);
		BOOST_TEST(header.headers().headers().size() == 2);
		BOOST_TEST(header.headers().content_size().value() == 2);
	};
	acceptor("POST /pa/th?a=b HTTP/1.1\r\nH1:v1\r\nContent-Length: 2\r\n\r\nok_extra"sv);
	BOOST_TEST(traits.count == 1);
	BOOST_TEST(traits.head_count == 1);
}
BOOST_AUTO_TEST_CASE(chunked_body)
{
	test_acceptor traits;
	parser_t acceptor( &traits );
	traits.check = [&traits](const http1_msg_t& header, const auto& body) {
		BOOST_TEST(traits.head_count == 1);
		BOOST_TEST_CONTEXT("current count " << traits.count) {
			if(traits.count == 1) {
				BOOST_TEST(body.size() == 2);
				BOOST_TEST(body == "ok"sv);
			} else if(traits.count == 2) {
				BOOST_TEST(body.size() == 10);
				BOOST_TEST(body == "1234567890"sv);
			} else if(traits.count == 3) {
				BOOST_TEST(body.size() == 0x5a);
				BOOST_TEST(body == "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"sv);
			} else if(traits.count == 4) {
				BOOST_TEST(body.size() == 0);
				BOOST_TEST(body == ""sv);
			} else {
				BOOST_FAIL("the count is "s << traits.count << ' ' << body);
			}
		}
	};
	traits.head_check = [&traits](const http1_msg_t& header) {
		BOOST_TEST(traits.count == 0);
		BOOST_TEST(header.headers().is_chunked() == true);
	};
	acceptor("POST /pa/th?a=b HTTP/1.1\r\nH1:v1\r\nTransfer-Encoding: chunked\r\n\r\n2\r\nokA\r\n12345678905a"sv);
	BOOST_TEST(traits.count == 2);
	BOOST_TEST(traits.head_count == 1);

	acceptor("\r\n"sv);
	BOOST_TEST(traits.count == 2);
	BOOST_TEST(traits.head_count == 1);

	acceptor("1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678900\r"sv);
	BOOST_TEST(traits.count == 3);
	BOOST_TEST(traits.head_count == 1);

	acceptor("\n"sv);
	BOOST_TEST(traits.count == 4);
	BOOST_TEST(traits.head_count == 1);
}
BOOST_AUTO_TEST_CASE(chunked_body_trash)
{
	test_acceptor traits;
	parser_t acceptor( &traits );
	traits.check = [&traits](const http1_msg_t& header, const auto& body) {
		BOOST_TEST(traits.head_count == 1);
		BOOST_TEST_CONTEXT("current count " << traits.count) {
			if(traits.count == 1) {
				BOOST_TEST(body.size() == 2);
				BOOST_TEST(body == "ok"sv);
			} else if(traits.count == 2) {
				BOOST_TEST(body.size() == 10);
				BOOST_TEST(body == "1234567890"sv);
			}
		}
	};

	acceptor("POST /pa/th?a=b HTTP/1.1\r\nH1:v1\r\nTransfer-Encoding: chunked\r\n\r\n2\r\noktrashA\r\n12345678905a"sv);
	BOOST_TEST(traits.count == 2);
	BOOST_TEST(traits.head_count == 1);
}
BOOST_AUTO_TEST_CASE(chunked_body_error)
{
	test_acceptor traits;
	parser_t acceptor( &traits );
	traits.error_check = [&traits](const http1_msg_t& header, const auto& body) {
		BOOST_TEST(traits.count == 0);
		BOOST_TEST(traits.head_count == 1);
	};
	acceptor("POST /pa/th?a=b HTTP/1.1\r\nH1:v1\r\nTransfer-Encoding: chunked\r\n\r\n\r\nok"sv);
	BOOST_TEST(traits.error_count == 1);
}
BOOST_AUTO_TEST_CASE(head_limit_overflow)
{
	test_acceptor traits;
	parser_t acceptor( &traits );
	BOOST_CHECK_THROW( acceptor(
	                       "POST /p HTTP/1.1\r\n"
	                       "H1:1234567890123456789012345678901234567890"
	                       "1234567890123456789012345678901234567890"
	                       "12345678901234567890\r\n"sv), std::out_of_range );
}
BOOST_AUTO_TEST_CASE(body_limit_overflow)
{
	test_acceptor traits;
	parser_t acceptor( &traits );
	BOOST_CHECK_NO_THROW( acceptor(
	                       "POST /p HTTP/1.1\r\nContent-Length: 120\r\n\r\n"
	                       "1234567890123456789012345678901234567890"
	                       "1234567890123456789012345678901234567890"
	                       ""sv) );
	BOOST_CHECK_THROW( acceptor("0034567890123456789012345678901234567890"sv), std::out_of_range);
}
BOOST_AUTO_TEST_CASE(head_by_peaces)
{
	test_acceptor traits;
	parser_t acceptor( &traits );
	traits.check = [](const http1_msg_t& header, const auto& body) {
		BOOST_TEST(header.head().method() == "DELETE"sv);
		BOOST_TEST(header.head().url().uri() == "/path"sv);
		BOOST_TEST(header.find_header("H1").value() == "v1"sv);
		BOOST_TEST(header.headers().headers().size() == 1);
		BOOST_TEST(body.size() == 0);
	};
	acceptor("DELETE /path "sv);
	BOOST_TEST(traits.count == 0);
	acceptor("HTTP/1.1\r\nH"sv);
	BOOST_TEST(traits.count == 0);
	acceptor("1:v1\r\n\r"sv);
	BOOST_TEST(traits.count == 0);
	acceptor("\n"sv);
	BOOST_TEST(traits.count == 1);
	BOOST_TEST(traits.head_count == 0);
}
BOOST_AUTO_TEST_CASE(memory)
{
	struct raii {
		raii() {
			std::pmr::set_default_resource(std::pmr::null_memory_resource());
		}
		~raii() {
			std::pmr::set_default_resource(std::pmr::new_delete_resource());
		}
	} mr_setter;
	test_acceptor traits;
	traits.mem = std::pmr::new_delete_resource();
	parser_t acceptor( &traits );
	traits.check = [&traits](const http1_msg_t& header, const auto& body) {
		BOOST_TEST(traits.head_count == 1);
		BOOST_TEST(header.head().method() == "POST"sv);
		BOOST_TEST(header.head().url().uri() == "/pa/th?a=b"sv);
		BOOST_TEST(header.find_header("H1").value() == "v1"sv);
		BOOST_TEST(header.headers().headers().size() == 2);
		BOOST_TEST(body.size() == 2);
		BOOST_TEST(body == "ok"sv);
	};
	traits.head_check = [&traits](const http1_msg_t& header) {
		BOOST_TEST(traits.count == 0);
		BOOST_TEST(header.head().method() == "POST"sv);
		BOOST_TEST(header.head().url().uri() == "/pa/th?a=b"sv);
		BOOST_TEST(header.find_header("H1").value() == "v1"sv);
		BOOST_TEST(header.headers().headers().size() == 2);
		BOOST_TEST(header.headers().content_size().value() == 2);
	};
	BOOST_TEST_CHECKPOINT("start parse");
	acceptor("POST /pa/th?a=b HTTP/1.1\r\nH1:v1\r\nContent-Length: 2\r\n\r\nok_extra"sv);
	BOOST_TEST(traits.count == 1);
	BOOST_TEST(traits.head_count == 1);
}
BOOST_AUTO_TEST_SUITE_END() // request

BOOST_AUTO_TEST_SUITE(response)
using parser_t = http_parser::http1_resp_parser<std::pmr::vector, std::pmr::string, 100, 100>;
using http1_msg_t = parser_t::message_t;
struct test_acceptor : parser_t::traits_type {
	std::size_t count = 0;
	std::size_t head_count = 0;
	std::size_t data_created_count = 0;
	std::size_t headers_created_count = 0;
	std::function<void(const http1_msg_t& req_head_message)> head_check;
	std::function<void(const http1_msg_t& req_head_message, const data_view& body)> check;

	std::pmr::string create_data_container() override { ++data_created_count; return std::pmr::string{}; }
	http1_msg_t::headers_container create_headers_container() override {
		++headers_created_count;
		return http1_msg_t::headers_container{};
	}

	void on_head(const http1_msg_t& head) override { ++head_count; if(head_check) head_check(head); }
	void on_message(const http1_msg_t& head, const data_view& body) override {
		++count;
		if(check) check(head, body);
	}
};
BOOST_AUTO_TEST_CASE(simple_haed)
{
	test_acceptor traits;
	parser_t acceptor( &traits );
	traits.check = [](const http1_msg_t& header, const auto& body) {
		BOOST_TEST(header.head().code == 300);
		BOOST_TEST(header.head().reason == "TEST"sv);
		BOOST_TEST(header.find_header("H1").value() == "v1"sv);
		BOOST_TEST(header.headers().headers().size() == 1);
		BOOST_TEST(body.size() == 0);
	};
	acceptor("HTTP/1.1 300 TEST\r\nH1:v1\r\n\r\n"sv);
	BOOST_TEST(traits.count == 1);
	BOOST_TEST(traits.head_count == 0);
}
BOOST_AUTO_TEST_CASE(simple_body)
{
	test_acceptor traits;
	parser_t acceptor( &traits );
	traits.check = [&traits](const http1_msg_t& header, const auto& body) {
		BOOST_TEST(header.head().code == 250);
		BOOST_TEST(header.head().reason == "OK"sv);
		BOOST_TEST(header.find_header("H1").value() == "v1"sv);
		BOOST_TEST(header.headers().headers().size() == 2);
		BOOST_TEST(body.size() == 2);
		BOOST_TEST(body == "ok"sv);
	};
	traits.head_check = [&traits](const http1_msg_t& header) {
		BOOST_TEST(header.head().code == 250);
		BOOST_TEST(header.head().reason == "OK"sv);
		BOOST_TEST(header.find_header("H1").value() == "v1"sv);
		BOOST_TEST(header.headers().headers().size() == 2);
		BOOST_TEST(header.headers().content_size().value() == 2);
	};
	acceptor("HTTP/1.1 250 OK\r\nH1:v1\r\nContent-Length: 2\r\n\r\nok_extra"sv);
	BOOST_TEST(traits.count == 1);
	BOOST_TEST(traits.head_count == 1);
}
BOOST_AUTO_TEST_SUITE_END() // response

BOOST_AUTO_TEST_SUITE_END() // acceptor
BOOST_AUTO_TEST_SUITE_END() // core

ext: cpp


text:
/*
** EPITECH PROJECT, 2019
** oop_indie_studio_2018
** File description:
** Player
*/

#include "Player.hpp"
#include "Bonus.hpp"
#include <boost/lexical_cast.hpp>
#include <iostream>

static const int HITBOX = 50;
static const int PHIT = 30;
static const int NOMOVE_TRESHOLD = 10;
static const int TILESIZE = 50;

game_logic::Player::Player(unsigned int id, std::pair<float, float> position, const bool &isAlive)
    : _bombHandler(new BombHandler(id)),
      _position(position),
      _direction(Direction::NONE),
      _noMove(0),
      _id(id),
      _speed(5),
      _isAlive(isAlive)
{
}

void game_logic::Player::dropBomb(std::vector<Bomb> &bombs)
{
    if (_isAlive == false)
        return;
    std::pair<float, float> roundedPos;
    int q = (int) _position.first % TILESIZE;
    roundedPos.first = (q > TILESIZE / 2) ? std::trunc(_position.first - q) + TILESIZE : std::trunc(_position.first - q);
    q = (int)_position.second % TILESIZE;
    roundedPos.second = (q > TILESIZE / 2) ? std::trunc(_position.second - q) + TILESIZE : std::trunc(_position.second - q);
    auto it = find_if(bombs.begin(), bombs.end(), [&](Bomb const &bomb) {
        return roundedPos == bomb.getPosition();
    });
    if (it == bombs.end())
    {
        _bombHandler->newBomb(bombs, _position.first, _position.second);
    }
}

void game_logic::Player::update(std::vector<Wall> &walls, std::vector<Bomb> &bombs)
{
    if (!_isAlive)
        return;
    _noMove += 1;
    if (_noMove >= NOMOVE_TRESHOLD)
        _direction = NONE;
    _bombHandler->udpate(walls, bombs, _position);
    _isAlive = !_bombHandler->playerHit();
}

bool game_logic::Player::isAlive()
{
    return _isAlive;
}

void game_logic::Player::serialize(std::string &sdata)
{
    sdata += boost::lexical_cast<std::string>(_id) + ",";
    sdata += boost::lexical_cast<std::string>(_position.first) + ",";
    sdata += boost::lexical_cast<std::string>(_position.second) + ",";
    sdata += boost::lexical_cast<std::string>(_direction) + ",";
    sdata += (_isAlive) ? "1;" : "0;";
}

void game_logic::Player::move(std::vector<Wall> &walls, Direction direction)
{
    if (_isAlive == false)
        return;
    _direction = direction;
    _noMove = 0;
    switch (direction)
    {
    case Direction::UP:
        _position.second -= _speed;
        break;
    case Direction::DOWN:
        _position.second += _speed;
        break;
    case Direction::LEFT:
        _position.first -= _speed;
        break;
    case Direction::RIGHT:
        _position.first += _speed;
        break;
    default:
        break;
    }
    auto it = find_if(walls.begin(), walls.end(), [&](Wall const &wall) {
        return _position.first > wall.getPosition().first - PHIT && _position.first < wall.getPosition().first + HITBOX &&
        _position.second > wall.getPosition().second - PHIT && _position.second < wall.getPosition().second + HITBOX && !wall.bonusMode();
    });
    if (it != walls.end()) {
        switch (direction)
        {
        case Direction::UP:
            _position.second = it->getPosition().second + HITBOX;
            break;
        case Direction::DOWN:
            _position.second = it->getPosition().second - PHIT;
            break;
        case Direction::LEFT:
            _position.first = it->getPosition().first + HITBOX;
            break;
        case Direction::RIGHT:
            _position.first = it->getPosition().first - PHIT;
            break;
        default:
            break;
        }
    }
    it = find_if(walls.begin(), walls.end(), [&](Wall const &wall) {
        return _position.first > wall.getPosition().first - PHIT && _position.first < wall.getPosition().first + HITBOX &&
        _position.second > wall.getPosition().second - PHIT && _position.second < wall.getPosition().second + HITBOX && wall.bonusMode();
    });
    if (it == walls.end())
        return;
    switch (it->getBonus())
    {
    case Bonus::POWER:
        _bombHandler->increasePower(1);
        break;
    case Bonus::SPEED:
        _bombHandler->increaseExpSpeed(0.25f);
        break;
    case Bonus::STACK:
        _bombHandler->increaseThreshold(1);
        break;
    case Bonus::PASST:
        // Work in progress
        break;
    default:
        break;
    }
    it->destroy();
}

unsigned int game_logic::Player::getId() const
{
    return _id;
}

void game_logic::Player::setSpeed(unsigned int speed)
{
    _speed = speed;
}

void game_logic::Player::setPosition(std::pair<float, float> position)
{
    _position = position;
}


text:
#ifndef INCLUDE_CSV_PRINT_HPP_
#define INCLUDE_CSV_PRINT_HPP_

#include <stdio.h>
#include <string.h>

#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <boost/scoped_array.hpp>
#include <boost/scoped_ptr.hpp>

#include <csv/constants.hpp>
#include <csv/error.hpp>
#include <csv/match.hpp>
#include <csv/st.hpp>

namespace csv {

  // LCOV_EXCL_START
  inline void print(const char* buf, size_t length) {
    fwrite(buf, sizeof(char), length, stdout);
  }
  // LCOV_EXCL_END

  // LCOV_EXCL_START
  inline void print_field(const char* buf,
			  const std::vector<size_t>& offsets,
			  size_t field_idx){
    size_t next_field_idx = field_idx + 1;
    assert(offsets.size() > next_field_idx);
    size_t offset = offsets[field_idx];
    size_t length = offsets[next_field_idx] - offset - 1;
    csv::print(buf + offset, length);
  }
  // LCOV_EXCL_END

  class Field_Printer {
  private:
    const std::vector<size_t> _fields;
    const char _delimiter;
    const bool _crnl;
    const bool _nl;
    const bool _cont;
    bool _allow_out_of_bounds;

  public:
    void print(const char* buf,
	       const std::vector<size_t>& offsets) const;
    void print(const std::vector<std::string>& fields) const;
    void allow_out_of_bounds(bool v) { _allow_out_of_bounds = v; };
    Field_Printer(std::vector<size_t> fields,
		  char delimiter,
		  bool crnl,
		  bool nl,
		  bool cont) :
      _fields {fields}, _delimiter {delimiter}, _crnl {crnl},
      _nl {nl}, _cont {cont}, _allow_out_of_bounds {false} {};
  };

  class Linescan_Printer { // LCOV_EXCL_START
  public:
    virtual void print(const Linescan& sc_result) const = 0;
    virtual ~Linescan_Printer(){};
  }; // LCOV_EXCL_STOP

  class Linescan_Line_Printer : public Linescan_Printer { // LCOV_EXCL_START
  public:
    void print(const Linescan& sc_result) const override;
  }; // LCOV_EXCL_STOP

  class Linescan_Field_Printer : public Linescan_Printer { // LCOV_EXCL_START
  private:
    const std::unique_ptr<csv::Field_Printer> _printer;

  public:
    void print(const Linescan& sc_result) const override;
    Linescan_Field_Printer(std::unique_ptr<csv::Field_Printer> printer) :
      _printer {std::move(printer)} {};
  }; // LCOV_EXCL_STOP

}

#endif

max_stars_repo_name: mrkschneider/cpptab

max_issues_repo_name: mrkschneider/cpptab

max_forks_repo_name: mrkschneider/cpptab


text:
/**
 * @file FileLogger.cpp
 *
 * @author Nicolae Natea
 * Contact: nicu@natea.ro
 */

#include <algorithm>
#include <iostream>
#include <filesystem>
#include <fstream>
#include <regex>
#include <string>

#include <boost/format.hpp>

#include <core/util/Time.hpp>

#include <core/logger/impl/FileLogger.hpp>

namespace util
{
    namespace logger
	{
        FileLogger::FileLogger(const boost::property_tree::ptree::value_type &config)
        {
            m_file_prefix      = config.second.get<std::string>("file.prefix", "");
            m_file_suffix      = config.second.get<std::string> ("file.suffix", "");
            m_file_path        = config.second.get<std::string>("file.path", "");
            m_max_nbr_of_files = config.second.get<uint32_t>("max.files", 0);
            m_max_file_size_b  = config.second.get<uint32_t>("max.file_size", 0);
            m_current_file     = get_file_path(0);
            m_current_index    = 0;

            initialize_fs();
        }

        std::string FileLogger::get_file_path(uint32_t index) const
        {
            boost::format filename("%s%d%s");
            filename % this->m_file_prefix
                     % index
                     % this->m_file_suffix;

            std::filesystem::path path(this->m_file_path);
            path /= filename.str();

            return path.string();
        }

        void FileLogger::log_event(const util::logger::LogEntryCPtr& param)
        {
            // Prepare the log message
            std::string message;
            {
                boost::format logMsg("[%s][%s] %s: %s (%s:%u)\n");
                logMsg  % core::util::time::to_string(param->get_timestamp())
                        % logger_level_map(param->get_level())
                        % param->get_domain()
                        % param->get_message()
                        % param->get_filename()
                        % param->get_line();

                message = logMsg.str();
            }

            // Trim the message if it exceeds the maximum log file size
            if ((message.length() > (this->m_max_file_size_b)) and (this->m_max_file_size_b > 0))
            {
                message = message.substr(0, this->m_max_file_size_b);
            }

            // If the file exists and is full
            if (std::filesystem::exists(m_current_file) and
                (not ((std::filesystem::file_size(m_current_file) + message.length())
                            <= (m_max_file_size_b)) or (m_max_file_size_b == 0)))
            {
                // Ensure that the directory exists. Maybe the user removed it.
                std::filesystem::create_directories(this->m_file_path);

                this->m_current_index++;

                if (this->m_max_nbr_of_files > 0)
                {
                   uint32_t oldestIndex = this->m_current_index - this->m_max_nbr_of_files;

                   // Remove the oldest file
                   std::filesystem::remove(get_file_path(oldestIndex));
                }

                // Make sure the current file is removed so that
                // the next message is written in an empty file
                m_current_file = get_file_path(this->m_current_index);
                std::filesystem::remove(m_current_file);
            }

            // Commit the changes to the disk
            std::ofstream file;
            file.open(m_current_file, std::ios_base::app);
            file << message;
            file.close();
        }

        void FileLogger::initialize_fs()
        {
            // Create the log path if it does not exist
            std::filesystem::create_directories(m_file_path);

            std::vector<uint32_t> indexes;

            // Get list of available log indexes
            {
                std::filesystem::path path(this->m_file_path);

                // Check all the existing files in the current path
                if (std::filesystem::exists(path))
                {
                    std::regex pattern(
                        "^" + this->m_file_prefix + "([0-9]*)" + this->m_file_suffix + "$");

                    for (const auto &entry : std::filesystem::directory_iterator(path))
                    {
                        if (std::filesystem::is_regular_file(entry))
                        {
                            std::string fileName = entry.path().filename().string();
                            std::smatch match;

                            if (std::regex_search(fileName, match, pattern))
                            {
                                uint32_t index = std::stoul(match[1]);
                                indexes.push_back(index);
                            }
                        }
                    }
                }

                std::sort(indexes.begin(), indexes.end());
            }

            if (not indexes.empty())
            {
                // If there is a gap larger than m_max_nr_of_files,
                // we consider that we have found the latest file
                uint32_t i;
                for (i = 0; i < indexes.size() - 1; i++)
                {
                    if ((indexes.at(i + 1) - indexes.at(i)) >= (this->m_max_nbr_of_files))
                    {
                        break;
                    }
                }

                m_current_index = i;
                m_current_file = get_file_path(this->m_current_index);

                // Remove old logs
                {
                    uint32_t maxIndex = m_current_index;
                    uint32_t minIndex = m_current_index - m_max_nbr_of_files + 1;

                    // We consider that there was an overflow
                    if (minIndex > maxIndex)
                    {
                        for (uint32_t index : indexes)
                        {
                            if ((index < minIndex) and (index > maxIndex))
                            {
                                std::filesystem::remove(get_file_path(index));
                            }
                        }
                    }
                    else
                    {
                        for (uint32_t index : indexes)
                        {
                            if ((index < minIndex) or (index > maxIndex))
                            {
                                std::filesystem::remove(get_file_path(index));
                            }
                        }
                    }
                }
            }
        }

        FileLogger::~FileLogger()
        {
        }
    }
}

max_stars_repo_name: nicsor/BreadCrumbs

max_issues_repo_name: nicsor/BreadCrumbs

max_forks_repo_name: nicsor/BreadCrumbs


text:
// Copyright (c) 2018-2019 The Llamacoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <key.h>

#include <uint256.h>
#include <test/util/setup_common.h>
#include <vector>

#include <boost/test/unit_test.hpp>
#include <rapidcheck/boost_test.h>
#include <rapidcheck/gen/Arbitrary.h>
#include <rapidcheck/Gen.h>

#include <test/gen/crypto_gen.h>

BOOST_FIXTURE_TEST_SUITE(key_properties, BasicTestingSetup)

/** Check CKey uniqueness */
RC_BOOST_PROP(key_uniqueness, (const CKey& key1, const CKey& key2))
{
    RC_ASSERT(!(key1 == key2));
}

/** Verify that a private key generates the correct public key */
RC_BOOST_PROP(key_generates_correct_pubkey, (const CKey& key))
{
    CPubKey pubKey = key.GetPubKey();
    RC_ASSERT(key.VerifyPubKey(pubKey));
}

/** Create a CKey using the 'Set' function must give us the same key */
RC_BOOST_PROP(key_set_symmetry, (const CKey& key))
{
    CKey key1;
    key1.Set(key.begin(), key.end(), key.IsCompressed());
    RC_ASSERT(key1 == key);
}

/** Create a CKey, sign a piece of data, then verify it with the public key */
RC_BOOST_PROP(key_sign_symmetry, (const CKey& key, const uint256& hash))
{
    std::vector<unsigned char> vchSig;
    key.Sign(hash, vchSig, 0);
    const CPubKey& pubKey = key.GetPubKey();
    RC_ASSERT(pubKey.Verify(hash, vchSig));
}
BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: LlamaCoinCore/LlamaCoin

max_issues_repo_name: LlamaCoinCore/LlamaCoin

max_forks_repo_name: LlamaCoinCore/LlamaCoin


text:
#include "log_entries.h"

#include "../include/remote/rpc_client.h"

#include <boost/asio.hpp>
#include <future>
#include <iostream>
#include <string>
#include <thread>
#include <tuple>

int main() {
    try {
        boost::asio::io_service io_service;
        boost::asio::io_service::work work{io_service};
        std::thread t{[&io_service](){io_service.run();}};

        remote::rpc_client c{io_service, "127.0.0.1", 12345};

        std::mutex mutex;

        remote::rpc_future<int, std::string> foo_result = c.async_call<int, std::string>("foo", 123);
        auto t1 = foo_result.then([&mutex](std::future<std::tuple<int, std::string>>& res) {
            try {
                std::lock_guard<std::mutex> lock{mutex};
                const auto tuple = res.get();
                std::cout << "Result: " << std::get<0>(tuple) << ", " << std::get<1>(tuple) << std::endl;
            } catch (const std::exception& ex) {
                std::cout << "Failure: " << ex.what() << std::endl;
            }
        });

        std::getchar();

        try {
            remote::rpc_future<double> sin_result = c.async_call<double>("sin", 3.14);
            auto t2 = sin_result.then([&mutex](std::future<std::tuple<double>>& res) {
                try {
                    std::lock_guard<std::mutex> lock{mutex};
                    const auto tuple = res.get();
                    std::cout << "Result: " << std::get<0>(tuple) << std::endl;
                } catch (const std::exception& ex) {
                    std::cout << "Failure: " << ex.what() << std::endl;
                }
            });
        } catch (const std::exception& ex) {
            std::cout << ex.what() << std::endl;
        }

        remote::rpc_future<std::string> complex_result = c.async_call<std::string>("complex", std::vector<int>{1, 2, 3});
        auto t3 = complex_result.then([&mutex](std::future<std::tuple<std::string>>& res) {
            try {
                std::lock_guard<std::mutex> lock{mutex};
                const auto tuple = res.get();
                std::cout << "Result: " << std::get<0>(tuple) << std::endl;
            } catch (const std::exception& ex) {
                std::cout << "Failure: " << ex.what() << std::endl;
            }
        });

        uint32_t term = 123;
        uint32_t leader_id = 321;
        uint32_t prev_log_index = 1;
        uint32_t prev_log_term = 2;
        log_entry_vector entries;
        log_entry entry1;
        log_entry entry2;
        entries.push_back(entry1);
        entries.push_back(entry2);
        uint32_t leader_commit = 1;

        remote::rpc_future<uint32_t, bool> append_entries_result = c.async_call<uint32_t, bool>(
            "AppendEntries", term, leader_id, prev_log_index, prev_log_term, entries, leader_commit);
        auto t4 = append_entries_result.then([&mutex](std::future<std::tuple<uint32_t, bool>>& res) {
            try {
                std::lock_guard<std::mutex> lock{mutex};
                const auto tuple = res.get();
                std::cout << "Result: " << std::get<0>(tuple) << ", " << std::get<1>(tuple) << std::endl;
            } catch (const std::exception& ex) {
                std::cout << "Failure: " << ex.what() << std::endl;
            }
        });

        t.join();

    } catch (const std::exception& ex) {
        std::cout << ex.what() << std::endl;
    }

    return 0;
}

max_stars_repo_name: polaris/remote

max_issues_repo_name: polaris/remote

max_forks_repo_name: polaris/remote