text:
#define BOOST_TEST_MODULE card_check_test
#include <boost/test/included/unit_test.hpp>
#include <boost/test/data/test_case.hpp>
#include <boost/test/data/monomorphic.hpp>

#include "card_check.hpp"

namespace bdata = boost::unit_test::data;

BOOST_AUTO_TEST_SUITE( suite_luhn )

BOOST_AUTO_TEST_CASE( luhn )
{
  CardCheck cc;
  BOOST_TEST(cc.testLuhn("378282246310005"));
  BOOST_TEST(cc.testLuhn("371449635398431"));
  BOOST_TEST(cc.testLuhn("378734493671000"));
  BOOST_TEST(cc.testLuhn("30569309025904"));
  BOOST_TEST(cc.testLuhn("38520000023237"));
  BOOST_TEST(cc.testLuhn("6011111111111117"));
  BOOST_TEST(cc.testLuhn("6011000990139424"));
  BOOST_TEST(cc.testLuhn("3530111333300000"));
  BOOST_TEST(cc.testLuhn("3566002020360505"));
  BOOST_TEST(cc.testLuhn("5555555555554444"));
  BOOST_TEST(cc.testLuhn("5105105105105100"));
  BOOST_TEST(cc.testLuhn("4111111111111111"));
  BOOST_TEST(cc.testLuhn("4012888888881881"));
  BOOST_TEST(cc.testLuhn("4222222222222"));
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE( suite_jcb )

BOOST_DATA_TEST_CASE( jcb_issuer1, bdata::xrange(3528,3589) )
{
  CardCheck cc(std::to_string(sample));
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[JCB]);
  BOOST_TEST(!cc.testLength());
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE( suite_amex )

BOOST_AUTO_TEST_CASE( amex_issuer1 )
{
  CardCheck cc;
  cc.setNumber("34");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[Amex]);
  BOOST_TEST(!cc.testLength());
  cc.setNumber("37");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[Amex]);
  BOOST_TEST(!cc.testLength());
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE( suite_visa )

BOOST_AUTO_TEST_CASE( visa_issuer1 )
{
  CardCheck cc;
  cc.setNumber("4");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[Visa]);
  BOOST_TEST(!cc.testLength());
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE( suite_mastercard )

BOOST_DATA_TEST_CASE( mastercard_issuer1, bdata::xrange(2221,2720) )
{
  CardCheck cc(std::to_string(sample));
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[MasterCard]);
  BOOST_TEST(!cc.testLength());
}

BOOST_DATA_TEST_CASE( mastercard_issuer2, bdata::xrange(51,55) )
{
  CardCheck cc(std::to_string(sample));
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[MasterCard]);
  BOOST_TEST(!cc.testLength());
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE( suite_dinersclub )

BOOST_DATA_TEST_CASE( dinersclub_issuer1, bdata::xrange(300,305) )
{
  CardCheck cc(std::to_string(sample));
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[DinersClub]);
  BOOST_TEST(!cc.testLength());
}

BOOST_AUTO_TEST_CASE( dinersclub_issuer2 )
{
  CardCheck cc;
  cc.setNumber("36");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[DinersClub]);
  BOOST_TEST(!cc.testLength());
  cc.setNumber("38");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[DinersClub]);
  BOOST_TEST(!cc.testLength());
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE( suite_discover )

BOOST_DATA_TEST_CASE( discover_issuer1, bdata::xrange(622126,622925) )
{
  CardCheck cc(std::to_string(sample));
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[Discover]);
  BOOST_TEST(!cc.testLength());
}

BOOST_DATA_TEST_CASE( discover_issuer2, bdata::xrange(644,649) )
{
  CardCheck cc(std::to_string(sample));
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[Discover]);
  BOOST_TEST(!cc.testLength());
}

BOOST_AUTO_TEST_CASE( discover_issuer3 )
{
  CardCheck cc;
  cc.setNumber("6011");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[Discover]);
  BOOST_TEST(!cc.testLength());
  cc.setNumber("65");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[Discover]);
  BOOST_TEST(!cc.testLength());
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE( suite_unionpay )

BOOST_AUTO_TEST_CASE( unionpay_issuer1 )
{
  CardCheck cc;
  cc.setNumber("62");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[UnionPay]);
  BOOST_TEST(!cc.testLength());
  cc.setNumber("622125");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[UnionPay]);
  BOOST_TEST(!cc.testLength());
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE( suite_corner )

BOOST_AUTO_TEST_CASE( corner_issuer1 )
{
  CardCheck cc;
  cc.setNumber("0");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[Unknown]);
  BOOST_TEST(!cc.testLength());
  cc.setNumber("1");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[Unknown]);
  BOOST_TEST(!cc.testLength());
  cc.setNumber("2");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[Unknown]);
  BOOST_TEST(!cc.testLength());
  cc.setNumber("3");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[Unknown]);
  BOOST_TEST(!cc.testLength());
  cc.setNumber("4");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[Visa]);
  BOOST_TEST(!cc.testLength());
  cc.setNumber("5");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[Unknown]);
  BOOST_TEST(!cc.testLength());
  cc.setNumber("6");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[Unknown]);
  BOOST_TEST(!cc.testLength());
  cc.setNumber("7");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[Unknown]);
  BOOST_TEST(!cc.testLength());
  cc.setNumber("8");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[Unknown]);
  BOOST_TEST(!cc.testLength());
  cc.setNumber("9");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[Unknown]);
  BOOST_TEST(!cc.testLength());

  cc.setNumber("63");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[Unknown]);
  BOOST_TEST(!cc.testLength());
  cc.setNumber("306");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[Unknown]);
  BOOST_TEST(!cc.testLength());
}

BOOST_AUTO_TEST_SUITE_END()

/** test from paypal test credit card numbers
 https://www.paypalobjects.com/en_US/vhelp/paypalmanager_help/credit_card_numbers.htm
 */
BOOST_AUTO_TEST_SUITE( suite_paypal )

BOOST_AUTO_TEST_CASE( paypal_issuer1 )
{
  CardCheck cc;

  // Amex
  cc.setNumber("378282246310005");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[Amex]);
  BOOST_TEST(cc.testLength());
  cc.setNumber("371449635398431");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[Amex]);
  BOOST_TEST(cc.testLength());
  cc.setNumber("378734493671000");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[Amex]);
  BOOST_TEST(cc.testLength());

  // Bankcard, not supported
  cc.setNumber("5610591081018250");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[Unknown]);
  BOOST_TEST(!cc.testLength());

  // Diner's Club
  cc.setNumber("30569309025904");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[DinersClub]);
  BOOST_TEST(cc.testLength());
  cc.setNumber("38520000023237");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[DinersClub]);
  BOOST_TEST(cc.testLength());

  // Discover Card
  cc.setNumber("6011111111111117");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[Discover]);
  BOOST_TEST(cc.testLength());
  cc.setNumber("6011000990139424");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[Discover]);
  BOOST_TEST(cc.testLength());

  // JCB
  cc.setNumber("3530111333300000");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[JCB]);
  BOOST_TEST(cc.testLength());
  cc.setNumber("3566002020360505");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[JCB]);
  BOOST_TEST(cc.testLength());

  // MasterCard
  cc.setNumber("5555555555554444");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[MasterCard]);
  BOOST_TEST(cc.testLength());
  cc.setNumber("5105105105105100");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[MasterCard]);
  BOOST_TEST(cc.testLength());

  // Visa
  cc.setNumber("4111111111111111");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[Visa]);
  BOOST_TEST(cc.testLength());
  cc.setNumber("4012888888881881");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[Visa]);
  BOOST_TEST(cc.testLength());
  cc.setNumber("4222222222222");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[Visa]);
  BOOST_TEST(cc.testLength());

  // Dankort (PBS), not supported
  cc.setNumber("76009244561");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[Unknown]);
  cc.setNumber("5019717010103742");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[Unknown]);
  BOOST_TEST(!cc.testLength());

  // Switch/Solo (Paymentech), not supported
  cc.setNumber("6331101999990016");
  BOOST_TEST(cc.getIssuer() == IssuerStat::name[Unknown]);
  BOOST_TEST(!cc.testLength());

}

BOOST_AUTO_TEST_SUITE_END()

ext: cpp

max_stars_repo_name: rlan/libcardcheck

max_issues_repo_name: rlan/libcardcheck

max_forks_repo_name: rlan/libcardcheck


text:
// Software License for MTL
//
// Copyright (c) 2007 The Trustees of Indiana University.
//               2008 Dresden University of Technology and the Trustees of Indiana University.
//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.
// All rights reserved.
// Authors: Peter Gottschling and Andrew Lumsdaine
//
// This file is part of the Matrix Template Library
//
// See also license.short.txt in the distribution.

#ifndef MTL_VECTOR_EXTRACTER_INCLUDE
#define MTL_VECTOR_EXTRACTER_INCLUDE

#include <boost/numeric/mtl/concept/collection.hpp>

namespace mtl {	namespace vector {

template< typename Vector >
struct indexbuffer
{
    typedef typename Collection<Vector>::value_type value_type;
    typedef typename Collection<Vector>::size_type size_type;
    typedef indexbuffer self;

    indexbuffer(const Vector& v) : vec(v) {}

    inline self& operator()(const size_type p, value_type& dest)
    {
	dest = vec[p];
	return *this;
    }

    inline void update() {}
  private:
    const Vector& vec;
};

template< typename Vector >
class extracter
{
  public:
    typedef typename Collection<Vector>::value_type value_type;
    typedef typename Collection<Vector>::size_type  size_type;
    typedef indexbuffer< Vector >                   buffer_type;

    extracter(const Vector& vec):
      destroyBuffer(true), buffer(new buffer_type(vec))
    {}
    extracter(buffer_type& buf):
      destroyBuffer(false), buffer(&buf)
    {}

    struct bracket_proxy
    {
	const size_type p;
	buffer_type& buffer;
	bracket_proxy(const size_type p, buffer_type& b) : p(p), buffer(b) {}

	inline buffer_type& operator>>(value_type& dest) { return buffer(p, dest); }
    };

    inline bracket_proxy operator[](const size_type p) { return bracket_proxy(p, *buffer); }

    ~extracter() {
	buffer->update();
	if(destroyBuffer)
	    delete buffer;
    }
  private:
    const bool destroyBuffer;
    buffer_type* buffer;
};

}} //namespace mtl::vector
#endif

ext: hpp


text:
/*
    Boost Competency Test - GSoC 2020
    digu_J - Digvijay Janartha
    NIT Hamirpur - INDIA
*/

#include <algorithm>
#include <iostream>
#include <iterator>
#include <utility>
#include <vector>
#include <random>
#include <chrono>

#include <boost/geometry/geometry.hpp>

#include "../../includes/concave_hull_k_nearest_neighbours_optimized.hpp"
#include "../../includes/concave_hull_k_nearest_neighbours.hpp"

namespace bg = boost::geometry;
using bg::dsv;

std::mt19937_64 rang(std::chrono::high_resolution_clock::now().time_since_epoch().count());

