text:
#define _WIN32_WINNT 0x0601
#include <iostream>
#include <list>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include "server.h"
#include "sessionbase.h"
using namespace boost::asio;

void error_msg(const std::string& type, const boost::system::error_code& e) {
	std::cerr << type << " error[" << e.value() << "] " << e.message() << std::endl;
}
struct service { io_service ios; };
struct TcpServerImpl {
	typedef std::shared_ptr<SessionBase> SessionType;
	typedef SessionBase::socketType socketType;
	typedef std::list<SessionType> SessionContainer;

	io_service& ios;
	ip::tcp::acceptor acceptor;
	int backlog;
	unsigned short port_num;
	SessionContainer sessionlist;
	std::shared_ptr<SessionCreator> creator;

	TcpServerImpl(io_service& _ios) : ios(_ios), acceptor(_ios) {}

	void prepare_acceptor() {
		ip::tcp::endpoint ep(ip::tcp::v4(), port_num);
		acceptor.open(ep.protocol());
		acceptor.bind(ep);
	}

	SessionType prepare_session() {
		SessionType session = creator->create();
		sessionlist.push_back(session);
		session->socket() = std::make_shared<socketType>(ios);

		return session;
	}
	void operation_accept() {
		SessionType session = prepare_session();

		acceptor.async_accept((*session->socket()),
			boost::bind(&TcpServerImpl::handler_accept, this, boost::placeholders::_1, session));
	}
	void handler_accept(const boost::system::error_code& e, SessionType& session) {
		if (e.value() != 0) {
			error_msg("accept", e);
			return;
		}
		operation_accept();

		operation_recv(session);

		operation_send(session);
	}
	void operation_recv(SessionType& session) {
		operation_recv_header(session);
	}
	void operation_recv_header(SessionType& session) {
		session->prepare_header_buffer();

		session->socket()->async_receive(buffer(session->header()),
			boost::bind(&TcpServerImpl::handler_recv_header, this, boost::placeholders::_1,
				boost::placeholders::_2, session));
	}
	void handler_recv_header(const boost::system::error_code& e, std::size_t read_size, SessionType& session) {
		if (e.value() != 0) {
			error_msg("recv header", e);
			return;
		}

		if (!session->validate_header()) {
			error_msg("invalid header", boost::system::error_code());
			return;
		}

		operation_recv_data(session);
	}
	void operation_recv_data(SessionType& session) {
		session->prepare_data_buffer();

		session->socket()->async_receive(buffer(session->data()),
			boost::bind(&TcpServerImpl::handler_recv_data, this, boost::placeholders::_1,
				boost::placeholders::_2, session));
	}
	void handler_recv_data(const boost::system::error_code& e, std::size_t read_size, SessionType& session) {
		if (e.value() != 0) {
			error_msg("recv data", e);
			return;
		}

		operation_recv(session);

		session->process_received_data();
	}
	void operation_send(SessionType& session) {
		// check whether there is something to send or not.
		session->process_send_data();

		session->prepare_send_buffer();

		session->socket()->async_send(buffer(session->out_packet()),
			boost::bind(&TcpServerImpl::handler_send, this, boost::placeholders::_1,
				boost::placeholders::_2, session));
	}
	void handler_send(const boost::system::error_code& e, std::size_t send_size, SessionType& session) {
		if (e.value() != 0) {
			error_msg("send", e);
			return;
		}

		session->notify_sent_result();
	}
};
TcpServer::TcpServer()
	: impl(new TcpServerImpl(service().ios)) {

}
TcpServer::~TcpServer() {
	if (impl) {
		delete impl;
		impl = nullptr;
	}
}
void TcpServer::setSessionCreator(std::shared_ptr<SessionCreator> creator) {
	impl->creator = creator;
}
void TcpServer::open(unsigned short port_num, int MAXCON) {
	impl->port_num = port_num;
	impl->backlog = MAXCON;

	impl->prepare_acceptor();

	impl->acceptor.listen(MAXCON);

	impl->operation_accept();
}
void TcpServer::run() {
	impl->ios.run();
}

ext: cpp


text:
#include <boost/test/unit_test.hpp>
#include <ygo/deck/c/User.h>
#include <ygo/deck/c/DB.h>

struct User_Fixture
{
    User_Fixture()
    {
        DB_NAME(set_path)("test/card.db");
    }
};

BOOST_FIXTURE_TEST_SUITE(User, User_Fixture)

BOOST_AUTO_TEST_CASE(Create)
{
    auto user = USER_NAME(new_create)("Test");
    auto name = USER_NAME(name)(user);
    BOOST_CHECK_EQUAL(std::string(name), "Test");
    USER_NAME(delete_name)(name);
    USER_NAME(delete)(user);
}

BOOST_AUTO_TEST_CASE(Open)
{
    auto user = USER_NAME(new)("Test");
    auto name = USER_NAME(name)(user);
    BOOST_CHECK_EQUAL(std::string(name), "Test");
    USER_NAME(delete_name)(name);
    USER_NAME(delete)(user);
}

BOOST_AUTO_TEST_CASE(Unknown)
{
    auto user = USER_NAME(new)("NotKnown");
    BOOST_CHECK(user == nullptr);
}

BOOST_AUTO_TEST_CASE(Remove)
{
    auto user = USER_NAME(new)("Test");
    auto name = USER_NAME(name)(user);
    BOOST_CHECK_EQUAL(std::string(name), "Test");
    USER_NAME(remove)(user);
    USER_NAME(delete_name)(name);
    USER_NAME(delete)(user);

    auto user2 = USER_NAME(new)("Test");
    BOOST_CHECK(user2 == nullptr);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: DeonPoncini/ygodeck-c

max_issues_repo_name: DeonPoncini/ygodeck-c

max_forks_repo_name: DeonPoncini/ygodeck-c


text:
/**
 * Swaggy Jenkins
 * Jenkins API clients generated from Swagger / Open API specification
 *
 * The version of the OpenAPI document: 1.1.2-pre.0
 * Contact: blah@cliffano.com
 *
 * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0.
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

#include "ClassesByClass.h"

#include <string>
#include <vector>
#include <sstream>
#include <stdexcept>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

using boost::property_tree::ptree;
using boost::property_tree::read_json;
using boost::property_tree::write_json;

namespace org {
namespace openapitools {
namespace server {
namespace model {

ClassesByClass::ClassesByClass(boost::property_tree::ptree const& pt)
{
        fromPropertyTree(pt);
}

std::string ClassesByClass::toJsonString(bool prettyJson /* = false */)
{
    return toJsonString_internal(prettyJson);
}

void ClassesByClass::fromJsonString(std::string const& jsonString)
{
    fromJsonString_internal(jsonString);
}

boost::property_tree::ptree ClassesByClass::toPropertyTree()
{
    return toPropertyTree_internal();
}

void ClassesByClass::fromPropertyTree(boost::property_tree::ptree const& pt)
{
    fromPropertyTree_internal(pt);
}

std::string ClassesByClass::toJsonString_internal(bool prettyJson)
{
	std::stringstream ss;
	write_json(ss, this->toPropertyTree(), prettyJson);
	return ss.str();
}

void ClassesByClass::fromJsonString_internal(std::string const& jsonString)
{
	std::stringstream ss(jsonString);
	ptree pt;
	read_json(ss,pt);
	this->fromPropertyTree(pt);
}

ptree ClassesByClass::toPropertyTree_internal()
{
	ptree pt;
	ptree tmp_node;
	// generate tree for Classes
	if (!m_Classes.empty()) {
		for (const auto &childEntry : m_Classes) {
            ptree Classes_node;
            Classes_node.put("", childEntry);
            tmp_node.push_back(std::make_pair("", Classes_node));
		}
		pt.add_child("classes", tmp_node);
		tmp_node.clear();
	}
	pt.put("_class", m__class);
	return pt;
}

void ClassesByClass::fromPropertyTree_internal(ptree const &pt)
{
	ptree tmp_node;
	// push all items of Classes into member vector
	if (pt.get_child_optional("classes")) {
		for (const auto &childTree : pt.get_child("classes")) {
            std::string val =
                childTree.second.data();
            m_Classes.emplace_back(std::move(val));
		}
	}
	m__class = pt.get("_class", "");
}

std::vector<std::string> ClassesByClass::getClasses() const
{
    return m_Classes;
}

void ClassesByClass::setClasses(std::vector<std::string> value)
{
	m_Classes = value;
}
std::string ClassesByClass::get_Class() const
{
    return m__class;
}

void ClassesByClass::set_Class(std::string value)
{
	m__class = value;
}

std::vector<ClassesByClass> createClassesByClassVectorFromJsonString(const std::string& json)
{
    std::stringstream sstream(json);
    boost::property_tree::ptree pt;
    boost::property_tree::json_parser::read_json(sstream,pt);

    auto vec = std::vector<ClassesByClass>();
    for (const auto& child: pt) {
        vec.emplace_back(ClassesByClass(child.second));
    }

    return vec;
}

}
}
}
}

max_stars_repo_name: cliffano/jenkins-api-clients-generator

max_issues_repo_name: cliffano/jenkins-api-clients-generator

max_forks_repo_name: cliffano/jenkins-api-clients-generator


text:
// General ROS functionality
#include <ros/ros.h>

#include <boost/regex.hpp>

// Quadrotor controllers
#include <hal_quadrotor/control/Hover.h>

using namespace std;

// Main entry point of application
int main(int argc, char **argv)
{
	// Initialise the ROS client
	string nodestr = string("land_muav");
  	ros::init(argc, argv, nodestr.c_str());

  	// Create a node handle, which this C code will use to bind to the ROS server
  	ros::NodeHandle n;

	// Try and get a list of topics currently being braodcast
	ros::master::V_TopicInfo topics;
	vector<string> names;
	vector<ros::Subscriber> top_state;

	// Iterate over the topics
	if (ros::master::getTopics(topics)) {
		for (ros::master::V_TopicInfo::iterator i = topics.begin(); i != topics.end(); i++) {

			boost::cmatch mr;
			if (boost::regex_match(i->name.c_str(), mr, boost::regex("^/hal/(.+)/(.+)/(.+)/Estimate$")))
			{
				string land_cmd = string("/hal/") + mr[1].str() + "/" + mr[2].str() + "/" + mr[3].str() + string("/controller/Hover");
				ROS_INFO("land command %s", land_cmd.c_str());
				ros::ServiceClient srvLand = n.serviceClient<hal_quadrotor::Hover>(land_cmd.c_str());
				hal_quadrotor::Hover msgLand;
				if(!srvLand.call(msgLand))
					ROS_FATAL("NO Land!!");
			}
		}
	}

  // Success!
  return 0;
}


text:
#include "GpuImageSample.h"
#include "GPUContext.h"
#include "Utilities/utilitiesImage.h"

using namespace Limitless;

//#define DEBUG_OWNER

#ifdef DEBUG_OWNER
#include <boost/format.hpp>
#endif //DEBUG_OWNER

GpuImageSample::GpuImageSample():
m_flags(CL_MEM_READ_WRITE),
m_width(0),
m_height(0),
m_channels(0),
m_channelBits(0),
m_texture(0)
{}

GpuImageSample::GpuImageSample(unsigned int width, unsigned int height, unsigned int channels, unsigned int channelBits):
m_flags(CL_MEM_READ_WRITE),
m_channels(channels),
m_channelBits(channelBits),
m_texture(0)
{
	resize(width, height, channels);
}

GpuImageSample::GpuImageSample(unsigned char *buffer, unsigned int width, unsigned int height, unsigned int channels, unsigned int channelBits):
m_flags(CL_MEM_READ_WRITE),
m_channels(channels),
m_channelBits(channelBits),
m_texture(0)
{
	cl::Event event;

	resize(width, height, channels);
	if(write(buffer, width, height, channels, event))
		event.wait();
}

GpuImageSample::~GpuImageSample()
{
}

unsigned char *GpuImageSample::buffer(size_t index)
{
    if(index!=0)
        return nullptr;

	if(m_hostBuffer.size() == m_size)
		return m_hostBuffer.data();

	cl::Event event;

	m_hostBuffer.resize(m_size);

	if(!read(m_hostBuffer.data(), m_width, m_height, event))
		return NULL;

	event.wait();
	return m_hostBuffer.data();
}

