text:
//  Copyright John Maddock 2006, 2007
//  Copyright Paul A. Bristow 2007

//  Use, modification and distribution are 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)

#include <pch.hpp>

#ifdef _MSC_VER
#  pragma warning(disable : 4127) // conditional expression is constant
#  pragma warning(disable : 4512) // assignment operator could not be generated
#  pragma warning(disable : 4756) // overflow in constant arithmetic
// Constants are too big for float case, but this doesn't matter for test.
#endif

#include <boost/math/concepts/real_concept.hpp>
#include <boost/test/test_exec_monitor.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/math/special_functions/hermite.hpp>
#include <boost/math/constants/constants.hpp>
#include <boost/array.hpp>
#include "functor.hpp"

#include "handle_test_result.hpp"
#include "test_legendre_hooks.hpp"

//
// DESCRIPTION:
// ~~~~~~~~~~~~
//
// This file tests the Hermite polynomials.
// There are two sets of tests, spot
// tests which compare our results with selected values computed
// using the online special function calculator at
// functions.wolfram.com, while the bulk of the accuracy tests
// use values generated with NTL::RR at 1000-bit precision
// and our generic versions of these functions.
//
// Note that when this file is first run on a new platform many of
// these tests will fail: the default accuracy is 1 epsilon which
// is too tight for most platforms.  In this situation you will
// need to cast a human eye over the error rates reported and make
// a judgement as to whether they are acceptable.  Either way please
// report the results to the Boost mailing list.  Acceptable rates of
// error are marked up below as a series of regular expressions that
// identify the compiler/stdlib/platform/data-type/test-data/test-function
// along with the maximum expected peek and RMS mean errors for that
// test.
//

void expected_results()
{
   //
   // Define the max and mean errors expected for
   // various compilers and platforms.
   //
   const char* largest_type;
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
   if(boost::math::policies::digits<double, boost::math::policies::policy<> >() == boost::math::policies::digits<long double, boost::math::policies::policy<> >())
   {
      largest_type = "(long\\s+)?double";
   }
   else
   {
      largest_type = "long double";
   }
#else
   largest_type = "(long\\s+)?double";
#endif

   //
   // Catch all cases come last:
   //
   add_expected_result(
      ".*",                          // compiler
      ".*",                          // stdlib
      ".*",                          // platform
      largest_type,                  // test type(s)
      ".*",      // test data group
      "boost::math::hermite", 10, 5);  // test function
   add_expected_result(
      ".*",                          // compiler
      ".*",                          // stdlib
      ".*",                          // platform
      "real_concept",                  // test type(s)
      ".*",      // test data group
      "boost::math::hermite", 10, 5);  // test function
   //
   // Finish off by printing out the compiler/stdlib/platform names,
   // we do this to make it easier to mark up expected error rates.
   //
   std::cout << "Tests run with " << BOOST_COMPILER << ", "
      << BOOST_STDLIB << ", " << BOOST_PLATFORM << std::endl;
}

template <class T>
void do_test_hermite(const T& data, const char* type_name, const char* test_name)
{
   typedef typename T::value_type row_type;
   typedef typename row_type::value_type value_type;

   typedef value_type (*pg)(unsigned, value_type);
#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)
   pg funcp = boost::math::hermite<value_type>;
#else
   pg funcp = boost::math::hermite;
#endif

   typedef unsigned (*cast_t)(value_type);

   boost::math::tools::test_result<value_type> result;

   std::cout << "Testing " << test_name << " with type " << type_name
      << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";

   //
   // test hermite against data:
   //
   result = boost::math::tools::test(
      data,
      bind_func_int1(funcp, 0, 1),
      extract_result(2));
   handle_test_result(result, data[result.worst()], result.worst(), type_name, "boost::math::hermite", test_name);

   std::cout << std::endl;
}

template <class T>
void test_hermite(T, const char* name)
{
   //
   // The actual test data is rather verbose, so it's in a separate file
   //
   // The contents are as follows, each row of data contains
   // three items, input value a, input value b and erf(a, b):
   //
#  include "hermite.ipp"

   do_test_hermite(hermite, name, "Hermite Polynomials");
}

template <class T>
void test_spots(T, const char* t)
{
   std::cout << "Testing basic sanity checks for type " << t << std::endl;
   //
   // basic sanity checks, tolerance is 100 epsilon:
   // These spots were generated by MathCAD, precision is
   // 14-16 digits.
   //
   T tolerance = (std::max)(boost::math::tools::epsilon<T>() * 100, static_cast<T>(1e-14));
   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(0, static_cast<T>(1)), static_cast<T>(1.L), tolerance);
   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(1, static_cast<T>(1)), static_cast<T>(2.L), tolerance);
   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(1, static_cast<T>(2)), static_cast<T>(4.L), tolerance);
   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(1, static_cast<T>(10)), static_cast<T>(20), tolerance);
   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(1, static_cast<T>(100)), static_cast<T>(200), tolerance);
   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(1, static_cast<T>(1e6)), static_cast<T>(2e6), tolerance);
   if(std::numeric_limits<T>::max_exponent >= std::numeric_limits<double>::max_exponent)
   {
      BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(1, static_cast<T>(1e307)), static_cast<T>(2e307), tolerance);
      BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(99, static_cast<T>(100)), static_cast<T>(4.967223743011310E+227L), tolerance);
   }
   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(10, static_cast<T>(30)), static_cast<T>(5.896624628001300E+17L), tolerance);
   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(10, static_cast<T>(1000)), static_cast<T>(1.023976960161280E+33L), tolerance);
   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(10, static_cast<T>(10)), static_cast<T>(8.093278209760000E+12L), tolerance);
   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(10, static_cast<T>(-10)), static_cast<T>(8.093278209760000E+12L), tolerance);
   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(3, static_cast<T>(-10)), static_cast<T>(-7.880000000000000E+3L), tolerance);
   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(3, static_cast<T>(-1000)), static_cast<T>(-7.999988000000000E+9L), tolerance);
   BOOST_CHECK_CLOSE_FRACTION(::boost::math::hermite(3, static_cast<T>(-1000000)), static_cast<T>(-7.999999999988000E+18L), tolerance);
}

int test_main(int, char* [])
{
   BOOST_MATH_CONTROL_FP;

   boost::math::hermite(51, 915.0);

#ifndef BOOST_MATH_BUGGY_LARGE_FLOAT_CONSTANTS
   test_spots(0.0F, "float");
#endif
   test_spots(0.0, "double");
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
   test_spots(0.0L, "long double");
   test_spots(boost::math::concepts::real_concept(0.1), "real_concept");
#endif

   expected_results();

#ifndef BOOST_MATH_BUGGY_LARGE_FLOAT_CONSTANTS
   test_hermite(0.1F, "float");
#endif
   test_hermite(0.1, "double");
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
   test_hermite(0.1L, "long double");
#ifndef BOOST_MATH_NO_REAL_CONCEPT_TESTS
   test_hermite(boost::math::concepts::real_concept(0.1), "real_concept");
#endif
#else
   std::cout << "<note>The long double tests have been disabled on this platform "
      "either because the long double overloads of the usual math functions are "
      "not available at all, or because they are too inaccurate for these tests "
      "to pass.</note>" << std::cout;
#endif
   return 0;
}

max_stars_repo_name: zyiacas/boost-doc-zh

max_issues_repo_name: sdfict/boost-doc-zh

max_forks_repo_name: sdfict/boost-doc-zh


text:
// Copyright (C) 2011-2020 Roki. Distributed under the MIT License
#define BOOST_TEST_MAIN
#include <boost/test/included/unit_test.hpp>
#include <srook/optional.hpp>
#include <srook/type_traits/is_empty.hpp>

BOOST_AUTO_TEST_SUITE(sroptional_test)
BOOST_AUTO_TEST_CASE(optional)
{
    using namespace srook;
    SROOK_ST_ASSERT((is_same<SROOK_DECLTYPE(nullopt), const nullopt_t>{}));
    SROOK_ST_ASSERT((is_empty<nullopt_t>{}));
    SROOK_ST_ASSERT((std::is_literal_type<nullopt_t>{}));
    SROOK_ST_ASSERT((type_traits::detail::Lnot<is_default_constructible<nullopt_t>>{}));

    {
        srook::optional<int> o = srook::nullopt;
        BOOST_TEST( !o );
    }
    {
        srook::optional<int> o = { srook::nullopt };
        BOOST_TEST( !o );
    }
    {
        srook::optional<int> o { srook::nullopt };
        BOOST_TEST( !o );
    }
    {
        srook::optional<int, srook::optionally::safe_optional_payload> o = srook::nullopt;
        BOOST_TEST( !o );
    }
    {
        srook::optional<int, srook::optionally::safe_optional_payload> o = { srook::nullopt };
        BOOST_TEST( !o );
    }
    {
        srook::optional<int, srook::optionally::safe_optional_payload> o { srook::nullopt };
        BOOST_TEST( !o );
    }
}
BOOST_AUTO_TEST_SUITE_END()

ext: cpp

max_stars_repo_name: falgon/srookCppLibraries

max_issues_repo_name: falgon/srookCppLibraries

max_forks_repo_name: falgon/srookCppLibraries


text:
#include <vector>
#include <string>

// boost options
#include <boost/program_options.hpp>
namespace po = boost::program_options;

#include "seq.hpp"

