text:
/**
 * @file _httpservice.cpp
 * @brief Internal definitions of the Http service thread
 *
 * $LicenseInfo:firstyear=2012&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2012-2013, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "_httpservice.h"

#include <boost/bind.hpp>
#include <boost/function.hpp>

#include "_httpoperation.h"
#include "_httprequestqueue.h"
#include "_httppolicy.h"
#include "_httplibcurl.h"
#include "_thread.h"
#include "_httpinternal.h"

#include "lltimer.h"
#include "llthread.h"

namespace LLCore
{

const HttpService::OptionDescriptor HttpService::sOptionDesc[] =
{ //    isLong     isDynamic  isGlobal    isClass
	{	true,		true,		true,		true	},		// PO_CONNECTION_LIMIT
	{	true,		true,		false,		true	},		// PO_PER_HOST_CONNECTION_LIMIT
	{	false,		false,		true,		false	},		// PO_CA_PATH
	{	false,		false,		true,		false	},		// PO_CA_FILE
	{	false,		true,		true,		false	},		// PO_HTTP_PROXY
	{	true,		true,		true,		false	},		// PO_LLPROXY
	{	true,		true,		true,		false	},		// PO_TRACE
	{	true,		true,		false,		true	},		// PO_ENABLE_PIPELINING
	{	true,		true,		false,		true	}		// PO_THROTTLE_RATE
};
HttpService * HttpService::sInstance(NULL);
volatile HttpService::EState HttpService::sState(NOT_INITIALIZED);

HttpService::HttpService()
	: mRequestQueue(NULL),
	  mExitRequested(0U),
	  mThread(NULL),
	  mPolicy(NULL),
	  mTransport(NULL),
	  mLastPolicy(0)
{}

HttpService::~HttpService()
{
	mExitRequested = 1U;
	if (RUNNING == sState)
	{
		// Trying to kill the service object with a running thread
		// is a bit tricky.
		if (mRequestQueue)
		{
			mRequestQueue->stopQueue();
		}

		if (mThread)
		{
			if (! mThread->timedJoin(250))
			{
				// Failed to join, expect problems ahead so do a hard termination.
				mThread->cancel();

				LL_WARNS("CoreHttp") << "Destroying HttpService with running thread.  Expect problems."
									 << LL_ENDL;
			}
		}
	}

	if (mRequestQueue)
	{
		mRequestQueue->release();
		mRequestQueue = NULL;
	}

	delete mTransport;
	mTransport = NULL;

	delete mPolicy;
	mPolicy = NULL;

	if (mThread)
	{
		mThread->release();
		mThread = NULL;
	}
}

void HttpService::init(HttpRequestQueue * queue)
{
	llassert_always(! sInstance);
	llassert_always(NOT_INITIALIZED == sState);
	sInstance = new HttpService();

	queue->addRef();
	sInstance->mRequestQueue = queue;
	sInstance->mPolicy = new HttpPolicy(sInstance);
	sInstance->mTransport = new HttpLibcurl(sInstance);
	sState = INITIALIZED;
}

void HttpService::term()
{
	if (sInstance)
	{
		if (RUNNING == sState && sInstance->mThread)
		{
			// Unclean termination.  Thread appears to be running.  We'll
			// try to give the worker thread a chance to cancel using the
			// exit flag...
			sInstance->mExitRequested = 1U;
			sInstance->mRequestQueue->stopQueue();

			// And a little sleep
			for (int i(0); i < 10 && RUNNING == sState; ++i)
			{
				ms_sleep(100);
			}
		}

		delete sInstance;
		sInstance = NULL;
	}
	sState = NOT_INITIALIZED;
}

HttpRequest::policy_t HttpService::createPolicyClass()
{
	mLastPolicy = mPolicy->createPolicyClass();
	return mLastPolicy;
}

bool HttpService::isStopped()
{
	// What is really wanted here is something like:
	//
	//     HttpService * service = instanceOf();
	//     return STOPPED == sState && (! service || ! service->mThread || ! service->mThread->joinable());
	//
	// But boost::thread is not giving me a consistent story on joinability
	// of a thread after it returns.  Debug and non-debug builds are showing
	// different behavior on Linux/Etch so we do a weaker test that may
	// not be globally correct (i.e. thread *is* stopping, may not have
	// stopped but will very soon):

	return STOPPED == sState;
}

/// Threading:  callable by consumer thread *once*.
void HttpService::startThread()
{
	llassert_always(! mThread || STOPPED == sState);
	llassert_always(INITIALIZED == sState || STOPPED == sState);

	if (mThread)
	{
		mThread->release();
	}

	// Push current policy definitions, enable policy & transport components
	mPolicy->start();
	mTransport->start(mLastPolicy + 1);

	mThread = new LLCoreInt::HttpThread(boost::bind(&HttpService::threadRun, this, _1));
	sState = RUNNING;
}

/// Threading:  callable by worker thread.
void HttpService::stopRequested()
{
	mExitRequested = 1U;
}

/// Threading:  callable by worker thread.
bool HttpService::changePriority(HttpHandle handle, HttpRequest::priority_t priority)
{
	bool found(false);

	// Skip the request queue as we currently don't leave earlier
	// requests sitting there.  Start with the ready queue...
	found = mPolicy->changePriority(handle, priority);

	// If not there, we could try the transport/active queue but priority
	// doesn't really have much effect there so we don't waste cycles.

	return found;
}

/// Try to find the given request handle on any of the request
/// queues and cancel the operation.
///
/// @return			True if the request was canceled.
///
/// Threading:  callable by worker thread.
bool HttpService::cancel(HttpHandle handle)
{
	bool canceled(false);

	// Request can't be on request queue so skip that.

	// Check the policy component's queues first
	canceled = mPolicy->cancel(handle);

	if (! canceled)
	{
		// If that didn't work, check transport's.
		canceled = mTransport->cancel(handle);
	}

	return canceled;
}

/// Threading:  callable by worker thread.
void HttpService::shutdown()
{
	// Disallow future enqueue of requests
	mRequestQueue->stopQueue();

	// Cancel requests already on the request queue
	HttpRequestQueue::OpContainer ops;
	mRequestQueue->fetchAll(false, ops);
	while (! ops.empty())
	{
		HttpOperation * op(ops.front());
		ops.erase(ops.begin());

		op->cancel();
		op->release();
	}

	// Shutdown transport canceling requests, freeing resources
	mTransport->shutdown();

	// And now policy
	mPolicy->shutdown();
}

// Working thread loop-forever method.  Gives time to
// each of the request queue, policy layer and transport
// layer pieces and then either sleeps for a small time
// or waits for a request to come in.  Repeats until
// requested to stop.
void HttpService::threadRun(LLCoreInt::HttpThread * thread)
{
	boost::this_thread::disable_interruption di;

	LLThread::registerThreadID();

	ELoopSpeed loop(REQUEST_SLEEP);
	while (! mExitRequested)
	{
		loop = processRequestQueue(loop);

		// Process ready queue issuing new requests as needed
		ELoopSpeed new_loop = mPolicy->processReadyQueue();
		loop = (std::min)(loop, new_loop);

		// Give libcurl some cycles
		new_loop = mTransport->processTransport();
		loop = (std::min)(loop, new_loop);

		// Determine whether to spin, sleep briefly or sleep for next request
		if (REQUEST_SLEEP != loop)
		{
			ms_sleep(HTTP_SERVICE_LOOP_SLEEP_NORMAL_MS);
		}
	}

	shutdown();
	sState = STOPPED;
}

HttpService::ELoopSpeed HttpService::processRequestQueue(ELoopSpeed loop)
{
	HttpRequestQueue::OpContainer ops;
	const bool wait_for_req(REQUEST_SLEEP == loop);

	mRequestQueue->fetchAll(wait_for_req, ops);
	while (! ops.empty())
	{
		HttpOperation * op(ops.front());
		ops.erase(ops.begin());

		// Process operation
		if (! mExitRequested)
		{
			// Setup for subsequent tracing
			long tracing(HTTP_TRACE_OFF);
			mPolicy->getGlobalOptions().get(HttpRequest::PO_TRACE, &tracing);
			op->mTracing = (std::max)(op->mTracing, int(tracing));

			if (op->mTracing > HTTP_TRACE_OFF)
			{
				LL_INFOS("CoreHttp") << "TRACE, FromRequestQueue, Handle:  "
									 << static_cast<HttpHandle>(op)
									 << LL_ENDL;
			}

			// Stage
			op->stageFromRequest(this);
		}

		// Done with operation
		op->release();
	}

	// Queue emptied, allow polling loop to sleep
	return REQUEST_SLEEP;
}

HttpStatus HttpService::getPolicyOption(HttpRequest::EPolicyOption opt, HttpRequest::policy_t pclass,
										long * ret_value)
{
	if (opt < HttpRequest::PO_CONNECTION_LIMIT											// option must be in range
		|| opt >= HttpRequest::PO_LAST													// ditto
		|| (! sOptionDesc[opt].mIsLong)													// datatype is long
		|| (pclass != HttpRequest::GLOBAL_POLICY_ID && pclass > mLastPolicy)			// pclass in valid range
		|| (pclass == HttpRequest::GLOBAL_POLICY_ID && ! sOptionDesc[opt].mIsGlobal)	// global setting permitted
		|| (pclass != HttpRequest::GLOBAL_POLICY_ID && ! sOptionDesc[opt].mIsClass))	// class setting permitted
																						// can always get, no dynamic check
	{
		return HttpStatus(HttpStatus::LLCORE, LLCore::HE_INVALID_ARG);
	}

	HttpStatus status;
	if (pclass == HttpRequest::GLOBAL_POLICY_ID)
	{
		HttpPolicyGlobal & opts(mPolicy->getGlobalOptions());

		status = opts.get(opt, ret_value);
	}
	else
	{
		HttpPolicyClass & opts(mPolicy->getClassOptions(pclass));

		status = opts.get(opt, ret_value);
	}

	return status;
}

HttpStatus HttpService::getPolicyOption(HttpRequest::EPolicyOption opt, HttpRequest::policy_t pclass,
										std::string * ret_value)
{
	HttpStatus status(HttpStatus::LLCORE, LLCore::HE_INVALID_ARG);

	if (opt < HttpRequest::PO_CONNECTION_LIMIT											// option must be in range
		|| opt >= HttpRequest::PO_LAST													// ditto
		|| (sOptionDesc[opt].mIsLong)													// datatype is string
		|| (pclass != HttpRequest::GLOBAL_POLICY_ID && pclass > mLastPolicy)			// pclass in valid range
		|| (pclass == HttpRequest::GLOBAL_POLICY_ID && ! sOptionDesc[opt].mIsGlobal)	// global setting permitted
		|| (pclass != HttpRequest::GLOBAL_POLICY_ID && ! sOptionDesc[opt].mIsClass))	// class setting permitted
																						// can always get, no dynamic check
	{
		return status;
	}

	// Only global has string values
	if (pclass == HttpRequest::GLOBAL_POLICY_ID)
	{
		HttpPolicyGlobal & opts(mPolicy->getGlobalOptions());

		status = opts.get(opt, ret_value);
	}

	return status;
}

HttpStatus HttpService::setPolicyOption(HttpRequest::EPolicyOption opt, HttpRequest::policy_t pclass,
										long value, long * ret_value)
{
	HttpStatus status(HttpStatus::LLCORE, LLCore::HE_INVALID_ARG);

	if (opt < HttpRequest::PO_CONNECTION_LIMIT											// option must be in range
		|| opt >= HttpRequest::PO_LAST													// ditto
		|| (! sOptionDesc[opt].mIsLong)													// datatype is long
		|| (pclass != HttpRequest::GLOBAL_POLICY_ID && pclass > mLastPolicy)			// pclass in valid range
		|| (pclass == HttpRequest::GLOBAL_POLICY_ID && ! sOptionDesc[opt].mIsGlobal)	// global setting permitted
		|| (pclass != HttpRequest::GLOBAL_POLICY_ID && ! sOptionDesc[opt].mIsClass)		// class setting permitted
		|| (RUNNING == sState && ! sOptionDesc[opt].mIsDynamic))						// dynamic setting permitted
	{
		return status;
	}

	if (pclass == HttpRequest::GLOBAL_POLICY_ID)
	{
		HttpPolicyGlobal & opts(mPolicy->getGlobalOptions());

		status = opts.set(opt, value);
		if (status && ret_value)
		{
			status = opts.get(opt, ret_value);
		}
	}
	else
	{
		HttpPolicyClass & opts(mPolicy->getClassOptions(pclass));

		status = opts.set(opt, value);
		if (status && ret_value)
		{
			status = opts.get(opt, ret_value);
		}
	}

	return status;
}

HttpStatus HttpService::setPolicyOption(HttpRequest::EPolicyOption opt, HttpRequest::policy_t pclass,
										const std::string & value, std::string * ret_value)
{
	HttpStatus status(HttpStatus::LLCORE, LLCore::HE_INVALID_ARG);

	if (opt < HttpRequest::PO_CONNECTION_LIMIT											// option must be in range
		|| opt >= HttpRequest::PO_LAST													// ditto
		|| (sOptionDesc[opt].mIsLong)													// datatype is string
		|| (pclass != HttpRequest::GLOBAL_POLICY_ID && pclass > mLastPolicy)			// pclass in valid range
		|| (pclass == HttpRequest::GLOBAL_POLICY_ID && ! sOptionDesc[opt].mIsGlobal)	// global setting permitted
		|| (pclass != HttpRequest::GLOBAL_POLICY_ID && ! sOptionDesc[opt].mIsClass)		// class setting permitted
		|| (RUNNING == sState && ! sOptionDesc[opt].mIsDynamic))						// dynamic setting permitted
	{
		return status;
	}

	// Only string values are global at this time
	if (pclass == HttpRequest::GLOBAL_POLICY_ID)
	{
		HttpPolicyGlobal & opts(mPolicy->getGlobalOptions());

		status = opts.set(opt, value);
		if (status && ret_value)
		{
			status = opts.get(opt, ret_value);
		}
	}

	return status;
}

}  // end namespace LLCore

max_stars_repo_name: humbletim/archived-casviewer

max_issues_repo_name: humbletim/archived-casviewer

max_forks_repo_name: humbletim/archived-casviewer


text:
// Copyright Louis Dionne 2013-2016
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)

#include <boost/hana/assert.hpp>
#include <boost/hana/contains.hpp>
#include <boost/hana/find.hpp>
#include <boost/hana/integral_constant.hpp>
#include <boost/hana/optional.hpp>
#include <boost/hana/string.hpp>
namespace hana = boost::hana;

int main() {
    BOOST_HANA_CONSTANT_CHECK(hana::char_c<'c'> ^hana::in^ BOOST_HANA_STRING("abcde"));
    BOOST_HANA_CONSTANT_CHECK(!(hana::char_c<'z'> ^hana::in^ BOOST_HANA_STRING("abcde")));

    BOOST_HANA_CONSTANT_CHECK(
        hana::find(BOOST_HANA_STRING("abcxefg"), hana::char_c<'x'>) == hana::just(hana::char_c<'x'>)
    );
}

ext: cpp

max_issues_repo_name: lipper/arangodb

max_forks_repo_name: lipper/arangodb


text:
#include <cstdlib>
#include <iostream>
#include <complex>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/bindings/lower.hpp>
#include <boost/numeric/bindings/upper.hpp>
#include <boost/numeric/bindings/ublas/matrix.hpp>
#include <boost/numeric/bindings/blas/level3.hpp>
#include <boost/numeric/bindings/conj.hpp>
#include "print.hpp"
#include "random.hpp"

namespace ublas=boost::numeric::ublas;
namespace blas=boost::numeric::bindings::blas;

int main(int argc, char *argv[]) {
  {
    typedef std::complex<double> complex;
    typedef ublas::matrix<complex, ublas::column_major> matrix;
    typedef matrix::size_type size_type;
    rand_normal<complex>::reset();
    size_type n=8;
    matrix A(n, n), B(n, n), C(n, n);
    for (size_type j=0; j<n; ++j)
      for (size_type i=0; i<n; ++i) {
	A(i, j)=rand_normal<complex>::get();
	B(i, j)=rand_normal<complex>::get();
      }
    for (size_type j=0; j<n; ++j) {
      for (size_type i=0; i<j; ++i) {
	C(i, j)=rand_normal<complex>::get();
	C(j, i)=std::conj(C(i, j));
      }
      C(j, j)=rand_normal<complex>::get().real();
    }
    complex alpha(rand_normal<complex>::get());
    double beta(rand_normal<complex>::get().real());
    {
      matrix C1(alpha*ublas::prod(A, ublas::trans(ublas::conj(B)))+
		std::conj(alpha)*ublas::prod(B, ublas::trans(ublas::conj(A)))+
		beta*C);
      for (size_type j=0; j<n; ++j)
	for (size_type i=j+1; i<n; ++i)
	  C1(i, j)=C(i, j);
      matrix C2(C);
      blas::her2k(alpha, A, B, beta, blas::upper(C2));
      std::cout << "testing boost::ublas containers\n"
		<< "using ublas (A right htrans, C upper):\n" << print_mat(C1) << '\n'
		<< "using blas (A right htrans, C upper):\n" << print_mat(C2) << '\n'
		<< '\n';
    }
    {
      matrix C1(alpha*ublas::prod(A, ublas::trans(ublas::conj(B)))+
		std::conj(alpha)*ublas::prod(B, ublas::trans(ublas::conj(A)))+
		beta*C);
      for (size_type j=0; j<n; ++j)
    	for (size_type i=0; i<j; ++i)
    	  C1(i, j)=C(i, j);
      matrix C2(C);
      blas::her2k(alpha, A, B, beta, blas::lower(C2));
      std::cout << "testing boost::ublas containers\n"
    		<< "using ublas (A right htrans, C lower):\n" << print_mat(C1) << '\n'
    		<< "using blas (A right htrans, C lower):\n" << print_mat(C2) << '\n'
    		<< '\n';
    }
    {
      matrix C1(alpha*ublas::prod(ublas::trans(ublas::conj(A)), B)+
		std::conj(alpha)*ublas::prod(ublas::trans(ublas::conj(B)), A)+
		beta*C);
      for (size_type j=0; j<n; ++j)
    	for (size_type i=j+1; i<n; ++i)
    	  C1(i, j)=C(i, j);
      matrix C2(C);
      blas::her2k(alpha, blas::conj(A), B, beta, blas::upper(C2));
      std::cout << "testing boost::ublas containers\n"
    		<< "using ublas (A left htrans, C upper):\n" << print_mat(C1) << '\n'
    		<< "using blas (A left htrans, C upper):\n" << print_mat(C2) << '\n'
    		<< '\n';
    }
    {
      matrix C1(alpha*ublas::prod(ublas::trans(ublas::conj(A)), B)+
		std::conj(alpha)*ublas::prod(ublas::trans(ublas::conj(B)), A)+
		beta*C);
      for (size_type j=0; j<n; ++j)
    	for (size_type i=0; i<j; ++i)
    	  C1(i, j)=C(i, j);
      matrix C2(C);
      blas::her2k(alpha, blas::conj(A), B, beta, blas::lower(C2));
      std::cout << "testing boost::ublas containers\n"
    		<< "using ublas (A left htrans, C lower):\n" << print_mat(C1) << '\n'
    		<< "using blas (A left htrans, C lower):\n" << print_mat(C2) << '\n'
    		<< '\n';
    }
  }
  return EXIT_SUCCESS;
}

ext: cc


text:
#include <limits>
#include <memory>
#include <stdexcept>
#include <unordered_map>
#include <boost/filesystem.hpp>
#include <Minigames-Services/Acores.hpp>
#include <Minigames-Services/Bermudes.hpp>
#include <Minigames-Services/Canaries.hpp>
#include <Minigames-Services/ChatService.hpp>
#include <Minigames-Services/LobbyService.hpp>
#include <Minigames-Services/MinigameService.hpp>
#include <RpT-Config/Config.hpp>
#include <RpT-Core/Executor.hpp>
#include <RpT-Core/InputEvent.hpp>
#include <RpT-Network/SafeBeastWebsocketBackend.hpp>
#include <RpT-Network/UnsafeBeastWebsocketBackend.hpp>
#include <RpT-Utils/CommandLineOptionsParser.hpp>

constexpr int SUCCESS { 0 };
constexpr int INVALID_ARGS { 1 };
constexpr int RUNTIME_ERROR { 2 };

constexpr std::uint16_t DEFAULT_PORT { 35555 };

/// Represents a parsed option for one of the 3 available RpT Minigames
enum struct Minigame {
    Acores, Bermudes, Canaries
};

/**
 * @brief Parses RpT Minigame string and converts it to enum value.
 *
 * @param rpt_minigame String representing initial letter of selected minigame
 *
 * @throws std::invalid_argument if `rpt_minigame` first char isn't 'a', 'b' or 'c' or it has not a length of 1
 *
 * @returns Corresponding `Minigame` enum value
 */
