text:
/**
 * Canary Lib - Canary Project a free 2D game platform
 * Copyright (C) 2020  Lucas Grossi <lucas.ggrossi@gmail.com>
 *
 * 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; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "connection.h"

#include <framework/core/application.h>
#include <framework/core/eventdispatcher.h>

#include <boost/asio.hpp>
#include <memory>

asio::io_service g_ioService;

Connection::Connection() :
    m_readTimer(g_ioService),
    m_writeTimer(g_ioService),
    m_delayedWriteTimer(g_ioService),
    m_resolver(g_ioService),
    m_socket(g_ioService)
{
    m_connected = false;
    m_connecting = false;
}

Connection::~Connection()
{
#ifndef NDEBUG
    assert(!g_app.isTerminated());
#endif
    close();
}

void Connection::poll()
{
    // reset must always be called prior to poll
    g_ioService.reset();
    g_ioService.poll();
}

void Connection::terminate()
{
    g_ioService.stop();
}

void Connection::close()
{
    if (!m_connected && !m_connecting)
        return;

    // flush send data before disconnecting on clean connections
    if (!m_error)
      internalSend(boost::system::error_code());

    m_connecting = false;
    m_connected = false;
    m_connectCallback = nullptr;
    m_errorCallback = nullptr;
    m_recvCallback = nullptr;

    m_resolver.cancel();
    m_readTimer.cancel();
    m_writeTimer.cancel();
    m_delayedWriteTimer.cancel();

    if (m_socket.is_open()) {
        boost::system::error_code ec;
        m_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
        m_socket.close();
    }
}

void Connection::connect(const std::string& host, uint16 port, const std::function<void()>& connectCallback)
{
    m_connected = false;
    m_connecting = true;
    m_error.clear();
    m_connectCallback = connectCallback;

    asio::ip::tcp::resolver::query query(host, stdext::unsafe_cast<std::string>(port));
    m_resolver.async_resolve(query, std::bind(&Connection::onResolve, asConnection(), std::placeholders::_1, std::placeholders::_2));

    m_readTimer.cancel();
    m_readTimer.expires_from_now(boost::posix_time::seconds(static_cast<uint32>(READ_TIMEOUT)));
    m_readTimer.async_wait(std::bind(&Connection::onTimeout, asConnection(), std::placeholders::_1));
}

void Connection::internal_connect(asio::ip::basic_resolver<asio::ip::tcp>::iterator endpointIterator)
{
    m_socket.async_connect(*endpointIterator, std::bind(&Connection::onConnect, asConnection(), std::placeholders::_1));

    m_readTimer.cancel();
    m_readTimer.expires_from_now(boost::posix_time::seconds(static_cast<uint32>(READ_TIMEOUT)));
    m_readTimer.async_wait(std::bind(&Connection::onTimeout, asConnection(), std::placeholders::_1));
}

Wrapper_ptr Connection::getOutputWrapper() {
  if (!m_connected) return nullptr;

  Wrapper_ptr wrapper;
  if (!wrapperList.empty()) {
    wrapper = wrapperList.front();
  }

  // we can't send the data right away, otherwise we could create tcp congestion
  if (!wrapper || wrapper->isWriteLocked()) {
      wrapper = std::make_shared<Wrapper>();
      wrapperList.emplace_back(wrapper);
  }

  return wrapper;
}

void Connection::internalSend(const boost::system::error_code& error)
{
    m_delayedWriteTimer.cancel();

    if (error == asio::error::operation_aborted || !m_connected || wrapperList.empty())
      return;

    Wrapper_ptr wrapper = wrapperList.front();

    wrapper->Finish(xtea);

    asio::async_write(m_socket,
        boost::asio::buffer(wrapper->Buffer(), wrapper->Size() + CanaryLib::WRAPPER_HEADER_SIZE),
        std::bind(&Connection::onWrite, asConnection(), std::placeholders::_1, std::placeholders::_2));

    m_writeTimer.cancel();
    m_writeTimer.expires_from_now(boost::posix_time::seconds(static_cast<uint32>(WRITE_TIMEOUT)));
    m_writeTimer.async_wait(std::bind(&Connection::onTimeout, asConnection(), std::placeholders::_1));
}

void Connection::read(uint16 bytes, const RecvCallback& callback)
{
    if (!m_connected)
        return;

    m_recvCallback = callback;
    asio::async_read(m_socket,
        asio::buffer(m_inputStream.prepare(bytes)),
        std::bind(&Connection::onRecv, asConnection(), std::placeholders::_1, std::placeholders::_2));

    m_readTimer.cancel();
    m_readTimer.expires_from_now(boost::posix_time::seconds(static_cast<uint32>(READ_TIMEOUT)));
    m_readTimer.async_wait(std::bind(&Connection::onTimeout, asConnection(), std::placeholders::_1));
}

void Connection::read_until(const std::string& what, const RecvCallback& callback)
{
    if (!m_connected)
        return;

    m_recvCallback = callback;

    asio::async_read_until(m_socket,
        m_inputStream,
        what,
        std::bind(&Connection::onRecv, asConnection(), std::placeholders::_1, std::placeholders::_2));

    m_readTimer.cancel();
    m_readTimer.expires_from_now(boost::posix_time::seconds(static_cast<uint32>(READ_TIMEOUT)));
    m_readTimer.async_wait(std::bind(&Connection::onTimeout, asConnection(), std::placeholders::_1));
}

void Connection::onResolve(const boost::system::error_code& error, asio::ip::basic_resolver<asio::ip::tcp>::iterator endpointIterator)
{
    m_readTimer.cancel();

    if (error == asio::error::operation_aborted)
        return;

    if (!error)
        internal_connect(endpointIterator);
    else
        handleError(error);
}

void Connection::onConnect(const boost::system::error_code& error)
{
    m_readTimer.cancel();
    m_activityTimer.restart();

    if (error == asio::error::operation_aborted)
        return;

    if (!error) {
        m_connected = true;

        // disable nagle's algorithm, this make the game play smoother
        boost::asio::ip::tcp::no_delay option(true);
        m_socket.set_option(option);

        if (m_connectCallback)
            m_connectCallback();
    }
    else
        handleError(error);

    m_connecting = false;
}

void Connection::onCanWrite()
{
  if (!m_connected) return;
  m_delayedWriteTimer.cancel();
  m_delayedWriteTimer.expires_from_now(boost::posix_time::milliseconds(0));
  m_delayedWriteTimer.async_wait(std::bind(&Connection::internalSend, asConnection(), std::placeholders::_1));
}

void Connection::onWrite(const boost::system::error_code& error, size_t)
{
    m_writeTimer.cancel();

    if (error == asio::error::operation_aborted)
        return;

    if (!wrapperList.empty()) {
      wrapperList.pop_front();
    }

    if (m_connected && error)
        handleError(error);
}

void Connection::onRecv(const boost::system::error_code& error, size_t recvSize)
{
    m_readTimer.cancel();
    m_activityTimer.restart();

    if (error == asio::error::operation_aborted)
        return;

    if (m_connected) {
        if (!error) {
            if (m_recvCallback) {
                const char* header = boost::asio::buffer_cast<const char*>(m_inputStream.data());
                m_recvCallback((uint8*)header, recvSize);
            }
        }
        else
            handleError(error);
    }

    if (!error)
        m_inputStream.consume(recvSize);
}

void Connection::onTimeout(const boost::system::error_code& error)
{
    if (error == asio::error::operation_aborted)
        return;

    handleError(asio::error::timed_out);
}

void Connection::handleError(const boost::system::error_code& error)
{
    if (error == asio::error::operation_aborted)
        return;

    m_error = error;
    if (m_errorCallback)
        m_errorCallback(error);
    if (m_connected || m_connecting)
        close();
}

int Connection::getIp()
{
    boost::system::error_code error;
    const boost::asio::ip::tcp::endpoint ip = m_socket.remote_endpoint(error);
    if (!error)
        return boost::asio::detail::socket_ops::host_to_network_long(ip.address().to_v4().to_ulong());

    g_logger.error("Getting remote ip");
    return 0;
}

max_stars_repo_name: Costallat/canary-client

max_issues_repo_name: Costallat/canary-client

max_forks_repo_name: CanaryProject/canary-client


text:
/*
 * Copyright (c) 2020, Robobrain.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * 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.
 *     * Neither the name of the Willow Garage, Inc. 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 OWNER 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.
 */

/* Author: Konstantinos Konstantinidis */

#pragma once
#include <ros/ros.h>
#include "l_shape_tracker.hpp"
#include <Eigen/Dense>
#include <tf/transform_listener.h>
#include <visualization_msgs/Marker.h>
#include "datmo/Track.h"
#include <tf2/LinearMath/Quaternion.h>
#include <tf2_geometry_msgs/tf2_geometry_msgs.h>
#include <vector>

using namespace Eigen;

typedef std::pair<double, double> Point;
typedef std::vector<Point> pointList;

class Cluster {
public:

  Cluster(unsigned long int id, const pointList&, const double&, const std::string&, const tf::Transform& ego_pose);

  std::string frame_name;
  Point ego_coordinates;

  datmo::Track msg_track_box_kf;

  unsigned long int id; //identifier for the cluster
  unsigned long int age; //age of the cluster
  float r, g, b, a; //color of the cluster

  visualization_msgs::Marker getBoundingBoxCenterVisualisationMessage();
  visualization_msgs::Marker getClosestCornerPointVisualisationMessage();
  visualization_msgs::Marker getClusterVisualisationMessage();
  visualization_msgs::Marker getLineVisualisationMessage();
  visualization_msgs::Marker getArrowVisualisationMessage();
  visualization_msgs::Marker getThetaL2VisualisationMessage();
  visualization_msgs::Marker getThetaL1VisualisationMessage();
  visualization_msgs::Marker getThetaBoxVisualisationMessage();
  visualization_msgs::Marker getBoundingBoxVisualisationMessage();
  visualization_msgs::Marker getBoxModelKFVisualisationMessage();
  visualization_msgs::Marker getLShapeVisualisationMessage();
  visualization_msgs::Marker getBoxSolidVisualisationMessage();

  void update(const pointList&, const double dt, const tf::Transform& ego_pose);

  std::pair<double, double> mean() { return mean_values; }; //Return mean of cluster.
  double meanX() { return mean_values.first; };
  double meanY() { return mean_values.second;};

  LshapeTracker Lshape;

  double old_thetaL1;
  double L1, L2, thetaL1, thetaL2;
  double cx, cy, cvx, cvy, L1_box, L2_box, th, psi, comega, length_box, width_box;
  double x_ukf,  y_ukf, vx_ukf,  vy_ukf, omega_ukf;

private:

  pointList new_cluster;
  std::vector<Point> corner_list;
  tf2::Quaternion quaternion; //used for transformations between quaternions and angles
  std::vector<Point> l1l2; //save coordinates of the three points that define the lines

  // mean value of the cluster
  std::pair<double, double> mean_values;
  std::pair<double, double> previous_mean_values;

  Point closest_corner_point;

  visualization_msgs::Marker boxcenter_marker_;
  void populateTrackingMsgs(const double& dt);
  void calcMean(const pointList& ); //Find the mean value of the cluster
  void rectangleFitting(const pointList& ); //Search-Based Rectangle Fitting
  double areaCriterion(const VectorXd&, const VectorXd& );
  double closenessCriterion(const VectorXd& ,const VectorXd&, const double& );
  Point lineIntersection(double& , double& , double& , double& , double& , double& );
  double perpendicularDistance(const Point&, const Point&, const Point&);
  void ramerDouglasPeucker(const std::vector<Point>&, double, std::vector<Point>&);
};

ext: hpp

max_stars_repo_name: kostaskonkk/datmo

max_issues_repo_name: NamDinhRobotics/datmo

max_forks_repo_name: NamDinhRobotics/datmo


text:
// Copyright (c) 2017-2018 The Infinex Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "stdafx.h"
#include "actualtrade.h"
#include "orderbook.h"
#include "tradepair.h"
#include "userbalance.h"
#include "usertrade.h"

#include <boost/multiprecision/cpp_int.hpp>
#include <chrono>

class CUserTrade;
class CUserTradeSetting;
class CUserTradeManager;

std::map<int, PairBidAskCUserTrade> mapUserTradeRequest; //trade pair and bid ask data
CUserTradeManager userTradeManager;

bool CUserTrade::VerifyUserSignature()
{
	return true;
}

bool CUserTrade::VerifyMNSignature()
{
	return true;
}

bool CUserTrade::MNSign()
{
	return true;
}

void CUserTrade::RelayTo(CNode* node, CConnman& connman)
{

}

void CUserTrade::RelayToHandler(CConnman& connman)
{

}

uint64_t CUserTradeManager::GetAdjustedTime()
{
	return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
}

