text:
/*
 * Copyright 2017-2019 Janek Bevendorff, Webis Group
 *
 * 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 OBFUSCATION_SEARCH_ABSTRACTWORD_HPP
#define OBFUSCATION_SEARCH_ABSTRACTWORD_HPP

#include "ObfuscationOperator.hpp"

#include <string>
#include <mutex>
#include <deque>
//#include <netspeak/NetspeakRS3.hpp>
#include <boost/compute/detail/lru_cache.hpp>

namespace bd = boost::compute::detail;

/**
 * Abstract base class for word-based operators.
 */
class AbstractWordOperator: public ObfuscationOperator {
public:
    AbstractWordOperator(std::string const& name, double cost, std::string const& description);

protected:
//    typedef std::shared_ptr<netspeak::generated::Response> NetspeakResponse;
    typedef std::pair<StrPos, StrPos> WordBounds;
    typedef std::vector<WordBounds> WordBoundsList;
    typedef std::pair<WordBoundsList, WordBoundsList> WordBoundsListPair;
    typedef std::unordered_map<std::string, std::vector<std::string>> Dictionary;

    static WordBoundsListPair parseWordBounds(FocusPoint const& focusPoint, std::size_t wordsBefore, std::size_t wordsAfter);
    static inline bool isWordBoundary(char c);
    static inline StrPos parseWordStart(std::string const& text, StrPos pos);
    static inline StrPos parseWordEnd(std::string const& text, StrPos pos);
    static std::shared_ptr<Dictionary const> loadDictionary(std::string const& dictFile, char separator = '\t');

private:
    static std::mutex s_dictMutex;
    static std::unordered_map<std::string, std::shared_ptr<Dictionary>> s_dictionaries;
    static std::mutex s_boundsCacheMutex;
    static bd::lru_cache<std::string, WordBoundsListPair> s_cachedWordBounds;
};

#endif //OBFUSCATION_SEARCH_ABSTRACTWORD_HPP

ext: hpp


text:
// Author: Dmitry Kukovinets (d1021976@gmail.com), 28.05.2017, 20:00

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <regex>
#include <algorithm>
#include <iterator>
#include <exception>
#include <stdexcept>

#include <boost/program_options.hpp>

int
main(int argc, char **argv)
{
	namespace po = boost::program_options;

	const auto print_help =
		[&](std::ostream &stream = std::cout)
		{
			stream
				<< "Usage:" << std::endl
				<< "    " << argv[0] << " [OPTIONS] REGEX [FILE ...]" << std::endl;
		};

	std::string regex;
	std::vector<std::string> input_files;

	try {
		// Declare the supported options.
		po::options_description options_description("Allowed options");
		options_description.add_options()
			(
				"help,h",
				"Print help message and exit"
			)

			(
				"escape,e",
				"Process regex as string with escaped backslashes (just copy regex from .cpp file)"
			)

			(
				"regex,r", po::value<std::string>(&regex),
				"Set regex"
			)

			(
				"input-file,i", po::value<std::vector<std::string>>(&input_files),
				"Set input file"
			)
		;

		po::positional_options_description positional_options;
		positional_options.add("regex", 1);
		positional_options.add("input-file", -1);

		po::variables_map vm;

		po::store(
			po::command_line_parser(argc, argv).options(options_description).positional(positional_options).run(),
			vm
		);

		po::notify(vm);

		if (vm.count("help")) {
			print_help();
			std::cout << options_description;
			return 0;
		}

		if (input_files.empty())
			throw std::logic_error{"No input files given"};

		if (vm.count("escape")) {
			std::string tmp;
			tmp.reserve(regex.size());

			std::regex_replace(
				std::back_inserter(tmp),
				regex.begin(), regex.end(),
				std::regex{"\\\\\\\\", std::regex::optimize},
				"\\"
			);

			regex = std::move(tmp);
		}

		const std::regex r{regex, std::regex::optimize};
		std::smatch m;
		std::string str;

		for (const auto &input_file: input_files) {
			std::ifstream fin;
			fin.exceptions(std::ifstream::failbit);
			try {
				fin.open(input_file);
			} catch (const std::exception &e) {
				std::cerr << "Error with file: \"" << input_file << "\": " << e.what() << '.' << std::endl;
				continue;
			}
			fin.exceptions(std::ifstream::goodbit);

			std::cout << input_file << ':' << std::endl;

			std::size_t line_number = 1;
			while (std::getline(fin, str)) {
				if (std::regex_match(str, m, r)) {
					std::cout << "    [" << line_number << "] match (groups: " << m.size() << "):" << std::endl;

					auto max_group_index = m.size();
					if (max_group_index > 0)
						--max_group_index;
					const auto group_index_width = std::to_string(max_group_index).size();

					const auto str_index_width = std::to_string(str.size()).size();

					std::size_t group_index = 0;
					for (const auto &g: m) {
						std::cout
							<< "        ["
							<< std::setw(group_index_width) << std::right << group_index
							<< std::setw(0) << std::left << "; pos: "
							<< std::setw(str_index_width) << std::right << std::distance(str.cbegin(), g.first)
							<< std::setw(0) << std::left << "; len: "
							<< std::setw(str_index_width) << std::right << g.length()
							<< "] \"" << g.str() << '\"' << std::endl;

						++group_index;
					}
				} else {
					std::cout << "    [" << line_number << "] --" << std::endl;
				}

				++line_number;
			}
		}
	} catch (const std::exception &e) {
		std::cerr << "Error: " << e.what() << '.' << std::endl;
		return 1;
	}

	return 0;
}

ext: cpp

max_stars_repo_name: DmitryKuk/reggae-cpp

max_issues_repo_name: DmitryKuk/reggae-cpp

max_forks_repo_name: DmitryKuk/reggae-cpp


text:
/*
 *  nextpnr -- Next Generation Place and Route
 *
 *  Copyright (C) 2018  Clifford Wolf <clifford@symbioticeda.com>
 *  Copyright (C) 2018  David Shah <david@symbioticeda.com>
 *  Copyright (C) 2018  Serge Bazanski <q3k@symbioticeda.com>
 *
 *  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.
 *
 */

#include "cells.h"
#include "nextpnr.h"
#include "util.h"

#include <boost/range/iterator_range.hpp>

NEXTPNR_NAMESPACE_BEGIN

bool Arch::logicCellsCompatible(const CellInfo **it, const size_t size) const
{
    // TODO: Check clock, clock-enable, and set-reset compatiility
    return true;
}

bool Arch::isBelLocationValid(BelId bel) const
{
    if (getBelType(bel) == id("XC7_LC")) {
        std::array<const CellInfo *, 4> bel_cells;
        size_t num_cells = 0;
        Loc bel_loc = getBelLocation(bel);
        for (auto bel_other : getBelsByTile(bel_loc.x, bel_loc.y)) {
            CellInfo *ci_other = getBoundBelCell(bel_other);
            if (ci_other != nullptr)
                bel_cells[num_cells++] = ci_other;
        }
        return logicCellsCompatible(bel_cells.data(), num_cells);
    } else {
        CellInfo *ci = getBoundBelCell(bel);
        if (ci == nullptr)
            return true;
        else
            return isValidBelForCell(ci, bel);
    }
}

bool Arch::isValidBelForCell(CellInfo *cell, BelId bel) const
{
    if (cell->type == id("XC7_LC")) {
        std::array<const CellInfo *, 4> bel_cells;
        size_t num_cells = 0;

        Loc bel_loc = getBelLocation(bel);
        for (auto bel_other : getBelsByTile(bel_loc.x, bel_loc.y)) {
            CellInfo *ci_other = getBoundBelCell(bel_other);
            if (ci_other != nullptr && bel_other != bel)
                bel_cells[num_cells++] = ci_other;
        }

        bel_cells[num_cells++] = cell;
        return logicCellsCompatible(bel_cells.data(), num_cells);
    } else {
        return true;
    }
}

NEXTPNR_NAMESPACE_END

ext: cc


text:
/*
 * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
 */

#include <boost/bind.hpp>
#include <boost/asio/ip/host_name.hpp>
#include <boost/foreach.hpp>
#include <boost/tokenizer.hpp>
#include <boost/assign/list_of.hpp>

#include <isc/hmacmd5.h>
#include <isc/hmacsha.h>

#include "base/contrail_ports.h"
#include "http/http_request.h"
#include "http/http_session.h"
#include "http/http_server.h"
#include "http/client/http_client.h"
#include "http/client/http_curl.h"
#include "io/event_manager.h"
#include "cmn/agent_cmn.h"
#include "oper/operdb_init.h"
#include "oper/mirror_table.h"
#include "oper/interface_common.h"
#include "oper/global_vrouter.h"
#include "pkt/pkt_handler.h"
#include "services/services_types.h"
#include "services/services_init.h"
#include "services/metadata_proxy.h"
#include "services/services_sandesh.h"

////////////////////////////////////////////////////////////////////////////////

#define METADATA_TRACE(obj, arg)                                               \
do {                                                                           \
    std::ostringstream _str;                                                   \
    _str << arg;                                                               \
    Metadata##obj::TraceMsg(MetadataTraceBuf, __FILE__, __LINE__, _str.str()); \
} while (false)                                                                \

// Get HMAC SHA256 digest
static std::string
GetHmacSha256(const std::string &key, const std::string &data) {
    isc_hmacsha256_t hmacsha256;
    isc_hmacsha256_init(&hmacsha256, (const unsigned char *)key.c_str(),
                        key.length());
    isc_hmacsha256_update(&hmacsha256, (const isc_uint8_t *)data.c_str(),
                          data.length());
    unsigned char hmac_sha256_digest[ISC_SHA512_DIGESTLENGTH];
    isc_hmacsha256_sign(&hmacsha256, hmac_sha256_digest,
                        ISC_SHA256_DIGESTLENGTH);
    std::stringstream str;
    for (unsigned int i = 0; i < ISC_SHA256_DIGESTLENGTH; i++) {
        str << std::hex << std::setfill('0') << std::setw(2)
            << (int) hmac_sha256_digest[i];
    }
    return str.str();
}

////////////////////////////////////////////////////////////////////////////////

MetadataProxy::MetadataProxy(ServicesModule *module,
                             const std::string &secret)
    : services_(module), shared_secret_(secret),
      http_server_(new HttpServer(services_->agent()->GetEventManager())),
      http_client_(new HttpClient(services_->agent()->GetEventManager())) {

    // Register wildcard entry to match any URL coming on the metadata port
    http_server_->RegisterHandler(HTTP_WILDCARD_ENTRY,
        boost::bind(&MetadataProxy::HandleMetadataRequest, this, _1, _2));
    http_server_->Initialize(0);
    services_->agent()->SetMetadataServerPort(http_server_->GetPort());

    http_client_->Init();
}

MetadataProxy::~MetadataProxy() {
}

void
MetadataProxy::Shutdown() {
    http_server_->Shutdown();
    http_server_ = NULL;
    http_client_->Shutdown();
    http_client_ = NULL;
}

void
MetadataProxy::HandleMetadataRequest(HttpSession *session, const HttpRequest *request) {
    bool conn_close = false;
    std::string msg;
    std::string uri;
    std::string header_options;
    std::string vm_ip, vm_uuid, vm_project_uuid;
    metadata_stats_.requests++;
    boost::asio::ip::address_v4 ip = session->remote_endpoint().address().to_v4();

    if (!services_->agent()->GetInterfaceTable()->
         FindVmUuidFromMetadataIp(ip, &vm_ip, &vm_uuid, &vm_project_uuid)) {
        ErrorClose(session);
        http_server_->DeleteSession(session);
        delete request;
        METADATA_TRACE(Trace, "Metadata GET for VM : " << ip <<
                       " Error : Interface Config not available");
        return;
    }
    std::string signature = GetHmacSha256(shared_secret_, vm_uuid);
    const HttpRequest::HeaderMap &req_header = request->Headers();
    for (HttpRequest::HeaderMap::const_iterator it = req_header.begin();
         it != req_header.end(); ++it) {
        std::string option = boost::to_lower_copy(it->first);
        if (option == "host") {
            continue;
        }
        if (option == "connection") {
            std::string val = boost::to_lower_copy(it->second);
            if (val == "close")
                conn_close = true;
            continue;
        }
        header_options += it->first + ": " + it->second + "\r\n";
    }

    // keystone uses uuids without dashes and that is what ends up in
    // the nova database entry for the instance. Remove dashes from the
    // uuid string representation.
    boost::replace_all(vm_project_uuid, "-", "");
    header_options += "X-Forwarded-For: " + vm_ip + "\r\n" +
                      "X-Instance-ID: " + vm_uuid + "\r\n" +
                      "X-Tenant-ID: " + vm_project_uuid + "\r\n" +
                      "X-Instance-ID-Signature: " + signature;

    bool delete_session = false;
    uri = request->UrlPath().substr(1); // ignore the first "/"
    switch(request->GetMethod()) {
        case HTTP_GET: {
            tbb::mutex::scoped_lock lock(mutex_);
            HttpConnection *conn = GetProxyConnection(session, conn_close);
            if (conn) {
                conn->HttpGet(uri, true, false, header_options,
                boost::bind(&MetadataProxy::HandleMetadataResponse,
                            this, conn, HttpSessionPtr(session), _1, _2));
                METADATA_TRACE(Trace, "Metadata GET for VM : " << vm_ip <<
                               " URL : " << uri);
            } else {
                ErrorClose(session);
                delete_session = true;
                METADATA_TRACE(Trace, "Metadata GET for VM : " << vm_ip <<
                               " Error : Metadata Config not available");
            }
            break;
        }

        default:
            METADATA_TRACE(Trace, "Metadata Unsupported Request Method : " <<
                           request->GetMethod());
            break;
    }

    if (delete_session)
        http_server_->DeleteSession(session);

    delete request;
}

