text:
/*********************************************************************/
/* Copyright (c) 2016, EPFL/Blue Brain Project                       */
/*                     Raphael Dumusc <raphael.dumusc@epfl.ch>       */
/* All rights reserved.                                              */
/*                                                                   */
/* Redistribution and use in source and binary forms, with or        */
/* without modification, are permitted provided that the following   */
/* conditions are met:                                               */
/*                                                                   */
/*   1. Redistributions of source code must retain the above         */
/*      copyright notice, this list of conditions and the following  */
/*      disclaimer.                                                  */
/*                                                                   */
/*   2. Redistributions in binary form must reproduce the above      */
/*      copyright notice, this list of conditions and the following  */
/*      disclaimer in the documentation and/or other materials       */
/*      provided with the distribution.                              */
/*                                                                   */
/*    THIS  SOFTWARE  IS  PROVIDED  BY  THE  ECOLE  POLYTECHNIQUE    */
/*    FEDERALE DE LAUSANNE  ''AS IS''  AND ANY EXPRESS OR IMPLIED    */
/*    WARRANTIES, INCLUDING, BUT  NOT  LIMITED  TO,  THE  IMPLIED    */
/*    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR  A PARTICULAR    */
/*    PURPOSE  ARE  DISCLAIMED.  IN  NO  EVENT  SHALL  THE  ECOLE    */
/*    POLYTECHNIQUE  FEDERALE  DE  LAUSANNE  OR  CONTRIBUTORS  BE    */
/*    LIABLE  FOR  ANY  DIRECT,  INDIRECT,  INCIDENTAL,  SPECIAL,    */
/*    EXEMPLARY,  OR  CONSEQUENTIAL  DAMAGES  (INCLUDING, BUT NOT    */
/*    LIMITED TO,  PROCUREMENT  OF  SUBSTITUTE GOODS OR SERVICES;    */
/*    LOSS OF USE, DATA, OR  PROFITS;  OR  BUSINESS INTERRUPTION)    */
/*    HOWEVER CAUSED AND  ON ANY THEORY OF LIABILITY,  WHETHER IN    */
/*    CONTRACT, STRICT LIABILITY,  OR TORT  (INCLUDING NEGLIGENCE    */
/*    OR OTHERWISE) ARISING  IN ANY WAY  OUT OF  THE USE OF  THIS    */
/*    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.   */
/*                                                                   */
/* The views and conclusions contained in the software and           */
/* documentation are those of the authors and should not be          */
/* interpreted as representing official policies, either expressed   */
/* or implied, of Ecole polytechnique federale de Lausanne.          */
/*********************************************************************/

#define BOOST_TEST_MODULE RestServerTests
#include <boost/test/unit_test.hpp>

#include "rest/RestServer.h"

#include <QNetworkAccessManager>
#include <QNetworkReply>

#include "MinimalGlobalQtApp.h"

using namespace rockets;

namespace
{
bool _isMethodForbidden(const QNetworkReply::NetworkError error)
{
    // QNetworkReply ContentAccessDenied and ContentOperationNotPermittedError
    //  correspond to HTTP error code 403
    if (error == QNetworkReply::ContentAccessDenied ||
        error == QNetworkReply::ContentOperationNotPermittedError)
        return true;
    return false;
}
}

BOOST_GLOBAL_FIXTURE(MinimalGlobalQtApp);

BOOST_AUTO_TEST_CASE(testDefaultPort)
{
    RestServer server;
    BOOST_CHECK_GT(server.getPort(), 0);
}

BOOST_AUTO_TEST_CASE(testUnavailablePort)
{
#ifndef __APPLE__
    const auto port = 80; // privileged port (<1024)
#else
    // Since OSX Mojave the ports below 1024 are no longer restricted to root.
    RestServer server;
    const auto port = server.getPort();
#endif
    BOOST_CHECK_THROW(RestServer server2{port}, std::runtime_error);
}

std::pair<std::string, QNetworkReply::NetworkError> sendHttpRequest(
    const QUrl& url, const http::Method method)
{
    // create custom temporary event loop on stack
    QEventLoop eventLoop;
    // quit the event-loop when the network request finished
    QNetworkAccessManager manager;
    QObject::connect(&manager, &QNetworkAccessManager::finished, &eventLoop,
                     &QEventLoop::quit);

    std::unique_ptr<QNetworkReply> reply;
    switch (method)
    {
    case http::Method::GET:
        reply.reset(manager.get(QNetworkRequest{url}));
        break;
    case http::Method::POST:
        reply.reset(manager.post(QNetworkRequest{url}, ""));
        break;
    case http::Method::PUT:
        reply.reset(manager.put(QNetworkRequest{url}, ""));
        break;
    case http::Method::OPTIONS:
        reply.reset(manager.sendCustomRequest(QNetworkRequest{url}, "OPTIONS"));
        break;
    case http::Method::DELETE:
        reply.reset(manager.deleteResource(QNetworkRequest{url}));
        break;
    case http::Method::PATCH:
        reply.reset(manager.sendCustomRequest(QNetworkRequest{url}, "PATCH"));
        break;
    case http::Method::ALL:
        break;
    }

    eventLoop.exec(); // blocks stack until "finished()" has been called

    const auto response = (reply->error() == QNetworkReply::NoError)
                              ? reply->readAll()
                              : reply->errorString();
    return std::make_pair(response.toStdString(), reply->error());
}

struct TestObject
{
    std::string json = "Hello World!";
};
std::string to_json(const TestObject& obj)
{
    return obj.json;
}

BOOST_AUTO_TEST_CASE(testServerReturnsSimpleContent)
{
    RestServer server;
    BOOST_REQUIRE_GT(server.getPort(), 0);

    TestObject test;
    server.handleGET("test", test);

    const auto url = QString("http://localhost:%1/test").arg(server.getPort());
    const auto response = sendHttpRequest(url, http::Method::GET);

    BOOST_CHECK_EQUAL(response.first, "Hello World!");
    BOOST_CHECK_EQUAL(response.second, int(QNetworkReply::NoError));
}

class MockRestServer : public RestServer
{
public:
    bool skipWhitelistCheck = true;

private:
    // Bypass hardcoded localhost exception for block()
    bool _isWhitelisted(const std::string&) const final
    {
        return skipWhitelistCheck;
    }
};

BOOST_AUTO_TEST_CASE(block_all_methods)
{
    MockRestServer server;

    for (int method = 0; method < int(http::Method::ALL); ++method)
    {
        server.handle(http::Method(method), "test", [](const http::Request&) {
            return http::make_ready_response(http::Code::OK);
        });
    };

    const auto url = QString("http://localhost:%1/test").arg(server.getPort());

    for (int method = 0; method < int(http::Method::ALL); ++method)
    {
        const auto response = sendHttpRequest(url, http::Method(method));
        BOOST_CHECK_EQUAL(response.second, int(QNetworkReply::NoError));
    }

    server.skipWhitelistCheck = false;

    for (int method = 0; method < int(http::Method::ALL); ++method)
    {
        server.block(http::Method(method));
        const auto response = sendHttpRequest(url, http::Method(method));
        // localhost is no longer whitelisted because of bypassWhitelist flag.
        BOOST_CHECK(_isMethodForbidden(response.second));
    }
}

BOOST_AUTO_TEST_CASE(test_whitelist)
{
    MockRestServer server;
    server.handle(http::Method::PUT, "test", [](const http::Request&) {
        return http::make_ready_response(http::Code::OK);
    });
    server.block(http::Method::PUT);

    const auto url = QString("http://localhost:%1/test").arg(server.getPort());

    server.skipWhitelistCheck = true;

    auto response = sendHttpRequest(url, http::Method::PUT);
    BOOST_CHECK_EQUAL(response.second, int(QNetworkReply::NoError));

    server.skipWhitelistCheck = false;

    response = sendHttpRequest(url, http::Method::PUT);
    BOOST_CHECK(_isMethodForbidden(response.second));
}

max_stars_repo_name: BlueBrain/Tide

max_issues_repo_name: BlueBrain/Tide

max_forks_repo_name: BlueBrain/Tide


text:
// NetlibExample1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include <boost/network/protocol/http/client.hpp>
#include <iostream>
#include "Logger.h"
#include "Crawler.h"
#include <Geography\Cities.h>
#include <Datastructures\parallel.h>
#include "app_settings.h"

bool read_app_settings(app_settings &_apps){
	std::string app_setting_file = R"(B:\Workspace\NetlibExample1\app_settings.txt)";
	AceLogger::Log("Reading app settings file at : " + app_setting_file);
	return _apps.read_settings(app_setting_file);
}