constexpr Minigame parseMinigame(const std::string_view rpt_minigame) {
    if (rpt_minigame.length() != 1) // An abbreviation is the first letter so it must be a single char string
        throw std::invalid_argument { "RpT Minigame abbreviation must be a single letter" };

    const char minigame_initial_letter { rpt_minigame.at(0) };

    if (minigame_initial_letter == 'a')
        return Minigame::Acores;
    else if (minigame_initial_letter == 'b')
        return Minigame::Bermudes;
    else if (minigame_initial_letter == 'c')
        return Minigame::Canaries;
    else {
        throw std::invalid_argument {
            std::string { "Unable to parse minigame name for abbreviation " } + minigame_initial_letter
        };
    }
}

/**
 * @brief Parses log level string and converts to enum value.
 *
 * @param level String or first char of log level
 *
 * @throws std::invalid_argument If level string cannot be parsed into LogLevel value
 *
 * @return Corresponding `RpT::Core::LogLevel` enum value
 */
constexpr RpT::Utils::LogLevel parseLogLevel(const std::string_view level) {
    if (level == "t" || level == "trace")
        return RpT::Utils::LogLevel::TRACE;
    else if (level == "d" || level == "debug")
        return RpT::Utils::LogLevel::DEBUG;
    else if (level == "i" || level == "info")
        return RpT::Utils::LogLevel::INFO;
    else if (level == "w" || level == "warn")
        return RpT::Utils::LogLevel::WARN;
    else if (level == "e" || level == "error")
        return RpT::Utils::LogLevel::ERR;
    else if (level == "f" || level == "fatal")
        return RpT::Utils::LogLevel::FATAL;
    else
        throw std::invalid_argument { "Unable to parse level \"" + std::string { level }+ "\"" };
}