bool GpuImageSample::resize(unsigned int width, unsigned int height, unsigned int channels, unsigned int channelBits, bool inDrawThread)
{
	cl_int error = CL_SUCCESS;

	if((width == 0) || (height == 0))
		return false;

	bool createTexture=false;

	if(m_texture==0)
		createTexture=true;
	else if(m_channels != channels)
		createTexture=true;

    if(createTexture)
    {
        GLuint internalFormat;
        GLuint format;

        switch(channels)
        {
        case 1:
            internalFormat=GL_R8UI;
            format=GL_RED_INTEGER;
            break;
        case 2:
            internalFormat=GL_RG8UI;
            format=GL_RG_INTEGER;
            break;
        case 3:
            internalFormat=GL_RGB8UI;
            format=GL_RGB_INTEGER;
            break;
        case 4:
        default:
            internalFormat=GL_RGBA8UI;
            format=GL_RGBA_INTEGER;
            break;
        }

        if(inDrawThread)
        {
            //we are inside the draw thread so it can be created here
            glGenTextures(1, &m_texture);

            glBindTexture(GL_TEXTURE_2D, m_texture);
            glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, width, height, 0, format, GL_UNSIGNED_BYTE, NULL);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
            glBindTexture(GL_TEXTURE_2D, 0);
        }
        else
            m_texture=GPUContext::createTexture(GL_TEXTURE_2D, internalFormat, width, height, format, GL_UNSIGNED_BYTE);

        m_image=cl::ImageGL(GPUContext::openCLContext(), m_flags, GL_TEXTURE_2D, 0, m_texture, &error);

#ifdef DEBUG_OWNER
        OutputDebugStringA((boost::format("GpuImageSample resize (%08x, %08x) Opengl\n")%m_texture%m_image()).str().c_str());
#endif //DEBUG_OWNER

        m_owned=OpenGl;
        //	m_image=GPUContext::createClImage(m_flags, GL_TEXTURE_2D, GL_RGBA8UI, width, height, GL_RGBA_INTEGER, GL_UNSIGNED_BYTE, m_texture);

        if(error!=CL_SUCCESS)
        {
            m_width=0;
            m_height=0;
            assert(false);
            return false;
        }

        m_channels=channels;
    }

    if((width!=m_width)||(height!=m_height))
    {
        m_width=width;
        m_height=height;
//        m_channels=channels;
        m_size=m_width*m_height*m_channels*sizeof(unsigned char);
    }

	return true;
}

bool GpuImageSample::save(std::string fileName)
{
	std::vector<unsigned char> m_size(m_size);
	cl::Event event;

	read(m_size.data(), m_width, m_height, event);
	event.wait();

	if(m_channels==4)
		savePPM(fileName.c_str(), RGBA, m_size.data(), m_width, m_height);
	else
		savePPM(fileName.c_str(), RGB, m_size.data(), m_width, m_height);

	return true;
}

bool GpuImageSample::write(IImageSample *imageSample, cl::Event &event, std::vector<cl::Event> *events)
{
	return write(imageSample->buffer(), imageSample->width(), imageSample->height(), imageSample->channels(), event, events);
}

bool GpuImageSample::write(unsigned char *buffer, unsigned int width, unsigned int height, unsigned int channels, cl::Event &event, std::vector<cl::Event> *events)
{
	if(width <= 0)
		return false;
	if(height <= 0)
		return false;

	if((m_width != width) || (m_height != height) || (m_channels != channels))
		resize(width, height, channels);

	cl_int status;
	cl::size_t<3> origin;
	cl::size_t<3> region;

	origin[0]=0;
	origin[1]=0;
	origin[2]=0;

	region[0]=m_width;
	region[1]=m_height;
	region[2]=1;

	cl::Event acquireEvent;

	if(acquireOpenCl(acquireEvent))
		acquireEvent.wait();

	status=GPUContext::openCLCommandQueue().enqueueWriteImage(m_image, CL_FALSE, origin, region, 0, 0, buffer, events, &event);
//	status=GPUContext::enqueueWriteImage(m_image, origin, region, 0, 0, buffer, events, &event);

	if(status != CL_SUCCESS)
	{
		assert(false);
		return false;
	}
	return true;
}

bool GpuImageSample::read(IImageSample *imageSample, cl::Event &event, std::vector<cl::Event> *events)
{
	return read(imageSample->buffer(), imageSample->width(), imageSample->height(), event, events);
}

bool GpuImageSample::read(unsigned char *buffer, unsigned int width, unsigned int height, cl::Event &event, std::vector<cl::Event> *events)
{
	if(width <= 0)
		return false;
	if(height <= 0)
		return false;

	if((m_width != width) || (m_height != height))
		return false;

	cl_int status;
	cl::size_t<3> origin;
	cl::size_t<3> region;

	origin[0]=0;
	origin[1]=0;
	origin[2]=0;

	region[0]=m_width;
	region[1]=m_height;
	region[2]=1;

	status=GPUContext::openCLCommandQueue().enqueueReadImage(m_image, CL_FALSE, origin, region, 0, 0, buffer, events, &event);

	if(status != CL_SUCCESS)
	{
		assert(false);
		return false;
	}
	return true;
}

bool GpuImageSample::copy(GpuImageSample *sample, cl::Event &event, std::vector<cl::Event> *waitEvents)
{
	cl::Event localEvent;
	std::vector<cl::Event> localWaitEvents;

	if((m_width != sample->width()) || (m_height != sample->height()))
		resize(sample->width(), sample->height(), sample->channels(), sample->channelBits());

	if(waitEvents != nullptr)
		localWaitEvents.insert(localWaitEvents.end(), waitEvents->begin(), waitEvents->end());

	if(acquireOpenCl(localEvent))
		localWaitEvents.push_back(localEvent);
	if(sample->acquireOpenCl(localEvent))
		localWaitEvents.push_back(localEvent);

	cl_int status;
	cl::size_t<3> origin;
	cl::size_t<3> region;

	origin[0]=0;
	origin[1]=0;
	origin[2]=0;

	region[0]=m_width;
	region[1]=m_height;
	region[2]=1;

	if(localWaitEvents.empty())
		status=GPUContext::openCLCommandQueue().enqueueCopyImage(sample->glImage(), m_image, origin, origin, region, nullptr, &event);
	else
		status=GPUContext::openCLCommandQueue().enqueueCopyImage(sample->glImage(), m_image, origin, origin, region, &localWaitEvents, &event);

	if(status != CL_SUCCESS)
	{
		assert(false);
		return false;
	}
	return true;
}

bool GpuImageSample::acquireMultipleOpenCl(std::vector<GpuImageSample *> samples, cl::Event &event, std::vector<cl::Event> *waitEvents)
{
	std::vector<cl::Memory> glImages;

	for(size_t i=0; i<samples.size(); ++i)
	{
		GpuImageSample *sample=samples[i];

		if(sample->m_owned != OpenCl)
			glImages.push_back(sample->m_image);
	}

	if(glImages.empty())
		return false;

	GPUContext::openCLCommandQueue().enqueueAcquireGLObjects(&glImages, waitEvents, &event);

    for(size_t i=0; i<samples.size(); ++i)
    {
        GpuImageSample *sample=samples[i];

        if(sample->m_owned!=OpenCl)
            sample->m_owned=OpenCl;
    }

	return true;
}

bool GpuImageSample::releaseMultipleOpenCl(std::vector<GpuImageSample *> samples, cl::Event &event, std::vector<cl::Event> *waitEvents)
{
	std::vector<cl::Memory> glImages;

	for(size_t i=0; i<samples.size(); ++i)
	{
		GpuImageSample *sample=samples[i];

		if(sample->m_owned == OpenCl)
			glImages.push_back(sample->m_image);
	}

	if(glImages.empty())
		return false;

    cl_int error=GPUContext::openCLCommandQueue().enqueueReleaseGLObjects(&glImages, waitEvents, &event);

    for(size_t i=0; i<samples.size(); ++i)
    {
        GpuImageSample *sample=samples[i];

        if(sample->m_owned==OpenCl)
            sample->m_owned=OpenGl;
    }
    assert(error==CL_SUCCESS);
	return true;
}

bool GpuImageSample::acquireOpenCl(cl::Event &event, std::vector<cl::Event> *waitEvents)
{
	if(m_owned == OpenCl)
		return false;

	std::vector<cl::Memory> glImages;

	glImages.push_back(m_image);
	cl_int error=GPUContext::openCLCommandQueue().enqueueAcquireGLObjects(&glImages, waitEvents, &event);
	m_owned=OpenCl;
#ifdef DEBUG_OWNER
    OutputDebugStringA((boost::format("GpuImageSample acquireOpenCl (%08x, %08x) OpenCl\n")%m_texture%m_image()).str().c_str());
#endif //DEBUG_OWNER
    assert(error==CL_SUCCESS);
	return true;
}

bool GpuImageSample::releaseOpenCl(cl::Event &event, std::vector<cl::Event> *waitEvents)
{
	if(m_owned != OpenCl)
		return false;

	std::vector<cl::Memory> glImages;

	glImages.push_back(m_image);
    cl_int error=GPUContext::openCLCommandQueue().enqueueReleaseGLObjects(&glImages, waitEvents, &event);
	m_owned=OpenGl;
#ifdef DEBUG_OWNER
    OutputDebugStringA((boost::format("GpuImageSample releaseOpenCl (%08x, %08x) OpenGl\n")%m_texture%m_image()).str().c_str());
#endif //DEBUG_OWNER
    assert(error==CL_SUCCESS);
	return true;
}

bool GpuImageSample::acquireOpenGl()
{
    bool released=false;

	if(m_owned == OpenCl)
	{
		cl::Event event;

		releaseOpenCl(event);
		event.wait();
        released=true;
	}
	m_owned=OpenGl;
#ifdef DEBUG_OWNER
    OutputDebugStringA((boost::format("GpuImageSample acquireOpenGl (%08x, %08x) OpenGl %d\n")%m_texture%m_image()%released).str().c_str());
#endif //DEBUG_OWNER

	return true;
}

bool GpuImageSample::releaseOpenGl()
{
//	m_owned=None;
	return true;
}

max_stars_repo_name: InfiniteInteractive/LimitlessSDK

max_issues_repo_name: InfiniteInteractive/LimitlessSDK

max_forks_repo_name: InfiniteInteractive/LimitlessSDK


text: #include <boost/uuid/basic_name_generator.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#ifndef __SIMULATION_MODULE_HPP
#define __SIMULATION_MODULE_HPP

#include "../aqlib/Module.hpp"
#include "../aqlib/Thread.hpp"
#include <log4cxx/logger.h>
#include <boost/shared_ptr.hpp>
#include "SimulationRequest.hpp"
#include "SimulationListener.hpp"
#include <set>

namespace simulation
{

class ConnectionManager;
class ConnectionListener;

class Module: public aqlib::Module
{
    static log4cxx::LoggerPtr logger;

    aqlib::Monitor mLock;
    // Set to true when application is shutting down
    bool mShutdownRequested;
    // Reset to false at the beginning of a simulation,
    // set to true by the client if he wants a long running simulation interrupted.
    // The simulations should poll this flag and stop if it was requested
    bool mSimulationStopRequested;

    class ProcessorThread: public aqlib::Thread
    {
        Module *mOwner;
    public:
        ProcessorThread(Module *owner);
        void run();
    };
    boost::shared_ptr<ProcessorThread> mProcessorThread;

    // Only one simulation runs at a time
    SimulationRequestPtr mSimulationRequest;

    typedef std::set<SimulationListener *> SimulationListeners;
    SimulationListeners mSimulationListeners;

public:
    static const std::string NAME;
    Module();

    // Implement the Module interface
    const std::string& getModuleName() const;
    void init();
    void cleanup();

    void run();
    void process();

    bool isShutdownRequested();
    void requestShutdown();

    bool isSimulationStopRequested();
    void requestSimulationStop();

    // Runs this simulation
    void requestSimulation(const SimulationRequestPtr &request);

    void addSimulationListener(SimulationListener *listener);
    void removeSimulationListener(SimulationListener *listener);

    void notifySimulationProgressUpdate(double percentRemaining, const SimulationResultPtr &result);

private:
    SimulationRequestPtr waitSimulationRequest();
};

} // namespace simulation

#endif // __SIMULATION_MODULE_HPP

max_stars_repo_name: aquarians/Public

max_issues_repo_name: aquarians/Public

max_forks_repo_name: aquarians/Public


text:
//
//  untitled
//
//  Created by Arnold Müller on 2016-02-11.
//  Copyright (c) 2016 __MyCompanyName__. All rights reserved.
//
//# /Users/arnold/Documents/prg/clang/bin/clang++ -U__STRICT_ANSI__ -std=c++14 -I/Users/arnold/Documents/prg/libraries/boost_1_56_0/ -I/Developer/SDKs/MacOSX10.6.sdk/usr/include -Wall -O2 -L/Users/arnold/Documents/prg/libraries/boost_1_56_0/stage/lib  -o excepttest excepttest.cpp -lboost_system -lboost_filesystem -lboost_iostreams

#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <exception>
#include <boost/filesystem.hpp>

namespace b = boost;
namespace bfs = boost::filesystem;

int main (int argc, char const *argv[])
{
	using namespace std;
	int ret {0};
	try {
		cout << f1() << endl;
	} catch(const std::exception& e) {
		std::cerr << e.what() << std::endl;
	} catch(...) {
		std::cerr << "Unknown exception" << std::endl;
	}
	return ret;
}

max_stars_repo_name: noeld/cpp

max_issues_repo_name: noeld/cpp

max_forks_repo_name: noeld/cpp


text:
// Copyright 2019 Hans Dembinski
//
// 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_HISTOGRAM_DETAIL_NOOP_MUTEX_HPP
#define BOOST_HISTOGRAM_DETAIL_NOOP_MUTEX_HPP

#include <boost/core/empty_value.hpp>
#include <boost/histogram/detail/axes.hpp>
#include <boost/mp11/utility.hpp> // mp_if
#include <mutex>