int my_rand(int l, int r)
{
    if (l > r)
    {
        std::swap(l, r);
    }
	std::uniform_int_distribution <int> uid(l, r);
	return uid(rang);
}

int main()
{
    std::cout << std::fixed << std::setprecision(0);
    #ifdef HOME
        freopen("input.txt", "r", stdin);
        freopen("output.txt", "w", stdout);
    #endif
    typedef bg::model::point<double, 2, bg::cs::cartesian> point_t;
    typedef bg::model::multi_point<point_t> mpoint_t;

    mpoint_t mpt1, hull1, hull2;

    int points = 200, k = 3;
    for (int i = 0; i < points; ++i)
    {
        int x = my_rand(0, 1000);
        int y = my_rand(0, 1000);
        bg::append(mpt1, point_t(x, y));
    }

    algo2::ConcaveHullKNN(mpt1, hull1, k);
    int t1 = (int)(clock() * 1000. / CLOCKS_PER_SEC);

    algo3::ConcaveHullKNN(mpt1, hull2, k);
    int t2 = (int)(clock() * 1000. / CLOCKS_PER_SEC) - t1;

    std::cout << "Dataset: " << dsv(mpt1) << std::endl;
    std::cout << "Convex hull: " << dsv(hull1) << std::endl;

    std:: cout << t1 << " " << t2 << std::endl;
    return 0;
}

/*
Output is very big, I made this file to check performance (execution time) using clock()
*/


text:
#include "arguments.hpp"

#include <filesystem>
#include <sstream>
#include <boost/program_options.hpp>
#include <path.hpp>

using namespace git_watch;

void arguments::fill(char const** arguments, int argument_count)
{
    namespace bpo = boost::program_options;
    namespace fs = std::filesystem;

    auto configDir(
        path::config_directory()
            .value_or(fs::current_path().append("config"))
            .append("git_watch")
            .generic_string()
    );
    std::string operation;

    bpo::options_description desc("Allowed options");
    desc.add_options()
            ("help,h", "Show help message")
            ("config-dir,c", bpo::value<std::string>(&_config_dir)->default_value(configDir), "Set the configuration directory")
            ("operation,o", bpo::value<std::string>(&_operation), "Operation of choice");
    bpo::positional_options_description pdesc;
    pdesc.add("operation", 1);
    auto configDirPath = fs::path(configDir);

    bpo::variables_map vm;
    auto parser{bpo::command_line_parser(argument_count, arguments)};

    store(parser.options(desc).run(), vm);
    store(parser.positional(pdesc).run(), vm);
    notify(vm);

    _help = vm.count("help");

    std::ostringstream usage;
    usage << "Usage " << arguments[0] << " " << "operation [options]" << std::endl << desc;
    _usage = usage.str();
}

max_stars_repo_name: JoshuaBehrens/git-watch

max_issues_repo_name: JoshuaBehrens/git-watch

max_forks_repo_name: JoshuaBehrens/git-watch


text: #include <boost/units/physical_dimensions/stress.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text: #include <boost/python/object/class_metadata.hpp>


text:
/* CirKit: A circuit toolkit
 * Copyright (C) 2009-2015  University of Bremen
 * Copyright (C) 2015-2017  EPFL
 *
 * 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.
 */

/**
 * @file gate.hpp
 *
 * @brief Gate class
 *
 * @author Mathias Soeken
 * @author Stefan Frehse
 * @since  1.0
 */

#ifndef GATE_HPP
#define GATE_HPP

#include <reversible/variable.hpp>

#include <iostream>
#include <set>
#include <vector>

#include <boost/any.hpp>

namespace cirkit
{

  /**
   * @brief Represents a gate in a circuit
   *
   * @since  1.0
   */
  class gate
  {
  public:
    /**
     * @brief Vector type of gates
     * @since  1.0
     */
    using vector = std::vector<gate>;

    /**
     * @brief Container for storing control lines
     * @since  2.0
     */
    using control_container = std::vector<variable>;

    /**
     * @brief Container for storing target lines
     * @since 2.0
     */
    using target_container = std::vector<unsigned>;

  public:
    /**
     * @brief Default constructor
     *
     * Initializes private data
     *
     * @since  1.0
     */
    gate();

    /**
     * @brief Copy Constructor
     *
     * Initializes private data and copies gate
     *
     * @param other Gate to be assigned
     *
     * @since  1.0
     */
    gate( const gate& other );

    /**
     * @brief Default deconstructor
     *
     * Clears private data
     *
     * @since  1.0
     */
    virtual ~gate();

    /**
     * @brief Assignment operator
     *
     * @param other Gate to be assigned
     *
     * @return Pointer to instance
     *
     * @since  1.0
     */
    gate& operator=( const gate& other );

    /**
     * @brief Returns the control lines
     *
     * @since  2.0
     */
    gate::control_container& controls() const;

    /**
     * @brief Returns the target lines
     *
     * @since  2.0
     */
    gate::target_container& targets() const;

    /**
     * @brief Returns the number of control and target lines as sum
     *
     * This method returns the number of control and target
     * lines as sum and can be used for e.g. calculating costs.
     *
     * @since  1.0
     *
     * @return Number of control and target lines.
     */
    virtual unsigned size() const;

    /**
     * @brief Adds a control line to the gate
     *
     * @param c control variable to add
     *
     * @since 1.0
     */
    virtual void add_control( variable c );

    /**
     * @brief Remove control line to the gate
     *
     * @param c control variable to remove
     *
     * @since 1.0
     */
    virtual void remove_control( variable c );

    /**
     * @brief Adds a target to the desired line
     *
     * @param l target line
     *
     * @since 1.0
     */
    virtual void add_target( unsigned l );

    /**
     * @brief Removes a target from the desired line
     *
     * @param l target line
     *
     * @since 1.0
     */
    virtual void remove_target( unsigned l );

    /**
     * @brief Sets the type of the target line(s)
     *
     * @param t target type
     *
     * @since  1.0
     */
    virtual void set_type( const boost::any& t );

    /**
     * @brief Returns the type of the target line(s)
     *
     * @return target type
     *
     * @since  1.0
     */
    virtual const boost::any& type() const;

  private:
    class priv;
    priv* const d;
  };
}

#endif /* GATE_HPP */

// Local Variables:
// c-basic-offset: 2
// eval: (c-set-offset 'substatement-open 0)
// eval: (c-set-offset 'innamespace 0)
// End:

max_stars_repo_name: eletesta/cirkit

max_issues_repo_name: eletesta/cirkit

max_forks_repo_name: eletesta/cirkit


text:
#include "map/pathfinder.h"

#include "database/defines.h"
#include "map/province.h"
#include "util/container_util.h"

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/astar_search.hpp>

namespace metternich {

class pathfinder::impl
{
	using cost = int;
	using graph = boost::adjacency_list<boost::listS, boost::vecS, boost::undirectedS, boost::no_property, boost::property<boost::edge_weight_t, cost>>;
	using vertex = graph::vertex_descriptor;
	using edge = graph::edge_descriptor;

public:
	impl(const std::set<province *> &provinces);

	find_trade_path_result find_trade_path(const province *start_province, const province *goal_province) const;

private:
	size_t get_province_index(const province *province) const
	{
		return this->province_to_index.find(province)->second;
	}

	cost get_trade_cost(const edge e) const;

private:
	std::vector<province *> provinces;
	std::map<const province *, size_t> province_to_index;
	graph province_graph;
};

template <class graph, class cost>
class trade_path_heuristic final : public boost::astar_heuristic<graph, cost>
{
public:
	using vertex = typename boost::graph_traits<graph>::vertex_descriptor;

	trade_path_heuristic(vertex goal, const std::vector<province *> &provinces)
		: goal(goal), provinces(provinces)
	{}

	cost operator()(vertex v)
	{
		return this->provinces[v]->get_kilometers_distance_to(this->provinces[this->goal]) * 100 / province::base_distance * defines::get()->get_trade_cost_modifier_per_distance() / 100;
	}

private:
	vertex goal;
	const std::vector<province *> &provinces;
};

template <class vertex>
class astar_visitor final : public boost::default_astar_visitor
{
public:
	astar_visitor(vertex goal) : goal(goal)
	{}

	template <class graph>
	void examine_vertex(vertex v, graph &g) {
		Q_UNUSED(g)

		if (v == this->goal) {
			throw found_goal();
		}
	}

private:
	vertex goal;
};

struct found_goal
{
};

pathfinder::pathfinder(const std::set<province *> &provinces)
{
	this->implementation = std::make_unique<impl>(provinces);
}

pathfinder::~pathfinder()
{
}

find_trade_path_result pathfinder::find_trade_path(const province *start_province, const province *goal_province) const
{
	return this->implementation->find_trade_path(start_province, goal_province);
}

pathfinder::impl::impl(const std::set<province *> &provinces)
	: provinces(container::to_vector(provinces)), province_graph(provinces.size())
{
	for (size_t i = 0; i < this->provinces.size(); ++i) {
		const province *province = this->provinces[i];
		this->province_to_index[province] = i;
	}

	for (province *province : this->provinces) {
		for (metternich::province *border_province : province->get_border_provinces()) {
			edge e;
			bool inserted;
			boost::tie(e, inserted) = boost::add_edge(this->province_to_index[province], this->province_to_index[border_province], this->province_graph);
		}
	}
}

find_trade_path_result pathfinder::impl::find_trade_path(const province *start_province, const province *goal_province) const
{
	vertex start = this->get_province_index(start_province);
	vertex goal = this->get_province_index(goal_province);

	std::vector<vertex> vertex_predecessors(boost::num_vertices(this->province_graph));
	std::vector<cost> vertex_costs(boost::num_vertices(this->province_graph));

	auto weight_function = boost::make_function_property_map<edge, cost>([this](edge e) {
		return this->get_trade_cost(e);
	});

	try {
		astar_search_tree(this->province_graph, start, trade_path_heuristic<graph, cost>(goal, this->provinces),
			weight_map(weight_function).
			predecessor_map(make_iterator_property_map(vertex_predecessors.begin(), get(boost::vertex_index, this->province_graph))).
			distance_map(make_iterator_property_map(vertex_costs.begin(), get(boost::vertex_index, this->province_graph))).
			visitor(astar_visitor<vertex>(goal)));
	} catch (found_goal) {
		find_trade_path_result result(true);
		for (vertex v = goal;; v = vertex_predecessors[v]) {
			result.path.push_back(this->provinces[v]);
			if (vertex_predecessors[v] == v) {
				break;
			}
		}
		std::reverse(result.path.begin(), result.path.end());
		result.trade_cost = vertex_costs[goal];
		return result;
	}

	return find_trade_path_result(false);
}

pathfinder::impl::cost pathfinder::impl::get_trade_cost(const edge e) const
{
	const province *source_province = this->provinces[e.m_source];
	const province *target_province = this->provinces[e.m_target];

	int trade_cost = source_province->get_kilometers_distance_to(target_province) * 100 / province::base_distance * defines::get()->get_trade_cost_modifier_per_distance() / 100;

	if (source_province->is_water() != target_province->is_water()) {
		trade_cost += defines::get()->get_base_port_trade_cost_modifier();
	}

	return trade_cost;
}

}