int main(const int argc, const char** argv) {
    RpT::Utils::LoggingContext server_logging;
    RpT::Utils::LoggerView logger { "Main", server_logging };

    try {
        // Read and parse command line options
        const RpT::Utils::CommandLineOptionsParser cmd_line_options {
            argc, argv, { "game", "log-level", "testing", "ip", "port", "net-backend", "crt", "privkey" }
        };

        // Get game name from command line options and parses it to an available RpT Minigame
        const std::string_view game_abbreviation { cmd_line_options.get("game") };
        const Minigame selected_minigame { parseMinigame(game_abbreviation) };

        logger.info("Playing on game {}", game_abbreviation);

        // Try to get and parse logging level from command line options
        if (cmd_line_options.has("log-level")) { // Only if option is enabled
            try {
                // Get option value from command line
                const std::string_view log_level_argument { cmd_line_options.get("log-level") };
                // Parse option value
                const RpT::Utils::LogLevel parsed_log_level { parseLogLevel(log_level_argument) };

                server_logging.updateLoggingLevel(parsed_log_level);
                logger.debug("Logging level set to \"{}\".", log_level_argument);
            } catch (const std::logic_error& err) { // Option value may be missing, or parse may fail
                logger.error("Log-level parsing: {}", err.what());
                logger.warn("log-level option has been ignored, \"info\" will be used.");
            }
        }

        std::uint16_t server_local_port;
        // Try to get and parse server local port from command line options
        if (cmd_line_options.has("port")) {
            // String copy must be created anyway to use stoull function
            const std::string port_argument { cmd_line_options.get("port") };
            const std::uint64_t parsed_port { std::stoull(port_argument) };

            if (parsed_port > std::numeric_limits<std::uint16_t>::max())
                throw RpT::Utils::OptionsError { "port argument must be included inside 0..65535" };

            logger.debug("Switch listening port to {}", parsed_port);

            server_local_port = parsed_port;
        } else { // If option isn't specified, use default value
            logger.debug("Keeps default listening port {}", DEFAULT_PORT);

            server_local_port = DEFAULT_PORT;
        }

        // Default local protocol is IPv4
        boost::asio::ip::tcp server_local_protocol { boost::asio::ip::tcp::v4() };
        // Try to get and parse provided custom protocol from command line options
        if (cmd_line_options.has("ip")) {
            const std::string_view mode { cmd_line_options.get("ip") };

            // Must be IPv4 or IPv6 mode
            if (mode == "v4") { // Nothing to, as default is already IPv4
                logger.debug("Keeps mode IPv4, as specified by command line options");
            } else if (mode == "v6") {
                logger.debug("Switch to IPv6 mode, as specified by command line options");

                server_local_protocol = boost::asio::ip::tcp::v6();
            } else {
                throw RpT::Utils::OptionsError { "Unknown IP protocol: " + std::string { mode } };
            }
        } else {
            logger.debug("Keeps mode IPv4, no command line options \"ip\"");
        }

        logger.info("Running minigames server {} on {}.", RpT::Config::VERSION, RpT::Config::runtimePlatformName());

        // Selected backend for IO interface, defaults to WSS (Safe Websocket)
        std::string_view selected_network_bakcend { "wss" };
        // If backend is supplied by command line options, then override default behavior
        if (cmd_line_options.has("net-backend"))
            selected_network_bakcend = cmd_line_options.get("net-backend");

        // Dynamic selection from command line options, requires dynamic allocation
        std::unique_ptr<RpT::Network::NetworkBackend> network_backend;
        // Local server endpoint evaluated from configurable port and IP protocol version
        const boost::asio::ip::tcp::endpoint server_local_endpoint { server_local_protocol, server_local_port };

        if (selected_network_bakcend == "wss") { // Websockets switched from HTTPS
            logger.debug("Using Secure Websocket backend for IO interface.");

            // Retrieves and copies options from command line
            const std::string certificate_option { cmd_line_options.get("crt") };
            const std::string private_key_option { cmd_line_options.get("privkey") };

            // Get and parse valid paths from appropriate command line options
            const boost::filesystem::path certificate_path { certificate_option };
            const boost::filesystem::path private_path { private_key_option };

            // Checks for both path validity and file type

            if (!boost::filesystem::is_regular_file(certificate_path))
                throw RpT::Utils::OptionsError { "Given certificate path isn't a valid path to regular file" };

            if (!boost::filesystem::is_regular_file(private_path))
                throw RpT::Utils::OptionsError { "Given private key path isn't a valid path to reguler file" };

            // If both paths are valid, uses them to build backend with appropriate TLS features configuration
            network_backend = std::make_unique<RpT::Network::SafeBeastWebsocketBackend>(
                    certificate_option, private_key_option, server_local_endpoint, server_logging);
        } else if (selected_network_bakcend == "unsafe-ws") { // Websockets switched from HTTP
            logger.debug("Using NON-Secure Websocket backend for IO interface.");

            network_backend = std::make_unique<RpT::Network::UnsafeBeastWebsocketBackend>(
                    server_local_endpoint, server_logging);
        } else { // Unknown network backend
            const std::string backend_copy { selected_network_bakcend }; // Copy required for string concat

            throw RpT::Utils::OptionsError { "Unknown networking backend " + backend_copy };
        }

        /*
         * Create executor with listed resources paths, game name argument and run main loop with dynamically
         * initialized NetworkBackend implementation
         */

        // For testing if executable is properly launched inside continuous integration, main loop must not continue
        if (cmd_line_options.has("testing")) {
            logger.info("Testing mode for CI, server will be immediately closed.");

            network_backend->close();
        }

        /*
         * Initializes executor for main loop without user-provided callbacks
         */

        RpT::Core::Executor rpt_executor { *network_backend, server_logging };

        /*
         * Initializes online services
         */

        // Provides a polymorphic minigame depending on command line parsed options
        MinigamesServices::BoardGameProvider game_provider {
                [selected_minigame]() -> std::unique_ptr<MinigamesServices::BoardGame> {
                    switch (selected_minigame) {
                    case Minigame::Acores:
                        return std::make_unique<MinigamesServices::Acores>();
                    case Minigame::Bermudes:
                        return std::make_unique<MinigamesServices::Bermudes>();
                    case Minigame::Canaries:
                        return std::make_unique<MinigamesServices::Canaries>();
                    }
                }
        };

        RpT::Core::ServiceContext services_context;
        MinigamesServices::ChatService chat_svc { services_context, 2000 };
        MinigamesServices::MinigameService minigame_svc { services_context, std::move(game_provider) };
        MinigamesServices::LobbyService lobby_svc { services_context, minigame_svc, 5000 };

        /*
         * Adds and removes players from Lobby when actors connects or disconnects to server
         */

        rpt_executor.handle<RpT::Core::JoinedEvent>([&lobby_svc](const RpT::Core::JoinedEvent& event) {
            lobby_svc.assignActor(event.actor());
        });

        rpt_executor.handle<RpT::Core::LeftEvent>([&lobby_svc, &minigame_svc](const RpT::Core::LeftEvent& event) {
            lobby_svc.removeActor(event.actor());

            // If one of the two players is disconnected during a game, then it should stop or it would never end
            if (minigame_svc.isStarted())
                minigame_svc.stop();
        });

        bool game_was_running { false }; // Previous loop iteration MinigameService state
        rpt_executor.make([&game_was_running, &lobby_svc, &minigame_svc]() {
            const bool is_game_running { minigame_svc.isStarted() }; // Current loop iteration MinigameService state

            // For each loop iteration, if the game go from running to not running, it stopped and clients must be
            // notified about that
            if (game_was_running && !is_game_running)
                lobby_svc.notifyWaiting();

            // Save this loop iteration result for the next iteration check
            game_was_running = is_game_running;
        });

        const bool done_successfully { rpt_executor.run({ chat_svc, minigame_svc, lobby_svc }) };

        // Process exit code depends on main loop result
        if (done_successfully) {
            logger.info("Successfully shut down.");

            return SUCCESS;
        } else {
            logger.fatal("Shut down for unhandled error.");

            return RUNTIME_ERROR;
        }
    } catch (const RpT::Utils::OptionsError& err) {
        logger.fatal("Command line error: {}", err.what());

        return INVALID_ARGS;
    } catch (const std::exception& err) {
        logger.fatal("Unhandled runtime error: {}", err.what());

        return RUNTIME_ERROR;
    }
}

max_stars_repo_name: ThisALV/RpT-Minigames-Server

max_issues_repo_name: ThisALV/RpT-Minigames-Server

max_forks_repo_name: ThisALV/RpT-Minigames-Server


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

#include <ros/package.h>
#include <signal.h>
#include <boost/filesystem.hpp>
#include <chrono>
#include <iostream>
#include <memory>
#include <vector>
#include <ctime>
#include <ratio>
#include "kacanopen/core/canopen_error.h"
#include "kacanopen/core/core.h"
#include "kacanopen/core/logger.h"
#include "kacanopen/master/device.h"
#include "kacanopen/master/master.h"
#include "kacanopen/tools/device_rpdo.h"
#include "kacanopen/tools/device_tpdo.h"
#include "kacanopen/core/logger.h"
#include "kacanopen/ros_bridge/bridge.h"
#include "kacanopen/ros_bridge/entry_publisher.h"
#include "kacanopen/ros_bridge/entry_subscriber.h"
#include "kacanopen/ros_bridge/joint_state_publisher.h"
#include "kacanopen/ros_bridge/joint_state_subscriber.h"

#include <chrono>
#include <memory>
#include <thread>

static volatile int keepRunning = 1;

void intHandler(int dummy) {
  (void)dummy;
  keepRunning = 0;
}

bool printDeviceInfo(std::shared_ptr<kaco::Device> device) {
  try {
    std::string display_device_type;
    auto device_type =
        device->get_entry(0x1000, 0x0, kaco::ReadAccessMethod::sdo);
    if (131474 == static_cast<uint32_t>(device_type))
      display_device_type = "DS402";  // 131474 is the type number for DS-402;
    auto device_name =
        device->get_entry(0x1008, 0x0, kaco::ReadAccessMethod::sdo);
    auto vendor_id =
        device->get_entry(0x1018, 0x01, kaco::ReadAccessMethod::sdo);
    auto product_id =
        device->get_entry(0x1018, 0x02, kaco::ReadAccessMethod::sdo);
    auto revision =
        device->get_entry(0x1018, 0x03, kaco::ReadAccessMethod::sdo);

    auto serial_no =
        device->get_entry(0x1018, 0x04, kaco::ReadAccessMethod::sdo);

    std::cout << "" << std::endl;
    std::cout << "" << std::endl;
    std::cout << "*************************************************************"
              << std::endl;
    std::cout << "*************************************************************"
              << std::endl;
    std::cout << "* Device Name found as '" << device_name << "'" << std::endl;
    std::cout << "* Device Type found as CiA-" << display_device_type << "'"
              << std::endl;
    std::cout << "* Vendor ID=" << vendor_id << std::endl;
    std::cout << "* Product ID=" << product_id << std::endl;
    std::cout << "* Serial Number=" << serial_no << std::endl;
    std::cout << "* Revision Number=" << revision << std::endl;
    std::cout << "*************************************************************"
              << std::endl;
    std::cout << "*************************************************************"
              << std::endl;
    std::cout << "" << std::endl;
    std::cout << "" << std::endl;
    return true;
  } catch (...) {
    std::cout << "Exception occured while acquiring device information.!"
              << std::endl;
    return false;
  }
}

