text:
//---------------------------------------------------------------------------//
// Copyright (c) 2018-2021 Mikhail Komarov <nemo@nil.foundation>
//
// MIT License
//
// 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.
//---------------------------------------------------------------------------//

#pragma once

#include <boost/container/pmr/polymorphic_allocator.hpp>

#include <nil/actor/core/resource.hh>
#include <nil/actor/core/bitops.hh>

#include <new>
#include <functional>
#include <vector>

namespace nil {
    namespace actor {

        /// \defgroup memory-module Memory management
        ///
        /// Functions and classes for managing memory.
        ///
        /// Memory management in actor consists of the following:
        ///
        ///   - Low-level memory management in the \ref memory namespace.
        ///   - Various smart pointers: \ref shared_ptr, \ref lw_shared_ptr,
        ///     and \ref foreign_ptr.
        ///   - zero-copy support: \ref temporary_buffer and \ref deleter.

        /// Low-level memory management support
        ///
        /// The \c memory namespace provides functions and classes for interfacing
        /// with the actor memory allocator.
        ///
        /// The actor memory allocator splits system memory into a pool per
        /// logical core (lcore).  Memory allocated one an lcore should be freed
        /// on the same lcore; failing to do so carries a severe performance
        /// penalty.  It is possible to share memory with another core, but this
        /// should be limited to avoid cache coherency traffic.
        /// You can obtain the memory layout of the current shard with
        /// \ref get_memory_layout().
        ///
        /// ## Critical allocation scopes
        ///
        /// =nil; Actor supports marking scopes as critical allocation scopes for the purpose
        /// of special treatment from various memory related utilities.
        /// See \ref scoped_critical_alloc_section.
        ///
        /// ## Diagnostics and debugging features
        ///
        /// ### Allocation failure injector
        ///
        /// Allows injecting allocation failures for testing resiliency against
        /// allocation failures, or exceptions in general. See:
        /// * \ref alloc_failure_injector
        /// * \ref with_allocation_failures()
        ///
        /// ### Large allocation warning
        ///
        /// Large allocations put great pressure on the allocator which might be unable
        /// to serve them even if there is enough memory available, due to memory
        /// fragmentation. This is especially relevant for long-running applications,
        /// the kind of applications that are typically built with actor. This feature
        /// allows finding these large by logging a warning on large allocations, with
        /// the stacktrace of the. See:
        /// * \ref set_large_allocation_warning_threshold()
        /// * \ref get_large_allocation_warning_threshold()
        /// * \ref scoped_large_allocation_warning_threshold
        /// * \ref scoped_large_allocation_warning_disable
        ///
        /// ### Heap profiling
        ///
        /// Heap profiling allows finding out how memory is used by your application, by
        /// recording the stacktrace of all allocations. See:
        /// * \ref set_heap_profiling_enabled()
        /// * \ref scoped_heap_profiling
        ///
        /// ### Abort on allocation failure
        ///
        /// Often, the best way to debug an allocation failure is a coredump. This
        /// feature allows dumping core on allocation failures, containing the stack of
        /// the failed allocation, by means of aborting. To enable set the
        /// `abort_on_actor_bad_alloc` configuration option or the respective command
        /// line flag.
        ///
        /// ### Dump diagnostics report
        ///
        /// Dump a diagnostic report of the state of the actor allocator upon allocation
        /// failure. The report is dumped with the `actor_memory` logger, with debug
        /// level.
        /// You can configure a report to be dumped with error level on certain allocation
        /// kinds, see:
        /// * set_dump_memory_diagnostics_on_alloc_failure_kind()
        /// * set_additional_diagnostics_producer()
        /// * generate_memory_diagnostics_report()
        ///
        /// The diagnostics report dump can be configured with the command
        /// line/configuration file via the \p dump-memory-diagnostics-on-alloc-failure-kind
        /// command-line flag/configuration item.
        namespace memory {

            /// \cond internal

#ifdef ACTOR_OVERRIDE_ALLOCATOR_PAGE_SIZE
#define ACTOR_INTERNAL_ALLOCATOR_PAGE_SIZE (ACTOR_OVERRIDE_ALLOCATOR_PAGE_SIZE)
#else
#define ACTOR_INTERNAL_ALLOCATOR_PAGE_SIZE 4096
#endif

            static constexpr size_t page_size = ACTOR_INTERNAL_ALLOCATOR_PAGE_SIZE;
            static constexpr size_t page_bits = log2ceil(page_size);
            static constexpr size_t huge_page_size =
#if defined(__x86_64__) || defined(__i386__) || defined(__s390x__) || defined(__zarch__)
                1 << 21;    // 2M
#elif defined(__aarch64__)
                1 << 21;    // 2M
#elif defined(__PPC__)
                1 << 24;    // 16M
#else
#error "Huge page size is not defined for this architecture"
#endif

            void configure(std::vector<resource::memory> m, bool mbind, boost::optional<std::string> hugetlbfs_path = {});

            void enable_abort_on_allocation_failure();

            class disable_abort_on_alloc_failure_temporarily {
            public:
                disable_abort_on_alloc_failure_temporarily();
                ~disable_abort_on_alloc_failure_temporarily() noexcept;
            };

            // Disables heap profiling as long as this object is alive.
            // Can be nested, in which case the profiling is re-enabled when all
            // the objects go out of scope.
            class disable_backtrace_temporarily {
                bool _old;

            public:
                disable_backtrace_temporarily();
                ~disable_backtrace_temporarily();
            };

            enum class reclaiming_result { reclaimed_nothing, reclaimed_something };

            // Determines when reclaimer can be invoked
            enum class reclaimer_scope {
                //
                // Reclaimer is only invoked in its own fiber. That fiber will be
                // given higher priority than regular application fibers.
                //
                async,

                //
                // Reclaimer may be invoked synchronously with allocation.
                // It may also be invoked in async scope.
                //
                // Reclaimer may invoke allocation, though it is discouraged because
                // the system may be low on memory and such allocations may fail.
                // Reclaimers which allocate should be prepared for re-entry.
                //
                sync
            };

            class reclaimer {
            public:
                struct request {
                    // The number of bytes which is needed to be released.
                    // The reclaimer can release a different amount.
                    // If less is released then the reclaimer may be invoked again.
                    size_t bytes_to_reclaim;
                };
                using reclaim_fn = std::function<reclaiming_result()>;

            private:
                std::function<reclaiming_result(request)> _reclaim;
                reclaimer_scope _scope;

            public:
                // Installs new reclaimer which will be invoked when system is falling
                // low on memory. 'scope' determines when reclaimer can be executed.
                reclaimer(std::function<reclaiming_result()> reclaim, reclaimer_scope scope = reclaimer_scope::async);
                reclaimer(std::function<reclaiming_result(request)> reclaim,
                          reclaimer_scope scope = reclaimer_scope::async);
                ~reclaimer();
                reclaiming_result do_reclaim(size_t bytes_to_reclaim) {
                    return _reclaim(request {bytes_to_reclaim});
                }
                reclaimer_scope scope() const {
                    return _scope;
                }
            };

            extern boost::container::pmr::polymorphic_allocator<char> *malloc_allocator;

            // Call periodically to recycle objects that were freed
            // on cpu other than the one they were allocated on.
            //
            // Returns @true if any work was actually performed.
            bool drain_cross_cpu_freelist();

            // We don't want the memory code calling back into the rest of
            // the system, so allow the rest of the system to tell the memory
            // code how to initiate reclaim.
            //
            // When memory is low, calling \c hook(fn) will result in fn being called
            // in a safe place wrt. allocations.
            void set_reclaim_hook(std::function<void(std::function<void()>)> hook);

            /// \endcond

            class statistics;

            /// Capture a snapshot of memory allocation statistics for this lcore.
            statistics stats();

            /// Memory allocation statistics.
            class statistics {
                uint64_t _mallocs;
                uint64_t _frees;
                uint64_t _cross_cpu_frees;
                size_t _total_memory;
                size_t _free_memory;
                uint64_t _reclaims;
                uint64_t _large_allocs;

                uint64_t _foreign_mallocs;
                uint64_t _foreign_frees;
                uint64_t _foreign_cross_frees;

            private:
                statistics(uint64_t mallocs, uint64_t frees, uint64_t cross_cpu_frees, uint64_t total_memory,
                           uint64_t free_memory, uint64_t reclaims, uint64_t large_allocs, uint64_t foreign_mallocs,
                           uint64_t foreign_frees, uint64_t foreign_cross_frees) :
                    _mallocs(mallocs),
                    _frees(frees), _cross_cpu_frees(cross_cpu_frees), _total_memory(total_memory),
                    _free_memory(free_memory), _reclaims(reclaims), _large_allocs(large_allocs),
                    _foreign_mallocs(foreign_mallocs), _foreign_frees(foreign_frees),
                    _foreign_cross_frees(foreign_cross_frees) {
                }