using namespace AceLogger;
int main(int argc, char *argv[]) {

	REGISTER_LOGGER("B:\\Logs", "NetLibExample", "0.0.0.1");
	app_settings apps;
	if (!read_app_settings(apps)){
		Log("Cannot continue as unable to read settings file.", LOG_ERROR);
		exit(0);
	}
	using namespace boost::network;
	Crawler crawler;

	std::string file_name = AceLogger::time_stamp_file_name();
	std::string file_dir = apps.p_output_dir;
	std::string file_path = file_dir+"\\"+file_name;
	if (!AceLogger::create_dir(file_dir)){
		Log("unable to create output dir", LOG_ERROR);
		file_path = "";
	}
	if (!apps.p_save_data)
		file_path = "";
	//crawler.Run("http://en.wikipedia.org/wiki/Main_Page",".*wikipedia\.org.*", file_path,false);
	//crawler.Run("http://www.cnn.com/", ".*wsj\.com.*", file_path,false);
	//crawler.Run("http://online.wsj.com", ".*wsj\.com.*", file_path,true);
	//crawler.Run("http://timesofindia.indiatimes.com/international-home", ".*indiatimes\.com.*", file_path, true);

	crawler.Run(apps.p_starting_web_address, apps.p_stay_within_pattern, file_path, apps.p_run_as_drain);

	return 0;
}

ext: cpp

max_stars_repo_name: PrakaramJoshi/NetLibExample

max_issues_repo_name: PrakaramJoshi/NetLibExample

max_forks_repo_name: PrakaramJoshi/NetLibExample


text:
/* Copyright (C) 2014 InfiniDB, Inc.

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License
   as published by the Free Software Foundation; version 2 of
   the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
   MA 02110-1301, USA. */

// $Id: tdriver.cpp 3495 2013-01-21 14:09:51Z rdempsey $
#include <string>
#include <stdexcept>
#include <iostream>
#include <fstream>
using namespace std;
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <boost/thread.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/scoped_array.hpp>
#include <boost/shared_ptr.hpp>

#include <cppunit/extensions/HelperMacros.h>

#include "threadpool.h"

int thecount = 0;
boost::mutex mutex;

class ThreadPoolTestSuite : public CppUnit::TestFixture
{

    CPPUNIT_TEST_SUITE( ThreadPoolTestSuite );

    CPPUNIT_TEST( test_1 );

    CPPUNIT_TEST_SUITE_END();

private:

    // Functor class
    struct foo
    {
        void operator ()()
        {
            for (int i = 0; i < 500; i++)
            {
                // simulate some work
                fData++;
            }

            boost::mutex::scoped_lock lock(mutex);

            std::cout << "count = " << ++thecount << ' ' << fData << std::endl;
        }

        foo(int i):
            fData(i)
        {}

        foo(const foo& copy)
            : fData(copy.fData)
        {}

        int fData;

    };

public:
    void setUp()
    {}

    void tearDown()
    {}

    void test_1()
    {

        threadpool::ThreadPool pool( 5, 10 );

        for (int y = 0; y < 10; y++)
        {
            foo bar(y);

            for (int i = 0; i < 10; ++i)
            {
                pool.invoke(bar);
            }

            // Wait until all of the queued up and in-progress work has finished
            pool.wait();
            pool.dump();
        }

    }

};

CPPUNIT_TEST_SUITE_REGISTRATION( ThreadPoolTestSuite );

#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>

int main( int argc, char** argv)
{
    CppUnit::TextUi::TestRunner runner;
    CppUnit::TestFactoryRegistry& registry = CppUnit::TestFactoryRegistry::getRegistry();
    runner.addTest( registry.makeTest() );
    bool wasSuccessful = runner.run( "", false );
    return (wasSuccessful ? 0 : 1);
}

max_stars_repo_name: zettadb/zettalib

max_issues_repo_name: zettadb/zettalib

max_forks_repo_name: zettadb/zettalib


text:
//
// Copyright (c) 2020 Kasper Laudrup (laudrup at stacktrace dot dk)
//
// 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 "async_echo_server.hpp"
#include "async_echo_client.hpp"

#include <boost/wintls.hpp>

#include <catch2/catch.hpp>

#include <boost/beast/_experimental/test/stream.hpp>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>

#include <fstream>
#include <string>
#include <thread>
#include <tuple>
#include <cstdint>

namespace net = boost::asio;
namespace asio_ssl = boost::asio::ssl;
using test_stream = boost::beast::test::stream;

namespace {
std::string generate_data(std::size_t size) {
  std::string ret(size, '\0');
  for (std::size_t i = 0; i < size - 1; ++i) {
  const char cur_char = i % 26;
    ret[i] = cur_char + 65;
  }
  return ret;
}

std::vector<char> pem_cert_bytes() {
  std::ifstream ifs{TEST_CERTIFICATE_PATH};
  REQUIRE(ifs.good());
  return {std::istreambuf_iterator<char>{ifs}, {}};
}

}

struct asio_ssl_client_context : public asio_ssl::context {
  asio_ssl_client_context()
    : asio_ssl::context(asio_ssl::context_base::tlsv12) {
    load_verify_file(TEST_CERTIFICATE_PATH);
  }
};

struct asio_ssl_server_context : public asio_ssl::context {
  asio_ssl_server_context()
    : asio_ssl::context(asio_ssl::context_base::tlsv12) {
    use_certificate_file(TEST_CERTIFICATE_PATH, asio_ssl::context_base::pem);
    use_private_key_file(TEST_PRIVATE_KEY_PATH, asio_ssl::context_base::pem);
  }
};

struct asio_ssl_client_stream {
  using handshake_type = asio_ssl::stream_base::handshake_type;

  template <class... Args>
  asio_ssl_client_stream(Args&&... args)
    : tst(std::forward<Args>(args)...)
    , stream(tst, ctx) {
  }

  asio_ssl_client_context ctx;
  test_stream tst;
  asio_ssl::stream<test_stream&> stream;
};

struct asio_ssl_server_stream {
  using handshake_type = asio_ssl::stream_base::handshake_type;

  template <class... Args>
  asio_ssl_server_stream(Args&&... args)
    : tst(std::forward<Args>(args)...)
    , stream(tst, ctx) {
  }

  asio_ssl_server_context ctx;
  test_stream tst;
  asio_ssl::stream<test_stream&> stream;
};

struct wintls_client_context : public boost::wintls::context {
  wintls_client_context()
    : boost::wintls::context(boost::wintls::method::system_default) {
    const auto x509 = pem_cert_bytes();
    const auto cert_ptr = x509_to_cert_context(net::buffer(x509), boost::wintls::file_format::pem);
    add_certificate_authority(cert_ptr.get());
  }
};

struct wintls_server_context : public boost::wintls::context {
  wintls_server_context()
    : boost::wintls::context(boost::wintls::method::system_default) {
    use_certificate_file(TEST_CERTIFICATE_PATH, boost::wintls::file_format::pem);
    use_private_key_file(TEST_PRIVATE_KEY_PATH, boost::wintls::file_format::pem);
  }
};

struct wintls_client_stream {
  using handshake_type = boost::wintls::handshake_type;

  template <class... Args>
  wintls_client_stream(Args&&... args)
    : tst(std::forward<Args>(args)...)
    , stream(tst, ctx) {
  }

  wintls_client_context ctx;
  test_stream tst;
  boost::wintls::stream<test_stream&> stream;
};

struct wintls_server_stream {
  using handshake_type = boost::wintls::handshake_type;

  template <class... Args>
  wintls_server_stream(Args&&... args)
    : tst(std::forward<Args>(args)...)
    , stream(tst, ctx) {
  }

  wintls_server_context ctx;
  test_stream tst;
  boost::wintls::stream<test_stream&> stream;
};

using TestTypes = std::tuple<std::tuple<asio_ssl_client_stream, asio_ssl_server_stream>,
                             std::tuple<wintls_client_stream, asio_ssl_server_stream>,
                             std::tuple<asio_ssl_client_stream, wintls_server_stream>,
                             std::tuple<wintls_client_stream, wintls_server_stream>>;

TEMPLATE_LIST_TEST_CASE("echo test", "", TestTypes) {
  using Client = typename std::tuple_element<0, TestType>::type;
  using Server = typename std::tuple_element<1, TestType>::type;

  auto test_data_size = GENERATE(0x100, 0x100 - 1, 0x100 + 1,
                                 0x1000, 0x1000 - 1, 0x1000 + 1,
                                 0x10000, 0x10000 - 1, 0x10000 + 1,
                                 0x100000, 0x100000 - 1, 0x100000 + 1);
  const std::string test_data = generate_data(test_data_size);

  boost::system::error_code client_ec{};
  boost::system::error_code server_ec{};

  net::io_context io_context;

  SECTION("sync test") {
    Client client(io_context);
    Server server(io_context);

    client.stream.next_layer().connect(server.stream.next_layer());

    // As the handshake requires multiple read and writes between client
    // and server, we have to run the synchronous version in a separate
    // thread. Unfortunately.
    std::thread server_handshake([&server, &server_ec]() {
      server.stream.handshake(Server::handshake_type::server, server_ec);
    });
    client.stream.handshake(Client::handshake_type::client, client_ec);
    REQUIRE_FALSE(client_ec);

    server_handshake.join();
    REQUIRE_FALSE(server_ec);

    net::write(client.stream, net::buffer(test_data));

    net::streambuf server_data;
    net::read_until(server.stream, server_data, '\0');
    net::write(server.stream, server_data);

    net::streambuf client_data;
    net::read_until(client.stream, client_data, '\0');

    // As a shutdown potentially requires multiple read and writes
    // between client and server, we have to run the synchronous version
    // in a separate thread. Unfortunately.
    std::thread server_shutdown([&server, &server_ec]() {
      server.stream.shutdown(server_ec);
    });
    client.stream.shutdown(client_ec);
    REQUIRE_FALSE(client_ec);

    server_shutdown.join();
    REQUIRE_FALSE(server_ec);

    CHECK(std::string(net::buffers_begin(client_data.data()),
                      net::buffers_begin(client_data.data()) + client_data.size()) == test_data);
  }

  SECTION("async test") {
    async_server<Server> server(io_context);
    async_client<Client> client(io_context, test_data);
    client.stream.next_layer().connect(server.stream.next_layer());
    server.run();
    client.run();
    io_context.run();
    CHECK(client.received_message() == test_data);
  }
}