int main(int argc, char *argv[]) {
	try {
		// generate argument parser
		po::options_description desc("Image: allowed options");
		desc.add_options()
			("help", "Print help messages")
			("source", po::value<std::string>(), "h5 source file")
			("target", po::value<std::string>(), "Flow target directory")
			("channel", po::value<int>(), "Channel number")
			("origin", po::value<int>(), "Origin size")
			("out", po::value<int>(), "Output size")
			("label", po::value<bool>(), "Print label in output file name")
			("bound", po::value<double>(), "Bound for normalization");

		po::variables_map vm;
		po::store(po::parse_command_line(argc, argv, desc), vm);
		po::notify(vm);

		std::string source, target;
		int numChannel = 1, origin = 32, out = 32;
		bool label = false;
		double bound = 15.0;

		// assign argument to local variables
		if (vm.count("help")) {
			std::cout << "Image" << std::endl << desc << std::endl;
			return 0;
		} else {
			if (vm.count("source")) source = vm["source"].as<std::string>();
			if (vm.count("target")) target = vm["target"].as<std::string>();
			if (vm.count("channel")) numChannel = vm["channel"].as<int>();
			if (vm.count("origin")) origin = vm["origin"].as<int>();
			if (vm.count("out")) out = vm["out"].as<int>();
			if (vm.count("label")) label = vm["label"].as<bool>();
			if (vm.count("bound")) bound = vm["bound"].as<double>();

			// generate flow for different channels
			Seq seq = Seq(source, target, numChannel, label);
			for (int i = 0; i < numChannel; i++) {
				seq.flow(i, origin, origin, out, out, bound);
			}
		}
	} catch (std::exception& e) {
			std::cerr << "Error: " << e.what() << std::endl;
			return 1;
	} catch (...) {
			std::cerr << "Exception of unknown type" << std::endl;
			return 1;
	}

	return 0;
}

max_issues_repo_name: pedrodinisf/deep-soli

max_forks_repo_name: pedrodinisf/deep-soli


text:
/*************************************************************************
 * Copyright (C) 2017-2019 Barcelona Supercomputing Center               *
 *                         Centro Nacional de Supercomputacion           *
 * All rights reserved.                                                  *
 *                                                                       *
 * This file is part of NORNS, a service that allows other programs to   *
 * start, track and manage asynchronous transfers of data resources      *
 * between different storage backends.                                   *
 *                                                                       *
 * See AUTHORS file in the top level directory for information regarding *
 * developers and contributors.                                          *
 *                                                                       *
 * This software was developed as part of the EC H2020 funded project    *
 * NEXTGenIO (Project ID: 671951).                                       *
 *     www.nextgenio.eu                                                  *
 *                                                                       *
 * Permission is hereby granted, free of charge, to any person obtaining *
 * a copy of this software and associated documentation files (the       *
 * "Software"), to deal in the Software without restriction, including   *
 * without limitation the rights to use, copy, modify, merge, publish,   *
 * distribute, sublicense, and/or sell copies of the Software, and to    *
 * permit persons to whom the Software is furnished to do so, subject to *
 * the following conditions:                                             *
 *                                                                       *
 * The above copyright notice and this permission notice shall be        *
 * included in all copies or substantial portions of the Software.       *
 *                                                                       *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       *
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    *
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND                 *
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS   *
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN    *
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN     *
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE      *
 * SOFTWARE.                                                             *
 *************************************************************************/

#ifndef __SIGNAL_LISTENER_HPP__
#define __SIGNAL_LISTENER_HPP__

#include <functional>
#include <boost/asio.hpp>
#include <boost/asio/signal_set.hpp>

namespace ba = boost::asio;

namespace norns {
namespace api {

template <class F>
void do_for(F /*f*/) {
    // Parameter pack is empty.
}

template <class F, class First, class... Rest>
void do_for(F f, First first, Rest... rest) {
    f(first);
    do_for(f, rest...);
}

struct signal_listener {

    using SignalHandler = std::function<void(int)>;

    explicit signal_listener(ba::io_service& ios) :
        m_signals(ios) {}

    template <typename... Args>
    void set_handler(const SignalHandler& handler, Args... signums) {

        m_handler = std::move(handler);

        m_signals.clear();

        do_for(
                [&](int signum) {
                    m_signals.add(signum);
                },
                signums...);
    }

    void clear_handler() {
        m_handler = nullptr;
        m_signals.clear();
    }

    void do_accept() {

        if(m_handler) {
            m_signals.async_wait(
                std::bind(&signal_listener::signal_handler, this,
                    std::placeholders::_1, std::placeholders::_2));
        }
    }

private:
    void signal_handler(boost::system::error_code error, int signal_number) {
        if(!error) {

            // a signal occurred, invoke handler
            if(m_handler) {
                m_handler(signal_number);
            }

            // reinstall handler
            m_signals.async_wait(
                std::bind(&signal_listener::signal_handler, this,
                    std::placeholders::_1, std::placeholders::_2));
        }
    }

    ba::io_service m_ios;
    ba::signal_set m_signals;
    SignalHandler  m_handler;
};

} // namespace api
} // namespace norns

#endif /* __SIGNAL_LISTENER_HPP__ */

ext: hpp

max_stars_repo_name: bsc-ssrg/NORNS

max_issues_repo_name: bsc-ssrg/NORNS

max_forks_repo_name: bsc-ssrg/NORNS


text:
// This file is part of SWGANH which is released under the MIT license.
// See file LICENSE or go to http://swganh.com/LICENSE

#include <boost/python/module.hpp>

#include "base_combat_command_binding.h"
#include "command_binding.h"
#include "command_properties_binding.h"
#include "command_service_binding.h"

BOOST_PYTHON_MODULE(py_command)
{
    swganh::command::ExportCommand();
    swganh::command::ExportBaseCombatCommand();
    swganh::command::ExportCommandProperties();
    swganh::command::ExportCommandService();
}

ext: cc

max_stars_repo_name: obi-two/GameServer

max_issues_repo_name: apathyboy/swganh

max_forks_repo_name: apathyboy/swganh


text:
/*
shared_mutex 这个名字并不十分贴切，不如 pthread 直呼「读写锁」。

所谓「读写锁」，就是同时可以被多个读者拥有，但是只能被一个写者拥有的锁。
而所谓「多个读者、单个写者」，并非指程序中只有一个写者（线程），而是说不能有多个写者同时去写。

shared_mutex 比一般的 mutex 多了函数 lock_shared() / unlock_shared()，
允许多个（读者）线程同时加锁、解锁，而 shared_lock 则相当于共享版的 lock_guard。

对 shared_mutex 使用 lock_guard 或 unique_lock 就达到了写者独占的目的。

于计数器来说，原子类型 std::atomic<> 也许是更好的选择。
*/
#include <iostream>
//std::unique_lock
#include <mutex>
#include <boost/thread.hpp>
#include <thread>

class ThreadSafeCounter {
public:
    ThreadSafeCounter() = default;

    // 多个线程/读者能同时读计数器的值。
    unsigned int get() const {
        boost::shared_lock<boost::shared_mutex> lock(mutex_);
        return value_;
    }

    // 只有一个线程/写者能增加/写线程的值。
    void increment() {
        boost::unique_lock<boost::shared_mutex> lock(mutex_);
        value_++;
    }

    // 只有一个线程/写者能重置/写线程的值。
    void reset() {
        boost::unique_lock<boost::shared_mutex> lock(mutex_);
        value_ = 0;
    }

private:
    mutable boost::shared_mutex mutex_;
    unsigned int value_ = 0;
};

int main() {
    ThreadSafeCounter counter;

    auto increment_and_print = [&counter]() {
        for (int i = 0; i < 3; i++) {
            counter.increment();
            std::cout << std::this_thread::get_id() << '\t' << counter.get() << std::endl;
        }
    };

    std::thread thread1(increment_and_print);
    std::thread thread2(increment_and_print);

    thread1.join();
    thread2.join();

    return 0;
}

max_stars_repo_name: chanchann/lighao

max_issues_repo_name: chanchann/Thread

max_forks_repo_name: chanchann/Thread


text:
/*
 *          Copyright Andrey Semashev 2007 - 2015.
 * 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   record_emission.cpp
 * \author Andrey Semashev
 * \date   22.03.2009
 *
 * \brief  This code measures performance of log record emission
 */

// #define BOOST_LOG_USE_CHAR
// #define BOOST_ALL_DYN_LINK 1
// #define BOOST_LOG_DYN_LINK 1
#define BOOST_NO_DYN_LINK 1

#include <iomanip>
#include <iostream>
#include <boost/ref.hpp>
#include <boost/bind.hpp>
#include <boost/smart_ptr/shared_ptr.hpp>
#include <boost/smart_ptr/make_shared_object.hpp>
#include <boost/date_time/microsec_time_clock.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/barrier.hpp>

#include <boost/log/core.hpp>
#include <boost/log/common.hpp>
#include <boost/log/attributes.hpp>
#include <boost/log/sinks.hpp>
#include <boost/log/sinks/basic_sink_backend.hpp>

#include <boost/log/expressions.hpp>

#include <boost/log/attributes/scoped_attribute.hpp>

enum config
{
    RECORD_COUNT = 50000000,
    THREAD_COUNT = 3,
    SINK_COUNT = 3
};

namespace logging = boost::log;
namespace expr = boost::log::expressions;
namespace sinks = boost::log::sinks;
namespace attrs = boost::log::attributes;
namespace src = boost::log::sources;
namespace keywords = boost::log::keywords;

enum severity_level
{
    normal,
    warning,
    error
};

BOOST_LOG_ATTRIBUTE_KEYWORD(severity, "Severity", severity_level)

namespace {

    //! A fake sink backend that receives log records
    class fake_backend :
        public sinks::basic_sink_backend< sinks::concurrent_feeding >
    {
    public:
        void consume(logging::record_view const& rec)
        {
        }
    };

} // namespace

void test(unsigned int record_count, boost::barrier& bar)
{
    BOOST_LOG_SCOPED_THREAD_TAG("ThreadID", boost::this_thread::get_id());
    bar.wait();

    src::severity_logger< severity_level > slg;
    for (unsigned int i = 0; i < record_count; ++i)
    {
        BOOST_LOG_SEV(slg, warning) << "Test record";
    }
}