void initializeDevice(std::shared_ptr<kaco::Device> device,
                      uint16_t heartbeat_interval, uint8_t node_id) {
  // set the our desired heartbeat_interval time
  device->set_entry(0x1017, 0x0, heartbeat_interval,
                    kaco::WriteAccessMethod::sdo);

  // Mater side Periodic Tranmit pdo1 value initialization
  device->set_entry("target_velocity", 0x0, kaco::WriteAccessMethod::sdo);
  // device->set_entry("target_position", 0x0, kaco::WriteAccessMethod::sdo);

  device->set_entry("controlword", static_cast<uint16_t>(0x0006),
                    kaco::WriteAccessMethod::sdo);

  // Master side tpdo1 mapping
  device->add_transmit_pdo_mapping(
      0x200 + node_id, {{"target_velocity", 0}, {"controlword", 4}},
      kaco::TransmissionType::PERIODIC, std::chrono::milliseconds(5));

  // device->add_transmit_pdo_mapping(
  //     0x200 + node_id, {{"target_position", 0}, {"controlword", 4}},
  //     kaco::TransmissionType::PERIODIC, std::chrono::milliseconds(250));

  // Master side RPDO mapping starts here; This must be in line with device
  // side TPDOs

  // Master side rpdo1 mapping
  device->add_receive_pdo_mapping(0x180 + node_id, "velocity_actual_value",
                                  0);                                 // 32bit
  device->add_receive_pdo_mapping(0x180 + node_id, "position_actual_value",
                                  4);                                 // 32bit
  // device->add_receive_pdo_mapping(0x180 + node_id, "statusword", 4);  // 16bit
  // device->add_receive_pdo_mapping(0x180 + node_id, "error_code", 6);  // 16bit

  // Master side rpdo2 mapping
  // device->add_receive_pdo_mapping(0x280 + node_id, "position_actual_value",
  //                                 0);  // 32bit
  // device->add_receive_pdo_mapping(0x280 + node_id,
                                  // "current_actual_value",
                                  // 4);  // 32bit

  // // Master side rpdo3 mapping
  // device->add_receive_pdo_mapping(0x380 + node_id, "digital_inputs",
  //                                 0);  // 32bit
  // device->add_receive_pdo_mapping(0x380 + node_id, "torque_actual_value",
  //                                 4);  // 16bit
  // device->add_receive_pdo_mapping(
  //     0x380 + node_id, "torque_actual_values/torque_actual_value_averaged",
  //     6);  // 16bit

  // Master side RPDO mapping ends here

  /***************** TPDO MAPPING in DEVICE *****************/
  /// Device side TPDO mapping starts here. This must be in line with the
  /// master side RPDOs.

  // Device side tpdo1 mapping entries and mapping
  std::vector<uint32_t> tpdo1_entries_to_be_mapped = {0x606C0020, 0x60640020,
                                                      };
  map_tpdo_in_device(TPDO_1, tpdo1_entries_to_be_mapped, 255, device);

  // Device side tpdo2 mapping entries and mapping
  std::vector<uint32_t> tpdo2_entries_to_be_mapped = {0x60640020, 0x606C0020};
  // std::vector<uint32_t> tpdo2_entries_to_be_mapped = {0x60640020, 0x30D10220};
  map_tpdo_in_device(TPDO_2, tpdo2_entries_to_be_mapped, 255, device);

  // Device side tpdo3 mapping entries and mapping
  // std::vector<uint32_t> tpdo3_entries_to_be_mapped = {0x60FD0020, 0x60770010,
  //                                                     0x30D20110};
  // map_tpdo_in_device(TPDO_3, tpdo3_entries_to_be_mapped, 255, device);

  /// Device side TPDO mapping ends here;

  /***************** RPDO MAPPING in DEVICE *****************/
  /// Device side RPDO mapping starts here.This must be in line with the
  /// master side TPDOs.
  std::vector<uint32_t> rpdo1_entries_to_be_mapped = {
      0x60FF0020, 0x60400010,
  };
  map_rpdo_in_device(RPDO_1, rpdo1_entries_to_be_mapped, 255, device);
  /// Device side RPDO mapping ends here

  // Try to clear all possible errors in the CANOpen device
  device->set_entry("controlword", static_cast<uint16_t>(0x0080),
                    kaco::WriteAccessMethod::sdo);
}
using namespace std::chrono;
int main(int argc, char* argv[]) {

  // Create bridge
  ros::init(argc, argv, "canopen_bridge");
  kaco::Bridge bridge;

  // Signal handleing
  signal(SIGINT, intHandler);

  // ----------- //
  // Preferences //
  // ----------- //

  // A Roboteq motor driver with firmware version v2.0beta07032018 was used to
  // test this program.//

  // The node ID of the slave we want to communicate with.
  const uint8_t node_id_0 = 7;
  const uint8_t node_id_1 = 1;

  // Set the name of your CAN bus. "slcan0" is a common bus name
  // for the first SocketCAN device on a Linux system.
  const std::string busname = "can0";

  // Set the baudrate of your CAN bus. Most drivers support the values
  // "1M", "500K", "125K", "100K", "50K", "20K", "10K" and "5K".
  const std::string baudrate = "1M";

  // Set the heartbeat interval for slave device. Most drivers support the
  // values can be "125", "250", "500" and "1000" millisecond.
  const uint16_t heartbeat_interval = 1000;

  // Set the heartbeat time out, after which the system should detect slave
  // disconnection; values can be "250", "500", "1000" and "2000" millisecond.
  // Temporary disabled the timeout parameters; A gloabl 2 second time is now
  // used in device_alive and device_dead callback
  // const uint16_t heartbeat_timeout = heartbeat_interval * 3;

  // -------------- //
  // Initialization //
  // -------------- //

  // Create core.
  kaco::Core core;
  volatile bool found_node = false;
  volatile bool device_connected = false;
  std::mutex device_mutex;
  volatile bool found_node_1 = false;
  volatile bool device_connected_1 = false;
  std::mutex device_mutex_1;

  std::cout << "Starting Core (connect to the driver and start the receiver "
               "thread)...Hi"
            << std::endl;
  if (!core.start(busname, baudrate)) {
    std::cout << "Starting core failed." << std::endl;
    return EXIT_FAILURE;
  }
  // Create device pointer
  std::shared_ptr<kaco::Device> device;
  std::shared_ptr<kaco::Device> device_1;
  // This will be set to true by the callback below.

  std::cout << "Registering a callback which is called when a device is "
               "detected via NMT..."
            << std::endl;
  // make sure that the node is reset and goes back to NMT preoperational
  core.nmt.send_nmt_message(node_id_0, kaco::NMT::Command::reset_node);
  core.nmt.send_nmt_message(node_id_1, kaco::NMT::Command::reset_node);
  core.nmt.register_device_alive_callback([&](const uint8_t new_node_id) {
    //std::cout << "callback"  << std::endl;
    // Check if this is the node we are looking for.
    if (new_node_id == node_id_0) {
      // lock
      if (!found_node) {
        found_node = true;
        // Lock device mutex
        std::lock_guard<std::mutex> lock(device_mutex);
        try {
          // Initialize the device
          device.reset(new kaco::Device(core, node_id_0));
          std::string path = ros::package::getPath("kacanopen");

          //boost::filesystem::path full_path =
            //  path + "/eds_library/MaxonMotor/epos2_347717.eds";

          boost::filesystem::path full_path = "/home/pi/hexa_workspace/src/hexa_package/edsFiles/epos2_347717.eds";

          device->load_dictionary_from_eds(full_path.string());
          std::cout << "Printing Device Object Dictionary" << std::endl;
          //device->print_dictionary();
          core.nmt.send_nmt_message(node_id_0,
                                    kaco::NMT::Command::enter_preoperational);

          initializeDevice(device, heartbeat_interval, node_id_0);
          //device->set_entry("controlword", static_cast<uint16_t>(0x0006),
          //                  kaco::WriteAccessMethod::pdo);
          int8_t set_mode_of_operation = 3;

          std::this_thread::sleep_for(std::chrono::microseconds(5));

          device->set_entry(0x6060, 0x00, set_mode_of_operation,
                           kaco::WriteAccessMethod::sdo);
          //  device->request_heartbeat(node_id, heartbeat_interval, true,
          //                           kaco::NMT::State::operational);
          device->start();
          printDeviceInfo(device);
          device_connected = true;
        } catch (const std::exception &exc) {
          std::cout << "Exception in device alive!" << std::endl;
          std::cerr <<exc.what();
          found_node = false;
          device_connected = false;
        }
      }
    }
    if (new_node_id == node_id_1) {
      // lock
      if (!found_node_1) {
        found_node_1 = true;
        // Lock device mutex
        std::lock_guard<std::mutex> lock(device_mutex);
        try {
          // Initialize the device
          device_1.reset(new kaco::Device(core, node_id_1));
          std::string path = ros::package::getPath("kacanopen");

          //boost::filesystem::path full_path =
            //  path + "/eds_library/MaxonMotor/epos2_347717.eds";

          boost::filesystem::path full_path = "/home/pi/hexa_workspace/src/hexa_package/edsFiles/epos2_347717.eds";

          device_1->load_dictionary_from_eds(full_path.string());
          std::cout << "Printing Device Object Dictionary" << std::endl;
          //device->print_dictionary();
          core.nmt.send_nmt_message(node_id_1,
                                    kaco::NMT::Command::enter_preoperational);

          initializeDevice(device_1, heartbeat_interval, node_id_1);
          //device->set_entry("controlword", static_cast<uint16_t>(0x0006),
          //                  kaco::WriteAccessMethod::pdo);
          int8_t set_mode_of_operation = 3;

          std::this_thread::sleep_for(std::chrono::microseconds(100));

          device_1->set_entry(0x6060, 0x00, set_mode_of_operation,
                           kaco::WriteAccessMethod::sdo);
          //  device->request_heartbeat(node_id, heartbeat_interval, true,
          //                           kaco::NMT::State::operational);
          device_1->start();
          printDeviceInfo(device_1);
          device_connected_1 = true;
        } catch (const std::exception &exc) {
          std::cout <<  "Exception in device alive!" << std::endl;
          std::cerr <<  exc.what();
          found_node_1 = false;
          device_connected_1 = false;
        }
      }
    }
  });
  // core.nmt.register_device_dead_callback([&](const uint8_t new_node_id) {
  //   if ((device_connected && found_node) && (new_node_id == node_id)) {
  //     // Lock device mutex
  //     std::lock_guard<std::mutex> lock(device_mutex);
  //     // Check if our node is disconnected.
  //     found_node = false;
  //     device_connected = false;
  //     device.reset();
  //     std::cout << "Device with Node ID=0x" << std::hex << node_id
  //               << " is disconnected...." << std::endl;
  //   }
  // });
  int loopCounter = 0;
  high_resolution_clock::time_point lastTime = high_resolution_clock::now();

  static const int max_itr = 100000;
  int actValues [max_itr];
  int targetValues [max_itr];
  double  CurrentTime [max_itr];

  int tar_vel = 0;
  int Domain = 500;

  std::ofstream outfileTargetValues;
	std::ofstream outfileActualValues;
  std::ofstream outfileCurrentTime;

	outfileTargetValues.open("TargetValues.csv");
	outfileActualValues.open("ActualValues.csv");
  outfileCurrentTime.open("CurrentTime.csv");

  high_resolution_clock::time_point startprogramm = high_resolution_clock::now();
  while (keepRunning) {
    high_resolution_clock::time_point startloop = high_resolution_clock::now();
    if (device_connected && device_connected_1) {

      // Lock device mutex
      std::lock_guard<std::mutex> lock(device_mutex);

      try {
        duration<double, std::milli> time_take_to_this = high_resolution_clock::now() - startprogramm;
        double currentTime = time_take_to_this.count() ;
        int32_t actual_vel_0 =
            device->get_entry("velocity_actual_value",
                              kaco::ReadAccessMethod::pdo_request_and_wait);

        int32_t actual_vel_1 =
            device_1->get_entry("velocity_actual_value",
                              kaco::ReadAccessMethod::pdo_request_and_wait);

        duration<double, std::milli> time_span = high_resolution_clock::now() - lastTime;
        // std::cout << "time take for one iteration of loop =" << time_span.count() << std::endl;
        lastTime = high_resolution_clock::now();

        tar_vel = int(Domain * sin(loopCounter / 30000.0) + Domain * sin(loopCounter / 10000.0)  * 3);
        tar_vel = 125;
        device->set_entry("target_velocity", static_cast<int>(actual_vel_1 * 1000),
                          kaco::WriteAccessMethod::pdo);

        // device_1->set_entry("target_velocity", static_cast<int>(actual_vel_1 / 100),
        //                   kaco::WriteAccessMethod::pdo);

        // targetValues[loopCounter] = tar_vel;
				// actValues[loopCounter] = actual_vel_0;
        // CurrentTime[loopCounter] = currentTime ;

        device->set_entry("controlword", static_cast<uint16_t>(0x000F),
                          kaco::WriteAccessMethod::pdo);

        device_1->set_entry("controlword", static_cast<uint16_t>(0x000F),
                          kaco::WriteAccessMethod::pdo);

        loopCounter = loopCounter + 1;

        // if (loopCounter == max_itr){

        //   for(int i=0;i<max_itr;i++){
				//     outfileTargetValues<< targetValues[i] << std::endl;
				//     outfileActualValues<< actValues[i] << std::endl;
        //     outfileCurrentTime<< CurrentTime[i] << std::endl;
			  //   }

			  //   outfileTargetValues.close();
			  //   outfileActualValues.close();
        //   outfileCurrentTime.close();
        //   std::cout << "Saving is done ..." << std::endl;
        //   break;
        // }

      } catch (const std::exception &exc) {
        std::cout << "Exception in main!" << std::endl;
        std::cerr <<exc.what();
      }
    }
    duration<double, std::milli> loop_calculation_time_span = high_resolution_clock::now() - startloop;
    // Sleep
    if((unsigned int)loop_calculation_time_span.count() < 5 ){
      std::this_thread::sleep_for(std::chrono::milliseconds(5 - (unsigned int)loop_calculation_time_span.count() ));
    }else{
      std::this_thread::sleep_for(std::chrono::microseconds(100));
    }
  }

  std::cout << "Finished." << std::endl;
  return EXIT_SUCCESS;
};