max_stars_repo_name: Andrettin/Metternich

max_issues_repo_name: Andrettin/Metternich

max_forks_repo_name: Andrettin/Metternich


text:
#include "common.h"

#include <boost/format.hpp>

#include "config.h"

namespace common
{
    string getElapsedTimeString()
    {
        ostringstream result;
        int et = static_cast<int>(ofGetElapsedTimef());
        auto h = et / 3600;
        auto m = (et % 3600) / 60;
        auto s = et % 60;

        result << boost::format("%02u:%02u:%02u") % h % m % s;

        return result.str();
    }

    // Log levels are (in order of priority):
    //
    // OF_LOG_VERBOSE
    // OF_LOG_NOTICE
    // OF_LOG_WARNING
    // OF_LOG_ERROR
    // OF_LOG_FATAL_ERROR
    // OF_LOG_SILENT
    //
    void log(const string& message, ofLogLevel level)
    {
        ofLogToFile("data/logs/" + Config::getInstance().parameters.camname + ".log", true);
        ofLog(level) << message << endl;

        ofLogToConsole();
        ofLog(level) << message << endl;
    }

    string getTimestamp(const string& time_zone, const string& format_string)
    {
        time_t t = time(nullptr);
        char buf[32];

        sprintf(buf, "TZ=%s", time_zone.c_str());
        setenv("TZ", time_zone.c_str(), 1);

        strftime(buf, sizeof buf, format_string.c_str(), localtime(&t));
        unsetenv("TZ");

        return buf;
    }

    string getTimestampMillis(const string& time_zone, const string& format_string)
    {
        // char buf[32];

        //  sprintf(buf, "TZ=%s", time_zone.c_str());
        setenv("TZ", time_zone.c_str(), 1);
        // get a precise timestamp as a string
        const auto now = std::chrono::system_clock::now();
        const auto nowAsTimeT = std::chrono::system_clock::to_time_t(now);
        const auto nowMs =
            std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000;

        std::stringstream nowSs;
        nowSs << std::put_time(std::localtime(&nowAsTimeT),
                               format_string.c_str() /* "%a %b %d %Y %T"*/)
              << ':' << std::setfill('0') << std::setw(2) << nowMs.count() / 10;

        unsetenv("TZ");
        return nowSs.str();
    }

    /*
     *  ausume t hast yyyy.mm.dd hh:mm:ss format
     *  and the length must be 19 characters.
     */
    int getHours(const string& t)
    {
        size_t l = t.length();
        if (l != 19) return 0;

        size_t idx = t.find(" ");
        if (idx == string::npos) return 0;

        string cumulator{};
        for (size_t i = idx; i < l; ++i) {
            if (t[i] == ':') {
                return stoi(cumulator);
            }

            cumulator += t[i];
        }

        return 0;
    }

    /*
     *  ausume t hast yyyy.mm.dd hh:mm:ss format
     *  and the length must be 19 characters.
     */
    int getSeconds(const string& t)
    {
        size_t l = t.length();
        if (l != 19) return 0;

        size_t idx = t.find(":");
        if (idx == string::npos) return 0;

        string cumulator{};
        for (size_t i = idx + 1; i < l; ++i) {
            if (t[i] == ':') {
                return stoi(cumulator);
            }

            cumulator += t[i];
        }

        return 0;
    }

    // OpenCV uses BGR as its default colour order for images,
    // OF and VideoCapture uses RGB.
    // When you display an image loaded with OpenCv in VideoCapture the channels will
    // be back to front.
    // avoid cvtColor(img, frame, COLOR_BGR2RGB) High CPU Usage.
    void bgr2rgb(cv::Mat& img)
    {
        uchar r, g, b;
        // loop inside the image matrix
        for (int y = 0; y < img.rows; y++) {
            uchar* color = img.ptr<uchar>(y);  // point to first color in row
            uchar* pixel = color;
            for (int x = 0; x < img.cols; x++) {
                // get the BGR color
                b = *color++;
                g = *color++;
                r = *color++;

                // set the RGB color
                *pixel++ = r;
                *pixel++ = g;
                *pixel++ = b;
            }
        }
    }

    Timex::Timex() {}
    Timex::Timex(uint64_t limit) { this->m_limit = limit; }

    void Timex::setLimit(uint64_t limit) { this->m_limit = limit; }
    bool Timex::elapsed()
    {
        m_currentMillis = ofGetElapsedTimeMillis();
        return (m_currentMillis - m_previousMillis >= m_limit);
    }
    void Timex::set() { m_previousMillis = m_currentMillis; }
    void Timex::reset() { m_previousMillis = ofGetElapsedTimeMillis(); }
    string trim(const string& s)
    {
        string::const_iterator it = s.begin();
        while (it != s.end() && isspace(*it)) it++;

        string::const_reverse_iterator rit = s.rbegin();
        while (rit.base() != it && isspace(*rit)) rit++;

        return string(it, rit.base());
    }

    string exec(const char* cmd)
    {
        char buffer[NAME_MAX];
        string result = "";
        FILE* pipe = popen(cmd, "r");
        if (!pipe) throw runtime_error("popen() failed!");
        try {
            while (!feof(pipe)) {
                if (fgets(buffer, 128, pipe) != NULL) result += buffer;
            }
        } catch (...) {
            pclose(pipe);
            throw;
        }
        pclose(pipe);

        return trim(result);
    }
}  // namespace common

max_stars_repo_name: yoosamui/secam

max_issues_repo_name: yoosamui/secam

max_forks_repo_name: yoosamui/secam


text:
//此源码被清华学神尹成大魔王专业翻译分析并修改
//尹成QQ77025077
//尹成微信18510341407
//尹成所在QQ群721929980
//尹成邮箱 yinc13@mails.tsinghua.edu.cn
//尹成毕业于清华大学,微软区块链领域全球最有价值专家
//https://mvp.microsoft.com/zh-cn/PublicProfile/4033620
//版权所有（c）2011-2018比特币核心开发者
//根据MIT软件许可证分发，请参见随附的
//文件复制或http://www.opensource.org/licenses/mit-license.php。

#define BOOST_TEST_MODULE Bitcoin Test Suite

#include <net.h>

#include <memory>

#include <boost/test/unit_test.hpp>

std::unique_ptr<CConnman> g_connman;

[[noreturn]] void Shutdown(void* parg)
{
  std::exit(EXIT_SUCCESS);
}

[[noreturn]] void StartShutdown()
{
  std::exit(EXIT_SUCCESS);
}

bool ShutdownRequested()
{
  return false;
}

max_stars_repo_name: yinchengtsinghua/BitCoinCppChinese

max_issues_repo_name: yinchengtsinghua/BitCoinCppChinese

max_forks_repo_name: yinchengtsinghua/BitCoinCppChinese


text:
// Copyright (c) 2015 Jonas Schnelli
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "bpwalletclient.h"

#include "config/_dbb-config.h"

#include <algorithm>

#include <assert.h>
#include <string.h>

#include "base58.h"
#include "core_io.h"
#include "eccryptoverify.h"
#include "keystore.h"
#include "serialize.h"
#include "streams.h"
#include "pubkey.h"
#include "util.h"
#include "utilstrencodings.h"

#include "libdbb/crypto.h"
#include "dbb_util.h"

#include <boost/filesystem.hpp>

//ignore osx depracation warning
#pragma clang diagnostic ignored "-Wdeprecated-declarations"

#include <climits>

std::string BitPayWalletClient::ReversePairs(std::string const& src)
{
    assert(src.size() % 2 == 0);
    std::string result;
    result.reserve(src.size());

    for (std::size_t i = src.size(); i != 0; i -= 2) {
        result.append(src, i - 2, 2);
    }

    return result;
}

BitPayWalletClient::BitPayWalletClient()
{
    SelectParams(CBaseChainParams::TESTNET);
    baseURL = "https://bws.bitpay.com/bws/api";
}

BitPayWalletClient::~BitPayWalletClient()
{
}

std::vector<std::string> BitPayWalletClient::split(const std::string& str, std::vector<int> indexes)
{
    std::vector<std::string> parts;
    indexes.push_back(str.size());
    int i = 0;
    while (i < indexes.size()) {
        int from = i == 0 ? 0 : indexes[i - 1];
        parts.push_back(str.substr(from, indexes[i] - from));
        i++;
    };
    return parts;
};

std::string BitPayWalletClient::_copayerHash(const std::string& name, const std::string& xPubKey, const std::string& requestPubKey)
{
    return name + "|" + xPubKey + "|" + requestPubKey;
};

std::string BitPayWalletClient::GetXPubKey()
{
    CBitcoinExtPubKey xpubkey;
    xpubkey.SetKey(masterPubKey);
    return xpubkey.ToString();
}
bool BitPayWalletClient::GetCopayerHash(const std::string& name, std::string& out)
{
    if (!requestKey.IsValid())
        return false;

    CBitcoinExtPubKey xpubkey;
    xpubkey.SetKey(masterPubKey);

    std::string requestKeyHex;
    if (!GetRequestPubKey(requestKeyHex))
        return false;

    out = _copayerHash(name, xpubkey.ToString(), requestKeyHex);
    return true;
};

bool BitPayWalletClient::GetCopayerSignature(const std::string& stringToHash, const CKey& privKey, std::string& sigHexOut)
{
    uint256 hash = Hash(stringToHash.begin(), stringToHash.end());
    std::vector<unsigned char> signature;
    privKey.Sign(hash, signature);

    sigHexOut = HexStr(signature);
    return true;
};

void BitPayWalletClient::setMasterPubKey(const std::string& xPubKey)
{
    printf("Set IN Master XPubKey: %s\n", xPubKey.c_str());
    //set the extended public key from the key chain
    CBitcoinExtPubKey b58keyDecodeCheckXPubKey(xPubKey);
    CExtPubKey checkKey = b58keyDecodeCheckXPubKey.GetKey();
    masterPubKey = checkKey;

    SaveLocalData();
}

void BitPayWalletClient::setRequestPubKey(const std::string& xPubKeyRequestKeyEntropy)
{
    CBitcoinExtPubKey b58PubkeyDecodeCheck(masterPubKey);
    printf("Set Master XPubKey: %s\n", b58PubkeyDecodeCheck.ToString().c_str());

    //now this is a ugly workaround because we need a request keypair (pub/priv)
    //for signing the requests after BitAuth
    //Signing over the hardware wallet would be a very bad UX (press button on
    // every request) and it would be slow
    //the request key should be deterministic and linked to the master key
    //
    //we now generate a private key by (miss)using the xpub at m/1'/0' as entropy
    //for a new private key
    CBitcoinExtPubKey requestXPub(xPubKeyRequestKeyEntropy);
    CExtPubKey requestEntropyKey = requestXPub.GetKey();
    std::vector<unsigned char> data;
    data.resize(74);
    requestEntropyKey.Encode(&data[0]);

    CKeyingMaterial vSeed;
    vSeed.resize(32);
    int shift = 0;
    int cnt = 0;
    do {
        memcpy(&vSeed[0], (void*)(&data[0] + shift), 32);
        printf("current hex: %s\n", HexStr(vSeed, false).c_str());
        printf("seed round: %d shift: %d \n", cnt, shift);
        shift++;

        if (shift + 32 >= data.size()) {
            printf("reverse\n");
            shift = 0;
            //might turn into a endless loop
            std::reverse(data.begin(), data.end()); //do some more deterministic byte shuffeling
        }
    } while (!eccrypto::Check(&vSeed[0]));

    requestKey.Set(vSeed.begin(), vSeed.end(), true);

    SaveLocalData();
}