namespace boost {
namespace histogram {
namespace detail {

struct null_mutex {
  bool try_lock() noexcept { return true; }
  void lock() noexcept {}
  void unlock() noexcept {}
};

template <class Axes, class Storage,
          class DetailMutex = mp11::mp_if_c<(Storage::has_threading_support &&
                                             detail::has_growing_axis<Axes>::value),
                                            std::mutex, detail::null_mutex>>
struct mutex_base : empty_value<DetailMutex> {
  mutex_base() = default;
  // do not copy or move mutex
  mutex_base(const mutex_base&) : empty_value<DetailMutex>() {}
  // do not copy or move mutex
  mutex_base& operator=(const mutex_base&) { return *this; }
};

} // namespace detail
} // namespace histogram
} // namespace boost

#endif

max_stars_repo_name: kindlychung/mediasoup-sfu-cpp

max_issues_repo_name: kindlychung/mediasoup-sfu-cpp

max_forks_repo_name: kindlychung/mediasoup-sfu-cpp


text:
#include <badem/rpc/rpc_connection_secure.hpp>
#include <badem/rpc/rpc_secure.hpp>

#include <boost/polymorphic_pointer_cast.hpp>

badem::rpc_connection_secure::rpc_connection_secure (badem::rpc_config const & rpc_config, boost::asio::io_context & io_ctx, badem::logger_mt & logger, badem::rpc_handler_interface & rpc_handler_interface, boost::asio::ssl::context & ssl_context) :
badem::rpc_connection (rpc_config, io_ctx, logger, rpc_handler_interface),
stream (socket, ssl_context)
{
}

void badem::rpc_connection_secure::parse_connection ()
{
	// Perform the SSL handshake
	auto this_l = std::static_pointer_cast<badem::rpc_connection_secure> (shared_from_this ());
	stream.async_handshake (boost::asio::ssl::stream_base::server,
	[this_l](auto & ec) {
		this_l->handle_handshake (ec);
	});
}

void badem::rpc_connection_secure::on_shutdown (const boost::system::error_code & error)
{
	// No-op. We initiate the shutdown (since the RPC server kills the connection after each request)
	// and we'll thus get an expected EOF error. If the client disconnects, a short-read error will be expected.
}

void badem::rpc_connection_secure::handle_handshake (const boost::system::error_code & error)
{
	if (!error)
	{
		read ();
	}
	else
	{
		logger.always_log ("TLS: Handshake error: ", error.message ());
	}
}

void badem::rpc_connection_secure::write_completion_handler (std::shared_ptr<badem::rpc_connection> rpc)
{
	auto rpc_connection_secure = boost::polymorphic_pointer_downcast<badem::rpc_connection_secure> (rpc);
	rpc_connection_secure->stream.async_shutdown (boost::asio::bind_executor (rpc->strand, [rpc_connection_secure](auto const & ec_shutdown) {
		rpc_connection_secure->on_shutdown (ec_shutdown);
	}));
}

max_stars_repo_name: bademcurrency/badem-node

max_issues_repo_name: bademcurrency/badem-node

max_forks_repo_name: bademcurrency/badem-node


text:
/**
* Connected Vision - https://github.com/ConnectedVision
* MIT License
*/

// auto-generated header by CodeFromTemplate - Connected Vision - https://github.com/ConnectedVision
// CodeFromTemplate Version: 0.3 alpha
// stubs/Stub_ModuleStatus.cpp
// NEVER TOUCH this file!

#include <utility>

#include <rapidjson/document.h>
#include <rapidjson/prettywriter.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/error/en.h>
#include <boost/make_shared.hpp>

#include "Stub_ModuleStatus.h"
#include "../Class_ModuleStatus.h"

// --> Do NOT EDIT <--
namespace ConnectedVision {

const boost::shared_ptr<std::string> Stub_ModuleStatus::moduleStatus_na = boost::make_shared<std::string>("n/a");
const boost::shared_ptr<std::string> Stub_ModuleStatus::moduleStatus_up = boost::make_shared<std::string>("up");
const boost::shared_ptr<std::string> Stub_ModuleStatus::moduleStatus_down = boost::make_shared<std::string>("down");

// --> Do NOT EDIT <--
/* copy constructors */
Stub_ModuleStatus::Stub_ModuleStatus(const Stub_ModuleStatus& other)
{
	// TODO: other.readLock
	// name
	if ( other.name )
		name = boost::make_shared<std::string>(*other.name);
	// moduleID
	moduleID = other.moduleID;
	// moduleStatus
	if ( other.moduleStatus )
		moduleStatus = boost::make_shared<std::string>(*other.moduleStatus);
	// configsRunning
	{
		const auto& n0 = other.configsRunning;
		auto a0 = boost::make_shared<std::vector<ConnectedVision::id_t>>( (n0->size()) );
		for (size_t i0 = 0; i0 < n0->size(); ++i0)
		{
			a0->at(i0) = n0->at(i0);
		}
		configsRunning = a0;
	}
	// configsWaiting
	{
		const auto& n0 = other.configsWaiting;
		auto a0 = boost::make_shared<std::vector<ConnectedVision::id_t>>( (n0->size()) );
		for (size_t i0 = 0; i0 < n0->size(); ++i0)
		{
			a0->at(i0) = n0->at(i0);
		}
		configsWaiting = a0;
	}
	// configID
	configID = other.configID;
	// timestamp
	timestamp = other.timestamp;
}

// --> Do NOT EDIT <--
/* copy assignment operator */
Stub_ModuleStatus& Stub_ModuleStatus::operator =(const Stub_ModuleStatus& other)
{
	Stub_ModuleStatus tmp(other); // re-use copy-constructor
	*this = std::move(tmp); // re-use move-assignment
	return *this;
}

// --> Do NOT EDIT <--
/* mopy assignment operator */
Stub_ModuleStatus& Stub_ModuleStatus::operator =(Stub_ModuleStatus&& other) noexcept
{
	// name
    std::swap(name, other.name);
	// moduleID
    std::swap(moduleID, other.moduleID);
	// moduleStatus
    std::swap(moduleStatus, other.moduleStatus);
	// configsRunning
    std::swap(configsRunning, other.configsRunning);
	// configsWaiting
    std::swap(configsWaiting, other.configsWaiting);
	// configID
    std::swap(configID, other.configID);
	// timestamp
    std::swap(timestamp, other.timestamp);

	return *this;
}

// --> Do NOT EDIT <--
/* default constructors */
Stub_ModuleStatus::Stub_ModuleStatus()
{
	clear();
}

// --> Do NOT EDIT <--
Stub_ModuleStatus::Stub_ModuleStatus(const rapidjson::Value& value)
{
	clear();
	parseJson( value );
}

// --> Do NOT EDIT <--
Stub_ModuleStatus::Stub_ModuleStatus(const std::string& str)
{
	clear();
	parseJson( str );
}

// --> Do NOT EDIT <--
Stub_ModuleStatus::~Stub_ModuleStatus()
{
}

// --> Do NOT EDIT <--
void Stub_ModuleStatus::clear()
{
	this->name.reset( new std::string("") );
	this->moduleID = "";
	this->moduleStatus.reset( new std::string("") );
	this->configsRunning.reset( new std::vector<ConnectedVision::id_t> );
	this->configsWaiting.reset( new std::vector<ConnectedVision::id_t> );
	this->configID = "";
	this->timestamp = 0;
}

// --> Do NOT EDIT <--
void Stub_ModuleStatus::parseJson(const char *str)
{
	// ignore empty data
	if ( str[0] == 0 )
		return;

	// parse data
	rapidjson::Document document;
	if (document.Parse<0>(str).HasParseError())
	{
		std::string context;
		size_t off = document.GetErrorOffset();
		size_t i, line_start = 0, context_start = 0;
		int num_line = 1;
		for ( i = 0; (i < off) && str[i]; i++ )
		{
			if ( str[i] == '\n' )
			{ line_start = i+1; context_start = i+1; num_line++; }
			if ( str[i] == '{' || str[i] == '[' )
			{ context_start = i; }
		}
		for ( i = context_start; str[i]; i++ )
		{
			if ( str[i] == '\n' || str[i] == '\r' ) break;
			context += str[i];
			if ( str[i] == '}' || str[i] == ']' ) break;
		}
		throw ConnectedVision::runtime_error( std::string("parse error of JSON Object: ") + rapidjson::GetParseError_En(document.GetParseError()) + std::string(" at line ") + ConnectedVision::intToStr( num_line ) + ": " + context);
	}

	parseJson(document);
}

// --> Do NOT EDIT <--
void Stub_ModuleStatus::parseJson(const rapidjson::Value& value)
{
	clear();
	if ( !value.IsObject() )
		throw ConnectedVision::runtime_error( "no JSON Object");

	// name
	if ((value.HasMember("name")) && value["name"].IsString())
	{
		set_name( boost::shared_ptr<std::string>( new std::string( value["name"].GetString() ) ) );
	}
	else
		throw ConnectedVision::runtime_error( "required member is missing: 'name'");

	// moduleID
	if ((value.HasMember("moduleID")) && value["moduleID"].IsString())
	{
		set_moduleID( ConnectedVision::strToID( value["moduleID"].GetString() ) );
	}
	else
		throw ConnectedVision::runtime_error( "required member is missing: 'moduleID'");

	// moduleStatus
	if ((value.HasMember("moduleStatus")) && value["moduleStatus"].IsString())
	{
		set_moduleStatus( boost::shared_ptr<std::string>( new std::string( value["moduleStatus"].GetString() ) ) );
	}
	else
		throw ConnectedVision::runtime_error( "required member is missing: 'moduleStatus'");

	// configsRunning
	if ((value.HasMember("configsRunning")) && value["configsRunning"].IsArray())
	{
		const rapidjson::Value& n0 = value["configsRunning"];
		boost::shared_ptr<std::vector<ConnectedVision::id_t>> a0( new std::vector<ConnectedVision::id_t>(n0.Size()) );
		for (rapidjson::SizeType i0 = 0; i0 < n0.Size(); i0++)
		{
			a0->at(i0) = ConnectedVision::strToID( n0[i0].GetString() );
		}
		set_configsRunning( a0 );
	}
	else
		throw ConnectedVision::runtime_error( "required member is missing: 'configsRunning'");

	// configsWaiting
	if ((value.HasMember("configsWaiting")) && value["configsWaiting"].IsArray())
	{
		const rapidjson::Value& n0 = value["configsWaiting"];
		boost::shared_ptr<std::vector<ConnectedVision::id_t>> a0( new std::vector<ConnectedVision::id_t>(n0.Size()) );
		for (rapidjson::SizeType i0 = 0; i0 < n0.Size(); i0++)
		{
			a0->at(i0) = ConnectedVision::strToID( n0[i0].GetString() );
		}
		set_configsWaiting( a0 );
	}
}

// --> Do NOT EDIT <--
std::string Stub_ModuleStatus::toJsonStr() const
{
	rapidjson::StringBuffer s;
	rapidjson::Document doc; doc.SetObject();
	this->toJson(doc, doc.GetAllocator());
	rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(s);
	doc.Accept(writer);
	return std::string(s.GetString());
}

// --> Do NOT EDIT <--
std::string Stub_ModuleStatus::toJson() const
{
	rapidjson::StringBuffer s;
	rapidjson::Document doc; doc.SetObject();
	this->toJson(doc, doc.GetAllocator());
	rapidjson::Writer<rapidjson::StringBuffer> writer(s);
	doc.Accept(writer);
	return std::string(s.GetString());
}

// --> Do NOT EDIT <--
rapidjson::Value& Stub_ModuleStatus::toJson(rapidjson::Value& node, rapidjson::Value::AllocatorType& allocator) const
{
	{ // name
		node.AddMember("name", rapidjson::Value().SetString( get_name()->c_str(), allocator), allocator);
	}
	{ // moduleID
		node.AddMember("moduleID", rapidjson::Value().SetString( ConnectedVision::IDToChar( get_moduleID() ), allocator), allocator);
	}
	{ // moduleStatus
		node.AddMember("moduleStatus", rapidjson::Value().SetString( get_moduleStatus()->c_str(), allocator), allocator);
	}
	{ // configsRunning
		rapidjson::Value n0; n0.SetArray();
		boost::shared_ptr<std::vector<ConnectedVision::id_t>>&& a0 = get_configsRunning(); // rvalue reference for const functions
		for (size_t i0 = 0; i0 < a0->size(); i0++)
		{
			// process array level 0
			// final level of array, add ID
			n0.PushBack(rapidjson::Value().SetString( ConnectedVision::IDToChar( a0->at(i0) ), allocator), allocator);
		}
		node.AddMember("configsRunning", n0, allocator);
	}
	{ // configsWaiting
		rapidjson::Value n0; n0.SetArray();
		boost::shared_ptr<std::vector<ConnectedVision::id_t>>&& a0 = get_configsWaiting(); // rvalue reference for const functions
		for (size_t i0 = 0; i0 < a0->size(); i0++)
		{
			// process array level 0
			// final level of array, add ID
			n0.PushBack(rapidjson::Value().SetString( ConnectedVision::IDToChar( a0->at(i0) ), allocator), allocator);
		}
		node.AddMember("configsWaiting", n0, allocator);
	}
	return node;
}

// --> Do NOT EDIT <--
boost::shared_ptr<std::string> Stub_ModuleStatus::get_name() const
{
	return( this->name );
}

// --> Do NOT EDIT <--
const boost::shared_ptr<const std::string> Stub_ModuleStatus::getconst_name() const
{
	return( boost::static_pointer_cast<const std::string>(this->name) );
}

// --> Do NOT EDIT <--
void Stub_ModuleStatus::set_name(boost::shared_ptr<std::string> value)
{
	this->name = value;
}

// --> Do NOT EDIT <--
ConnectedVision::id_t Stub_ModuleStatus::get_moduleID() const
{
	return( this->moduleID );
}

// --> Do NOT EDIT <--
const ConnectedVision::id_t Stub_ModuleStatus::getconst_moduleID() const
{
	return( this->moduleID );
}

// --> Do NOT EDIT <--
void Stub_ModuleStatus::set_moduleID(ConnectedVision::id_t value)
{
	this->moduleID = value;
}

// --> Do NOT EDIT <--
boost::shared_ptr<std::string> Stub_ModuleStatus::get_moduleStatus() const
{
	return( this->moduleStatus );
}

// --> Do NOT EDIT <--
const boost::shared_ptr<const std::string> Stub_ModuleStatus::getconst_moduleStatus() const
{
	return( boost::static_pointer_cast<const std::string>(this->moduleStatus) );
}

// --> Do NOT EDIT <--
void Stub_ModuleStatus::set_moduleStatus(boost::shared_ptr<std::string> value)
{
	this->moduleStatus = value;
}

// --> Do NOT EDIT <--
bool Stub_ModuleStatus::is_moduleStatus(const boost::shared_ptr<std::string> &value) const
{
	return ( (*this->moduleStatus) == (*value) );
}

// --> Do NOT EDIT <--
boost::shared_ptr<std::vector<ConnectedVision::id_t>> Stub_ModuleStatus::get_configsRunning() const
{
	return( this->configsRunning );
}

// --> Do NOT EDIT <--
const boost::shared_ptr<const std::vector<ConnectedVision::id_t>> Stub_ModuleStatus::getconst_configsRunning() const
{
	return( boost::static_pointer_cast<const std::vector<ConnectedVision::id_t>>(this->configsRunning) );
}

// --> Do NOT EDIT <--
void Stub_ModuleStatus::set_configsRunning(boost::shared_ptr<std::vector<ConnectedVision::id_t>> value)
{
	this->configsRunning = value;
}

// --> Do NOT EDIT <--
ConnectedVision::id_t Stub_ModuleStatus::get_configsRunning(int index) const
{
	return( this->configsRunning->at(index) );
}

// --> Do NOT EDIT <--
const ConnectedVision::id_t& Stub_ModuleStatus::getconst_configsRunning(int index) const
{
	return( this->configsRunning->at(index) );
}

// --> Do NOT EDIT <--
void Stub_ModuleStatus::add_configsRunning(ConnectedVision::id_t value)
{
	this->configsRunning->push_back(value);
}

// --> Do NOT EDIT <--
boost::shared_ptr<std::vector<ConnectedVision::id_t>> Stub_ModuleStatus::get_configsWaiting() const
{
	return( this->configsWaiting );
}

// --> Do NOT EDIT <--
const boost::shared_ptr<const std::vector<ConnectedVision::id_t>> Stub_ModuleStatus::getconst_configsWaiting() const
{
	return( boost::static_pointer_cast<const std::vector<ConnectedVision::id_t>>(this->configsWaiting) );
}

// --> Do NOT EDIT <--
void Stub_ModuleStatus::set_configsWaiting(boost::shared_ptr<std::vector<ConnectedVision::id_t>> value)
{
	this->configsWaiting = value;
}

// --> Do NOT EDIT <--
ConnectedVision::id_t Stub_ModuleStatus::get_configsWaiting(int index) const
{
	return( this->configsWaiting->at(index) );
}

// --> Do NOT EDIT <--
const ConnectedVision::id_t& Stub_ModuleStatus::getconst_configsWaiting(int index) const
{
	return( this->configsWaiting->at(index) );
}

// --> Do NOT EDIT <--
void Stub_ModuleStatus::add_configsWaiting(ConnectedVision::id_t value)
{
	this->configsWaiting->push_back(value);
}

// --> Do NOT EDIT <--
ConnectedVision::id_t Stub_ModuleStatus::get_configID() const
{
	return( this->configID );
}

// --> Do NOT EDIT <--
const ConnectedVision::id_t Stub_ModuleStatus::getconst_configID() const
{
	return( this->configID );
}

// --> Do NOT EDIT <--
void Stub_ModuleStatus::set_configID(ConnectedVision::id_t value)
{
	this->configID = value;
}

// --> Do NOT EDIT <--
ConnectedVision::timestamp_t Stub_ModuleStatus::get_timestamp() const
{
	return( this->timestamp );
}

// --> Do NOT EDIT <--
const ConnectedVision::timestamp_t Stub_ModuleStatus::getconst_timestamp() const
{
	return( this->timestamp );
}

// --> Do NOT EDIT <--
void Stub_ModuleStatus::set_timestamp(ConnectedVision::timestamp_t value)
{
	this->timestamp = value;
}

} // namespace ConnectedVision