int main(int argc, char* argv[])
{
    std::cout << "Test config: " << THREAD_COUNT << " threads, " << SINK_COUNT << " sinks, " << RECORD_COUNT << " records" << std::endl;
//__debugbreak();
//    typedef sinks::unlocked_sink< fake_backend > fake_sink;
//    typedef sinks::synchronous_sink< fake_backend > fake_sink;
    typedef sinks::asynchronous_sink< fake_backend > fake_sink;
    for (unsigned int i = 0; i < SINK_COUNT; ++i)
        logging::core::get()->add_sink(boost::make_shared< fake_sink >());

    logging::core::get()->add_global_attribute("LineID", attrs::counter< unsigned int >(1));
    logging::core::get()->add_global_attribute("TimeStamp", attrs::local_clock());
    logging::core::get()->add_global_attribute("Scope", attrs::named_scope());

//    logging::core::get()->set_filter(severity > normal); // all records pass the filter
//    logging::core::get()->set_filter(severity > error); // all records don't pass the filter

    logging::core::get()->set_filter(severity > error); // all records don't pass the filter

    const unsigned int record_count = RECORD_COUNT / THREAD_COUNT;
    boost::barrier bar(THREAD_COUNT);
    boost::thread_group threads;

    for (unsigned int i = 1; i < THREAD_COUNT; ++i)
        threads.create_thread(boost::bind(&test, record_count, boost::ref(bar)));

    boost::posix_time::ptime start = boost::date_time::microsec_clock< boost::posix_time::ptime >::universal_time(), end;
    test(record_count, bar);
    if (THREAD_COUNT > 1)
        threads.join_all();
    end = boost::date_time::microsec_clock< boost::posix_time::ptime >::universal_time();

    unsigned long long duration = (end - start).total_microseconds();

    std::cout << "Test duration: " << duration << " us ("
        << std::fixed << std::setprecision(3) << static_cast< double >(RECORD_COUNT) / (static_cast< double >(duration) / 1000000.0)
        << " records per second)" << std::endl;

    return 0;
}


text:
/**
 * @project zqrpc
 * @file src/RpcChannel.cc
 * @author  S Roychowdhury <sroycode @ gmail DOT com>
 * @version 0.1
 *
 * @section LICENSE
 *
 * Copyright (c) 2014 S Roychowdhury
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * @section DESCRIPTION
 *
 *  RpcChannel.cc : Channel Implementation
 *
 */
#include <google/protobuf/descriptor.h>
#include "zqrpc/RpcHeaders.hh"
#include "zqrpc/RpcChannel.hh"
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include <deque>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <climits>

zqrpc::RpcChannel::RpcChannel(zmq::context_t* context, const char* url) :
	context_(context),
	socket_(context,ZMQ_DEALER,boost::lexical_cast<std::string>(boost::this_thread::get_id())),
	url_(url),
	nextreply_(0)
{
	socket_.connect(url);
}

zqrpc::RpcChannel::~RpcChannel()
{
	Close();
}

void zqrpc::RpcChannel::ZSendMethod(const google::protobuf::MethodDescriptor* method,
                                    zqrpc::ZController* controller,
                                    const google::protobuf::Message* request)
{
	try {
		std::string opcode=std::string(method->full_name());
		std::string buffer;
		if (! request->SerializeToString(&buffer) )
			throw zqrpc::ZError(ZEC_INVALIDHEADER);
		typedef std::vector<std::string> FramesT;
		std::string myid = boost::lexical_cast<std::string>(boost::this_thread::get_id());
		std::string nextid = boost::lexical_cast<std::string>(++nextreply_);
		FramesT frames;
		frames.push_back("");
		frames.push_back(nextid);
		frames.push_back(opcode);
		frames.push_back(buffer);
		bool status = socket_.Send<FramesT>(frames);
		if (!status) throw zmq::error_t();

		// OK
		controller->rcode_ = ZRC_WORKING;
		controller->reqno_ = replylist_.size();
		replylist_[nextreply_]=controller;
	} catch (zqrpc::ZError& e) {
		controller->zerror_.reset(ZEC_INVALIDHEADER);
		controller->rcode_ = ZRC_ERROR;
	} catch (zqrpc::RetryException& e) {
		controller->zerror_.reset(ZEC_CONNECTIONERROR);
		controller->rcode_ = ZRC_ERROR;
	} catch (zmq::error_t& e) {
		controller->zerror_.reset(ZEC_CONNECTIONERROR);
		controller->rcode_ = ZRC_ERROR;
	} catch (std::exception& e) {
		controller->zerror_.reset(ZEC_CLIENTERROR);
		controller->rcode_ = ZRC_ERROR;
	}
}

void zqrpc::RpcChannel::ZRecvMethod(ZController* controller,
                                    google::protobuf::Message* response,
                                    long timeout)
{
	// TODO: handle -1 , bad hack to make it 60 secs
	if (timeout<=0) timeout=60000;

	// The Loop below keeps polling and taking in data
	const long start = zqrpc::mstime();
	bool toget=false;
	typedef std::vector<std::string> FramesT;
	FramesT frames;
	do {
		// check if we need to poll
		// if there is toget we poll and get the data anyway for whosoever
		// if not toget we check if our controller has got its data , if so break
		if (!toget && controller->rcode_ != ZRC_WORKING) break;
		long elapsed = zqrpc::mstime() - start;
		// if time elapsed is more than timeout
		if (elapsed > timeout) break;
		if (!toget) toget = socket_.Poll(timeout-elapsed);
		// if toget is false we have spent all the wait time
		if (!toget) break;

		// we have action
		typedef std::vector<std::string> FramesT;
		try {
			frames = socket_.NonBlockingRecv<FramesT>();
		} catch (zqrpc::RetryException& e) {
			// no more data , set toget false and loop
			toget=false;
			continue;
		}
		// discard bad data , but toget remains true hence loop
		if (frames.size() !=4) continue;
		// BLANK ID ERRORCODE DATA
		// data looks ok
		std::size_t nextid = boost::lexical_cast<std::size_t>(frames[1]);
		// check if nextid is rogue , reject and loop
		if (nextid > nextreply_) continue;
		// get the associated controller pointer
		zqrpc::RpcChannel::ReplyListT::iterator it = replylist_.find(nextid);
		if (it==replylist_.end()) continue;
		zqrpc::ZController* othercon = it->second;
		int error = atoi(frames.at(2).c_str());
		if (error) {
			othercon->zerror_ = zqrpc::ZError(static_cast<zqrpc::ErrorCodeE>(error),frames.at(4).c_str());
			othercon->rcode_ = ZRC_ERROR;
		} else {
			othercon->payload_ = frames.at(3);
			othercon->rcode_ = ZRC_READY;
		}
		replylist_.erase(it);
	} while(true);

	if (controller->rcode_==ZRC_READY)
		response->ParseFromString(controller->payload_);
}

void zqrpc::RpcChannel::Close()
{
	socket_.disconnect(url_);
	socket_.close();
}

max_stars_repo_name: sroycode/zqrpc

max_issues_repo_name: sroycode/zqrpc

max_forks_repo_name: sroycode/zqrpc


text:
#include <stan/math/prim/scal.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <gtest/gtest.h>
#include <limits>

TEST(MathFunctions, logical_gte) {
  using stan::math::logical_gte;
  EXPECT_TRUE(logical_gte(1, 0));
  EXPECT_TRUE(logical_gte(2.0, 1.0));
  EXPECT_TRUE(logical_gte(2.0, 1));
  EXPECT_TRUE(logical_gte(0, -1));
  EXPECT_TRUE(logical_gte(1, 1));
  EXPECT_TRUE(logical_gte(5.7, 5.7));

  EXPECT_FALSE(logical_gte(-9.0, 5.7));
  EXPECT_FALSE(logical_gte(-2, -1));
}

TEST(MathFunctions, logical_gte_nan) {
  double nan = std::numeric_limits<double>::quiet_NaN();

  EXPECT_FALSE(stan::math::logical_gte(1.0, nan));
  EXPECT_FALSE(stan::math::logical_gte(nan, 2.0));
  EXPECT_FALSE(stan::math::logical_gte(nan, nan));
}

max_stars_repo_name: jrmie/math

max_issues_repo_name: jrmie/math

max_forks_repo_name: jrmie/math


text:
/**
* Copyright (C), 2017-2018, 北京钜石科技有限公司
* FileName: run_context.hpp
* Author:   aiyong
* Date:     2018/7/7 22:35
*/
#pragma once

#include <assert.h>

#include <map>
#include <chrono>
#include <atomic>
#include <boost/context/fiber.hpp>

#include "task.hpp"
#include "css_data.hpp"
#include "wait_queue.hpp"
#include "stack_allocator.hpp"

namespace tianxing {

class scheduler;

/**
 *
 */
class context
{
private:

    friend class wait_queue;
    template <typename T>
    friend class coroutine_local;

private:
    task *m_task;
    scheduler* m_scheduler;
    wait_queue m_wait_queue;
    boost::context::fiber m_fiber;
    std::map<void*,css_data> m_css_data;

public:
    static thread_local context* current_context;
public:

    context(task *t);

    ~context();

    context(context&&) = delete;
    context(context const&&) = delete;

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

public:

    scheduler* get_scheduler();

    /**
     * 启动协程运行。
     * @param s
     * @param alloctor
     */
    void bind_to(scheduler *s, stack_alloctor &&alloctor);

    /**
     * 恢复协程运行
     */
    void resume();

public:

    /**
     * 执行下一个上下文
     */
    void yield();