void BitPayWalletClient::seed()
{
    CKeyingMaterial vSeed;
    vSeed.resize(32);

    RandAddSeedPerfmon();
    do {
        GetRandBytes(&vSeed[0], vSeed.size());
    } while (!eccrypto::Check(&vSeed[0]));

    CExtKey masterPrivKeyRoot;
    masterPrivKeyRoot.SetMaster(&vSeed[0], vSeed.size()); //m
    masterPrivKeyRoot.Derive(masterPrivKey, 45);          //m/45' xpriv
    masterPubKey = masterPrivKey.Neuter();                //m/45' xpub

    CExtKey requestKeyChain;
    masterPrivKeyRoot.Derive(requestKeyChain, 1); //m/1'

    CExtKey requestKeyExt;
    requestKeyChain.Derive(requestKeyExt, 0);

    requestKey = requestKeyExt.key;
    printf("seed: request key: %s\n", HexStr(requestKey.begin(), requestKey.end(), false).c_str());
}

bool BitPayWalletClient::GetRequestPubKey(std::string& pubKeyOut)
{
    if (!requestKey.IsValid())
        return false;

    pubKeyOut = HexStr(requestKey.GetPubKey(), false);
    return true;
}

std::string BitPayWalletClient::GetCopayerId()
{
    CBitcoinExtPubKey base58(masterPubKey);
    std::string output = base58.ToString();
    unsigned char rkey[32];
    CSHA256().Write((const unsigned char*)output.c_str(), output.size()).Finalize(rkey);
    return HexStr(rkey, rkey + DBB_SHA256_DIGEST_LENGTH);
}

bool BitPayWalletClient::ParseWalletInvitation(const std::string& walletInvitation, BitpayWalletInvitation& invitationOut)
{
    std::vector<int> splits = {22, 74};
    std::vector<std::string> secretSplit = split(walletInvitation, splits);

    //TODO: var widBase58 = secretSplit[0].replace(/0/g, '');
    std::string widBase58 = secretSplit[0];
    std::vector<unsigned char> vch;
    if (!DecodeBase58(widBase58.c_str(), vch))
        return false;

    std::string widHex = HexStr(vch, false);

    splits = {8, 12, 16, 20};
    std::vector<std::string> walletIdParts = split(widHex, splits);
    invitationOut.walletID = walletIdParts[0] + "-" + walletIdParts[1] + "-" + walletIdParts[2] + "-" + walletIdParts[3] + "-" + walletIdParts[4];

    SelectParams(CBaseChainParams::MAIN);
    std::string walletPrivKeyStr = secretSplit[1];
    CBitcoinSecret vchSecret;
    if (!vchSecret.SetString(walletPrivKeyStr))
        return false;

    SelectParams(CBaseChainParams::TESTNET);
    invitationOut.walletPrivKey = vchSecret.GetKey();
    invitationOut.network = secretSplit[2] == "T" ? "testnet" : "livenet";
    return true;
}

bool BitPayWalletClient::JoinWallet(const std::string& name, const std::string& walletInvitation, std::string& response)
{
    std::string requestPubKey;
    if (!GetRequestPubKey(requestPubKey))
        return false;

    BitpayWalletInvitation invitation;
    if (!ParseWalletInvitation(walletInvitation, invitation))
        return false;

    std::string copayerHash;
    if (!GetCopayerHash(name, copayerHash))
        return false;

    std::string copayerSignature;
    if (!GetCopayerSignature(copayerHash, invitation.walletPrivKey, copayerSignature))
        return false;

    //form request
    UniValue jsonArgs(UniValue::VOBJ);
    jsonArgs.push_back(Pair("walletId", invitation.walletID));
    jsonArgs.push_back(Pair("name", name));
    jsonArgs.push_back(Pair("xPubKey", GetXPubKey()));
    jsonArgs.push_back(Pair("requestPubKey", requestPubKey));
    jsonArgs.push_back(Pair("isTemporaryRequestKey", false));
    jsonArgs.push_back(Pair("copayerSignature", copayerSignature));
    std::string json = jsonArgs.write();

    long httpStatusCode = 0;
    SendRequest("post", "/v1/wallets/" + invitation.walletID + "/copayers", json, response, httpStatusCode);

    std::string getWalletsResponse;
    GetWallets(getWalletsResponse);

    if (httpStatusCode != 200)
        return false;

    return true;
}

bool BitPayWalletClient::GetWallets(std::string& response)
{
    std::string requestPubKey;
    if (!GetRequestPubKey(requestPubKey))
        return false;

    long httpStatusCode = 0;
    SendRequest("get", "/v1/wallets/?r=16354", "{}", response, httpStatusCode);

    if (httpStatusCode != 200)
        return false;

    return true;
}

std::string BitPayWalletClient::ParseTxProposal(const UniValue& txProposal, std::vector<std::pair<std::string, uint256> >& vInputTxHashes)
{
    CMutableTransaction t;
    std::vector<std::string> keys = txProposal.getKeys();
    std::vector<UniValue> values = txProposal.getValues();

    std::string toAddress;
    CAmount toAmount = -1;
    CAmount fee = -1;
    std::vector<int> outputOrder;
    int requiredSignatures = -1;
    int i = 0;
    int j = 0;
    for (i = 0; i < keys.size(); i++) {
        UniValue val = values[i];

        if (keys[i] == "toAddress")
            toAddress = val.get_str();

        if (keys[i] == "amount")
            toAmount = val.get_int64();

        if (keys[i] == "fee")
            fee = val.get_int64();

        if (keys[i] == "outputOrder")
            for (UniValue aVal : val.getValues())
                outputOrder.push_back(aVal.get_int());

        if (keys[i] == "requiredSignatures")
            requiredSignatures = val.get_int();
    }

    UniValue inputsObj = find_value(txProposal, "inputs");
    std::vector<UniValue> inputs = inputsObj.getValues();
    CAmount inTotal = 0;

    CScript checkScript;
    std::vector<std::pair<std::string, CScript> > inputsScriptAndPath;
    for (i = 0; i < inputs.size(); i++) {
        UniValue aInput = inputs[i];
        std::vector<std::string> keys = aInput.getKeys();
        std::vector<UniValue> values = aInput.getValues();

        std::string txId;
        std::vector<CPubKey> publicKeys;
        std::string path;
        CScript script;
        int nInput = -1;

        for (j = 0; j < keys.size(); j++) {
            UniValue val = values[j];
            if (keys[j] == "txid")
                txId = val.get_str();

            if (keys[j] == "vout")
                nInput = val.get_int();

            if (keys[j] == "satoshis")
                inTotal = val.get_int();

            if (keys[j] == "path")
                path = val.get_str();

            if (keys[j] == "publicKeys") {
                std::vector<UniValue> pubKeyValue = val.getValues();
                std::vector<std::string> keys;
                int k;
                for (k = 0; k < pubKeyValue.size(); k++) {
                    UniValue aPubKeyObj = pubKeyValue[k];
                    keys.push_back(aPubKeyObj.get_str());
                }
                std::sort(keys.begin(), keys.end());
                for (k = 0; k < keys.size(); k++) {
                    CPubKey vchPubKey(ParseHex(keys[k]));
                    publicKeys.push_back(vchPubKey);
                }
            }
        }
        uint256 aHash;
        aHash.SetHex(txId);
        script << OP_0 << OP_PUSHDATA1 << OP_VERIFY;
        script += GetScriptForMultisig(requiredSignatures, publicKeys);

        path.erase(0, 2); //remove m/ from path
        inputsScriptAndPath.push_back(std::make_pair(path, GetScriptForMultisig(requiredSignatures, publicKeys)));
        t.vin.insert(t.vin.begin(), CTxIn(aHash, nInput, script));
    }

    UniValue changeAddrObj = find_value(txProposal, "changeAddress");
    keys = changeAddrObj.getKeys();
    values = changeAddrObj.getValues();
    std::string changeAdr = "";
    for (i = 0; i < keys.size(); i++) {
        UniValue val = values[i];

        if (keys[i] == "address")
            changeAdr = val.get_str();
    }

    SelectParams(CBaseChainParams::TESTNET);
    CBitcoinAddress addr(toAddress);
    CBitcoinAddress addrC(changeAdr);
    CScript scriptPubKey = GetScriptForDestination(addr.Get());
    CScript scriptPubKeyC = GetScriptForDestination(addrC.Get());

    CTxOut txout(toAmount, scriptPubKey);
    t.vout.push_back(txout);

    CTxOut txoutC(inTotal - toAmount - fee, scriptPubKeyC);
    if (outputOrder[1] == 0)
        t.vout.insert(t.vout.begin(), txoutC);
    else
        t.vout.push_back(txoutC);

    int cnt = 0;
    for (const CTxIn& txIn : t.vin) {
        std::pair<std::string, CScript> scriptAndPath = inputsScriptAndPath[cnt];
        CScript aScript = scriptAndPath.second;
        uint256 hash = SignatureHash(aScript, t, 0, SIGHASH_ALL);
        vInputTxHashes.push_back(std::make_pair(scriptAndPath.first, hash));
        cnt++;
    }
    std::string hex = EncodeHexTx(t);
    SelectParams(CBaseChainParams::TESTNET);

    return hex;
}

int ecdsa_sig_to_der(const uint8_t* sig, uint8_t* der)
{
    int i;
    uint8_t* p = der, *len, *len1, *len2;
    *p = 0x30;
    p++; // sequence
    *p = 0x00;
    len = p;
    p++; // len(sequence)

    *p = 0x02;
    p++; // integer
    *p = 0x00;
    len1 = p;
    p++; // len(integer)

    // process R
    i = 0;
    while (sig[i] == 0 && i < 32) {
        i++;
    }                     // skip leading zeroes
    if (sig[i] >= 0x80) { // put zero in output if MSB set
        *p = 0x00;
        p++;
        *len1 = *len1 + 1;
    }
    while (i < 32) { // copy bytes to output
        *p = sig[i];
        p++;
        *len1 = *len1 + 1;
        i++;
    }

    *p = 0x02;
    p++; // integer
    *p = 0x00;
    len2 = p;
    p++; // len(integer)

    // process S
    i = 32;
    while (sig[i] == 0 && i < 64) {
        i++;
    }                     // skip leading zeroes
    if (sig[i] >= 0x80) { // put zero in output if MSB set
        *p = 0x00;
        p++;
        *len2 = *len2 + 1;
    }
    while (i < 64) { // copy bytes to output
        *p = sig[i];
        p++;
        *len2 = *len2 + 1;
        i++;
    }

    *len = *len1 + *len2 + 4;
    return *len + 2;
}

