text:
/*
 * variable_selection.cpp
 *
 *  Created on: 19 Aug 2020
 *      Author: kovesarki
 */

#include <Eigen/Dense>
#include "include/monopoly.h"
#include <random>
#include <iostream>
#include <vector>
#include <string>

#include "include/tensor_serie.hh"
#include "include/correlation_tensor_serie.hh"

int main(void) {
	std::vector<std::vector<double> > signal(10000, std::vector<double>(3,0.0) );
	std::vector<std::vector<double> > background(10000, std::vector<double>(3,0.0) );

	std::random_device rd;
	std::mt19937 gen(rd());

	std::normal_distribution<> sx(0,1.01);
	std::normal_distribution<> sy(1.0,0.4);
	std::normal_distribution<> sz(0.7,2.0);

	std::normal_distribution<> bx(0.5,0.9);
	std::normal_distribution<> by(1.4,0.7);
	std::normal_distribution<> bz(0.73,2.01);

	std::vector<std::string >  variable_names(3);
	variable_names[0] = "parameter x";
	variable_names[1] = "parameter y";
	variable_names[2] = "parameter z";

	for(int i=0; i!= signal.size(); i++ ){
		signal[i][0] = sx(gen);
		signal[i][1] = sy(gen);
		signal[i][2] = sz(gen);
	}

	for(int i=0; i!= background.size(); i++ ){
		background[i][0] = bx(gen);
		background[i][1] = by(gen);
		background[i][2] = bz(gen);
	}

	tensor_serie<double> m_x(3,2);
	correlation_tensor_serie<double> signal_fourier(3,1); //number of dimensions, number of degree (linear is enough for comparison)
	for(int i=0; i!= signal.size(); i++){
		m_x.create_diad(signal[i]);
		signal_fourier.fill(m_x,1.0,1.0); //training for target y=1.0,weights=1.0
	}
	signal_fourier.normalize();

	correlation_tensor_serie<double> background_fourier(3,1); //number of dimensions, number of degree (linear is enough for comparison)
	for(int i=0; i!= background.size(); i++) {
		m_x.create_diad(background[i]);
		background_fourier.fill(m_x,1.0,1.0);
	}
	background_fourier.normalize();

	signal_fourier.cov_matrix(1);
	background_fourier.cov_matrix(1);

	double a = signal_fourier.sigma_distance(background_fourier);
	std::cout << "significance is " << a << std::endl;

	std::vector<double> sigmas(variable_names.size(), 0.0);
	std::vector<int> variable_ordering(variable_names.size(), 0.0);

	signal_fourier.variable_selection(background_fourier, sigmas, variable_ordering);

	std::cout << "Variable order, from best to worst. " << std::endl
			  << "Significance is meant for the group of best variables" << std::endl
			  << "(the variable, and all the variables above)." << std::endl;
	for(int i=0; i!= variable_ordering.size(); i++)
	{
	  std::cout << sigmas[variable_ordering[i]] << " \t" << variable_names[variable_ordering[i]] << std::endl;
	}

	std::cout << "varnames["<< variable_ordering.size()<< "] = {" << std::endl;
	for(int i=variable_ordering.size()-1; i!= -1; i--)
	{
	  std::cout << "\"" << variable_names[variable_ordering[i]] << "\"";
	  if(i!=0) {std::cout << ","; }
	  else {std::cout << std::endl << "}";}
	  std::cout << std::endl;
	}
}

max_stars_repo_name: freemeson/multinomial

max_issues_repo_name: freemeson/multinomial

max_forks_repo_name: freemeson/multinomial


text:
// Copyright (C) 2012  JINMEI Tatuya
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.

// Many helper methods and classes for tests are derived from BIND 10 tests,
// whose copyright notice follow:
// Copyright (C) 2011  Internet Systems Consortium, Inc. ("ISC")
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.

#include <asio_message_manager.h>

#include <gtest/gtest.h>

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

#include <cstring>
#include <string>
#include <utility>

#include <sys/types.h>
#include <sys/errno.h>
#include <sys/socket.h>
#include <netinet/in.h>

#include <netdb.h>

using namespace std;
using namespace Queryperf;
using boost::scoped_ptr;
using boost::lexical_cast;
using namespace boost::posix_time;
using boost::posix_time::seconds;
using boost::posix_time::ptime;

namespace {
const char TEST_DATA[] = "queryperf test";

// A simple helper structure to automatically close test sockets on return
// or exception in a RAII manner.  non copyable to prevent duplicate close.
struct ScopedSocket : boost::noncopyable {
    ScopedSocket() : fd(-1) {}
    ScopedSocket(int sock) : fd(sock) {}
    ~ScopedSocket() {
        closeSocket();
    }
    void reset(int sock) {
        closeSocket();
        fd = sock;
    }
    int fd;
private:
    void closeSocket() {
        if (fd >= 0) {
            close(fd);
        }
    }
};

// Lower level C-APIs require conversion between various variants of
// sockaddr's, which is not friendly with C++.  The following templates
// are a shortcut of common workaround conversion in such cases.

template <typename SAType>
const struct sockaddr*
convertSockAddr(const SAType* sa) {
    const void* p = sa;
    return (static_cast<const struct sockaddr*>(p));
}

template <typename SAType>
const SAType*
convertSockAddr(const struct sockaddr* sa) {
    const void* p = sa;
    return (static_cast<const SAType*>(p));
}

template <typename SAType>
struct sockaddr*
convertSockAddr(SAType* sa) {
    void* p = sa;
    return (static_cast<struct sockaddr*>(p));
}

template <typename SAType>
SAType*
convertSockAddr(struct sockaddr* sa) {
    void* p = sa;
    return (static_cast<SAType*>(p));
}

// A helper to impose some reasonable amount of wait on recv(from)
// if possible.  It returns an option flag to be set for the system call
// (when necessary).
int
setRecvDelay(int s) {
    const struct timeval timeo = { 10, 0 };
    if (setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &timeo, sizeof(timeo)) == -1) {
        if (errno == ENOPROTOOPT) {
            // Workaround for Solaris: see recursive_query_unittest
            return (MSG_DONTWAIT);
        } else {
            throw runtime_error(string("set RCVTIMEO failed: ") +
                                strerror(errno));
        }
    }
    return (0);
}

// A shortcut type that is convenient to be used for socket related
// system calls, which generally require this pair
typedef pair<const struct sockaddr*, socklen_t> SockAddrInfo;

// A helper class to convert textual representation of IP address and port
// to a pair of sockaddr and its length (in the form of a SockAddrInfo
// pair).  Its get method uses getaddrinfo(3) for the conversion and stores
// the result in the addrinfo_list_ vector until the object is destructed.
// The allocated resources will be automatically freed in an RAII manner.
class SockAddrCreator {
public:
    ~SockAddrCreator() {
        vector<struct addrinfo*>::const_iterator it;
        for (it = addrinfo_list_.begin(); it != addrinfo_list_.end(); ++it) {
            freeaddrinfo(*it);
        }
    }
    SockAddrInfo get(const string& addr_str, const string& port_str) {
        struct addrinfo hints, *res;
        memset(&hints, 0, sizeof(hints));
        hints.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV;
        hints.ai_family = AF_UNSPEC;
        hints.ai_socktype = SOCK_DGRAM; // could be either DGRAM or STREAM here
        const int error = getaddrinfo(addr_str.c_str(), port_str.c_str(),
                                      &hints, &res);
        if (error != 0) {
            throw runtime_error("getaddrinfo failed for " + addr_str + ", " +
                                port_str + ": " + gai_strerror(error));
        }

        // Technically, this is not entirely exception safe; if push_back
        // throws, the resources allocated for 'res' will leak.  We prefer
        // brevity here and ignore the minor failure mode.
        addrinfo_list_.push_back(res);

        return (SockAddrInfo(res->ai_addr, res->ai_addrlen));
    }
private:
    vector<struct addrinfo*> addrinfo_list_;
};

// An empty call back for MessageSocket::send.  Used when we don't have
// to test the callback behavior.
void
noopSocketCallback(const MessageSocket::Event&) {
}

// Same for the timer
void
noopTimerCallback() {
}

class ASIOMessageManagerTest : public ::testing::Test {
public:
    ASIOMessageManagerTest() : sendcallback_called_(0),
                               timercallback_called_(0),
                               helpercallback_called_(0),
                               send_done_(0)
    {}

    // A convenient shortcut for the namespace-scope version of getSockAddr
    SockAddrInfo getSockAddr(const string& addr_str, const string& port_str) {
        return (addr_creator_.get(addr_str, port_str));
    }

    // Common callback for the message socket.
    void sendCallback(const MessageSocket::Event& ev) {
        ++sendcallback_called_;
        // In the TCP test, a complete response message hasn't be sent
        // until callbackForTCPTest is called at least 4 times.  See that
        // function.
        // (helpercallback_called_ should be 0 for UDP)
        if (helpercallback_called_ > 0 && helpercallback_called_ <= 3) {
            EXPECT_EQ(0, ev.datalen);
        } else {
            EXPECT_EQ(sizeof(TEST_DATA), ev.datalen);
            EXPECT_STREQ(TEST_DATA, static_cast<const char*>(ev.data));
        }
        if (send_done_ == sendcallback_called_) {
            asio_manager_.stop();
        }
    }

    void timerCallback() {
        ++timercallback_called_;
    }

    // A helper method that creates a specified type of socket that is
    // supposed to be passed via a SocketSessionForwarder.  It will bound
    // to the specified address and port in sainfo.  If do_listen is true
    // and it's a TCP socket, it will also start listening to new connection
    // requests.
    int createSocket(int family, int type, int protocol,
                     const SockAddrInfo& sainfo, bool do_listen = true)
    {
        int s = socket(family, type, protocol);
        if (s < 0) {
            throw runtime_error(string("socket(2) failed: ") +
                                strerror(errno));
        }
        const int on = 1;
        if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
            throw runtime_error(string("setsockopt(SO_REUSEADDR) failed: ") +
                                strerror(errno));
        }
        if (bind(s, sainfo.first, sainfo.second) < 0) {
            close(s);
            throw runtime_error(string("bind(2) failed: ") + strerror(errno));
        }
        if (do_listen && protocol == IPPROTO_TCP) {
            if (listen(s, 1) == -1) {
                throw runtime_error(string("listen(2) failed: ") +
                                    strerror(errno));
            }
        }
        return (s);
    }

    void sendUDPCheck(int recv_fd, const string& addr, uint16_t port,
                      MessageSocket::Callback callback);
    void sendTCPCheck(int recv_fd, int udp_af, const string& addr,
                      const string& port, size_t callback_limit);
    void callbackForTCPTest(const MessageSocket::Event& ev,
                            int tcp_fd, int udp_fd, size_t callback_limit);

    size_t sendcallback_called_;
    size_t timercallback_called_;
    size_t helpercallback_called_; // # of times callbackForTCPTest is called
    size_t send_done_;
    ASIOMessageManager asio_manager_;
    scoped_ptr<MessageSocket> test_sock_;
    scoped_ptr<MessageSocket> udp_sock_; // auxiliary socket used in TCP test
    scoped_ptr<MessageTimer> test_timer_;
    ScopedSocket accept_s_;
    uint8_t recvbuf_[65535];

private:
    SockAddrCreator addr_creator_;
};

TEST_F(ASIOMessageManagerTest, createMessageSocketIPv6) {
    scoped_ptr<ASIOMessageSocket> sock(
        dynamic_cast<ASIOMessageSocket*>(
            asio_manager_.createMessageSocket(
                IPPROTO_UDP, "::1", 5300, recvbuf_, sizeof(recvbuf_),
                noopSocketCallback)));
    ASSERT_TRUE(sock);
    const int s =  sock->native(); // note: this doesn't have to be closed
    EXPECT_NE(-1, s);

    // The socket should be already bound (and connected)
    struct sockaddr_in6 sin6;
    memset(&sin6, 0, sizeof(sin6));
    socklen_t salen = sizeof(sin6);
    EXPECT_NE(-1, getsockname(s, static_cast<struct sockaddr*>(
                                  static_cast<void*>(&sin6)),
                              &salen));
    EXPECT_NE(0, sin6.sin6_port);
}

TEST_F(ASIOMessageManagerTest, createMessageSocketTCPIPv6) {
    scoped_ptr<ASIOMessageSocket> sock(
        dynamic_cast<ASIOMessageSocket*>(
            asio_manager_.createMessageSocket(
                IPPROTO_TCP, "::1", 5300, recvbuf_, sizeof(recvbuf_),
                noopSocketCallback)));
    ASSERT_TRUE(sock);
    // In the case of TCP, the underlying socket is not open until send()
    EXPECT_EQ(-1, sock->native());
}