    /**
     * 当前上下文睡眠至指定时间点
     * @param tp
     */
    void sleep_until(std::chrono::high_resolution_clock::time_point tp);

    /**
     * 终止当前上下文
     */
    void kill();

    /**
     * 等待协程退出
     * @param waiter
     */
    void join();

    /**
     *挂起当前协程
     */
    void suspend();

    /**
     * 调度coroutine 运行
     * @param c
     */
    void schedule(context *c);

    /**
     * 调度自己运行
     */
    void schedule();

public:

    void run();

};

}

max_stars_repo_name: AiYong/tianxing

max_issues_repo_name: AiYong/tianxing

max_forks_repo_name: AiYong/tianxing


text:
/*
 *  Copyright (c) 2004-present, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */
#include "NeighborUpdater.h"
#include "fboss/agent/ArpCache.h"
#include "fboss/agent/ArpHandler.h"
#include "fboss/agent/FbossError.h"
#include "fboss/agent/IPv6Handler.h"
#include "fboss/agent/NdpCache.h"
#include "fboss/agent/SwSwitch.h"
#include "fboss/agent/state/AggregatePort.h"
#include "fboss/agent/state/ArpTable.h"
#include "fboss/agent/state/DeltaFunctions.h"
#include "fboss/agent/state/NdpTable.h"
#include "fboss/agent/state/Port.h"
#include "fboss/agent/state/StateDelta.h"
#include "fboss/agent/state/SwitchState.h"
#include "fboss/agent/state/Vlan.h"
#include "fboss/agent/state/VlanMap.h"

#include <boost/container/flat_map.hpp>
#include <folly/logging/xlog.h>
#include <list>
#include <mutex>
#include <string>
#include <vector>

using boost::container::flat_map;
using folly::IPAddress;
using folly::IPAddressV4;
using folly::IPAddressV6;
using folly::MacAddress;
using std::shared_ptr;

namespace facebook {
namespace fboss {

using facebook::fboss::DeltaFunctions::forEachChanged;

NeighborUpdater::NeighborUpdater(SwSwitch* sw)
    : AutoRegisterStateObserver(sw, "NeighborUpdater"),
      impl_(std::make_shared<NeighborUpdaterImpl>()),
      sw_(sw) {}

NeighborUpdater::~NeighborUpdater() {
  // we make sure to destroy the NeighborUpdaterImpl on the neighbor
  // cache thread to avoid racing between background entry processing
  // and destruction.
  sw_->getNeighborCacheEvb()->runImmediatelyOrRunInEventBaseThreadAndWait(
      [this]() mutable { return impl_.reset(); });
}

void NeighborUpdater::waitForPendingUpdates() {
  folly::via(sw_->getNeighborCacheEvb(), [impl = this->impl_]() {}).get();
}

auto NeighborUpdater::createCaches(const SwitchState* state, const Vlan* vlan)
    -> std::shared_ptr<NeighborCaches> {
  auto caches = std::make_shared<NeighborCaches>(
      sw_, state, vlan->getID(), vlan->getName(), vlan->getInterfaceID());

  // We need to populate the caches from the SwitchState when a vlan is added
  // After this, we no longer process Arp or Ndp deltas for this vlan.
  caches->arpCache->repopulate(vlan->getArpTable());
  caches->ndpCache->repopulate(vlan->getNdpTable());

  return caches;
}

void NeighborUpdater::stateUpdated(const StateDelta& delta) {
  CHECK(sw_->getUpdateEvb()->inRunningEventBaseThread());
  for (const auto& entry : delta.getVlansDelta()) {
    sendNeighborUpdates(entry);
    auto oldEntry = entry.getOld();
    auto newEntry = entry.getNew();

    if (!newEntry) {
      vlanDeleted(oldEntry->getID());
    } else if (!oldEntry) {
      vlanAdded(
          newEntry->getID(),
          createCaches(delta.newState().get(), newEntry.get()));
    } else {
      if (newEntry->getInterfaceID() != oldEntry->getInterfaceID() ||
          newEntry->getName() != oldEntry->getName()) {
        // For now we only care about changes to the interfaceID and VlanName
        vlanChanged(
            newEntry->getID(), newEntry->getInterfaceID(), newEntry->getName());
      }
    }
  }

  const auto& oldState = delta.oldState();
  const auto& newState = delta.newState();
  if (oldState->getArpTimeout() != newState->getArpTimeout() ||
      oldState->getNdpTimeout() != newState->getNdpTimeout() ||
      oldState->getMaxNeighborProbes() != newState->getMaxNeighborProbes() ||
      oldState->getStaleEntryInterval() != newState->getStaleEntryInterval()) {
    timeoutsChanged(
        newState->getArpTimeout(),
        newState->getNdpTimeout(),
        newState->getStaleEntryInterval(),
        newState->getMaxNeighborProbes());
  }

  forEachChanged(delta.getPortsDelta(), &NeighborUpdater::portChanged, this);
  forEachChanged(
      delta.getAggregatePortsDelta(),
      &NeighborUpdater::aggregatePortChanged,
      this);
}

template <typename T>
void collectPresenceChange(
    const T& delta,
    std::vector<std::string>* added,
    std::vector<std::string>* deleted) {
  for (const auto& entry : delta) {
    auto oldEntry = entry.getOld();
    auto newEntry = entry.getNew();
    if (oldEntry && !newEntry) {
      if (oldEntry->nonZeroPort()) {
        deleted->push_back(folly::to<std::string>(oldEntry->getIP()));
      }
    } else if (newEntry && !oldEntry) {
      if (newEntry->nonZeroPort()) {
        added->push_back(folly::to<std::string>(newEntry->getIP()));
      }
    } else {
      if (oldEntry->zeroPort() && newEntry->nonZeroPort()) {
        // Entry was resolved, add it
        added->push_back(folly::to<std::string>(newEntry->getIP()));
      } else if (oldEntry->nonZeroPort() && newEntry->zeroPort()) {
        // Entry became unresolved, prune it
        deleted->push_back(folly::to<std::string>(oldEntry->getIP()));
      }
    }
  }
}

void NeighborUpdater::sendNeighborUpdates(const VlanDelta& delta) {
  std::vector<std::string> added;
  std::vector<std::string> deleted;
  collectPresenceChange(delta.getArpDelta(), &added, &deleted);
  collectPresenceChange(delta.getNdpDelta(), &added, &deleted);
  if (!(added.empty() && deleted.empty())) {
    sw_->invokeNeighborListener(added, deleted);
  }
}

void NeighborUpdater::portChanged(
    const std::shared_ptr<Port>& oldPort,
    const std::shared_ptr<Port>& newPort) {
  if (oldPort->getOperState() == Port::OperState::UP &&
      newPort->getOperState() == Port::OperState::DOWN) {
    // Fire explicit callback for purging neighbor entries.
    CHECK_EQ(oldPort->getID(), newPort->getID());
    auto portId = newPort->getID();

    sw_->getBackgroundEvb()->runInEventBaseThread([this, portId]() {
      XLOG(INFO) << "Purging neighbor entry for physical port " << portId;
      portDown(PortDescriptor(portId));
    });
  }
}

void NeighborUpdater::aggregatePortChanged(
    const std::shared_ptr<AggregatePort>& oldAggPort,
    const std::shared_ptr<AggregatePort>& newAggPort) {
  CHECK_EQ(oldAggPort->getID(), newAggPort->getID());

  auto oldSubportRange = oldAggPort->sortedSubports();

  bool transitionedToDown = oldAggPort->isUp() && !newAggPort->isUp();
  bool membershipChanged = !std::equal(
      oldSubportRange.begin(),
      oldSubportRange.end(),
      newAggPort->sortedSubports().begin());

  if (transitionedToDown || membershipChanged) {
    auto aggregatePortID = newAggPort->getID();
    sw_->getBackgroundEvb()->runInEventBaseThread([this, aggregatePortID]() {
      XLOG(INFO) << "Purging neighbor entry for aggregate port "
                 << aggregatePortID;
      portDown(PortDescriptor(aggregatePortID));
    });
  }
}
} // namespace fboss
} // namespace facebook

max_stars_repo_name: bkoray/fboss

max_issues_repo_name: bkoray/fboss

max_forks_repo_name: bkoray/fboss


text:
#include "ast.hpp"
#include "parser.hpp"

#include <boost/iostreams/device/mapped_file.hpp> // for mmap

#include <cstdlib>  // for EXIT_SUCCESS
#include <iostream> // for std::cout

namespace bio = boost::iostreams;

auto main(int argc, char **argv) -> int {
  if (argc != 2) {
    std::cerr << "usage: " << argv[0] << " path/to/source.tcc\n";
    std::exit(EXIT_FAILURE); // NOLINT(concurrency-mt-unsafe)
  }

  auto mmap = bio::mapped_file(argv[1], bio::mapped_file::readonly);
  auto p = parser{std::string_view{mmap.const_data(), mmap.size()}};
  auto ast = p.generate_ast();

  p.print_diagnostics(std::cout);
  ast_utils::pretty_print(std::cout, *ast);

  return EXIT_SUCCESS;
}

max_stars_repo_name: tobiashienzsch/tcc

max_issues_repo_name: tobiashienzsch/tcc

max_forks_repo_name: tobiashienzsch/tcc


text:
//  Copyright (c) 2006, Giovanni P. Deretta
//
//  This code may be used under either of the following two licences:
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
//  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE. OF SUCH DAMAGE.
//
//  Or:
//
//  Distributed under the Boost Software License, Version 1.0.
//  (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_COROUTINE_DETAIL_CALL_IMPL_HPP_20060728
#define BOOST_COROUTINE_DETAIL_CALL_IMPL_HPP_20060728