// Metadata Response from Nova API service
void
MetadataProxy::HandleMetadataResponse(HttpConnection *conn, HttpSessionPtr session,
                                      std::string &msg, boost::system::error_code &ec) {
    bool delete_session = false;
    {
        tbb::mutex::scoped_lock lock(mutex_);

        // Ignore if session is closed in the meantime
        SessionMap::iterator it = metadata_sessions_.find(session.get());
        if (it == metadata_sessions_.end())
            return;

        std::string vm_ip, vm_uuid, vm_project_uuid;
        boost::asio::ip::address_v4 ip = session->remote_endpoint().address().to_v4();
        services_->agent()->GetInterfaceTable()->
            FindVmUuidFromMetadataIp(ip, &vm_ip, &vm_uuid, &vm_project_uuid);

        if (!ec) {
            METADATA_TRACE(Trace, "Metadata for VM : " << vm_ip << " Response : " << msg);
            session->Send(reinterpret_cast<const u_int8_t *>(msg.c_str()),
                          msg.length(), NULL);
        } else {
            METADATA_TRACE(Trace, "Metadata for VM : " << vm_ip << " Error : " <<
                                  boost::system::system_error(ec).what());
            CloseClientSession(conn);
            ErrorClose(session.get());
            delete_session = true;
            goto done;
        }

        if (!ec && it->second.close_req) {
            std::stringstream str(msg);
            std::string option;
            str >> option;
            if (option == "Content-Length:") {
                str >> it->second.content_len;
            } else if (msg == "\r\n") {
                it->second.header_end = true;
                if (it->second.header_end && !it->second.content_len) {
                    CloseClientSession(it->second.conn);
                    CloseServerSession(session.get());
                    delete_session = true;
                    metadata_stats_.responses++;
                }
            } else if (it->second.header_end) {
                it->second.data_sent += msg.length();
                if (it->second.data_sent >= it->second.content_len) {
                    CloseClientSession(it->second.conn);
                    CloseServerSession(session.get());
                    delete_session = true;
                    metadata_stats_.responses++;
                }
            }
        }
    }

done:
    if (delete_session) {
        http_server_->DeleteSession(session.get());
    }
}

void
MetadataProxy::OnServerSessionEvent(HttpSession *session, TcpSession::Event event) {
    switch (event) {
        case TcpSession::CLOSE: {
            tbb::mutex::scoped_lock lock(mutex_);
            SessionMap::iterator it = metadata_sessions_.find(session);
            if (it == metadata_sessions_.end())
                break;
            CloseClientSession(it->second.conn);
            metadata_sessions_.erase(it);
            break;
        }

        default:
            break;
    }
}

void
MetadataProxy::OnClientSessionEvent(HttpClientSession *session, TcpSession::Event event) {
    switch (event) {
        case TcpSession::CLOSE: {
            {
                tbb::mutex::scoped_lock lock(mutex_);
                ConnectionSessionMap::iterator it =
                    metadata_proxy_sessions_.find(session->Connection());
                if (it == metadata_proxy_sessions_.end())
                    break;
                CloseServerSession(it->second);
                CloseClientSession(session->Connection());
            }
            http_server_->DeleteSession(session);
            break;
        }

        default:
            break;
    }
}

HttpConnection *
MetadataProxy::GetProxyConnection(HttpSession *session, bool conn_close) {
    SessionMap::iterator it = metadata_sessions_.find(session);
    if (it != metadata_sessions_.end()) {
        it->second.close_req = conn_close;
        return it->second.conn;
    }

    uint16_t nova_port, linklocal_port;
    Ip4Address nova_server, linklocal_server;
    if (!services_->agent()->oper_db()->global_vrouter()->FindLinkLocalService(
        GlobalVrouter::kMetadataService, &linklocal_server, &linklocal_port,
        &nova_server, &nova_port))
        return NULL;

    boost::asio::ip::tcp::endpoint http_ep;
    http_ep.address(nova_server);
    http_ep.port(nova_port);

    HttpConnection *conn = http_client_->CreateConnection(http_ep);
    conn->RegisterEventCb(
             boost::bind(&MetadataProxy::OnClientSessionEvent, this, _1, _2));
    session->RegisterEventCb(
             boost::bind(&MetadataProxy::OnServerSessionEvent, this, _1, _2));
    SessionData data(conn, conn_close);
    metadata_sessions_.insert(SessionPair(session, data));
    metadata_proxy_sessions_.insert(ConnectionSessionPair(conn, session));
    metadata_stats_.proxy_sessions++;
    return conn;
}

void
MetadataProxy::CloseServerSession(HttpSession *session) {
    session->Close();
    metadata_sessions_.erase(session);
}

void
MetadataProxy::CloseClientSession(HttpConnection *conn) {
    HttpClient *client = conn->client();
    client->RemoveConnection(conn);
    metadata_proxy_sessions_.erase(conn);
}

void
MetadataProxy::ErrorClose(HttpSession *session) {
    const char body[] = "\n"
                        "\n"
                        " <title>404 Not Found</title>\n"
                        "\n"
                        "\n";
    char response[512];
    snprintf(response, sizeof(response),
             "HTTP/1.1 404 Not Found\n"
             "Content-Type: text/html; charset=UTF-8\n"
             "Content-Length: %u\n"
             "\n%s", (unsigned int) strlen(body), body);
    session->Send(reinterpret_cast<const u_int8_t *>(response),
                  strlen(response), NULL);
    CloseServerSession(session);
    metadata_stats_.internal_errors++;
}

max_stars_repo_name: safchain/contrail-controller

max_issues_repo_name: safchain/contrail-controller

max_forks_repo_name: safchain/contrail-controller


text:
//  Copyright (c) 2001-2009 Hartmut Kaiser
//
//  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 <boost/config/warning_disable.hpp>
#include <boost/detail/lightweight_test.hpp>

#include <boost/spirit/include/karma_char.hpp>
#include <boost/spirit/include/karma_string.hpp>
#include <boost/spirit/include/karma_generate.hpp>
#include <boost/spirit/include/karma_directive.hpp>

#include "test.hpp"

using namespace spirit_test;

///////////////////////////////////////////////////////////////////////////////
int
main()
{
    using namespace boost::spirit;

    {
        using namespace boost::spirit::ascii;

        BOOST_TEST(test("x", lower['X']));
        BOOST_TEST(test("x", lower['x']));
        BOOST_TEST(test(L"x", lower[L'X']));
        BOOST_TEST(test(L"x", lower[L'x']));

        BOOST_TEST(test("x", lower[char_], 'X'));
        BOOST_TEST(test("x", lower[char_], 'x'));
        BOOST_TEST(test("x", lower[char_('X')]));
        BOOST_TEST(test("x", lower[char_('x')]));

        BOOST_TEST(test(" ", lower[space]));
        BOOST_TEST(test("\t", lower[space], '\t'));
        BOOST_TEST(test("\t", lower[space('\t')]));

        BOOST_TEST(test("x", lower[lower['X']]));
        BOOST_TEST(test("x", lower[lower['x']]));
        BOOST_TEST(test(L"x", lower[lower[L'X']]));
        BOOST_TEST(test(L"x", lower[lower[L'x']]));

        BOOST_TEST(test("x", lower[lower[char_]], 'X'));
        BOOST_TEST(test("x", lower[lower[char_]], 'x'));
        BOOST_TEST(test("x", lower[lower[char_('X')]]));
        BOOST_TEST(test("x", lower[lower[char_('x')]]));

        BOOST_TEST(test(" ", lower[lower[space]]));
        BOOST_TEST(test("\t", lower[lower[space]], '\t'));
        BOOST_TEST(test("\t", lower[lower[space('\t')]]));

        BOOST_TEST(test("X", upper[lower['X']]));
        BOOST_TEST(test("X", upper[lower['x']]));
        BOOST_TEST(test(L"X", upper[lower[L'X']]));
        BOOST_TEST(test(L"X", upper[lower[L'x']]));

        BOOST_TEST(test("X", upper[lower[char_]], 'X'));
        BOOST_TEST(test("X", upper[lower[char_]], 'x'));
        BOOST_TEST(test("X", upper[lower[char_('X')]]));
        BOOST_TEST(test("X", upper[lower[char_('x')]]));

        BOOST_TEST(test(" ", upper[lower[space]]));
        BOOST_TEST(test("\t", upper[lower[space]], '\t'));
        BOOST_TEST(test("\t", upper[lower[space('\t')]]));

        BOOST_TEST(test("X", upper['X']));
        BOOST_TEST(test("X", upper['x']));
        BOOST_TEST(test(L"X", upper[L'X']));
        BOOST_TEST(test(L"X", upper[L'x']));

        BOOST_TEST(test("X", upper[char_], 'X'));
        BOOST_TEST(test("X", upper[char_], 'x'));
        BOOST_TEST(test("X", upper[char_('X')]));
        BOOST_TEST(test("X", upper[char_('x')]));

        BOOST_TEST(test(" ", upper[space]));
        BOOST_TEST(test("\t", upper[space], '\t'));
        BOOST_TEST(test("\t", upper[space('\t')]));

        BOOST_TEST(test("x", lower[upper['X']]));
        BOOST_TEST(test("x", lower[upper['x']]));
        BOOST_TEST(test(L"x", lower[upper[L'X']]));
        BOOST_TEST(test(L"x", lower[upper[L'x']]));

        BOOST_TEST(test("x", lower[upper[char_]], 'X'));
        BOOST_TEST(test("x", lower[upper[char_]], 'x'));
        BOOST_TEST(test("x", lower[upper[char_('X')]]));
        BOOST_TEST(test("x", lower[upper[char_('x')]]));

        BOOST_TEST(test(" ", lower[upper[space]]));
        BOOST_TEST(test("\t", lower[upper[space]], '\t'));
        BOOST_TEST(test("\t", lower[upper[space('\t')]]));

        BOOST_TEST(test("X", upper[upper['X']]));
        BOOST_TEST(test("X", upper[upper['x']]));
        BOOST_TEST(test(L"X", upper[upper[L'X']]));
        BOOST_TEST(test(L"X", upper[upper[L'x']]));

        BOOST_TEST(test("X", upper[upper[char_]], 'X'));
        BOOST_TEST(test("X", upper[upper[char_]], 'x'));
        BOOST_TEST(test("X", upper[upper[char_('X')]]));
        BOOST_TEST(test("X", upper[upper[char_('x')]]));

        BOOST_TEST(test(" ", upper[upper[space]]));
        BOOST_TEST(test("\t", upper[upper[space]], '\t'));
        BOOST_TEST(test("\t", upper[upper[space('\t')]]));
    }

    {
        using namespace boost::spirit::ascii;

        BOOST_TEST(test("a1- ", lower["a1- "]));
        BOOST_TEST(test("a1- ", lower["a1- "]));
        BOOST_TEST(test("a1- ", lower["a1- "]));
        BOOST_TEST(test("a1- ", lower["A1- "]));

        BOOST_TEST(test("a1- ", lower[lit], "a1- "));
        BOOST_TEST(test("a1- ", lower[lit], "A1- "));
        BOOST_TEST(test("a1- ", lower[lit("a1- ")]));
        BOOST_TEST(test("a1- ", lower[lit("A1- ")]));

        BOOST_TEST(test("a1- ", lower[lower["a1- "]]));
        BOOST_TEST(test("a1- ", lower[lower["a1- "]]));
        BOOST_TEST(test("a1- ", lower[lower["a1- "]]));
        BOOST_TEST(test("a1- ", lower[lower["A1- "]]));

        BOOST_TEST(test("a1- ", lower[lower[lit]], "a1- "));
        BOOST_TEST(test("a1- ", lower[lower[lit]], "A1- "));
        BOOST_TEST(test("a1- ", lower[lower[lit("a1- ")]]));
        BOOST_TEST(test("a1- ", lower[lower[lit("A1- ")]]));

        BOOST_TEST(test("A1- ", upper[lower["a1- "]]));
        BOOST_TEST(test("A1- ", upper[lower["a1- "]]));
        BOOST_TEST(test("A1- ", upper[lower["a1- "]]));
        BOOST_TEST(test("A1- ", upper[lower["A1- "]]));

        BOOST_TEST(test("A1- ", upper[lower[lit]], "a1- "));
        BOOST_TEST(test("A1- ", upper[lower[lit]], "A1- "));
        BOOST_TEST(test("A1- ", upper[lower[lit("a1- ")]]));
        BOOST_TEST(test("A1- ", upper[lower[lit("A1- ")]]));

        BOOST_TEST(test("A1- ", upper["a1- "]));
        BOOST_TEST(test("A1- ", upper["a1- "]));
        BOOST_TEST(test("A1- ", upper["a1- "]));
        BOOST_TEST(test("A1- ", upper["A1- "]));

        BOOST_TEST(test("A1- ", upper[lit], "a1- "));
        BOOST_TEST(test("A1- ", upper[lit], "A1- "));
        BOOST_TEST(test("A1- ", upper[lit("a1- ")]));
        BOOST_TEST(test("A1- ", upper[lit("A1- ")]));

        BOOST_TEST(test("a1- ", lower[upper["a1- "]]));
        BOOST_TEST(test("a1- ", lower[upper["a1- "]]));
        BOOST_TEST(test("a1- ", lower[upper["a1- "]]));
        BOOST_TEST(test("a1- ", lower[upper["A1- "]]));

        BOOST_TEST(test("a1- ", lower[upper[lit]], "a1- "));
        BOOST_TEST(test("a1- ", lower[upper[lit]], "A1- "));
        BOOST_TEST(test("a1- ", lower[upper[lit("a1- ")]]));
        BOOST_TEST(test("a1- ", lower[upper[lit("A1- ")]]));

        BOOST_TEST(test("A1- ", upper[upper["a1- "]]));
        BOOST_TEST(test("A1- ", upper[upper["a1- "]]));
        BOOST_TEST(test("A1- ", upper[upper["a1- "]]));
        BOOST_TEST(test("A1- ", upper[upper["A1- "]]));

        BOOST_TEST(test("A1- ", upper[upper[lit]], "a1- "));
        BOOST_TEST(test("A1- ", upper[upper[lit]], "A1- "));
        BOOST_TEST(test("A1- ", upper[upper[lit("a1- ")]]));
        BOOST_TEST(test("A1- ", upper[upper[lit("A1- ")]]));
    }

    return boost::report_errors();
}


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2013-2019 Regents of the University of California.
 *
 * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
 *
 * ndn-cxx 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 3 of the License, or (at your option) any later version.
 *
 * ndn-cxx 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 copies of the GNU General Public License and GNU Lesser
 * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
 * <http://www.gnu.org/licenses/>.
 *
 * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
 */