uint64_t CUserTradeManager::GetBidRequiredAmount(uint64_t Price, uint64_t Qty, int TradeFee)
{
	//overflow prevention
	boost::multiprecision::uint128_t amount = Price * Qty * 10000 / (10000 + TradeFee);
	return (uint64_t)amount;
}

uint64_t CUserTradeManager::GetAskExpectedAmount(uint64_t Price, uint64_t Qty, int TradeFee)
{
	//overflow prevention
	boost::multiprecision::uint128_t amount = Price * Qty * 10000 / (10000 - TradeFee);
	return (uint64_t)amount;
}

bool CUserTradeManager::IsSubmittedBidAmountValid(CUserTrade userTrade, int nTradeFee)
{
	uint64_t ExpectedAmount = GetBidRequiredAmount(userTrade.nPrice, userTrade.nQuantity, nTradeFee);
	if ((ExpectedAmount - 1) <= userTrade.nAmount <= (ExpectedAmount + 1))
		return true;
	return false;
}

bool CUserTradeManager::IsSubmittedAskAmountValid(CUserTrade userTrade, int nTradeFee)
{
	uint64_t ExpectedAmount = GetAskExpectedAmount(userTrade.nPrice, userTrade.nQuantity, nTradeFee);
	if ((ExpectedAmount - 1) <= userTrade.nAmount <= (ExpectedAmount + 1))
		return true;
	return false;
}

//change to enum for more return info
bool CUserTradeManager::IsSubmittedBidValid(CUserTrade UserTrade, CTradePair TradePair)
{
	if (TradePair.nTradePairID != UserTrade.nTradePairID)
		return false;

	if (UserTrade.nAmount < TradePair.nMaximumTradeAmount)
		return false;

	if (UserTrade.nAmount > TradePair.nMaximumTradeAmount)
		return false;

	if (!IsSubmittedBidAmountValid(UserTrade, TradePair.nBidTradeFee))
		return false;

	return true;
}

//change to enum for more return info
bool CUserTradeManager::IsSubmittedAskValid(CUserTrade UserTrade, CTradePair TradePair)
{
	if (TradePair.nTradePairID != UserTrade.nTradePairID)
		return false;

	if (UserTrade.nAmount < TradePair.nMaximumTradeAmount)
		return false;

	if (UserTrade.nAmount > TradePair.nMaximumTradeAmount)
		return false;

	if (!IsSubmittedAskAmountValid(UserTrade, TradePair.nAskTradeFee))
		return false;

	return true;
}

//to convert into enum return
void CUserTradeManager::UserSellRequest(CUserTrade userTrade)
{
	CTradePair tradePair = tradePairManager.GetTradePair(userTrade.nTradePairID);
	if (tradePair.nTradePairID != userTrade.nTradePairID)
		return;

	std::shared_ptr<CUserTrade> cut = std::make_shared<CUserTrade>(userTrade);
	MapPriceCUserTrade mpcut;
	MapPubKeyCUserTrade mucut;

	std::map<int, PairBidAskCUserTrade>::iterator it = mapUserTradeRequest.find(cut->nTradePairID);
	if (it != mapUserTradeRequest.end())
	{
		if (!IsSubmittedAskValid(userTrade, tradePair))
			return;

		userbalance_to_exchange_enum_t result = userBalanceManager.BalanceToExchange(tradePair.nCoinID1, cut->nUserPubKey, cut->nAmount);
		if (result != USER_BALANCE_DEDUCTED)
		{
			//we should not be here
			//for future user banning
			return;
		}

		MapPriceCUserTrade buySideRequest = it->second.first.first;
		MapPriceCUserTrade::reverse_iterator itBuySideRequest = buySideRequest.rbegin();
		while (itBuySideRequest != buySideRequest.rend())
		{
			if (cut->nQuantity == 0)
			{
				return;
			}

			if (itBuySideRequest->first >= cut->nPrice)
			{
				for (int i = 0; i < itBuySideRequest->second.size(); i++)
				{
					std::shared_ptr<CUserTrade> ExistingTrade = itBuySideRequest->second[i].second;
					int qty = 0;
					if (cut->nBalanceQty <= ExistingTrade->nBalanceQty)
					{
						qty = cut->nBalanceQty;
					}
					else
					{
						qty = ExistingTrade->nBalanceQty;
					}

					if (qty <= 0)
					{
						//should not be here, let's think what should we do
					}

					ExistingTrade->nBalanceQty -= qty;
					cut->nBalanceQty -= qty;
					int bidTradeFee = (ExistingTrade->nTradeFee < tradePair.nBidTradeFee) ? ExistingTrade->nTradeFee : tradePair.nBidTradeFee;
					int askTradeFee = (cut->nTradeFee < tradePair.nAskTradeFee) ? cut->nTradeFee : tradePair.nAskTradeFee;
					uint64_t bidAmount = GetBidRequiredAmount(ExistingTrade->nPrice, qty, bidTradeFee);
					uint64_t askAmount = GetAskExpectedAmount(cut->nPrice, qty, askTradeFee);
					uint64_t actualAmount = cut->nPrice*qty;
					//userBalanceManager.UpdateAfterTradeBalance(ExistingTrade->nUserPubKey, cut->nUserPubKey, tradePair.nCoinInfoID1, tradePair.nCoinInfoID2, -bidAmount, qty, -qty, askAmount);
					orderBookManager.AdjustAskQuantity(tradePair.nTradePairID, ExistingTrade->nPrice, qty);
					//actualTradeManager.InputNewCompletedTrade(CActualTrade(ExistingTrade->nUserPubKey, cut->nUserPubKey, tradePair.nTradePairID, ExistingTrade->nPrice, qty, actualAmount, bidAmount - actualAmount, tradePair.nBidTradeFeeCoinID, actualAmount - askAmount, tradePair.nAskTradeFeeCoinID, "", GetAdjustedTime()));
					if (cut->nBalanceQty == 0)
						return;
				}
				++itBuySideRequest;
			}
			else
			{
				break;
			}
		}

		PairPricePubKeyCUserTrade sellSidePairPricePubKeyContainer = it->second.second;
		mpcut = sellSidePairPricePubKeyContainer.first;
		mucut = sellSidePairPricePubKeyContainer.second;

		if (mpcut.count(cut->nPrice))
		{
			mapUserTradeRequest[cut->nTradePairID].second.first[cut->nPrice].push_back(std::make_pair(cut->nUserTradeID, cut));
		}
		else
		{
			std::vector<PairSignatureUserTrade> vecCut;
			vecCut.push_back(std::make_pair(cut->nUserTradeID, cut));
			mapUserTradeRequest[cut->nTradePairID].second.first.insert(std::make_pair(cut->nPrice, vecCut));
		}
		if (mucut.count(cut->nUserPubKey))
		{
			mapUserTradeRequest[cut->nTradePairID].second.second[cut->nUserPubKey].push_back(std::make_pair(cut->nUserTradeID, cut));
		}
		else
		{
			std::vector<PairSignatureUserTrade> vecCut;
			vecCut.push_back(std::make_pair(cut->nUserTradeID, cut));
			mapUserTradeRequest[cut->nTradePairID].second.second.insert(std::make_pair(cut->nUserPubKey, vecCut));
		}
	}
	else
	{
		//for testing purpose
		//to remove on actual implementation
		std::vector<PairSignatureUserTrade> vecCut;
		vecCut.push_back(std::make_pair(cut->nUserTradeID, cut));
		mpcut.insert(std::make_pair(cut->nPrice, vecCut));
		mucut.insert(std::make_pair(cut->nUserPubKey, vecCut));
		PairPricePubKeyCUserTrade sellSide = std::make_pair(mpcut, mucut);

		MapPriceCUserTrade mpcut2;
		MapPubKeyCUserTrade mucut2;
		PairPricePubKeyCUserTrade buySide = std::make_pair(mpcut2, mucut2);

		mapUserTradeRequest.insert(std::make_pair(cut->nTradePairID, std::make_pair(buySide, sellSide)));
	}
}

//to convert into enum return
void CUserTradeManager::UserBuyRequest(CUserTrade userTrade)
{
	int BuySideCoinID = tradePairManager.GetBidSideCoinID(userTrade.nTradePairID);
	if (BuySideCoinID < 0)
		return;

	//to shift into if loop after remove else on actual implementation
	std::shared_ptr<CUserTrade> cut = std::make_shared<CUserTrade>(userTrade);
	MapPriceCUserTrade mpcut;
	MapPubKeyCUserTrade mucut;

	std::map<int, PairBidAskCUserTrade>::iterator it = mapUserTradeRequest.find(cut->nTradePairID);
	if (it != mapUserTradeRequest.end())
	{
		userbalance_to_exchange_enum_t result = userBalanceManager.BalanceToExchange(BuySideCoinID, cut->nUserPubKey, cut->nAmount);
		if (result != USER_BALANCE_DEDUCTED)
		{
			//we should not be here
			//for future user banning
			return;
		}

		MapPriceCUserTrade sellSideRequest = it->second.first.first;
		MapPriceCUserTrade::iterator itSellSideRequest = sellSideRequest.begin();
		while (itSellSideRequest != sellSideRequest.end())
		{
			if (itSellSideRequest->first <= cut->nPrice)
			{
				for (int i = 0; i < itSellSideRequest->second.size(); i++)
				{
					std::shared_ptr<CUserTrade> ExistingTrade = itSellSideRequest->second[i].second;
					if (cut->nBalanceQty <= ExistingTrade->nBalanceQty)
					{
						int qty = cut->nBalanceQty;
						ExistingTrade->nBalanceQty -= qty;
						cut->nBalanceQty -= qty;
						return;
					}
					else
					{
						int qty = ExistingTrade->nBalanceQty;
						ExistingTrade->nBalanceQty -= qty;
						cut->nBalanceQty -= qty;
					}
				}
				++itSellSideRequest;
			}
			else
			{
				break;
			}
		}

		PairPricePubKeyCUserTrade buySidePairPricePubKeyContainer = it->second.first;
		mpcut = buySidePairPricePubKeyContainer.first;
		mucut = buySidePairPricePubKeyContainer.second;

		if (mpcut.count(cut->nPrice))
		{
			mapUserTradeRequest[cut->nTradePairID].first.first[cut->nPrice].push_back(std::make_pair(cut->nUserTradeID, cut));
		}
		else
		{
			std::vector<PairSignatureUserTrade> vecCut;
			vecCut.push_back(std::make_pair(cut->nUserTradeID, cut));
			mapUserTradeRequest[cut->nTradePairID].first.first.insert(std::make_pair(cut->nPrice, vecCut));
		}
		if (mucut.count(cut->nUserPubKey))
		{
			mapUserTradeRequest[cut->nTradePairID].first.second[cut->nUserPubKey].push_back(std::make_pair(cut->nUserTradeID, cut));
		}
		else
		{
			std::vector<PairSignatureUserTrade> vecCut;
			vecCut.push_back(std::make_pair(cut->nUserTradeID, cut));
			mapUserTradeRequest[cut->nTradePairID].first.second.insert(std::make_pair(cut->nUserPubKey, vecCut));
		}
	}
	else
	{
		//for testing purpose
		//to remove on actual implementation
		std::vector<PairSignatureUserTrade> vecCut;
		vecCut.push_back(std::make_pair(cut->nUserTradeID, cut));
		mpcut.insert(std::make_pair(cut->nPrice, vecCut));
		mucut.insert(std::make_pair(cut->nUserPubKey, vecCut));
		PairPricePubKeyCUserTrade buySide = std::make_pair(mpcut, mucut);

		MapPriceCUserTrade mpcut2;
		MapPubKeyCUserTrade mucut2;
		PairPricePubKeyCUserTrade sellSide = std::make_pair(mpcut2, mucut2);

		mapUserTradeRequest.insert(std::make_pair(cut->nTradePairID, std::make_pair(buySide, sellSide)));
	}
}

ext: cpp

max_stars_repo_name: frkl/Infinex

max_issues_repo_name: frkl/Infinex

max_forks_repo_name: frkl/Infinex


text:
#include <iostream>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/connected_components.hpp>
#include <boost/graph/filtered_graph.hpp>

namespace boost {
	enum vertex_component_t { vertex_component = 1111111 };
	BOOST_INSTALL_PROPERTY(vertex, component);
}

using namespace boost;

template <typename ComponentMap>
struct vertexComponent {

	vertexComponent() {}

	vertexComponent(ComponentMap component, int f_component) : m_component(component), m_f_component(f_component) {}

	template <typename Vertex>
	bool operator()(const Vertex& v) const {
		return (get(m_component, v) == m_f_component);
	}

	ComponentMap m_component;
	int m_f_component;
};