max_stars_repo_name: FUMRobotics/FUMHexa

max_issues_repo_name: FUMRobotics/FUMHexa

max_forks_repo_name: FUMRobotics/FUMHexa


text:
//          Copyright Carl Philipp Reh 2009 - 2016.
// 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 FCPPT_FORMAT_HPP_INCLUDED
#define FCPPT_FORMAT_HPP_INCLUDED

#include <fcppt/char_type.hpp>
#include <fcppt/config/external_begin.hpp>
#include <boost/format.hpp>
#include <fcppt/config/external_end.hpp>

namespace fcppt
{

/**
\brief A fcppt::char_type typedef for boost.format
\ingroup fcpptstring

See the \link fcpptstring string module description \endlink for more
information about fcppt::char_type.
*/
typedef boost::basic_format<
	fcppt::char_type
> format;

}

#endif

ext: hpp

max_stars_repo_name: vinzenz/fcppt

max_issues_repo_name: vinzenz/fcppt

max_forks_repo_name: vinzenz/fcppt


text:
// -*- mode: c++ -*-
/*********************************************************************
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2016, JSK Lab
 *  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/o2r other materials provided
 *     with the distribution.
 *   * Neither the name of the JSK Lab 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.
 *********************************************************************/

#include "jsk_perception/rect_array_to_density_image.h"
#include <boost/assign.hpp>
#include <jsk_topic_tools/log_utils.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/opencv.hpp>
#include <cv_bridge/cv_bridge.h>

namespace jsk_perception
{
  void RectArrayToDensityImage::onInit()
  {
    DiagnosticNodelet::onInit();
    pnh_->param("approximate_sync", approximate_sync_, false);
    pnh_->param("queue_size", queue_size_, 100);
    pub_ = advertise<sensor_msgs::Image>(*pnh_, "output", 1);
    onInitPostProcess();
  }

  void RectArrayToDensityImage::subscribe()
  {
    sub_image_.subscribe(*pnh_, "input/image", 1);
    sub_rects_.subscribe(*pnh_, "input/rect_array", 1);
    if (approximate_sync_) {
      async_ = boost::make_shared<message_filters::Synchronizer<ApproximateSyncPolicy> >(queue_size_);
      async_->connectInput(sub_image_, sub_rects_);
      async_->registerCallback(boost::bind(&RectArrayToDensityImage::convert, this, _1, _2));
    }
    else {
      sync_ = boost::make_shared<message_filters::Synchronizer<SyncPolicy> >(queue_size_);
      sync_->connectInput(sub_image_, sub_rects_);
      sync_->registerCallback(boost::bind(&RectArrayToDensityImage::convert, this, _1, _2));
    }
    ros::V_string names = boost::assign::list_of("~input/image")("~input/rect_array");
    jsk_topic_tools::warnNoRemap(names);
  }

  void RectArrayToDensityImage::unsubscribe()
  {
    sub_image_.unsubscribe();
    sub_rects_.unsubscribe();
  }

  void RectArrayToDensityImage::convert(
    const sensor_msgs::Image::ConstPtr& image_msg,
    const jsk_recognition_msgs::RectArray::ConstPtr& rects_msg)
  {
    vital_checker_->poke();
    cv::Mat density_image = cv::Mat::zeros(image_msg->height, image_msg->width, CV_32FC1);

    // Compute density
    for (size_t k=0; k<rects_msg->rects.size(); k++) {
      jsk_recognition_msgs::Rect rect = rects_msg->rects[k];
      for (int j=rect.y; j<(rect.y + rect.height); j++) {
        for (int i=rect.x; i<(rect.x + rect.width); i++) {
          density_image.at<float>(j, i)++;
        }
      }
    }

    // Scale the density image value to [0, 1]
    double min_image_value;
    double max_image_value;
    cv::minMaxLoc(density_image, &min_image_value, &max_image_value);
    cv::Mat(density_image - min_image_value).convertTo(
        density_image, CV_32FC1, 1. / (max_image_value - min_image_value));

    pub_.publish(cv_bridge::CvImage(
                    image_msg->header,
                    "32FC1",
                    density_image).toImageMsg());
  }
}

#include <pluginlib/class_list_macros.h>
PLUGINLIB_EXPORT_CLASS (jsk_perception::RectArrayToDensityImage, nodelet::Nodelet);


text:
#include <boost/phoenix/phoenix.hpp>
#include <vector>
#include <algorithm>
#include <iostream>

bool is_odd(int i) { return i % 2 == 1; }

int main()
{
  std::vector<int> v{1, 2, 3, 4, 5};

  using namespace boost::phoenix;
  using namespace boost::phoenix::placeholders;
  std::cout << std::count_if(v.begin(), v.end(), bind(is_odd, arg1)) << '\n';
}

max_stars_repo_name: KwangjoJeong/Boost

max_issues_repo_name: KwangjoJeong/Boost

max_forks_repo_name: KwangjoJeong/Boost


text:
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <iterator>
#include <bits/stdc++.h>
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include "../stem/stemming/english_stem.h"
#include <cstdlib>

using namespace std;
using namespace boost;

string stopWords[] = {
    "ourselves", "hers", "between", "yourself", "but", "again", "there", "about", "once", "during", "out", "very", "having",
    "with", "they", "own", "an", "be", "some", "for", "do", "its", "yours", "such", "into", "of", "most", "itself", "other", "off", "is", "s",
    "am", "or", "who", "as", "from", "him", "each", "the", "themselves", "until", "below", "are", "we", "these", "your", "his", "through", "don",
    "nor", "me", "were", "her", "more", "himself", "this", "down", "should", "our", "their", "while", "above", "both", "up", "to", "ours", "had",
    "she", "all", "no", "when", "at", "any", "before", "them", "same", "and", "been", "have", "in", "will", "on", "does", "yourselves", "then",
    "that", "because", "what", "over", "why", "so", "can", "did", "not", "now", "under", "he", "you", "herself", "has", "just", "where", "too",
    "only", "myself", "which", "those", "i", "after", "few", "whom", "t", "being", "if", "theirs", "my", "against", "a", "by", "doing", "it",
    "how", "further", "was", "here", "than"
};

int sizeStop = sizeof(stopWords)/sizeof(stopWords[0]);

bool isStopWord(string s){
    for(int i=0;i<sizeStop;i++){
        if(s==stopWords[i])
            return true;
    }
    return false;
}

std::wstring my_to_wstring(const std::string& s){
    std::wstring temp(s.length(),L' ');
    std::copy(s.begin(), s.end(), temp.begin());
    return temp;
}

std::string my_to_string(const std::wstring& s){
    std::string temp(s.length(), ' ');
    std::copy(s.begin(), s.end(), temp.begin());
    return temp;
}

map<int, double> getDocs(vector<string> query, map<string, vector<pair<double,int>>> invIndex){
    std::map<string, vector<pair<double,int>>>::iterator it;
    map<string, int> queryTerms;
    std::map<string, int>::iterator itr;
    for(int i=0;i<query.size();i++){
        itr = queryTerms.find(query[i]);
        if(itr==queryTerms.end()){
            queryTerms.insert(make_pair(query[i], 1));
        }
    }
    map<int, double> relevance;
    std::map<int, double>::iterator itrDocs;
    string term;
    int tf;
    pair<double, int> tempPair;
    for(itr = queryTerms.begin(); itr!=queryTerms.end(); itr++){
        term = itr->first;
        tf = itr->second;
        it = invIndex.find(term);
        if(it==invIndex.end())
            continue;
        vector<pair<double, int>> termIndex = it->second;
        for(int i=0;i<termIndex.size();i++){
            tempPair = termIndex[i];
            itrDocs = relevance.find(tempPair.second);
            if(itrDocs!=relevance.end())
                itrDocs->second += tf*tempPair.first;
            else
                relevance.insert(make_pair(tempPair.second, tf*tempPair.first));
        }
    }
    return relevance;
}

int main(){
    const char * fileName;
    stemming::english_stem<> StemEnglish;
    string line;
    //documents
    vector<string> a;
    map<string, vector<pair<double,int>>> invIndex;
    std::map<string, vector<pair<double,int>>>::iterator it;
    pair<double,int> tempPair;
    vector<string> splitVec;

    try {
        ifstream file("index");
        if(file.is_open()){
            while(getline(file,line)){
                trim(line);
                split(splitVec, line, is_any_of("@"), token_compress_on);
                for(int i=1;i<splitVec.size();i++){
                    trim(splitVec[i]);
                    if(splitVec[i]=="")
                        continue;
                    a.push_back(splitVec[i]);
                }
                break;
            }
            // cout<<a.size()<<endl;
            while(getline(file, line)) {
                trim(line);
                split(splitVec, line, is_any_of(" "), token_compress_on);
                if(splitVec.size()==0)
                    continue;
                if(splitVec[0]=="")
                    continue;
                vector<pair<double,int>> tempVec;
                // cout<<splitVec.size()<<" "<<line<<endl;
                for(int i=1;i<splitVec.size();i+=2){
                    tempPair.first = stod(splitVec[i]);
                    tempPair.second = stod(splitVec[i+1]);
                    tempVec.push_back(tempPair);
                }
                invIndex.insert(make_pair(splitVec[0], tempVec));
            }
            file.close();
        }
        else{
            throw 1;
        }
    }
    catch(...) {
        cout<<"Index file not present.\n";
        exit(0);
    }

    // query processing
    string query, input, stemmed;
    do{
        cout<<"Type query: ";
        getline(cin, query);
        to_lower(query);
        trim(query);
        split(splitVec, query, is_any_of(" .,-:'\"?/_()*!#@;[]{}<>&"), token_compress_on);
        vector<string> splitQuery;
        for(int i=0;i<splitVec.size();i++){
            if(splitVec[i]=="")
                continue;
            if(!isStopWord(splitVec[i])){
                wstring temp = my_to_wstring(splitVec[i]);
                StemEnglish(temp);
                stemmed = my_to_string(temp);
                splitQuery.push_back(stemmed);
            }
        }
        map<int, double> result = getDocs(splitQuery, invIndex);
        priority_queue< pair<double, int>> ans;
        int ansSize = 0;
        std::map<int, double>::iterator itResult;
        if(result.size()==0){
            cout<<"No results found!\n";
            goto nextQuery;
        }
        for(itResult = result.begin(); itResult!=result.end(); itResult++){
            ans.push(make_pair(itResult->second, itResult->first));
            ansSize++;
        }
        for(int i=0;i<min(50,ansSize);i++) {
            tempPair = ans.top();
            cout<<a[tempPair.second]<<" "<<tempPair.first<<endl;
            ans.pop();
        }
        nextQuery: cout<<"Test more queries? If yes, type yes. If no, type anything else.\n";
        getline(cin, input);
    }while(input=="yes");

    return 0;
}


text:
#include <boost/test/included/unit_test.hpp>

using namespace boost::unit_test;

int add( int i, int j ) { return i+j; }

static void test1(){
    BOOST_CHECK( add( 2,2 ) == 4 );        // #1 continues on error
}

static void test2(){
    BOOST_CHECK( add( 2,3 ) == 4 );        // #1 continues on error
}

static void test3(){
    BOOST_FAIL( "un test failed" );        // #1 continues on error
}

test_suite *
init_unit_test_suite(int, char ** const) {
    test_suite* ts = BOOST_TEST_SUITE("array test");
    ts->add(BOOST_TEST_CASE(&test1));
    ts->add(BOOST_TEST_CASE(&test2));
    ts->add(BOOST_TEST_CASE(&test3));
    //framework::master_test_suite().add(ts);
    return ts;
}