bool BitPayWalletClient::PostSignaturesForTxProposal(const UniValue& txProposal, const std::vector<std::string>& vHexSigs)
{
    //parse out the txpid
    UniValue pID = find_value(txProposal, "id");
    std::string txpID = "";
    if (pID.isStr())
        txpID = pID.get_str();

    UniValue signaturesRequest = UniValue(UniValue::VOBJ);
    UniValue sigs = UniValue(UniValue::VARR);
    for (const std::string& sSig : vHexSigs) {
        std::vector<unsigned char> data = ParseHex(sSig);
        unsigned char sig[74];
        int sizeN = ecdsa_sig_to_der(&data[0], sig);
        std::string sSigDER = HexStr(sig, sig + sizeN);
        sigs.push_back(sSigDER);
    }
    signaturesRequest.push_back(Pair("signatures", sigs));
    std::string response;
    long httpStatusCode = 0;
    SendRequest("post", "/v1/txproposals/" + txpID + "/signatures/", signaturesRequest.write(), response, httpStatusCode);
    if (httpStatusCode != 200)
        return false;

    return true;
}

bool BitPayWalletClient::BroadcastProposal(const UniValue& txProposal)
{
    std::string requestPubKey;
    if (!GetRequestPubKey(requestPubKey))
        return false;

    UniValue pID = find_value(txProposal, "id");
    std::string txpID = "";
    if (pID.isStr())
        txpID = pID.get_str();

    std::string response;
    long httpStatusCode = 0;
    SendRequest("post", "/v1/txproposals/" + txpID + "/broadcast/", "{}", response, httpStatusCode);
    printf("Response: %s\n", response.c_str());
    if (httpStatusCode != 200)
        return false;

    return true;
}

std::string BitPayWalletClient::SignRequest(const std::string& method,
                                            const std::string& url,
                                            const std::string& args)
{
    std::string message = method + "|" + url + "|" + args;
    uint256 hash = Hash(message.begin(), message.end());
    std::vector<unsigned char> signature;
    printf("signing message: %s\n", message.c_str());
    requestKey.Sign(hash, signature);
    return HexStr(signature);
};

static size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp)
{
    ((std::string*)userp)->append((char*)contents, size * nmemb);
    return size * nmemb;
}

bool BitPayWalletClient::SendRequest(const std::string& method,
                                     const std::string& url,
                                     const std::string& args,
                                     std::string& responseOut,
                                     long& httpcodeOut)
{
    CURL* curl;
    CURLcode res;

    bool error = false;

    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();
    if (curl) {
        struct curl_slist* chunk = NULL;
        std::string requestPubKey;
        GetRequestPubKey(requestPubKey);
        std::string signature = SignRequest(method, url, args);
        chunk = curl_slist_append(chunk, ("x-identity: " + GetCopayerId()).c_str()); //requestPubKey).c_str());
        chunk = curl_slist_append(chunk, ("x-signature: " + signature).c_str());
        chunk = curl_slist_append(chunk, ("x-client-version: dbb-1.0.0"));
        chunk = curl_slist_append(chunk, "Content-Type: application/json");
        res = curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
        curl_easy_setopt(curl, CURLOPT_URL, (baseURL + url).c_str());
        if (method == "post")
            curl_easy_setopt(curl, CURLOPT_POSTFIELDS, args.c_str());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &responseOut);

#ifdef DBB_ENABLE_DEBUG
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
#endif

        res = curl_easy_perform(curl);
        if (res != CURLE_OK) {
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
            error = true;
        } else {
            curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpcodeOut);
            if (httpcodeOut != 200)
                error = true;
        }

        curl_easy_cleanup(curl);
    }
    curl_global_cleanup();

#ifdef DBB_ENABLE_DEBUG
    printf("response: %s", responseOut.c_str());
#endif

    return error;
};

boost::filesystem::path GetDefaultDBBDataDir()
{
    namespace fs = boost::filesystem;
// Windows < Vista: C:\Documents and Settings\Username\Application Data\Bitcoin
// Windows >= Vista: C:\Users\Username\AppData\Roaming\Bitcoin
// Mac: ~/Library/Application Support/Bitcoin
// Unix: ~/.bitcoin
#ifdef WIN32
    // Windows
    return GetSpecialFolderPath(CSIDL_APPDATA) / "DBB";
#else
    fs::path pathRet;
    char* pszHome = getenv("HOME");
    if (pszHome == NULL || strlen(pszHome) == 0)
        pathRet = fs::path("/");
    else
        pathRet = fs::path(pszHome);
#ifdef MAC_OSX
    // Mac
    pathRet /= "Library/Application Support";
    TryCreateDirectory(pathRet);
    return pathRet / "DBB";
#else
    // Unix
    return pathRet / ".dbb";
#endif
#endif
}

bool BitPayWalletClient::IsSeeded()
{
    if (requestKey.IsValid())
        return true;

    return false;
}

void BitPayWalletClient::SaveLocalData()
{
    if (!requestKey.IsValid())
        return;

    boost::filesystem::path dataDir = GetDefaultDBBDataDir();
    boost::filesystem::create_directories(dataDir);
    FILE* writeFile = fopen((dataDir / "copay.dat").string().c_str(), "wb");
    if (writeFile) {
        CAutoFile copayDatFile(writeFile, SER_DISK, 1);
        copayDatFile << requestKey.GetPrivKey();

        CKeyingMaterial encoded;
        encoded.resize(76);

        CBitcoinExtPubKey b58PubkeyDecodeCheck(masterPubKey);
        printf("Save Master XPubKey: %s\n ", b58PubkeyDecodeCheck.ToString().c_str());

        masterPubKey.Encode(&encoded[0]);
        copayDatFile << encoded;
    }
    fclose(writeFile);
}

void BitPayWalletClient::LoadLocalData()
{
    boost::filesystem::path dataDir = GetDefaultDBBDataDir();
    boost::filesystem::create_directories(dataDir);
    FILE* fh = fopen((dataDir / "copay.dat").string().c_str(), "rb");
    if (fh) {
        CAutoFile copayDatFile(fh, SER_DISK, 1);
        if (!copayDatFile.IsNull()) {
            CPrivKey pkey;
            copayDatFile >> pkey;
            requestKey.SetPrivKey(pkey, true);

            CKeyingMaterial encoded;
            encoded.resize(74);
            copayDatFile >> encoded;

            masterPubKey.Decode(&encoded[0]);

            CBitcoinExtPubKey b58PubkeyDecodeCheck(masterPubKey);
            printf("Load Master XPubKey: %s\n", b58PubkeyDecodeCheck.ToString().c_str());
        }
        fclose(fh);
    }
}

void BitPayWalletClient::RemoveLocalData()
{
    boost::filesystem::path dataDir = GetDefaultDBBDataDir();
    boost::filesystem::remove(dataDir / "copay.dat");
}


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

#include <boost/lexical_cast.hpp>
#include "misc_log_ex.h"
#include "rctOps.h"
using namespace crypto;
using namespace std;

#undef MONEA_DEFAULT_LOG_CATEGORY
#define MONEA_DEFAULT_LOG_CATEGORY "ringct"

#define CHECK_AND_ASSERT_THROW_MES_L1(expr, message) {if(!(expr)) {MWARNING(message); throw std::runtime_error(message);}}

namespace rct {

    //Various key initialization functions

    //initializes a key matrix;
    //first parameter is rows,
    //second is columns
    keyM keyMInit(size_t rows, size_t cols) {
        keyM rv(cols);
        size_t i = 0;
        for (i = 0 ; i < cols ; i++) {
            rv[i] = keyV(rows);
        }
        return rv;
    }

    //Various key generation functions

    //generates a random scalar which can be used as a secret key or mask
    void skGen(key &sk) {
        sk = crypto::rand<key>();
        sc_reduce32(sk.bytes);
    }

    //generates a random scalar which can be used as a secret key or mask
    key skGen() {
        key sk = crypto::rand<key>();
        sc_reduce32(sk.bytes);
        return sk;
    }

    //Generates a vector of secret key
    //Mainly used in testing
    keyV skvGen(size_t rows ) {
        CHECK_AND_ASSERT_THROW_MES(rows > 0, "0 keys requested");
        keyV rv(rows);
        size_t i = 0;
        crypto::rand(rows * sizeof(key), (uint8_t*)&rv[0]);
        for (i = 0 ; i < rows ; i++) {
            sc_reduce32(rv[i].bytes);
        }
        return rv;
    }

    //generates a random curve point (for testing)
    key  pkGen() {
        key sk = skGen();
        key pk = scalarmultBase(sk);
        return pk;
    }

    //generates a random secret and corresponding public key
    void skpkGen(key &sk, key &pk) {
        skGen(sk);
        scalarmultBase(pk, sk);
    }

    //generates a random secret and corresponding public key
    tuple<key, key>  skpkGen() {
        key sk = skGen();
        key pk = scalarmultBase(sk);
        return make_tuple(sk, pk);
    }

    //generates C =aG + bH from b, a is given..
    void genC(key & C, const key & a, xmr_amount amount) {
        key bH = scalarmultH(d2h(amount));
        addKeys1(C, a, bH);
    }

    //generates a <secret , public> / Pedersen commitment to the amount
    tuple<ctkey, ctkey> ctskpkGen(xmr_amount amount) {
        ctkey sk, pk;
        skpkGen(sk.dest, pk.dest);
        skpkGen(sk.mask, pk.mask);
        key am = d2h(amount);
        key bH = scalarmultH(am);
        addKeys(pk.mask, pk.mask, bH);
        return make_tuple(sk, pk);
    }

    //generates a <secret , public> / Pedersen commitment but takes bH as input
    tuple<ctkey, ctkey> ctskpkGen(const key &bH) {
        ctkey sk, pk;
        skpkGen(sk.dest, pk.dest);
        skpkGen(sk.mask, pk.mask);
        addKeys(pk.mask, pk.mask, bH);
        return make_tuple(sk, pk);
    }

    key zeroCommit(xmr_amount amount) {
        key mask = identity();
        mask = scalarmultBase(mask);
        key am = d2h(amount);
        key bH = scalarmultH(am);
        addKeys(mask, mask, bH);
        return mask;
    }

    key commit(xmr_amount amount, const key &mask) {
        key c = scalarmultBase(mask);
        key am = d2h(amount);
        key bH = scalarmultH(am);
        addKeys(c, c, bH);
        return c;
    }

    //generates a random uint long long (for testing)
    xmr_amount randXmrAmount(xmr_amount upperlimit) {
        return h2d(skGen()) % (upperlimit);
    }

    //Scalar multiplications of curve points

    //does a * G where a is a scalar and G is the curve basepoint
    void scalarmultBase(key &aG,const key &a) {
        ge_p3 point;
        sc_reduce32copy(aG.bytes, a.bytes); //do this beforehand!
        ge_scalarmult_base(&point, aG.bytes);
        ge_p3_tobytes(aG.bytes, &point);
    }