int main(int argc, char ** argv) {

	typedef adjacency_list<vecS, vecS, undirectedS, property<vertex_component_t, int> > Graph;

	typedef property_map<Graph, vertex_component_t>::type ComponentMap;
	typedef filtered_graph<Graph, keep_all,	vertexComponent<ComponentMap> > FilteredGraph;

	graph_traits < Graph >::vertex_iterator vi, vi_end;
	graph_traits < Graph >::out_edge_iterator oei, oei_end;
	graph_traits < FilteredGraph >::vertex_iterator fvi, fvi_end;
	graph_traits < FilteredGraph >::out_edge_iterator foei, foei_end;

	Graph * g;
	FilteredGraph * fg;

	enum { A, B, C, D, E, F, G, H, I, N };
	const char* name = "ABCDEFGHI";
	g = new Graph(N);
	add_edge(A, B, *g);
	add_edge(C, D, *g);
	add_edge(D, E, *g);
	add_edge(E, C, *g);
	add_edge(F, A, *g);
	add_edge(F, B, *g);
	add_edge(G, H, *g);
	add_edge(G, I, *g);
	add_edge(H, I, *g);

	std::cout<<std::endl<<"Graph out-edges:"<<std::endl;
	for (tie(vi, vi_end) = vertices(*g); vi != vi_end; ++vi) {
		std::cout<<name[*vi]<<" outedges - ";
		for(tie(oei, oei_end)=out_edges(*vi, *g); oei != oei_end; ++oei) {
			std::cout<<name[source(*oei, *g)]<<"-->"<<name[target(*oei, *g)]<<"  ";
		}
		std::cout<<std::endl;
	}
	std::cout<<std::endl;

	int numComponents = connected_components(*g, get(vertex_component, *g));

	std::cout<<"Graph has "<<numComponents<<" components."<<std::endl<<std::endl;

	for(int i=0; i<numComponents; i++) {
		keep_all efilter;
		vertexComponent<ComponentMap> vfilter(get(vertex_component, *g), i);
		fg = new FilteredGraph(*g, efilter, vfilter);

		std::cout<<"Filtered graph (component "<<i<<") out-edges:"<<std::endl;
		for (tie(fvi, fvi_end) = vertices(*fg); fvi != fvi_end; ++fvi) {
			std::cout<<name[*fvi]<<" outedges - ";
			for(tie(foei, foei_end)=out_edges(*fvi, *fg); foei != foei_end; ++foei) {
				std::cout<<name[source(*foei, *fg)]<<"-->"<<name[target(*foei, *fg)]<<"  ";
			}
			std::cout<<std::endl;
		}
		std::cout<<std::endl;

		delete fg;
		fg = NULL;
	}

	delete g;
	g = NULL;

	return EXIT_SUCCESS;
}

max_stars_repo_name: preciserobot/rex

max_issues_repo_name: preciserobot/rex

max_forks_repo_name: preciserobot/rex


text:
#ifndef PLUGIN_P_SERIAL_IPP
#define PLUGIN_P_SERIAL_IPP

// Ourselves:
#include <Plugin/P.hpp>

// Third Party:
// - Boost:
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/base_object.hpp>

namespace plugin {

  template <class Archive>
  void P::serialize(Archive & ar_, const unsigned int version_)
  {
    ar_ & boost::serialization::make_nvp("xy__A", boost::serialization::base_object<xy::A>(*this));
    ar_ & boost::serialization::make_nvp("val2", _val2_);
    return;
  }

}

#endif // PLUGIN_P_SERIAL_IPP


text:
#include "Drawing/GLRenderWindow.h"

#include <boost/filesystem.hpp>
#include <iostream>
#include <string>

int main()
{
#ifdef TOY_WORKING_DIR
    boost::filesystem::current_path(TOY_WORKING_DIR);
#endif
    std::cout << "Hello Shaders!" << std::endl;
    std::cout << "Working Directory: " << boost::filesystem::current_path() << std::endl;

    GLRenderWindow glRenderWindow;

    if (glRenderWindow.GLInit())
    {
        glRenderWindow.AddAllRenderables();
        while (!glRenderWindow.GetShouldClose())
        {
            // Will also update the internal state of our window so needs to go at the start of the frame.
            glRenderWindow.NewFrame();

            // Update anything we want to update between frames.

            // Do the actual render.
            glRenderWindow.Render();
        }
    }

    glRenderWindow.GLCleanUp();

    return 0;
}

max_stars_repo_name: drmattsuu/ShaderToyOpenGL

max_issues_repo_name: drmattsuu/ShaderToyOpenGL

max_forks_repo_name: drmattsuu/ShaderToyOpenGL


text:
/**
 * BCL to FASTQ file converter
 * Copyright (c) 2007-2017 Illumina, Inc.
 *
 * This software is covered by the accompanying EULA
 * and certain third party copyright/licenses, and any user of this
 * source file is bound by the terms therein.
 *
 * \file FastqCreator.hh
 *
 * \brief Declaration of FASTQ creator.
 *
 * \author Marek Balint
 * \author Mauricio Varea
 */

#ifndef BCL2FASTQ_CONVERSION_FASTQCREATOR_HH
#define BCL2FASTQ_CONVERSION_FASTQCREATOR_HH

#include "layout/Layout.hh"
#include "stats/TileStats.hpp"
#include "stats/BarcodeHits.hh"
#include "data/BclBuffer.hh"
#include "conversion/FastqBuffer.hh"
#include "conversion/Stage.hh"
#include "conversion/Task.hh"
#include "conversion/FastqIterator.hh"
#include "conversion/AdapterLocator.hh"
#include "conversion/SampleIndex.hh"

#include <boost/ptr_container/ptr_vector.hpp>

namespace bcl2fastq
{

namespace io
{
    class GzipCompressor;
}

namespace conversion
{

class FastqCreateTaskManager;

/// \brief BaseCalling statistics (one per tile, sample, barcode).
typedef std::pair< stats::TileBarcodeStats,
                   std::vector<stats::ReadBarcodeStats> > ConversionStats;

// First index is tile, second is sample, third is barcode
typedef std::vector<std::vector<std::vector<ConversionStats>>> ConversionStatsForSampleTileBarcode;

typedef ConversionStatsForSampleTileBarcode::value_type ConversionStatsForTileBarcode;

// There will be 1 of these objects for every processing thread.
struct AllConversionStats : private boost::noncopyable
{
    AllConversionStats(ConversionStatsForSampleTileBarcode& summaryConversionStats,
                       stats::BarcodeHits& summaryUnknownBarcodes);

    // Record to the summary stats in the destructor
    ~AllConversionStats();

private:
    ConversionStatsForSampleTileBarcode& summaryConversionStats_;
    stats::BarcodeHits& summaryUnknownBarcodes_;

public:
    ConversionStatsForSampleTileBarcode conversionStats_;
    stats::BarcodeHits unknownBarcodes_;
};

// Stats for all tasks (index is task number)
    typedef std::vector<std::shared_ptr<AllConversionStats>> FastqCreateStats;

    typedef std::shared_ptr<FastqCreateStats> FastqCreateStatsPtr;

/// \brief Task: Convert BCLs to FASTQs.
template<common::NumBasesPerByte numBasesPerByte>
class FastqCreateTask : public Task
{
public:

    /// \brief Constructor.
    /// \param bclBuffer BCL buffer.
    /// \param cyclesBegin Beginning of BCL cycles to process.
    /// \param cyclesEnd End of BCL cycles to process.
    /// \param flowcellInfo Flowcell meta data.
    /// \param laneInfo Lane meata data.
    /// \param readInfo Read meta data.
    /// \param offsetNumber Offset number.
    /// \param offsetsBegin Beginning of FASTQ offsets range.
    /// \param offsetsEnd End of FASTQ offsets range.
    /// \param maskShortAdapterReads Maximum number of useful bases in read after adapter trimming for which whole read is masked.
    /// \param adapterStringency Adapter stringency.
    /// \param maskAdapters Mask adapters.
    /// \param trimAdapters Trim adapters.
    /// \param generateReverseComplementFastqs Generate reverse complement FASTQs flag.
    /// \param includeNonPfClusters Include non-PF clusters in created FASTQ files flag.
    /// \param layout Flowcell layout.
    /// \param useBgzf If true, use BGZF compression
    /// \param compressionLevel Compression level used by zlib
    /// \param findAdaptersWithSlidingWindow If true, find adapters with the sliding window algorithm.
    /// \param tileStats Statistics collected for a tile
    /// \param outputBuffer FASTQ output buffer.
    FastqCreateTask(
        std::shared_ptr<FastqCreateTaskManager>& taskManager,
        const data::BclBufferVec& bclBuffers,
        size_t cyclesIndex,
        size_t cycleIndexEnd,
        const layout::FlowcellInfo &flowcellInfo,
        const layout::LaneInfo &laneInfo,
        const layout::ReadInfo& currentReadInfo,
        SampleIndex::FastqOffsetsContainer::const_iterator offsetsBegin,
        SampleIndex::FastqOffsetsContainer::const_iterator offsetsEnd,
        std::size_t maskShortAdapterReads,
        float adapterStringency,
        const boost::ptr_vector<AdapterLocator<numBasesPerByte>>& maskAdapters,
        const boost::ptr_vector<AdapterLocator<numBasesPerByte>>& trimAdapters,
        bool generateReverseComplementFastqs,
        bool includeNonPfClusters,
        bool useBgzf,
        int compressionLevel,
        bool findAdaptersWithSlidingWindow,
        FastqCreateStats &stats,
        FastqBuffer::FastqsContainer::value_type::value_type::value_type &outputBuffer
    );

    virtual PriorityLevel getPriority() const { return PriorityLevel::Three; }

    virtual bool execute(int32_t threadNum);

private:

    /// \brief Update tileStats_ accordingly.
    /// \param basesBegin Beginning of data.
    /// \param basesEnd End of data.
    /// \param barcode Index for this read.
    /// \param filterFlag Whether data passes chastity filter or not.
    /// \param trimmedCount Number of trimmed bases.
    /// \return Whether or not the barcode has been found in the table.
    bool computeStatistics(
        const FastqConstIterator<numBasesPerByte>& basesBegin,
        const FastqConstIterator<numBasesPerByte>& basesEnd,
        SampleIndex::FastqOffsetsContainer::value_type offset,
        int32_t threadNum,
        bool filterFlag,
        size_t trimmedCount,
        const std::vector<uint32_t>& remappedQscores
    );

    /// \brief Crate FASTQ.
    /// \param offset Offset of the FASTQ in the input buffer.
    /// \param compressor Gzip compressor.
    void fastqCreate(
        SampleIndex::FastqOffsetsContainer::value_type offset,
        int32_t threadNum,
        io::GzipCompressor& compressor
    );

    /// \brief Create the barcode strings for the current read.
    /// \param barcodeStrings Vector of barcode strings.
    /// \param offset Offset of the FASTQ in the input buffer.
    void createBarcodeStrings(std::vector<std::string>&                      barcodeStrings,
                              SampleIndex::FastqOffsetsContainer::value_type offset);

    /// \brief Write a header element.
    /// \param element Element to write.
    void writeHeaderElement(const std::string& element);

    /// \brief Create the header.
    /// \param offset Offset of the FASTQ in the input buffer.
    /// \param filterFlag True if filter passed.
    void createHeader(SampleIndex::FastqOffsetsContainer::value_type offset,
                      bool                                           filterFlag);

    /// \brief Create the bases and quality scores.
    /// \param offset Offset of the FASTQ in the input buffer.
    /// \param compressor Gzip compressor.
    /// \param trimmedCount Number of trimmed bases.
    void createBasesAndQualities(SampleIndex::FastqOffsetsContainer::value_type offset,
                                 io::GzipCompressor& compressor,
                                 size_t& trimmedCount);

private:

    /// \brief BCL buffer.
    const data::BclBufferVec& bclBuffers_;

    /// \brief Beginning of BCL cycles to process.
    const size_t cycleIndex_;

    /// \brief End of BCL cycles to process.
    const size_t cycleIndexEnd_;

    /// \brief Flowcell meta data.
    const layout::FlowcellInfo &flowcellInfo_;

    /// \brief Lane meta data.
    const layout::LaneInfo &laneInfo_;

    /// \brief Read meta data.
    const layout::ReadInfo &readInfo_;

    /// \brief Sample number.
    const layout::BarcodeTranslationTable::SampleMetadata sampleMetadata_;

    /// \brief Beginning of FASTQ offsets range.
    const SampleIndex::FastqOffsetsContainer::const_iterator offsetsBegin_;

    /// \brief End of FASTQ offsets range.
    const SampleIndex::FastqOffsetsContainer::const_iterator offsetsEnd_;

    /// \brief Buffer to write FASTQs to.
    FastqBuffer::FastqsContainer::value_type::value_type::value_type &outputBuffer_;