max_stars_repo_name: ConnectedVision/ConnectedVision

max_issues_repo_name: ConnectedVision/ConnectedVision

max_forks_repo_name: ConnectedVision/ConnectedVision


text:
// Warning! This file is autogenerated.
#ifndef BOOST_TEXT_DATA_UG_HPP
#define BOOST_TEXT_DATA_UG_HPP

#include <boost/text/string_view.hpp>

namespace boost { namespace text { namespace data { namespace ug {

inline string_view standard_collation_tailoring()
{
    return string_view(
u8R"(
[reorder Arab]
&ا<ە<ب
&ك<گ<ڭ<ل
&ھ<و<ۇ<ۆ<ۈ<ۋ<ې<ى<ي
  )");
}

}}}}

#endif

max_stars_repo_name: eightysquirrels/text

max_issues_repo_name: eightysquirrels/text

max_forks_repo_name: eightysquirrels/text


text:
#ifndef __GRAPH__
#define __GRAPH__

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/reverse_graph.hpp>
#include <boost/graph/graph_utility.hpp>
#include <boost/graph/graphviz.hpp>
#include <boost/filesystem/fstream.hpp>
#include "data_type.hpp"
#include "memory.hpp"

#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include <vector>
#include <queue>

//------------------
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/gzip.hpp>
//----------
//from bloom

using namespace std;
using namespace boost;

class Graph{

  private:
        BoostGraph orig_graph;
        BoostGraph in_graph;
        uint64_t graph_limit;
        bool g_en   = false;
        bool g_rdy  = false;
        uint64_t g_iter = 0;
        uint64_t g_mem_req_count =0;
        std::string g_input_filestring;
        uint64_t m_prev_completion_cycles=0;

        uint64_t g_total_termination_cycles=0;
        uint64_t g_total_bloom_yes_ld =0;
        uint64_t g_total_bloom_yes_st =0;
        uint64_t g_total_bloom_no_ld =0;
        uint64_t g_total_bloom_no_st =0;
        uint64_t g_total_bloom_fp =0;
        uint64_t g_total_bloom_stall_cycles =0;
        bool m_stall_on_bloom = false;

  public:

        Memory* m_memory;

        //variables
        uint64_t next_event_time_vertex=0;
        uint64_t next_event_time_edge=0;
        uint64_t global_clock=0;
        uint64_t mlp=0;
        std::fstream mlpfile;
        std::ifstream ldstfile;

        uint64_t g_total_memops=0;
        uint64_t g_total_ldops=0;
        uint64_t g_total_LiveOut =0;
        //-----------------------------------------------------

        //VEctor of arrays
        //Vertex queues
        std::vector< graph_traits<BoostGraph>::vertex_descriptor>  vertex_state_map [LEN_VSTATE];

        //Edge queues
        std::vector< graph_traits<BoostGraph>::edge_descriptor> edge_state_map [LEN_ESTATE];

        //functions

        //constructors
        Graph(uint64_t n, string ldstfile_path, string input_filestring,O3sim_ruby* _ruby,bool _is_stall_on_bloom/*, uint64_t start_clock*/, std::string _bloom_type);

        //destructor
        ~Graph();

        void set_state_maps();
        void readGraph();
        void initialize(uint64_t _iter );
        void printGraph();
        void printstats();
				unsigned int getOpcodeStr(string op_code);
        int traverse_graph();
        void update_states_VWAIT_queue();
        void update_states_VREADY_queue();
        void update_states_EWAIT_queue();
        void update_states_VCOMPLETE_queue();
        void print_states();
        void update_mlp_stats_1();
        void update_mlp_stats( uint64_t elatency);
        void read_memcsv(std::ifstream& file);
        void print_memmap();
        int run_a_cycle();
};

#endif


text:
//
// Created by jorge on 8/14/21.
//

#include "Configuration.h"
//
// Created by Jorge Imperial-Sosa on 1/26/21.
//
//
// Created by Jorge Imperial on 11/17/20.
//

#include <yaml-cpp/yaml.h>
#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/algorithm/string.hpp>
#include <fstream>
#include <Configuration.h>

int Configuration::read() {

    try {
        BOOST_LOG_TRIVIAL(info) << "Alias file in  " << this->path;
        root = YAML::LoadFile(this->path);
        YAML::Node aliases_node = root["aliases"];

        for(YAML::const_iterator it=aliases_node.begin();it != aliases_node.end();++it) {
            auto key = it->first.as<std::string>();  // <- key
            auto value = it->second.as<std::string>();    // <- value
            this->aliases.emplace(key,value);
            BOOST_LOG_TRIVIAL(info) << "Alias: " << value;
        }
        return 0;
    }

    catch (YAML::ParserException &pe) {
        BOOST_LOG_TRIVIAL(fatal) << "Configuration.read() " << this->path << " " << pe.msg;
        return 1;
    }

    catch(YAML::Exception &e ) {
        BOOST_LOG_TRIVIAL(fatal) << "Configuration.read() " << this->path << " " << e.msg;
        return 1;
    }
}

int Configuration::write() {

    YAML::Emitter out;
    out << YAML::BeginMap;
    out << YAML::Key << "aliases";
    out << YAML::BeginMap;

    for (auto &a : this->aliases) {
        out << YAML::Key << a.first;
        out << YAML::Value << a.second;
    }
    out << YAML::EndMap;
    out << YAML::EndMap;

    try {
        std::ofstream out_file_name;
        out_file_name.open(this->path, std::ios::out);
        out_file_name << out.c_str();
        out_file_name.close();
    }
    catch ( YAML::Exception &e) {
        BOOST_LOG_TRIVIAL(fatal) << e.msg;
        return 1;
    }
    return 0;
}

int Configuration::WriteDefaultConfiguration() {
    YAML::Emitter out;

    // Useful defaults
    std::map <std::string, std::string> alias_test = std::map <std::string, std::string>();
    alias_test.emplace("find_failed", "serverStatus.metrics.commands.find.ailed");
    alias_test.emplace("find_total",  "serverStatus.metrics.commands.find.total");
    alias_test.emplace("find_modify_failed", "serverStatus.metrics.commands.findAndModify.failed");
    alias_test.emplace("find_modify_total", "serverStatus.metrics.commands.findAndModify.total");
    alias_test.emplace("update_failed",  "serverStatus.metrics.commands.update.failed");
    alias_test.emplace("update_total", "serverStatus.metrics.commands.update.total");
    alias_test.emplace("delete_failed", "serverStatus.metrics.commands.delete.failed");
    alias_test.emplace("delete_total", "serverStatus.metrics.commands.delete.total");
    alias_test.emplace("insert_failed", "serverStatus.metrics.commands.insert.failed");
    alias_test.emplace("insert_total", "serverStatus.metrics.commands.insert.total");
    alias_test.emplace("ops_command", "serverStatus.opcounters.command");
    alias_test.emplace("ops_insert", "serverStatus.opcounters.insert");
    alias_test.emplace("ops_query", "serverStatus.opcounters.query");
    alias_test.emplace("ops_update", "serverStatus.opcounters.update");
    alias_test.emplace("ops_getmore", "serverStatus.opcounters.getmore");
    alias_test.emplace("ops_delete", "serverStatus.opcounters.delete");
    alias_test.emplace("rs_state_0", "replSetGetStatus.members.0.state");
    alias_test.emplace("rs_state_1", "replSetGetStatus.members.1.state");
    alias_test.emplace("rs_state_2", "replSetGetStatus.members.2.state");

    out << YAML::BeginMap;
    out << YAML::Key << "aliases";

    out << YAML::BeginMap;
    for (auto &a : alias_test) {
        out << YAML::Key << a.first;
        out << YAML::Value << a.second;
    }
    out << YAML::EndMap;
    out << YAML::EndMap;

    try {
        std::ofstream out_file_name;
        out_file_name.open(this->path, std::ios::out);
        out_file_name << out.c_str();
        out_file_name.close();
    }

    catch ( YAML::Exception &e) {
        BOOST_LOG_TRIVIAL(fatal) << "Configuration.WriteDefaultConfiguration() " << e.msg;
        return 1;
    }

    return 0;
}