TEST_F(ASIOMessageManagerTest, createMessageSocketIPv4) {
    scoped_ptr<ASIOMessageSocket> sock(
        dynamic_cast<ASIOMessageSocket*>(
            asio_manager_.createMessageSocket(
                IPPROTO_UDP, "127.0.0.1", 5304, recvbuf_, sizeof(recvbuf_),
                noopSocketCallback)));
    ASSERT_TRUE(sock);
    const int s =  sock->native();
    EXPECT_NE(-1, s);

    // Receive buffer size should be at least 32KB.
    int bufsize;
    socklen_t optlen = sizeof(bufsize);
    EXPECT_EQ(0, getsockopt(s, SOL_SOCKET, SO_RCVBUF, &bufsize, &optlen));
    EXPECT_LE(32768, bufsize);

    // The socket should be already bound (and connected)
    struct sockaddr_in sin4;
    memset(&sin4, 0, sizeof(sin4));
    socklen_t salen = sizeof(sin4);
    EXPECT_NE(-1, getsockname(s, static_cast<struct sockaddr*>(
                                  static_cast<void*>(&sin4)),
                              &salen));
    EXPECT_NE(0, sin4.sin_port);
}

TEST_F(ASIOMessageManagerTest, createMessageSocketTCPIPv4) {
    scoped_ptr<ASIOMessageSocket> sock(
        dynamic_cast<ASIOMessageSocket*>(
            asio_manager_.createMessageSocket(
                IPPROTO_TCP, "127.0.0.1", 5304, recvbuf_, sizeof(recvbuf_),
                noopSocketCallback)));
    ASSERT_TRUE(sock);
    // In the case of TCP, the underlying socket is not open until send()
    EXPECT_EQ(-1, sock->native());
}

TEST_F(ASIOMessageManagerTest, createMessageSocketBadParam) {
    // Unspecified protocol (assuming it's neither UDP or TCP)
    EXPECT_THROW(asio_manager_.createMessageSocket(
                     0, "::1", 5300, recvbuf_, sizeof(recvbuf_),
                     noopSocketCallback),
                 MessageSocketError);

    // Bad address
    EXPECT_THROW(asio_manager_.createMessageSocket(
                     IPPROTO_UDP, "127.0.0..1", 5300, recvbuf_,
                     sizeof(recvbuf_), noopSocketCallback),
                 MessageSocketError);

    // Null callback
    EXPECT_THROW(asio_manager_.createMessageSocket(IPPROTO_UDP, "127.0.0.1",
                                                   5300, recvbuf_,
                                                   sizeof(recvbuf_), NULL),
                 MessageSocketError);
}

void
ASIOMessageManagerTest::sendUDPCheck(int recv_fd, const string& addr,
                                     uint16_t port,
                                     MessageSocket::Callback callback =
                                     noopSocketCallback)
{
    // Create a socket on the manager if not created
    if (!test_sock_) {
        test_sock_.reset(asio_manager_.createMessageSocket(
                             IPPROTO_UDP, addr, port, recvbuf_,
                             sizeof(recvbuf_), callback));
    }

    // Send data from the first socket, and receive on the second one.
    test_sock_->send(TEST_DATA, sizeof(TEST_DATA));
    ++send_done_;

    char recvbuf[sizeof(TEST_DATA)];
    sockaddr_storage ss;
    socklen_t sa_len = sizeof(ss);
    EXPECT_EQ(sizeof(TEST_DATA), recvfrom(recv_fd, recvbuf, sizeof(recvbuf),
                                          setRecvDelay(recv_fd),
                                          convertSockAddr(&ss), &sa_len));
    EXPECT_STREQ(TEST_DATA, recvbuf);

    // Then echo back the received data to the sender (which may or may not be
    // used in the test)
    EXPECT_EQ(sizeof(TEST_DATA), sendto(recv_fd, recvbuf, sizeof(recvbuf), 0,
                     convertSockAddr(&ss), sa_len));
}

TEST_F(ASIOMessageManagerTest, sendUDP) {
    ScopedSocket recv_s(createSocket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP,
                                     getSockAddr("::1", "5306")));
    sendUDPCheck(recv_s.fd, "::1", 5306);

    test_sock_.reset(NULL);
    recv_s.reset(createSocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP,
                              getSockAddr("127.0.0.1", "5304")));
    sendUDPCheck(recv_s.fd, "127.0.0.1", 5304);
}

// This is a helper function used below.  It allows the test code to get
// the control back from the underlying ASIO service.  The sendto() call
// at the end of this function will cause callbackForTCPTest to be called
// from ASIO.
void
triggerCallback(MessageSocket& sender_sock, int recv_fd) {
    sender_sock.send(TEST_DATA, sizeof(TEST_DATA));

    char recvbuf[sizeof(TEST_DATA)];
    sockaddr_storage ss;
    socklen_t sa_len = sizeof(ss);
    EXPECT_EQ(sizeof(TEST_DATA), recvfrom(recv_fd, recvbuf, sizeof(recvbuf),
                                          setRecvDelay(recv_fd),
                                          convertSockAddr(&ss), &sa_len));
    EXPECT_STREQ(TEST_DATA, recvbuf);
    EXPECT_EQ(sizeof(TEST_DATA), sendto(recv_fd, recvbuf, sizeof(recvbuf), 0,
                     convertSockAddr(&ss), sa_len));
}

void
ASIOMessageManagerTest::callbackForTCPTest(const MessageSocket::Event&,
                                           int tcp_fd, int udp_fd,
                                           size_t callback_limit)
{
    ++helpercallback_called_;

    char lenbuf[2];
    ASSERT_GE(sizeof(lenbuf), 2);
    char databuf[sizeof(TEST_DATA)];
    const char* const DUMMY_DATA = "dummy data";

    switch (helpercallback_called_) {
    case 1:
        // First two octets store the message length
        EXPECT_EQ(2, recv(tcp_fd, lenbuf, 2, MSG_WAITALL));
        EXPECT_EQ(sizeof(TEST_DATA), lenbuf[0] * 256 + lenbuf[1]);

        // Then the following real data and check it.
        EXPECT_EQ(sizeof(TEST_DATA), recv(tcp_fd, databuf, sizeof(databuf),
                                          MSG_WAITALL));
        EXPECT_STREQ(TEST_DATA, databuf);
        break;
    case 2:
        // Confirm the client has made sure there would be no more query.
        EXPECT_EQ(0, recv(accept_s_.fd, lenbuf, 1, setRecvDelay(accept_s_.fd)));
        break;
    case 3:
        // Send response, 1st part (message length)
        lenbuf[0] = 0;
        lenbuf[1] = sizeof(TEST_DATA);
        EXPECT_EQ(sizeof(lenbuf), send(tcp_fd, lenbuf, sizeof(lenbuf), 0));
        break;
    case 4:
        // send response, 2nd part (the message)
        EXPECT_EQ(sizeof(TEST_DATA), send(tcp_fd, TEST_DATA, sizeof(TEST_DATA),
                                          0));
        break;
    default:
        // additional message.  Using different content so we can confirm
        // whether the first one will appear in the callback.
        lenbuf[0] = 0;
        lenbuf[1] = sizeof(DUMMY_DATA);
        EXPECT_EQ(sizeof(lenbuf), send(tcp_fd, lenbuf, sizeof(lenbuf), 0));
        EXPECT_EQ(sizeof(DUMMY_DATA), send(tcp_fd, DUMMY_DATA,
                                           sizeof(DUMMY_DATA), 0));
        break;
    }

    if (helpercallback_called_ == callback_limit) {
        // If we reached the upper limit of callback, we'll close the server
        // side connection.  This will trigger the callback at the client.
        accept_s_.reset(-1);
    } else {
        // Otherwise, we'll move to the next state in this callback.
        triggerCallback(*udp_sock_, udp_fd);
    }
}

void
ASIOMessageManagerTest::sendTCPCheck(int listen_fd, int udp_af,
                                     const string& addr,
                                     const string& port,
                                     size_t callback_limit)
{
    // Create a socket on the manager if not created
    if (!test_sock_) {
        test_sock_.reset(asio_manager_.createMessageSocket(
                             IPPROTO_TCP, addr, lexical_cast<uint16_t>(port),
                             recvbuf_, sizeof(recvbuf_),
                             boost::bind(
                                 &ASIOMessageManagerTest::sendCallback, this,
                                 _1)));
    }

    // Send data from the first socket, and receive on the second one.
    test_sock_->send(TEST_DATA, sizeof(TEST_DATA));
    ++send_done_;

    // Accept the connection
    sockaddr_storage ss;
    socklen_t sa_len = sizeof(ss);
    accept_s_.reset(accept(listen_fd, convertSockAddr(&ss), &sa_len));
    ASSERT_NE(-1, accept_s_.fd);

    // We use a helper UDP socket to internally handle our own events;
    // otherwise the test could get stuck within the ASIO main loop.
    ScopedSocket udp_s(createSocket(udp_af, SOCK_DGRAM, IPPROTO_UDP,
                                    getSockAddr(addr, port)));

    // Send data from the UDP test socket, receive on the UDP socket,
    // and then send the data back.  This way we can be called back from
    // the manager, and handle the TCP events.
    uint8_t udp_recvbuf[128];
    udp_sock_.reset(
        asio_manager_.createMessageSocket(
            IPPROTO_UDP, addr, lexical_cast<uint16_t>(port), udp_recvbuf,
            sizeof(udp_recvbuf),
            boost::bind(&ASIOMessageManagerTest::callbackForTCPTest, this,
                        _1, accept_s_.fd, udp_s.fd, callback_limit)));
    triggerCallback(*udp_sock_, udp_s.fd);

    // Then start the manager loop.  TCP message will be sent, and the socket
    // will wait for the response.
    asio_manager_.run();
}

TEST_F(ASIOMessageManagerTest, sendCallbackUDPIPv6) {
    ScopedSocket recv_s(createSocket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP,
                                     getSockAddr("::1", "5306")));
    EXPECT_EQ(0, sendcallback_called_);
    sendUDPCheck(recv_s.fd, "::1", 5306,
              boost::bind(&ASIOMessageManagerTest::sendCallback, this, _1));
    EXPECT_EQ(0, sendcallback_called_); // callback still shouldn't be called
    asio_manager_.run();
    EXPECT_EQ(1, sendcallback_called_);
}

TEST_F(ASIOMessageManagerTest, sendCallbackUDPIPv4) {
    // same test as the previous one, for IPv4.
    ScopedSocket recv_s(createSocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP,
                                     getSockAddr("127.0.0.1", "5304")));
    EXPECT_EQ(0, sendcallback_called_);
    sendUDPCheck(recv_s.fd, "127.0.0.1", 5304,
              boost::bind(&ASIOMessageManagerTest::sendCallback, this, _1));
    EXPECT_EQ(0, sendcallback_called_);
    asio_manager_.run();
    EXPECT_EQ(1, sendcallback_called_);
}

// Note: this test could block if the tested code has a bug.
TEST_F(ASIOMessageManagerTest, sendTCPIPv6) {
    ScopedSocket listen_s(createSocket(AF_INET6, SOCK_STREAM, IPPROTO_TCP,
                                       getSockAddr("::1", "5306")));
    sendTCPCheck(listen_s.fd, AF_INET6, "::1", "5306", 1);
    EXPECT_EQ(1, sendcallback_called_);
}

TEST_F(ASIOMessageManagerTest, sendTCPIPv6Partial) {
    // We'll stop sending after sending length
    ScopedSocket listen_s(createSocket(AF_INET6, SOCK_STREAM, IPPROTO_TCP,
                                       getSockAddr("::1", "5306")));
    sendTCPCheck(listen_s.fd, AF_INET6, "::1", "5306", 3);
    EXPECT_EQ(1, sendcallback_called_);
}

TEST_F(ASIOMessageManagerTest, sendTCPIPv6Complete) {
    ScopedSocket listen_s(createSocket(AF_INET6, SOCK_STREAM, IPPROTO_TCP,
                                       getSockAddr("::1", "5306")));
    // We'll call callbackForTCPTest 4 times, at which point the process will
    // be completed.
    sendTCPCheck(listen_s.fd, AF_INET6, "::1", "5306", 4);
    EXPECT_EQ(1, sendcallback_called_);
}

TEST_F(ASIOMessageManagerTest, sendTCPIPv6Multi) {
    ScopedSocket listen_s(createSocket(AF_INET6, SOCK_STREAM, IPPROTO_TCP,
                                       getSockAddr("::1", "5306")));
    // We'll call callbackForTCPTest one more than the previous case, which
    // will result in two response messages.
    sendTCPCheck(listen_s.fd, AF_INET6, "::1", "5306", 5);
    EXPECT_EQ(1, sendcallback_called_);
}

TEST_F(ASIOMessageManagerTest, sendTCPIPv4) {
    ScopedSocket listen_s(createSocket(AF_INET, SOCK_STREAM, IPPROTO_TCP,
                                       getSockAddr("127.0.0.1", "5304")));
    sendTCPCheck(listen_s.fd, AF_INET, "127.0.0.1", "5304", 1);
    EXPECT_EQ(1, sendcallback_called_);
}