    /// \brief Intermediate buffer.
    FastqBuffer::FastqsContainer::value_type::value_type::value_type buffer_;

    /// \brief Use BGZF compression if true.
    bool useBgzf_;

    /// \brief Compression level.
    int compressionLevel_;

    /// \brief Find adapters with the sliding window algorithm if true.
    bool findAdaptersWithSlidingWindow_;

    /// \brief Minimum read length after adapter trimming.
    std::size_t minimumTrimmedReadLength_;

    /// \brief Maximum number of useful bases in read after adapter trimming for which whole read is masked.
    std::size_t maskShortAdapterReads_;

    /// \brief Adapter stringency.
    float adapterStringency_;

    /// \brief Mask adapters.
    const boost::ptr_vector<AdapterLocator<numBasesPerByte>>& maskAdapters_;

    /// \brief Trim adapters.
    const boost::ptr_vector<AdapterLocator<numBasesPerByte>>& trimAdapters_;

    /// \brief Generate reverse complement FASTQs flag.
    bool generateReverseComplementFastqs_;

    /// \brief Include non-PF clusters in created FASTQ files.
    bool includeNonPfClusters_;

    /// \brief Conversion statistics.
    FastqCreateStats &stats_;

    /// \brief UMI cycles.
    std::vector< common::CycleRange > umiCycles_;
};

class FastqCreateTaskManager : public TaskManager
{
public:
    FastqCreateTaskManager(std::shared_ptr<DemuxBuffer>& inputBuffer,
                           ThreadSafeQueue<std::shared_ptr<DemuxBuffer>>& inputBuffersToRecycle,
                           std::shared_ptr<FastqBuffer>& outputBuffer,
                           ThreadSafeMap<uint32_t, std::shared_ptr<FastqBuffer>>& outputBufferMap);

    virtual ~FastqCreateTaskManager();

    static void waitForAllTasksToFinish();

    DemuxBuffer& getInputBuffer() { return *inputBuffer_; }
    FastqBuffer& getOutputBuffer() { return *outputBuffer_; }

private:
    std::shared_ptr<DemuxBuffer> inputBuffer_;
    ThreadSafeQueue<std::shared_ptr<DemuxBuffer>>& inputBuffersToRecycle_;
    std::shared_ptr<FastqBuffer> outputBuffer_;
    ThreadSafeMap<uint32_t, std::shared_ptr<FastqBuffer>>& outputBufferMap_;

    static std::atomic<uint32_t> numTaskManagers_;
    static std::condition_variable cvAllTaskManagersDone_;
    static std::mutex mut_;
};

/// \brief FASTQ creator.
template<common::NumBasesPerByte numBasesPerByte>
class FastqCreator : public Stage
{
public:

    /// \brief Constructor.
    /// \param threadsCount Number of threads.
    /// \param layout Flowcell layout.
    /// \param laneInfo Lane meata data.
    /// \param maskShortAdapterReads Maximum number of useful bases in read after adapter trimming for which whole read is masked.
    /// \param adapterStringency Adapter stringency.
    /// \param generateReverseComplementFastqs Generate reverse complement FASTQs.
    /// \param includeNonPfClusters Include non-PF clusters in created FASTQ files flag.
    /// \param createFastqsForIndexReads Create FASTQ files also for index reads flag.
    /// \param useBgzf If true, use BGZF compression
    /// \param compressionLevel Compression level used by zlib
    /// \param findAdaptersWithSlidingWindow If true, find adapters with the sliding window algorithm.
    /// \param tileStats Statistics collected for a tile
    /// \param unknownBarcodeHits Counts of unknown barcodes
    FastqCreator(
        TaskQueue& taskQueue,
        ThreadSafeQueue<std::shared_ptr<DemuxBuffer>>& inputBuffersToUse,
        ThreadSafeQueue<std::shared_ptr<DemuxBuffer>>& inputBuffersToRecycle,
        ThreadSafeMap<uint32_t, std::shared_ptr<FastqBuffer>>& outputBuffersToSubmit,
        ThreadSafeQueue<std::shared_ptr<FastqBuffer>>& outputBuffersToUse,
        const layout::Layout &layout,
        const layout::LaneInfo &laneInfo,
        std::size_t maskShortAdapterReads,
        float adapterStringency,
        bool generateReverseComplementFastqs,
        bool includeNonPfClusters,
        bool createFastqsForIndexReads,
        bool useBgzf,
        int compressionLevel,
        bool findAdaptersWithSlidingWindow,
        uint32_t numProcessingThreads,
        ConversionStatsForSampleTileBarcode &summaryTileStats,
        stats::BarcodeHits &unknownBarcodeHits
    );

    virtual ~FastqCreator();

public:

    virtual bool startNewTasks();

private:

    virtual void terminate();

    virtual std::shared_ptr<FastqCreateTaskManager> getNewTaskManager();

    void createTileStats();

    void createAdapters(boost::ptr_vector<AdapterLocator<numBasesPerByte>>& adapters,
                        layout::ReadInfo::AdaptersContainer::const_iterator begin,
                        layout::ReadInfo::AdaptersContainer::const_iterator end) const;

private:

    ThreadSafeQueue<std::shared_ptr<DemuxBuffer>>& inputBuffersToUse_;
    ThreadSafeQueue<std::shared_ptr<DemuxBuffer>>& inputBuffersToRecycle_;
    ThreadSafeMap<uint32_t, std::shared_ptr<FastqBuffer>>& outputBuffersToSubmit_;
    ThreadSafeQueue<std::shared_ptr<FastqBuffer>>& outputBuffersToUse_;

    /// \brief Layout.
    const layout::Layout &layout_;

    /// \brief Current lane.
    const layout::LaneInfo &laneInfo_;

    /// \brief Maximum number of useful bases in read after adapter trimming for which whole read is masked.
    std::size_t maskShortAdapterReads_;

    /// \brief Adapter stringency.
    float adapterStringency_;

    /// \brief Mask adapters.
    boost::ptr_vector< boost::ptr_vector<AdapterLocator<numBasesPerByte>> > maskAdapters_;

    /// \brief Trim adapters.
    boost::ptr_vector< boost::ptr_vector<AdapterLocator<numBasesPerByte>> > trimAdapters_;

    /// \brief Generate reverse complement FASTQs flag.
    bool generateReverseComplementFastqs_;

    /// \brief Include non-PF clusters in created FASTQ files.
    bool includeNonPfClusters_;

    /// \brief Create FASTQ files also for index reads.
    bool createFastqsForIndexReads_;

    /// \brief Use BGZF compression if true.
    bool useBgzf_;

    /// \brief Compression level used by zlib
    int compressionLevel_;

    /// \brief Find adapters with the sliding window algorithm if true.
    bool findAdaptersWithSlidingWindow_;

    /// \brief Conversion statistics (summary).
    ConversionStatsForSampleTileBarcode &summaryTileStats_;

    /// \brief Unknown barcodes statistics (summary).
    stats::BarcodeHits &unknownBarcodesHits_;

    FastqCreateStats statsForEachThread_;

    uint32_t prevGroupNumber_;

    uint32_t numBuffersCreated_;
};

} // namespace conversion
} // namespace bcl2fastq

#include "conversion/FastqCreator.hpp"

#endif // BCL2FASTQ_CONVERSION_FASTQCREATOR_HH

ext: hh


text:
#include <stdio.h>
#include <inttypes.h>
#include <iostream>
#include <Eigen/Dense>
#include <boost/shared_ptr.hpp>

#include <lcm/lcm-cpp.hpp>

#include <bot_lcmgl_client/lcmgl.h>
#include <GL/gl.h>

#include <bot_frames/bot_frames.h>
#include <bot_param/param_client.h>
#include <bot_param/param_util.h>

#include "lcmtypes/bot_core.hpp"
#include "lcmtypes/multisense.hpp"

#include <ConciseArgs>

// define the following in order to eliminate the deprecated headers warning
//#define VTK_EXCLUDE_STRSTREAM_HEADERS
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/PolygonMesh.h>
#include <pcl/io/vtk_lib_io.h>
#include <pronto_utils/pronto_vis.hpp> // visualize pt clds

#include <image_io_utils/image_io_utils.hpp> // to simplify jpeg/zlib compression and decompression
#include <rgbd_simulation/rgbd_primitives.hpp>

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"

using namespace std;
using namespace Eigen;

struct CommandLineConfig
{
    std::string lidar_channel;
};

class Pass{
  public:
    Pass(boost::shared_ptr<lcm::LCM> &lcm_, const CommandLineConfig& cl_cfg_);

    ~Pass(){
    }

    void doWork();

  private:
    boost::shared_ptr<lcm::LCM> lcm_;
    const CommandLineConfig& cl_cfg_;

    int get_trans_with_utime(std::string from_frame, std::string to_frame,
                                 int64_t utime, Eigen::Isometry3d & mat);

    bot_lcmgl_t* lcmgl_;
    BotParam* botparam_;
    BotFrames* botframes_;

    int printf_counter_; // used for terminal feedback
    Eigen::Isometry3d scan_to_local_; // transform used to do conversion
    std::vector<Eigen::Vector3d> cloud_transformed_; // incoming lidar converted to 3D points
    std::vector<Eigen::Vector3d> color_;
    void drawPoints(int64_t last_utime);

       image_io_utils*  imgutils_;
    uint8_t* left_buf_;

    boost::shared_ptr<rgbd_primitives>  prim_;

    std::vector<Eigen::Vector3d> other_cloud_;
    std::vector<Eigen::Vector3d> other_color_;

};

Pass::Pass(boost::shared_ptr<lcm::LCM> &lcm_, const CommandLineConfig& cl_cfg_):
    lcm_(lcm_), cl_cfg_(cl_cfg_){
  lcmgl_= bot_lcmgl_init(lcm_->getUnderlyingLCM(), "lidar-to-3dpoints");
  botparam_ = bot_param_new_from_server(lcm_->getUnderlyingLCM(), 0);
  botframes_= bot_frames_get_global(lcm_->getUnderlyingLCM(), botparam_);

  printf_counter_ =0;

      left_buf_ = (uint8_t*) malloc(1*1024* 1280);
      imgutils_ = new image_io_utils( lcm_->getUnderlyingLCM(), 1024, 3*1280); // extra space for stereo tasks

      scan_to_local_.setIdentity();
}

// from pronto_lcm
void convertLidar(std::vector< float > ranges, int numPoints, double thetaStart,
        double thetaStep,
        std::vector<Eigen::Vector3d> &cloud,
        double minRange = 0., double maxRange = 1e10,
        double validRangeStart = -1000, double validRangeEnd = 1000)
{
  double theta = thetaStart;
  for (int i = 0; i < numPoints; i++) {
    if (ranges[i] > minRange && ranges[i] < maxRange && theta > validRangeStart
            && theta < validRangeEnd) {
      Eigen::Vector3d pt;
      pt(0) = ranges[i] * cos(theta);
      pt(1) = ranges[i] * sin(theta);
      pt(2) = 0;
      cloud.push_back(pt);
    }
    theta += thetaStep;
  }
}

int Pass::get_trans_with_utime(std::string from_frame, std::string to_frame,
                                 int64_t utime, Eigen::Isometry3d & mat){
  int status;
  double matx[16];
  status = bot_frames_get_trans_mat_4x4_with_utime( botframes_, from_frame.c_str(),  to_frame.c_str(), utime, matx);
  for (int i = 0; i < 4; ++i) {
    for (int j = 0; j < 4; ++j) {
      mat(i,j) = matx[i*4+j];
    }
  }
  return status;
}

void bot_lcmgl_draw_axes(bot_lcmgl_t * lcmgl, const Eigen::Affine3d & trans, double scale)
{
  lcmglPushMatrix();
  lcmglMultMatrixd(trans.data());
  lcmglScalef(scale, scale, scale);
  bot_lcmgl_draw_axes(lcmgl);
  lcmglPopMatrix();
}