std::vector<std::string>
Configuration::AliasesToPrefixes(const std::string &all_aliases) {

    // break comma separated
    std::vector<std::string> strs;
    boost::split(strs, all_aliases, boost::is_any_of(","));
    return strs;
}


text:
#include <boost/python.hpp>

#include "OpenPGP/RNG/BBS.h"

void BBS_init()
{
boost::python::class_<BBS>("BBS")
    .def(boost::python::init<const PGPMPI &, const unsigned int &, PGPMPI, PGPMPI>())
    .def("rand", &BBS::rand)
    ;
}

max_stars_repo_name: mugwort-rc/pyOpenPGP

max_issues_repo_name: mugwort-rc/pyOpenPGP

max_forks_repo_name: mugwort-rc/pyOpenPGP


text:
//============================================================================
// Name        : LBFGS_MPI.cpp
// Author      : Yaser
// Version     :
// Copyright   :
// Description : LBFGS MPI implementation
//============================================================================

/*
 ** consider quadratic function, f(x) = 0.5*\|Ax-b\|^2
 ** Implement LBFGS algorithm as is explained in
 ** https://en.wikipedia.org/wiki/Limited-memory_BFGS
 **
 */

#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <cstdlib>  /* rand, srand */
#include <vector>

#include <time.h>
#include <boost/mpi.hpp>
namespace mpi = boost::mpi;

#include <boost/timer/timer.hpp>

#include "solvers/OptimizationParameters.h"
#include "solvers/ProblemData.h"
#include "solvers/QuasiNewtonSolver.h"
#include "solvers/LBFGSSolver.h"

using namespace std;

int main(int argc, char* argv[]) {
	mpi::environment env(argc, argv);
	mpi::communicator world;
	srand(1);
	ProblemData problemData;
	OptimizationParameters optParams;
	optParams.m = 1000;
	optParams.n = 2000;
	optParams.num_iterations = 10000;//100 initially
	optParams.lbfgs_memory = 100; //10 initially
	optParams.stepsize = 10 / (0.0 + optParams.n);
	if (world.rank() == 0) { //Generate data on node 0
		int nnz = optParams.m * optParams.n;
		problemData.A.resize(nnz);
		for (int i = 0; i < optParams.n; i++) {
			double tmp = 0;
			for (int j = 0; j < optParams.m; j++) {
				double r = rand() / (RAND_MAX + 0.0);
				problemData.A[i * optParams.m + j] = r;
				tmp += r * r;
			}
			tmp = 1 / sqrt(tmp);
			for (int j = 0; j < optParams.m; j++) {
				problemData.A[i * optParams.m + j] = problemData.A[i * optParams.m + j] * tmp;
			}

		}
		problemData.b.resize(optParams.m);
		for (int i = 0; i < optParams.m; i++) {
			problemData.b[i] = rand() / (RAND_MAX + 0.0);
		}
		problemData.x.resize(optParams.n, 0);
	}

/*
	if (world.rank() == 0) {
		cout<<"Amatrix: "<<endl;
		for (int i = 0; i < optParams.n; i++) {
			for (int j = 0; j < optParams.m; j++) {
				cout<< std::setprecision(17)<<problemData.A[i*optParams.m+j]<<"     ";
			}
			cout<<endl;
		}

		cout<<"endA"<<endl;
		cout<<"bvec"<<endl;

		for (int i = 0; i < optParams.m; i++) {
			cout<< std::setprecision(17)<<problemData.b[i]<<"     ";
		}
		cout<<"bvecEnd"<<endl;
	}
*/

	boost::timer::cpu_timer timer;
	LBFGSSolver solver(problemData, optParams);
	boost::timer::cpu_times elapsedInInitialization = timer.elapsed();
	if (world.rank() == 0) { // Writes total running time
		std::cout << "Initialization of class took: " << (elapsedInInitialization.user + elapsedInInitialization.system) / 1e9 << " (sec)" << "  Wallclock time: "
				<< elapsedInInitialization.wall / 1e9 << " (sec)" << std::endl;
	}

	/* this function computes and takes the step to obtain a new iterate */
	double objVal = solver.computeCurrentObjectiveValue();
	if (world.rank() == 0) {
		cout << "Initial Obj Value is " << objVal << endl;
	}

	for (int it = 0; it < optParams.num_iterations; it++) {

		timer.start();
		solver.computeAndTakeStep(); // this function computes and takes the step to obtain a new iterate
		boost::timer::cpu_times computingStep = timer.elapsed();

		timer.start();
		objVal = solver.computeCurrentObjectiveValue(); // this function computes and takes the step to obtain a new iterate
		boost::timer::cpu_times objValTime = timer.elapsed();

		if (world.rank() == 0) { // Writes total running time
			std::cout << "Iteration: " << it << " ObjVal: " << objVal << " Times: " << (computingStep.user + computingStep.system) / 1e9 << " (sec)"
					<< "  Wall clock time: " << computingStep.wall / 1e9 << " (sec)" << " " << (objValTime.user + objValTime.system) / 1e9 << " (sec)"
					<< "  Wall clock time: " << objValTime.wall / 1e9 << " (sec)" << std::endl;
		}

	}

	return 0;
}


text:
#include "block_convolver_test_utils.hpp"
#include <Eigen/Core>
#include <cassert>
#include <cmath>
#include <fstream>
#include <random>

/// Generate random impulses.
/// @param len length of returned buffer
/// @param num_nonzero The number of values to randomise
/// @param seedval Seed for rng.
Eigen::VectorXf generate_random(size_t len, size_t num_nonzero,
                                long int seedval) {
  Eigen::VectorXf data = Eigen::VectorXf::Zero(len);

  std::mt19937 gen(seedval);
  for (size_t i = 0; i < num_nonzero; i++) {
    data[std::uniform_int_distribution<int>(0, (int)len - 1)(gen)] =
        std::uniform_real_distribution<float>()(gen);
  }

  return data;
}

/// Simple convolution implementation.
/// @param len output and input lengths
/// @param out[out] output data
/// @param out[in] input data
/// @param ir_len length of impulse response
/// @param ir impulse response data
void convolve(size_t len, float *out, float *in, size_t ir_len, float *ir) {
  for (size_t i = 0; i < len; i++) {
    float total = 0.0;
    for (size_t j = 0; j < ir_len; j++) {
      if (j > i) break;
      total += in[i - j] * ir[j];
    }
    out[i] = total;
  }
}

/// Fade up linearly over a block.
void fade_up(float *out, float *in, size_t n) {
  float i_scale = 1.0f / n;

  for (size_t i = 0; i < n; i++) {
    float a_v = (float)i * i_scale;
    out[i] = a_v * in[i];
  }
}

/// Fade down linearly over a block.
void fade_down(float *out, float *in, size_t n) {
  float i_scale = 1.0f / n;

  for (size_t i = 0; i < n; i++) {
    float a_v = (float)i * i_scale;
    out[i] = (1 - a_v) * in[i];
  }
}

/// Write a float array to a file, readable by numpy.loadtext
void write_array(const std::string &base, const std::string &name, size_t n,
                 float *x) {
  if (base != "") {
    std::ofstream out(base + name);
    assert(out.is_open());
    for (size_t i = 0; i < n; i++) out << x[i] << std::endl;
  }
}

max_stars_repo_name: rsjtaylor/libear

max_issues_repo_name: rsjtaylor/libear

max_forks_repo_name: rsjtaylor/libear


text: #include <boost/mpl/aux_/preprocessed/gcc/list_c.hpp>


text:
#pragma once

#include <istream>
#include <type_traits>

#include <boost/endian/conversion.hpp>

#include "types.hpp"
#include "osrfile.hpp"

namespace orde {

	template <typename Type>
	inline void unserialize(std::istream& stream, Type& data)
	{
		static_assert(std::is_arithmetic<Type>::value, "data must be an arithmetical type");
		stream.read(reinterpret_cast<char*>(&data), sizeof(data));
		data = boost::endian::little_to_native(data);
	}

	template <>
	void unserialize<std::string>(std::istream& stream, std::string& str);

	void unserialize(std::istream& stream, Actions& actions, Integer size);

	template <>
	void unserialize<Graph>(std::istream& stream, Graph& graph);

}

max_stars_repo_name: zeFresk/osu-replay---Data-Extractor

max_issues_repo_name: zeFresk/osu-anticheat

max_forks_repo_name: zeFresk/osu-anticheat


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)

#include <stdio.h>
#include <stdlib.h>

#include <cmath>
#include <cstdint>
#include <cstdio>
#include <iostream>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <string>
#include <thread>
#include <utility>
#include <vector>

#include <boost/array.hpp>
#include <boost/assert.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/utility.hpp>
#include <boost/variant.hpp>

#include <boost/context/continuation.hpp>
#include <boost/context/detail/config.hpp>

#ifdef BOOST_WINDOWS
#include <windows.h>
#endif

#if defined(BOOST_MSVC)
# pragma warning(push)
# pragma warning(disable: 4702 4723 4996)
#endif

typedef boost::variant<int,std::string> variant_t;

namespace ctx = boost::context;

int value1 = 0;
std::string value2;
double value3 = 0.;

struct X {
    ctx::continuation foo( ctx::continuation && c, int i) {
        value1 = i;
        return std::move( c);
    }
};

struct Y {
    Y() {
        value1 = 3;
    }

    Y( Y const&) = delete;
    Y & operator=( Y const&) = delete;

    ~Y() {
        value1 = 7;
    }
};

class moveable {
public:
    bool    state;
    int     value;

    moveable() :
        state( false),
        value( -1) {
    }

    moveable( int v) :
        state( true),
        value( v) {
    }

    moveable( moveable && other) :
        state( other.state),
        value( other.value) {
        other.state = false;
        other.value = -1;
    }

    moveable & operator=( moveable && other) {
        if ( this == & other) return * this;
        state = other.state;
        value = other.value;
        other.state = false;
        other.value = -1;
        return * this;
    }

    moveable( moveable const& other) = delete;
    moveable & operator=( moveable const& other) = delete;

    void operator()() {
        value1 = value;
    }
};

struct my_exception : public std::runtime_error {
    ctx::continuation   c;
    my_exception( ctx::continuation && c_, char const* what) :
        std::runtime_error( what),
        c{ std::move( c_) } {
    }
};

#ifdef BOOST_MSVC
// Optimizations can remove the integer-divide-by-zero here.
#pragma optimize("", off)
void seh( bool & catched) {
    __try {
        int i = 1;
        i /= 0;
    } __except( EXCEPTION_EXECUTE_HANDLER) {
        catched = true;
    }
}
#pragma optimize("", on)
#endif

void test_move() {
    value1 = 0;
    int i = 1;
    BOOST_CHECK_EQUAL( 0, value1);
    ctx::continuation c1 = ctx::callcc(
        [&i](ctx::continuation && c) {
            value1 = i;
            c = c.resume();
            value1 = i;
            return std::move( c);
        });
    BOOST_CHECK_EQUAL( 1, value1);
    BOOST_CHECK( c1);
    ctx::continuation c2;
    BOOST_CHECK( ! c2);
    c2 = std::move( c1);
    BOOST_CHECK( ! c1);
    BOOST_CHECK( c2);
    i = 3;
    c2.resume();
    BOOST_CHECK_EQUAL( 3, value1);
    BOOST_CHECK( ! c1);
    BOOST_CHECK( ! c2);
}

void test_bind() {
    value1 = 0;
    X x;
    ctx::continuation c = ctx::callcc( std::bind( & X::foo, x, std::placeholders::_1, 7) );
    BOOST_CHECK_EQUAL( 7, value1);
}

void test_exception() {
    {
        const char * what = "hello world";
        ctx::continuation c = ctx::callcc(
            [&what](ctx::continuation && c) {
                try {
                    throw std::runtime_error( what);
                } catch ( std::runtime_error const& e) {
                    value2 = e.what();
                }
                return std::move( c);
            });
        BOOST_CHECK_EQUAL( std::string( what), value2);
        BOOST_CHECK( ! c);
    }
#ifdef BOOST_MSVC
    {
        bool catched = false;
        std::thread([&catched](){
                ctx::continuation c = ctx::callcc([&catched](ctx::continuation && c){
                            c = c.resume();
                            seh( catched);
                            return std::move( c);
                        });
            BOOST_CHECK( c );
            c.resume();
        }).join();
        BOOST_CHECK( catched);
    }
#endif
}

void test_fp() {
    value3 = 0.;
    double d = 7.13;
    ctx::continuation c = ctx::callcc(
        [&d]( ctx::continuation && c) {
            d += 3.45;
            value3 = d;
            return std::move( c);
        });
    BOOST_CHECK_EQUAL( 10.58, value3);
    BOOST_CHECK( ! c);
}

void test_stacked() {
    value1 = 0;
    value3 = 0.;
    ctx::continuation c = ctx::callcc(
        [](ctx::continuation && c) {
            ctx::continuation c1 = ctx::callcc(
                [](ctx::continuation && c) {
                    value1 = 3;
                    return std::move( c);
                });
            value3 = 3.14;
            return std::move( c);
        });
    BOOST_CHECK_EQUAL( 3, value1);
    BOOST_CHECK_EQUAL( 3.14, value3);
    BOOST_CHECK( ! c );
}