            public:
                /// Total number of memory allocations calls since the system was started.
                uint64_t mallocs() const {
                    return _mallocs;
                }
                /// Total number of memory deallocations calls since the system was started.
                uint64_t frees() const {
                    return _frees;
                }
                /// Total number of memory deallocations that occured on a different lcore
                /// than the one on which they were allocated.
                uint64_t cross_cpu_frees() const {
                    return _cross_cpu_frees;
                }
                /// Total number of objects which were allocated but not freed.
                size_t live_objects() const {
                    return mallocs() - frees();
                }
                /// Total free memory (in bytes)
                size_t free_memory() const {
                    return _free_memory;
                }
                /// Total allocated memory (in bytes)
                size_t allocated_memory() const {
                    return _total_memory - _free_memory;
                }
                /// Total memory (in bytes)
                size_t total_memory() const {
                    return _total_memory;
                }
                /// Number of reclaims performed due to low memory
                uint64_t reclaims() const {
                    return _reclaims;
                }
                /// Number of allocations which violated the large allocation threshold
                uint64_t large_allocations() const {
                    return _large_allocs;
                }
                /// Number of foreign allocations
                uint64_t foreign_mallocs() const {
                    return _foreign_mallocs;
                }
                /// Number of foreign frees
                uint64_t foreign_frees() const {
                    return _foreign_frees;
                }
                /// Number of foreign frees on reactor threads
                uint64_t foreign_cross_frees() const {
                    return _foreign_cross_frees;
                }
                friend statistics stats();
            };

            struct memory_layout {
                uintptr_t start;
                uintptr_t end;
            };

            // Discover virtual address range used by the allocator on current shard.
            // Supported only when actor allocator is enabled.
            memory::memory_layout get_memory_layout();

            /// Returns the value of free memory low water mark in bytes.
            /// When free memory is below this value, reclaimers are invoked until it goes above again.
            size_t min_free_memory();

            /// Sets the value of free memory low water mark in memory::page_size units.
            void set_min_free_pages(size_t pages);

            /// Enable the large allocation warning threshold.
            ///
            /// Warn when allocation above a given threshold are performed.
            ///
            /// \param threshold size (in bytes) above which an allocation will be logged
            void set_large_allocation_warning_threshold(size_t threshold);

            /// Gets the current large allocation warning threshold.
            size_t get_large_allocation_warning_threshold();

            /// Disable large allocation warnings.
            void disable_large_allocation_warning();

            /// Set a different large allocation warning threshold for a scope.
            class scoped_large_allocation_warning_threshold {
                size_t _old_threshold;

            public:
                explicit scoped_large_allocation_warning_threshold(size_t threshold) :
                    _old_threshold(get_large_allocation_warning_threshold()) {
                    set_large_allocation_warning_threshold(threshold);
                }
                scoped_large_allocation_warning_threshold(const scoped_large_allocation_warning_threshold &) = delete;
                scoped_large_allocation_warning_threshold(scoped_large_allocation_warning_threshold &&x) = delete;
                ~scoped_large_allocation_warning_threshold() {
                    if (_old_threshold) {
                        set_large_allocation_warning_threshold(_old_threshold);
                    }
                }
                void operator=(const scoped_large_allocation_warning_threshold &) const = delete;
                void operator=(scoped_large_allocation_warning_threshold &&) = delete;
            };

            /// Disable large allocation warnings for a scope.
            class scoped_large_allocation_warning_disable {
                size_t _old_threshold;

            public:
                scoped_large_allocation_warning_disable() : _old_threshold(get_large_allocation_warning_threshold()) {
                    disable_large_allocation_warning();
                }
                scoped_large_allocation_warning_disable(const scoped_large_allocation_warning_disable &) = delete;
                scoped_large_allocation_warning_disable(scoped_large_allocation_warning_disable &&x) = delete;
                ~scoped_large_allocation_warning_disable() {
                    if (_old_threshold) {
                        set_large_allocation_warning_threshold(_old_threshold);
                    }
                }
                void operator=(const scoped_large_allocation_warning_disable &) const = delete;
                void operator=(scoped_large_allocation_warning_disable &&) = delete;
            };

            /// Enable/disable heap profiling.
            ///
            /// In order to use heap profiling you have to define
            /// `ACTOR_HEAPPROF`.
            /// Heap profiling data is not currently exposed via an API for
            /// inspection, instead it was designed to be inspected from a
            /// debugger.
            /// For an example script that makes use of the heap profiling data
            /// see [scylla-gdb.py]
            /// (https://github.com/scylladb/scylla/blob/e1b22b6a4c56b4f1d0adf65d1a11db4bcb51fe7d/scylla-gdb.py#L1439)
            /// This script can generate either textual representation of the data, or a zoomable flame graph ([flame
            /// graph generation instructions](https://github.com/scylladb/scylla/wiki/=nil; Actor-heap-profiler),
            /// [example flame
            /// graph](https://user-images.githubusercontent.com/1389273/72920437-f0cf8a80-3d51-11ea-92f0-f3dbeb698871.png)).
            void set_heap_profiling_enabled(bool);

            /// Enable heap profiling for the duration of the scope.
            ///
            /// For more information about heap profiling see
            /// \ref set_heap_profiling_enabled().
            class scoped_heap_profiling {
            public:
                scoped_heap_profiling() noexcept;
                ~scoped_heap_profiling();
            };

        }    // namespace memory
    }        // namespace actor
}    // namespace nil

ext: hh

max_stars_repo_name: NilFoundation/actor-core

max_issues_repo_name: NilFoundation/actor-core

max_forks_repo_name: NilFoundation/actor-core


text:
/*
 * main.cpp
 *
 *  Created on: 11.07.2017
 *      Author: thies
 */

#include <deal.II/base/logstream.h>
#include <deal.II/base/mpi.h>
#include <deal.II/base/timer.h>
#include <gtest/gtest.h>
#include <fstream>
#include <Version.h>

using namespace dealii;
using namespace wavepi;

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  Utilities::MPI::MPI_InitFinalize mpi_init(argc, argv);

  std::ofstream logout("wavepi-test.log", std::ios_base::trunc);
  deallog.attach(logout);
  deallog.depth_console(0);
  deallog.depth_file(100);
  deallog.precision(3);
  deallog.pop();

  deallog << Version::get_identification() << std::endl;
  deallog << Version::get_infos() << std::endl;

  Timer timer; timer.start();
  int rc = RUN_ALL_TESTS();
  timer.stop();

  deallog << "Total wall time: " << timer.wall_time() << "s, cpu time: " << timer.cpu_time() << "s" << std::endl;

  return rc;
}

ext: cpp

max_stars_repo_name: thiesgerken/wavepi

max_issues_repo_name: thiesgerken/wavepi

max_forks_repo_name: thiesgerken/wavepi


text:
#include <iostream>

#include <elemental.hpp>
#include <boost/mpi.hpp>
#include <boost/format.hpp>
#include <skylark.hpp>

/*******************************************/
namespace bmpi =  boost::mpi;
namespace skybase = skylark::base;
namespace skysk =  skylark::sketch;
namespace skynla = skylark::nla;
namespace skyalg = skylark::algorithms;
namespace skyutil = skylark::utility;
/*******************************************/

const int m = 50000;
const int n = 500;

typedef elem::DistMatrix<double, elem::VC, elem::STAR> matrix_type;
typedef elem::DistMatrix<double, elem::VC, elem::STAR> rhs_type;
typedef elem::DistMatrix<double, elem::STAR, elem::STAR> sol_type;

template<typename MatrixType, typename RhsType, typename SolType>
void check_solution(const MatrixType &A, const RhsType &b, const SolType &x,
    const RhsType &r0,
    double &res, double &resAtr, double &resFac) {
    RhsType r(b);
    skybase::Gemv(elem::NORMAL, -1.0, A, x, 1.0, r);
    res = skybase::Nrm2(r);

    SolType Atr(x.Height(), x.Width(), x.Grid());
    skybase::Gemv(elem::TRANSPOSE, 1.0, A, r, 0.0, Atr);
    resAtr = skybase::Nrm2(Atr);

    skybase::Axpy(-1.0, r0, r);
    RhsType dr(b);
    skybase::Axpy(-1.0, r0, dr);
    resFac = skybase::Nrm2(r) / skybase::Nrm2(dr);
}