    //does a * G where a is a scalar and G is the curve basepoint
    key scalarmultBase(const key & a) {
        ge_p3 point;
        key aG;
        sc_reduce32copy(aG.bytes, a.bytes); //do this beforehand
        ge_scalarmult_base(&point, aG.bytes);
        ge_p3_tobytes(aG.bytes, &point);
        return aG;
    }

    //does a * P where a is a scalar and P is an arbitrary point
    void scalarmultKey(key & aP, const key &P, const key &a) {
        ge_p3 A;
        ge_p2 R;
        CHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&A, P.bytes) == 0, "ge_frombytes_vartime failed at "+boost::lexical_cast<std::string>(__LINE__));
        ge_scalarmult(&R, a.bytes, &A);
        ge_tobytes(aP.bytes, &R);
    }

    //does a * P where a is a scalar and P is an arbitrary point
    key scalarmultKey(const key & P, const key & a) {
        ge_p3 A;
        ge_p2 R;
        CHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&A, P.bytes) == 0, "ge_frombytes_vartime failed at "+boost::lexical_cast<std::string>(__LINE__));
        ge_scalarmult(&R, a.bytes, &A);
        key aP;
        ge_tobytes(aP.bytes, &R);
        return aP;
    }

    //Computes aH where H= toPoint(cn_fast_hash(G)), G the basepoint
    key scalarmultH(const key & a) {
        ge_p3 A;
        ge_p2 R;
        CHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&A, H.bytes) == 0, "ge_frombytes_vartime failed at "+boost::lexical_cast<std::string>(__LINE__));
        ge_scalarmult(&R, a.bytes, &A);
        key aP;
        ge_tobytes(aP.bytes, &R);
        return aP;
    }

    //Curve addition / subtractions

    //for curve points: AB = A + B
    void addKeys(key &AB, const key &A, const key &B) {
        ge_p3 B2, A2;
        CHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&B2, B.bytes) == 0, "ge_frombytes_vartime failed at "+boost::lexical_cast<std::string>(__LINE__));
        CHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&A2, A.bytes) == 0, "ge_frombytes_vartime failed at "+boost::lexical_cast<std::string>(__LINE__));
        ge_cached tmp2;
        ge_p3_to_cached(&tmp2, &B2);
        ge_p1p1 tmp3;
        ge_add(&tmp3, &A2, &tmp2);
        ge_p1p1_to_p3(&A2, &tmp3);
        ge_p3_tobytes(AB.bytes, &A2);
    }

    rct::key addKeys(const key &A, const key &B) {
      key k;
      addKeys(k, A, B);
      return k;
    }

    //addKeys1
    //aGB = aG + B where a is a scalar, G is the basepoint, and B is a point
    void addKeys1(key &aGB, const key &a, const key & B) {
        key aG = scalarmultBase(a);
        addKeys(aGB, aG, B);
    }

    //addKeys2
    //aGbB = aG + bB where a, b are scalars, G is the basepoint and B is a point
    void addKeys2(key &aGbB, const key &a, const key &b, const key & B) {
        ge_p2 rv;
        ge_p3 B2;
        CHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&B2, B.bytes) == 0, "ge_frombytes_vartime failed at "+boost::lexical_cast<std::string>(__LINE__));
        ge_double_scalarmult_base_vartime(&rv, b.bytes, &B2, a.bytes);
        ge_tobytes(aGbB.bytes, &rv);
    }

    //Does some precomputation to make addKeys3 more efficient
    // input B a curve point and output a ge_dsmp which has precomputation applied
    void precomp(ge_dsmp rv, const key & B) {
        ge_p3 B2;
        CHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&B2, B.bytes) == 0, "ge_frombytes_vartime failed at "+boost::lexical_cast<std::string>(__LINE__));
        ge_dsm_precomp(rv, &B2);
    }

    //addKeys3
    //aAbB = a*A + b*B where a, b are scalars, A, B are curve points
    //B must be input after applying "precomp"
    void addKeys3(key &aAbB, const key &a, const key &A, const key &b, const ge_dsmp B) {
        ge_p2 rv;
        ge_p3 A2;
        CHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&A2, A.bytes) == 0, "ge_frombytes_vartime failed at "+boost::lexical_cast<std::string>(__LINE__));
        ge_double_scalarmult_precomp_vartime(&rv, a.bytes, &A2, b.bytes, B);
        ge_tobytes(aAbB.bytes, &rv);
    }

    //addKeys3
    //aAbB = a*A + b*B where a, b are scalars, A, B are curve points
    //A and B must be input after applying "precomp"
    void addKeys3(key &aAbB, const key &a, const ge_dsmp A, const key &b, const ge_dsmp B) {
        ge_p2 rv;
        ge_double_scalarmult_precomp_vartime2(&rv, a.bytes, A, b.bytes, B);
        ge_tobytes(aAbB.bytes, &rv);
    }

    //subtract Keys (subtracts curve points)
    //AB = A - B where A, B are curve points
    void subKeys(key & AB, const key &A, const key &B) {
        ge_p3 B2, A2;
        CHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&B2, B.bytes) == 0, "ge_frombytes_vartime failed at "+boost::lexical_cast<std::string>(__LINE__));
        CHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&A2, A.bytes) == 0, "ge_frombytes_vartime failed at "+boost::lexical_cast<std::string>(__LINE__));
        ge_cached tmp2;
        ge_p3_to_cached(&tmp2, &B2);
        ge_p1p1 tmp3;
        ge_sub(&tmp3, &A2, &tmp2);
        ge_p1p1_to_p3(&A2, &tmp3);
        ge_p3_tobytes(AB.bytes, &A2);
    }

    //checks if A, B are equal in terms of bytes (may say no if one is a non-reduced scalar)
    //without doing curve operations
    bool equalKeys(const key & a, const key & b) {
        bool rv = true;
        for (int i = 0; i < 32; ++i) {
          if (a.bytes[i] != b.bytes[i]) {
            rv = false;
          }
        }
        return rv;
    }

    //Hashing - cn_fast_hash
    //be careful these are also in crypto namespace
    //cn_fast_hash for arbitrary multiples of 32 bytes
    void cn_fast_hash(key &hash, const void * data, const std::size_t l) {
        keccak((const uint8_t *)data, l, hash.bytes, 32);
    }

    void hash_to_scalar(key &hash, const void * data, const std::size_t l) {
        cn_fast_hash(hash, data, l);
        sc_reduce32(hash.bytes);
    }

    //cn_fast_hash for a 32 byte key
    void cn_fast_hash(key & hash, const key & in) {
        keccak((const uint8_t *)in.bytes, 32, hash.bytes, 32);
    }

    void hash_to_scalar(key & hash, const key & in) {
        cn_fast_hash(hash, in);
        sc_reduce32(hash.bytes);
    }

    //cn_fast_hash for a 32 byte key
    key cn_fast_hash(const key & in) {
        key hash;
        keccak((const uint8_t *)in.bytes, 32, hash.bytes, 32);
        return hash;
    }

     key hash_to_scalar(const key & in) {
        key hash = cn_fast_hash(in);
        sc_reduce32(hash.bytes);
        return hash;
     }

    //cn_fast_hash for a 128 byte unsigned char
    key cn_fast_hash128(const void * in) {
        key hash;
        keccak((const uint8_t *)in, 128, hash.bytes, 32);
        return hash;
    }

    key hash_to_scalar128(const void * in) {
        key hash = cn_fast_hash128(in);
        sc_reduce32(hash.bytes);
        return hash;
    }

    //cn_fast_hash for multisig purpose
    //This takes the outputs and commitments
    //and hashes them into a 32 byte sized key
    key cn_fast_hash(const ctkeyV &PC) {
        if (PC.empty()) return rct::hash2rct(crypto::cn_fast_hash("", 0));
        key rv;
        cn_fast_hash(rv, &PC[0], 64*PC.size());
        return rv;
    }

    key hash_to_scalar(const ctkeyV &PC) {
        key rv = cn_fast_hash(PC);
        sc_reduce32(rv.bytes);
        return rv;
    }

   //cn_fast_hash for a key-vector of arbitrary length
   //this is useful since you take a number of keys
   //put them in the key vector and it concatenates them
   //and then hashes them
   key cn_fast_hash(const keyV &keys) {
       if (keys.empty()) return rct::hash2rct(crypto::cn_fast_hash("", 0));
       key rv;
       cn_fast_hash(rv, &keys[0], keys.size() * sizeof(keys[0]));
       //dp(rv);
       return rv;
   }

   key hash_to_scalar(const keyV &keys) {
       key rv = cn_fast_hash(keys);
       sc_reduce32(rv.bytes);
       return rv;
   }

   key cn_fast_hash(const key64 keys) {
      key rv;
      cn_fast_hash(rv, &keys[0], 64 * sizeof(keys[0]));
      //dp(rv);
      return rv;
   }

   key hash_to_scalar(const key64 keys) {
       key rv = cn_fast_hash(keys);
       sc_reduce32(rv.bytes);
       return rv;
   }

    key hashToPointSimple(const key & hh) {
        key pointk;
        ge_p1p1 point2;
        ge_p2 point;
        ge_p3 res;
        key h = cn_fast_hash(hh);
        CHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&res, h.bytes) == 0, "ge_frombytes_vartime failed at "+boost::lexical_cast<std::string>(__LINE__));
        ge_p3_to_p2(&point, &res);
        ge_mul8(&point2, &point);
        ge_p1p1_to_p3(&res, &point2);
        ge_p3_tobytes(pointk.bytes, &res);
        return pointk;
    }

    key hashToPoint(const key & hh) {
        key pointk;
        ge_p2 point;
        ge_p1p1 point2;
        ge_p3 res;
        key h = cn_fast_hash(hh);
        ge_fromfe_frombytes_vartime(&point, h.bytes);
        ge_mul8(&point2, &point);
        ge_p1p1_to_p3(&res, &point2);
        ge_p3_tobytes(pointk.bytes, &res);
        return pointk;
    }

    void hashToPoint(key & pointk, const key & hh) {
        ge_p2 point;
        ge_p1p1 point2;
        ge_p3 res;
        key h = cn_fast_hash(hh);
        ge_fromfe_frombytes_vartime(&point, h.bytes);
        ge_mul8(&point2, &point);
        ge_p1p1_to_p3(&res, &point2);
        ge_p3_tobytes(pointk.bytes, &res);
    }

    //sums a vector of curve points (for scalars use sc_add)
    void sumKeys(key & Csum, const keyV &  Cis) {
        identity(Csum);
        size_t i = 0;
        for (i = 0; i < Cis.size(); i++) {
            addKeys(Csum, Csum, Cis[i]);
        }
    }

    //Elliptic Curve Diffie Helman: encodes and decodes the amount b and mask a
    // where C= aG + bH
    void ecdhEncode(ecdhTuple & unmasked, const key & sharedSec) {
        key sharedSec1 = hash_to_scalar(sharedSec);
        key sharedSec2 = hash_to_scalar(sharedSec1);
        //encode
        sc_add(unmasked.mask.bytes, unmasked.mask.bytes, sharedSec1.bytes);
        sc_add(unmasked.amount.bytes, unmasked.amount.bytes, sharedSec2.bytes);
    }
    void ecdhDecode(ecdhTuple & masked, const key & sharedSec) {
        key sharedSec1 = hash_to_scalar(sharedSec);
        key sharedSec2 = hash_to_scalar(sharedSec1);
        //decode
        sc_sub(masked.mask.bytes, masked.mask.bytes, sharedSec1.bytes);
        sc_sub(masked.amount.bytes, masked.amount.bytes, sharedSec2.bytes);
    }
}