#include <boost/preprocessor/repetition.hpp>
#include <boost/call_traits.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/bind.hpp>
#include <boost/coroutine/coroutine.hpp>
#include <boost/coroutine/detail/arg_max.hpp>
#include <boost/coroutine/detail/signal.hpp>
#include <boost/coroutine/detail/coroutine_accessor.hpp>
namespace boost { namespace coroutines { namespace detail {

#define BOOST_COROUTINE_tuple_param_n(z, n, tuple)\
  BOOST_DEDUCED_TYPENAME                          \
  boost::tuples::element<n, tuple>::type          \
  BOOST_PP_CAT(arg, n)                            \
 /**/

  template<typename Future>
  class callback {
  public:

    typedef void result_type;

    callback(Future& future) :
      m_future_pimpl(wait_gateway::get_impl(future)) {
      m_future_pimpl->mark_pending();
    }

    typedef BOOST_DEDUCED_TYPENAME
    Future::tuple_type tuple_type;

    typedef BOOST_DEDUCED_TYPENAME
    Future::tuple_traits_type tuple_traits_type;

    /*
     * By default a callback is one shot only.
     * By calling this method you can revive a
     * callback for another shot.
     * You must guaranee that the future
     * is still alive.
     */
    void revive() {
      m_future_pimpl->mark_pending();
    }

#define BOOST_COROUTINE_gen_argn_type(z, n, unused) \
    typedef BOOST_DEDUCED_TYPENAME                  \
    tuple_traits_type::                             \
    template at<n>::type                            \
    BOOST_PP_CAT(BOOST_PP_CAT(arg, n), _type);      \
/**/

    BOOST_PP_REPEAT(BOOST_COROUTINE_ARG_MAX,
		    BOOST_COROUTINE_gen_argn_type,
		    ~);

#define BOOST_COROUTINE_param_with_default(z, n, type_prefix) \
    BOOST_DEDUCED_TYPENAME call_traits                   \
    <BOOST_PP_CAT(BOOST_PP_CAT(type_prefix, n), _type)>  \
    ::param_type                                         \
    BOOST_PP_CAT(arg, n) =                               \
    BOOST_PP_CAT(BOOST_PP_CAT(type_prefix, n), _type)()  \
/**/

    void operator()
      (BOOST_PP_ENUM
       (BOOST_COROUTINE_ARG_MAX,
	BOOST_COROUTINE_param_with_default,
	arg)) {
      m_future_pimpl->assign(tuple_type
	(BOOST_PP_ENUM_PARAMS
	 (BOOST_COROUTINE_ARG_MAX, arg)));
    }

  private:
    BOOST_DEDUCED_TYPENAME
    Future::impl_pointer
    m_future_pimpl;
  };

#undef BOOST_COROUTINE_gen_future_assigner
#undef BOOST_COROUTINE_tuple_param_n

  template<typename Future, typename Functor, typename CoroutineSelf>
  Future call_impl(Functor fun, const CoroutineSelf& coro_self) {
    Future future(coro_self);
    fun(callback<Future>(future));
    return future;
  }

} } }

#endif

max_stars_repo_name: erikfrey/coroutine

max_issues_repo_name: erikfrey/coroutine

max_forks_repo_name: erikfrey/coroutine


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

/**
 * \file
 *
 * Implementation for combine_grids.h
 *
 * \author Bhaskara Marthi
 * \author Jiri Horner
 */

#include <occupancy_grid_utils/combine_grids.h>
#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <boost/make_shared.hpp> /* used only in deprecated functions */

namespace occupancy_grid_utils
{

namespace nm=nav_msgs;
namespace gm=geometry_msgs;

using boost::bind;
using boost::ref;
using std::vector;
using std::multiset;
using std::set;
using std::min;
using std::max;

inline Cell point32Cell (const nm::MapMetaData& info, const gm::Point32& p)
{
  gm::Point pt;
  pt.x = p.x;
  pt.y = p.y;
  pt.z = p.z;
  return pointCell(info, pt);
}

// Does this cell contain a vertex of this polygon?
inline bool containsVertex (const nm::MapMetaData& info, const Cell& c, const gm::Polygon& poly)
{
  BOOST_FOREACH (const gm::Point32& p, poly.points) {
    if (point32Cell(info, p)==c)
      return true;
  }
  return false;
}

// Do the two cells (on different grids) intersect?
inline bool cellsIntersect (const nm::MapMetaData& info1, const Cell& c1, const nm::MapMetaData& info2, const Cell& c2)
{
  const gm::Polygon p1=cellPolygon(info1, c1);
  const gm::Polygon p2=cellPolygon(info2, c2);
  return containsVertex(info1, c1, p2) || containsVertex(info2, c2, p1);
}

inline gm::Polygon expandPolygon(const gm::Polygon& p, const double r)
{
  double sx=0;
  double sy=0;
  double sz=0;
  const size_t n = p.points.size();
  for (unsigned i=0; i<n; i++) {
    sx += p.points[i].x;
    sy += p.points[i].y;
    sz += p.points[i].z;
  }
  sx /= n;
  sy /= n;
  sz /= n;
  gm::Polygon p2;
  p2.points.resize(n);
  for (unsigned i=0; i<n; i++) {
    p2.points[i].x = sx + r*(p.points[i].x-sx);
    p2.points[i].y = sy + r*(p.points[i].y-sy);
    p2.points[i].z = sz + r*(p.points[i].z-sz);
  }
  return p2;
}

// Return set of intersecting cells in grid info, of cell cell2 in info2
set<Cell> intersectingCells (const nm::MapMetaData& info, const nm::MapMetaData& info2, const Cell& cell2)
{
  // The expansion is to avoid weird effects due to rounding when intersecting parallel grids
  const gm::Polygon poly=expandPolygon(cellPolygon(info2, cell2), 1.0001);

  // Figure out the candidates
  vector<Cell> corners(4);
  transform(poly.points.begin(), poly.points.end(), corners.begin(),
            bind(point32Cell, boost::ref(info), _1));
  const coord_t min_x=min(corners[0].x, min(corners[1].x, min(corners[2].x, corners[3].x)));
  const coord_t min_y=min(corners[0].y, min(corners[1].y, min(corners[2].y, corners[3].y)));
  const coord_t max_x=max(corners[0].x, max(corners[1].x, max(corners[2].x, corners[3].x)));
  const coord_t max_y=max(corners[0].y, max(corners[1].y, max(corners[2].y, corners[3].y)));

  set<Cell> cells;
  for (coord_t x=min_x; x<=max_x; x++) {
    for (coord_t y=min_y; y<=max_y; y++) {
      const Cell candidate(x, y);
      if (withinBounds(info, candidate) &&
          cellsIntersect(info, candidate, info2, cell2))
        cells.insert(candidate);
    }
  }

  return cells;
}

gm::Pose transformPose (const tf::Pose trans, const gm::Pose p)
{
  tf::Pose pose;
  tf::poseMsgToTF(p, pose);
  gm::Pose transformed;
  tf::poseTFToMsg(trans*pose, transformed);
  return transformed;
}

/* deprecated functions */

nav_msgs::OccupancyGrid::Ptr combineGrids(const std::vector<nav_msgs::OccupancyGrid::ConstPtr>& grids, double resolution) {
  vector<boost::reference_wrapper<nav_msgs::OccupancyGrid const> > grids_refs;
  grids_refs.reserve(grids.size());
  nav_msgs::OccupancyGrid::Ptr result = boost::make_shared<nm::OccupancyGrid>();

  BOOST_FOREACH (const nav_msgs::OccupancyGrid::ConstPtr& g, grids) {
    grids_refs.push_back(boost::cref(*(g.get())));
  }

  combineGrids(grids_refs.begin(), grids_refs.end(), resolution, *result);

  return result;
}

nav_msgs::OccupancyGrid::Ptr combineGrids(const std::vector<nav_msgs::OccupancyGrid::ConstPtr>& grids) {
  ROS_ASSERT (!grids.empty());
  return combineGrids(grids, grids[0]->info.resolution);
}

} // namespace occupancy_grid_utils


text:
/**
 * \ file MultipleUniversalFixedDelayLineFilter.cpp
 */

#include <ATK/Delay/MultipleUniversalFixedDelayLineFilter.h>

#include <array>
#include <fstream>

#include <ATK/Core/InPointerFilter.h>
#include <ATK/Core/OutPointerFilter.h>
#include <ATK/Core/Utilities.h>

#include <ATK/Mock/SimpleSinusGeneratorFilter.h>
#include <ATK/Mock/TriangleCheckerFilter.h>

#include <ATK/Tools/SumFilter.h>

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_NO_MAIN
#include <boost/test/unit_test.hpp>

#include <boost/math/constants/constants.hpp>

#define PROCESSSIZE (1024*64)

BOOST_AUTO_TEST_CASE( StereoUniversalFixedDelayLineFilter_sinus_linel100_delay50_test )
{
  std::vector<double> data(PROCESSSIZE);
  for(gsl::index i = 0; i < PROCESSSIZE; ++i)
  {
    data[i] = std::sin(2 * boost::math::constants::pi<double>() * (i+1.)/48000 * 1000);
  }

  ATK::InPointerFilter<double> generator(data.data(), 1, PROCESSSIZE, false);
  generator.set_output_sampling_rate(48000);

  std::vector<double> outdata(PROCESSSIZE);

  ATK::MultipleUniversalFixedDelayLineFilter<double, 2> filter(100);
  filter.set_input_sampling_rate(48000);
  filter.set_input_port(0, &generator, 0);
  filter.set_input_port(1, &generator, 0);
  filter.set_delay(0, 50);
  filter.set_feedforward(0, 0, 1);

  ATK::OutPointerFilter<double> output(outdata.data(), 1, PROCESSSIZE, false);
  output.set_input_sampling_rate(48000);
  output.set_input_port(0, &filter, 0);

  output.process(49);
  output.process(1);
  output.process(51);
  output.process(PROCESSSIZE - 1 - 49 -51);

  for(gsl::index i = 0; i < 50; ++i)
  {
    BOOST_REQUIRE_EQUAL(0, outdata[i]);
  }

  for(gsl::index i = 50; i < PROCESSSIZE; ++i)
  {
    BOOST_REQUIRE_EQUAL(data[i - 50], outdata[i]);
  }
}