int main(int argc, char** argv) {
    double res, resAtr, resFac;

    elem::Initialize(argc, argv);

    bmpi::communicator world;
    int rank = world.rank();

    skybase::context_t context(23234);

    // Setup problem and righthand side
    // Using Skylark's uniform generator (as opposed to Elemental's)
    // will insure the same A and b are generated regardless of the number
    // of processors.
    matrix_type A =
        skyutil::uniform_matrix_t<matrix_type>::generate(m,
            n, elem::DefaultGrid(), context);
    matrix_type b =
        skyutil::uniform_matrix_t<matrix_type>::generate(m,
            1, elem::DefaultGrid(), context);

    sol_type x(n,1);
    rhs_type r(b);

    boost::mpi::timer timer;
    double telp;

    // Solve using Elemental. Note: Elemental only supports [MC,MR]...
    elem::DistMatrix<double> A1 = A, b1 = b, x1;
    timer.restart();
    elem::LeastSquares(elem::NORMAL, A1, b1, x1);
    telp = timer.elapsed();
    x = x1;
    check_solution(A, b, x, r, res, resAtr, resFac);
    if (rank == 0)
        std::cout << "Elemental:\t\t\t||r||_2 =  "
                  << boost::format("%.2f") % res
                  << "\t\t\t\t\t\t\t||A' * r||_2 = " << boost::format("%.2e") % resAtr
                  << "\t\tTime: " << boost::format("%.2e") % telp << " sec"
                  << std::endl;
    double res_opt = res;

    skybase::Gemv(elem::NORMAL, -1.0, A, x, 1.0, r);

    // Solve using Sylark
    timer.restart();
    skynla::FastLeastSquares(elem::NORMAL, A, b, x, context);
    telp = timer.elapsed();
    check_solution(A, b, x, r, res, resAtr, resFac);
    if (rank == 0)
        std::cout << "Skylark:\t\t\t||r||_2 =  "
                  << boost::format("%.2f") % res
                  << " (x " << boost::format("%.5f") % (res / res_opt) << ")"
                  << "\t||r - r*||_2 / ||b - r*||_2 = " << boost::format("%.2e") % resFac
                  << "\t||A' * r||_2 = " << boost::format("%.2e") % resAtr
                  << "\t\tTime: " << boost::format("%.2e") % telp << " sec"
                  << std::endl;

    // Approximately solve using Sylark
    timer.restart();
    skynla::ApproximateLeastSquares(elem::NORMAL, A, b, x, context);
    telp = timer.elapsed();
    check_solution(A, b, x, r, res, resAtr, resFac);
    if (rank == 0)
        std::cout << "Skylark (approximate):\t\t||r||_2 =  "
                  << boost::format("%.2f") % res
                  << " (x " << boost::format("%.5f") % (res / res_opt) << ")"
                  << "\t||r - r*||_2 / ||b - r*||_2 = " << boost::format("%.2e") % resFac
                  << "\t||A' * r||_2 = " << boost::format("%.2e") % resAtr
                  << "\t\tTime: " << boost::format("%.2e") % telp << " sec"
                  << std::endl;

    return 0;
}

max_issues_repo_name: cjiyer/libskylark

max_forks_repo_name: cjiyer/libskylark


text:
#include "arguments.hh"
#include <iostream>
#include <iomanip>

#include <boost/program_options.hpp>

namespace fs = std::filesystem;
namespace po = boost::program_options;

#include "errors.hh"

Arguments compiler_arguments;

[[noreturn]]
void help(po::options_description const& desc)
{
	std::cout << "usage: stacky <build|run> [options] <sources...>\n";
	std::cout << desc << '\n';
	exit(1);
}

void Arguments::parse(int argc, char **argv)
try {
	po::options_description common("Common options");
	common.add_options()
		("help,h", "produce help message")
		("verbose,v", "print all unnesesary info during compilation")
		("check,c", "type check program")
		("no-colors,C", "errors, warnings and info messages will NOT show color coded")
	;

	po::options_description build("Build options");
	build.add_options()
		("output,o", po::value<std::string>()->value_name("<path>"), "file name of produced executable")
	;

	po::options_description config("Configuration");
	config.add_options()
		("include,I", po::value<std::vector<fs::path>>()->composing()->value_name("<path>"), "adds path to the list of dirs where Stacky files are searched when `include` or `import` word is executed")
	;

	po::options_description debug("Debugging");
	debug.add_options()
		("dump-effects", "dump all defined words types")
		("control-flow", "generate control flow graph of a program")
		("control-flow-for", po::value<std::string>()->value_name("<function>"), "generate control flow graph of a function")
	;

	po::options_description hidden("Hidden options");
	hidden.add_options()
		("source", po::value<std::vector<std::string>>(), "Source files with Stacky code")
		("command", po::value<std::string>(), "command to execute");

	po::positional_options_description pos;
	pos.add("command", 1).add("source", -1);

	po::options_description cmdline_options;
	cmdline_options.add(common).add(config).add(debug).add(hidden);

	po::options_description visible;
	visible.add(common).add(build).add(config).add(debug);

	po::parsed_options parsed = po::command_line_parser(argc, argv)
		.options(cmdline_options)
		.positional(pos)
		.allow_unregistered()
		.run();

	po::variables_map vm;
	po::store(parsed, vm);

	if (!vm.count("command") || argc == 0 || vm.count("help")) {
		help(visible);
	}

	auto const& command = vm["command"].as<std::string>();

	std::vector<std::string> opts = po::collect_unrecognized(parsed.options, po::include_positional);
	opts.erase(opts.begin());

	if (command == "build" || (run_mode = command == "run")) {
		po::store(po::command_line_parser(opts).options(build).run(), vm);
	} else {
		error_fatal("Unrecognized command: "_format(command));
	}

	ensure_fatal(vm.count("source"), "no input files");
	source_files = vm["source"].as<std::vector<std::string>>();

	if (vm.count("output")) {
		executable = vm["output"].as<std::string>();
	} else {
		auto src_path = fs::path(source_files[0]);
		executable = src_path.parent_path();
		executable /= src_path.stem();
	}

	assembly = executable;
	assembly += ".asm";

	if (vm.count("include"))
		include_search_paths = vm["include"].as<std::vector<fs::path>>();

	compiler = fs::canonical("/proc/self/exe");
	include_search_paths.push_back(compiler.parent_path() / "std");

	verbose   = vm.count("verbose");
	typecheck = vm.count("check");
	dump_words_effects = vm.count("dump-effects");
	output_colors = !vm.count("no-colors") && isatty(STDOUT_FILENO);

	if (control_flow_graph = vm.count("control-flow")) {
		control_flow = executable;
		control_flow += ".dot";
	}

	if (vm.count("control-flow-for")) {
		control_flow_graph = true;
		control_flow_function = vm["control-flow-for"].as<std::string>();
		control_flow = executable;
		control_flow += ".fun.dot";
	}
} catch (boost::program_options::unknown_option const& u) {
	error_fatal(u.what());
}

ext: cc

max_stars_repo_name: RobertBendun/stacky

max_issues_repo_name: RobertBendun/stacky

max_forks_repo_name: RobertBendun/stacky


text:
/**
 * @file EuclideanParamBlock.hpp
 * @brief Header file for the EuclideanParamBlock class.
 * @author Jianzhu Huai
 */

#ifndef INCLUDE_OKVIS_CERES_EUCLIDEANPARAMBLOCK_HPP_
#define INCLUDE_OKVIS_CERES_EUCLIDEANPARAMBLOCK_HPP_

#include <okvis/ceres/ParameterBlockDynamic.hpp>
#include <Eigen/Core>
#include <okvis/Time.hpp>

namespace okvis {
/// \brief ceres Namespace for ceres-related functionality implemented in okvis.
namespace ceres {

/// \brief Wraps the parameter block for camera projection intrinsic estimate
class EuclideanParamBlock
    : public ParameterBlockDynamic {
 public:
  EIGEN_MAKE_ALIGNED_OPERATOR_NEW

  typedef Eigen::Matrix<double, Eigen::Dynamic, 1> estimate_t;
  /// \brief Set the time.
  /// @param[in] timestamp The timestamp of this state.
  void setTimestamp(const okvis::Time& timestamp) { timestamp_ = timestamp; }

  /// \brief Default constructor (assumes not fixed).
  EuclideanParamBlock() : ParameterBlockDynamic(0, 0) {
    ParameterBlock::setFixed(false);
  }

  /// \brief Trivial destructor.
  virtual ~EuclideanParamBlock() {
  }

  /// \brief Constructor with estimate and time.
  /// @param[in] ProjectionIntrinsicParams
  /// @param[in] id The (unique) ID of this block.
  /// @param[in] timestamp The timestamp of this state.
  /// @param[in] dim The dim and minDim of this state.
  EuclideanParamBlock(const Eigen::VectorXd& params, uint64_t id,
      const okvis::Time& timestamp, const int dim) :
      ParameterBlockDynamic(dim, dim) {
    setEstimate(params);
    setId(id);
    setTimestamp(timestamp);
    setFixed(false);
  }

  // setters
  /// @brief Set estimate of this parameter block.
  /// @param[in] ProjectionIntrinsicParams The estimate to set this to.
  void setEstimate(
      const Eigen::VectorXd& params) {
    for (int i = 0; i < dim_; ++i)
      parameters_[i] = params[i];
  }

  /// getters
  /// @brief Get estimate.
  Eigen::VectorXd estimate() const {
    Eigen::VectorXd params(dim_);
    for (int i = 0; i < dim_; ++i)
      params[i] = parameters_[i];
    return params;
  }

  /// \brief Get the time.
  /// \return The timestamp of this state.
  okvis::Time timestamp() const { return timestamp_; }

  // minimal internal parameterization
  // x0_plus_Delta=Delta_Chi[+]x0
  /// \brief Generalization of the addition operation,
  ///        x_plus_delta = Plus(x, delta)
  ///        with the condition that Plus(x, 0) = x.
  /// @param[in] x0 Variable.
  /// @param[in] Delta_Chi Perturbation.
  /// @param[out] x0_plus_Delta Perturbed x.
  virtual void plus(const double* x0, const double* Delta_Chi,
                    double* x0_plus_Delta) const {
    Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic, 1> > x0_(x0, dim_);
    Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic, 1> > Delta_Chi_(
        Delta_Chi, minDim_);
    Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, 1> > x0_plus_Delta_(
        x0_plus_Delta, dim_);
    x0_plus_Delta_ = x0_ + Delta_Chi_;
  }

  /// \brief The jacobian of Plus(x, delta) w.r.t delta at delta = 0.
  /// @param[in] x0 Variable.
  /// @param[out] jacobian The Jacobian.
  virtual void plusJacobian(const double* /*unused: x*/,
                            double* jacobian) const {
    Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic,
                             Eigen::RowMajor> >
        identity(jacobian, dim_, minDim_);
    identity.setIdentity();
  }

  // Delta_Chi=x0_plus_Delta[-]x0
  /// \brief Computes the minimal difference between a variable x and a
  /// perturbed variable x_plus_delta
  /// @param[in] x0 Variable.
  /// @param[in] x0_plus_Delta Perturbed variable.
  /// @param[out] Delta_Chi Minimal difference.
  /// \return True on success.
  virtual void minus(const double* x0, const double* x0_plus_Delta,
                     double* Delta_Chi) const {
    Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic, 1> > x0_(x0, dim_);
    Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, 1> > Delta_Chi_(Delta_Chi, minDim_);
    Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic, 1> > x0_plus_Delta_(
        x0_plus_Delta, dim_);
    Delta_Chi_ = x0_plus_Delta_ - x0_;
  }

  /// \brief Computes the Jacobian from minimal space to naively
  /// overparameterised space as used by ceres.
  //  /// @param[in] x0 Variable.
  /// @param[out] jacobian the Jacobian (dimension minDim x dim).
  /// \return True on success.
  virtual void liftJacobian(const double* /*unused: x*/,
                            double* jacobian) const {
    Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic,
                             Eigen::RowMajor> >
        identity(jacobian, minDim_, dim_);
    identity.setIdentity();
  }

  /// @brief Return parameter block type as string
  virtual std::string typeInfo() const { return "EuclideanParamBlock"; }

 private:
  okvis::Time timestamp_;  ///< Time of this state.
};
}  // namespace ceres
}  // namespace okvis