max_stars_repo_name: creativedisassembly/boost-wintls

max_issues_repo_name: creativedisassembly/boost-wintls

max_forks_repo_name: creativedisassembly/boost-wintls


text:
/*
 *          Copyright Andrey Semashev 2007 - 2014.
 * 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)
 */
/*!
 * \file   light_rw_mutex.hpp
 * \author Andrey Semashev
 * \date   24.03.2009
 *
 * \brief  This header is the Boost.Log library implementation, see the library documentation
 *         at http://www.boost.org/doc/libs/release/libs/log/doc/html/index.html.
 */

#ifndef BOOST_LOG_DETAIL_LIGHT_RW_MUTEX_HPP_INCLUDED_
#define BOOST_LOG_DETAIL_LIGHT_RW_MUTEX_HPP_INCLUDED_

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

#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif

#ifndef BOOST_LOG_NO_THREADS

#include <boost/log/detail/header.hpp>

#if defined(BOOST_THREAD_POSIX) // This one can be defined by users, so it should go first
#define BOOST_LOG_LWRWMUTEX_USE_PTHREAD
#elif defined(BOOST_WINDOWS) && defined(BOOST_LOG_USE_WINNT6_API)
#define BOOST_LOG_LWRWMUTEX_USE_SRWLOCK
#elif defined(BOOST_HAS_PTHREADS)
#define BOOST_LOG_LWRWMUTEX_USE_PTHREAD
#endif

#if defined(BOOST_LOG_LWRWMUTEX_USE_SRWLOCK)

#if defined(BOOST_USE_WINDOWS_H)

#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0600 // _WIN32_WINNT_LONGHORN
#endif

#include <windows.h>

#else // defined(BOOST_USE_WINDOWS_H)

namespace boost {

BOOST_LOG_OPEN_NAMESPACE

namespace aux {

extern "C" {

struct SRWLOCK { void* p; };
__declspec(dllimport) void __stdcall InitializeSRWLock(SRWLOCK*);
__declspec(dllimport) void __stdcall ReleaseSRWLockExclusive(SRWLOCK*);
__declspec(dllimport) void __stdcall ReleaseSRWLockShared(SRWLOCK*);
__declspec(dllimport) void __stdcall AcquireSRWLockExclusive(SRWLOCK*);
__declspec(dllimport) void __stdcall AcquireSRWLockShared(SRWLOCK*);

} // extern "C"

} // namespace aux

BOOST_LOG_CLOSE_NAMESPACE // namespace log

} // namespace boost

#endif // BOOST_USE_WINDOWS_H

namespace boost {

BOOST_LOG_OPEN_NAMESPACE

namespace aux {

//! A light read/write mutex that uses WinNT 6 and later APIs
class light_rw_mutex
{
    SRWLOCK m_Mutex;

public:
    light_rw_mutex()
    {
        InitializeSRWLock(&m_Mutex);
    }
    void lock_shared()
    {
        AcquireSRWLockShared(&m_Mutex);
    }
    void unlock_shared()
    {
        ReleaseSRWLockShared(&m_Mutex);
    }
    void lock()
    {
        AcquireSRWLockExclusive(&m_Mutex);
    }
    void unlock()
    {
        ReleaseSRWLockExclusive(&m_Mutex);
    }

    // Noncopyable
    BOOST_DELETED_FUNCTION(light_rw_mutex(light_rw_mutex const&))
    BOOST_DELETED_FUNCTION(light_rw_mutex& operator= (light_rw_mutex const&))
};

} // namespace aux

BOOST_LOG_CLOSE_NAMESPACE // namespace log

} // namespace boost

#elif defined(BOOST_LOG_LWRWMUTEX_USE_PTHREAD)

#include <pthread.h>

namespace boost {

BOOST_LOG_OPEN_NAMESPACE

namespace aux {

//! A light read/write mutex that maps directly onto POSIX threading library
class light_rw_mutex
{
    pthread_rwlock_t m_Mutex;

public:
    light_rw_mutex()
    {
        pthread_rwlock_init(&m_Mutex, NULL);
    }
    ~light_rw_mutex()
    {
        pthread_rwlock_destroy(&m_Mutex);
    }
    void lock_shared()
    {
        pthread_rwlock_rdlock(&m_Mutex);
    }
    void unlock_shared()
    {
        pthread_rwlock_unlock(&m_Mutex);
    }
    void lock()
    {
        pthread_rwlock_wrlock(&m_Mutex);
    }
    void unlock()
    {
        pthread_rwlock_unlock(&m_Mutex);
    }

    // Noncopyable
    BOOST_DELETED_FUNCTION(light_rw_mutex(light_rw_mutex const&))
    BOOST_DELETED_FUNCTION(light_rw_mutex& operator= (light_rw_mutex const&))
};

} // namespace aux

BOOST_LOG_CLOSE_NAMESPACE // namespace log

} // namespace boost

#else

namespace boost {

BOOST_LOG_OPEN_NAMESPACE

namespace aux {

//! A light read/write mutex
class light_rw_mutex
{
    struct { void* p; } m_Mutex;

public:
    BOOST_LOG_API light_rw_mutex();
    BOOST_LOG_API ~light_rw_mutex();
    BOOST_LOG_API void lock_shared();
    BOOST_LOG_API void unlock_shared();
    BOOST_LOG_API void lock();
    BOOST_LOG_API void unlock();

    // Noncopyable
    BOOST_DELETED_FUNCTION(light_rw_mutex(light_rw_mutex const&))
    BOOST_DELETED_FUNCTION(light_rw_mutex& operator= (light_rw_mutex const&))
};

} // namespace aux

BOOST_LOG_CLOSE_NAMESPACE // namespace log

} // namespace boost

#endif

#include <boost/log/detail/footer.hpp>

#endif // BOOST_LOG_NO_THREADS

#endif // BOOST_LOG_DETAIL_LIGHT_RW_MUTEX_HPP_INCLUDED_

ext: hpp

max_stars_repo_name: bowlofstew/omim

max_issues_repo_name: bowlofstew/omim

max_forks_repo_name: bowlofstew/omim


text:
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
//    names, trademarks, service marks, or product names of the Licensor
//    and its affiliates, except as required to comply with Section 4(c) of
//    the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//

#include "pxr/pxr.h"
#include "pxr/base/gf/half.h"

#include <boost/python/def.hpp>
#include <boost/python/handle.hpp>
#include <boost/python/to_python_converter.hpp>
#include <boost/python/converter/from_python.hpp>

using namespace boost::python;

PXR_NAMESPACE_USING_DIRECTIVE

namespace {

// Registers to and from python conversions with boost.python for half.
struct HalfPythonConversions
{
    static void Register() {
        // to-python
        to_python_converter<GfHalf, HalfPythonConversions>();
        // from-python
        converter::registry::push_back(&_convertible, &_construct,
                                       boost::python::type_id<GfHalf>());
    }

    // to-python
    static PyObject *convert(GfHalf h) { return PyFloat_FromDouble(h); }

private:
    // from-python
    static void *_convertible(PyObject *obj_ptr) {
        // Must be number-like.
        if (!PyNumber_Check(obj_ptr))
            return NULL;
        // Try to convert to python float: if we can, then we can make a GfHalf.
        if (PyObject *flt = PyNumber_Float(obj_ptr))
            return flt;
        // Otherwise we cannot produce a GfHalf.  Clear any python exception
        // raised above when attempting to create the float.
        if (PyErr_Occurred())
            PyErr_Clear();
        return NULL;
    }
    static void _construct(PyObject *obj_ptr, converter::
                           rvalue_from_python_stage1_data *data) {
        // Pull out the python float we returned from _convertible().
        PyObject *flt = (PyObject *)data->convertible;
        // Turn the python float into a C++ double, make a GfHalf from that
        // double, and store it where boost.python expects it.
        void *storage =
            ((converter::rvalue_from_python_storage<GfHalf>*)data)->storage.bytes;
        new (storage) GfHalf(static_cast<float>(PyFloat_AsDouble(flt)));
        data->convertible = storage;
        // Drop our reference to the python float we created.
        Py_DECREF(flt);
    }
};

// Simple test function that takes and returns a GfHalf.
static GfHalf _HalfRoundTrip(GfHalf in) { return in; }

} // anonymous namespace