TEST_F(ASIOMessageManagerTest, sendTCPIPv4Partial) {
    ScopedSocket listen_s(createSocket(AF_INET, SOCK_STREAM, IPPROTO_TCP,
                                       getSockAddr("127.0.0.1", "5304")));
    sendTCPCheck(listen_s.fd, AF_INET, "127.0.0.1", "5304", 3);
    EXPECT_EQ(1, sendcallback_called_);
}

TEST_F(ASIOMessageManagerTest, sendCallbackTCPIPv4) {
    ScopedSocket listen_s(createSocket(AF_INET, SOCK_STREAM, IPPROTO_TCP,
                                       getSockAddr("127.0.0.1", "5304")));
    sendTCPCheck(listen_s.fd, AF_INET, "127.0.0.1", "5304", 4);
    EXPECT_EQ(1, sendcallback_called_);
}

TEST_F(ASIOMessageManagerTest, sendTCPIPv4Multi) {
    ScopedSocket listen_s(createSocket(AF_INET, SOCK_STREAM, IPPROTO_TCP,
                                       getSockAddr("127.0.0.1", "5304")));
    sendTCPCheck(listen_s.fd, AF_INET, "127.0.0.1", "5304", 5);
    EXPECT_EQ(1, sendcallback_called_);
}

TEST_F(ASIOMessageManagerTest, multipleUDPSends) {
    ScopedSocket recv_s(createSocket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP,
                                     getSockAddr("::1", "5306")));
    EXPECT_EQ(0, sendcallback_called_);
    sendUDPCheck(recv_s.fd, "::1", 5306,
                 boost::bind(&ASIOMessageManagerTest::sendCallback, this,
                             _1));
    sendUDPCheck(recv_s.fd, "::1", 5306,
                 boost::bind(&ASIOMessageManagerTest::sendCallback, this,
                             _1));
    asio_manager_.run();
    EXPECT_EQ(2, sendcallback_called_);
}

TEST_F(ASIOMessageManagerTest, createMessageTimer) {
    test_timer_.reset(asio_manager_.createMessageTimer(noopTimerCallback));
    EXPECT_TRUE(test_timer_);
}

// Note: this test takes time, so disabled by default.
TEST_F(ASIOMessageManagerTest, DISABLED_startMessageTimer) {
    test_timer_.reset(asio_manager_.createMessageTimer(
                          boost::bind(&ASIOMessageManagerTest::timerCallback,
                                      this)));
    ASSERT_TRUE(test_timer_);
    const ptime start_tm = microsec_clock::local_time();
    test_timer_->start(seconds(1));
    EXPECT_EQ(0, timercallback_called_);
    asio_manager_.run();
    const ptime end_tm = microsec_clock::local_time();
    EXPECT_EQ(1, timercallback_called_);

    // Check the duration is in some conservative range for the specified timer
    const long duration = (end_tm - start_tm).total_microseconds();
    EXPECT_GE(1500000, duration);
    EXPECT_LE(500000, duration);
}

TEST_F(ASIOMessageManagerTest, cancelMessageTimer) {
    test_timer_.reset(asio_manager_.createMessageTimer(
                          boost::bind(&ASIOMessageManagerTest::timerCallback,
                                      this)));
    ASSERT_TRUE(test_timer_);
    test_timer_->start(seconds(1));
    test_timer_->cancel();
    asio_manager_.run();
    EXPECT_EQ(0, timercallback_called_);
}
} // unnamed namespace

ext: cc

max_stars_repo_name: cstrotm/queryperfpp

max_issues_repo_name: cstrotm/queryperfpp

max_forks_repo_name: cstrotm/queryperfpp


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

#include <boost/gil/gil_all.hpp>

#include <boost/gil/extension/io/detail/typedefs.hpp>
#include <boost/gil/extension/io/tiff_all.hpp>

#include "color_space_write_test.hpp"
#include "mandel_view.hpp"
#include "paths.hpp"

using namespace std;
using namespace boost::gil;

typedef tiff_tag tag_t;

BOOST_AUTO_TEST_SUITE( tiff_test )

BOOST_AUTO_TEST_CASE( rgb_color_space_write_test )
{
    color_space_write_test< tag_t >( tiff_out + "rgb_color_space_test.tif"
                                   , tiff_out + "bgr_color_space_test.tif"
                                   );
}

BOOST_AUTO_TEST_SUITE_END()

ext: cpp

max_stars_repo_name: smart-make/boost

max_issues_repo_name: smart-make/boost

max_forks_repo_name: smart-make/boost


text:
/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2012 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
#ifndef PLACEMENTS_DUMMY_HPP
#define PLACEMENTS_DUMMY_HPP

// mapnik
#include <mapnik/config.hpp>
#include <mapnik/text_placements/base.hpp>
// boost
#include <boost/concept_check.hpp>

namespace mapnik
{

class text_placements_info_dummy;

// Dummy placement algorithm. Always takes the default value.
class MAPNIK_DECL text_placements_dummy: public text_placements
{
public:
text_placement_info_ptr get_placement_info(double scale_factor) const;
friend class text_placement_info_dummy;
};

// Placement info object for dummy placement algorithm. Always takes the default value.
class MAPNIK_DECL text_placement_info_dummy : public text_placement_info
{
public:
text_placement_info_dummy(text_placements_dummy const* parent, double scale_factor)
    : text_placement_info(parent, scale_factor),
      state(0) {}

    bool next();
private:
unsigned state;
};

} //ns mapnik

#endif // PLACEMENTS_DUMMY_HPP

ext: hpp

max_stars_repo_name: Wujingli/OpenWebGlobeDataProcessing

max_issues_repo_name: Wujingli/OpenWebGlobeDataProcessing

max_forks_repo_name: Wujingli/OpenWebGlobeDataProcessing


text:
// Copyright (c) 2020 OUXT Polaris
//
// 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 PURE_PURSUIT_PLANNER__PURE_PURSUIT_PLANNER_COMPONENT_HPP_
#define PURE_PURSUIT_PLANNER__PURE_PURSUIT_PLANNER_COMPONENT_HPP_

#if __cplusplus
extern "C" {
#endif

// The below macros are taken from https://gcc.gnu.org/wiki/Visibility and from
// demos/composition/include/composition/visibility_control.h at https://github.com/ros2/demos
#if defined _WIN32 || defined __CYGWIN__
#ifdef __GNUC__
#define PURE_PURSUIT_PLANNER_PURE_PURSUIT_PLANNER_COMPONENT_EXPORT __attribute__((dllexport))
#define PURE_PURSUIT_PLANNER_PURE_PURSUIT_PLANNER_COMPONENT_IMPORT __attribute__((dllimport))
#else
#define PURE_PURSUIT_PLANNER_PURE_PURSUIT_PLANNER_COMPONENT_EXPORT __declspec(dllexport)
#define PURE_PURSUIT_PLANNER_PURE_PURSUIT_PLANNER_COMPONENT_IMPORT __declspec(dllimport)
#endif
#ifdef PURE_PURSUIT_PLANNER_PURE_PURSUIT_PLANNER_COMPONENT_BUILDING_DLL
#define PURE_PURSUIT_PLANNER_PURE_PURSUIT_PLANNER_COMPONENT_PUBLIC \
  PURE_PURSUIT_PLANNER_PURE_PURSUIT_PLANNER_COMPONENT_EXPORT
#else
#define PURE_PURSUIT_PLANNER_PURE_PURSUIT_PLANNER_COMPONENT_PUBLIC \
  PURE_PURSUIT_PLANNER_PURE_PURSUIT_PLANNER_COMPONENT_IMPORT
#endif
#define PURE_PURSUIT_PLANNER_PURE_PURSUIT_PLANNER_COMPONENT_PUBLIC_TYPE \
  PURE_PURSUIT_PLANNER_PURE_PURSUIT_PLANNER_COMPONENT_PUBLIC
#define PURE_PURSUIT_PLANNER_PURE_PURSUIT_PLANNER_COMPONENT_LOCAL
#else
#define PURE_PURSUIT_PLANNER_PURE_PURSUIT_PLANNER_COMPONENT_EXPORT \
  __attribute__((visibility("default")))
#define PURE_PURSUIT_PLANNER_PURE_PURSUIT_PLANNER_COMPONENT_IMPORT
#if __GNUC__ >= 4
#define PURE_PURSUIT_PLANNER_PURE_PURSUIT_PLANNER_COMPONENT_PUBLIC \
  __attribute__((visibility("default")))
#define PURE_PURSUIT_PLANNER_PURE_PURSUIT_PLANNER_COMPONENT_LOCAL \
  __attribute__((visibility("hidden")))
#else
#define PURE_PURSUIT_PLANNER_PURE_PURSUIT_PLANNER_COMPONENT_PUBLIC
#define PURE_PURSUIT_PLANNER_PURE_PURSUIT_PLANNER_COMPONENT_LOCAL
#endif
#define PURE_PURSUIT_PLANNER_PURE_PURSUIT_PLANNER_COMPONENT_PUBLIC_TYPE
#endif

#if __cplusplus
}  // extern "C"
#endif

#include <quaternion_operation/quaternion_operation.h>
#include <tf2_geometry_msgs/tf2_geometry_msgs.h>
#include <tf2_ros/buffer.h>
#include <tf2_ros/transform_listener.h>

#include <boost/optional.hpp>
#include <geometry_msgs/msg/pose_stamped.hpp>
#include <geometry_msgs/msg/twist.hpp>
#include <hermite_path_planner/hermite_path_generator.hpp>
#include <memory>
#include <rclcpp/rclcpp.hpp>
#include <visualization_msgs/msg/marker_array.hpp>

namespace pure_pursuit_planner
{
class PurePursuitPlannerComponent : public rclcpp::Node
{
public:
  PURE_PURSUIT_PLANNER_PURE_PURSUIT_PLANNER_COMPONENT_PUBLIC
  explicit PurePursuitPlannerComponent(const rclcpp::NodeOptions & options);

private:
  boost::optional<geometry_msgs::msg::Twist> getTargetTwist(double target_t);
  void currentTwistCallback(const geometry_msgs::msg::Twist::SharedPtr data);
  rclcpp::Subscription<geometry_msgs::msg::Twist>::SharedPtr current_twist_sub_;
  void hermitePathCallback(const hermite_path_msgs::msg::HermitePathStamped::SharedPtr data);
  rclcpp::Subscription<hermite_path_msgs::msg::HermitePathStamped>::SharedPtr hermite_path_sub_;
  boost::optional<geometry_msgs::msg::Twist> current_twist_;
  void currentPoseCallback(const geometry_msgs::msg::PoseStamped::SharedPtr data);
  boost::optional<geometry_msgs::msg::PoseStamped> current_pose_;
  boost::optional<geometry_msgs::msg::PoseStamped> current_pose_transformed_;
  rclcpp::Subscription<geometry_msgs::msg::PoseStamped>::SharedPtr current_pose_sub_;
  rclcpp::Publisher<geometry_msgs::msg::Twist>::SharedPtr target_twist_pub_;
  std::shared_ptr<hermite_path_planner::HermitePathGenerator> generator_;
  double lookahead_distance_;
  double minimum_lookahead_distance_;
  double lookahead_ratio_;
  tf2_ros::Buffer buffer_;
  tf2_ros::TransformListener listener_;
  rclcpp::Publisher<visualization_msgs::msg::MarkerArray>::SharedPtr marker_pub_;
  boost::optional<hermite_path_msgs::msg::HermitePathStamped> path_;
  boost::optional<double> current_t_, target_t_;
  boost::optional<geometry_msgs::msg::Point> target_position_;
  visualization_msgs::msg::MarkerArray generateMarker(
    boost::optional<geometry_msgs::msg::Twist> twist);
};
}  // namespace pure_pursuit_planner

#endif  // PURE_PURSUIT_PLANNER__PURE_PURSUIT_PLANNER_COMPONENT_HPP_


text:
#include "pch.h"
#include <boost/foreach.hpp>
#include <boost/range/algorithm.hpp>
#include <boost/assert.hpp>
#include <glload/gl_all.hpp>
#include "glscene/Style.h"
#include "NodeData.h"
#include "ResourceData.h"

namespace glscene
{
	NodeData::NodeData( const boost::optional<IdString> &name, NodeData *pParent, int numLayers )
		: m_name(name)
		, m_pParent(pParent)
		, m_layers(numLayers)
	{
		BOOST_ASSERT(m_pParent);
		m_pParent->m_children.push_back(this);
	}

	NodeData::NodeData( int numLayers )
		: m_pParent(NULL)
		, m_layers(numLayers)
	{}

	namespace
	{
		struct DeletePipelineVisitor : public boost::static_visitor<>
		{
			void operator()(const SeparableProgramBindingData &sepData) const
			{
				gl::DeleteProgramPipelines(1, &sepData.pipelineObj);
			}