BOOST_AUTO_TEST_CASE(StereoUniversalFixedDelayLineFilter_sinus_line100_delay50_progressive_test)
{
  ATK::SimpleSinusGeneratorFilter<double> generator;
  generator.set_output_sampling_rate(48000);
  generator.set_frequency(480);

  ATK::MultipleUniversalFixedDelayLineFilter<double, 2> filter(100);
  filter.set_input_sampling_rate(48000);
  filter.set_input_port(0, &generator, 0);
  filter.set_input_port(1, &generator, 0);
  filter.set_delay(0, 50);
  filter.set_feedforward(0, 0, 1);
  filter.process(50);

  ATK::SumFilter<double> sum;
  sum.set_input_sampling_rate(48000);
  sum.set_input_port(0, &filter, 0);
  sum.set_input_port(1, &generator, 0);

  ATK::TriangleCheckerFilter<double> output;
  output.set_input_sampling_rate(48000);
  output.set_input_port(0, &sum, 0);
  output.set_amplitude(0);

  for (std::size_t i = 1; i < 100; ++i)
  {
    output.process(i);
  }
}

BOOST_AUTO_TEST_CASE(StereoUniversalFixedDelayLineFilter_sinus_line1000_delay50_progressive_test)
{
  ATK::SimpleSinusGeneratorFilter<double> generator;
  generator.set_output_sampling_rate(48000);
  generator.set_frequency(480);

  ATK::MultipleUniversalFixedDelayLineFilter<double, 2> filter(1000);
  filter.set_input_sampling_rate(48000);
  filter.set_input_port(0, &generator, 0);
  filter.set_input_port(1, &generator, 0);
  filter.set_delay(0, 50);
  filter.set_feedforward(0, 0, 1);
  filter.process(50);

  ATK::SumFilter<double> sum;
  sum.set_input_sampling_rate(48000);
  sum.set_input_port(0, &filter, 0);
  sum.set_input_port(1, &generator, 0);

  ATK::TriangleCheckerFilter<double> output;
  output.set_input_sampling_rate(48000);
  output.set_input_port(0, &sum, 0);
  output.set_amplitude(0);

  for (std::size_t i = 50; i < 1000; ++i)
  {
    output.process(i);
  }
}

BOOST_AUTO_TEST_CASE( StereoUniversalFixedDelayLineFilter_sinus_linel25_delay24_blend_1_feedforward_1_feedback_0_test )
{
  std::vector<double> data(PROCESSSIZE);
  for(gsl::index i = 0; i < PROCESSSIZE; ++i)
  {
    data[i] = std::sin(2 * boost::math::constants::pi<double>() * (i+1.)/48000 * 1000);
  }

  ATK::InPointerFilter<double> generator(data.data(), 1, PROCESSSIZE, false);
  generator.set_output_sampling_rate(48000);

  std::vector<double> outdata(PROCESSSIZE);

  ATK::MultipleUniversalFixedDelayLineFilter<double, 2> filter(25);
  filter.set_input_sampling_rate(48000);
  filter.set_input_port(0, &generator, 0);
  filter.set_input_port(1, &generator, 0);
  filter.set_delay(0, 24);
  filter.set_blend(0, 1);
  filter.set_feedback(0, 0, 0);
  filter.set_feedforward(0, 0, 1);

  ATK::OutPointerFilter<double> output(outdata.data(), 1, PROCESSSIZE, false);
  output.set_input_sampling_rate(48000);
  output.set_input_port(0, &filter, 0);

  output.process(49);
  output.process(1);
  output.process(51);
  output.process(PROCESSSIZE - 1 - 49 -51);

  for(gsl::index i = 24; i < PROCESSSIZE; ++i)
  {
    BOOST_REQUIRE_SMALL(outdata[i], 0.0001);
  }
}

BOOST_AUTO_TEST_CASE( StereoUniversalFixedDelayLineFilter_sinus_linel25_delay24_blend_0_feedforward_0_feedback_1_test )
{
  std::vector<double> data(PROCESSSIZE);
  for(gsl::index i = 0; i < PROCESSSIZE; ++i)
  {
    data[i] = std::sin(2 * boost::math::constants::pi<double>() * (i+1.)/48000 * 1000);
  }

  ATK::InPointerFilter<double> generator(data.data(), 1, PROCESSSIZE, false);
  generator.set_output_sampling_rate(48000);

  std::vector<double> outdata(PROCESSSIZE);

  ATK::MultipleUniversalFixedDelayLineFilter<double, 2> filter(25);
  filter.set_input_sampling_rate(48000);
  filter.set_input_port(0, &generator, 0);
  filter.set_input_port(1, &generator, 0);
  filter.set_delay(0, 24);
  filter.set_blend(0, 0);
  filter.set_feedback(0, 0, .999999);
  filter.set_feedforward(0, 0, 0);

  ATK::OutPointerFilter<double> output(outdata.data(), 1, PROCESSSIZE, false);
  output.set_input_sampling_rate(48000);
  output.set_input_port(0, &filter, 0);

  output.process(49);
  output.process(1);
  output.process(51);
  output.process(PROCESSSIZE - 1 - 49 -51);

  for(gsl::index i = 24; i < PROCESSSIZE; ++i)
  {
    BOOST_REQUIRE_SMALL(outdata[i], 0.0001);
  }
}

BOOST_AUTO_TEST_CASE( StereoUniversalFixedDelayLineFilter_sinus_liner100_delay50_test )
{
  std::vector<double> data(PROCESSSIZE);
  for(gsl::index i = 0; i < PROCESSSIZE; ++i)
  {
    data[i] = std::sin(2 * boost::math::constants::pi<double>() * (i+1.)/48000 * 1000);
  }

  ATK::InPointerFilter<double> generator(data.data(), 1, PROCESSSIZE, false);
  generator.set_output_sampling_rate(48000);

  std::vector<double> outdata(PROCESSSIZE);

  ATK::MultipleUniversalFixedDelayLineFilter<double, 2> filter(100);
  filter.set_input_sampling_rate(48000);
  filter.set_input_port(0, &generator, 0);
  filter.set_input_port(1, &generator, 0);
  filter.set_delay(1, 50);
  filter.set_feedforward(1, 1, 1);

  ATK::OutPointerFilter<double> output(outdata.data(), 1, PROCESSSIZE, false);
  output.set_input_sampling_rate(48000);
  output.set_input_port(0, &filter, 1);

  output.process(49);
  output.process(1);
  output.process(51);
  output.process(PROCESSSIZE - 1 - 49 -51);

  for(gsl::index i = 0; i < 50; ++i)
  {
    BOOST_REQUIRE_EQUAL(0, outdata[i]);
  }

  for(gsl::index i = 50; i < PROCESSSIZE; ++i)
  {
    BOOST_REQUIRE_EQUAL(data[i - 50], outdata[i]);
  }
}

BOOST_AUTO_TEST_CASE(StereoUniversalFixedDelayLineFilter_sinus_liner100_delay50_progressive_test)
{
  ATK::SimpleSinusGeneratorFilter<double> generator;
  generator.set_output_sampling_rate(48000);
  generator.set_frequency(480);

  ATK::MultipleUniversalFixedDelayLineFilter<double, 2> filter(100);
  filter.set_input_sampling_rate(48000);
  filter.set_input_port(0, &generator, 0);
  filter.set_input_port(1, &generator, 0);
  filter.set_delay(1, 50);
  filter.set_feedforward(1, 1, 1);
  filter.process(50);

  ATK::SumFilter<double> sum;
  sum.set_input_sampling_rate(48000);
  sum.set_input_port(0, &filter, 1);
  sum.set_input_port(1, &generator, 0);

  ATK::TriangleCheckerFilter<double> output;
  output.set_input_sampling_rate(48000);
  output.set_input_port(0, &sum, 0);
  output.set_amplitude(0);

  for (std::size_t i = 1; i < 100; ++i)
  {
    output.process(i);
  }
}

BOOST_AUTO_TEST_CASE(StereoUniversalFixedDelayLineFilter_sinus_liner1000_delay50_progressive_test)
{
  ATK::SimpleSinusGeneratorFilter<double> generator;
  generator.set_output_sampling_rate(48000);
  generator.set_frequency(480);

  ATK::MultipleUniversalFixedDelayLineFilter<double, 2> filter(1000);
  filter.set_input_sampling_rate(48000);
  filter.set_input_port(0, &generator, 0);
  filter.set_input_port(1, &generator, 0);
  filter.set_delay(1, 50);
  filter.set_feedforward(1, 1, 1);
  filter.process(50);

  ATK::SumFilter<double> sum;
  sum.set_input_sampling_rate(48000);
  sum.set_input_port(0, &filter, 1);
  sum.set_input_port(1, &generator, 0);

  ATK::TriangleCheckerFilter<double> output;
  output.set_input_sampling_rate(48000);
  output.set_input_port(0, &sum, 0);
  output.set_amplitude(0);

  for (std::size_t i = 50; i < 1000; ++i)
  {
    output.process(i);
  }
}