void wrapHalf()
{
    HalfPythonConversions::Register();
    boost::python::def("_HalfRoundTrip", _HalfRoundTrip);
}

max_stars_repo_name: DougRogers-DigitalFish/USD

max_issues_repo_name: DougRogers-DigitalFish/USD

max_forks_repo_name: DougRogers-DigitalFish/USD


text:
#include <cmath>
#include <iostream>
#include <fstream>
#include <OpenEXR/ImathVec.h>
#include <boost/format.hpp>

/*!
 * see http://cubic.org/docs/hermite.htm
 *
 */
namespace interpolate
{
	template <typename T> void hermite(const Imath::Vec3<T>& P1,
									   const Imath::Vec3<T>& T1,
									   const Imath::Vec3<T>& P2,
									   const Imath::Vec3<T>& T2,
									   T s,
									   Imath::Vec3<T>& P)
	{
		T h1 =  2.0*std::pow(s,3.0) - 3.0*std::pow(s,2.0) + 1.0; // calculate basis function 1
		T h2 = -2.0*std::pow(s,3.0) + 3.0*std::pow(s,2.0)      ; // calculate basis function 2
		T h3 =  std::pow(s,3.0)     - 2.0*std::pow(s,2.0) + s  ; // calculate basis function 3
		T h4 =  std::pow(s,3.0)     - std::pow(s,2.0)          ; // calculate basis function 4

		P = h1*P1 + // multiply and sum all funtions
			h2*P2 + // together to build the interpolated
			h3*T1 + // point along the curve.
			h4*T2;
	}
}

// == Emacs ================
// -------------------------
// Local variables:
// tab-width: 4
// indent-tabs-mode: t
// c-basic-offset: 4
// end:
//
// == vi ===================
// -------------------------
// Format block
// ex:ts=4:sw=4:expandtab
// -------------------------


text:
#include <cstdlib>
#include <cstring>
#include <deque>
#include <iostream>
#include <string>
#include <sstream>
#include <utility>
#include <vector>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/algorithm/string.hpp>
#include "ttt_shared.hpp"

using boost::asio::ip::tcp;

//------------------------------------------------------------------------------

class ttt_client_base {
 public:
  ttt_client_base(boost::asio::io_service& io_service,
                  tcp::resolver::iterator endpoint_iterator)
      : io_service_(io_service), socket_(io_service) {
    do_connect(endpoint_iterator);
  }

  void close() {
    static bool got_here = false;
    if (got_here) {
      return;
    }
    got_here = true;

    socket_.shutdown(tcp::socket::shutdown_both);
    socket_.close();

    log("Disconnected from the server");
    on_server_disconnection();
  }

 protected:
  virtual void on_server_connection() {}

  virtual void on_message_received(const ttt_message& msg) {}

  virtual void on_message_sent(const ttt_message& msg) {}

  virtual void on_server_disconnection() {}

  virtual void log(const std::string& msg) const {
    std::string buffer = "tic_tac_toe_client '" + msg + "'\n";
    std::cout << buffer;
  }

  void write(const ttt_message& msg) {
    io_service_.post([this, msg]() {
      bool write_in_progress = !write_msgs_.empty();
      write_msgs_.push_back(msg);
      if (!write_in_progress) {
        do_write();
      }
    });
  }

 private:
  void do_connect(tcp::resolver::iterator endpoint_iterator) {
    boost::asio::async_connect(
        socket_, endpoint_iterator,
        [this](boost::system::error_code ec, tcp::resolver::iterator) {
          if (!ec) {
            log("Connected to the server");
            on_server_connection();

            do_read_header();
          } else {
            log("Could not connect to the server");
          }
        });
  }

  void do_read_header() {
    boost::asio::async_read(
        socket_,
        boost::asio::buffer(read_msg_.data(), ttt_message::header_length),
        [this](boost::system::error_code ec, std::size_t /*length*/) {
          if (!ec && read_msg_.decode_header()) {
            do_read_body();
          } else {
            log("An error occurred while listening to the server");
            this->close();
          }
        });
  }

  void do_read_body() {
    boost::asio::async_read(
        socket_, boost::asio::buffer(read_msg_.body(), read_msg_.body_length()),
        [this](boost::system::error_code ec, std::size_t /*length*/) {
          if (!ec) {
            log("Received server message");
            on_message_received(read_msg_);

            do_read_header();
          } else {
            log("An error occurred while listening to the server");
            this->close();
          }
        });
  }

  void do_write() {
    log("Sending message...");
    boost::asio::async_write(
        socket_, boost::asio::buffer(write_msgs_.front().data(),
                                     write_msgs_.front().length()),
        [this](boost::system::error_code ec, std::size_t /*length*/) {
          if (!ec) {
            log("A message was sent");
            on_message_sent(write_msgs_.front());

            write_msgs_.pop_front();

            if (!write_msgs_.empty()) {
              do_write();
            }
          } else {
            log("An error occurred while writing to the server");
            this->close();
          }
        });
  }

 private:
  boost::asio::io_service& io_service_;
  tcp::socket socket_;
  ttt_message read_msg_;
  ttt_message_queue write_msgs_;
};

//------------------------------------------------------------------------------

class ttt_client : public ttt_client_base {
 public:
  ttt_client(boost::asio::io_service& io_service,
             tcp::resolver::iterator endpoint_iterator)
      : ttt_client_base(io_service, endpoint_iterator) {}

  void take(int x, int y) {
    std::stringstream ss;
    ss << x << ", " << y;

    std::string msg_body = ss.str();

    ttt_message msg;
    memcpy(msg.body(), msg_body.c_str(), msg_body.size());
    msg.body_length(msg_body.size());
    msg.encode_header();

    write(msg);
  }

 protected:
  void on_server_connection() override {
    std::cout << "Waiting for the game to start...\n";

    last_umsg_.playing = true;

    boost::thread input_t([this]() {
      while (this->last_umsg_.playing) {  // While the game is running...
        std::string token;
        std::cin >> token;

        int value;
        bool got_int = (std::sscanf(token.c_str(), "%d", &value) == 1);

        if (got_int && 1 <= value && value <= 9) {
          auto mapped_res = this->numpad_to_cell(value);
          this->take(mapped_res.first, mapped_res.second);
        }
      }
    });

    input_t.detach();
  }

  void on_message_received(const ttt_message& msg) override {
    ttt_update_message umsg;

    if (!ttt_update_message::try_parse(msg, umsg)) {
      return;
    }

    std::cout << '\n';
    draw_game(umsg);

    last_umsg_ = umsg;
  }

  void on_server_disconnection() override {
    last_umsg_.playing = false;

    std::cout << "Client session finished.\n";
  }

 protected:
  void log(const std::string& msg) const {}

 private:
  /*
  ** Draws a representation of a TTT game from an TTT Update Message
  */
  void draw_game(const ttt_update_message& umsg) {
    // Players naming
    std::string player_name[ttt_number_of_players];
    for (int i = 0; i < ttt_number_of_players; i++) {
      player_name[i] = (i == (int)umsg.player_id ? "you" : "your opponent");
    }

    // Game title
    // std::cout << enclose_text("TIC TAC TOE") << '\n';

    // Game board
    const std::string board = draw_board_str(umsg);

    // How to play
    std::string instructions = "";
    if (umsg.playing) {
      instructions +=
          "HOW TO PLAY\n"
          "Type a digit from your numeric pad (numpad) to choose a cell.\n"
          "Digits correspond to cells so that the game board resembles your "
          "numpad.\n";
    }

    // Game status information
    std::string status = "";
    if (umsg.playing) {
      status +=
          "Waiting for " + player_name[(int)umsg.current_player] + " to move";
    } else if (umsg.winner == ttt_player_id::none) {
      status += "GAME OVER, you tied!";
    } else {
      status += "GAME OVER, you ";
      status += (umsg.winner == umsg.player_id ? "won!" : "lost!");
    }
    status += "\n";

    // Draw it!
    std::cout << board << '\n';
    std::cout << instructions << '\n';
    std::cout << status << '\n';
  }

  /*
  ** 'Encloses' a given text around a box,
  ** whose edges are drawn with a given char
  */
  std::string enclose_text(const std::string str, char fill_char = '*') {
    std::deque<std::string> content;
    boost::split(content, str, boost::is_any_of("\n"));

    unsigned max_len = 0;
    for (auto line : content) {
      max_len = std::max((unsigned)line.size(), max_len);
    }

    std::string separator(max_len + 4, fill_char);

    if (content.front() != "") {
      content.push_front("");
    }
    if (content.back() != "") {
      content.push_back("");
    }

    std::stringstream result;

    result << separator << '\n';
    for (std::string line : content) {
      line = line + std::string(max_len - line.size(), ' ');
      result << fill_char << ' ' << line << ' ' << fill_char << '\n';
    }
    result << separator << '\n';

    return result.str();
  }