#endif /* INCLUDE_OKVIS_CERES_EUCLIDEANPARAMBLOCK_HPP_ */

ext: hpp


text:
// Copyright Louis Dionne 2013-2017
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)

#include <boost/hana/assert.hpp>
#include <boost/hana/contains.hpp>
#include <boost/hana/core/make.hpp>
#include <boost/hana/integral_constant.hpp>
#include <boost/hana/not.hpp>
#include <boost/hana/range.hpp>

#include <support/cnumeric.hpp>
namespace hana = boost::hana;

int main() {
    BOOST_HANA_CONSTANT_CHECK(hana::not_(hana::contains(
        hana::make_range(hana::int_c<0>, hana::int_c<0>),
        cnumeric<int, 0>
    )));

    BOOST_HANA_CONSTANT_CHECK(hana::contains(
        hana::make_range(hana::int_c<0>, hana::int_c<1>),
        cnumeric<int, 0>
    ));

    BOOST_HANA_CONSTANT_CHECK(hana::contains(
        hana::make_range(hana::int_c<0>, hana::int_c<10>),
        cnumeric<int, 3>
    ));

    BOOST_HANA_CONSTANT_CHECK(hana::contains(
        hana::make_range(hana::int_c<0>, hana::int_c<10>),
        cnumeric<int, 9>
    ));

    BOOST_HANA_CONSTANT_CHECK(hana::contains(
        hana::make_range(hana::int_c<-10>, hana::int_c<10>),
        cnumeric<int, -10>
    ));

    BOOST_HANA_CONSTANT_CHECK(hana::contains(
        hana::make_range(hana::int_c<-10>, hana::int_c<10>),
        cnumeric<int, -5>
    ));

    BOOST_HANA_CONSTANT_CHECK(hana::not_(hana::contains(
        hana::make_range(hana::int_c<-10>, hana::int_c<0>),
        cnumeric<int, 3>
    )));

    BOOST_HANA_CONSTANT_CHECK(hana::not_(hana::contains(
        hana::make_range(hana::int_c<0>, hana::int_c<10>),
        cnumeric<int, 15>
    )));
}


text:
#ifndef CAFFE_SERIALIZATION_PROTOSERIALIZE_HPP_
#define CAFFE_SERIALIZATION_PROTOSERIALIZE_HPP_

#include <boost/function.hpp>
#include <boost/optional.hpp>
#include <string>
#include "caffe/blob.hpp"
#include "caffe/proto/caffe.pb.h"

namespace caffe {

bool deserialize(const char* data,
                 size_t size,
                 ::google::protobuf::Message* msg);

string serialize(const ::google::protobuf::Message& msg);

}  // namespace caffe

#endif  // CAFFE_SERIALIZATION_PROTOSERIALIZE_HPP_


text:
//==================================================================================================
/*!
  @file

  @copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_EXTRACT_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_EXTRACT_HPP_INCLUDED

#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{
  /*!
    @ingroup group-arithmetic

    Random-access extraction of a value subcomponent

    Extract a sub-element of a given value @c v

    @par Semantic

    For any value @c v of type @c Value and @c o of type @c Offset:

    @code
    auto x = extract(v,o);
    @endcode

    is similar to:

    - If @c v is a scalar value:

      @code
      x = v;
      @endcode

    - If @c v is a SIMD value:

      @code
      x = v[o];
      @endcode

    @param v   Value to extract
    @param o   Position to extract from (offset)

    @return The extracted value
  **/
  template<typename Value, typename Offset>
  scalar_of_t<Value> extract( Value const& v, Offset const& o);
} }
#endif

#include <boost/simd/function/scalar/extract.hpp>
#include <boost/simd/function/simd/extract.hpp>

#endif

max_stars_repo_name: xmar/pythran

max_issues_repo_name: xmar/pythran

max_forks_repo_name: xmar/pythran


text:
#include "i_notify.h"

// Based on https://www.man7.org/linux/man-pages/man7/inotify.7.html#EXAMPLES

#include "i_notify_helper.h"

#include <boost/log/trivial.hpp>
#include <sys/inotify.h>
#include <sys/eventfd.h>
#include <iostream>
#include <thread>
#include <poll.h>
#include <unistd.h>

namespace std {

std::ostream& operator<< (std::ostream &out, const NotifyEvent &ne) {
  out << "{wd: " << ne.wd
      << ", mask: \"" << strMask(ne.mask)
      << "\", cookie: " << ne.cookie
      << "\", name: \"" << ne.name
      << "\"}";
  return out;
}

} //namespace std

namespace {

// it throws on error
void handle_events(int fd, std::function<void(NotifyEvent)> fn) {

   // Some systems cannot read integer variables if they are not
   // properly aligned. On other systems, incorrect alignment may
   // decrease performance. Hence, the buffer used for reading from
   // the inotify file descriptor should have the same alignment as
   // struct inotify_event.

   char buf[4096]
       __attribute__ ((aligned(__alignof__(struct inotify_event))));

   // Loop while events can be read from inotify file descriptor.
   for (;;) {
     // Read some events.
     ssize_t len = read(fd, buf, sizeof(buf));
     if (len == -1 && errno != EAGAIN) {
       std::stringstream sstr;
       sstr<< "Can't read from file descriptor, error: " << strerror(errno);
       BOOST_LOG_TRIVIAL(error) << sstr.str();
       throw std::runtime_error(sstr.str());
     }

     // If the nonblocking read() found no events to read, then
     // it returns -1 with errno set to EAGAIN. In that case,
     // we exit the loop.
     if (len <= 0)
       break;

     // Loop over all events in the buffer
     const struct inotify_event *event;
     for (char *ptr = buf; ptr < buf + len;
          ptr += sizeof(struct inotify_event) + event->len)
     {
       event = reinterpret_cast<const struct inotify_event *>(ptr);
       auto ne = NotifyEvent{event};
       BOOST_LOG_TRIVIAL(debug) << "Passing event to the client-provided callback. " << ne;
       fn(ne);
     }// for events
   }
} //handle_events

} //namespace

INotify::INotify(std::function<void(NotifyEvent)> fn) {
  BOOST_LOG_TRIVIAL(info) << "Initializing inotify";

  efd = eventfd(0,0);

  fd = inotify_init1(IN_NONBLOCK);
  if (fd == -1) {
    std::stringstream sstr;
    sstr<< "inotify_init1 failed with error: " << strerror(errno);
    BOOST_LOG_TRIVIAL(error) << sstr.str();
    throw std::runtime_error(sstr.str());
  }

  int lfd = fd;
  th = std::thread([lfd, fn, this]() {
    // Prepare for polling
    const int nfds = 2;

    pollfd fds[2];

    // Inotify input
    fds[0].fd = lfd;
    fds[0].events = POLLIN;
    fds[1].fd = efd;
    fds[1].events = POLLIN;

    BOOST_LOG_TRIVIAL(info) << "Listening for events.";
    while (true) {
      BOOST_LOG_TRIVIAL(trace)<<"Entering poll";
      int poll_num = poll(fds, nfds, -1);
      BOOST_LOG_TRIVIAL(trace)<<"poll returned";
      if (poll_num == -1) {
        if (errno == EINTR) {
         continue;
        }

        std::stringstream sstr;
        sstr<< "Polling of file descriptors failed, error: " << strerror(errno);
        BOOST_LOG_TRIVIAL(error) << sstr.str();
        throw std::runtime_error(sstr.str());
      }
      if (poll_num > 0) {
        if (fds[1].revents & POLLIN) {
          BOOST_LOG_TRIVIAL(debug) << "exiting event received";
          break;
        } else if (fds[0].revents & POLLIN) {
          // Inotify events are available
          handle_events(lfd, fn);
        } else {
          BOOST_LOG_TRIVIAL(info) << "Unexpected result of polling. Check what it is."
            << " [0].events: " << fds[0].events
            << " [1].events: " << fds[1].events;
        }
      }
    } //while
  });
}