BOOST_AUTO_TEST_CASE( StereoUniversalFixedDelayLineFilter_sinus_liner25_delay24_blend_1_feedforward_1_feedback_0_test )
{
  std::vector<double> data(PROCESSSIZE);
  for(gsl::index i = 0; i < PROCESSSIZE; ++i)
  {
    data[i] = std::sin(2 * boost::math::constants::pi<double>() * (i+1.)/48000 * 1000);
  }

  ATK::InPointerFilter<double> generator(data.data(), 1, PROCESSSIZE, false);
  generator.set_output_sampling_rate(48000);

  std::vector<double> outdata(PROCESSSIZE);

  ATK::MultipleUniversalFixedDelayLineFilter<double, 2> filter(25);
  filter.set_input_sampling_rate(48000);
  filter.set_input_port(0, &generator, 0);
  filter.set_input_port(1, &generator, 0);
  filter.set_delay(1, 24);
  filter.set_blend(1, 1);
  filter.set_feedback(1, 1, 0);
  filter.set_feedforward(1, 1, 1);

  ATK::OutPointerFilter<double> output(outdata.data(), 1, PROCESSSIZE, false);
  output.set_input_sampling_rate(48000);
  output.set_input_port(0, &filter, 1);

  output.process(49);
  output.process(1);
  output.process(51);
  output.process(PROCESSSIZE - 1 - 49 -51);

  for(gsl::index i = 24; i < PROCESSSIZE; ++i)
  {
    BOOST_REQUIRE_SMALL(outdata[i], 0.0001);
  }
}

BOOST_AUTO_TEST_CASE( StereoUniversalFixedDelayLineFilter_sinus_liner25_delay24_blend_0_feedforward_0_feedback_1_test )
{
  std::vector<double> data(PROCESSSIZE);
  for(gsl::index i = 0; i < PROCESSSIZE; ++i)
  {
    data[i] = std::sin(2 * boost::math::constants::pi<double>() * (i+1.)/48000 * 1000);
  }

  ATK::InPointerFilter<double> generator(data.data(), 1, PROCESSSIZE, false);
  generator.set_output_sampling_rate(48000);

  std::vector<double> outdata(PROCESSSIZE);

  ATK::MultipleUniversalFixedDelayLineFilter<double, 2> filter(25);
  filter.set_input_sampling_rate(48000);
  filter.set_input_port(0, &generator, 0);
  filter.set_input_port(1, &generator, 0);
  filter.set_delay(1, 24);
  filter.set_blend(1, 0);
  filter.set_feedback(1, 1, .999999);
  filter.set_feedforward(1, 1, 0);

  ATK::OutPointerFilter<double> output(outdata.data(), 1, PROCESSSIZE, false);
  output.set_input_sampling_rate(48000);
  output.set_input_port(0, &filter, 1);

  output.process(49);
  output.process(1);
  output.process(51);
  output.process(PROCESSSIZE - 1 - 49 -51);

  for(gsl::index i = 24; i < PROCESSSIZE; ++i)
  {
    BOOST_REQUIRE_SMALL(outdata[i], 0.0001);
  }
}

const int OTHERPROCESSSIZE = 9600;

BOOST_AUTO_TEST_CASE(StereoUniversalFixedDelayLineFilter_sinus_lr_complex_test)
{
  std::vector<double> datal(OTHERPROCESSSIZE);
  {
    std::ifstream input(ATK_SOURCE_TREE "/tests/data/input_lstereo.dat", std::ios::binary);
    input.read(reinterpret_cast<char*>(datal.data()), OTHERPROCESSSIZE * sizeof(double));
  }
  std::vector<double> datar(OTHERPROCESSSIZE);
  {
    std::ifstream input(ATK_SOURCE_TREE "/tests/data/input_rstereo.dat", std::ios::binary);
    input.read(reinterpret_cast<char*>(datar.data()), OTHERPROCESSSIZE * sizeof(double));
  }

  ATK::InPointerFilter<double> generatorl(datal.data(), 1, OTHERPROCESSSIZE, false);
  generatorl.set_output_sampling_rate(96000);
  ATK::InPointerFilter<double> generatorr(datar.data(), 1, OTHERPROCESSSIZE, false);
  generatorr.set_output_sampling_rate(96000);

  ATK::MultipleUniversalFixedDelayLineFilter<double, 2> filter(100000);
  filter.set_input_sampling_rate(96000);
  filter.set_input_port(0, &generatorl, 0);
  filter.set_input_port(1, &generatorr, 0);
  filter.set_delay(0, 4800);
  filter.set_delay(1, 3600);
  filter.set_blend(0, 1);
  filter.set_blend(1, 1);
  filter.set_feedforward(0, 0, -1);
  filter.set_feedforward(0, 1, .1);
  filter.set_feedforward(1, 0, .7);
  filter.set_feedforward(1, 1, -1);
  filter.set_feedback(0, 0, -.5);
  filter.set_feedback(0, 1, .1);
  filter.set_feedback(1, 0, .3);
  filter.set_feedback(1, 1, -.1);

  filter.process(OTHERPROCESSSIZE);

  std::vector<double> outdatal(OTHERPROCESSSIZE);
  {
    std::ifstream input(ATK_SOURCE_TREE "/tests/data/output_lstereo.dat", std::ios::binary);
    input.read(reinterpret_cast<char*>(outdatal.data()), OTHERPROCESSSIZE * sizeof(double));
  }
  std::vector<double> outdatar(OTHERPROCESSSIZE);
  {
    std::ifstream input(ATK_SOURCE_TREE "/tests/data/output_rstereo.dat", std::ios::binary);
    input.read(reinterpret_cast<char*>(outdatar.data()), OTHERPROCESSSIZE * sizeof(double));
  }

  for (unsigned int i = 0; i < OTHERPROCESSSIZE; ++i)
  {
    BOOST_CHECK_CLOSE(outdatal[i], filter.get_output_array(0)[i], 0.0001);
    BOOST_CHECK_CLOSE(outdatar[i], filter.get_output_array(1)[i], 0.0001);
  }
}

BOOST_AUTO_TEST_CASE( StereoUniversalFixedDelayLineFilter_sinus_delay_test )
{
  ATK::MultipleUniversalFixedDelayLineFilter<double, 2> filter(128);
  filter.set_delay(0, 10);
  BOOST_CHECK_EQUAL(filter.get_delay(0), 10);
}

BOOST_AUTO_TEST_CASE( StereoUniversalFixedDelayLineFilter_sinus_delay_range_test )
{
  ATK::MultipleUniversalFixedDelayLineFilter<double, 2> filter(128);
  BOOST_CHECK_THROW(filter.set_delay(0, 0), ATK::RuntimeError);
}

BOOST_AUTO_TEST_CASE( StereoUniversalFixedDelayLineFilter_sinus_delay_range2_test )
{
  ATK::MultipleUniversalFixedDelayLineFilter<double, 2> filter(128);
  BOOST_CHECK_THROW(filter.set_delay(0, 128), ATK::RuntimeError);
}

BOOST_AUTO_TEST_CASE( StereoUniversalFixedDelayLineFilter_sinus_blend_test )
{
  ATK::MultipleUniversalFixedDelayLineFilter<double, 2> filter(128);
  filter.set_blend(0, 0.5);
  BOOST_CHECK_EQUAL(filter.get_blend(0), 0.5);
}

BOOST_AUTO_TEST_CASE( StereoUniversalFixedDelayLineFilter_sinus_feedforward_test )
{
  ATK::MultipleUniversalFixedDelayLineFilter<double, 2> filter(128);
  filter.set_feedforward(0, 0, 0.5);
  BOOST_CHECK_EQUAL(filter.get_feedforward(0, 0), 0.5);
}

BOOST_AUTO_TEST_CASE( StereoUniversalFixedDelayLineFilter_sinus_feedback_test )
{
  ATK::MultipleUniversalFixedDelayLineFilter<double, 2> filter(128);
  filter.set_feedback(0, 0, 0.5);
  BOOST_CHECK_EQUAL(filter.get_feedback(0, 0), 0.5);
}

BOOST_AUTO_TEST_CASE( StereoUniversalFixedDelayLineFilter_sinus_feedback_range_test )
{
  ATK::MultipleUniversalFixedDelayLineFilter<double, 2> filter(128);
  BOOST_CHECK_THROW(filter.set_feedback(0, 0, 1), ATK::RuntimeError);
}

BOOST_AUTO_TEST_CASE( StereoUniversalFixedDelayLineFilter_sinus_feedback_range2_test )
{
  ATK::MultipleUniversalFixedDelayLineFilter<double, 2> filter(128);
  BOOST_CHECK_THROW(filter.set_feedback(0, 0, -1), ATK::RuntimeError);
}

max_stars_repo_name: D-J-Roberts/AudioTK

max_issues_repo_name: D-J-Roberts/AudioTK

max_forks_repo_name: D-J-Roberts/AudioTK


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

struct Format_Fixture
{
    Format_Fixture()
    {
        ygo::deck::DB::get().path("test/card.db");
    }
};

BOOST_FIXTURE_TEST_SUITE(Format, Format_Fixture)

BOOST_AUTO_TEST_CASE(Create)
{
    auto formatDates = ygo::deck::Format::formatDates();
    for (auto&& f : formatDates) {
        ygo::deck::Format formatA(ygo::data::Format::ADVANCED, f);
        BOOST_CHECK_EQUAL(formatA.formatDate(), f);
        BOOST_CHECK(formatA.format() == ygo::data::Format::ADVANCED);

        ygo::deck::Format formatT(ygo::data::Format::TRADITIONAL, f);
        BOOST_CHECK_EQUAL(formatT.formatDate(), f);
        BOOST_CHECK(formatT.format() == ygo::data::Format::TRADITIONAL);

        ygo::deck::Format formatM(ygo::data::Format::MEGABANNED, f);
        BOOST_CHECK_EQUAL(formatM.formatDate(), f);
        BOOST_CHECK(formatM.format() == ygo::data::Format::MEGABANNED);
    }
}