			void operator()(const SingleProgramBindingData &) const {}
		};
	}

	NodeData::~NodeData()
	{
		//Remove from parent's list.
		if(m_pParent)
			RemoveFromParent();

		BOOST_FOREACH(NodeData *pChild, m_children)
		{
			//Stop his destructor from removing himself from my list while I'm iterating over it.
			pChild->m_pParent = NULL;
			delete pChild;
		}

		BOOST_FOREACH(const StyleMap::value_type &stylePair, m_styles)
		{
			boost::apply_visitor(DeletePipelineVisitor(), stylePair.second.progBinding);
		}
	}

	void NodeData::AddToLayer( int layerIx )
	{
		if(layerIx < (int)m_layers.size())
			m_layers.set(layerIx);
	}

	void NodeData::RemoveFromLayer( int layerIx )
	{
		if(layerIx < (int)m_layers.size())
			m_layers.reset(layerIx);
	}

	bool NodeData::IsInLayer( int layerIx ) const
	{
		if(layerIx < (int)m_layers.size())
			return m_layers.test(layerIx);
		return false;
	}

	void NodeData::RemoveFromParent()
	{
		if(m_pParent)
		{
			m_pParent->m_children.erase(
				boost::range::remove(m_pParent->m_children, this), m_pParent->m_children.end());
		}
	}

	NodeData * NodeData::FindByName( const IdString &name )
	{
		if(m_name && m_name.get() == name)
			return this;

		BOOST_FOREACH(NodeData *pChild, m_children)
		{
			NodeData *pRet = pChild->FindByName(name);
			if(pRet)
				return pRet;
		}

		return NULL;
	}

	void NodeData::MakeChildOfNode( NodeData &newParent )
	{
		if(!m_pParent)
			throw CannotChangeTheRootParentException();

		//Already the parent. No-op.
		if(m_pParent == &newParent)
			return;

		//First, remove ourself from the nodes in our parent list.
		NodeData &currParent = *m_pParent;
		currParent.m_children.erase(
			boost::range::remove(currParent.m_children, this), currParent.m_children.end());

		//Now, add ourselves to the new parent's list.
		newParent.m_children.push_back(this);

		//Change our parent.
		m_pParent = &newParent;
	}

	NodeData & NodeData::CreateChildNode( const boost::optional<IdString> &name )
	{
		//Child will automatically add itself.
		NodeData *pRet = new NodeData(name, this, (int)m_layers.size());
		return *pRet;
	}

	void NodeData::ReparentChildrenToParent()
	{
		while(!m_children.empty())
			m_children.front()->MakeChildOfNode(*m_pParent);
	}

	namespace
	{
		struct ProgDataExtraction : public boost::static_visitor<ProgramBindingData>
		{
			SingleProgramBindingData operator()(const SingleProgramBinding &binding) const
			{
				SingleProgramBindingData data(binding.programId);
				data.uniformIds.reserve(binding.uniformIds.size());
				BOOST_FOREACH(const std::string &uniformId, binding.uniformIds)
				{
					data.uniformIds.push_back(UniformBindingData(uniformId));
				}

				return data;
			}

			SeparableProgramBindingData operator()(const SeparableProgramBinding &binding) const
			{
				SeparableProgramBindingData data;
				data.pipeline.reserve(binding.pipeline.size());
				gl::GenProgramPipelines(1, &data.pipelineObj);
				gl::BindProgramPipeline(data.pipelineObj);
				BOOST_FOREACH(const ProgramMask &prog, binding.pipeline)
				{
					data.pipeline.push_back(ProgramMaskData((*this)(prog.prog), prog.stages));

				}
				gl::BindProgramPipeline(0);
				return data;
			}
		};
	}

	void NodeData::DefineStyle( const boost::string_ref &styleName, const StyleInfo &style )
	{
		if(m_styles.find(styleName) != m_styles.end())
			throw StyleMultiplyDefinedException(std::string(styleName.begin(), styleName.end()));

		m_styles.emplace(styleName, StyleData(style.meshResourceId));
		StyleData &data = m_styles.find(styleName)->second;
		data.meshVariantString = style.meshVariantString;

		data.progBinding = boost::apply_visitor(ProgDataExtraction(), style.progBinding);

		data.textureBindings.reserve(style.textureBindings.size());
		BOOST_FOREACH(const TextureBinding &texBinding, style.textureBindings)
		{
			TextureBindingData newBinding(texBinding.textureId, texBinding.samplerId);
			data.textureBindings.emplace(texBinding.textureUnit, newBinding);
		}

		data.imageBindings.reserve(style.imageBindings.size());
		BOOST_FOREACH(const ImageBinding &imgBinding, style.imageBindings)
		{
			ImageBindingData newBinding(imgBinding.textureId);
			newBinding.mipmapLevel = imgBinding.mipmapLevel;
			newBinding.arrayLayer = imgBinding.arrayLayer;
			newBinding.access = imgBinding.access;
			newBinding.format = imgBinding.format;
			data.imageBindings.emplace(imgBinding.imageUnit, newBinding);
		}

		data.uniformBufferBindings.reserve(style.uniformBufferBindings.size());
		BOOST_FOREACH(const BufferInterfaceBinding &bufBinding, style.uniformBufferBindings)
		{
			BufferInterfaceBindingData newBinding(bufBinding.bufferId);
			newBinding.bindPoint = bufBinding.bindPoint;
			newBinding.bindOffset = bufBinding.bindOffset;
			data.uniformBufferBindings.push_back(newBinding);
		}

		data.storageBufferBindings.reserve(style.storageBufferBindings.size());
		BOOST_FOREACH(const BufferInterfaceBinding &bufBinding, style.storageBufferBindings)
		{
			BufferInterfaceBindingData newBinding(bufBinding.bufferId);
			newBinding.bindPoint = bufBinding.bindPoint;
			newBinding.bindOffset = bufBinding.bindOffset;
			data.storageBufferBindings.push_back(newBinding);
		}
	}

	const StyleData * NodeData::FindStyle( const IdString &styleId ) const
	{
		StyleMap::const_iterator theIt = m_styles.find(styleId);
		return theIt != m_styles.end() ? &theIt->second : NULL;
	}
}


text:
//---------------------------------------------------------------------------//
// Copyright (c) 2013-2014 Kyle Lutz <kyle.r.lutz@gmail.com>
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
// See http://kylelutz.github.com/compute for more information.
//---------------------------------------------------------------------------//

#ifndef BOOST_COMPUTE_CONTAINER_DYNAMIC_BITSET_HPP
#define BOOST_COMPUTE_CONTAINER_DYNAMIC_BITSET_HPP

#include <boost/compute/lambda.hpp>
#include <boost/compute/algorithm/any_of.hpp>
#include <boost/compute/algorithm/fill.hpp>
#include <boost/compute/algorithm/transform_reduce.hpp>
#include <boost/compute/container/vector.hpp>
#include <boost/compute/functional/integer.hpp>
#include <boost/compute/types/fundamental.hpp>

namespace boost {
namespace compute {

/// \class dynamic_bitset
/// \brief The dynamic_bitset class contains a resizable bit array.
///
/// For example, to create a dynamic-bitset with space for 1000 bits on the
/// device:
/// \code
/// boost::compute::dynamic_bitset<> bits(1000, queue);
/// \endcode
///
/// The Boost.Compute \c dynamic_bitset class provides a STL-like API and is
/// modeled after the \c boost::dynamic_bitset class from Boost.
///
/// \see \ref vector "vector<T>"
template<class Block = ulong_, class Alloc = buffer_allocator<Block> >
class dynamic_bitset
{
public:
    typedef Block block_type;
    typedef Alloc allocator_type;
    typedef vector<Block, Alloc> container_type;
    typedef typename container_type::size_type size_type;

    BOOST_STATIC_CONSTANT(size_type, bits_per_block = sizeof(block_type) * CHAR_BIT);
    BOOST_STATIC_CONSTANT(size_type, npos = static_cast<size_type>(-1));

    /// Creates a new dynamic bitset with storage for \p size bits. Initializes
    /// all bits to zero.
    dynamic_bitset(size_type size, command_queue &queue)
        : m_bits(size / sizeof(block_type), queue.get_context()),
          m_size(size)
    {
        // initialize all bits to zero
        reset(queue);
    }

    /// Creates a new dynamic bitset as a copy of \p other.
    dynamic_bitset(const dynamic_bitset &other)
        : m_bits(other.m_bits),
          m_size(other.m_size)
    {
    }

    /// Copies the data from \p other to \c *this.
    dynamic_bitset& operator=(const dynamic_bitset &other)
    {
        if(this != &other){
            m_bits = other.m_bits;
            m_size = other.m_size;
        }

        return *this;
    }

    /// Destroys the dynamic bitset.
    ~dynamic_bitset()
    {
    }

    /// Returns the size of the dynamic bitset.
    size_type size() const
    {
        return m_size;
    }

    /// Returns the number of blocks to store the bits in the dynamic bitset.
    size_type num_blocks() const
    {
        return m_bits.size();
    }

    /// Returns the maximum possible size for the dynamic bitset.
    size_type max_size() const
    {
        return m_bits.max_size() * bits_per_block;
    }

    /// Returns \c true if the dynamic bitset is empty (i.e. \c size() == \c 0).
    bool empty() const
    {
        return size() == 0;
    }

    /// Returns the number of set bits (i.e. '1') in the bitset.
    size_type count(command_queue &queue) const
    {
        ulong_ count = 0;
        transform_reduce(
            m_bits.begin(),
            m_bits.end(),
            &count,
            popcount<block_type>(),
            plus<ulong_>(),
            queue
        );
        return static_cast<size_type>(count);
    }

    /// Resizes the bitset to contain \p num_bits. If the new size is greater
    /// than the current size the new bits are set to zero.
    void resize(size_type num_bits, command_queue &queue)
    {
        // resize bits
        const size_type current_block_count = m_bits.size();
        m_bits.resize(num_bits * bits_per_block, queue);

        // fill new block with zeros (if new blocks were added)
        const size_type new_block_count = m_bits.size();
        if(new_block_count > current_block_count){
            fill_n(
                m_bits.begin() + current_block_count,
                new_block_count - current_block_count,
                block_type(0),
                queue
            );
        }

        // store new size
        m_size = num_bits;
    }

    /// Sets the bit at position \p n to \c true.
    void set(size_type n, command_queue &queue)
    {
        set(n, true, queue);
    }

    /// Sets the bit at position \p n to \p value.
    void set(size_type n, bool value, command_queue &queue)
    {
        const size_type bit = n % bits_per_block;
        const size_type block = n / bits_per_block;

        // load current block
        block_type block_value;
        copy_n(m_bits.begin() + block, 1, &block_value, queue);

        // update block value
        if(value){
            block_value |= (size_type(1) << bit);
        }
        else {
            block_value &= ~(size_type(1) << bit);
        }

        // store new block
        copy_n(&block_value, 1, m_bits.begin() + block, queue);
    }

    /// Returns \c true if the bit at position \p n is set (i.e. '1').
    bool test(size_type n, command_queue &queue)
    {
        const size_type bit = n % (sizeof(block_type) * CHAR_BIT);
        const size_type block = n / (sizeof(block_type) * CHAR_BIT);

        block_type block_value;
        copy_n(m_bits.begin() + block, 1, &block_value, queue);

        return block_value & (size_type(1) << bit);
    }

    /// Flips the value of the bit at position \p n.
    void flip(size_type n, command_queue &queue)
    {
        set(n, !test(n, queue), queue);
    }

    /// Returns \c true if any bit in the bitset is set (i.e. '1').
    bool any(command_queue &queue) const
    {
        return any_of(
            m_bits.begin(), m_bits.end(), lambda::_1 != block_type(0), queue
        );
    }

    /// Returns \c true if all of the bits in the bitset are set to zero.
    bool none(command_queue &queue) const
    {
        return !any(queue);
    }

    /// Sets all of the bits in the bitset to zero.
    void reset(command_queue &queue)
    {
        fill(m_bits.begin(), m_bits.end(), block_type(0), queue);
    }

    /// Sets the bit at position \p n to zero.
    void reset(size_type n, command_queue &queue)
    {
        set(n, false, queue);
    }

    /// Empties the bitset (e.g. \c resize(0)).
    void clear()
    {
        m_bits.clear();
    }

    /// Returns the allocator used to allocate storage for the bitset.
    allocator_type get_allocator() const
    {
        return m_bits.get_allocator();
    }

private:
    container_type m_bits;
    size_type m_size;
};

} // end compute namespace
} // end boost namespace

#endif // BOOST_COMPUTE_CONTAINER_DYNAMIC_BITSET_HPP

max_stars_repo_name: skozilla/compute

max_issues_repo_name: junmuz/compute