#include "ndn-cxx/util/scheduler.hpp"

#include <boost/scope_exit.hpp>

namespace ndn {
namespace scheduler {

/** \brief Stores internal information about a scheduled event
 */
class EventInfo : noncopyable
{
public:
  EventInfo(time::nanoseconds after, EventCallback&& cb, uint32_t context)
    : callback(std::move(cb))
    , expireTime(time::steady_clock::now() + after)
    , context(context)
  {
  }

  NDN_CXX_NODISCARD time::nanoseconds
  expiresFromNow() const
  {
    return std::max(expireTime - time::steady_clock::now(), 0_ns);
  }

public:
  EventCallback callback;
  Scheduler::EventQueue::const_iterator queueIt;
  time::steady_clock::TimePoint expireTime;
  bool isExpired = false;
  uint32_t context = 0;
};

EventId::EventId(Scheduler& sched, weak_ptr<EventInfo> info)
  : CancelHandle([&sched, info] { sched.cancelImpl(info.lock()); })
  , m_info(std::move(info))
{
}

EventId::operator bool() const noexcept
{
  auto sp = m_info.lock();
  return sp != nullptr && !sp->isExpired;
}

void
EventId::reset() noexcept
{
  *this = {};
}

std::ostream&
operator<<(std::ostream& os, const EventId& eventId)
{
  return os << eventId.m_info.lock();
}

bool
Scheduler::EventQueueCompare::operator()(const shared_ptr<EventInfo>& a,
                                         const shared_ptr<EventInfo>& b) const noexcept
{
  return a->expireTime < b->expireTime;
}

Scheduler::Scheduler(DummyIoService& ioService)
{
}

Scheduler::~Scheduler()
{
  cancelAllEvents();
}

EventId
Scheduler::schedule(time::nanoseconds after, EventCallback callback)
{
  BOOST_ASSERT(callback != nullptr);

  auto i = m_queue.insert(make_shared<EventInfo>(after, std::move(callback), ns3::Simulator::GetContext()));
  (*i)->queueIt = i;

  if (!m_isEventExecuting && i == m_queue.begin()) {
    // the new event is the first one to expire
    this->scheduleNext();
  }

  return EventId(*this, *i);
}

void
Scheduler::cancelImpl(const shared_ptr<EventInfo>& info)
{
  if (info == nullptr || info->isExpired) {
    return;
  }

  if (m_timerEvent) {
    if (!m_timerEvent->IsExpired()) {
      ns3::Simulator::Remove(*m_timerEvent);
    }
    m_timerEvent.reset();
  }
  m_queue.erase(info->queueIt);

  if (!m_isEventExecuting) {
    this->scheduleNext();
  }
}

void
Scheduler::cancelAllEvents()
{
  m_queue.clear();
  if (m_timerEvent) {
    if (!m_timerEvent->IsExpired()) {
      ns3::Simulator::Remove(*m_timerEvent);
    }
    m_timerEvent.reset();
  }
}

void
Scheduler::scheduleNext()
{
auto now = ns3::Simulator::Now();
  if (!m_queue.empty()) {
	  //Check for event duplicates
     if(now.GetSeconds() > 0 && m_nextScheduled.GetNanoSeconds() == (ns3::NanoSeconds((*m_queue.begin())->expiresFromNow().count()).GetNanoSeconds()+ now.GetNanoSeconds()))  return;
     else m_nextScheduled = ns3::Time::From((ns3::NanoSeconds((*m_queue.begin())->expiresFromNow().count()).GetNanoSeconds()+ now.GetNanoSeconds()),ns3::Time::NS);
     m_timerEvent = ns3::Simulator::Schedule(ns3::NanoSeconds((*m_queue.begin())->expiresFromNow().count()),
                                            &Scheduler::executeEvent, this);
  }
}

void
Scheduler::executeEvent()
{
  m_isEventExecuting = true;

  m_timerEvent.reset();
  BOOST_SCOPE_EXIT(this_) {
    this_->m_isEventExecuting = false;
    this_->scheduleNext();
  } BOOST_SCOPE_EXIT_END

  // process all expired events
  auto now = time::steady_clock::now();
auto ns3Now = ns3::Simulator::Now();
  while (!m_queue.empty()) {
    auto head = m_queue.begin();
    shared_ptr<EventInfo> info = *head;
    if (info->expireTime > now) {
      break;
    }

    m_queue.erase(head);
    info->isExpired = true;
    if (ns3::Simulator::GetContext() == info->context) {
      info->callback();
    }
    else {
      ns3::Simulator::ScheduleWithContext(info->context, ns3::Seconds(0), ns3::MakeEvent(info->callback));
    }
  }
}

} // namespace scheduler
} // namespace ndn

max_stars_repo_name: gtorresz/ndn-cxx-PEC

max_issues_repo_name: gtorresz/ndn-cxx-PEC

max_forks_repo_name: gtorresz/ndn-cxx-PEC


text:
/* =========================================================================
   Copyright (c) 2010-2014, Institute for Microelectronics,
                            Institute for Analysis and Scientific Computing,
                            TU Wien.
   Portions of this software are copyright by UChicago Argonne, LLC.

                            -----------------
                  ViennaCL - The Vienna Computing Library
                            -----------------

   Project Head:    Karl Rupp                   rupp@iue.tuwien.ac.at

   (A list of authors and contributors can be found in the PDF manual)

   License:         MIT (X11), see file LICENSE in the base directory
============================================================================= */

/*
Solutions for testdata were generated with Scilab line:

M=fscanfMat('nsm1.example');e=spec(M);e=gsort(e);rr=real(e);ii=imag(e);e=cat(1, rr, ii); s=strcat(string(e), ' ');write('tmp', s);
*/

#ifndef NDEBUG
  #define NDEBUG
#endif

//#define VIENNACL_DEBUG_ALL
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <vector>

#include "viennacl/linalg/prod.hpp"
#include "viennacl/linalg/qr-method.hpp"

#include <examples/benchmarks/benchmark-utils.hpp>

#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/matrix.hpp>

namespace ublas = boost::numeric::ublas;

typedef float ScalarType;

const ScalarType EPS = 0.0001f;

void read_matrix_size(std::fstream& f, std::size_t& sz)
{
    if(!f.is_open())
    {
        throw std::invalid_argument("File is not opened");
    }

    f >> sz;
}

template <typename MatrixLayout>
void read_matrix_body(std::fstream& f, viennacl::matrix<ScalarType, MatrixLayout>& A)
{
    if(!f.is_open())
    {
        throw std::invalid_argument("File is not opened");
    }

    boost::numeric::ublas::matrix<ScalarType> h_A(A.size1(), A.size2());

    for(std::size_t i = 0; i < h_A.size1(); i++) {
        for(std::size_t j = 0; j < h_A.size2(); j++) {
            ScalarType val = 0.0;
            f >> val;
            h_A(i, j) = val;
        }
    }

    viennacl::copy(h_A, A);
}

void read_vector_body(std::fstream& f, std::vector<ScalarType>& v) {
    if(!f.is_open())
        throw std::invalid_argument("File is not opened");

    for(std::size_t i = 0; i < v.size(); i++)
    {
            ScalarType val = 0.0;
            f >> val;
            v[i] = val;
    }
}

template <typename MatrixLayout>
bool check_tridiag(viennacl::matrix<ScalarType, MatrixLayout>& A_orig)
{
    ublas::matrix<ScalarType> A(A_orig.size1(), A_orig.size2());
    viennacl::copy(A_orig, A);

    for (unsigned int i = 0; i < A.size1(); i++) {
        for (unsigned int j = 0; j < A.size2(); j++) {
            if ((std::abs(A(i, j)) > EPS) && ((i - 1) != j) && (i != j) && ((i + 1) != j))
            {
                // std::cout << "Failed at " << i << " " << j << " " << A(i, j) << "\n";
                return false;
            }
        }
    }
    return true;
}

template <typename MatrixLayout>
bool check_hessenberg(viennacl::matrix<ScalarType, MatrixLayout>& A_orig)
{
    ublas::matrix<ScalarType> A(A_orig.size1(), A_orig.size2());
    viennacl::copy(A_orig, A);

    for (std::size_t i = 0; i < A.size1(); i++) {
        for (std::size_t j = 0; j < A.size2(); j++) {
            if ((std::abs(A(i, j)) > EPS) && (i > (j + 1)))
            {
                // std::cout << "Failed at " << i << " " << j << " " << A(i, j) << "\n";
                return false;
            }
        }
    }
    return true;
}

ScalarType matrix_compare(ublas::matrix<ScalarType>& res,
                            ublas::matrix<ScalarType>& ref)
{
    ScalarType diff = 0.0;
    ScalarType mx = 0.0;

    for(std::size_t i = 0; i < res.size1(); i++)
    {
        for(std::size_t j = 0; j < res.size2(); j++)
        {
            diff = std::max(diff, std::abs(res(i, j) - ref(i, j)));
            mx = std::max(mx, res(i, j));
        }
    }

    return diff / mx;
}

ScalarType vector_compare(std::vector<ScalarType> & res,
                          std::vector<ScalarType> & ref)
{
    std::sort(ref.begin(), ref.end());
    std::sort(res.begin(), res.end());

    ScalarType diff = 0.0;
    ScalarType mx = 0.0;
    for(size_t i = 0; i < res.size(); i++)
    {
        diff = std::max(diff, std::abs(res[i] - ref[i]));
        mx = std::max(mx, res[i]);
    }

    return diff / mx;
}

template <typename MatrixLayout>
void matrix_print(viennacl::matrix<ScalarType, MatrixLayout>& A)
{
    for (unsigned int i = 0; i < A.size1(); i++) {
        for (unsigned int j = 0; j < A.size2(); j++)
           std::cout << std::fixed << A(i, j) << "\t";
        std::cout << "\n";
    }
}