void test_prealloc() {
    value1 = 0;
    ctx::default_stack alloc;
    ctx::stack_context sctx( alloc.allocate() );
    void * sp = static_cast< char * >( sctx.sp) - 10;
    std::size_t size = sctx.size - 10;
    int i = 7;
    ctx::continuation c = ctx::callcc(
        std::allocator_arg, ctx::preallocated( sp, size, sctx), alloc,
        [&i]( ctx::continuation && c) {
            value1 = i;
            return std::move( c);
        });
    BOOST_CHECK_EQUAL( 7, value1);
    BOOST_CHECK( ! c);
}

void test_ontop() {
    {
        int i = 3;
        ctx::continuation c = ctx::callcc([&i](ctx::continuation && c) {
                    for (;;) {
                        i *= 10;
                        c = c.resume();
                    }
                    return std::move( c);
                });
        c = c.resume_with(
               [&i](ctx::continuation && c){
                   i -= 10;
                   return std::move( c);
               });
        BOOST_CHECK( c);
        BOOST_CHECK_EQUAL( i, 200);
    }
    {
        ctx::continuation c1;
        ctx::continuation c = ctx::callcc([&c1](ctx::continuation && c) {
                    c = c.resume();
                    BOOST_CHECK( ! c);
                    return std::move( c1);
                });
        c = c.resume_with(
               [&c1](ctx::continuation && c){
                   c1 = std::move( c);
                   return std::move( c);
               });
    }
}

void test_ontop_exception() {
    value1 = 0;
    value2 = "";
    ctx::continuation c = ctx::callcc([](ctx::continuation && c){
            for (;;) {
                value1 = 3;
                try {
                    c = c.resume();
                } catch ( my_exception & ex) {
                    value2 = ex.what();
                    return std::move( ex.c);
                }
            }
            return std::move( c);
    });
    c = c.resume();
    BOOST_CHECK_EQUAL( 3, value1);
    const char * what = "hello world";
    c.resume_with(
       [what](ctx::continuation && c){
            throw my_exception( std::move( c), what);
            return std::move( c);
       });
    BOOST_CHECK_EQUAL( 3, value1);
    BOOST_CHECK_EQUAL( std::string( what), value2);
}

void test_termination1() {
    {
        value1 = 0;
        ctx::continuation c = ctx::callcc(
            [](ctx::continuation && c){
                Y y;
                return c.resume();
            });
        BOOST_CHECK_EQUAL( 3, value1);
    }
    BOOST_CHECK_EQUAL( 7, value1);
    {
        value1 = 0;
        BOOST_CHECK_EQUAL( 0, value1);
        ctx::continuation c = ctx::callcc(
            [](ctx::continuation && c) {
                value1 = 3;
                return std::move( c);
            });
        BOOST_CHECK_EQUAL( 3, value1);
        BOOST_CHECK( ! c );
    }
    {
        value1 = 0;
        BOOST_CHECK_EQUAL( 0, value1);
        int i = 3;
        ctx::continuation c = ctx::callcc(
            [&i](ctx::continuation && c){
                value1 = i;
                c = c.resume();
                value1 = i;
                return std::move( c);
            });
        BOOST_CHECK( c);
        BOOST_CHECK_EQUAL( i, value1);
        BOOST_CHECK( c);
        i = 7;
        c = c.resume();
        BOOST_CHECK( ! c);
        BOOST_CHECK_EQUAL( i, value1);
    }
}

void test_termination2() {
    {
        value1 = 0;
        value3 = 0.0;
        ctx::continuation c = ctx::callcc(
            [](ctx::continuation && c){
                Y y;
                value1 = 3;
                value3 = 4.;
                c = c.resume();
                value1 = 7;
                value3 = 8.;
                c = c.resume();
                return std::move( c);
            });
        BOOST_CHECK_EQUAL( 3, value1);
        BOOST_CHECK_EQUAL( 4., value3);
        c = c.resume();
    }
    BOOST_CHECK_EQUAL( 7, value1);
    BOOST_CHECK_EQUAL( 8., value3);
}

void test_sscanf() {
    ctx::continuation c = ctx::callcc(
		[]( ctx::continuation && c) {
			{
				double n1 = 0;
				double n2 = 0;
				sscanf("3.14 7.13", "%lf %lf", & n1, & n2);
				BOOST_CHECK( n1 == 3.14);
				BOOST_CHECK( n2 == 7.13);
			}
			{
				int n1=0;
				int n2=0;
				sscanf("1 23", "%d %d", & n1, & n2);
				BOOST_CHECK( n1 == 1);
				BOOST_CHECK( n2 == 23);
			}
			{
				int n1=0;
				int n2=0;
				sscanf("1 jjj 23", "%d %*[j] %d", & n1, & n2);
				BOOST_CHECK( n1 == 1);
				BOOST_CHECK( n2 == 23);
			}
			return std::move( c);
	});
}

void test_snprintf() {
    ctx::continuation c = ctx::callcc(
		[]( ctx::continuation && c) {
            {
                const char *fmt = "sqrt(2) = %f";
                char buf[19];
                snprintf( buf, sizeof( buf), fmt, std::sqrt( 2) );
                BOOST_CHECK( 0 < sizeof( buf) );
                BOOST_ASSERT( std::string("sqrt(2) = 1.41") == std::string( buf, 14) );
            }
            {
                std::uint64_t n = 0xbcdef1234567890;
                const char *fmt = "0x%016llX";
                char buf[100];
                snprintf( buf, sizeof( buf), fmt, n);
                BOOST_ASSERT( std::string("0x0BCDEF1234567890") == std::string( buf, 18) );
            }
			return std::move( c);
	});
}

#ifdef BOOST_WINDOWS
void test_bug12215() {
        ctx::continuation c = ctx::callcc(
            [](ctx::continuation && c) {
                char buffer[MAX_PATH];
                GetModuleFileName( nullptr, buffer, MAX_PATH);
                return std::move( c);
            });
}
#endif

void test_goodcatch() {
    value1 = 0;
    value3 = 0.0;
    {
        ctx::continuation c = ctx::callcc(
            [](ctx::continuation && c) {
                Y y;
                value3 = 2.;
                c = c.resume();
                try {
                    value3 = 3.;
                    c = c.resume();
                } catch ( boost::context::detail::forced_unwind const&) {
                    value3 = 4.;
                    throw;
                } catch (...) {
                    value3 = 5.;
                }
                value3 = 6.;
                return std::move( c);
            });
        BOOST_CHECK_EQUAL( 3, value1);
        BOOST_CHECK_EQUAL( 2., value3);
        c = c.resume();
        BOOST_CHECK_EQUAL( 3, value1);
        BOOST_CHECK_EQUAL( 3., value3);
    }
    BOOST_CHECK_EQUAL( 7, value1);
    BOOST_CHECK_EQUAL( 4., value3);
}

void test_badcatch() {
#if 0
    value1 = 0;
    value3 = 0.;
    {
        ctx::continuation c = ctx::callcc(
            [](ctx::continuation && c) {
                Y y;
                try {
                    value3 = 3.;
                    c = c.resume();
                } catch (...) {
                    value3 = 5.;
                }
                return std::move( c);
            });
        BOOST_CHECK_EQUAL( 3, value1);
        BOOST_CHECK_EQUAL( 3., value3);
        // the destruction of ctx here will cause a forced_unwind to be thrown that is not caught
        // in fn19.  That will trigger the "not caught" assertion in ~forced_unwind.  Getting that
        // assertion to propogate bak here cleanly is non-trivial, and there seems to not be a good
        // way to hook directly into the assertion when it happens on an alternate stack.
        std::move( c);
    }
    BOOST_CHECK_EQUAL( 7, value1);
    BOOST_CHECK_EQUAL( 4., value3);
#endif
}

boost::unit_test::test_suite * init_unit_test_suite( int, char* [])
{
    boost::unit_test::test_suite * test =
        BOOST_TEST_SUITE("Boost.Context: callcc test suite");

    test->add( BOOST_TEST_CASE( & test_move) );
    test->add( BOOST_TEST_CASE( & test_bind) );
    test->add( BOOST_TEST_CASE( & test_exception) );
    test->add( BOOST_TEST_CASE( & test_fp) );
    test->add( BOOST_TEST_CASE( & test_stacked) );
    test->add( BOOST_TEST_CASE( & test_prealloc) );
    test->add( BOOST_TEST_CASE( & test_ontop) );
    test->add( BOOST_TEST_CASE( & test_ontop_exception) );
    test->add( BOOST_TEST_CASE( & test_termination1) );
    test->add( BOOST_TEST_CASE( & test_termination2) );
    test->add( BOOST_TEST_CASE( & test_sscanf) );
    test->add( BOOST_TEST_CASE( & test_snprintf) );
#ifdef BOOST_WINDOWS
    test->add( BOOST_TEST_CASE( & test_bug12215) );
#endif
    test->add( BOOST_TEST_CASE( & test_goodcatch) );
    test->add( BOOST_TEST_CASE( & test_badcatch) );

    return test;
}

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

max_stars_repo_name: Jackarain/tinyrpc

max_issues_repo_name: avplayer/cxxrpc

max_forks_repo_name: avplayer/cxxrpc


text:
#include "k_points_util.h"

#include <algorithm>
#include <boost/functional/hash.hpp>
#include <cmath>
#include <exception>
#include <unordered_set>
#include "../array_math.h"

int KPointsUtil::get_n_k_points(const double rcut) {
  int count = 0;
  const int n_max = std::floor(static_cast<float>(rcut));
  double rcut_square = rcut * rcut;
  for (int i = -n_max; i <= n_max; i++) {
    for (int j = -n_max; j <= n_max; j++) {
      for (int k = -n_max; k <= n_max; k++) {
        if (i * i + j * j + k * k > rcut_square) continue;
        count++;
      }
    }
  }
  return count;
}

std::vector<std::array<int8_t, 3>> KPointsUtil::generate_k_points(
    const double rcut) {
  std::vector<std::array<int8_t, 3>> k_points;
  const int n_max = std::floor(static_cast<float>(rcut));
  assert(n_max < 127);
  double rcut_square = rcut * rcut;
  for (int i = -n_max; i <= n_max; i++) {
    for (int j = -n_max; j <= n_max; j++) {
      for (int k = -n_max; k <= n_max; k++) {
        if (i * i + j * j + k * k > rcut_square) continue;
        k_points.push_back(std::array<int8_t, 3>({static_cast<int8_t>(i),
                                                  static_cast<int8_t>(j),
                                                  static_cast<int8_t>(k)}));
      }
    }
  }
  std::stable_sort(
      k_points.begin(),
      k_points.end(),
      [](const auto& a, const auto& b) -> bool {
        return squared_norm(a) < squared_norm(b);
      });
  return k_points;
}

std::vector<std::array<int8_t, 3>> KPointsUtil::get_k_diffs(
    const std::vector<std::array<int8_t, 3>>& k_points) {
  // Generate all possible differences between two different k points.
  std::unordered_set<std::array<int8_t, 3>, boost::hash<std::array<int8_t, 3>>>
      k_diffs_set;
  std::vector<std::array<int8_t, 3>> k_diffs;
  const int n_k_points = k_points.size();
  for (int p = 0; p < n_k_points; p++) {
    for (int q = 0; q < n_k_points; q++) {
      if (p == q) continue;
      const auto& diff_pq = k_points[q] - k_points[p];
      if (k_diffs_set.count(diff_pq) == 1) continue;
      k_diffs.push_back(diff_pq);
      k_diffs_set.insert(diff_pq);
    }
  }

  // Sort k_diffs into ascending order so that later sorting hci queue will be
  // faster.
  std::stable_sort(
      k_diffs.begin(), k_diffs.end(), [](const auto& a, const auto& b) -> bool {
        return squared_norm(a) < squared_norm(b);
      });

  return k_diffs;
}

ext: cc


text:
/*
@copyright Louis Dionne 2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
 */

#ifndef BOOST_HANA_TEST_LAWS_ITERABLE_HPP
#define BOOST_HANA_TEST_LAWS_ITERABLE_HPP

#include <boost/hana/assert.hpp>
#include <boost/hana/bool.hpp>
#include <boost/hana/comparable.hpp>
#include <boost/hana/core/models.hpp>
#include <boost/hana/core/operators.hpp>
#include <boost/hana/core/when.hpp>
#include <boost/hana/foldable.hpp>
#include <boost/hana/range.hpp>

#include <laws/base.hpp>

namespace boost { namespace hana { namespace test {
    template <typename It, typename = when<true>>
    struct TestIterable : TestIterable<It, laws> {
        using TestIterable<It, laws>::TestIterable;
    };

    template <typename It>
    struct TestIterable<It, laws> {
        static_assert(_models<Iterable, It>{}, "");

        template <typename Xs>
        TestIterable(Xs xs) {
            hana::for_each(xs, [](auto xs) {

                BOOST_HANA_CONSTANT_CHECK(
                    hana::is_empty(xs) ^iff^ hana::is_empty(hana::to<Tuple>(xs))
                );

                only_when_(hana::not_(hana::is_empty(xs)), [=](auto _) {
                    auto xs_ = _(xs);

                    BOOST_HANA_CHECK(hana::equal(
                        hana::head(xs_),
                        hana::head(hana::to<Tuple>(xs_))
                    ));

                    BOOST_HANA_CHECK(hana::equal(
                        hana::to<Tuple>(hana::tail(xs_)),
                        hana::tail(hana::to<Tuple>(xs_))
                    ));

                    // methods
                    // drop(1, xs) == tail(xs) unless xs is empty
                    BOOST_HANA_CHECK(hana::equal(
                        hana::drop(size_t<1>, xs_),
                        hana::tail(xs_)
                    ));

                    // last(xs) == at(length(xs)-1, xs)
                    BOOST_HANA_CHECK(hana::equal(
                        hana::last(xs_),
                        hana::at(hana::pred(hana::length(xs_)), xs_)
                    ));

                });

                // drop(0, xs) == xs
                BOOST_HANA_CHECK(hana::equal(
                    hana::drop(size_t<0>, xs),
                    xs
                ));

                // at(n, xs) == head(drop(n, xs))
                hana::for_each(hana::make_range(size_t<0>, hana::length(xs)), [=](auto n) {
                    BOOST_HANA_CHECK(hana::equal(
                        hana::at(n, xs),
                        hana::head(hana::drop(n, xs))
                    ));
                });

                // operators
                only_when_(bool_<has_operator<It, decltype(at)>{}>, [=](auto _) {
                    hana::for_each(hana::make_range(size_t<0>, hana::length(xs)), [=](auto n) {
                        BOOST_HANA_CHECK(hana::equal(
                            hana::at(n, _(xs)),
                            _(xs)[n]
                        ));
                    });
                });

                // Foldable
                // when length == 0
                test::_injection<0> f{};
                test::_constant<0> state{};

                only_when_(hana::equal(hana::length(xs), size_t<0>), [=](auto _) {
                    auto xs_ = _(xs);
                    BOOST_HANA_CONSTANT_CHECK(hana::equal(
                        hana::foldl(xs_, state, f),
                        state
                    ));

                    BOOST_HANA_CONSTANT_CHECK(hana::equal(
                        hana::foldr(xs_, state, f),
                        state
                    ));
                });

                // when length == 1
                only_when_(hana::equal(hana::length(xs), size_t<1>), [=](auto _) {
                    auto xs_ = _(xs);

                    BOOST_HANA_CHECK(hana::equal(
                        hana::foldl(xs_, state, f),
                        f(state, at_c<0>(xs_))
                    ));

                    BOOST_HANA_CHECK(hana::equal(
                        hana::foldr(xs_, state, f),
                        f(at_c<0>(xs_), state)
                    ));

                    BOOST_HANA_CHECK(hana::equal(
                        hana::foldl1(xs_, f),
                        at_c<0>(xs_)
                    ));

                    BOOST_HANA_CHECK(hana::equal(
                        hana::foldr1(xs_, f),
                        at_c<0>(xs_)
                    ));
                });

                // when length == 2
                only_when_(hana::equal(hana::length(xs), size_t<2>), [=](auto _) {
                    auto xs_ = _(xs);

                    BOOST_HANA_CHECK(hana::equal(
                        hana::foldl(xs_, state, f),
                        f(f(state, at_c<0>(xs_)), at_c<1>(xs_))
                    ));

                    BOOST_HANA_CHECK(hana::equal(
                        hana::foldr(xs_, state, f),
                        f(at_c<0>(xs_), f(at_c<1>(xs_), state))
                    ));

                    BOOST_HANA_CHECK(hana::equal(
                        hana::foldl1(xs_, f),
                        f(at_c<0>(xs_), at_c<1>(xs_))
                    ));

                    BOOST_HANA_CHECK(hana::equal(
                        hana::foldr1(xs_, f),
                        f(at_c<0>(xs_), at_c<1>(xs_))
                    ));
                });

                // when length == 3
                only_when_(hana::equal(hana::length(xs), size_t<3>), [=](auto _) {
                    auto xs_ = _(xs);

                    BOOST_HANA_CHECK(hana::equal(
                        hana::foldl(xs_, state, f),
                        f(f(f(state, at_c<0>(xs_)), at_c<1>(xs_)), at_c<2>(xs_))
                    ));

                    BOOST_HANA_CHECK(hana::equal(
                        hana::foldr(xs_, state, f),
                        f(at_c<0>(xs_), f(at_c<1>(xs_), f(at_c<2>(xs_), state)))
                    ));

                    BOOST_HANA_CHECK(hana::equal(
                        hana::foldl1(xs_, f),
                        f(f(at_c<0>(xs_), at_c<1>(xs_)), at_c<2>(xs_))
                    ));

                    BOOST_HANA_CHECK(hana::equal(
                        hana::foldr1(xs_, f),
                        f(at_c<0>(xs_), f(at_c<1>(xs_), at_c<2>(xs_)))
                    ));
                });

                // when length == 4
                only_when_(hana::equal(hana::length(xs), size_t<4>), [=](auto _) {
                    auto xs_ = _(xs);

                    BOOST_HANA_CHECK(hana::equal(
                        hana::foldl(xs_, state, f),
                        f(f(f(f(state, at_c<0>(xs_)), at_c<1>(xs_)), at_c<2>(xs_)), at_c<3>(xs_))
                    ));

                    BOOST_HANA_CHECK(hana::equal(
                        hana::foldr(xs_, state, f),
                        f(at_c<0>(xs_), f(at_c<1>(xs_), f(at_c<2>(xs_), f(at_c<3>(xs_), state))))
                    ));

                    BOOST_HANA_CHECK(hana::equal(
                        hana::foldl1(xs_, f),
                        f(f(f(at_c<0>(xs_), at_c<1>(xs_)), at_c<2>(xs_)), at_c<3>(xs_))
                    ));

                    BOOST_HANA_CHECK(hana::equal(
                        hana::foldr1(xs_, f),
                        f(at_c<0>(xs_), f(at_c<1>(xs_), f(at_c<2>(xs_), at_c<3>(xs_))))
                    ));
                });

                // Searchable
                hana::eval_if(hana::is_empty(xs),
                    [=](auto _) {
                        auto xs_ = _(xs);

                        BOOST_HANA_CONSTANT_CHECK(
                            hana::not_(hana::any_of(xs_, hana::always(true_)))
                        );

                        BOOST_HANA_CONSTANT_CHECK(hana::equal(
                            hana::find_if(xs_, hana::always(true_)),
                            nothing
                        ));
                    },
                    [=](auto _) {
                        auto xs_ = _(xs);

                        BOOST_HANA_CHECK(
                            hana::any_of(xs_, hana::always(true_))
                        );
                        BOOST_HANA_CHECK(
                            hana::not_(hana::any_of(xs_, hana::always(false_)))
                        );

                        BOOST_HANA_CHECK(hana::equal(
                            hana::find_if(xs_, hana::always(true_)),
                            hana::just(hana::head(xs_))
                        ));
                    }
                );

            });
        }
    };

    template <typename S>
    struct TestIterable<S, when<_models<Sequence, S>{}>> : TestIterable<S, laws> {
        template <int i>
        using x = _constant<i>;

        template <int i = 0>
        struct invalid { };

        template <typename Xs>
        TestIterable(Xs xs) : TestIterable<S, laws>{xs} {
            constexpr auto list = make<S>;

            //////////////////////////////////////////////////////////////////
            // head
            //////////////////////////////////////////////////////////////////
            BOOST_HANA_CONSTANT_CHECK(equal(
                head(list(x<0>{})),
                x<0>{}
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                head(list(x<0>{}, invalid<>{})),
                x<0>{}
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                head(list(x<0>{}, invalid<1>{}, invalid<2>{})),
                x<0>{}
            ));

            BOOST_HANA_CONSTEXPR_CHECK(equal(
                head(list(1)), 1
            ));
            BOOST_HANA_CONSTEXPR_CHECK(equal(
                head(list(1, '2')), 1
            ));
            BOOST_HANA_CONSTEXPR_CHECK(equal(
                head(list(1, '2', 3.3)), 1
            ));

            //////////////////////////////////////////////////////////////////
            // is_empty
            //////////////////////////////////////////////////////////////////
            BOOST_HANA_CONSTANT_CHECK(is_empty(list()));
            BOOST_HANA_CONSTANT_CHECK(not_(is_empty(list(invalid<>{}))));
            BOOST_HANA_CONSTANT_CHECK(not_(is_empty(list(invalid<0>{}, invalid<1>{}))));

            int i = 0; // non-constexpr
            BOOST_HANA_CONSTANT_CHECK(not_(is_empty(list(i))));
            BOOST_HANA_CONSTANT_CHECK(not_(is_empty(list(i, i))));

            //////////////////////////////////////////////////////////////////
            // tail
            //////////////////////////////////////////////////////////////////
            BOOST_HANA_CONSTANT_CHECK(equal(
                tail(list(invalid<>{}, x<0>{})), list(x<0>{})
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                tail(list(invalid<>{}, x<0>{}, x<1>{})), list(x<0>{}, x<1>{})
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                tail(list(invalid<>{}, x<0>{}, x<1>{}, x<2>{})), list(x<0>{}, x<1>{}, x<2>{})
            ));

            BOOST_HANA_CONSTANT_CHECK(equal(
                tail(list(1)), list()
            ));
            BOOST_HANA_CONSTEXPR_CHECK(equal(
                tail(list(1, '2')), list('2')
            ));
            BOOST_HANA_CONSTEXPR_CHECK(equal(
                tail(list(1, '2', 3.3)), list('2', 3.3)
            ));

            //////////////////////////////////////////////////////////////////
            // at
            //////////////////////////////////////////////////////////////////
            BOOST_HANA_CONSTANT_CHECK(equal(
                at(size_t<0>, list(x<0>{})), x<0>{}
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                at(size_t<0>, list(x<0>{}, invalid<>{})), x<0>{}
            ));

            BOOST_HANA_CONSTANT_CHECK(equal(
                at(size_t<1>, list(invalid<>{}, x<1>{})), x<1>{}
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                at(size_t<1>, list(invalid<0>{}, x<1>{}, invalid<2>{})), x<1>{}
            ));

            BOOST_HANA_CONSTANT_CHECK(equal(
                at(size_t<2>, list(invalid<0>{}, invalid<1>{}, x<2>{})), x<2>{}
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                at(size_t<2>, list(invalid<0>{}, invalid<1>{}, x<2>{}, invalid<3>{})), x<2>{}
            ));

            BOOST_HANA_CONSTEXPR_CHECK(equal(
                at(size_t<0>, list(1)), 1
            ));
            BOOST_HANA_CONSTEXPR_CHECK(equal(
                at(size_t<0>, list(1, '2')), 1
            ));
            BOOST_HANA_CONSTEXPR_CHECK(equal(
                at(size_t<0>, list(1, '2', 3.3)), 1
            ));

            BOOST_HANA_CONSTEXPR_CHECK(equal(
                at(size_t<1>, list(1, '2')), '2'
            ));
            BOOST_HANA_CONSTEXPR_CHECK(equal(
                at(size_t<1>, list(1, '2', 3.3)), '2'
            ));

            BOOST_HANA_CONSTEXPR_CHECK(equal(
                at(size_t<2>, list(1, '2', 3.3)), 3.3
            ));

            // make sure we can use non-pods on both sides
            at(size_t<1>, list(Tracked{0}, x<1>{}, Tracked{1}));

            //////////////////////////////////////////////////////////////////
            // last
            //////////////////////////////////////////////////////////////////
            BOOST_HANA_CONSTANT_CHECK(equal(
                last(list(x<0>{})),
                x<0>{}
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                last(list(invalid<0>{}, x<1>{})),
                x<1>{}
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                last(list(invalid<0>{}, invalid<1>{}, x<2>{})),
                x<2>{}
            ));

            BOOST_HANA_CONSTEXPR_CHECK(equal(
                last(list(1)), 1
            ));
            BOOST_HANA_CONSTEXPR_CHECK(equal(
                last(list(1, '2')), '2'
            ));
            BOOST_HANA_CONSTEXPR_CHECK(equal(
                last(list(1, '2', 3.3)), 3.3
            ));

            //////////////////////////////////////////////////////////////////
            // drop
            //////////////////////////////////////////////////////////////////
            BOOST_HANA_CONSTANT_CHECK(equal(
                drop(size_t<0>, list()),
                list()
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                drop(size_t<1>, list()),
                list()
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                drop(size_t<2>, list()),
                list()
            ));

            BOOST_HANA_CONSTANT_CHECK(equal(
                drop(size_t<0>, list(x<0>{})),
                list(x<0>{})
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                drop(size_t<1>, list(x<0>{})),
                list()
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                drop(size_t<2>, list(x<0>{})),
                list()
            ));

            BOOST_HANA_CONSTANT_CHECK(equal(
                drop(size_t<0>, list(x<0>{}, x<1>{})),
                list(x<0>{}, x<1>{})
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                drop(size_t<1>, list(x<0>{}, x<1>{})),
                list(x<1>{})
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                drop(size_t<2>, list(x<0>{}, x<1>{})),
                list()
            ));

            //////////////////////////////////////////////////////////////////
            // drop_until
            //////////////////////////////////////////////////////////////////
            BOOST_HANA_CONSTANT_CHECK(equal(
                drop_until(list(), id),
                list()
            ));

            BOOST_HANA_CONSTANT_CHECK(equal(
                drop_until(list(true_), id),
                list(true_)
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                drop_until(list(false_), id),
                list()
            ));

            BOOST_HANA_CONSTANT_CHECK(equal(
                drop_until(list(true_, true_), id),
                list(true_, true_)
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                drop_until(list(true_, false_), id),
                list(true_, false_)
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                drop_until(list(false_, true_), id),
                list(true_)
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                drop_until(list(false_, false_), id),
                list()
            ));

            //////////////////////////////////////////////////////////////////
            // drop_while
            //////////////////////////////////////////////////////////////////
            BOOST_HANA_CONSTANT_CHECK(equal(
                drop_while(list(), id),
                list()
            ));

            BOOST_HANA_CONSTANT_CHECK(equal(
                drop_while(list(true_), id),
                list()
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                drop_while(list(false_), id),
                list(false_)
            ));

            BOOST_HANA_CONSTANT_CHECK(equal(
                drop_while(list(true_, true_), id),
                list()
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                drop_while(list(true_, false_), id),
                list(false_)
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                drop_while(list(false_, true_), id),
                list(false_, true_)
            ));
            BOOST_HANA_CONSTANT_CHECK(equal(
                drop_while(list(false_, false_), id),
                list(false_, false_)
            ));
        }
    };
}}} // end namespace boost::hana::test