max_stars_repo_name: ianmartin/xunit-plugin

max_issues_repo_name: ianmartin/xunit-plugin

max_forks_repo_name: ianmartin/xunit-plugin


text:
/*
 Copyright (C) 2016 Quaternion Risk Management Ltd
 All rights reserved.

 This file is part of ORE, a free-software/open-source library
 for transparent pricing and risk analysis - http://opensourcerisk.org

 ORE is free software: you can redistribute it and/or modify it
 under the terms of the Modified BSD License.  You should have received a
 copy of the license along with this program.
 The license is also available online at <http://opensourcerisk.org>

 This program is distributed on the basis that it will form a useful
 contribution to risk analytics and model standardisation, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/

/*! \file qle/termstructures/swaptionvolatilityconverter.hpp
    \brief Convert swaption volatilities from one type to another
    \ingroup termstructures
*/

#ifndef quantext_swaptionvolatilityconverter_hpp
#define quantext_swaptionvolatilityconverter_hpp

#include <ql/indexes/iborindex.hpp>
#include <ql/indexes/swapindex.hpp>
#include <ql/termstructures/volatility/swaption/swaptionvolmatrix.hpp>

#include <boost/shared_ptr.hpp>

namespace QuantExt {
using namespace QuantLib;
using std::vector;

//! Container for holding swap conventions needed by the SwaptionVolatilityConverter
//! \ingroup termstructures
class SwapConventions {
public:
    //! Constructor
    SwapConventions(Natural settlementDays, const Period& fixedTenor, const Calendar& fixedCalendar,
                    BusinessDayConvention fixedConvention, const DayCounter& fixedDayCounter,
                    const boost::shared_ptr<IborIndex>& floatIndex)
        : settlementDays_(settlementDays), fixedTenor_(fixedTenor), fixedCalendar_(fixedCalendar),
          fixedConvention_(fixedConvention), fixedDayCounter_(fixedDayCounter), floatIndex_(floatIndex) {}

    //! \name Inspectors
    //@{
    Natural settlementDays() const { return settlementDays_; }
    const Period& fixedTenor() const { return fixedTenor_; }
    const Calendar& fixedCalendar() const { return fixedCalendar_; }
    BusinessDayConvention fixedConvention() const { return fixedConvention_; }
    const DayCounter& fixedDayCounter() const { return fixedDayCounter_; }
    const boost::shared_ptr<IborIndex> floatIndex() const { return floatIndex_; }
    //@}

private:
    Natural settlementDays_;
    Period fixedTenor_;
    Calendar fixedCalendar_;
    BusinessDayConvention fixedConvention_;
    DayCounter fixedDayCounter_;
    boost::shared_ptr<IborIndex> floatIndex_;
};

//! Class that converts a supplied SwaptionVolatilityStructure to one of another type with possibly different shifts
/*! \ingroup termstructures

    \warning the converted <tt>SwaptionVolatilityStructure</tt> object has a fixed reference date eqaul to
             <tt>asof</tt> and fixed market data regardless of the type of reference date and market data of the
             original <tt>SwaptionVolatilityStructure</tt> that is passed in
*/
class SwaptionVolatilityConverter {
public:
    //! Construct from SwapConventions
    SwaptionVolatilityConverter(const Date& asof, const boost::shared_ptr<SwaptionVolatilityStructure>& svsIn,
                                const Handle<YieldTermStructure>& discount,
                                const Handle<YieldTermStructure>& shortDiscount,
                                const boost::shared_ptr<SwapConventions>& conventions,
                                const boost::shared_ptr<SwapConventions>& shortConventions,
                                const Period& conventionsTenor, const Period& shortConventionsTenor,
                                const VolatilityType targetType, const Matrix& targetShifts = Matrix());
    //! Construct from SwapIndex
    SwaptionVolatilityConverter(const Date& asof, const boost::shared_ptr<SwaptionVolatilityStructure>& svsIn,
                                const boost::shared_ptr<SwapIndex>& swapIndex,
                                const boost::shared_ptr<SwapIndex>& shortSwapIndex, const VolatilityType targetType,
                                const Matrix& targetShifts = Matrix());

    //! Method that returns the converted <tt>SwaptionVolatilityStructure</tt>
    boost::shared_ptr<SwaptionVolatilityStructure> convert() const;

    // Convert a single vol associated with a given swaption
    Real convert(const Date& expiry, const Period& swapTenor, Real strikeSpread, const DayCounter& volDayCounter,
                 VolatilityType outType, Real outShift = 0.0) const;

    //! Set implied volatility solver accuracy
    Real& accuracy() { return accuracy_; }
    //! Set implied volatility solver max evaluations
    Natural& maxEvaluations() { return maxEvaluations_; }

private:
    // Check inputs
    void checkInputs() const;

    // Method that is called depending on the type of svsIn
    boost::shared_ptr<SwaptionVolatilityStructure>
    convert(const boost::shared_ptr<SwaptionVolatilityMatrix>& svMatrix) const;

    const Date asof_;
    const boost::shared_ptr<SwaptionVolatilityStructure> svsIn_;
    Handle<YieldTermStructure> discount_, shortDiscount_;
    const boost::shared_ptr<SwapConventions> conventions_, shortConventions_;
    const Period conventionsTenor_, shortConventionsTenor_;
    const VolatilityType targetType_;
    const Matrix targetShifts_;

    // Variables for implied volatility solver
    Real accuracy_;
    Natural maxEvaluations_;
    static const Volatility minVol_;
    static const Volatility maxVol_;
    static const Real minVega_;
};
} // namespace QuantExt

#endif

max_stars_repo_name: mrslezak/Engine

max_issues_repo_name: mrslezak/Engine

max_forks_repo_name: mrslezak/Engine


text:
/****************************************************************************
*
*    Copyright (c) 2019 Vivante Corporation
*
*    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.
*
*****************************************************************************/

#pragma once

#include <backendsCommon/CpuTensorHandle.hpp>
#include <backendsCommon/Workload.hpp>
#include <backendsCommon/WorkloadData.hpp>
#include <boost/log/trivial.hpp>
#include <FloatingPointConverter.hpp>
#include "TNpuWorkloads.hpp"

#include "FakeBiasSelector.hpp"

namespace armnn {

template <typename armnn::DataType... DataTypes>
class NpuConvolution2dWorkload : public TNpuWorkload<Convolution2dQueueDescriptor, DataTypes...> {
   public:
    using FakeBias = FakeBiasTypeSelector<DataTypes...>;

    static_assert(std::is_same<typename FakeBias::type, void>::value == false,
                  "FakeBias data type In DepthWiseConv not added");

    using base_type = TNpuWorkload<Convolution2dQueueDescriptor, DataTypes...>;
    explicit NpuConvolution2dWorkload(const Convolution2dQueueDescriptor& descriptor,
                                      const WorkloadInfo& info)
        : TNpuWorkload<Convolution2dQueueDescriptor, DataTypes...>(descriptor, info),
          m_Weight(std::make_unique<ScopedCpuTensorHandle>(*(descriptor.m_Weight))),
          m_Bias(descriptor.m_Parameters.m_BiasEnabled
                     ? std::make_unique<ScopedCpuTensorHandle>(*(descriptor.m_Bias))
                     : nullptr),
          m_StrideX(descriptor.m_Parameters.m_StrideX),
          m_StrideY(descriptor.m_Parameters.m_StrideY),
          m_PadLeft(descriptor.m_Parameters.m_PadLeft),
          m_PadRight(descriptor.m_Parameters.m_PadRight),
          m_PadTop(descriptor.m_Parameters.m_PadTop),
          m_PadBottom(descriptor.m_Parameters.m_PadBottom),
          m_DataLayout(descriptor.m_Parameters.m_DataLayout) {
        uint32_t inputIds[11];
        // Add input operand
        auto inputPtr = dynamic_cast<NpuTensorHandler*>(descriptor.m_Inputs[0]);
        inputIds[0] =
            this->AddOperandAndSetValue(inputPtr->GetTensorInfo(), inputPtr->GetShape(), nullptr);
        // inputPtr->SetOperandId(inputIds[0]);

        // Add filter operand
        const TensorShape& weightShape = m_Weight->GetShape();
        const TensorInfo& weightInfo = m_Weight->GetTensorInfo();
        // assert(m_DataLayout == armnn::DataLayout::NHWC);
        inputIds[1] =
            this->AddOperandAndSetValue(weightInfo, weightShape, m_Weight->GetTensor<void>());

        // Add bias operand
        // assert(m_Bias != nullptr);
        if (m_Bias) {
            TensorInfo biasInfo = m_Bias->GetTensorInfo();
            const TensorShape biasShape = m_Bias->GetShape();
            if (biasInfo.GetDataType() == DataType::Float16) {
                biasInfo.SetDataType(DataType::Float32);
                m_Fp32BiasData.reset(new float[biasInfo.GetNumElements()]);
                armnnUtils::FloatingPointConverter::ConvertFloat16To32(
                    m_Bias->GetTensor<Half>(), biasInfo.GetNumElements(), m_Fp32BiasData.get());
                inputIds[2] =
                    this->AddOperandAndSetValue(biasInfo, biasShape, m_Fp32BiasData.get());
            } else {
                inputIds[2] =
                    this->AddOperandAndSetValue(biasInfo, biasShape, m_Bias->GetTensor<void>());
            }
        } else {
            TensorShape biasShape(1);
            TensorInfo biasInfo(biasShape, FakeBias::value);
            biasShape[0] = weightShape[0];  // Channels
            m_FakeBiasData.resize(biasShape[0]);
            biasInfo.SetShape(biasShape);

            if (FakeBias::value == DataType::Signed32) {
                auto biasScale = inputPtr->GetTensorInfo().GetQuantizationScale() *
                                 weightInfo.GetQuantizationScale();
                int32_t biasZp = 0;

                biasInfo.SetQuantizationOffset(biasZp);
                biasInfo.SetQuantizationScale(biasScale);
            }
            memset(m_FakeBiasData.data(), 0, m_FakeBiasData.size());

            inputIds[2] = (this->AddOperandAndSetValue(biasInfo, biasShape, m_FakeBiasData.data()));
        }

        // Add padding left operand
        inputIds[3] = this->AddOperandAndSetValue(m_PadLeft);

        // Add padding right operand
        inputIds[4] = this->AddOperandAndSetValue(m_PadRight);

        // Add padding top operand
        inputIds[5] = this->AddOperandAndSetValue(m_PadTop);

        // Add padding bottom operand
        inputIds[6] = this->AddOperandAndSetValue(m_PadBottom);

        // Add stride width operand
        inputIds[7] = this->AddOperandAndSetValue(m_StrideX);

        // Add stride height operand
        inputIds[8] = this->AddOperandAndSetValue(m_StrideY);

        // Add fusecode operand
        int32_t fuseCode = 0;
        inputIds[9] = this->AddOperandAndSetValue(fuseCode);

        // Add layout operand
        int32_t layoutCode = m_DataLayout == armnn::DataLayout::NCHW
                                 ? int32_t(nnrt::DataLayout::NCHW)
                                 : int32_t(nnrt::DataLayout::NHWC);
        inputIds[10] = this->AddOperandAndSetValue(layoutCode);

        // Add output operand
        int outputSize = descriptor.m_Outputs.size();
        uint32_t outputIds[outputSize];

        for (int i = 0; i < outputSize; i++) {
            auto outputPtr = dynamic_cast<NpuTensorHandler*>(descriptor.m_Outputs[i]);
            outputIds[i] = this->AddOperandAndSetValue(
                outputPtr->GetTensorInfo(), outputPtr->GetShape(), nullptr);
            // outputPtr->SetOperandId(outputIds[i]);
        }

        this->AddOperation(nnrt::OperationType::CONV_2D, 11, inputIds, outputSize, outputIds);
    }

   private:
    std::unique_ptr<ScopedCpuTensorHandle> m_Weight;
    std::unique_ptr<ScopedCpuTensorHandle> m_Bias;
    uint32_t m_StrideX;
    uint32_t m_StrideY;
    uint32_t m_PadLeft;
    uint32_t m_PadRight;
    uint32_t m_PadTop;
    uint32_t m_PadBottom;
    armnn::DataLayout m_DataLayout;