template <typename MatrixLayout>
void test_eigen(const std::string& fn, bool is_symm)
{
    std::cout << "Reading..." << "\n";
    std::size_t sz;
    // read file
    std::fstream f(fn.c_str(), std::fstream::in);
    //read size of input matrix
    read_matrix_size(f, sz);

    if (viennacl::is_row_major<MatrixLayout>::value)
      std::cout << "Testing row-major matrix of size " << sz << "-by-" << sz << std::endl;
    else
      std::cout << "Testing column-major matrix of size " << sz << "-by-" << sz << std::endl;

    viennacl::matrix<ScalarType> A_input(sz, sz), A_ref(sz, sz), Q(sz, sz);
    // reference vector with reference values from file
    std::vector<ScalarType> eigen_ref_re(sz);
    // calculated real eigenvalues
    std::vector<ScalarType> eigen_re(sz);
    // calculated im. eigenvalues
    std::vector<ScalarType> eigen_im(sz);

    // read input matrix from file
    read_matrix_body(f, A_input);
    // read reference eigenvalues from file
    read_vector_body(f, eigen_ref_re);

    f.close();

    A_ref = A_input;

    std::cout << "Calculation..." << "\n";

    Timer timer;
    timer.start();
    // Start the calculation
    if(is_symm)
        viennacl::linalg::qr_method_sym(A_input, Q, eigen_re);
    else
        viennacl::linalg::qr_method_nsm(A_input, Q, eigen_re, eigen_im);
/*

    std::cout << "\n\n Matrix A: \n\n";
    matrix_print(A_input);
    std::cout << "\n\n";

    std::cout << "\n\n Matrix Q: \n\n";
    matrix_print(Q);
    std::cout << "\n\n";
*/

    double time_spend = timer.get();

    std::cout << "Verification..." << "\n";

    bool is_hessenberg = check_hessenberg(A_input);
    bool is_tridiag = check_tridiag(A_input);

    ublas::matrix<ScalarType> A_ref_ublas(sz, sz), A_input_ublas(sz, sz), Q_ublas(sz, sz), result1(sz, sz), result2(sz, sz);
    viennacl::copy(A_ref, A_ref_ublas);
    viennacl::copy(A_input, A_input_ublas);
    viennacl::copy(Q, Q_ublas);

    // compute result1 = ublas::prod(Q_ublas, A_input_ublas);   (terribly slow when using ublas directly)
    for (std::size_t i=0; i<result1.size1(); ++i)
      for (std::size_t j=0; j<result1.size2(); ++j)
      {
        ScalarType value = 0;
        for (std::size_t k=0; k<Q_ublas.size2(); ++k)
          value += Q_ublas(i, k) * A_input_ublas(k, j);
        result1(i,j) = value;
      }
    // compute result2 = ublas::prod(A_ref_ublas, Q_ublas);   (terribly slow when using ublas directly)
    for (std::size_t i=0; i<result2.size1(); ++i)
      for (std::size_t j=0; j<result2.size2(); ++j)
      {
        ScalarType value = 0;
        for (std::size_t k=0; k<A_ref_ublas.size2(); ++k)
          value += A_ref_ublas(i, k) * Q_ublas(k, j);
        result2(i,j) = value;
      }

    ScalarType prods_diff = matrix_compare(result1, result2);
    ScalarType eigen_diff = vector_compare(eigen_re, eigen_ref_re);

    bool is_ok = is_hessenberg;

    if(is_symm)
        is_ok = is_ok && is_tridiag;

    is_ok = is_ok && (eigen_diff < EPS);
    is_ok = is_ok && (prods_diff < EPS);

    // std::cout << A_ref << "\n";
    // std::cout << A_input << "\n";
    // std::cout << Q << "\n";
    // std::cout << eigen_re << "\n";
    // std::cout << eigen_im << "\n";
    // std::cout << eigen_ref_re << "\n";
    // std::cout << eigen_ref_im << "\n";

    // std::cout << result1 << "\n";
    // std::cout << result2 << "\n";
    // std::cout << eigen_ref << "\n";
    // std::cout << eigen << "\n";

    printf("%6s [%dx%d] %40s time = %.4f\n", is_ok?"[[OK]]":"[FAIL]", (int)A_ref.size1(), (int)A_ref.size2(), fn.c_str(), time_spend);
    printf("tridiagonal = %d, hessenberg = %d prod-diff = %f eigen-diff = %f\n", is_tridiag, is_hessenberg, prods_diff, eigen_diff);
    std::cout << std::endl << std::endl;

    if (!is_ok)
      exit(EXIT_FAILURE);

}

int main()
{

  test_eigen<viennacl::row_major>("../../examples/testdata/eigen/symm5.example", true);
 // test_eigen<viennacl::row_major>("../../examples/testdata/eigen/symm3.example", true);  // Computation of this matrix takes very long

  test_eigen<viennacl::column_major>("../../examples/testdata/eigen/symm5.example", true);
//  test_eigen<viennacl::column_major>("../../examples/testdata/eigen/symm3.example", true);

#ifdef VIENNACL_WITH_OPENCL
  test_eigen<viennacl::row_major>("../../examples/testdata/eigen/nsm2.example", false);
#endif
  //test_eigen<viennacl::row_major>("../../examples/testdata/eigen/nsm2.example", false);
  //test_eigen("../../examples/testdata/eigen/nsm3.example", false);
  //test_eigen("../../examples/testdata/eigen/nsm4.example", false); //Note: This test suffers from round-off errors in single precision, hence disabled

  std::cout << std::endl;
  std::cout << "------- Test completed --------" << std::endl;
  std::cout << std::endl;

  return EXIT_SUCCESS;
}


text:
// Copyright 2014 Renato Tegon Forti, Antony Polukhin.
// Copyright 2015-2019 Antony Polukhin.
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)

//[plugcpp_my_plugin_static
#include <boost/dll/alias.hpp>                          // for BOOST_DLL_ALIAS
#include <boost/shared_ptr.hpp>
#include "../tutorial_common/my_plugin_api.hpp"

namespace my_namespace {
    boost::shared_ptr<my_plugin_api> create_plugin();   // Forward declaration
} // namespace my_namespace

BOOST_DLL_ALIAS(
    my_namespace::create_plugin,                        // <-- this function is exported with...
    create_plugin                                       // <-- ...this alias name
)
//]


text:
// Copyright 2021 by FORTYSS

#ifndef INCLUDE_FTPFILE_HPP_
#define INCLUDE_FTPFILE_HPP_

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

using path = boost::filesystem::path;
using directory_iterator = boost::filesystem::directory_iterator;
using filesystem_error = boost::filesystem::filesystem_error;
using string = std::string;

struct Account {
 private:
  int data;
  string ac_name;
  string br_name;
  bool type;

 public:
  explicit Account(const path&);
  explicit Account(
      string acc_name, int dat = 0, string brok_name ="", bool typ = true);
  static string cutter(const string&);

  static inline bool cor_file(const path&);

  void setter(const string&, const string&, const string&);

  int get_data() const;

  string get_ac_name() const;

  string get_br_name() const;

  void inp_data(int);

  void inp_br_name(string);

  bool get_type();

  void print(std::ostream&);
};

class FTPFile {
 public:
  explicit FTPFile(const path&);
  void Check(const path& pat);
  void Unique(std::vector<string>);
  std::vector<string> AcName();
  friend std::ostream& operator << (std::ostream&,const FTPFile&);
  void OutAll (std::ostream&) const;
  void OutUnique(std::ostream&) const;

 private:
  std::vector<Account> all_ac;
  std::vector<Account> unic_ac;
  std::vector<int> count_ac;
};

#endif // INCLUDE_FTPFILE_HPP_


text:
#ifndef TYPE_PRINT_HPP_INCLUDED
#define TYPE_PRINT_HPP_INCLUDED

#include "../config.hpp"
#include "../string/string.hpp"
#include "../string/inline_string.hpp"
#include "../fundamental/for_each_exec.hpp"

#ifdef HAS_BOOST_STRING_ALGORITHM
#include <boost/algorithm/string/replace.hpp>
#endif

#include <iostream>
#include <sstream>

#if defined(CLANG) || defined(GCC)
#include <typeinfo>

#ifndef __BORLANDC__
#	include <cxxabi.h>
#endif

namespace mplex {
    template <typename T, unsigned bufferSize = 1 << 16>
    static std::ostream& stream_demangled(std::ostream &stream)
	{
#ifndef __BORLANDC__
		char buffer[bufferSize];
		int status = 0;
		std::size_t bufSizeCpy = bufferSize;
		abi::__cxa_demangle(typeid(T).name(), buffer, &bufSizeCpy, &status);
		stream << buffer;
#else
		stream << typeid(T).name();
#endif
		return stream;
    }
}
#else
namespace mplex {
    template <typename T, unsigned bufferSize = 1 << 16>
    static std::ostream& stream_demangled(std::ostream &stream)
    {
        stream << typeid(T).name();
        return stream;
    }
}
#endif

namespace mplex {
    namespace internal {
        template <typename Sequence, unsigned ReverseCounter>
        struct print_sequence {
            static inline void print(std::ostream& stream, char const* glue)
            {
                stream_demangled <typename std::tuple_element <print_sequence <Sequence, 1>::size_ - ReverseCounter, Sequence >::type> (stream);
                stream << glue;

                print_sequence <Sequence, ReverseCounter - 1>::print(stream, glue);
            }
        };

        template <typename Sequence>
        struct print_sequence <Sequence, 1> {
            enum {
                size_ = std::tuple_size <Sequence>::value
            };

            static inline void print(std::ostream& stream, char const *glue)
            {
                stream_demangled <typename std::tuple_element <size_ - 1, Sequence >::type> (stream);
                stream << glue;
            }
        };

        template <typename Glue>
        struct print_tuple_impl {
            template <typename Tuple>
            struct apply {
                static inline void execute(std::ostream& stream) {
                    print_sequence <Tuple, std::tuple_size <Tuple>::value>::print(stream, Glue::c_str);
                }
            };
        };
    }

    template <typename StringList, typename Glue = SHORT_STRING(" ")>
    inline std::ostream& print_string_list(std::ostream& stream = std::cout) {
        for_each <StringList, print_string<Glue> >::execute(stream);
        return stream;
    }

    template <typename T>
    inline std::ostream& print_single(std::ostream& stream = std::cout) {
        stream_demangled<T>(stream);
        return stream;
    }

    template <typename Tuple, typename Glue = SHORT_STRING(", ")>
    inline std::ostream& print_tuple(std::ostream& stream = std::cout) {
        internal::print_tuple_impl <Glue>::template apply <Tuple>::execute(stream);
        return stream;
    }

    // WARNING! THIS MAKE THE OUTPUT LESS CORRECT, BUT MORE READABLE
    #ifdef HAS_BOOST_STRING_ALGORITHM
    inline std::string declutter_mplex_type_name (std::string const& typenom) {
        std::string result = typenom;

        auto replace = [&](std::string const& what, std::string const& with) {
            boost::ireplace_all (result, what, with);
        };

        replace ("std::integral_constant<int, ", "int_<");
        replace ("std::integral_constant<long, ", "long_<");
        replace ("std::integral_constant<short, ", "short_<");
        replace ("std::integral_constant<unsigned, ", "unsigned_<");
        replace ("std::integral_constant<unsigned int, ", "unsigned_<");
        replace ("std::integral_constant<long long, ", "long_long_<");
        replace ("std::integral_constant<unsigned long long, ", "unsigned_long_long_<");
        replace ("std::integral_constant<char, ", "char_<");
        replace ("std::integral_constant<unsigned char, ", "unsigned_char_<");
        replace ("std::integral_constant<bool, ", "bool_<");

        // placeholders
        replace ("mplex::placeholders::_<1u>", "_1");
        replace ("mplex::placeholders::_<2u>", "_2");
        replace ("mplex::placeholders::_<3u>", "_3");
        replace ("mplex::placeholders::_<4u>", "_4");
        replace ("mplex::placeholders::_<5u>", "_5");
        replace ("mplex::placeholders::_<6u>", "_6");
        replace ("mplex::placeholders::_<7u>", "_7");
        replace ("mplex::placeholders::_<8u>", "_8");
        replace ("mplex::placeholders::_<9u>", "_9");
        replace ("mplex::placeholders::_<10u>", "_10");
        replace ("mplex::placeholders::_<11u>", "_11");
        replace ("mplex::placeholders::_<12u>", "_12");
        replace ("mplex::placeholders::_<13u>", "_13");
        replace ("mplex::placeholders::_<14u>", "_14");
        replace ("mplex::placeholders::_<15u>", "_15");
        replace ("mplex::placeholders::_<16u>", "_16");
        replace ("mplex::placeholders::_<17u>", "_17");
        replace ("mplex::placeholders::_<18u>", "_18");
        replace ("mplex::placeholders::_<19u>", "_19");
        replace ("mplex::placeholders::_<20u>", "_20");

        replace (" >", ">");

        replace ("mplex::", "");

        replace ("mplex::internal", "intern");
        replace ("std::tuple", "tuple");

        for (int i = 0x20 /* space */; i != 127; ++i)
        {
            std::string c;
            c.push_back((char)i);
            replace(std::string("(char)") + std::to_string(i), std::string("'") + c + "'");
        }

        return result;
    }