BOOST_AUTO_TEST_CASE(Invalid)
{
    try {
        ygo::deck::Format f(ygo::data::Format::ADVANCED, "InvalidFormat");
        BOOST_CHECK_EQUAL(0, 1);
    } catch (std::runtime_error& e) {
        BOOST_CHECK_EQUAL(1, 1);
    }
}

BOOST_AUTO_TEST_CASE(Limits)
{
    ygo::deck::Format formatA(ygo::data::Format::ADVANCED, "April 2004");
    ygo::deck::Format formatT(ygo::data::Format::TRADITIONAL, "April 2004");
    ygo::deck::Format formatM(ygo::data::Format::MEGABANNED, "April 2004");

    BOOST_CHECK_EQUAL(0, formatA.cardCount("Change of Heart"));
    BOOST_CHECK_EQUAL(1, formatT.cardCount("Change of Heart"));
    BOOST_CHECK_EQUAL(0, formatM.cardCount("Change of Heart"));

    BOOST_CHECK_EQUAL(1, formatA.cardCount("Mage Power"));
    BOOST_CHECK_EQUAL(1, formatT.cardCount("Mage Power"));
    BOOST_CHECK_EQUAL(0, formatM.cardCount("Mage Power"));

    BOOST_CHECK_EQUAL(2, formatA.cardCount("Creature Swap"));
    BOOST_CHECK_EQUAL(2, formatT.cardCount("Creature Swap"));
    BOOST_CHECK_EQUAL(0, formatM.cardCount("Creature Swap"));

    BOOST_CHECK_EQUAL(3, formatA.cardCount("Kuriboh"));
    BOOST_CHECK_EQUAL(3, formatT.cardCount("Kuriboh"));
    BOOST_CHECK_EQUAL(3, formatM.cardCount("Kuriboh"));
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: DeonPoncini/ygodeck

max_issues_repo_name: DeonPoncini/ygodeck

max_forks_repo_name: DeonPoncini/ygodeck


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

#include "base/lifetime.h"

#include <boost/bind.hpp>

LifetimeRefBase::LifetimeRefBase(LifetimeActor *actor)
        : ref_(this, actor) {
}

LifetimeRefBase::~LifetimeRefBase() {
}

LifetimeActor::LifetimeActor(LifetimeManager *manager)
        : manager_(manager), refcount_(0), shutdown_invoked_(false),
          delete_paused_(false),
          create_time_stamp_usecs_(UTCTimestampUsec()),
          delete_time_stamp_usecs_(0) {
    deleted_ = false;
}

LifetimeActor::~LifetimeActor() {
    assert(refcount_ == 0);
    assert(dependents_.empty());
}

//
// Concurrency: called in the context of any Task or the main thread.
//
// Used to trigger delete for a managed object and it's dependents.
//
// Walk the list of dependent LifetimeRefs and cascade the delete.  A mutex is
// used to ensure that the dependent list does not change while we are walking
// through it.
//
// Also enqueue a delete event for this actor to the Lifetime Manager.
//
void LifetimeActor::Delete() {
    if (deleted_.fetch_and_store(true)) {
        return;
    }
    tbb::mutex::scoped_lock lock(mutex_);
    delete_time_stamp_usecs_ = UTCTimestampUsec();
    for (Dependents::iterator iter = dependents_.begin();
         iter != dependents_.end(); ++iter) {
        iter->Delete();
    }
    refcount_++;
    manager_->EnqueueNoIncrement(this);
}

//
// Concurrency: called in the context of the LifetimeManager's Task.
//
// Called immediately before the object is destroyed.
//
void LifetimeActor::DeleteComplete() {
}

//
// Concurrency: called in the context of the LifetimeManager's Task.
//
// Can be called multiple times - when the managed object is initially deleted
// and whenever a delete event is enqueued to the Lifetime Manager. The latter
// happens when the list of dependents becomes empty or the refcount of the
// lightweight dependents goes to 0.
//
void LifetimeActor::Shutdown() {
}

//
// Concurrency: called in the context of main thread.
// TaskScheduler should be stopped prior to invoking this method.
//
// Prevent object from getting destroyed - testing only.
//
void LifetimeActor::PauseDelete() {
    tbb::mutex::scoped_lock lock(mutex_);
    assert(!deleted_);
    delete_paused_ = true;
}

//
// Concurrency: called in the context of main thread.
// TaskScheduler should be stopped prior to invoking this method.
//
// Allow object to get destroyed - testing only.
//
void LifetimeActor::ResumeDelete() {
    tbb::mutex::scoped_lock lock(mutex_);
    assert(deleted_);
    delete_paused_ = false;
    refcount_++;
    manager_->EnqueueNoIncrement(this);
}

//
// Concurrency: called in the context of any Task.
//
// Add the LifetimeRef as a dependent for this Actor.
//
void LifetimeActor::DependencyAdd(
    DependencyRef<LifetimeRefBase, LifetimeActor> *node) {
    tbb::mutex::scoped_lock lock(mutex_);
    assert(!deleted_);
    dependents_.Add(node);
}

//
// Concurrency: called in the context of the LifetimeManager's Task.
//
// Remove the LifetimeRef as a dependent of this Actor.  Note that this can
// happen when the dependent object itself is being deleted i.e. this actor
// itself need not be marked deleted.
//
void LifetimeActor::DependencyRemove(
    DependencyRef<LifetimeRefBase, LifetimeActor> *node) {
    tbb::mutex::scoped_lock lock(mutex_);
    dependents_.Remove(node);
    if (deleted_ && dependents_.empty()) {
        refcount_++;
        manager_->EnqueueNoIncrement(this);
    }
}

// When the actor is placed in the queue the caller must still hold an
// "lock" on the object in the form of either a dependency or an
// explicit test performed by the derived class MayDelete() method.
void LifetimeActor::ReferenceIncrement() {
    tbb::mutex::scoped_lock lock(mutex_);
    refcount_++;
}

bool LifetimeActor::ReferenceDecrementAndTest()  {
    tbb::mutex::scoped_lock lock(mutex_);
    refcount_--;
    return (refcount_ == 0 && dependents_.empty() && !delete_paused_ &&
            MayDelete());
}

LifetimeManager::LifetimeManager(int task_id, TaskEntryCallback on_entry_cb)
        : queue_(task_id, 0,
                 boost::bind(&LifetimeManager::DeleteExecutor, this, _1)) {
    queue_.SetEntryCallback(on_entry_cb);
}

LifetimeManager::~LifetimeManager() {
    queue_.Shutdown();
}

//
// Concurrency: called in the context of any Task or the main thread.
//
// Enqueue a delete event for the actor.
//
void LifetimeManager::Enqueue(LifetimeActor *actor) {
    LifetimeActorRef actor_ref;
    actor->ReferenceIncrement();
    actor_ref.actor = actor;
    queue_.Enqueue(actor_ref);
}

void LifetimeManager::EnqueueNoIncrement(LifetimeActor *actor) {
    LifetimeActorRef actor_ref;
    actor_ref.actor = actor;
    queue_.Enqueue(actor_ref);
}

//
// Concurrency: called in the context of the LifetimeManager's Task.
//
// Ask the managed object to shut itself i.e. take care of cleaning up any
// state that's not represented as an explicit LifetimeRef dependent. Then
// go ahead and destroy the object if all conditions are satisfied.
//
bool LifetimeManager::DeleteExecutor(LifetimeActorRef actor_ref) {
    LifetimeActor *actor = actor_ref.actor;
    if (!actor->shutdown_invoked()) {
        actor->Shutdown();
        actor->set_shutdown_invoked();
    }
    if (actor->ReferenceDecrementAndTest()) {
        actor->DeleteComplete();
        actor->Destroy();
    }
    return true;
}

max_stars_repo_name: safchain/contrail-controller

max_issues_repo_name: sysbot/contrail-controller

max_forks_repo_name: sysbot/contrail-controller


text:
//  Copyright (c) 2001-2010 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)

//  This example implements a simple utility allowing to print the attribute
//  type as it is exposed by an arbitrary Qi parser expression. Just insert
//  your expression below, compile and run this example to see what Qi is
//  seeing!

#if !defined (DISPLAY_ATTRIBUTE_OF_PARSER_JAN_2010_30_0722PM)
#define DISPLAY_ATTRIBUTE_OF_PARSER_JAN_2010_30_0722PM

#include <iostream>
#include <boost/spirit/include/qi.hpp>

namespace tools
{
    namespace spirit = boost::spirit;

    template <typename Expr, typename Iterator = spirit::unused_type>
    struct attribute_of_parser
    {
        typedef typename spirit::result_of::compile<
            spirit::qi::domain, Expr
        >::type parser_expression_type;

        typedef typename spirit::traits::attribute_of<
            parser_expression_type, spirit::unused_type, Iterator
        >::type type;
    };

    template <typename T>
    void display_attribute_of_parser(T const &)
    {
        // Report invalid expression error as early as possible.
        // If you got an error_invalid_expression error message here,
        // then the expression (expr) is not a valid spirit qi expression.
        BOOST_SPIRIT_ASSERT_MATCH(spirit::qi::domain, T);

        typedef typename attribute_of_parser<T>::type type;
        std::cout << typeid(type).name() << std::endl;
    }

    template <typename T>
    void display_attribute_of_parser(std::ostream& os, T const &)
    {
        // Report invalid expression error as early as possible.
        // If you got an error_invalid_expression error message here,
        // then the expression (expr) is not a valid spirit qi expression.
        BOOST_SPIRIT_ASSERT_MATCH(spirit::qi::domain, T);

        typedef typename attribute_of_parser<T>::type type;
        os << typeid(type).name() << std::endl;
    }
}

#endif

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema