text:
/* $Id: visitor.cpp 49173 2011-04-10 16:48:33Z mordante $ */
/*
   Copyright (C) 2011 by Mark de Wever <koraq@xs4all.nl>
   Part of the Battle for Wesnoth Project http://www.wesnoth.org/

   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; either version 2 of the License, or
   (at your option) any later version.
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY.

   See the COPYING file for more details.
*/

#define GETTEXT_DOMAIN "wesnoth-lib"

#include <boost/test/unit_test.hpp>

#include "config_cache.hpp"
#include "gui/auxiliary/iterator/walker.hpp"
#include "gui/widgets/label.hpp"
#include "gui/widgets/grid.hpp"

#include <iostream>
#include <typeinfo>

static void add_widget(gui2::tgrid& grid
		, gui2::twidget* widget
		, const std::string& id
		, const unsigned row
		, const unsigned column)
{
	BOOST_REQUIRE_NE(widget, (gui2::twidget*)NULL);

	widget->set_id(id);
	grid.set_child(widget
			, row
			, column
			, gui2::tgrid::VERTICAL_GROW_SEND_TO_CLIENT
				| gui2::tgrid::HORIZONTAL_GROW_SEND_TO_CLIENT
			, 0);
}

template<class T>
static void test_control()
{
	std::cerr << __func__ << ": " << typeid(T).name() << ".\n";

	T control;
	std::auto_ptr<gui2::iterator::twalker_> visitor(control.create_walker());

	BOOST_REQUIRE_NE(visitor.get(), (void*)NULL);

	/***** INITIAL STATE *****/

	BOOST_CHECK_EQUAL(visitor->at_end(gui2::iterator::twalker_::widget), false);
	BOOST_CHECK_EQUAL(visitor->at_end(gui2::iterator::twalker_::grid), true);
	BOOST_CHECK_EQUAL(visitor->at_end(gui2::iterator::twalker_::child), true);

	BOOST_CHECK_EQUAL(visitor->get(gui2::iterator::twalker_::widget), &control);
	BOOST_CHECK_EQUAL(visitor->get(gui2::iterator::twalker_::grid), (void*)NULL);
	BOOST_CHECK_EQUAL(visitor->get(gui2::iterator::twalker_::child), (void*)NULL);

	/***** VISITING WIDGET *****/

	BOOST_CHECK_EQUAL(visitor->next(gui2::iterator::twalker_::widget), gui2::iterator::twalker_::invalid);
	BOOST_CHECK_EQUAL(visitor->next(gui2::iterator::twalker_::grid), gui2::iterator::twalker_::fail);
	BOOST_CHECK_EQUAL(visitor->next(gui2::iterator::twalker_::child), gui2::iterator::twalker_::fail);

	BOOST_CHECK_EQUAL(visitor->at_end(gui2::iterator::twalker_::widget), true);
	BOOST_CHECK_EQUAL(visitor->at_end(gui2::iterator::twalker_::grid), true);
	BOOST_CHECK_EQUAL(visitor->at_end(gui2::iterator::twalker_::child), true);

	BOOST_CHECK_EQUAL(visitor->get(gui2::iterator::twalker_::widget), (void*)NULL);
	BOOST_CHECK_EQUAL(visitor->get(gui2::iterator::twalker_::grid), (void*)NULL);
	BOOST_CHECK_EQUAL(visitor->get(gui2::iterator::twalker_::child), (void*)NULL);

	/***** POST END *****/

	BOOST_CHECK_EQUAL(visitor->next(gui2::iterator::twalker_::widget), gui2::iterator::twalker_::fail);
}

static void test_control()
{
	/* Could add more widgets to the list. */
	test_control<gui2::tlabel>();

}

static void test_grid()
{
	/* An empty grid behaves the same as a control so test here. */
	test_control<gui2::tgrid>();

	std::cerr << __func__ << ": Detailed test.\n";

	/* Test the child part here. */
	gui2::tgrid grid(2 ,2);
	add_widget(grid, new gui2::tlabel(), "(1,1)", 0, 0);
	add_widget(grid, new gui2::tlabel(), "(1,2)", 0, 1);
	add_widget(grid, new gui2::tlabel(), "(2,1)", 1, 0);
	add_widget(grid, new gui2::tlabel(), "(2,2)", 1, 1);

	std::auto_ptr<gui2::iterator::twalker_> visitor(grid.create_walker());

	/***** LABEL 1,1 *****/

	BOOST_CHECK_EQUAL(visitor->at_end(gui2::iterator::twalker_::child), false);

	BOOST_REQUIRE_NE(visitor->get(gui2::iterator::twalker_::child), (void*)NULL);
	BOOST_CHECK_EQUAL(visitor->get(gui2::iterator::twalker_::child)->id(), "(1,1)");

	/***** LABEL 2,1 *****/

	BOOST_CHECK_EQUAL(visitor->next(gui2::iterator::twalker_::child), gui2::iterator::twalker_::valid);

	BOOST_CHECK_EQUAL(visitor->at_end(gui2::iterator::twalker_::child), false);

	BOOST_REQUIRE_NE(visitor->get(gui2::iterator::twalker_::child), (void*)NULL);
	BOOST_CHECK_EQUAL(visitor->get(gui2::iterator::twalker_::child)->id(), "(2,1)");

	/***** LABEL 1,2 *****/

	BOOST_CHECK_EQUAL(visitor->next(gui2::iterator::twalker_::child), gui2::iterator::twalker_::valid);

	BOOST_CHECK_EQUAL(visitor->at_end(gui2::iterator::twalker_::child), false);

	BOOST_REQUIRE_NE(visitor->get(gui2::iterator::twalker_::child), (void*)NULL);
	BOOST_CHECK_EQUAL(visitor->get(gui2::iterator::twalker_::child)->id(), "(1,2)");

	/***** LABEL 2,2 *****/

	BOOST_CHECK_EQUAL(visitor->next(gui2::iterator::twalker_::child), gui2::iterator::twalker_::valid);

	BOOST_CHECK_EQUAL(visitor->at_end(gui2::iterator::twalker_::child), false);

	BOOST_REQUIRE_NE(visitor->get(gui2::iterator::twalker_::child), (void*)NULL);
	BOOST_CHECK_EQUAL(visitor->get(gui2::iterator::twalker_::child)->id(), "(2,2)");

	/***** END *****/

	BOOST_CHECK_EQUAL(visitor->next(gui2::iterator::twalker_::child), gui2::iterator::twalker_::invalid);

	BOOST_CHECK_EQUAL(visitor->at_end(gui2::iterator::twalker_::child), true);

	BOOST_CHECK_EQUAL(visitor->get(gui2::iterator::twalker_::child), (void*)NULL);

	/***** POST END *****/

	BOOST_CHECK_EQUAL(visitor->next(gui2::iterator::twalker_::child), gui2::iterator::twalker_::fail);
}

BOOST_AUTO_TEST_CASE(test_gui2_visitor)
{

	/**** Initialize the environment. *****/
	game_config::config_cache& cache = game_config::config_cache::instance();

	cache.clear_defines();
	cache.add_define("EDITOR");
	cache.add_define("MULTIPLAYER");

	test_control();
	test_grid();
}

ext: cpp

max_stars_repo_name: blackberry/Wesnoth

max_issues_repo_name: blackberry/Wesnoth

max_forks_repo_name: blackberry/Wesnoth


text:
#ifndef HTTP_CONNECTION_HPP_
#define HTTP_CONNECTION_HPP_

#include <openssl/opensslconf.h>
#ifdef OPENSSL_NO_SSL2
#include <openssl/ssl.h>
inline const SSL_METHOD *SSLv2_method() { return NULL; }
inline const SSL_METHOD *SSLv2_server_method() { return NULL; }
inline const SSL_METHOD *SSLv2_client_method() { return NULL; }
#endif
#include <boost/scoped_ptr.hpp>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/noncopyable.hpp>