void Pass::drawPoints(int64_t last_utime){
  // a. Visualize the axes of interest:
  bot_lcmgl_push_matrix(lcmgl_);
  bot_lcmgl_rotated(lcmgl_, -90, 1, 0, 0);

  bot_lcmgl_draw_axes(lcmgl_, scan_to_local_, 4);

  if(1==1){
  // b. Plot scan from camera frame:
  bot_lcmgl_point_size(lcmgl_, 4.5f);
  bot_lcmgl_begin(lcmgl_, GL_POINTS);  // render as points
//  bot_lcmgl_color3f(lcmgl_, 0, 0, 1); // Blue
  for (size_t i=0; i < cloud_transformed_.size(); ++i) {

    Eigen::Vector3d c = color_[i];
    bot_lcmgl_color3f(lcmgl_, c(0)/255, c(1)/255, c(2)/255); // Blue

    Eigen::Vector3d pt = cloud_transformed_[i];
    bot_lcmgl_vertex3d(lcmgl_, pt(0), pt(1), pt(2)); // 100 points in line
  }
  bot_lcmgl_end(lcmgl_);
  }

  if(1==1){
  // b. Plot scan from camera frame:
  bot_lcmgl_point_size(lcmgl_, 4.5f);
  bot_lcmgl_begin(lcmgl_, GL_POINTS);  // render as points
  bot_lcmgl_color3f(lcmgl_, 0, 0, 1); // Blue
  for (size_t i=0; i < other_cloud_.size(); ++i) {

    Eigen::Vector3d c = other_color_[i];
    bot_lcmgl_color3f(lcmgl_, c(0)/255, c(1)/255, c(2)/255); // Blue

    Eigen::Vector3d pt = other_cloud_[i];

    bot_lcmgl_vertex3d(lcmgl_, pt(0), pt(1), pt(2)); // 100 points in line
    //bot_lcmgl_vertex3d(lcmgl_, 1,1,1); // 100 points in line
  }
  bot_lcmgl_end(lcmgl_);
  }

  bot_lcmgl_pop_matrix(lcmgl_);
  bot_lcmgl_switch_buffer(lcmgl_);

  std::cout << other_cloud_.size() << " other cloud\n";
  if (printf_counter_%80 ==0){
    cout << "Scan @ "  << last_utime << "\n";
  }
  printf_counter_++;
}

void Pass::doWork( ){

  pcl::PolygonMesh mesh;
  pcl::io::loadPolygonFile(  "atlas_one_mesh.ply"    ,mesh);
  pcl::PolygonMesh::Ptr mesh_ptr (new pcl::PolygonMesh(mesh));
  cout << "read in ply\n";

  //pcl::PointCloud<pcl::PointXYZRGB>::Ptr mesh_cloud;
  //pcl::fromPCLPointCloud2(mesh.cloud, *mesh_cloud);

  pcl::PointCloud<pcl::PointXYZRGB>::Ptr mesh_cloud =prim_->sampleMesh(mesh_ptr, 100000); // NB: disc sampled for both top and bottom lid - givine twice the density

  Eigen::Isometry3d pose_out = Eigen::Isometry3d::Identity();

  pose_out.translation()  << -0.15,1.4,-1.15;
  Eigen::Quaterniond quat = euler_to_quat(90*M_PI/180, -20*M_PI/180, 0 );
  //90.0*M_PI/180.0, -90.0*M_PI/180.0, 0.0*M_PI/180.0
  pose_out.rotate( quat);

  Eigen::Isometry3f visual_origin_f= pose_out.cast<float>();
  Eigen::Quaternionf visual_origin_quat(visual_origin_f.rotation());
  pcl::transformPointCloud (*mesh_cloud, *mesh_cloud,
                            visual_origin_f.translation(), visual_origin_quat);

  std::cout << "doWork\n";
  BotCamTrans *camtrans;

  camtrans = bot_param_get_new_camtrans(botparam_, "CAMERACHEST_LEFT");

  int height = 1280;
  int width = 1024;

  cloud_transformed_.clear();
  color_.clear();

  other_cloud_.clear();
  other_color_.clear();

  cv::Mat img = cv::Mat::zeros(height,width,CV_8UC1); // h,w
  img.data = left_buf_;

  for (size_t i=0; i < mesh_cloud->points.size();    i++) {

      Eigen::Vector3d pt( mesh_cloud->points[i].x,
                          mesh_cloud->points[i].y,
                          mesh_cloud->points[i].z + 1) ;
      other_cloud_.push_back(pt);

      double p[] = { mesh_cloud->points[i].x,
                      mesh_cloud->points[i].y,
                   mesh_cloud->points[i].z +1      };

      double im_xyz[3];
      bot_camtrans_project_point(camtrans, p, im_xyz );
      // std::cout<< im_xyz[0] << " " << im_xyz[1] <<" " << im_xyz[2]<<"\n";

      if (( im_xyz[0] > 0 ) && ( im_xyz[0] < width)){
        if (( im_xyz[1] > 0 ) && ( im_xyz[1] < height)){
          //int pixel = round(im_xyz[1]) *width + round(im_xyz[0]);
          //left_buf_[pixel] = 100;

          cv::circle( img, cv::Point( im_xyz[0], im_xyz[1] ),
            8.0,         100,         -1,         8 );

        }
      }

      Eigen::Vector3d c(0,0,0);
      other_color_.push_back(c);
  }

  for (int y = 0; y < height; y=y+4) {
    for (int x = 0; x < width; x=x+4) {
      double ray_cam[3];
      bot_camtrans_unproject_pixel(camtrans, x, y, ray_cam);

      Eigen::Vector3d pt(2.5*ray_cam[0], 2.5*ray_cam[1], 2.5*ray_cam[2] ) ;
      cloud_transformed_.push_back(pt);

      int pixel = y*width + x;

      Eigen::Vector3d c( left_buf_[pixel],
        left_buf_[pixel], left_buf_[pixel] ) ;
      color_.push_back(c);
    }
  }

  cv::imwrite("image_out.png", img);

  /*
  for (double y = -30; y < 30; y=y+0.1) {
    for (double x = -40; x < 40; x=x+0.1) {

      Eigen::Vector3d pt(x,y, 5.0 ) ;
      other_cloud_.push_back(pt);

      double p[] = {x,y,5.0};
      double im_xyz[3];
      bot_camtrans_project_point(camtrans, p, im_xyz );
      //std::cout<< im_xyz[0] << " " << im_xyz[1] <<" " << im_xyz[2]<<"\n";
      Eigen::Vector3d pt2(im_xyz[0] ,im_xyz[1], im_xyz[2] ) ;
      //other_cloud_.push_back(pt2);

      int pixel = round(im_xyz[1]) *width + round(im_xyz[0]);

      Eigen::Vector3d c( left_buf_[pixel],
        left_buf_[pixel], left_buf_[pixel] ) ;

      other_color_.push_back(c);
    }
    std::cout << y << " b\n";
  }
  */

  drawPoints(0);
}

int main( int argc, char** argv ){
  CommandLineConfig cl_cfg;
  cl_cfg.lidar_channel = "CAMERACHEST_LEFT";
  ConciseArgs opt(argc, (char**)argv);
  opt.add(cl_cfg.lidar_channel, "l", "lidar_channel","lidar_channel");
  opt.parse();
  std::cout << "lidar_channel: " << cl_cfg.lidar_channel << "\n";

  boost::shared_ptr<lcm::LCM> lcm(new lcm::LCM);
  if(!lcm->good()){
    std::cerr <<"ERROR: lcm is not good()" <<std::endl;
  }

  Pass app(lcm, cl_cfg);

 // while(0 == lcm->handle());

  app.doWork();

  return 0;
}

max_stars_repo_name: liangfok/oh-distro

max_issues_repo_name: liangfok/oh-distro

max_forks_repo_name: liangfok/oh-distro


text:
// Copyright (C) 2018 Thejaka Amila Kanewala, Marcin Zalewski, Andrew Lumsdaine.

// Boost Software License - Version 1.0 - August 17th, 2003

// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:

// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.

// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

//  Authors: Thejaka Kanewala
//           Andrew Lumsdaine

#include "../common/utils.hpp"
#include <boost/graph/agm/util/eagm_buckets.hpp>
#include <boost/tuple/tuple.hpp>

#include <limits.h>
// These tests are for dynamic configuration

struct chaotic {
public:
  template <typename T>
  bool operator()(T i, T j) {
    return false;
  }
};

template<int index>
struct dijkstra {
public:
  template <typename T>
  bool operator()(T i, T j) {
    return (std::get<index>(i) < std::get<index>(j));
  }
};

template<int index, typename delta_t>
struct delta_ord {

private:
  delta_t delta;

public:
  delta_ord(delta_t _d) : delta(_d) {}

  delta_ord(const delta_ord& _do) : delta(_do.delta) {}

  template <typename T>
  bool operator()(T i, T j) {
    return ((std::get<index>(i)/delta) < (std::get<index>(j)/delta));
  }
};

struct chaotic_ordering_gen {
public:
  typedef chaotic strict_ordering;
};

//typedef boost::tuple<uint64_t, uint64_t> pwork_item_t;
typedef std::tuple<uint64_t, uint64_t> work_item_t;
void init_data(std::vector<work_item_t>& wis) {
  work_item_t w1(0,5);
  work_item_t w2(0,1);
  work_item_t w3(0,9);
  work_item_t w4(0,25);
  work_item_t w5(0,15);
  work_item_t w6(0,2);
  work_item_t w7(0,34);
  work_item_t w8(0,16);
  work_item_t w9(0,8);
  work_item_t w10(0,9);
  work_item_t w11(8, 45);

  wis.push_back(w1);
  wis.push_back(w2);
  wis.push_back(w3);
  wis.push_back(w4);
  wis.push_back(w5);
  wis.push_back(w6);
  wis.push_back(w7);
  wis.push_back(w8);
  wis.push_back(w9);
  wis.push_back(w10);
  wis.push_back(w11);

}

template<typename ordering>
void execute(int argc, char* argv[],
             ordering _ord,
             uint64_t expected) {

  std::vector<work_item_t> wis;
  init_data(wis);

  /*  typedef boost::graph::agm::buckets<work_item_t, ordering> buckets_t;
  buckets_t all_buckets(_ord);

  for (int i=0; i < wis.size(); i++) {
    all_buckets.push(wis[i]);
  }

  assert(all_buckets.get_buckets_created() == expected);
  all_buckets.print_buckets();*/
}

template<typename buckets>
class thread_executor {

private:
  int nthreads;
  buckets& all_bkts;

public:
  thread_executor(int _n,
                  buckets& _all) : nthreads(_n),
                                   all_bkts(_all){}

  void operator()(int numa,
                  int tid,
                  std::vector<work_item_t>& wis) {
    for (typename std::vector<work_item_t>::size_type i = tid ;
         i < wis.size(); i+= nthreads) {
      work_item_t& wi = wis[i];
      all_bkts.push(wi, numa, tid);
    }
  }
};

template<typename ordering>
void execute_mt(int argc, char* argv[],
                ordering _ord,
                int nthreads,
                uint64_t expected) {

  std::vector<work_item_t> wis;
  init_data(wis);

  /*typedef boost::graph::agm::buckets<work_item_t, ordering> buckets_t;
  buckets_t all_buckets(_ord);

  thread_executor<buckets_t> te(nthreads, all_buckets);

  boost::scoped_array<boost::thread> threads(new boost::thread[nthreads - 1]);
  for (int i = 0; i < nthreads - 1; ++i) {
    boost::thread thr(boost::ref(te), i + 1, wis);
    threads[i].swap(thr);
  }

  te(0, wis);

  for (int i = 0; i < (nthreads - 1); ++i)
    threads[i].join();

  std::cout << "All buckets created = " << all_buckets.get_buckets_created()
            << std::endl;

  assert(all_buckets.get_buckets_created() == expected);
  all_buckets.print_buckets();*/
}

template<typename T1,
         typename T2,
         typename T3,
         typename T4>
boost::graph::agm::eagm_configs<T1, T2, T3, T4> create_eagm_config(T1 _t1,
                                                                   T2 _t2,
                                                                   T3 _t3,
                                                                   T4 _t4) {
  typedef boost::graph::agm::eagm_configs<T1, T2, T3, T4> eagm_config_t;
  eagm_config_t config(_t1,
                       _t2,
                       _t3,
                       _t4);

  config.ranks = 1;
  config.threads = 1;
  config.numa_domains = 1;

  return config;
}

template<typename T1,
         typename T2,
         typename T3,
         typename T4>
void test_optimizations(T1 _t1,
                        T2 _t2,
                        T3 _t3,
                        T4 _t4) {

  typedef boost::graph::agm::eagm_configs<T1,
                                          T2,
                                          T3,
                                          T4> ordered_config_t;

  CHAOTIC_ORDERING_T ch;
  ordered_config_t config = create_eagm_config<T1,
                                               T2,
                                               T3,
                                               T4>(_t1,
                                                   _t2,
                                                   _t3,
                                                   _t4);

  config.optimize();
  config.print();
}

template<typename T1,
         typename T2,
         typename T3,
         typename T4>