text:
/*
* Copyright (C) 2017 Vrije Universiteit Amsterdam
*
* Licensed under the Apache License, Version 2.0 (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.
*
* Author: Elte Hupkes
*
*/

#include <string>
#include <utility>

#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread/thread.hpp>

#include "BodyAnalyzer.h"

namespace gz = gazebo;

using namespace revolve::gazebo;

void BodyAnalyzer::Load(
        gz::physics::WorldPtr world,
        sdf::ElementPtr /*_sdf*/)
{
    // Store pointer to the world
    world_ = world;

    // Pause the world if it is not already paused
    world->SetPaused(true);

    // Set initial state values
    processing_ = false;
    counter_ = 0;
    currentRequest_ = -1;

    // Create a new transport node for advertising / subscribing
    node_.reset(new gz::transport::Node());
    node_->Init();

    // Subscribe to the contacts message. Note that the contact manager does
    // not generate data without at least one subscriber, so there is no use
    // in bypassing the messaging mechanism.
    contactsSub_ = node_->Subscribe(
            "~/physics/contacts",
            &BodyAnalyzer::OnContacts,
            this);

    // Subscribe to analysis request messages
    requestSub_ = node_->Subscribe(
            "~/request",
            &BodyAnalyzer::AnalyzeRequest,
            this);

    // Since models are added asynchronously, we need some way of detecting
    // our model add. We do this using a model info subscriber.
    modelSub_ = node_->Subscribe(
            "~/model/info",
            &BodyAnalyzer::OnModel,
            this);

    // Publisher for the results
    responsePub_ = node_->Advertise< gz::msgs::Response >("~/response");

    // Subscribe to model delete events
    deleteSub_ = node_->Subscribe(
            "~/response",
            &BodyAnalyzer::OnModelDelete,
            this);

    // Hello world!
    std::cout << "Body analyzer ready" << std::endl;
}

void BodyAnalyzer::OnModel(ConstModelPtr &msg)
{
    std::string expectedName =
            "analyze_bot_" + boost::lexical_cast< std::string >(counter_);
    if (msg->name() not_eq expectedName)
    {
        throw std::runtime_error(
                "INTERNAL ERROR: Expecting model with name '" + expectedName +
                "', created model was '" + msg->name() + "'.");
    }

    if (world_->Models().size() > 1)
    {
        throw std::runtime_error(
                "INTERNAL ERROR: Too many models in analyzer.");
    }

    // Unpause the world so contacts will be handled
    world_->SetPaused(false);
}

void BodyAnalyzer::OnModelDelete(ConstResponsePtr &msg)
{
    if (msg->request() == "entity_delete")
    {
        // This might have cleared the world
        this->ProcessQueue();
    }
}

void BodyAnalyzer::Advance()
{
    processingMutex_.lock();

    // Clear current request to indicate nothing is being
    // processed, and move on to the next item if there is one.
    counter_++;
    processing_ = false;
    currentRequest_ = -1;

    // ProcessQueue needs the processing mutex, release it
    processingMutex_.unlock();
    this->ProcessQueue();
}

void BodyAnalyzer::OnContacts(ConstContactsPtr &msg)
{
    // Pause the world so no new contacts will come in
    world_->SetPaused(true);

    boost::mutex::scoped_lock plock(processingMutex_);
    if (not processing_)
    {
        return;
    }
    plock.unlock();

    if (world_->ModelCount() > 1)
    {
        std::cerr << "WARNING: Too many models in the world." << std::endl;
    }

    // Create a response
    msgs::BodyAnalysisResponse response;
    gz::msgs::Response wrapper;
    wrapper.set_id(currentRequest_);
    wrapper.set_request("analyze_body");

    // Add contact info
    for (const auto &contact : msg->contact())
    {
        auto msgContact = response.add_contact();
        msgContact->set_collision1(contact.collision1());
        msgContact->set_collision2(contact.collision2());
    }

    auto name = "analyze_bot_" + boost::lexical_cast< std::string >(counter_);
    auto model = world_->ModelByName(name);

    if (not model)
    {
        std::cerr << "------------------------------------" << std::endl;
        std::cerr << "INTERNAL ERROR, contact model not found: " << name
                  << std::endl;
        std::cerr << "Please retry this request." << std::endl;
        std::cerr << "------------------------------------" << std::endl;
        wrapper.set_response("error");
        response.SerializeToString(wrapper.mutable_serialized_data());
        responsePub_->Publish(wrapper);

        // Advance manually
        this->Advance();
        return;
    }

    // Add the bounding box to the message
    // Model collision bounding box is currently broken in Gazebo:
    // https://bitbucket.org/osrf/gazebo/issue/1325/getboundingbox-returns-the-models-last
    // My suggested fixes are present in the gazebo6-revolve branch
    auto bbox = model->BoundingBox();
    auto box = response.mutable_boundingbox();
    gz::msgs::Set(box->mutable_min(), bbox.Min());
    gz::msgs::Set(box->mutable_max(), bbox.Max());

    // Publish the message, serializing the response message in the wrapper
    // data
    response.SerializeToString(wrapper.mutable_serialized_data());
    wrapper.set_response("success");
    responsePub_->Publish(wrapper);
    std::cout << "Response for request " << currentRequest_
              << " sent." << std::endl;

    // Remove all models from the world and advance
    world_->Clear();
    this->Advance();
}

void BodyAnalyzer::AnalyzeRequest(ConstRequestPtr &request)
{
    auto request_title = request->request();

    if (request_title not_eq "analyze_body")
    {
        // Request is not meant for us
        return;
    }

    if (not request->has_data())
    {
        std::cerr << "An `analyze_body` request should have data." << std::endl;
        return;
    }

    // Create the request pair before locking the mutex - this seems
    // to prevent threading and "unknown message type" problems.
    std::pair< int, std::string > req(request->id(), request->data());
    std::cout << "Received request " << request->id() << std::endl;

    boost::mutex::scoped_lock lock(queueMutex_);

    if (requests_.size() >= MAX_QUEUE_SIZE)
    {
        std::cerr << "Ignoring request " << request->id()
                  << ": maximum queue size (" << MAX_QUEUE_SIZE << ") reached."
                  << std::endl;
        return;
    }

    // This actually copies the message, but since everything is const
    // we don't really have a choice in that regard. This shouldn't
    // be the performance bottleneck anyway.
    requests_.push(req);

    // Release the lock explicitly to prevent deadlock in ProcessQueue
    lock.unlock();

    this->ProcessQueue();
}

void BodyAnalyzer::ProcessQueue()
{
    // Acquire mutex on queue
    boost::mutex::scoped_lock lock(queueMutex_);

    if (requests_.empty())
    {
        // No requests to handle
        return;
    }

    boost::mutex::scoped_lock plock(processingMutex_);
    if (processing_)
    {
        // Another item is being processed, wait for it
        return;
    }

    if (world_->ModelCount() > 0)
    {
        // There are still some items in the world, wait until
        // `Clear()` has done its job.
        return;
    }

    processing_ = true;

    // Pop one request off the queue and set the
    // currently processed ID on the class
    auto request = requests_.front();
    requests_.pop();

    currentRequest_ = request.first;
    std::cout << "Now handling request: " << currentRequest_ << std::endl;

    // Create model SDF
    sdf::SDF robotSDF;
    robotSDF.SetFromString(request.second);

    // Force the model name to something we know
    std::string name =
            "analyze_bot_" + boost::lexical_cast< std::string >(counter_);
    robotSDF.Root()->GetElement("model")
            ->GetAttribute("name")->SetFromString(name);

    // Insert the model into the world. For clarity we use
    // `InsertModelString` directly, this is actually also what
    // `InsertModelSdf` does.
    world_->InsertModelString(robotSDF.ToString());

    // The contents of the SDF element are *not* cleared automatically
    // when robotSDF goes out of scope.
    // https://bitbucket.org/osrf/sdformat/issues/104/memory-leak-in-element
    robotSDF.Root()->Reset();

    // Analysis will proceed once the model insertion message comes through
}

max_stars_repo_name: MRebolle/Battery-Robot

max_issues_repo_name: Ravi-Bossema/revolve

max_forks_repo_name: Ravi-Bossema/revolve


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

#include "EquiUndistorter.h"

#include <sstream>
#include <fstream>

#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <opencv2/opencv.hpp>
#include <Eigen/Core>
#include <locale.h>

UndistorterEqui::UndistorterEqui()
{
	remapX = nullptr;
	remapY = nullptr;
	valid = false;
}