NAMESPACE_CIRCLE_BEGIN
namespace httpc {
	struct socket_stream_wrapper: boost::noncopyable {
		typedef asio::mutable_buffers_1 mutable_buffer;
		typedef asio::const_buffers_1 const_buffer;
		typedef asio::io_service io_service;
		typedef function<void (const error_code &)> ConnectHandler;
		typedef function<void (const error_code &)> HandshakeHandler;
		typedef function<void (const error_code &, size_t)> ReadHandler;
		typedef function<void (const error_code &)> ShutdownHandler;
		typedef function<void (const error_code &, size_t)> WriteHandler;
		typedef asio::ip::tcp::socket::lowest_layer_type lowest_layer_type;
		typedef asio::ip::tcp::endpoint endpoint_type;
		typedef asio::ip::tcp::socket tcp_stream_type;
		typedef tcp_stream_type::shutdown_type shutdown_type;
		typedef asio::ssl::stream<asio::ip::tcp::socket> ssl_stream_type;
		typedef ssl_stream_type::handshake_type handshake_type;

		void async_connect(const endpoint_type &peer_endpoint, ConnectHandler handler) { do_async_connect(peer_endpoint, handler); }
		void async_handshake(HandshakeHandler handler) { do_async_handshake(ssl_stream_type::client, handler); }
		void async_handshake(handshake_type type, HandshakeHandler handler) { do_async_handshake(type, handler); }
		void async_read_some(const mutable_buffer &buffers, ReadHandler handler) { do_async_read_some(buffers, handler); }
		void async_shutdown(ShutdownHandler handler) { do_async_shutdown(handler); }
		void async_write_some(const const_buffer &buffers, WriteHandler handler) { do_async_write_some(buffers, handler); }
		void close() { lowest_layer().close(); }
		error_code close(error_code &ec) { return lowest_layer().close(ec); }
		void connect(const endpoint_type &peer_endpoint) { do_connect(peer_endpoint); }
		error_code connect(const endpoint_type &peer_endpoint, error_code &ec) { return do_connect(peer_endpoint, ec); }
		io_service &get_io_service() { return do_get_io_service(); }
		void handshake() { do_handshake(ssl_stream_type::client); };
		void handshake(handshake_type type) { do_handshake(type); }
		error_code handshake(error_code &ec) { return do_handshake(ssl_stream_type::client, ec); }
		error_code handshake(handshake_type type, error_code &ec) { return do_handshake(type, ec); }
		bool is_open() const { return const_cast<socket_stream_wrapper *>(this)->lowest_layer().is_open(); }
		endpoint_type local_endpoint() const { return lowest_layer().local_endpoint(); }
		endpoint_type local_endpoint(error_code &ec) const { return lowest_layer().local_endpoint(ec); }
		lowest_layer_type &lowest_layer()  { return do_lowest_layer(); }
		const lowest_layer_type &lowest_layer() const { return do_lowest_layer(); }
		size_t read_some(const mutable_buffer &buffers) { return do_read_some(buffers); }
		size_t read_some(const mutable_buffer &buffers, error_code &ec) { return do_read_some(buffers, ec); }
		endpoint_type remote_endpoint() { return lowest_layer().remote_endpoint(); }
		endpoint_type remote_endpoint(error_code &ec) { return lowest_layer().remote_endpoint(); }
		void shutdown() { do_shutdown(tcp_stream_type::shutdown_both); }
		void shutdown(shutdown_type what) { do_shutdown(what); }
		error_code shutdown(error_code &ec) { return do_shutdown(tcp_stream_type::shutdown_both, ec); }
		error_code shutdown(shutdown_type what, error_code &ec) { return do_shutdown(what, ec); }
		size_t write_some(const const_buffer &buffers) { return do_write_some(buffers); }
		size_t write_some(const const_buffer &buffers, error_code &ec) { return do_write_some(buffers); }
		virtual ~socket_stream_wrapper() { }
	private:
		virtual void do_async_connect(const endpoint_type &peer_endpoint, ConnectHandler handler) = 0;
		virtual void do_async_handshake(handshake_type type, HandshakeHandler handler) = 0;
		virtual void do_async_read_some(const mutable_buffer &buffers, ReadHandler handler) = 0;
		virtual void do_async_shutdown(ShutdownHandler handler) = 0;
		virtual void do_async_write_some(const const_buffer &buffers, WriteHandler handler) = 0;
		virtual void do_connect(const endpoint_type &peer_endpoint) = 0;
		virtual error_code do_connect(const endpoint_type &peer_endpoint, error_code &ec) = 0;
		virtual io_service &do_get_io_service() = 0;
		virtual void do_handshake(handshake_type type) = 0;
		virtual error_code do_handshake(handshake_type type, error_code &ec) = 0;
		virtual lowest_layer_type &do_lowest_layer() = 0;
		virtual const lowest_layer_type &do_lowest_layer() const = 0;
		virtual size_t do_read_some(const mutable_buffer &buffers) = 0;
		virtual size_t do_read_some(const mutable_buffer &buffers, error_code &ec) = 0;
		virtual void do_shutdown(shutdown_type what) = 0;
		virtual error_code do_shutdown(shutdown_type what, error_code &ec) = 0;
		virtual size_t do_write_some(const const_buffer &buffers) = 0;
		virtual size_t do_write_some(const const_buffer &buffers, error_code &ec) = 0;
	};
	template <typename Socket>
	struct basic_socket_stream_wrapper: socket_stream_wrapper {
		typedef Socket socket_type;
		socket_type socket;
		template <typename Arg1>
		basic_socket_stream_wrapper(Arg1 &arg1): socket(arg1) { }
		template <typename Arg1, typename Arg2>
		basic_socket_stream_wrapper(Arg1 &arg1, Arg2 &arg2): socket(arg1, arg2) { }
		void do_async_read_some(const mutable_buffer &buffers, ReadHandler handler) { socket.async_read_some(buffers, handler); }
		void do_async_write_some(const const_buffer &buffers, WriteHandler handler) { socket.async_write_some(buffers, handler); }
		io_service &do_get_io_service() { return socket.get_io_service(); }
		lowest_layer_type &do_lowest_layer() { return socket.lowest_layer(); }
		const lowest_layer_type &do_lowest_layer() const { return socket.lowest_layer(); }
		size_t do_read_some(const mutable_buffer &buffers) { return socket.read_some(buffers); }
		size_t do_read_some(const mutable_buffer &buffers, error_code &ec) { return socket.read_some(buffers, ec); }
		size_t do_write_some(const const_buffer &buffers) { return socket.write_some(buffers); }
		size_t do_write_some(const const_buffer &buffers, error_code &ec) { return socket.write_some(buffers, ec); }
	};
	struct tcp_socket_stream: basic_socket_stream_wrapper<asio::ip::tcp::socket> {
		typedef basic_socket_stream_wrapper<asio::ip::tcp::socket> base_type;
		tcp_socket_stream(io_service &service): base_type(service) { }
		void do_async_connect(const endpoint_type &peer_endpoint, ConnectHandler handler) { lowest_layer().async_connect(peer_endpoint, handler); }
		void do_async_handshake(handshake_type, HandshakeHandler handler) { get_io_service().post(bind(handler, error_code())); }
		void do_async_shutdown(ShutdownHandler handler) {
			error_code ec;
			socket.shutdown(asio::ip::tcp::socket::shutdown_both, ec);
			get_io_service().post(bind(handler, ec));
		}
		void do_connect(const endpoint_type &peer_endpoint) { lowest_layer().connect(peer_endpoint); }
		error_code do_connect(const endpoint_type &peer_endpoint, error_code &ec) { return lowest_layer().connect(peer_endpoint, ec); }
		void do_handshake(handshake_type) { }
		error_code do_handshake(handshake_type, error_code &ec) { return ec = error_code(); }
		void do_shutdown() { socket.shutdown(asio::ip::tcp::socket::shutdown_both); }
		void do_shutdown(shutdown_type what) { socket.shutdown(what); }
		error_code do_shutdown(shutdown_type what, error_code &ec) { return socket.shutdown(what, ec); }
	};
	struct ssl_socket_stream: basic_socket_stream_wrapper<asio::ssl::stream<asio::ip::tcp::socket> > {
		typedef basic_socket_stream_wrapper<asio::ssl::stream<asio::ip::tcp::socket> > base_type;
		ssl_socket_stream(io_service &service, asio::ssl::context &ctx): base_type(service, ctx) { }
		void do_async_connect(const endpoint_type &peer_endpoint, ConnectHandler handler) { lowest_layer().async_connect(peer_endpoint, handler); }
		void do_async_handshake(handshake_type type, ConnectHandler handler) { socket.async_handshake(type, handler); }
		void do_async_shutdown(ShutdownHandler handler) { socket.async_shutdown(handler); }
		void do_connect(const endpoint_type &peer_endpoint) { lowest_layer().connect(peer_endpoint); }
		error_code do_connect(const endpoint_type &peer_endpoint, error_code &ec) { return lowest_layer().connect(peer_endpoint, ec); }
		void do_handshake(handshake_type type) { socket.handshake(type); }
		error_code do_handshake(handshake_type type, error_code &ec) { return socket.handshake(type, ec); }
		void do_shutdown(shutdown_type) { socket.shutdown(); }
		error_code do_shutdown(shutdown_type, error_code &ec) { return socket.shutdown(ec); }
	};

	class connection: boost::noncopyable {
	public:
		typedef socket_stream_wrapper stream_type;
		typedef stream_type::endpoint_type endpoint_type;
	public:
		connection(asio::io_service &serv, const endpoint_type &ep): ctx(), pstream(new tcp_socket_stream(serv)) {
			pstream->connect(ep);
		}
		connection(asio::io_service &serv, const endpoint_type &ep, asio::ssl::context &ctx): ctx(&ctx), pstream(new ssl_socket_stream(serv, ctx)) {
			pstream->connect(ep);
			pstream->handshake();
		}
		~connection() try {
			error_code ec;
			pstream->lowest_layer().cancel(ec);
			pstream->close(ec);
		} catch (...) {
		}
		stream_type &get_stream() { return *pstream; }
		const stream_type &get_stream() const { return *pstream; }
		asio::ssl::context *get_context_ptr() const { return ctx; }
	private:
		asio::ssl::context *ctx;
		boost::scoped_ptr<stream_type> pstream;
	};
}
NAMESPACE_CIRCLE_END

#endif

ext: hpp


text:
/*Copyright (c) 2014 The Paradox Game Converters Project

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/

#include "EU3Localisation.h"
#include <fstream>
#include <vector>
#include <boost/tokenizer.hpp>
#include <iterator>
using namespace std;
using namespace boost;

#include <filesystem>
namespace fs = std::filesystem;
#include <set>

enum
{
	CODE,
	ENGLISH,
	FRENCH,
	GERMAN,
	POLSKI,
	SPANISH,
	ITALIAN,
	SWEDISH,
	CZECH,
	HUNGARIAN,
	DUTCH,
	PORTUGESE,
	RUSSIAN,
	FINNISH,
	x
} languages;

void EU3Localisation::ReadFromFile(const std::string& fileName)
{
	std::ifstream in(fileName);

	const int maxLineLength = 10000;	// the maximum line length
	char lineArray[maxLineLength];			// the line being processed
	string line;

	// Subsequent lines are 'KEY: "Text"'
	while (!in.eof())
	{
		in.getline(lineArray, maxLineLength);
		line = lineArray;
		if (!in.eof())
		{
			string key;
			string currentLocalisation;

			char_separator<char> separator(";");
			tokenizer<char_separator<char>> tokens(line, separator);
			int language = CODE;
			for (auto tItr = tokens.begin(); tItr != tokens.end(); ++tItr)
			{
				if (distance(tokens.begin(), tItr) == 0)
				{
					key = *tItr;
				}
				else
				{
					currentLocalisation = *tItr;
					localisations[key][language] = currentLocalisation;
				}
				language++;
			}
		}
	}
}

void EU3Localisation::ReadFromAllFilesInFolder(const std::string& folderPath)
{
	// Get all files in the folder.
	set<std::string> fileNames;
	if (!fs::exists(fs::u8path(folderPath))) return;
	if (fs::is_empty(fs::u8path(folderPath))) return;
	for (auto& p : fs::directory_iterator(fs::u8path(folderPath)))
	{
		if (!p.is_directory())
		{
			fileNames.insert(p.path().filename().string());
		}

	}
	for (const auto& fileName : fileNames)
	{
		ReadFromFile(folderPath + '\\' + fileName);
	}
}

const std::string& EU3Localisation::GetText(const std::string& key, unsigned int language) const
{
	static const std::string noLocalisation = "";	// used if there's no localisation

	const auto keyFindIter = localisations.find(key);	// the localisations for this key
	if (keyFindIter == localisations.end())
	{
		return noLocalisation;
	}
	const auto& localisationsByLanguage = keyFindIter->second;	// the localisations for this language
	const auto languageFindIter = localisationsByLanguage.find(language);	// the localisation we want
	if (languageFindIter == localisationsByLanguage.end())
	{
		return noLocalisation;
	}

	return languageFindIter->second;
}

const std::map<unsigned int, std::string>& EU3Localisation::GetTextInEachLanguage(const std::string& key) const
{
	static const std::map<unsigned int, std::string> noLocalisation;	// used if there's no localisation

	const auto keyFindIter = localisations.find(key);	// the localisation we want
	if (keyFindIter == localisations.end())
	{
		return noLocalisation;
	}

	return keyFindIter->second;
}

std::string EU3Localisation::DetermineLanguageForFile(const std::string& text)
{
	static const std::string noLanguageIndicated = "";	// used when no language is indicated

	if (text.size() < 2 || text[0] != 'l' || text[1] != '_')
	{	// Not in the desired format - no "l_"
		return noLanguageIndicated;
	}
	size_t beginPos = 2;	// Skip l_ for our language name.
	size_t endPos = text.find(':', beginPos);	// the end of the language name
	if (endPos == std::string::npos)
	{	// Not in the desired format - no ":"
		return noLanguageIndicated;
	}

	return text.substr(beginPos, endPos - beginPos);
}

std::pair<std::string, std::string> EU3Localisation::DetermineKeyLocalisationPair(const std::string& text)
{
	static const std::pair<std::string, std::string> noLocalisationPair;	// used when there's no localisation pair

	size_t keyBeginPos = text.find_first_not_of(' ');	// the first non-space character
	if (keyBeginPos == std::string::npos)
	{
		return noLocalisationPair;
	}
	size_t keyEndPos = text.find_first_of(':', keyBeginPos + 1);	// the end of the key
	size_t quotePos = text.find_first_of('"', keyEndPos);				// the begining of the string literal
	if (quotePos == std::string::npos)
	{
		return noLocalisationPair;
	}
	size_t localisationBeginPos = quotePos + 1;	// where the localisation begins
	size_t localisationEndPos = text.find_first_of('"', localisationBeginPos);	// where the localisation ends
	return std::make_pair(text.substr(keyBeginPos, keyEndPos - keyBeginPos), text.substr(localisationBeginPos, localisationEndPos - localisationBeginPos));
}

std::string EU3Localisation::RemoveUTF8BOM(const std::string& text)
{
	if (text.size() >= 3 && text[0] == '\xEF' && text[1] == '\xBB' && text[2] == '\xBF')
	{
		return text.substr(3);
	}
	else
	{
		return text;
	}
}


text:
/* Copyright 2019, LAAS-CNRS
 *
 * Olivier Stasse
 *
 */
#include <sstream>
#include <iostream>
#include <dynamic-graph/entity.h>
#include <dynamic-graph/exception-factory.h>
#include "dynamic-graph/factory.h"
#include "dynamic-graph/pool.h"

#define VP_DEBUG 1
#define VP_DEBUG_MODE 50
#define VP_TEMPLATE_DEBUG_MODE 50

#include <dynamic-graph/debug.h>

#define BOOST_TEST_MODULE debug-trace

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

using boost::test_tools::output_test_stream;

namespace dynamicgraph
{
  class CustomEntity : public Entity
  {
  public:
    static const std::string CLASS_NAME;
    virtual const std::string& getClassName () const
    {
      return CLASS_NAME;
    }
    CustomEntity (const std::string n)
      : Entity (n)
    {
      dynamicgraph::dgDEBUGFLOW.openFile("/tmp/dynamic-graph-traces.txt");
    }
    ~CustomEntity()
    {
      dynamicgraph::dgDEBUGFLOW.closeFile("/tmp/dynamic-graph-traces.txt");
    }
    void testDebugTrace()
    {
      /// Test debugging information when entering the code.
      dgDEBUGIN(5);

      /// Intermediate test.
      dgDEBUGINOUT(5);

      dgDEBUG(5) << "Here is a test" << std::endl;

      /// Test debugging information when going out of the code.
      dgDEBUGOUT(5);
    }
  };
  DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN (CustomEntity,"CustomEntity");
}