max_forks_repo_name: junmuz/compute


text:
#pragma once

#include <optional>
#include <utility>
#include <vector>

#include <boost/predef.h>

// Prevent some old features from being defined.
// See also https://www.boost.org/doc/libs/1_66_0/libs/filesystem/doc/index.htm.
#define BOOST_FILESYSTEM_NO_DEPRECATED
#include <boost/filesystem.hpp>

#if BOOST_OS_LINUX
#include <dirent.h> // for iter_dir()
#endif

/**
 * Wrapepr library of Boost.Filesystem
 */
namespace lib::filesystem
{

namespace boost_fs = boost::filesystem;

using u8string = std::string;

/**
 * Wrapper structure of boost::filesystem::path.
 *
 * - No implicit conversion from/to string classes and char arrays.
 *   - Exception: UTF-8 string literals is implicitly convertible to `path`.
 * - Some destructive methods are changed to non-destructive.
 */
struct path
{
    using inner_type = boost_fs::path;
    using value_type = inner_type::value_type;
    using string_type = inner_type::string_type;

    path()
        : _inner()
    {
    }

    ~path() = default;
    path(const path&) = default;
    path(path&&) noexcept = default;
    path& operator=(const path&) = default;
    path& operator=(path&&) noexcept = default;

    /**
     * Construct path from a string literal.
     */
    template <size_t N>
    /* explicit(false) */ path(const u8string::value_type (&u8str)[N])
        : path(from_u8string(u8str))
    {
    }

    explicit path(const inner_type& inner)
        : _inner(inner)
    {
    }

    explicit path(inner_type&& inner)
        : _inner(std::move(inner))
    {
    }

    static path from_u8string(const u8string& u8str);
    static path from_u8string(u8string&& u8str);
    static path from_u8string(const u8string::value_type* u8str);

    static path from_native_string(const string_type& native_string)
    {
        return path(inner_type(native_string));
    }

    static path from_native_string(string_type&& native_string)
    {
        return path(inner_type(std::move(native_string)));
    }

    static path from_native_string(const value_type* native_string)
    {
        return path(inner_type(native_string));
    }

    u8string to_u8string() const;

    bool empty() const
    {
        return inner().empty();
    }

    size_t size() const noexcept
    {
        return inner().size();
    }

    decltype(auto) native() const noexcept
    {
        return inner().native();
    }

    path filename() const
    {
        return path(inner().filename());
    }

    path extension() const
    {
        return path(inner().extension());
    }

    path parent_path() const
    {
        return path(inner().parent_path());
    }

    bool has_filename() const
    {
        return inner().has_filename();
    }

    /**
     * Returns *a new instance* without filename.
     */
    path remove_filename() const
    {
        auto tmp = inner();
        tmp.remove_filename();
        return path(tmp);
    }

    /**
     * Returns *a new instance* with no extension.
     */
    path remove_extension() const
    {
        auto tmp = inner();
        tmp.replace_extension();
        return path(tmp);
    }

    bool operator==(const path& other) const
    {
        return inner() == other.inner();
    }

    bool operator!=(const path& other) const
    {
        return !(*this == other);
    }

    path operator/(const path& path_segment) const
    {
        return path(inner() / path_segment.inner());
    }

    const inner_type& inner() const noexcept
    {
        return _inner;
    }

    operator inner_type() const noexcept
    {
        return inner();
    }

private:
    inner_type _inner;
};

/**
 * Short-hand for `path::from_u8string()`.
 */
inline path u8path(const u8string& u8str)
{
    return path::from_u8string(u8str);
}

/**
 * Short-hand for `path::from_u8string()`.
 */
inline path u8path(u8string&& u8str)
{
    return path::from_u8string(std::move(u8str));
}

/**
 * Short-hand for `path::from_u8string()`.
 */
inline path u8path(const u8string::value_type* u8str)
{
    return path::from_u8string(u8str);
}

/**
 * Get the executable path for various platforms.
 *
 * @return The executable on success; none on failure.
 */
std::optional<path> get_executable_path();

/**
 * Check if @a filename is portable on many platforms. It returns the same
 * result for the same @a filename regardless of the platform where you compile
 * this file and the program runs.
 *
 * @param filename The filename to check
 * @returns True if @a filename is portable; otherwise, false.
 */
bool is_portable_path(const path& filename);

/**
 * Check if @a file is contained in @a base_dir.
 */
bool file_contained_in_dir(const path& file, const path& base_dir);

inline path canonical(const path& p)
{
    return path(boost_fs::canonical(p));
}

inline path relative(const path& p, const path& base_dir)
{
    return path(boost_fs::relative(p, base_dir));
}

// Import boost::filesystem functions/enums.
using boost_fs::copy_file;
using boost_fs::create_directories;
using boost_fs::create_directory;
using boost_fs::exists;
using boost_fs::is_directory;
using boost_fs::is_regular_file;
using boost_fs::remove;
using boost_fs::remove_all;
using boost_fs::rename;

using boost_fs::copy_option;

struct dir_entry
{
    dir_entry(const path& path)
        : _path(path)
    {
    }

    struct path path() const
    {
        return _path;
    }

private:
    struct path _path;
};

template <typename F>
std::vector<dir_entry> iter_dir(const path& base_dir, F predicate)
{
// boost::filesystem::directory_iterator does not work properly on Linux.
// See commit message of ce30879c9b73ad9b21f749efc9861dbfb79b0cc6 for details.
#if BOOST_OS_LINUX
    /* Linux */

    std::vector<dir_entry> entries;

    struct dirent* entry = nullptr;
    DIR* dp = opendir(base_dir.native().c_str());
    if (dp)
    {
        while ((entry = readdir(dp)))
        {
            const auto p = base_dir / path::from_native_string(entry->d_name);
            if (!predicate(p))
            {
                continue;
            }
            entries.emplace_back(p);
        }
        closedir(dp);
    }

    return entries;

#else
    /* Windows and macOS */

    std::vector<dir_entry> entries;

    for (const auto& entry : boost_fs::directory_iterator{base_dir})
    {
        const auto p = path(entry.path());
        if (!predicate(p))
        {
            continue;
        }
        entries.emplace_back(p);
    }

    return entries;
#endif
}

inline std::vector<dir_entry> iter_dir(const path& base_dir)
{
    return iter_dir(base_dir, [](const auto&) { return true; });
}

// Emulates std::filesystem::copy_options::recursive in C++17.
void copy_recursively(const path& source, const path& destination);

} // namespace lib::filesystem

// Hash support for path
namespace std
{

template <>
struct hash<::lib::filesystem::path>
{
    size_t operator()(const ::lib::filesystem::path& key) const
    {
        return hash<::lib::filesystem::path::string_type>()(key.native());
    }
};

} // namespace std


text:
// Copyright (c) 2019-2021 Duality Blockchain Solutions Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "dht/limits.h"

#include "bdap/domainentrydb.h"
#include "bdap/linkingdb.h"
#include "chain.h"
#include "utilstrencodings.h"
#include "tinyformat.h"

#include <boost/algorithm/string.hpp>

#include <map>
#include <vector>

//  Default accepted DHT record types:
std::multimap<std::string, CAllowDataCode> mapAllowedData = {
    //name                          salt,        slots,  start,   expire
    {"info",        CAllowDataCode("info",       32,     0,       0)},
    {"denylink",    CAllowDataCode("denylink",   32,     0,       0)},
    {"ignore",      CAllowDataCode("ignore",     32,     0,       0)},
    {"index",       CAllowDataCode("index",      32,     0,       0)},
    {"avatar",      CAllowDataCode("avatar",      4,     0,       0)},
    {"ldap",        CAllowDataCode("ldap",       32,     0,       0)},
    {"oauth",       CAllowDataCode("oauth",      16,     0,       0)},
    {"pshare",      CAllowDataCode("pshare",     48,     0,       0)},
    {"pconsult",    CAllowDataCode("pconsult",   48,     0,       0)},
    {"noid",        CAllowDataCode("noid",       48,     0,       0)},
    {"whispers",    CAllowDataCode("whispers",   48,     0,       0)},
    {"spam",        CAllowDataCode("spam",       64,     0,       0)},
    {"groups",      CAllowDataCode("groups",     48,     0,       0)},
    {"chat",        CAllowDataCode("chat",       32,     0,       0)},
    {"message",     CAllowDataCode("message",    32,     0,       0)},
    {"data",        CAllowDataCode("data",      128,     0,       0)},
    {"keys",        CAllowDataCode("keys",       32,     0,       0)},
    {"test",        CAllowDataCode("test",        8,     0,       0)},
    {"ice",         CAllowDataCode("ice",        24,     0,       0)},
    {"webrtc",      CAllowDataCode("webrtc",     16,     0,       0)},
    {"webbridge",   CAllowDataCode("webbridge",  48,     0,       0)},
    {"status",      CAllowDataCode("status",      2,     0,       0)},
    {"verity",      CAllowDataCode("verity",     48,     0,       0)},
    {"unity",       CAllowDataCode("unity",      48,     0,       0)},
    {"ping",        CAllowDataCode("ping",        1,     0,       0)},
};

bool CheckSalt(const std::string& strSalt, const unsigned int nHeight, std::string& strErrorMessage)
{
    strErrorMessage = "";
    std::vector<std::string> vSplit;
    boost::split(vSplit, strSalt, boost::is_any_of(":"));
    if (vSplit.size() != 2) {
        strErrorMessage = strprintf("Invalid salt (%s). Could not find ':' delimiter\n", strSalt);
        return false;
    }
    uint32_t nSlots;
    if (!ParseUInt32(vSplit[1], &nSlots)) {
        strErrorMessage = strprintf("Invalid salt (%s). Could not parse slot number after : %s\n", strSalt, vSplit[1]);
        return false;
    }
    std::multimap<std::string, CAllowDataCode>::iterator iAllowed = mapAllowedData.find(vSplit[0]);
    while (iAllowed != mapAllowedData.end()) {
        if (iAllowed->second.nStartHeight > nHeight) {
            strErrorMessage = strprintf("%sAllow data type found but height (%d) is greater than allowed data start height %d.\n", strErrorMessage, nHeight, iAllowed->second.nStartHeight);
            iAllowed++;
            continue;
        }
        if (nHeight > iAllowed->second.nExpireTime && iAllowed->second.nExpireTime != 0) {
            strErrorMessage = strprintf("%sAllow data type found but expired %d.\n", strErrorMessage, iAllowed->second.nExpireTime);
            iAllowed++;
            continue;
        }
        if ((uint16_t)nSlots > iAllowed->second.nMaximumSlots) {
            strErrorMessage = strprintf("%sAllow data type found but too many slots (%d) used. Max slots = %d\n", strErrorMessage, nSlots, iAllowed->second.nMaximumSlots);
            iAllowed++;
            continue;
        }
        return true;
    }
    strErrorMessage = strprintf("%sInvalid salt (%s). Allow data type salt not found in allowed data map.", strErrorMessage, vSplit[0]);
    return false;
}

bool CheckPubKey(const std::vector<unsigned char>& vchPubKey)
{
    bool fAccountPubkey = AccountPubKeyExists(vchPubKey);
    bool fLinkPubkey = LinkPubKeyExists(vchPubKey);
    if (fAccountPubkey || fLinkPubkey)
        return true;

    return false;
}

uint16_t GetMaximumSlots(const std::string& salt)
{
    std::multimap<std::string, CAllowDataCode>::iterator iRecord = mapAllowedData.find(salt);
    if (iRecord != mapAllowedData.end())
        return iRecord->second.nMaximumSlots;

    return 0;
}

max_stars_repo_name: AmirAbrams/dynamic-swap

max_issues_repo_name: AmirAbrams/dynamic-swap


text:
//
//  Copyright Silvin Lubecki 2010
//
//  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 "depend_pch.h"
#include "IncludeVisitor.h"
#include "IncludeObserver_ABC.h"
#include <boost/foreach.hpp>

using namespace depend;
using namespace boost::xpressive;

// -----------------------------------------------------------------------------
// Name: IncludeVisitor constructor
// Created: SLI 2010-08-17
// -----------------------------------------------------------------------------
IncludeVisitor::IncludeVisitor( Subject< UncommentedLineObserver_ABC >& visitor )
    : Observer< UncommentedLineObserver_ABC >( visitor )
{
    // NOTHING
}

// -----------------------------------------------------------------------------
// Name: IncludeVisitor destructor
// Created: SLI 2010-08-17
// -----------------------------------------------------------------------------
IncludeVisitor::~IncludeVisitor()
{
    // NOTHING
}