    template <typename T>
    inline std::ostream& print_single_decluttered (std::ostream& stream = std::cout) {
        std::stringstream sstr;
        stream_demangled<T>(sstr);
        stream << declutter_mplex_type_name(sstr.str());
        return stream;
    }

    #endif
}

#endif // TYPE_PRINT_HPP_INCLUDED


text:
#include "diary.h"

#include <vector>
#include <string>

#include <glog/logging.h>

#include <boost/date_time.hpp>
#include <boost/format.hpp>
#include <boost/algorithm/string/join.hpp>

namespace rows {

    Diary::Diary()
            : date_(boost::date_time::not_a_date_time),
              events_() {}

    Diary::Diary(boost::gregorian::date date, std::vector<rows::Event> events)
            : date_(date),
              events_(std::move(events)) {}

    Diary::Diary(const Diary &other)
            : date_(other.date_),
              events_(other.events_) {}

    Diary::Diary(Diary &&other) noexcept
            : date_(other.date_),
              events_(std::move(other.events_)) {}

    Diary &Diary::operator=(const Diary &other) {
        date_ = other.date_;
        events_ = other.events_;
        return *this;
    }

    Diary &Diary::operator=(Diary &&other) noexcept {
        date_ = other.date_;
        events_ = std::move(other.events_);
        return *this;
    }

    bool Diary::operator==(const Diary &other) const {
        return date_ == other.date_
               && events_ == other.events_;
    }

    bool Diary::operator!=(const Diary &other) const {
        return !operator==(other);
    }

    const boost::gregorian::date &Diary::date() const {
        return date_;
    }

    // TODO: using hardcoded constant to compute breaks is likely to cause problems
    std::vector<rows::Event> Diary::Breaks(const boost::posix_time::time_period &time_horizon) const {
        if (events_.empty()) {
            return {rows::Event(time_horizon)};
        }

        auto breaks = std::vector<Event>();
        breaks.emplace_back(
                boost::posix_time::time_period{boost::posix_time::ptime{events_.front().begin().date()},
                                               events_.front().begin().time_of_day()});

        const auto events_size = events_.size();
        for (int index = 1; index < events_size; ++index) {
            const auto last_event_finish = events_[index - 1].end();
            const auto current_event_start = events_[index].begin();
            breaks.emplace_back(boost::posix_time::time_period{last_event_finish, current_event_start});
        }

        breaks.emplace_back(boost::posix_time::time_period{events_.back().end(), time_horizon.end()});
        return breaks;
    }

    const std::vector<rows::Event> &Diary::events() const {
        return events_;
    }

    boost::posix_time::ptime::time_duration_type Diary::begin_time() const {
        if (events_.empty()) {
            return {};
        }

        return events_.front().begin().time_of_day();
    }

    boost::posix_time::ptime Diary::begin_date_time() const {
        if (events_.empty()) {
            return boost::posix_time::not_a_date_time;
        }

        return events_.front().begin();
    }

    boost::posix_time::ptime::time_duration_type Diary::end_time() const {
        if (events_.empty()) {
            return {};
        }

        return events_.back().end().time_of_day();
    }

    boost::posix_time::ptime Diary::end_date_time() const {
        if (events_.empty()) {
            return boost::posix_time::not_a_date_time;
        }

        return events_.back().end();
    }

    boost::posix_time::ptime::time_duration_type Diary::duration() const {
        boost::posix_time::ptime::time_duration_type duration;
        for (const auto &event : events_) {
            duration += event.duration();
        }
        return duration;
    }

    std::ostream &operator<<(std::ostream &out, const Diary &object) {
        std::vector<std::string> events;
        for (const auto &event : object.events_) {
            std::stringstream stream;
            stream << event;
            events.emplace_back(stream.str());
        }

        out << boost::format("(%1%, [%2%])")
               % object.date_
               % boost::algorithm::join(events, ", ");
        return out;
    }

    // requires evens in diary to be sorted
    Diary Diary::Intersect(const Diary &other) const {
        DCHECK_EQ(date_, other.date_);

        auto left_events_it = std::begin(events_);
        auto right_events_it = std::begin(other.events_);
        const auto left_events_it_end = std::end(events_);
        const auto right_events_it_end = std::end(other.events_);

        std::vector<rows::Event> overlapping_events;
        while ((left_events_it != left_events_it_end) && (right_events_it != right_events_it_end)) {
            if (right_events_it->end() > left_events_it->end()) {
                // left finishes faster

                if (left_events_it->end() > right_events_it->begin()) {
                    const auto begin = std::max(left_events_it->begin(), right_events_it->begin());
                    if (begin < left_events_it->end()) {
                        overlapping_events.emplace_back(boost::posix_time::time_period(begin, left_events_it->end()));
                    }
                }

                ++left_events_it;
            } else if (left_events_it->end() > right_events_it->end()) {
                // right finishes faster

                if (right_events_it->end() > left_events_it->begin()) {
                    const auto begin = std::max(left_events_it->begin(), right_events_it->begin());
                    if (begin < right_events_it->end()) {
                        overlapping_events.emplace_back(boost::posix_time::time_period(begin, right_events_it->end()));
                    }
                }

                ++right_events_it;
            } else {
                // both finish at the same time
                const auto begin = std::max(left_events_it->begin(), right_events_it->begin());
                if (begin < left_events_it->end()) {
                    overlapping_events.emplace_back(boost::posix_time::time_period(begin, left_events_it->end()));
                }

                ++left_events_it;
                ++right_events_it;
            }
        }

        return {date_, overlapping_events};
    }

    bool Diary::IsAvailable(const boost::posix_time::ptime date_time,
                            const boost::posix_time::time_duration adjustment) const {
        for (const auto &event : events_) {
            if (event.Contains(date_time)) {
                return true;
            }
        }

        if (adjustment.total_seconds() > 0 && !events_.empty()) {
            return ((date_time < events_.front().begin()) && ((events_.front().begin() - date_time) <= adjustment))
                   || ((date_time > events_.back().end()) && ((date_time - events_.back().end()) <= adjustment));
        }

        return false;
    }
}

max_stars_repo_name: pmateusz/cordia

max_issues_repo_name: pmateusz/cordia

max_forks_repo_name: pmateusz/cordia


text: #include <boost/preprocessor/facilities/is_empty.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#ifndef QUADRIC_H
#define QUADRIC_H

#include <Core/RaCore.hpp>
#include <Core/Math/LinearAlgebra.hpp>

#include <Eigen/Eigenvalues>

namespace Ra
{
    namespace Core
    {

        /// A representation for quadratic equation as
        /// v^T A v + 2 b^T v + c
        ///
        /// Reminder on ProgressiveMesh
        /// ---------------------------
        ///
        ///     Calculate the Quadric of the edge Qe = sum(Qf) with f all the faces adjacent
        ///     to e
        ///
        ///     Calculate vmin = Ae^(-1) be                with Qe = (Ae, be, ce)
        ///
        ///     Calculate the error on the edge
        ///         error = vmin^T Ae vmin + 2 be^T vmin + ce       with Qe = (Ae, be, ce)

        //template<int _DIM = 3>
        template<int _DIM>
        class Quadric
        {
        public:
            static constexpr int DIM = _DIM;
            using Matrix = Eigen::Matrix<Scalar, DIM, DIM>;
            using Vector = Eigen::Matrix<Scalar, DIM, 1>;

            /// Construct an initialized quadric.
            Quadric();

            /// Construct and initialize a quadric.
            Quadric(const Matrix &a, const Vector &b, double c) : m_a(a), m_b(b), m_c(c) {}

            /// Construct a quadric from an other.
            Quadric(const Quadric<DIM> &q);

            /// Create a quadric from a normal vector n and the scalar which
            /// represent the distance from the plane of normal n to the origin
            /// \see compute
            Quadric(const Vector& n, Scalar ndotp);

            ~Quadric();

            /// Getters and setters

            inline const Matrix& getA() const;
            inline void setA(const Matrix &a);

            inline const Vector& getB() const;
            inline void setB(const Vector &b);

            inline const double & getC() const;
            inline void setC(const double &c);

            /// Create a quadric from a normal vector n and the scalar which
            /// represent the distance from the plane of normal n to the origin
            /// \deprecated Use constructor instead
            void compute(const Vector& n, double ndotp);

            /// Computes eigen values and vectors of matrix A
            inline typename Eigen::EigenSolver<Matrix3>::EigenvalueType computeEigenValuesA();
            inline typename Eigen::EigenSolver<Matrix3>::EigenvectorsType computeEigenVectorsA();

            /// Operators

            inline Quadric operator+(const Quadric& q) const;
            inline Quadric operator*(const Scalar scal);

            inline Quadric& operator+=(const Quadric& q);
            inline Quadric& operator*=(Scalar scal);

        private:

            Matrix m_a;
            Vector m_b;
            double m_c;
        };

    }

}

#include <Core/Math/Quadric.inl>

#endif // QUADRIC_H

max_stars_repo_name: nmellado/Radium-Engine

max_issues_repo_name: nmellado/Radium-Engine

max_forks_repo_name: nmellado/Radium-Engine


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

#ifndef BOOST_BEAST_WEBSOCKET_DETAIL_SAVED_HANDLER_HPP
#define BOOST_BEAST_WEBSOCKET_DETAIL_SAVED_HANDLER_HPP

#include <boost/beast/core/detail/allocator.hpp>
#include <boost/asio/associated_allocator.hpp>
#include <boost/asio/associated_executor.hpp>
#include <boost/asio/executor_work_guard.hpp>
#include <boost/assert.hpp>
#include <memory>
#include <utility>

namespace boost {
namespace beast {
namespace websocket {
namespace detail {

// A container that holds a suspended, asynchronous composed
// operation. The contained object may be invoked later to
// resume the operation, or the container may be destroyed.
//
class saved_handler
{
    struct base
    {
        base() = default;
        base(base &&) = delete;
        base(base const&) = delete;
        virtual void destroy() = 0;
        virtual void invoke() = 0;

    protected:
        ~base() = default;
    };

    template<class Handler>
    class impl : public base
    {
        Handler h_;
        net::executor_work_guard<
            net::associated_executor_t<Handler>> wg_;

    public:
        template<class DeducedHandler>
        impl(DeducedHandler&& h)
            : h_(std::forward<DeducedHandler>(h))
            , wg_(net::get_associated_executor(h_))
        {
        }

        void
        destroy() override
        {
            using A = typename beast::detail::allocator_traits<
                net::associated_allocator_t<
                    Handler>>::template rebind_alloc<impl>;
            using alloc_traits =
                beast::detail::allocator_traits<A>;
            Handler h(std::move(h_));
            A alloc(net::get_associated_allocator(h));
            alloc_traits::destroy(alloc, this);
            alloc_traits::deallocate(alloc, this, 1);
        }

        void
        invoke() override
        {
            using A = typename beast::detail::allocator_traits<
                net::associated_allocator_t<
                    Handler>>::template rebind_alloc<impl>;
            using alloc_traits =
                beast::detail::allocator_traits<A>;
            Handler h(std::move(h_));
            A alloc(net::get_associated_allocator(h));
            alloc_traits::destroy(alloc, this);
            alloc_traits::deallocate(alloc, this, 1);
            h();
        }
    };

    base* p_ = nullptr;

public:
    saved_handler() = default;
    saved_handler(saved_handler const&) = delete;
    saved_handler& operator=(saved_handler const&) = delete;

    ~saved_handler()
    {
        if(p_)
            p_->destroy();
    }

    saved_handler(saved_handler&& other)
    {
        boost::ignore_unused(other);
        // Moving a saved handler that
        // owns an object is illegal
        BOOST_ASSERT(! other.p_);
    }

    saved_handler&
    operator=(saved_handler&& other)
    {
        boost::ignore_unused(other);
        // Moving a saved handler that
        // owns an object is illegal
        BOOST_ASSERT(! p_);
        BOOST_ASSERT(! other.p_);
        return *this;
    }