UndistorterEqui::UndistorterEqui(const char* configFileName)
{

	setlocale(LC_NUMERIC, "C");
	remapX = nullptr;
	remapY = nullptr;
	valid = false;

	// read parameters
	std::ifstream infile(configFileName);
	if (!infile.good())
	{
		printf("Failed to read camera calibration (invalid format?)\nCalibration file: %s\n", configFileName);
		return;
	}

	std::string l1, l2, l3, l4;
	std::getline(infile, l1);
	std::getline(infile, l2);
	std::getline(infile, l3);
	std::getline(infile, l4);

	// l1 & l2
	if (std::sscanf(l1.c_str(), "%f %f %f %f %f %f %f %f", &inputCalibration[0], &inputCalibration[1], &inputCalibration[2], &inputCalibration[3], &inputCalibration[4], &inputCalibration[5], &inputCalibration[6], &inputCalibration[7]) == 8 &&
		std::sscanf(l2.c_str(), "%d %d", &in_width, &in_height) == 2)
	{
		printf("Input resolution: %d %d\n", in_width, in_height);
		printf("Input Calibration (fx fy cx cy | k1 k2 k3 k4): %f %f %f %f | %f %f %f %f\n",
			in_width*inputCalibration[0], in_height*inputCalibration[1], in_width*inputCalibration[2], in_height*inputCalibration[3], inputCalibration[4], inputCalibration[5], inputCalibration[6], inputCalibration[7]);
	}
	else
	{
		printf("Failed to read camera calibration (invalid format?)\nCalibration file: %s\n", configFileName);
		return;
	}

	// l3
	if (std::sscanf(l3.c_str(), "%f %f %f %f", &outputCalibration[0], &outputCalibration[1], &outputCalibration[2], &outputCalibration[3]) == 4)
	{
		printf("Out: %f %f %f\n",
			outputCalibration[0], outputCalibration[1], outputCalibration[2], outputCalibration[3]);
	}
	else
	{
		printf("Out: Failed to Read Output pars... not rectifying.\n");
		return;
	}

	// l4
	if (std::sscanf(l4.c_str(), "%d %d", &out_width, &out_height) == 2)
	{
		printf("Output resolution: %d %d\n", out_width, out_height);
	}
	else
	{
		printf("Out: Failed to Read Output resolution... not rectifying.\n");
		return;
	}

	valid = true;

	// =============================== build rectification map ===============================
	remapX = new float[out_width * out_height];
	remapY = new float[out_width * out_height];
	for (int y = 0; y < out_height; y++)
		for (int x = 0; x < out_width; x++)
		{
			remapX[x + y * out_width] = x;
			remapY[x + y * out_width] = y;
		}
	distortCoordinates(remapX, remapY, out_height*out_width);

	bool hasBlackPoints = false;
	for (int i = 0; i < out_width * out_height; i++)
	{
		if (remapX[i] == 0) remapX[i] = 0.01;
		if (remapY[i] == 0) remapY[i] = 0.01;
		if (remapX[i] == in_width - 1) remapX[i] = in_width - 1.01;
		if (remapY[i] == in_height - 1) remapY[i] = in_height - 1.01;

		if (!(remapX[i] > 0 && remapY[i] > 0 && remapX[i] < in_width - 1 && remapY[i] < in_height - 1))
		{
			//printf("black pixel at %d %d %f %f!\n", i, i, remapX[i], remapY[i]);
			hasBlackPoints = true;
			remapX[i] = -1;
			remapY[i] = -1;

		}
	}

	if (hasBlackPoints)
		printf("\n\nEqui Undistorter: Warning! Image has black pixels.\n\n\n");

	// =============================== set Krect ===============================
	Krect.setIdentity();
	Krect(0, 0) = outputCalibration[0] * out_width;
	Krect(1, 1) = outputCalibration[1] * out_height;
	Krect(0, 2) = outputCalibration[2] * out_width - 0.5;
	Krect(1, 2) = outputCalibration[3] * out_height - 0.5;

	Korg.setIdentity();
	Korg(0, 0) = inputCalibration[0] * in_width;
	Korg(1, 1) = inputCalibration[1] * in_height;
	Korg(0, 2) = inputCalibration[2] * in_width - 0.5;
	Korg(1, 2) = inputCalibration[3] * in_height - 0.5;
}

UndistorterEqui::~UndistorterEqui()
{
	if (remapX != 0) delete[] remapX;
	if (remapY != 0) delete[] remapY;
}

void UndistorterEqui::distortCoordinates(float* in_x, float* in_y, int n)
{
	if (!valid)
	{
		printf("ERROR: invalid UndistorterEqui!\n");
		return;
	}

	float k1 = inputCalibration[4];
	float k2 = inputCalibration[5];
	float k3 = inputCalibration[6];
	float k4 = inputCalibration[7];

	// current camera parameters
	float fx = inputCalibration[0] * in_width;
	float fy = inputCalibration[1] * in_height;
	float cx = inputCalibration[2] * in_width - 0.5;
	float cy = inputCalibration[3] * in_height - 0.5;

	float ofx = outputCalibration[0] * out_width;
	float ofy = outputCalibration[1] * out_height;
	float ocx = outputCalibration[2] * out_width - 0.5f;
	float ocy = outputCalibration[3] * out_height - 0.5f;

	for (int i = 0; i < n; i++)
	{
		float x = in_x[i];
		float y = in_y[i];
		float ix = (x - ocx) / ofx;
		float iy = (y - ocy) / ofy;

		float r = sqrtf(ix * ix + iy * iy);

		float theta = atan(r);
		float theta2 = theta * theta;
		float theta4 = theta2 * theta2;
		float theta6 = theta4 * theta2;
		float theta8 = theta4 * theta4;
		float thetad = theta * (1 + k1 * theta2 + k2 * theta4 + k3 * theta6 + k4 * theta8);
		float scaling = (r > 1e-15) ? thetad / r : 1.0;

		float ox = fx * ix*scaling + cx;
		float oy = fy * iy*scaling + cy;

		in_x[i] = ox;
		in_y[i] = oy;
	}
}

template<typename T>
void UndistorterEqui::undistort(const T* input, float* output, int nPixIn, int nPixOut) const
{
	if (!valid) return;

	if (nPixIn != in_width * in_height)
	{
		printf("ERROR: undistort called with wrong input image dismesions (expected %d pixel, got %d pixel)\n",
			in_width*in_height, nPixIn);
		return;
	}
	if (nPixOut != out_width * out_height)
	{
		printf("ERROR: undistort called with wrong output image dismesions (expected %d pixel, got %d pixel)\n",
			out_width*out_height, nPixOut);
		return;
	}

	for (int idx = 0; idx < out_width*out_height; idx++)
	{
		// get interp. values
		float xx = remapX[idx];
		float yy = remapY[idx];

		if (xx < 0)
			output[idx] = 0;
		else
		{
			// get integer and rational parts
			int xxi = xx;
			int yyi = yy;
			xx -= xxi;
			yy -= yyi;
			float xxyy = xx * yy;

			// get array base pointer
			const T* src = input + xxi + yyi * in_width;

			// interpolate (bilinear)
			output[idx] = xxyy * src[1 + in_width]
				+ (yy - xxyy) * src[in_width]
				+ (xx - xxyy) * src[1]
				+ (1 - xx - yy + xxyy) * src[0];
		}
	}
}
template void UndistorterEqui::undistort<float>(const float* input, float* output, int nPixIn, int nPixOut) const;
template void UndistorterEqui::undistort<unsigned char>(const unsigned char* input, float* output, int nPixIn, int nPixOut) const;


text:
//
// Copyright (c) 2021 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/CPPAlliance/http_proto
//

#ifndef BOOST_HTTP_PROTO_FIELDS_HPP
#define BOOST_HTTP_PROTO_FIELDS_HPP

#include <boost/http_proto/detail/config.hpp>
#include <boost/http_proto/fields_base.hpp>

namespace boost {
namespace http_proto {

#ifndef BOOST_HTTP_PROTO_DOCS
class fields_view;
#endif

/** A modifiable container of HTTP fields

    @par Iterators

    Iterators obtained from @ref fields
    containers are not invalidated when
    the underlying container is modified.
*/
class BOOST_SYMBOL_VISIBLE
    fields
    : public fields_base
{
public:
    /** Constructor

        Default-constructed fields have no
        name-value pairs.
    */
    BOOST_HTTP_PROTO_DECL
    fields() noexcept;

    /** Constructor
    */
    BOOST_HTTP_PROTO_DECL
    fields(fields&& other) noexcept;

    /** Constructor
    */
    BOOST_HTTP_PROTO_DECL
    fields(fields const& other);

    /** Constructor
    */
    BOOST_HTTP_PROTO_DECL
    fields(fields_view_base const& f);

    /** Assignment
    */
    BOOST_HTTP_PROTO_DECL
    fields&
    operator=(fields&& f) noexcept;

    /** Assignment
    */
    BOOST_HTTP_PROTO_DECL
    fields&
    operator=(fields const& f);

    /** Assignment
    */
    BOOST_HTTP_PROTO_DECL
    fields&
    operator=(fields_view const& f);

    //--------------------------------------------
    //
    // Modifiers
    //
    //--------------------------------------------

    /** Clear the contents, but not the capacity
    */
    void
    clear() noexcept
    {
        this->fields_base::clear();
    }

    /** Swap this with another instance
    */
    void
    swap(fields& other) noexcept
    {
        this->fields_base::swap(other);
    }

    /** Swap two instances
    */
    friend
    void
    swap(
        fields& v1,
        fields& v2) noexcept
    {
        v1.swap(v2);
    }
};

} // http_proto
} // boost

#endif


text:
// Copyright 2019, University of Texas at Austin
// Authors: Xuhao Chen <cxh@utexas.edu>
#include "kclique_cuda.h"
#include "galois/Timer.h"
#include "DistBenchStart.h"
#include "galois/DistGalois.h"
#include "llvm/Support/CommandLine.h"
#include <boost/iterator/transform_iterator.hpp>

const char* name = "Kcl";
const char* desc = "Counts the K-Cliques in a graph using BFS extension";
const char* url  = 0;

namespace cll = llvm::cl;
static cll::opt<std::string> filetype(cll::Positional, cll::desc("<filetype: txt,adj,mtx,gr>"), cll::Required);
//static cll::opt<std::string> filename(cll::Positional, cll::desc("<filename: symmetrized graph>"), cll::Required);
static cll::opt<unsigned> k("k", cll::desc("max number of vertices in k-clique (default value 3)"), cll::init(3));
static cll::opt<unsigned> show("s", cll::desc("print out the details"), cll::init(0));
//typedef galois::graphs::LC_CSR_Graph<uint32_t, void>::with_numa_alloc<true>::type ::with_no_lockable<true>::type Graph;
//typedef Graph::GraphNode GNode;

#define USE_DAG
#define USE_SIMPLE
#define USE_BASE_TYPES

#include "util.h"

#ifndef __GALOIS_HET_CUDA__
#define CHUNK_SIZE 256
typedef MGraph Graph;
#include "cpu_mining/vertex_miner.h"

void KclSolverCPU(VertexMiner &miner, EmbeddingList &emb_list) {
	unsigned level = 1;
	while (1) {
		miner.extend_vertex_clique(level, emb_list);
		if (level == k-2) break;
		level ++;
	}
}
#endif

int main(int argc, char** argv) {
	galois::DistMemSys G;
	DistBenchStart(argc, argv, name, desc, url);
	//auto& net = galois::runtime::getSystemNetworkInterface();

	bool need_dag = false;
	#ifdef USE_DAG
	printf("Orientation enabled, using DAG\n");
	need_dag = true;
	#endif
	MGraph graph(need_dag);
	galois::StatTimer Tinitial("GraphReadingTime");
	Tinitial.start();
	read_graph(graph, filetype, inputFile);
	Tinitial.stop();
	assert(k > 2);
	std::cout << "num_vertices " << graph.num_vertices()
		<< " num_edges " << graph.num_edges() << "\n";

	AccType total = 0;
	//ResourceManager rm;
#ifdef __GALOIS_HET_CUDA__
	KclInitGPU(graph, k);
#else
	VertexMiner miner(&graph, k);
	EmbeddingList emb_list;
	emb_list.init(graph, k, need_dag);
#endif
	galois::StatTimer Tcomp("Compute");
	Tcomp.start();
#ifdef __GALOIS_HET_CUDA__
	KclSolverGPU(k, total);
#else
	KclSolverCPU(miner, emb_list);
	total = miner.get_total_count();
#endif
	Tcomp.stop();
	std::cout << "\n\ttotal_num_cliques = " << total << "\n\n";
	//std::cout << "\t" << rm.get_peak_memory() << "\n\n";
	return 0;
}

max_stars_repo_name: bowu/Galois

max_issues_repo_name: bowu/Galois

max_forks_repo_name: bowu/Galois