INotify::~INotify() {
  BOOST_LOG_TRIVIAL(info) << "Stopping the thread";

  uint64_t u = 1;
  auto s = write(efd, &u, sizeof(u));
  if (s!=sizeof(u)) {
    BOOST_LOG_TRIVIAL(error) << "Failed to write to event fd, error: " << strerror(errno);
  }
  BOOST_LOG_TRIVIAL(debug) << "Joining the thread";
  th.join();
  if (fd!=-1) {
    BOOST_LOG_TRIVIAL(debug) << "Closing file descriptor";
    close(fd);
  }
  close(efd);
  BOOST_LOG_TRIVIAL(info) << "INotify is destructed";
}

int INotify::monitorPath(fs::path const &path) {
  int wd = inotify_add_watch(fd, path.c_str(), IN_ALL_EVENTS);
  if (wd == -1) {
    std::stringstream sstr;
    sstr << "inotify_add_watch failed for path " + std::to_string(wd)
         << ", error: " << strerror(errno);
    BOOST_LOG_TRIVIAL(error) << sstr.str();
    throw std::runtime_error(sstr.str());
  }
  return wd;
}

void INotify::removeWatch(int wd) {
  int res = inotify_rm_watch(fd, wd);
  if (res == -1) {
    std::stringstream sstr;
    sstr << "inotify_rm_watch failed for watch descriptor " << wd
         << ", error: " << strerror(errno);
    BOOST_LOG_TRIVIAL(error) << sstr.str();
    throw std::runtime_error(sstr.str());
  }
}

max_stars_repo_name: IvaKom/notibeast

max_issues_repo_name: IvaKom/notibeast

max_forks_repo_name: IvaKom/notibeast


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

#include <boost/iterator/function_input_iterator.hpp>
#include <vector>
#include <iterator>
#include <cassert>
#include <algorithm>
#include <iostream>

struct ones {
    typedef int result_type;
    result_type operator() () {
        return 1;
    }
};

int ones_function () {
    return 1;
}

using namespace std;

int main(int argc, char * argv[])
{
    // test the iterator with function objects
    ones ones_generator;
    vector<int> values(10);
    generate(values.begin(), values.end(), ones());

    vector<int> generated;
    copy(
        boost::make_function_input_iterator(ones_generator, 0),
        boost::make_function_input_iterator(ones_generator, 10),
        back_inserter(generated)
        );

    assert(values.size() == generated.size());
    assert(equal(values.begin(), values.end(), generated.begin()));
    cout << "function iterator test with function objects successful." << endl;

    // test the iterator with normal functions
    vector<int>().swap(generated);
    copy(
        boost::make_function_input_iterator(&ones_function, 0),
        boost::make_function_input_iterator(&ones_function, 10),
        back_inserter(generated)
        );

    assert(values.size() == generated.size());
    assert(equal(values.begin(), values.end(), generated.begin()));
    cout << "function iterator test with pointer to function successful." << endl;

    // test the iterator with a reference to a function
    vector<int>().swap(generated);
    copy(
        boost::make_function_input_iterator(ones_function, 0),
        boost::make_function_input_iterator(ones_function, 10),
        back_inserter(generated)
        );

    assert(values.size() == generated.size());
    assert(equal(values.begin(), values.end(), generated.begin()));
    cout << "function iterator test with reference to function successful." << endl;

    return 0;
}

max_forks_repo_name: olegshnitko/libboost


text:
#pragma once
/*
**  Copyright (C) 2012 Aldebaran Robotics
**  See COPYING for the license
*/

#ifndef _SRC_SERVER_HPP_
#define _SRC_SERVER_HPP_

#include <boost/thread/recursive_mutex.hpp>
#include <boost/noncopyable.hpp>
#include <boost/smart_ptr/shared_ptr.hpp>
#include "boundobject.hpp"
#include "authprovider_p.hpp"

namespace qi
{

  namespace detail
  {
    namespace server
    {
      /// Wraps a socket with its server specific information, such as an authentication state and
      /// automatizes the connection/disconnection of a handler for server messages.
      class SocketInfo
      {
      public:
      // NonCopyable:
        SocketInfo(const SocketInfo&) = delete;
        SocketInfo& operator=(const SocketInfo&) = delete;

      // SocketInfo:
        SocketInfo(const MessageSocketPtr& socket,
                   SignalSubscriber onDisconnected,
                   AuthProviderPtr authProvider = {}) noexcept;
        ~SocketInfo();

        MessageSocketPtr socket() const noexcept { return _socket.lock(); }

        /// @invariant `(x.setAuthenticated(), x.isAuthenticated()) == true`
        void setAuthenticated() noexcept { _authenticated = true; }
        bool isAuthenticated() const noexcept{ return _authenticated; }

        /// @post `extractCapabilities().empty()`
        CapabilityMap extractCapabilities();

        /// @invariant `(x.setAuthProvider(p), x.authProvider()) == p`
        void setAuthProvider(AuthProviderPtr prov) noexcept { _authProvider = std::move(prov); }
        AuthProviderPtr authProvider() const noexcept { return _authProvider; }

        /// Adds a message handler for server specific messages.
        /// @throws A `std::logic_error` exception if an handler was already set.
        void setServerMessageHandler(MessageDispatcher::MessageHandler handler);

        struct Tracker : qi::Trackable<Tracker> { using Trackable::destroy; };
        Tracker tracker;

      private:
        const MessageSocketWeakPtr _socket;
        const qi::SignalLink _disconnected = qi::SignalBase::invalidSignalLink;
        AuthProviderPtr _authProvider;
        boost::optional<MessageDispatchConnection> _msgDispatchConnection;
        bool _authenticated = false;
        bool _capabilitiesTaken = false;
      };
      using SocketInfoPtr = std::unique_ptr<SocketInfo>;

      /// Helper class that simplifies the creation and destruction of bindings between service bound
      /// objects and sockets. It automatically binds each object with each socket that it stores.
      class BoundObjectSocketBinder
      {
        using SocketInfoList = std::vector<SocketInfoPtr>;
        using BoundObjectPtrMap = boost::container::flat_map<unsigned int, BoundObjectPtr>;
        using BoundObjectSocketBindingList = std::vector<detail::boundObject::SocketBinding>;

      public:
      // NonCopyable:
        BoundObjectSocketBinder(const BoundObjectSocketBinder&) = delete;
        BoundObjectSocketBinder& operator=(const BoundObjectSocketBinder&) = delete;

      // BoundObjectSocketBinder:
        BoundObjectSocketBinder() noexcept;

        /// A socket must be validated before it is bound to the objects. Usually a validation
        /// requires an authentication success.
        /// @throws A `std::logic_error` exception if the socket already exists in this binder.
        SocketInfo& addSocketPendingValidation(const MessageSocketPtr& socket,
                                               SignalSubscriber disconnectionHandlerAnyFunc);

        /// Removes a socket and unbinds it from the objects.
        /// @returns True if the socket existed in this binder and was succesfully removed.
        bool removeSocket(const MessageSocketPtr& socket) noexcept;

        /// Validates the socket and binds it to the objects.
        /// @returns The number of bindings that were created.
        std::size_t validateSocket(const MessageSocketPtr& socket) noexcept;

        struct ClearSocketsResult
        {
          std::size_t socketCount;
          std::size_t bindingCount;
          KA_GENERATE_FRIEND_REGULAR_OPS_2(ClearSocketsResult, socketCount, bindingCount)
        };

        /// Removes all sockets and consequently all existing bindings.
        /// @returns A result containing the number of socket that were removed and disconnected and
        /// the number of bindings destroyed.
        /// @post `socketsInfo().empty()`
        ClearSocketsResult clearSockets() noexcept;

        const SocketInfoList& socketsInfo() const { return _socketsInfo; }

        /// Adds a service bound object and binds it to the sockets.
        /// @returns True if an object did not exist already for this service id and the object was
        /// successfully added.
        bool addObject(unsigned int serviceId, BoundObjectPtr object) noexcept;

        /// Removes a service bound object and unbinds it from the sockets.
        /// @returns True if an object existed for this service id and it was successfully removed.
        bool removeObject(unsigned int serviceId) noexcept;

        const BoundObjectPtrMap& boundObjects() const { return _boundObjects; }

      private:
        /// @returns The number of bindings that were created.
        std::size_t bindObject(const BoundObjectPtr& object) noexcept;

        /// @returns The number of bindings that were created.
        std::size_t bindSocket(const MessageSocketPtr& socket) noexcept;

        /// @returns The number of bindings that were destroyed.
        std::size_t unbindSocket(const MessageSocketPtr& socket) noexcept;