    template<class Handler>
    void
    emplace(Handler&& handler)
    {
        // Can't emplace twice without invoke
        BOOST_ASSERT(! p_);
        using A = typename beast::detail::allocator_traits<
            net::associated_allocator_t<Handler>>::template
                rebind_alloc<impl<Handler>>;
        using alloc_traits =
            beast::detail::allocator_traits<A>;
        A alloc(net::get_associated_allocator(handler));
        auto const d =
            [&alloc](impl<Handler>* p)
            {
                alloc_traits::deallocate(alloc, p, 1);
            };
        std::unique_ptr<impl<Handler>, decltype(d)> p(
            alloc_traits::allocate(alloc, 1), d);
        alloc_traits::construct(alloc, p.get(),
            std::forward<Handler>(handler));
        p_ = p.release();
    }

    explicit
    operator bool() const noexcept
    {
        return p_ != nullptr;
    }

    bool
    maybe_invoke()
    {
        if(p_)
        {
            auto const h = p_;
            p_ = nullptr;
            h->invoke();
            return true;
        }
        return false;
    }
};

} // detail
} // websocket
} // beast
} // boost

#endif

max_stars_repo_name: octobanana/beast

max_issues_repo_name: octobanana/beast

max_forks_repo_name: octobanana/beast


text:
#include <ctime>
#include <vector>
#include <math.h>

#include <Eigen/Dense>
#include <Eigen/Core>

#include "mex.h"
#include "nlopt.hpp"

int counter = 0;

using namespace std;
using namespace Eigen;
using Eigen::MatrixXd;

struct mFuncData
{
	int numDims, numSamples;
	MatrixXd X, Y;
	MatrixXd XX, YX;
};

double myfunc(unsigned n, const double *inW, double *grad, void *inData)
{
	++counter;

	mFuncData* data = (mFuncData*)inData;
	MatrixXd W = Map<MatrixXd>((double*)inW, data->numDims, data->numDims);

	// 2 * W*(X*X') - Y*X' - Y*X';
	if (grad)
	{
		clock_t beginM = clock();

		mwSize size[2]; size[0] = data->numDims;  size[1] = data->numDims;
		mxArray* prhs[2];
		prhs[0] = mxCreateNumericArray(2, size, mxDOUBLE_CLASS, mxREAL);
		double* WMatlab = (double*)mxGetData(prhs[0]);
		Map<MatrixXd>(WMatlab, data->numDims, data->numDims) = W;
		prhs[1] = mxCreateNumericArray(2, size, mxDOUBLE_CLASS, mxREAL);
		double* XMatlab = (double*)mxGetData(prhs[1]);
		Map<MatrixXd>(XMatlab, data->numDims, data->numDims) = data->XX;

		mxArray* plhs[1];
		int output = mexCallMATLAB(1, plhs, 2, prhs, "mtimes");
		double* res = (double*)mxGetData(plhs[0]);
		MatrixXd newW = Map<MatrixXd>(res, data->numDims, data->numDims);
		MatrixXd gradient = 2.0*newW - data->YX - data->YX;

		Map<MatrixXd>(grad, data->numDims, data->numDims) = gradient;

		clock_t endM = clock();
		// mexPrintf("time step newgrad: %f\n", difftime(endM, beginM));
	}

	// val = norm(W*X - Y);
	clock_t begin1 = clock();
	MatrixXd res = W*data->X - data->Y;
	clock_t end1 = clock();
	//mexPrintf("time step main: %f\n", difftime(end1, begin1));

	// Matlab call
	clock_t beginM = clock();
	mxArray* prhs[1];
	mwSize size[2]; size[0] = data->numDims;  size[1] = data->numSamples;
	prhs[0] = mxCreateNumericArray(2, size, mxDOUBLE_CLASS, mxREAL);
	double* resMatlab = (double*)mxGetData(prhs[0]);
	Map<MatrixXd>(resMatlab, data->numDims, data->numSamples) = res;
	mxArray* plhs[1];
	mexCallMATLAB(1, plhs, 1, prhs, "norm");
	double norm = (double)mxGetScalar(plhs[0]);
	clock_t endM = clock();
	// mexPrintf("time step norm: %f\n", difftime(endM, beginM));
	mexPrintf("[iter %d] energy: %f\n", counter, norm);

	/*
	clock_t begin2 = clock();
	double energy = res.operatorNorm();
	clock_t end2 = clock();
	mexPrintf("time step norm: %f\n", difftime(end2, begin2));
	mexPrintf("[iter %d] energy: %f\n", counter, energy);
	return energy;
	*/

	return norm;
}

typedef struct
{
	double a, b;
} mConstraintData;

double myconstraint(unsigned n, const double *x, double *grad, void *data)
{
	mConstraintData *d = (mConstraintData *)data;
	double a = d->a, b = d->b;
	if (grad) {
		grad[0] = 3 * a * (a*x[0] + b) * (a*x[0] + b);
		grad[1] = -1.0;
	}
	return ((a*x[0] + b) * (a*x[0] + b) * (a*x[0] + b) - x[1]);
}

void run_optimiser(double* x, double* residual, int numDims, int numSamples, double* srcCentres, double* tgtCentres)
{
	nlopt_opt opt;

	opt = nlopt_create(NLOPT_LD_MMA, numDims*numDims); /* algorithm and dimensionality */
	// opt = nlopt_create(NLOPT_LN_COBYLA, numDims*numDims); /* algorithm and dimensionality */

	mFuncData funcData;
	funcData.numDims = numDims;
	funcData.numSamples = numSamples;
	funcData.X = Map<MatrixXd>(srcCentres, numDims, numSamples);
	funcData.Y = Map<MatrixXd>(tgtCentres, numDims, numSamples);

	// Precomputation
	funcData.XX = funcData.X * funcData.X.transpose();
	funcData.YX = funcData.Y * funcData.X.transpose();

	nlopt_set_min_objective(opt, myfunc, &funcData);
	nlopt_set_xtol_rel(opt, 1e-4);
	nlopt_set_maxeval(opt, 25);

	// Constraints:
	//mConstraintData data[2] = { { 2, 0 }, { -1, 1 } };
	//nlopt_add_inequality_constraint(opt, myconstraint, &data[0], 1e-4);
	//nlopt_add_inequality_constraint(opt, myconstraint, &data[1], 1e-4);

	if (nlopt_optimize(opt, x, residual) < 0)
		printf("nlopt failed!\n");
	else
		printf("found minimum after %d evaluations with residual %f\n", counter, *residual);

	nlopt_destroy(opt);
}

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
	/* Macros for the input arguments */
	#define srcCentres_IN prhs[0]
	#define tgtCentres_IN prhs[1]

	/* Macros for the output arguments */
	#define x_OUT plhs[0]
	#define residual_OUT plhs[1]

	/* Check correctness of input/output arguments */
	if (nrhs < 2 || nrhs > 2)
		mexErrMsgTxt("Wrong number of input arguments.");
	else if (nlhs > 2)
		mexErrMsgTxt("Too many output arguments.");

	/* Get input data */
	double* srcCentres = (double*)mxGetData(srcCentres_IN);
	double* tgtCentres = (double*)mxGetData(tgtCentres_IN);
	int numDims = (int)mxGetM(srcCentres_IN);
	int numSamples = (int)mxGetN(srcCentres_IN);

	/* Create output data */
	x_OUT = mxCreateNumericMatrix(numDims, numDims, mxDOUBLE_CLASS, mxREAL);
	double* x = (double*)mxGetData(x_OUT);
	residual_OUT = mxCreateNumericMatrix(1, 1, mxDOUBLE_CLASS, mxREAL);
	double* residual = (double*)mxGetData(residual_OUT);

	// Initial guess (Id matrix)
	for (int idx = 0; idx < numDims*numDims; ++idx)
	{
		if (idx % (numDims + 1) == 0)
			x[idx] = 1.0;
		else
			x[idx] = 0.0;
	}

	// Reset counter
	counter = 0;

	/* Call method */
	run_optimiser(x, residual, numDims, numSamples, srcCentres, tgtCentres);

	return;
}


text:
// ParticleUtilities.cpp
// Copyright 2019 Mikko Lauri
//
// 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.

#include "ParticleUtilities.h"
#include <boost/random/uniform_real_distribution.hpp>
#include <eigen3/Eigen/Dense>
#include "common.hpp"

namespace pgi {
double normalize(std::vector<double>& weights) {
  if (weights.empty()) {
    return 0.0;
  } else {
    Eigen::Map<Eigen::VectorXd> w(weights.data(), weights.size());
    const double wsum = w.lpNorm<1>();
    if (!is_almost_zero(wsum)) w /= wsum;
    return wsum;
  }
}

// Implements systematic resampling
void resample(const std::vector<double>& weights,
              std::vector<std::size_t>& resample_indices, PRNG& rng) {
  resample_indices.resize(weights.size());
  double cdf = 0.0;
  std::size_t curr_index = 0;

  const double incr = 1.0 / static_cast<double>(weights.size());
  boost::random::uniform_real_distribution<double> U(0, incr);
  double u = rng(U);
  for (auto& resample_index : resample_indices) {
    while (u > cdf) {
      cdf += weights[curr_index];
      ++curr_index;
    }
    resample_index = curr_index - 1;
    u += incr;
  }
}

double effective_size(const std::vector<double>& weights) {
  Eigen::Map<const Eigen::VectorXd> w(weights.data(), weights.size());
  return 1.0 / w.squaredNorm();
}

}  // namespace pgi


text:
/**
 * @file fslogicWrapper.cc
 * @author Konrad Zemek
 * @copyright (C) 2015 ACK CYFRONET AGH
 * @copyright This software is released under the MIT license cited in
 * 'LICENSE.txt'
 */

#include "nullHelper.h"

#include "communication/communicator.h"
#include "context.h"
#include "events/manager.h"
#include "fslogic/fsLogic.h"
#include "fslogic/withUuids.h"
#include "messages/configuration.h"
#include "options/options.h"
#include "scheduler.h"

#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/make_shared.hpp>
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <folly/fibers/Baton.h>
#include <folly/fibers/FiberManager.h>
#include <folly/fibers/FiberManagerMap.h>
#include <folly/fibers/ForEach.h>
#if FUSE_USE_VERSION > 30
#include <fuse3/fuse.h>
#else
#include <fuse/fuse.h>
#endif

#include <atomic>
#include <memory>

using namespace one;
using namespace one::client;
using namespace one::communication;
using namespace boost::python;
using namespace std::literals;

struct Stat {
    time_t atime;
    time_t mtime;
    time_t ctime;
    int gid;
    int uid;
    int mode;
    size_t size;

    bool operator==(const Stat &o)
    {
        return atime == o.atime && mtime == o.mtime && ctime == o.ctime &&
            gid == o.gid && uid == o.uid && mode == o.mode && size == o.size;
    }
};

struct Ubuf {
    time_t actime;
    time_t modtime;
};

struct Xattr {
    std::string name;
    std::string value;
};

class ReleaseGIL {
public:
    ReleaseGIL()
        : threadState{PyEval_SaveThread(), PyEval_RestoreThread}
    {
    }

private:
    std::unique_ptr<PyThreadState, decltype(&PyEval_RestoreThread)> threadState;
};

class HelpersCacheProxy : public one::client::cache::HelpersCache {
public:
    using HelpersCache::HelpersCache;

    std::shared_ptr<NullHelperMock> m_helper =
        std::make_shared<NullHelperMock>();

    folly::Future<HelperPtr> get(const folly::fbstring &,
        const folly::fbstring &, const folly::fbstring &, const bool,
        const bool) override
    {
        m_helper->m_real.setNeedsDataConsistencyCheck(
            m_needsDataConsistencyCheck);
        return folly::makeFuture<HelperPtr>(m_helper);
    }

    bool m_needsDataConsistencyCheck{false};
};

constexpr auto FSLOGIC_PROXY_RETRY_COUNT = 2;

class FsLogicProxy {
public:
    FsLogicProxy(std::shared_ptr<Context> context,
        unsigned int metadataCacheSize = 10000,
        unsigned int dropDirectoryCacheAfter = 60)
        : m_helpersCache{new HelpersCacheProxy(*context->communicator(),
              context->scheduler(), *context->options())}
        , m_fsLogic{context, std::make_shared<messages::Configuration>(),
              std::unique_ptr<HelpersCacheProxy>{m_helpersCache},
              metadataCacheSize, false, false, 10s,
              std::chrono::seconds{dropDirectoryCacheAfter},
              makeRunInFiber() /*[](auto f) { f(); }*/}
        , m_context{context}
    {
        m_fsLogic.setMaxRetryCount(FSLOGIC_PROXY_RETRY_COUNT);
        m_thread = std::thread{[this] {
            folly::setThreadName("InFiber");
            m_eventBase.loopForever();
        }};
    }

    void stop()
    {
        if (!m_stopped.test_and_set()) {
            ReleaseGIL guard;

            folly::Promise<folly::Unit> stopped;
            auto stoppedFuture = stopped.getFuture();

            m_fiberManager.addTaskRemote(
                [this, stopped = std::move(stopped)]() mutable {
                    m_context->communicator()->stop();
                    stopped.setValue();
                });

            std::move(stoppedFuture).get();
        }
    }