// -----------------------------------------------------------------------------
// Name: IncludeVisitor::NotifyUncommentedLine
// Created: SLI 2010-08-17
// -----------------------------------------------------------------------------
void IncludeVisitor::NotifyUncommentedLine( const std::string& line, const std::string& context )
{
    const mark_tag internal_tag( 1 );
    const mark_tag external_tag( 2 );
    const sregex spaces = *space;
    const sregex keyword = "#" >> spaces >> "include";
    const sregex rule = keyword >> spaces >>
                        ( ( '\"' >> ( internal_tag = ( *_ ) ) >> '\"' )
                        | ( '<'  >> ( external_tag = ( *_ ) ) >> '>' ) );
    sregex_iterator it( line.begin(), line.end(), rule );
    sregex_iterator end;
    if( it != end )
    {
        BOOST_FOREACH( T_Observers::value_type& observer, observers_ )
        {
            if( !std::string( (*it)[ internal_tag ] ).empty() )
                observer->NotifyInternalInclude( (*it)[ internal_tag ], context ); // $$$$ _RC_ SLI 2010-08-19: seperate in two different visitors
            else
                observer->NotifyExternalInclude( (*it)[ external_tag ], context );
        }
    }
}

max_stars_repo_name: vinsle/dependency-analysis

max_issues_repo_name: vinsle/dependency-analysis

max_forks_repo_name: vinsle/dependency-analysis


text:
//==============================================================================
//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//         Copyright 2012 - 2013   MetaScale SAS
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#include <boost/simd/memory/iterator_category.hpp>
#include <boost/dispatch/meta/nth_hierarchy.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/mpl/int.hpp>

#include <nt2/sdk/unit/module.hpp>
#include <nt2/sdk/unit/tests/type_expr.hpp>

NT2_TEST_CASE(void_ptr)
{
  using boost::mpl::_;
  using boost::mpl::int_;
  using boost::dispatch::meta::nth_hierarchy;
  using boost::dispatch::meta::generic_;
  using boost::dispatch::meta::iterator_;
  using boost::dispatch::meta::void_;

  void* p = 0;
  void* const pc = 0;

  NT2_TEST_EXPR_TYPE( p
                    , (nth_hierarchy<_, int_<0> >)
                    , iterator_<generic_<void_<void*> > >
                    );

  NT2_TEST_EXPR_TYPE( pc
                    , (nth_hierarchy<_, int_<0> >)
                    , iterator_<generic_<void_<void*> > >
                    );
}

NT2_TEST_CASE(typed_ptr)
{
  using boost::dispatch::meta::nth_hierarchy;
  using boost::dispatch::meta::unspecified_;
  using boost::dispatch::meta::iterator_;
  using boost::dispatch::meta::scalar_;
  using boost::dispatch::meta::single_;
  using boost::mpl::int_;
  using boost::mpl::_;

  float*       p = 0;
  float const*  c = 0;
  float* BOOST_DISPATCH_RESTRICT r = 0;
  float const * BOOST_DISPATCH_RESTRICT q = 0;

  NT2_TEST_EXPR_TYPE( p , (nth_hierarchy<_, int_<0> >), iterator_< scalar_< single_<float*> > >  );
  NT2_TEST_EXPR_TYPE( p , (nth_hierarchy<_, int_<16> >), iterator_< unspecified_<float*> >  );

  NT2_TEST_EXPR_TYPE( c , (nth_hierarchy<_, int_<0> >), iterator_< scalar_< single_<float const*> > >  );
  NT2_TEST_EXPR_TYPE( c , (nth_hierarchy<_, int_<16> >), iterator_< unspecified_<float const*> >  );

  NT2_TEST_EXPR_TYPE( r , (nth_hierarchy<_, int_<0> >), iterator_< scalar_< single_<float* BOOST_DISPATCH_RESTRICT> > > );
  NT2_TEST_EXPR_TYPE( r , (nth_hierarchy<_, int_<16> >), iterator_< unspecified_<float* BOOST_DISPATCH_RESTRICT> > );

  NT2_TEST_EXPR_TYPE( q , (nth_hierarchy<_, int_<0> >), iterator_< scalar_< single_<float const* BOOST_DISPATCH_RESTRICT> > > );
  NT2_TEST_EXPR_TYPE( q , (nth_hierarchy<_, int_<16> >), iterator_< unspecified_<float const* BOOST_DISPATCH_RESTRICT> > );
}

NT2_TEST_CASE(typed_ptr_const)
{
  using boost::dispatch::meta::nth_hierarchy;
  using boost::dispatch::meta::unspecified_;
  using boost::dispatch::meta::iterator_;
  using boost::dispatch::meta::scalar_;
  using boost::dispatch::meta::single_;
  using boost::mpl::int_;
  using boost::mpl::_;

  float* const       p = 0;
  float const*  const c = 0;
  float* const BOOST_DISPATCH_RESTRICT r = 0;
  float const * const BOOST_DISPATCH_RESTRICT q = 0;

  NT2_TEST_EXPR_TYPE( p
                    , (nth_hierarchy<_, int_<0> >)
                    , iterator_< scalar_< single_<float*> > >
                    );

  NT2_TEST_EXPR_TYPE( p
                    , (nth_hierarchy<_, int_<16> >)
                    , iterator_< unspecified_<float*> >
                    );

  NT2_TEST_EXPR_TYPE( c
                    , (nth_hierarchy<_, int_<0> >)
                    , iterator_< scalar_< single_<float const*> > >
                    );

  NT2_TEST_EXPR_TYPE( c
                    , (nth_hierarchy<_, int_<16> >)
                    , iterator_< unspecified_<float const*> >
                    );

  NT2_TEST_EXPR_TYPE( r
                    , (nth_hierarchy<_, int_<0> >)
                    , iterator_< scalar_< single_<float* BOOST_DISPATCH_RESTRICT> > >
                    );

  NT2_TEST_EXPR_TYPE( r
                    , (nth_hierarchy<_, int_<16> >)
                    , iterator_< unspecified_<float* BOOST_DISPATCH_RESTRICT> >
                    );

  NT2_TEST_EXPR_TYPE( q , (nth_hierarchy<_, int_<0> >), iterator_< scalar_< single_<float const* BOOST_DISPATCH_RESTRICT> > > );
  NT2_TEST_EXPR_TYPE( q , (nth_hierarchy<_, int_<16> >), iterator_< unspecified_<float const* BOOST_DISPATCH_RESTRICT> > );
}


text:
//=====================================================================//
/*!	@file
	@brief	JPEG 画像を扱うクラス
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2017 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/glfw3_app/blob/master/LICENSE
*/
//=====================================================================//
#include <cstdio>
#include <cstdlib>
extern "C" {
#include <jpeglib.h>
#include <jerror.h>
/// #include <turbojpeg.h>
};
#include "utils/file_io.hpp"
#include "jpeg_io.hpp"
#include <boost/lexical_cast.hpp>
#include <iostream>

namespace img {

	static const size_t INPUT_BUF_SIZE = 4096;

	struct fio_src_mgr {
		struct jpeg_source_mgr	pub;		// public fields

		utils::file_io*	infile;				// source stream

		JOCTET*			buffer;
		bool			start_of_file;
		bool			err_empty;
		bool			wrn_eof;
	};

	typedef fio_src_mgr* fio_src_ptr;

	METHODDEF(void) init_source(j_decompress_ptr cinfo)
	{
		fio_src_ptr src = (fio_src_ptr) cinfo->src;

		/* We reset the empty-input-file flag for each image,
		 * but we don't clear the input buffer.
		 * This is correct behavior for reading a series of images from one source.
		 */
		src->start_of_file = true;

		src->err_empty = false;
		src->wrn_eof = false;
	}

	METHODDEF(boolean) fill_input_buffer(j_decompress_ptr cinfo)
	{
		fio_src_ptr src = (fio_src_ptr)cinfo->src;

		size_t nbytes = src->infile->read(src->buffer, 1, INPUT_BUF_SIZE);
		if(nbytes == 0) {
			if(src->start_of_file) {
				// Treat empty input file as fatal error
//				ERREXIT(cinfo, JERR_INPUT_EMPTY);
				src->err_empty = true;
			}
//			WARNMS(cinfo, JWRN_JPEG_EOF);
			src->wrn_eof = true;

			// Insert a fake EOI marker
			src->buffer[0] = (JOCTET) 0xFF;
			src->buffer[1] = (JOCTET) JPEG_EOI;
			nbytes = 2;
		}

		src->pub.next_input_byte = src->buffer;
		src->pub.bytes_in_buffer = nbytes;
		src->start_of_file = false;

		return TRUE;
	}

	METHODDEF(void) skip_input_data(j_decompress_ptr cinfo, long num_bytes)
	{
		fio_src_ptr src = (fio_src_ptr)cinfo->src;

		/* Just a dumb implementation for now.  Could use fseek() except
		 * it doesn't work on pipes.  Not clear that being smart is worth
		 * any trouble anyway --- large skips are infrequent.
		 */
		if(num_bytes > 0) {
			while(num_bytes > (long) src->pub.bytes_in_buffer) {
				num_bytes -= (long) src->pub.bytes_in_buffer;
				(void)fill_input_buffer(cinfo);
				/* note we assume that fill_input_buffer will never return FALSE,
				 * so suspension need not be handled.
				 */
			}
			src->pub.next_input_byte += (size_t) num_bytes;
			src->pub.bytes_in_buffer -= (size_t) num_bytes;
		}
	}

	METHODDEF(void) term_source(j_decompress_ptr cinfo)
	{
	}

	static GLOBAL(void) fio_jpeg_file_io_src(j_decompress_ptr cinfo, utils::file_io* infile)
	{
		if(cinfo->src == NULL) {	/* first time for this JPEG object? */
			cinfo->src = (struct jpeg_source_mgr *)
				(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
				sizeof(fio_src_mgr));
			fio_src_ptr src = (fio_src_ptr) cinfo->src;
			src->buffer = (JOCTET *)
			(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
				INPUT_BUF_SIZE * sizeof(JOCTET));
		}

		fio_src_ptr src = (fio_src_ptr) cinfo->src;
		src->pub.init_source		= init_source;
		src->pub.fill_input_buffer	= fill_input_buffer;
		src->pub.skip_input_data	= skip_input_data;
		src->pub.resync_to_restart	= jpeg_resync_to_restart;	// use default method
		src->pub.term_source		= term_source;
		src->infile					= infile;
		src->pub.bytes_in_buffer = 0;		// forces fill_input_buffer on first read
		src->pub.next_input_byte = NULL;	// until buffer loaded
	}

	static const size_t OUTPUT_BUF_SIZE = 4096;

	struct fio_dst_mgr {
		struct jpeg_destination_mgr	pub;	// public fields

		utils::file_io*	outfile;			// output stream

		JOCTET*			buffer;
		bool			error;
	};

	typedef fio_dst_mgr* fio_dst_ptr;

	METHODDEF(void) init_destination(j_compress_ptr cinfo)
	{
		fio_dst_ptr dst = (fio_dst_ptr) cinfo->dest;

		dst->pub.next_output_byte = dst->buffer;
		dst->pub.free_in_buffer = OUTPUT_BUF_SIZE;

		dst->error = false;
	}

	METHODDEF(boolean) empty_output_buffer(j_compress_ptr cinfo)
	{
		fio_dst_ptr dst = (fio_dst_ptr)cinfo->dest;

		size_t n = dst->outfile->write(dst->buffer, 1, OUTPUT_BUF_SIZE);
		if(n != OUTPUT_BUF_SIZE) {
			dst->error = true;
		}
		dst->pub.free_in_buffer = OUTPUT_BUF_SIZE;
		dst->pub.next_output_byte = dst->buffer;

		if(dst->error) return FALSE;

		return TRUE;
	}

	METHODDEF(void) term_destination(j_compress_ptr cinfo)
	{
		fio_dst_ptr dst = (fio_dst_ptr)cinfo->dest;

		size_t ws = OUTPUT_BUF_SIZE - dst->pub.free_in_buffer;
		size_t n = dst->outfile->write(dst->buffer, 1, ws);
		if(n != ws) {
			dst->error = true;
		}
	}

	static GLOBAL(void) fio_jpeg_file_io_dst(j_compress_ptr cinfo, utils::file_io* outfile)
	{
		if(cinfo->dest == NULL) {	/* first time for this JPEG object? */
			cinfo->dest = (struct jpeg_destination_mgr *)
				(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
				sizeof(fio_dst_mgr));
			fio_dst_ptr dst = (fio_dst_ptr) cinfo->dest;
			dst->buffer = (JOCTET *)
			(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
				OUTPUT_BUF_SIZE * sizeof(JOCTET));
		}

		fio_dst_ptr dst = (fio_dst_ptr) cinfo->dest;
		dst->pub.init_destination    = init_destination;
		dst->pub.empty_output_buffer = empty_output_buffer;
		dst->pub.term_destination    = term_destination;
		dst->pub.next_output_byte    = NULL;
		dst->pub.free_in_buffer      = 0;
		dst->outfile                 = outfile;

		dst->error = false;
	}

	static volatile int error_code_;