        /// @returns The number of bindings that were destroyed.
        std::size_t unbindObject(const BoundObjectPtr& object) noexcept;

        BoundObjectPtrMap _boundObjects;
        SocketInfoList _socketsInfo;
        BoundObjectSocketBindingList _bindings;
      };
    }
  }

  /// Wraps a transport server and ensures the binding between service bound objects and message
  /// sockets. It handles messages of the protocol destinated to the "Server" of a endpoint, which
  /// includes the authentication of clients and exchange of protocol capabilities.
  ///
  /// The kinematics of server messages processing are as follows:
  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  ///                      ╔═══════════════════════════╗
  ///                      ║ Socket received message { ║
  ///                      ║   service: Server(0)      ║
  ///                      ║   object: None(0)         ║
  ///                      ║ }                         ║
  ///                      ╚════════════╤══════════════╝
  ///                                   ▼
  ///              ╔════════════════════╧══════════════════════╗
  ///              ║ must_auth = Is authentication required ?  ║
  ///              ╟───────────────────────────────────────────╢
  ///              ║ is_auth = message.type == Call(1) and     ║
  ///              ║ message.action == Authenticate(8) ?       ║
  ///              ╚════════════════╤════════╤═════════════════╝
  ///               must_auth = yes ┤        ├ must_auth = no
  ///                               ╎        ╎
  ///          ┌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┬╌╌╌┘        └╌╌╌┬╌╌╌╌╌╌╌╌╌╌╌╌╌╌┐
  ///          ╎                ╎                ╎              ╎
  ///          ├ is_auth        ├ is_auth        ├ is_auth      ├ is_auth
  ///          ╎ = yes          ╎ = no           ╎ = yes        ╎ = no
  ///          ╎                ╎                ╎              ╎
  ///          ╎                ▼                ╎              ▼
  ///          ╎    ╔═══════════╧═══════════╗    ╎  ╔═══════════╧═══════════╗
  ///          ╎    ║ Socket send message { ║    ╎  ║ Socket send message { ║
  ///          ╎    ║   type: Error(3)      ║    ╎  ║   type: Capability(6) ║
  ///          ╎    ║   service: Server(0)  ║    ╎  ║   service: Server(0)  ║
  ///          ╎    ║   object: None(0)     ║    ╎  ║   value: {            ║
  ///          ╎    ║ }                     ║    ╎  ║     <capabilities>    ║
  ///          ╎    ╚═══════════╤═══════════╝    ╎  ║   }                   ║
  ///          ▼                └╌╌╌╌╌╌╌╌╌╌╌╌╌╌┐ ╎  ║ }                     ║
  /// ╔════════╧══════════════════════╗        ╎ ╎  ╚═══════════╤═══════════╝
  /// ║  Is pair message.auth_user    ║        ╎ ╎              ╎
  /// ║ message.auth_password valid ? ║        ╎ ╎              ╎
  /// ╚════════╤═══════════════╤══════╝        ╎ ╎              ╎
  ///      yes ┤            no ┤               ╎ ╎              ╎
  ///          ╎               ▼               ╎ ╎              ╎
  ///          ╎  ╔════════════╧═════════════╗ ╎ ╎              ╎
  ///          ╎  ║ Socket send message {    ║ ╎ ╎              ╎
  ///          ╎  ║   type: Error(3)         ║ ╎ ╎              ╎
  ///          ╎  ║   service: Server(0)     ║ ╎ ╎              ╎
  ///          ╎  ║   object: None(0)        ║ ╎ ╎              ╎
  ///          ╎  ║   value: {               ║ ╎ ╎              ╎
  ///          ╎  ║     auth_state: Error(1) ║ ╎ ╎              ╎
  ///          ╎  ║   }                      ║ ╎ ╎              ╎
  ///          ╎  ║ }                        ║ ╎ ╎              ╎
  ///          ╎  ╚════════════╤═════════════╝ ╎ ╎              ╎
  ///          ╎               ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┘ ╎              ╎
  ///          ╎               ▼                 ╎              ╎
  ///          ╎     ╔═════════╧═════════╗       ╎              ╎
  ///          ╎     ║ Disconnect socket ║       ╎              ╎
  ///          ╎     ╚═══════════════════╝       ╎              ╎
  ///          └╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┬╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┘              ╎
  ///                          ▼                                ╎
  ///             ╔════════════╧════════════╗                   ╎
  ///             ║ Socket send message {   ║                   ╎
  ///             ║   type: Reply(2)        ║                   ╎
  ///             ║   service: Server(0)    ║                   ╎
  ///             ║   object: None(0)       ║                   ╎
  ///             ║   value: {              ║                   ╎
  ///             ║     auth_state: Done(3) ║                   ╎
  ///             ║   }                     ║                   ╎
  ///             ║ }                       ║                   ╎
  ///             ╚════════════╤════════════╝                   ╎
  ///                          └╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┬╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┘
  ///                                           ▼
  ///                         ╔═════════════════╧════════════════╗
  ///                         ║ Ignore further socket messages { ║
  ///                         ║   service: Server(0)             ║
  ///                         ║   object: None(0)                ║
  ///                         ║ }                                ║
  ///                         ╚══════════════════════════════════╝
  /// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  ///
  class Server : private boost::noncopyable
  {
  public:
    Server(bool enforceAuth = false);
    ~Server();

    /// @see `TransportServer::listen`
    /// @post The server is not dying.
    qi::Future<void> listen(const qi::Url& address);

    /// @see `TransportServer::close`
    /// @post The server is dying.
    Future<void> close();

    /// Notifies the server that it's up again.
    /// @post The server is not dying.
    Future<bool> open();

    /// @see `TransportServer::setIdentity`
    Future<bool> setIdentity(const std::string& key, const std::string& crt);

    /// @returns True if the object is not null, an object did not exist already for this service id
    /// and the object was succesfully added.
    Future<bool> addObject(unsigned int serviceId, qi::AnyObject obj);
    Future<bool> addObject(unsigned int serviceId, qi::BoundObjectPtr obj);

    /// @returns True if an object existed for this service id and it was succesfully removed.
    Future<bool> removeObject(unsigned int idx);

    /// Adds an outgoing socket (a socket that was connected to a remote server endpoint instead of
    /// the usual listening server sockets). This allows service bounds objects to process messages
    /// coming from such sockets.
    /// @returns True if the socket started accepting messages.
    /// @throws
    ///   - A `std::invalid_argument` exception if the socket is null.
    Future<bool> addOutgoingSocket(MessageSocketPtr socket);

    /// @see `TransportServer::endpoints`
    Future<UrlVector> endpoints() const;

    Future<void> setAuthProviderFactory(AuthProviderFactoryPtr factory);

  private:
    using SocketInfo = detail::server::SocketInfo;
    using BoundObjectSocketBinder = detail::server::BoundObjectSocketBinder;

    void closeImpl();

    /// Adds an incoming socket (a socket created from a client connecting to the server),
    /// optionally requiring authentication.
    /// @returns True if the socket started accepting messages.
    /// @pre The function is executed in the context of the strand.
    /// @throws
    ///   - A `std::invalid_argument` exception if the socket is null.
    bool addIncomingSocket(MessageSocketPtr socket);

    /// @pre The function is executed in the context of the strand.
    /// @returns true if a reply was sent to the client.
    bool handleServerMessage(const Message& msg, SocketInfo& socketInfo);

    /// @pre The function is executed in the context of the strand.
    /// @pre `_enforceAuth == true`
    /// @returns true if a reply was sent to the client.
    bool handleServerMessageAuth(const Message& msg, SocketInfo& socketInfo);

    /// @pre The function is executed in the context of the strand.
    /// @pre `_enforceAuth == false`
    /// @returns true if a reply was sent to the client.
    bool handleServerMessageNoAuth(const Message& msg, SocketInfo& socketInfo);

    /// @pre The function is executed in the context of the strand.
    /// @returns true if a reply was sent to the client.
    bool authenticateSocket(const qi::Message& msg, SocketInfo& socketInfo, Message reply);

    /// @pre The function is executed in the context of the strand.
    void finalizeSocketAuthentication(SocketInfo& socketInfo) noexcept;

    struct SendAuthErrorResult
    {
      bool errorSent;
      Future<void> disconnected;
      KA_GENERATE_FRIEND_REGULAR_OPS_2(SendAuthErrorResult, errorSent, disconnected)
    };

    static SendAuthErrorResult sendAuthError(std::string error,
                                             MessageSocket& socket,
                                             Message reply);

    static bool sendAuthReply(CapabilityMap authResult,
                              SocketInfo& socketInfo,
                              Message reply);

    static bool sendSuccessfulAuthReply(SocketInfo& socketInfo, Message reply);

    static bool sendCapabilitiesMessage(SocketInfo& socketInfo);

    struct RemoveSocketResult
    {
      bool removed;
      Future<void> disconnected;
      KA_GENERATE_FRIEND_REGULAR_OPS_2(RemoveSocketResult, removed, disconnected)
    };

    /// @see `BoundObjectSocketBinder::removeSocket`
    /// @pre `socket != nullptr`
    /// @pre The function is executed in the context of the strand.
    /// @returns A struct containing a boolean stating if the socket existed in the server and was
    /// succesfully removed and a future of the socket disconnection result.
    RemoveSocketResult removeSocket(const MessageSocketPtr& socket);