void test_eagm(T1 _t1,
               T2 _t2,
               T3 _t3,
               T4 _t4) {

  typedef boost::graph::agm::eagm_configs<T1,
                                          T2,
                                          T3,
                                          T4> ordered_config_t;

  CHAOTIC_ORDERING_T ch;
  ordered_config_t config = create_eagm_config<T1,
                                               T2,
                                               T3,
                                               T4>(_t1,
                                                   _t2,
                                                   _t3,
                                                   _t4);

  config.optimize();
  config.print();

  typedef boost::graph::agm::eagm_buckets<work_item_t,
                                          typename ordered_config_t::global_ordering_t,
                                          ordered_config_t> eagms;

  eagms e(config.global_ord,
          config,
          boost::graph::agm::spatial_level::global);

  std::vector<work_item_t> wis;
  init_data(wis);

  for (int i=0; i < wis.size(); i++) {
    e.push(wis[i], 0, 0);
  }

  e.print();
}

template<typename T1,
         typename T2,
         typename T3,
         typename T4>
void test_eagm_multiple_threads(T1 _t1,
                                T2 _t2,
                                T3 _t3,
                                T4 _t4,
                                int _threads) {

  typedef boost::graph::agm::eagm_configs<T1,
                                          T2,
                                          T3,
                                          T4> ordered_config_t;

  CHAOTIC_ORDERING_T ch;
  ordered_config_t config = create_eagm_config<T1,
                                               T2,
                                               T3,
                                               T4>(_t1,
                                                   _t2,
                                                   _t3,
                                                   _t4);

  config.threads = _threads;
  config.optimize();
  config.print();

  typedef boost::graph::agm::eagm_buckets<work_item_t,
                                          typename ordered_config_t::global_ordering_t,
                                          ordered_config_t> eagms;

  eagms e(config.global_ord,
          config,
          boost::graph::agm::spatial_level::global);

  std::vector<work_item_t> wis;
  init_data(wis);

  for (int i=0; i < wis.size(); i++) {
    e.push(wis[i], 0, (i%config.threads));
  }

  e.print();
}

template<typename T1,
         typename T2,
         typename T3,
         typename T4>
void test_eagm_multiple_numa_domains(T1 _t1,
                                T2 _t2,
                                T3 _t3,
                                T4 _t4,
                                int _numa) {

  typedef boost::graph::agm::eagm_configs<T1,
                                          T2,
                                          T3,
                                          T4> ordered_config_t;

  CHAOTIC_ORDERING_T ch;
  ordered_config_t config = create_eagm_config<T1,
                                               T2,
                                               T3,
                                               T4>(_t1,
                                                   _t2,
                                                   _t3,
                                                   _t4);

  config.numa_domains = _numa;
  config.optimize();
  config.print();

  typedef boost::graph::agm::eagm_buckets<work_item_t,
                                          typename ordered_config_t::global_ordering_t,
                                          ordered_config_t> eagms;

  eagms e(config.global_ord,
          config,
          boost::graph::agm::spatial_level::global);

  std::vector<work_item_t> wis;
  init_data(wis);

  for (int i=0; i < wis.size(); i++) {
    e.push(wis[i], (i%config.numa_domains), 0);
  }

  e.print();
}

template<typename T1,
         typename T2,
         typename T3,
         typename T4>
void test_eagm_multiple_numa_domains_multiple_threads(T1 _t1,
                                                      T2 _t2,
                                                      T3 _t3,
                                                      T4 _t4,
                                                      int _threads,
                                                      int _numa) {

  typedef boost::graph::agm::eagm_configs<T1,
                                          T2,
                                          T3,
                                          T4> ordered_config_t;

  CHAOTIC_ORDERING_T ch;
  ordered_config_t config = create_eagm_config<T1,
                                               T2,
                                               T3,
                                               T4>(_t1,
                                                   _t2,
                                                   _t3,
                                                   _t4);
  //configs
  config.numa_domains = _numa;
  config.threads = _threads;
  config.optimize();
  config.print();

  typedef boost::graph::agm::eagm_buckets<work_item_t,
                                          typename ordered_config_t::global_ordering_t,
                                          ordered_config_t> eagms;

  eagms e(config.global_ord,
          config,
          boost::graph::agm::spatial_level::global);

  std::vector<work_item_t> wis;
  init_data(wis);

  for (int i=0; i < wis.size(); i++) {
    e.push(wis[i], (i%config.numa_domains), i%config.threads);
  }

  e.print();
}

template<typename T1,
         typename T2,
         typename T3,
         typename T4>
void mt_test_eagm(T1 _t1,
                  T2 _t2,
                  T3 _t3,
                  T4 _t4,
                  int _threads,
                  int _numa) {

  typedef boost::graph::agm::eagm_configs<T1,
                                          T2,
                                          T3,
                                          T4> ordered_config_t;

  CHAOTIC_ORDERING_T ch;
  ordered_config_t config = create_eagm_config<T1,
                                               T2,
                                               T3,
                                               T4>(_t1,
                                                   _t2,
                                                   _t3,
                                                   _t4);

  config.numa_domains = _numa;
  config.threads = _threads;
  config.optimize();
  config.print();

  typedef boost::graph::agm::eagm_buckets<work_item_t,
                                          typename ordered_config_t::global_ordering_t,
                                          ordered_config_t> eagms;

  eagms e(config.global_ord,
          config,
          boost::graph::agm::spatial_level::global);

  std::vector<work_item_t> wis;
  init_data(wis);

  thread_executor<eagms> te(config.threads, e);

  boost::scoped_array<boost::thread> threads(new boost::thread[config.threads - 1]);
  for (int i = 0; i < config.threads - 1; ++i) {
    boost::thread thr(boost::ref(te), (i%config.numa_domains), i+1, wis);
    threads[i].swap(thr);
  }

  te(0, 0, wis);

  for (int i = 0; i < (config.threads - 1); ++i)
    threads[i].join();

  e.print();
}

int main(int argc, char* argv[]) {

  CHAOTIC_ORDERING_T ch;
  DIJKSTRA_ORDERING_T dj;
  DELTA_ORDERING_T delta(10);
  /*
      test_optimizations(ch, ch, ch, ch);

      std::cout << "======================================================" << std::endl;

      test_optimizations(ch, ch, ch, dj);

      std::cout << "======================================================" << std::endl;

      test_optimizations(delta, ch, ch, dj);

      std::cout << "======================================================" << std::endl;
      test_optimizations(ch, delta, ch, dj);

      std::cout << "======================================================" << std::endl;
      test_optimizations(ch, delta, dj, dj);

      std::cout << "======================================================" << std::endl;
      test_optimizations(ch, ch, dj, ch);*/

  /*test_eagm(ch, ch, ch, ch);

  std::cout << "======================================================" << std::endl;

  test_eagm(ch, ch, ch, dj);

  std::cout << "======================================================" << std::endl;

  test_eagm(delta, ch, ch, dj);

  std::cout << "======================================================" << std::endl;

  test_eagm(ch, delta, ch, ch);

  std::cout << "======================================================" << std::endl;

  test_eagm(ch, delta, ch, dj);

  std::cout << "======================================================" << std::endl;

  test_eagm(ch, ch, dj, ch);*/

  int threads = 4;
  int numa_domains = 2;

  //test_eagm_multiple_threads(ch, ch, ch, ch, threads);

  //std::cout << "======================================================" << std::endl;

  //test_eagm_multiple_threads(ch, ch, ch, dj, threads);

  //std::cout << "======================================================" << std::endl;

  //test_eagm_multiple_threads(delta, ch, ch, dj, threads);

  //std::cout << "======================================================" << std::endl;

  //test_eagm_multiple_threads(ch, delta, ch, ch, threads);

  //std::cout << "======================================================" << std::endl;

  //test_eagm_multiple_threads(ch, delta, ch, dj, threads);

  //std::cout << "======================================================" << std::endl;

  //test_eagm_multiple_threads(ch, ch, dj, ch, threads);

  //  test_eagm_multiple_numa_domains(ch, ch, ch, ch, numa_domains);

  //std::cout << "======================================================" << std::endl;

  //test_eagm_multiple_numa_domains(ch, ch, dj, ch, numa_domains);

  //std::cout << "======================================================" << std::endl;

  //test_eagm_multiple_numa_domains(delta, ch, ch, dj, numa_domains);

  //std::cout << "======================================================" << std::endl;

  //test_eagm_multiple_numa_domains(ch, delta, ch, ch, numa_domains);

  //std::cout << "======================================================" << std::endl;

  //test_eagm_multiple_numa_domains(ch, delta, dj, ch, numa_domains);

  //std::cout << "======================================================" << std::endl;

  //test_eagm_multiple_numa_domains(ch, ch, dj, ch, numa_domains);

  //test_eagm_multiple_numa_domains_multiple_threads(ch, ch, delta, dj, threads, numa_domains);

  mt_test_eagm(ch, ch, delta, dj, threads, numa_domains);

  mt_test_eagm(ch, ch, ch, ch, threads, numa_domains);

  std::cout << "======================================================" << std::endl;

  mt_test_eagm(ch, ch, ch, dj, threads, numa_domains);

  std::cout << "======================================================" << std::endl;

  mt_test_eagm(delta, ch, ch, dj, threads, numa_domains);

  std::cout << "======================================================" << std::endl;

  mt_test_eagm(ch, delta, ch, ch, threads, numa_domains);

  std::cout << "======================================================" << std::endl;

  mt_test_eagm(ch, delta, ch, dj, threads, numa_domains);

  std::cout << "======================================================" << std::endl;

  mt_test_eagm(ch, ch, dj, ch, threads, numa_domains);

}

max_stars_repo_name: thejkane/AGM

max_issues_repo_name: thejkane/AGM

max_forks_repo_name: thejkane/AGM


text:
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Vicente J. Botet Escriba 20010.
// 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)
//
// Based on the unique_threader/unique_joiner design from of Kevlin Henney (n1883)
//
// See http://www.boost.org/libs/chrono for documentation.
//
//////////////////////////////////////////////////////////////////////////////

#ifndef BOOST_CHRONO_TYPEOF_CHRONO_HPP
#define BOOST_CHRONO_TYPEOF_CHRONO_HPP

#include <boost/chrono/chrono.hpp>
#define BOOST_TYPEOF_SILENT
#include <boost/typeof/typeof.hpp>

#include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()

BOOST_TYPEOF_REGISTER_TEMPLATE(boost::chrono::duration, (typename)(typename))
BOOST_TYPEOF_REGISTER_TEMPLATE(boost::chrono::time_point, (typename)(typename))
#if 0
BOOST_TYPEOF_REGISTER_TYPE(boost::chrono::system_clock)
#ifdef BOOST_CHRONO_HAS_CLOCK_STEADY
BOOST_TYPEOF_REGISTER_TYPE(boost::chrono::steady_clock)
#endif
BOOST_TYPEOF_REGISTER_TYPE(boost::chrono::high_resolution_clock)

#endif
#endif

max_stars_repo_name: importlib/klib

max_issues_repo_name: isuhao/klib

max_forks_repo_name: isuhao/klib


text:
// Copyright (c) 2016-2022 Antony Polukhin
//
// 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)

#ifndef BOOST_PFR_DETAIL_SIZE_ARRAY_HPP
#define BOOST_PFR_DETAIL_SIZE_ARRAY_HPP
#pragma once

#include <boost/pfr/detail/config.hpp>

#include <cstddef>      // metaprogramming stuff

namespace boost { namespace pfr { namespace detail {

///////////////////// Array that has the constexpr
template <std::size_t N>
struct size_array {                         // libc++ misses constexpr on operator[]
    typedef std::size_t type;
    std::size_t data[N];

    static constexpr std::size_t size() noexcept { return N; }

    constexpr std::size_t count_nonzeros() const noexcept {
        std::size_t count = 0;
        for (std::size_t i = 0; i < size(); ++i) {
            if (data[i]) {
                ++ count;
            }
        }
        return count;
    }

    constexpr std::size_t count_from_opening_till_matching_parenthis_seq(std::size_t from, std::size_t opening_parenthis, std::size_t closing_parenthis) const noexcept {
        if (data[from] != opening_parenthis) {
            return 0;
        }
        std::size_t unclosed_parnthesis = 0;
        std::size_t count = 0;
        for (; ; ++from) {
            if (data[from] == opening_parenthis) {
                ++ unclosed_parnthesis;
            } else if (data[from] == closing_parenthis) {
                -- unclosed_parnthesis;
            }
            ++ count;

            if (unclosed_parnthesis == 0) {
                return count;
            }
        }

        return count;
    }
};

template <>
struct size_array<0> {                         // libc++ misses constexpr on operator[]
    typedef std::size_t type;
    std::size_t data[1];

    static constexpr std::size_t size() noexcept { return 0; }

    constexpr std::size_t count_nonzeros() const noexcept {
        return 0;
    }
};

template <std::size_t I, std::size_t N>
constexpr std::size_t get(const size_array<N>& a) noexcept {
    static_assert(I < N, "====================> Boost.PFR: Array index out of bounds");
    return a.data[I];
}

}}} // namespace boost::pfr::detail