    ~FsLogicProxy()
    {
        stop();

        ReleaseGIL guard;
        m_eventBase.terminateLoopSoon();
        m_thread.join();
    }

    void failHelper()
    {
        m_helpersCache->m_helper->set_ec(
            std::make_error_code(std::errc::owner_dead));
    }

    struct statvfs statfs(std::string uuid)
    {
        ReleaseGIL guard;

        return m_fiberManager
            .addTaskRemoteFuture(
                [this, uuid]() { return m_fsLogic.statfs(uuid); })
            .get();
    }

    Stat lookup(std::string parentUuid, std::string name)
    {
        ReleaseGIL guard;

        auto attr = m_fiberManager
                        .addTaskRemoteFuture([this, parentUuid, name]() {
                            return m_fsLogic.lookup(parentUuid, name);
                        })
                        .get();

        auto statbuf = one::client::fslogic::detail::toStatbuf(attr, 123);
        Stat stat;

        stat.atime = statbuf.st_atime;
        stat.mtime = statbuf.st_mtime;
        stat.ctime = statbuf.st_ctime;
        stat.gid = statbuf.st_gid;
        stat.uid = statbuf.st_uid;
        stat.mode = statbuf.st_mode;
        stat.size = statbuf.st_size;

        return stat;
    }

    Stat getattr(std::string uuid)
    {
        ReleaseGIL guard;

        auto attr = m_fiberManager
                        .addTaskRemoteFuture(
                            [this, uuid]() { return m_fsLogic.getattr(uuid); })
                        .get();

        auto statbuf = one::client::fslogic::detail::toStatbuf(attr, 123);
        Stat stat;

        stat.atime = statbuf.st_atime;
        stat.mtime = statbuf.st_mtime;
        stat.ctime = statbuf.st_ctime;
        stat.gid = statbuf.st_gid;
        stat.uid = statbuf.st_uid;
        stat.mode = statbuf.st_mode;
        stat.size = statbuf.st_size;

        return stat;
    }

    void mkdir(std::string parentUuid, std::string name, int mode)
    {
        ReleaseGIL guard;
        m_fiberManager
            .addTaskRemoteFuture([this, parentUuid, name, mode]() {
                m_fsLogic.mkdir(parentUuid, name, mode);
            })
            .get();
    }

    void unlink(std::string parentUuid, std::string name)
    {
        ReleaseGIL guard;
        m_fiberManager
            .addTaskRemoteFuture([this, parentUuid, name]() {
                m_fsLogic.unlink(parentUuid, name);
            })
            .get();
    }

    void rmdir(std::string parentUuid, std::string name)
    {
        unlink(parentUuid, name);
    }

    void rename(std::string parentUuid, std::string name,
        std::string newParentUuid, std::string newName)
    {
        ReleaseGIL guard;
        m_fiberManager
            .addTaskRemoteFuture(
                [this, parentUuid, name, newParentUuid, newName]() {
                    m_fsLogic.rename(parentUuid, name, newParentUuid, newName);
                })
            .get();
    }

    void chmod(std::string uuid, int mode)
    {
        ReleaseGIL guard;

        m_fiberManager
            .addTaskRemoteFuture([this, uuid, mode]() {
                struct stat statbuf = {};
                statbuf.st_mode = mode;
                m_fsLogic.setattr(uuid, statbuf, FUSE_SET_ATTR_MODE);
            })
            .get();
    }

    void utime(std::string uuid)
    {
        ReleaseGIL guard;

#if defined(FUSE_SET_ATTR_ATIME_NOW) && defined(FUSE_SET_ATTR_MTIME_NOW)

        m_fiberManager
            .addTaskRemoteFuture([this, uuid]() {
                struct stat statbuf = {};
                m_fsLogic.setattr(uuid, statbuf,
                    FUSE_SET_ATTR_ATIME_NOW | FUSE_SET_ATTR_MTIME_NOW);
            })
            .get();
#endif
    }

    void utime_buf(std::string uuid, Ubuf ubuf)
    {
        ReleaseGIL guard;

        m_fiberManager
            .addTaskRemoteFuture([this, uuid, ubuf]() {
                struct stat statbuf = {};
                statbuf.st_atime = ubuf.actime;
                statbuf.st_mtime = ubuf.modtime;

                m_fsLogic.setattr(
                    uuid, statbuf, FUSE_SET_ATTR_ATIME | FUSE_SET_ATTR_MTIME);
            })
            .get();
    }

    int opendir(std::string uuid)
    {
        ReleaseGIL guard;

        return m_fiberManager
            .addTaskRemoteFuture(
                [this, uuid]() { return m_fsLogic.opendir(uuid); })
            .get();
    }

    void releasedir(std::string uuid, int fuseHandleId)
    {
        ReleaseGIL guard;
        m_fiberManager
            .addTaskRemoteFuture([this, uuid, fuseHandleId]() {
                m_fsLogic.releasedir(uuid, fuseHandleId);
            })
            .get();
    }

    std::vector<std::string> readdir(
        std::string uuid, int chunkSize, int offset)
    {
        ReleaseGIL guard;

        return m_fiberManager
            .addTaskRemoteFuture([this, uuid, chunkSize, offset]() {
                std::vector<std::string> children;
                for (auto &name : m_fsLogic.readdir(uuid, chunkSize, offset))
                    children.emplace_back(name.toStdString());

                return children;
            })
            .get();
    }

    void mknod(std::string parentUuid, std::string name, int mode)
    {
        ReleaseGIL guard;
        m_fiberManager
            .addTaskRemoteFuture([this, parentUuid, name, mode]() {
                m_fsLogic.mknod(parentUuid, name, mode);
            })
            .get();
    }

    void link(std::string uuid, std::string parentUuid, std::string name)
    {
        ReleaseGIL guard;
        m_fiberManager
            .addTaskRemoteFuture([this, uuid, parentUuid, name]() {
                m_fsLogic.link(uuid, parentUuid, name);
            })
            .get();
    }

    void symlink(std::string parentUuid, std::string name, std::string link)
    {
        ReleaseGIL guard;
        m_fiberManager
            .addTaskRemoteFuture([this, parentUuid, name, link]() {
                m_fsLogic.symlink(parentUuid, name, link);
            })
            .get();
    }

    std::string readlink(std::string uuid)
    {
        ReleaseGIL guard;
        return m_fiberManager
            .addTaskRemoteFuture([this, uuid]() {
                return m_fsLogic.readlink(uuid).toStdString();
            })
            .get();
    }

    int open(std::string uuid, int flags)
    {
        ReleaseGIL guard;
        return m_fiberManager
            .addTaskRemoteFuture(
                [this, uuid, flags]() { return m_fsLogic.open(uuid, flags); })
            .get();
    }

    std::string read(std::string uuid, int fileHandleId, int offset, int size)
    {
        ReleaseGIL guard;
        return m_fiberManager
            .addTaskRemoteFuture([this, uuid, fileHandleId, offset, size]() {
                auto buf = m_fsLogic.read(uuid, fileHandleId, offset, size, {},
                    FSLOGIC_PROXY_RETRY_COUNT);

                std::string data;
                buf.appendToString(data);

                return data;
            })
            .get();
    }

    int write(std::string uuid, int fuseHandleId, int offset, int size)
    {
        ReleaseGIL guard;

        return m_fiberManager
            .addTaskRemoteFuture([this, uuid, fuseHandleId, offset, size]() {
                auto buf = folly::IOBuf::create(size);
                buf->append(size);

                return m_fsLogic.write(uuid, fuseHandleId, offset,
                    std::move(buf), FSLOGIC_PROXY_RETRY_COUNT);
            })
            .get();
    }

    void release(std::string uuid, int fuseHandleId)
    {
        ReleaseGIL guard;
        m_fiberManager
            .addTaskRemoteFuture([this, uuid, fuseHandleId]() {
                m_fsLogic.release(uuid, fuseHandleId);
            })
            .get();
    }

    void truncate(std::string uuid, int size)
    {
        ReleaseGIL guard;

        m_fiberManager
            .addTaskRemoteFuture([this, uuid, size]() {
                struct stat statbuf = {};
                statbuf.st_size = size;
                m_fsLogic.setattr(uuid, statbuf, FUSE_SET_ATTR_SIZE);
            })
            .get();
    }

    std::vector<std::string> listxattr(std::string uuid)
    {
        ReleaseGIL guard;

        return m_fiberManager
            .addTaskRemoteFuture([this, uuid]() {
                std::vector<std::string> xattrs;
                for (auto &xattrName : m_fsLogic.listxattr(uuid))
                    xattrs.emplace_back(xattrName.toStdString());

                return xattrs;
            })
            .get();
    }

    Xattr getxattr(std::string uuid, std::string name)
    {
        ReleaseGIL guard;

        return m_fiberManager
            .addTaskRemoteFuture([this, uuid, name]() {
                auto xattrValue = m_fsLogic.getxattr(uuid, name);

                Xattr xattr;
                xattr.name = name;
                xattr.value = xattrValue.toStdString();

                return xattr;
            })
            .get();
    }

    void setxattr(std::string uuid, std::string name, std::string value,
        bool create, bool replace)
    {
        ReleaseGIL guard;
        m_fiberManager
            .addTaskRemoteFuture([this, uuid, name, value, create, replace]() {
                m_fsLogic.setxattr(uuid, name, value, create, replace);
            })
            .get();
    }

    void removexattr(std::string uuid, std::string name)
    {
        ReleaseGIL guard;
        m_fiberManager
            .addTaskRemoteFuture(
                [this, uuid, name]() { m_fsLogic.removexattr(uuid, name); })
            .get();
    }

    int metadataCacheSize()
    {
        ReleaseGIL guard;
        return m_fsLogic.metadataCache().size();
    }

    bool metadataCacheContains(std::string uuid)
    {
        ReleaseGIL guard;
        return m_fiberManager
            .addTaskRemoteFuture([this, uuid]() {
                return m_fsLogic.metadataCache().contains(uuid);
            })
            .get();
    }

    void expect_call_sh_open(std::string uuid, int times)
    {
        m_helpersCache->m_helper->expect_call_sh_open(uuid, times);
    }

    void expect_call_sh_release(std::string uuid, int times)
    {
        m_helpersCache->m_helper->expect_call_sh_release(uuid, times);
    }

    bool verify_and_clear_expectations()
    {
        return m_helpersCache->m_helper->verify_and_clear_expectations();
    }

    void setNeedsDataConsistencyCheck(bool needsDataConsistencyCheck)
    {
        m_helpersCache->m_needsDataConsistencyCheck = needsDataConsistencyCheck;
    }

private:
    folly::fibers::FiberManager::Options makeFiberManagerOpts()
    {
        folly::fibers::FiberManager::Options opts;
        opts.stackSize = FIBER_STACK_SIZE;
        return opts;
    }

    std::function<void(folly::Function<void()>)> makeRunInFiber()
    {
        return [this](folly::Function<void()> fun) mutable {
            m_fiberManager.addTaskRemote(std::move(fun));
        };
    }

    folly::EventBase m_eventBase;
    folly::fibers::FiberManager &m_fiberManager{
        folly::fibers::getFiberManager(m_eventBase, makeFiberManagerOpts())};

    std::thread m_thread;
    std::atomic_flag m_stopped = ATOMIC_FLAG_INIT;

    HelpersCacheProxy *m_helpersCache;
    fslogic::FsLogic m_fsLogic;
    std::shared_ptr<Context> m_context;
};

namespace {
boost::shared_ptr<FsLogicProxy> create(std::string ip, int port,
    unsigned int metadataCacheSize, unsigned int dropDirectoryCacheAfter,
    std::string cliOptions = "")
{
    FLAGS_minloglevel = 1;

    auto communicator = std::make_shared<Communicator>(/*connections*/ 10,
        /*threads*/ 1, ip, port,
        /*verifyServerCertificate*/ false, /*upgrade to clproto*/ true,
        /*perform handshake*/ false);

    auto context = std::make_shared<Context>();
    context->setScheduler(std::make_shared<Scheduler>(1));
    context->setCommunicator(communicator);

    const auto globalConfigPath = boost::filesystem::unique_path();

    auto options = std::make_shared<options::Options>();
    std::vector<std::string> optionsTokens;
    std::string optionsString = std::string("oneclient -H ") + ip +
        " -t TOKEN " + cliOptions + " mountpoint";
    boost::split(optionsTokens, optionsString, boost::is_any_of(" "),
        boost::token_compress_on);

    std::vector<const char *> cmdArgs;
    std::transform(optionsTokens.begin(), optionsTokens.end(),
        std::back_inserter(cmdArgs), [](auto &s) { return s.c_str(); });

    options->parse(cmdArgs.size(), cmdArgs.data());
    context->setOptions(std::move(options));

    communicator->setScheduler(context->scheduler());

    communicator->connect();

    return boost::make_shared<FsLogicProxy>(
        context, metadataCacheSize, dropDirectoryCacheAfter);
}

int regularMode() { return S_IFREG; }

void translate(const std::errc &err)
{
    PyErr_SetString(
        PyExc_RuntimeError, std::make_error_code(err).message().c_str());
}
}