    // Mutable state of the object.
    struct State
    {
      AuthProviderFactoryPtr authProviderFactory;
      BoundObjectSocketBinder binder;
    };
    State _state;
    boost::shared_ptr<Strand> _strand = boost::make_shared<Strand>();

    struct Tracker : qi::Trackable<Tracker> { using Trackable::destroy; };
    Tracker _tracker;

    template<typename R>
    static Future<R> serverClosedError()
    {
      return makeFutureError<R>("The server is closed.");
    }

    template<
      typename Proc1,
      typename Result = ka::Decay<decltype(std::declval<Proc1>()())>,
      typename Proc2 = decltype(serverClosedError<Result>)>
      Future<Result> safeCall(Proc1&& proc, Proc2&& onFail = serverClosedError<Result>) const
    {
      if (auto ptr = boost::atomic_load(&_strand))
        return ptr->async(std::forward<Proc1>(proc));
      else
        return std::forward<Proc2>(onFail)();
    }

    /// @pre The function is executed in the context of the strand.
    /// @throws
    ///   - A `std::invalid_argument` exception if the socket is null.
    SocketInfo& addSocket(MessageSocketPtr socket);

  protected:
    const bool _enforceAuth;
    TransportServer _server;
    const qi::MetaCallType _defaultCallType;
  };

}

#endif  // _SRC_SERVER_HPP_

max_stars_repo_name: arntanguy/libqi

max_issues_repo_name: arntanguy/libqi

max_forks_repo_name: arntanguy/libqi


text:
//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//

#include "BatchToSpaceNd.hpp"

#include "RefWorkloadUtils.hpp"

#include <armnn/Types.hpp>

#include <boost/assert.hpp>

namespace armnn
{

inline unsigned int Offset(const TensorShape& shape, unsigned int batch, unsigned int height, unsigned int width,
        unsigned int channels, const DataLayoutIndexed& dataLayout)
{
    if (dataLayout.GetDataLayout() == DataLayout::NHWC)
    {
        return ((batch * shape[dataLayout.GetHeightIndex()] + height) * shape[dataLayout.GetWidthIndex()] + width) *
               shape[dataLayout.GetChannelsIndex()] + channels;
    }
    else
    {
        return ((batch * shape[dataLayout.GetChannelsIndex()] + channels) *
               shape[dataLayout.GetHeightIndex()] + height) *
               shape[dataLayout.GetWidthIndex()] + width;
    }
}

void BatchToSpaceNd(const DataLayoutIndexed& dataLayout,
                    const TensorInfo& inputTensorInfo,
                    const TensorInfo& outputTensorInfo,
                    const std::vector<unsigned int>& blockShape,
                    const std::vector<std::pair<unsigned int, unsigned int>>& cropsData,
                    const float* inputData,
                    float* outputData)
{
    TensorShape inputShape = inputTensorInfo.GetShape();

    BOOST_ASSERT_MSG(inputShape.GetNumDimensions() == 4, "Expected Input with 4 Dimensions");

    TensorShape outputShape = outputTensorInfo.GetShape();

    BOOST_ASSERT_MSG(outputShape.GetNumDimensions() == 4, "Expected Output with 4 Dimensions");

    const unsigned int inputBatchSize = inputShape[0];
    const unsigned int channels = inputShape[dataLayout.GetChannelsIndex()];

    const unsigned int outputBatchSize = outputShape[0];
    const unsigned int outputHeight = outputShape[dataLayout.GetHeightIndex()];
    const unsigned int outputWidth = outputShape[dataLayout.GetWidthIndex()];

    BOOST_ASSERT_MSG(blockShape.size() > 0, "BlockShape must contain 1 or more entries");

    const unsigned int blockShapeHeight = blockShape[0];
    const unsigned int blockShapeWidth = blockShape[1];

    BOOST_ASSERT_MSG(cropsData.size() > 0, "Crops must contain 1 or more entries");

    const unsigned int cropsTop = cropsData[0].first;
    const unsigned int cropsLeft = cropsData[1].first;

    for (unsigned int inBatch = 0; inBatch < inputBatchSize; ++inBatch)
    {
        const unsigned int outBatch = inBatch % outputBatchSize;
        const unsigned int spatialOffset = inBatch / outputBatchSize;

        for (unsigned int inH = 0; inH < inputTensorInfo.GetShape()[dataLayout.GetHeightIndex()]; ++inH) {
            const unsigned int outH = inH * blockShapeHeight + spatialOffset / blockShapeWidth - cropsTop;

            if (outH >= outputHeight)
            {
                continue;
            }

            for (unsigned int inW = 0; inW < inputTensorInfo.GetShape()[dataLayout.GetWidthIndex()]; ++inW) {
                const unsigned int outW = inW * blockShapeWidth + spatialOffset % blockShapeWidth - cropsLeft;

                if (outW >= outputWidth)
                {
                    continue;
                }

                for (unsigned int c = 0; c < channels; c++)
                {
                    unsigned int outOffset = Offset(outputShape, outBatch, outH, outW, c, dataLayout);
                    unsigned int inOffset = Offset(inputShape, inBatch, inH, inW, c, dataLayout);
                    outputData[outOffset] = inputData[inOffset];
                }
            }
        }
    }
}

} //namespace armnn

max_issues_repo_name: SYjianli/armnn

max_forks_repo_name: SYjianli/armnn


text:
//
// 	Copyright (c) 2018, Cem Bassoy, cem.bassoy@gmail.com
// 	Copyright (c) 2019, Amit Singh, amitsingh19975@gmail.com
//
//  Distributed under the Boost Software License, Version 1.0. (See
//  accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//
//  The authors gratefully acknowledge the support of
//  Google and Fraunhofer IOSB, Ettlingen, Germany
//

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