	METHODDEF(void) error_exit_task(jpeg_common_struct *st)
	{
		error_code_ = 1;
	}

#if 0
	//-----------------------------------------------------------------//
	/*!
		@brief	初期化
	*/
	//-----------------------------------------------------------------//
	void jpeg_io::initialize()
	{
#ifdef __PPU__
		int ret = cellSysmoduleLoadModule(CELL_SYSMODULE_JPGDEC);
		if(ret != CELL_OK){
			std::cout << "Can't load jpeg module...." << std::endl;
			return;
		}
#endif
	}
#endif

	//-----------------------------------------------------------------//
	/*!
		@brief	JPEG ファイルか確認する
		@param[in]	fin	file_io クラス
		@return エラーなら「false」を返す
	*/
	//-----------------------------------------------------------------//
	bool jpeg_io::probe(utils::file_io& fin)
	{
		unsigned char sig[2];
		long pos = fin.tell();
		size_t l = fin.read(sig, 1, 2);
		fin.seek(pos, utils::file_io::SEEK::SET);
		if(l == 2) {
			if(sig[0] == 0xff && sig[1] == 0xd8) {
				return true;
			}
		}
		return false;
	}

	//-----------------------------------------------------------------//
	/*!
		@brief	画像ファイルの情報を取得する
		@param[in]	fin	file_io クラス
		@param[in]	fo	情報を受け取る構造体
		@return エラーなら「false」を返す
	*/
	//-----------------------------------------------------------------//
	bool jpeg_io::info(utils::file_io& fin, img::img_info& fo)
	{
		if(!probe(fin)) {
			return false;
		}

		struct jpeg_decompress_struct cinfo;
		struct jpeg_error_mgr errmgr;

		long pos = fin.tell();
std::cout << "info: " << pos << std::endl;
		// エラーのハンドリング
		cinfo.err = jpeg_std_error(&errmgr);
		errmgr.error_exit = error_exit_task;

	    // 構造体の初期設定
		jpeg_create_decompress(&cinfo);

		// file_io クラス設定
		fio_jpeg_file_io_src(&cinfo, &fin);

		// ファイルの情報ヘッダの読込み
		error_code_ = 0;
		jpeg_read_header(&cinfo, TRUE);
		fin.seek(pos, utils::file_io::SEEK::SET);

		if(error_code_) {
///			std::endl << "JPEG decode error: 'header'(" << static_cast<int>(error_code_) << ")" << std::endl;
			jpeg_destroy_decompress(&cinfo);
			return false;
		}

		fo.width = cinfo.output_width;
		fo.height = cinfo.output_height;
		fo.mipmap_level = 0;
		fo.multi_level = 0;
		fo.i_depth = 0;

		if(cinfo.output_components == 4) {
			fo.r_depth = 8;
			fo.g_depth = 8;
			fo.b_depth = 8;
			fo.a_depth = 8;
			fo.grayscale = false;
		} else if(cinfo.output_components == 3) {
			fo.r_depth = 8;
			fo.g_depth = 8;
			fo.b_depth = 8;
			fo.a_depth = 0;
			fo.grayscale = false;
		} else if(cinfo.output_components == 2) {
			fo.r_depth = 8;
			fo.g_depth = 8;
			fo.b_depth = 8;
			fo.a_depth = 8;
			fo.grayscale = true;
		} else if(cinfo.output_components == 1) {
			fo.r_depth = 8;
			fo.g_depth = 8;
			fo.b_depth = 8;
			fo.a_depth = 0;
			fo.grayscale = true;
		} else {
			fo.r_depth = 0;
			fo.g_depth = 0;
			fo.b_depth = 0;
			fo.a_depth = 0;
			fo.grayscale = false;
			return false;
		}

		return true;
	}

	//-----------------------------------------------------------------//
	/*!
		@brief	JPEG ファイル、ロード
		@param[in]	fin	file_io クラス
		@param[in]	opt	フォーマット固有の設定文字列
		@return エラーなら「false」を返す
	*/
	//-----------------------------------------------------------------//
	bool jpeg_io::load(utils::file_io& fin, const std::string& opt)
	{
		// とりあえず、ヘッダーの検査
		if(probe(fin) == false) {
			return false;
		}

		struct jpeg_decompress_struct cinfo;
		struct jpeg_error_mgr errmgr;

		// エラーのハンドリング
		cinfo.err = jpeg_std_error(&errmgr);
		errmgr.error_exit = error_exit_task;

	    // 構造体の初期設定
		jpeg_create_decompress(&cinfo);

		// file_io クラス設定
		fio_jpeg_file_io_src(&cinfo, &fin);

		// ファイルの情報ヘッダの読込み
		error_code_ = 0;
		jpeg_read_header(&cinfo, TRUE);
		if(error_code_) {
			std::cout << "JPEG decode error: 'header' (" << error_code_ << ")" << std::endl;
			jpeg_destroy_decompress(&cinfo);
			return false;
		}

		// 解凍の開始
		error_code_ = 0;
		jpeg_start_decompress(&cinfo);
		if(error_code_) {
			std::cout << "JPEG decode error: 'decompress' (" << error_code_ << ")" << std::endl;
			jpeg_finish_decompress(&cinfo);
			jpeg_destroy_decompress(&cinfo);
			return false;
		}

		/// cinfo.in_color_space
		if(cinfo.output_components == 1) {
			img_ = shared_img(new img_rgba8);
			img_->create(vtx::spos(cinfo.image_width, cinfo.image_height), true);
		} else if(cinfo.output_components == 3) {
			img_ = shared_img(new img_rgba8);
			img_->create(vtx::spos(cinfo.image_width, cinfo.image_height), true);
		} else if(cinfo.output_components == 4) {
			img_ = shared_img(new img_rgba8);
			img_->create(vtx::spos(cinfo.image_width, cinfo.image_height), true);
		} else {
			img_ = 0;
			std::cout << "JPEG decode error: Can not support components: " <<
				static_cast<int>(cinfo.output_components) << std::endl;
			jpeg_finish_decompress(&cinfo);
			jpeg_destroy_decompress(&cinfo);
			return false;
		}

		prgl_ref_ = cinfo.image_height;
		prgl_pos_ = 0;

		unsigned char* line = new unsigned char[cinfo.output_width * cinfo.output_components];
		unsigned char* lines[1];
		lines[0] = &line[0];
		vtx::spos pos;
		for(pos.y = 0; pos.y < cinfo.image_height; ++pos.y) {
			jpeg_read_scanlines(&cinfo, (JSAMPLE**)lines, 1);
			unsigned char* p = &line[0];
			if(cinfo.output_components == 4) {
				for(pos.x = 0; pos.x < cinfo.image_width; ++pos.x) {
					img::rgba8 c;
					c.r = *p++;
					c.g = *p++;
					c.b = *p++;
					c.a = *p++;
					img_->put_pixel(pos, c);
				}
			} else if(cinfo.output_components == 3) {
				for(pos.x = 0; pos.x < cinfo.image_width; ++pos.x) {
					img::rgba8 c;
					c.r = *p++;
					c.g = *p++;
					c.b = *p++;
					c.a = 255;
					img_->put_pixel(pos, c);
				}
			} else if(cinfo.output_components == 1) {
				for(pos.x = 0; pos.x < cinfo.image_width; ++pos.x) {
					img::rgba8 c;
					c.b = c.g = c.r = *p++;
					c.a = 255;
					img_->put_pixel(pos, c);
				}
			}
			prgl_pos_ = pos.y;
		}
		delete[] line;

		jpeg_finish_decompress(&cinfo);
		jpeg_destroy_decompress(&cinfo);

		fio_src_ptr src = (fio_src_ptr)cinfo.src;
		if(src->err_empty) {
			return false;
		} else {
			return true;
		}
	}

	//-----------------------------------------------------------------//
	/*!
		@brief	JPEG ファイルをセーブする
		@param[in]	fout	file_io クラス
		@param[in]	opt	フォーマット固有の設定文字列
		@return エラーがあれば「false」
	*/
	//-----------------------------------------------------------------//
	bool jpeg_io::save(utils::file_io& fout, const std::string& opt)
	{
		if(!img_) return false;
		if(img_->get_size().x == 0 || img_->get_size().y == 0) return false;

		int q = 75;
		// 0 to 100
		if(!opt.empty()) {
			try {
				q = boost::lexical_cast<int>(opt);
			} catch (boost::bad_lexical_cast&) {
				q = 75;
			}
		}

		struct jpeg_compress_struct cinfo;
		struct jpeg_error_mgr errmgr;

		// エラーのハンドリング
		cinfo.err = jpeg_std_error(&errmgr);
//		errmgr.error_exit = NULL;

		// 構造体の初期設定
		jpeg_create_compress(&cinfo);

		// file_io クラス設定
		fio_jpeg_file_io_dst(&cinfo, &fout);
		fio_dst_ptr dst = (fio_dst_ptr)cinfo.dest;

		int w = img_->get_size().x;
		int h = img_->get_size().y;

		prgl_ref_ = h;
		prgl_pos_ = 0;

		cinfo.image_width  = w;
		cinfo.image_height = h;
#if (defined JCS_ALPHA_EXTENSIONS)
		if(img_->test_alpha()) {
			cinfo.input_components = 4;
			cinfo.in_color_space = JCS_EXT_RGBA;

		} else {
			cinfo.input_components = 3;
			cinfo.in_color_space = JCS_RGB;
		}
#else
		cinfo.input_components = 3;
		cinfo.in_color_space = JCS_RGB;
#endif
		jpeg_set_defaults(&cinfo);
		jpeg_set_quality(&cinfo, q, TRUE);

		jpeg_start_compress(&cinfo, TRUE);

		JSAMPROW row_pointer[1];
		unsigned char* tmp = new unsigned char[w * cinfo.input_components];
		row_pointer[0] = (JSAMPLE *)tmp;
		vtx::spos pos;
		pos.y = 0;
		while(cinfo.next_scanline < h) {
			unsigned char* p = tmp;
			for(pos.x = 0; pos.x < w; ++pos.x) {
				rgba8 c;
				img_->get_pixel(pos, c);
				*p++ = c.r;
				*p++ = c.g;
				*p++ = c.b;
#if (defined JCS_ALPHA_EXTENSIONS)
				if(img_->test_alpha()) *p++ = c.a;
#endif
			}
			jpeg_write_scanlines(&cinfo, row_pointer, 1);
			if(dst->error) break;
			++pos.y;
			++prgl_pos_;
		}
		delete[] tmp;

		// 圧縮後のサイズ
//		int ret = row_stride * height - cinfo.dest->free_in_buffer;

		jpeg_finish_compress(&cinfo);
		jpeg_destroy_compress(&cinfo);

		if(dst->error) {
			return false;
		} else {
			return true;
		}
	}

}


text:
// gnuplot-c++ includes
#include <gnuplot-iostream.h>

// MLearn includes
#include <MLearn/Core>
#include <MLearn/Sampling/GaussianSampling.h>

// STL includes
#include <vector>
#include <tuple>
#include <string>
#include <cmath>

// Eigen includes
#include <Eigen/Core>
#include <Eigen/SVD>

int main(int argc, char** argv){
	std::srand((unsigned int) time(0));

	Gnuplot gp;

	using namespace MLearn;
	using namespace Sampling::Gaussian;

	typedef double float_type;
	typedef MLMatrix<float_type> Matrix;
	typedef MLVector<float_type> Vector;

	uint DIM = 2;
	uint N = 5000;

	// compute a random covariance matrix
	Matrix random = Matrix::Random(DIM, DIM);
	Eigen::JacobiSVD<Matrix> svd(random,
		Eigen::ComputeFullU | Eigen::ComputeFullV );
	Matrix covariance = svd.matrixU();
	Matrix eig_val = (svd.singularValues().cwiseAbs().cwiseSqrt()).asDiagonal();
	covariance = covariance*eig_val*eig_val;
	covariance = covariance*(svd.matrixU().transpose());
	// compute mean
	Vector mean = Vector::Random(DIM);
	mean.array() -= float_type(0.5);

	// sample
	Matrix samples = MultivariateGaussian<float_type>::sample(
		mean, covariance, N);

	// draw the samples
	std::vector<std::pair<double, double> > xy_pts;
	for(uint i = 0; i < N; ++i) {
		xy_pts.push_back(std::make_pair(samples(0, i), samples(1, i)));
	}
	gp << "set multiplot\n";
	gp << "set xrange [-5:5]\nset yrange [-5:5]\n";
	gp << "plot '-' with points notitle\n";
	gp.send1d(xy_pts);

	gp << "set parametric\n";
	gp << "set trange [0:2*pi]\n";
	gp << "fx(t)=" +
	      std::to_string(svd.matrixU()(0,0)*eig_val(0,0)*1.96) +
	      "*cos(t)+" +
	      std::to_string(svd.matrixU()(0,1)*eig_val(1,1)*1.96) +
	      "*sin(t)+" + std::to_string(mean(0)) + "\n";
	gp << "fy(t) = " +
	      std::to_string(svd.matrixU()(1,0)*eig_val(0,0)*1.96) +
	      "*cos(t) + " +
	      std::to_string(svd.matrixU()(1,1)*eig_val(1,1)*1.96) +
	      "*sin(t) + " + std::to_string(mean(1)) + "\n";
	gp << "plot fx(t), fy(t) linecolor rgb \"blue\" notitle\n";

	return 0;
}

max_stars_repo_name: phineasng/MLearn

max_issues_repo_name: phineasng/MLearn

max_forks_repo_name: phineasng/MLearn


text:
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Regression

#include <fstream>
#include <iostream>

#include <boost/test/unit_test.hpp>

#include <xolotl/core/advection/W111AdvectionHandler.h>
#include <xolotl/core/network/PSIReactionNetwork.h>
#include <xolotl/options/Options.h>
#include <xolotl/test/CommandLine.h>
#include <xolotl/util/MPIUtils.h>

using namespace std;
using namespace xolotl;
using namespace core;
using namespace advection;

using Kokkos::ScopeGuard;
BOOST_GLOBAL_FIXTURE(ScopeGuard);

/**
 * This suite is responsible for testing the W111AdvectionHandler.
 */
BOOST_AUTO_TEST_SUITE(W111AdvectionHandler_testSuite)

/**
 * Method checking the initialization and the compute advection methods.
 */
BOOST_AUTO_TEST_CASE(checkAdvection)
{
	// Create the option to create a network
	xolotl::options::Options opts;
	// Create a good parameter file
	std::string parameterFile = "param.txt";
	std::ofstream paramFile(parameterFile);
	paramFile << "netParam=8 0 0 1 0" << std::endl;
	paramFile.close();

	// Create a fake command line to read the options
	test::CommandLine<2> cl{{"fakeXolotlAppNameForTests", parameterFile}};
	util::mpiInit(cl.argc, cl.argv);
	opts.readParams(cl.argc, cl.argv);

	std::remove(parameterFile.c_str());

	// Create a grid
	std::vector<double> grid;
	std::vector<double> temperatures;
	for (int l = 0; l < 5; l++) {
		grid.push_back((double)l);
		temperatures.push_back(1000.0);
	}

	// Create the network
	using NetworkType =
		network::PSIReactionNetwork<network::PSIFullSpeciesList>;
	NetworkType::AmountType maxV = opts.getMaxV();
	NetworkType::AmountType maxI = opts.getMaxI();
	NetworkType::AmountType maxHe = opts.getMaxImpurity();
	NetworkType::AmountType maxD = opts.getMaxD();
	NetworkType::AmountType maxT = opts.getMaxT();
	NetworkType network({maxHe, maxD, maxT, maxV, maxI}, grid.size(), opts);
	network.syncClusterDataOnHost();
	network.getSubpaving().syncZones(plsm::onHost);
	// Get its size
	const int dof = network.getDOF();

	// Create ofill
	network::IReactionNetwork::SparseFillMap ofill;

	// Create a collection of advection handlers
	std::vector<IAdvectionHandler*> advectionHandlers;

	// Create the advection handler and initialize it
	W111AdvectionHandler advectionHandler;
	advectionHandler.initialize(network, ofill);
	advectionHandler.initializeAdvectionGrid(advectionHandlers, grid, 3, 0);

	// Check the total number of advecting clusters
	BOOST_REQUIRE_EQUAL(advectionHandler.getNumberOfAdvecting(), 7);

	// Check the clusters in ofill
	BOOST_REQUIRE_EQUAL(ofill[1][0], 1);
	BOOST_REQUIRE_EQUAL(ofill[3][0], 3);
	BOOST_REQUIRE_EQUAL(ofill[5][0], 5);
	BOOST_REQUIRE_EQUAL(ofill[7][0], 7);
	BOOST_REQUIRE_EQUAL(ofill[9][0], 9);
	BOOST_REQUIRE_EQUAL(ofill[11][0], 11);
	BOOST_REQUIRE_EQUAL(ofill[13][0], 13);

	// Set the size parameter in the x direction
	double hx = 1.0;

	// Create the arrays of concentration
	double concentration[3 * dof];
	double newConcentration[3 * dof];

	// Initialize their values
	for (int i = 0; i < 3 * dof; i++) {
		concentration[i] = (double)i * i;
		newConcentration[i] = 0.0;
	}

	// Set the temperature to 1000K to initialize the diffusion coefficients
	network.setTemperatures(temperatures);
	network.syncClusterDataOnHost();

	// Get pointers
	double* conc = &concentration[0];
	double* updatedConc = &newConcentration[0];

	// Get the offset for the grid point in the middle
	double* concOffset = conc + dof;
	double* updatedConcOffset = updatedConc + dof;

	// Fill the concVector with the pointer to the middle, left, and right grid
	// points
	double* concVector[3]{};
	concVector[0] = concOffset; // middle
	concVector[1] = conc; // left
	concVector[2] = conc + 2 * dof; // right

	// Set the grid position
	plsm::SpaceVector<double, 3> gridPosition{hx, 0.0, 0.0};

	// Compute the advection at this grid point
	advectionHandler.computeAdvection(
		network, gridPosition, concVector, updatedConcOffset, hx, hx, 0);

	// Check the new values of updatedConcOffset
	BOOST_REQUIRE_CLOSE(updatedConcOffset[1], -2.0171e+11, 0.01);
	BOOST_REQUIRE_CLOSE(updatedConcOffset[3], -2.2012e+11, 0.01);
	BOOST_REQUIRE_CLOSE(updatedConcOffset[5], -2.8037e+11, 0.01);
	BOOST_REQUIRE_CLOSE(updatedConcOffset[7], -2.6928e+11, 0.01);
	BOOST_REQUIRE_CLOSE(updatedConcOffset[9], -1.0761e+12, 0.01);
	BOOST_REQUIRE_CLOSE(updatedConcOffset[11], -3.6701e+10, 0.01);
	BOOST_REQUIRE_CLOSE(updatedConcOffset[13], -1.0429e+10, 0.01);
	BOOST_REQUIRE_CLOSE(updatedConcOffset[0], 0.0, 0.01); // Does not advect
	BOOST_REQUIRE_CLOSE(updatedConcOffset[15], 0.0, 0.01); // Does not advect

	// Initialize the rows, columns, and values to set in the Jacobian
	int nAdvec = advectionHandler.getNumberOfAdvecting();
	IdType indices[nAdvec];
	double val[2 * nAdvec];
	// Get the pointer on them for the compute advection method
	IdType* indicesPointer = &indices[0];
	double* valPointer = &val[0];

	// Compute the partial derivatives for the advection a the grid point 1
	advectionHandler.computePartialsForAdvection(
		network, valPointer, indicesPointer, gridPosition, hx, hx, 0);

	// Check the values for the indices
	BOOST_REQUIRE_EQUAL(indices[0], 1);
	BOOST_REQUIRE_EQUAL(indices[1], 3);
	BOOST_REQUIRE_EQUAL(indices[2], 5);
	BOOST_REQUIRE_EQUAL(indices[3], 7);
	BOOST_REQUIRE_EQUAL(indices[4], 9);
	BOOST_REQUIRE_EQUAL(indices[5], 11);
	BOOST_REQUIRE_EQUAL(indices[6], 13);

	// Check values
	BOOST_REQUIRE_CLOSE(val[0], -815207266.0, 0.01);
	BOOST_REQUIRE_CLOSE(val[1], 50950454.0, 0.01);
	BOOST_REQUIRE_CLOSE(val[2], -700039625.0, 0.01);
	BOOST_REQUIRE_CLOSE(val[3], 43752477.0, 0.01);

	// Get the stencil
	auto stencil = advectionHandler.getStencilForAdvection(gridPosition);

	// Check the value of the stencil
	BOOST_REQUIRE_EQUAL(stencil[0], 1); // x
	BOOST_REQUIRE_EQUAL(stencil[1], 0);
	BOOST_REQUIRE_EQUAL(stencil[2], 0);

	// Finalize MPI
	MPI_Finalize();
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: ORNL-Fusion/xolotl

max_issues_repo_name: ORNL-Fusion/xolotl

max_forks_repo_name: ORNL-Fusion/xolotl


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

namespace EventTypes {
const EventType WorkQueue="WorkQueue";
const EventType Tick="Tick";
const EventType AvatarCreated="AvatarCreated";
const EventType ObjectDatabaseRestored="ObjectDatabaseRestored";

const EventType ObjectCreated="ObjectCreated";
const EventType ObjectRestored="ObjectRestored";
const EventType ObjectDestroyed="ObjectDestroyed";

const EventType NamedProxyCreated="NamedProxyCreated";
const EventType NamedProxyDeleted="NamedProxyDeleted";
const EventType PositionUpdate="PositionUpdate";
const EventType LocalPositionUpdate="LocalPositionUpdate";
const EventType ProxySelected="ProxySelected";
const EventType ProxyDeselected="ProxyDeselected";
const EventType Quit="Quit";
}

TickEvent::TickEvent(const Time& t, const Duration& dt)
    : Event(EventID(EventTypes::Tick)),
     mTime(t),
     mDuration(dt)
{
}

String TickEvent::toString() const {
    std::ostringstream os;
    os<<"("<< getId().toString() <<" - ["<< (mTime-Time::null()).toSeconds() << "])";
    return os.str();
}

UserEvent::UserEvent(const EventID& evt_id, const SpaceObjectReference& id)
: Event(evt_id), mObject(id)
{
}

String UserEvent::toString() const {
    return String("(") + getId().toString() + String(" - ") + mObject.toString() + String(")");
}

ObjectEvent::ObjectEvent(const EventID& evt_id, const UUID& id)
: Event(evt_id), mUUID(id)
{
}

String ObjectEvent::toString() const {
    return String("(") + getId().toString() + String(" - ") + mUUID.toString() + String(")");
}

ProximityEvent::ProximityEvent(const EventID& evt_id, const ObjectReference& id1, const ObjectReference& id2)
: Event(evt_id)
{
    mObjects[0] = id1;
    mObjects[1] = id2;
}

String ProximityEvent::toString() const {
    return String("(") + getId().toString() + String(" - [") + mObjects[0].toString() + String(",") + mObjects[1].toString() + String("]") + String(")");
}

PositionUpdate::PositionUpdate(const SpaceObjectReference& id, const Time t, const Vector3d& pos, const Quaternion& orient, const Vector3f& vel)
: Event(EventID(EventTypes::PositionUpdate)), time(t), position(pos), orientation(orient), velocity(vel), mID(id)
{
}

String PositionUpdate::toString() const {
  std::ostringstream os;
  os <<String("(")<< getId().toString()<< String(" - [") << mID.toString() <<
        String(" at ") << (time-Time::null()).toSeconds() << String(", ") <<
        position.toString() << String(", ") << orientation.toString() << String(", ") <<
        velocity.toString() << String("])");
    return os.str();
}

LocalPositionUpdate::LocalPositionUpdate(const SpaceObjectReference& id, const Time t, const Vector3d& pos, const Quaternion& orient, const Vector3f& vel)
: Event(EventID(EventTypes::LocalPositionUpdate,id.toString())), time(t), position(pos), orientation(orient), velocity(vel), mID(id)
{
}

String LocalPositionUpdate::toString() const {
    std::ostringstream os;
    os << "(" << getId().toString() << " - [" << (time-Time::null()).toSeconds() << ", " <<
        position.toString() << ", " << orientation.toString() << ", " <<
        velocity.toString() << "])";
    return os.str();
}

EventID WorkQueueEvent::getID(int identifier) {
    return EventID(EventTypes::WorkQueue,boost::lexical_cast<String>(identifier));
}
WorkQueueEvent::WorkQueueEvent(int identifier):Event(getID(identifier)) {

}
QuitEvent::QuitEvent()
: Event(EventID(EventTypes::Quit))
{
}

NamedProxyCreated::NamedProxyCreated(const SpaceObjectReference& id, const String &_name) : Event(EventID(EventTypes::NamedProxyCreated,id.toString())), source(id), name(_name)
{
}

NamedProxyDeleted::NamedProxyDeleted(const SpaceObjectReference& id) : Event(EventID(EventTypes::NamedProxyDeleted,id.toString())),  source(id)
{
}

ProxySelected::ProxySelected(const SpaceObjectReference& id) : Event(EventID(EventTypes::ProxySelected,id.toString())), source(id)
{
}

ProxyDeselected::ProxyDeselected(const SpaceObjectReference& id) : Event(EventID(EventTypes::ProxyDeselected,id.toString())),  source(id)
{
}

} // namespace Meru

max_stars_repo_name: danielrh/sirikata

max_issues_repo_name: danielrh/sirikata

max_forks_repo_name: danielrh/sirikata