BOOST_AUTO_TEST_CASE(testDebugTrace)
{

  BOOST_CHECK_EQUAL (dynamicgraph::CustomEntity::CLASS_NAME, "CustomEntity");

  dynamicgraph::CustomEntity& entity = *(dynamic_cast<dynamicgraph::CustomEntity *>(
    dynamicgraph::FactoryStorage::getInstance()->newEntity("CustomEntity",
							   "my-entity")));
  entity.testDebugTrace();

  /// Copy the debug file into the oss_debug_file
  output_test_stream output;
  std::fstream the_debug_file;
  the_debug_file.open(dynamicgraph::DebugTrace::DEBUG_FILENAME_DEFAULT,
		      std::ios::in );

  // Extract the filename and this source file from the output
  std::string astr;
  std::ostringstream oss_debug_file;
  while(std::getline(the_debug_file,astr))
    {
      std::size_t found=astr.find(":");
      std::string asubstr = astr.substr(found+1,astr.length());
      found = asubstr.find(":");
      std::string asubstr2 = asubstr.substr(found+1,astr.length());
      oss_debug_file << asubstr2;
    }

  the_debug_file.close();

  // Compare with the strings put inside this source file
  std::string str_to_test =  "# In {"
    "# In/Out { }"
    "Here is a test"
    "# Out }";
  bool two_sub_string_identical;

  // Make comparisons.
  two_sub_string_identical = str_to_test == oss_debug_file.str();

  BOOST_CHECK(two_sub_string_identical);

}

max_stars_repo_name: corentinberge/dynamic-graph

max_issues_repo_name: corentinberge/dynamic-graph

max_forks_repo_name: corentinberge/dynamic-graph


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

#include "wallet/wallet_db.h"
#include <assert.h>
#include "test_helpers.h"
#include "utility/test_helpers.h"

#include "utility/logger.h"
#include <boost/filesystem.hpp>
#include <numeric>

using namespace std;
using namespace ECC;
using namespace beam;

WALLET_TEST_INIT

namespace
{
    IKeyChain::Ptr createSqliteKeychain()
    {
        const char* dbName = "wallet.db";
        if (boost::filesystem::exists(dbName))
        {
            boost::filesystem::remove(dbName);
        }
        ECC::NoLeak<ECC::uintBig> seed;
        seed.V = Zero;
        auto keychain = Keychain::init(dbName, string("pass123"), seed);
        beam::Block::SystemState::ID id = { };
        id.m_Height = 134;
        keychain->setSystemStateID(id);
        return keychain;
    }
}

void TestKeychain()
{
	auto keychain = createSqliteKeychain();

	Coin coin1(5, Coin::Unspent, 0, 10);
	keychain->store(coin1);

    WALLET_CHECK(coin1.m_id == 1);

	Coin coin2(2, Coin::Unspent, 0, 10);
	keychain->store(coin2);

    WALLET_CHECK(coin2.m_id == 2);

    {
	    auto coins = keychain->selectCoins(7);
        WALLET_CHECK(coins.size() == 2);

		vector<Coin> localCoins;
		localCoins.push_back(coin2);
		localCoins.push_back(coin1);

		for (size_t i = 0; i < coins.size(); ++i)
		{
            WALLET_CHECK(localCoins[i].m_id == coins[i].m_id);
            WALLET_CHECK(localCoins[i].m_amount == coins[i].m_amount);
            WALLET_CHECK(coins[i].m_status == Coin::Locked);
		}
	}

	{
		coin2.m_status = Coin::Spent;

		keychain->update(coin2);

        WALLET_CHECK(keychain->selectCoins(5).size() == 0);
	}

	{
		Block::SystemState::ID a;
		Hash::Processor() << static_cast<uint32_t>(rand()) >> a.m_Hash;
		a.m_Height = rand();

		const char* name = "SystemStateID";
		keychain->setVar(name, "dummy");
		keychain->setVar(name, a);

		Block::SystemState::ID b;
        WALLET_CHECK(keychain->getVar(name, b));

		WALLET_CHECK(a == b);
	}
}

void TestStoreCoins()
{
    auto keychain = createSqliteKeychain();

    Coin coin = { 5, Coin::Unspent, 1, 10, KeyType::Coinbase };
    keychain->store(coin);
    coin = { 4, Coin::Unspent, 1, 10, KeyType::Comission };
    keychain->store(coin);
    coin = { 2, Coin::Unspent, 1, 10, KeyType::Regular };
    keychain->store(coin);
    coin = { 5, Coin::Unspent, 1, 10, KeyType::Coinbase };
    keychain->store(coin);
    coin = { 1, Coin::Unspent, 1, 10, KeyType::Regular };
    keychain->store(coin);
    coin = { 5, Coin::Unspent, 1, 10, KeyType::Coinbase };
    keychain->store(coin);
    coin = { 4, Coin::Unspent, 1, 10, KeyType::Comission };
    keychain->store(coin);
    coin = { 1, Coin::Unspent, 1, 10, KeyType::Regular };
    keychain->store(coin);
    coin = { 4, Coin::Unspent, 1, 10, KeyType::Comission };
    keychain->store(coin);
    coin = { 1, Coin::Unspent, 1, 10, KeyType::Regular };
    keychain->store(coin);
    coin = { 1, Coin::Unspent, 1, 10, KeyType::Regular };
    keychain->store(coin);

    auto coins = vector<Coin>{
            Coin{ 5, Coin::Unspent, 1, 10, KeyType::Coinbase },
            Coin{ 4, Coin::Unspent, 1, 10, KeyType::Comission },
            Coin{ 2, Coin::Unspent, 1, 10, KeyType::Regular },
            Coin{ 5, Coin::Unspent, 3, 10, KeyType::Coinbase },
            Coin{ 1, Coin::Unspent, 1, 10, KeyType::Regular },
            Coin{ 5, Coin::Unspent, 1, 10, KeyType::Coinbase },
            Coin{ 4, Coin::Unspent, 1, 10, KeyType::Comission },
            Coin{ 1, Coin::Unspent, 1, 10, KeyType::Regular },
            Coin{ 4, Coin::Unspent, 3, 10, KeyType::Comission },
            Coin{ 1, Coin::Unspent, 1, 10, KeyType::Regular },
            Coin{ 1, Coin::Unspent, 1, 10, KeyType::Regular } };
    keychain->store(coins);

    int coinBase = 0;
    int comission = 0;
    int regular = 0;
    keychain->visit([&coinBase, &comission, &regular](const Coin& coin)->bool
    {
        if (coin.m_key_type == KeyType::Coinbase)
        {
            ++coinBase;
        }
        else if (coin.m_key_type == KeyType::Comission)
        {
            ++comission;
        }
        else if (coin.m_key_type == KeyType::Regular)
        {
            ++regular;
        }
        return true;
    });

    WALLET_CHECK(coinBase == 2);
    WALLET_CHECK(comission == 2);
    WALLET_CHECK(regular == 10);

    coins.clear();
    keychain->visit([&coins](const auto& coin)->bool
    {
        coins.push_back(coin);
        return false;
    });
    WALLET_CHECK(coins[0].m_confirmHash == Zero);
    WALLET_CHECK(coins[0].m_confirmHeight == MaxHeight);
    coins[0].m_confirmHeight = 423;
    coins[0].m_confirmHash = 12345678U;
    keychain->update(coins[0]);
    coins.clear();
    keychain->visit([&coins](const auto& coin)->bool
    {
        coins.push_back(coin);
        return false;
    });
    beam::Merkle::Hash t;
    t = 12345678U;
    WALLET_CHECK(coins[0].m_confirmHash == t);
    WALLET_CHECK(coins[0].m_confirmHeight == 423);
}
using namespace beam;
using namespace beam::wallet;
void TestStoreTxRecord()
{
    auto keychain = createSqliteKeychain();
    TxID id = {{1, 3, 4, 5 ,65}};
    TxDescription tr;
    tr.m_txId = id;
    tr.m_amount = 34;
    tr.m_peerId = unsigned(23);
    tr.m_myId = unsigned(42);
    tr.m_createTime = 123456;
    tr.m_minHeight = 134;
    tr.m_sender = true;
    tr.m_status = TxDescription::InProgress;
	tr.m_change = 5;

    WALLET_CHECK_NO_THROW(keychain->saveTx(tr));
    WALLET_CHECK_NO_THROW(keychain->saveTx(tr));
    TxDescription tr2 = tr;
    tr2.m_txId = id;
    tr2.m_amount = 43;
    tr2.m_minHeight = 234;
    tr2.m_createTime = 1234564;
    tr2.m_modifyTime = 12345644;
    tr2.m_status = TxDescription::Completed;
	tr2.m_change = 5;
    WALLET_CHECK_NO_THROW(keychain->saveTx(tr2));

    auto t = keychain->getTxHistory();
    WALLET_CHECK(t.size() == 1);
    WALLET_CHECK(t[0].m_txId == tr.m_txId);
    WALLET_CHECK(t[0].m_amount == tr.m_amount);
    WALLET_CHECK(t[0].m_minHeight == tr2.m_minHeight);
    WALLET_CHECK(t[0].m_peerId == tr.m_peerId);
    WALLET_CHECK(t[0].m_myId == tr.m_myId);
    WALLET_CHECK(t[0].m_createTime == tr.m_createTime);
    WALLET_CHECK(t[0].m_modifyTime == tr2.m_modifyTime);
    WALLET_CHECK(t[0].m_sender == tr2.m_sender);
	WALLET_CHECK(t[0].m_status == tr2.m_status);
    WALLET_CHECK(t[0].m_change == tr2.m_change);
    TxID id2 = {{ 3,4,5 }};
    WALLET_CHECK_NO_THROW(keychain->deleteTx(id2));
    WALLET_CHECK_NO_THROW(keychain->deleteTx(id));

    WALLET_CHECK_NO_THROW(keychain->saveTx(tr2));
    WALLET_CHECK_NO_THROW(keychain->saveTx(tr2));
    boost::optional<TxDescription> tr3;
    WALLET_CHECK_NO_THROW(tr3 = keychain->getTx(tr2.m_txId));
    WALLET_CHECK(tr3.is_initialized());
    WALLET_CHECK(tr3->m_txId == tr2.m_txId);
    WALLET_CHECK(tr3->m_amount == tr2.m_amount);
    WALLET_CHECK(tr3->m_peerId == tr2.m_peerId);
    WALLET_CHECK(tr3->m_myId == tr2.m_myId);
    WALLET_CHECK(tr3->m_message == tr2.m_message);
    WALLET_CHECK(tr3->m_createTime == tr2.m_createTime);
    WALLET_CHECK(tr3->m_modifyTime == tr2.m_modifyTime);
    WALLET_CHECK(tr3->m_sender == tr2.m_sender);
    WALLET_CHECK(tr3->m_status == tr2.m_status);
    WALLET_CHECK(tr3->m_fsmState == tr2.m_fsmState);
    WALLET_CHECK_NO_THROW(keychain->deleteTx(tr2.m_txId));
    WALLET_CHECK(keychain->getTxHistory().empty());

    for (uint8_t i = 0; i < 100; ++i)
    {
        tr.m_txId[0] = i;
        WALLET_CHECK_NO_THROW(keychain->saveTx(tr));
    }
    WALLET_CHECK(keychain->getTxHistory().size() == 100);
    t = keychain->getTxHistory(50, 2);
    WALLET_CHECK(t.size() == 2);
    t = keychain->getTxHistory(99, 10);
    WALLET_CHECK(t.size() == 1);
    t = keychain->getTxHistory(9, 0);
    WALLET_CHECK(t.size() == 0);
    t = keychain->getTxHistory(50, 2);
    id[0] = 50;
    WALLET_CHECK(t[0].m_txId == id);
    id[0] = 51;
    WALLET_CHECK(t[1].m_txId == id);

    t = keychain->getTxHistory(0, 1);
    WALLET_CHECK(t.size() == 1 && t[0].m_txId[0] == 0);

    t = keychain->getTxHistory(99, 1);
    WALLET_CHECK(t.size() == 1 && t[0].m_txId[0] == 99);

    t = keychain->getTxHistory(100, 1);
    WALLET_CHECK(t.size() == 0);
}

void TestRollback()
{
    auto db = createSqliteKeychain();
    for (uint64_t i = 0; i < 9; ++i)
    {
        Coin coin1 = { 5, Coin::Unspent, i, i + 10, KeyType::Regular, Height(i + 1) };
        coin1.m_confirmHash = unsigned(123);
        db->store(coin1);
    }

    for (uint64_t i = 9; i < 10; ++i)
    {
        Coin coin1 = { 5, Coin::Spent, 0, 0, KeyType::Regular, Height(1), Height(i + 1) };
        db->store(coin1);
    }

    // was created after branch
    {
        Coin coin1 = { 5, Coin::Spent, 7, 7, KeyType::Regular, Height(8) };
        db->store(coin1);
    }

    // rewards
    // should be deleted
    {
        Coin coin1 = { 5, Coin::Spent, 7, 8, KeyType::Coinbase, Height(8) };
        db->store(coin1);
    }

    {
        Coin coin1 = { 5, Coin::Spent, 7, 8, KeyType::Comission, Height(8) };
        db->store(coin1);
    }

    {
        Coin coin1 = { 5, Coin::Unspent, 8, 9, KeyType::Coinbase, Height(9) };
        db->store(coin1);
    }

    {
        Coin coin1 = { 5, Coin::Unspent, 8, 9, KeyType::Comission, Height(9) };
        db->store(coin1);
    }
    // should be preserved
    {
        Coin coin1 = { 5, Coin::Spent, 6, 7, KeyType::Coinbase, Height(7) };
        db->store(coin1);
    }

    {
        Coin coin1 = { 5, Coin::Spent, 6, 7, KeyType::Comission, Height(7) };
        db->store(coin1);
    }

    {
        Coin coin1 = { 5, Coin::Spent, 4, 5, KeyType::Coinbase, Height(5) };
        db->store(coin1);
    }

    {
        Coin coin1 = { 5, Coin::Spent, 4, 5, KeyType::Comission, Height(5) };
        db->store(coin1);
    }

    {
        Coin coin1 = { 5, Coin::Unspent, 3, 4, KeyType::Coinbase, Height(4) };
        db->store(coin1);
    }

    {
        Coin coin1 = { 5, Coin::Unspent, 3, 4, KeyType::Comission, Height(4) };
        db->store(coin1);
    }

    db->rollbackConfirmedUtxo(6);

    vector<Coin> coins;
    db->visit([&coins](const auto& c)->bool
    {
        coins.push_back(c);
        return true;
    });

    WALLET_CHECK(coins.size() == 17);

    for (int i = 0; i < 5; ++i)
    {
        auto& c = coins[i];
        WALLET_CHECK(c.m_status == Coin::Unspent);
        WALLET_CHECK(c.m_confirmHeight != MaxHeight);
        WALLET_CHECK(c.m_lockedHeight == MaxHeight);
    }

    for (int i = 6; i < 9; ++i)
    {
        auto& c = coins[i];
        WALLET_CHECK(c.m_status == Coin::Unconfirmed);
        WALLET_CHECK(c.m_confirmHeight == MaxHeight);
        WALLET_CHECK(c.m_lockedHeight == MaxHeight);
        WALLET_CHECK(c.m_confirmHash == Zero);
    }
    for (int i = 9; i < 10; ++i)
    {
        auto& c = coins[i];
        WALLET_CHECK(c.m_status == Coin::Unspent);
        WALLET_CHECK(c.m_confirmHeight != MaxHeight);
        WALLET_CHECK(c.m_lockedHeight == MaxHeight);
    }

    {
        // for now it is unconfirmed in future we would have to distinguish such coins
        auto& c = coins[10];
        WALLET_CHECK(c.m_status == Coin::Unconfirmed);
        WALLET_CHECK(c.m_confirmHeight == MaxHeight);
        WALLET_CHECK(c.m_lockedHeight == MaxHeight);
        WALLET_CHECK(c.m_confirmHash == Zero);
    }

    for (int i = 11; i < 13; ++i)
    {
        auto& c = coins[i];
        WALLET_CHECK(c.m_status == Coin::Unconfirmed);
        WALLET_CHECK(c.m_confirmHeight == MaxHeight);
        WALLET_CHECK(c.m_lockedHeight == MaxHeight);
    }
    for (int i = 13; i < 15; ++i)
    {
        auto& c = coins[i];
        WALLET_CHECK(c.m_status == Coin::Spent);
        WALLET_CHECK(c.m_confirmHeight != MaxHeight);
        WALLET_CHECK(c.m_lockedHeight == MaxHeight);
    }
    for (int i = 15; i < 17; ++i)
    {
        auto& c = coins[i];
        WALLET_CHECK(c.m_status == Coin::Unspent);
        WALLET_CHECK(c.m_confirmHeight != MaxHeight);
        WALLET_CHECK(c.m_lockedHeight == MaxHeight);
    }
}

void TestTxRollback()
{
    auto keychain = createSqliteKeychain();
    TxID id = { { 1, 3, 4, 5 ,65 } };
    TxID id2 = { {1, 3, 4} };

    Coin coin1 = { 5, Coin::Unspent, 1, 10, KeyType::Coinbase };
    keychain->store(coin1);
    Coin coin2 = { 6, Coin::Unspent, 2, 11, KeyType::Coinbase };
    keychain->store(coin2);

    coin2.m_spentTxId = id;
    coin2.m_status = Coin::Locked;

    Coin coin3 = { 3, Coin::Unconfirmed, 2 };
    coin3.m_createTxId = id;
    keychain->store(coin3);
    keychain->update({ coin2 });

    vector<Coin> coins;
    keychain->visit([&coins](const Coin& c)->bool
    {
        coins.push_back(c);
        return true;
    });

    WALLET_CHECK(coins.size() == 3);

    WALLET_CHECK(coins[1].m_status == Coin::Locked);
    WALLET_CHECK(coins[1].m_spentTxId == id);
    WALLET_CHECK(coins[2].m_status == Coin::Unconfirmed);
    WALLET_CHECK(coins[2].m_createTxId == id);

    keychain->rollbackTx(id2);

    coins.clear();
    keychain->visit([&coins](const Coin& c)->bool
    {
        coins.push_back(c);
        return true;
    });
    WALLET_CHECK(coins.size() == 3);

    keychain->rollbackTx(id);

    coins.clear();
    keychain->visit([&coins](const Coin& c)->bool
    {
        coins.push_back(c);
        return true;
    });

    WALLET_CHECK(coins.size() == 2);
    WALLET_CHECK(coins[1].m_status == Coin::Unspent);
    WALLET_CHECK(coins[1].m_spentTxId.is_initialized() == false);
}

void TestTxComplete()
{
    auto db = createSqliteKeychain();
    TxID id = { { 1, 3, 4, 5 ,65 } };

    vector<Coin> coins;

    {
        Coin coin = { 5, Coin::Locked, 1, 10, KeyType::Coinbase };
        coin.m_spentTxId = id;
        coins.push_back(coin);
    }
    {
        Coin coin = { 5, Coin::Unconfirmed, 1, 10, KeyType::Regular };
        coin.m_createTxId = id;
        coins.push_back(coin);
    }
    {
        Coin coin = { 5, Coin::Locked, 1, 10, KeyType::Regular };
        coin.m_spentTxId = id;
        coins.push_back(coin);
    }
    db->store(coins);
    db->completeTx(id);

    coins.clear();
    db->visit([&coins](const Coin& coin)
    {
        coins.push_back(coin);
        return true;
    });

    WALLET_CHECK(coins.size() == 3);
    WALLET_CHECK(coins[0].m_status == Coin::Spent);
    WALLET_CHECK(coins[1].m_status == Coin::Unspent);
    WALLET_CHECK(coins[2].m_status == Coin::Spent);
}

void TestPeers()
{
    auto db = createSqliteKeychain();
    auto peers = db->getPeers();
    WALLET_CHECK(peers.empty());
    TxPeer peer = {};
    peer.m_walletID = unsigned(1234567890);
    peer.m_label = u8"test peer";
    auto p = db->getPeer(peer.m_walletID);
    WALLET_CHECK(p.is_initialized() == false);
    peer.m_address = "92.123.10.3:3255";
    db->addPeer(peer);
    p = db->getPeer(peer.m_walletID);
    WALLET_CHECK(p.is_initialized() == true);
    WALLET_CHECK(p->m_address == peer.m_address);
    WALLET_CHECK(p->m_walletID == peer.m_walletID);
    WALLET_CHECK(p->m_label == peer.m_label);
    peers = db->getPeers();
    WALLET_CHECK(peers.size() == 1);

    WALLET_CHECK(peers[0].m_address == peer.m_address);
    WALLET_CHECK(peers[0].m_walletID == peer.m_walletID);
    WALLET_CHECK(peers[0].m_label == peer.m_label);
}

void TestAddresses()
{
    auto db = createSqliteKeychain();
    auto addresses = db->getAddresses(true);
    WALLET_CHECK(addresses.empty());
    addresses = db->getAddresses(false);
    WALLET_CHECK(addresses.empty());

    WalletAddress a = {};
    a.m_walletID = unsigned(9876543);
    a.m_label = "test label";
    a.m_category = "test category";
    a.m_createTime = beam::getTimestamp();
    a.m_duration = 23;
    a.m_own = true;

    db->saveAddress(a);

    addresses = db->getAddresses(true);
    WALLET_CHECK(addresses.size() == 1);
    WALLET_CHECK(addresses[0].m_walletID == a.m_walletID);
    WALLET_CHECK(addresses[0].m_label == a.m_label);
    WALLET_CHECK(addresses[0].m_category == a.m_category);
    WALLET_CHECK(addresses[0].m_createTime == a.m_createTime);
    WALLET_CHECK(addresses[0].m_duration == a.m_duration);
    WALLET_CHECK(addresses[0].m_own == a.m_own);

    a.m_category = "cat2";

    db->saveAddress(a);

    addresses = db->getAddresses(true);
    WALLET_CHECK(addresses.size() == 1);
    WALLET_CHECK(addresses[0].m_walletID == a.m_walletID);
    WALLET_CHECK(addresses[0].m_label == a.m_label);
    WALLET_CHECK(addresses[0].m_category == a.m_category);
    WALLET_CHECK(addresses[0].m_createTime == a.m_createTime);
    WALLET_CHECK(addresses[0].m_duration == a.m_duration);
    WALLET_CHECK(addresses[0].m_own == a.m_own);

    auto a2 = db->getAddress(a.m_walletID);
    WALLET_CHECK(a2.is_initialized());

    db->deleteAddress(a.m_walletID);
    WALLET_CHECK(db->getAddresses(true).empty());

    a2 = db->getAddress(a.m_walletID);
    WALLET_CHECK(!a2.is_initialized());
}

void TestSelect()
{
    auto db = createSqliteKeychain();
    const Amount c = 10;
    for (Amount i = 1; i <= c; ++i)
    {
        Coin c{ i, Coin::Unspent, 1, 10, KeyType::Regular };
        db->store(c);
    }
    for (Amount i = 1; i <= c; ++i)
    {
        auto coins = db->selectCoins(i, false);
        WALLET_CHECK(coins.size() == 1);
        WALLET_CHECK(coins[0].m_amount == i);
    }
    {
        auto coins = db->selectCoins(56, false);
        WALLET_CHECK(coins.empty());
    }
    {
        auto coins = db->selectCoins(55, false);
        WALLET_CHECK(coins.size() == 10);
    }
    {
        auto coins = db->selectCoins(15, false);
        WALLET_CHECK(coins.size() == 2);
    }
    for (Amount i = c + 1; i <= 55; ++i)
    {
        auto coins = db->selectCoins(i, false);
        WALLET_CHECK(!coins.empty());
    }
    // double coins
    for (Amount i = 1; i <= c; ++i)
    {
        Coin c{ i, Coin::Unspent, 1, 10, KeyType::Regular };
        db->store(c);
    }
    for (Amount i = 1; i <= c; ++i)
    {
        auto coins = db->selectCoins(i, false);
        WALLET_CHECK(coins.size() == 1);
        WALLET_CHECK(coins[0].m_amount == i);
    }
    {
        auto coins = db->selectCoins(111, false);
        WALLET_CHECK(coins.empty());
    }
    {
        auto coins = db->selectCoins(110, false);
        WALLET_CHECK(coins.size() == 20);
    }
    for (Amount i = c + 1; i <= 110; ++i)
    {
        auto coins = db->selectCoins(i, false);
        WALLET_CHECK(!coins.empty());
        auto sum = accumulate(coins.begin(), coins.end(), Amount(0), [](const auto& left, const auto& right) {return left + right.m_amount; });
        WALLET_CHECK(sum == i);
    }

    {
        db->remove(db->selectCoins(110, false));
        vector<Coin> coins = {
            Coin{ 2, Coin::Unspent, 1, 10, KeyType::Regular },
            Coin{ 1, Coin::Unspent, 1, 10, KeyType::Regular },
            Coin{ 9, Coin::Unspent, 1, 10, KeyType::Regular } };
        db->store(coins);
        coins = db->selectCoins(6, false);
        WALLET_CHECK(coins.size() == 1);
        WALLET_CHECK(coins[0].m_amount == 9);
    }
    {
        db->remove(db->selectCoins(12, false));
        vector<Coin> coins = {
            Coin{ 2, Coin::Unspent, 1, 10, KeyType::Regular },
            Coin{ 4, Coin::Unspent, 1, 10, KeyType::Regular },
            Coin{ 4, Coin::Unspent, 1, 10, KeyType::Regular },
            Coin{ 4, Coin::Unspent, 1, 10, KeyType::Regular },
            Coin{ 4, Coin::Unspent, 1, 10, KeyType::Regular } };
        db->store(coins);
        coins = db->selectCoins(5, false);
        WALLET_CHECK(coins.size() == 2);
        WALLET_CHECK(coins[0].m_amount == 2);
    }
    {
        db->remove(db->selectCoins(18, false));
        vector<Coin> coins = {
            Coin{ 4, Coin::Unspent, 1, 10, KeyType::Regular },
            Coin{ 4, Coin::Unspent, 1, 10, KeyType::Regular },
            Coin{ 4, Coin::Unspent, 1, 10, KeyType::Regular },
            Coin{ 4, Coin::Unspent, 1, 10, KeyType::Regular } };
        db->store(coins);
        coins = db->selectCoins(1, false);
        WALLET_CHECK(coins.size() == 1);
        WALLET_CHECK(coins[0].m_amount == 4);
    }
    {
        db->remove(db->selectCoins(16, false));
        vector<Coin> coins = {
            Coin{ 3, Coin::Unspent, 1, 10, KeyType::Regular },
            Coin{ 4, Coin::Unspent, 1, 10, KeyType::Regular },
            Coin{ 5, Coin::Unspent, 1, 10, KeyType::Regular },
            Coin{ 7, Coin::Unspent, 1, 10, KeyType::Regular } };
        db->store(coins);
        coins = db->selectCoins(6, false);
        WALLET_CHECK(coins.size() == 1);
        WALLET_CHECK(coins[0].m_amount == 7);
    }
    {
        db->remove(db->selectCoins(19, false));
        vector<Coin> coins = {
            Coin{ 1, Coin::Unspent, 1, 10, KeyType::Regular },
            Coin{ 2, Coin::Unspent, 1, 10, KeyType::Regular },
            Coin{ 3, Coin::Unspent, 1, 10, KeyType::Regular },
            Coin{ 4, Coin::Unspent, 1, 10, KeyType::Regular } };
        db->store(coins);
        coins = db->selectCoins(4, false);
        WALLET_CHECK(coins.size() == 1);
        WALLET_CHECK(coins[0].m_amount == 4);

        coins = db->selectCoins(7, false);
        WALLET_CHECK(coins.size() == 2);
        WALLET_CHECK(coins[0].m_amount == 3);
        WALLET_CHECK(coins[1].m_amount == 4);
    }
    {
        db->remove(db->selectCoins(10, false));
        vector<Coin> coins = {
            Coin{ 2, Coin::Unspent, 1, 10, KeyType::Regular },
            Coin{ 5, Coin::Unspent, 1, 10, KeyType::Regular },
            Coin{ 7, Coin::Unspent, 1, 10, KeyType::Regular } };
        db->store(coins);
        coins = db->selectCoins(6, false);
        WALLET_CHECK(coins.size() == 1);
        WALLET_CHECK(coins[0].m_amount == 7);
    }
    {
        db->remove(db->selectCoins(14, false));
        vector<Coin> coins = {
            Coin{ 235689, Coin::Unspent, 1, 10, KeyType::Regular },
            Coin{ 2999057, Coin::Unspent, 1, 10, KeyType::Regular },
            Coin{ 500000, Coin::Unspent, 1, 10, KeyType::Regular },
            Coin{ 5000000, Coin::Unspent, 1, 10, KeyType::Regular },
            Coin{ 40000000, Coin::Unspent, 1, 10, KeyType::Regular },
            Coin{ 40000000, Coin::Unspent, 1, 10, KeyType::Regular },
            Coin{ 40000000, Coin::Unspent, 1, 10, KeyType::Regular },
        };
        db->store(coins);
        coins = db->selectCoins(41000000, false);
        WALLET_CHECK(coins.size() == 2);
        WALLET_CHECK(coins[0].m_amount == 2999057);
        WALLET_CHECK(coins[1].m_amount == 40000000);
        coins = db->selectCoins(4000000, false);
        WALLET_CHECK(coins.size() == 1);
        WALLET_CHECK(coins[0].m_amount == 5000000);
    }
}

void TestSelect2()
{
    auto db = createSqliteKeychain();
    const Amount c = 1000000;
    vector<Coin> t;
    t.reserve(c);
    for (Amount i = 1; i <= c; ++i)
    {
        t.emplace_back( 40000000, Coin::Unspent, 1, 10, KeyType::Regular );
    }
    db->store(t);
    {
        Coin c{ 30000000, Coin::Unspent, 1, 10, KeyType::Regular };
        db->store(c);
    }
	helpers::StopWatch sw;

	sw.start();
    auto coins = db->selectCoins(347000000, false);
	sw.stop();
	cout << "TestSelect2 elapsed time: " << sw.milliseconds() << " ms\n";
    WALLET_CHECK(coins.size() == 9);
    WALLET_CHECK(coins[0].m_amount == 30000000);
}

int main()
{
    int logLevel = LOG_LEVEL_DEBUG;
#if LOG_VERBOSE_ENABLED
    logLevel = LOG_LEVEL_VERBOSE;
#endif
    auto logger = beam::Logger::create(logLevel, logLevel);
	ECC::InitializeContext();

	TestKeychain();
    TestStoreCoins();
    TestStoreTxRecord();
    TestTxRollback();
    TestTxComplete();
    TestRollback();
    TestPeers();
    TestSelect();
    //TestSelect2();
    TestAddresses();

    return WALLET_CHECK_RESULT;
}

max_stars_repo_name: akhavr/beam

max_issues_repo_name: akhavr/beam

max_forks_repo_name: akhavr/beam


text:
// Boost.Polygon library voronoi_benchmark.cpp file

//          Copyright Andrii Sydorchuk 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

// See http://www.boost.org for updates, documentation, and revision history.

#include <algorithm>
#include <iomanip>
#include <iostream>
#include <fstream>
#include <numeric>
#include <vector>
#include <utility>

#include <boost/random/mersenne_twister.hpp>
#include <boost/timer/timer.hpp>

typedef boost::int32_t int32;
using boost::timer::cpu_times;
using boost::timer::nanosecond_type;

// Include for the Boost.Polygon Voronoi library.
#include <boost/polygon/voronoi.hpp>
typedef boost::polygon::voronoi_diagram<double> VD_BOOST;

// Includes for the CGAL library.
#include <CGAL/Simple_cartesian.h>
#include <CGAL/Segment_Delaunay_graph_filtered_traits_2.h>
#include <CGAL/Segment_Delaunay_graph_2.h>

typedef CGAL::Simple_cartesian<double> K;
typedef CGAL::Segment_Delaunay_graph_filtered_traits_without_intersections_2<K> GT;
typedef CGAL::Segment_Delaunay_graph_2<GT>  SDT_CGAL;
typedef SDT_CGAL::Point_2 Point_CGAL;
typedef SDT_CGAL::Site_2 Site_CGAL;

// Include for the Boost.Polygon library.
#include <boost/polygon/polygon.hpp>
typedef boost::polygon::point_data<int32> POINT_POLYGON;
typedef boost::polygon::segment_data<int32> SEGMENT_POLYGON;
typedef std::vector<SEGMENT_POLYGON> SSD_POLYGON;

const int RANDOM_SEED = 27;
const int NUM_TESTS = 6;
const int NUM_SEGMENTS[] = {10, 100, 1000, 10000, 100000, 1000000};
const int NUM_RUNS[] = {100000, 10000, 1000, 100, 10, 1};
std::ofstream bf("benchmark_segments.txt",
                 std::ios_base::out | std::ios_base::app);
boost::timer::cpu_timer timer;

void format_line(int num_points, int num_tests, double time_per_test) {
  bf << "| " << std::setw(16) << num_points << " ";
  bf << "| " << std::setw(15) << num_tests << " ";
  bf << "| " << std::setw(17) << time_per_test << " ";
  bf << "|" << std::endl;
}

double get_elapsed_secs() {
  cpu_times elapsed_times(timer.elapsed());
  return 1E-9 * static_cast<double>(
      elapsed_times.system + elapsed_times.user);
}

void clean_segment_set(std::vector<SEGMENT_POLYGON>* data) {
  typedef int32 Unit;
  typedef boost::polygon::scanline_base<Unit>::Point Point;
  typedef boost::polygon::scanline_base<Unit>::half_edge half_edge;
  typedef int segment_id;
  std::vector<std::pair<half_edge, segment_id> > half_edges;
  std::vector<std::pair<half_edge, segment_id> > half_edges_out;
  segment_id id = 0;
  half_edges.reserve(data->size());
  for (std::vector<SEGMENT_POLYGON>::iterator it = data->begin();
       it != data->end(); ++it) {
    POINT_POLYGON l = it->low();
    POINT_POLYGON h = it->high();
    half_edges.push_back(std::make_pair(half_edge(l, h), id++));
  }
  half_edges_out.reserve(half_edges.size());
  // Apparently no need to pre-sort data when calling validate_scan.
  boost::polygon::line_intersection<Unit>::validate_scan(
      half_edges_out, half_edges.begin(), half_edges.end());
  std::vector<SEGMENT_POLYGON> result;
  result.reserve(half_edges_out.size());
  for (std::size_t i = 0; i < half_edges_out.size(); ++i) {
    id = half_edges_out[i].second;
    POINT_POLYGON l = half_edges_out[i].first.first;
    POINT_POLYGON h = half_edges_out[i].first.second;
    SEGMENT_POLYGON orig_seg = data->at(id);
    if (orig_seg.high() < orig_seg.low())
      std::swap(l, h);
    result.push_back(SEGMENT_POLYGON(l, h));
  }
  std::swap(result, *data);
}

std::vector<double> get_intersection_runtime() {
  std::vector<double> running_times;
  boost::mt19937 gen(RANDOM_SEED);
  for (int i = 0; i < NUM_TESTS; ++i) {
    timer.start();
    for (int j = 0; j < NUM_RUNS[i]; ++j) {
      SSD_POLYGON ssd;
      for (int k = 0; k < NUM_SEGMENTS[i]; ++k) {
        int32 x1 = gen();
        int32 y1 = gen();
        int32 dx = (gen() & 1023) + 1;
        int32 dy = (gen() & 1023) + 1;
        ssd.push_back(SEGMENT_POLYGON(
            POINT_POLYGON(x1, y1), POINT_POLYGON(x1 + dx, y1 + dy)));
      }
      clean_segment_set(&ssd);
    }
    running_times.push_back(get_elapsed_secs());
  }
  return running_times;
}

void run_boost_voronoi_test(const std::vector<double> &running_times) {
  boost::mt19937 gen(RANDOM_SEED);
  bf << "Boost.Polygon Voronoi of Segments:\n";
  for (int i = 0; i < NUM_TESTS; ++i) {
    timer.start();
    for (int j = 0; j < NUM_RUNS[i]; ++j) {
      SSD_POLYGON ssd;
      VD_BOOST vd;
      for (int k = 0; k < NUM_SEGMENTS[i]; ++k) {
        int32 x1 = gen();
        int32 y1 = gen();
        int32 dx = (gen() & 1023) + 1;
        int32 dy = (gen() & 1023) + 1;
        ssd.push_back(SEGMENT_POLYGON(
            POINT_POLYGON(x1, y1),
            POINT_POLYGON(x1 + dx, y1 + dy)));
      }
      clean_segment_set(&ssd);
      boost::polygon::construct_voronoi(ssd.begin(), ssd.end(), &vd);
    }
    double time_per_test =
        (get_elapsed_secs() - running_times[i]) / NUM_RUNS[i];
    format_line(NUM_SEGMENTS[i], NUM_RUNS[i], time_per_test);
  }
  bf << "\n";
}

void run_cgal_delaunay_test(const std::vector<double> &running_times) {
  boost::mt19937 gen(RANDOM_SEED);
  bf << "CGAL Triangulation of Segments:\n";
  for (int i = 0; i < NUM_TESTS; ++i) {
    timer.start();
    for (int j = 0; j < NUM_RUNS[i]; ++j) {
      SSD_POLYGON ssd;
      for (int k = 0; k < NUM_SEGMENTS[i]; ++k) {
        int32 x1 = gen();
        int32 y1 = gen();
        int32 dx = (gen() & 1023) + 1;
        int32 dy = (gen() & 1023) + 1;
        ssd.push_back(SEGMENT_POLYGON(
            POINT_POLYGON(x1, y1),
            POINT_POLYGON(x1 + dx, y1 + dy)));
      }
      clean_segment_set(&ssd);

      typedef std::vector<Point_CGAL> Points_container;
      typedef std::vector<Points_container>::size_type Index_type;
      typedef std::vector< std::pair<Index_type, Index_type> > Constraints_container;
      Points_container points;
      Constraints_container constraints;
      points.reserve(ssd.size() * 2);
      constraints.reserve(ssd.size());
      for (SSD_POLYGON::iterator it = ssd.begin(); it != ssd.end(); ++it) {
        points.push_back(Point_CGAL(
            boost::polygon::x(it->low()),
            boost::polygon::y(it->low())));
        points.push_back(Point_CGAL(
            boost::polygon::x(it->high()),
            boost::polygon::y(it->high())));
        constraints.push_back(
            std::make_pair(points.size() - 2, points.size() - 1));
      }

      SDT_CGAL sdg;
      sdg.insert_segments(
          points.begin(), points.end(),
          constraints.begin(), constraints.end());
    }
    double time_per_test =
        (get_elapsed_secs() - running_times[i]) / NUM_RUNS[i];
    format_line(NUM_SEGMENTS[i], NUM_RUNS[i], time_per_test);
  }
  bf << "\n";
}

int main() {
  bf << std::setiosflags(std::ios::right | std::ios::fixed)
     << std::setprecision(6);
  std::vector<double> running_times = get_intersection_runtime();
  run_boost_voronoi_test(running_times);
  run_cgal_delaunay_test(running_times);
  bf.close();
  return 0;
}

max_stars_repo_name: cpp-pm/boost

max_issues_repo_name: cpp-pm/boost

max_forks_repo_name: cpp-pm/boost


text: #include <boost/geometry/strategies/strategies.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#pragma once

#include <regex>

#include <boost/algorithm/string.hpp>

// using namespace std;

namespace utils {

    bool exists_file(std::string filename);

    std::string read_file(std::string filename);

    std::vector<std::string> read_lines(std::string filename);

    std::string get_uuid();

    bool url_decode(const std::string &in, std::string &out);

    std::vector<std::string> split(const std::string &str, const char primary);

    std::map<std::string, std::string>
    double_split(const std::string &in, const char primary, const char secondary);

    std::map<std::string, std::string> url_to_map(const std::string &in);

    void url_to_map(std::map<std::string, std::string> *mp, const std::string &in);

    int s2i(std::string, int = 0);

    std::string i2s(int, std::string = "");

    double s2d(std::string, double = 0);

    std::string d2s(double, std::string = "");

    long s2l(std::string, long = 0);

    std::string l2s(long, std::string = "");

    std::string join(std::vector<std::string>, std::string);

    long timestamp();

    std::vector<std::string> split2(const std::string& input, const std::string& reText);

    inline bool ends_with(std::string const &value, std::string const &ending) {
        if (ending.size() > value.size())
            return false;
        return std::equal(ending.rbegin(), ending.rend(), value.rbegin());
    }

    std::vector<std::tuple<bool,std::string>> tokenize(std::string, std::regex r);

} // namespace utils

namespace color {
    enum Code {
        FG_RED = 31,
        FG_GREEN = 32,
        FG_BLUE = 34,
        FG_DEFAULT = 39,
        BG_RED = 41,
        BG_GREEN = 42,
        BG_BLUE = 44,
        BG_DEFAULT = 49
    };

    class Modifier {
        Code code;

    public:
        Modifier(Code pCode) : code(pCode) {}

        friend std::ostream &operator<<(std::ostream &os, const Modifier &mod) {
            return os << "\033[" << mod.code << "m";
        }
    };
} // namespace color

max_stars_repo_name: martinskou/wolf

max_issues_repo_name: martinskou/wolf

max_forks_repo_name: martinskou/wolf