  /*
  ** Returns a text representation of the board inside a TTT Update Message
  */
  std::string draw_board_str(const ttt_update_message& umsg) {
    std::string board = empty_board;

    for (unsigned i = 0; i < ttt_board_side; i++) {
      for (unsigned j = 0; j < ttt_board_side; j++) {
        // Skip drawing if no player owns the spot
        if (umsg.board[i][j] == ttt_player_id::none) {
          continue;
        }

        // Get player's corresponding letter
        std::string letter = (umsg.board[i][j] == umsg.player_id ? X : O);

        // Draw it!
        const int x = 8 * i, y = 8 * j;
        for (unsigned a = 0, b = 0; a < letter.size(); a++) {
          if (letter[a] == '\n') {
            b += 1;
            continue;
          }

          const int row = x + b, col = y + (a % 8);
          board[row * 24 + col] = letter[a];
        }
      }
    }

    return board;
  }

  std::pair<int, int> numpad_to_cell(int i) {
    static const std::vector<std::pair<int, int>> data {
      {9, 9},
      {2, 0}, {2, 1}, {2, 2},
      {1, 0}, {1, 1}, {1, 2},
      {0, 0}, {0, 1}, {0, 2}
    };
    return data[i];
  }

 private:
  ttt_update_message last_umsg_;
  const std::string X =
      "       \n \\   / \n  \\ /  \n   x   \n  / \\  \n /   \\ \n       \n";
  const std::string O =
      "   _   \n  / \\  \n |   | \n |   | \n |   | \n  \\_/  \n       \n";
  const std::string empty_board =
      "       |       |       \n       |       |       \n       |       |    "
      "   \n       |       |       \n       |       |       \n       |       "
      "|       \n       |       |       \n-----------------------\n       |  "
      "     |       \n       |       |       \n       |       |       \n     "
      "  |       |       \n       |       |       \n       |       |       "
      "\n       |       |       \n-----------------------\n       |       |  "
      "     \n       |       |       \n       |       |       \n       |     "
      "  |       \n       |       |       \n       |       |       \n       "
      "|       |       \n";
};

//------------------------------------------------------------------------------

int main(int argc, char* argv[]) {
  try {
    if (argc != 3) {
      std::cerr << "Usage: client <host> <port>\n";
      return 1;
    }

    boost::asio::io_service io_service;

    tcp::resolver resolver(io_service);
    auto endpoint_iterator = resolver.resolve({argv[1], argv[2]});
    ttt_client c(io_service, endpoint_iterator);

    boost::thread client_t([&io_service]() { io_service.run(); });

    client_t.join();
  } catch (std::exception& e) {
    std::cerr << "Exception: " << e.what() << "\n";
  }

  return 0;
}

max_stars_repo_name: alexpizarroj/tic-tac-toe

max_issues_repo_name: alexpizarroj/tic-tac-toe

max_forks_repo_name: alexpizarroj/tic-tac-toe


text:
//
// Copyright Antoine Leblanc 2010 - 2015
// Distributed under the MIT license.
//
// http://nauths.fr
// http://github.com/nicuveo
// mailto://antoine.jp.leblanc@gmail.com
//

//HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
// Includes

#include <cstdlib>
#include <iostream>
#include <boost/test/unit_test.hpp>
#include "nauths/mcl/mcl.hh"

//HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
// Local code

namespace
{

#define CREATE(R, D, S)                         \
  case mcl::spaces::S:                          \
  {                                             \
    mcl::S color;                               \
    fill(color, alpha);                         \
    return color;                               \
  }                                             \

  void init()
  {
    srand(42);
  }

  template <typename T>
  T random()
  {
    return T((rand() % 10000) / 10000.);
  }

  template <>
  mcl::byte random()
  {
    return (rand() >> 8) % 256;
  }

  template <typename T>
  T normalize(double x)
  {
    return x;
  }

  template <>
  mcl::byte normalize(double x)
  {
    return x * 255;
  }

  template <typename T, std::size_t N>
  void fill(std::array<T, N>& color, double alpha, double factor = 1.0)
  {
    for (std::size_t i = 0; i < N - 1; ++i)
      color[i] = random<T>() * factor;
    color[N - 1] = normalize<T>(alpha);
  }

  mcl::Color make(mcl::SpaceType s, double alpha)
  {
    switch (s)
    {
      BOOST_PP_SEQ_FOR_EACH(CREATE, _, MCL_SPACES)
    }

    return mcl::Color();
  }

}

//HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
// Implementation

BOOST_AUTO_TEST_SUITE(color)

BOOST_AUTO_TEST_CASE(color_00)
{
  init();

  for (mcl::SpaceType s1 : mcl::COLOR_SPACES)
  {
    const double a = random<double>();
    const mcl::Color c1 = make(s1, a);

    switch (s1)
    {
      case MCL_RGBub: BOOST_CHECK_EQUAL(c1.alpha(), (mcl::byte(a * 255)) / 255.0); break;
      case MCL_RGBf:  BOOST_CHECK_EQUAL(c1.alpha(), (float) a);                    break;
      default:        BOOST_CHECK_EQUAL(c1.alpha(), a);                            break;
    }

    BOOST_CHECK_EQUAL(c1.type(), s1);
  }
}

BOOST_AUTO_TEST_CASE(clamp_cmy)
{
  init();

  for (int i = 0; i < 100; ++i)
  {
    mcl::CMY c;

    fill(c, random<double>(), 10.0);
    c.clamp();

    BOOST_REQUIRE(c.c() >=    0.0 and c.c() <=   1.0);
    BOOST_REQUIRE(c.m() >=    0.0 and c.m() <=   1.0);
    BOOST_REQUIRE(c.y() >=    0.0 and c.y() <=   1.0);
  }
}

BOOST_AUTO_TEST_CASE(clamp_cmyk)
{
  init();

  for (int i = 0; i < 100; ++i)
  {
    mcl::CMYK c;

    fill(c, random<double>(), 10.0);
    c.clamp();

    BOOST_REQUIRE(c.c() >=    0.0 and c.c() <=   1.0);
    BOOST_REQUIRE(c.m() >=    0.0 and c.m() <=   1.0);
    BOOST_REQUIRE(c.y() >=    0.0 and c.y() <=   1.0);
    BOOST_REQUIRE(c.k() >=    0.0 and c.k() <=   1.0);
  }
}

BOOST_AUTO_TEST_CASE(clamp_rgb)
{
  init();

  for (int i = 0; i < 100; ++i)
  {
    mcl::RGB c;

    fill(c, random<double>(), 10.0);
    c.clamp();

    BOOST_REQUIRE(c.r() >=    0.0 and c.r() <=   1.0);
    BOOST_REQUIRE(c.g() >=    0.0 and c.g() <=   1.0);
    BOOST_REQUIRE(c.b() >=    0.0 and c.b() <=   1.0);
  }
}

BOOST_AUTO_TEST_CASE(clamp_rgbf)
{
  init();

  for (int i = 0; i < 100; ++i)
  {
    mcl::RGBf c;

    fill(c, random<float>(), 10.f);
    c.clamp();

    BOOST_REQUIRE(c.r() >=    0.f and c.r() <=   1.f);
    BOOST_REQUIRE(c.g() >=    0.f and c.g() <=   1.f);
    BOOST_REQUIRE(c.b() >=    0.f and c.b() <=   1.f);
  }
}

BOOST_AUTO_TEST_CASE(clamp_hsl)
{
  init();

  for (int i = 0; i < 100; ++i)
  {
    mcl::HSL c;

    fill(c, random<double>(), 10.0);
    c.clamp();

    BOOST_REQUIRE(c.h() >=    0.0 and c.h() <= 360.0);
    BOOST_REQUIRE(c.s() >=    0.0 and c.s() <=   1.0);
    BOOST_REQUIRE(c.l() >=    0.0 and c.l() <=   1.0);
  }
}

BOOST_AUTO_TEST_CASE(clamp_hsv)
{
  init();

  for (int i = 0; i < 100; ++i)
  {
    mcl::HSV c;

    fill(c, random<double>(), 10.0);
    c.clamp();

    BOOST_REQUIRE(c.h() >=    0.0 and c.h() <= 360.0);
    BOOST_REQUIRE(c.s() >=    0.0 and c.s() <=   1.0);
    BOOST_REQUIRE(c.v() >=    0.0 and c.v() <=   1.0);
  }
}

BOOST_AUTO_TEST_CASE(clamp_lab)
{
  init();

  for (int i = 0; i < 100; ++i)
  {
    mcl::LAB c;

    fill(c, random<double>(), 10.0);
    c.clamp();

    BOOST_REQUIRE(c.l() >=    0.0 and c.l() <= 100.0);
    BOOST_REQUIRE(c.a() >= -120.0 and c.a() <= 120.0);
    BOOST_REQUIRE(c.b() >= -120.0 and c.b() <= 120.0);
  }
}

BOOST_AUTO_TEST_CASE(clamp_lch)
{
  init();

  for (int i = 0; i < 100; ++i)
  {
    mcl::LCH c;

    fill(c, random<double>(), 10.0);
    c.clamp();

    BOOST_REQUIRE(c.l() >=    0.0 and c.l() <= 100.0);
    BOOST_REQUIRE(c.c() >= -120.0 and c.c() <= 120.0);
    BOOST_REQUIRE(c.h() >=    0.0 and c.h() <= 360.0);
  }
}

BOOST_AUTO_TEST_CASE(clamp_xyz)
{
  init();

  for (int i = 0; i < 100; ++i)
  {
    mcl::XYZ c;

    fill(c, random<double>(), 10.0);
    c.clamp();

    BOOST_REQUIRE(c.x() >=    0.0 and c.x() <= 120.0);
    BOOST_REQUIRE(c.y() >=    0.0 and c.y() <= 120.0);
    BOOST_REQUIRE(c.z() >=    0.0 and c.z() <= 120.0);
  }
}

BOOST_AUTO_TEST_SUITE_END()

ext: cc

max_stars_repo_name: nicuveo/MCL

max_issues_repo_name: nicuveo/MCL

max_forks_repo_name: nicuveo/MCL


text:
#include <iostream>
#include <vector>
#include <algorithm>

#include <Eigen/Dense>

#include "timer.h"

//! \brief Structure holding a triplet in format (row, col, value)
//! For convenience, we provide a void constructor and a init constructor. All members are public
//! Used in the TripletMatrix class to provide a nice wrapper for a triplet
//! \tparam scalar represents the type of the triplet (e.g. double)
template <class scalar>
struct Triplet {
    Triplet(void)
    : i(0), j(0), v(0) { }

    Triplet(std::size_t i_, std::size_t j_, scalar v_)
        : i(i_), j(j_), v(v_) { }

    std::size_t i, j; //< row and col
    scalar v; //< value @ (row,col)
};

//! \brief Defines a matrix stored in triplet format (using the Triplet<scalar> class.
//! Triplets may be duplicated and in *any* order. If there is a multiple triplet for (row,col) pair, we assume
//! that the values are intended to be added together
//! Also stores dimension
//! \tparam scalar represents the scalar type of the matrix (and of the triplet) (e.g. double)
template <class scalar>
struct TripletMatrix {
    std::size_t rows, cols; //< Sizes: nrows and ncols
    std::vector< Triplet<scalar> > triplets;

    //! \brief Converts *this to an eigen (dense) function, used for visualization
    //! Loops over all triplets and add value to Zero matrix (read-only)
    //! WARNING: just for debug, may fill-in a lot of nonzeros if n,m >> 1
    //! \return Eigen::Matrix of Dynamic size and scalar type
    Eigen::Matrix<scalar, -1, -1> densify() const {
        Eigen::Matrix<scalar, -1, -1> M = Eigen::Matrix<scalar, -1, -1>::Zero(rows, cols);
        for(auto it = triplets.begin(); it != triplets.end(); ++it) {
            M(it->i, it->j) += it->v;
        }
        return M;
    }
};

// const TripletMatrix;

//! \brief Structure holding a pair column index-value to be used in CRS format
//! Provides handy constructor and comparison operators.
//! \tparam scalar represents the scalar type of the value stored (e.g. double)
template <class scalar>
struct ColValPair {
    ColValPair(std::size_t col_, scalar v_)
        : col(col_), v(v_) { }

    //! \brief Comparison operator for std::sort and std::lower_bound
    //! Basic sorting operator < for use with std:: functions (i.e. for ordering according to first component (col)
    //! We keep the column values sorted, either by sorting after insertion of by sorted insertion
    //! \return true if this->col < other.col
    bool operator<(const ColValPair & other) const {
        return this->col < other.col;
    }

    std::size_t col; //< col index
    scalar v; //< scalar value at col
};

//! \brief Defines a matrix stored in CRS format (using the ColValPair<scalar> struct.
//! The row_pt contains the data, indexed by row and column position
//! Also stores dimension
//! \tparam scalar represents the scalar type of the matrix (and of the ColValPair) (e.g. double)
template <class scalar>
struct CRSMatrix {
    std::size_t rows, cols; //< Size of the matrix rows, cols
    std::vector< std::vector< ColValPair<scalar> > > row_pt; //< Vector containing, for each row, al vector of (col, value) pairs (CRS format)

    //! \brief Converts *this to an eigen (dense) function, used for visualization
    //! Loops over all rows and add value at col (in ColValPair) to Zero matrix (read-only)
    //! WARNING: just for debug, may fill-in a lot of nonzeros if n,m >> 1
    //! \return Eigen::Matrix of Dynamic size and scalar type
    Eigen::Matrix<scalar, -1, -1> densify() const {
        Eigen::Matrix<scalar, -1, -1> M = Eigen::Matrix<scalar, -1, -1>::Zero(rows, cols);
        std::size_t i = 0;
        for(auto it = row_pt.begin(); it != row_pt.end(); ++it) {
            for(auto it2 = it->begin(); it2 != it->end(); ++it2) {
                M(i, it2->col) = it2->v;
            }
            ++i;
        }
        return M;
    }
};

//! \brief Converts a matrix given as triplet matrix to a matrix in CRS format
//! No assumption is made on the triplets, may be unsorted and/or duplicated
//! In case of duplicated triplets, values are added toghether
//! The output CRS matrix may be empty (in that case T = C) or may be already filled with values (in which case C += T)
//! This version inserts the ColValParis already sorted in the list
//! Complexity: loops over all triplets (lets say k) and look up over all columns of the row (say n_i), performing a
//! linear search and an insertion (complexity O(n_i))
//! Assuming n_i is bounded by n small, complexity is k*n, otherwise k^2
template <class scalar>
void tripletToCRS(const TripletMatrix<scalar> & T, CRSMatrix<scalar> & C) {
    // Copy sizes and reserve memory for rows
    C.rows = T.rows;
    C.cols = T.cols;
    C.row_pt.resize(C.rows);

    // Loop over all triplets
    for(auto triplet_it = T.triplets.begin(); triplet_it != T.triplets.end(); ++triplet_it) {
        // Store row (containing the ColValPairs for this row) inside the row_pt vector
        auto & row = C.row_pt.at(triplet_it->i);
        // Create a ColVal pair that must be inserted somewhere
        ColValPair<scalar> col_val(triplet_it->j, triplet_it->v);
        // Find the place (as iterator) where to insert col_val, i.e. the first place where col_val < C.row_pt.at(i)
        // WARNING: Costly call (loops over all of row (worts case scenario))
        auto lb_it = std::lower_bound(row.begin(), row.end(), col_val);
        // If lower bound has already a col (and is not end()) with some value, just add the value to the column, othervise insert it
        if(lb_it != row.end() && lb_it->col == triplet_it->j) {
            lb_it->v += triplet_it->v;
        } else {
            // WARNING: Costly call (loops over all of row (worts case scenario))
            row.insert(lb_it, col_val);
        }
    }
}

//! \brief Converts a matrix given as triplet matrix to a matrix in CRS format
//! No assumption is made on the triplets, may be unsorted and/or duplicated
//! In case of duplicated triplets, values are added toghether
//! The output CRS matrix may be empty (in that case T = C) or may be already filled with values (in which case C += T)
//! This version inserts all the triplets (push_back) then sorts eatch row and cumsum al the duplicated col values
//! *** Complexity: loops over all triplets (lets say k) and do a cheap (amortized) o(1) push back (complexity k*1). Then sorts an array
//! of rows (ith quicksort complexity k * log(k))
template <class scalar>
void tripletToCRS_sortafter(const TripletMatrix<scalar> & T, CRSMatrix<scalar> & C) {
    // Copy dimensions and reserve known space
    C.rows = T.rows;
    C.cols = T.cols;
    C.row_pt.resize(C.rows);

    // Loops over all triplets and push them at the ritgh place (cheap)
    for(auto triplets_it = T.triplets.begin(); triplets_it != T.triplets.end(); ++triplets_it) {
        ColValPair<scalar> cp(triplets_it->j, triplets_it->v);
        C.row_pt.at(triplets_it->i).push_back(cp);
    }
    // Loops over all rows , sort them (according to col) and sum duplicated values
    for(auto row_it = C.row_pt.begin(); row_it != C.row_pt.end(); ++row_it) {
        // WARNING: costly call in this case
        std::sort(row_it->begin(), row_it->end());
        // Sum duplicated cols
        // NOTE: iterating backwards should be faster
        for(auto col_it = row_it->begin(); col_it != row_it->end(); ++col_it) {
            // Check that next col is not at the end and that has same col value
            if((col_it + 1) != row_it->end() && (col_it + 1)->col == col_it->col) {
                // Last col with same value (starting from next col)
                auto last_col_it = col_it + 1;
                while(last_col_it != row_it->end() && last_col_it->col == col_it->col) {
                    col_it->v += last_col_it->v;
                    ++last_col_it;
                }
                // Remove range from next col to last col with same value
                // WARNING: std::vector keeps the data as c-array, so mildly costly call (from col_it to end() (at most M)
                row_it->erase(col_it+1, last_col_it);
            }
        }
    }
}