int main()
{
  namespace ublas = boost::numeric::ublas;
  using value   = float;
  using layout  = ublas::layout::first_order; // storage format
  using tensor  = ublas::tensor_dynamic<value,layout>;
  using shape   = typename tensor::extents_type;
  using matrix  = ublas::matrix<value,layout>;

  constexpr auto ones = ublas::ones<value,layout>{};

  // NOLINTNEXTLINE(google-build-using-namespace)
  using namespace boost::numeric::ublas::index;

  using namespace boost::numeric::ublas::index;
  using tensor  = boost::numeric::ublas::tensor_dynamic<float>;
  auto fones    = boost::numeric::ublas::ones<float>{};

  tensor X = fones(3,4,5);
  tensor Y = fones(4,6,3,2);

  tensor Z = 2*ones(5,6,2) + X(_i,_j,_k)*Y(_j,_l,_i,_m) + 5;

  // Matlab Compatible Formatted Output
  std::cout << "C=" << Z << ";" << std::endl;

  // Tensor-Vector-Multiplications - Including Transposition
  try {

    auto n  = shape{3,4,2};

    tensor A  = ones(n);
    matrix B1 = 2*matrix(n[1],n[2]);
    tensor v1 = 2*ones(n[0],1);
    tensor v2 = 2*ones(n[1],1);
    //      auto v3 = tensor(shape{n[2],1},2);

    // C1(j,k) = B1(j,k) + A(i,j,k)*v1(i);
    // tensor C1 = B1 + prod(A,vector_t(n[0],1),1);
    tensor C1 = B1 + A(_i,_,_) * v1(_i,_);

    // C2(i,k) = A(i,j,k)*v2(j) + 4;
    //tensor C2 = prod(A,vector_t(n[1],1),2) + 4;
    tensor C2 = A(_,_i,_) * v2(_i,_) + 4;

    // not yet implemented!
    // C3() = A(i,j,k)*T1(i)*T2(j)*T2(k);
        // tensor C3 = prod(prod(prod(A,v1,1),v2,1),v3,1);
    // tensor C3 = A(_i,_j,_k) * v1(_i,_) * v2(_j,_) * v3(_k,_);

    // formatted output
    std::cout << "% --------------------------- " << std::endl;
    std::cout << "% --------------------------- " << std::endl << std::endl;
    std::cout << "% C1(j,k) = B1(j,k) + A(i,j,k)*v1(i);" << std::endl << std::endl;
    std::cout << "C1=" << C1 << ";" << std::endl << std::endl;

    // formatted output
    std::cout << "% --------------------------- " << std::endl;
    std::cout << "% --------------------------- " << std::endl << std::endl;
    std::cout << "% C2(i,k) = A(i,j,k)*v2(j) + 4;" << std::endl << std::endl;
    std::cout << "C2=" << C2 << ";" << std::endl << std::endl;

  } catch (const std::exception& e) {
    std::cerr << "Cought exception " << e.what();
    std::cerr << "in the main function of multiply-tensor-einstein-notation when doing tensor-vector multiplication." << std::endl;
  }

  // Tensor-Matrix-Multiplications - Including Transposition
  try {
    auto n  = shape{3,4,2};
    auto m  = 5u;
    tensor A  = 2*ones(n);
    tensor B  = 2*ones(n[1],n[2],m);
    tensor B1 =   ones(m,n[0]);
    tensor B2 =   ones(m,n[1]);

    // C1(l,j,k) = B(j,k,l) + A(i,j,k)*B1(l,i);
    // tensor C1 = B + prod(A,B1,1);
    tensor C1 = B + A(_i,_,_) * B1(_,_i);

    // C2(i,l,k) = A(i,j,k)*B2(l,j) + 4;
    // tensor C2 = prod(A,B2) + 4;
    tensor C2 =  A(_,_j,_) * B2(_,_j) + 4;

    // C3(i,l1,l2) = A(i,j,k)*T1(l1,j)*T2(l2,k);
    // not yet implemented.

    // formatted output
    std::cout << "% --------------------------- " << std::endl;
    std::cout << "% --------------------------- " << std::endl << std::endl;
    std::cout << "% C1(l,j,k) = B(j,k,l) + A(i,j,k)*B1(l,i);" << std::endl << std::endl;
    std::cout << "C1=" << C1 << ";" << std::endl << std::endl;

    // formatted output
    std::cout << "% --------------------------- " << std::endl;
    std::cout << "% --------------------------- " << std::endl << std::endl;
    std::cout << "% C2(i,l,k) = A(i,j,k)*B2(l,j) + 4;" << std::endl << std::endl;
    std::cout << "C2=" << C2 << ";" << std::endl << std::endl;

    // formatted output
    //        std::cout << "% --------------------------- " << std::endl;
    //        std::cout << "% --------------------------- " << std::endl << std::endl;
    //        std::cout << "% C3(i,l1,l2) = A(i,j,k)*T1(l1,j)*T2(l2,k);" << std::endl << std::endl;
    //        std::cout << "C3=" << C3 << ";" << std::endl << std::endl;
  } catch (const std::exception& e) {
    std::cerr << "Cought exception " << e.what();
    std::cerr << "in the main function of multiply-tensor-einstein-notation when doing tensor-matrix multiplication." << std::endl;
  }

  // Tensor-Tensor-Multiplications Including Transposition
  try {
    auto na = shape{3,4,5};
    auto nb = shape{4,6,3,2};
    tensor A  = 2*ones(na);
    tensor B  = 3*ones(nb);
    tensor T1 = 2*ones(na[2],na[2]);
    tensor T2 = 2*ones(na[2],nb[1],nb[3]);

    // C1(j,l) = T1(j,l) + A(i,j,k)*A(i,j,l) + 5;
    // tensor C1 = T1 + prod(A,A,perm_t{1,2}) + 5;
    tensor C1 = T1 + A(_i,_j,_m)*A(_i,_j,_l) + 5;

    // formatted output
    std::cout << "% --------------------------- " << std::endl;
    std::cout << "% --------------------------- " << std::endl << std::endl;
    std::cout << "% C1(k,l) = T1(k,l) + A(i,j,k)*A(i,j,l) + 5;" << std::endl << std::endl;
    std::cout << "C1=" << C1 << ";" << std::endl << std::endl;

    // C2(k,l,m) = T2(k,l,m) + A(i,j,k)*B(j,l,i,m) + 5;
    //tensor C2 = T2 + prod(A,B,perm_t{1,2},perm_t{3,1}) + 5;
    tensor C2 = T2 + A(_i,_j,_k)*B(_j,_l,_i,_m) + 5;

    // formatted output
    std::cout << "% --------------------------- " << std::endl;
    std::cout << "% --------------------------- " << std::endl << std::endl;
    std::cout << "%  C2(k,l,m) = T2(k,l,m) + A(i,j,k)*B(j,l,i,m) + 5;" << std::endl << std::endl;
    std::cout << "C2=" << C2 << ";" << std::endl << std::endl;

  } catch (const std::exception& e) {
    std::cerr << "Cought exception " << e.what();
    std::cerr << "in the main function of multiply-tensor-einstein-notation when doing transpose." << std::endl;
  }
}


text:
// Author(s): Jeroen Keiren
// Copyright: see the accompanying file COPYING or copy at
// https://github.com/mCRL2org/mCRL2/blob/master/COPYING
//
// 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 logger_test.cpp

#define BOOST_AUTO_TEST_MAIN
#include <boost/test/included/unit_test_framework.hpp>

#include "mcrl2/utilities/logger.h"

using namespace mcrl2::log;

void print_all_log_levels()
{
  mCRL2log(error) << "An error message" << std::endl;
  mCRL2log(warning) << "A warning" << std::endl;
  mCRL2log(info) << "Some information" << std::endl;
  mCRL2log(verbose) << "Detailed information" << std::endl;
  mCRL2log(debug) << "Debugging info" << std::endl;
  mCRL2log(debug1) << "Detailed debugging info" << std::endl;
  mCRL2log(debug2) << "Detailed debugging info (2)" << std::endl;
  mCRL2log(debug3) << "Detailed debugging info (3)" << std::endl;
  mCRL2log(debug4) << "Detailed debugging info (4)" << std::endl;
  mCRL2log(debug5) << "Detailed debugging info (5)" << std::endl;
}

BOOST_AUTO_TEST_CASE(test_logging_basic)
{
  // Messages will only be printed up to debug, due to standard MCRL2_MAX_LOG_LEVEL
  mcrl2_logger::set_reporting_level(debug2);
  print_all_log_levels();
}

BOOST_AUTO_TEST_CASE(test_logging_use_case)
{
  mCRL2log(info) << "Entering logging use case" << std::endl;
  const int count = 3;
  mCRL2log(debug) << "A loop with " << count << " iterations" << std::endl;
  for (int i = 0; i < count; ++i)
  {
    mCRL2log(debug1) << "the counter i = " << i << std::endl;
    if(i >= 2)
    {
      mCRL2log(debug2) << "the counter is greater then 2" << std::endl;
    }
  }
}

BOOST_AUTO_TEST_CASE(test_indentation)
{
  mCRL2log(info) << "Entering indentation test" << std::endl;
  const int count = 3;
  mCRL2log(info) << "A loop with " << count << " iterations" << std::endl;
  for (int i = 0; i < count; ++i)
  {
    mCRL2log(debug) << "the counter i = " << i << std::endl;
    if(i >= 2)
    {
      mCRL2log(debug) << "the counter is greater then 2" << std::endl;
    }
  }
}

BOOST_AUTO_TEST_CASE(test_logging_multiline)
{
  mCRL2log(info) << "Testing multiline logging (line 1)" << std::endl
                 << "line 2" << std::endl
                 << "the last last line" << std::endl;
}

BOOST_AUTO_TEST_CASE(test_logging_hint)
{
  mcrl2_logger::set_reporting_level(info);
  mCRL2log(debug, "test_hint") << "Testing hint, should not be printed" << std::endl;
  mcrl2_logger::set_reporting_level(debug, "test_hint");
  mCRL2log(debug, "test_hint") << "Testing hint, should be printed" << std::endl;
  mCRL2log(debug) << "Testing hint, should not be printed" << std::endl;
  mcrl2_logger::set_reporting_level(verbose, "test_hint");
  mCRL2log(info) << "Testing hint, should still be printed" << std::endl;
  mcrl2_logger::clear_reporting_level("test_hint");
}

BOOST_AUTO_TEST_CASE(test_file_logging)
{
  FILE * pFile;
  pFile = fopen ("logger_test_file.txt" , "w");
  BOOST_REQUIRE(pFile != nullptr);

  file_output::set_stream(pFile);
  mCRL2log(info) << "This line is written to logger_test_file.txt" << std::endl;
  file_output::set_stream(stderr);
  fclose(pFile);
  mCRL2log(info) << "This line is written to stderr" << std::endl;
}

std::string test_assert()
{
  BOOST_CHECK(false);
  return "BOOM!";
}

// Show that arguments to logging are not executed if the log level is larger
// than MCRL2_MAX_LOG_LEVEL (i.e. the BOOST_CHECK(false) in test_assert() should
// never be triggered.
BOOST_AUTO_TEST_CASE(test_non_execution_of_arguments_static)
{
  BOOST_CHECK(MCRL2MaxLogLevel < debug5);
  mCRL2log(debug5) << "This line should not end with BOOM! ............. " << test_assert() << std::endl;
}

// Show that arguments to logging are not executed if the log level is larger
// than mcrl2_logger::reporting_level() (i.e. the BOOST_CHECK(false) in test_assert() should
// never be triggered.
BOOST_AUTO_TEST_CASE(test_non_execution_of_arguments_dynamic)
{
  BOOST_CHECK(MCRL2MaxLogLevel >= debug);
  mcrl2_logger::set_reporting_level(verbose);
  mCRL2log(debug) << "This line should not end with BOOM! ............. " << test_assert() << std::endl;
}

BOOST_AUTO_TEST_CASE(test_fflush)
{
  for(int i = 0; i < 10; ++i)
  {
    fprintf(stderr, "%d", i);
    fflush(stderr);
  }
  fprintf(stderr, "\n");
  fflush(stderr);
}

BOOST_AUTO_TEST_CASE(test_multiline_nonewline)
{
  mCRL2log(info) << "There is just one newline";
  mCRL2log(info) << "in this message" << std::endl;
}

BOOST_AUTO_TEST_CASE(test_enabled_constexpr)
{
  static_assert(!mCRL2logEnabled(debug3), "This function should evaluate to false at compile time.");
}