BOOST_PYTHON_MODULE(fslogic)
{
    PyEval_InitThreads();
    register_exception_translator<std::errc>(&translate);

    class_<struct statvfs>("StatVFS")
        .def_readonly("bsize", &statvfs::f_bsize)
        .def_readonly("frsize", &statvfs::f_frsize)
        .def_readonly("blocks", &statvfs::f_blocks)
        .def_readonly("bfree", &statvfs::f_bfree)
        .def_readonly("bavail", &statvfs::f_bavail)
        .def_readonly("files", &statvfs::f_files)
        .def_readonly("ffree", &statvfs::f_ffree)
        .def_readonly("favail", &statvfs::f_favail)
        .def_readonly("fsid", &statvfs::f_fsid)
        .def_readonly("flag", &statvfs::f_flag)
        .def_readonly("namemax", &statvfs::f_namemax);

    class_<Stat>("Stat")
        .def_readonly("atime", &Stat::atime)
        .def_readonly("mtime", &Stat::mtime)
        .def_readonly("ctime", &Stat::ctime)
        .def_readonly("gid", &Stat::gid)
        .def_readonly("uid", &Stat::uid)
        .def_readonly("mode", &Stat::mode)
        .def_readonly("size", &Stat::size)
        .def("__eq__", &Stat::operator==);

    class_<Ubuf>("Ubuf")
        .def_readwrite("actime", &Ubuf::actime)
        .def_readwrite("modtime", &Ubuf::modtime);

    class_<Xattr>("Xattr")
        .def_readwrite("name", &Xattr::name)
        .def_readwrite("value", &Xattr::value);

    class_<std::vector<std::string>>("vector").def(
        vector_indexing_suite<std::vector<std::string>>());

    class_<FsLogicProxy, boost::noncopyable>("FsLogicProxy", no_init)
        .def("__init__", make_constructor(create))
        .def("failHelper", &FsLogicProxy::failHelper)
        .def("stop", &FsLogicProxy::stop)
        .def("statfs", &FsLogicProxy::statfs)
        .def("getattr", &FsLogicProxy::getattr)
        .def("lookup", &FsLogicProxy::lookup)
        .def("mkdir", &FsLogicProxy::mkdir)
        .def("unlink", &FsLogicProxy::unlink)
        .def("rmdir", &FsLogicProxy::rmdir)
        .def("rename", &FsLogicProxy::rename)
        .def("chmod", &FsLogicProxy::chmod)
        .def("utime", &FsLogicProxy::utime)
        .def("utime_buf", &FsLogicProxy::utime_buf)
        .def("opendir", &FsLogicProxy::opendir)
        .def("releasedir", &FsLogicProxy::releasedir)
        .def("readdir", &FsLogicProxy::readdir)
        .def("mknod", &FsLogicProxy::mknod)
        .def("link", &FsLogicProxy::link)
        .def("symlink", &FsLogicProxy::symlink)
        .def("readlink", &FsLogicProxy::readlink)
        .def("open", &FsLogicProxy::open)
        .def("read", &FsLogicProxy::read)
        .def("write", &FsLogicProxy::write)
        .def("release", &FsLogicProxy::release)
        .def("truncate", &FsLogicProxy::truncate)
        .def("listxattr", &FsLogicProxy::listxattr)
        .def("getxattr", &FsLogicProxy::getxattr)
        .def("setxattr", &FsLogicProxy::setxattr)
        .def("removexattr", &FsLogicProxy::removexattr)
        .def("metadata_cache_size", &FsLogicProxy::metadataCacheSize)
        .def("metadata_cache_contains", &FsLogicProxy::metadataCacheContains)
        .def("set_needs_data_consistency_check",
            &FsLogicProxy::setNeedsDataConsistencyCheck)
        .def("expect_call_sh_open", &FsLogicProxy::expect_call_sh_open)
        .def("expect_call_sh_release", &FsLogicProxy::expect_call_sh_release)
        .def("verify_and_clear_expectations",
            &FsLogicProxy::verify_and_clear_expectations);

    def("regularMode", &regularMode);
}

max_stars_repo_name: onedata/oneclient

max_issues_repo_name: onedata/oneclient

max_forks_repo_name: onedata/oneclient


text:
#include <armadillo>
#include <json.hpp>
#include <iostream>
#include <ForwardBackward.hpp>
#include <HSMM.hpp>
#include <memory>

using namespace arma;
using namespace hsmm;
using namespace std;
using json = nlohmann::json;

int main() {
    int ndurations = 4;
    int min_duration = 4;
    mat transition = {{0.0, 0.1, 0.4, 0.5},
                      {0.3, 0.0, 0.6, 0.1},
                      {0.2, 0.2, 0.0, 0.6},
                      {0.4, 0.4, 0.2, 0.0}};
    int nstates = transition.n_rows;
    vec pi(nstates, fill::eye);
    pi.fill(1.0/nstates);
    // mat durations(nstates, ndurations, fill::eye);
    mat durations =  {{0.0, 0.1, 0.4, 0.5},
                      {0.3, 0.0, 0.6, 0.1},
                      {0.2, 0.2, 0.0, 0.6},
                      {0.4, 0.4, 0.2, 0.0}};

    // Instantiating the emission process.
    vec means = {0, 5, 10, 15};
    vec std_devs =  {0.5, 1.0, 0.1, 2.0};
    shared_ptr<AbstractEmission> ptr_emission(new DummyGaussianEmission(
            means, std_devs));

    // Multivariate emission.
    mat mult_means(nstates, 2, fill::zeros);
    for(int i = 0; i < nstates; i++)
        mult_means.row(i).fill(i);
    shared_ptr<AbstractEmission> ptr_mult_emission(
            new DummyMultivariateGaussianEmission(mult_means, 0.1));

    // Instantiating the HSMM.
    HSMM dhsmm(ptr_emission, transition, pi, durations, min_duration);

    ivec hiddenStates, hiddenDurations;
    int nSampledSegments = 50;
    field<mat> samples = dhsmm.sampleSegments(nSampledSegments, hiddenStates,
            hiddenDurations);
    int nobs = samples.n_elem;

    cout << "Generated samples" << endl;
    // cout << samples << endl;
    cout << "Generated states and durations" << endl;
    cout << join_horiz(hiddenStates, hiddenDurations) << endl;

    mat alpha(nstates, nobs, fill::zeros);
    mat beta(nstates, nobs, fill::zeros);
    mat alpha_s(nstates, nobs, fill::zeros);
    mat beta_s(nstates, nobs, fill::zeros);
    vec beta_s_0(nstates, fill::zeros);
    cube eta(nstates, ndurations, nobs, fill::zeros);
    cube zeta(nstates, nstates, nobs - 1, fill::zeros);
    cube logpdf = dhsmm.computeEmissionsLogLikelihood(samples);
    Labels obs_segments;
    logsFB(log(transition), log(pi), log(durations), logpdf, obs_segments,
            alpha, beta, alpha_s, beta_s, beta_s_0, eta, zeta, min_duration,
            nobs);
    mat compare_alpha = exp(alpha);
    mat compare_alpha_s = exp(alpha_s);
    mat compare_beta = exp(beta);
    mat compare_beta_s = exp(beta_s);
    cube compare_eta = exp(eta);
    mat compare_beta_s_0 = exp(beta_s_0);
    cube pdf = dhsmm.computeEmissionsLikelihood(samples);
    FB(transition, pi, durations, pdf, obs_segments, alpha, beta, alpha_s,
            beta_s, beta_s_0, eta, min_duration, nobs);

    cout << "TEST" << endl;
    mat a = compare_beta - beta;
    mat b = compare_beta_s - beta_s;
    cube c = compare_eta - eta;
    mat d = compare_beta_s_0 - beta_s_0;
    mat e = compare_alpha - alpha;
    mat f = compare_alpha_s - alpha_s;
    cout << a.min() << " " << a.max() << endl;
    cout << b.min() << " " << b.max() << endl;
    cout << c.min() << " " << c.max() << endl;
    cout << d.min() << " " << d.max() << endl;
    cout << e.min() << " " << e.max() << endl;
    cout << f.min() << " " << f.max() << endl;

    cout << "Sums rows" << endl;
    cout << sum(alpha, 1) << endl;
    cout << sum(alpha_s, 1) << endl;
    cout << sum(beta, 1) << endl;
    cout << sum(beta_s, 1) << endl;

    imat psi_duration(nstates, nobs, fill::zeros);
    imat psi_state(nstates, nobs, fill::zeros);
    mat delta(nstates, nobs, fill::zeros);
    Viterbi(transition, pi, durations, logpdf, delta, psi_duration, psi_state,
            min_duration, nobs);
    cout << "Delta last column" << endl;
    cout << delta.col(nobs - 1) << endl;
    ivec viterbiStates, viterbiDurations;
    viterbiPath(psi_duration, psi_state, delta, viterbiStates,
            viterbiDurations);

    cout << "Viterbi states and durations" << endl;
    cout << join_horiz(viterbiStates, viterbiDurations) << endl;

    // Debug
    int differences = 0;
    if (viterbiStates.n_elem == hiddenStates.n_elem) {
        for(int t = 0; t < viterbiStates.n_elem; t++)
            if (hiddenStates(t) != viterbiStates(t))
                differences++;
        cout << " Differences: " << differences << endl;
    }
    else
        cout << "The dimensions don't match." << endl;

    // Generating multiple synthetic sequences.
    int nseq = 10;
    int nsegments = 100;
    field<field<mat>> mobs;
    field<ivec> mhs, mdur;
    mobs = dhsmm.sampleMultipleSequences(nseq, nsegments, mhs, mdur);

    // Initializing uniformly the transitions, initial state pmf and durations.
    transition.fill(1.0/(nstates-1));
    transition.diag().zeros();  // No self-loops.
    dhsmm.setTransition(transition);
    pi.fill(1.0/nstates);
    dhsmm.setPi(pi);
    durations.fill(1.0/ndurations);
    dhsmm.setDuration(durations);

    // Resetting emission parameters.
    vec new_means = {0.1, 0.2, 0.3, 30};
    vec new_std_devs = ones<vec>(nstates) * 10;
    shared_ptr<AbstractEmission> init_emission(new DummyGaussianEmission(
            new_means, new_std_devs));
    dhsmm.setEmission(init_emission);

    // Testing the learning algorithm.
    dhsmm.fit(mobs, 100, 1e-10);

    vec best_pi(nstates, fill::zeros);
    for(int s = 0; s < nseq; s++)
        best_pi(mhs(s)(0))++;
    best_pi /= nseq;
    cout << "Best initial state pmf we can aim at:" << endl << best_pi << endl;

    cout << "Learnt pi:" << endl;
    cout << dhsmm.pi_ << endl;

    cout << "Best transition matrix we can aim at:" << endl;
    mat prueba(nstates, nstates, fill::zeros);
    for(int s = 0; s < nseq; s++) {
        ivec& hiddenStates = mhs(s);
        for(int i = 0; i < hiddenStates.n_elem - 1; i++)
            prueba(hiddenStates(i), hiddenStates(i + 1))++;
    }
    mat pruebasum = sum(prueba, 1);
    for(int i = 0; i < nstates; i++)
        prueba.row(i) /= pruebasum(i);
    cout << prueba << endl;

    cout << "Learnt matrix:" << endl;
    cout << dhsmm.transition_ << endl;

    cout << "Best duration matrix we can aim at:" << endl;
    mat emp_durations(nstates, ndurations, fill::zeros);
    for(int s = 0; s < nseq; s++) {
        ivec& hiddenStates = mhs(s);
        ivec& hiddenDurations = mdur(s);
        for(int i = 0; i < hiddenStates.n_elem; i++)
            emp_durations(hiddenStates(i), hiddenDurations(i) - min_duration)++;
    }
    mat emp_durations_sum = sum(emp_durations, 1);
    for(int i = 0; i < nstates; i++)
        emp_durations.row(i) /= emp_durations_sum(i);
    cout << emp_durations << endl;
    cout << "Learnt durations:" << endl;
    cout << dhsmm.duration_ << endl;

    cout << "Learnt parameters (json)" << endl;
    json params = dhsmm.to_stream();
    cout << params.dump(4) << endl;
    return 0;
}

max_stars_repo_name: DiegoAE/BOSD

max_issues_repo_name: DiegoAE/BOSD

max_forks_repo_name: DiegoAE/BOSD