//! \brief overload of operator << for output of Triplet Matrix (debug).
//! WARNING: uses densify() so there may be a lot of fill-in
//! \param o standard output stream
//! \param S matrix in Triplet matrix format
//! \return a ostream o, s.t. you can write o << A << B;
std::ostream & operator<<(std::ostream & o, const TripletMatrix<double> & S) {
    return o << S.densify();
}

//! \brief overload of operator << for output of CRS Matrix (debug).
//! WARNING: uses densify() so there may be a lot of fill-in
//! \param o standard output stream
//! \param S matrix in CRS matrix format
//! \return a ostream o, s.t. you can write o << A << B;
std::ostream & operator<<(std::ostream & o, const CRSMatrix<double> & S) {
    return o << S.densify();
}

int main() {
    //// Correctness test
    std::size_t nrows = 7, ncols = 5, ntriplets = 9;

    TripletMatrix<double> T;
    CRSMatrix<double> C,D;

    T.rows = nrows;
    T.cols = ncols;
    T.triplets.reserve(ntriplets); // Always reserve space if you can
    for(auto i = 0u; i < ntriplets; ++i) {
        // Test unordered triplets, random and maybe repeated triplets
        T.triplets.push_back(Triplet<double>(rand() % nrows, rand() % ncols, rand() % 1000));
    }

    std::cout << "***Test conversion with random matrices***" << std::endl;
    tripletToCRS(T, C);
    std::cout << "--> Frobenius norm of T - C: " << (T.densify()-C.densify()).norm() << std::endl;
    std::cout << "T = " << std::endl << T << std::endl;
    std::cout << "C = " << std::endl << C << std::endl;

    tripletToCRS_sortafter(T, D);
    std::cout << "--> Frobenius norm of T - D: " << (T.densify()-D.densify()).norm() << std::endl;
    std::cout << "D = " << D << std::endl;

    // Big benefit of how we defined our functions: can add new triplets to the old ones:
    std::cout << "***Test addition with random matrices***" << std::endl;
    TripletMatrix<double> T2;
    T2.rows = nrows;
    T2.cols = ncols;
    T2.triplets.reserve(ntriplets); // Always reserve space if you can
    for(auto i = 0u; i < ntriplets; ++i) {
        // Test unordered triplets, random and maybe repeated triplets
        T2.triplets.push_back(Triplet<double>(rand() % nrows, rand() % ncols, rand() % 1000));
    }
    tripletToCRS(T2, C);
    tripletToCRS_sortafter(T2, D);
    std::cout << "T = " << std::endl << T << std::endl;
    std::cout << "T2 = " << std::endl << T2 << std::endl;
    std::cout << "C = " << std::endl << C << std::endl;
    std::cout << "D = " << std::endl << D << std::endl;

    //// Runtime test
    bool noruntime = false; // Skip runtime measurments
    bool noaddition = true; // Do not test addition of new triplets

    if(noruntime) {
        return 0;
    }
    std::cout << "***Runtime test***" << std::endl;

    // Play around with this parameters (also introducing lambda functions)
    auto frows = [](std::size_t M) { return 2*M; };
    auto fcols = [](std::size_t M) { return M; };
    auto ftriplets = [](std::size_t M) { return M*5; };

    // Do some timings
    timer<> sortafter_timer, insertsort_timer;
    for(std::size_t M = 2u; M < 1024u; M *= 2u) {
        sortafter_timer.reset();
        insertsort_timer.reset();
        std::cout << "Runtime for " << M << "x" << M/2 << " matrix (with nnz(A) <= " << M << "):" << std::endl;
        for(int r = 0; r < 4; ++r) {

            TripletMatrix<double> A;
            CRSMatrix<double> B, E;

            A.rows = frows(M); // nrows
            A.cols = fcols(M); //ncols
            A.triplets.reserve(ftriplets(M));
            for(auto i = 0u; i < ftriplets(M); ++i) {
                A.triplets.push_back(Triplet<double>(rand() % A.rows, rand() % A.cols, rand() % 1000));
            }

            insertsort_timer.start();
            tripletToCRS(A, B);
            if(!noaddition) tripletToCRS(A, B);
            insertsort_timer.stop();

            sortafter_timer.start();
            tripletToCRS_sortafter(A, E);
            if(!noaddition) tripletToCRS_sortafter(A, E);
            sortafter_timer.stop();
        }
        std::cout << "Insertsort took:  " << insertsort_timer.min().count() / 1000. << " ms." << std::endl;
        std::cout << "Sortafter took:   " << sortafter_timer.min().count() / 1000. << " ms." << std::endl;
    }
}

max_stars_repo_path: Nummerical Methods for CSE/PS3/solutions_ps3/tripletToCRS_solution.cpp

max_stars_repo_name: valentinjacot/backupETHZ

max_issues_repo_path: Nummerical Methods for CSE/PS3/tripletToCRS_solution.cpp

max_issues_repo_name: valentinjacot/backupETHZ

max_forks_repo_name: valentinjacot/backupETHZ


text:
//          Copyright Dean Michael Berris 2007.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#ifndef __NETWORK_MESSAGE_TRANSFORMERS_TO_UPPER_HPP__
#define __NETWORK_MESSAGE_TRANSFORMERS_TO_UPPER_HPP__

#include <boost/algorithm/string.hpp>

/** to_upper.hpp
 *
 * Implements the to_upper transformer. This applies
 * the to_upper string algorithm to a string, which
 * is selected by the appropriate selector.
 *
 * This defines a type, to be applied using template
 * metaprogramming on the selected string target.
 */
namespace boost { namespace network {

    namespace impl {

        template <class Selector>
            struct to_upper_transformer { };

        template <>
            struct to_upper_transformer<selectors::source_selector> {
                template <class Tag>
                    void operator() (basic_message<Tag> & message_) const {
                        boost::to_upper(message_.source());
                    }

                protected:
                    ~to_upper_transformer() { };
            };

        template <>
            struct to_upper_transformer<selectors::destination_selector> {
                template <class Tag>
                    void operator() (basic_message<Tag> & message_) const {
                        boost::to_upper(message_.destination());
                    }

                protected:
                    ~to_upper_transformer() { };
            };

    } // namespace impl

	namespace detail {
		struct to_upper_placeholder_helper;
	}

	detail::to_upper_placeholder_helper to_upper_(detail::to_upper_placeholder_helper);

	namespace detail {

		struct to_upper_placeholder_helper {
			template <class Selector>
				struct type : public impl::to_upper_transformer<Selector> { };
		private:
			to_upper_placeholder_helper() {}
			to_upper_placeholder_helper(to_upper_placeholder_helper const &) {}
			friend to_upper_placeholder_helper boost::network::to_upper_(to_upper_placeholder_helper);
		};

	}

	typedef detail::to_upper_placeholder_helper (*to_upper_placeholder)(detail::to_upper_placeholder_helper);

	inline detail::to_upper_placeholder_helper to_upper_(detail::to_upper_placeholder_helper) {
		return detail::to_upper_placeholder_helper();
	}

} // namespace network

} // namespace boost

#endif // __NETWORK_MESSAGE_TRANSFORMERS_TO_UPPER_HPP__

max_stars_repo_name: mclow/cpp-netlib

max_issues_repo_name: mclow/cpp-netlib

max_forks_repo_name: mclow/cpp-netlib


text:
/*=============================================================================
    Copyright (c) 2004 Joao Abecasis
    http://spirit.sourceforge.net/

    Use, modification and distribution is subject to 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)
=============================================================================*/

#define BOOST_SPIRIT_ASSERT_EXCEPTION ::spirit_exception

struct spirit_exception
{
    spirit_exception(char const * msg)
        : message(msg)
    {
    }

    char const * message;
};

#include <boost/spirit/core/scanner/scanner.hpp>
#include <boost/spirit/symbols/impl/tst.ipp>
#include <boost/utility/addressof.hpp>

#include <cassert>

typedef char char_type;
typedef char const * iterator;

char_type data_[] = "whatever";

iterator begin = data_;
iterator end = data_
    + sizeof(data_)/sizeof(char_type); // Yes, this is an intentional bug ;)

char_type data2_[] = "\0something";
iterator begin2 = data2_;
iterator end2 = data2_ + sizeof(data2_)/sizeof(char_type) - 1;

int main()
{
    typedef boost::spirit::scanner<> scanner;
    typedef boost::spirit::impl::tst<void *, char_type> symbols;

    symbols symbols_;

    try
    {
        // It is not ok to add strings containing the null character.
        symbols_.add(begin, end, (void*) boost::addressof(symbols_));
        assert(0);
    }
    catch (spirit_exception &e)
    {
    }

    try
    {
        // It is not ok to add strings containing the null character.
        symbols_.add(begin2, end2, (void*) boost::addressof(symbols_));
        assert(0);
    }
    catch (spirit_exception &e)
    {
    }
}