    std::vector<typename FakeBias::type> m_FakeBiasData;  //!< workaround: bias required by shader
    mutable boost::scoped_array<float> m_Fp32BiasData;
};
using NpuConvolution2dFloat32Workload = NpuConvolution2dWorkload<armnn::DataType::Float32>;
using NpuConvolution2dFloat16Workload = NpuConvolution2dWorkload<armnn::DataType::Float16>;
using NpuConvolution2dUint8Workload = NpuConvolution2dWorkload<armnn::DataType::QuantisedAsymm8>;
}  // namespace armnn

max_stars_repo_name: phytec-mirrors/nn-imx

max_issues_repo_name: phytec-mirrors/nn-imx

max_forks_repo_name: phytec-mirrors/nn-imx


text:
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE model
#include <boost/test/unit_test.hpp>

#include "model/node/node.h"
#include "mockup/nodesignaltester.h"

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

BOOST_AUTO_TEST_SUITE( node_suite )

BOOST_AUTO_TEST_CASE(constructor)
{

    //for (int i = 0 ; i < 99999 ; ++i)
    //{
        std::shared_ptr<Node> n = Node::create() ;

        BOOST_CHECK_EQUAL(n->graphIndex(),ULONG_MAX);
        BOOST_CHECK_EQUAL(n->x(),-1);
        BOOST_CHECK_EQUAL(n->y(),-1);
        BOOST_CHECK_EQUAL(n->exists(),false);
        BOOST_CHECK_EQUAL(n->isCandidate(),false);
        BOOST_CHECK_EQUAL(n->isAbsent(),true);
        BOOST_CHECK_EQUAL(n->consolePrintCharacter(), " ");
    //}

}
BOOST_AUTO_TEST_CASE(sets)
{
    std::shared_ptr<Node> n = Node::create() ;
    n->setX(5);
    n->setY(6);
    n->setGraphIndex(7);
    BOOST_CHECK_EQUAL(n->graphIndex(),7);
    BOOST_CHECK_EQUAL(n->x(),5);
    BOOST_CHECK_EQUAL(n->y(),6);
}

BOOST_AUTO_TEST_CASE(setIntoCandidateStateFirst_ThenExisting)
{
    std::shared_ptr<Node> n = Node::create() ;
    NodeSignalTester signalTester1, signalTester2;
    n->addToCandidateList.connect(      boost::bind( &NodeSignalTester::slotGetNode, &signalTester1, _1 ));
    n->setAdjacentsAsCandidate.connect( boost::bind( &NodeSignalTester::slotGetNode, &signalTester2, _1 ));

    BOOST_CHECK(signalTester1.node() == nullptr);
    BOOST_CHECK(signalTester2.node() == nullptr);

    n->setIntoCandidateState();

    BOOST_CHECK_EQUAL(n->exists(),false);
    BOOST_CHECK_EQUAL(n->isCandidate(),true);
    BOOST_CHECK_EQUAL(n->isAbsent(),false);
    BOOST_CHECK_EQUAL(n->consolePrintCharacter(), " ");
    BOOST_CHECK_EQUAL(signalTester1.node(), n);
    BOOST_CHECK(signalTester2.node() == nullptr);

    signalTester1.setNode(nullptr);
    n->setIntoExistingState();

    BOOST_CHECK_EQUAL(n->exists(),true);
    BOOST_CHECK_EQUAL(n->isCandidate(),false);
    BOOST_CHECK_EQUAL(n->isAbsent(),false);
    BOOST_CHECK_EQUAL(n->consolePrintCharacter(), "O");
    BOOST_CHECK(signalTester1.node() == nullptr);
    BOOST_CHECK_EQUAL(signalTester2.node(), n);

    // try to go back state
    signalTester2.setNode(nullptr);

    n->setIntoCandidateState();

    BOOST_CHECK_EQUAL(n->exists(),true);
    BOOST_CHECK_EQUAL(n->isCandidate(),false);
    BOOST_CHECK_EQUAL(n->isAbsent(),false);
    BOOST_CHECK_EQUAL(n->consolePrintCharacter(), "O");
    BOOST_CHECK(signalTester1.node() == nullptr);
    BOOST_CHECK(signalTester2.node() == nullptr);

}