#endif // BOOST_PFR_DETAIL_SIZE_ARRAY_HPP

max_stars_repo_name: clayne/pfr

max_issues_repo_name: clayne/pfr

max_forks_repo_name: clayne/pfr


text:
/**
 ** Isaac Genome Alignment Software
 ** Copyright (c) 2010-2017 Illumina, Inc.
 ** All rights reserved.
 **
 ** This software is provided under the terms and conditions of the
 ** GNU GENERAL PUBLIC LICENSE Version 3
 **
 ** You should have received a copy of the GNU GENERAL PUBLIC LICENSE Version 3
 ** along with this program. If not, see
 ** <https://github.com/illumina/licenses/>.
 **
 ** \file MathCompatibility.hh
 **
 ** \brief  Compatibility layer for math-related constructs.
 **
 ** \author Come Raczy
 **/

#ifndef iSAACCOMMON_MATH_COMPATIBILITY_HH
#define iSAACCOMMON_MATH_COMPATIBILITY_HH

#include <cmath>

#include "config.h"

#ifndef HAVE_FLOORF
inline float floorf(float x)
{
    return static_cast<float> (floor(x));
}
#define HAVE_FLOORF
#endif

#ifndef HAVE_ROUND
inline double round(double x)
{
    return (x - floor(x) < 0.5) ? floor(x) : ceil(x);
}
#define HAVE_ROUND
#endif

#ifndef HAVE_ROUNDF
inline float roundf(float x)
{
    return (x - floorf(x) < 0.5f ? floorf(x) : ceil(x));
}
#define HAVE_ROUNDF
#endif

#ifndef HAVE_POWF
inline float powf(float x, float y)
{
    return static_cast<float> (pow(x, y));
}
#define HAVE_POWF
#endif

#ifndef HAVE_ERF
#include <boost/math/special_functions/erf.hpp>
inline double erf(double x)
{
    return boost::math::erf(x);
}
#define HAVE_ERF
#endif

#ifndef HAVE_ERFF
#include <boost/math/special_functions/erf.hpp>
inline float erff(float x)
{
    return boost::math::erf(x);
}
#define HAVE_ERFF
#endif

#ifndef HAVE_ERFC
#include <boost/math/special_functions/erf.hpp>
inline double erfc(double x)
{
    return boost::math::erfc(x);
}
#define HAVE_ERFC
#endif

#ifndef HAVE_ERFCF
#include <boost/math/special_functions/erf.hpp>
inline float erfc(float x)
{
    return boost::math::erfc(x);
}
#define HAVE_ERFCF
#endif

#endif // #ifndef iSAACCOMMON_MATH_COMPATIBILITY_HH


text:
/* vim:set ts=3 sw=3 sts=3 et: */
/**
 * Copyright © 2008-2013 Last.fm Limited
 *
 * This file is part of libmoost.
 *
 * 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 option.hpp
* @brief A Moost C++ wrapper that represents a LibCurl option
* @author Ricky Cormier
* @version 0.0.0.1
* @date 2011-10-17
*/

#ifndef FM_LAST_MOOST_MURCL_OPTION_HPP__
#define FM_LAST_MOOST_MURCL_OPTION_HPP__

#include <vector>

#include <curl/curl.h>

#include <boost/shared_ptr.hpp>

#include "option_setter.hpp"

namespace moost { namespace murcl {

/**
* @brief This is a polymorphic base class for options
*
* Each option has to be stashed. Although LibCurl can take a copy of each
* option's value this is not probably not the most efficient thing to do
* and since we already have the option anyway we just need to shove it in
* to a container. Problem: each option is a different type. Solution: each
* option derived from this trivial base, which means we can then store a
* polymorphic pointer in our generic container (a vector) and; thus, preserve
* the value of the option for the required lifetime in a simple manner.
*/
class option_base
{
public:
   virtual ~option_base() {}
};

/**
* @brief This is our option stash, used to store the options.
*/
typedef std::vector<boost::shared_ptr<option_base> > option_stash;

/**
* @brief This class is an abstract representation of a LibCurl option.
*        Upon construction it requires an interface handle and a value,
*        which it will use to set the appropriate LibCurl option.
*
*  @param OptTraits
*     Represents the traits of the option being set
*/
template <typename OptTraits>
class option : public option_base
{
public:
   typedef OptTraits option_traits;

   /*
   * @brief Construct and set a LibCurl option
   *
   * @param handle
   *     a valid LibCurl interface handle
   * @param val
   *     the value being set for this option
   */
   option(
      typename option_traits::handle_type handle,
      typename option_traits::value_type const & val
      )
      : val_(val)
   {
      option_setter<typename option_traits::curl_option,
         typename option_traits::value_type>::set(handle, val_);
   }

private:
   typename option_traits::value_type val_;
};

}}

#endif //FM_LAST_MOOST_MURCL_OPTION_HPP__

max_stars_repo_name: lastfm/libmoost

max_issues_repo_name: lastfm/libmoost

max_forks_repo_name: lastfm/libmoost


text:
#include <thread>
#include <mutex>
#include <chrono>

#define BOOST_THREAD_PROVIDES_FUTURE
#define BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION
#define BOOST_THREAD_PROVIDES_FUTURE_WHEN_ALL_WHEN_ANY
#include <boost/thread/future.hpp>

#define THREAD_POOL_USE_BOOST_FUTURE 1
#include <thread_pool/thread_pool.hpp>

using namespace std::literals;

using ts =
    tp::ThreadPoolSettings<tp::PackagedTaskAdaptorBoost<boost::packaged_task>>;

using tptp = tp::ThreadPool<ts>;

tptp _tp;
std::mutex mtx;

auto slp = [](auto x)
{
    std::this_thread::sleep_for(x);
};

auto df = [](auto ys, auto yms)
{
    {
        std::lock_guard<decltype(mtx)> l(mtx);
        std::cout << "Starting " << ys << "\n";
    }

    slp(yms);

    {
        std::lock_guard<decltype(mtx)> l(mtx);
        std::cout << "Finished " << ys << "\n";
    }
};

void bf_test()
{
    auto mkf = [](auto s, auto xms)
    {
        return boost::async(boost::launch::async, [s, xms]
            {
                df(s, xms);
            });
    };

    auto f0 = mkf(0, 1000ms);
    auto f1 = mkf(1, 1000ms);
    auto f2 = mkf(2, 1000ms);
    auto f3 = mkf(3, 1000ms);

    auto fwa = boost::when_all( // .
        std::move(f0),          // .
        std::move(f1),          // .
        std::move(f2),          // .
        std::move(f3));

    auto fwat = fwa.then([](auto)
        {
            {
                std::lock_guard<decltype(mtx)> l(mtx);
                std::cout << "All done!\n";
            }
        });

    fwat.get();
}

void bf_test_tp()
{
    auto mkf = [](auto s, auto xms)
    {
        return _tp.process([s, xms]
            {
                df(s, xms);
            });
    };

    auto f0 = mkf(0, 1000ms);
    auto f1 = mkf(1, 1000ms);
    auto f2 = mkf(2, 1000ms);
    auto f3 = mkf(3, 1000ms);

    auto fwa = boost::when_all( // .
        std::move(f0),          // .
        std::move(f1),          // .
        std::move(f2),          // .
        std::move(f3));

    auto fwat = fwa.then([](auto)
        {
            {
                std::lock_guard<decltype(mtx)> l(mtx);
                std::cout << "All done!\n";
            }
        });

    fwat.get();
}

void bf_test_tp2()
{
    auto mkf = [](auto s, auto xms)
    {
        return _tp.process([s, xms]
            {
                // TODO: correctly 100%'s all cores
                /*
                volatile int kk = 0;

                for(volatile int jj= 0; jj < 100; ++jj)
                for(volatile int k = 0; k < 10000000; ++k)
                {
                    kk += 1;
                }
                */

                df(s, xms);
            });
    };

    std::vector<boost::future<void>> vf;

    for(auto i(0); i < 1000; ++i)
    {
        auto f0 = mkf(i, 1ms);
        vf.emplace_back(std::move(f0));
    }

    auto fwa = boost::when_all(std::begin(vf), std::end(vf));

    auto fwat = fwa.then([](auto)
        {
            {
                std::lock_guard<decltype(mtx)> l(mtx);
                std::cout << "All done!\n";
            }
        });

    fwat.get();
}

int main()
{
    bf_test();
    bf_test_tp();
    bf_test_tp2();

    return 0;
}

max_issues_repo_name: vittorioromeo/ecst

max_forks_repo_name: vittorioromeo/ecst


text:
#pragma once

#include <bunsan/curl/http/response_head.hpp>
#include <bunsan/curl/options/callback.hpp>

#include <boost/optional.hpp>
#include <boost/range/iterator_range.hpp>

#include <functional>
#include <vector>

namespace bunsan::curl::http {

class header_parser {
 private:
  using map_type = std::vector<response_head>;

 public:
  using value_type = map_type::value_type;
  using const_iterator = map_type::const_iterator;
  using const_range = boost::iterator_range<const_iterator>;
  using option_type = options::headerfunction;
  using callback_type = option_type::function_type;

 public:
  header_parser() = default;

  callback_type callback();
  option_type option();

  const_range responses() const { return const_range(begin(), end()); }
  const_iterator begin() const { return m_responses.begin(); }
  const_iterator end() const { return m_responses.end(); }

  bool empty() const { return m_responses.empty(); }
  std::size_t size() const { return m_responses.size(); }

  const response_head &at(const std::size_t index) const;
  const response_head &operator[](const std::size_t index) const {
    return at(index);
  }

  const response_head &front() const;
  const response_head &first() const { return front(); }

  const response_head &back() const;
  const response_head &last() const { return back(); }

  /// Status line or header without CRLF
  void parse(const std::string &header_data);

 private:
  std::size_t parse_header_callback(const char *ptr, std::size_t size);

 private:
  std::vector<response_head> m_responses;
};

inline header_parser::const_iterator begin(const header_parser &p) {
  return p.begin();
}

inline header_parser::const_iterator end(const header_parser &p) {
  return p.end();
}

}  // namespace bunsan::curl::http

max_stars_repo_name: bacsorg/bacs

max_issues_repo_name: bacsorg/bacs

max_forks_repo_name: bacsorg/bacs