max_stars_repo_name: spxuw/RFIM

max_issues_repo_name: spxuw/RFIM

max_forks_repo_name: spxuw/RFIM


text:
//
// Created by Abdessattar Sassi on 6/11/18.
//

#include <map>
#include <vector>

//#include <boost/asio.hpp>
#ifdef WIN32
// TODO: windows includes for interfaces enumeration
#else
#include <arpa/inet.h>
#include <ifaddrs.h>
#endif  // WIN32

#include <common/logging.h>

#include <nat/nat.h>
#include <nat/upnp_port_mapper.h>

using asap::logging::Logger;
using asap::logging::Registry;

namespace blocxxi {
namespace nat {

namespace {

/**!
 * @bried Check if an IP address (IPV4 or IPV6) is a loopback address.
 *
 * @param address the address to check
 * @param ipv6 indicates if the address is an IPV4 or IPV6 address.
 * @return true if the address is a loopback address; false otherwise.
 */
bool IsLoopback(std::string const &address, bool ipv6 = false) {
  return address == ((ipv6) ? "::1" : "127.0.0.1");
}

/*!
 * @brief Check if the address (IPV4 or IPV6) is a local address or an external
 * one by comparing it to the standard pre-allocated local IP address ranges.
 *
 * @param address the address to check
 * @param ipv6 indicates if the address is an IPV4 or IPV6 address.
 * @return true if the address is a loopback address; false otherwise.
 */
bool IsLocal(std::string address, bool ipv6 = false) {
  if (IsLoopback(address, ipv6)) return true;
  if (ipv6) {
    std::transform(address.begin(), address.end(), address.begin(), ::tolower);
    return address.substr(0, 4) == "fe80";
  } else {
    if (address.substr(0, 3) == "10.") return true;
    if (address.substr(0, 8) == "192.168.") return true;
    if (address.substr(0, 8) == "169.254.") return true;
    auto sub = address.substr(0, 7);
    return sub == "172.16" || sub == "172.17" || sub == "172.18";
  }
}

/*!
 * @brief Use the underlying operating system facilities to discover the system
 * network interfaces and their associated IP addresses, then select the most
 * suitable IPV4 one to be used for the application.
 *
 * Preference is given to an external IP address, if not, to a local IP address
 * but on an interface that has both IPV4 and IPV6 addresses configured, and if
 * not then to a local non-loopback address. If everything fails the loopback
 * address will be returned, unless we fail to even query the system for its
 * network interfaces.
 *
 * @return the most suitable IPV4 address to be used for the application.
 */
std::string FindBestAddress() {
  auto &logger = Registry::GetLogger(asap::logging::Id::NAT);
  // Try to find a suitable interface, preferably with an external IPV4
  // address

  // Enumerate all interfaces and their IP addresses within the IPV4 domain
  struct AddressInfo {
    std::string value_;
    bool is_loopback_;
    bool is_external_;
    bool is_v4_;
  };
  using IfceAddressList = std::vector<AddressInfo>;
  std::map<std::string, IfceAddressList> interfaces;

  // This will hold the best available address or an empty string if we were not
  // able to find one.
  std::string selected_address;

#ifdef WIN32
// TODO: Implement network interface enumeration for Windows
#else   // WIN32
  struct ifaddrs *ifaddr, *ifa;

  ASLOG_TO_LOGGER(logger, debug,
                  "enumerating network interfaces and IP addresses");
  if (getifaddrs(&ifaddr) == -1) {
    ASLOG_TO_LOGGER(
        logger, warn,
        "could not gather any info on available network interfaces (e={})",
        errno);
    return selected_address;
  }

  // Walk through linked list, maintaining head pointer so we can free list
  // later
  for (ifa = ifaddr; ifa != nullptr; ifa = ifa->ifa_next) {
    if (ifa->ifa_addr == nullptr || (ifa->ifa_addr->sa_family != AF_INET &&
                                     ifa->ifa_addr->sa_family != AF_INET6))
      continue;

    char address[45];
    if (ifa->ifa_addr->sa_family == AF_INET) {
      auto res = inet_ntop(ifa->ifa_addr->sa_family,
                           &(((struct sockaddr_in *)(ifa->ifa_addr))->sin_addr),
                           address, 32);
      if (!res) perror("inet_ntop");
    } else {
      auto res = inet_ntop(
          ifa->ifa_addr->sa_family,
          &(((struct sockaddr_in6 *)(ifa->ifa_addr))->sin6_addr), address, 32);
      if (!res) perror("inet_ntop");
    }

    AddressInfo addr_info{
        address, IsLoopback(address, ifa->ifa_addr->sa_family == AF_INET6),
        !IsLocal(address, ifa->ifa_addr->sa_family == AF_INET6),
        ifa->ifa_addr->sa_family == AF_INET};

    ASLOG_TO_LOGGER(logger, debug, "{}: {} {} {} {}", ifa->ifa_name,
                    addr_info.is_v4_ ? "v4" : "v6",
                    addr_info.is_external_ ? "ext" : "loc", addr_info.value_,
                    addr_info.is_loopback_ ? "(loopback)" : "");

    interfaces[ifa->ifa_name].push_back(addr_info);
  }
  freeifaddrs(ifaddr);
#endif  // WIN32

  // We only select IPV4 address
  for (auto it : interfaces) {
    auto has_v4 = false;
    auto has_v6 = false;
    auto definitely_found = false;
    for (auto &ainfo : it.second) {
      // We got an external IP address on this interface -> best candidate
      if (ainfo.is_external_ && ainfo.is_v4_) {
        selected_address = ainfo.value_;
        definitely_found = true;
        break;
      }
      // Not external
      else {
        // If it's the loopback interface and we still have not seen any
        // non-loopback address yet, just keep it as this may end up as our
        // only option
        if (ainfo.is_loopback_) {
          if (selected_address.empty()) selected_address = ainfo.value_;
        } else {
          // We need IPv4 as many gateways are still configured for IPv4 only.
          // We also prefer interfaces that have both the v4 and v6 provisioned,
          // as this indicates the main interface of the system.
          if (ainfo.is_v4_) {
            has_v4 = true;
            selected_address = ainfo.value_;
          } else {
            has_v6 = true;
          }
          if (has_v4 && has_v6) {
            definitely_found = true;
            break;
          }
        }
      }
    }
    // If we have already found a suitable address, no need to go any further
    if (definitely_found) break;
  }

  ASLOG_TO_LOGGER(logger, info, "selected address: {}",
                  selected_address.empty() ? "none" : selected_address);

  return selected_address;
}

}  // namespace

std::unique_ptr<PortMapper> GetPortMapper(std::string const &spec) {
  auto &logger = Registry::GetLogger(asap::logging::Id::NAT);

  ASLOG_TO_LOGGER(logger, debug, "NAT port mapper spec: [{}]", spec);

  std::vector<std::string> parts;
  auto token_start = 0UL;
  auto token_end = spec.find(':');
  while (token_end != std::string::npos) {
    parts.emplace_back(spec.substr(token_start, token_end - token_start));
    token_start = token_end + 1;
    token_end = spec.find(':', token_start);
  }
  parts.emplace_back(spec.substr(token_start));

  PortMapper *mapper = nullptr;
  auto mechanism = parts[0];
  if (mechanism == "extip") {
    if (parts.size() == 3) {
      mapper = new NoPortMapper(parts[1], parts[2]);
    } else if (parts.size() == 2) {
      mapper = new NoPortMapper(parts[1], parts[1]);
    } else {
      ASLOG_TO_LOGGER(logger, debug,
                      "Missing explicit external IP in 'extip' nat spec");
    }
    ASLOG_TO_LOGGER(logger, debug, "Using mapper {}", mapper->ToString());
    return std::unique_ptr<PortMapper>(mapper);

  } else if (mechanism == "upnp") {
    return DiscoverUPNP(std::chrono::milliseconds(2000));

  } else if (mechanism == "pmp") {
    // TODO: Not implemented yet (pmp)
    ASLOG_TO_LOGGER(logger, error, "PMP port mapper is not implemented yet");
    return nullptr;

  } else {
    // Try to auto discover the environment

    auto address = FindBestAddress();
    if (address.empty()) {
      return nullptr;
    } else if (IsLocal(address)) {
      // Try UPNP
      auto upnp = DiscoverUPNP(std::chrono::milliseconds(2000));
      if (upnp) return upnp;

      // TODO: Try PMP

      ASLOG_TO_LOGGER(logger, warn, "Could not discover external IP address.");
      ASLOG_TO_LOGGER(logger, info,
                      "Consider using nat spec 'extip' to manually specify it");
    }
    mapper = new NoPortMapper(address, address);
    return std::unique_ptr<PortMapper>(mapper);
  }
}

}  // namespace nat
}  // namespace blocxxi