#endif // !BOOST_HANA_TEST_LAWS_ITERABLE_HPP

max_stars_repo_name: josephwinston/hana

max_issues_repo_name: josephwinston/hana

max_forks_repo_name: josephwinston/hana


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

#ifndef HTTPUTILS_HPP_
#define HTTPUTILS_HPP_

#include <cstdint>
#include <string>

#include <boost/asio.hpp>

namespace kaa {

class HttpUtils {
public:
    static boost::asio::ip::tcp::endpoint resolveEndpoint(std::string host,
                                                          std::uint16_t port,
                                                          boost::system::error_code& errorCode)
    {
        boost::asio::io_service io_service;
        boost::asio::ip::tcp::resolver resolver(io_service);
        boost::asio::ip::tcp::resolver::query query(host,
                                                    std::to_string(port),
                                                    boost::asio::ip::resolver_query_base::numeric_service);

        auto endpointIt = resolver.resolve(query, errorCode);

        if (errorCode) {
            return boost::asio::ip::tcp::endpoint();
        }

        return *endpointIt;
    }
};

}

#endif /* HTTPUTILS_HPP_ */

max_stars_repo_name: akokhanovskyi/kaa

max_issues_repo_name: akokhanovskyi/kaa

max_forks_repo_name: akokhanovskyi/kaa


text:
#ifndef STAN_MATH_REV_MAT_FUN_COV_EXP_QUAD_HPP
#define STAN_MATH_REV_MAT_FUN_COV_EXP_QUAD_HPP

#include <stan/math/rev/core.hpp>
#include <stan/math/rev/scal/fun/value_of.hpp>
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/scal/err/check_not_nan.hpp>
#include <stan/math/prim/scal/err/check_positive.hpp>
#include <stan/math/prim/scal/fun/square.hpp>
#include <stan/math/prim/scal/fun/squared_distance.hpp>
#include <stan/math/prim/scal/fun/exp.hpp>
#include <stan/math/prim/scal/meta/scalar_type.hpp>
#include <boost/math/tools/promotion.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits.hpp>
#include <vector>
#include <cmath>

namespace stan {
namespace math {

/**
 * This is a subclass of the vari class for precomputed
 * gradients of cov_exp_quad.
 *
 * The class stores the double values for the distance
 * matrix, pointers to the varis for the covariance
 * matrix, along with a pointer to the vari for sigma,
 * and the vari for l.
 *
 * @tparam T_x type of std::vector of elements
 * @tparam T_sigma type of sigma
 * @tparam T_l type of length scale
 */
template <typename T_x, typename T_sigma, typename T_l>
class cov_exp_quad_vari : public vari {
 public:
  const size_t size_;
  const size_t size_ltri_;
  const double l_d_;
  const double sigma_d_;
  const double sigma_sq_d_;
  double* dist_;
  vari* l_vari_;
  vari* sigma_vari_;
  vari** cov_lower_;
  vari** cov_diag_;

  /**
   * Constructor for cov_exp_quad.
   *
   * All memory allocated in
   * ChainableStack's stack_alloc arena.
   *
   * It is critical for the efficiency of this object
   * that the constructor create new varis that aren't
   * popped onto the var_stack_, but rather are
   * popped onto the var_nochain_stack_. This is
   * controlled to the second argument to
   * vari's constructor.
   *
   * @param x std::vector input that can be used in square distance
   *    Assumes each element of x is the same size
   * @param sigma standard deviation
   * @param l length scale
   */
  cov_exp_quad_vari(const std::vector<T_x>& x, const T_sigma& sigma,
                    const T_l& l)
      : vari(0.0),
        size_(x.size()),
        size_ltri_(size_ * (size_ - 1) / 2),
        l_d_(value_of(l)),
        sigma_d_(value_of(sigma)),
        sigma_sq_d_(sigma_d_ * sigma_d_),
        dist_(ChainableStack::instance().memalloc_.alloc_array<double>(
            size_ltri_)),
        l_vari_(l.vi_),
        sigma_vari_(sigma.vi_),
        cov_lower_(ChainableStack::instance().memalloc_.alloc_array<vari*>(
            size_ltri_)),
        cov_diag_(
            ChainableStack::instance().memalloc_.alloc_array<vari*>(size_)) {
    double inv_half_sq_l_d = 0.5 / (l_d_ * l_d_);
    size_t pos = 0;
    for (size_t j = 0; j < size_ - 1; ++j) {
      for (size_t i = j + 1; i < size_; ++i) {
        double dist_sq = squared_distance(x[i], x[j]);
        dist_[pos] = dist_sq;
        cov_lower_[pos] = new vari(
            sigma_sq_d_ * std::exp(-dist_sq * inv_half_sq_l_d), false);
        ++pos;
      }
    }
    for (size_t i = 0; i < size_; ++i)
      cov_diag_[i] = new vari(sigma_sq_d_, false);
  }

  virtual void chain() {
    double adjl = 0;
    double adjsigma = 0;

    for (size_t i = 0; i < size_ltri_; ++i) {
      vari* el_low = cov_lower_[i];
      double prod_add = el_low->adj_ * el_low->val_;
      adjl += prod_add * dist_[i];
      adjsigma += prod_add;
    }
    for (size_t i = 0; i < size_; ++i) {
      vari* el = cov_diag_[i];
      adjsigma += el->adj_ * el->val_;
    }
    l_vari_->adj_ += adjl / (l_d_ * l_d_ * l_d_);
    sigma_vari_->adj_ += adjsigma * 2 / sigma_d_;
  }
};

/**
 * This is a subclass of the vari class for precomputed
 * gradients of cov_exp_quad.
 *
 * The class stores the double values for the distance
 * matrix, pointers to the varis for the covariance
 * matrix, along with a pointer to the vari for sigma,
 * and the vari for l.
 *
 * @tparam T_x type of std::vector of elements
 * @tparam T_l type of length scale
 */
template <typename T_x, typename T_l>
class cov_exp_quad_vari<T_x, double, T_l> : public vari {
 public:
  const size_t size_;
  const size_t size_ltri_;
  const double l_d_;
  const double sigma_d_;
  const double sigma_sq_d_;
  double* dist_;
  vari* l_vari_;
  vari** cov_lower_;
  vari** cov_diag_;

  /**
   * Constructor for cov_exp_quad.
   *
   * All memory allocated in
   * ChainableStack's stack_alloc arena.
   *
   * It is critical for the efficiency of this object
   * that the constructor create new varis that aren't
   * popped onto the var_stack_, but rather are
   * popped onto the var_nochain_stack_. This is
   * controlled to the second argument to
   * vari's constructor.
   *
   * @param x std::vector input that can be used in square distance
   *    Assumes each element of x is the same size
   * @param sigma standard deviation
   * @param l length scale
   */
  cov_exp_quad_vari(const std::vector<T_x>& x, double sigma, const T_l& l)
      : vari(0.0),
        size_(x.size()),
        size_ltri_(size_ * (size_ - 1) / 2),
        l_d_(value_of(l)),
        sigma_d_(value_of(sigma)),
        sigma_sq_d_(sigma_d_ * sigma_d_),
        dist_(ChainableStack::instance().memalloc_.alloc_array<double>(
            size_ltri_)),
        l_vari_(l.vi_),
        cov_lower_(ChainableStack::instance().memalloc_.alloc_array<vari*>(
            size_ltri_)),
        cov_diag_(
            ChainableStack::instance().memalloc_.alloc_array<vari*>(size_)) {
    double inv_half_sq_l_d = 0.5 / (l_d_ * l_d_);
    size_t pos = 0;
    for (size_t j = 0; j < size_ - 1; ++j) {
      for (size_t i = j + 1; i < size_; ++i) {
        double dist_sq = squared_distance(x[i], x[j]);
        dist_[pos] = dist_sq;
        cov_lower_[pos] = new vari(
            sigma_sq_d_ * std::exp(-dist_sq * inv_half_sq_l_d), false);
        ++pos;
      }
    }
    for (size_t i = 0; i < size_; ++i)
      cov_diag_[i] = new vari(sigma_sq_d_, false);
  }

  virtual void chain() {
    double adjl = 0;

    for (size_t i = 0; i < size_ltri_; ++i) {
      vari* el_low = cov_lower_[i];
      adjl += el_low->adj_ * el_low->val_ * dist_[i];
    }
    l_vari_->adj_ += adjl / (l_d_ * l_d_ * l_d_);
  }
};

/**
 * Returns a squared exponential kernel.
 *
 * @param x std::vector input that can be used in square distance
 *    Assumes each element of x is the same size
 * @param sigma standard deviation
 * @param l length scale
 * @return squared distance
 * @throw std::domain_error if sigma <= 0, l <= 0, or
 *   x is nan or infinite
 */
template <typename T_x>
inline typename boost::enable_if_c<
    boost::is_same<typename scalar_type<T_x>::type, double>::value,
    Eigen::Matrix<var, -1, -1> >::type
cov_exp_quad(const std::vector<T_x>& x, const var& sigma, const var& l) {
  check_positive("cov_exp_quad", "sigma", sigma);
  check_positive("cov_exp_quad", "l", l);
  size_t x_size = x.size();
  for (size_t i = 0; i < x_size; ++i)
    check_not_nan("cov_exp_quad", "x", x[i]);

  Eigen::Matrix<var, -1, -1> cov(x_size, x_size);
  if (x_size == 0)
    return cov;

  cov_exp_quad_vari<T_x, var, var>* baseVari
      = new cov_exp_quad_vari<T_x, var, var>(x, sigma, l);

  size_t pos = 0;
  for (size_t j = 0; j < x_size - 1; ++j) {
    for (size_t i = (j + 1); i < x_size; ++i) {
      cov.coeffRef(i, j).vi_ = baseVari->cov_lower_[pos];
      cov.coeffRef(j, i).vi_ = cov.coeffRef(i, j).vi_;
      ++pos;
    }
    cov.coeffRef(j, j).vi_ = baseVari->cov_diag_[j];
  }
  cov.coeffRef(x_size - 1, x_size - 1).vi_ = baseVari->cov_diag_[x_size - 1];
  return cov;
}

/**
 * Returns a squared exponential kernel.
 *
 * @param x std::vector input that can be used in square distance
 *    Assumes each element of x is the same size
 * @param sigma standard deviation
 * @param l length scale
 * @return squared distance
 * @throw std::domain_error if sigma <= 0, l <= 0, or
 *   x is nan or infinite
 */
template <typename T_x>
inline typename boost::enable_if_c<
    boost::is_same<typename scalar_type<T_x>::type, double>::value,
    Eigen::Matrix<var, -1, -1> >::type
cov_exp_quad(const std::vector<T_x>& x, double sigma, const var& l) {
  check_positive("cov_exp_quad", "marginal variance", sigma);
  check_positive("cov_exp_quad", "length-scale", l);
  size_t x_size = x.size();
  for (size_t i = 0; i < x_size; ++i)
    check_not_nan("cov_exp_quad", "x", x[i]);

  Eigen::Matrix<var, -1, -1> cov(x_size, x_size);
  if (x_size == 0)
    return cov;

  cov_exp_quad_vari<T_x, double, var>* baseVari
      = new cov_exp_quad_vari<T_x, double, var>(x, sigma, l);

  size_t pos = 0;
  for (size_t j = 0; j < x_size - 1; ++j) {
    for (size_t i = (j + 1); i < x_size; ++i) {
      cov.coeffRef(i, j).vi_ = baseVari->cov_lower_[pos];
      cov.coeffRef(j, i).vi_ = cov.coeffRef(i, j).vi_;
      ++pos;
    }
    cov.coeffRef(j, j).vi_ = baseVari->cov_diag_[j];
  }
  cov.coeffRef(x_size - 1, x_size - 1).vi_ = baseVari->cov_diag_[x_size - 1];
  return cov;
}

}  // namespace math
}  // namespace stan
#endif

max_stars_repo_name: sakrejda/math

max_issues_repo_name: sakrejda/math

max_forks_repo_name: sakrejda/math