BOOST_AUTO_TEST_CASE(setIntoExistingStateDirectly)
{
    std::shared_ptr<Node> n = Node::create() ;
    NodeSignalTester signalTester1, signalTester2;
    n->addToCandidateList.connect(      boost::bind( &NodeSignalTester::slotGetNode, &signalTester1, _1 ));
    n->setAdjacentsAsCandidate.connect( boost::bind( &NodeSignalTester::slotGetNode, &signalTester2, _1 ));

    BOOST_CHECK(signalTester1.node() == nullptr);
    BOOST_CHECK(signalTester2.node() == nullptr);

    n->setIntoExistingState();

    BOOST_CHECK_EQUAL(n->exists(),true);
    BOOST_CHECK_EQUAL(n->isCandidate(),false);
    BOOST_CHECK_EQUAL(n->isAbsent(),false);
    BOOST_CHECK_EQUAL(n->consolePrintCharacter(), "O");
    BOOST_CHECK(signalTester1.node() == nullptr);
    BOOST_CHECK_EQUAL(signalTester2.node(), n);

    // try to go back state
    signalTester2.setNode(nullptr);

    n->setIntoCandidateState();

    BOOST_CHECK_EQUAL(n->exists(),true);
    BOOST_CHECK_EQUAL(n->isCandidate(),false);
    BOOST_CHECK_EQUAL(n->isAbsent(),false);
    BOOST_CHECK_EQUAL(n->consolePrintCharacter(), "O");
    BOOST_CHECK(signalTester1.node() == nullptr);
    BOOST_CHECK(signalTester2.node() == nullptr);

    //set the player
    n->setHostThePlayer(true);
    BOOST_CHECK_EQUAL(n->consolePrintCharacter(), "@");
    n->setHostThePlayer(false);
    BOOST_CHECK_EQUAL(n->consolePrintCharacter(), "O");
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: jonpetri/CollectGame

max_issues_repo_name: jonpetri/CollectGame

max_forks_repo_name: jonpetri/CollectGame


text:
//          Copyright Oliver Kowalke 2009.
// 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_FIBERS_SPIN_COUNT_DOWN_EVENT_H
#define BOOST_FIBERS_SPIN_COUNT_DOWN_EVENT_H

#include <cstddef>

#include <boost/atomic.hpp>
#include <boost/config.hpp>
#include <boost/utility.hpp>

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

#ifdef BOOST_HAS_ABI_HEADERS
#  include BOOST_ABI_PREFIX
#endif

# if defined(BOOST_MSVC)
# pragma warning(push)
# pragma warning(disable:4355 4251 4275)
# endif

namespace boost {
namespace fibers {
namespace spin {

class BOOST_FIBER_DECL count_down_event : private noncopyable
{
private:
	std::size_t				initial_;
	atomic< std::size_t >	current_;

public:
	explicit count_down_event( std::size_t);

	std::size_t initial() const;

	std::size_t current() const;

	bool is_set() const;

	void set();

	void wait();
};

}}}

# if defined(BOOST_MSVC)
# pragma warning(pop)
# endif

#ifdef BOOST_HAS_ABI_HEADERS
#  include BOOST_ABI_SUFFIX
#endif

#endif // BOOST_FIBERS_SPIN_COUNT_DOWN_EVENT_H

max_stars_repo_name: ghisguth/tasks

max_issues_repo_name: ghisguth/tasks

max_forks_repo_name: ghisguth/tasks


text:
#ifndef HERMIT_SPIRIT_KARMA_UTF32_HPP
#define HERMIT_SPIRIT_KARMA_UTF32_HPP

#include <iostream>
#include <vector>
#include <string>
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/phoenix.hpp>

namespace hermit {
  namespace spirit {
    namespace karma {
      template< typename OutputIterator >
        class utf32be :
          public boost::spirit::karma::grammar< OutputIterator, char32_t() > {
            public:
              utf32be() : utf32be::base_type( root ) {
                namespace karma = boost::spirit::karma;
                root = karma::big_dword[ karma::_pass = karma::_val <= 0x10FFFFul, karma::_1 = karma::_val ];
              }
            private:
              boost::spirit::karma::rule< OutputIterator, char32_t() > root;
      };
      template< typename OutputIterator >
        class utf32le :
          public boost::spirit::karma::grammar< OutputIterator, char32_t() > {
            public:
              utf32le() : utf32le::base_type( root ) {
                namespace karma = boost::spirit::karma;
                root = karma::little_dword[ karma::_pass = karma::_val <= 0x10FFFFul, karma::_1 = karma::_val ];
              }
            private:
              boost::spirit::karma::rule< OutputIterator, char32_t() > root;
      };
      template< typename OutputIterator >
        class utf32bestring :
          public boost::spirit::karma::grammar< OutputIterator, std::u32string() > {
            public:
              utf32bestring() : utf32bestring::base_type( root ) {
                root = *big_endian;
              }
            private:
              utf32be< OutputIterator > big_endian;
              boost::spirit::karma::rule< OutputIterator, std::u32string() > root;
      };
      template< typename OutputIterator >
        class utf32lestring :
          public boost::spirit::karma::grammar< OutputIterator, std::u32string() > {
            public:
              utf32lestring() : utf32lestring::base_type( root ) {
                root = *little_endian;
              }
            private:
              utf32le< OutputIterator > little_endian;
              boost::spirit::karma::rule< OutputIterator, std::u32string() > root;
      };
      template< typename OutputIterator >
        class utf32string :
          public boost::spirit::karma::grammar< OutputIterator, std::u32string() > {
            public:
              utf32string() : utf32string::base_type( root ) {
                namespace karma = boost::spirit::karma;
                root = karma::big_dword( 0xfeff ) << big_endian;
              }
            private:
              utf32be< OutputIterator > big_endian;
              boost::spirit::karma::rule< OutputIterator, std::u32string() > root;
      };
    }
  }
}

#endif

max_stars_repo_name: Fadis/hermit

max_issues_repo_name: Fadis/hermit

max_forks_repo_name: Fadis/hermit


text:
/**
 *    Copyright (C) 2019-present MongoDB, Inc.
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the Server Side Public License, version 1,
 *    as published by MongoDB, Inc.
 *
 *    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
 *    Server Side Public License for more details.
 *
 *    You should have received a copy of the Server Side Public License
 *    along with this program. If not, see
 *    <http://www.mongodb.com/licensing/server-side-public-license>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the Server Side Public License in all respects for
 *    all of the code used other than as permitted herein. If you modify file(s)
 *    with this exception, you may extend this exception to your version of the
 *    file(s), but you are not obligated to do so. If you do not wish to do so,
 *    delete this exception statement from your version. If you delete this
 *    exception statement from all source files in the program, then also delete
 *    it in the license file.
 */

#include "mongo/platform/basic.h"

#include "mongo/util/latch_analyzer.h"

#include <boost/iterator/transform_iterator.hpp>
#include <deque>

#include <fmt/format.h>

#include "mongo/util/hierarchical_acquisition.h"

#include "mongo/base/init.h"
#include "mongo/db/client.h"
#include "mongo/db/service_context.h"
#include "mongo/logv2/log.h"
#include "mongo/platform/mutex.h"
#include "mongo/util/fail_point.h"
#include "mongo/util/latch_analyzer.h"
#include "mongo/util/testing_proctor.h"

#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kDefault

namespace mongo {

using namespace fmt::literals;

namespace {

auto kLatchAnalysisName = "latchAnalysis"_sd;
auto kLatchViolationKey = "hierarchicalAcquisitionLevelViolations"_sd;

// LatchAnalyzer Decoration getter
const auto getLatchAnalyzer = ServiceContext::declareDecoration<LatchAnalyzer>();

/**
 * DiagnosticListener sub-class to implement updating set in LatchSetState
 */
class DiagnosticListener : public latch_detail::DiagnosticListener {
public:
    void onContendedLock(const Identity& id) override {
        if (auto client = Client::getCurrent()) {
            LatchAnalyzer::get(client).onContention(id);
        }
    }

    void onQuickLock(const Identity& id) override {
        if (auto client = Client::getCurrent()) {
            LatchAnalyzer::get(client).onAcquire(id);
        }
    }

    void onSlowLock(const Identity& id) override {
        if (auto client = Client::getCurrent()) {
            LatchAnalyzer::get(client).onAcquire(id);
        }
    }

    void onUnlock(const Identity& id) override {
        if (auto client = Client::getCurrent()) {
            LatchAnalyzer::get(client).onRelease(id);
        }
    }
};

// Register our DiagnosticListener
MONGO_INITIALIZER_GENERAL(LatchAnalysis, (/* NO PREREQS */), ("FinalizeDiagnosticListeners"))
(InitializerContext* context) {
    latch_detail::installDiagnosticListener<DiagnosticListener>();
}

// Create a FailPoint to analyze latches more seriously for diagnostic purposes. This can be used
// with a new set of test suites to verify our lock hierarchies.
MONGO_FAIL_POINT_DEFINE(enableLatchAnalysis);

bool shouldAnalyzeLatches() {
    return enableLatchAnalysis.shouldFail();
}

// Define a new serverStatus section "latchAnalysis"
class LatchAnalysisSection final : public ServerStatusSection {
public:
    LatchAnalysisSection() : ServerStatusSection(kLatchAnalysisName.toString()) {}

    bool includeByDefault() const override {
        return false;
    }

    BSONObj generateSection(OperationContext* opCtx, const BSONElement&) const override {
        BSONObjBuilder analysis;
        LatchAnalyzer::get(opCtx->getClient()).appendToBSON(analysis);
        return analysis.obj();
    };
} gLatchAnalysisSection;

// Latching state object to pin onto the Client (i.e. thread)
struct LatchSetState {
    using LatchIdentitySet = std::deque<const latch_detail::Identity*>;

    LatchSetState() {
        if (TestingProctor::instance().isEnabled()) {
            identities = std::make_unique<LatchIdentitySet>();
        }
    }

    HierarchicalAcquisitionSet levelsHeld;

    // This is a set of latches by unique Identity alone. It is not and cannot be in order of
    // acquisition or release. We only populate this when shouldAnalyzeLatches() is true.
    stdx::unordered_set<const latch_detail::Identity*> latchesHeld;

    // This is an ordered list of latch Identities. Each acquired Latch will add itself to the end
    // of this list and each released Latch will remove itself from the end. This is populated when
    // TestingProctor::instance().isEnabled() is true, i.e. in a testing environment.
    std::unique_ptr<LatchIdentitySet> identities;
};

const auto getLatchSetState = Client::declareDecoration<LatchSetState>();
}  // namespace

void LatchAnalyzer::setAllowExitOnViolation(bool allowExitOnViolation) {
    _allowExitOnViolation.store(allowExitOnViolation);
}

bool LatchAnalyzer::allowExitOnViolation() {
    return _allowExitOnViolation.load() && TestingProctor::instance().isEnabled();
}

LatchAnalyzer& LatchAnalyzer::get(ServiceContext* serviceContext) {
    return getLatchAnalyzer(serviceContext);
}

LatchAnalyzer& LatchAnalyzer::get(Client* client) {
    return get(client->getServiceContext());
}

LatchAnalyzer& LatchAnalyzer::get() {
    auto serviceContext = getCurrentServiceContext();
    invariant(serviceContext);
    return get(serviceContext);
}

void LatchAnalyzer::onContention(const latch_detail::Identity&) {
    // Nothing at the moment
}

void LatchAnalyzer::_handleAcquireViolation(ErrorCodes::Error ec,
                                            StringData message,
                                            const latch_detail::Identity& identity,
                                            Client* client) noexcept {

    {
        stdx::lock_guard lk(_mutex);

        auto& violation = _violations[identity.index()];
        ++violation.onAcquire;
    }

    _handleViolation(ec, message, identity, client);
}

void LatchAnalyzer::_handleReleaseViolation(ErrorCodes::Error ec,
                                            StringData message,
                                            const latch_detail::Identity& identity,
                                            Client* client) noexcept {

    {
        stdx::lock_guard lk(_mutex);

        auto& violation = _violations[identity.index()];
        ++violation.onRelease;
    }

    _handleViolation(ec, message, identity, client);
}

void LatchAnalyzer::_handleViolation(ErrorCodes::Error ec,
                                     StringData message,
                                     const latch_detail::Identity& identity,
                                     Client* client) noexcept {
    if (allowExitOnViolation()) {
        auto identities = LatchSetState::LatchIdentitySet{};

        auto& state = getLatchSetState(client);
        if (state.identities) {
            // We're in fatal territory, we can take our Client's list to the local stack.
            identities = std::move(*state.identities);
        }

        const auto derefIdentity = [](const auto& id) -> const latch_detail::Identity& {
            return *id;
        };
        auto begin = boost::make_transform_iterator(identities.begin(), derefIdentity);
        auto end = boost::make_transform_iterator(identities.end(), derefIdentity);

        LOGV2_FATAL_OPTIONS(ec,
                            {logv2::LogTruncation::Disabled},
                            "Theoretical deadlock found on use of latch",
                            "reason"_attr = message,
                            "latch"_attr = identity,
                            "latchesHeld"_attr = logv2::seqLog(begin, end));
    } else {
        LOGV2_WARNING(ec,
                      "Theoretical deadlock found on use of latch",
                      "reason"_attr = message,
                      "latch"_attr = identity);
    }
}

void LatchAnalyzer::onAcquire(const latch_detail::Identity& identity) {
    auto client = Client::getCurrent();
    if (!client) {
        return;
    }

    if (shouldAnalyzeLatches()) {
        // If we should analyze latches, annotate the Client state
        auto& latchSet = getLatchSetState(client).latchesHeld;

        stdx::lock_guard lk(_mutex);
        for (auto otherIdentity : latchSet) {
            auto& stat = _hierarchies[identity.index()][otherIdentity->index()];
            stat.identity = otherIdentity;
            ++stat.acquiredAfter;
        }

        latchSet.insert(&identity);
    }

    if (!identity.level()) {
        // If we weren't given a HierarchicalAcquisitionLevel, don't verify hierarchies
        return;
    }

    auto level = *identity.level();
    auto& handle = getLatchSetState(client);
    auto result = handle.levelsHeld.add(level);
    switch (result) {
        case HierarchicalAcquisitionSet::AddResult::kValidWasAbsent: {
            // The good result. Nothing to do.
        } break;
        case HierarchicalAcquisitionSet::AddResult::kInvalidWasAbsent: {
            _handleAcquireViolation(ErrorCodes::Error{5106800},
                                    "Latch acquired after other latch of lower level"_sd,
                                    identity,
                                    client);
        } break;
        case HierarchicalAcquisitionSet::AddResult::kInvalidWasPresent: {
            _handleAcquireViolation(ErrorCodes::Error{5106801},
                                    "Latch acquired after other latch of same level"_sd,
                                    identity,
                                    client);
        } break;
    };

    if (handle.identities) {
        // Since this latch has a verified Level, we can add it to the stack of identities
        handle.identities->push_back(&identity);
    }
}

void LatchAnalyzer::onRelease(const latch_detail::Identity& identity) {
    auto client = Client::getCurrent();
    if (!client) {
        return;
    }

    if (shouldAnalyzeLatches()) {
        // If we should analyze latches, annotate the Client state
        auto& latchSet = getLatchSetState(client).latchesHeld;
        latchSet.erase(&identity);

        stdx::lock_guard lk(_mutex);
        for (auto otherIdentity : latchSet) {
            auto& stat = _hierarchies[identity.index()][otherIdentity->index()];
            stat.identity = otherIdentity;
            ++stat.releasedBefore;
        }
    }

    if (!identity.level()) {
        // If we weren't given a HierarchicalAcquisitionLevel, don't verify hierarchies
        return;
    }

    auto level = *identity.level();
    auto& handle = getLatchSetState(client);
    auto result = handle.levelsHeld.remove(level);
    switch (result) {
        case HierarchicalAcquisitionSet::RemoveResult::kValidWasPresent: {
            // The good result. Nothing to do.
        } break;
        case HierarchicalAcquisitionSet::RemoveResult::kInvalidWasAbsent: {
            _handleReleaseViolation(
                ErrorCodes::Error{5106802},
                "Latch released after other latch of same level (usually the same latch twice)"_sd,
                identity,
                client);
        } break;
        case HierarchicalAcquisitionSet::RemoveResult::kInvalidWasPresent: {
            _handleReleaseViolation(ErrorCodes::Error{5106803},
                                    "Latch released before other latch of lower level"_sd,
                                    identity,
                                    client);
        } break;
    };

    if (handle.identities) {
        // Since this latch has a verified Level, we can remove it from the stack of identities
        handle.identities->pop_back();
    }
}

void LatchAnalyzer::appendToBSON(mongo::BSONObjBuilder& result) const {
    for (auto iter = latch_detail::Catalog::get().iter(); iter.more();) {
        auto data = iter.next();
        if (!data) {
            continue;
        }

        auto& identity = data->identity();

        BSONObjBuilder latchObj = result.subobjStart(identity.name());
        latchObj.append("created", data->counts().created.loadRelaxed());
        latchObj.append("destroyed", data->counts().destroyed.loadRelaxed());
        latchObj.append("acquired", data->counts().acquired.loadRelaxed());
        latchObj.append("released", data->counts().released.loadRelaxed());
        latchObj.append("contended", data->counts().contended.loadRelaxed());

        auto appendViolations = [&] {
            stdx::lock_guard lk(_mutex);
            auto it = _violations.find(identity.index());
            if (it == _violations.end()) {
                return;
            }
            auto& violation = it->second;

            BSONObjBuilder violationObj = latchObj.subobjStart(kLatchViolationKey);
            violationObj.append("onAcquire", violation.onAcquire);
            violationObj.append("onRelease", violation.onRelease);
        };

        appendViolations();

        if (!shouldAnalyzeLatches()) {
            // Only append hierarchical information if we should analyze latches
            continue;
        }

        stdx::lock_guard lk(_mutex);
        auto it = _hierarchies.find(identity.index());
        if (it == _hierarchies.end()) {
            continue;
        }

        auto& latchHierarchy = it->second;
        if (latchHierarchy.empty()) {
            continue;
        }

        {
            BSONObjBuilder acquiredAfterObj = latchObj.subobjStart("acquiredAfter");
            for (auto& [_, stat] : latchHierarchy) {
                auto count = stat.acquiredAfter;
                if (count == 0) {
                    continue;
                }
                acquiredAfterObj.append(stat.identity->name(), count);
            }
        }

        {
            BSONObjBuilder releasedBeforeObj = latchObj.subobjStart("releasedBefore");
            for (auto& [_, stat] : latchHierarchy) {
                auto count = stat.releasedBefore;
                if (count == 0) {
                    continue;
                }
                releasedBeforeObj.append(stat.identity->name(), count);
            }
        }
    }
}

void LatchAnalyzer::dump() {
    if (!shouldAnalyzeLatches()) {
        return;
    }

    BSONObjBuilder bob(1024 * 1024);
    appendToBSON(bob);

    LOGV2_OPTIONS(25003,
                  {logv2::LogTruncation::Disabled},
                  "LatchAnalyzer dump",
                  "latchAnalysis"_attr = bob.done());
}

LatchAnalyzerDisabledBlock::LatchAnalyzerDisabledBlock() {
    LatchAnalyzer::get().setAllowExitOnViolation(false);
}

LatchAnalyzerDisabledBlock::~LatchAnalyzerDisabledBlock() {
    LatchAnalyzer::get().setAllowExitOnViolation(true);
}

}  // namespace mongo

max_stars_repo_name: benety/mongo

max_issues_repo_name: benety/mongo

max_forks_repo_name: benety/mongo