text:
/*
 * Copyright 2014 RWTH Aachen University. All rights reserved.
 *
 * Licensed under the RWTH LM License (the "License");
 * you may not use this file except in compliance with the License.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <cassert>
#include <cstdint>  // for int64_t
#include <sstream>
#include <boost/algorithm/string/trim.hpp>
#include "data.h"
#include "file.h"

Data::Data(const std::string &data_file_name,
           const int max_batch_size,
           const int max_sequence_length,
           const WordWrappingType word_wrapping_type,
           const bool debug_no_sb,
           ConstVocabularyPointer vocabulary)
    : max_batch_size_(max_batch_size),
      max_sequence_length_(max_sequence_length),
      debug_no_sb_(debug_no_sb),
      vocabulary_(vocabulary) {
  switch (word_wrapping_type) {
  case kConcatenated:
    PrepareDataSequenceWise(data_file_name, true);
    break;
  case kVerbatim:
    PrepareDataSequenceWise(data_file_name, false);
    break;
  case kFixed:
    PrepareDataWithFixedLength(data_file_name);
    break;
  }
}

Data::Data(const SequenceVector data,
           const int max_batch_size,
           const int max_sequence_length,
           ConstVocabularyPointer vocabulary)
    : data_(data),
      max_batch_size_(max_batch_size),
      max_sequence_length_(max_sequence_length),
      debug_no_sb_(false),
      vocabulary_(vocabulary) {
}

int64_t Data::ReadIndices(const std::string &data_file_name,
                          const ConstVocabularyPointer &vocabulary,
                          SequenceVector *data) {
  int64_t num_running_words = 0;
  assert(data->empty());
  // read text from file
  ReadableFile file(data_file_name);
  std::string line, word;
  while (file.GetLine(&line)) {
    // istringstream does not work with trailing whitespace (duplicate words)
    boost::trim(line);
    assert(!boost::algorithm::starts_with(line, "<s>"));
    assert(!boost::algorithm::ends_with(line, "</s>"));
    std::istringstream iss(line);
    std::vector<int> indices;
    while (!iss.eof()) {
      iss >> word;
      indices.push_back(vocabulary->GetIndex(word));
    }
    assert(!vocabulary->IsSentenceBoundary(word));
    if (!debug_no_sb_)
      indices.push_back(vocabulary->sb_index());
    num_running_words += indices.size();
    data->push_back(indices);
  }
  return num_running_words;
}

void Data::PrepareDataSequenceWise(const std::string &data_file_name,
                                   const bool concatenate) {
  SequenceVector indices;
  ReadIndices(data_file_name, vocabulary_, &indices);
  for (Sequence line : indices) {
    Append(max_sequence_length_ - 1, concatenate, &line);
  }

  // prepend last token of previous sequence
  if (!debug_no_sb_) {
    for (size_t i = 0; i < data_.size(); ++i) {
      data_[i].insert(data_[i].begin(),
                      i == 0 ? vocabulary_->sb_index() : data_[i - 1].back());
    }
  }
  SortBatches();
  for (auto &sentence : data_) {
    assert(sentence.size() <= static_cast<size_t>(max_sequence_length_));
  }
}

void Data::PrepareDataWithFixedLength(const std::string &data_file_name) {
  SequenceVector indices;
  int64_t num_running_words = ReadIndices(data_file_name, vocabulary_,
                                          &indices);
  assert(data_.empty());
  data_.resize(max_batch_size_, Sequence());
  int j = 0,
      batch = 0,
      // number of words per batch (incl. final <sb>, excl. overlapping words)
      n = static_cast<int>(num_running_words / max_batch_size_) +
          (static_cast<int>(num_running_words % max_batch_size_) > 0),
      last_word = vocabulary_->sb_index();
  for (Sequence line : indices) {
    // split current line into BPTT sequences
    while (line.size() > 0) {
      // last word used for probability computation, but not yet for training
      if (data_[j].empty())
        data_[j].push_back(last_word);
      const int num_move = std::min(std::min(static_cast<int>(line.size()),
          max_sequence_length_ - static_cast<int>(data_[j].size())), n);
      data_[j].insert(data_[j].end(), line.begin(), line.begin() + num_move);
      line.erase(line.begin(), line.begin() + num_move);
      n -= num_move;
      last_word = data_[j].back();
      // next BPTT sequence?
      if (data_[j].size() == max_sequence_length_) {
        if (batch == 0)
          data_.resize(data_.size() + max_batch_size_, Sequence());
        j += max_batch_size_;
      }
      // next batch?
      if (n == 0 && batch != max_batch_size_ - 1) {
        n = static_cast<int>(num_running_words / max_batch_size_) +
            (++batch < static_cast<int>(num_running_words % max_batch_size_));
        j = batch;
      }
    }
  }
  // we may have added too many empty lines in advance
  while (data_.back().empty())
    data_.pop_back();
}

void Data::Append(const size_t max_length,
                  const bool concatenate,
                  Sequence *current) {
  if (concatenate) {
    if (data_.empty())
      data_.push_back(Sequence());
    Sequence *last = &data_.back();
    if (last->size() + current->size() <= max_length) {
      // sentence can be appended
      last->insert(last->end(), current->begin(), current->end());
    } else if (current->size() <= max_length) {
      // sentence alone is not too long
      data_.push_back(*current);
    } else {
      // break at maximum lengths + append
      while (current->size() > 0) {
        const int size = std::min(max_length - last->size(), current->size());
        last->insert(last->end(), current->begin(), current->begin() + size);
        current->erase(current->begin(), current->begin() + size);
        if (current->size() > 0) {
          data_.push_back(std::vector<int>());
          last = &data_.back();
        }
      }
    }
  } else {
    data_.push_back(*current);
  }
}

void Data::SortBatches() {
  SequenceVector::iterator begin = data_.begin(), end;
  while (begin != data_.end()) {
    end = data_.end() - begin >= max_batch_size_ ?
          begin + max_batch_size_ : data_.end();
    std::sort(begin, end, [](const Sequence &s, const Sequence &t)
              { return s.size() > t.size(); });
    begin = end;
  }
}

ext: cc


text:
#include <DebugHelper.hpp>
#include <boost/interprocess/ipc/message_queue.hpp>
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <boost/interprocess/sync/named_sharable_mutex.hpp>
#include <boost/interprocess/sync/sharable_lock.hpp>

#include "GameFunctions.hpp"
#include <MessageTranslation/FlatbufferTranslator.hpp>
#include <MessageTranslation/StructToRLBotFlatbuffer.hpp>
#include <flatbuffers/flatbuffers.h>
#include <rlbot_generated.h>

#include <chrono>
#include <thread>
#include "RLBotSockets/bot_client.hpp"

namespace GameFunctions
{

	extern "C" void RLBOT_CORE_API Free(void* ptr)
	{
		free(ptr);
	}

	extern "C" RLBotCoreStatus RLBOT_CORE_API SetGameState(void* gameStateData, int size)
	{
		std::string game_state_message((char *)gameStateData, size);
		BotClientStatic::botClientInstance()->write(game_state_message, TcpClient::DataType::rlbot_state_setting);
		return RLBotCoreStatus::Success;
	}

	// Start match

	bool isValidName(wchar_t* pName)
	{
		for (int i = 0; i < sizeof(PlayerConfiguration::name) / sizeof(wchar_t); i++)
		{
			wchar_t wideChar = pName[i];

			if (wideChar == L'\0')
				return true;

			if (wideChar < L' ' || wideChar > L'~')
				return false;
		}

		return false;
	}

	RLBotCoreStatus checkPlayerConfiguration(PlayerConfiguration playerConfiguration[CONST_MaxPlayers], int numPlayers)
	{
		if (numPlayers < 0 || numPlayers > CONST_MaxPlayers)
			return RLBotCoreStatus::InvalidNumPlayers;

		for (int i = 0; i < numPlayers; i++)
		{
			PlayerConfiguration& playerConfig = playerConfiguration[i];

			if (playerConfig.bot)
			{
				if (!playerConfig.rlbotControlled)
				{
					if (playerConfig.botSkill < 0.0f || playerConfig.botSkill > 1.0f)
						return RLBotCoreStatus::InvalidBotSkill;
				}

				if (!isValidName(playerConfig.name))
					RLBotCoreStatus::InvalidName;
			}

			if (playerConfig.team < 0 || playerConfig.team > 1)
				return RLBotCoreStatus::InvalidTeam;

			if (playerConfig.teamColorID < 0 || playerConfig.teamColorID > 69)
				return RLBotCoreStatus::InvalidTeamColorID;

			if (playerConfig.customColorID < 0 || playerConfig.customColorID > 104)
				return RLBotCoreStatus::InvalidTeamColorID;

			//Todo: Add items validation
		}

		return RLBotCoreStatus::Success;
	}

	extern "C" RLBotCoreStatus RLBOT_CORE_API StartMatch(MatchSettings matchSettings)
	{
		int numPlayers = matchSettings.numPlayers;
		//ToDo: Check the other settings
		RLBotCoreStatus status = checkPlayerConfiguration(matchSettings.playerConfiguration, numPlayers);

		if (status != RLBotCoreStatus::Success)
			return status;

		flatbuffers::FlatBufferBuilder builder;
		StructToRLBotFlatbuffer::BuildStartMatchMessage(&builder, matchSettings);
		std::string start_match_string((char *) builder.GetBufferPointer(), builder.GetSize());
		BotClientStatic::botClientInstance()->write(start_match_string, TcpClient::DataType::rlbot_match_settings);

		return RLBotCoreStatus::Success;
	}

	extern "C" RLBotCoreStatus RLBOT_CORE_API StartMatchFlatbuffer(void* startMatchSettings, int size)
	{
		ByteBuffer buf;
		buf.ptr = startMatchSettings;
		buf.size = size;

		MatchSettings matchSettings = { 0 };

		FlatbufferTranslator::translateToMatchSettingsStruct(buf, &matchSettings);

		return StartMatch(matchSettings);
	}

	inline boost::asio::ip::address localhost = boost::asio::ip::address::from_string("127.0.0.1");
	boost::asio::io_context ioc;

	void run_ioc(int port) {
		ioc.run();
	}

	extern "C" RLBotCoreStatus RLBOT_CORE_API StartTcpCommunication(int port, int desiredTickRate, bool wantsBallPredictions, bool wantsQuickChat) {
		DEBUG_LOG("Beginning StartTcp.\n");
		BotClientStatic::initBotClient(port, &ioc, desiredTickRate, wantsBallPredictions, wantsQuickChat);
		std::thread io_thread(run_ioc, port);
		io_thread.detach();

		DEBUG_LOG("Returning from StartTcp.\n");
		return RLBotCoreStatus::Success;
	}
}

max_stars_repo_name: akaBrainlin/RLBot

max_issues_repo_name: akaBrainlin/RLBot

max_forks_repo_name: akaBrainlin/RLBot


text:
#include "rmsd_align.hpp"
#include <Eigen/Dense>

#include <iostream> // delete me

namespace timemachine {

/*
Optimally align x2 onto x1. In particular, x2 is shifted so that its centroid is placed
at the same position as the of x1's centroid. x2 is also rotated so that the RMSD
is minimized.
*/
void rmsd_align_cpu(const int N, const double *x1_raw, const double *x2_raw, double *x2_aligned_raw) {

    Eigen::MatrixXd x1(N, 3);
    Eigen::MatrixXd x2(N, 3);

    for (int i = 0; i < N; i++) {
        x1(i, 0) = x1_raw[i * 3 + 0];
        x1(i, 1) = x1_raw[i * 3 + 1];
        x1(i, 2) = x1_raw[i * 3 + 2];

        x2(i, 0) = x2_raw[i * 3 + 0];
        x2(i, 1) = x2_raw[i * 3 + 1];
        x2(i, 2) = x2_raw[i * 3 + 2];
    }

    Eigen::Vector3d x1_centroid = x1.colwise().mean();
    Eigen::Vector3d x2_centroid = x2.colwise().mean();
    Eigen::Vector3d translation = x2_centroid - x1_centroid;

    // shift to the center
    Eigen::MatrixXd x1_centered = x1.rowwise() - x1_centroid.transpose();
    Eigen::MatrixXd x2_centered = x2.rowwise() - x2_centroid.transpose();

    // compute correlations
    Eigen::MatrixXd c = x2_centered.transpose() * x1_centered;
    Eigen::JacobiSVD<Eigen::MatrixXd> svd(c, Eigen::ComputeFullU | Eigen::ComputeFullV);
    auto s = svd.singularValues();

    Eigen::MatrixXd u = svd.matrixU();
    Eigen::MatrixXd v = svd.matrixV();
    Eigen::MatrixXd v_t = v.transpose();

    bool is_reflection = u.determinant() * v_t.determinant() < 0.0;
    if (is_reflection) {
        for (int i = 0; i < 3; i++) {
            u(i, 2) = -u(i, 2);
        }
    }

    Eigen::MatrixXd rotation = u * v_t;

    // x2 is centered
    Eigen::MatrixXd x2_rot = x2_centered * rotation;
    Eigen::MatrixXd x2_aligned = x2_rot.rowwise() - (translation.transpose() - x2_centroid.transpose());

    for (int i = 0; i < N; i++) {
        x2_aligned_raw[i * 3 + 0] = x2_aligned(i, 0);
        x2_aligned_raw[i * 3 + 1] = x2_aligned(i, 1);
        x2_aligned_raw[i * 3 + 2] = x2_aligned(i, 2);
    }
}

} // namespace timemachine

max_stars_repo_name: proteneer/timemachine

max_issues_repo_name: proteneer/timemachine

max_forks_repo_name: proteneer/timemachine


text:
#include <boost/property_tree/info_parser.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <iostream>

namespace pt = boost::property_tree;

static void
usage()
{
  std::cerr << "USAGE\n"
               "  infoconv info2json < config.info > config.json\n"
               "  infoconv json2info < config.info > config.info\n"
               "  infoconv info2xml  < config.info > config.xml\n"
               "  infoconv xml2info  < config.xml  > config.info\n";
}

static void
info2json()
{
  pt::ptree tree;
  pt::info_parser::read_info(std::cin, tree);
  pt::json_parser::write_json(std::cout, tree);
}

static void
json2info()
{
  pt::ptree tree;
  pt::json_parser::read_json(std::cin, tree);
  pt::info_parser::write_info(std::cout, tree);
}

static void
info2xml()
{
  pt::ptree tree;
  pt::info_parser::read_info(std::cin, tree);
  pt::xml_parser::write_xml(std::cout, tree);
}

static void
xml2info()
{
  pt::ptree tree;
  pt::xml_parser::read_xml(std::cin, tree);
  pt::info_parser::write_info(std::cout, tree);
}

int
main(int argc, char** argv)
{
  if (argc != 2) {
    usage();
    return 2;
  }
  std::string action(argv[1]);
  if (action == "info2json") {
    info2json();
  } else if (action == "json2info") {
    json2info();
  } else if (action == "info2xml") {
    info2xml();
  } else if (action == "xml2info") {
    xml2info();
  } else {
    usage();
    return 2;
  }
}

max_stars_repo_name: NDN-Routing/infoedit

max_issues_repo_name: NDN-Routing/infoedit

max_forks_repo_name: NDN-Routing/infoedit